Search in sources :

Example 6 with ASTNode

use of org.sbml.jsbml.ASTNode in project vcell by virtualcell.

the class SBMLExporter method addCompartments.

/**
 * addCompartments comment.
 * @throws XMLStreamException
 * @throws SbmlException
 */
protected void addCompartments() throws XMLStreamException, SbmlException {
    Model vcModel = vcBioModel.getModel();
    cbit.vcell.model.Structure[] vcStructures = vcModel.getStructures();
    for (int i = 0; i < vcStructures.length; i++) {
        Compartment sbmlCompartment = sbmlModel.createCompartment();
        sbmlCompartment.setId(TokenMangler.mangleToSName(vcStructures[i].getName()));
        sbmlCompartment.setName(vcStructures[i].getName());
        VCUnitDefinition sbmlSizeUnit = null;
        StructureTopology structTopology = getSelectedSimContext().getModel().getStructureTopology();
        Structure parentStructure = structTopology.getParentStructure(vcStructures[i]);
        if (vcStructures[i] instanceof Feature) {
            sbmlCompartment.setSpatialDimensions(3);
            String outside = null;
            if (parentStructure != null) {
                outside = TokenMangler.mangleToSName(parentStructure.getName());
            }
            if (outside != null) {
                if (outside.length() > 0) {
                    sbmlCompartment.setOutside(outside);
                }
            }
            sbmlSizeUnit = sbmlExportSpec.getVolumeUnits();
            UnitDefinition unitDefn = getOrCreateSBMLUnit(sbmlSizeUnit);
            sbmlCompartment.setUnits(unitDefn);
        } else if (vcStructures[i] instanceof Membrane) {
            Membrane vcMembrane = (Membrane) vcStructures[i];
            sbmlCompartment.setSpatialDimensions(2);
            Feature outsideFeature = structTopology.getOutsideFeature(vcMembrane);
            if (outsideFeature != null) {
                sbmlCompartment.setOutside(TokenMangler.mangleToSName(outsideFeature.getName()));
                sbmlSizeUnit = sbmlExportSpec.getAreaUnits();
                UnitDefinition unitDefn = getOrCreateSBMLUnit(sbmlSizeUnit);
                sbmlCompartment.setUnits(unitDefn);
            } else if (lg.isWarnEnabled()) {
                lg.warn(this.sbmlModel.getName() + " membrame " + vcMembrane.getName() + " has not outside feature");
            }
        }
        sbmlCompartment.setConstant(true);
        StructureMapping vcStructMapping = getSelectedSimContext().getGeometryContext().getStructureMapping(vcStructures[i]);
        try {
            if (vcStructMapping.getSizeParameter().getExpression() != null) {
                sbmlCompartment.setSize(vcStructMapping.getSizeParameter().getExpression().evaluateConstant());
            } else {
            // really no need to set sizes of compartments in spatial ..... ????
            // throw new RuntimeException("Compartment size not set for compartment \"" + vcStructures[i].getName() + "\" ; Please set size and try exporting again.");
            }
        } catch (cbit.vcell.parser.ExpressionException e) {
            // If it is in the catch block, it means that the compartment size was probably not a double, but an assignment.
            // Check if the expression for the compartment size is not null and add it as an assignment rule.
            Expression sizeExpr = vcStructMapping.getSizeParameter().getExpression();
            if (sizeExpr != null) {
                ASTNode ruleFormulaNode = getFormulaFromExpression(sizeExpr);
                AssignmentRule assignRule = sbmlModel.createAssignmentRule();
                assignRule.setVariable(vcStructures[i].getName());
                assignRule.setMath(ruleFormulaNode);
                // If compartmentSize is specified by an assignment rule, the 'constant' field should be set to 'false' (default - true).
                sbmlCompartment.setConstant(false);
                sbmlModel.addRule(assignRule);
            }
        }
        // Add the outside compartment of given compartment as annotation to the compartment.
        // This is required later while trying to read in compartments ...
        Element sbmlImportRelatedElement = null;
        // if (parentStructure != null) {
        // sbmlImportRelatedElement = new Element(XMLTags.VCellRelatedInfoTag, sbml_vcml_ns);
        // Element compartmentElement = new Element(XMLTags.OutsideCompartmentTag, sbml_vcml_ns);
        // compartmentElement.setAttribute(XMLTags.NameAttrTag, TokenMangler.mangleToSName(parentStructure.getName()));
        // sbmlImportRelatedElement.addContent(compartmentElement);
        // }
        // Get annotation (RDF and non-RDF) for reactionStep from SBMLAnnotationUtils
        sbmlAnnotationUtil.writeAnnotation(vcStructures[i], sbmlCompartment, sbmlImportRelatedElement);
        // Now set notes,
        sbmlAnnotationUtil.writeNotes(vcStructures[i], sbmlCompartment);
    }
}
Also used : StructureTopology(cbit.vcell.model.Model.StructureTopology) Compartment(org.sbml.jsbml.Compartment) AssignmentRule(org.sbml.jsbml.AssignmentRule) Element(org.jdom.Element) ExpressionException(cbit.vcell.parser.ExpressionException) Feature(cbit.vcell.model.Feature) StructureMapping(cbit.vcell.mapping.StructureMapping) InteriorPoint(org.sbml.jsbml.ext.spatial.InteriorPoint) VCUnitDefinition(cbit.vcell.units.VCUnitDefinition) Expression(cbit.vcell.parser.Expression) Model(cbit.vcell.model.Model) BioModel(cbit.vcell.biomodel.BioModel) ASTNode(org.sbml.jsbml.ASTNode) Membrane(cbit.vcell.model.Membrane) Structure(cbit.vcell.model.Structure) VCUnitDefinition(cbit.vcell.units.VCUnitDefinition) UnitDefinition(org.sbml.jsbml.UnitDefinition)

