Search in sources :

Example 1 with VarIniCondition

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

the class SimulationWorkspace method getEstimatedNumTimePointsForStoch.

private static long getEstimatedNumTimePointsForStoch(SimulationSymbolTable simSymbolTable) {
    Simulation sim = simSymbolTable.getSimulation();
    SolverTaskDescription solverTaskDescription = sim.getSolverTaskDescription();
    TimeBounds tb = solverTaskDescription.getTimeBounds();
    double startTime = tb.getStartingTime();
    double endTime = tb.getEndingTime();
    OutputTimeSpec tSpec = solverTaskDescription.getOutputTimeSpec();
    // hybrid G_E and G_M are fixed time step methods using uniform output time spec
    if (tSpec.isUniform()) {
        double outputTimeStep = ((UniformOutputTimeSpec) tSpec).getOutputTimeStep();
        return (long) ((endTime - startTime) / outputTimeStep);
    }
    double maxProbability = 0;
    SubDomain subDomain = sim.getMathDescription().getSubDomains().nextElement();
    List<VarIniCondition> varInis = subDomain.getVarIniConditions();
    // get all the probability expressions
    ArrayList<Expression> probList = new ArrayList<Expression>();
    for (JumpProcess jp : subDomain.getJumpProcesses()) {
        probList.add(jp.getProbabilityRate());
    }
    // loop through probability expressions
    for (int i = 0; i < probList.size(); i++) {
        try {
            Expression pExp = new Expression(probList.get(i));
            pExp.bindExpression(simSymbolTable);
            pExp = simSymbolTable.substituteFunctions(pExp);
            pExp = pExp.flatten();
            String[] symbols = pExp.getSymbols();
            // substitute stoch vars with it's initial condition expressions
            if (symbols != null) {
                for (int j = 0; symbols != null && j < symbols.length; j++) {
                    for (int k = 0; k < varInis.size(); k++) {
                        if (symbols[j].equals(varInis.get(k).getVar().getName())) {
                            pExp.substituteInPlace(new Expression(symbols[j]), new Expression(varInis.get(k).getIniVal()));
                            break;
                        }
                    }
                }
            }
            pExp = simSymbolTable.substituteFunctions(pExp);
            pExp = pExp.flatten();
            double val = pExp.evaluateConstant();
            if (maxProbability < val) {
                maxProbability = val;
            }
        } catch (ExpressionBindingException e) {
            System.out.println("Cannot estimate the total time points for stochastic simulation!! Due to the reason below...");
            e.printStackTrace();
        } catch (ExpressionException ex) {
            System.out.println("Cannot estimate the total time points for stochastic simulation!! Due to the reason below...");
            ex.printStackTrace();
        } catch (MathException e) {
            System.out.println("Cannot estimate the total time points for stochastic simulation!! Due to the reason below...");
            e.printStackTrace();
        }
    }
    int keepEvery = 1;
    if (tSpec.isDefault()) {
        keepEvery = ((DefaultOutputTimeSpec) tSpec).getKeepEvery();
    }
    // points = (endt-startt)/(t*keepEvery) = (endt - startt)/(keepEvery*1/prob)
    long estimatedPoints = Math.round((tb.getEndingTime() - tb.getStartingTime()) * maxProbability / keepEvery) + 1;
    return estimatedPoints;
}
Also used : VarIniCondition(cbit.vcell.math.VarIniCondition) UniformOutputTimeSpec(cbit.vcell.solver.UniformOutputTimeSpec) ArrayList(java.util.ArrayList) ExpressionBindingException(cbit.vcell.parser.ExpressionBindingException) ExpressionException(cbit.vcell.parser.ExpressionException) SubDomain(cbit.vcell.math.SubDomain) TimeBounds(cbit.vcell.solver.TimeBounds) OutputTimeSpec(cbit.vcell.solver.OutputTimeSpec) DefaultOutputTimeSpec(cbit.vcell.solver.DefaultOutputTimeSpec) UniformOutputTimeSpec(cbit.vcell.solver.UniformOutputTimeSpec) Simulation(cbit.vcell.solver.Simulation) Expression(cbit.vcell.parser.Expression) MathException(cbit.vcell.math.MathException) JumpProcess(cbit.vcell.math.JumpProcess) SolverTaskDescription(cbit.vcell.solver.SolverTaskDescription)

