sbmlmath 0.1.1__tar.gz → 0.3.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 (42) hide show
  1. {sbmlmath-0.1.1 → sbmlmath-0.3.0}/.github/workflows/ci.yaml +6 -3
  2. {sbmlmath-0.1.1 → sbmlmath-0.3.0}/.gitignore +1 -0
  3. sbmlmath-0.3.0/.pre-commit-config.yaml +26 -0
  4. sbmlmath-0.3.0/CITATION.cff +25 -0
  5. {sbmlmath-0.1.1/sbmlmath.egg-info → sbmlmath-0.3.0}/PKG-INFO +11 -4
  6. {sbmlmath-0.1.1 → sbmlmath-0.3.0}/README.md +3 -1
  7. sbmlmath-0.3.0/pyproject.toml +55 -0
  8. sbmlmath-0.3.0/sbmlmath/__init__.py +127 -0
  9. sbmlmath-0.3.0/sbmlmath/cfunction.py +156 -0
  10. {sbmlmath-0.1.1 → sbmlmath-0.3.0}/sbmlmath/csymbol.py +22 -3
  11. {sbmlmath-0.1.1 → sbmlmath-0.3.0}/sbmlmath/mathml_parser.py +24 -12
  12. {sbmlmath-0.1.1 → sbmlmath-0.3.0}/sbmlmath/mathml_printer.py +15 -3
  13. {sbmlmath-0.1.1 → sbmlmath-0.3.0}/sbmlmath/species_symbol.py +1 -0
  14. {sbmlmath-0.1.1 → sbmlmath-0.3.0/sbmlmath.egg-info}/PKG-INFO +11 -4
  15. {sbmlmath-0.1.1 → sbmlmath-0.3.0}/sbmlmath.egg-info/SOURCES.txt +1 -0
  16. {sbmlmath-0.1.1 → sbmlmath-0.3.0}/sbmlmath.egg-info/requires.txt +1 -1
  17. sbmlmath-0.3.0/tests/test_csymbol.py +63 -0
  18. {sbmlmath-0.1.1 → sbmlmath-0.3.0}/tests/test_mathml_parser_sbml_semantic_suite.py +5 -2
  19. {sbmlmath-0.1.1 → sbmlmath-0.3.0}/tests/test_misc.py +24 -3
  20. {sbmlmath-0.1.1 → sbmlmath-0.3.0}/tests/test_species_symbol.py +3 -1
  21. sbmlmath-0.1.1/.pre-commit-config.yaml +0 -25
  22. sbmlmath-0.1.1/pyproject.toml +0 -29
  23. sbmlmath-0.1.1/sbmlmath/__init__.py +0 -70
  24. sbmlmath-0.1.1/sbmlmath/cfunction.py +0 -61
  25. sbmlmath-0.1.1/tests/test_csymbol.py +0 -13
  26. {sbmlmath-0.1.1 → sbmlmath-0.3.0}/.github/dependabot.yml +0 -0
  27. {sbmlmath-0.1.1 → sbmlmath-0.3.0}/.github/workflows/deploy_release.yaml +0 -0
  28. {sbmlmath-0.1.1 → sbmlmath-0.3.0}/.readthedocs.yml +0 -0
  29. {sbmlmath-0.1.1 → sbmlmath-0.3.0}/LICENSE +0 -0
  30. {sbmlmath-0.1.1 → sbmlmath-0.3.0}/doc/.gitignore +0 -0
  31. {sbmlmath-0.1.1 → sbmlmath-0.3.0}/doc/Makefile +0 -0
  32. {sbmlmath-0.1.1 → sbmlmath-0.3.0}/doc/about.rst +0 -0
  33. {sbmlmath-0.1.1 → sbmlmath-0.3.0}/doc/api.rst +0 -0
  34. {sbmlmath-0.1.1 → sbmlmath-0.3.0}/doc/conf.py +0 -0
  35. {sbmlmath-0.1.1 → sbmlmath-0.3.0}/doc/index.rst +0 -0
  36. {sbmlmath-0.1.1 → sbmlmath-0.3.0}/doc/make.bat +0 -0
  37. {sbmlmath-0.1.1 → sbmlmath-0.3.0}/doc/rtd_requirements.txt +0 -0
  38. {sbmlmath-0.1.1 → sbmlmath-0.3.0}/sbmlmath.egg-info/dependency_links.txt +0 -0
  39. {sbmlmath-0.1.1 → sbmlmath-0.3.0}/sbmlmath.egg-info/top_level.txt +0 -0
  40. {sbmlmath-0.1.1 → sbmlmath-0.3.0}/setup.cfg +0 -0
  41. {sbmlmath-0.1.1 → sbmlmath-0.3.0}/tests/test_parser.py +0 -0
  42. {sbmlmath-0.1.1 → sbmlmath-0.3.0}/tests/test_printer.py +0 -0
@@ -44,13 +44,16 @@ jobs:
44
44
 
45
45
  - name: Install local packages
46
46
  run: |
47
- pip install --upgrade pip setuptools && pip install .[test]
47
+ python -m pip install --upgrade pip setuptools && python -m pip install .[test]
48
48
 
49
49
  - name: Unit tests
50
50
  env:
51
51
  SBML_TEST_SUITE_ROOT: "${{ github.workspace }}/sbml-test-suite/"
52
52
  run: pytest -vv
53
53
 
54
+ - name: Run pre-commit hooks
55
+ run: pre-commit run --all-files
56
+
54
57
  test-macos:
55
58
  runs-on: macos-latest
56
59
 
@@ -88,7 +91,7 @@ jobs:
88
91
 
89
92
  - name: Install local packages
90
93
  run: |
91
- pip install --upgrade pip setuptools && pip install .[test]
94
+ python -m pip install --upgrade pip setuptools && python -m pip install .[test]
92
95
 
93
96
  - name: Unit tests
94
97
  env:
@@ -132,7 +135,7 @@ jobs:
132
135
 
133
136
  - name: Install local packages
134
137
  run: |
135
- pip install --upgrade pip setuptools && pip install .[test]
138
+ python -m pip install --upgrade pip setuptools && python -m pip install .[test]
136
139
 
