Search in sources :

Example 31 with ExpressionException

use of cbit.vcell.parser.ExpressionException in project vcell by virtualcell.

the class SpeciesContextSpec method computeStructureSize.

private double computeStructureSize() throws ExpressionException, MappingException {
    Structure structure = getSpeciesContext().getStructure();
    StructureMapping sm = getSimulationContext().getGeometryContext().getStructureMapping(structure);
    double structSize = 0;
    if (getSimulationContext().getGeometry().getDimension() == 0) {
        Expression sizeParameterExpression = sm.getSizeParameter().getExpression();
        if (sizeParameterExpression == null || sizeParameterExpression.isZero()) {
            throw new RuntimeException("\nIn application '" + getSimulationContext().getName() + "', " + "size of structure '" + structure.getName() + "' is required to convert " + "concentration to number of particles.\n\nPlease go to 'Structure Mapping' tab to check the size.");
        }
        structSize = sizeParameterExpression.evaluateConstant();
    } else {
        StructureMapping structureMapping = getSimulationContext().getGeometryContext().getStructureMapping(structure);
        GeometryClass gc = structureMapping.getGeometryClass();
        if (gc == null) {
            throw new MappingException("model structure '" + structure.getName() + "' not mapped to a geometry subdomain");
        }
        try {
            GeometricRegion[] geometricRegions = getSimulationContext().getGeometry().getGeometrySurfaceDescription().getGeometricRegions(gc);
            if (geometricRegions == null) {
                throw new MappingException("Geometry is not updated.");
            }
            for (GeometricRegion gr : geometricRegions) {
                structSize += gr.getSize();
            }
        } catch (Exception ex) {
        }
    }
    return structSize;
}
Also used : GeometryClass(cbit.vcell.geometry.GeometryClass) Expression(cbit.vcell.parser.Expression) Structure(cbit.vcell.model.Structure) PropertyVetoException(java.beans.PropertyVetoException) ExpressionBindingException(cbit.vcell.parser.ExpressionBindingException) ModelException(cbit.vcell.model.ModelException) ExpressionException(cbit.vcell.parser.ExpressionException) GeometricRegion(cbit.vcell.geometry.surface.GeometricRegion)

Example 32 with ExpressionException