Example 7 with ASTNode

use of org.sbml.jsbml.ASTNode in project vcell by virtualcell.

the class SBMLExporter method addInitialAssignments.

protected void addInitialAssignments() throws ExpressionException, MappingException, MathException, MatrixException, ModelException {
    // for species, the initial assignments are done in addSpecies()
    if (vcSelectedSimJob == null) {
        return;
    }
    int index = vcSelectedSimJob.getJobIndex();
    System.out.println("Simulation Job index = " + index);
    MathOverrides mo = vcSelectedSimJob.getSimulation().getMathOverrides();
    if (mo == null || !mo.hasOverrides()) {
        return;
    }
    // 
    // TODO: SEDMLExporter is doing it differently, much more complicated
    // 
    MathMapping mm = vcSelectedSimContext.createNewMathMapping();
    MathSymbolMapping msm = mm.getMathSymbolMapping();
    String[] ocns = mo.getOverridenConstantNames();
    for (String ocn : ocns) {
        SymbolTableEntry ste = SEDMLExporter.getSymbolTableEntryForModelEntity(msm, ocn);
        ModelParameter mp = vcSelectedSimContext.getModel().getModelParameter(ocn);
        Expression exp = mo.getActualExpression(ocn, index);
        String name = "";
        if (ste != null && ste instanceof SpeciesContextSpecParameter) {
            SpeciesContextSpecParameter scsp = (SpeciesContextSpecParameter) ste;
            SpeciesContext sc = scsp.getSpeciesContext();
            name = sc.getName();
        } else if (ste != null && ste instanceof ModelParameter) {
            name = ste.getName();
        } else if (ste != null && ste instanceof KineticsParameter) {
            // note: if we call this before adding the reactions, we can't verify that the name we use
            // here will match the name we assign when we actually add the reaction
            KineticsParameter kp = (KineticsParameter) ste;
            Kinetics ks = kp.getKinetics();
            ReactionStep rs = ks.getReactionStep();
            name = TokenMangler.mangleToSName(kp.getName() + "_" + rs.getName());
        } else {
            name = ocn;
            System.out.println("Unexpected override or parameter scan entity: " + ocn);
        }
        // System.out.println("  symbol: " + name + ", overriden constant: " + ocn + ", expression: " + exp.infix());
        org.sbml.jsbml.InitialAssignment ia = sbmlModel.createInitialAssignment();
        // String id = TokenMangler.mangleToSName("initialAssignment_" + name "_" + index);	// no point in defining id or name for initial assignment
        // ia.setId(id);
        // ia.setName(id);
        ia.setVariable(name);
        ASTNode math = getFormulaFromExpression(exp);
        ia.setMath(math);
    }
}
Also used : SpeciesContext(cbit.vcell.model.SpeciesContext) MathSymbolMapping(cbit.vcell.mapping.MathSymbolMapping) InteriorPoint(org.sbml.jsbml.ext.spatial.InteriorPoint) MathOverrides(cbit.vcell.solver.MathOverrides) ModelParameter(cbit.vcell.model.Model.ModelParameter) InitialAssignment(org.sbml.jsbml.InitialAssignment) SymbolTableEntry(cbit.vcell.parser.SymbolTableEntry) KineticsParameter(cbit.vcell.model.Kinetics.KineticsParameter) Expression(cbit.vcell.parser.Expression) ReactionStep(cbit.vcell.model.ReactionStep) MathMapping(cbit.vcell.mapping.MathMapping) ASTNode(org.sbml.jsbml.ASTNode) Kinetics(cbit.vcell.model.Kinetics) DistributedKinetics(cbit.vcell.model.DistributedKinetics) LumpedKinetics(cbit.vcell.model.LumpedKinetics) SpeciesContextSpecParameter(cbit.vcell.mapping.SpeciesContextSpec.SpeciesContextSpecParameter)

Example 8 with ASTNode

use of org.sbml.jsbml.ASTNode in project vcell by virtualcell.

the class SBMLExporter method addReactions.

/**
 * addReactions comment.
 * @throws SbmlException
 * @throws XMLStreamException
 */
protected void addReactions() throws SbmlException, XMLStreamException {
    // Check if any reaction has electrical mapping
    boolean bCalculatePotential = false;
    StructureMapping[] structureMappings = getSelectedSimContext().getGeometryContext().getStructureMappings();
    for (int i = 0; i < structureMappings.length; i++) {
        if (structureMappings[i] instanceof MembraneMapping) {
            if (((MembraneMapping) structureMappings[i]).getCalculateVoltage()) {
                bCalculatePotential = true;
            }
        }
    }
    // If it does, VCell doesn't export it to SBML (no representation).
    if (bCalculatePotential) {
        throw new RuntimeException("This VCell model has Electrical mapping; cannot be exported to SBML at this time");
    }
    l2gMap.clear();
    ReactionSpec[] vcReactionSpecs = getSelectedSimContext().getReactionContext().getReactionSpecs();
    for (int i = 0; i < vcReactionSpecs.length; i++) {
        if (vcReactionSpecs[i].isExcluded()) {
            continue;
        }
        ReactionStep vcReactionStep = vcReactionSpecs[i].getReactionStep();
        // Create sbml reaction
        String rxnName = vcReactionStep.getName();
        org.sbml.jsbml.Reaction sbmlReaction = sbmlModel.createReaction();
        sbmlReaction.setId(org.vcell.util.TokenMangler.mangleToSName(rxnName));
        sbmlReaction.setName(rxnName);
        String rxnSbmlName = vcReactionStep.getSbmlName();
        if (rxnSbmlName != null && !rxnSbmlName.isEmpty()) {
            sbmlReaction.setName(rxnSbmlName);
        }
        // If the reactionStep is a flux reaction, add the details to the annotation (structure, carrier valence, flux carrier, fluxOption, etc.)
        // If reactionStep is a simple reaction, add annotation to indicate the structure of reaction.
        // Useful when roundtripping ...
        Element sbmlImportRelatedElement = null;
        // try {
        // sbmlImportRelatedElement = getAnnotationElement(vcReactionStep);
        // } catch (XmlParseException e1) {
        // e1.printStackTrace(System.out);
        // //			throw new RuntimeException("Error ");
        // }
        // Get annotation (RDF and non-RDF) for reactionStep from SBMLAnnotationUtils
        sbmlAnnotationUtil.writeAnnotation(vcReactionStep, sbmlReaction, sbmlImportRelatedElement);
        // Now set notes,
        sbmlAnnotationUtil.writeNotes(vcReactionStep, sbmlReaction);
        // Get reaction kineticLaw
        Kinetics vcRxnKinetics = vcReactionStep.getKinetics();
        org.sbml.jsbml.KineticLaw sbmlKLaw = sbmlReaction.createKineticLaw();
        try {
            // Convert expression from kinetics rate parameter into MathML and use libSBMl utilities to convert it to formula
            // (instead of directly using rate parameter's expression infix) to maintain integrity of formula :
            // for example logical and inequalities are not handled gracefully by libSBMl if expression.infix is used.
            final Expression localRateExpr;
            final Expression lumpedRateExpr;
            if (vcRxnKinetics instanceof DistributedKinetics) {
                localRateExpr = ((DistributedKinetics) vcRxnKinetics).getReactionRateParameter().getExpression();
                lumpedRateExpr = null;
            } else if (vcRxnKinetics instanceof LumpedKinetics) {
                localRateExpr = null;
                lumpedRateExpr = ((LumpedKinetics) vcRxnKinetics).getLumpedReactionRateParameter().getExpression();
            } else {
                throw new RuntimeException("unexpected Rate Law '" + vcRxnKinetics.getClass().getSimpleName() + "', not distributed or lumped type");
            }
            // if (vcRxnKinetics instanceof DistributedKinetics)
            // Expression correctedRateExpr = kineticsAdapter.getExpression();
            // Add parameters, if any, to the kineticLaw
            Kinetics.KineticsParameter[] vcKineticsParams = vcRxnKinetics.getKineticsParameters();
            // In the first pass thro' the kinetic params, store the non-numeric param names and expressions in arrays
            String[] kinParamNames = new String[vcKineticsParams.length];
            Expression[] kinParamExprs = new Expression[vcKineticsParams.length];
            for (int j = 0; j < vcKineticsParams.length; j++) {
                if (true) {
                    // Since local reaction parameters cannot be defined by a rule, such parameters (with rules) are exported as global parameters.
                    if ((vcKineticsParams[j].getRole() == Kinetics.ROLE_CurrentDensity && (!vcKineticsParams[j].getExpression().isZero())) || (vcKineticsParams[j].getRole() == Kinetics.ROLE_LumpedCurrent && (!vcKineticsParams[j].getExpression().isZero()))) {
                        throw new RuntimeException("Electric current not handled by SBML export; failed to export reaction \"" + vcReactionStep.getName() + "\" at this time");
                    }
                    if (!vcKineticsParams[j].getExpression().isNumeric()) {
                        // NON_NUMERIC KINETIC PARAM
                        // Create new name for kinetic parameter and store it in kinParamNames, store corresponding exprs in kinParamExprs
                        // Will be used later to add this param as global.
                        String newParamName = TokenMangler.mangleToSName(vcKineticsParams[j].getName() + "_" + vcReactionStep.getName());
                        kinParamNames[j] = newParamName;
                        kinParamExprs[j] = new Expression(vcKineticsParams[j].getExpression());
                    }
                }
            }
            // If so, these need to be added as global param (else the SBML doc will not be valid)
            for (int j = 0; j < vcKineticsParams.length; j++) {
                final KineticsParameter vcKParam = vcKineticsParams[j];
                if ((vcKParam.getRole() != Kinetics.ROLE_ReactionRate) && (vcKParam.getRole() != Kinetics.ROLE_LumpedReactionRate)) {
                    // if expression of kinetic param evaluates to a double, the parameter value is set
                    if ((vcKParam.getRole() == Kinetics.ROLE_CurrentDensity && (!vcKParam.getExpression().isZero())) || (vcKParam.getRole() == Kinetics.ROLE_LumpedCurrent && (!vcKParam.getExpression().isZero()))) {
                        throw new RuntimeException("Electric current not handled by SBML export; failed to export reaction \"" + vcReactionStep.getName() + "\" at this time");
                    }
                    if (vcKParam.getExpression().isNumeric()) {
                        // NUMERIC KINETIC PARAM
                        // check if it is used in other parameters that have expressions,
                        boolean bAddedParam = false;
                        String origParamName = vcKParam.getName();
                        String newParamName = TokenMangler.mangleToSName(origParamName + "_" + vcReactionStep.getName());
                        VCUnitDefinition vcUnit = vcKParam.getUnitDefinition();
                        for (int k = 0; k < vcKineticsParams.length; k++) {
                            if (kinParamExprs[k] != null) {
                                // The param could be in the expression for any other param
                                if (kinParamExprs[k].hasSymbol(origParamName)) {
                                    // mangle its name to avoid conflict with other globals
                                    if (globalParamNamesHash.get(newParamName) == null) {
                                        globalParamNamesHash.put(newParamName, newParamName);
                                        org.sbml.jsbml.Parameter sbmlKinParam = sbmlModel.createParameter();
                                        sbmlKinParam.setId(newParamName);
                                        sbmlKinParam.setValue(vcKParam.getConstantValue());
                                        final boolean constValue = vcKParam.isConstant();
                                        sbmlKinParam.setConstant(true);
                                        // Set SBML units for sbmlParam using VC units from vcParam
                                        if (!vcUnit.isTBD()) {
                                            UnitDefinition unitDefn = getOrCreateSBMLUnit(vcUnit);
                                            sbmlKinParam.setUnits(unitDefn);
                                        }
                                        Pair<String, String> origParam = new Pair<String, String>(rxnName, origParamName);
                                        l2gMap.put(origParam, newParamName);
                                        bAddedParam = true;
                                    } else {
                                    // need to get another name for param and need to change all its refereces in the other kinParam euqations.
                                    }
                                    // update the expression to contain new name, since the globalparam has new name
                                    kinParamExprs[k].substituteInPlace(new Expression(origParamName), new Expression(newParamName));
                                }
                            }
                        }
                        // If the param hasn't been added yet, it is definitely a local param. add it to kineticLaw now.
                        if (!bAddedParam) {
                            org.sbml.jsbml.LocalParameter sbmlKinParam = sbmlKLaw.createLocalParameter();
                            sbmlKinParam.setId(origParamName);
                            sbmlKinParam.setValue(vcKParam.getConstantValue());
                            System.out.println("tis constant " + sbmlKinParam.isExplicitlySetConstant());
                            // Set SBML units for sbmlParam using VC units from vcParam
                            if (!vcUnit.isTBD()) {
                                UnitDefinition unitDefn = getOrCreateSBMLUnit(vcUnit);
                                sbmlKinParam.setUnits(unitDefn);
                            }
                        } else {
                            // hence change its occurance in rate expression if it contains that param name
                            if (localRateExpr != null && localRateExpr.hasSymbol(origParamName)) {
                                localRateExpr.substituteInPlace(new Expression(origParamName), new Expression(newParamName));
                            }
                            if (lumpedRateExpr != null && lumpedRateExpr.hasSymbol(origParamName)) {
                                lumpedRateExpr.substituteInPlace(new Expression(origParamName), new Expression(newParamName));
                            }
                        }
                    }
                }
            }
            // (using the kinParamNames and kinParamExprs above) to ensure uniqueness in the global parameter names.
            for (int j = 0; j < vcKineticsParams.length; j++) {
                if (((vcKineticsParams[j].getRole() != Kinetics.ROLE_ReactionRate) && (vcKineticsParams[j].getRole() != Kinetics.ROLE_LumpedReactionRate)) && !(vcKineticsParams[j].getExpression().isNumeric())) {
                    String oldName = vcKineticsParams[j].getName();
                    String newName = kinParamNames[j];
                    // change the name of this parameter in the rate expression
                    if (localRateExpr != null && localRateExpr.hasSymbol(oldName)) {
                        localRateExpr.substituteInPlace(new Expression(oldName), new Expression(newName));
                    }
                    if (lumpedRateExpr != null && lumpedRateExpr.hasSymbol(oldName)) {
                        lumpedRateExpr.substituteInPlace(new Expression(oldName), new Expression(newName));
                    }
                    // Change the occurence of this param in other param expressions
                    for (int k = 0; k < vcKineticsParams.length; k++) {
                        if (((vcKineticsParams[k].getRole() != Kinetics.ROLE_ReactionRate) && (vcKineticsParams[j].getRole() != Kinetics.ROLE_LumpedReactionRate)) && !(vcKineticsParams[k].getExpression().isNumeric())) {
                            if (k != j && vcKineticsParams[k].getExpression().hasSymbol(oldName)) {
                                // for all params except the current param represented by index j (whose name was changed)
                                kinParamExprs[k].substituteInPlace(new Expression(oldName), new Expression(newName));
                            }
                            if (k == j && vcKineticsParams[k].getExpression().hasSymbol(oldName)) {
                                throw new RuntimeException("A parameter cannot refer to itself in its expression");
                            }
                        }
                    }
                // end for - k
                }
            }
            // In the fifth pass thro' the kinetic params, the non-numeric params are added to the global params of the model
            for (int j = 0; j < vcKineticsParams.length; j++) {
                if (((vcKineticsParams[j].getRole() != Kinetics.ROLE_ReactionRate) && (vcKineticsParams[j].getRole() != Kinetics.ROLE_LumpedReactionRate)) && !(vcKineticsParams[j].getExpression().isNumeric())) {
                    // Now, add this param to the globalParamNamesHash and add a global parameter to the sbmlModel
                    String paramName = kinParamNames[j];
                    if (globalParamNamesHash.get(paramName) == null) {
                        globalParamNamesHash.put(paramName, paramName);
                    } else {
                    // need to get another name for param and need to change all its refereces in the other kinParam euqations.
                    }
                    Pair<String, String> origParam = new Pair<String, String>(rxnName, paramName);
                    // keeps its name but becomes a global (?)
                    l2gMap.put(origParam, paramName);
                    ASTNode paramFormulaNode = getFormulaFromExpression(kinParamExprs[j]);
                    AssignmentRule sbmlParamAssignmentRule = sbmlModel.createAssignmentRule();
                    sbmlParamAssignmentRule.setVariable(paramName);
                    sbmlParamAssignmentRule.setMath(paramFormulaNode);
                    org.sbml.jsbml.Parameter sbmlKinParam = sbmlModel.createParameter();
                    sbmlKinParam.setId(paramName);
                    if (!vcKineticsParams[j].getUnitDefinition().isTBD()) {
                        sbmlKinParam.setUnits(getOrCreateSBMLUnit(vcKineticsParams[j].getUnitDefinition()));
                    }
                    // Since the parameter is being specified by a Rule, its 'constant' field shoud be set to 'false' (default - true).
                    sbmlKinParam.setConstant(false);
                }
            }
            // end for (j) - fifth pass
            // After making all necessary adjustments to the rate expression, now set the sbmlKLaw.
            final ASTNode exprFormulaNode;
            if (lumpedRateExpr != null) {
                exprFormulaNode = getFormulaFromExpression(lumpedRateExpr);
            } else {
                if (bSpatial) {
                    exprFormulaNode = getFormulaFromExpression(localRateExpr);
                } else {
                    exprFormulaNode = getFormulaFromExpression(Expression.mult(localRateExpr, new Expression(vcReactionStep.getStructure().getName())));
                }
            }
            sbmlKLaw.setMath(exprFormulaNode);
        } catch (cbit.vcell.parser.ExpressionException e) {
            e.printStackTrace(System.out);
            throw new RuntimeException("Error getting value of parameter : " + e.getMessage());
        }
        // Add kineticLaw to sbmlReaction - not needed now, since we use sbmlRxn.createKLaw() ??
        // sbmlReaction.setKineticLaw(sbmlKLaw);
        // Add reactants, products, modifiers
        // Simple reactions have catalysts, fluxes have 'flux'
        cbit.vcell.model.ReactionParticipant[] rxnParticipants = vcReactionStep.getReactionParticipants();
        for (ReactionParticipant rxnParticpant : rxnParticipants) {
            SimpleSpeciesReference ssr = null;
            SpeciesReference sr = null;
            // to get unique ID when the same species is both a reactant and a product
            String rolePostfix = "";
            if (rxnParticpant instanceof cbit.vcell.model.Reactant) {
                rolePostfix = "r";
                ssr = sr = sbmlReaction.createReactant();
            } else if (rxnParticpant instanceof cbit.vcell.model.Product) {
                rolePostfix = "p";
                ssr = sr = sbmlReaction.createProduct();
            }
            if (rxnParticpant instanceof cbit.vcell.model.Catalyst) {
                rolePostfix = "c";
                ssr = sbmlReaction.createModifier();
            }
            if (ssr != null) {
                ssr.setSpecies(rxnParticpant.getSpeciesContext().getName());
            }
            if (sr != null) {
                sr.setStoichiometry(Double.parseDouble(Integer.toString(rxnParticpant.getStoichiometry())));
                String modelUniqueName = vcReactionStep.getName() + '_' + rxnParticpant.getName() + rolePostfix;
                sr.setId(TokenMangler.mangleToSName(modelUniqueName));
                // SBML-REVIEW
                sr.setConstant(true);
            // int rcode = sr.appendNotes("<
            // we know that in VCell we can't override stoichiometry anywhere, below is no longer questionable
            // try {
            // SBMLHelper.addNote(sr, "VCELL guess: how do we know if reaction is constant?");
            // } catch (Exception e) {
            // e.printStackTrace();
            // }
            }
        }
        sbmlReaction.setFast(vcReactionSpecs[i].isFast());
        // this attribute is mandatory for L3, optional for L2. So explicitly setting value.
        sbmlReaction.setReversible(true);
        if (bSpatial) {
            // set compartment for reaction if spatial
            sbmlReaction.setCompartment(vcReactionStep.getStructure().getName());
            // CORE  HAS ALT MATH true
            // set the "isLocal" attribute = true (in 'spatial' namespace) for each species
            SpatialReactionPlugin srplugin = (SpatialReactionPlugin) sbmlReaction.getPlugin(SBMLUtils.SBML_SPATIAL_NS_PREFIX);
            srplugin.setIsLocal(vcRxnKinetics instanceof DistributedKinetics);
        }
    }
}
Also used : MembraneMapping(cbit.vcell.mapping.MembraneMapping) LumpedKinetics(cbit.vcell.model.LumpedKinetics) Element(org.jdom.Element) StructureMapping(cbit.vcell.mapping.StructureMapping) SimpleSpeciesReference(org.sbml.jsbml.SimpleSpeciesReference) KineticsParameter(cbit.vcell.model.Kinetics.KineticsParameter) SpeciesReference(org.sbml.jsbml.SpeciesReference) SimpleSpeciesReference(org.sbml.jsbml.SimpleSpeciesReference) ASTNode(org.sbml.jsbml.ASTNode) VCUnitDefinition(cbit.vcell.units.VCUnitDefinition) UnitDefinition(org.sbml.jsbml.UnitDefinition) Pair(org.vcell.util.Pair) DistributedKinetics(cbit.vcell.model.DistributedKinetics) SpatialReactionPlugin(org.sbml.jsbml.ext.spatial.SpatialReactionPlugin) ReactionSpec(cbit.vcell.mapping.ReactionSpec) AssignmentRule(org.sbml.jsbml.AssignmentRule) ExpressionException(cbit.vcell.parser.ExpressionException) InteriorPoint(org.sbml.jsbml.ext.spatial.InteriorPoint) VCUnitDefinition(cbit.vcell.units.VCUnitDefinition) Expression(cbit.vcell.parser.Expression) ReactionStep(cbit.vcell.model.ReactionStep) Kinetics(cbit.vcell.model.Kinetics) DistributedKinetics(cbit.vcell.model.DistributedKinetics) LumpedKinetics(cbit.vcell.model.LumpedKinetics) ReactionParticipant(cbit.vcell.model.ReactionParticipant)