137
140
  - name: Unit tests
138
141
  env:
@@ -6,3 +6,4 @@ dist/
6
6
  activate
7
7
  create_venv.sh
8
8
  *deleteme*
9
+ build/
@@ -0,0 +1,26 @@
1
+ # See https://pre-commit.com for more information
2
+ # See https://pre-commit.com/hooks.html for more hooks
3
+ repos:
4
+ - repo: https://github.com/pre-commit/pre-commit-hooks
5
+ rev: v5.0.0
6
+ hooks:
7
+ - id: trailing-whitespace
8
+ - id: end-of-file-fixer
9
+ - id: check-yaml
10
+ - id: check-added-large-files
11
+ - repo: https://github.com/astral-sh/ruff-pre-commit
12
+ # Ruff version.
13
+ rev: v0.6.9
14
+ hooks:
15
+ # Run the linter.
16
+ - id: ruff
17
+ args:
18
+ - --fix
19
+ - --config
20
+ - pyproject.toml
21
+
22
+ # Run the formatter.
23
+ - id: ruff-format
24
+ args:
25
+ - --config
26
+ - pyproject.toml
@@ -0,0 +1,25 @@
1
+ # This CITATION.cff file was generated with cffinit.
2
+ # Visit https://bit.ly/cffinit to generate yours today!
3
+
4
+ cff-version: 1.2.0
5
+ title: sbmlmath
6
+ message: >-
7
+ If you use this software, please cite it using the
8
+ metadata from this file.
9
+ type: software
10
+ authors:
11
+ - given-names: Daniel
12
+ family-names: Weindl
13
+ email: sci@danielweindl.de
14
+ orcid: 'https://orcid.org/0000-0001-9963-6057'
15
+ repository-code: 'https://github.com/dweindl/sbmlmath/'
16
+ url: 'https://sbmlmath.readthedocs.io/'
17
+ abstract: >-
18
+ sbmlmath is a Python package for the interconversion of
19
+ SBML MathML and sympy expressions.
20
+ keywords:
21
+ - SBML
22
+ - SymPy
23
+ - math expressions
24
+ - Python
25
+ license: BSD-3-Clause
@@ -1,13 +1,18 @@
1
- Metadata-Version: 2.1
1
+ Metadata-Version: 2.2
2
2
  Name: sbmlmath
3
- Version: 0.1.1
3
+ Version: 0.3.0
4
4
  Summary: SBML Math <-> SymPy
5
5
  Author-email: Daniel Weindl <sci@danielweindl.de>
6
6
  License: 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/
7
12
  Requires-Python: >=3.9
8
13
  Description-Content-Type: text/markdown
9
14
  License-File: LICENSE
10
- Requires-Dist: python-libsbml
15
+ Requires-Dist: python-libsbml>=5.20.4
11
16
  Requires-Dist: sympy
12
17
  Requires-Dist: pint
13
18
  Requires-Dist: lxml>=4.6.4
@@ -17,7 +22,9 @@ Requires-Dist: pre-commit>=3; extra == "test"
17
22
 
18
23
  # sbmlmath — a Python library for handling SBML MathML
19
24
 