use of cbit.vcell.parser.ExpressionException 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()) {
        System.out.println(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 33 with ExpressionException

use of cbit.vcell.parser.ExpressionException in project vcell by virtualcell.

the class StochMathMapping method addJumpProcesses.

private void addJumpProcesses(VariableHash varHash, GeometryClass geometryClass, SubDomain subDomain) throws ExpressionException, ModelException, MappingException, MathException {
    // set up jump processes
    // get all the reactions from simulation context
    // ReactionSpec[] reactionSpecs = simContext.getReactionContext().getReactionSpecs();---need to take a look here!
    ModelUnitSystem modelUnitSystem = getSimulationContext().getModel().getUnitSystem();
    ReactionSpec[] reactionSpecs = getSimulationContext().getReactionContext().getReactionSpecs();
    for (ReactionSpec reactionSpec : reactionSpecs) {
        if (reactionSpec.isExcluded()) {
            continue;
        }
        // get the reaction
        ReactionStep reactionStep = reactionSpec.getReactionStep();
        Kinetics kinetics = reactionStep.getKinetics();
        // probability parameter from modelUnitSystem
        VCUnitDefinition probabilityParamUnit = modelUnitSystem.getStochasticSubstanceUnit().divideBy(modelUnitSystem.getTimeUnit());
        // Different ways to deal with simple reactions and flux reactions
        if (// simple reactions
        reactionStep instanceof SimpleReaction) {
            // check the reaction rate law to see if we need to decompose a reaction(reversible) into two jump processes.
            // rate constants are important in calculating the probability rate.
            // for Mass Action, we use KForward and KReverse,
            // for General Kinetics we parse reaction rate J to see if it is in Mass Action form.
            Expression forwardRate = null;
            Expression reverseRate = null;
            if (kinetics.getKineticsDescription().equals(KineticsDescription.MassAction) || kinetics.getKineticsDescription().equals(KineticsDescription.General)) {
                Expression rateExp = new Expression(kinetics.getKineticsParameterFromRole(Kinetics.ROLE_ReactionRate), reactionStep.getNameScope());
                Parameter forwardRateParameter = null;
                Parameter reverseRateParameter = null;
                if (kinetics.getKineticsDescription().equals(KineticsDescription.MassAction)) {
                    forwardRateParameter = kinetics.getKineticsParameterFromRole(Kinetics.ROLE_KForward);
                    reverseRateParameter = kinetics.getKineticsParameterFromRole(Kinetics.ROLE_KReverse);
                }
                MassActionSolver.MassActionFunction maFunc = MassActionSolver.solveMassAction(forwardRateParameter, reverseRateParameter, rateExp, reactionStep);
                if (maFunc.getForwardRate() == null && maFunc.getReverseRate() == null) {
                    throw new MappingException("Cannot generate stochastic math mapping for the reaction:" + reactionStep.getName() + "\nLooking for the rate function according to the form of k1*Reactant1^Stoir1*Reactant2^Stoir2...-k2*Product1^Stoip1*Product2^Stoip2.");
                } else {
                    if (maFunc.getForwardRate() != null) {
                        forwardRate = maFunc.getForwardRate();
                    }
                    if (maFunc.getReverseRate() != null) {
                        reverseRate = maFunc.getReverseRate();
                    }
                }
            } else // if it's macro/microscopic kinetics, we'll have them set up as reactions with only forward rate.
            if (kinetics.getKineticsDescription().equals(KineticsDescription.Macroscopic_irreversible) || kinetics.getKineticsDescription().equals(KineticsDescription.Microscopic_irreversible)) {
                Expression Kon = getIdentifierSubstitutions(new Expression(reactionStep.getKinetics().getKineticsParameterFromRole(Kinetics.ROLE_KOn), getNameScope()), reactionStep.getKinetics().getKineticsParameterFromRole(Kinetics.ROLE_Binding_Radius).getUnitDefinition(), geometryClass);
                if (Kon != null) {
                    Expression KonCopy = new Expression(Kon);
                    try {
                        MassActionSolver.substituteParameters(KonCopy, true).evaluateConstant();
                        forwardRate = new Expression(Kon);
                    } catch (ExpressionException e) {
                        throw new MathException(VCellErrorMessages.getMassActionSolverMessage(reactionStep.getName(), "Problem with Kon parameter in " + reactionStep.getName() + ":  '" + KonCopy.infix() + "', " + e.getMessage()));
                    }
                } else {
                    throw new MathException(VCellErrorMessages.getMassActionSolverMessage(reactionStep.getName(), "Kon parameter of " + reactionStep.getName() + " is null."));
                }
            }
            boolean isForwardRatePresent = false;
            boolean isReverseRatePresent = false;
            if (forwardRate != null) {
                isForwardRatePresent = true;
            }
            if (reverseRate != null) {
                isReverseRatePresent = true;
            }
            // we process it as forward reaction
            if ((isForwardRatePresent)) /*|| ((forwardRate == null) && (reverseRate == null))*/
            {
                // get jump process name
                String jpName = TokenMangler.mangleToSName(reactionStep.getName());
                // get probability
                Expression exp = null;
                // reactions are of mass action form
                exp = getProbabilityRate(reactionStep, forwardRate, true);
                ProbabilityParameter probParm = null;
                try {
                    probParm = addProbabilityParameter(PARAMETER_PROBABILITYRATE_PREFIX + jpName, exp, PARAMETER_ROLE_P, probabilityParamUnit, reactionStep);
                } catch (PropertyVetoException pve) {
                    pve.printStackTrace();
                    throw new MappingException(pve.getMessage());
                }
                // add probability to function or constant
                varHash.addVariable(newFunctionOrConstant(getMathSymbol(probParm, geometryClass), getIdentifierSubstitutions(exp, probabilityParamUnit, geometryClass), geometryClass));
                JumpProcess jp = new JumpProcess(jpName, new Expression(getMathSymbol(probParm, geometryClass)));
                // actions
                ReactionParticipant[] reacPart = reactionStep.getReactionParticipants();
                for (int j = 0; j < reacPart.length; j++) {
                    Action action = null;
                    SpeciesCountParameter spCountParam = getSpeciesCountParameter(reacPart[j].getSpeciesContext());
                    if (reacPart[j] instanceof Reactant) {
                        // check if the reactant is a constant. If the species is a constant, there will be no action taken on this species
                        if (// not a constant
                        !simContext.getReactionContext().getSpeciesContextSpec(reacPart[j].getSpeciesContext()).isConstant()) {
                            int stoi = ((Reactant) reacPart[j]).getStoichiometry();
                            action = Action.createIncrementAction(varHash.getVariable(getMathSymbol(spCountParam, geometryClass)), new Expression(-stoi));
                            jp.addAction(action);
                        }
                    } else if (reacPart[j] instanceof Product) {
                        // check if the product is a constant. If the product is a constant, there will be no action taken on this species
                        if (// not a constant
                        !simContext.getReactionContext().getSpeciesContextSpec(reacPart[j].getSpeciesContext()).isConstant()) {
                            int stoi = ((Product) reacPart[j]).getStoichiometry();
                            action = Action.createIncrementAction(varHash.getVariable(getMathSymbol(spCountParam, geometryClass)), new Expression(stoi));
                            jp.addAction(action);
                        }
                    }
                }
                // add jump process to compartment subDomain
                subDomain.addJumpProcess(jp);
            }
            if (// one more jump process for a reversible reaction
            isReverseRatePresent) {
                // get jump process name
                String jpName = TokenMangler.mangleToSName(reactionStep.getName()) + PARAMETER_PROBABILITY_RATE_REVERSE_SUFFIX;
                Expression exp = null;
                // reactions are mass actions
                exp = getProbabilityRate(reactionStep, reverseRate, false);
                ProbabilityParameter probRevParm = null;
                try {
                    probRevParm = addProbabilityParameter(PARAMETER_PROBABILITYRATE_PREFIX + jpName, exp, PARAMETER_ROLE_P_reverse, probabilityParamUnit, reactionStep);
                } catch (PropertyVetoException pve) {
                    pve.printStackTrace();
                    throw new MappingException(pve.getMessage());
                }
                // add probability to function or constant
                varHash.addVariable(newFunctionOrConstant(getMathSymbol(probRevParm, geometryClass), getIdentifierSubstitutions(exp, probabilityParamUnit, geometryClass), geometryClass));
                JumpProcess jp = new JumpProcess(jpName, new Expression(getMathSymbol(probRevParm, geometryClass)));
                // actions
                ReactionParticipant[] reacPart = reactionStep.getReactionParticipants();
                for (int j = 0; j < reacPart.length; j++) {
                    Action action = null;
                    SpeciesCountParameter spCountParam = getSpeciesCountParameter(reacPart[j].getSpeciesContext());
                    if (reacPart[j] instanceof Reactant) {
                        // check if the reactant is a constant. If the species is a constant, there will be no action taken on this species
                        if (// not a constant
                        !simContext.getReactionContext().getSpeciesContextSpec(reacPart[j].getSpeciesContext()).isConstant()) {
                            int stoi = ((Reactant) reacPart[j]).getStoichiometry();
                            action = Action.createIncrementAction(varHash.getVariable(getMathSymbol(spCountParam, geometryClass)), new Expression(stoi));
                            jp.addAction(action);
                        }
                    } else if (reacPart[j] instanceof Product) {
                        // check if the product is a constant. If the product is a constant, there will be no action taken on this species
                        if (// not a constant
                        !simContext.getReactionContext().getSpeciesContextSpec(reacPart[j].getSpeciesContext()).isConstant()) {
                            int stoi = ((Product) reacPart[j]).getStoichiometry();
                            action = Action.createIncrementAction(varHash.getVariable(getMathSymbol(spCountParam, geometryClass)), new Expression(-stoi));
                            jp.addAction(action);
                        }
                    }
                }
                // add jump process to compartment subDomain
                subDomain.addJumpProcess(jp);
            }
        // end of if(isForwardRateNonZero), if(isReverseRateNonRate)
        } else if (// flux reactions
        reactionStep instanceof FluxReaction) {
            // we could set jump processes for general flux rate in forms of p1*Sout + p2*Sin
            if (kinetics.getKineticsDescription().equals(KineticsDescription.General) || kinetics.getKineticsDescription().equals(KineticsDescription.GeneralPermeability)) {
                Expression fluxRate = new Expression(kinetics.getKineticsParameterFromRole(Kinetics.ROLE_ReactionRate), reactionStep.getNameScope());
                // we have to pass the math description para to flux solver, coz somehow math description in simulation context is not updated.
                // forward and reverse rate parameters may be null
                Parameter forwardRateParameter = null;
                Parameter reverseRateParameter = null;
                if (kinetics.getKineticsDescription().equals(KineticsDescription.GeneralPermeability)) {
                    forwardRateParameter = kinetics.getKineticsParameterFromRole(Kinetics.ROLE_Permeability);
                    reverseRateParameter = kinetics.getKineticsParameterFromRole(Kinetics.ROLE_Permeability);
                }
                MassActionSolver.MassActionFunction fluxFunc = MassActionSolver.solveMassAction(forwardRateParameter, reverseRateParameter, fluxRate, (FluxReaction) reactionStep);
                // create jump process for forward flux if it exists.
                Expression rsStructureSize = new Expression(reactionStep.getStructure().getStructureSize(), getNameScope());
                VCUnitDefinition probRateUnit = modelUnitSystem.getStochasticSubstanceUnit().divideBy(modelUnitSystem.getAreaUnit()).divideBy(modelUnitSystem.getTimeUnit());
                Expression rsRateUnitFactor = getUnitFactor(probRateUnit.divideBy(modelUnitSystem.getFluxReactionUnit()));
                if (fluxFunc.getForwardRate() != null && !fluxFunc.getForwardRate().isZero()) {
                    Expression rate = fluxFunc.getForwardRate();
                    // get species expression (depend on structure, if mem: Species/mem_Size, if vol: species*KMOLE/vol_size)
                    if (fluxFunc.getReactants().size() != 1) {
                        throw new MappingException("Flux " + reactionStep.getName() + " should have only one reactant.");
                    }
                    SpeciesContext scReactant = fluxFunc.getReactants().get(0).getSpeciesContext();
                    Expression scConcExpr = new Expression(getSpeciesConcentrationParameter(scReactant), getNameScope());
                    Expression probExp = Expression.mult(rate, rsRateUnitFactor, rsStructureSize, scConcExpr);
                    // jump process name
                    // +"_reverse";
                    String jpName = TokenMangler.mangleToSName(reactionStep.getName());
                    ProbabilityParameter probParm = null;
                    try {
                        probParm = addProbabilityParameter(PARAMETER_PROBABILITYRATE_PREFIX + jpName, probExp, PARAMETER_ROLE_P, probabilityParamUnit, reactionStep);
                    } catch (PropertyVetoException pve) {
                        pve.printStackTrace();
                        throw new MappingException(pve.getMessage());
                    }
                    // add probability to function or constant
                    String ms = getMathSymbol(probParm, geometryClass);
                    Expression is = getIdentifierSubstitutions(probExp, probabilityParamUnit, geometryClass);
                    Variable nfoc = newFunctionOrConstant(ms, is, geometryClass);
                    varHash.addVariable(nfoc);
                    JumpProcess jp = new JumpProcess(jpName, new Expression(getMathSymbol(probParm, geometryClass)));
                    // actions
                    Action action = null;
                    SpeciesContext sc = fluxFunc.getReactants().get(0).getSpeciesContext();
                    if (!simContext.getReactionContext().getSpeciesContextSpec(sc).isConstant()) {
                        SpeciesCountParameter spCountParam = getSpeciesCountParameter(sc);
                        action = Action.createIncrementAction(varHash.getVariable(getMathSymbol(spCountParam, geometryClass)), new Expression(-1));
                        jp.addAction(action);
                    }
                    sc = fluxFunc.getProducts().get(0).getSpeciesContext();
                    if (!simContext.getReactionContext().getSpeciesContextSpec(sc).isConstant()) {
                        SpeciesCountParameter spCountParam = getSpeciesCountParameter(sc);
                        action = Action.createIncrementAction(varHash.getVariable(getMathSymbol(spCountParam, geometryClass)), new Expression(1));
                        jp.addAction(action);
                    }
                    subDomain.addJumpProcess(jp);
                }
                // create jump process for reverse flux if it exists.
                if (fluxFunc.getReverseRate() != null && !fluxFunc.getReverseRate().isZero()) {
                    // jump process name
                    String jpName = TokenMangler.mangleToSName(reactionStep.getName()) + PARAMETER_PROBABILITY_RATE_REVERSE_SUFFIX;
                    Expression rate = fluxFunc.getReverseRate();
                    // get species expression (depend on structure, if mem: Species/mem_Size, if vol: species*KMOLE/vol_size)
                    if (fluxFunc.getProducts().size() != 1) {
                        throw new MappingException("Flux " + reactionStep.getName() + " should have only one product.");
                    }
                    SpeciesContext scProduct = fluxFunc.getProducts().get(0).getSpeciesContext();
                    Expression scConcExpr = new Expression(getSpeciesConcentrationParameter(scProduct), getNameScope());
                    Expression probExp = Expression.mult(rate, rsRateUnitFactor, rsStructureSize, scConcExpr);
                    ProbabilityParameter probRevParm = null;
                    try {
                        probRevParm = addProbabilityParameter(PARAMETER_PROBABILITYRATE_PREFIX + jpName, probExp, PARAMETER_ROLE_P_reverse, probabilityParamUnit, reactionStep);
                    } catch (PropertyVetoException pve) {
                        pve.printStackTrace();
                        throw new MappingException(pve.getMessage());
                    }
                    // add probability to function or constant
                    varHash.addVariable(newFunctionOrConstant(getMathSymbol(probRevParm, geometryClass), getIdentifierSubstitutions(probExp, probabilityParamUnit, geometryClass), geometryClass));
                    JumpProcess jp = new JumpProcess(jpName, new Expression(getMathSymbol(probRevParm, geometryClass)));
                    // actions
                    Action action = null;
                    SpeciesContext sc = fluxFunc.getReactants().get(0).getSpeciesContext();
                    if (!simContext.getReactionContext().getSpeciesContextSpec(sc).isConstant()) {
                        SpeciesCountParameter spCountParam = getSpeciesCountParameter(sc);
                        action = Action.createIncrementAction(varHash.getVariable(getMathSymbol(spCountParam, geometryClass)), new Expression(1));
                        jp.addAction(action);
                    }
                    sc = fluxFunc.getProducts().get(0).getSpeciesContext();
                    if (!simContext.getReactionContext().getSpeciesContextSpec(sc).isConstant()) {
                        SpeciesCountParameter spCountParam = getSpeciesCountParameter(sc);
                        action = Action.createIncrementAction(varHash.getVariable(getMathSymbol(spCountParam, geometryClass)), new Expression(-1));
                        jp.addAction(action);
                    }
                    subDomain.addJumpProcess(jp);
                }
            }
        }
    // end of if (simplereaction)...else if(fluxreaction)
    }
// end of reaction step loop
}
Also used : Action(cbit.vcell.math.Action) StochVolVariable(cbit.vcell.math.StochVolVariable) Variable(cbit.vcell.math.Variable) Product(cbit.vcell.model.Product) FluxReaction(cbit.vcell.model.FluxReaction) SpeciesContext(cbit.vcell.model.SpeciesContext) Reactant(cbit.vcell.model.Reactant) ExpressionException(cbit.vcell.parser.ExpressionException) JumpProcess(cbit.vcell.math.JumpProcess) ModelUnitSystem(cbit.vcell.model.ModelUnitSystem) SimpleReaction(cbit.vcell.model.SimpleReaction) PropertyVetoException(java.beans.PropertyVetoException) VCUnitDefinition(cbit.vcell.units.VCUnitDefinition) Expression(cbit.vcell.parser.Expression) MathException(cbit.vcell.math.MathException) ReactionStep(cbit.vcell.model.ReactionStep) Parameter(cbit.vcell.model.Parameter) KineticsParameter(cbit.vcell.model.Kinetics.KineticsParameter) ModelParameter(cbit.vcell.model.Model.ModelParameter) Kinetics(cbit.vcell.model.Kinetics) LumpedKinetics(cbit.vcell.model.LumpedKinetics) MassActionSolver(cbit.vcell.model.MassActionSolver) ReactionParticipant(cbit.vcell.model.ReactionParticipant)

Example 34 with ExpressionException

use of cbit.vcell.parser.ExpressionException in project vcell by virtualcell.

the class StructureMapping method gatherIssues.

/**
 * Insert the method's description here.
 * Creation date: (11/1/2005 9:57:23 AM)
 * @param issueVector java.util.Vector
 */
public void gatherIssues(IssueContext issueContext, List<Issue> issueVector) {
    // size parameter must be set to non zero value for new ode, and all stoch simulations.
    if (simulationContext != null) {
        Parameter sizeParam = null;
        if (simulationContext.getGeometry().getDimension() == 0) {
            sizeParam = getSizeParameter();
        } else {
            sizeParam = getUnitSizeParameter();
        }
        if (sizeParam != null) {
            if (sizeParam.getExpression() == null) {
                if (!simulationContext.getGeometryContext().isAllVolFracAndSurfVolSpecified()) {
                    issueVector.add(new Issue(this, issueContext, IssueCategory.StructureMappingSizeParameterNotSet, "Size parameter is not set.", Issue.SEVERITY_ERROR));
                }
            } else {
                try {
                    double val = sizeParam.getExpression().evaluateConstant();
                    if (val <= 0) {
                        issueVector.add(new Issue(this, issueContext, IssueCategory.StructureMappingSizeParameterNotPositive, "Size parameter is not positive.", Issue.SEVERITY_ERROR));
                    }
                } catch (ExpressionException e) {
                    e.printStackTrace();
                    issueVector.add(new Issue(this, issueContext, IssueCategory.StructureMappingSizeParameterNotConstant, "Size parameter is not a constant.", Issue.SEVERITY_ERROR));
                }
            }
        }
    }
    // 
    for (int i = 0; fieldParameters != null && i < fieldParameters.length; i++) {
        RealInterval simpleBounds = parameterBounds[fieldParameters[i].getRole()];
        if (simpleBounds != null) {
            String parmName = fieldParameters[i].getNameScope().getName() + "." + fieldParameters[i].getName();
            issueVector.add(new SimpleBoundsIssue(fieldParameters[i], issueContext, simpleBounds, "parameter " + parmName + ": must be within " + simpleBounds.toString()));
        }
    }
    if (geometryClass == null) {
        issueVector.add(new Issue(this, issueContext, IssueCategory.StructureNotMapped, getStructure().getTypeName() + " " + getStructure().getName() + " is not mapped to a geometry subdomain.", Issue.SEVERITY_WARNING));
    }
    if (geometryClass != null && simulationContext.getGeometryContext().getGeometry().getDimension() > 0) {
        detectMappingConflictIssues(issueContext, issueVector, this);
    }
}
Also used : SimpleBoundsIssue(cbit.vcell.model.SimpleBoundsIssue) Issue(org.vcell.util.Issue) SimpleBoundsIssue(cbit.vcell.model.SimpleBoundsIssue) Parameter(cbit.vcell.model.Parameter) RealInterval(net.sourceforge.interval.ia_math.RealInterval) ExpressionException(cbit.vcell.parser.ExpressionException)

Example 35 with ExpressionException

use of cbit.vcell.parser.ExpressionException in project vcell by virtualcell.

the class MathMapping_4_8 method getMathSymbol0.

/**
 * Substitutes appropriate variables for speciesContext bindings
 *
 * @return cbit.vcell.parser.Expression
 * @param origExp cbit.vcell.parser.Expression
 * @param structureMapping cbit.vcell.mapping.StructureMapping
 */
private String getMathSymbol0(SymbolTableEntry ste, StructureMapping structureMapping) throws MappingException {
    String steName = ste.getName();
    if (ste instanceof Kinetics.KineticsParameter) {
        Integer count = localNameCountHash.get(steName);
        if (count == null) {
            throw new MappingException("KineticsParameter " + steName + " not found in local name count");
        }
        if (count > 1 || steName.equals("J")) {
            return steName + "_" + ste.getNameScope().getName();
        // return getNameScope().getSymbolName(ste);
        } else {
            return steName;
        }
    }
    if (ste instanceof MathMapping_4_8.ProbabilityParameter) {
        // be careful here, to see if we need mangle the reaction name
        MathMapping_4_8.ProbabilityParameter probParm = (MathMapping_4_8.ProbabilityParameter) ste;
        return probParm.getName();
    }
    if (ste instanceof MathMapping_4_8.SpeciesConcentrationParameter) {
        MathMapping_4_8.SpeciesConcentrationParameter concParm = (MathMapping_4_8.SpeciesConcentrationParameter) ste;
        return concParm.getSpeciesContextSpec().getSpeciesContext().getName() + MATH_FUNC_SUFFIX_SPECIES_CONCENTRATION;
    }
    if (ste instanceof MathMapping_4_8.SpeciesCountParameter) {
        MathMapping_4_8.SpeciesCountParameter countParm = (MathMapping_4_8.SpeciesCountParameter) ste;
        return countParm.getSpeciesContextSpec().getSpeciesContext().getName() + MATH_VAR_SUFFIX_SPECIES_COUNT;
    }
    if (ste instanceof MathMapping_4_8.EventAssignmentInitParameter) {
        MathMapping_4_8.EventAssignmentInitParameter eventInitParm = (MathMapping_4_8.EventAssignmentInitParameter) ste;
        return eventInitParm.getName() + MATH_FUNC_SUFFIX_EVENTASSIGN_INIT;
    }
    if (ste instanceof Model.ReservedSymbol) {
        return steName;
    }
    if (ste instanceof Membrane.MembraneVoltage) {
        return steName;
    }
    if (ste instanceof Structure.StructureSize) {
        Structure structure = ((Structure.StructureSize) ste).getStructure();
        StructureMapping.StructureMappingParameter sizeParameter = simContext.getGeometryContext().getStructureMapping(structure).getSizeParameter();
        return getMathSymbol(sizeParameter, structureMapping);
    }
    if (ste instanceof ProxyParameter) {
        ProxyParameter pp = (ProxyParameter) ste;
        return getMathSymbol0(pp.getTarget(), structureMapping);
    }
    // 
    Model model = simContext.getModel();
    if (ste instanceof ModelParameter) {
        ModelParameter mp = (ModelParameter) ste;
        if (simContext.getGeometry().getDimension() == 0) {
            return mp.getName();
        } else {
            if (mp.getExpression().getSymbols() == null) {
                return mp.getName();
            }
            // check if global param variant name exists in globalVarsHash. If so, return it, else, throw exception.
            Hashtable<String, Expression> smVariantsHash = globalParamVariantsHash.get(mp);
            String variantName = mp.getName() + "_" + TokenMangler.fixTokenStrict(structureMapping.getStructure().getName());
            if (smVariantsHash.get(variantName) != null) {
                return variantName;
            } else {
                // global param variant doesn't exist in the hash, so get the substituted expression for global param and
                // gather all symbols (speciesContexts) that do not match with arg 'structureMapping' to display a proper error message.
                Expression expr = null;
                try {
                    expr = substituteGlobalParameters(mp.getExpression());
                } catch (ExpressionException e) {
                    e.printStackTrace(System.out);
                    throw new RuntimeException("Could not substitute expression for global parameter '" + mp.getName() + "' with expression '" + "'" + e.getMessage());
                }
                // find symbols (typically speciesContexts) in 'exp' that do not match with the arg 'structureMapping'
                String[] symbols = expr.getSymbols();
                String msg = "";
                if (symbols != null) {
                    Vector<String> spContextNamesVector = new Vector<String>();
                    for (int j = 0; j < symbols.length; j++) {
                        SpeciesContext sc = model.getSpeciesContext(symbols[j]);
                        if (sc != null) {
                            if (!sc.getStructure().compareEqual(structureMapping.getStructure())) {
                                spContextNamesVector.addElement(sc.getName());
                            }
                        }
                    }
                    for (int i = 0; (spContextNamesVector != null && i < spContextNamesVector.size()); i++) {
                        if (i == 0) {
                            msg += "'" + spContextNamesVector.elementAt(i) + ", ";
                        } else if (i == spContextNamesVector.size() - 1) {
                            msg += spContextNamesVector.elementAt(i) + "'";
                        } else {
                            msg += spContextNamesVector.elementAt(i) + ", ";
                        }
                    }
                }
                throw new RuntimeException("Global parameter '" + mp.getName() + "' is not defined in compartment '" + structureMapping.getStructure().getName() + "', but was referenced in that compartment." + "\n\nExpression '" + mp.getExpression().infix() + "' for global parameter '" + mp.getName() + "' expands to '" + expr.infix() + "' " + "and contains species " + msg + " that is/are not in adjacent compartments.");
            }
        // return (mp.getName()+"_"+TokenMangler.fixTokenStrict(structureMapping.getStructure().getName()));
        }
    }
    if (ste instanceof SpeciesContextSpec.SpeciesContextSpecParameter) {
        SpeciesContextSpec.SpeciesContextSpecParameter scsParm = (SpeciesContextSpec.SpeciesContextSpecParameter) ste;
        if (scsParm.getRole() == SpeciesContextSpec.ROLE_InitialConcentration) {
            return ((SpeciesContextSpec) (scsParm.getNameScope().getScopedSymbolTable())).getSpeciesContext().getName() + MATH_FUNC_SUFFIX_SPECIES_INIT_CONCENTRATION;
        }
        if (scsParm.getRole() == SpeciesContextSpec.ROLE_InitialCount) {
            return ((SpeciesContextSpec) (scsParm.getNameScope().getScopedSymbolTable())).getSpeciesContext().getName() + MATH_FUNC_SUFFIX_SPECIES_INIT_COUNT;
        }
        if (scsParm.getRole() == SpeciesContextSpec.ROLE_DiffusionRate) {
            return ((SpeciesContextSpec) (scsParm.getNameScope().getScopedSymbolTable())).getSpeciesContext().getName() + "_diffusionRate";
        }
        if (scsParm.getRole() == SpeciesContextSpec.ROLE_BoundaryValueXm) {
            return ((SpeciesContextSpec) (scsParm.getNameScope().getScopedSymbolTable())).getSpeciesContext().getName() + "_boundaryXm";
        }
        if (scsParm.getRole() == SpeciesContextSpec.ROLE_BoundaryValueXp) {
            return ((SpeciesContextSpec) (scsParm.getNameScope().getScopedSymbolTable())).getSpeciesContext().getName() + "_boundaryXp";
        }
        if (scsParm.getRole() == SpeciesContextSpec.ROLE_BoundaryValueYm) {
            return ((SpeciesContextSpec) (scsParm.getNameScope().getScopedSymbolTable())).getSpeciesContext().getName() + "_boundaryYm";
        }
        if (scsParm.getRole() == SpeciesContextSpec.ROLE_BoundaryValueYp) {
            return ((SpeciesContextSpec) (scsParm.getNameScope().getScopedSymbolTable())).getSpeciesContext().getName() + "_boundaryYp";
        }
        if (scsParm.getRole() == SpeciesContextSpec.ROLE_BoundaryValueZm) {
            return ((SpeciesContextSpec) (scsParm.getNameScope().getScopedSymbolTable())).getSpeciesContext().getName() + "_boundaryZm";
        }
        if (scsParm.getRole() == SpeciesContextSpec.ROLE_BoundaryValueZp) {
            return ((SpeciesContextSpec) (scsParm.getNameScope().getScopedSymbolTable())).getSpeciesContext().getName() + "_boundaryZp";
        }
        if (scsParm.getRole() == SpeciesContextSpec.ROLE_VelocityX) {
            return ((SpeciesContextSpec) (scsParm.getNameScope().getScopedSymbolTable())).getSpeciesContext().getName() + "_velocityX";
        }
        if (scsParm.getRole() == SpeciesContextSpec.ROLE_VelocityY) {
            return ((SpeciesContextSpec) (scsParm.getNameScope().getScopedSymbolTable())).getSpeciesContext().getName() + "_velocityY";
        }
        if (scsParm.getRole() == SpeciesContextSpec.ROLE_VelocityZ) {
            return ((SpeciesContextSpec) (scsParm.getNameScope().getScopedSymbolTable())).getSpeciesContext().getName() + "_velocityZ";
        }
    }
    if (ste instanceof ElectricalDevice.ElectricalDeviceParameter) {
        ElectricalDevice.ElectricalDeviceParameter edParm = (ElectricalDevice.ElectricalDeviceParameter) ste;
        ElectricalDevice electricalDevice = (ElectricalDevice) edParm.getNameScope().getScopedSymbolTable();
        if (electricalDevice instanceof MembraneElectricalDevice) {
            String nameWithScope = ((MembraneElectricalDevice) electricalDevice).getMembraneMapping().getMembrane().getNameScope().getName();
            if (edParm.getRole() == ElectricalDevice.ROLE_TotalCurrent) {
                return "I_" + nameWithScope;
            }
            if (edParm.getRole() == ElectricalDevice.ROLE_TransmembraneCurrent) {
                return "F_" + nameWithScope;
            }
        // }else if (electricalDevice instanceof CurrentClampElectricalDevice) {
        // if (edParm.getRole()==ElectricalDevice.ROLE_TotalCurrentDensity){
        // return "I_"+((CurrentClampElectricalDevice)electricalDevice).getCurrentClampStimulus().getNameScope().getName();
        // }
        // if (edParm.getRole()==ElectricalDevice.ROLE_TransmembraneCurrentDensity){
        // return "F_"+((CurrentClampElectricalDevice)electricalDevice).getCurrentClampStimulus().getNameScope().getName();
        // }
        // }else if (electricalDevice instanceof VoltageClampElectricalDevice) {
        // if (edParm.getRole()==ElectricalDevice.ROLE_TotalCurrentDensity){
        // return "I_"+((VoltageClampElectricalDevice)electricalDevice).getVoltageClampStimulus().getNameScope().getName();
        // }
        // if (edParm.getRole()==ElectricalDevice.ROLE_TransmembraneCurrentDensity){
        // return "F_"+((VoltageClampElectricalDevice)electricalDevice).getVoltageClampStimulus().getNameScope().getName();
        // }
        }
    }
    if (ste instanceof LocalParameter && ((LocalParameter) ste).getNameScope() instanceof ElectricalStimulus.ElectricalStimulusNameScope) {
        LocalParameter esParm = (LocalParameter) ste;
        String nameWithScope = esParm.getNameScope().getName();
        if (esParm.getRole() == ElectricalStimulusParameterType.TotalCurrent) {
            return "I_" + nameWithScope;
        } else if (esParm.getRole() == ElectricalStimulusParameterType.Voltage) {
            return "V_" + nameWithScope;
        }
    }
    StructureTopology structTopology = model.getStructureTopology();
    if (ste instanceof StructureMapping.StructureMappingParameter) {
        StructureMapping.StructureMappingParameter smParm = (StructureMapping.StructureMappingParameter) ste;
        Structure structure = ((StructureMapping) (smParm.getNameScope().getScopedSymbolTable())).getStructure();
        int role = smParm.getRole();
        if (role == StructureMapping.ROLE_VolumeFraction) {
            return "VolFract_" + (structTopology.getInsideFeature((Membrane) structure)).getNameScope().getName();
        } else {
            String nameWithScope = structure.getNameScope().getName();
            if (role == StructureMapping.ROLE_SurfaceToVolumeRatio) {
                return "SurfToVol_" + nameWithScope;
            } else if (role == StructureMapping.ROLE_InitialVoltage) {
                return smParm.getName();
            } else if (role == StructureMapping.ROLE_SpecificCapacitance) {
                return "C_" + nameWithScope;
            } else if (role == StructureMapping.ROLE_AreaPerUnitArea) {
                return "AreaPerUnitArea_" + nameWithScope;
            } else if (role == StructureMapping.ROLE_AreaPerUnitVolume) {
                return "AreaPerUnitVolume_" + nameWithScope;
            } else if (role == StructureMapping.ROLE_VolumePerUnitArea) {
                return "VolumePerUnitArea_" + nameWithScope;
            } else if (role == StructureMapping.ROLE_VolumePerUnitVolume) {
                return "VolumePerUnitVolume_" + nameWithScope;
            } else if (role == StructureMapping.ROLE_Size) {
                if (simContext.getGeometry().getDimension() == 0) {
                    // if geometry is compartmental, make sure compartment sizes are set if referenced in model.
                    if (smParm.getExpression() == null || smParm.getExpression().isZero()) {
                        throw new MappingException("\nIn non-spatial application '" + getSimulationContext().getName() + "', " + "size of structure '" + structure.getName() + "' must be assigned a " + "positive value if referenced in the model.\n\nPlease go to 'Structure Mapping' tab to check the size.");
                    }
                }
                return "Size_" + nameWithScope;
            }
        }
    }
    // 
    if (ste instanceof SpeciesContext) {
        SpeciesContext sc = (SpeciesContext) ste;
        SpeciesContextMapping scm = getSpeciesContextMapping(sc);
        // 
        if (structureMapping instanceof FeatureMapping) {
            // 
            if (scm.getVariable() != null && !scm.getVariable().getName().equals(steName)) {
                return scm.getVariable().getName();
            }
        // 
        // for reactions within a spatially resolved membrane, may need "_INSIDE" or "_OUTSIDE" for jump condition
        // 
        // if the membrane is distributed, then always use the plain variable.
        // 
        } else if (structureMapping instanceof MembraneMapping) {
            Membrane membrane = ((MembraneMapping) structureMapping).getMembrane();
            // 
            if (sc.getStructure() instanceof Membrane || getResolved(structureMapping) == false) {
                if (scm.getVariable() != null && !(scm.getVariable().getName().equals(steName))) {
                    return scm.getVariable().getName();
                }
            // 
            // if the speciesContext is outside the membrane
            // 
            } else {
                SpeciesContextSpec scs = simContext.getReactionContext().getSpeciesContextSpec(sc);
                if (sc.getStructure() == structTopology.getInsideFeature(membrane) || sc.getStructure() == structTopology.getOutsideFeature(membrane)) {
                    if (getResolved(structureMapping) && !scs.isConstant()) {
                        if (!scs.isDiffusing()) {
                            throw new MappingException("Enable diffusion in Application '" + simContext.getName() + "'. This must be done for any species (e.g '" + sc.getName() + "') in flux reactions.\n\n" + "To save or run simulations, set the diffusion rate to a non-zero " + "value in Initial Conditions or disable those reactions in Specifications->Reactions.");
                        }
                        return scm.getVariable().getName() + (sc.getStructure() == structTopology.getInsideFeature(membrane) ? "_INSIDE" : "_OUTSIDE");
                    } else {
                        return scm.getSpeciesContext().getName();
                    }
                } else {
                    throw new MappingException(sc.getName() + " shouldn't be involved with structure " + structureMapping.getStructure().getName());
                }
            }
        }
    }
    return getNameScope().getSymbolName(ste);
}
Also used : MembraneMapping(cbit.vcell.mapping.MembraneMapping) SpeciesContextMapping(cbit.vcell.mapping.SpeciesContextMapping) SpeciesContext(cbit.vcell.model.SpeciesContext) StructureMappingParameter(cbit.vcell.mapping.StructureMapping.StructureMappingParameter) SpeciesContextSpec(cbit.vcell.mapping.SpeciesContextSpec) StructureMapping(cbit.vcell.mapping.StructureMapping) ExpressionException(cbit.vcell.parser.ExpressionException) MappingException(cbit.vcell.mapping.MappingException) KineticsParameter(cbit.vcell.model.Kinetics.KineticsParameter) FeatureMapping(cbit.vcell.mapping.FeatureMapping) Membrane(cbit.vcell.model.Membrane) Structure(cbit.vcell.model.Structure) Vector(java.util.Vector) SpeciesContextSpecParameter(cbit.vcell.mapping.SpeciesContextSpec.SpeciesContextSpecParameter) SpeciesContextSpecParameter(cbit.vcell.mapping.SpeciesContextSpec.SpeciesContextSpecParameter) StructureTopology(cbit.vcell.model.Model.StructureTopology) LocalParameter(cbit.vcell.mapping.ParameterContext.LocalParameter) ModelParameter(cbit.vcell.model.Model.ModelParameter) ElectricalStimulus(cbit.vcell.mapping.ElectricalStimulus) ProxyParameter(cbit.vcell.model.ProxyParameter) SpeciesContextSpecProxyParameter(cbit.vcell.mapping.SpeciesContextSpec.SpeciesContextSpecProxyParameter) StructureMappingParameter(cbit.vcell.mapping.StructureMapping.StructureMappingParameter) Expression(cbit.vcell.parser.Expression) Model(cbit.vcell.model.Model)

Aggregations

ExpressionException (cbit.vcell.parser.ExpressionException)199 Expression (cbit.vcell.parser.Expression)138 MathException (cbit.vcell.math.MathException)58 PropertyVetoException (java.beans.PropertyVetoException)51 DataAccessException (org.vcell.util.DataAccessException)34 ArrayList (java.util.ArrayList)32 Variable (cbit.vcell.math.Variable)30 IOException (java.io.IOException)29 Element (org.jdom.Element)26 ExpressionBindingException (cbit.vcell.parser.ExpressionBindingException)25 MappingException (cbit.vcell.mapping.MappingException)24 Function (cbit.vcell.math.Function)24 Vector (java.util.Vector)24 ModelException (cbit.vcell.model.ModelException)23 SolverException (cbit.vcell.solver.SolverException)23 CompartmentSubDomain (cbit.vcell.math.CompartmentSubDomain)22 VCUnitDefinition (cbit.vcell.units.VCUnitDefinition)21 Constant (cbit.vcell.math.Constant)20 MathDescription (cbit.vcell.math.MathDescription)19 Structure (cbit.vcell.model.Structure)18