Search in sources :

Example 1 with Discontinuity

use of cbit.vcell.parser.Discontinuity in project vcell by virtualcell.

the class FiniteVolumeFileWriter method writeSimulationParamters.

/**
 * @param timeFunction
 * @param startTime
 * @param endTime
 * @param rootFinder
 * @param uniqueRootTimes
 * @param bPrintIterations
 * @throws ExpressionException
 *
 * for testing within scrapbook, see below:
 *
 * try {
 *	edu.northwestern.at.utils.math.rootfinders.MonadicFunctionRootFinder rootFinder =
 *//			new edu.northwestern.at.utils.math.rootfinders.Brent();
 *			new edu.northwestern.at.utils.math.rootfinders.Bisection();
 *//			new edu.northwestern.at.utils.math.rootfinders.NewtonRaphson();
 *//			new edu.northwestern.at.utils.math.rootfinders.Secant();
 *	cbit.vcell.parser.SimpleSymbolTable simpleSymbolTable = new cbit.vcell.parser.SimpleSymbolTable(new String[] { "t" });
 *
 *	cbit.vcell.parser.Expression exp = new cbit.vcell.parser.Expression("t-0.56");
 *
 *	exp.bindExpression(simpleSymbolTable);
 *	java.util.TreeSet<Double> rootTimes = new java.util.TreeSet<Double>();
 *	double startTime = 0.0;
 *	double endTime = 100.0;
 *	System.out.print("exp = '"+ exp.infix() + "'");
 *	long currentTimeMS = System.currentTimeMillis();
 *	cbit.vcell.solvers.FiniteVolumeFileWriter.findAllRoots(exp,startTime,endTime,rootFinder,rootTimes,false);
 *	long finalTimeMS = System.currentTimeMillis();
 *	for (double root : rootTimes){
 *		System.out.println("root = "+root);
 *	}
 *	System.out.println("elapsedTime of computation = "+(finalTimeMS-currentTimeMS)+" ms, found " + rootTimes.size() + " roots (not unique)");
 *
 *}catch (Exception e){
 *	e.printStackTrace(System.out);
 *}
 */
/*public static void findAllRoots(Expression timeFunction, double startTime, double endTime, MonadicFunctionRootFinder rootFinder, TreeSet<Double> uniqueRootTimes, boolean bPrintIterations) throws ExpressionException{
	TreeSet<Double> allRootTimes = new TreeSet<Double>();
	final Expression function_exp = new Expression(timeFunction);
	MonadicFunction valueFunction = new MonadicFunction() {
		double[] values = new double[1];
		public double f(double t) {
			values[0] = t;
			try {
				return function_exp.evaluateVector(values);
			} catch (ExpressionException e) {
				e.printStackTrace();
				throw new RuntimeException("expression exception "+e.getMessage());
			}
		}
	};
	
	final Expression derivative_exp = new Expression(timeFunction.differentiate(ReservedVariable.TIME.getName()));
	MonadicFunction derivativeFunction = new MonadicFunction() {
		double[] values = new double[1];
		public double f(double t) {
			values[0] = t;
			try {
				return derivative_exp.evaluateVector(values);
			} catch (ExpressionException e) {
				e.printStackTrace();
				throw new RuntimeException("expression exception "+e.getMessage());
			}
		}
	};
	
	RootFinderConvergenceTest convergenceTest = new StandardRootFinderConvergenceTest();
	RootFinderIterationInformation iterationInformation = null;
	if (bPrintIterations){
		iterationInformation = new RootFinderIterationInformation() {				
			public void iterationInformation(double x, double fx, double dfx, int currentIteration) {
				System.out.println(currentIteration+") x="+x+", fx="+fx+", dfx="+dfx);
			}
		};
	}
	int NUM_BRACKETS = 1000;
	double simulationTime = endTime - startTime;
	double tolerance = simulationTime/1e10;
	int maxIter = 1000;
	
	for (int i=0;i<NUM_BRACKETS-1;i++){
		double bracketMin = startTime + simulationTime*i/NUM_BRACKETS;
		double bracketMax = startTime + simulationTime*(i+1)/NUM_BRACKETS;
	
		double root = rootFinder.findRoot(bracketMin, bracketMax, tolerance, maxIter, valueFunction, derivativeFunction, convergenceTest, iterationInformation);
		if (root>startTime && root<endTime && valueFunction.f(root)<=tolerance){
			allRootTimes.add(root);
		}
	}
	double uniqueTolerance = tolerance * 100;
	double lastUniqueRoot = Double.NEGATIVE_INFINITY;
	for (double root : allRootTimes){
		if (root-lastUniqueRoot > uniqueTolerance){
			uniqueRootTimes.add(root);
		}
		lastUniqueRoot = root;
	}

}  ---------------------------------JIM's CODE COMMENTTED FOR FUTURE DEVELOPMENT*/
/**
 *# Simulation Parameters
 *SIMULATION_PARAM_BEGIN
 *SOLVER SUNDIALS_PDE_SOLVER 1.0E-7 1.0E-9
 *DISCONTINUITY_TIMES 2 1.0E-4 3.0000000000000003E-4
 *BASE_FILE_NAME c:/Vcell/users/fgao/SimID_31746636_0_
 *ENDING_TIME 4.0E-4
 *KEEP_EVERY ONE_STEP 3
 *KEEP_AT_MOST 1000
 *SIMULATION_PARAM_END
 * @throws MathException
 * @throws ExpressionException
 */