20
- This is a Python library for interconverting [SymPy](https://github.com/sympy/sympy/)
25
+ [![PyPI - Version](https://img.shields.io/pypi/v/sbmlmath)](https://pypi.org/project/sbmlmath/)
26
+
27
+ `sbmlmath` is a Python library for interconverting [SymPy](https://github.com/sympy/sympy/)
21
28
  expressions and [SBML](https://sbml.org/)-MathML.
22
29
  SBML uses a subset of [MathML](https://www.w3.org/Math/) that this library
23
30
  aims to support. This is not (intended to be) a general MathML parser.
@@ -1,6 +1,8 @@
1
1
  # sbmlmath — a Python library for handling SBML MathML
2
2
 
3
- This is a Python library for interconverting [SymPy](https://github.com/sympy/sympy/)
3
+ [![PyPI - Version](https://img.shields.io/pypi/v/sbmlmath)](https://pypi.org/project/sbmlmath/)
4
+
5
+ `sbmlmath` is a Python library for interconverting [SymPy](https://github.com/sympy/sympy/)
4
6
  expressions and [SBML](https://sbml.org/)-MathML.
5
7
  SBML uses a subset of [MathML](https://www.w3.org/Math/) that this library
6
8
  aims to support. This is not (intended to be) a general MathML parser.
@@ -0,0 +1,55 @@
1
+ [build-system]
2
+ requires = ["setuptools>=64", "setuptools-scm>=8"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "sbmlmath"
7
+ dynamic = ["version"]
8
+ authors = [
9
+ {name = "Daniel Weindl", email = "sci@danielweindl.de"},
10
+ ]
11
+ description = "SBML Math <-> SymPy"
12
+ readme = "README.md"
13
+ requires-python = ">=3.9"
14
+ license = {text = "BSD-3-Clause"}
15
+ dependencies = [
16
+ "python-libsbml>=5.20.4",
17
+ "sympy",
18
+ "pint",
19
+ "lxml>=4.6.4",
20
+ ]
21
+
22
+ [project.urls]
23
+ Homepage = "https://github.com/dweindl/sbmlmath"
24
+ Documentation = "https://sbmlmath.readthedocs.io/"
25
+ Repository = "https://github.com/dweindl/sbmlmath.git"
26
+ "Bug Tracker" = "https://github.com/dweindl/sbmlmath/issues"
27
+ PyPI = "https://pypi.org/project/sbmlmath/"
28
+
29
+ [project.optional-dependencies]
30
+ test = ["pytest>=7", "pre-commit>=3"]
31
+
32
+ [tool.setuptools_scm]
33
+
34
+ [tool.ruff]
35
+ line-length = 79
36
+ exclude = ["sbml-test-suite"]
37
+ lint.extend-select = [
38
+ "T", "W", "E", "F", "B", "C", "S", "I", "UP",
39
+ # "D",
40
+ # "ANN",
41
+ ]
42
+ lint.ignore = [
43
+ "S101", # Use of assert detected
44
+ "F405", # star import
45
+ "F403", # star import
46
+ "E501", # Line too long
47
+ ]
48
+ [tool.ruff.lint.per-file-ignores]
49
+ "tests/*" = ["T201"] # print statement
50
+ "sbmlmath/__init__.py" = [
51
+ "F401", # module imported but unused
52
+ "E402", # import not at top of file
53
+ ]
54
+ [tool.pytest.ini_options]
55
+ addopts = "--doctest-modules --ignore=doc/conf.py --ignore=sbml-test-suite"
@@ -0,0 +1,127 @@
1
+ from importlib.metadata import PackageNotFoundError, version
2
+ from typing import Union
3
+
4
+ import libsbml
5
+ import sympy as sp
6
+
7
+ try:
8
+ __version__ = version("sbmlmath")
9
+ except PackageNotFoundError:
10
+ # package is not installed
11
+ pass
12
+
13
+ #: Default SBML level if not specified otherwise.
14
+ _DEFAULT_SBML_LEVEL = 3
15
+ #: Default SBML version if not specified otherwise.
16
+ _DEFAULT_SBML_VERSION = 2
17
+
18
+
19
+ def sympy_to_sbml_math(sp_expr: sp.Expr) -> libsbml.ASTNode:
20
+ """Convert sympy expression to SBML math ASTNode.
21
+
22
+ This function takes a SymPy expression and converts it to an SBML math
23
+ ASTNode.
24
+
25
+ Args:
26
+ sp_expr: The SymPy expression to be converted.
27
+
28
+ Returns:
29
+ The resulting SBML math ASTNode.
30
+
31
+ Raises:
32
+ ValueError:
33
+ If there is an error in converting the math expression.
34
+ """
35
+ mathml = SBMLMathMLPrinter().doprint(sp_expr)
36
+
37
+ if ast_node := libsbml.readMathMLFromString(mathml):
38
+ return ast_node
39
+
40
+ raise ValueError(
41
+ f"Unknown error handling math expression:\n{sp_expr}\n" f"{mathml}"
42
+ )
43
+
44
+
45
+ def sbml_math_to_sympy(
46
+ sbml_obj: Union[libsbml.SBase, libsbml.ASTNode],
47
+ ) -> sp.Expr:
48
+ """Convert SBML MathML to sympy expression.
49
+
50
+ Conversion is done using the default settings of :class:`SBMLMathMLParser`.
51
+
52
+ Args:
53
+ sbml_obj:
54
+ The SBML object to be converted.
55
+ (Either directly the ASTNode or the surrounding SBase object).
56
+ Returns:
57
+ The resulting sympy expression.
58
+ """
59
+ if isinstance(sbml_obj, libsbml.ASTNode):
60
+ ast_node = sbml_obj
61
+ sbml_obj = ast_node.getParentSBMLObject()
62
+ else:
63
+ ast_node = sbml_obj.getMath()
64
+
65
+ level = (
66
+ sbml_obj.getLevel() if sbml_obj is not None else _DEFAULT_SBML_LEVEL
67
+ )
68
+ version = (
69
+ sbml_obj.getVersion()
70
+ if sbml_obj is not None
71
+ else _DEFAULT_SBML_VERSION
72
+ )
73
+ mathml = libsbml.writeMathMLWithNamespaceToString(
74
+ ast_node, libsbml.SBMLNamespaces(level, version)
75
+ )
76
+ return SBMLMathMLParser(sbml_level=level, sbml_version=version).parse_str(
77
+ mathml
78
+ )
79
+
80
+
81
+ def set_math(
82
+ element: libsbml.SBase,
83
+ expr: sp.Expr,
84
+ ) -> None:
85
+ """Set the math expression of an SBML object.
86
+
87
+ Args:
88
+ element:
89
+ The SBML object to set the math expression for.
90
+ expr:
91
+ The sympy expression to set as the math expression.
92
+ """
93
+ mathml = SBMLMathMLPrinter(
94
+ sbml_level=element.getLevel(),
95
+ sbml_version=element.getVersion(),
96
+ ).doprint(expr)
97
+
98
+ if ast_node := libsbml.readMathMLFromString(mathml):
99
+ if element.setMath(ast_node) == libsbml.LIBSBML_OPERATION_SUCCESS:
100
+ return
101
+ sbml_document = element.getSBMLDocument()
102
+ raise ValueError(
103
+ f"Error setting math expression:\n{expr}\n"
104
+ f"{mathml}\n{sbml_document.getErrorLog().toString()}"
105
+ )
106
+ raise ValueError(
107
+ f"Unknown error parsing math expression:\n{expr}\n{mathml}"
108
+ )
109
+
110
+
111
+ from .cfunction import *
112
+ from .csymbol import *
113
+ from .mathml_parser import SBMLMathMLParser
114
+ from .mathml_printer import SBMLMathMLPrinter
115
+ from .species_symbol import SpeciesSymbol
116
+
117
+ __all__ = [
118
+ "set_math",
119
+ "SBMLMathMLParser",
120
+ "SBMLMathMLPrinter",
121
+ "SpeciesSymbol",
122
+ "TimeSymbol",
123
+ "sympy_to_sbml_math",
124
+ "sbml_math_to_sympy",
125
+ *csymbol.__all__,
126
+ *cfunction.__all__,
127
+ ]
@@ -0,0 +1,156 @@
1
+ """Handling of ``<csymbol>`` functions"""
2
+
3
+ from __future__ import annotations
4
+
5
+ from sympy import Number
6
+ from sympy.core.function import UndefinedFunction
7
+
8
+ __all__ = ["CFunction", "delay", "rate_of", "Delay", "RateOf"]
9
+
10
+ DEF_URL_BASE = "http://www.sbml.org/sbml/symbols/"
11
+ DEF_URL_RATE_OF = DEF_URL_BASE + "rateOf"
12
+ DEF_URL_DELAY = DEF_URL_BASE + "delay"
13
+
14
+
15
+ class CFunction(UndefinedFunction):
16
+ """
17
+ Represents ``<csymbol>`` functions.
18
+
19
+ Examples: :func:`rateOf() <rate_of>`, :func:`delay`,
20
+ distributions from the `distrib package
21
+ <https://synonym.caltech.edu/documents/specifications/level-3/version-1/distrib/>`_.
22
+
23
+
24
+ See also https://www.w3.org/TR/MathML2/chapter4.html#contm.deffun.
25
+ """
26
+
27
+ DEFINITION_URL = None
28
+ _cache = {}
29
+ _definition_url_to_derived_class = {}
30
+
31
+ def __new__(
32
+ cls: type[CFunction],
33
+ *args,
34
+ definition_url: str = None,
35
+ encoding: str = "text",
36
+ **kwargs,
37
+ ):
38
+ definition_url = definition_url or cls.DEFINITION_URL
39
+ if definition_url is None:
40
+ raise ValueError("definition_url must be provided")
41
+
42
+ # Cache instances.
43
+ # If not done: (CFunction("A", definition_url="x")
44
+ # == CFunction("A", definition_url="y")) == False
45
+ if not (name := kwargs.get("name")):
46
+ if not len(args):
47
+ raise ValueError("name argument must be provided")
48
+ name = args[0]
49
+
50
+ cache_key = (name, definition_url, encoding)
51
+ if cached := cls._cache.get(cache_key):
52
+ return cached
53
+
54
+ obj = super().__new__(cls, *args, **kwargs)
55
+
56
+ # ensure there are no collisions with super() attributes
57
+ assert not hasattr(obj, "definition_url")
58
+ assert not hasattr(obj, "encoding")
59
+ obj.definition_url = definition_url
60
+ obj.encoding = encoding
61
+ if hasattr(cls, "eval"):
62
+ obj.eval = cls.eval
63
+
64
+ cls._cache[cache_key] = obj
65
+
66
+ return obj
67
+
68
+ def __eq__(self, other):
69
+ if not isinstance(other, CFunction):
70
+ return False
71
+
72
+ # if they represent the same value, they are equal
73
+ return self.definition_url == other.definition_url
74
+
75
+ def __hash__(self):
76
+ return hash(
77
+ (
78
+ self.__class__.__name__,
79
+ self.DEFINITION_URL,
80
+ self.definition_url,
81
+ self.name,
82
+ )
83
+ )
84
+
85
+ @classmethod
86
+ def register_subclass(cls, derived_class: type[CFunction]):
87
+ cls._definition_url_to_derived_class[derived_class.DEFINITION_URL] = (
88
+ derived_class
89
+ )
90
+
91
+
92
+ # Derived classes for specific SBML functions
93
+ class Delay(CFunction):
94
+ """Produces a SBML ``delay()`` function.
95
+
96
+ Usually, it's preferable to use the :func:`delay` function.
97
+ This class can be used if a *delay* function with a different name is
98
+ needed.
99
+
100
+ Examples:
101
+ >>> from sympy.abc import a
102
+ >>> my_delay = Delay("my_delay")
103
+ >>> my_delay(a)
104
+ my_delay(a)
105
+ >>> delay(a) == my_delay(a)
106
+ True
107
+ """
108
+
109
+ DEFINITION_URL = DEF_URL_DELAY
110
+
111
+ def __new__(cls, *args, **kwargs):
112
+ return super().__new__(cls, *args, **kwargs)
113
+
114
+
115
+ CFunction.register_subclass(Delay)
116
+
117
+
118
+ class RateOf(CFunction):
119
+ """Produces a SBML ``rateOf()`` function.
120
+
121
+ Usually, it's preferable to use the :func:`rate_of` function.
122
+ This class can be used if a *rateOf* function with a different name is
123
+ needed.
124
+
125
+ Examples:
126
+ >>> from sympy.abc import a
127
+ >>> my_rate_of = RateOf("my_rate_of")
128
+ >>> my_rate_of(a)
129
+ my_rate_of(a)
130
+ >>> rate_of(a) == my_rate_of(a)
131
+ True
132
+ >>> rate_of(1)
133
+ 0
134
+ """
135
+
136
+ DEFINITION_URL = DEF_URL_RATE_OF
137
+
138
+ def __new__(cls, *args, **kwargs):
139
+ return super().__new__(cls, *args, **kwargs)
140
+
141
+ @classmethod
142
+ def eval(cls, x):
143
+ if isinstance(x, Number):
144
+ # the rate of a constant is 0
145
+ return 0
146
+
147
+
148
+ CFunction.register_subclass(RateOf)
149
+
150
+ # SBML-defined functions
151
+
152
+ #: The SBML ``delay()`` function.
153
+ delay = Delay("delay")
154
+
155
+ #: The SBML ``rateOf()`` function.
156
+ rate_of = RateOf("rateOf")
@@ -1,5 +1,6 @@
1
1
  """Handling of <csymbol> constants"""
2
- from typing import Literal, Optional
2
+
3
+ from __future__ import annotations
3
4
 
4
5
  import sympy as sp
5
6
 
@@ -30,7 +31,9 @@ class CSymbol(sp.Dummy):
30
31
  See also https://www.w3.org/TR/MathML2/chapter4.html#contm.csymbol.
31
32
  """
32
33
 
34
+ DEFINITION_URL = None
33
35
  _cache = {}
36
+ _definition_url_to_derived_class = {}
34
37
 
35
38
  def __new__(
36
39
  cls,
@@ -47,7 +50,12 @@ class CSymbol(sp.Dummy):
47
50
  if cached := cls._cache.get(cache_key):
48
51
  return cached
49
52
 
50
- obj = super().__new__(cls, *args, **kwargs)
53
+ # return the matching subtype, depending on the definition URL
54
+ obj = super().__new__(
55
+ cls._definition_url_to_derived_class.get(definition_url, cls),
56
+ *args,
57
+ **kwargs,
58
+ )
51
59
 
52
60
  # ensure there are no collisions with super() attributes
53
61
  assert not hasattr(obj, "definition_url")
@@ -79,6 +87,12 @@ class CSymbol(sp.Dummy):
79
87
  return SBML_L3V2_AVOGADRO_VALUE
80
88
  return super().__float__()
81
89
 
90
+ @classmethod
91
+ def register_subclass(cls, derived_class: type[CSymbol]):
92
+ cls._definition_url_to_derived_class[derived_class.DEFINITION_URL] = (
93
+ derived_class
94
+ )
95
+
82
96
 
83
97
  class TimeSymbol(CSymbol):
84
98
  """The current internal simulation time.
@@ -92,6 +106,8 @@ class TimeSymbol(CSymbol):
92
106
  name: The name of the symbol.
93
107
  """
94
108
 
109
+ DEFINITION_URL = "http://www.sbml.org/sbml/symbols/time"
110
+
95
111
  def __new__(
96
112
  cls,
97
113
  name: str,
@@ -99,5 +115,8 @@ class TimeSymbol(CSymbol):
99
115
  return super().__new__(
100
116
  cls,
101
117
  name=name,
102
- definition_url="http://www.sbml.org/sbml/symbols/time",
118
+ definition_url=cls.DEFINITION_URL,
103
119
  )
120
+
121
+
122
+ CSymbol.register_subclass(TimeSymbol)
@@ -1,6 +1,8 @@
1
1
  """SBML mathml to sympy."""
2
+
2
3
  import contextlib
3
4
  import operator as operators
5
+ import warnings
4
6
  from functools import reduce
5
7
  from io import BytesIO
6
8
  from typing import Union
@@ -10,6 +12,7 @@ from lxml import etree
10
12
  from pint import UnitRegistry
11
13
  from sympy.logic.boolalg import Boolean, BooleanFalse, BooleanTrue
12
14
 
15
+ from . import _DEFAULT_SBML_LEVEL, _DEFAULT_SBML_VERSION
13
16
  from .cfunction import CFunction
14
17
  from .csymbol import CSymbol
15
18
  from .species_symbol import SpeciesSymbol
@@ -139,8 +142,8 @@ class SBMLMathMLParser:
139
142
 
140
143
  See also: `MathML 2.0 specification <https://www.w3.org/TR/MathML2/>`_.
141
144
 
142
- :param level: SBML level
143
- :param version: SBML version
145
+ :param sbml_level: SBML level
146
+ :param sbml_version: SBML version
144
147
  :param ureg:
145
148
  Optional :class:`pint.UnitRegistry` to use for unit conversion.
146
149
  :param floats_as_rationals:
@@ -159,22 +162,26 @@ class SBMLMathMLParser:
159
162
 
160
163
  def __init__(
161
164
  self,
162
- level: Union[int, str] = 3,
163
- version: Union[int, str] = 2,
165
+ sbml_level: Union[int, str] = _DEFAULT_SBML_LEVEL,
166
+ sbml_version: Union[int, str] = _DEFAULT_SBML_VERSION,
164
167
  ureg: UnitRegistry = None,
165
168
  floats_as_rationals=True,
166
169
  ignore_units=False,
167
170
  symbol_kwargs=None,
168
171
  ):
169
172
  """Constructor"""
173
+ if sbml_level < 3:
174
+ warnings.warn(
175
+ "SBML level < 3 has not been thoroughly tested.",
176
+ UserWarning,
177
+ stacklevel=2,
178
+ )
170
179
  self.ureg = ureg or _ureg or UnitRegistry()
171
- self.sbml_core_ns = (
172
- f"http://www.sbml.org/sbml/level{level}/version{version}/core"
173
- )
180
+ self.sbml_core_ns = f"http://www.sbml.org/sbml/level{sbml_level}/version{sbml_version}/core"
174
181
  # TODO {prefix=>url}
175
182
  self.sbml_multi_ns = (
176
183
  # L3V2 doesn't work
177
- f"http://www.sbml.org/sbml/level{level}/version1/multi/version1"
184
+ f"http://www.sbml.org/sbml/level{sbml_level}/version1/multi/version1"
178
185
  )
179
186
  self.floats_as_rationals = floats_as_rationals
180
187
  self.ignore_units = ignore_units
@@ -191,7 +198,9 @@ class SBMLMathMLParser:
191
198
  and the MathML ``math`` element.
192
199
  :return: The sympy representation of the MathML expression.
193
200
  """
194
- element_tree = etree.parse(file_like)
201
+ # Using `lxml` to parse untrusted data is known to be vulnerable to XML
202
+ # attacks
203
+ element_tree = etree.parse(file_like) # noqa S320
195
204
  for element in element_tree.iter():
196
205
  if element.tag == f"{{{mathml_ns}}}math":
197
206
  continue
@@ -240,7 +249,7 @@ class SBMLMathMLParser:
240
249
 
241
250
  raise NotImplementedError(f"Unhandled element: {element.tag}.")
242
251
 
243
- def handle_apply(self, element: etree._Element) -> sp.Expr:
252
+ def handle_apply(self, element: etree._Element) -> sp.Expr: # noqa C901
244
253
  """Handle <apply>"""
245
254
  operator, *operands = element
246
255
  sym_operands = list(map(self._parse_element, operands))
@@ -289,7 +298,8 @@ class SBMLMathMLParser:
289
298
  expr = True
290
299
  for i in range(len(sym_operands) - 1):
291
300
  expr = sp.And(
292
- expr, sym_operator(sym_operands[i], sym_operands[i + 1])
301
+ expr,
302
+ sym_operator(sym_operands[i], sym_operands[i + 1]),
293
303
  )
294
304
  return expr
295
305
 
@@ -383,7 +393,9 @@ class SBMLMathMLParser:
383
393
  species_reference = element.attrib.get(
384
394
  f"{{{self.sbml_multi_ns}}}speciesReference", None
385
395
  ) or element.attrib.get("multi:speciesReference", None)
386
- symbol_name = self.preprocess_symbol_name(element.text.strip(), element)
396
+ symbol_name = self.preprocess_symbol_name(
397
+ element.text.strip(), element
398
+ )
387
399
  if representation_type or species_reference:
388
400
  return SpeciesSymbol(
389
401
  name=symbol_name,
@@ -1,9 +1,12 @@
1
1
  """Convenience functions for libsbml core"""
2
+
3
+ import warnings
2
4
  from numbers import Number
3
5
 
4
6
  import sympy as sp
5
7
  from sympy.printing.mathml import MathMLContentPrinter
6
8
 
9
+ from . import _DEFAULT_SBML_LEVEL, _DEFAULT_SBML_VERSION
7
10
  from .csymbol import CSymbol
8
11
  from .species_symbol import SpeciesSymbol
9
12
 
@@ -25,8 +28,8 @@ class SBMLMathMLPrinter(MathMLContentPrinter):
25
28
  self,
26
29
  *args,
27
30
  literals_dimensionless=True,
28
- sbml_level: int = 3,
29
- sbml_version: int = 2,
31
+ sbml_level: int = _DEFAULT_SBML_LEVEL,
32
+ sbml_version: int = _DEFAULT_SBML_VERSION,
30
33
  **kwargs,
31
34
  ):
32
35
  """Construct.
@@ -36,6 +39,13 @@ class SBMLMathMLPrinter(MathMLContentPrinter):
36
39
  """
37
40
  super().__init__(*args, **kwargs)
38
41
 
42
+ if sbml_level < 3:
43
+ warnings.warn(
44
+ "SBML level < 3 has not been thoroughly tested.",
45
+ UserWarning,
46
+ stacklevel=2,
47
+ )
48
+
39
49
  self.mathml_ns = 'xmlns="http://www.w3.org/1998/Math/MathML"'
40
50
  self.sbml_ns = f'xmlns:sbml="http://www.sbml.org/sbml/level{sbml_level}/version{sbml_version}/core"'
41
51
  # note: so far, there is no L3V2-multi
@@ -56,7 +66,9 @@ class SBMLMathMLPrinter(MathMLContentPrinter):
56
66
  def _print_SpeciesSymbol(self, sym: SpeciesSymbol):
57
67
  ci = self._print_Symbol(sym)
58
68
  if sym.representation_type:
59
- ci.setAttribute("multi:representationType", sym.representation_type)
69
+ ci.setAttribute(
70
+ "multi:representationType", sym.representation_type
71
+ )
60
72
  if sym.species_reference:
61
73
  ci.setAttribute("multi:speciesReference", sym.species_reference)
62
74
  return ci
@@ -1,4 +1,5 @@
1
1
  """SBML MathML related functionality"""
2
+
2
3
  from typing import Literal, Optional
3
4
 
4
5
  import sympy as sp
@@ -1,13 +1,18 @@
1
- Metadata-Version: 2.1
1
+ Metadata-Version: 2.2
2
2
  Name: sbmlmath
3
- Version: 0.1.1
3
+ Version: 0.3.0
4
4
  Summary: SBML Math <-> SymPy
5
5
  Author-email: Daniel Weindl <sci@danielweindl.de>
6
6
  License: 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/
7
12
  Requires-Python: >=3.9
8
13
  Description-Content-Type: text/markdown
9
14
  License-File: LICENSE
10
- Requires-Dist: python-libsbml
15
+ Requires-Dist: python-libsbml>=5.20.4
11
16
  Requires-Dist: sympy
12
17
  Requires-Dist: pint
13
18
  Requires-Dist: lxml>=4.6.4
@@ -17,7 +22,9 @@ Requires-Dist: pre-commit>=3; extra == "test"
17
22
 
18
23
  # sbmlmath — a Python library for handling SBML MathML
19
24
 
20
- This is a Python library for interconverting [SymPy](https://github.com/sympy/sympy/)
25
+ [![PyPI - Version](https://img.shields.io/pypi/v/sbmlmath)](https://pypi.org/project/sbmlmath/)
26
+
27
+ `sbmlmath` is a Python library for interconverting [SymPy](https://github.com/sympy/sympy/)
21
28
  expressions and [SBML](https://sbml.org/)-MathML.
22
29
  SBML uses a subset of [MathML](https://www.w3.org/Math/) that this library
23
30
  aims to support. This is not (intended to be) a general MathML parser.
@@ -1,6 +1,7 @@
1
1
  .gitignore
2
2
  .pre-commit-config.yaml
3
3
  .readthedocs.yml
4
+ CITATION.cff
4
5
  LICENSE
5
6
  README.md
6
7
  pyproject.toml
@@ -1,4 +1,4 @@
1
- python-libsbml
1
+ python-libsbml>=5.20.4
2
2
  sympy
3
3
  pint
4
4
  lxml>=4.6.4
@@ -0,0 +1,63 @@
1
+ import sympy as sp
2
+ from sympy.core.function import UndefinedFunction
3
+
4
+ from sbmlmath.cfunction import *
5
+ from sbmlmath.cfunction import DEF_URL_DELAY, DEF_URL_RATE_OF
6
+ from sbmlmath.csymbol import *
7
+
8
+
9
+ def test_time_symbol():
10
+ assert TimeSymbol("t") is TimeSymbol("t")
11
+
12
+ assert TimeSymbol("t") == TimeSymbol("time")
13
+ assert TimeSymbol("t") is not TimeSymbol("time")
14
+
15
+ t1, t2 = TimeSymbol("t"), TimeSymbol("time")
16
+ eight_t = t1 + t2 + 3 * t1 + 3 * t2
17
+ # is the result defined?
18
+ assert eight_t in [8 * t1, 8 * t2]
19
+
20
+ # test with a non-cached symbol (i.e. a new name)
21
+ assert isinstance(
22
+ CSymbol(
23
+ "new_name_for_time",
24
+ definition_url=TimeSymbol.DEFINITION_URL,
25
+ ),
26
+ TimeSymbol,
27
+ )
28
+ assert TimeSymbol("new_name_for_time2") == CSymbol(
29
+ "new_name_for_time3",
30
+ definition_url=TimeSymbol.DEFINITION_URL,
31
+ )
32
+
33
+ assert (2 * t1).has(t1) is True
34
+ assert (2 * t1).has(TimeSymbol) is True
35
+ assert (2 * t1).has(CSymbol) is True
36
+ assert (sp.sympify("l * e * e * t")).has(TimeSymbol) is False
37
+
38
+
39
+ def test_cfunction():
40
+ rate_of = CFunction("rateOf", definition_url=DEF_URL_RATE_OF)
41
+ # test that the cache works
42
+ assert rate_of is CFunction("rateOf", definition_url=DEF_URL_RATE_OF)
43
+ # test that definition URL is considered, not only the name
44
+ assert rate_of is not CFunction("rateOf", definition_url=DEF_URL_DELAY)
45
+
46
+ assert rate_of == CFunction("rateOf", definition_url=DEF_URL_RATE_OF)
47
+ assert rate_of != CFunction("rateOf", definition_url=DEF_URL_DELAY)
48
+ assert isinstance(rate_of, CFunction)
49
+ assert isinstance(rate_of, RateOf)
50
+ assert not isinstance(rate_of, delay)
51
+ a, b = sp.symbols("a b")
52
+ assert (rate_of(a) * 4).has(rate_of) is True
53
+ assert (rate_of(a) * 4).has(RateOf("rAteOf")) is True
54
+ assert rate_of(a) == rate_of(a)
55
+ assert rate_of(a) != rate_of(b)
56
+ assert (rate_of(a) * 4).has(RateOf) is False
57
+
58
+ assert UndefinedFunction(rate_of.name) != rate_of
59
+ assert UndefinedFunction(rate_of.name)(a).has(rate_of) is False
60
+
61
+ assert rate_of(1) == 0
62
+ assert rate_of(1, evaluate=False).has(rate_of) is True
63
+ assert rate_of(1, evaluate=False).doit() == 0
@@ -2,6 +2,7 @@
2
2
 
3
3
  (test suite at https://github.com/sbmlteam/sbml-test-suite/)
4
4
  """
5
+
5
6
  import os
6
7
  from pathlib import Path
7
8
 
@@ -15,12 +16,14 @@ if not sbml_test_suite_root:
15
16
  pytest.skip("$SBML_TEST_SUITE_ROOT not set", allow_module_level=True)
16
17
 
17
18
  cases_root = Path(sbml_test_suite_root, "cases", "semantic")
18
- cases = sorted(cases_root.rglob("*-sbml-l3v2.xml"))
19
+ cases = sorted(cases_root.rglob("*-sbml-l3v?.xml"))
19
20
  assert len(cases)
20
21
 
21
22
 
22
23
  @pytest.mark.parametrize(
23
- ("sbml_file",), [[file] for file in cases], ids=map(lambda x: x.stem, cases)
24
+ ("sbml_file",),
25
+ [[file] for file in cases],
26
+ ids=map(lambda x: x.stem, cases), # noqa: C417
24
27
  )
25
28
  def test_sbml(sbml_file):
26
29
  print()
@@ -1,10 +1,27 @@
1
1
  import libsbml
2
- import pytest
3
2
  import sympy as sp
4
3
 
5
4
  from sbmlmath import *
6
5
 
7
6
 
7
+ def test_set_math():
8
+ """Test setting math on SBML objects."""
9
+ # create some model
10
+ doc = libsbml.SBMLDocument(3, 1)
11
+ model = doc.createModel()
12
+ s = model.createSpecies()
13
+ s.setId("s")
14
+ p = model.createParameter()
15
+ p.setId("p")
16
+ ia = model.createInitialAssignment()
17
+ ia.setSymbol("s")
18
+
19
+ # actual test
20
+ expr = sp.sympify("2 * p^2")
21
+ set_math(ia, expr)
22
+ assert expr == sbml_math_to_sympy(ia)
23
+
24
+
8
25
  def test_large_mathml():
9
26
  """
10
27
  lxml.etree.iterparse simply truncates long input (>2**15 chars);
@@ -55,7 +72,9 @@ def test_abs():
55
72
 
56
73
 
57
74
  def test_math_dimensionless():
58
- xml = SBMLMathMLPrinter(literals_dimensionless=False).doprint(sp.Integer(1))
75
+ xml = SBMLMathMLPrinter(literals_dimensionless=False).doprint(
76
+ sp.Integer(1)
77
+ )
59
78
  assert "dimensionless" not in xml
60
79
 
61
80
  xml = SBMLMathMLPrinter(literals_dimensionless=True).doprint(sp.Integer(1))
@@ -152,7 +171,9 @@ def test_integer_overflow():
152
171
  </math>"""
153
172
 
154
173
  i = 2**31 - 1
155
- assert (ast_node := libsbml.readMathMLFromString(get_mathml(i))) is not None
174
+ assert (
175
+ ast_node := libsbml.readMathMLFromString(get_mathml(i))
176
+ ) is not None
156
177
  assert str(i) in libsbml.writeMathMLToString(ast_node)
157
178
 
158
179
  # FIXME: change to assert not None, if that restriction is ever lifted
@@ -75,7 +75,9 @@ def test_species_symbol_operations():
75
75
  '<cn sbml:units="dimensionless">2</cn></apply></apply>'
76
76
  "</math>"
77
77
  )
78
- sym_expr = SBMLMathMLParser(floats_as_rationals=False).parse_str(mathml_exp)
78
+ sym_expr = SBMLMathMLParser(floats_as_rationals=False).parse_str(
79
+ mathml_exp
80
+ )
79
81
  mathml_act = SBMLMathMLPrinter().doprint(sym_expr)
80
82
 
81
83
  # not an exact match, but close enough, for now
@@ -1,25 +0,0 @@
1
- # See https://pre-commit.com for more information
2
- # See https://pre-commit.com/hooks.html for more hooks
3
- repos:
4
- - repo: https://github.com/pycqa/isort
5
- rev: 5.13.2
6
- hooks:
7
- - id: isort
8
- name: isort (python)
9
- args: ["--profile", "black", "--filter-files"]
10
- - repo: https://github.com/pre-commit/pre-commit-hooks
11
- rev: v4.5.0
12
- hooks:
13
- - id: trailing-whitespace
14
- - id: end-of-file-fixer
15
- - id: check-yaml
16
- - id: check-added-large-files
17
- - repo: https://github.com/psf/black
18
- rev: 23.12.0
19
- hooks:
20
- - id: black
21
- # It is recommended to specify the latest version of Python
22
- # supported by your project here, or alternatively use
23
- # pre-commit's default_language_version, see
24
- # https://pre-commit.com/#top_level-default_language_version
25
- language_version: python3.11
@@ -1,29 +0,0 @@
1
- [build-system]
2
- requires = ["setuptools", "setuptools-scm"]
3
- build-backend = "setuptools.build_meta"
4
-
5
- [project]
6
- name = "sbmlmath"
7
- version = "0.1.1"
8
- authors = [
9
- {name = "Daniel Weindl", email = "sci@danielweindl.de"},
10
- ]
11
- description = "SBML Math <-> SymPy"
12
- readme = "README.md"
13
- requires-python = ">=3.9"
14
- license = {text = "BSD-3-Clause"}
15
- dependencies = [
16
- "python-libsbml",
17
- "sympy",
18
- "pint",
19
- "lxml>=4.6.4",
20
- ]
21
-
22
- [project.optional-dependencies]
23
- test = ["pytest>=7", "pre-commit>=3"]
24
-
25
- [tool.black]
26
- line-length = 80
27
-
28
- [tool.pytest.ini_options]
29
- addopts = "--doctest-modules --ignore=doc/conf.py"
@@ -1,70 +0,0 @@
1
- from typing import Union
2
-
3
- import libsbml
4
- import sympy as sp
5
-
6
- from .cfunction import *
7
- from .csymbol import *
8
- from .mathml_parser import SBMLMathMLParser
9
- from .mathml_printer import SBMLMathMLPrinter
10
- from .species_symbol import SpeciesSymbol
11
-
12
- __all__ = [
13
- "SBMLMathMLParser",
14
- "SBMLMathMLPrinter",
15
- "SpeciesSymbol",
16
- "TimeSymbol",
17
- "sympy_to_sbml_math",
18
- "sbml_math_to_sympy",
19
- *csymbol.__all__,
20
- *cfunction.__all__,
21
- ]
22
-
23
-
24
- def sympy_to_sbml_math(sp_expr: sp.Expr) -> libsbml.ASTNode:
25
- """Convert sympy expression to SBML math ASTNode.
26
-
27
- This function takes a SymPy expression and converts it to an SBML math
28
- ASTNode.
29
-
30
- Args:
31
- sp_expr: The SymPy expression to be converted.
32
-
33
- Returns:
34
- The resulting SBML math ASTNode.
35
-
36
- Raises:
37
- ValueError:
38
- If there is an error in converting the math expression.
39
- """
40
- mathml = SBMLMathMLPrinter().doprint(sp_expr)
41
-
42
- if ast_node := libsbml.readMathMLFromString(mathml):
43
- return ast_node
44
-
45
- raise ValueError(
46
- f"Unknown error handling math expression:\n{sp_expr}\n" f"{mathml}"
47
- )
48
-
49
-
50
- def sbml_math_to_sympy(
51
- sbml_obj: Union[libsbml.SBase, libsbml.ASTNode]
52
- ) -> sp.Expr:
53
- """Convert SBML MathML to sympy expression.
54
-
55
- Conversion is done using the default settings of :class:`SBMLMathMLParser`.
56
-
57
- Args:
58
- sbml_obj:
59
- The SBML object to be converted.
60
- (Either directly the ASTNode or the surrounding SBase object).
61
- Returns:
62
- The resulting sympy expression.
63
- """
64
- ast_node = (
65
- sbml_obj
66
- if isinstance(sbml_obj, libsbml.ASTNode)
67
- else sbml_obj.getMath()
68
- )
69
- mathml = libsbml.writeMathMLToString(ast_node)
70
- return SBMLMathMLParser().parse_str(mathml)
@@ -1,61 +0,0 @@
1
- """Handling of ``<csymbol>`` functions"""
2
- import sympy as sp
3
- from sympy.core.function import UndefinedFunction
4
-
5
- __all__ = ["CFunction", "delay", "rate_of"]
6
-
7
-
8
- class CFunction(UndefinedFunction):
9
- """
10
- Represents ``<csymbol>`` functions.
11
-
12
- Examples: :func:`rateOf() <rate_of>`, :func:`delay`,
13
- distributions from the `distrib package
14
- <https://synonym.caltech.edu/documents/specifications/level-3/version-1/distrib/>`_.
15
-
16
-
17
- See also https://www.w3.org/TR/MathML2/chapter4.html#contm.deffun.
18
- """
19
-
20
- _cache = {}
21
-
22
- def __new__(
23
- cls,
24
- *args,
25
- definition_url: str,
26
- encoding: str = "text",
27
- **kwargs,
28
- ):
29
- # Cache instances.
30
- # If not done: (CFunction("A", definition_url="x")
31
- # == CFunction("A", definition_url="y")) == False
32
- if not (name := kwargs.get("name")):
33
- name = args[0]
34
- cache_key = (name, definition_url, encoding)
35
- if cached := cls._cache.get(cache_key):
36
- return cached
37
-
38
- obj = super().__new__(cls, *args, **kwargs)
39
-
40
- # ensure there are no collisions with super() attributes
41
- assert not hasattr(obj, "definition_url")
42
- assert not hasattr(obj, "encoding")
43
- obj.definition_url = definition_url
44
- obj.encoding = encoding
45
-
46
- cls._cache[cache_key] = obj
47
-
48
- return obj
49
-
50
-
51
- # SBML-defined functions
52
-
53
- #: The SBML ``delay()`` function.
54
- delay = CFunction(
55
- "delay", definition_url="http://www.sbml.org/sbml/symbols/delay"
56
- )
57
-
58
- #: The SBML ``rateOf()`` function.
59
- rate_of = CFunction(
60
- "rateOf", definition_url="http://www.sbml.org/sbml/symbols/rateOf"
61
- )
@@ -1,13 +0,0 @@
1
- from sbmlmath.csymbol import *
2
-
3
-
4
- def test_time_symbol():
5
- assert TimeSymbol("t") is TimeSymbol("t")
6
-
7
- assert TimeSymbol("t") == TimeSymbol("time")
8
- assert TimeSymbol("t") is not TimeSymbol("time")
9
-
10
- t1, t2 = TimeSymbol("t"), TimeSymbol("time")
11
- eight_t = t1 + t2 + 3 * t1 + 3 * t2
12
- # is the result defined?
13
- assert eight_t in [8 * t1, 8 * t2]
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes