sbmlmath 0.4.0__tar.gz → 0.5.0__tar.gz

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.
Files changed (44) hide show
  1. {sbmlmath-0.4.0 → sbmlmath-0.5.0}/.github/workflows/ci.yaml +18 -18
  2. {sbmlmath-0.4.0 → sbmlmath-0.5.0}/.github/workflows/deploy_release.yaml +5 -6
  3. sbmlmath-0.5.0/MANIFEST.in +3 -0
  4. {sbmlmath-0.4.0/sbmlmath.egg-info → sbmlmath-0.5.0}/PKG-INFO +8 -3
  5. {sbmlmath-0.4.0 → sbmlmath-0.5.0}/README.md +6 -1
  6. sbmlmath-0.5.0/doc/changelog.rst +4 -0
  7. sbmlmath-0.5.0/doc/development.rst +94 -0
  8. {sbmlmath-0.4.0 → sbmlmath-0.5.0}/doc/index.rst +2 -0
  9. {sbmlmath-0.4.0 → sbmlmath-0.5.0}/pyproject.toml +1 -1
  10. {sbmlmath-0.4.0 → sbmlmath-0.5.0}/sbmlmath/__init__.py +1 -1
  11. {sbmlmath-0.4.0 → sbmlmath-0.5.0}/sbmlmath/mathml_parser.py +136 -44
  12. {sbmlmath-0.4.0 → sbmlmath-0.5.0}/sbmlmath/mathml_printer.py +65 -4
  13. {sbmlmath-0.4.0 → sbmlmath-0.5.0}/sbmlmath/species_symbol.py +2 -2
  14. {sbmlmath-0.4.0 → sbmlmath-0.5.0/sbmlmath.egg-info}/PKG-INFO +8 -3
  15. {sbmlmath-0.4.0 → sbmlmath-0.5.0}/sbmlmath.egg-info/SOURCES.txt +5 -2
  16. sbmlmath-0.5.0/sbmlmath.egg-info/scm_file_list.json +37 -0
  17. sbmlmath-0.5.0/sbmlmath.egg-info/scm_version.json +8 -0
  18. {sbmlmath-0.4.0 → sbmlmath-0.5.0}/tests/test_misc.py +55 -2
  19. sbmlmath-0.5.0/tests/test_parser.py +339 -0
  20. sbmlmath-0.5.0/tests/test_printer.py +112 -0
  21. sbmlmath-0.4.0/.gitignore +0 -9
  22. sbmlmath-0.4.0/doc/.gitignore +0 -3
  23. sbmlmath-0.4.0/tests/test_parser.py +0 -57
  24. sbmlmath-0.4.0/tests/test_printer.py +0 -25
  25. {sbmlmath-0.4.0 → sbmlmath-0.5.0}/.github/dependabot.yml +0 -0
  26. {sbmlmath-0.4.0 → sbmlmath-0.5.0}/.pre-commit-config.yaml +0 -0
  27. {sbmlmath-0.4.0 → sbmlmath-0.5.0}/.readthedocs.yml +0 -0
  28. {sbmlmath-0.4.0 → sbmlmath-0.5.0}/CITATION.cff +0 -0
  29. {sbmlmath-0.4.0 → sbmlmath-0.5.0}/LICENSE +0 -0
  30. {sbmlmath-0.4.0 → sbmlmath-0.5.0}/doc/Makefile +0 -0
  31. {sbmlmath-0.4.0 → sbmlmath-0.5.0}/doc/about.rst +0 -0
  32. {sbmlmath-0.4.0 → sbmlmath-0.5.0}/doc/api.rst +0 -0
  33. {sbmlmath-0.4.0 → sbmlmath-0.5.0}/doc/conf.py +0 -0
  34. {sbmlmath-0.4.0 → sbmlmath-0.5.0}/doc/make.bat +0 -0
  35. {sbmlmath-0.4.0 → sbmlmath-0.5.0}/doc/rtd_requirements.txt +0 -0
  36. {sbmlmath-0.4.0 → sbmlmath-0.5.0}/sbmlmath/cfunction.py +0 -0
  37. {sbmlmath-0.4.0 → sbmlmath-0.5.0}/sbmlmath/csymbol.py +0 -0
  38. {sbmlmath-0.4.0 → sbmlmath-0.5.0}/sbmlmath.egg-info/dependency_links.txt +0 -0
  39. {sbmlmath-0.4.0 → sbmlmath-0.5.0}/sbmlmath.egg-info/requires.txt +0 -0
  40. {sbmlmath-0.4.0 → sbmlmath-0.5.0}/sbmlmath.egg-info/top_level.txt +0 -0
  41. {sbmlmath-0.4.0 → sbmlmath-0.5.0}/setup.cfg +0 -0
  42. {sbmlmath-0.4.0 → sbmlmath-0.5.0}/tests/test_csymbol.py +0 -0
  43. {sbmlmath-0.4.0 → sbmlmath-0.5.0}/tests/test_mathml_parser_sbml_semantic_suite.py +0 -0
  44. {sbmlmath-0.4.0 → sbmlmath-0.5.0}/tests/test_species_symbol.py +0 -0