private void writeSimulationParamters() throws ExpressionException, MathException {
    Simulation simulation = simTask.getSimulation();
    SolverTaskDescription solverTaskDesc = simulation.getSolverTaskDescription();
    printWriter.println("# Simulation Parameters");
    printWriter.println(FVInputFileKeyword.SIMULATION_PARAM_BEGIN);
    if (solverTaskDesc.getSolverDescription().equals(SolverDescription.SundialsPDE)) {
        printWriter.print(FVInputFileKeyword.SOLVER + " " + FVInputFileKeyword.SUNDIALS_PDE_SOLVER + " " + solverTaskDesc.getErrorTolerance().getRelativeErrorTolerance() + " " + solverTaskDesc.getErrorTolerance().getAbsoluteErrorTolerance() + " " + solverTaskDesc.getTimeStep().getMaximumTimeStep());
        if (simulation.getMathDescription().hasVelocity()) {
            printWriter.print(" " + solverTaskDesc.getSundialsPdeSolverOptions().getMaxOrderAdvection());
        }
        if (solverTaskDesc.isBorderExtrapolationDisabled()) {
            // Set with GUI checkbox in SolverTaskDescriptionAdvancedPanel
            // Tells vcell-solvers/VCell/src/SundialsPdeScheduler.cpp not to extrapolate values at boundaries
            // Read by vcell-solvers/VCell/src/FVSolver.cpp::loadSimulationParameters(...) from file {vcellUserDataDir}/SimID_xxx.fvinput
            printWriter.print(" " + ("" + solverTaskDesc.isBorderExtrapolationDisabled()).toLowerCase());
        }
        printWriter.println();
        Vector<Discontinuity> discontinuities = new Vector<Discontinuity>();
        TreeSet<Double> discontinuityTimes = new TreeSet<Double>();
        MathDescription mathDesc = simulation.getMathDescription();
        Enumeration<SubDomain> enum1 = mathDesc.getSubDomains();
        while (enum1.hasMoreElements()) {
            SubDomain sd = enum1.nextElement();
            Enumeration<Equation> enum_equ = sd.getEquations();
            while (enum_equ.hasMoreElements()) {
                Equation equation = enum_equ.nextElement();
                equation.getDiscontinuities(simTask.getSimulationJob().getSimulationSymbolTable(), discontinuities);
            }
        }
        getDiscontinuityTimes(discontinuities, discontinuityTimes);
        if (discontinuityTimes.size() > 0) {
            printWriter.print(FVInputFileKeyword.DISCONTINUITY_TIMES + " " + discontinuityTimes.size());
            for (double d : discontinuityTimes) {
                printWriter.print(" " + d);
            }
            printWriter.println();
        }
    } else if (solverTaskDesc.getSolverDescription().equals(SolverDescription.Chombo)) {
        printWriter.println(FVInputFileKeyword.SOLVER + " " + FVInputFileKeyword.CHOMBO_SEMIIMPLICIT_SOLVER);
    } else if (solverTaskDesc.getSolverDescription().equals(SolverDescription.VCellPetsc)) {
        printWriter.println(FVInputFileKeyword.SOLVER + " " + FVInputFileKeyword.VCELL_PETSC_SOLVER);
    } else {
        printWriter.println(FVInputFileKeyword.SOLVER + " " + FVInputFileKeyword.FV_SOLVER + " " + solverTaskDesc.getErrorTolerance().getRelativeErrorTolerance());
    }
    printWriter.println(FVInputFileKeyword.BASE_FILE_NAME + " " + new File(workingDirectory, simTask.getSimulationJob().getSimulationJobID()).getAbsolutePath());
    if (solverTaskDesc.isParallel() && destinationDirectory != null && !destinationDirectory.equals(workingDirectory)) {
        printWriter.println(FVInputFileKeyword.PRIMARY_DATA_DIR + " " + destinationDirectory.getAbsolutePath());
    }
    printWriter.println(FVInputFileKeyword.ENDING_TIME + " " + solverTaskDesc.getTimeBounds().getEndingTime());
    OutputTimeSpec outputTimeSpec = solverTaskDesc.getOutputTimeSpec();
    if (solverTaskDesc.getSolverDescription().isChomboSolver()) {
        List<TimeInterval> timeIntervalList = solverTaskDesc.getChomboSolverSpec().getTimeIntervalList();
        printWriter.println(FVInputFileKeyword.TIME_INTERVALS + " " + timeIntervalList.size());
        for (TimeInterval ti : timeIntervalList) {
            printWriter.println(ti.getEndingTime() + " " + ti.getTimeStep() + " " + ti.getKeepEvery());
        }
    } else if (solverTaskDesc.getSolverDescription().equals(SolverDescription.SundialsPDE)) {
        if (outputTimeSpec.isDefault()) {
            DefaultOutputTimeSpec defaultOutputTimeSpec = (DefaultOutputTimeSpec) outputTimeSpec;
            printWriter.println(FVInputFileKeyword.KEEP_EVERY + " " + FVInputFileKeyword.ONE_STEP + " " + defaultOutputTimeSpec.getKeepEvery());
            printWriter.println(FVInputFileKeyword.KEEP_AT_MOST + " " + defaultOutputTimeSpec.getKeepAtMost());
        } else {
            printWriter.println(FVInputFileKeyword.TIME_STEP + " " + ((UniformOutputTimeSpec) outputTimeSpec).getOutputTimeStep());
            printWriter.println(FVInputFileKeyword.KEEP_EVERY + " 1");
        }
    } else {
        double defaultTimeStep = solverTaskDesc.getTimeStep().getDefaultTimeStep();
        printWriter.println(FVInputFileKeyword.TIME_STEP + " " + defaultTimeStep);
        int keepEvery = 1;
        if (outputTimeSpec.isDefault()) {
            keepEvery = ((DefaultOutputTimeSpec) outputTimeSpec).getKeepEvery();
        } else if (outputTimeSpec.isUniform()) {
            UniformOutputTimeSpec uots = (UniformOutputTimeSpec) outputTimeSpec;
            double ots = uots.getOutputTimeStep();
            keepEvery = (int) Math.round(ots / defaultTimeStep);
        } else {
            throw new RuntimeException("unexpected OutputTime specification type :" + outputTimeSpec.getClass().getName());
        }
        if (keepEvery <= 0) {
            throw new RuntimeException("Output KeepEvery must be a positive integer. Try to change the output option.");
        }
        printWriter.println(FVInputFileKeyword.KEEP_EVERY + " " + keepEvery);
    }
    MathDescription md = simulation.getMathDescription();
    if (md.isSpatialHybrid()) {
        SmoldynSimulationOptions smoldynSimulationOptions = simulation.getSolverTaskDescription().getSmoldynSimulationOptions();
        if (smoldynSimulationOptions != null && smoldynSimulationOptions.getSmoldynStepMultiplier() > 1) {
            printWriter.println(FVInputFileKeyword.SMOLDYN_STEP_MULTIPLIER + " " + smoldynSimulationOptions.getSmoldynStepMultiplier());
        }
    }
    ErrorTolerance stopAtSpatiallyUniformErrorTolerance = solverTaskDesc.getStopAtSpatiallyUniformErrorTolerance();
    if (stopAtSpatiallyUniformErrorTolerance != null) {
        printWriter.println(FVInputFileKeyword.CHECK_SPATIALLY_UNIFORM + " " + stopAtSpatiallyUniformErrorTolerance.getAbsoluteErrorTolerance() + " " + stopAtSpatiallyUniformErrorTolerance.getRelativeErrorTolerance());
    }
    printWriter.println(FVInputFileKeyword.SIMULATION_PARAM_END);
    printWriter.println();
}
Also used : Discontinuity(cbit.vcell.parser.Discontinuity) TimeInterval(org.vcell.chombo.TimeInterval) UniformOutputTimeSpec(cbit.vcell.solver.UniformOutputTimeSpec) MathDescription(cbit.vcell.math.MathDescription) MeasureEquation(cbit.vcell.math.MeasureEquation) PdeEquation(cbit.vcell.math.PdeEquation) VolumeRegionEquation(cbit.vcell.math.VolumeRegionEquation) MembraneRegionEquation(cbit.vcell.math.MembraneRegionEquation) Equation(cbit.vcell.math.Equation) CompartmentSubDomain(cbit.vcell.math.CompartmentSubDomain) SubDomain(cbit.vcell.math.SubDomain) MembraneSubDomain(cbit.vcell.math.MembraneSubDomain) SmoldynSimulationOptions(cbit.vcell.solver.SmoldynSimulationOptions) DefaultOutputTimeSpec(cbit.vcell.solver.DefaultOutputTimeSpec) OutputTimeSpec(cbit.vcell.solver.OutputTimeSpec) UniformOutputTimeSpec(cbit.vcell.solver.UniformOutputTimeSpec) Simulation(cbit.vcell.solver.Simulation) TreeSet(java.util.TreeSet) ErrorTolerance(cbit.vcell.solver.ErrorTolerance) SolverTaskDescription(cbit.vcell.solver.SolverTaskDescription) Vector(java.util.Vector) File(java.io.File) DefaultOutputTimeSpec(cbit.vcell.solver.DefaultOutputTimeSpec)

