Search in sources :

Example 6 with StochVolVariable

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

the class StochMathMapping_4_8 method refreshVariables.

/**
 * Map speciesContext to variable, used for structural analysis (slow reactions and fast reactions)
 * Creation date: (10/25/2006 8:59:43 AM)
 * @exception cbit.vcell.mapping.MappingException The exception description.
 */
private void refreshVariables() throws MappingException {
    // 
    // non-constant dependant variables(means rely on other contants/functions) require a function
    // 
    Enumeration<SpeciesContextMapping> enum1 = getSpeciesContextMappings();
    while (enum1.hasMoreElements()) {
        SpeciesContextMapping scm = enum1.nextElement();
        SpeciesContextSpec scs = getSimulationContext().getReactionContext().getSpeciesContextSpec(scm.getSpeciesContext());
        if (scm.getDependencyExpression() != null && !scs.isConstant()) {
            // scm.setVariable(new Function(scm.getSpeciesContext().getName(),scm.getDependencyExpression()));
            scm.setVariable(null);
        }
    }
    // 
    // non-constant independant variables require either a membrane or volume variable
    // 
    enum1 = getSpeciesContextMappings();
    // stochastic substance unit from modelUnitSystem
    ModelUnitSystem modelUnitSystem = getSimulationContext().getModel().getUnitSystem();
    VCUnitDefinition stochSubstanceUnit = modelUnitSystem.getStochasticSubstanceUnit();
    while (enum1.hasMoreElements()) {
        SpeciesContextMapping scm = (SpeciesContextMapping) enum1.nextElement();
        SpeciesContextSpec scs = getSimulationContext().getReactionContext().getSpeciesContextSpec(scm.getSpeciesContext());
        // stochastic variable is always a function of size.
        MathMapping_4_8.SpeciesCountParameter spCountParm = null;
        try {
            String countName = scs.getSpeciesContext().getName() + BIO_PARAM_SUFFIX_SPECIES_COUNT;
            Expression countExp = new Expression(0.0);
            spCountParm = addSpeciesCountParameter(countName, countExp, MathMapping_4_8.PARAMETER_ROLE_COUNT, stochSubstanceUnit, scs);
        } catch (PropertyVetoException pve) {
            pve.printStackTrace();
            throw new MappingException(pve.getMessage());
        }
        // add concentration of species as MathMappingParameter - this will map to species concentration function
        try {
            String concName = scs.getSpeciesContext().getName() + BIO_PARAM_SUFFIX_SPECIES_CONCENTRATION;
            Expression concExp = getExpressionAmtToConc(new Expression(spCountParm.getName()), scs.getSpeciesContext());
            concExp.bindExpression(this);
            addSpeciesConcentrationParameter(concName, concExp, MathMapping_4_8.PARAMETER_ROLE_CONCENRATION, scs.getSpeciesContext().getUnitDefinition(), scs);
        } catch (Exception e) {
            e.printStackTrace();
            throw new MappingException(e.getMessage());
        }
        if (scm.getDependencyExpression() == null && !scs.isConstant()) {
            scm.setVariable(new StochVolVariable(getMathSymbol(spCountParm, getSimulationContext().getGeometryContext().getStructureMapping(scs.getSpeciesContext().getStructure()))));
            mathSymbolMapping.put(scm.getSpeciesContext(), scm.getVariable().getName());
        }
    }
}
Also used : SpeciesContextMapping(cbit.vcell.mapping.SpeciesContextMapping) SpeciesContextSpec(cbit.vcell.mapping.SpeciesContextSpec) PropertyVetoException(java.beans.PropertyVetoException) MatrixException(cbit.vcell.matrix.MatrixException) ModelException(cbit.vcell.model.ModelException) ExpressionException(cbit.vcell.parser.ExpressionException) MappingException(cbit.vcell.mapping.MappingException) MathException(cbit.vcell.math.MathException) MappingException(cbit.vcell.mapping.MappingException) PropertyVetoException(java.beans.PropertyVetoException) VCUnitDefinition(cbit.vcell.units.VCUnitDefinition) Expression(cbit.vcell.parser.Expression) StochVolVariable(cbit.vcell.math.StochVolVariable) ModelUnitSystem(cbit.vcell.model.ModelUnitSystem)

Example 7 with StochVolVariable

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

the class TestingFrameworkWindowManager method getVariableNamesToCompare.

