Search in sources :

Example 16 with Expression

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

the class SBMLImporter method addParameters.

/**
 * addParameters : Adds global parameters from SBML model to VCell model. If
 * expression for global parameter contains species, creates a conc_factor
 * parameter (conversion from SBML - VCell conc units) and adds this factor
 * to VC global params list, and replaces occurances of 'sp' with
 * 'sp*concFactor' in original param expression.
 *
 * @throws PropertyVetoException
 */
protected void addParameters() throws Exception {
    ListOf listofGlobalParams = sbmlModel.getListOfParameters();
    if (listofGlobalParams == null) {
        System.out.println("No Global Parameters");
        return;
    }
    Model vcModel = vcBioModel.getSimulationContext(0).getModel();
    ArrayList<ModelParameter> vcModelParamsList = new ArrayList<Model.ModelParameter>();
    // create a hash of reserved symbols so that if there is any reserved
    // symbol occurring as a global parameter in the SBML model,
    // the hash can be used to check for reserved symbols, so that it will
    // not be added as a global parameter in VCell,
    // since reserved symbols cannot be used as other variables (species,
    // structureSize, parameters, reactions, etc.).
    HashSet<String> reservedSymbolHash = new HashSet<String>();
    for (ReservedSymbol rs : vcModel.getReservedSymbols()) {
        reservedSymbolHash.add(rs.getName());
    }
    ModelUnitSystem modelUnitSystem = vcModel.getUnitSystem();
    for (int i = 0; i < sbmlModel.getNumParameters(); i++) {
        Parameter sbmlGlobalParam = (Parameter) listofGlobalParams.get(i);
        String paramName = sbmlGlobalParam.getId();
        SpatialParameterPlugin spplugin = null;
        if (bSpatial) {
            // check if parameter id is x/y/z : if so, check if its
            // 'spatialSymbolRef' child's spatial id and type are non-empty.
            // If so, the parameter represents a spatial element.
            // If not, throw an exception, since a parameter that does not
            // represent a spatial element cannot have an id of x/y/z
            spplugin = (SpatialParameterPlugin) sbmlGlobalParam.getPlugin(SBMLUtils.SBML_SPATIAL_NS_PREFIX);
            if (paramName.equals("x") || paramName.equals("y") || paramName.equals("z")) {
                boolean bSpatialParam = (spplugin != null && spplugin.getParamType() instanceof SpatialSymbolReference);
                // if (a) and (b) are true, continue with the next parameter
                if (!bSpatialParam) {
                    throw new RuntimeException("Parameter '" + paramName + "' is not a spatial parameter : Cannot have a variable in VCell named '" + paramName + "' unless it is a spatial variable.");
                } else {
                    // parameter to the list of vcell parameters.
                    continue;
                }
            }
        }
        // 
        // Get param value if set or get its expression from rule
        // 
        // Check if param is defined by an assignment rule or initial
        // assignment. If so, that value overrides the value existing in the
        // param element.
        // assignment rule, first
        Expression valueExpr = getValueFromAssignmentRule(paramName);
        if (valueExpr == null) {
            if (sbmlGlobalParam.isSetValue()) {
                double value = sbmlGlobalParam.getValue();
                valueExpr = new Expression(value);
            } else {
                // if value for global param is not set and param has a rate
                // rule, need to set an init value for param (else, there
                // will be a problem in reaction which uses this parameter).
                // use a 'default' initial value of '0'
                valueExpr = new Expression(0.0);
            // logger.sendMessage(VCLogger.Priority.MediumPriority,
            // VCLogger.Priority.LowPriority,
            // "Parameter did not have an initial value, but has a rate rule specified. Using a default value of 0.0.");
            }
        }
        if (valueExpr != null) {
            // valueExpr will be changed
            valueExpr = adjustExpression(valueExpr, vcModel);
        }
        // extension
        if (bSpatial) {
            VCAssert.assertTrue(spplugin != null, "invalid initialization logic");
            ParameterType sbmlParamType = spplugin.getParamType();
            SpeciesContext paramSpContext = null;
            SpeciesContextSpec vcSpContextsSpec = null;
            // Check for diffusion coefficient(s)
            if (sbmlParamType instanceof DiffusionCoefficient) {
                DiffusionCoefficient diffCoeff = (DiffusionCoefficient) sbmlParamType;
                if (diffCoeff != null && diffCoeff.isSetVariable()) {
                    // get the var of diffCoeff; find appropriate spContext
                    // in vcell; set its diff param to param value.
                    paramSpContext = vcModel.getSpeciesContext(diffCoeff.getVariable());
                    if (paramSpContext != null) {
                        vcSpContextsSpec = vcBioModel.getSimulationContext(0).getReactionContext().getSpeciesContextSpec(paramSpContext);
                        vcSpContextsSpec.getDiffusionParameter().setExpression(valueExpr);
                    }
                    // coeff parameter to the list of vcell parameters.
                    continue;
                }
            }
            // Check for advection coefficient(s)
            if (sbmlParamType instanceof AdvectionCoefficient) {
                AdvectionCoefficient advCoeff = (AdvectionCoefficient) sbmlParamType;
                if (advCoeff != null && advCoeff.isSetVariable()) {
                    // get the var of advCoeff; find appropriate spContext
                    // in vcell; set its adv param to param value.
                    paramSpContext = vcModel.getSpeciesContext(advCoeff.getVariable());
                    if (paramSpContext != null) {
                        vcSpContextsSpec = vcBioModel.getSimulationContext(0).getReactionContext().getSpeciesContextSpec(paramSpContext);
                        CoordinateKind coordKind = advCoeff.getCoordinate();
                        SpeciesContextSpecParameter param = null;
                        switch(coordKind) {
                            case cartesianX:
                                {
                                    param = vcSpContextsSpec.getParameterFromRole(SpeciesContextSpec.ROLE_VelocityX);
                                    break;
                                }
                            case cartesianY:
                                {
                                    param = vcSpContextsSpec.getParameterFromRole(SpeciesContextSpec.ROLE_VelocityY);
                                    break;
                                }
                            case cartesianZ:
                                {
                                    param = vcSpContextsSpec.getParameterFromRole(SpeciesContextSpec.ROLE_VelocityZ);
                                    break;
                                }
                        }
                        param.setExpression(valueExpr);
                    }
                    // coeff parameter to the list of vcell parameters.
                    continue;
                }
            }
            // Check for Boundary condition(s)
            if (sbmlParamType instanceof BoundaryCondition) {
                BoundaryCondition bCondn = (BoundaryCondition) sbmlParamType;
                if (bCondn != null && bCondn.isSetVariable()) {
                    // get the var of boundaryCondn; find appropriate
                    // spContext in vcell;
                    // set the BC param of its speciesContextSpec to param
                    // value.
                    paramSpContext = vcModel.getSpeciesContext(bCondn.getVariable());
                    if (paramSpContext == null) {
                        throw new RuntimeException("unable to process boundary condition for variable " + bCondn.getVariable());
                    }
                    StructureMapping sm = vcBioModel.getSimulationContext(0).getGeometryContext().getStructureMapping(paramSpContext.getStructure());
                    vcSpContextsSpec = vcBioModel.getSimulationContext(0).getReactionContext().getSpeciesContextSpec(paramSpContext);
                    for (CoordinateComponent coordComp : getSbmlGeometry().getListOfCoordinateComponents()) {
                        if (bCondn.getSpatialRef().equals(coordComp.getBoundaryMinimum().getSpatialId())) {
                            switch(coordComp.getType()) {
                                case cartesianX:
                                    {
                                        vcSpContextsSpec.getBoundaryXmParameter().setExpression(valueExpr);
                                    }
                                case cartesianY:
                                    {
                                        vcSpContextsSpec.getBoundaryYmParameter().setExpression(valueExpr);
                                    }
                                case cartesianZ:
                                    {
                                        vcSpContextsSpec.getBoundaryZmParameter().setExpression(valueExpr);
                                    }
                            }
                        }
                        if (bCondn.getSpatialRef().equals(coordComp.getBoundaryMaximum().getSpatialId())) {
                            switch(coordComp.getType()) {
                                case cartesianX:
                                    {
                                        vcSpContextsSpec.getBoundaryXpParameter().setExpression(valueExpr);
                                    }
                                case cartesianY:
                                    {
                                        vcSpContextsSpec.getBoundaryYpParameter().setExpression(valueExpr);
                                    }
                                case cartesianZ:
                                    {
                                        vcSpContextsSpec.getBoundaryZpParameter().setExpression(valueExpr);
                                    }
                            }
                        }
                    }
                    continue;
                }
            }
            // Check for Boundary condition(s)
            if (sbmlParamType instanceof SpatialSymbolReference) {
                SpatialSymbolReference spatialSymbolRef = (SpatialSymbolReference) sbmlParamType;
                throw new RuntimeException("generic Spatial Symbol References not yet supported, unresolved spatial reference '" + spatialSymbolRef.getSpatialRef() + "'");
            }
        }
        // doesn't exist.
        if (vcModel.getModelParameter(paramName) == null) {
            VCUnitDefinition glParamUnitDefn = sbmlUnitIdentifierHash.get(sbmlGlobalParam.getUnits());
            // set it to TBD or check if it was dimensionless.
            if (glParamUnitDefn == null) {
                glParamUnitDefn = modelUnitSystem.getInstance_TBD();
            }
            // VCell : cannot add reserved symbol to model params.
            if (!reservedSymbolHash.contains(paramName)) {
                ModelParameter vcGlobalParam = vcModel.new ModelParameter(paramName, valueExpr, Model.ROLE_UserDefined, glParamUnitDefn);
                if (paramName.length() > 64) {
                    // record global parameter name in annotation if it is
                    // longer than 64 characeters
                    vcGlobalParam.setDescription("Parameter Name : " + paramName);
                }
                vcModelParamsList.add(vcGlobalParam);
            }
        }
    }
    // end for - sbmlModel.parameters
    vcModel.setModelParameters(vcModelParamsList.toArray(new ModelParameter[0]));
}
Also used : ReservedSymbol(cbit.vcell.model.Model.ReservedSymbol) ArrayList(java.util.ArrayList) SpatialParameterPlugin(org.sbml.jsbml.ext.spatial.SpatialParameterPlugin) SpeciesContext(cbit.vcell.model.SpeciesContext) SpeciesContextSpec(cbit.vcell.mapping.SpeciesContextSpec) StructureMapping(cbit.vcell.mapping.StructureMapping) CoordinateKind(org.sbml.jsbml.ext.spatial.CoordinateKind) ListOf(org.sbml.jsbml.ListOf) HashSet(java.util.HashSet) ModelUnitSystem(cbit.vcell.model.ModelUnitSystem) SpeciesContextSpecParameter(cbit.vcell.mapping.SpeciesContextSpec.SpeciesContextSpecParameter) CoordinateComponent(org.sbml.jsbml.ext.spatial.CoordinateComponent) AdvectionCoefficient(org.sbml.jsbml.ext.spatial.AdvectionCoefficient) ParameterType(org.sbml.jsbml.ext.spatial.ParameterType) BioEventParameterType(cbit.vcell.mapping.BioEvent.BioEventParameterType) DiffusionCoefficient(org.sbml.jsbml.ext.spatial.DiffusionCoefficient) InteriorPoint(org.sbml.jsbml.ext.spatial.InteriorPoint) SpatialSymbolReference(org.sbml.jsbml.ext.spatial.SpatialSymbolReference) ModelParameter(cbit.vcell.model.Model.ModelParameter) VCUnitDefinition(cbit.vcell.units.VCUnitDefinition) Expression(cbit.vcell.parser.Expression) BoundaryCondition(org.sbml.jsbml.ext.spatial.BoundaryCondition) Model(cbit.vcell.model.Model) BioModel(cbit.vcell.biomodel.BioModel) KineticsParameter(cbit.vcell.model.Kinetics.KineticsParameter) Parameter(org.sbml.jsbml.Parameter) ModelParameter(cbit.vcell.model.Model.ModelParameter) SpeciesContextSpecParameter(cbit.vcell.mapping.SpeciesContextSpec.SpeciesContextSpecParameter) LocalParameter(org.sbml.jsbml.LocalParameter) KineticsProxyParameter(cbit.vcell.model.Kinetics.KineticsProxyParameter) UnresolvedParameter(cbit.vcell.model.Kinetics.UnresolvedParameter)

