Skip to content

Commit 4238588

Browse files
authored
Add SbmlModel.{to_antimony,to_sbml_str} (#371)
Simplify conversion of SBML models to antimony and XML strings. Convenient in particular for debugging.
1 parent d5589c8 commit 4238588

File tree

2 files changed

+25
-4
lines changed

2 files changed

+25
-4
lines changed

petab/v1/models/sbml_model.py

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -65,9 +65,7 @@ def __getstate__(self):
6565

6666
# libsbml stuff cannot be serialized directly
6767
if self.sbml_model:
68-
sbml_document = self.sbml_model.getSBMLDocument()
69-
sbml_writer = libsbml.SBMLWriter()
70-
state["sbml_string"] = sbml_writer.writeSBMLToString(sbml_document)
68+
state["sbml_string"] = self.to_sbml_str()
7169

7270
exclude = ["sbml_reader", "sbml_document", "sbml_model"]
7371
for key in exclude:
@@ -133,6 +131,26 @@ def from_antimony(ant_model: str | Path) -> SbmlModel:
133131
sbml_str = antimony2sbml(ant_model)
134132
return SbmlModel.from_string(sbml_str)
135133

134+
def to_antimony(self) -> str:
135+
"""Convert the SBML model to an Antimony string."""
136+
import antimony as ant
137+
138+
sbml_str = self.to_sbml_str()
139+
140+
ant.clearPreviousLoads()
141+
ant.freeAll()
142+
143+
if ant.loadSBMLString(sbml_str) < 0:
144+
raise RuntimeError(ant.getLastError())
145+
146+
return ant.getAntimonyString()
147+
148+
def to_sbml_str(self) -> str:
149+
"""Convert the SBML model to an SBML/XML string."""
150+
sbml_document = self.sbml_model.getSBMLDocument()
151+
sbml_writer = libsbml.SBMLWriter()
152+
return sbml_writer.writeSBMLToString(sbml_document)
153+
136154
@property
137155
def model_id(self):
138156
return self._model_id

tests/v1/test_sbml.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -134,7 +134,7 @@ def test_sbml_model_repr():
134134
assert repr(petab_model) == "<SbmlModel 'test'>"
135135

136136

137-
def test_sbml_from_ant():
137+
def test_sbml_from_to_ant():
138138
ant_model = """
139139
model test
140140
R1: S1 -> S2; k1*S1
@@ -147,3 +147,6 @@ def test_sbml_from_ant():
147147
assert set(petab_model.get_valid_parameters_for_parameter_table()) == {
148148
"k1"
149149
}
150+
151+
# convert back to antimony
152+
assert "R1: S1 -> S2; k1*S1" in petab_model.to_antimony()

0 commit comments

Comments
 (0)