Search in sources :

Example 11 with Equation

use of cbit.vcell.math.Equation 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());
        }
        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);
    }
    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) 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 12 with Equation

use of cbit.vcell.math.Equation in project vcell by virtualcell.

the class ITextWriter method writeSubDomainsEquationsAsImages.

// currently not used.
protected void writeSubDomainsEquationsAsImages(Section mathDescSection, MathDescription mathDesc) {
    Enumeration<SubDomain> subDomains = mathDesc.getSubDomains();
    Expression[] expArray;
    Section volDomains = mathDescSection.addSection("Volume Domains", mathDescSection.depth() + 1);
    Section memDomains = mathDescSection.addSection("Membrane Domains", mathDescSection.depth() + 1);
    // arbitrary
    int scale = 1, height = 200;
    int viewableWidth = (int) (document.getPageSize().width() - document.leftMargin() - document.rightMargin());
    BufferedImage dummy = new BufferedImage(viewableWidth, height, BufferedImage.TYPE_3BYTE_BGR);
    while (subDomains.hasMoreElements()) {
        SubDomain subDomain = subDomains.nextElement();
        Enumeration<Equation> equationsList = subDomain.getEquations();
        ArrayList<Expression> expList = new ArrayList<Expression>();
        while (equationsList.hasMoreElements()) {
            Equation equ = equationsList.nextElement();
            try {
                Enumeration<Expression> enum_equ = equ.getTotalExpressions();
                while (enum_equ.hasMoreElements()) {
                    Expression exp = new Expression(enum_equ.nextElement());
                    expList.add(exp.flatten());
                }
            } catch (ExpressionException ee) {
                System.err.println("Unable to process the equation for subdomain: " + subDomain.getName());
                ee.printStackTrace();
                continue;
            }
        }
        expArray = (Expression[]) expList.toArray(new Expression[expList.size()]);
        Section tempSection = null;
        if (subDomain instanceof CompartmentSubDomain) {
            tempSection = volDomains.addSection(subDomain.getName(), volDomains.depth() + 1);
        } else if (subDomain instanceof MembraneSubDomain) {
            tempSection = memDomains.addSection(subDomain.getName(), memDomains.depth() + 1);
        }
        try {
            Dimension dim = ExpressionCanvas.getExpressionImageSize(expArray, (Graphics2D) dummy.getGraphics());
            System.out.println("Image dim: " + dim.width + " " + dim.height);
            BufferedImage bufferedImage = new BufferedImage((int) dim.getWidth() * scale, (int) dim.getHeight() * scale, BufferedImage.TYPE_3BYTE_BGR);
            ExpressionCanvas.getExpressionAsImage(expArray, bufferedImage, scale);
            // Table imageTable = null;;
            com.lowagie.text.Image expImage = com.lowagie.text.Image.getInstance(bufferedImage, null);
            expImage.setAlignment(com.lowagie.text.Image.LEFT);
            if (viewableWidth < expImage.scaledWidth()) {
                expImage.scaleToFit(viewableWidth, expImage.height());
                System.out.println("SubDomain expresions After scaling: " + expImage.scaledWidth());
            }
            /*Cell imageCell = new Cell();
				imageCell.add(expImage);
				if (imageTable == null) {
					imageTable = getTable(1, 100, 1, 1, 0);
				}
				imageTable.setTableFitsPage(false);
 				imageTable.setCellsFitPage(false);
				imageTable.addCell(imageCell);
				imageTable.setWidth(100);
				tempSection.add(imageTable);*/
            tempSection.add(expImage);
        } catch (Exception e) {
            System.err.println("Unable to add subdomain equation image to report.");
            e.printStackTrace();
        }
    }
    if (volDomains.isEmpty()) {
        mathDescSection.remove(volDomains);
    }
    if (memDomains.isEmpty()) {
        mathDescSection.remove(memDomains);
    }
}
Also used : MembraneSubDomain(cbit.vcell.math.MembraneSubDomain) ArrayList(java.util.ArrayList) PdeEquation(cbit.vcell.math.PdeEquation) VolumeRegionEquation(cbit.vcell.math.VolumeRegionEquation) OdeEquation(cbit.vcell.math.OdeEquation) FilamentRegionEquation(cbit.vcell.math.FilamentRegionEquation) MembraneRegionEquation(cbit.vcell.math.MembraneRegionEquation) Equation(cbit.vcell.math.Equation) Dimension(java.awt.Dimension) Section(com.lowagie.text.Section) BufferedImage(java.awt.image.BufferedImage) ExpressionException(cbit.vcell.parser.ExpressionException) DocumentException(com.lowagie.text.DocumentException) ExpressionException(cbit.vcell.parser.ExpressionException) CompartmentSubDomain(cbit.vcell.math.CompartmentSubDomain) FilamentSubDomain(cbit.vcell.math.FilamentSubDomain) SubDomain(cbit.vcell.math.SubDomain) MembraneSubDomain(cbit.vcell.math.MembraneSubDomain) Expression(cbit.vcell.parser.Expression) CompartmentSubDomain(cbit.vcell.math.CompartmentSubDomain) SimulationContext(cbit.vcell.mapping.SimulationContext) GeometryContext(cbit.vcell.mapping.GeometryContext) ReactionContext(cbit.vcell.mapping.ReactionContext)

