sbmlmath 0.5.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,255 @@
1
+ """Convenience functions for libsbml core"""
2
+
3
+ import textwrap
4
+ import warnings
5
+ from numbers import Number
6
+
7
+ import sympy as sp
8
+ from sympy.printing.mathml import MathMLContentPrinter
9
+
10
+ from . import _DEFAULT_SBML_LEVEL, _DEFAULT_SBML_VERSION
11
+ from .csymbol import CSymbol
12
+ from .species_symbol import SpeciesSymbol
13
+
14
+ __all__ = ["SBMLMathMLPrinter"]
15
+
16
+
17
+ class SBMLMathMLPrinter(MathMLContentPrinter):
18
+ """MathML code printer.
19
+
20
+ This printer converts SymPy expressions to MathML code that can be used in
21
+ SBML models.
22
+
23
+ Note:
24
+
25
+ * assumes all constants are dimensionless
26
+ """
27
+
28
+ def __init__(
29
+ self,
30
+ *args,
31
+ literals_dimensionless=True,
32
+ sbml_level: int = _DEFAULT_SBML_LEVEL,
33
+ sbml_version: int = _DEFAULT_SBML_VERSION,
34
+ **kwargs,
35
+ ):
36
+ """Construct.
37
+
38
+ :param literals_dimensionless:
39
+ Assume numeric literals are dimensionless.
40
+ """
41
+ super().__init__(*args, **kwargs)
42
+
43
+ if sbml_level < 3:
44
+ warnings.warn(
45
+ "SBML level < 3 has not been thoroughly tested.",
46
+ UserWarning,
47
+ stacklevel=2,
48
+ )
49
+
50
+ self.mathml_ns = 'xmlns="http://www.w3.org/1998/Math/MathML"'
51
+ self.sbml_ns = f'xmlns:sbml="http://www.sbml.org/sbml/level{sbml_level}/version{sbml_version}/core"'
52
+ # note: so far, there is no L3V2-multi
53
+ self.multi_ns = f'xmlns:multi="http://www.sbml.org/sbml/level{sbml_level}/version1/multi/version1"'
54
+ self.literals_dimensionless = literals_dimensionless
55
+
56
+ def _print_Symbol(self, sym):
57
+ """
58
+ Print Symbol (<ci>)
59
+
60
+ Skip MathML presentation layer, which is not part of the SBML MathML
61
+ subset.
62
+ """
63
+ ci = self.dom.createElement(self.mathml_tag(sym))
64
+ ci.appendChild(self.dom.createTextNode(sym.name))
65
+ return ci
66
+
67
+ def _print_SpeciesSymbol(self, sym: SpeciesSymbol):
68
+ ci = self._print_Symbol(sym)
69
+ if sym.representation_type:
70
+ ci.setAttribute(
71
+ "multi:representationType", sym.representation_type
72
+ )
73
+ if sym.species_reference:
74
+ ci.setAttribute("multi:speciesReference", sym.species_reference)
75
+ return ci
76
+
77
+ def doprint(
78
+ self, expr, with_prolog=True, with_math=True, pretty=False
79
+ ) -> str:
80
+ """Convert SymPy expression to MathML string.
81
+
82
+ :param expr: The SymPy expression to be converted.
83
+ :param with_prolog: Whether to include the XML prolog.
84
+ :param with_math: Whether to include the <math> tags.
85
+ :param pretty: Whether to add line breaks and indentation.
86
+
87
+ >>> SBMLMathMLPrinter().doprint(sp.sympify("3 * a"))
88
+ '<?xml version="1.0" encoding="UTF-8"?>\\n<math xmlns="http://www.w3.org/1998/Math/MathML" xmlns:sbml="http://www.sbml.org/sbml/level3/version2/core">\\n<apply><times/><cn type="integer" sbml:units="dimensionless">3</cn><ci>a</ci></apply></math>'
89
+
90
+ >>> SBMLMathMLPrinter().doprint(sp.sympify("cbrt(3)"), with_math=False, with_prolog=False)
91
+ '<apply><root/><degree><cn>3</cn></degree><cn type="integer" sbml:units="dimensionless">3</cn></apply>'
92
+
93
+ >>> print(SBMLMathMLPrinter().doprint(sp.sympify("a + b"), pretty=True))
94
+ <?xml version="1.0" encoding="UTF-8"?>
95
+ <math xmlns="http://www.w3.org/1998/Math/MathML">
96
+ <apply>
97
+ <plus/>
98
+ <ci>a</ci>
99
+ <ci>b</ci>
100
+ </apply>
101
+ </math>
102
+ """
103
+ if isinstance(expr, float):
104
+ expr = sp.Float(expr)
105
+ try:
106
+ if pretty:
107
+ mathml = (
108
+ self._print(expr)
109
+ .toprettyxml(indent=" ")
110
+ .encode("ascii", "xmlcharrefreplace")
111
+ .decode()
112
+ )
113
+ else:
114
+ mathml = super().doprint(expr)
115
+ except Exception as e:
116
+ raise ValueError(f"MathML printing failed for {expr}") from e
117
+
118
+ if pretty:
119
+ mathml = mathml.rstrip("\n")
120
+ if with_math:
121
+ mathml = textwrap.indent(mathml, " ") + "\n"
122
+
123
+ if not with_math:
124
+ return mathml
125
+
126
+ prolog = (
127
+ '<?xml version="1.0" encoding="UTF-8"?>\n' if with_prolog else ""
128
+ )
129
+
130
+ sbml_ns = f" {self.sbml_ns}" if " sbml:" in mathml else ""
131
+ multi_ns = f" {self.multi_ns}" if " multi:" in mathml else ""
132
+ return (
133
+ f"{prolog}<math {self.mathml_ns}{sbml_ns}{multi_ns}>\n"
134
+ f"{mathml}</math>"
135
+ )
136
+
137
+ def _print_Number(self, e):
138
+ # only try printing as int if it fits int32
139
+ if isinstance(e, int) and _is_sbml_compatible_int(e):
140
+ res = self._print_int(e)
141
+ else:
142
+ res = super()._print_Number(e)
143
+
144
+ if self.literals_dimensionless:
145
+ res.setAttribute("sbml:units", "dimensionless")
146
+ return res
147
+
148
+ def _print_Rational(self, e):
149
+ if e.q == 1:
150
+ # don't divide by one
151
+ return self._print_int(e.p)
152
+
153
+ if not (_is_sbml_compatible_int(e.p) and _is_sbml_compatible_int(e.q)):
154
+ # avoid int32 under/overflow in libsbml and print as float
155
+ return self._print_Number(e.evalf())
156
+
157
+ res = self.dom.createElement("cn")
158
+ res.setAttribute("type", "rational")
159
+ res.appendChild(self.dom.createTextNode(f"{e.p} <sep/> {e.q}"))
160
+
161
+ if self.literals_dimensionless:
162
+ res.setAttribute("sbml:units", "dimensionless")
163
+ return res
164
+
165
+ def _print_int(self, e):
166
+ if not _is_sbml_compatible_int(e):
167
+ # avoid int32 under/overflow in libsbml and print as float
168
+ return self._print_Number(e)
169
+ res = super()._print_int(e)
170
+ res.setAttribute("type", "integer")
171
+ if self.literals_dimensionless:
172
+ res.setAttribute("sbml:units", "dimensionless")
173
+ return res
174
+
175
+ def _print_Float(self, e):
176
+ res = super()._print_Float(e)
177
+ if self.literals_dimensionless:
178
+ res.setAttribute("sbml:units", "dimensionless")
179
+ return res
180
+
181
+ def _print_One(self, e):
182
+ res = self._print_int(e)
183
+ if self.literals_dimensionless:
184
+ res.setAttribute("sbml:units", "dimensionless")
185
+ return res
186
+
187
+ def _print_Quantity(self, e):
188
+ res = self._print(e.m)
189
+ if isinstance(e.m, Number):
190
+ # TODO this unit may not exist and might have to be created
191
+ # TODO if Quantities are used in sympy expressions, they might
192
+ # units might get shuffled around and end up <apply>. In this case
193
+ # we skip settings units for now.
194
+ res.setAttribute("sbml:units", str(e.u))
195
+ return res
196
+
197
+ def _print_CSymbol(self, e: CSymbol):
198
+ dom_element = self.dom.createElement("csymbol")
199
+ dom_element.appendChild(self.dom.createTextNode(str(e)))
200
+ if e.definition_url:
201
+ dom_element.setAttribute("definitionURL", e.definition_url)
202
+ if e.encoding:
203
+ dom_element.setAttribute("encoding", e.encoding)
204
+
205
+ return dom_element
206
+
207
+ def _print_Function(self, e):
208
+ if hasattr(e, "definition_url"):
209
+ return self._print_CFunction(e)
210
+ return super()._print_Function(e)
211
+
212
+ def _print_CFunction(self, e):
213
+ dom_element = self.dom.createElement("apply")
214
+ csymbol = self.dom.createElement("csymbol")
215
+ csymbol.appendChild(self.dom.createTextNode(e.name))
216
+
217
+ if e.definition_url:
218
+ csymbol.setAttribute("definitionURL", e.definition_url)
219
+ if e.encoding:
220
+ csymbol.setAttribute("encoding", e.encoding)
221
+ dom_element.appendChild(csymbol)
222
+ for arg in e.args:
223
+ dom_element.appendChild(self._print(arg))
224
+
225
+ return dom_element
226
+
227
+ def _print_ITE(self, e):
228
+ # SBML MathML has no if-then-else operator, so print as
229
+ # <piecewise>. Nested ITEs in the else-branch become additional
230
+ # pieces.
231
+ root = self.dom.createElement("piecewise")
232
+ while isinstance(e, sp.ITE):
233
+ cond, then, e = e.args
234
+ piece = self.dom.createElement("piece")
235
+ piece.appendChild(self._print(then))
236
+ piece.appendChild(self._print(cond))
237
+ root.appendChild(piece)
238
+ otherwise = self.dom.createElement("otherwise")
239
+ otherwise.appendChild(self._print(e))
240
+ root.appendChild(otherwise)
241
+ return root
242
+
243
+ def _print_Mod(self, e):
244
+ # SBML MathML has no operator with sympy.Mod's floored-division
245
+ # semantics (`<rem/>` is C/truncated-division, see #46/#48), so
246
+ # expand it into its definition using operators that do exist.
247
+ a, b = e.args
248
+ with sp.evaluate(False):
249
+ expanded = a - b * sp.floor(a / b)
250
+ return self._print(expanded)
251
+
252
+
253
+ def _is_sbml_compatible_int(value: int) -> bool:
254
+ """Check if integer is compatible with SBML (fits into signed int32)."""
255
+ return 2**31 > value >= -(2**31)
@@ -0,0 +1,79 @@
1
+ """SBML MathML related functionality"""
2
+
3
+ from typing import Literal
4
+
5
+ import sympy as sp
6
+
7
+ __all__ = ["SpeciesSymbol"]
8
+
9
+
10
+ class SpeciesSymbol(sp.Dummy):
11
+ """
12
+ Represents a ``<ci>`` element containing a species.
13
+
14
+ Represents, for example,
15
+ ``<ci multi:representationType="sum"> bla </ci>`` or
16
+ ``<ci multi:speciesReference="refS"> S </ci>``
17
+ (see SBML multi specs 3.26).
18
+
19
+ Subclassed from :class:`sympy.Dummy` to avoid caching issues, due to using
20
+ the same name but with different attributes / meanings.
21
+
22
+ Arguments
23
+ ---------
24
+ representation_type:
25
+ What the species symbol represents (see also SBML-multi spec 3.26.2).
26
+ species_reference:
27
+ ID of a species reference in the same reaction
28
+ (see also SBML-multi spec 3.26.1).
29
+
30
+
31
+ >>> SpeciesSymbol("S") + SpeciesSymbol("S", representation_type="sum")
32
+ _S + _S
33
+
34
+ >>> SpeciesSymbol("S") == SpeciesSymbol("S", representation_type="sum")
35
+ False
36
+
37
+ >>> SpeciesSymbol("ref_to_S", species_reference="S")
38
+ <ref_to_S(species_reference=S)>
39
+ """
40
+
41
+ _cache = {}
42
+
43
+ def __new__(
44
+ cls,
45
+ *args,
46
+ representation_type: Literal["sum", "numericValue"] | None = None,
47
+ species_reference: str = None,
48
+ **kwargs,
49
+ ):
50
+ # Cache instances.
51
+ # If not done: (SpeciesSymbol("A") == SpeciesSymbol("A")) == False
52
+ if not (name := kwargs.get("name")):
53
+ name = args[0]
54
+ cache_key = (name, representation_type, species_reference)
55
+ if cached := cls._cache.get(cache_key):
56
+ return cached
57
+
58
+ obj = super().__new__(cls, *args, **kwargs)
59
+ obj.representation_type = representation_type
60
+ obj.species_reference = species_reference
61
+
62
+ cls._cache[cache_key] = obj
63
+
64
+ return obj
65
+
66
+ def __repr__(self):
67
+ rt = (
68
+ f"representation_type={self.representation_type}"
69
+ if self.representation_type
70
+ else ""
71
+ )
72
+ sr = (
73
+ f"species_reference={self.species_reference}"
74
+ if self.species_reference
75
+ else ""
76
+ )
77
+ rt = f"{rt}, " if rt and sr else rt
78
+
79
+ return f"<{self.name}({rt}{sr})>"
@@ -0,0 +1,84 @@
1
+ Metadata-Version: 2.4
2
+ Name: sbmlmath
3
+ Version: 0.5.0
4
+ Summary: SBML Math <-> SymPy
5
+ Author-email: Daniel Weindl <sci@danielweindl.de>
6
+ License-Expression: BSD-3-Clause
7
+ Project-URL: Homepage, https://github.com/dweindl/sbmlmath
8
+ Project-URL: Documentation, https://sbmlmath.readthedocs.io/
9
+ Project-URL: Repository, https://github.com/dweindl/sbmlmath.git
10
+ Project-URL: Bug Tracker, https://github.com/dweindl/sbmlmath/issues
11
+ Project-URL: PyPI, https://pypi.org/project/sbmlmath/
12
+ Requires-Python: >=3.10
13
+ Description-Content-Type: text/markdown
14
+ License-File: LICENSE
15
+ Requires-Dist: python-libsbml>=5.20.4
16
+ Requires-Dist: sympy
17
+ Requires-Dist: pint
18
+ Requires-Dist: lxml>=4.6.4
19
+ Provides-Extra: test
20
+ Requires-Dist: pytest>=7; extra == "test"
21
+ Requires-Dist: pre-commit>=3; extra == "test"
22
+ Dynamic: license-file
23
+
24
+ # sbmlmath — a Python library for handling SBML MathML
25
+
26
+ [![PyPI - Version](https://img.shields.io/pypi/v/sbmlmath)](https://pypi.org/project/sbmlmath/)
27
+ [![DOI](https://zenodo.org/badge/617871948.svg)](https://doi.org/10.5281/zenodo.14814669)
28
+
29
+
30
+ `sbmlmath` is a Python library for interconverting [SymPy](https://github.com/sympy/sympy/)
31
+ expressions and [SBML](https://sbml.org/)-MathML.
32
+ SBML uses a subset of [MathML](https://www.w3.org/Math/) that this library
33
+ aims to support. This is not (intended to be) a general MathML parser.
34
+
35
+ Main functionality:
36
+
37
+ * sympy -> SBML MathML
38
+ * SBML MathML -> sympy
39
+ * in particular for cases where `sympy.sympify(libsbml.formulaToL3String(...))`
40
+ won't do the job
41
+ (mind, e.g., the differences in operator precedence between
42
+ sympy/[Python](https://docs.python.org/3/reference/expressions.html#operator-precedence)
43
+ and [libsbml L3 formulas](https://synonym.caltech.edu/software/libsbml/5.18.0/docs/formatted/python-api/libsbml-math.html#math-l3)!)
44
+ * retaining unit annotations and other `<ci>` attributes
45
+
46
+ **NOTE: This is under development and the API is to be considered unstable**
47
+
48
+ Python support policy: sbmlmath follows [NEP 29](https://numpy.org/neps/nep-0029-deprecation_policy.html).
49
+
50
+ ## Usage
51
+
52
+ ```python
53
+ from sbmlmath import SBMLMathMLPrinter, SBMLMathMLParser
54
+ import sympy as sp
55
+
56
+ sympy_expr = sp.sympify("A ** B + exp(C) * D")
57
+ mathml = SBMLMathMLPrinter().doprint(sympy_expr)
58
+ print(mathml)
59
+
60
+ cycled_sympy = SBMLMathMLParser().parse_str(mathml)
61
+ print(cycled_sympy)
62
+ assert sympy_expr == cycled_sympy
63
+ ```
64
+
65
+ ## Documentation
66
+
67
+ Under construction at [sbmlmath.readthedocs.io](https://sbmlmath.readthedocs.io/).
68
+
69
+ ## Installation
70
+
71
+ Releases from [PyPI](https://pypi.org/project/sbmlmath/):
72
+ ```bash
73
+ pip install sbmlmath
74
+ ```
75
+
76
+ Releases from [conda-forge](https://anaconda.org/conda-forge/sbmlmath):
77
+ ```bash
78
+ conda install conda-forge::sbmlmath
79
+ ```
80
+
81
+ The latest development version from GitHub:
82
+ ```bash
83
+ pip install git+https://github.com/dweindl/sbmlmath.git
84
+ ```
@@ -0,0 +1,11 @@
1
+ sbmlmath/__init__.py,sha256=gh20rjBgw7yHvi7aD5cksJuvqpkwMqChe_3g80hk2t0,3509
2
+ sbmlmath/cfunction.py,sha256=JjUdmsrSgXFZEtXq0uth1G7FJXANg9tCn1v7TKk6nIE,4166
3
+ sbmlmath/csymbol.py,sha256=0GV7KQUVRsrw2KFhpMLBgSvrXUeislbKQ1vAOpU2AYw,3792
4
+ sbmlmath/mathml_parser.py,sha256=qhO_ayGCFsHRNl2Bd4uiLzbNK0q6uEapjcxat_HChRE,25629
5
+ sbmlmath/mathml_printer.py,sha256=6HpLiDYBrYAJ4RKjCxUZDiQZ1pNpQq3iJCAy4nrLiQo,9005
6
+ sbmlmath/species_symbol.py,sha256=cLcMfMKxGRnk3w4fKPhFTp6-edB8PnNnECv2Ar4Lex4,2187
7
+ sbmlmath-0.5.0.dist-info/licenses/LICENSE,sha256=NxPfyufLEMJr03V2-KepWHOJr_886MJ9LmynfTKqvAs,1462
8
+ sbmlmath-0.5.0.dist-info/METADATA,sha256=uh3ujR8YNqq2Ekf4VQq_Fu55qwiRzYNt7o6U_NXt9d4,2804
9
+ sbmlmath-0.5.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
10
+ sbmlmath-0.5.0.dist-info/top_level.txt,sha256=JXVIsHPpcwLYja4iHtCWOnNncdJUHe0jeCrpxNqE2Lo,9
11
+ sbmlmath-0.5.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,11 @@
1
+ Copyright 2023 Daniel Weindl
2
+
3
+ Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
4
+
5
+ 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
6
+
7
+ 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
8
+
9
+ 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
10
+
11
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
@@ -0,0 +1 @@
1
+ sbmlmath