Example 2 with Discontinuity

use of cbit.vcell.parser.Discontinuity in project vcell by virtualcell.

the class OdeFileWriter method getSubsitutedAndFlattened.

public Discontinuity getSubsitutedAndFlattened(Discontinuity discontinuity, SymbolTable st) throws ExpressionException {
    Expression discontinuityExp = MathUtilities.substituteFunctions(discontinuity.getDiscontinuityExp(), st).flatten();
    Expression rootFindingExp = MathUtilities.substituteFunctions(discontinuity.getRootFindingExp(), st).flatten();
    return new Discontinuity(discontinuityExp, rootFindingExp, discontinuity.getASTRelationOperator());
}
Also used : Discontinuity(cbit.vcell.parser.Discontinuity) Expression(cbit.vcell.parser.Expression)

Example 3 with Discontinuity

use of cbit.vcell.parser.Discontinuity in project vcell by virtualcell.

the class IDAFileWriter method writeEquations.

/**
 * Insert the method's description here.
 * Creation date: (3/8/00 10:31:52 PM)
 */
protected String writeEquations(HashMap<Discontinuity, String> discontinuityNameMap) throws MathException, ExpressionException {
    Simulation simulation = simTask.getSimulation();
    StringBuffer sb = new StringBuffer();
    MathDescription mathDescription = simulation.getMathDescription();
    if (mathDescription.hasFastSystems()) {
        // 
        // define vector of original variables
        // 
        SimulationSymbolTable simSymbolTable = simTask.getSimulationJob().getSimulationSymbolTable();
        CompartmentSubDomain subDomain = (CompartmentSubDomain) mathDescription.getSubDomains().nextElement();
        FastSystem fastSystem = subDomain.getFastSystem();
        FastSystemAnalyzer fs_Analyzer = new FastSystemAnalyzer(fastSystem, simSymbolTable);
        int numIndependent = fs_Analyzer.getNumIndependentVariables();
        int systemDim = mathDescription.getStateVariableNames().size();
        int numDependent = systemDim - numIndependent;
        // 
        // get all variables from fast system (dependent and independent)
        // 
        HashSet<String> fastSystemVarHash = new HashSet<String>();
        Enumeration<Variable> dependentfastSystemVarEnum = fs_Analyzer.getDependentVariables();
        while (dependentfastSystemVarEnum.hasMoreElements()) {
            fastSystemVarHash.add(dependentfastSystemVarEnum.nextElement().getName());
        }
        Enumeration<Variable> independentfastSystemVarEnum = fs_Analyzer.getIndependentVariables();
        while (independentfastSystemVarEnum.hasMoreElements()) {
            fastSystemVarHash.add(independentfastSystemVarEnum.nextElement().getName());
        }
        // 
        // get all equations including for variables that are not in the fastSystem (ode equations for "slow system")
        // 
        RationalExpMatrix origInitVector = new RationalExpMatrix(systemDim, 1);
        RationalExpMatrix origSlowRateVector = new RationalExpMatrix(systemDim, 1);
        RationalExpMatrix origVarColumnVector = new RationalExpMatrix(systemDim, 1);
        Enumeration<Equation> enumEquations = subDomain.getEquations();
        int varIndex = 0;
        while (enumEquations.hasMoreElements()) {
            Equation equation = enumEquations.nextElement();
            origVarColumnVector.set_elem(varIndex, 0, new RationalExp(equation.getVariable().getName()));
            Expression rateExpr = equation.getRateExpression();
            rateExpr.bindExpression(varsSymbolTable);
            rateExpr = MathUtilities.substituteFunctions(rateExpr, varsSymbolTable);
            origSlowRateVector.set_elem(varIndex, 0, new RationalExp("(" + rateExpr.flatten().infix() + ")"));
            Expression initExpr = new Expression(equation.getInitialExpression());
            initExpr.substituteInPlace(new Expression("t"), new Expression(0.0));
            initExpr = MathUtilities.substituteFunctions(initExpr, varsSymbolTable).flatten();
            origInitVector.set_elem(varIndex, 0, new RationalExp("(" + initExpr.flatten().infix() + ")"));
            varIndex++;
        }
        // 
        // make symbolic matrix for fast invariants (from FastSystem's fastInvariants as well as a new fast invariant for each variable not included in the fast system.
        // 
        RationalExpMatrix fastInvarianceMatrix = new RationalExpMatrix(numDependent, systemDim);
        int row = 0;
        for (int i = 0; i < origVarColumnVector.getNumRows(); i++) {
            // 
            if (!fastSystemVarHash.contains(origVarColumnVector.get(i, 0).infixString())) {
                fastInvarianceMatrix.set_elem(row, i, RationalExp.ONE);
                row++;
            }
        }
        Enumeration<FastInvariant> enumFastInvariants = fastSystem.getFastInvariants();
        while (enumFastInvariants.hasMoreElements()) {
            FastInvariant fastInvariant = enumFastInvariants.nextElement();
            Expression fastInvariantExpression = fastInvariant.getFunction();
            for (int col = 0; col < systemDim; col++) {
                Expression coeff = fastInvariantExpression.differentiate(origVarColumnVector.get(col, 0).infixString()).flatten();
                coeff = simSymbolTable.substituteFunctions(coeff);
                fastInvarianceMatrix.set_elem(row, col, RationalExpUtils.getRationalExp(coeff));
            }
            row++;
        }
        for (int i = 0; i < systemDim; i++) {
            sb.append("VAR " + origVarColumnVector.get(i, 0).infixString() + " INIT " + origInitVector.get(i, 0).infixString() + ";\n");
        }
        RationalExpMatrix fullMatrix = null;
        RationalExpMatrix inverseFullMatrix = null;
        RationalExpMatrix newSlowRateVector = null;
        try {
            RationalExpMatrix fastMat = ((RationalExpMatrix) fastInvarianceMatrix.transpose().findNullSpace());
            fullMatrix = new RationalExpMatrix(systemDim, systemDim);
            row = 0;
            for (int i = 0; i < fastInvarianceMatrix.getNumRows(); i++) {
                for (int col = 0; col < systemDim; col++) {
                    fullMatrix.set_elem(row, col, fastInvarianceMatrix.get(i, col));
                }
                row++;
            }
            for (int i = 0; i < fastMat.getNumRows(); i++) {
                for (int col = 0; col < systemDim; col++) {
                    fullMatrix.set_elem(row, col, fastMat.get(i, col));
                }
                row++;
            }
            inverseFullMatrix = new RationalExpMatrix(systemDim, systemDim);
            inverseFullMatrix.identity();
            RationalExpMatrix copyOfFullMatrix = new RationalExpMatrix(fullMatrix);
            copyOfFullMatrix.gaussianElimination(inverseFullMatrix);
            newSlowRateVector = new RationalExpMatrix(numDependent, 1);
            newSlowRateVector.matmul(fastInvarianceMatrix, origSlowRateVector);
        } catch (MatrixException ex) {
            ex.printStackTrace();
            throw new MathException(ex.getMessage());
        }
        sb.append("TRANSFORM\n");
        for (row = 0; row < systemDim; row++) {
            for (int col = 0; col < systemDim; col++) {
                sb.append(fullMatrix.get(row, col).getConstant().doubleValue() + " ");
            }
            sb.append("\n");
        }
        sb.append("INVERSETRANSFORM\n");
        for (row = 0; row < systemDim; row++) {
            for (int col = 0; col < systemDim; col++) {
                sb.append(inverseFullMatrix.get(row, col).getConstant().doubleValue() + " ");
            }
            sb.append("\n");
        }
        int numDifferential = numDependent;
        int numAlgebraic = numIndependent;
        sb.append("RHS DIFFERENTIAL " + numDifferential + " ALGEBRAIC " + numAlgebraic + "\n");
        int equationIndex = 0;
        while (equationIndex < numDependent) {
            // print row of mass matrix followed by slow rate corresponding to fast invariant
            Expression slowRateExp = new Expression(newSlowRateVector.get(equationIndex, 0).infixString()).flatten();
            slowRateExp.bindExpression(simSymbolTable);
            slowRateExp = MathUtilities.substituteFunctions(slowRateExp, varsSymbolTable).flatten();
            Vector<Discontinuity> v = slowRateExp.getDiscontinuities();
            for (Discontinuity od : v) {
                od = getSubsitutedAndFlattened(od, varsSymbolTable);
                String dname = discontinuityNameMap.get(od);
                if (dname == null) {
                    dname = ROOT_VARIABLE_PREFIX + discontinuityNameMap.size();
                    discontinuityNameMap.put(od, dname);
                }
                slowRateExp.substituteInPlace(od.getDiscontinuityExp(), new Expression("(" + dname + "==1)"));
            }
            sb.append(slowRateExp.infix() + ";\n");
            equationIndex++;
        }
        Enumeration<FastRate> enumFastRates = fastSystem.getFastRates();
        while (enumFastRates.hasMoreElements()) {
            // print the fastRate for this row
            Expression fastRateExp = new Expression(enumFastRates.nextElement().getFunction());
            fastRateExp = MathUtilities.substituteFunctions(fastRateExp, varsSymbolTable).flatten();
            Vector<Discontinuity> v = fastRateExp.getDiscontinuities();
            for (Discontinuity od : v) {
                od = getSubsitutedAndFlattened(od, varsSymbolTable);
                String dname = discontinuityNameMap.get(od);
                if (dname == null) {
                    dname = ROOT_VARIABLE_PREFIX + discontinuityNameMap.size();
                    discontinuityNameMap.put(od, dname);
                }
                fastRateExp.substituteInPlace(od.getDiscontinuityExp(), new Expression("(" + dname + "==1)"));
            }
            sb.append(fastRateExp.flatten().infix() + ";\n");
            equationIndex++;
        }
    } else {
        for (int i = 0; i < getStateVariableCount(); i++) {
            StateVariable stateVar = getStateVariable(i);
            Expression initExpr = new Expression(stateVar.getInitialRateExpression());
            initExpr = MathUtilities.substituteFunctions(initExpr, varsSymbolTable);
            initExpr.substituteInPlace(new Expression("t"), new Expression(0.0));
            sb.append("VAR " + stateVar.getVariable().getName() + " INIT " + initExpr.flatten().infix() + ";\n");
        }
        sb.append("TRANSFORM\n");
        for (int row = 0; row < getStateVariableCount(); row++) {
            for (int col = 0; col < getStateVariableCount(); col++) {
                sb.append((row == col ? 1 : 0) + " ");
            }
            sb.append("\n");
        }
        sb.append("INVERSETRANSFORM\n");
        for (int row = 0; row < getStateVariableCount(); row++) {
            for (int col = 0; col < getStateVariableCount(); col++) {
                sb.append((row == col ? 1 : 0) + " ");
            }
            sb.append("\n");
        }
        sb.append("RHS DIFFERENTIAL " + getStateVariableCount() + " ALGEBRAIC 0\n");
        for (int i = 0; i < getStateVariableCount(); i++) {
            StateVariable stateVar = getStateVariable(i);
            Expression rateExpr = new Expression(stateVar.getRateExpression());
            rateExpr = MathUtilities.substituteFunctions(rateExpr, varsSymbolTable).flatten();
            Vector<Discontinuity> v = rateExpr.getDiscontinuities();
            for (Discontinuity od : v) {
                od = getSubsitutedAndFlattened(od, varsSymbolTable);
                String dname = discontinuityNameMap.get(od);
                if (dname == null) {
                    dname = ROOT_VARIABLE_PREFIX + discontinuityNameMap.size();
                    discontinuityNameMap.put(od, dname);
                }
                rateExpr.substituteInPlace(od.getDiscontinuityExp(), new Expression("(" + dname + "==1)"));
            }
            sb.append(rateExpr.infix() + ";\n");
        }
    }
    return sb.toString();
}
Also used : Variable(cbit.vcell.math.Variable) MathDescription(cbit.vcell.math.MathDescription) MatrixException(cbit.vcell.matrix.MatrixException) RationalExpMatrix(cbit.vcell.matrix.RationalExpMatrix) HashSet(java.util.HashSet) Discontinuity(cbit.vcell.parser.Discontinuity) SimulationSymbolTable(cbit.vcell.solver.SimulationSymbolTable) Equation(cbit.vcell.math.Equation) FastRate(cbit.vcell.math.FastRate) RationalExp(cbit.vcell.matrix.RationalExp) FastInvariant(cbit.vcell.math.FastInvariant) FastSystemAnalyzer(cbit.vcell.mapping.FastSystemAnalyzer) Simulation(cbit.vcell.solver.Simulation) FastSystem(cbit.vcell.math.FastSystem) Expression(cbit.vcell.parser.Expression) CompartmentSubDomain(cbit.vcell.math.CompartmentSubDomain) MathException(cbit.vcell.math.MathException)

