use of org.sbml.jsbml.SBMLDocument in project vcell by virtualcell.
the class SBMLExporter method convertToSBML.
public VCellSBMLDoc convertToSBML() throws SbmlException, SBMLException, XMLStreamException {
SBMLDocument sbmlDocument = new SBMLDocument(sbmlLevel, sbmlVersion);
// If the chosen simulation is not null, the exported model's name should reflect it
String modelName = vcBioModel.getName() + "_" + getSelectedSimContext().getName();
if (getSelectedSimulation() != null) {
modelName += "_" + getSelectedSimulation().getName();
}
sbmlModel = sbmlDocument.createModel(TokenMangler.mangleToSName(modelName));
sbmlModel.setName(modelName);
// needed?
sbmlLevel = (int) sbmlModel.getLevel();
sbmlVersion = (int) sbmlModel.getVersion();
translateBioModel();
// include specific vcellInfo annotations
// new Element(XMLTags.VCellRelatedInfoTag, sbml_vcml_ns);
Element sbmlImportRelatedElement = null;
// Element biomodelElement = new Element(XMLTags.BioModelTag, sbml_vcml_ns);
// biomodelElement.setAttribute(XMLTags.NameAttrTag, org.vcell.util.TokenMangler.mangleToSName(vcBioModel.getName()));
// if (vcBioModel.getVersion() != null) {
// biomodelElement.setAttribute(XMLTags.KeyValueAttrTag, vcBioModel.getVersion().getVersionKey().toString());
// }
// sbmlImportRelatedElement.addContent(biomodelElement);
// Element simSpecElement = new Element(XMLTags.SimulationSpecTag, sbml_vcml_ns);
// simSpecElement.setAttribute(XMLTags.NameAttrTag, org.vcell.util.TokenMangler.mangleToSName(getSelectedSimContext().getName()));
// if (getSelectedSimContext().getVersion() != null) {
// simSpecElement.setAttribute(XMLTags.KeyValueAttrTag, getSelectedSimContext().getVersion().getVersionKey().toString());
// }
// sbmlImportRelatedElement.addContent(simSpecElement);
// if (getSelectedSimulation() != null) {
// Element simElement = new Element(XMLTags.SimulationTag, sbml_vcml_ns);
// simElement.setAttribute(XMLTags.NameAttrTag, org.vcell.util.TokenMangler.mangleToSName(getSelectedSimulation().getName()));
// if (getSelectedSimulation().getVersion() != null) {
// simElement.setAttribute(XMLTags.KeyValueAttrTag, getSelectedSimulation().getVersion().getVersionKey().toString());
// }
// sbmlImportRelatedElement.addContent(simElement);
// }
// Get RDF annotation for species from SBMLAnnotationUtils
sbmlAnnotationUtil.writeAnnotation(vcBioModel, sbmlModel, sbmlImportRelatedElement);
// Now set notes,
sbmlAnnotationUtil.writeNotes(vcBioModel, sbmlModel);
// write sbml document into sbml writer, so that the sbml str can be retrieved
SBMLWriter sbmlWriter = new SBMLWriter();
String sbmlStr = sbmlWriter.writeSBMLToString(sbmlDocument);
return new VCellSBMLDoc(sbmlDocument, sbmlModel, sbmlStr);
}
use of org.sbml.jsbml.SBMLDocument in project vcell by virtualcell.
the class SBMLImporter method getBioModel.
// /**
// * @ TODO: This method doesn't take care of adjusting species in nested
// parameter rules with the species_concetration_factor.
// * @param kinetics
// * @param paramExpr
// * @throws ExpressionException
// */
// private void substituteOtherGlobalParams(Kinetics kinetics, Expression
// paramExpr) throws ExpressionException, PropertyVetoException {
// String[] exprSymbols = paramExpr.getSymbols();
// if (exprSymbols == null || exprSymbols.length == 0) {
// return;
// }
// Model vcModel = vcBioModel.getSimulationContext(0).getModel();
// for (int kk = 0; kk < exprSymbols.length; kk++) {
// ModelParameter mp = vcModel.getModelParameter(exprSymbols[kk]);
// if (mp != null) {
// Expression expr = mp.getExpression();
// if (expr != null) {
// Expression newExpr = new Expression(expr);
// substituteGlobalParamRulesInPlace(newExpr, false);
// // param has constant value, add it as a kinetic parameter if it is not
// already in the kinetics
// kinetics.setParameterValue(exprSymbols[kk], newExpr.infix());
// kinetics.getKineticsParameter(exprSymbols[kk]).setUnitDefinition(getSBMLUnit(sbmlModel.getParameter(exprSymbols[kk]).getUnits(),
// null));
// if (newExpr.getSymbols() != null) {
// substituteOtherGlobalParams(kinetics, newExpr);
// }
// }
// }
// }
// }
/**
* parse SBML file into biomodel logs errors to log4j if present in source
* document
*
* @return new Biomodel
* @throws IOException
* @throws XMLStreamException
*/
public BioModel getBioModel() throws XMLStreamException, IOException {
SBMLDocument document;
String output = "didn't check";
try {
if (sbmlFileName != null) {
// Read SBML model into libSBML SBMLDocument and create an SBML model
SBMLReader reader = new SBMLReader();
document = reader.readSBML(sbmlFileName);
// document.checkConsistencyOffline();
// long numProblems = document.getNumErrors();
//
// System.out.println("\n\nSBML Import Error Report");
// ByteArrayOutputStream os = new ByteArrayOutputStream();
// PrintStream ps = new PrintStream(os);
// document.printErrors(ps);
// String output = os.toString();
// if (numProblems > 0 && lg.isEnabledFor(Level.WARN)) {
// lg.warn("Num problems in original SBML document : " + numProblems);
// lg.warn(output);
// }
sbmlModel = document.getModel();
if (sbmlModel == null) {
throw new SBMLImportException("Unable to read SBML file : \n" + output);
}
} else {
if (sbmlModel == null) {
throw new IllegalStateException("Expected non-null SBML model");
}
document = sbmlModel.getSBMLDocument();
}
// Convert SBML Model to VCell model
// An SBML model will correspond to a simcontext - which needs a
// Model and a Geometry
// SBML handles only nonspatial geometries at this time, hence
// creating a non-spatial default geometry
String modelName = sbmlModel.getId();
if (modelName == null || modelName.trim().equals("")) {
modelName = sbmlModel.getName();
}
// name, say 'newModel'
if (modelName == null || modelName.trim().equals("")) {
modelName = "newModel";
}
// get namespace based on SBML model level and version to use in
// SBMLAnnotationUtil
this.level = sbmlModel.getLevel();
// this.version = sbmlModel.getVersion();
String ns = document.getNamespace();
try {
// create SBML unit system for the model and create the bioModel.
ModelUnitSystem modelUnitSystem;
try {
modelUnitSystem = createSBMLUnitSystemForVCModel();
} catch (Exception e) {
e.printStackTrace(System.out);
throw new SBMLImportException("Inconsistent unit system. Cannot import SBML model into VCell", Category.INCONSISTENT_UNIT, e);
}
Geometry geometry = new Geometry(BioModelChildSummary.COMPARTMENTAL_GEO_STR, 0);
vcBioModel = new BioModel(null, modelUnitSystem);
SimulationContext simulationContext = new SimulationContext(vcBioModel.getModel(), geometry, null, null, Application.NETWORK_DETERMINISTIC);
vcBioModel.addSimulationContext(simulationContext);
simulationContext.setName(vcBioModel.getSimulationContext(0).getModel().getName());
// vcBioModel.getSimulationContext(0).setName(vcBioModel.getSimulationContext(0).getModel().getName()+"_"+vcBioModel.getSimulationContext(0).getGeometry().getName());
} catch (PropertyVetoException e) {
e.printStackTrace(System.out);
throw new SBMLImportException("Could not create simulation context corresponding to the input SBML model", e);
}
// SBML annotation
sbmlAnnotationUtil = new SBMLAnnotationUtil(vcBioModel.getVCMetaData(), vcBioModel, ns);
translateSBMLModel();
try {
// **** TEMPORARY BLOCK - to name the biomodel with proper name,
// rather than model id
String biomodelName = sbmlModel.getName();
// if name is not set, use id
if ((biomodelName == null) || biomodelName.trim().equals("")) {
biomodelName = sbmlModel.getId();
}
// if id is not set, use a default, say, 'newModel'
if ((biomodelName == null) || biomodelName.trim().equals("")) {
biomodelName = "newBioModel";
}
vcBioModel.setName(biomodelName);
// **** end - TEMPORARY BLOCK
} catch (Exception e) {
e.printStackTrace(System.out);
throw new SBMLImportException("Could not create Biomodel", e);
}
sbmlAnnotationUtil.readAnnotation(vcBioModel, sbmlModel);
sbmlAnnotationUtil.readNotes(vcBioModel, sbmlModel);
vcBioModel.refreshDependencies();
Issue[] warningIssues = localIssueList.toArray(new Issue[localIssueList.size()]);
if (warningIssues != null && warningIssues.length > 0) {
StringBuffer messageBuffer = new StringBuffer("Issues encountered during SBML Import:\n");
int issueCount = 0;
for (int i = 0; i < warningIssues.length; i++) {
if (warningIssues[i].getSeverity() == Issue.SEVERITY_WARNING || warningIssues[i].getSeverity() == Issue.SEVERITY_INFO) {
messageBuffer.append(warningIssues[i].getCategory() + " " + warningIssues[i].getSeverityName() + " : " + warningIssues[i].getMessage() + "\n");
issueCount++;
}
}
if (issueCount > 0) {
try {
logger.sendMessage(VCLogger.Priority.MediumPriority, VCLogger.ErrorType.OverallWarning, messageBuffer.toString());
} catch (Exception e) {
e.printStackTrace(System.out);
}
// PopupGenerator.showWarningDialog(requester,messageBuffer.toString(),new
// String[] { "OK" }, "OK");
}
}
} catch (Exception e) {
throw new SBMLImportException("Unable to read SBML file : \n" + output, e);
}
return vcBioModel;
}
use of org.sbml.jsbml.SBMLDocument in project vcell by virtualcell.
the class ImportSBMLCommand method run.
@Override
public void run() {
// Read SBML document
SBMLDocument document = null;
try {
document = SBMLReader.read(file);
} catch (XMLStreamException | IOException e) {
e.printStackTrace();
}
// Get SBML geometry
SpatialModelPlugin modelPlugin = (SpatialModelPlugin) document.getModel().getPlugin("spatial");
Geometry geometry = modelPlugin.getGeometry();
SampledField sampledField = geometry.getListOfSampledFields().get(0);
// Parse pixel values to int
String[] imgStringArray = sampledField.getSamples().split(" ");
int[] imgArray = new int[imgStringArray.length];
for (int i = 0; i < imgStringArray.length; i++) {
imgArray[i] = Integer.parseInt(imgStringArray[i]);
}
// Create the image and display
int width = sampledField.getNumSamples1();
int height = sampledField.getNumSamples2();
ArrayImg<UnsignedIntType, IntArray> img = ArrayImgs.unsignedInts(imgArray, width, height);
displayService.createDisplay(img);
}
use of org.sbml.jsbml.SBMLDocument in project vcell by virtualcell.
the class VCellService method getSBML.
public SBMLDocument getSBML(final String vcml, final String applicationName) {
try {
final SimulationServiceImpl client = setupClient();
final SBMLDocument document = getSBML(client, vcml, applicationName);
return document;
} catch (final Throwable e) {
e.printStackTrace();
}
return null;
}
use of org.sbml.jsbml.SBMLDocument 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;
}
Aggregations