Search in sources :

Example 56 with Simulation

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

the class XmlHelper method exportSBML.

/**
 * Exports VCML format to another supported format (currently: SBML or CellML). It allows
 *   choosing a specific Simulation Spec to export.
 * Creation date: (4/8/2003 12:30:27 PM)
 * @return java.lang.String
 */
public static String exportSBML(VCDocument vcDoc, int level, int version, int pkgVersion, boolean isSpatial, SimulationContext simContext, SimulationJob simJob) throws XmlParseException {
    if (vcDoc == null) {
        throw new XmlParseException("Invalid arguments for exporting SBML.");
    }
    if (vcDoc instanceof BioModel) {
        try {
            // check if model to be exported to SBML has units compatible with SBML default units (default units in SBML can be assumed only until SBML Level2)
            ModelUnitSystem forcedModelUnitSystem = simContext.getModel().getUnitSystem();
            if (level < 3 && !ModelUnitSystem.isCompatibleWithDefaultSBMLLevel2Units(forcedModelUnitSystem)) {
                forcedModelUnitSystem = ModelUnitSystem.createDefaultSBMLLevel2Units();
            }
            // create new Biomodel with new (SBML compatible)  unit system
            BioModel modifiedBiomodel = ModelUnitConverter.createBioModelWithNewUnitSystem(simContext.getBioModel(), forcedModelUnitSystem);
            // extract the simContext from new Biomodel. Apply overrides to *this* modified simContext
            SimulationContext simContextFromModifiedBioModel = modifiedBiomodel.getSimulationContext(simContext.getName());
            SimulationContext clonedSimContext = applyOverridesForSBML(modifiedBiomodel, simContextFromModifiedBioModel, simJob);
            // extract sim (in simJob) from modified Biomodel, if not null
            SimulationJob modifiedSimJob = null;
            if (simJob != null) {
                Simulation simFromModifiedBiomodel = clonedSimContext.getSimulation(simJob.getSimulation().getName());
                modifiedSimJob = new SimulationJob(simFromModifiedBiomodel, simJob.getJobIndex(), null);
            }
            SBMLExporter sbmlExporter = new SBMLExporter(modifiedBiomodel, level, version, isSpatial);
            sbmlExporter.setSelectedSimContext(simContextFromModifiedBioModel);
            sbmlExporter.setSelectedSimulationJob(modifiedSimJob);
            return sbmlExporter.getSBMLFile();
        } catch (ExpressionException | SbmlException | SBMLException | XMLStreamException e) {
            e.printStackTrace(System.out);
            throw new XmlParseException(e);
        }
    } else if (vcDoc instanceof MathModel) {
        try {
            return MathModel_SBMLExporter.getSBMLString((MathModel) vcDoc, level, version);
        } catch (ExpressionException | IOException | SBMLException | XMLStreamException e) {
            e.printStackTrace(System.out);
            throw new XmlParseException(e);
        }
    } else {
        throw new RuntimeException("unsupported Document Type " + vcDoc.getClass().getName() + " for SBML export");
    }
}
Also used : SBMLException(org.sbml.jsbml.SBMLException) MathModel(cbit.vcell.mathmodel.MathModel) MathModel_SBMLExporter(org.vcell.sbml.vcell.MathModel_SBMLExporter) SBMLExporter(org.vcell.sbml.vcell.SBMLExporter) SimulationContext(cbit.vcell.mapping.SimulationContext) ExpressionException(cbit.vcell.parser.ExpressionException) Simulation(cbit.vcell.solver.Simulation) XMLStreamException(javax.xml.stream.XMLStreamException) BioModel(cbit.vcell.biomodel.BioModel) SbmlException(org.vcell.sbml.SbmlException) SimulationJob(cbit.vcell.solver.SimulationJob) ModelUnitSystem(cbit.vcell.model.ModelUnitSystem)

Example 57 with Simulation

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

the class NetCDFWriter method initialize.

/**
 * Extract infomation from simulation to write hybrid input file.
 * Validate the information. If it is valid, a true value will be return.
 * The function will be called by writeHybridInputFile().
 * Creation date: (5/22/2007 3:59:34 PM)
 * @return boolean
 */
