use of org.sbml.jsbml.InitialAssignment in project vcell by virtualcell.
the class SBMLImporter method addCompartments.
protected void addCompartments(VCMetaData metaData) {
if (sbmlModel == null) {
throw new SBMLImportException("SBML model is NULL");
}
ListOf listofCompartments = sbmlModel.getListOfCompartments();
if (listofCompartments == null) {
throw new SBMLImportException("Cannot have 0 compartments in model");
}
// Using a vector here - since there can be SBML models with only
// features and no membranes.
// Hence keeping the datastructure flexible.
List<Structure> structList = new ArrayList<Structure>();
java.util.HashMap<String, Structure> structureNameMap = new java.util.HashMap<String, Structure>();
try {
int structIndx = 0;
// First pass - create the structures
for (int i = 0; i < sbmlModel.getNumCompartments(); i++) {
org.sbml.jsbml.Compartment compartment = (org.sbml.jsbml.Compartment) listofCompartments.get(i);
String compartmentName = compartment.getId();
if (!compartment.isSetSpatialDimensions() || compartment.getSpatialDimensions() == 3) {
Feature feature = new Feature(compartmentName);
structList.add(structIndx, feature);
structureNameMap.put(compartmentName, feature);
} else if (compartment.getSpatialDimensions() == 2) {
// spatial dimensions is set (see clause above)
Membrane membrane = new Membrane(compartmentName);
structList.add(structIndx, membrane);
structureNameMap.put(compartmentName, membrane);
} else {
logger.sendMessage(VCLogger.Priority.HighPriority, VCLogger.ErrorType.CompartmentError, "Cannot deal with spatial dimension : " + compartment.getSpatialDimensions() + " for compartments at this time.");
throw new SBMLImportException("Cannot deal with spatial dimension : " + compartment.getSpatialDimensions() + " for compartments at this time");
}
structIndx++;
sbmlAnnotationUtil.readAnnotation(structList.get(i), compartment);
sbmlAnnotationUtil.readNotes(structList.get(i), compartment);
}
// Second pass - connect the structures
Model model = vcBioModel.getSimulationContext(0).getModel();
for (int i = 0; i < sbmlModel.getNumCompartments(); i++) {
org.sbml.jsbml.Compartment sbmlCompartment = (org.sbml.jsbml.Compartment) listofCompartments.get(i);
String outsideCompartmentId = null;
if (sbmlCompartment.getOutside() != null && sbmlCompartment.getOutside().length() > 0) {
// compartment.getOutside returns the Sid of the 'outside'
// compartment, so get the compartment from model.
outsideCompartmentId = sbmlCompartment.getOutside();
} else {
Element sbmlImportRelatedElement = sbmlAnnotationUtil.readVCellSpecificAnnotation(sbmlCompartment);
if (sbmlImportRelatedElement != null) {
Element embeddedVCellElement = sbmlImportRelatedElement.getChild(OUTSIDE_COMP_NAME, Namespace.getNamespace(SBMLUtils.SBML_VCELL_NS));
if (embeddedVCellElement != null) {
outsideCompartmentId = embeddedVCellElement.getAttributeValue(XMLTags.NameTag);
}
}
}
if (outsideCompartmentId != null) {
Compartment outsideCompartment = sbmlModel.getCompartment(outsideCompartmentId);
Structure outsideStructure = (Structure) structureNameMap.get(outsideCompartment.getId());
Structure struct = (Structure) structureNameMap.get(sbmlCompartment.getId());
struct.setSbmlParentStructure(outsideStructure);
}
}
// set the structures in vc vcBioModel.getSimulationContext(0)
Structure[] structures = structList.toArray(new Structure[structList.size()]);
model.setStructures(structures);
// Third pass thro' the list of compartments : set the sizes on the
// structureMappings - can be done only after setting
// the structures on vcBioModel.getSimulationContext(0).
boolean allSizesSet = true;
for (int i = 0; i < sbmlModel.getNumCompartments(); i++) {
org.sbml.jsbml.Compartment compartment = (org.sbml.jsbml.Compartment) listofCompartments.get(i);
String compartmentName = compartment.getId();
if (!compartment.isSetSize()) {
// logger.sendMessage(VCLogger.Priority.MediumPriority,
// TranslationMessage.COMPARTMENT_ERROR,
// "compartment "+compartmentName+" size is not set in SBML document.");
allSizesSet = false;
} else {
double size = compartment.getSize();
// Check if size is specified by a rule
Expression sizeExpr = getValueFromAssignmentRule(compartmentName);
if (sizeExpr != null && !sizeExpr.isNumeric()) {
// We are NOT handling compartment sizes with assignment
// rules/initial Assignments that are NON-numeric at
// this time ...
logger.sendMessage(VCLogger.Priority.HighPriority, VCLogger.ErrorType.CompartmentError, "compartment " + compartmentName + " size has an assignment rule which is not a numeric value, cannot handle it at this time.");
}
// check if it is specified by initial assignment
if (sizeExpr == null) {
InitialAssignment compInitAssgnment = sbmlModel.getInitialAssignment(compartmentName);
if (compInitAssgnment != null) {
sizeExpr = getExpressionFromFormula(compInitAssgnment.getMath());
}
}
if (sizeExpr != null && !sizeExpr.isNumeric()) {
// We are NOT handling compartment sizes with assignment
// rules/initial Assignments that are NON-numeric at
// this time ...
logger.sendMessage(VCLogger.Priority.HighPriority, VCLogger.ErrorType.CompartmentError, "compartment " + compartmentName + " size has an initial assignment which is not a numeric value, cannot handle it at this time.");
}
// from 'size' attribute,
if (sizeExpr == null) {
sizeExpr = new Expression(size);
}
// Now set the size of the compartment.
Structure struct = model.getStructure(compartmentName);
StructureMapping.StructureMappingParameter mappingParam = vcBioModel.getSimulationContext(0).getGeometryContext().getStructureMapping(struct).getSizeParameter();
mappingParam.setExpression(sizeExpr);
}
}
// size is set
if (allSizesSet) {
StructureSizeSolver.updateRelativeStructureSizes(vcBioModel.getSimulationContext(0));
}
} catch (Exception e) {
e.printStackTrace(System.out);
throw new SBMLImportException("Error adding Feature to vcModel " + e.getMessage(), e);
}
}
use of org.sbml.jsbml.InitialAssignment in project vcell by virtualcell.
the class SBMLImporter method addCompartments.
protected void addCompartments(VCMetaData metaData, Map<String, Expression> deferredStructureExpression) {
if (sbmlModel == null) {
throw new SBMLImportException("SBML model is NULL");
}
ListOf listofCompartments = sbmlModel.getListOfCompartments();
if (listofCompartments == null) {
throw new SBMLImportException("Cannot have 0 compartments in model");
}
// Using a vector here - since there can be SBML models with only
// features and no membranes.
// Hence keeping the datastructure flexible.
List<Structure> structList = new ArrayList<Structure>();
java.util.HashMap<String, Structure> structureNameMap = new java.util.HashMap<String, Structure>();
try {
int structIndx = 0;
// First pass - create the structures
for (int i = 0; i < sbmlModel.getNumCompartments(); i++) {
org.sbml.jsbml.Compartment compartment = (org.sbml.jsbml.Compartment) listofCompartments.get(i);
String compartmentName = compartment.getId();
if (!compartment.isSetSpatialDimensions() || compartment.getSpatialDimensions() == 3) {
Feature feature = new Feature(compartmentName);
structList.add(structIndx, feature);
structureNameMap.put(compartmentName, feature);
} else if (compartment.getSpatialDimensions() == 2) {
// spatial dimensions is set (see clause above)
Membrane membrane = new Membrane(compartmentName);
structList.add(structIndx, membrane);
structureNameMap.put(compartmentName, membrane);
} else {
String msg = "Cannot deal with spatial dimension : " + compartment.getSpatialDimensions() + " for compartments at this time.";
logger.sendMessage(VCLogger.Priority.HighPriority, VCLogger.ErrorType.CompartmentError, msg);
throw new SBMLImportException(msg);
}
if (compartment.isSetName()) {
structList.get(structIndx).setSbmlName(compartment.getName());
}
structIndx++;
sbmlAnnotationUtil.readAnnotation(structList.get(i), compartment);
sbmlAnnotationUtil.readNotes(structList.get(i), compartment);
}
// Second pass - connect the structures
Model model = vcBioModel.getSimulationContext(0).getModel();
for (int i = 0; i < sbmlModel.getNumCompartments(); i++) {
org.sbml.jsbml.Compartment sbmlCompartment = (org.sbml.jsbml.Compartment) listofCompartments.get(i);
String outsideCompartmentId = null;
if (sbmlCompartment.getOutside() != null && sbmlCompartment.getOutside().length() > 0) {
// compartment.getOutside returns the Sid of the 'outside'
// compartment, so get the compartment from model.
outsideCompartmentId = sbmlCompartment.getOutside();
} else {
Element sbmlImportRelatedElement = sbmlAnnotationUtil.readVCellSpecificAnnotation(sbmlCompartment);
if (sbmlImportRelatedElement != null) {
Element embeddedVCellElement = sbmlImportRelatedElement.getChild(OUTSIDE_COMP_NAME, Namespace.getNamespace(SBMLUtils.SBML_VCELL_NS));
if (embeddedVCellElement != null) {
outsideCompartmentId = embeddedVCellElement.getAttributeValue(XMLTags.NameTag);
}
}
}
if (outsideCompartmentId != null) {
Compartment outsideCompartment = sbmlModel.getCompartment(outsideCompartmentId);
Structure outsideStructure = (Structure) structureNameMap.get(outsideCompartment.getId());
Structure struct = (Structure) structureNameMap.get(sbmlCompartment.getId());
struct.setSbmlParentStructure(outsideStructure);
}
}
// set the structures in vc vcBioModel.getSimulationContext(0)
Structure[] structures = structList.toArray(new Structure[structList.size()]);
model.setStructures(structures);
// Third pass thro' the list of compartments : set the sizes on the
// structureMappings - can be done only after setting
// the structures on vcBioModel.getSimulationContext(0).
boolean allSizesSet = true;
for (int i = 0; i < sbmlModel.getNumCompartments(); i++) {
org.sbml.jsbml.Compartment compartment = (org.sbml.jsbml.Compartment) listofCompartments.get(i);
String compartmentName = compartment.getId();
if (!compartment.isSetSize()) {
// logger.sendMessage(VCLogger.Priority.MediumPriority,
// TranslationMessage.COMPARTMENT_ERROR,
// "compartment "+compartmentName+" size is not set in SBML document.");
allSizesSet = false;
} else {
double size = compartment.getSize();
// Check if size is specified by an assignment rule
// Note that we'll do the x,y,z correction for assignmentRulesHash only after loading the species
// However, it doesn't matter here because compartments must have a numeric expression
Expression sizeExpr = getValueFromAssignmentRule(compartmentName);
if (sizeExpr != null && !sizeExpr.isNumeric()) {
// We are NOT handling compartment sizes with assignment
// rules/initial Assignments that are NON-numeric at this time ...
logger.sendMessage(VCLogger.Priority.HighPriority, VCLogger.ErrorType.CompartmentError, "Compartment '" + compartmentName + "' size has an assignment rule which is not a numeric value, cannot handle it at this time.");
}
// check if it is specified by initial assignment
if (sizeExpr == null) {
InitialAssignment compInitAssgnment = sbmlModel.getInitialAssignment(compartmentName);
if (compInitAssgnment != null) {
sizeExpr = getExpressionFromFormula(compInitAssgnment.getMath());
}
}
if (sizeExpr != null && !sizeExpr.isNumeric()) {
// We are NOT handling compartment sizes with assignment
// rules/initial Assignments that are NON-numeric at
// this time ...
// logger.sendMessage(VCLogger.Priority.HighPriority, VCLogger.ErrorType.CompartmentError,
// "Compartment '" + compartmentName + "' size has an initial assignment which is not a numeric value, cannot handle it at this time.");
// TODO: uncomment below to try and compute the expression later, in finalizeCompartment()
allSizesSet = false;
System.out.println(sizeExpr.infix());
deferredStructureExpression.put(compartmentName, sizeExpr);
sizeExpr = new Expression(size);
}
// from 'size' attribute,
if (sizeExpr == null) {
sizeExpr = new Expression(size);
}
// Now set the size of the compartment.
Structure struct = model.getStructure(compartmentName);
GeometryContext gc = vcBioModel.getSimulationContext(0).getGeometryContext();
StructureMapping.StructureMappingParameter mappingParam = gc.getStructureMapping(struct).getSizeParameter();
// if(!deferredStructureExpression.containsKey(compartmentName)) {
mappingParam.setExpression(sizeExpr);
// }
}
}
// size is set
if (allSizesSet) {
StructureSizeSolver.updateRelativeStructureSizes(vcBioModel.getSimulationContext(0));
}
} catch (Exception e) {
e.printStackTrace(System.out);
throw new SBMLImportException("Error adding Feature to vcModel " + e.getMessage(), e);
}
}
use of org.sbml.jsbml.InitialAssignment 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.InitialAssignment in project vcell by virtualcell.
the class SBMLImporter method addInitialAssignments.
protected void addInitialAssignments() {
if (sbmlModel == null) {
throw new SBMLImportException("SBML model is NULL");
}
ListOf listofInitialAssgns = sbmlModel.getListOfInitialAssignments();
if (listofInitialAssgns == null) {
System.out.println("No Initial Assignments specified");
return;
}
Model vcModel = vcBioModel.getSimulationContext(0).getModel();
for (int i = 0; i < sbmlModel.getNumInitialAssignments(); i++) {
try {
InitialAssignment initAssgn = (InitialAssignment) listofInitialAssgns.get(i);
String initAssgnSymbol = initAssgn.getSymbol();
Expression initAssignMathExpr = getExpressionFromFormula(initAssgn.getMath());
// support compartmentSize expressions, warn and bail out.
if (sbmlModel.getCompartment(initAssgnSymbol) != null) {
if (!initAssignMathExpr.isNumeric()) {
logger.sendMessage(VCLogger.Priority.HighPriority, VCLogger.ErrorType.CompartmentError, "compartment '" + initAssgnSymbol + "' size has an initial assignment, cannot handle it at this time.");
}
// if init assgn for compartment is numeric, the numeric
// value for size is set in addCompartments().
}
// or other species. Not allowed for species.
if (!bSpatial && sbmlModel.getSpecies(initAssgnSymbol) != null) {
if (initAssignMathExpr.hasSymbol(vcModel.getX().getName()) || initAssignMathExpr.hasSymbol(vcModel.getY().getName()) || initAssignMathExpr.hasSymbol(vcModel.getZ().getName())) {
logger.sendMessage(VCLogger.Priority.HighPriority, VCLogger.ErrorType.SpeciesError, "species '" + initAssgnSymbol + "' initial assignment expression cannot contain 'x', 'y', 'z'.");
}
}
initAssignMathExpr = adjustExpression(initAssignMathExpr, vcModel);
// set the init assgn expr on VCell species init condn or global
// parameter expression
SpeciesContextSpec scs = vcBioModel.getSimulationContext(0).getReactionContext().getSpeciesContextSpec(vcBioModel.getSimulationContext(0).getModel().getSpeciesContext(initAssgnSymbol));
ModelParameter mp = vcBioModel.getSimulationContext(0).getModel().getModelParameter(initAssgnSymbol);
if (scs != null) {
scs.getInitialConditionParameter().setExpression(initAssignMathExpr);
} else if (mp != null) {
mp.setExpression(initAssignMathExpr);
} else {
localIssueList.add(new Issue(new SBMLIssueSource(initAssgn), issueContext, IssueCategory.SBMLImport_UnsupportedAttributeOrElement, "Symbol '" + initAssgnSymbol + "' not a species or global parameter in VCell; initial assignment ignored.", Issue.SEVERITY_WARNING));
// logger.sendMessage(VCLogger.Priority.MediumPriority,
// VCLogger.ErrorType.UnsupportedConstruct,
// "Symbol '"+initAssgnSymbol+"' not a species or global parameter in VCell; initial assignment ignored..");
}
} catch (Exception e) {
e.printStackTrace(System.out);
throw new RuntimeException("Error reading InitialAssignment : " + e.getMessage());
}
}
}
use of org.sbml.jsbml.InitialAssignment 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());
if (vcSpeciesContexts[i].getSbmlName() != null) {
sbmlSpecies.setName(vcSpeciesContexts[i].getSbmlName());
}
// 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 'true', since export to SBML is done by converting to initial amounts.
sbmlSpecies.setHasOnlySubstanceUnits(true);
// 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]);
// since we are setting the substance units for species to 'molecule' or 'item', a unit that is originally in uM (or molecules/um2),
// we need to convert concentration from uM -> molecules/um3; this can be achieved by dividing by KMOLE.
// for now we don't do this here and defer to the mechanisms built into the SimContext to convert and set amount instead of concentration
// TO-DO: change to export either concentrations or amounts depending on the type of SimContext and setting
SpeciesContextSpecParameter initCount = vcSpeciesContextsSpec.getInitialCountParameter();
if (initCount.getExpression() == null) {
try {
getSelectedSimContext().convertSpeciesIniCondition(false);
} catch (MappingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
throw new RuntimeException(e.getMessage());
} catch (PropertyVetoException e) {
// TODO Auto-generated catch block
e.printStackTrace();
throw new RuntimeException(e.getMessage());
}
}
Expression initCountExpr = initCount.getExpression();
try {
sbmlSpecies.setInitialAmount(initCountExpr.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 (initCountExpr != null) {
if ((sbmlLevel == 2 && sbmlVersion >= 3) || (sbmlLevel > 2)) {
// L2V3 and above - add expression as init assignment
cbit.vcell.mapping.AssignmentRule vcellAs = getSelectedSimContext().getAssignmentRule(vcSpeciesContexts[i]);
if (vcellAs == null) {
// we don't create InitialAssignment for an AssignmentRule variable (Reference: L3V1 Section 4.8)
ASTNode initAssgnMathNode = getFormulaFromExpression(initCountExpr);
InitialAssignment initAssignment = sbmlModel.createInitialAssignment();
initAssignment.setSymbol(vcSpeciesContexts[i].getName());
initAssignment.setMath(initAssgnMathNode);
}
} else {
// L2V1 (or L1V2 also??)
// do nothing - we no longer support export to level <3
// // 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(initCountExpr);
// 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