Example 17 with Expression

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

the class SBMLImporter method addReactions.

/**
 * addReactions:
 */
protected void addReactions(VCMetaData metaData) {
    if (sbmlModel == null) {
        throw new SBMLImportException("SBML model is NULL");
    }
    ListOf<Reaction> reactions = sbmlModel.getListOfReactions();
    final int numReactions = reactions.size();
    if (numReactions == 0) {
        lg.info("No Reactions");
        return;
    }
    // all reactions
    ArrayList<ReactionStep> vcReactionList = new ArrayList<>();
    // just the fast ones
    ArrayList<ReactionStep> fastReactionList = new ArrayList<>();
    Model vcModel = vcBioModel.getSimulationContext(0).getModel();
    ModelUnitSystem vcModelUnitSystem = vcModel.getUnitSystem();
    SpeciesContext[] vcSpeciesContexts = vcModel.getSpeciesContexts();
    try {
        for (Reaction sbmlRxn : reactions) {
            ReactionStep vcReaction = null;
            String rxnName = sbmlRxn.getId();
            boolean bReversible = true;
            if (sbmlRxn.isSetReversible()) {
                bReversible = sbmlRxn.getReversible();
            }
            // Check of reaction annotation is present; if so, does it have
            // an embedded element (flux or simpleRxn).
            // Create a fluxReaction or simpleReaction accordingly.
            Element sbmlImportRelatedElement = sbmlAnnotationUtil.readVCellSpecificAnnotation(sbmlRxn);
            Structure reactionStructure = getReactionStructure(sbmlRxn, vcSpeciesContexts, sbmlImportRelatedElement);
            if (sbmlImportRelatedElement != null) {
                Element embeddedRxnElement = getEmbeddedElementInAnnotation(sbmlImportRelatedElement, REACTION);
                if (embeddedRxnElement != null) {
                    if (embeddedRxnElement.getName().equals(XMLTags.FluxStepTag)) {
                        // If embedded element is a flux reaction, set flux
                        // reaction's strucure, flux carrier, physicsOption
                        // from the element attributes.
                        String structName = embeddedRxnElement.getAttributeValue(XMLTags.StructureAttrTag);
                        CastInfo<Membrane> ci = SBMLHelper.getTypedStructure(Membrane.class, vcModel, structName);
                        if (!ci.isGood()) {
                            throw new SBMLImportException("Appears that the flux reaction is occuring on " + ci.actualName() + ", not a membrane.");
                        }
                        vcReaction = new FluxReaction(vcModel, ci.get(), null, rxnName, bReversible);
                        vcReaction.setModel(vcModel);
                        // Set the fluxOption on the flux reaction based on
                        // whether it is molecular, molecular & electrical,
                        // electrical.
                        String fluxOptionStr = embeddedRxnElement.getAttributeValue(XMLTags.FluxOptionAttrTag);
                        if (fluxOptionStr.equals(XMLTags.FluxOptionMolecularOnly)) {
                            ((FluxReaction) vcReaction).setPhysicsOptions(ReactionStep.PHYSICS_MOLECULAR_ONLY);
                        } else if (fluxOptionStr.equals(XMLTags.FluxOptionMolecularAndElectrical)) {
                            ((FluxReaction) vcReaction).setPhysicsOptions(ReactionStep.PHYSICS_MOLECULAR_AND_ELECTRICAL);
                        } else if (fluxOptionStr.equals(XMLTags.FluxOptionElectricalOnly)) {
                            ((FluxReaction) vcReaction).setPhysicsOptions(ReactionStep.PHYSICS_ELECTRICAL_ONLY);
                        } else {
                            localIssueList.add(new Issue(vcReaction, issueContext, IssueCategory.SBMLImport_Reaction, "Unknown FluxOption : " + fluxOptionStr + " for SBML reaction : " + rxnName, Issue.SEVERITY_WARNING));
                        // logger.sendMessage(VCLogger.Priority.MediumPriority,
                        // VCLogger.ErrorType.ReactionError,
                        // "Unknown FluxOption : " + fluxOptionStr +
                        // " for SBML reaction : " + rxnName);
                        }
                    } else if (embeddedRxnElement.getName().equals(XMLTags.SimpleReactionTag)) {
                        // if embedded element is a simple reaction, set
                        // simple reaction's structure from element
                        // attributes
                        vcReaction = new SimpleReaction(vcModel, reactionStructure, rxnName, bReversible);
                    }
                } else {
                    vcReaction = new SimpleReaction(vcModel, reactionStructure, rxnName, bReversible);
                }
            } else {
                vcReaction = new SimpleReaction(vcModel, reactionStructure, rxnName, bReversible);
            }
            // set annotations and notes on vcReactions[i]
            sbmlAnnotationUtil.readAnnotation(vcReaction, sbmlRxn);
            sbmlAnnotationUtil.readNotes(vcReaction, sbmlRxn);
            // the limit on the reactionName length.
            if (rxnName.length() > 64) {
                String freeTextAnnotation = metaData.getFreeTextAnnotation(vcReaction);
                if (freeTextAnnotation == null) {
                    freeTextAnnotation = "";
                }
                StringBuffer oldRxnAnnotation = new StringBuffer(freeTextAnnotation);
                oldRxnAnnotation.append("\n\n" + rxnName);
                metaData.setFreeTextAnnotation(vcReaction, oldRxnAnnotation.toString());
            }
            // Now add the reactants, products, modifiers as specified by
            // the sbmlRxn
            addReactionParticipants(sbmlRxn, vcReaction);
            KineticLaw kLaw = sbmlRxn.getKineticLaw();
            Kinetics kinetics = null;
            if (kLaw != null) {
                // Convert the formula from kineticLaw into MathML and then
                // to an expression (infix) to be used in VCell kinetics
                ASTNode sbmlRateMath = kLaw.getMath();
                Expression kLawRateExpr = getExpressionFromFormula(sbmlRateMath);
                Expression vcRateExpression = new Expression(kLawRateExpr);
                // modifier (catalyst) to the reaction.
                for (int k = 0; k < vcSpeciesContexts.length; k++) {
                    if (vcRateExpression.hasSymbol(vcSpeciesContexts[k].getName())) {
                        if ((vcReaction.getReactant(vcSpeciesContexts[k].getName()) == null) && (vcReaction.getProduct(vcSpeciesContexts[k].getName()) == null) && (vcReaction.getCatalyst(vcSpeciesContexts[k].getName()) == null)) {
                            // This means that the speciesContext is not a
                            // reactant, product or modifier : it has to be
                            // added to the VC Rxn as a catalyst
                            vcReaction.addCatalyst(vcSpeciesContexts[k]);
                        }
                    }
                }
                // set kinetics on VCell reaction
                if (bSpatial) {
                    // if spatial SBML ('isSpatial' attribute set), create
                    // DistributedKinetics)
                    SpatialReactionPlugin ssrplugin = (SpatialReactionPlugin) sbmlRxn.getPlugin(SBMLUtils.SBML_SPATIAL_NS_PREFIX);
                    // 'spatial'
                    if (ssrplugin != null && ssrplugin.getIsLocal()) {
                        kinetics = new GeneralKinetics(vcReaction);
                    } else {
                        kinetics = new GeneralLumpedKinetics(vcReaction);
                    }
                } else {
                    kinetics = new GeneralLumpedKinetics(vcReaction);
                }
                // set kinetics on vcReaction
                vcReaction.setKinetics(kinetics);
                // If the name of the rate parameter has been changed by
                // user, or matches with global/local param,
                // it has to be changed.
                resolveRxnParameterNameConflicts(sbmlRxn, kinetics, sbmlImportRelatedElement);
                /**
                 * Now, based on the kinetic law expression, see if the rate
                 * is expressed in concentration/time or substance/time : If
                 * the compartment_id of the compartment corresponding to
                 * the structure in which the reaction takes place occurs in
                 * the rate law expression, it is in concentration/time;
                 * divide it by the compartment size and bring in the rate
                 * law as 'Distributed' kinetics. If not, the rate law is in
                 * substance/time; bring it in (as is) as 'Lumped' kinetics.
                 */
                ListOf<LocalParameter> localParameters = kLaw.getListOfLocalParameters();
                for (LocalParameter p : localParameters) {
                    String paramName = p.getId();
                    KineticsParameter kineticsParameter = kinetics.getKineticsParameter(paramName);
                    if (kineticsParameter == null) {
                        // add unresolved for now to prevent errors in kinetics.setParameterValue(kp,vcRateExpression) below
                        kinetics.addUnresolvedParameter(paramName);
                    }
                }
                KineticsParameter kp = kinetics.getAuthoritativeParameter();
                if (lg.isDebugEnabled()) {
                    lg.debug("Setting " + kp.getName() + ":  " + vcRateExpression.infix());
                }
                kinetics.setParameterValue(kp, vcRateExpression);
                // If there are any global parameters used in the kinetics,
                // and if they have species,
                // check if the species are already reactionParticipants in
                // the reaction. If not, add them as catalysts.
                KineticsProxyParameter[] kpps = kinetics.getProxyParameters();
                for (int j = 0; j < kpps.length; j++) {
                    if (kpps[j].getTarget() instanceof ModelParameter) {
                        ModelParameter mp = (ModelParameter) kpps[j].getTarget();
                        HashSet<String> refSpeciesNameHash = new HashSet<String>();
                        getReferencedSpeciesInExpr(mp.getExpression(), refSpeciesNameHash);
                        java.util.Iterator<String> refSpIterator = refSpeciesNameHash.iterator();
                        while (refSpIterator.hasNext()) {
                            String spName = refSpIterator.next();
                            org.sbml.jsbml.Species sp = sbmlModel.getSpecies(spName);
                            ArrayList<ReactionParticipant> rpArray = getVCReactionParticipantsFromSymbol(vcReaction, sp.getId());
                            if (rpArray == null || rpArray.size() == 0) {
                                // This means that the speciesContext is not
                                // a reactant, product or modifier : it has
                                // to be added as a catalyst
                                vcReaction.addCatalyst(vcModel.getSpeciesContext(sp.getId()));
                            }
                        }
                    }
                }
                // model - local params cannot be defined by rules.
                for (LocalParameter param : localParameters) {
                    String paramName = param.getId();
                    Expression exp = new Expression(param.getValue());
                    String unitString = param.getUnits();
                    VCUnitDefinition paramUnit = sbmlUnitIdentifierHash.get(unitString);
                    if (paramUnit == null) {
                        paramUnit = vcModelUnitSystem.getInstance_TBD();
                    }
                    // check if sbml local param is in kinetic params list;
                    // if so, add its value.
                    boolean lpSet = false;
                    KineticsParameter kineticsParameter = kinetics.getKineticsParameter(paramName);
                    if (kineticsParameter != null) {
                        if (lg.isDebugEnabled()) {
                            lg.debug("Setting local " + kineticsParameter.getName() + ":  " + exp.infix());
                        }
                        kineticsParameter.setExpression(exp);
                        kineticsParameter.setUnitDefinition(paramUnit);
                        lpSet = true;
                    } else {
                        UnresolvedParameter ur = kinetics.getUnresolvedParameter(paramName);
                        if (ur != null) {
                            kinetics.addUserDefinedKineticsParameter(paramName, exp, paramUnit);
                            lpSet = true;
                        }
                    }
                    if (!lpSet) {
                        // check if it is a proxy parameter (specifically,
                        // speciesContext or model parameter (structureSize
                        // too)).
                        KineticsProxyParameter kpp = kinetics.getProxyParameter(paramName);
                        // and units to local param values
                        if (kpp != null && kpp.getTarget() instanceof ModelParameter) {
                            kinetics.convertParameterType(kpp, false);
                            kineticsParameter = kinetics.getKineticsParameter(paramName);
                            kinetics.setParameterValue(kineticsParameter, exp);
                            kineticsParameter.setUnitDefinition(paramUnit);
                        }
                    }
                }
            } else {
                // sbmlKLaw was null, so creating a GeneralKinetics with 0.0
                // as rate.
                kinetics = new GeneralKinetics(vcReaction);
            }
            // end - if-else KLaw != null
            // set the reaction kinetics, and add reaction to the vcell
            // model.
            kinetics.resolveUndefinedUnits();
            // System.out.println("ADDED SBML REACTION : \"" + rxnName +
            // "\" to VCModel");
            vcReactionList.add(vcReaction);
            if (sbmlRxn.isSetFast() && sbmlRxn.getFast()) {
                fastReactionList.add(vcReaction);
            }
        }
        // end - for vcReactions
        ReactionStep[] array = vcReactionList.toArray(new ReactionStep[vcReactionList.size()]);
        vcModel.setReactionSteps(array);
        final ReactionContext rc = vcBioModel.getSimulationContext(0).getReactionContext();
        for (ReactionStep frs : fastReactionList) {
            final ReactionSpec rs = rc.getReactionSpec(frs);
            rs.setReactionMapping(ReactionSpec.FAST);
        }
    } catch (ModelPropertyVetoException mpve) {
        throw new SBMLImportException(mpve.getMessage(), mpve);
    } catch (Exception e1) {
        e1.printStackTrace(System.out);
        throw new SBMLImportException(e1.getMessage(), e1);
    }
}
Also used : Issue(org.vcell.util.Issue) ArrayList(java.util.ArrayList) FluxReaction(cbit.vcell.model.FluxReaction) SpeciesContext(cbit.vcell.model.SpeciesContext) GeneralKinetics(cbit.vcell.model.GeneralKinetics) KineticsParameter(cbit.vcell.model.Kinetics.KineticsParameter) ReactionContext(cbit.vcell.mapping.ReactionContext) HashSet(java.util.HashSet) KineticsProxyParameter(cbit.vcell.model.Kinetics.KineticsProxyParameter) ReactionSpec(cbit.vcell.mapping.ReactionSpec) ModelPropertyVetoException(cbit.vcell.model.ModelPropertyVetoException) ModelParameter(cbit.vcell.model.Model.ModelParameter) VCUnitDefinition(cbit.vcell.units.VCUnitDefinition) ReactionStep(cbit.vcell.model.ReactionStep) Kinetics(cbit.vcell.model.Kinetics) GeneralKinetics(cbit.vcell.model.GeneralKinetics) GeneralLumpedKinetics(cbit.vcell.model.GeneralLumpedKinetics) KineticLaw(org.sbml.jsbml.KineticLaw) ReactionParticipant(cbit.vcell.model.ReactionParticipant) Element(org.jdom.Element) UnresolvedParameter(cbit.vcell.model.Kinetics.UnresolvedParameter) GeneralLumpedKinetics(cbit.vcell.model.GeneralLumpedKinetics) ASTNode(org.sbml.jsbml.ASTNode) Membrane(cbit.vcell.model.Membrane) Structure(cbit.vcell.model.Structure) ModelUnitSystem(cbit.vcell.model.ModelUnitSystem) SpatialReactionPlugin(org.sbml.jsbml.ext.spatial.SpatialReactionPlugin) SimpleReaction(cbit.vcell.model.SimpleReaction) Reaction(org.sbml.jsbml.Reaction) SimpleReaction(cbit.vcell.model.SimpleReaction) FluxReaction(cbit.vcell.model.FluxReaction) InteriorPoint(org.sbml.jsbml.ext.spatial.InteriorPoint) XMLStreamException(javax.xml.stream.XMLStreamException) SbmlException(org.vcell.sbml.SbmlException) IOException(java.io.IOException) PropertyVetoException(java.beans.PropertyVetoException) SBMLException(org.sbml.jsbml.SBMLException) ModelPropertyVetoException(cbit.vcell.model.ModelPropertyVetoException) ExpressionException(cbit.vcell.parser.ExpressionException) LocalParameter(org.sbml.jsbml.LocalParameter) Expression(cbit.vcell.parser.Expression) Model(cbit.vcell.model.Model) BioModel(cbit.vcell.biomodel.BioModel)

