use of org.sbml.jsbml.SBMLWriter 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.SBMLWriter 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.SBMLWriter in project vcell by virtualcell.
the class ProjectService method saveModel.
private void saveModel(VCellModel model, Path path) throws IOException, SBMLException, XMLStreamException {
Path modelPath = Paths.get(path.toString(), model.getName());
Files.createDirectories(modelPath);
FileUtils.cleanDirectory(modelPath.toFile());
Path sbmlPath = Paths.get(modelPath.toString(), model.getName() + ".xml");
new SBMLWriter().write(model.getSbmlDocument(), sbmlPath.toFile());
Path imagePath = Paths.get(modelPath.toString(), model.getName() + ".png");
ImageIO.write(model.getImage(), "png", imagePath.toFile());
}
use of org.sbml.jsbml.SBMLWriter in project vcell by virtualcell.
the class VCellService method runSimulation.
private static Task<List<Dataset>, SimulationState> runSimulation(final SimulationServiceImpl client, final VCellModel vCellModel, final SimulationSpec simSpec, final List<Species> outputSpecies, final boolean shouldCreateIndividualDatasets, final OpService opService, final DatasetService datasetService) throws IOException, XMLStreamException {
final Task<List<Dataset>, SimulationState> task = new Task<List<Dataset>, SimulationState>() {
@Override
protected List<Dataset> doInBackground() throws Exception {
setSubtask(SimulationState.notRun);
final File sbmlSpatialFile = new File(vCellModel.getName() + ".xml");
new SBMLWriter().write(vCellModel.getSbmlDocument(), sbmlSpatialFile);
final SBMLModel model = new SBMLModel();
model.setFilepath(sbmlSpatialFile.getAbsolutePath());
final SimulationInfo simulationInfo = client.computeModel(model, simSpec);
try {
Thread.sleep(500);
} catch (final InterruptedException e) {
e.printStackTrace();
}
setSubtask(SimulationState.running);
while (client.getStatus(simulationInfo).getSimState() == SimulationState.running) {
System.out.println("waiting for simulation results");
try {
Thread.sleep(500);
} catch (final InterruptedException e) {
e.printStackTrace();
}
}
if (client.getStatus(simulationInfo).getSimState() == SimulationState.failed) {
setSubtask(SimulationState.failed);
return null;
}
final List<Dataset> results = new ArrayList<>();
final List<VariableInfo> vars = client.getVariableList(simulationInfo);
final List<Double> times = client.getTimePoints(simulationInfo);
for (final VariableInfo var : vars) {
if (outputSpecies.stream().anyMatch(species -> species.getId().equals(var.getVariableVtuName()))) {
// Get data for first time point and determine dimensions
List<Double> data = client.getData(simulationInfo, var, 0);
final int[] dimensions = getDimensions(data, times);
final Img<DoubleType> img = opService.create().img(dimensions);
final RandomAccess<DoubleType> imgRA = img.randomAccess();
// Copy data to the ImgLib2 Img
for (int t = 0; t < times.size(); t++) {
data = client.getData(simulationInfo, var, t);
for (int d = 0; d < data.size(); d++) {
imgRA.setPosition(new int[] { d, t });
imgRA.get().set(data.get(d));
}
}
// Create ImageJ Dataset and add to results
final Dataset dataset = datasetService.create(img);
dataset.setName(var.getVariableVtuName());
results.add(dataset);
}
}
// If desired, add all datasets with the same dimensions
if (!shouldCreateIndividualDatasets && !results.isEmpty()) {
// First, group datasets according to dimensions
final List<List<Dataset>> datasetGroups = new ArrayList<>();
final List<Dataset> initialGroup = new ArrayList<>();
initialGroup.add(results.get(0));
datasetGroups.add(initialGroup);
for (int i = 1; i < results.size(); i++) {
final Dataset result = results.get(i);
for (final List<Dataset> datasetGroup : datasetGroups) {
final Dataset[] datasets = new Dataset[] { datasetGroup.get(0), result };
if (Datasets.areSameSize(datasets, 0, 1)) {
datasetGroup.add(result);
} else {
final List<Dataset> newGroup = new ArrayList<>();
newGroup.add(result);
datasetGroups.add(newGroup);
}
}
}
final List<Dataset> summedResults = new ArrayList<>();
for (final List<Dataset> datasetGroup : datasetGroups) {
final Img<DoubleType> sum = opService.create().img(datasetGroup.get(0));
for (final Dataset dataset : datasetGroup) {
@SuppressWarnings("unchecked") final RandomAccessibleInterval<DoubleType> current = (Img<DoubleType>) dataset.getImgPlus().getImg();
opService.math().add(sum, sum, current);
}
final Dataset result = datasetService.create(sum);
result.setName(datasetGroup.stream().map(d -> d.getName()).collect(Collectors.joining("+")));
summedResults.add(result);
}
return summedResults;
}
setSubtask(SimulationState.done);
return results;
}
};
return task;
}
Aggregations