Example 4 with Discontinuity

use of cbit.vcell.parser.Discontinuity in project vcell by virtualcell.

the class CVodeFileWriter method writeEquations.

/**
 * Insert the method's description here.
 * Creation date: (3/8/00 10:31:52 PM)
 */
protected String writeEquations(HashMap<Discontinuity, String> discontinuityNameMap) throws MathException, ExpressionException {
    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < getStateVariableCount(); i++) {
        StateVariable stateVar = getStateVariable(i);
        Expression rateExpr = new Expression(stateVar.getRateExpression());
        Expression initExpr = new Expression(stateVar.getInitialRateExpression());
        initExpr = MathUtilities.substituteFunctions(initExpr, varsSymbolTable).flatten();
        initExpr.substituteInPlace(new Expression("t"), new Expression(0.0));
        String[] symbols0 = initExpr.getSymbols();
        if (symbols0 != null) {
            for (String symbol : symbols0) {
                SymbolTableEntry ste = initExpr.getSymbolBinding(symbol);
                if (!ste.equals(ReservedVariable.X) && !ste.equals(ReservedVariable.Y) && !ste.equals(ReservedVariable.Z)) {
                    throw new MathException("Variables are not allowed in initial condition.\nInitial condition of variable:" + stateVar.getVariable().getName() + " has variable(" + symbol + ") in expression.");
                }
            }
        }
        rateExpr = MathUtilities.substituteFunctions(rateExpr, varsSymbolTable).flatten();
        Vector<Discontinuity> v = rateExpr.getDiscontinuities();
        for (Discontinuity od : v) {
            od = getSubsitutedAndFlattened(od, varsSymbolTable);
            String dname = discontinuityNameMap.get(od);
            if (dname == null) {
                dname = ROOT_VARIABLE_PREFIX + discontinuityNameMap.size();
                discontinuityNameMap.put(od, dname);
            }
            rateExpr.substituteInPlace(od.getDiscontinuityExp(), new Expression("(" + dname + "==1)"));
        }
        sb.append("ODE " + stateVar.getVariable().getName() + " INIT " + initExpr.flatten().infix() + ";\n\t RATE " + rateExpr.flatten().infix() + ";\n");
    }
    return sb.toString();
}
Also used : Discontinuity(cbit.vcell.parser.Discontinuity) SymbolTableEntry(cbit.vcell.parser.SymbolTableEntry) Expression(cbit.vcell.parser.Expression) MathException(cbit.vcell.math.MathException)

