use of org.sbml.jsbml.AssignmentRule 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.isEnabledFor(Level.WARN)) {
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);
}
}
use of org.sbml.jsbml.AssignmentRule 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);
// 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;
if (rxnParticpant instanceof cbit.vcell.model.Reactant) {
ssr = sr = sbmlReaction.createReactant();
} else if (rxnParticpant instanceof cbit.vcell.model.Product) {
ssr = sr = sbmlReaction.createProduct();
}
if (rxnParticpant instanceof cbit.vcell.model.Catalyst) {
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();
sr.setId(TokenMangler.mangleToSName(modelUniqueName));
// SBML-REVIEW
sr.setConstant(true);
// int rcode = sr.appendNotes("<
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);
}
}
}
use of org.sbml.jsbml.AssignmentRule 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
}
use of org.sbml.jsbml.AssignmentRule 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.AssignmentRule in project vcell by virtualcell.
the class SBMLExporter method addSpecies.
/**
* addSpecies comment.
* @throws XMLStreamException
* @throws SbmlException
*/
protected void addSpecies() throws XMLStreamException, SbmlException {
Model vcModel = vcBioModel.getModel();
SpeciesContext[] vcSpeciesContexts = vcModel.getSpeciesContexts();
for (int i = 0; i < vcSpeciesContexts.length; i++) {
org.sbml.jsbml.Species sbmlSpecies = sbmlModel.createSpecies();
sbmlSpecies.setId(vcSpeciesContexts[i].getName());
// Assuming that at this point, the compartment(s) for the model are already filled in.
Compartment compartment = sbmlModel.getCompartment(TokenMangler.mangleToSName(vcSpeciesContexts[i].getStructure().getName()));
if (compartment != null) {
sbmlSpecies.setCompartment(compartment.getId());
}
// 'hasSubstanceOnly' field will be 'false', since VC deals only with initial concentrations and not initial amounts.
sbmlSpecies.setHasOnlySubstanceUnits(false);
// Get (and set) the initial concentration value
if (getSelectedSimContext() == null) {
throw new RuntimeException("No simcontext (application) specified; Cannot proceed.");
}
// Get the speciesContextSpec in the simContext corresponding to the 'speciesContext'; and extract its initial concentration value.
SpeciesContextSpec vcSpeciesContextsSpec = getSelectedSimContext().getReactionContext().getSpeciesContextSpec(vcSpeciesContexts[i]);
// we need to convert concentration from uM -> molecules/um3; this can be achieved by dividing by KMOLE.
try {
sbmlSpecies.setInitialConcentration(vcSpeciesContextsSpec.getInitialConditionParameter().getExpression().evaluateConstant());
} catch (cbit.vcell.parser.ExpressionException e) {
// If exporting to L2V3, if species concentration is not an expr with x, y, z or other species, add as InitialAssignment, else complain.
if (vcSpeciesContextsSpec.getInitialConditionParameter().getExpression() != null) {
Expression initConcExpr = vcSpeciesContextsSpec.getInitialConditionParameter().getExpression();
if ((sbmlLevel == 2 && sbmlVersion >= 3) || (sbmlLevel > 2)) {
// L2V3 and above - add expression as init assignment
ASTNode initAssgnMathNode = getFormulaFromExpression(initConcExpr);
InitialAssignment initAssignment = sbmlModel.createInitialAssignment();
initAssignment.setSymbol(vcSpeciesContexts[i].getName());
initAssignment.setMath(initAssgnMathNode);
} else {
// L2V1 (or L1V2 also??)
// L2V1 (and L1V2?) and species is 'fixed' (constant), and not fn of x,y,z, other sp, add expr as assgn rule
ASTNode assgnRuleMathNode = getFormulaFromExpression(initConcExpr);
AssignmentRule assgnRule = sbmlModel.createAssignmentRule();
assgnRule.setVariable(vcSpeciesContexts[i].getName());
assgnRule.setMath(assgnRuleMathNode);
}
}
}
// Get (and set) the boundary condition value
boolean bBoundaryCondition = getBoundaryCondition(vcSpeciesContexts[i]);
sbmlSpecies.setBoundaryCondition(bBoundaryCondition);
// mandatory for L3, optional for L2
sbmlSpecies.setConstant(false);
// set species substance units as 'molecules' - same as defined in the model; irrespective of it is in surface or volume.
UnitDefinition unitDefn = getOrCreateSBMLUnit(sbmlExportSpec.getSubstanceUnits());
sbmlSpecies.setSubstanceUnits(unitDefn);
// need to do the following if exporting to SBML spatial
if (bSpatial) {
// Required for setting BoundaryConditions : structureMapping for vcSpeciesContext[i] & sbmlGeometry.coordinateComponents
StructureMapping sm = getSelectedSimContext().getGeometryContext().getStructureMapping(vcSpeciesContexts[i].getStructure());
SpatialModelPlugin mplugin = (SpatialModelPlugin) sbmlModel.getPlugin(SBMLUtils.SBML_SPATIAL_NS_PREFIX);
org.sbml.jsbml.ext.spatial.Geometry sbmlGeometry = mplugin.getGeometry();
CoordinateComponent ccX = sbmlGeometry.getListOfCoordinateComponents().get(vcModel.getX().getName());
CoordinateComponent ccY = sbmlGeometry.getListOfCoordinateComponents().get(vcModel.getY().getName());
CoordinateComponent ccZ = sbmlGeometry.getListOfCoordinateComponents().get(vcModel.getZ().getName());
// add diffusion, advection, boundary condition parameters for species, if they exist
Parameter[] scsParams = vcSpeciesContextsSpec.getParameters();
if (scsParams != null) {
for (int j = 0; j < scsParams.length; j++) {
if (scsParams[j] != null) {
SpeciesContextSpecParameter scsParam = (SpeciesContextSpecParameter) scsParams[j];
// no need to add parameters in SBML for init conc or init count
int role = scsParam.getRole();
switch(role) {
case SpeciesContextSpec.ROLE_BoundaryValueXm:
{
break;
}
case SpeciesContextSpec.ROLE_BoundaryValueXp:
{
break;
}
case SpeciesContextSpec.ROLE_BoundaryValueYm:
{
break;
}
case SpeciesContextSpec.ROLE_BoundaryValueYp:
{
break;
}
case SpeciesContextSpec.ROLE_BoundaryValueZm:
{
break;
}
case SpeciesContextSpec.ROLE_BoundaryValueZp:
{
break;
}
case SpeciesContextSpec.ROLE_DiffusionRate:
{
break;
}
case SpeciesContextSpec.ROLE_InitialConcentration:
{
// done elsewhere??
continue;
// break;
}
case SpeciesContextSpec.ROLE_InitialCount:
{
// done elsewhere??
continue;
// break;
}
case SpeciesContextSpec.ROLE_VelocityX:
{
break;
}
case SpeciesContextSpec.ROLE_VelocityY:
{
break;
}
case SpeciesContextSpec.ROLE_VelocityZ:
{
break;
}
default:
{
throw new RuntimeException("SpeciesContext Specification parameter with role " + SpeciesContextSpec.RoleNames[role] + " not yet supported for SBML export");
}
}
// if diffusion is 0 && vel terms are not specified, boundary condition not present
if (vcSpeciesContextsSpec.isAdvecting() || vcSpeciesContextsSpec.isDiffusing()) {
Expression diffExpr = vcSpeciesContextsSpec.getDiffusionParameter().getExpression();
boolean bDiffExprNull = (diffExpr == null);
boolean bDiffExprIsZero = false;
if (!bDiffExprNull && diffExpr.isNumeric()) {
try {
bDiffExprIsZero = (diffExpr.evaluateConstant() == 0.0);
} catch (Exception e) {
e.printStackTrace(System.out);
throw new RuntimeException("Unable to evalute numeric value of diffusion parameter for speciesContext '" + vcSpeciesContexts[i] + "'.");
}
}
boolean bDiffusionZero = (bDiffExprNull || bDiffExprIsZero);
Expression velX_Expr = vcSpeciesContextsSpec.getVelocityXParameter().getExpression();
SpatialQuantity[] velX_Quantities = vcSpeciesContextsSpec.getVelocityQuantities(QuantityComponent.X);
boolean bVelX_ExprIsNull = (velX_Expr == null && velX_Quantities.length == 0);
Expression velY_Expr = vcSpeciesContextsSpec.getVelocityYParameter().getExpression();
SpatialQuantity[] velY_Quantities = vcSpeciesContextsSpec.getVelocityQuantities(QuantityComponent.Y);
boolean bVelY_ExprIsNull = (velY_Expr == null && velY_Quantities.length == 0);
Expression velZ_Expr = vcSpeciesContextsSpec.getVelocityZParameter().getExpression();
SpatialQuantity[] velZ_Quantities = vcSpeciesContextsSpec.getVelocityQuantities(QuantityComponent.Z);
boolean bVelZ_ExprIsNull = (velZ_Expr == null && velZ_Quantities.length == 0);
boolean bAdvectionNull = (bVelX_ExprIsNull && bVelY_ExprIsNull && bVelZ_ExprIsNull);
if (bDiffusionZero && bAdvectionNull) {
continue;
}
}
// for example, if scsParam is BC_Zm and if coordinateComponent 'ccZ' is null, no SBML parameter should be created for BC_Zm
if ((((role == SpeciesContextSpec.ROLE_BoundaryValueXm) || (role == SpeciesContextSpec.ROLE_BoundaryValueXp)) && (ccX == null)) || (((role == SpeciesContextSpec.ROLE_BoundaryValueYm) || (role == SpeciesContextSpec.ROLE_BoundaryValueYp)) && (ccY == null)) || (((role == SpeciesContextSpec.ROLE_BoundaryValueZm) || (role == SpeciesContextSpec.ROLE_BoundaryValueZp)) && (ccZ == null))) {
continue;
}
org.sbml.jsbml.Parameter sbmlParam = createSBMLParamFromSpeciesParam(vcSpeciesContexts[i], (SpeciesContextSpecParameter) scsParams[j]);
if (sbmlParam != null) {
BoundaryConditionType vcBCType_Xm = vcSelectedSimContext.getGeometryContext().getStructureMapping(vcSpeciesContexts[i].getStructure()).getBoundaryConditionTypeXm();
BoundaryConditionType vcBCType_Xp = vcSelectedSimContext.getGeometryContext().getStructureMapping(vcSpeciesContexts[i].getStructure()).getBoundaryConditionTypeXp();
BoundaryConditionType vcBCType_Ym = vcSelectedSimContext.getGeometryContext().getStructureMapping(vcSpeciesContexts[i].getStructure()).getBoundaryConditionTypeYm();
BoundaryConditionType vcBCType_Yp = vcSelectedSimContext.getGeometryContext().getStructureMapping(vcSpeciesContexts[i].getStructure()).getBoundaryConditionTypeYp();
BoundaryConditionType vcBCType_Zm = vcSelectedSimContext.getGeometryContext().getStructureMapping(vcSpeciesContexts[i].getStructure()).getBoundaryConditionTypeZm();
BoundaryConditionType vcBCType_Zp = vcSelectedSimContext.getGeometryContext().getStructureMapping(vcSpeciesContexts[i].getStructure()).getBoundaryConditionTypeZp();
SpatialParameterPlugin spplugin = (SpatialParameterPlugin) sbmlParam.getPlugin(SBMLUtils.SBML_SPATIAL_NS_PREFIX);
if (role == SpeciesContextSpec.ROLE_DiffusionRate) {
// set diffusionCoefficient element in SpatialParameterPlugin for param
DiffusionCoefficient sbmlDiffCoeff = new DiffusionCoefficient();
sbmlDiffCoeff.setVariable(vcSpeciesContexts[i].getName());
sbmlDiffCoeff.setDiffusionKind(DiffusionKind.isotropic);
sbmlDiffCoeff.setSpeciesRef(vcSpeciesContexts[i].getName());
spplugin.setParamType(sbmlDiffCoeff);
}
if ((role == SpeciesContextSpec.ROLE_BoundaryValueXm) && (ccX != null)) {
// set BoundaryCondn Xm element in SpatialParameterPlugin for param
BoundaryCondition sbmlBCXm = new BoundaryCondition();
spplugin.setParamType(sbmlBCXm);
sbmlBCXm.setType(getBoundaryConditionKind(vcBCType_Xm));
sbmlBCXm.setVariable(vcSpeciesContexts[i].getName());
sbmlBCXm.setCoordinateBoundary(ccX.getBoundaryMinimum().getId());
}
if ((role == SpeciesContextSpec.ROLE_BoundaryValueXp) && (ccX != null)) {
// set BoundaryCondn Xp element in SpatialParameterPlugin for param
BoundaryCondition sbmlBCXp = new BoundaryCondition();
spplugin.setParamType(sbmlBCXp);
sbmlBCXp.setType(getBoundaryConditionKind(vcBCType_Xp));
sbmlBCXp.setVariable(vcSpeciesContexts[i].getName());
sbmlBCXp.setType(sm.getBoundaryConditionTypeXp().boundaryTypeStringValue());
sbmlBCXp.setCoordinateBoundary(ccX.getBoundaryMaximum().getId());
}
if ((role == SpeciesContextSpec.ROLE_BoundaryValueYm) && (ccY != null)) {
// set BoundaryCondn Ym element in SpatialParameterPlugin for param
BoundaryCondition sbmlBCYm = new BoundaryCondition();
spplugin.setParamType(sbmlBCYm);
sbmlBCYm.setType(getBoundaryConditionKind(vcBCType_Yp));
sbmlBCYm.setVariable(vcSpeciesContexts[i].getName());
sbmlBCYm.setType(sm.getBoundaryConditionTypeYm().boundaryTypeStringValue());
sbmlBCYm.setCoordinateBoundary(ccY.getBoundaryMinimum().getId());
}
if ((role == SpeciesContextSpec.ROLE_BoundaryValueYp) && (ccY != null)) {
// set BoundaryCondn Yp element in SpatialParameterPlugin for param
BoundaryCondition sbmlBCYp = new BoundaryCondition();
spplugin.setParamType(sbmlBCYp);
sbmlBCYp.setType(getBoundaryConditionKind(vcBCType_Yp));
sbmlBCYp.setVariable(vcSpeciesContexts[i].getName());
sbmlBCYp.setType(sm.getBoundaryConditionTypeYp().boundaryTypeStringValue());
sbmlBCYp.setCoordinateBoundary(ccY.getBoundaryMaximum().getId());
}
if ((role == SpeciesContextSpec.ROLE_BoundaryValueZm) && (ccZ != null)) {
// set BoundaryCondn Zm element in SpatialParameterPlugin for param
BoundaryCondition sbmlBCZm = new BoundaryCondition();
spplugin.setParamType(sbmlBCZm);
sbmlBCZm.setType(getBoundaryConditionKind(vcBCType_Zm));
sbmlBCZm.setVariable(vcSpeciesContexts[i].getName());
sbmlBCZm.setType(sm.getBoundaryConditionTypeZm().boundaryTypeStringValue());
sbmlBCZm.setCoordinateBoundary(ccZ.getBoundaryMinimum().getId());
}
if ((role == SpeciesContextSpec.ROLE_BoundaryValueZp) && (ccZ != null)) {
// set BoundaryCondn Zp element in SpatialParameterPlugin for param
BoundaryCondition sbmlBCZp = new BoundaryCondition();
spplugin.setParamType(sbmlBCZp);
sbmlBCZp.setType(getBoundaryConditionKind(vcBCType_Zp));
sbmlBCZp.setVariable(vcSpeciesContexts[i].getName());
sbmlBCZp.setType(sm.getBoundaryConditionTypeZp().boundaryTypeStringValue());
sbmlBCZp.setCoordinateBoundary(ccZ.getBoundaryMaximum().getId());
}
if (role == SpeciesContextSpec.ROLE_VelocityX) {
// set advectionCoeff X element in SpatialParameterPlugin for param
AdvectionCoefficient sbmlAdvCoeffX = new AdvectionCoefficient();
spplugin.setParamType(sbmlAdvCoeffX);
sbmlAdvCoeffX.setVariable(vcSpeciesContexts[i].getName());
sbmlAdvCoeffX.setCoordinate(CoordinateKind.cartesianX);
}
if (role == SpeciesContextSpec.ROLE_VelocityY) {
// set advectionCoeff Y element in SpatialParameterPlugin for param
AdvectionCoefficient sbmlAdvCoeffY = new AdvectionCoefficient();
spplugin.setParamType(sbmlAdvCoeffY);
sbmlAdvCoeffY.setVariable(vcSpeciesContexts[i].getName());
sbmlAdvCoeffY.setCoordinate(CoordinateKind.cartesianY);
}
if (role == SpeciesContextSpec.ROLE_VelocityZ) {
// set advectionCoeff Z element in SpatialParameterPlugin for param
AdvectionCoefficient sbmlAdvCoeffZ = new AdvectionCoefficient();
spplugin.setParamType(sbmlAdvCoeffZ);
sbmlAdvCoeffZ.setVariable(vcSpeciesContexts[i].getName());
sbmlAdvCoeffZ.setCoordinate(CoordinateKind.cartesianZ);
}
}
// if sbmlParam != null
}
// if scsParams[j] != null
}
// end for scsParams
}
// end scsParams != null
}
// end if (bSpatial)
// Add the common name of species to annotation, and add an annotation element to the species.
// This is required later while trying to read in fluxes ...
// new Element(XMLTags.VCellRelatedInfoTag, sbml_vcml_ns);
Element sbmlImportRelatedElement = null;
// Element speciesElement = new Element(XMLTags.SpeciesTag, sbml_vcml_ns);
// speciesElement.setAttribute(XMLTags.NameAttrTag, TokenMangler.mangleToSName(vcSpeciesContexts[i].getSpecies().getCommonName()));
// sbmlImportRelatedElement.addContent(speciesElement);
// Get RDF annotation for species from SBMLAnnotationUtils
sbmlAnnotationUtil.writeAnnotation(vcSpeciesContexts[i].getSpecies(), sbmlSpecies, sbmlImportRelatedElement);
// Now set notes,
sbmlAnnotationUtil.writeNotes(vcSpeciesContexts[i].getSpecies(), sbmlSpecies);
}
}
Aggregations