Skip to content

Commit

Permalink
Add set_math (#25)
Browse files Browse the repository at this point in the history
Add `set_math(element: libsbml.SBase, expr: sp.Expr)` for updating a math element of an SBML entity.

Closes #24.

Also require `python-libsbml>=5.20.4`. At least with 5.20.0, the test fails due to duplicated `xmlns:sbml` attributes.
  • Loading branch information
dweindl authored Oct 14, 2024
1 parent ea4517f commit 58eecd8
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 1 deletion.
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ readme = "README.md"
requires-python = ">=3.9"
license = {text = "BSD-3-Clause"}
dependencies = [
"python-libsbml",
"python-libsbml>=5.20.4",
"sympy",
"pint",
"lxml>=4.6.4",
Expand Down
31 changes: 31 additions & 0 deletions sbmlmath/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
from .species_symbol import SpeciesSymbol

__all__ = [
"set_math",
"SBMLMathMLParser",
"SBMLMathMLPrinter",
"SpeciesSymbol",
Expand Down Expand Up @@ -75,3 +76,33 @@ def sbml_math_to_sympy(
)
mathml = libsbml.writeMathMLToString(ast_node)
return SBMLMathMLParser().parse_str(mathml)


def set_math(
element: libsbml.SBase,
expr: sp.Expr,
) -> None:
"""Set the math expression of an SBML object.
Args:
element:
The SBML object to set the math expression for.
expr:
The sympy expression to set as the math expression.
"""
sbml_document = element.getSBMLDocument()
mathml = SBMLMathMLPrinter(
sbml_level=sbml_document.getLevel(),
sbml_version=sbml_document.getVersion(),
).doprint(expr)

if ast_node := libsbml.readMathMLFromString(mathml):
if element.setMath(ast_node) == libsbml.LIBSBML_OPERATION_SUCCESS:
return
raise ValueError(
f"Error setting math expression:\n{expr}\n"
f"{mathml}\n{sbml_document.getErrorLog().toString()}"
)
raise ValueError(
f"Unknown error parsing math expression:\n{expr}\n{mathml}"
)
18 changes: 18 additions & 0 deletions tests/test_misc.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,24 @@
from sbmlmath import *


def test_set_math():
"""Test setting math on SBML objects."""
# create some model
doc = libsbml.SBMLDocument(3, 1)
model = doc.createModel()
s = model.createSpecies()
s.setId("s")
p = model.createParameter()
p.setId("p")
ia = model.createInitialAssignment()
ia.setSymbol("s")

# actual test
expr = sp.sympify("2 * p^2")
set_math(ia, expr)
assert expr == sbml_math_to_sympy(ia)


def test_large_mathml():
"""
lxml.etree.iterparse simply truncates long input (>2**15 chars);
Expand Down

0 comments on commit 58eecd8

Please sign in to comment.