Example 9 with ASTNode

use of org.sbml.jsbml.ASTNode in project vcell by virtualcell.

the class SBMLExporter method addRateRules.

/**
 * Export rate rules
 */
protected void addRateRules() {
    RateRule[] vcRateRules = getSelectedSimContext().getRateRules();
    if (vcRateRules != null) {
        for (RateRule vcRateRule : vcRateRules) {
            // set name
            org.sbml.jsbml.RateRule sbmlRateRule = sbmlModel.createRateRule();
            sbmlRateRule.setId(vcRateRule.getName());
            // set rate rule variable
            sbmlRateRule.setVariable(vcRateRule.getRateRuleVar().getName());
            // set rate rule math/expression
            Expression rateRuleExpr = vcRateRule.getRateRuleExpression();
            ASTNode math = getFormulaFromExpression(rateRuleExpr);
            sbmlRateRule.setMath(math);
        // set unit?? Same as rate rule var (symbolTableEntry) unit?
        }
    }
}
Also used : Expression(cbit.vcell.parser.Expression) ASTNode(org.sbml.jsbml.ASTNode) RateRule(cbit.vcell.mapping.RateRule)

Example 10 with ASTNode

use of org.sbml.jsbml.ASTNode in project vcell by virtualcell.

the class MathModel_SBMLExporter method getSBMLString.