// /**
// * Insert the method's description here.
// * Creation date: (11/23/2004 1:53:11 PM)
// * @return java.lang.String[]
// * @param sim1 cbit.vcell.solver.Simulation
// * @param sim2 cbit.vcell.solver.Simulation
// */
// private VariablePair[] getVariableNamesToCompare(BioModel testBioModel,SimulationSymbolTable testSymboltable, SimulationSymbolTable refSymbolTable){
// Vector<VariablePair> variablePairs = new Vector<VariablePair>();
// 
// //
// // get Variables from Simulation 1
// //
// Variable refVars[] = refSymbolTable.getVariables();
// for (int i = 0;refVars!=null && i < refVars.length; i++){
// if (refVars[i] instanceof VolVariable ||
// refVars[i] instanceof StochVolVariable ||
// refVars[i] instanceof MemVariable ||
// refVars[i] instanceof VolumeRegionVariable ||
// refVars[i] instanceof MembraneRegionVariable ||
// refVars[i] instanceof FilamentVariable ||
// refVars[i] instanceof FilamentRegionVariable){
// 
// VariablePair varPair = new VariablePair();
// varPair.refVariable = refVars[i];
// varPair.domain = refVars[i].getDomain();
// varPair.testVariable = null;
// variablePairs.add(varPair);
// }
// //		Constant sensitivityParameter = simSymbolTable1.getSimulation().getSolverTaskDescription().getSensitivityParameter();
// //		if (sensitivityParameter != null) {
// //			if (simVars[i] instanceof VolVariable) {
// //				hashSet.add(SensVariable.getSensName((VolVariable)simVars[i], sensitivityParameter));
// //			}
// //		}
// }
// 
// //
// // add Variables from Simulation 2
// //
// Variable[] testVars = testSymboltable.getVariables();
// for (int i = 0;testVars!=null && i < testVars.length; i++){
// if (testVars[i] instanceof VolVariable ||
// testVars[i] instanceof MemVariable ||
// testVars[i] instanceof VolumeRegionVariable ||
// testVars[i] instanceof MembraneRegionVariable ||
// testVars[i] instanceof FilamentVariable ||
// testVars[i] instanceof FilamentRegionVariable){
// 
// if(testVars[i].getDomain() == null){
// boolean BFoundMatchingName = false;
// for (int j = 0; j < variablePairs.size(); j++) {
// VariablePair varPair = variablePairs.elementAt(j);
// if(varPair.refVariable.getName().equals(testVars[i].getName())){
// varPair.testVariable = testVars[i];
// BFoundMatchingName = true;
// break;
// }
// }
// if(!BFoundMatchingName){
// //Try to find other matching variable types (e.g. functions)
// Variable dataSet1Match = refSymbolTable.getVariable(testVars[i].getName());
// if(dataSet1Match != null){
// VariablePair varPair = new VariablePair();
// varPair.refVariable = dataSet1Match;
// varPair.testVariable = testVars[i];
// varPair.domain = varPair.refVariable.getDomain();
// variablePairs.add(varPair);
// }else{
// SpeciesContext testSpeciescontext0 = testBioModel.getModel().getSpeciesContext(testVars[i].getName());
// if(testSpeciescontext0 != null){
// Species refspecies = testSpeciescontext0.getSpecies();
// Variable refVariable = refSymbolTable.getVariable(refspecies.getCommonName());
// if(refVariable != null){
// VariablePair varPair = new VariablePair();
// varPair.refVariable = refVariable;
// varPair.testVariable = testVars[i];
// varPair.domain = varPair.refVariable.getDomain();
// variablePairs.add(varPair);
// }
// }else{
// Species testSpecies = testBioModel.getModel().getSpecies(testVars[i].getName());
// if(testSpecies != null){
// for (int j = 0; j < testBioModel.getModel().getSpeciesContexts().length; j++) {
// if(testBioModel.getModel().getSpeciesContexts()[j].getSpecies() == testSpecies){
// Variable refVar = refSymbolTable.getVariable(testBioModel.getModel().getSpeciesContexts()[j].getName());
// if(refVar != null){
// VariablePair varPair = new VariablePair();
// varPair.refVariable = refVar;
// varPair.testVariable = testVars[i];
// varPair.domain = varPair.refVariable.getDomain();
// variablePairs.add(varPair);
// }
// }
// }
// }
// }
// }
// }
// }else{
// 
// }
// hashSet.add(simVars[i].getName());
// }
// Constant sensitivityParameter = refSymbolTable.getSimulation().getSolverTaskDescription().getSensitivityParameter();
// if (sensitivityParameter != null) {
// if (simVars[i] instanceof VolVariable) {
// hashSet.add(SensVariable.getSensName((VolVariable)simVars[i], sensitivityParameter));
// }
// }
// }
// 
// return (String[])hashSet.toArray(new String[hashSet.size()]);
// }
/**
 * Insert the method's description here.
 * Creation date: (11/23/2004 1:53:11 PM)
 * @return java.lang.String[]
 * @param sim1 cbit.vcell.solver.Simulation
 * @param sim2 cbit.vcell.solver.Simulation
 */