@@ -12,28 +12,28 @@ jobs:
12
12
 
13
13
  strategy:
14
14
  matrix:
15
- python-version: ["3.9", "3.12"]
15
+ python-version: ["3.10", "3.15"]
16
16
 
17
17
  steps:
18
18
  - name: Check out repository
19
- uses: actions/checkout@v4
19
+ uses: actions/checkout@v7
20
20
 
21
21
  - name: Set up Python ${{ matrix.python-version }}
22
- uses: actions/setup-python@v5
22
+ uses: actions/setup-python@v7
23
23
  with:
24
24
  python-version: ${{ matrix.python-version }}
25
25
 
26
26
  - name: Cache pip
27
- uses: actions/cache@v4
27
+ uses: actions/cache@v6
28
28
  with:
29
29
  path: ~/.cache/pip
30
- key: ${{ runner.os }}-${{ matrix.python-version }}-${{ hashFiles('setup.py') }}
30
+ key: ${{ runner.os }}-${{ matrix.python-version }}-${{ hashFiles('pyproject.toml') }}
31
31
  restore-keys: |
32
32
  ${{ runner.os }}-${{ matrix.python-version }}-
33
33
 
34
34
  - name: Cache / restore SBML test suite
35
35
  id: cache-sbml-test-suite
36
- uses: actions/cache@v4
36
+ uses: actions/cache@v6
37
37
  with:
38
38
  path: sbml-test-suite
39
39
  key: ${{ runner.os }}-sbml-test-suite
@@ -59,28 +59,28 @@ jobs:
59
59
 
60
60
  strategy:
61
61
  matrix:
62
- python-version: ["3.9", "3.12"]
62
+ python-version: ["3.10", "3.15"]
63
63
 
64
64
  steps:
65
65
  - name: Check out repository
66
- uses: actions/checkout@v4
66
+ uses: actions/checkout@v7
67
67
 
68
68
  - name: Set up Python ${{ matrix.python-version }}
69
- uses: actions/setup-python@v5
69
+ uses: actions/setup-python@v7
70
70
  with:
71
71
  python-version: ${{ matrix.python-version }}
72
72
 
73
73
  - name: Cache pip
74
- uses: actions/cache@v4
74
+ uses: actions/cache@v6
75
75
  with:
76
76
  path: ~/.cache/pip
77
- key: ${{ runner.os }}-${{ matrix.python-version }}-${{ hashFiles('setup.py') }}
77
+ key: ${{ runner.os }}-${{ matrix.python-version }}-${{ hashFiles('pyproject.toml') }}
78
78
  restore-keys: |
79
79
  ${{ runner.os }}-${{ matrix.python-version }}-
80
80
 
81
81
  - name: Cache / restore SBML test suite
82
82
  id: cache-sbml-test-suite
83
- uses: actions/cache@v4
83
+ uses: actions/cache@v6
84
84
  with:
85
85
  path: sbml-test-suite
86
86
  key: ${{ runner.os }}-sbml-test-suite
