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;
}
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
}
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));
// }
}
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);
}
}
}
Aggregations