Example 2 with VarIniCondition

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

the class FieldUtilities method collectFieldFuncAndExpressions.

private static Hashtable<FieldFunctionArguments, Vector<Expression>> collectFieldFuncAndExpressions(MathDescription mathDesc) throws MathException, ExpressionException {
    // make sure each field only added once
    Hashtable<FieldFunctionArguments, Vector<Expression>> fieldFuncArgsExpHash = new Hashtable<FieldFunctionArguments, Vector<Expression>>();
    Enumeration<SubDomain> enum1 = mathDesc.getSubDomains();
    Enumeration<Variable> mathDescEnumeration = mathDesc.getVariables();
    while (mathDescEnumeration.hasMoreElements()) {
        Variable variable = mathDescEnumeration.nextElement();
        if (variable instanceof Function) {
            Function function = (Function) variable;
            FieldUtilities.addFieldFuncArgsAndExpToCollection(fieldFuncArgsExpHash, function.getExpression());
        }
    }
    // go through each subdomain
    while (enum1.hasMoreElements()) {
        SubDomain subDomain = enum1.nextElement();
        // go through each equation
        Enumeration<Equation> enum_equ = subDomain.getEquations();
        while (enum_equ.hasMoreElements()) {
            Equation equation = (Equation) enum_equ.nextElement();
            Vector<Expression> exs = equation.getExpressions(mathDesc);
            // go through each expresson
            for (int i = 0; i < exs.size(); i++) {
                Expression exp = (Expression) exs.get(i);
                FieldUtilities.addFieldFuncArgsAndExpToCollection(fieldFuncArgsExpHash, exp);
            }
        }
        // go through each Fast System
        FastSystem fastSystem = subDomain.getFastSystem();
        if (fastSystem != null) {
            Expression[] fsExprArr = fastSystem.getExpressions();
            for (int i = 0; i < fsExprArr.length; i++) {
                FieldUtilities.addFieldFuncArgsAndExpToCollection(fieldFuncArgsExpHash, fsExprArr[i]);
            }
        }
        // go through each Jump Process
        for (JumpProcess jumpProcess : subDomain.getJumpProcesses()) {
            Expression[] jpExprArr = jumpProcess.getExpressions();
            for (int i = 0; i < jpExprArr.length; i++) {
                FieldUtilities.addFieldFuncArgsAndExpToCollection(fieldFuncArgsExpHash, jpExprArr[i]);
            }
        }
        // go through VarInitConditions
        for (VarIniCondition varInitCond : subDomain.getVarIniConditions()) {
            Expression[] vicExprArr = new Expression[] { varInitCond.getIniVal(), varInitCond.getVar().getExpression() };
            for (int i = 0; i < vicExprArr.length; i++) {
                FieldUtilities.addFieldFuncArgsAndExpToCollection(fieldFuncArgsExpHash, vicExprArr[i]);
            }
        }
    }
    return fieldFuncArgsExpHash;
}
Also used : VarIniCondition(cbit.vcell.math.VarIniCondition) Variable(cbit.vcell.math.Variable) Hashtable(java.util.Hashtable) Equation(cbit.vcell.math.Equation) SubDomain(cbit.vcell.math.SubDomain) Function(cbit.vcell.math.Function) Expression(cbit.vcell.parser.Expression) FastSystem(cbit.vcell.math.FastSystem) JumpProcess(cbit.vcell.math.JumpProcess) Vector(java.util.Vector)

Example 3 with VarIniCondition

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

the class StochMathMapping method refreshMathDescription.

/**
 * set up a math description based on current simulationContext.
 */
@Override
protected void refreshMathDescription() throws MappingException, MatrixException, MathException, ExpressionException, ModelException {
    // use local variable instead of using getter all the time.
    SimulationContext simContext = getSimulationContext();
    GeometryClass geometryClass = simContext.getGeometry().getGeometrySpec().getSubVolumes()[0];
    Domain domain = new Domain(geometryClass);
    // local structure mapping list
    StructureMapping[] structureMappings = simContext.getGeometryContext().getStructureMappings();
    // We have to check if all the reactions are able to tranform to stochastic jump processes before generating the math.
    String stochChkMsg = simContext.getModel().isValidForStochApp();
    if (!(stochChkMsg.equals(""))) {
        throw new ModelException("Problem updating math description: " + simContext.getName() + "\n" + stochChkMsg);
    }
    simContext.checkValidity();
    // 
    if (simContext.getGeometry().getDimension() > 0) {
        throw new MappingException("nonspatial stochastic math mapping requires 0-dimensional geometry");
    }
    // 
    for (int i = 0; i < structureMappings.length; i++) {
        if (structureMappings[i] instanceof MembraneMapping) {
            if (((MembraneMapping) structureMappings[i]).getCalculateVoltage()) {
                throw new MappingException("electric potential not yet supported for particle models");
            }
        }
    }
    // 
    // fail if any events
    // 
    BioEvent[] bioEvents = simContext.getBioEvents();
    if (bioEvents != null && bioEvents.length > 0) {
        throw new MappingException("events not yet supported for particle-based models");
    }
    // 
    // verify that all structures are mapped to subvolumes and all subvolumes are mapped to a structure
    // 
    Structure[] structures = simContext.getGeometryContext().getModel().getStructures();
    for (int i = 0; i < structures.length; i++) {
        StructureMapping sm = simContext.getGeometryContext().getStructureMapping(structures[i]);
        if (sm == null || (sm instanceof FeatureMapping && ((FeatureMapping) sm).getGeometryClass() == null)) {
            throw new MappingException("model structure '" + structures[i].getName() + "' not mapped to a geometry subVolume");
        }
        if (sm != null && (sm instanceof MembraneMapping) && ((MembraneMapping) sm).getVolumeFractionParameter() != null) {
            Expression volFractExp = ((MembraneMapping) sm).getVolumeFractionParameter().getExpression();
            try {
                if (volFractExp != null) {
                    double volFract = volFractExp.evaluateConstant();
                    if (volFract >= 1.0) {
                        throw new MappingException("model structure '" + (getSimulationContext().getModel().getStructureTopology().getInsideFeature(((MembraneMapping) sm).getMembrane()).getName() + "' has volume fraction >= 1.0"));
                    }
                }
            } catch (ExpressionException e) {
                e.printStackTrace(System.out);
            }
        }
    }
    SubVolume[] subVolumes = simContext.getGeometryContext().getGeometry().getGeometrySpec().getSubVolumes();
    for (int i = 0; i < subVolumes.length; i++) {
        Structure[] mappedStructures = simContext.getGeometryContext().getStructuresFromGeometryClass(subVolumes[i]);
        if (mappedStructures == null || mappedStructures.length == 0) {
            throw new MappingException("geometry subVolume '" + subVolumes[i].getName() + "' not mapped from a model structure");
        }
    }
    // 
    // gather only those reactionSteps that are not "excluded"
    // 
    ReactionSpec[] reactionSpecs = simContext.getReactionContext().getReactionSpecs();
    Vector<ReactionStep> rsList = new Vector<ReactionStep>();
    for (int i = 0; i < reactionSpecs.length; i++) {
        if (!reactionSpecs[i].isExcluded()) {
            rsList.add(reactionSpecs[i].getReactionStep());
        }
    }
    // 
    for (ReactionStep reactionStep : rsList) {
        Kinetics.UnresolvedParameter[] unresolvedParameters = reactionStep.getKinetics().getUnresolvedParameters();
        if (unresolvedParameters != null && unresolvedParameters.length > 0) {
            StringBuffer buffer = new StringBuffer();
            for (int j = 0; j < unresolvedParameters.length; j++) {
                if (j > 0) {
                    buffer.append(", ");
                }
                buffer.append(unresolvedParameters[j].getName());
            }
            throw new MappingException("In Application '" + simContext.getName() + "', " + reactionStep.getDisplayType() + " '" + reactionStep.getName() + "' contains unresolved identifier(s): " + buffer);
        }
    }
    // 
    // create new MathDescription (based on simContext's previous MathDescription if possible)
    // 
    MathDescription oldMathDesc = simContext.getMathDescription();
    mathDesc = null;
    if (oldMathDesc != null) {
        if (oldMathDesc.getVersion() != null) {
            mathDesc = new MathDescription(oldMathDesc.getVersion());
        } else {
            mathDesc = new MathDescription(oldMathDesc.getName());
        }
    } else {
        mathDesc = new MathDescription(simContext.getName() + "_generated");
    }
    // 
    // temporarily place all variables in a hashtable (before binding) and discarding duplicates
    // 
    VariableHash varHash = new VariableHash();
    // 
    // conversion factors
    // 
    Model model = simContext.getModel();
    varHash.addVariable(new Constant(getMathSymbol(model.getKMOLE(), null), getIdentifierSubstitutions(model.getKMOLE().getExpression(), model.getKMOLE().getUnitDefinition(), null)));
    varHash.addVariable(new Constant(getMathSymbol(model.getN_PMOLE(), null), getIdentifierSubstitutions(model.getN_PMOLE().getExpression(), model.getN_PMOLE().getUnitDefinition(), null)));
    varHash.addVariable(new Constant(getMathSymbol(model.getPI_CONSTANT(), null), getIdentifierSubstitutions(model.getPI_CONSTANT().getExpression(), model.getPI_CONSTANT().getUnitDefinition(), null)));
    varHash.addVariable(new Constant(getMathSymbol(model.getFARADAY_CONSTANT(), null), getIdentifierSubstitutions(model.getFARADAY_CONSTANT().getExpression(), model.getFARADAY_CONSTANT().getUnitDefinition(), null)));
    varHash.addVariable(new Constant(getMathSymbol(model.getFARADAY_CONSTANT_NMOLE(), null), getIdentifierSubstitutions(model.getFARADAY_CONSTANT_NMOLE().getExpression(), model.getFARADAY_CONSTANT_NMOLE().getUnitDefinition(), null)));
    varHash.addVariable(new Constant(getMathSymbol(model.getGAS_CONSTANT(), null), getIdentifierSubstitutions(model.getGAS_CONSTANT().getExpression(), model.getGAS_CONSTANT().getUnitDefinition(), null)));
    varHash.addVariable(new Constant(getMathSymbol(model.getTEMPERATURE(), null), getIdentifierSubstitutions(new Expression(simContext.getTemperatureKelvin()), model.getTEMPERATURE().getUnitDefinition(), null)));
    Enumeration<SpeciesContextMapping> enum1 = getSpeciesContextMappings();
    while (enum1.hasMoreElements()) {
        SpeciesContextMapping scm = enum1.nextElement();
        if (scm.getVariable() instanceof StochVolVariable) {
            varHash.addVariable(scm.getVariable());
        }
    }
    // deals with model parameters
    ModelParameter[] modelParameters = simContext.getModel().getModelParameters();
    for (int j = 0; j < modelParameters.length; j++) {
        Expression expr = getSubstitutedExpr(modelParameters[j].getExpression(), true, false);
        expr = getIdentifierSubstitutions(expr, modelParameters[j].getUnitDefinition(), geometryClass);
        varHash.addVariable(newFunctionOrConstant(getMathSymbol(modelParameters[j], geometryClass), expr, geometryClass));
    }
    // added July 2009, ElectricalStimulusParameter electric mapping tab
    ElectricalStimulus[] elecStimulus = simContext.getElectricalStimuli();
    if (elecStimulus.length > 0) {
        throw new MappingException("Modles with electrophysiology are not supported for stochastic applications.");
    }
    for (int j = 0; j < structureMappings.length; j++) {
        if (structureMappings[j] instanceof MembraneMapping) {
            MembraneMapping memMapping = (MembraneMapping) structureMappings[j];
            Parameter initialVoltageParm = memMapping.getInitialVoltageParameter();
            try {
                Expression exp = initialVoltageParm.getExpression();
                exp.evaluateConstant();
                varHash.addVariable(newFunctionOrConstant(getMathSymbol(memMapping.getMembrane().getMembraneVoltage(), memMapping.getGeometryClass()), getIdentifierSubstitutions(memMapping.getInitialVoltageParameter().getExpression(), memMapping.getInitialVoltageParameter().getUnitDefinition(), memMapping.getGeometryClass()), memMapping.getGeometryClass()));
            } catch (ExpressionException e) {
                e.printStackTrace(System.out);
                throw new MappingException("Membrane initial voltage: " + initialVoltageParm.getName() + " cannot be evaluated as constant.");
            }
        }
    }
    // 
    for (ReactionStep rs : rsList) {
        if (rs.getKinetics() instanceof LumpedKinetics) {
            throw new RuntimeException("Lumped Kinetics not yet supported for Stochastic Math Generation");
        }
        Kinetics.KineticsParameter[] parameters = rs.getKinetics().getKineticsParameters();
        for (KineticsParameter parameter : parameters) {
            // 
            if ((parameter.getRole() == Kinetics.ROLE_CurrentDensity) && (parameter.getExpression() == null || parameter.getExpression().isZero())) {
                continue;
            }
            // 
            // don't add rate, we'll do it later when creating the jump processes
            // 
            // if (parameter.getRole() == Kinetics.ROLE_ReactionRate) {
            // continue;
            // }
            // 
            // don't add mass action reverse parameter if irreversible
            // 
            // if (!rs.isReversible() && parameters[i].getRole() == Kinetics.ROLE_KReverse){
            // continue;
            // }
            Expression expr = getSubstitutedExpr(parameter.getExpression(), true, false);
            varHash.addVariable(newFunctionOrConstant(getMathSymbol(parameter, geometryClass), getIdentifierSubstitutions(expr, parameter.getUnitDefinition(), geometryClass), geometryClass));
        }
    }
    // the parameter "Size" is already put into mathsymbolmapping in refreshSpeciesContextMapping()
    for (int i = 0; i < structureMappings.length; i++) {
        StructureMapping sm = structureMappings[i];
        StructureMapping.StructureMappingParameter parm = sm.getParameterFromRole(StructureMapping.ROLE_Size);
        if (parm.getExpression() != null) {
            try {
                double value = parm.getExpression().evaluateConstant();
                varHash.addVariable(new Constant(getMathSymbol(parm, sm.getGeometryClass()), new Expression(value)));
            } catch (ExpressionException e) {
                // varHash.addVariable(new Function(getMathSymbol0(parm,sm),getIdentifierSubstitutions(parm.getExpression(),parm.getUnitDefinition(),sm)));
                e.printStackTrace(System.out);
                throw new MappingException("Size of structure:" + sm.getNameScope().getName() + " cannot be evaluated as constant.");
            }
        }
    }
    SpeciesContextSpec[] speciesContextSpecs = getSimulationContext().getReactionContext().getSpeciesContextSpecs();
    addInitialConditions(domain, speciesContextSpecs, varHash);
    // 
    // constant species (either function or constant)
    // 
    enum1 = getSpeciesContextMappings();
    while (enum1.hasMoreElements()) {
        SpeciesContextMapping scm = (SpeciesContextMapping) enum1.nextElement();
        if (scm.getVariable() instanceof Constant) {
            varHash.addVariable(scm.getVariable());
        }
    }
    // 
    if (simContext.getGeometryContext().getGeometry() != null) {
        try {
            mathDesc.setGeometry(simContext.getGeometryContext().getGeometry());
        } catch (java.beans.PropertyVetoException e) {
            e.printStackTrace(System.out);
            throw new MappingException("failure setting geometry " + e.getMessage());
        }
    } else {
        throw new MappingException("Geometry must be defined in Application " + simContext.getName());
    }
    // 
    // create subDomains
    // 
    SubVolume subVolume = simContext.getGeometry().getGeometrySpec().getSubVolumes()[0];
    SubDomain subDomain = new CompartmentSubDomain(subVolume.getName(), 0);
    mathDesc.addSubDomain(subDomain);
    // 
    // functions: species which is not a variable, but has dependency expression
    // 
    enum1 = getSpeciesContextMappings();
    while (enum1.hasMoreElements()) {
        SpeciesContextMapping scm = (SpeciesContextMapping) enum1.nextElement();
        if (scm.getVariable() == null && scm.getDependencyExpression() != null) {
            StructureMapping sm = simContext.getGeometryContext().getStructureMapping(scm.getSpeciesContext().getStructure());
            Expression exp = scm.getDependencyExpression();
            exp.bindExpression(this);
            SpeciesCountParameter spCountParam = getSpeciesCountParameter(scm.getSpeciesContext());
            varHash.addVariable(new Function(getMathSymbol(spCountParam, sm.getGeometryClass()), getIdentifierSubstitutions(exp, spCountParam.getUnitDefinition(), sm.getGeometryClass()), domain));
        }
    }
    addJumpProcesses(varHash, geometryClass, subDomain);
    // 
    for (int i = 0; i < fieldMathMappingParameters.length; i++) {
        if (fieldMathMappingParameters[i] instanceof UnitFactorParameter) {
            varHash.addVariable(newFunctionOrConstant(getMathSymbol(fieldMathMappingParameters[i], geometryClass), getIdentifierSubstitutions(fieldMathMappingParameters[i].getExpression(), fieldMathMappingParameters[i].getUnitDefinition(), geometryClass), fieldMathMappingParameters[i].getGeometryClass()));
        }
    }
    // 
    // set Variables to MathDescription all at once with the order resolved by "VariableHash"
    // 
    mathDesc.setAllVariables(varHash.getAlphabeticallyOrderedVariables());
    // 
    // set up variable initial conditions in subDomain
    // 
    SpeciesContextSpec[] scSpecs = simContext.getReactionContext().getSpeciesContextSpecs();
    for (int i = 0; i < speciesContextSpecs.length; i++) {
        // get stochastic variable by name
        SpeciesCountParameter spCountParam = getSpeciesCountParameter(speciesContextSpecs[i].getSpeciesContext());
        StructureMapping sm = simContext.getGeometryContext().getStructureMapping(speciesContextSpecs[i].getSpeciesContext().getStructure());
        String varName = getMathSymbol(spCountParam, sm.getGeometryClass());
        StochVolVariable var = (StochVolVariable) mathDesc.getVariable(varName);
        // stochastic use initial number of particles
        SpeciesContextSpec.SpeciesContextSpecParameter initParm = scSpecs[i].getInitialCountParameter();
        // stochastic variables initial expression.
        if (initParm != null) {
            VarIniCondition varIni = null;
            if (!scSpecs[i].isConstant() && getSimulationContext().isRandomizeInitCondition()) {
                varIni = new VarIniPoissonExpectedCount(var, new Expression(getMathSymbol(initParm, sm.getGeometryClass())));
            } else {
                varIni = new VarIniCount(var, new Expression(getMathSymbol(initParm, sm.getGeometryClass())));
            }
            subDomain.addVarIniCondition(varIni);
        }
    }
    // 
    for (int i = 0; i < fieldMathMappingParameters.length; i++) {
        if (fieldMathMappingParameters[i] instanceof UnitFactorParameter) {
            Variable variable = newFunctionOrConstant(getMathSymbol(fieldMathMappingParameters[i], geometryClass), getIdentifierSubstitutions(fieldMathMappingParameters[i].getExpression(), fieldMathMappingParameters[i].getUnitDefinition(), geometryClass), fieldMathMappingParameters[i].getGeometryClass());
            if (mathDesc.getVariable(variable.getName()) == null) {
                mathDesc.addVariable(variable);
            }
        }
        if (fieldMathMappingParameters[i] instanceof ObservableCountParameter) {
            Variable variable = newFunctionOrConstant(getMathSymbol(fieldMathMappingParameters[i], geometryClass), getIdentifierSubstitutions(fieldMathMappingParameters[i].getExpression(), fieldMathMappingParameters[i].getUnitDefinition(), geometryClass), fieldMathMappingParameters[i].getGeometryClass());
            if (mathDesc.getVariable(variable.getName()) == null) {
                mathDesc.addVariable(variable);
            }
        }
    }
    if (!mathDesc.isValid()) {
        lg.error(mathDesc.getVCML_database());
        throw new MappingException("generated an invalid mathDescription: " + mathDesc.getWarning());
    }
}
Also used : VarIniCondition(cbit.vcell.math.VarIniCondition) LumpedKinetics(cbit.vcell.model.LumpedKinetics) MathDescription(cbit.vcell.math.MathDescription) ExpressionException(cbit.vcell.parser.ExpressionException) PropertyVetoException(java.beans.PropertyVetoException) CompartmentSubDomain(cbit.vcell.math.CompartmentSubDomain) SubDomain(cbit.vcell.math.SubDomain) KineticsParameter(cbit.vcell.model.Kinetics.KineticsParameter) SubVolume(cbit.vcell.geometry.SubVolume) Vector(java.util.Vector) ModelException(cbit.vcell.model.ModelException) ModelParameter(cbit.vcell.model.Model.ModelParameter) CompartmentSubDomain(cbit.vcell.math.CompartmentSubDomain) ReactionStep(cbit.vcell.model.ReactionStep) CompartmentSubDomain(cbit.vcell.math.CompartmentSubDomain) SubDomain(cbit.vcell.math.SubDomain) Domain(cbit.vcell.math.Variable.Domain) GeometryClass(cbit.vcell.geometry.GeometryClass) StochVolVariable(cbit.vcell.math.StochVolVariable) Variable(cbit.vcell.math.Variable) VariableHash(cbit.vcell.math.VariableHash) Constant(cbit.vcell.math.Constant) VarIniPoissonExpectedCount(cbit.vcell.math.VarIniPoissonExpectedCount) Function(cbit.vcell.math.Function) Structure(cbit.vcell.model.Structure) StochVolVariable(cbit.vcell.math.StochVolVariable) VarIniCount(cbit.vcell.math.VarIniCount) Expression(cbit.vcell.parser.Expression) Model(cbit.vcell.model.Model) Parameter(cbit.vcell.model.Parameter) KineticsParameter(cbit.vcell.model.Kinetics.KineticsParameter) ModelParameter(cbit.vcell.model.Model.ModelParameter)