Example 5 with Discontinuity

use of cbit.vcell.parser.Discontinuity in project vcell by virtualcell.

the class Equation method getDiscontinuities.

public final void getDiscontinuities(MathSymbolTable simSymbolTable, Vector<Discontinuity> discontinuities) throws ExpressionException, MathException {
    Vector<Expression> expressions = getExpressions(simSymbolTable.getMathDescription());
    for (Expression exp : expressions) {
        Expression exp1 = new Expression(exp);
        exp1.bindExpression(simSymbolTable);
        exp1 = simSymbolTable.substituteFunctions(exp1).flatten();
        Vector<Discontinuity> v = exp1.getDiscontinuities();
        discontinuities.addAll(v);
    }
}
Also used : Discontinuity(cbit.vcell.parser.Discontinuity) Expression(cbit.vcell.parser.Expression)

Aggregations

Discontinuity (cbit.vcell.parser.Discontinuity)8 Expression (cbit.vcell.parser.Expression)6 Simulation (cbit.vcell.solver.Simulation)5 MathDescription (cbit.vcell.math.MathDescription)3 CompartmentSubDomain (cbit.vcell.math.CompartmentSubDomain)2 Equation (cbit.vcell.math.Equation)2 MathException (cbit.vcell.math.MathException)2 Variable (cbit.vcell.math.Variable)2 DefaultOutputTimeSpec (cbit.vcell.solver.DefaultOutputTimeSpec)2 ErrorTolerance (cbit.vcell.solver.ErrorTolerance)2 OutputTimeSpec (cbit.vcell.solver.OutputTimeSpec)2 SimulationSymbolTable (cbit.vcell.solver.SimulationSymbolTable)2 SolverTaskDescription (cbit.vcell.solver.SolverTaskDescription)2 UniformOutputTimeSpec (cbit.vcell.solver.UniformOutputTimeSpec)2 FastSystemAnalyzer (cbit.vcell.mapping.FastSystemAnalyzer)1 Event (cbit.vcell.math.Event)1 Delay (cbit.vcell.math.Event.Delay)1 EventAssignment (cbit.vcell.math.Event.EventAssignment)1 FastInvariant (cbit.vcell.math.FastInvariant)1 FastRate (cbit.vcell.math.FastRate)1