public boolean initialize() throws Exception {
    Simulation simulation = simTask.getSimulation();
    // check variables
    if (!simulation.getMathDescription().getVariables().hasMoreElements()) {
        throw new MathException("Stochastic model has no variable.");
    }
    // check subDomain
    SubDomain subDomain = null;
    Enumeration<SubDomain> e = simulation.getMathDescription().getSubDomains();
    if (e.hasMoreElements()) {
        subDomain = e.nextElement();
    } else
        throw new MathException("There is no sub domain.");
    // check jump processes
    if (subDomain.getJumpProcesses().size() < 1) {
        throw new MathException("Stochastic model has no jump process.");
    }
    return true;
}
Also used : SubDomain(cbit.vcell.math.SubDomain) Simulation(cbit.vcell.solver.Simulation) MathException(cbit.vcell.math.MathException)

Example 58 with Simulation

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

the class NetCDFWriter method getVariableSymbols.

private String[] getVariableSymbols(String[] symbols) {
    Simulation simulation = simTask.getSimulation();
    Vector<String> vars = new Vector<String>();
    if (symbols != null) {
        for (int i = 0; i < symbols.length; i++) {
            Variable v = simulation.getMathDescription().getVariable(symbols[i]);
            if ((v != null) && (v instanceof StochVolVariable)) {
                vars.add(symbols[i]);
            }
        }
        return vars.toArray(new String[vars.size()]);
    } else
        return vars.toArray(new String[0]);
}
Also used : StochVolVariable(cbit.vcell.math.StochVolVariable) Variable(cbit.vcell.math.Variable) Simulation(cbit.vcell.solver.Simulation) Vector(java.util.Vector) StochVolVariable(cbit.vcell.math.StochVolVariable)

Example 59 with Simulation

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

the class StochFileWriter method initialize.

/**
 * Get infomation for stochasic input file.
 * Validate the information. If it is valid, a true value will be return.
 * The function will be called by writeStochInputFile().
 * Creation date: (6/23/2006 3:59:34 PM)
 * @return boolean
 */
public void initialize() throws Exception {
    Simulation simulation = simTask.getSimulation();
    // check variables
    if (!simulation.getMathDescription().getVariables().hasMoreElements()) {
        throw new MathException("Stochastic model has no variable.");
    }
    // check subDomain
    SubDomain subDomain = null;
    Enumeration<SubDomain> e = simulation.getMathDescription().getSubDomains();
    if (e.hasMoreElements()) {
        subDomain = e.nextElement();
    } else
        throw new MathException("There is no sub domain.");
    // check jump processes
    if (subDomain.getJumpProcesses().size() < 1) {
        throw new MathException("Stochastic model has no jump process.");
    }
}
Also used : SubDomain(cbit.vcell.math.SubDomain) Simulation(cbit.vcell.solver.Simulation) MathException(cbit.vcell.math.MathException)

Example 60 with Simulation

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

the class StochFileWriter method write.

/**
 * Write the model to a text file which serves as an input for Stochastic simulation engine.
 * Creation date: (6/22/2006 5:37:26 PM)
 */