Example 4 with VarIniCondition

use of cbit.vcell.math.VarIniCondition 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());
        // need to overwrite limit hardcoded in C++
        double savePoints = (timeBounds.getEndingTime() - timeBounds.getStartingTime()) / ((UniformOutputTimeSpec) outputTimeSpec).getOutputTimeStep();
        printWriter.println("MAX_SAVE_POINTS" + "\t" + (Math.ceil(savePoints) + 1));
    }
    // boolean isMultiTrial = !solverTaskDescription.getStochOpt().isHistogram() &&
    // solverTaskDescription.getStochOpt().getNumOfTrials() > 1;
    // //Multi-trial 'NUM_TRIAL' handled by slurm array within .slurm.sh script
    // printWriter.println("NUM_TRIAL"+"\t"+(isMultiTrial?1:solverTaskDescription.getStochOpt().getNumOfTrials()));
    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);
    }
    if (isMultiTrialNonHisto) {
        printWriter.println("BMULTIBUTNOTHISTO" + "\t" + "1");
    }
    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) Math.round(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) UniformOutputTimeSpec(cbit.vcell.solver.UniformOutputTimeSpec) 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)

Example 5 with VarIniCondition

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

the class XmlReader method getVarIniCount.

/**
 * This method return a VarIniCondition object from a XML element.
 * Creation date: (7/24/2006 5:26:05 PM)
 * @return cbit.vcell.math.VarIniCondition
 * @param param org.jdom.Element
 * @exception cbit.vcell.xml.XmlParseException The exception description.
 */