Example 18 with Expression

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

the class SBMLImporter method addCompartments.

protected void addCompartments(VCMetaData metaData) {
    if (sbmlModel == null) {
        throw new SBMLImportException("SBML model is NULL");
    }
    ListOf listofCompartments = sbmlModel.getListOfCompartments();
    if (listofCompartments == null) {
        throw new SBMLImportException("Cannot have 0 compartments in model");
    }
    // Using a vector here - since there can be SBML models with only
    // features and no membranes.
    // Hence keeping the datastructure flexible.
    List<Structure> structList = new ArrayList<Structure>();
    java.util.HashMap<String, Structure> structureNameMap = new java.util.HashMap<String, Structure>();
    try {
        int structIndx = 0;
        // First pass - create the structures
        for (int i = 0; i < sbmlModel.getNumCompartments(); i++) {
            org.sbml.jsbml.Compartment compartment = (org.sbml.jsbml.Compartment) listofCompartments.get(i);
            String compartmentName = compartment.getId();
            if (!compartment.isSetSpatialDimensions() || compartment.getSpatialDimensions() == 3) {
                Feature feature = new Feature(compartmentName);
                structList.add(structIndx, feature);
                structureNameMap.put(compartmentName, feature);
            } else if (compartment.getSpatialDimensions() == 2) {
                // spatial dimensions is set (see clause above)
                Membrane membrane = new Membrane(compartmentName);
                structList.add(structIndx, membrane);
                structureNameMap.put(compartmentName, membrane);
            } else {
                logger.sendMessage(VCLogger.Priority.HighPriority, VCLogger.ErrorType.CompartmentError, "Cannot deal with spatial dimension : " + compartment.getSpatialDimensions() + " for compartments at this time.");
                throw new SBMLImportException("Cannot deal with spatial dimension : " + compartment.getSpatialDimensions() + " for compartments at this time");
            }
            structIndx++;
            sbmlAnnotationUtil.readAnnotation(structList.get(i), compartment);
            sbmlAnnotationUtil.readNotes(structList.get(i), compartment);
        }
        // Second pass - connect the structures
        Model model = vcBioModel.getSimulationContext(0).getModel();
        for (int i = 0; i < sbmlModel.getNumCompartments(); i++) {
            org.sbml.jsbml.Compartment sbmlCompartment = (org.sbml.jsbml.Compartment) listofCompartments.get(i);
            String outsideCompartmentId = null;
            if (sbmlCompartment.getOutside() != null && sbmlCompartment.getOutside().length() > 0) {
                // compartment.getOutside returns the Sid of the 'outside'
                // compartment, so get the compartment from model.
                outsideCompartmentId = sbmlCompartment.getOutside();
            } else {
                Element sbmlImportRelatedElement = sbmlAnnotationUtil.readVCellSpecificAnnotation(sbmlCompartment);
                if (sbmlImportRelatedElement != null) {
                    Element embeddedVCellElement = sbmlImportRelatedElement.getChild(OUTSIDE_COMP_NAME, Namespace.getNamespace(SBMLUtils.SBML_VCELL_NS));
                    if (embeddedVCellElement != null) {
                        outsideCompartmentId = embeddedVCellElement.getAttributeValue(XMLTags.NameTag);
                    }
                }
            }
            if (outsideCompartmentId != null) {
                Compartment outsideCompartment = sbmlModel.getCompartment(outsideCompartmentId);
                Structure outsideStructure = (Structure) structureNameMap.get(outsideCompartment.getId());
                Structure struct = (Structure) structureNameMap.get(sbmlCompartment.getId());
                struct.setSbmlParentStructure(outsideStructure);
            }
        }
        // set the structures in vc vcBioModel.getSimulationContext(0)
        Structure[] structures = structList.toArray(new Structure[structList.size()]);
        model.setStructures(structures);
        // Third pass thro' the list of compartments : set the sizes on the
        // structureMappings - can be done only after setting
        // the structures on vcBioModel.getSimulationContext(0).
        boolean allSizesSet = true;
        for (int i = 0; i < sbmlModel.getNumCompartments(); i++) {
            org.sbml.jsbml.Compartment compartment = (org.sbml.jsbml.Compartment) listofCompartments.get(i);
            String compartmentName = compartment.getId();
            if (!compartment.isSetSize()) {
                // logger.sendMessage(VCLogger.Priority.MediumPriority,
                // TranslationMessage.COMPARTMENT_ERROR,
                // "compartment "+compartmentName+" size is not set in SBML document.");
                allSizesSet = false;
            } else {
                double size = compartment.getSize();
                // Check if size is specified by a rule
                Expression sizeExpr = getValueFromAssignmentRule(compartmentName);
                if (sizeExpr != null && !sizeExpr.isNumeric()) {
                    // We are NOT handling compartment sizes with assignment
                    // rules/initial Assignments that are NON-numeric at
                    // this time ...
                    logger.sendMessage(VCLogger.Priority.HighPriority, VCLogger.ErrorType.CompartmentError, "compartment " + compartmentName + " size has an assignment rule which is not a numeric value, cannot handle it at this time.");
                }
                // check if it is specified by initial assignment
                if (sizeExpr == null) {
                    InitialAssignment compInitAssgnment = sbmlModel.getInitialAssignment(compartmentName);
                    if (compInitAssgnment != null) {
                        sizeExpr = getExpressionFromFormula(compInitAssgnment.getMath());
                    }
                }
                if (sizeExpr != null && !sizeExpr.isNumeric()) {
                    // We are NOT handling compartment sizes with assignment
                    // rules/initial Assignments that are NON-numeric at
                    // this time ...
                    logger.sendMessage(VCLogger.Priority.HighPriority, VCLogger.ErrorType.CompartmentError, "compartment " + compartmentName + " size has an initial assignment which is not a numeric value, cannot handle it at this time.");
                }
                // from 'size' attribute,
                if (sizeExpr == null) {
                    sizeExpr = new Expression(size);
                }
                // Now set the size of the compartment.
                Structure struct = model.getStructure(compartmentName);
                StructureMapping.StructureMappingParameter mappingParam = vcBioModel.getSimulationContext(0).getGeometryContext().getStructureMapping(struct).getSizeParameter();
                mappingParam.setExpression(sizeExpr);
            }
        }
        // size is set
        if (allSizesSet) {
            StructureSizeSolver.updateRelativeStructureSizes(vcBioModel.getSimulationContext(0));
        }
    } catch (Exception e) {
        e.printStackTrace(System.out);
        throw new SBMLImportException("Error adding Feature to vcModel " + e.getMessage(), e);
    }
}
Also used : HashMap(java.util.HashMap) Compartment(org.sbml.jsbml.Compartment) Element(org.jdom.Element) ArrayList(java.util.ArrayList) Feature(cbit.vcell.model.Feature) StructureMapping(cbit.vcell.mapping.StructureMapping) ListOf(org.sbml.jsbml.ListOf) Membrane(cbit.vcell.model.Membrane) Structure(cbit.vcell.model.Structure) InteriorPoint(org.sbml.jsbml.ext.spatial.InteriorPoint) XMLStreamException(javax.xml.stream.XMLStreamException) SbmlException(org.vcell.sbml.SbmlException) IOException(java.io.IOException) PropertyVetoException(java.beans.PropertyVetoException) SBMLException(org.sbml.jsbml.SBMLException) ModelPropertyVetoException(cbit.vcell.model.ModelPropertyVetoException) ExpressionException(cbit.vcell.parser.ExpressionException) InitialAssignment(org.sbml.jsbml.InitialAssignment) Expression(cbit.vcell.parser.Expression) Model(cbit.vcell.model.Model) BioModel(cbit.vcell.biomodel.BioModel) Compartment(org.sbml.jsbml.Compartment)