public void write(String[] parameterNames) throws Exception, ExpressionException {
    Simulation simulation = simTask.getSimulation();
    SimulationSymbolTable simSymbolTable = simTask.getSimulationJob().getSimulationSymbolTable();
    initialize();
    if (bUseMessaging) {
        writeJMSParamters();
    }
    // Write control information
    printWriter.println("<control>");
    cbit.vcell.solver.SolverTaskDescription solverTaskDescription = simulation.getSolverTaskDescription();
    cbit.vcell.solver.TimeBounds timeBounds = solverTaskDescription.getTimeBounds();
    cbit.vcell.solver.OutputTimeSpec outputTimeSpec = solverTaskDescription.getOutputTimeSpec();
    ErrorTolerance errorTolerance = solverTaskDescription.getErrorTolerance();
    NonspatialStochSimOptions stochOpt = solverTaskDescription.getStochOpt();
    printWriter.println("STARTING_TIME" + "\t" + timeBounds.getStartingTime());
    printWriter.println("ENDING_TIME " + "\t" + timeBounds.getEndingTime());
    // pw.println("MAX_ITERATION"+"\t"+outputTimeSpec.getKeepAtMost());
    printWriter.println("TOLERANCE " + "\t" + errorTolerance.getAbsoluteErrorTolerance());
    if (outputTimeSpec.isDefault()) {
        printWriter.println("SAMPLE_INTERVAL" + "\t" + ((DefaultOutputTimeSpec) outputTimeSpec).getKeepEvery());
        printWriter.println("MAX_SAVE_POINTS" + "\t" + ((DefaultOutputTimeSpec) outputTimeSpec).getKeepAtMost());
    } else if (outputTimeSpec.isUniform()) {
        printWriter.println("SAVE_PERIOD" + "\t" + ((UniformOutputTimeSpec) outputTimeSpec).getOutputTimeStep());
    }
    printWriter.println("NUM_TRIAL" + "\t" + solverTaskDescription.getStochOpt().getNumOfTrials());
    if (stochOpt.isUseCustomSeed()) {
        printWriter.println("SEED" + "\t" + stochOpt.getCustomSeed());
    } else {
        // we generate our own random seed
        RandomDataGenerator rdg = new RandomDataGenerator();
        int randomSeed = rdg.nextInt(1, Integer.MAX_VALUE);
        printWriter.println("SEED" + "\t" + randomSeed);
    }
    printWriter.println("</control>");
    printWriter.println();
    // write model information
    // Model info. will be extracted from subDomain of mathDescription
    Enumeration<SubDomain> e = simulation.getMathDescription().getSubDomains();
    SubDomain subDomain = null;
    if (e.hasMoreElements()) {
        subDomain = e.nextElement();
    }
    if (subDomain != null) {
        printWriter.println("<model>");
        // variables
        printWriter.println("<discreteVariables>");
        // Species iniCondition (if in concentration) is sampled from a poisson distribution(which has a mean of the current iniExp value)
        // There is only one subDomain for compartmental model
        List<VarIniCondition> varInis = subDomain.getVarIniConditions();
        if ((varInis != null) && (varInis.size() > 0)) {
            RandomDataGenerator dist = new RandomDataGenerator();
            if (simulation.getSolverTaskDescription().getStochOpt().isUseCustomSeed()) {
                Integer randomSeed = simulation.getSolverTaskDescription().getStochOpt().getCustomSeed();
                if (randomSeed != null) {
                    dist.reSeed(randomSeed);
                }
            }
            printWriter.println("TotalVars" + "\t" + varInis.size());
            for (VarIniCondition varIniCondition : varInis) {
                try {
                    Expression iniExp = varIniCondition.getIniVal();
                    iniExp.bindExpression(simSymbolTable);
                    iniExp = simSymbolTable.substituteFunctions(iniExp).flatten();
                    double expectedCount = iniExp.evaluateConstant();
                    // 1000 mill
                    final Integer limit = 1000000000;
                    if (limit < expectedCount) {
                        String eMessage = "The Initial count for Species '" + varIniCondition.getVar().getName() + "' is " + BigDecimal.valueOf(expectedCount).toBigInteger() + "\n";
                        eMessage += "which is higher than the internal vCell limit of " + limit + ".\n";
                        eMessage += "Please reduce the Initial Condition value for this Species or reduce the compartment size.";
                        throw new MathFormatException(eMessage);
                    }
                    long varCount = 0;
                    if (varIniCondition instanceof VarIniCount) {
                        varCount = (long) expectedCount;
                    } else {
                        if (expectedCount > 0) {
                            varCount = dist.nextPoisson(expectedCount);
                        }
                    }
                    // System.out.println("expectedCount: " + expectedCount + ", varCount: " + varCount);
                    printWriter.println(varIniCondition.getVar().getName() + "\t" + varCount);
                } catch (ExpressionException ex) {
                    ex.printStackTrace();
                    throw new MathFormatException("variable " + varIniCondition.getVar().getName() + "'s initial condition is required to be a constant.");
                }
            }
        } else
            printWriter.println("TotalVars" + "\t" + "0");
        printWriter.println("</discreteVariables>");
        printWriter.println();
        // jump processes
        printWriter.println("<jumpProcesses>");
        List<JumpProcess> jumpProcesses = subDomain.getJumpProcesses();
        if ((jumpProcesses != null) && (jumpProcesses.size() > 0)) {
            printWriter.println("TotalProcesses" + "\t" + jumpProcesses.size());
            for (int i = 0; i < jumpProcesses.size(); i++) {
                printWriter.println(jumpProcesses.get(i).getName());
            }
        } else
            printWriter.println("TotalProcesses" + "\t" + "0");
        printWriter.println("</jumpProcesses>");
        printWriter.println();
        // process description
        printWriter.println("<processDesc>");
        if ((jumpProcesses != null) && (jumpProcesses.size() > 0)) {
            printWriter.println("TotalDescriptions" + "\t" + jumpProcesses.size());
            for (int i = 0; i < jumpProcesses.size(); i++) {
                JumpProcess temProc = (JumpProcess) jumpProcesses.get(i);
                // jump process name
                printWriter.println("JumpProcess" + "\t" + temProc.getName());
                Expression probExp = temProc.getProbabilityRate();
                try {
                    probExp.bindExpression(simSymbolTable);
                    probExp = simSymbolTable.substituteFunctions(probExp).flatten();
                    if (!isValidProbabilityExpression(probExp)) {
                        throw new MathFormatException("probability rate in jump process " + temProc.getName() + " has illegal symbols(should only contain variable names).");
                    }
                } catch (cbit.vcell.parser.ExpressionException ex) {
                    ex.printStackTrace();
                    throw new cbit.vcell.parser.ExpressionException("Binding math description error in probability rate in jump process " + temProc.getName() + ". Some symbols can not be resolved.");
                }
                // Expression temp = replaceVarIniInProbability(probExp);
                // Propensity
                printWriter.println("\t" + "Propensity" + "\t" + probExp.infix());
                // effects
                printWriter.println("\t" + "Effect" + "\t" + temProc.getActions().size());
                for (int j = 0; j < temProc.getActions().size(); j++) {
                    printWriter.print("\t\t" + ((Action) temProc.getActions().get(j)).getVar().getName() + "\t" + ((Action) temProc.getActions().get(j)).getOperation());
                    printWriter.println("\t" + ((Action) temProc.getActions().get(j)).evaluateOperand());
                    printWriter.println();
                }
                // dependencies
                Vector<String> dependencies = getDependencies(temProc, jumpProcesses);
                if ((dependencies != null) && (dependencies.size() > 0)) {
                    printWriter.println("\t" + "DependentProcesses" + "\t" + dependencies.size());
                    for (int j = 0; j < dependencies.size(); j++) printWriter.println("\t\t" + dependencies.elementAt(j));
                } else
                    printWriter.println("\t" + "DependentProcesses" + "\t" + "0");
                printWriter.println();
            }
        } else
            printWriter.println("TotalDescriptions" + "\t" + "0");
        printWriter.println("</processDesc>");
        printWriter.println("</model>");
    }
// if (subDomain != null)
}
Also used : VarIniCondition(cbit.vcell.math.VarIniCondition) Action(cbit.vcell.math.Action) NonspatialStochSimOptions(cbit.vcell.solver.NonspatialStochSimOptions) MathFormatException(cbit.vcell.math.MathFormatException) ExpressionException(cbit.vcell.parser.ExpressionException) SubDomain(cbit.vcell.math.SubDomain) JumpProcess(cbit.vcell.math.JumpProcess) ErrorTolerance(cbit.vcell.solver.ErrorTolerance) RandomDataGenerator(org.apache.commons.math3.random.RandomDataGenerator) VarIniCount(cbit.vcell.math.VarIniCount) SimulationSymbolTable(cbit.vcell.solver.SimulationSymbolTable) ExpressionException(cbit.vcell.parser.ExpressionException) Simulation(cbit.vcell.solver.Simulation) Expression(cbit.vcell.parser.Expression) DefaultOutputTimeSpec(cbit.vcell.solver.DefaultOutputTimeSpec)

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