private VarIniCondition getVarIniCount(Element param, MathDescription md) throws XmlParseException, MathException, ExpressionException {
    // retrieve values
    Expression exp = unMangleExpression(param.getText());
    String name = unMangle(param.getAttributeValue(XMLTags.NameAttrTag));
    Variable var = md.getVariable(name);
    if (var == null) {
        throw new MathFormatException("variable " + name + " not defined");
    }
    if (!(var instanceof StochVolVariable)) {
        throw new MathFormatException("variable " + name + " not a Stochastic Volume Variable");
    }
    try {
        VarIniCondition varIni = new VarIniCount(var, exp);
        return varIni;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
Also used : VarIniCondition(cbit.vcell.math.VarIniCondition) FilamentVariable(cbit.vcell.math.FilamentVariable) OutsideVariable(cbit.vcell.math.OutsideVariable) StochVolVariable(cbit.vcell.math.StochVolVariable) RandomVariable(cbit.vcell.math.RandomVariable) VolumeRandomVariable(cbit.vcell.math.VolumeRandomVariable) VolumeParticleVariable(cbit.vcell.math.VolumeParticleVariable) VolumeRegionVariable(cbit.vcell.math.VolumeRegionVariable) InsideVariable(cbit.vcell.math.InsideVariable) VolVariable(cbit.vcell.math.VolVariable) MembraneRegionVariable(cbit.vcell.math.MembraneRegionVariable) PointVariable(cbit.vcell.math.PointVariable) MembraneRandomVariable(cbit.vcell.math.MembraneRandomVariable) MembraneParticleVariable(cbit.vcell.math.MembraneParticleVariable) ParticleVariable(cbit.vcell.math.ParticleVariable) MemVariable(cbit.vcell.math.MemVariable) FilamentRegionVariable(cbit.vcell.math.FilamentRegionVariable) Variable(cbit.vcell.math.Variable) Expression(cbit.vcell.parser.Expression) MathFormatException(cbit.vcell.math.MathFormatException) VarIniCount(cbit.vcell.math.VarIniCount) StochVolVariable(cbit.vcell.math.StochVolVariable) GeometryException(cbit.vcell.geometry.GeometryException) MathFormatException(cbit.vcell.math.MathFormatException) MappingException(cbit.vcell.mapping.MappingException) PropertyVetoException(java.beans.PropertyVetoException) ImageException(cbit.image.ImageException) ExpressionBindingException(cbit.vcell.parser.ExpressionBindingException) ModelException(cbit.vcell.model.ModelException) DataConversionException(org.jdom.DataConversionException) ExpressionException(cbit.vcell.parser.ExpressionException) MathException(cbit.vcell.math.MathException)

Aggregations

VarIniCondition (cbit.vcell.math.VarIniCondition)11 Expression (cbit.vcell.parser.Expression)9 ExpressionException (cbit.vcell.parser.ExpressionException)8 JumpProcess (cbit.vcell.math.JumpProcess)7 SubDomain (cbit.vcell.math.SubDomain)7 Action (cbit.vcell.math.Action)5 Function (cbit.vcell.math.Function)5 StochVolVariable (cbit.vcell.math.StochVolVariable)5 VarIniCount (cbit.vcell.math.VarIniCount)5 Variable (cbit.vcell.math.Variable)5 Vector (java.util.Vector)5 Constant (cbit.vcell.math.Constant)4 Equation (cbit.vcell.math.Equation)4 ModelException (cbit.vcell.model.ModelException)4 PropertyVetoException (java.beans.PropertyVetoException)4 MappingException (cbit.vcell.mapping.MappingException)3 CompartmentSubDomain (cbit.vcell.math.CompartmentSubDomain)3 MathException (cbit.vcell.math.MathException)3 MathFormatException (cbit.vcell.math.MathFormatException)3 ImageException (cbit.image.ImageException)2