Example 13 with Equation

use of cbit.vcell.math.Equation in project vcell by virtualcell.

the class ITextWriter method writeSubDomainsEquationsAsText.

protected void writeSubDomainsEquationsAsText(Section mathDescSection, MathDescription mathDesc) throws DocumentException {
    Enumeration<SubDomain> subDomains = mathDesc.getSubDomains();
    Section volDomains = mathDescSection.addSection("Volume Domains", mathDescSection.depth() + 1);
    Section memDomains = mathDescSection.addSection("Membrane Domains", mathDescSection.depth() + 1);
    Section filDomains = mathDescSection.addSection("Filament Domains", mathDescSection.depth() + 1);
    while (subDomains.hasMoreElements()) {
        Section tempSection = null;
        SubDomain subDomain = subDomains.nextElement();
        if (subDomain instanceof CompartmentSubDomain) {
            tempSection = volDomains.addSection(subDomain.getName(), volDomains.depth() + 1);
        } else if (subDomain instanceof MembraneSubDomain) {
            tempSection = memDomains.addSection(subDomain.getName(), memDomains.depth() + 1);
        } else if (subDomain instanceof FilamentSubDomain) {
            tempSection = filDomains.addSection(subDomain.getName(), filDomains.depth() + 1);
        }
        Enumeration<Equation> equationsList = subDomain.getEquations();
        while (equationsList.hasMoreElements()) {
            Equation equ = equationsList.nextElement();
            writeEquation(tempSection, equ);
        }
        if (subDomain.getFastSystem() != null) {
            writeFastSystem(tempSection, subDomain.getFastSystem());
        }
        if (subDomain instanceof MembraneSubDomain) {
            Enumeration<JumpCondition> jcList = ((MembraneSubDomain) subDomain).getJumpConditions();
            while (jcList.hasMoreElements()) {
                JumpCondition jc = jcList.nextElement();
                writeJumpCondition(tempSection, jc);
            }
        }
    }
    if (volDomains.isEmpty()) {
        mathDescSection.remove(volDomains);
    }
    if (memDomains.isEmpty()) {
        mathDescSection.remove(memDomains);
    }
    if (filDomains.isEmpty()) {
        mathDescSection.remove(filDomains);
    }
}
Also used : CompartmentSubDomain(cbit.vcell.math.CompartmentSubDomain) FilamentSubDomain(cbit.vcell.math.FilamentSubDomain) SubDomain(cbit.vcell.math.SubDomain) MembraneSubDomain(cbit.vcell.math.MembraneSubDomain) JumpCondition(cbit.vcell.math.JumpCondition) MembraneSubDomain(cbit.vcell.math.MembraneSubDomain) CompartmentSubDomain(cbit.vcell.math.CompartmentSubDomain) PdeEquation(cbit.vcell.math.PdeEquation) VolumeRegionEquation(cbit.vcell.math.VolumeRegionEquation) OdeEquation(cbit.vcell.math.OdeEquation) FilamentRegionEquation(cbit.vcell.math.FilamentRegionEquation) MembraneRegionEquation(cbit.vcell.math.MembraneRegionEquation) Equation(cbit.vcell.math.Equation) Section(com.lowagie.text.Section) FilamentSubDomain(cbit.vcell.math.FilamentSubDomain)