@@ -103,28 +103,28 @@ jobs:
103
103
 
104
104
  strategy:
105
105
  matrix:
106
- python-version: ["3.9", "3.12"]
106
+ python-version: ["3.10", "3.15"]
107
107
 
108
108
  steps:
109
109
  - name: Check out repository
110
- uses: actions/checkout@v4
110
+ uses: actions/checkout@v7
111
111
 
112
112
  - name: Set up Python ${{ matrix.python-version }}
113
- uses: actions/setup-python@v5
113
+ uses: actions/setup-python@v7
114
114
  with:
115
115
  python-version: ${{ matrix.python-version }}
116
116
 
117
117
  - name: Cache pip
118
- uses: actions/cache@v4
118
+ uses: actions/cache@v6
119
119
  with:
120
120
  path: ~/.cache/pip
121
- key: ${{ runner.os }}-${{ matrix.python-version }}-${{ hashFiles('setup.py') }}
121
+ key: ${{ runner.os }}-${{ matrix.python-version }}-${{ hashFiles('pyproject.toml') }}
122
122
  restore-keys: |
123
123
  ${{ runner.os }}-${{ matrix.python-version }}-
124
124
 
125
125
  - name: Cache / restore SBML test suite
126
126
  id: cache-sbml-test-suite
127
- uses: actions/cache@v4
127
+ uses: actions/cache@v6
128
128
  with:
129
129
  path: sbml-test-suite
130
130
  key: ${{ runner.os }}-sbml-test-suite
@@ -16,19 +16,18 @@ jobs:
16
16
 
17
17
  steps:
18
18
  - name: Set up Python
19
- uses: actions/setup-python@v5
19
+ uses: actions/setup-python@v7
20
20
  with:
21
21
  python-version: "3.11"
22
22
 
23
- - uses: actions/checkout@v4
23
+ - uses: actions/checkout@v7
24
24
  with:
25
25
  fetch-depth: 20
26
26
 
27
- - name: Install dependencies
27
+ - name: Build sdist and wheel
28
28
  run: |
29
- python -m pip install --upgrade pip
30
- pip install setuptools wheel build
31
- python -m build -s
29
+ python -m pip install --upgrade pip build
30
+ python -m build
32
31
 
33
32
  - name: Publish a Python distribution to PyPI
34
33
  uses: pypa/gh-action-pypi-publish@release/v1
@@ -0,0 +1,3 @@
1
+ # Exclude development files from packages
2
+ exclude .git_archival.txt
3
+ exclude .gitattributes
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: sbmlmath
3
- Version: 0.4.0
3
+ Version: 0.5.0
4
4
  Summary: SBML Math <-> SymPy
5
5
  Author-email: Daniel Weindl <sci@danielweindl.de>
6
6
  License-Expression: BSD-3-Clause
@@ -9,7 +9,7 @@ Project-URL: Documentation, https://sbmlmath.readthedocs.io/
9
9
  Project-URL: Repository, https://github.com/dweindl/sbmlmath.git
10
10
  Project-URL: Bug Tracker, https://github.com/dweindl/sbmlmath/issues
11
11
  Project-URL: PyPI, https://pypi.org/project/sbmlmath/
12
- Requires-Python: >=3.9
12
+ Requires-Python: >=3.10
13
13
  Description-Content-Type: text/markdown
14
14
  License-File: LICENSE
15
15
  Requires-Dist: python-libsbml>=5.20.4
