Search in sources :

Example 46 with Simulation

use of cbit.vcell.solver.Simulation in project vcell by virtualcell.

the class ITextWriter method writeSimulationContext.

// SimulationContext: ignored the constraints (steady/unsteady).
// Electrical Stimulus: ignored the Ground Electrode,
protected void writeSimulationContext(Chapter simContextsChapter, SimulationContext simContext, PublishPreferences preferences) throws Exception {
    Section simContextSection = simContextsChapter.addSection("Application: " + simContext.getName(), simContextsChapter.numberDepth() + 1);
    writeMetadata(simContextSection, simContext.getName(), simContext.getDescription(), null, "Application ");
    // add geometry context (structure mapping)
    writeStructureMapping(simContextSection, simContext);
    // add reaction context (Reaction Mapping)
    writeReactionContext(simContextSection, simContext);
    // add Membrane Mapping & electrical stimuli
    writeMembraneMapping(simContextSection, simContext);
    // 
    if (preferences.includeGeom()) {
        writeGeom(simContextSection, simContext.getGeometry(), simContext.getGeometryContext());
    }
    if (preferences.includeMathDesc()) {
        writeMathDescAsText(simContextSection, simContext.getMathDescription());
    // writeMathDescAsImages(simContextSection, simContext.getMathDescription());
    }
    if (preferences.includeSim()) {
        Section simSection = simContextSection.addSection("Simulation(s)", simContextSection.depth() + 1);
        Simulation[] sims = simContext.getSimulations();
        for (int i = 0; i < sims.length; i++) {
            writeSimulation(simSection, sims[i]);
        }
    }
}
Also used : Simulation(cbit.vcell.solver.Simulation) Section(com.lowagie.text.Section)

Example 47 with Simulation

use of cbit.vcell.solver.Simulation in project vcell by virtualcell.

the class AbstractJavaSolver method printToFile.

/**
 * Insert the method's description here.
 * Creation date: (6/27/2001 12:17:36 PM)
 */
protected final void printToFile(double progress) throws IOException {
    long currentTime = System.currentTimeMillis();
    // decide whether to fire progress event
    boolean shouldFire = false;
    if (progress <= 0 || progress >= 1) {
        // always fire at begin and end
        shouldFire = true;
    } else {
        // only fire at specified increment
        shouldFire = (progress - lastFiredProgress) * 100 > getProgressIncrement();
    }
    if (shouldFire) {
        lastFiredProgress = progress;
        fireSolverProgress(progress);
    }
    // decide whether to save to file
    boolean shouldSave = false;
    // only if enabled
    if (isSaveEnabled()) {
        // check to see whether we need to save
        if (progress <= 0) {
            // a new run just got initialized; save 0 datapoint
            shouldSave = true;
        } else if (progress >= 1) {
            // a run finished; save last datapoint
            shouldSave = true;
        } else {
            // in the middle of a run; only save at specified time interval
            shouldSave = currentTime - lastSavedMS > 1000 * getSaveToFileInterval();
        }
        if (shouldSave) {
            // write file and fire event
            if (this instanceof ODESolver) {
                ODESolverResultSet odeSolverResultSet = ((ODESolver) this).getODESolverResultSet();
                Simulation simulation = simTask.getSimulationJob().getSimulation();
                OutputTimeSpec outputTimeSpec = simulation.getSolverTaskDescription().getOutputTimeSpec();
                if (outputTimeSpec.isDefault()) {
                    odeSolverResultSet.trimRows(((DefaultOutputTimeSpec) outputTimeSpec).getKeepAtMost());
                }
                ODESimData odeSimData = new ODESimData(new VCSimulationDataIdentifier(simulation.getSimulationInfo().getAuthoritativeVCSimulationIdentifier(), getJobIndex()), odeSolverResultSet);
                String mathName = odeSimData.getMathName();
                if (lg.isTraceEnabled())
                    lg.trace("AbstractJavaSolver.printToFile(" + mathName + ")");
                File logFile = new File(getBaseName() + LOGFILE_EXTENSION);
                File dataFile = new File(getBaseName() + ODE_DATA_EXTENSION);
                ODESimData.writeODEDataFile(odeSimData, dataFile);
                odeSimData.writeODELogFile(logFile, dataFile);
            }
            lastSavedMS = System.currentTimeMillis();
            fireSolverPrinted(getCurrentTime());
        }
    }
}
Also used : DefaultOutputTimeSpec(cbit.vcell.solver.DefaultOutputTimeSpec) OutputTimeSpec(cbit.vcell.solver.OutputTimeSpec) Simulation(cbit.vcell.solver.Simulation) VCSimulationDataIdentifier(cbit.vcell.solver.VCSimulationDataIdentifier) File(java.io.File)

Example 48 with Simulation

use of cbit.vcell.solver.Simulation in project vcell by virtualcell.

the class DefaultODESolver method updateResultSet.

/**
 * This method was created by a SmartGuide.
 */
protected final void updateResultSet() throws IOException, ExpressionException {
    ODESolverResultSet results = getODESolverResultSet();
    synchronized (results) {
        // so that we don't mess up when saving or reading intermediate results; performance penalty minimal
        double[] valueVector = getValueVector(0);
        // one extra index for time.
        double[] values = new double[getStateVariableCount() + 1];
        for (int i = 0; i < getStateVariableCount(); i++) {
            int c = results.findColumn(getStateVariable(i).getVariable().getName());
            // cbit.util.Assertion.assert(c >= 0 && c < results.getDataColumnCount());
            values[c] = valueVector[getVariableIndex(i)];
        }
        values[ReservedVariable.TIME.getIndex()] = getCurrentTime();
        results.addRow(values);
    }
    // setSolverStatus(new SolverStatus (SolverStatus.SOLVER_RUNNING));
    Simulation sim = simTask.getSimulation();
    double t = getCurrentTime();
    TimeBounds timeBounds = sim.getSolverTaskDescription().getTimeBounds();
    double t0 = timeBounds.getStartingTime();
    double t1 = timeBounds.getEndingTime();
    printToFile((t - t0) / (t1 - t0));
}
Also used : TimeBounds(cbit.vcell.solver.TimeBounds) Simulation(cbit.vcell.solver.Simulation)

Example 49 with Simulation

use of cbit.vcell.solver.Simulation in project vcell by virtualcell.

the class DefaultODESolver method initialize.

/**
 * This method was created by a SmartGuide.
 * @exception SolverException The exception description.
 */
protected void initialize() throws SolverException {
    SimulationSymbolTable simSymbolTable = simTask.getSimulationJob().getSimulationSymbolTable();
    Simulation sim = simSymbolTable.getSimulation();
    try {
        // create a fast system if necessary
        fieldFastAlgebraicSystem = null;
        if (getSubDomain().getFastSystem() != null) {
            fieldFastAlgebraicSystem = new FastAlgebraicSystem(new FastSystemAnalyzer(getSubDomain().getFastSystem(), simSymbolTable));
        }
        // refreshIdentifiers();
        fieldIdentifiers = createIdentifiers();
        fieldSensVariables = createSensitivityVariables();
        // refreshStateVariables();
        fieldStateVariables = createStateVariables();
        // 
        // allocate ValueVectors object
        fieldValueVectors = new ValueVectors(getValueVectorCount(), fieldIdentifiers.size());
        // initialize indexes of variables
        fieldVariableIndexes = new int[getStateVariableCount()];
        for (int i = 0; i < getStateVariableCount(); i++) {
            fieldVariableIndexes[i] = getStateVariable(i).getVariable().getIndex();
        }
        // initialize constants
        double[] initialValues = getValueVector(0);
        for (int i = 0; i < fieldIdentifiers.size(); i++) {
            if (fieldIdentifiers.elementAt(i) instanceof Constant) {
                Constant constant = (Constant) fieldIdentifiers.elementAt(i);
                constant.bind(simSymbolTable);
                if (constant.isConstant()) {
                    // constant.getValue();
                    initialValues[constant.getIndex()] = constant.getExpression().evaluateConstant();
                } else {
                    throw new SolverException("cannot evaluate constant '" + constant.getName() + "' = " + constant.getExpression());
                }
            }
        }
        // initialize variables
        for (int i = 0; i < getStateVariableCount(); i++) {
            initialValues[getVariableIndex(i)] = getStateVariable(i).evaluateIC(initialValues);
        }
        fieldODESolverResultSet = createODESolverResultSet();
        // reset - in the ** default ** solvers we don't pick up from where we left off, we can override that behaviour in integrate() if ever necessary
        fieldCurrentTime = sim.getSolverTaskDescription().getTimeBounds().getStartingTime();
    } catch (ExpressionException expressionException) {
        expressionException.printStackTrace(System.out);
        throw new SolverException(expressionException.getMessage());
    } catch (MathException mathException) {
        mathException.printStackTrace(System.out);
        throw new SolverException(mathException.getMessage());
    }
}
Also used : FastSystemAnalyzer(cbit.vcell.mapping.FastSystemAnalyzer) Simulation(cbit.vcell.solver.Simulation) Constant(cbit.vcell.math.Constant) PseudoConstant(cbit.vcell.math.PseudoConstant) MathException(cbit.vcell.math.MathException) SimulationSymbolTable(cbit.vcell.solver.SimulationSymbolTable) SolverException(cbit.vcell.solver.SolverException) ExpressionException(cbit.vcell.parser.ExpressionException)

Example 50 with Simulation

use of cbit.vcell.solver.Simulation 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

Simulation (cbit.vcell.solver.Simulation)195 SimulationContext (cbit.vcell.mapping.SimulationContext)57 BioModel (cbit.vcell.biomodel.BioModel)53 MathDescription (cbit.vcell.math.MathDescription)48 KeyValue (org.vcell.util.document.KeyValue)33 Geometry (cbit.vcell.geometry.Geometry)29 MathModel (cbit.vcell.mathmodel.MathModel)27 Expression (cbit.vcell.parser.Expression)26 DataAccessException (org.vcell.util.DataAccessException)26 File (java.io.File)25 ExpressionException (cbit.vcell.parser.ExpressionException)24 IOException (java.io.IOException)24 SimulationJob (cbit.vcell.solver.SimulationJob)23 ArrayList (java.util.ArrayList)23 PropertyVetoException (java.beans.PropertyVetoException)20 UniformOutputTimeSpec (cbit.vcell.solver.UniformOutputTimeSpec)18 XMLSource (cbit.vcell.xml.XMLSource)18 SimulationTask (cbit.vcell.messaging.server.SimulationTask)17 TimeBounds (cbit.vcell.solver.TimeBounds)16 BigString (org.vcell.util.BigString)16