Example 14 with Equation

use of cbit.vcell.math.Equation in project vcell by virtualcell.

the class SimulationSymbolTable method hasTimeVaryingDiffusionOrAdvection.

public boolean hasTimeVaryingDiffusionOrAdvection(Variable variable) throws MathException, ExpressionException {
    Enumeration<SubDomain> enum1 = simulation.getMathDescription().getSubDomains();
    while (enum1.hasMoreElements()) {
        SubDomain subDomain = enum1.nextElement();
        Equation equation = subDomain.getEquation(variable);
        // 
        if (equation instanceof PdeEquation) {
            Vector<Expression> spatialExpressionList = new Vector<Expression>();
            spatialExpressionList.add(((PdeEquation) equation).getDiffusionExpression());
            if (((PdeEquation) equation).getVelocityX() != null) {
                spatialExpressionList.add(((PdeEquation) equation).getVelocityX());
            }
            if (((PdeEquation) equation).getVelocityY() != null) {
                spatialExpressionList.add(((PdeEquation) equation).getVelocityY());
            }
            if (((PdeEquation) equation).getVelocityZ() != null) {
                spatialExpressionList.add(((PdeEquation) equation).getVelocityZ());
            }
            for (int i = 0; i < spatialExpressionList.size(); i++) {
                Expression spatialExp = spatialExpressionList.elementAt(i);
                spatialExp = substituteFunctions(spatialExp);
                String[] symbols = spatialExp.getSymbols();
                if (symbols != null) {
                    for (int j = 0; j < symbols.length; j++) {
                        SymbolTableEntry entry = spatialExp.getSymbolBinding(symbols[j]);
                        if (entry instanceof ReservedVariable) {
                            if (((ReservedVariable) entry).isTIME()) {
                                return true;
                            }
                        }
                        if (entry instanceof VolVariable) {
                            return true;
                        }
                        if (entry instanceof VolumeRegionVariable) {
                            return true;
                        }
                        if (entry instanceof MemVariable || entry instanceof MembraneRegionVariable) {
                            return true;
                        }
                    }
                }
            }
        }
    }
    return false;
}
Also used : MembraneRegionVariable(cbit.vcell.math.MembraneRegionVariable) VolVariable(cbit.vcell.math.VolVariable) PdeEquation(cbit.vcell.math.PdeEquation) Equation(cbit.vcell.math.Equation) SubDomain(cbit.vcell.math.SubDomain) MembraneSubDomain(cbit.vcell.math.MembraneSubDomain) PdeEquation(cbit.vcell.math.PdeEquation) VolumeRegionVariable(cbit.vcell.math.VolumeRegionVariable) SymbolTableEntry(cbit.vcell.parser.SymbolTableEntry) ReservedVariable(cbit.vcell.math.ReservedVariable) MemVariable(cbit.vcell.math.MemVariable) Expression(cbit.vcell.parser.Expression) Vector(java.util.Vector)

Example 15 with Equation

use of cbit.vcell.math.Equation 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)

Aggregations

Equation (cbit.vcell.math.Equation)32 PdeEquation (cbit.vcell.math.PdeEquation)21 OdeEquation (cbit.vcell.math.OdeEquation)20 SubDomain (cbit.vcell.math.SubDomain)17 CompartmentSubDomain (cbit.vcell.math.CompartmentSubDomain)16 Variable (cbit.vcell.math.Variable)16 Expression (cbit.vcell.parser.Expression)16 Vector (java.util.Vector)14 MembraneRegionEquation (cbit.vcell.math.MembraneRegionEquation)13 MembraneSubDomain (cbit.vcell.math.MembraneSubDomain)13 VolVariable (cbit.vcell.math.VolVariable)13 MathDescription (cbit.vcell.math.MathDescription)12 VolumeRegionEquation (cbit.vcell.math.VolumeRegionEquation)12 MathException (cbit.vcell.math.MathException)10 Constant (cbit.vcell.math.Constant)8 JumpCondition (cbit.vcell.math.JumpCondition)8 MemVariable (cbit.vcell.math.MemVariable)8 MembraneRegionVariable (cbit.vcell.math.MembraneRegionVariable)8 SimulationSymbolTable (cbit.vcell.solver.SimulationSymbolTable)8 Function (cbit.vcell.math.Function)7