Example 19 with Expression

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

the class SBMLImporter method addAssignmentRules.

/**
 * addAssignmentRules : Adds Assignment Rules from the SBML document
 * Assignment rules are allowed (initial concentration of species; parameter
 * definitions, etc.
 */
protected void addAssignmentRules() throws Exception {
    if (sbmlModel == null) {
        throw new SBMLImportException("SBML model is NULL");
    }
    ListOf listofRules = sbmlModel.getListOfRules();
    if (listofRules == null) {
        System.out.println("No Rules specified");
        return;
    }
    for (int i = 0; i < sbmlModel.getNumRules(); i++) {
        Rule rule = (org.sbml.jsbml.Rule) listofRules.get(i);
        if (rule instanceof AssignmentRule) {
            // Get the assignment rule and store it in the hashMap.
            AssignmentRule assignmentRule = (AssignmentRule) rule;
            Expression assignmentRuleMathExpr = getExpressionFromFormula(assignmentRule.getMath());
            String assgnRuleVar = assignmentRule.getVariable();
            // check if assignment rule is for species. If so, check if
            // expression has x/y/z term. This is not allowed for
            // non-spatial models in vcell.
            org.sbml.jsbml.Species ruleSpecies = sbmlModel.getSpecies(assgnRuleVar);
            if (ruleSpecies != null) {
                if (assignmentRuleMathExpr != null) {
                    Model vcModel = vcBioModel.getSimulationContext(0).getModel();
                    if (!bSpatial) {
                        if (assignmentRuleMathExpr.hasSymbol(vcModel.getX().getName()) || assignmentRuleMathExpr.hasSymbol(vcModel.getY().getName()) || assignmentRuleMathExpr.hasSymbol(vcModel.getZ().getName())) {
                            logger.sendMessage(VCLogger.Priority.HighPriority, VCLogger.ErrorType.SpeciesError, "An assignment rule for species " + ruleSpecies.getId() + " contains " + RESERVED_SPATIAL + " variable(s) (x,y,z), this is not allowed for a non-spatial model in VCell");
                        }
                    }
                }
            }
            assignmentRulesHash.put(assignmentRule.getVariable(), assignmentRuleMathExpr);
        }
    }
// end - for i : rules
}
Also used : Expression(cbit.vcell.parser.Expression) AssignmentRule(org.sbml.jsbml.AssignmentRule) ListOf(org.sbml.jsbml.ListOf) Model(cbit.vcell.model.Model) BioModel(cbit.vcell.biomodel.BioModel) AlgebraicRule(org.sbml.jsbml.AlgebraicRule) Rule(org.sbml.jsbml.Rule) AssignmentRule(org.sbml.jsbml.AssignmentRule) RateRule(org.sbml.jsbml.RateRule) InteriorPoint(org.sbml.jsbml.ext.spatial.InteriorPoint)