private String[] getVariableNamesToCompare(SimulationSymbolTable simSymbolTable1, SimulationSymbolTable simSymbolTable2) {
    java.util.HashSet<String> hashSet = new java.util.HashSet<String>();
    // 
    // get Variables from Simulation 1
    // 
    Variable[] simVars = simSymbolTable1.getVariables();
    for (int i = 0; simVars != null && i < simVars.length; i++) {
        if (simVars[i] instanceof VolVariable || simVars[i] instanceof StochVolVariable || simVars[i] instanceof MemVariable || simVars[i] instanceof VolumeRegionVariable || simVars[i] instanceof MembraneRegionVariable || simVars[i] instanceof FilamentVariable || simVars[i] instanceof FilamentRegionVariable) {
            hashSet.add(simVars[i].getName());
        }
        Constant sensitivityParameter = simSymbolTable1.getSimulation().getSolverTaskDescription().getSensitivityParameter();
        if (sensitivityParameter != null) {
            if (simVars[i] instanceof VolVariable) {
                hashSet.add(SensVariable.getSensName((VolVariable) simVars[i], sensitivityParameter));
            }
        }
    }
    // 
    // add Variables from Simulation 2
    // 
    simVars = simSymbolTable2.getVariables();
    for (int i = 0; simVars != null && i < simVars.length; i++) {
        if (simVars[i] instanceof VolVariable || simVars[i] instanceof MemVariable || simVars[i] instanceof VolumeRegionVariable || simVars[i] instanceof MembraneRegionVariable || simVars[i] instanceof FilamentVariable || simVars[i] instanceof FilamentRegionVariable) {
            hashSet.add(simVars[i].getName());
        }
        Constant sensitivityParameter = simSymbolTable2.getSimulation().getSolverTaskDescription().getSensitivityParameter();
        if (sensitivityParameter != null) {
            if (simVars[i] instanceof VolVariable) {
                hashSet.add(SensVariable.getSensName((VolVariable) simVars[i], sensitivityParameter));
            }
        }
    }
    return (String[]) hashSet.toArray(new String[hashSet.size()]);
}
Also used : SensVariable(cbit.vcell.solver.ode.SensVariable) FilamentVariable(cbit.vcell.math.FilamentVariable) VolVariable(cbit.vcell.math.VolVariable) StochVolVariable(cbit.vcell.math.StochVolVariable) MembraneRegionVariable(cbit.vcell.math.MembraneRegionVariable) VolumeRegionVariable(cbit.vcell.math.VolumeRegionVariable) MemVariable(cbit.vcell.math.MemVariable) FilamentRegionVariable(cbit.vcell.math.FilamentRegionVariable) Variable(cbit.vcell.math.Variable) MembraneRegionVariable(cbit.vcell.math.MembraneRegionVariable) VolVariable(cbit.vcell.math.VolVariable) StochVolVariable(cbit.vcell.math.StochVolVariable) FilamentRegionVariable(cbit.vcell.math.FilamentRegionVariable) Constant(cbit.vcell.math.Constant) VolumeRegionVariable(cbit.vcell.math.VolumeRegionVariable) MemVariable(cbit.vcell.math.MemVariable) FilamentVariable(cbit.vcell.math.FilamentVariable) StochVolVariable(cbit.vcell.math.StochVolVariable) HashSet(java.util.HashSet)

Example 8 with StochVolVariable

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

the class RulebasedMathMapping method refreshMathDescription.

/**
 * This method was created in VisualAge.
 */