@@ -73,7 +73,12 @@ Releases from [PyPI](https://pypi.org/project/sbmlmath/):
73
73
  pip install sbmlmath
74
74
  ```
75
75
 
76
+ Releases from [conda-forge](https://anaconda.org/conda-forge/sbmlmath):
77
+ ```bash
78
+ conda install conda-forge::sbmlmath
79
+ ```
80
+
76
81
  The latest development version from GitHub:
77
82
  ```bash
78
- pip install git+https://github.com/dweindl/sbmlmath.git#egg=sbmlmath
83
+ pip install git+https://github.com/dweindl/sbmlmath.git
79
84
  ```
@@ -50,7 +50,12 @@ Releases from [PyPI](https://pypi.org/project/sbmlmath/):
50
50
  pip install sbmlmath
51
51
  ```
52
52
 
53
+ Releases from [conda-forge](https://anaconda.org/conda-forge/sbmlmath):
54
+ ```bash
55
+ conda install conda-forge::sbmlmath
56
+ ```
57
+
53
58
  The latest development version from GitHub:
54
59
  ```bash
55
- pip install git+https://github.com/dweindl/sbmlmath.git#egg=sbmlmath
60
+ pip install git+https://github.com/dweindl/sbmlmath.git
56
61
  ```
@@ -0,0 +1,4 @@
1
+ Changelog
2
+ =========
3
+
4
+ See `https://github.com/dweindl/sbmlmath/releases <https://github.com/dweindl/sbmlmath/releases>`__.
@@ -0,0 +1,94 @@
1
+ Development
2
+ ===========
3
+
4
+ Contributing to sbmlmath
5
+ ------------------------
6
+
7
+ We welcome contributions from the community.
8
+ If you're interested in contributing to the project, please follow these steps:
9
+
10
+ 1. Fork the repository on GitHub.
11
+ 2. Create a new branch for your feature or bug fix.
12
+ 3. Make your changes and commit them with clear messages.
13
+ 4. Push your changes to your forked repository.
14
+ 5. Open a pull request against the main repository.
15
+
16
+ Before submitting a pull request, please ensure that your code adheres to the
17
+ project's coding standards and includes appropriate tests.
18
+
19
+
20
+ Development setup
21
+ -----------------
22
+
23
+ Install the package in editable mode with the test dependencies
24
+ and enable the `pre-commit <https://pre-commit.com/>`_ hooks
25
+ (linters and formatters):
26
+
27
+ .. code-block:: bash
28
+
29
+ pip install -e .[test]
30
+ pre-commit install
31
+
32
+
33
+ Running tests
34
+ -------------
35
+
36
+ We use `pytest <https://docs.pytest.org/en/stable/>`_ for testing.
37
+ This includes the doctests in ``sbmlmath/``.
38
+ To run the test suite, execute the following command in the project root
39
+ directory:
40
+
41
+ .. code-block:: bash
42
+
43
+ pytest
44
+
45
+ The tests based on the
46
+ `SBML Test Suite <https://github.com/sbmlteam/sbml-test-suite/>`_
47
+ are skipped unless ``SBML_TEST_SUITE_ROOT`` points to a checkout of it:
48
+
49
+ .. code-block:: bash
50
+
51
+ git clone --depth=1 https://github.com/sbmlteam/sbml-test-suite/
52
+ SBML_TEST_SUITE_ROOT=$(pwd)/sbml-test-suite pytest
53
+
54
+
55
+ Building the documentation
56
+ --------------------------
57
+
58
+ .. code-block:: bash
59
+
60
+ pip install -r doc/rtd_requirements.txt
61
+ cd doc && make html
62
+
63
+
64
+ Release process
65
+ ---------------
66
+
67
+ Releases are managed via GitHub releases.
68
+
69
+ To create a new release:
70
+
71
+ 1. Ensure that the tests on ``main`` pass
72
+ and that ``CITATION.cff`` is up to date.
73
+ 2. Go to the "Releases" section of the GitHub repository.
74
+ 3. Click on "Draft a new release".
75
+ 4. Fill in the tag version, release title, and description.
76
+
77
+ Version & tag: We follow `Semantic Versioning <https://semver.org/>`_.
78
+ The tag should be in the format ``vX.Y.Z`` (e.g., ``v1.0.0``).
79
+ The release title is ``sbmlmath vX.Y.Z``.
80
+ The package version will be automatically inferred from the tag
81
+ via `setuptools_scm <https://setuptools-scm.readthedocs.io/en/latest/>`__.
82
+
83
+ Description: Use "Generate release notes" and edit as needed.
84
+ The release notes serve as the changelog.
85
+
86
+ 5. Publish the release.
87
+
88
+ A GitHub Action workflow will automatically build and upload the package to
89
+ PyPI. Ensure that the action completes successfully.
90
+ Zenodo archives the release automatically.
91
+
92
+ 6. Merge the version update pull request that the conda-forge bot opens at
93
+ https://github.com/conda-forge/sbmlmath-feedstock.
94
+ Update the recipe if the dependencies have changed.
@@ -7,3 +7,5 @@
7
7
 
8
8
  About <about>
9
9
  API reference <api>
10
+ Development <development>
11
+ Changelog <changelog>
@@ -10,7 +10,7 @@ authors = [
10
10
  ]
11
11
  description = "SBML Math <-> SymPy"
12
12
  readme = "README.md"
13
- requires-python = ">=3.9"
13
+ requires-python = ">=3.10"
14
14
  license = "BSD-3-Clause"
15
15
  dependencies = [
16
16
  "python-libsbml>=5.20.4",
@@ -43,7 +43,7 @@ def sympy_to_sbml_math(sp_expr: sp.Expr) -> libsbml.ASTNode:
43
43
 
44
44
 
45
45
  def sbml_math_to_sympy(
46
- sbml_obj: Union[libsbml.SBase, libsbml.ASTNode], **kwargs
46
+ sbml_obj: libsbml.SBase | libsbml.ASTNode, **kwargs
47
47
  ) -> sp.Expr:
48
48
  """Convert SBML MathML to sympy expression.
49
49
 
@@ -1,14 +1,16 @@
1
1
  """SBML mathml to sympy."""
2
2
 
3
+ from __future__ import annotations
4
+
3
5
  import contextlib
4
6
  import operator as operators
5
- from functools import reduce
7
+ import sys
8
+ from functools import cache, reduce
6
9
  from io import BytesIO
7
- from typing import Union
10
+ from typing import TYPE_CHECKING
8
11
 
9
12
  import sympy as sp
10
13
  from lxml import etree
11
- from pint import UnitRegistry
12
14
  from sympy import Piecewise
13
15
  from sympy.logic.boolalg import (
14
16
  Boolean,
@@ -21,15 +23,35 @@ from .cfunction import CFunction
21
23
  from .csymbol import CSymbol
22
24
  from .species_symbol import SpeciesSymbol
23
25
 
26
+ if TYPE_CHECKING:
27
+ from collections.abc import Collection
28
+
29
+ from pint import UnitRegistry
30
+
24
31
  __all__ = ["SBMLMathMLParser"]
25
32
 
26
33
 
27
34
  mathml_ns = "http://www.w3.org/1998/Math/MathML"
28
- # Create a default unit registry to be used if none is provided to SBMLMathMLParser.__init__.
29
- # Depending on the usage pattern, constructing a new UnitRegistry for each SBMLMathMLParser might be rather slow.
30
- _ureg = UnitRegistry()
31
- _ureg.Quantity.name = property(fget=lambda s: f"({s})")
32
- _ureg.Quantity_sympy_ = lambda s: sp.sympify(f"{s.m}*{s.u:~}")
35
+
36
+
37
+ @cache
38
+ def _get_default_ureg() -> UnitRegistry:
39
+ """Get the default unit registry, shared by all parsers.
40
+
41
+ Created lazily, because importing pint and creating a registry is slow.
42
+ """
43
+ from pint import UnitRegistry
44
+
45
+ ureg = UnitRegistry()
46
+ ureg.Quantity.name = property(fget=lambda s: f"({s})")
47
+ ureg.Quantity_sympy_ = lambda s: sp.sympify(f"{s.m}*{s.u:~}")
48
+ return ureg
49
+
50
+
51
+ def _is_quantity(x) -> bool:
52
+ """Check whether `x` is a :class:`pint.Quantity`, without importing pint."""
53
+ pint = sys.modules.get("pint")
54
+ return pint is not None and isinstance(x, pint.Quantity)
33
55
 
34
56
 
35
57
  # some operator implementations to handle `evaluate`
@@ -50,10 +72,43 @@ def _mul(*args, evaluate: bool = False):
50
72
 
51
73
 
52
74
  def _pow(base, exponent, evaluate: bool = False):
75
+ # pint can't raise units to a symbolic power. For a dimensionless base,
76
+ # the result is dimensionless, so we can drop the units.
77
+ if _is_quantity(base) and not isinstance(
78
+ _strip_dimensionless(exponent), int | float | sp.Number
79
+ ):
80
+ if not base.dimensionless:
81
+ raise ValueError(
82
+ f"Cannot raise `{base}` to the non-numeric power "
83
+ f"`{exponent}`: the units of the result are undefined."
84
+ )
85
+ base = _strip_dimensionless(base)
86
+ exponent = _strip_dimensionless(exponent)
87
+
53
88
  with sp.evaluate(evaluate):
54
89
  return base**exponent
55
90
 
56
91
 
92
+ def _strip_dimensionless(x):
93
+ """Convert a dimensionless quantity to its plain magnitude."""
94
+ if _is_quantity(x) and x.dimensionless:
95
+ return x.to("dimensionless").magnitude
96
+ return x
97
+
98
+
99
+ def _rem(a, b, evaluate: bool = False):
100
+ # SBML `<rem/>` uses C/truncated-division semantics (sign follows the
101
+ # dividend), unlike sympy.Mod (floored, sign follows the divisor).
102
+ # This matches the piecewise expansion libSBML uses for `%` on SBML
103
+ # levels/versions that don't support `<rem/>` directly, so both
104
+ # encodings of the same operator agree.
105
+ with sp.evaluate(evaluate):
106
+ return sp.Piecewise(
107
+ (a - b * sp.ceiling(a / b), sp.Xor(a < 0, b < 0)),
108
+ (a - b * sp.floor(a / b), True),
109
+ )
110
+
111
+
57
112
  mathml_op_sympy_trigonometric = {
58
113
  f"{{{mathml_ns}}}sin": sp.sin,
59
114
  f"{{{mathml_ns}}}cos": sp.cos,
@@ -81,15 +136,10 @@ mathml_op_sympy_trigonometric = {
81
136
  f"{{{mathml_ns}}}arccoth": sp.acoth,
82
137
  }
83
138
  mathml_op_sympy_boolean = {
84
- f"{{{mathml_ns}}}and": lambda *args, **kwargs: sp.And(*args, **kwargs)
85
- if kwargs.get("evaluate", False)
86
- else sp.And(*map(_num2bool, args), **kwargs),
87
- f"{{{mathml_ns}}}or": lambda *args, **kwargs: sp.Or(*args, **kwargs)
88
- if kwargs.get("evaluate", False)
89
- else sp.Or(*map(_num2bool, args), **kwargs),
90
- f"{{{mathml_ns}}}xor": lambda *args, **kwargs: sp.Xor(*args, **kwargs)
91
- if kwargs.get("evaluate", False)
92
- else sp.Xor(*map(_num2bool, args), **kwargs),
139
+ f"{{{mathml_ns}}}and": sp.And,
140
+ f"{{{mathml_ns}}}or": sp.Or,
141
+ f"{{{mathml_ns}}}xor": sp.Xor,
142
+ f"{{{mathml_ns}}}not": sp.Not,
93
143
  f"{{{mathml_ns}}}implies": sp.Implies,
94
144
  }
95
145
 
@@ -123,8 +173,7 @@ mathml_op_sympy = {
123
173
  f"{{{mathml_ns}}}floor": sp.floor,
124
174
  f"{{{mathml_ns}}}factorial": sp.factorial,
125
175
  f"{{{mathml_ns}}}ln": sp.log,
126
- f"{{{mathml_ns}}}not": sp.Not,
127
- f"{{{mathml_ns}}}rem": sp.Mod,
176
+ f"{{{mathml_ns}}}rem": _rem,
128
177
  **mathml_op_sympy_trigonometric,
129
178
  **mathml_op_sympy_boolean,
130
179
  }
@@ -141,7 +190,6 @@ unary = {
141
190
  f"{{{mathml_ns}}}floor",
142
191
  f"{{{mathml_ns}}}factorial",
143
192
  f"{{{mathml_ns}}}ln",
144
- f"{{{mathml_ns}}}not",
145
193
  f"{{{mathml_ns}}}min",
146
194
  f"{{{mathml_ns}}}max",
147
195
  f"{{{mathml_ns}}}root",
@@ -202,16 +250,16 @@ class SBMLMathMLParser:
202
250
 
203
251
  def __init__(
204
252
  self,
205
- sbml_level: Union[int, str] = _DEFAULT_SBML_LEVEL,
206
- sbml_version: Union[int, str] = _DEFAULT_SBML_VERSION,
207
- ureg: UnitRegistry = None,
253
+ sbml_level: int | str = _DEFAULT_SBML_LEVEL,
254
+ sbml_version: int | str = _DEFAULT_SBML_VERSION,
255
+ ureg: UnitRegistry | None = None,
208
256
  floats_as_rationals=True,
209
257
  ignore_units=False,
210
258
  symbol_kwargs=None,
211
259
  evaluate=False,
212
260
  ):
213
261
  """Constructor"""
214
- self.ureg = ureg or _ureg or UnitRegistry()
262
+ self._ureg = ureg
215
263
  self.sbml_core_ns = f"http://www.sbml.org/sbml/level{sbml_level}/version{sbml_version}/core"
216
264
  # TODO {prefix=>url}
217
265
  self.sbml_multi_ns = (
@@ -224,6 +272,8 @@ class SBMLMathMLParser:
224
272
  {} if symbol_kwargs is None else symbol_kwargs.copy()
225
273
  )
226
274
  self.evaluate = evaluate
275
+ # bound variables of the <lambda> currently being parsed
276
+ self._bound_symbols = frozenset()
227
277
 
228
278
  def parse_file(self, file_like) -> sp.Expr:
229
279
  """Parse a file-like object containing MathML.
@@ -243,6 +293,17 @@ class SBMLMathMLParser:
243
293
 
244
294
  return self._parse_element(element)
245
295
 
296
+ @property
297
+ def ureg(self) -> UnitRegistry:
298
+ """The unit registry used for ``sbml:units``."""
299
+ if self._ureg is None:
300
+ self._ureg = _get_default_ureg()
301
+ return self._ureg
302
+
303
+ @ureg.setter
304
+ def ureg(self, ureg: UnitRegistry | None):
305
+ self._ureg = ureg
306
+
246
307
  def parse_str(self, mathml: str):
247
308
  """Parse a string containing MathML.
248
309
 
@@ -309,13 +370,12 @@ class SBMLMathMLParser:
309
370
  if len(operands) == 1 and stripped_tag in {
310
371
  "plus",
311
372
  "times",
312
- "and",
313
- "or",
314
- "xor",
315
373
  "min",
316
374
  "max",
317
375
  }:
318
376
  return sym_operands[0]
377
+ if len(operands) == 1 and stripped_tag in {"and", "or", "xor"}:
378
+ return self._num2bool(sym_operands[0])
319
379
 
320
380
  if (
321
381
  stripped_tag in ("gt", "lt", "leq", "geq", "eq")
@@ -343,12 +403,11 @@ class SBMLMathMLParser:
343
403
  )
344
404
  return expr
345
405
 
346
- # TODO: need to handle boolean->{int,float} conversion via
347
- # `Piecewise((1, expr),(0,True))`
348
- # {int,float} -> bool
349
- # `Piecewise((True, expr != 0),(False,True))`
350
- # as sympy doesn't do that automatically
351
- if operator.tag not in mathml_op_sympy_boolean:
406
+ # explicit boolean->{int,float} conversion for non-boolean functions,
407
+ # since sympy does not do that automatically
408
+ if operator.tag in mathml_op_sympy_boolean:
409
+ sym_operands = list(map(self._num2bool, sym_operands))
410
+ else:
352
411
  sym_operands = list(map(_bool2num, sym_operands))
353
412
 
354
413
  with contextlib.suppress(KeyError):
@@ -520,7 +579,7 @@ class SBMLMathMLParser:
520
579
  # Only Boolean conditions are supported
521
580
  # -> convert
522
581
  # this won't round-trip
523
- cond = _num2bool(cond)
582
+ cond = self._num2bool(cond)
524
583
  expr_cond_pairs.append(
525
584
  (self._parse_element(e[0]), cond),
526
585
  )
@@ -546,7 +605,14 @@ class SBMLMathMLParser:
546
605
  assert len(e) == 1
547
606
  args.append(self._parse_element(e[0]))
548
607
 
549
- rhs = self._parse_element(element[-1])
608
+ # Bound variables may be Boolean, depending on the call site.
609
+ # Therefore, they must not be converted in Boolean contexts.
610
+ outer_bound_symbols = self._bound_symbols
611
+ self._bound_symbols = outer_bound_symbols | set(args)
612
+ try:
613
+ rhs = self._parse_element(element[-1])
614
+ finally:
615
+ self._bound_symbols = outer_bound_symbols
550
616
  return sp.Lambda(tuple(args), rhs)
551
617
 
552
618
  def handle_degree(self, element: etree._Element) -> sp.Expr:
@@ -566,6 +632,10 @@ class SBMLMathMLParser:
566
632
  **self.symbol_kwargs,
567
633
  )
568
634
 
635
+ def _num2bool(self, x: sp.Basic) -> sp.Basic:
636
+ """Convert operands in Boolean contexts to Boolean expressions."""
637
+ return _num2bool(x, boolean_symbols=self._bound_symbols)
638
+
569
639
  def preprocess_symbol_name(
570
640
  self, name: str, element: etree._Element = None
571
641
  ) -> str:
@@ -584,9 +654,12 @@ class SBMLMathMLParser:
584
654
 
585
655
 
586
656
  def _bool2num(x: sp.Basic) -> sp.Basic:
587
- """Convert sympy Booleans or BooleanFunctions to expressions or Integers.
657
+ """Convert sympy Booleans to expressions or Integers.
658
+
659
+ Peforms boolean->{int,float} conversion via
660
+ ``Piecewise((1, expr), (0, True))``.
588
661
 
589
- Return anything else as is
662
+ Return anything else as is.
590
663
  """
591
664
  if isinstance(x, BooleanFalse):
592
665
  return sp.Integer(0)
@@ -599,16 +672,35 @@ def _bool2num(x: sp.Basic) -> sp.Basic:
599
672
  return x
600
673
 
601
674
 
602
- def _num2bool(x: sp.Basic) -> sp.Basic:
675
+ def _num2bool(
676
+ x: sp.Basic, boolean_symbols: Collection[sp.Symbol] = ()
677
+ ) -> sp.Basic:
603
678
  """Convert non-Booleans to Boolean expressions.
604
679
 
680
+ ``expr -> Ne(expr, 0)``
681
+
682
+ Symbols are treated as numeric, except for those in `boolean_symbols`.
683
+
684
+ Piecewise expressions are converted to equivalent Boolean expressions:
685
+
686
+ ``Piecewise((v1, c1), (v2, c2), ...)
687
+ -> (c1 & v1) | (~c1 & c2 & v2) | ...``
688
+
689
+ where the values ``v_i`` are converted recursively.
690
+
605
691
  Return anything else as is.
606
692
  """
607
- if not isinstance(x, Boolean):
608
- if isinstance(x, Piecewise):
609
- # apply recursively to the expressiosn
610
- return Piecewise(
611
- *((_num2bool(expr), cond) for expr, cond in x.args)
693
+ if isinstance(x, Piecewise):
694
+ terms = []
695
+ previous_conds = []
696
+ for expr, cond in x.args:
697
+ terms.append(
698
+ sp.And(*previous_conds, cond, _num2bool(expr, boolean_symbols))
612
699
  )
613
- return Piecewise((True, x != 0), (False, True))
700
+ previous_conds.append(sp.Not(cond))
701
+ return sp.Or(*terms)
702
+ if isinstance(x, sp.Symbol):
703
+ return x if x in boolean_symbols else sp.Ne(x, 0)
704
+ if not isinstance(x, Boolean):
705
+ return sp.Ne(x, 0)
614
706
  return x