/**
 * Insert the method's description here.
 * Creation date: (4/11/2006 11:38:26 AM)
 * @return org.sbml.libsbml.Model
 * @param mathModel cbit.vcell.mathmodel.MathModel
 * @throws XMLStreamException
 * @throws SBMLException
 */
public static String getSBMLString(cbit.vcell.mathmodel.MathModel mathModel, long level, long version) throws cbit.vcell.parser.ExpressionException, java.io.IOException, SBMLException, XMLStreamException {
    if (mathModel.getMathDescription().isSpatial()) {
        throw new RuntimeException("spatial models export to SBML not supported");
    }
    if (mathModel.getMathDescription().hasFastSystems()) {
        throw new RuntimeException("math models with fast systems cannot be exported to SBML");
    }
    if (mathModel.getMathDescription().isNonSpatialStoch()) {
        throw new RuntimeException("stochastic math models cannot be exported to SBML");
    }
    if (!mathModel.getMathDescription().isValid()) {
        throw new RuntimeException("math model has an invalid Math Description, cannot export to SBML");
    }
    String dummyID = "ID_0";
    String compartmentId = "compartment";
    SBMLDocument sbmlDocument = new SBMLDocument((int) level, (int) version);
    Model sbmlModel = sbmlDocument.createModel();
    sbmlModel.setId("MathModel_" + TokenMangler.mangleToSName(mathModel.getName()));
    if (mathModel.getMathDescription().isSpatial()) {
        addGeometry(sbmlModel, mathModel);
    }
    Compartment compartment = sbmlModel.createCompartment();
    compartment.setId(compartmentId);
    // ------ For spatial SBML when implemented -----
    // if (vcMathModel.getMathDescription().isSpatial()){
    // // for spatial model, compartment(s) created in addGeometry(), based on number of subVolumes/surfaceClasses.
    // addGeometry();
    // } else {
    // // for non-spatial mathmodel, only 1 compartment; create it here.
    // String compartmentId = "compartment";
    // org.sbml.libsbml.Compartment compartment = sbmlModel.createCompartment();
    // compartment.setId(compartmentId);
    // }
    MathDescription mathDesc = mathModel.getMathDescription();
    Enumeration<Variable> enumVars = mathDesc.getVariables();
    while (enumVars.hasMoreElements()) {
        Variable vcVar = (Variable) enumVars.nextElement();
        // 
        if (vcVar instanceof cbit.vcell.math.VolVariable) {
        // 
        // skip for now, define later when defining ODEEquations.
        // 
        // org.sbml.libsbml.Species species = model.createSpecies();
        // species.setId(vcVar.getName());
        // species.setCompartment(compartmentId);
        } else if (vcVar instanceof cbit.vcell.math.Constant && ((cbit.vcell.math.Constant) vcVar).getExpression().isNumeric()) {
            Parameter param = sbmlModel.createParameter();
            param.setId(TokenMangler.mangleToSName(vcVar.getName()));
            param.setConstant(true);
            param.setValue(vcVar.getExpression().evaluateConstant());
        } else if (vcVar instanceof cbit.vcell.math.Constant || vcVar instanceof cbit.vcell.math.Function) {
            Parameter param = sbmlModel.createParameter();
            param.setId(TokenMangler.mangleToSName(vcVar.getName()));
            param.setConstant(false);
            // 
            // Function or Constant with expressions - create assignment rule and add to model.
            // 
            ASTNode mathNode = getFormulaFromExpression(vcVar.getExpression(), MathType.REAL);
            AssignmentRule assignmentRule = sbmlModel.createAssignmentRule();
            dummyID = TokenMangler.getNextEnumeratedToken(dummyID);
            assignmentRule.setId(dummyID);
            assignmentRule.setVariable(TokenMangler.mangleToSName(vcVar.getName()));
            assignmentRule.setMath(mathNode);
        // Create a parameter for this function/non-numeric constant, set its value to be 'not-constant',
        // add to model.
        }
    }
    cbit.vcell.math.CompartmentSubDomain subDomain = (cbit.vcell.math.CompartmentSubDomain) mathDesc.getSubDomains().nextElement();
    // System.out.println(model.toSBML());
    Enumeration<Equation> enumEqu = subDomain.getEquations();
    while (enumEqu.hasMoreElements()) {
        cbit.vcell.math.Equation equ = (cbit.vcell.math.Equation) enumEqu.nextElement();
        if (equ instanceof cbit.vcell.math.OdeEquation) {
            // For ODE equations, add the ode variable as a parameter, add rate as a rate rule and init condition as an initial assignment rule.
            Parameter param = sbmlModel.createParameter();
            param.setId(TokenMangler.mangleToSName(equ.getVariable().getName()));
            param.setConstant(false);
            // try to obtain the constant to which the init expression evaluates.
            RateRule rateRule = sbmlModel.createRateRule();
            rateRule.setVariable(TokenMangler.mangleToSName(equ.getVariable().getName()));
            rateRule.setMath(getFormulaFromExpression(equ.getRateExpression(), MathType.REAL));
            InitialAssignment initialAssignment = sbmlModel.createInitialAssignment();
            dummyID = TokenMangler.getNextEnumeratedToken(dummyID);
            initialAssignment.setId(dummyID);
            initialAssignment.setMath(getFormulaFromExpression(equ.getInitialExpression(), MathType.REAL));
            initialAssignment.setVariable(TokenMangler.mangleToSName(equ.getVariable().getName()));
        } else {
            throw new RuntimeException("equation type " + equ.getClass().getName() + " not supported");
        }
    }
    Iterator<Event> vcellEvents = mathDesc.getEvents();
    while (vcellEvents.hasNext()) {
        Event vcellEvent = vcellEvents.next();
        addSbmlEvent(sbmlModel, vcellEvent);
    }
    System.out.println(new SBMLWriter().writeSBMLToString(sbmlDocument));
    // validate the sbml document
    sbmlDocument.setConsistencyChecks(CHECK_CATEGORY.GENERAL_CONSISTENCY, true);
    sbmlDocument.setConsistencyChecks(CHECK_CATEGORY.IDENTIFIER_CONSISTENCY, true);
    sbmlDocument.setConsistencyChecks(CHECK_CATEGORY.MATHML_CONSISTENCY, true);
    sbmlDocument.setConsistencyChecks(CHECK_CATEGORY.MODELING_PRACTICE, false);
    sbmlDocument.setConsistencyChecks(CHECK_CATEGORY.OVERDETERMINED_MODEL, true);
    sbmlDocument.setConsistencyChecks(CHECK_CATEGORY.SBO_CONSISTENCY, false);
    sbmlDocument.setConsistencyChecks(CHECK_CATEGORY.UNITS_CONSISTENCY, false);
    sbmlDocument.checkConsistency();
    // sbmlDocument.checkConsistencyOffline();
    long internalErrCount = sbmlDocument.getNumErrors();
    if (internalErrCount > 0) {
        StringBuffer sbmlErrbuf = new StringBuffer();
        for (int i = 0; i < internalErrCount; i++) {
            SBMLError sbmlErr = sbmlDocument.getError(i);
            if (sbmlErr.isError() || sbmlErr.isFatal()) {
                sbmlErrbuf.append(sbmlErr.getCategory() + " :: " + sbmlErr.getSeverity() + " :: " + sbmlErr.getMessage() + "\n");
            }
        }
        if (sbmlErrbuf.length() > 0) {
            throw new RuntimeException("SBML Internal consistency checks failed: \n" + sbmlErrbuf.toString());
        }
    }
    sbmlDocument.setConsistencyChecks(CHECK_CATEGORY.GENERAL_CONSISTENCY, true);
    sbmlDocument.setConsistencyChecks(CHECK_CATEGORY.IDENTIFIER_CONSISTENCY, true);
    sbmlDocument.setConsistencyChecks(CHECK_CATEGORY.UNITS_CONSISTENCY, false);
    sbmlDocument.setConsistencyChecks(CHECK_CATEGORY.MATHML_CONSISTENCY, true);
    sbmlDocument.setConsistencyChecks(CHECK_CATEGORY.SBO_CONSISTENCY, false);
    sbmlDocument.setConsistencyChecks(CHECK_CATEGORY.OVERDETERMINED_MODEL, true);
    sbmlDocument.setConsistencyChecks(CHECK_CATEGORY.MODELING_PRACTICE, false);
    sbmlDocument.checkConsistency();
    // sbmlDocument.checkConsistencyOffline();
    long errCount = sbmlDocument.getNumErrors();
    if (errCount > 0) {
        StringBuffer sbmlErrbuf = new StringBuffer();
        for (int i = 0; i < errCount; i++) {
            SBMLError sbmlErr = sbmlDocument.getError(i);
            if (sbmlErr.isError() || sbmlErr.isFatal()) {
                sbmlErrbuf.append(sbmlErr.getCategory() + " :: " + sbmlErr.getSeverity() + " :: " + sbmlErr.getMessage() + "\n");
            }
        }
        if (sbmlErrbuf.length() > 0) {
            throw new RuntimeException("SBML validation failed: \n" + sbmlErrbuf.toString());
        }
    }
    // end of validation
    // start writing
    SBMLWriter sbmlWriter = new SBMLWriter();
    String sbmlStr = sbmlWriter.writeSBMLToString(sbmlDocument);
    // Error check - use libSBML's document.printError to print to outputstream
    System.out.println("\n\nSBML Export Error Report");
    sbmlDocument.printErrors(System.out);
    return sbmlStr;
}
Also used : ReservedVariable(cbit.vcell.math.ReservedVariable) Variable(cbit.vcell.math.Variable) SBMLDocument(org.sbml.jsbml.SBMLDocument) MathDescription(cbit.vcell.math.MathDescription) Compartment(org.sbml.jsbml.Compartment) SBMLError(org.sbml.jsbml.SBMLError) ASTNode(org.sbml.jsbml.ASTNode) RateRule(org.sbml.jsbml.RateRule) AssignmentRule(org.sbml.jsbml.AssignmentRule) Equation(cbit.vcell.math.Equation) InteriorPoint(org.sbml.jsbml.ext.spatial.InteriorPoint) InitialAssignment(org.sbml.jsbml.InitialAssignment) SBMLWriter(org.sbml.jsbml.SBMLWriter) Model(org.sbml.jsbml.Model) MathModel(cbit.vcell.mathmodel.MathModel) Parameter(org.sbml.jsbml.Parameter) Event(cbit.vcell.math.Event) Equation(cbit.vcell.math.Equation)