@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 transform 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("rule-based particle math mapping not implemented for spatial geometry - dimension >= 1");
    }
    // 
    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 reactionRules that are not "excluded"
    // 
    ArrayList<ReactionRule> rrList = new ArrayList<ReactionRule>();
    for (ReactionRuleSpec reactionRuleSpec : simContext.getReactionContext().getReactionRuleSpecs()) {
        if (!reactionRuleSpec.isExcluded()) {
            rrList.add(reactionRuleSpec.getReactionRule());
        }
    }
    // 
    for (ReactionRule reactionRule : rrList) {
        UnresolvedParameter[] unresolvedParameters = reactionRule.getKineticLaw().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() + "', " + reactionRule.getDisplayType() + " '" + reactionRule.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 (ReactionRule reactionRule : rrList) {
        // if (reactionRule.getKineticLaw() instanceof LumpedKinetics){
        // throw new RuntimeException("Lumped Kinetics not yet supported for RuleBased Modeling");
        // }
        LocalParameter[] parameters = reactionRule.getKineticLaw().getLocalParameters();
        for (LocalParameter parameter : parameters) {
            // 
            if ((parameter.getRole() == RbmKineticLawParameterType.RuleRate)) {
                continue;
            }
            // 
            if (!reactionRule.isReversible() && parameter.getRole() == RbmKineticLawParameterType.MassActionReverseRate) {
                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);
    // 
    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);
    // 
    // define all molecules and unique species patterns (add molecules to mathDesc and speciesPatterns to varHash).
    // 
    HashMap<SpeciesPattern, VolumeParticleSpeciesPattern> speciesPatternMap = addSpeciesPatterns(domain, rrList);
    HashSet<VolumeParticleSpeciesPattern> uniqueParticleSpeciesPatterns = new HashSet<>(speciesPatternMap.values());
    for (VolumeParticleSpeciesPattern volumeParticleSpeciesPattern : uniqueParticleSpeciesPatterns) {
        varHash.addVariable(volumeParticleSpeciesPattern);
    }
    // 
    // define observables (those explicitly declared and those corresponding to seed species.
    // 
    List<ParticleObservable> observables = addObservables(geometryClass, domain, speciesPatternMap);
    for (ParticleObservable particleObservable : observables) {
        varHash.addVariable(particleObservable);
    }
    try {
        addParticleJumpProcesses(varHash, geometryClass, subDomain, speciesPatternMap);
    } catch (PropertyVetoException e1) {
        e1.printStackTrace();
        throw new MappingException(e1.getMessage(), e1);
    }
    // 
    for (int i = 0; i < fieldMathMappingParameters.length; i++) {
        if (fieldMathMappingParameters[i] instanceof UnitFactorParameter || fieldMathMappingParameters[i] instanceof ObservableConcentrationParameter) {
            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());
    // 
    for (SpeciesContext sc : model.getSpeciesContexts()) {
        if (!sc.hasSpeciesPattern()) {
            throw new MappingException("species " + sc.getName() + " has no molecular pattern");
        }
        VolumeParticleSpeciesPattern volumeParticleSpeciesPattern = speciesPatternMap.get(sc.getSpeciesPattern());
        ArrayList<ParticleInitialCondition> particleInitialConditions = new ArrayList<ParticleProperties.ParticleInitialCondition>();
        // initial conditions from scs
        SpeciesContextSpec scs = simContext.getReactionContext().getSpeciesContextSpec(sc);
        Parameter initialCountParameter = scs.getInitialCountParameter();
        Expression e = getIdentifierSubstitutions(new Expression(initialCountParameter, getNameScope()), initialCountParameter.getUnitDefinition(), geometryClass);
        particleInitialConditions.add(new ParticleInitialConditionCount(e, new Expression(0.0), new Expression(0.0), new Expression(0.0)));
        ParticleProperties particleProperies = new ParticleProperties(volumeParticleSpeciesPattern, new Expression(0.0), new Expression(0.0), new Expression(0.0), new Expression(0.0), particleInitialConditions);
        subDomain.addParticleProperties(particleProperies);
    }
    // 
    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 ObservableConcentrationParameter) {
            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()) {
        System.out.println(mathDesc.getVCML_database());
        throw new MappingException("generated an invalid mathDescription: " + mathDesc.getWarning());
    }
}
Also used : MathDescription(cbit.vcell.math.MathDescription) ArrayList(java.util.ArrayList) SpeciesContext(cbit.vcell.model.SpeciesContext) ExpressionException(cbit.vcell.parser.ExpressionException) PropertyVetoException(java.beans.PropertyVetoException) CompartmentSubDomain(cbit.vcell.math.CompartmentSubDomain) SubDomain(cbit.vcell.math.SubDomain) SubVolume(cbit.vcell.geometry.SubVolume) HashSet(java.util.HashSet) ModelException(cbit.vcell.model.ModelException) VolumeParticleSpeciesPattern(cbit.vcell.math.VolumeParticleSpeciesPattern) PropertyVetoException(java.beans.PropertyVetoException) ModelParameter(cbit.vcell.model.Model.ModelParameter) CompartmentSubDomain(cbit.vcell.math.CompartmentSubDomain) ParticleInitialCondition(cbit.vcell.math.ParticleProperties.ParticleInitialCondition) ParticleProperties(cbit.vcell.math.ParticleProperties) VolumeParticleObservable(cbit.vcell.math.VolumeParticleObservable) ParticleObservable(cbit.vcell.math.ParticleObservable) CompartmentSubDomain(cbit.vcell.math.CompartmentSubDomain) SubDomain(cbit.vcell.math.SubDomain) Domain(cbit.vcell.math.Variable.Domain) GeometryClass(cbit.vcell.geometry.GeometryClass) VolumeParticleVariable(cbit.vcell.math.VolumeParticleVariable) ParticleVariable(cbit.vcell.math.ParticleVariable) StochVolVariable(cbit.vcell.math.StochVolVariable) Variable(cbit.vcell.math.Variable) VariableHash(cbit.vcell.math.VariableHash) MacroscopicRateConstant(cbit.vcell.math.MacroscopicRateConstant) Constant(cbit.vcell.math.Constant) UnresolvedParameter(cbit.vcell.mapping.ParameterContext.UnresolvedParameter) VolumeParticleSpeciesPattern(cbit.vcell.math.VolumeParticleSpeciesPattern) SpeciesPattern(org.vcell.model.rbm.SpeciesPattern) Structure(cbit.vcell.model.Structure) StochVolVariable(cbit.vcell.math.StochVolVariable) ReactionRule(cbit.vcell.model.ReactionRule) LocalParameter(cbit.vcell.mapping.ParameterContext.LocalParameter) Expression(cbit.vcell.parser.Expression) Model(cbit.vcell.model.Model) Parameter(cbit.vcell.model.Parameter) UnresolvedParameter(cbit.vcell.mapping.ParameterContext.UnresolvedParameter) LocalParameter(cbit.vcell.mapping.ParameterContext.LocalParameter) ModelParameter(cbit.vcell.model.Model.ModelParameter) ParticleInitialConditionCount(cbit.vcell.math.ParticleProperties.ParticleInitialConditionCount)

Example 9 with StochVolVariable

use of cbit.vcell.math.StochVolVariable 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 10 with StochVolVariable

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

the class StochMathMapping method refreshVariables.

/**
 * Map speciesContext to variable, used for structural analysis (slow reactions and fast reactions)
 * Creation date: (10/25/2006 8:59:43 AM)
 * @exception cbit.vcell.mapping.MappingException The exception description.
 */
@Override
protected void refreshVariables() throws MappingException {
    // 
    // stochastic species need  species variables require either a membrane or volume variable
    // 
    Enumeration<SpeciesContextMapping> enum1 = getSpeciesContextMappings();
    while (enum1.hasMoreElements()) {
        SpeciesContextMapping scm = (SpeciesContextMapping) enum1.nextElement();
        SpeciesContextSpec scs = getSimulationContext().getReactionContext().getSpeciesContextSpec(scm.getSpeciesContext());
        // stochastic variable is always a function of size.
        SpeciesCountParameter spCountParm = null;
        try {
            String countName = scs.getSpeciesContext().getName() + BIO_PARAM_SUFFIX_SPECIES_COUNT;
            Expression countExp = new Expression(0.0);
            spCountParm = addSpeciesCountParameter(countName, countExp, PARAMETER_ROLE_SPECIES_COUNT, scs.getInitialCountParameter().getUnitDefinition(), scs.getSpeciesContext());
        } catch (PropertyVetoException pve) {
            pve.printStackTrace();
            throw new MappingException(pve.getMessage());
        }
        // add concentration of species as MathMappingParameter - this will map to species concentration function
        try {
            String concName = scs.getSpeciesContext().getName() + BIO_PARAM_SUFFIX_SPECIES_CONCENTRATION;
            Expression concExp = getExpressionAmtToConc(new Expression(spCountParm, getNameScope()), scs.getSpeciesContext().getStructure());
            concExp.bindExpression(this);
            addSpeciesConcentrationParameter(concName, concExp, PARAMETER_ROLE_SPECIES_CONCENRATION, scs.getSpeciesContext().getUnitDefinition(), scs.getSpeciesContext());
        } catch (Exception e) {
            e.printStackTrace();
            throw new MappingException(e.getMessage(), e);
        }
        // we always add variables, all species are independent variables, no matter they are constant or not.
        String countMathSymbol = getMathSymbol(spCountParm, getSimulationContext().getGeometryContext().getStructureMapping(scs.getSpeciesContext().getStructure()).getGeometryClass());
        scm.setVariable(new StochVolVariable(countMathSymbol));
    }
    // 
    // if the original (untransformed) model has any explicit observables (which are rule-based components), then the transformed model maps these observables to "Concentration" ModelParameters.
    // 
    // for symmetry with the RuleBasedMathMapping, we want to generate a "_Count" version of these observables if applicable.
    // 
    // so if a rule-to-network "transformation" was performed, we want to find those ModelParameters which map to Observables (concentrations) so that we can generate an additional "Count" function (by scaling by compartment size and performing a unit conversion).
    // 
    SimContextTransformation transformation = getTransformation();
    if (transformation != null) {
        ModelEntityMapping[] modelEntityMappings = transformation.modelEntityMappings;
        if (modelEntityMappings != null) {
            for (ModelEntityMapping mem : modelEntityMappings) {
                if (mem.newModelObj instanceof ModelParameter && mem.origModelObj instanceof RbmObservable) {
                    ModelParameter concObservableParameter = (ModelParameter) mem.newModelObj;
                    RbmObservable observable = (RbmObservable) mem.origModelObj;
                    try {
                        Expression countExp = getExpressionConcToExpectedCount(new Expression(concObservableParameter, getNameScope()), observable.getStructure());
                        // countExp.bindExpression(this);
                        addObservableCountParameter(concObservableParameter.getName() + BIO_PARAM_SUFFIX_SPECIES_COUNT, countExp, PARAMETER_ROLE_OBSERVABLE_COUNT, getSimulationContext().getModel().getUnitSystem().getStochasticSubstanceUnit(), observable);
                    } catch (ExpressionException | PropertyVetoException e) {
                        e.printStackTrace();
                        throw new MappingException(e.getMessage(), e);
                    }
                }
            }
        }
    }
}
Also used : ModelEntityMapping(cbit.vcell.mapping.SimContextTransformer.ModelEntityMapping) RbmObservable(cbit.vcell.model.RbmObservable) SimContextTransformation(cbit.vcell.mapping.SimContextTransformer.SimContextTransformation) PropertyVetoException(java.beans.PropertyVetoException) MatrixException(cbit.vcell.matrix.MatrixException) ModelException(cbit.vcell.model.ModelException) ExpressionException(cbit.vcell.parser.ExpressionException) MathException(cbit.vcell.math.MathException) ExpressionException(cbit.vcell.parser.ExpressionException) PropertyVetoException(java.beans.PropertyVetoException) ModelParameter(cbit.vcell.model.Model.ModelParameter) Expression(cbit.vcell.parser.Expression) StochVolVariable(cbit.vcell.math.StochVolVariable)

Aggregations

StochVolVariable (cbit.vcell.math.StochVolVariable)13 Variable (cbit.vcell.math.Variable)9 Expression (cbit.vcell.parser.Expression)9 ExpressionException (cbit.vcell.parser.ExpressionException)9 ModelException (cbit.vcell.model.ModelException)8 PropertyVetoException (java.beans.PropertyVetoException)8 MappingException (cbit.vcell.mapping.MappingException)5 Constant (cbit.vcell.math.Constant)5 FilamentRegionVariable (cbit.vcell.math.FilamentRegionVariable)5 FilamentVariable (cbit.vcell.math.FilamentVariable)5 MathException (cbit.vcell.math.MathException)5 MemVariable (cbit.vcell.math.MemVariable)5 MembraneRegionVariable (cbit.vcell.math.MembraneRegionVariable)5 SubDomain (cbit.vcell.math.SubDomain)5 VarIniCondition (cbit.vcell.math.VarIniCondition)5 CompartmentSubDomain (cbit.vcell.math.CompartmentSubDomain)4 InsideVariable (cbit.vcell.math.InsideVariable)4 MembraneParticleVariable (cbit.vcell.math.MembraneParticleVariable)4 ParticleVariable (cbit.vcell.math.ParticleVariable)4 VarIniCount (cbit.vcell.math.VarIniCount)4