Example 20 with Expression

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

the class SBMLImporter method getReferencedSpecies.

/**
 * getReferencedSpecies(Reaction , HashSet<String> ) : Get the species
 * referenced in sbmlRxn (reactants and products); store their names in
 * hashSet (refereceNamesHash) Also, get the species referenced in the
 * reaction kineticLaw expression from getReferencedSpeciesInExpr.
 *
 * @param sbmlRxn
 * @param refSpeciesNameHash
 * @throws ExpressionException
 * @throws XMLStreamException
 * @throws SBMLException
 */
private void getReferencedSpecies(Reaction sbmlRxn, HashSet<String> refSpeciesNameHash) throws ExpressionException, SBMLException, XMLStreamException {
    // get all species referenced in listOfReactants
    for (int i = 0; i < (int) sbmlRxn.getNumReactants(); i++) {
        SpeciesReference reactRef = sbmlRxn.getReactant(i);
        refSpeciesNameHash.add(reactRef.getSpecies());
    }
    // get all species referenced in listOfProducts
    for (int i = 0; i < (int) sbmlRxn.getNumProducts(); i++) {
        SpeciesReference pdtRef = sbmlRxn.getProduct(i);
        refSpeciesNameHash.add(pdtRef.getSpecies());
    }
    // get all species referenced in reaction rate law
    if (sbmlRxn.getKineticLaw() != null) {
        Expression rateExpression = getExpressionFromFormula(sbmlRxn.getKineticLaw().getMath());
        getReferencedSpeciesInExpr(rateExpression, refSpeciesNameHash);
    }
}
Also used : Expression(cbit.vcell.parser.Expression) SpeciesReference(org.sbml.jsbml.SpeciesReference) ModifierSpeciesReference(org.sbml.jsbml.ModifierSpeciesReference) InteriorPoint(org.sbml.jsbml.ext.spatial.InteriorPoint)

Aggregations

Expression (cbit.vcell.parser.Expression)549 ExpressionException (cbit.vcell.parser.ExpressionException)163 VCUnitDefinition (cbit.vcell.units.VCUnitDefinition)76 PropertyVetoException (java.beans.PropertyVetoException)73 Variable (cbit.vcell.math.Variable)69 ArrayList (java.util.ArrayList)58 Vector (java.util.Vector)56 MathException (cbit.vcell.math.MathException)55 VolVariable (cbit.vcell.math.VolVariable)53 SymbolTableEntry (cbit.vcell.parser.SymbolTableEntry)51 SpeciesContext (cbit.vcell.model.SpeciesContext)50 Element (org.jdom.Element)47 KineticsParameter (cbit.vcell.model.Kinetics.KineticsParameter)45 ExpressionBindingException (cbit.vcell.parser.ExpressionBindingException)45 Model (cbit.vcell.model.Model)43 Function (cbit.vcell.math.Function)42 Constant (cbit.vcell.math.Constant)41 ModelParameter (cbit.vcell.model.Model.ModelParameter)41 ModelUnitSystem (cbit.vcell.model.ModelUnitSystem)41 LocalParameter (cbit.vcell.mapping.ParameterContext.LocalParameter)38