Search in sources :

Example 1 with RateRule

use of org.sbml.jsbml.RateRule 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)

Example 2 with RateRule

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

the class SBMLImporter method addRateRules.

/**
 * addRateRules : Adds Rate Rules from the SBML document Rate rules are
 * allowed (initial concentration of species; parameter definitions, etc.
 * @throws XMLStreamException
 * @throws SBMLException
 */
protected void addRateRules() throws ExpressionException, SBMLException, XMLStreamException {
    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 RateRule) {
            // Get the rate rule and store it in the hashMap, and create
            // VCell rateRule.
            RateRule sbmlRateRule = (RateRule) rule;
            // rate rule name
            String rateruleName = sbmlRateRule.getId();
            if (rateruleName == null || rateruleName.length() == 0) {
                rateruleName = TokenMangler.mangleToSName(sbmlRateRule.getName());
                // from vcBioModel.getSimulationContext(0).
                if (rateruleName == null || rateruleName.length() == 0) {
                    rateruleName = vcBioModel.getSimulationContext(0).getFreeRateRuleName();
                }
            }
            // rate rule variable
            String varName = sbmlRateRule.getVariable();
            SymbolTableEntry rateRuleVar = vcBioModel.getSimulationContext(0).getEntry(varName);
            if (rateRuleVar instanceof Structure) {
                throw new SBMLImportException("Compartment '" + rateRuleVar.getName() + "' has a rate rule : not allowed in VCell at this time.");
            }
            try {
                if (rateRuleVar != null) {
                    Expression vcRateRuleExpr = getExpressionFromFormula(sbmlRateRule.getMath());
                    cbit.vcell.mapping.RateRule vcRateRule = new cbit.vcell.mapping.RateRule(rateruleName, rateRuleVar, vcRateRuleExpr, vcBioModel.getSimulationContext(0));
                    vcRateRule.bind();
                    rateRulesHash.put(rateRuleVar.getName(), vcRateRuleExpr);
                    vcBioModel.getSimulationContext(0).addRateRule(vcRateRule);
                }
            } catch (PropertyVetoException e) {
                e.printStackTrace(System.out);
                throw new SBMLImportException("Unable to create and add rate rule to VC model : " + e.getMessage());
            }
        }
    // end if - RateRule
    }
// end - for i : rules
}
Also used : InteriorPoint(org.sbml.jsbml.ext.spatial.InteriorPoint) PropertyVetoException(java.beans.PropertyVetoException) ModelPropertyVetoException(cbit.vcell.model.ModelPropertyVetoException) SymbolTableEntry(cbit.vcell.parser.SymbolTableEntry) Expression(cbit.vcell.parser.Expression) ListOf(org.sbml.jsbml.ListOf) RateRule(org.sbml.jsbml.RateRule) AlgebraicRule(org.sbml.jsbml.AlgebraicRule) Rule(org.sbml.jsbml.Rule) AssignmentRule(org.sbml.jsbml.AssignmentRule) RateRule(org.sbml.jsbml.RateRule) Structure(cbit.vcell.model.Structure)

Example 3 with RateRule

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

the class SBMLImporter method readRateRules.

// ------------------------------------------------------------------------------------------------------------------------------------------
private void readRateRules(Map<String, String> sbmlToVcNameMap) throws ExpressionException, SBMLException, XMLStreamException {
    if (sbmlModel == null) {
        throw new SBMLImportException("SBML model is NULL");
    }
    ListOf<Rule> listofRules = sbmlModel.getListOfRules();
    if (listofRules == null) {
        System.out.println("No Rules specified");
        return;
    }
    rateRulesHash.clear();
    // when we import from SBML there can't be more than one sim context
    SimulationContext simContext = vcBioModel.getSimulationContext(0);
    boolean bRateRule = false;
    for (int i = 0; i < sbmlModel.getNumRules(); i++) {
        Rule rule = (org.sbml.jsbml.Rule) listofRules.get(i);
        if (rule instanceof RateRule) {
            bRateRule = true;
            // Get the rate rule and store it in the hashMap, and create VCell rateRule.
            RateRule sbmlRateRule = (RateRule) rule;
            // --------------------- rate rule variable
            String sbmlVarName = sbmlRateRule.getVariable();
            String vcSpeciesName = sbmlVarName;
            if (sbmlToVcNameMap.get(sbmlVarName) != null) {
                vcSpeciesName = sbmlToVcNameMap.get(sbmlVarName);
            }
            SymbolTableEntry ste = simContext.getEntry(vcSpeciesName);
            if (ste == null) {
                // TODO: this should never happen; verify !!!
                throw new RuntimeException("No SymbolTableEntry for SBML variable " + sbmlVarName);
            }
            Expression sbmlRateRuleExpr = getExpressionFromFormula(sbmlRateRule.getMath());
            // if the map is populated, we know for sure that it's non spatial model
            for (Map.Entry<String, String> entry : sbmlToVcNameMap.entrySet()) {
                String sbmlName = entry.getKey();
                String vcName = entry.getValue();
                sbmlRateRuleExpr.substituteInPlace(new Expression(sbmlName), new Expression(vcName));
            }
            Expression vcRateRuleExpr = new Expression(sbmlRateRuleExpr);
            rateRulesHash.put(ste.getName(), vcRateRuleExpr);
        }
    }
// if(bRateRule) {
// localIssueList.add(new Issue(vcBioModel, issueContext, IssueCategory.SBMLImport_RestrictedFeature,
// "RateRules are supported at this time with restrictions. Please check the generated math for consistency.", Issue.Severity.WARNING));
// }
}
Also used : SimulationContext(cbit.vcell.mapping.SimulationContext) InteriorPoint(org.sbml.jsbml.ext.spatial.InteriorPoint) SymbolTableEntry(cbit.vcell.parser.SymbolTableEntry) Expression(cbit.vcell.parser.Expression) RateRule(org.sbml.jsbml.RateRule) AlgebraicRule(org.sbml.jsbml.AlgebraicRule) Rule(org.sbml.jsbml.Rule) AssignmentRule(org.sbml.jsbml.AssignmentRule) RateRule(org.sbml.jsbml.RateRule) Map(java.util.Map) HashMap(java.util.HashMap)