Aggregations

ASTNode (org.sbml.jsbml.ASTNode)21 Expression (cbit.vcell.parser.Expression)17 InteriorPoint (org.sbml.jsbml.ext.spatial.InteriorPoint)13 ExpressionException (cbit.vcell.parser.ExpressionException)11 VCUnitDefinition (cbit.vcell.units.VCUnitDefinition)8 BioModel (cbit.vcell.biomodel.BioModel)7 Model (cbit.vcell.model.Model)7 XMLStreamException (javax.xml.stream.XMLStreamException)7 AssignmentRule (org.sbml.jsbml.AssignmentRule)7 SBMLException (org.sbml.jsbml.SBMLException)7 ModelParameter (cbit.vcell.model.Model.ModelParameter)6 PropertyVetoException (java.beans.PropertyVetoException)6 StructureMapping (cbit.vcell.mapping.StructureMapping)5 SpeciesContext (cbit.vcell.model.SpeciesContext)5 XmlParseException (cbit.vcell.xml.XmlParseException)5 IOException (java.io.IOException)5 Compartment (org.sbml.jsbml.Compartment)5 Kinetics (cbit.vcell.model.Kinetics)4 KineticsParameter (cbit.vcell.model.Kinetics.KineticsParameter)4 ModelPropertyVetoException (cbit.vcell.model.ModelPropertyVetoException)4