sbmlmath 0.0.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.
- sbmlmath-0.0.0/.github/workflows/ci.yaml +53 -0
- sbmlmath-0.0.0/.gitignore +4 -0
- sbmlmath-0.0.0/LICENSE +11 -0
- sbmlmath-0.0.0/PKG-INFO +42 -0
- sbmlmath-0.0.0/README.md +31 -0
- sbmlmath-0.0.0/pyproject.toml +26 -0
- sbmlmath-0.0.0/sbmlmath/__init__.py +32 -0
- sbmlmath-0.0.0/sbmlmath/mathml_parser.py +410 -0
- sbmlmath-0.0.0/sbmlmath/mathml_printer.py +98 -0
- sbmlmath-0.0.0/sbmlmath/species_symbol.py +54 -0
- sbmlmath-0.0.0/sbmlmath.egg-info/PKG-INFO +42 -0
- sbmlmath-0.0.0/sbmlmath.egg-info/SOURCES.txt +19 -0
- sbmlmath-0.0.0/sbmlmath.egg-info/dependency_links.txt +1 -0
- sbmlmath-0.0.0/sbmlmath.egg-info/requires.txt +7 -0
- sbmlmath-0.0.0/sbmlmath.egg-info/top_level.txt +1 -0
- sbmlmath-0.0.0/setup.cfg +4 -0
- sbmlmath-0.0.0/tests/test_mathml_parser_sbml_semantic_suite.py +45 -0
- sbmlmath-0.0.0/tests/test_misc.py +41 -0
- sbmlmath-0.0.0/tests/test_parser.py +29 -0
- sbmlmath-0.0.0/tests/test_printer.py +28 -0
- sbmlmath-0.0.0/tests/test_species_symbol.py +97 -0
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
name: Tests
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
push:
|
|
5
|
+
workflow_dispatch:
|
|
6
|
+
schedule:
|
|
7
|
+
- cron: '48 4 * * *'
|
|
8
|
+
|
|
9
|
+
jobs:
|
|
10
|
+
build:
|
|
11
|
+
runs-on: ubuntu-latest
|
|
12
|
+
|
|
13
|
+
strategy:
|
|
14
|
+
matrix:
|
|
15
|
+
python-version: ["3.11"]
|
|
16
|
+
|
|
17
|
+
steps:
|
|
18
|
+
- name: Check out repository
|
|
19
|
+
uses: actions/checkout@v3
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
- name: Set up Python ${{ matrix.python-version }}
|
|
23
|
+
uses: actions/setup-python@v4
|
|
24
|
+
with:
|
|
25
|
+
python-version: ${{ matrix.python-version }}
|
|
26
|
+
|
|
27
|
+
- name: Cache pip
|
|
28
|
+
uses: actions/cache@v3
|
|
29
|
+
with:
|
|
30
|
+
path: ~/.cache/pip
|
|
31
|
+
key: ${{ runner.os }}-${{ hashFiles('setup.py') }}
|
|
32
|
+
restore-keys: |
|
|
33
|
+
${{ runner.os }}-
|
|
34
|
+
|
|
35
|
+
- name: Cache / restore SBML test suite
|
|
36
|
+
id: cache-sbml-test-suite
|
|
37
|
+
uses: actions/cache@v3
|
|
38
|
+
with:
|
|
39
|
+
path: sbml-test-suite
|
|
40
|
+
key: ${{ runner.os }}-sbml-test-suite
|
|
41
|
+
|
|
42
|
+
- name: Download SBML test suite
|
|
43
|
+
if: steps.cache-sbml-test-suite.outputs.cache-hit != 'true'
|
|
44
|
+
run: git clone --depth=1 https://github.com/sbmlteam/sbml-test-suite/
|
|
45
|
+
|
|
46
|
+
- name: Install local packages
|
|
47
|
+
run: |
|
|
48
|
+
pip install .[test]
|
|
49
|
+
|
|
50
|
+
- name: Unit tests
|
|
51
|
+
env:
|
|
52
|
+
SBML_TEST_SUITE_ROOT: "${{ github.workspace }}/sbml-test-suite/"
|
|
53
|
+
run: pytest -vv
|
sbmlmath-0.0.0/LICENSE
ADDED
|
@@ -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.
|
sbmlmath-0.0.0/PKG-INFO
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
Metadata-Version: 2.1
|
|
2
|
+
Name: sbmlmath
|
|
3
|
+
Version: 0.0.0
|
|
4
|
+
Summary: SBML Math <-> SymPy
|
|
5
|
+
Author-email: Daniel Weindl <sci@danielweindl.de>
|
|
6
|
+
License: BSD-3-Clause
|
|
7
|
+
Requires-Python: >=3.10
|
|
8
|
+
Description-Content-Type: text/markdown
|
|
9
|
+
Provides-Extra: test
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
|
|
12
|
+
# sbmlmath - a Python library for handling SBML MathML
|
|
13
|
+
|
|
14
|
+
This is Python library for interconverting [SymPy](https://github.com/sympy/sympy/)
|
|
15
|
+
expressions and [SBML](https://sbml.org/) MathML.
|
|
16
|
+
SBML uses a subset of [MathML](https://www.w3.org/Math/) that this library
|
|
17
|
+
tries to support. This is not (intended to be) a general MathML parser.
|
|
18
|
+
|
|
19
|
+
Main functionality:
|
|
20
|
+
|
|
21
|
+
* sympy -> SBML MathML
|
|
22
|
+
* SBML MathML -> sympy
|
|
23
|
+
* in particular for cases where `sympy.sympify(libsbml.formulaToL3String(...))`
|
|
24
|
+
won't do the job
|
|
25
|
+
* retaining unit annotations and other `<ci>` attributes
|
|
26
|
+
|
|
27
|
+
**NOTE: This is under development and the API is to be considered unstable**
|
|
28
|
+
|
|
29
|
+
## Usage
|
|
30
|
+
|
|
31
|
+
```python
|
|
32
|
+
from sbmlmath import MyMathMLContentPrinter, SBMLMathMLParser
|
|
33
|
+
import sympy as sp
|
|
34
|
+
|
|
35
|
+
sympy_expr = sp.sympify("A ** B + exp(C) * D")
|
|
36
|
+
mathml = MyMathMLContentPrinter().doprint(sympy_expr)
|
|
37
|
+
print(mathml)
|
|
38
|
+
|
|
39
|
+
cycled_sympy = SBMLMathMLParser().parse_str(mathml)
|
|
40
|
+
print(cycled_sympy)
|
|
41
|
+
assert sympy_expr == cycled_sympy
|
|
42
|
+
```
|
sbmlmath-0.0.0/README.md
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
# sbmlmath - a Python library for handling SBML MathML
|
|
2
|
+
|
|
3
|
+
This is Python library for interconverting [SymPy](https://github.com/sympy/sympy/)
|
|
4
|
+
expressions and [SBML](https://sbml.org/) MathML.
|
|
5
|
+
SBML uses a subset of [MathML](https://www.w3.org/Math/) that this library
|
|
6
|
+
tries to support. This is not (intended to be) a general MathML parser.
|
|
7
|
+
|
|
8
|
+
Main functionality:
|
|
9
|
+
|
|
10
|
+
* sympy -> SBML MathML
|
|
11
|
+
* SBML MathML -> sympy
|
|
12
|
+
* in particular for cases where `sympy.sympify(libsbml.formulaToL3String(...))`
|
|
13
|
+
won't do the job
|
|
14
|
+
* retaining unit annotations and other `<ci>` attributes
|
|
15
|
+
|
|
16
|
+
**NOTE: This is under development and the API is to be considered unstable**
|
|
17
|
+
|
|
18
|
+
## Usage
|
|
19
|
+
|
|
20
|
+
```python
|
|
21
|
+
from sbmlmath import MyMathMLContentPrinter, SBMLMathMLParser
|
|
22
|
+
import sympy as sp
|
|
23
|
+
|
|
24
|
+
sympy_expr = sp.sympify("A ** B + exp(C) * D")
|
|
25
|
+
mathml = MyMathMLContentPrinter().doprint(sympy_expr)
|
|
26
|
+
print(mathml)
|
|
27
|
+
|
|
28
|
+
cycled_sympy = SBMLMathMLParser().parse_str(mathml)
|
|
29
|
+
print(cycled_sympy)
|
|
30
|
+
assert sympy_expr == cycled_sympy
|
|
31
|
+
```
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools", "setuptools-scm"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "sbmlmath"
|
|
7
|
+
authors = [
|
|
8
|
+
{name = "Daniel Weindl", email = "sci@danielweindl.de"},
|
|
9
|
+
]
|
|
10
|
+
description = "SBML Math <-> SymPy"
|
|
11
|
+
readme = "README.md"
|
|
12
|
+
requires-python = ">=3.10"
|
|
13
|
+
license = {text = "BSD-3-Clause"}
|
|
14
|
+
dependencies = [
|
|
15
|
+
"python-libsbml",
|
|
16
|
+
"sympy",
|
|
17
|
+
"pint",
|
|
18
|
+
"lxml",
|
|
19
|
+
]
|
|
20
|
+
dynamic = ["version"]
|
|
21
|
+
|
|
22
|
+
[project.optional-dependencies]
|
|
23
|
+
test = ["pytest",]
|
|
24
|
+
|
|
25
|
+
[tool.black]
|
|
26
|
+
line-length = 80
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
from typing import Union
|
|
2
|
+
|
|
3
|
+
import libsbml
|
|
4
|
+
import sympy as sp
|
|
5
|
+
|
|
6
|
+
from .mathml_parser import SBMLMathMLParser
|
|
7
|
+
from .mathml_printer import MyMathMLContentPrinter
|
|
8
|
+
from .species_symbol import SpeciesSymbol
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def sympy_to_sbml_math(sp_expr: sp.Expr) -> libsbml.ASTNode:
|
|
12
|
+
"""Convert sympy expression to SBML math ASTNode"""
|
|
13
|
+
mathml = MyMathMLContentPrinter().doprint(sp_expr)
|
|
14
|
+
|
|
15
|
+
if ast_node := libsbml.readMathMLFromString(mathml):
|
|
16
|
+
return ast_node
|
|
17
|
+
|
|
18
|
+
raise ValueError(
|
|
19
|
+
f"Unknown error handling math expression:\n{sp_expr}\n"
|
|
20
|
+
f"{mathml}"
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def sbml_math_to_sympy(
|
|
25
|
+
sbml_obj: Union[libsbml.SBase, libsbml.ASTNode]
|
|
26
|
+
) -> sp.Expr:
|
|
27
|
+
"""Convert SBML MathML to sympy using the custom MathML parser"""
|
|
28
|
+
ast_node = sbml_obj if isinstance(sbml_obj, libsbml.ASTNode) \
|
|
29
|
+
else sbml_obj.getMath()
|
|
30
|
+
mathml = libsbml.writeMathMLToString(ast_node)
|
|
31
|
+
return SBMLMathMLParser().parse_str(mathml)
|
|
32
|
+
|
|
@@ -0,0 +1,410 @@
|
|
|
1
|
+
"""SBML mathml to sympy."""
|
|
2
|
+
import contextlib
|
|
3
|
+
import operator as operators
|
|
4
|
+
from functools import reduce
|
|
5
|
+
from io import BytesIO
|
|
6
|
+
|
|
7
|
+
import sympy as sp
|
|
8
|
+
from lxml import etree
|
|
9
|
+
from pint import UnitRegistry
|
|
10
|
+
from sympy.logic.boolalg import Boolean, BooleanFalse, BooleanTrue
|
|
11
|
+
|
|
12
|
+
from .species_symbol import SpeciesSymbol
|
|
13
|
+
|
|
14
|
+
mathml_ns = "http://www.w3.org/1998/Math/MathML"
|
|
15
|
+
_ureg = UnitRegistry()
|
|
16
|
+
_ureg.Quantity.name = property(fget=lambda s: f"({s})")
|
|
17
|
+
_ureg.Quantity_sympy_ = lambda s: sp.sympify(f'{s.m}*{s.u:~}')
|
|
18
|
+
|
|
19
|
+
mathml_op_sympy_trigonometric = {
|
|
20
|
+
f"{{{mathml_ns}}}sin": sp.sin,
|
|
21
|
+
f"{{{mathml_ns}}}cos": sp.cos,
|
|
22
|
+
f"{{{mathml_ns}}}tan": sp.tan,
|
|
23
|
+
f"{{{mathml_ns}}}sec": sp.sec,
|
|
24
|
+
f"{{{mathml_ns}}}csc": sp.csc,
|
|
25
|
+
f"{{{mathml_ns}}}cot": sp.cot,
|
|
26
|
+
f"{{{mathml_ns}}}sinh": sp.sinh,
|
|
27
|
+
f"{{{mathml_ns}}}cosh": sp.cosh,
|
|
28
|
+
f"{{{mathml_ns}}}tanh": sp.tanh,
|
|
29
|
+
f"{{{mathml_ns}}}sech": sp.sech,
|
|
30
|
+
f"{{{mathml_ns}}}csch": sp.csch,
|
|
31
|
+
f"{{{mathml_ns}}}coth": sp.coth,
|
|
32
|
+
f"{{{mathml_ns}}}arccos": sp.acos,
|
|
33
|
+
f"{{{mathml_ns}}}arcsin": sp.asin,
|
|
34
|
+
f"{{{mathml_ns}}}arctan": sp.atan,
|
|
35
|
+
f"{{{mathml_ns}}}arcsec": sp.asec,
|
|
36
|
+
f"{{{mathml_ns}}}arccsc": sp.acsc,
|
|
37
|
+
f"{{{mathml_ns}}}arccot": sp.acot,
|
|
38
|
+
f"{{{mathml_ns}}}arcsinh": sp.asinh,
|
|
39
|
+
f"{{{mathml_ns}}}arccosh": sp.acosh,
|
|
40
|
+
f"{{{mathml_ns}}}arctanh": sp.atanh,
|
|
41
|
+
f"{{{mathml_ns}}}arcsech": sp.asech,
|
|
42
|
+
f"{{{mathml_ns}}}arccsch": sp.acsch,
|
|
43
|
+
f"{{{mathml_ns}}}arccoth": sp.acoth,
|
|
44
|
+
}
|
|
45
|
+
mathml_op_sympy_boolean = {
|
|
46
|
+
f"{{{mathml_ns}}}and": sp.And,
|
|
47
|
+
f"{{{mathml_ns}}}or": sp.Or,
|
|
48
|
+
f"{{{mathml_ns}}}xor": sp.Xor,
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
mathml_op_sympy = {
|
|
52
|
+
f"{{{mathml_ns}}}times":
|
|
53
|
+
lambda *args: reduce(operators.mul, args, sp.Integer(1)),
|
|
54
|
+
f"{{{mathml_ns}}}power": lambda base, exponent: base ** exponent,
|
|
55
|
+
f"{{{mathml_ns}}}eq": sp.Equality,
|
|
56
|
+
f"{{{mathml_ns}}}neq": sp.Unequality,
|
|
57
|
+
f"{{{mathml_ns}}}lt": sp.StrictLessThan,
|
|
58
|
+
f"{{{mathml_ns}}}gt": sp.StrictGreaterThan,
|
|
59
|
+
f"{{{mathml_ns}}}geq": sp.GreaterThan,
|
|
60
|
+
f"{{{mathml_ns}}}leq": sp.LessThan,
|
|
61
|
+
f"{{{mathml_ns}}}max": sp.Max,
|
|
62
|
+
f"{{{mathml_ns}}}min": sp.Min,
|
|
63
|
+
f"{{{mathml_ns}}}abs": sp.Abs,
|
|
64
|
+
f"{{{mathml_ns}}}exp": sp.exp,
|
|
65
|
+
f"{{{mathml_ns}}}ceiling": sp.ceiling,
|
|
66
|
+
f"{{{mathml_ns}}}floor": sp.floor,
|
|
67
|
+
f"{{{mathml_ns}}}factorial": sp.factorial,
|
|
68
|
+
f"{{{mathml_ns}}}ln": sp.log,
|
|
69
|
+
f"{{{mathml_ns}}}not": sp.Not,
|
|
70
|
+
f"{{{mathml_ns}}}rem": sp.Mod,
|
|
71
|
+
f"{{{mathml_ns}}}implies": sp.Implies,
|
|
72
|
+
**mathml_op_sympy_trigonometric,
|
|
73
|
+
**mathml_op_sympy_boolean,
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
# unary functions
|
|
77
|
+
unary = {
|
|
78
|
+
f"{{{mathml_ns}}}plus",
|
|
79
|
+
f"{{{mathml_ns}}}minus",
|
|
80
|
+
f"{{{mathml_ns}}}times",
|
|
81
|
+
*mathml_op_sympy_boolean,
|
|
82
|
+
f"{{{mathml_ns}}}abs",
|
|
83
|
+
f"{{{mathml_ns}}}exp",
|
|
84
|
+
f"{{{mathml_ns}}}ceiling",
|
|
85
|
+
f"{{{mathml_ns}}}floor",
|
|
86
|
+
f"{{{mathml_ns}}}factorial",
|
|
87
|
+
f"{{{mathml_ns}}}ln",
|
|
88
|
+
f"{{{mathml_ns}}}not",
|
|
89
|
+
f"{{{mathml_ns}}}min",
|
|
90
|
+
f"{{{mathml_ns}}}max",
|
|
91
|
+
f"{{{mathml_ns}}}root",
|
|
92
|
+
*mathml_op_sympy_trigonometric
|
|
93
|
+
}
|
|
94
|
+
# n-ary functions
|
|
95
|
+
n_ary = {
|
|
96
|
+
f"{{{mathml_ns}}}times",
|
|
97
|
+
f"{{{mathml_ns}}}plus",
|
|
98
|
+
*mathml_op_sympy_boolean,
|
|
99
|
+
f"{{{mathml_ns}}}lt",
|
|
100
|
+
f"{{{mathml_ns}}}gt",
|
|
101
|
+
f"{{{mathml_ns}}}geq",
|
|
102
|
+
f"{{{mathml_ns}}}leq",
|
|
103
|
+
f"{{{mathml_ns}}}eq",
|
|
104
|
+
f"{{{mathml_ns}}}min",
|
|
105
|
+
f"{{{mathml_ns}}}max",
|
|
106
|
+
}
|
|
107
|
+
# MathML-defined constants
|
|
108
|
+
constants = {
|
|
109
|
+
f"{{{mathml_ns}}}exponentiale": sp.E,
|
|
110
|
+
f"{{{mathml_ns}}}true": BooleanTrue(),
|
|
111
|
+
f"{{{mathml_ns}}}false": BooleanFalse(),
|
|
112
|
+
f"{{{mathml_ns}}}notanumber": sp.Float("nan"),
|
|
113
|
+
f"{{{mathml_ns}}}pi": sp.pi,
|
|
114
|
+
f"{{{mathml_ns}}}infinity": sp.Float("inf"),
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
class SBMLMathMLParser:
|
|
119
|
+
"""MathML parser for sympy, restricted to the SBML subset of MathML 2.0
|
|
120
|
+
|
|
121
|
+
SBML spec:
|
|
122
|
+
https://raw.githubusercontent.com/combine-org/combine-specifications/main/specifications/files/sbml.level-3.version-2.core.release-2.pdf
|
|
123
|
+
section 3.4
|
|
124
|
+
"""
|
|
125
|
+
|
|
126
|
+
def __init__(self, ureg: UnitRegistry = None):
|
|
127
|
+
self.ureg = ureg or _ureg or UnitRegistry()
|
|
128
|
+
# TODO configurable version
|
|
129
|
+
# TODO {prefix=>url}
|
|
130
|
+
self.sbml_core_ns = \
|
|
131
|
+
'http://www.sbml.org/sbml/level3/version2/core'
|
|
132
|
+
self.sbml_multi_ns = \
|
|
133
|
+
'http://www.sbml.org/sbml/level3/version1/multi/version1'
|
|
134
|
+
|
|
135
|
+
def parse_file(self, file_like) -> sp.Expr:
|
|
136
|
+
element_tree = etree.parse(file_like)
|
|
137
|
+
for element in element_tree.iter():
|
|
138
|
+
if element.tag == f"{{{mathml_ns}}}math":
|
|
139
|
+
continue
|
|
140
|
+
|
|
141
|
+
return self._parse_element(element)
|
|
142
|
+
|
|
143
|
+
def parse_str(self, mathml: str):
|
|
144
|
+
# (fragile) workaround for libsbml dropping xmlns declarations for
|
|
145
|
+
# namespaces other than 'sbml'
|
|
146
|
+
if "multi:" in mathml and 'xmlns:multi' not in mathml:
|
|
147
|
+
math_element = '<math xmlns="http://www.w3.org/1998/Math/MathML"'
|
|
148
|
+
mathml = mathml.replace(
|
|
149
|
+
math_element,
|
|
150
|
+
f'{math_element} xmlns:multi="{self.sbml_multi_ns}"'
|
|
151
|
+
)
|
|
152
|
+
# end
|
|
153
|
+
|
|
154
|
+
return self.parse_file(file_like=BytesIO(mathml.encode()))
|
|
155
|
+
|
|
156
|
+
def _parse_element(self, element: etree._Element) -> sp.Expr:
|
|
157
|
+
mathml_prefix = f"{{{mathml_ns}}}"
|
|
158
|
+
if not element.tag.startswith(mathml_prefix):
|
|
159
|
+
raise AssertionError(element.tag)
|
|
160
|
+
|
|
161
|
+
stripped_tag = element.tag[len(mathml_prefix):]
|
|
162
|
+
|
|
163
|
+
handler = f"handle_{stripped_tag}"
|
|
164
|
+
if handler := getattr(self, handler, None):
|
|
165
|
+
try:
|
|
166
|
+
return handler(element)
|
|
167
|
+
except NotImplementedError:
|
|
168
|
+
raise
|
|
169
|
+
except Exception as e:
|
|
170
|
+
raise ValueError(
|
|
171
|
+
f"Failed parsing:\n{etree.tostring(element).decode()}"
|
|
172
|
+
) from e
|
|
173
|
+
with contextlib.suppress(KeyError):
|
|
174
|
+
return constants[element.tag]
|
|
175
|
+
|
|
176
|
+
raise NotImplementedError(f"Unhandled element: {element.tag}.")
|
|
177
|
+
|
|
178
|
+
def handle_apply(self, element: etree._Element) -> sp.Expr:
|
|
179
|
+
"""Handle <apply>"""
|
|
180
|
+
operator, *operands = element
|
|
181
|
+
sym_operands = list(map(self._parse_element, operands))
|
|
182
|
+
|
|
183
|
+
# TODO cleanup; doesn't check properly if compatible with 2 args
|
|
184
|
+
if operator.tag not in (f"{{{mathml_ns}}}csymbol",
|
|
185
|
+
f"{{{mathml_ns}}}ci") \
|
|
186
|
+
and (len(operands) == 1 and operator.tag not in unary
|
|
187
|
+
or len(operands) > 2 and operator.tag not in n_ary):
|
|
188
|
+
raise AssertionError(
|
|
189
|
+
f"Unknown arity for {operator.tag} ({operands}"
|
|
190
|
+
)
|
|
191
|
+
|
|
192
|
+
if operator.tag.startswith(f"{{{mathml_ns}}}"):
|
|
193
|
+
stripped_tag = operator.tag[len(f"{{{mathml_ns}}}"):]
|
|
194
|
+
if len(operands) == 1 \
|
|
195
|
+
and stripped_tag in {'plus', 'times', 'and', 'or',
|
|
196
|
+
'xor', 'min', 'max'}:
|
|
197
|
+
return sym_operands[0]
|
|
198
|
+
|
|
199
|
+
if stripped_tag in ("gt", "lt", "leq", "geq", "eq") \
|
|
200
|
+
and len(operands) >= 3:
|
|
201
|
+
# n-ary relational operators:
|
|
202
|
+
# a < b < c cannot directory be represented in sympy.
|
|
203
|
+
# either change to `a < b and b < c`, to be sympy-evaluatable,
|
|
204
|
+
# or to Function('MathML_Lt')(a, b, c), which will cycle
|
|
205
|
+
# (although potentially collide with other functions with
|
|
206
|
+
# that name), but which cannot be evaluated in sympy.
|
|
207
|
+
# The Function-approach won't work when used in piecewise
|
|
208
|
+
# -> "Second argument must be a Boolean, not `lt`"
|
|
209
|
+
# Therefore, chain expressions with `and`.
|
|
210
|
+
sym_operator = mathml_op_sympy[operator.tag]
|
|
211
|
+
expr = True
|
|
212
|
+
for i in range(len(sym_operands) - 1):
|
|
213
|
+
expr = sp.And(
|
|
214
|
+
expr, sym_operator(sym_operands[i],
|
|
215
|
+
sym_operands[i + 1])
|
|
216
|
+
)
|
|
217
|
+
return expr
|
|
218
|
+
|
|
219
|
+
# TODO: need to handle boolean->{int,float} conversion via
|
|
220
|
+
# `Piecewise((1, expr),(0,True))`
|
|
221
|
+
# {int,float} -> bool
|
|
222
|
+
# `Piecewise((True, expr != 0),(False,True))`
|
|
223
|
+
# as sympy doesn't do that automatically
|
|
224
|
+
if operator.tag not in mathml_op_sympy_boolean:
|
|
225
|
+
sym_operands = list(map(_bool2num, sym_operands))
|
|
226
|
+
|
|
227
|
+
with contextlib.suppress(KeyError):
|
|
228
|
+
return mathml_op_sympy[operator.tag](*sym_operands)
|
|
229
|
+
|
|
230
|
+
if operator.tag == f"{{{mathml_ns}}}divide":
|
|
231
|
+
assert len(sym_operands) == 2
|
|
232
|
+
return sym_operands[0] / sym_operands[1]
|
|
233
|
+
|
|
234
|
+
if operator.tag == f"{{{mathml_ns}}}plus":
|
|
235
|
+
# note: unary version is handled above
|
|
236
|
+
# return sp.Add(*sym_operands)
|
|
237
|
+
return reduce(operators.add, sym_operands, sp.Integer(0))
|
|
238
|
+
|
|
239
|
+
if operator.tag == f"{{{mathml_ns}}}minus":
|
|
240
|
+
if len(sym_operands) == 2:
|
|
241
|
+
return sym_operands[0] - sym_operands[1]
|
|
242
|
+
if len(sym_operands) == 1:
|
|
243
|
+
return -sym_operands[0]
|
|
244
|
+
raise AssertionError(list(element))
|
|
245
|
+
|
|
246
|
+
if operator.tag == f"{{{mathml_ns}}}root":
|
|
247
|
+
assert len(sym_operands) in {1, 2}
|
|
248
|
+
if len(sym_operands) == 1:
|
|
249
|
+
# defaults to sqrt
|
|
250
|
+
degree = 2
|
|
251
|
+
else:
|
|
252
|
+
degree = sym_operands[0]
|
|
253
|
+
assert operands[0].tag == f"{{{mathml_ns}}}degree"
|
|
254
|
+
|
|
255
|
+
return sym_operands[-1] ** (1 / degree)
|
|
256
|
+
|
|
257
|
+
if operator.tag == f"{{{mathml_ns}}}log":
|
|
258
|
+
assert len(operands) == 2
|
|
259
|
+
assert operands[0].tag == f"{{{mathml_ns}}}logbase"
|
|
260
|
+
assert len(operands[0]) == 1
|
|
261
|
+
base, x = sym_operands
|
|
262
|
+
# won't cycle - will be transformed to ``log(x)/log(base)``
|
|
263
|
+
return sp.log(x, base)
|
|
264
|
+
|
|
265
|
+
if operator.tag == f"{{{mathml_ns}}}quotient":
|
|
266
|
+
# there is no direct correspondence for integer division in sympy,
|
|
267
|
+
# so we use modulo instead. this won't cycle.
|
|
268
|
+
# a // b = (a - a mod b) / b
|
|
269
|
+
assert len(operands) == 2
|
|
270
|
+
a, b = sym_operands
|
|
271
|
+
return (a - a % b) / b
|
|
272
|
+
|
|
273
|
+
if operator.tag == f"{{{mathml_ns}}}csymbol":
|
|
274
|
+
# TODO store definitionURL somewhere?
|
|
275
|
+
# TODO need to be able to distinguish between lambdas referenced
|
|
276
|
+
# through ci and functions from csymbols
|
|
277
|
+
assert operator.attrib['encoding'] == "text"
|
|
278
|
+
return sp.Function(operator.text.strip())(*sym_operands)
|
|
279
|
+
|
|
280
|
+
if operator.tag == f"{{{mathml_ns}}}ci":
|
|
281
|
+
assert not operator.attrib
|
|
282
|
+
return sp.Function(operator.text.strip())(*sym_operands)
|
|
283
|
+
|
|
284
|
+
raise NotImplementedError(f"Unsupported operator {operator.tag}.")
|
|
285
|
+
|
|
286
|
+
def handle_ci(self, element: etree._Element) -> sp.Expr:
|
|
287
|
+
"""Handle identifiers."""
|
|
288
|
+
handled_attrs = {
|
|
289
|
+
# TODO: remove after fixing xmlns in model
|
|
290
|
+
'multi:representationType',
|
|
291
|
+
'multi:speciesReference',
|
|
292
|
+
f'{{{self.sbml_multi_ns}}}representationType',
|
|
293
|
+
f'{{{self.sbml_multi_ns}}}speciesReference',
|
|
294
|
+
}
|
|
295
|
+
if unhandled_attrs := (set(element.attrib.keys()) - handled_attrs):
|
|
296
|
+
raise NotImplementedError(
|
|
297
|
+
f"Unhandled <ci> attributes: {unhandled_attrs}")
|
|
298
|
+
|
|
299
|
+
representation_type = element.attrib.get(
|
|
300
|
+
f'{{{self.sbml_multi_ns}}}representationType', None) \
|
|
301
|
+
or element.attrib.get('multi:representationType', None)
|
|
302
|
+
species_reference = element.attrib.get(
|
|
303
|
+
f'{{{self.sbml_multi_ns}}}speciesReference', None) \
|
|
304
|
+
or element.attrib.get('multi:speciesReference',
|
|
305
|
+
None)
|
|
306
|
+
symbol_name = element.text.strip()
|
|
307
|
+
if representation_type or species_reference:
|
|
308
|
+
return SpeciesSymbol(
|
|
309
|
+
name=symbol_name,
|
|
310
|
+
representation_type=representation_type,
|
|
311
|
+
species_reference=species_reference,
|
|
312
|
+
)
|
|
313
|
+
return sp.Symbol(symbol_name)
|
|
314
|
+
|
|
315
|
+
def handle_cn(self, element: etree._Element) -> sp.Expr:
|
|
316
|
+
"""Handle numbers."""
|
|
317
|
+
handled_attrs = {
|
|
318
|
+
'type',
|
|
319
|
+
f'{{{self.sbml_core_ns}}}units',
|
|
320
|
+
}
|
|
321
|
+
if unhandled_attrs := (set(element.attrib.keys()) - handled_attrs):
|
|
322
|
+
raise NotImplementedError(
|
|
323
|
+
f"Unhandled <cn> attributes: {unhandled_attrs}")
|
|
324
|
+
dtype = element.attrib.get('type', 'real')
|
|
325
|
+
converter = {
|
|
326
|
+
'real':
|
|
327
|
+
lambda element: sp.Float(element.text),
|
|
328
|
+
'integer':
|
|
329
|
+
lambda element: sp.Integer(element.text),
|
|
330
|
+
'rational':
|
|
331
|
+
lambda element: sp.Rational(element.text, element[0].tail),
|
|
332
|
+
'e-notation':
|
|
333
|
+
# this won't cycle. we don't have a corresponding
|
|
334
|
+
# representation in sympy
|
|
335
|
+
lambda element: sp.Float(
|
|
336
|
+
float(element.text) * 10 ** int(element[0].tail)
|
|
337
|
+
),
|
|
338
|
+
}.get(dtype)
|
|
339
|
+
if not converter:
|
|
340
|
+
raise NotImplementedError(f"Unhandled type: {dtype}")
|
|
341
|
+
obj = converter(element)
|
|
342
|
+
|
|
343
|
+
if units := element.attrib.get(f'{{{self.sbml_core_ns}}}units', None):
|
|
344
|
+
if units not in self.ureg:
|
|
345
|
+
# TODO fixme: replace rhs by base units
|
|
346
|
+
# this requires access to the underlying SBML model to access
|
|
347
|
+
# unit definitions. they should be parsed during __init__.
|
|
348
|
+
# base units defined in SBML can be handled without a model,
|
|
349
|
+
# as they are not allowed to be redefined (are they?).
|
|
350
|
+
# should start from an empty UnitRegistry, as sbml could
|
|
351
|
+
# redefine any (non-base?)unit to whatever.
|
|
352
|
+
self.ureg.define(f"{units} = {units}")
|
|
353
|
+
# TODO pint.Quantitiy causes issues with sympy functions:
|
|
354
|
+
# https://docs.sympy.org/latest/explanation/active-deprecations.html#non-expr-args-deprecated
|
|
355
|
+
return self.ureg.Quantity(obj, units)
|
|
356
|
+
return obj
|
|
357
|
+
|
|
358
|
+
def handle_piecewise(self, element: etree._Element) -> sp.Expr:
|
|
359
|
+
expr_cond_pairs = []
|
|
360
|
+
for e in element:
|
|
361
|
+
# TODO: cannot currently handle functions as condition-arguments.
|
|
362
|
+
# they need to be derived sympy.BooleanFunction
|
|
363
|
+
if e.tag == f"{{{mathml_ns}}}piece":
|
|
364
|
+
assert len(e) == 2
|
|
365
|
+
cond = self._parse_element(e[1])
|
|
366
|
+
if not isinstance(cond, Boolean):
|
|
367
|
+
raise NotImplementedError(
|
|
368
|
+
"Cannot handle non-boolean piecewise conditions: "
|
|
369
|
+
f"{cond}"
|
|
370
|
+
)
|
|
371
|
+
expr_cond_pairs.append((self._parse_element(e[0]), cond), )
|
|
372
|
+
elif e.tag == f"{{{mathml_ns}}}otherwise":
|
|
373
|
+
# may occur only as last condition
|
|
374
|
+
assert e is element[-1]
|
|
375
|
+
assert len(e) == 1
|
|
376
|
+
expr_cond_pairs.append((self._parse_element(e[0]), True), )
|
|
377
|
+
else:
|
|
378
|
+
raise AssertionError(e.tag)
|
|
379
|
+
return sp.Piecewise(*expr_cond_pairs)
|
|
380
|
+
|
|
381
|
+
def handle_lambda(self, element: etree._Element) -> sp.Expr:
|
|
382
|
+
# collect arguments / bound variables
|
|
383
|
+
args = []
|
|
384
|
+
for e in element[:-1]:
|
|
385
|
+
assert e.tag == f"{{{mathml_ns}}}bvar"
|
|
386
|
+
assert len(e) == 1
|
|
387
|
+
args.append(self._parse_element(e[0]))
|
|
388
|
+
|
|
389
|
+
rhs = self._parse_element(element[-1])
|
|
390
|
+
return sp.Lambda(tuple(args), rhs)
|
|
391
|
+
|
|
392
|
+
def handle_degree(self, element: etree._Element) -> sp.Expr:
|
|
393
|
+
assert len(element) == 1
|
|
394
|
+
return self._parse_element(element[0])
|
|
395
|
+
|
|
396
|
+
def handle_logbase(self, element: etree._Element) -> sp.Expr:
|
|
397
|
+
assert len(element) == 1
|
|
398
|
+
return self._parse_element(element[0])
|
|
399
|
+
|
|
400
|
+
def handle_csymbol(self, element: etree._Element) -> sp.Expr:
|
|
401
|
+
assert element.attrib['encoding'] == "text"
|
|
402
|
+
return sp.Dummy(element.text.strip())
|
|
403
|
+
|
|
404
|
+
|
|
405
|
+
def _bool2num(x):
|
|
406
|
+
if isinstance(x, BooleanFalse):
|
|
407
|
+
return sp.Integer(0)
|
|
408
|
+
if isinstance(x, BooleanTrue):
|
|
409
|
+
return sp.Integer(1)
|
|
410
|
+
return x
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
"""Convenience functions for libsbml core"""
|
|
2
|
+
from numbers import Number
|
|
3
|
+
|
|
4
|
+
import sympy as sp
|
|
5
|
+
from sympy.printing.mathml import MathMLContentPrinter
|
|
6
|
+
|
|
7
|
+
from .species_symbol import SpeciesSymbol
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class MyMathMLContentPrinter(MathMLContentPrinter):
|
|
11
|
+
"""MathML printer
|
|
12
|
+
|
|
13
|
+
* assumes all constants are dimensionless
|
|
14
|
+
"""
|
|
15
|
+
def __init__(self, *args, **kwargs):
|
|
16
|
+
super().__init__(*args, **kwargs)
|
|
17
|
+
|
|
18
|
+
# TODO don't hardcode version / level
|
|
19
|
+
self.mathml_ns = 'xmlns="http://www.w3.org/1998/Math/MathML"'
|
|
20
|
+
self.sbml_ns = 'xmlns:sbml="http://www.sbml.org/sbml/level3/version2/core"'
|
|
21
|
+
self.multi_ns = 'xmlns:multi="http://www.sbml.org/sbml/level3/version1/multi/version1"'
|
|
22
|
+
|
|
23
|
+
def _print_Symbol(self, sym):
|
|
24
|
+
"""
|
|
25
|
+
Print Symbol (<ci>)
|
|
26
|
+
|
|
27
|
+
Skip MathML presentation layer, which is not part of the SBML MathML
|
|
28
|
+
subset.
|
|
29
|
+
"""
|
|
30
|
+
ci = self.dom.createElement(self.mathml_tag(sym))
|
|
31
|
+
ci.appendChild(self.dom.createTextNode(sym.name))
|
|
32
|
+
return ci
|
|
33
|
+
|
|
34
|
+
def _print_SpeciesSymbol(self, sym: SpeciesSymbol):
|
|
35
|
+
ci = self._print_Symbol(sym)
|
|
36
|
+
if sym.representation_type:
|
|
37
|
+
# TODO should <math> should include multi-ns
|
|
38
|
+
ci.setAttribute("multi:representationType",
|
|
39
|
+
sym.representation_type)
|
|
40
|
+
if sym.species_reference:
|
|
41
|
+
ci.setAttribute("multi:speciesReference",
|
|
42
|
+
sym.species_reference)
|
|
43
|
+
return ci
|
|
44
|
+
|
|
45
|
+
def doprint(self, expr, with_prolog=True, with_math=True):
|
|
46
|
+
if isinstance(expr, float):
|
|
47
|
+
expr = sp.Float(expr)
|
|
48
|
+
try:
|
|
49
|
+
mathml = super().doprint(expr)
|
|
50
|
+
except Exception as e:
|
|
51
|
+
raise ValueError(f"MathML printing failed for {expr}") from e
|
|
52
|
+
|
|
53
|
+
if not with_math:
|
|
54
|
+
return mathml
|
|
55
|
+
|
|
56
|
+
prolog = '<?xml version="1.0" encoding="UTF-8"?>\n' \
|
|
57
|
+
if with_prolog else ""
|
|
58
|
+
|
|
59
|
+
# TODO: only include sbml_ns / multi_ns where required
|
|
60
|
+
return (
|
|
61
|
+
f'{prolog}<math {self.mathml_ns} {self.sbml_ns} {self.multi_ns}>\n'
|
|
62
|
+
f'{mathml}</math>'
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
def _print_Number(self, e):
|
|
66
|
+
res = super()._print_int(e)
|
|
67
|
+
res.setAttribute('sbml:units', 'dimensionless')
|
|
68
|
+
return res
|
|
69
|
+
|
|
70
|
+
def _print_Rational(self, e):
|
|
71
|
+
res = super()._print_int(e)
|
|
72
|
+
res.setAttribute('sbml:units', 'dimensionless')
|
|
73
|
+
return res
|
|
74
|
+
|
|
75
|
+
def _print_int(self, e):
|
|
76
|
+
res = super()._print_int(e)
|
|
77
|
+
res.setAttribute('sbml:units', 'dimensionless')
|
|
78
|
+
return res
|
|
79
|
+
|
|
80
|
+
def _print_Float(self, e):
|
|
81
|
+
res = super()._print_Float(e)
|
|
82
|
+
res.setAttribute('sbml:units', 'dimensionless')
|
|
83
|
+
return res
|
|
84
|
+
|
|
85
|
+
def _print_One(self, e):
|
|
86
|
+
res = super()._print_int(e)
|
|
87
|
+
res.setAttribute('sbml:units', 'dimensionless')
|
|
88
|
+
return res
|
|
89
|
+
|
|
90
|
+
def _print_Quantity(self, e):
|
|
91
|
+
res = self._print(e.m)
|
|
92
|
+
if isinstance(e.m, Number):
|
|
93
|
+
# TODO this unit may not exist and might have to be created
|
|
94
|
+
# TODO if Quantities are used in sympy expressions, they might
|
|
95
|
+
# units might get shuffled around and end up <apply>. In this case
|
|
96
|
+
# we skip settings units for now.
|
|
97
|
+
res.setAttribute('sbml:units', str(e.u))
|
|
98
|
+
return res
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
"""SBML MathML related functionality"""
|
|
2
|
+
from typing import Literal, Optional
|
|
3
|
+
|
|
4
|
+
import sympy as sp
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class SpeciesSymbol(sp.Dummy):
|
|
8
|
+
"""
|
|
9
|
+
Represents a <ci> element containing a species.
|
|
10
|
+
|
|
11
|
+
Represents e.g.:
|
|
12
|
+
``<ci multi:representationType="sum"> bla </ci>``
|
|
13
|
+
``<ci multi:speciesReference="refS"> S </ci>``
|
|
14
|
+
(see SBML multi specs 3.26)
|
|
15
|
+
|
|
16
|
+
Subclassed from sympy.Dummy to avoid caching issues, due to using the same
|
|
17
|
+
name but with different meanings.
|
|
18
|
+
|
|
19
|
+
representation_type: SBML-multi spec 3.26.2
|
|
20
|
+
species_reference: SBML-multi spec 3.26.1. ID of a species reference in the
|
|
21
|
+
same reaction.
|
|
22
|
+
"""
|
|
23
|
+
_cache = {}
|
|
24
|
+
|
|
25
|
+
def __new__(
|
|
26
|
+
cls, *args,
|
|
27
|
+
representation_type:
|
|
28
|
+
Optional[Literal['sum', 'numericValue']] = None,
|
|
29
|
+
species_reference: str = None,
|
|
30
|
+
**kwargs
|
|
31
|
+
):
|
|
32
|
+
# Cache instances.
|
|
33
|
+
# If not done: (SpeciesSymbol("A") == SpeciesSymbol("A")) == False
|
|
34
|
+
if not (name := kwargs.get("name")):
|
|
35
|
+
name = args[0]
|
|
36
|
+
cache_key = (name, representation_type, species_reference)
|
|
37
|
+
if cached := cls._cache.get(cache_key):
|
|
38
|
+
return cached
|
|
39
|
+
|
|
40
|
+
obj = super().__new__(cls, *args, **kwargs)
|
|
41
|
+
obj.representation_type = representation_type
|
|
42
|
+
obj.species_reference = species_reference
|
|
43
|
+
|
|
44
|
+
cls._cache[cache_key] = obj
|
|
45
|
+
|
|
46
|
+
return obj
|
|
47
|
+
|
|
48
|
+
def __repr__(self):
|
|
49
|
+
rt = f"representation_type={self.representation_type},"\
|
|
50
|
+
if self.representation_type else ""
|
|
51
|
+
sr = f"species_reference={self.species_reference}," \
|
|
52
|
+
if self.species_reference else ""
|
|
53
|
+
|
|
54
|
+
return f"<{self.name}({rt}{sr})>"
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
Metadata-Version: 2.1
|
|
2
|
+
Name: sbmlmath
|
|
3
|
+
Version: 0.0.0
|
|
4
|
+
Summary: SBML Math <-> SymPy
|
|
5
|
+
Author-email: Daniel Weindl <sci@danielweindl.de>
|
|
6
|
+
License: BSD-3-Clause
|
|
7
|
+
Requires-Python: >=3.10
|
|
8
|
+
Description-Content-Type: text/markdown
|
|
9
|
+
Provides-Extra: test
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
|
|
12
|
+
# sbmlmath - a Python library for handling SBML MathML
|
|
13
|
+
|
|
14
|
+
This is Python library for interconverting [SymPy](https://github.com/sympy/sympy/)
|
|
15
|
+
expressions and [SBML](https://sbml.org/) MathML.
|
|
16
|
+
SBML uses a subset of [MathML](https://www.w3.org/Math/) that this library
|
|
17
|
+
tries to support. This is not (intended to be) a general MathML parser.
|
|
18
|
+
|
|
19
|
+
Main functionality:
|
|
20
|
+
|
|
21
|
+
* sympy -> SBML MathML
|
|
22
|
+
* SBML MathML -> sympy
|
|
23
|
+
* in particular for cases where `sympy.sympify(libsbml.formulaToL3String(...))`
|
|
24
|
+
won't do the job
|
|
25
|
+
* retaining unit annotations and other `<ci>` attributes
|
|
26
|
+
|
|
27
|
+
**NOTE: This is under development and the API is to be considered unstable**
|
|
28
|
+
|
|
29
|
+
## Usage
|
|
30
|
+
|
|
31
|
+
```python
|
|
32
|
+
from sbmlmath import MyMathMLContentPrinter, SBMLMathMLParser
|
|
33
|
+
import sympy as sp
|
|
34
|
+
|
|
35
|
+
sympy_expr = sp.sympify("A ** B + exp(C) * D")
|
|
36
|
+
mathml = MyMathMLContentPrinter().doprint(sympy_expr)
|
|
37
|
+
print(mathml)
|
|
38
|
+
|
|
39
|
+
cycled_sympy = SBMLMathMLParser().parse_str(mathml)
|
|
40
|
+
print(cycled_sympy)
|
|
41
|
+
assert sympy_expr == cycled_sympy
|
|
42
|
+
```
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
.gitignore
|
|
2
|
+
LICENSE
|
|
3
|
+
README.md
|
|
4
|
+
pyproject.toml
|
|
5
|
+
.github/workflows/ci.yaml
|
|
6
|
+
sbmlmath/__init__.py
|
|
7
|
+
sbmlmath/mathml_parser.py
|
|
8
|
+
sbmlmath/mathml_printer.py
|
|
9
|
+
sbmlmath/species_symbol.py
|
|
10
|
+
sbmlmath.egg-info/PKG-INFO
|
|
11
|
+
sbmlmath.egg-info/SOURCES.txt
|
|
12
|
+
sbmlmath.egg-info/dependency_links.txt
|
|
13
|
+
sbmlmath.egg-info/requires.txt
|
|
14
|
+
sbmlmath.egg-info/top_level.txt
|
|
15
|
+
tests/test_mathml_parser_sbml_semantic_suite.py
|
|
16
|
+
tests/test_misc.py
|
|
17
|
+
tests/test_parser.py
|
|
18
|
+
tests/test_printer.py
|
|
19
|
+
tests/test_species_symbol.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
sbmlmath
|
sbmlmath-0.0.0/setup.cfg
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
"""Test MathML parser on SBML semantic cases
|
|
2
|
+
|
|
3
|
+
(test suite at https://github.com/sbmlteam/sbml-test-suite/)
|
|
4
|
+
"""
|
|
5
|
+
import os
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
import libsbml
|
|
9
|
+
import pytest
|
|
10
|
+
|
|
11
|
+
from sbmlmath import SBMLMathMLParser
|
|
12
|
+
|
|
13
|
+
sbml_test_suite_root = os.environ.get('SBML_TEST_SUITE_ROOT', '')
|
|
14
|
+
if not sbml_test_suite_root:
|
|
15
|
+
pytest.skip("$SBML_TEST_SUITE_ROOT not set", allow_module_level=True)
|
|
16
|
+
|
|
17
|
+
cases_root = Path(sbml_test_suite_root, 'cases', 'semantic')
|
|
18
|
+
cases = sorted(cases_root.rglob("*-sbml-l3v2.xml"))
|
|
19
|
+
assert len(cases)
|
|
20
|
+
@pytest.mark.parametrize(
|
|
21
|
+
('sbml_file', ),
|
|
22
|
+
[[file] for file in cases],
|
|
23
|
+
ids=map(lambda x: x.stem, cases)
|
|
24
|
+
)
|
|
25
|
+
def test_sbml(sbml_file):
|
|
26
|
+
print()
|
|
27
|
+
print(sbml_file)
|
|
28
|
+
|
|
29
|
+
# load file, try to parse all math elements
|
|
30
|
+
sbml_reader = libsbml.SBMLReader()
|
|
31
|
+
sbml_doc = sbml_reader.readSBMLFromFile(str(sbml_file))
|
|
32
|
+
sbml_model = sbml_doc.getModel()
|
|
33
|
+
|
|
34
|
+
parser = SBMLMathMLParser()
|
|
35
|
+
for element in sbml_model.getListOfAllElements():
|
|
36
|
+
if (get_math := getattr(element, 'getMath', None)) \
|
|
37
|
+
and (mathml := libsbml.writeMathMLToString(get_math())):
|
|
38
|
+
print(element.getId())
|
|
39
|
+
print(mathml)
|
|
40
|
+
try:
|
|
41
|
+
sym = parser.parse_str(mathml)
|
|
42
|
+
print(sym)
|
|
43
|
+
except NotImplementedError as e:
|
|
44
|
+
pytest.skip(str(e))
|
|
45
|
+
print()
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
from sbmlmath import *
|
|
2
|
+
import pytest
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
@pytest.mark.xfail()
|
|
6
|
+
def test_large_mathml():
|
|
7
|
+
"""On some setups, lxml.etree.iterparse simply truncates long input
|
|
8
|
+
(>2**15 chars); lxml.etree.parse seems to do fine.
|
|
9
|
+
"""
|
|
10
|
+
header = """<?xml version="1.0" encoding="UTF-8"?>
|
|
11
|
+
<math xmlns="http://www.w3.org/1998/Math/MathML" xmlns:sbml="http://www.sbml.org/sbml/level3/version2/core">
|
|
12
|
+
<apply>
|
|
13
|
+
<plus/>
|
|
14
|
+
"""
|
|
15
|
+
center = "<ci> some_long_identifier_whose_name_doesnt_matter</ci>\n"
|
|
16
|
+
footer = "</apply></math>"
|
|
17
|
+
mathml_exp = f"{header}{center * 600}{footer}"
|
|
18
|
+
print(len(mathml_exp))
|
|
19
|
+
assert len(mathml_exp) >= 2**15
|
|
20
|
+
|
|
21
|
+
assert SBMLMathMLParser().parse_str(mathml_exp) \
|
|
22
|
+
== sp.sympify("600 * some_long_identifier_whose_name_doesnt_matter")
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def test_multi_xmlns_works():
|
|
26
|
+
"""Test workaround for mathml handling in libsbml, where some xmlns
|
|
27
|
+
declarations may get dropped."""
|
|
28
|
+
xml = MyMathMLContentPrinter().doprint(
|
|
29
|
+
SpeciesSymbol("a", representation_type="sum")
|
|
30
|
+
)
|
|
31
|
+
assert "xmlns:multi" in xml
|
|
32
|
+
ast_node = libsbml.readMathMLFromString(xml)
|
|
33
|
+
new_xml = libsbml.writeMathMLToString(ast_node)
|
|
34
|
+
assert "xmlns:multi" not in new_xml
|
|
35
|
+
|
|
36
|
+
sym = SBMLMathMLParser().parse_str(new_xml)
|
|
37
|
+
print(sym)
|
|
38
|
+
assert any(
|
|
39
|
+
(isinstance(x, SpeciesSymbol) and x.representation_type == "sum")
|
|
40
|
+
for x in sym.free_symbols
|
|
41
|
+
)
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import libsbml
|
|
2
|
+
import pytest
|
|
3
|
+
import sympy as sp
|
|
4
|
+
from sbmlmath import *
|
|
5
|
+
|
|
6
|
+
# https://sbml.org/software/libsbml/5.18.0/docs/formatted/python-api/classlibsbml_1_1_a_s_t_node.html
|
|
7
|
+
@pytest.mark.parametrize(
|
|
8
|
+
('formula_str',),
|
|
9
|
+
(
|
|
10
|
+
("1 + a",),
|
|
11
|
+
("1.0 + a",),
|
|
12
|
+
("2.5 * x / 12",),
|
|
13
|
+
("(3 + a) * b",),
|
|
14
|
+
("5 - y * 3",),
|
|
15
|
+
("sqrt(y)",),
|
|
16
|
+
("pow(a, b)",),
|
|
17
|
+
("-a",),
|
|
18
|
+
("-a - b",),
|
|
19
|
+
# ("log(a) + log(x, y)",),
|
|
20
|
+
)
|
|
21
|
+
)
|
|
22
|
+
def test_mathmlparser_vs_sympify(formula_str):
|
|
23
|
+
ast_node = libsbml.parseL3Formula(formula_str)
|
|
24
|
+
mathml = libsbml.writeMathMLToString(ast_node)
|
|
25
|
+
parser = SBMLMathMLParser()
|
|
26
|
+
sym_expr = parser.parse_str(mathml)
|
|
27
|
+
print(sym_expr)
|
|
28
|
+
assert sym_expr == sp.sympify(formula_str)
|
|
29
|
+
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
from sbmlmath import SpeciesSymbol, MyMathMLContentPrinter
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
def test_species_symbol_repr_type():
|
|
5
|
+
sym = SpeciesSymbol("A", representation_type="sum")
|
|
6
|
+
mathml = MyMathMLContentPrinter().doprint(sym)
|
|
7
|
+
assert mathml == (
|
|
8
|
+
'<?xml version="1.0" encoding="UTF-8"?>\n'
|
|
9
|
+
'<math xmlns="http://www.w3.org/1998/Math/MathML" '
|
|
10
|
+
'xmlns:sbml="http://www.sbml.org/sbml/level3/version2/core" '
|
|
11
|
+
'xmlns:multi="http://www.sbml.org/sbml/level3/version1/multi/version1">\n'
|
|
12
|
+
'<ci multi:representationType="sum">A</ci>'
|
|
13
|
+
'</math>'
|
|
14
|
+
)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def test_species_symbol_spec_ref():
|
|
18
|
+
sym = SpeciesSymbol("A", species_reference="ref_to_A")
|
|
19
|
+
mathml = MyMathMLContentPrinter().doprint(sym)
|
|
20
|
+
assert mathml == (
|
|
21
|
+
'<?xml version="1.0" encoding="UTF-8"?>\n'
|
|
22
|
+
'<math xmlns="http://www.w3.org/1998/Math/MathML" '
|
|
23
|
+
'xmlns:sbml="http://www.sbml.org/sbml/level3/version2/core" '
|
|
24
|
+
'xmlns:multi="http://www.sbml.org/sbml/level3/version1/multi/version1">\n'
|
|
25
|
+
'<ci multi:speciesReference="ref_to_A">A</ci>'
|
|
26
|
+
'</math>'
|
|
27
|
+
)
|
|
28
|
+
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import libsbml
|
|
2
|
+
import pytest
|
|
3
|
+
import sympy as sp
|
|
4
|
+
from sbmlmath import *
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def test_species_symbol_equality():
|
|
8
|
+
sym1 = SpeciesSymbol("A", representation_type="sum")
|
|
9
|
+
sym2 = SpeciesSymbol("A", species_reference="ref_to_A")
|
|
10
|
+
|
|
11
|
+
# ensure they are not considered equal
|
|
12
|
+
assert sym1 is not sym2
|
|
13
|
+
assert sym1 != sym2
|
|
14
|
+
|
|
15
|
+
# Test caching works
|
|
16
|
+
assert SpeciesSymbol("A", representation_type="sum") \
|
|
17
|
+
== SpeciesSymbol("A", representation_type="sum")
|
|
18
|
+
assert SpeciesSymbol("A", representation_type="sum") \
|
|
19
|
+
is SpeciesSymbol("A", representation_type="sum")
|
|
20
|
+
assert SpeciesSymbol("A") is SpeciesSymbol("A")
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def test_species_symbol_operations():
|
|
24
|
+
sym1 = SpeciesSymbol("A", representation_type="sum")
|
|
25
|
+
sym2 = SpeciesSymbol("A", species_reference="ref_to_A")
|
|
26
|
+
|
|
27
|
+
expr = sym1 + sym2
|
|
28
|
+
mathml = MyMathMLContentPrinter().doprint(expr)
|
|
29
|
+
assert mathml == (
|
|
30
|
+
'<?xml version="1.0" encoding="UTF-8"?>\n'
|
|
31
|
+
'<math xmlns="http://www.w3.org/1998/Math/MathML" '
|
|
32
|
+
'xmlns:sbml="http://www.sbml.org/sbml/level3/version2/core" '
|
|
33
|
+
'xmlns:multi="http://www.sbml.org/sbml/level3/version1/multi/version1">\n'
|
|
34
|
+
'<apply><plus/><ci multi:representationType="sum">A</ci>'
|
|
35
|
+
'<ci multi:speciesReference="ref_to_A">A</ci></apply>'
|
|
36
|
+
'</math>'
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
expr = sym1 * sym2
|
|
40
|
+
mathml = MyMathMLContentPrinter().doprint(expr)
|
|
41
|
+
assert mathml == (
|
|
42
|
+
'<?xml version="1.0" encoding="UTF-8"?>\n'
|
|
43
|
+
'<math xmlns="http://www.w3.org/1998/Math/MathML" '
|
|
44
|
+
'xmlns:sbml="http://www.sbml.org/sbml/level3/version2/core" '
|
|
45
|
+
'xmlns:multi="http://www.sbml.org/sbml/level3/version1/multi/version1">\n'
|
|
46
|
+
'<apply><times/><ci multi:representationType="sum">A</ci>'
|
|
47
|
+
'<ci multi:speciesReference="ref_to_A">A</ci></apply>'
|
|
48
|
+
'</math>'
|
|
49
|
+
)
|
|
50
|
+
|
|
51
|
+
expr = sym1 + sym1 + sym2 * sym2
|
|
52
|
+
mathml = MyMathMLContentPrinter().doprint(expr)
|
|
53
|
+
assert mathml == (
|
|
54
|
+
'<?xml version="1.0" encoding="UTF-8"?>\n'
|
|
55
|
+
'<math xmlns="http://www.w3.org/1998/Math/MathML" '
|
|
56
|
+
'xmlns:sbml="http://www.sbml.org/sbml/level3/version2/core" '
|
|
57
|
+
'xmlns:multi="http://www.sbml.org/sbml/level3/version1/multi/version1">\n'
|
|
58
|
+
'<apply><plus/><apply><times/><cn sbml:units="dimensionless">2</cn>'
|
|
59
|
+
'<ci multi:representationType="sum">A</ci></apply>'
|
|
60
|
+
'<apply><power/><ci multi:speciesReference="ref_to_A">A</ci>'
|
|
61
|
+
'<cn sbml:units="dimensionless">2</cn></apply></apply>'
|
|
62
|
+
'</math>'
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
# check subs() works
|
|
66
|
+
assert (-1 + sym1).subs(sym1, 1) == 0
|
|
67
|
+
|
|
68
|
+
# test mathml -> sympy
|
|
69
|
+
mathml_exp = (
|
|
70
|
+
'<?xml version="1.0" encoding="UTF-8"?>\n'
|
|
71
|
+
'<math xmlns="http://www.w3.org/1998/Math/MathML" '
|
|
72
|
+
'xmlns:sbml="http://www.sbml.org/sbml/level3/version2/core" '
|
|
73
|
+
'xmlns:multi="http://www.sbml.org/sbml/level3/version1/multi/version1">\n'
|
|
74
|
+
'<apply><plus/><apply><times/><cn sbml:units="dimensionless">2</cn>'
|
|
75
|
+
'<ci multi:representationType="sum">A</ci></apply>'
|
|
76
|
+
'<apply><power/><ci multi:speciesReference="ref_to_A">A</ci>'
|
|
77
|
+
'<cn sbml:units="dimensionless">2</cn></apply></apply>'
|
|
78
|
+
'</math>'
|
|
79
|
+
)
|
|
80
|
+
sym_expr = SBMLMathMLParser().parse_str(mathml_exp)
|
|
81
|
+
mathml_act = MyMathMLContentPrinter().doprint(sym_expr)
|
|
82
|
+
|
|
83
|
+
# not an exact match, but close enough, for now
|
|
84
|
+
# TODO - some term re-ordering occurs
|
|
85
|
+
# TODO - integer / double handling is not happening
|
|
86
|
+
assert mathml_act == (
|
|
87
|
+
'<?xml version="1.0" encoding="UTF-8"?>\n'
|
|
88
|
+
'<math xmlns="http://www.w3.org/1998/Math/MathML" '
|
|
89
|
+
'xmlns:sbml="http://www.sbml.org/sbml/level3/version2/core" '
|
|
90
|
+
'xmlns:multi="http://www.sbml.org/sbml/level3/version1/multi/version1">\n'
|
|
91
|
+
'<apply><plus/><apply><power/>'
|
|
92
|
+
'<ci multi:speciesReference="ref_to_A">A</ci>'
|
|
93
|
+
'<cn sbml:units="dimensionless">2.0</cn></apply>'
|
|
94
|
+
'<apply><times/><cn sbml:units="dimensionless">2.0</cn>'
|
|
95
|
+
'<ci multi:representationType="sum">A</ci></apply></apply></math>'
|
|
96
|
+
)
|
|
97
|
+
|