Example 4 with RateRule

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

the class SBMLImporter method finalizeRateRules.

// at the very end, create the RateRules and add them to the simulation context
private void finalizeRateRules() {
    SimulationContext simContext = vcBioModel.getSimulationContext(0);
    Model vcModel = simContext.getModel();
    GeometryContext gc = simContext.getGeometryContext();
    boolean foundConstStructureSize = false;
    for (Map.Entry<String, Expression> entry : rateRulesHash.entrySet()) {
        String vcVariableName = entry.getKey();
        Expression vcExpression = entry.getValue();
        SymbolTableEntry ste = simContext.getEntry(vcVariableName);
        try {
            // --------------------- rate rule expression
            String vcRuleName = simContext.getFreeRateRuleName();
            cbit.vcell.mapping.RateRule vcRule = new cbit.vcell.mapping.RateRule(vcRuleName, ste, vcExpression, simContext);
            vcRule.bind();
            if (ste instanceof Structure.StructureSize) {
                double constantSize;
                try {
                    constantSize = vcExpression.evaluateConstant();
                } catch (ExpressionException e1) {
                    throw new SBMLImportException("Structure '" + ste.getName() + "' is used as a non-constant rate rule variable: not allowed in VCell at this time.");
                }
                // it is a constant, so we don't even make a rule, we just override the structure size in the geometry
                Structure.StructureSize ss = (Structure.StructureSize) ste;
                Structure struct = ss.getStructure();
                StructureMapping.StructureMappingParameter mapping = gc.getStructureMapping(struct).getSizeParameter();
                Expression constExpression = new Expression(constantSize);
                mapping.setExpression(constExpression);
                foundConstStructureSize = true;
            } else {
                simContext.addRateRule(vcRule);
            }
        } catch (PropertyVetoException | ExpressionException e) {
            e.printStackTrace(System.out);
            throw new SBMLImportException("Unable to create and add rate rule to VC model : " + e.getMessage());
        }
    }
    if (foundConstStructureSize) {
        try {
            StructureSizeSolver.updateRelativeStructureSizes(simContext);
            String msg = "One or more RateRule variables of StructureSize type evaluated to constant and were used as initial assignment for the Feature (Structure)";
            localIssueList.add(new Issue(vcModel, issueContext, IssueCategory.SBMLImport_RestrictedFeature, msg, Issue.Severity.WARNING));
        } catch (Exception e) {
            e.printStackTrace(System.out);
            String msg = "Error initializing a Feature from a RateRule StructureSize variable. ";
            throw new SBMLImportException(msg + e.getMessage(), e);
        }
    }
}
Also used : Issue(org.vcell.util.Issue) StructureMapping(cbit.vcell.mapping.StructureMapping) ExpressionException(cbit.vcell.parser.ExpressionException) SymbolTableEntry(cbit.vcell.parser.SymbolTableEntry) RateRule(org.sbml.jsbml.RateRule) GeometryContext(cbit.vcell.mapping.GeometryContext) Structure(cbit.vcell.model.Structure) SimulationContext(cbit.vcell.mapping.SimulationContext) XMLStreamException(javax.xml.stream.XMLStreamException) SbmlException(org.vcell.sbml.SbmlException) XmlParseException(cbit.vcell.xml.XmlParseException) IOException(java.io.IOException) PropertyVetoException(java.beans.PropertyVetoException) DivideByZeroException(cbit.vcell.parser.DivideByZeroException) SBMLException(org.sbml.jsbml.SBMLException) ExpressionBindingException(cbit.vcell.parser.ExpressionBindingException) ModelPropertyVetoException(cbit.vcell.model.ModelPropertyVetoException) ExpressionException(cbit.vcell.parser.ExpressionException) PropertyVetoException(java.beans.PropertyVetoException) ModelPropertyVetoException(cbit.vcell.model.ModelPropertyVetoException) Expression(cbit.vcell.parser.Expression) Model(cbit.vcell.model.Model) BioModel(cbit.vcell.biomodel.BioModel) Map(java.util.Map) HashMap(java.util.HashMap)

Aggregations

RateRule (org.sbml.jsbml.RateRule)4 Expression (cbit.vcell.parser.Expression)3 SymbolTableEntry (cbit.vcell.parser.SymbolTableEntry)3 AssignmentRule (org.sbml.jsbml.AssignmentRule)3 InteriorPoint (org.sbml.jsbml.ext.spatial.InteriorPoint)3 SimulationContext (cbit.vcell.mapping.SimulationContext)2 ModelPropertyVetoException (cbit.vcell.model.ModelPropertyVetoException)2 Structure (cbit.vcell.model.Structure)2 PropertyVetoException (java.beans.PropertyVetoException)2 HashMap (java.util.HashMap)2 Map (java.util.Map)2 AlgebraicRule (org.sbml.jsbml.AlgebraicRule)2 Rule (org.sbml.jsbml.Rule)2 BioModel (cbit.vcell.biomodel.BioModel)1 GeometryContext (cbit.vcell.mapping.GeometryContext)1 StructureMapping (cbit.vcell.mapping.StructureMapping)1 Equation (cbit.vcell.math.Equation)1 Event (cbit.vcell.math.Event)1 MathDescription (cbit.vcell.math.MathDescription)1 ReservedVariable (cbit.vcell.math.ReservedVariable)1