sbmlmath 0.5.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
sbmlmath/__init__.py ADDED
@@ -0,0 +1,130 @@
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{mathml}"
42
+ )
43
+
44
+
45
+ def sbml_math_to_sympy(
46
+ sbml_obj: libsbml.SBase | libsbml.ASTNode, **kwargs
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
+ kwargs:
57
+ Additional keyword arguments passed to
58
+ :attr:`SBMLMathMLParser.__init__`.
59
+ Returns:
60
+ The resulting sympy expression.
61
+ """
62
+ if isinstance(sbml_obj, libsbml.ASTNode):
63
+ ast_node = sbml_obj
64
+ sbml_obj = ast_node.getParentSBMLObject()
65
+ else:
66
+ ast_node = sbml_obj.getMath()
67
+
68
+ level = (
69
+ sbml_obj.getLevel() if sbml_obj is not None else _DEFAULT_SBML_LEVEL
70
+ )
71
+ version = (
72
+ sbml_obj.getVersion()
73
+ if sbml_obj is not None
74
+ else _DEFAULT_SBML_VERSION
75
+ )
76
+ mathml = libsbml.writeMathMLWithNamespaceToString(
77
+ ast_node, libsbml.SBMLNamespaces(level, version)
78
+ )
79
+ return SBMLMathMLParser(
80
+ sbml_level=level, sbml_version=version, **kwargs
81
+ ).parse_str(mathml)
82
+
83
+
84
+ def set_math(
85
+ element: libsbml.SBase,
86
+ expr: sp.Expr,
87
+ ) -> None:
88
+ """Set the math expression of an SBML object.
89
+
90
+ Args:
91
+ element:
92
+ The SBML object to set the math expression for.
93
+ expr:
94
+ The sympy expression to set as the math expression.
95
+ """
96
+ mathml = SBMLMathMLPrinter(
97
+ sbml_level=element.getLevel(),
98
+ sbml_version=element.getVersion(),
99
+ ).doprint(expr)
100
+
101
+ if ast_node := libsbml.readMathMLFromString(mathml):
102
+ if element.setMath(ast_node) == libsbml.LIBSBML_OPERATION_SUCCESS:
103
+ return
104
+ sbml_document = element.getSBMLDocument()
105
+ raise ValueError(
106
+ f"Error setting math expression:\n{expr}\n"
107
+ f"{mathml}\n{sbml_document.getErrorLog().toString()}"
108
+ )
109
+ raise ValueError(
110
+ f"Unknown error parsing math expression:\n{expr}\n{mathml}"
111
+ )
112
+
113
+
114
+ from .cfunction import *
115
+ from .csymbol import *
116
+ from .mathml_parser import SBMLMathMLParser
117
+ from .mathml_printer import SBMLMathMLPrinter
118
+ from .species_symbol import SpeciesSymbol
119
+
120
+ __all__ = [
121
+ "set_math",
122
+ "SBMLMathMLParser",
123
+ "SBMLMathMLPrinter",
124
+ "SpeciesSymbol",
125
+ "TimeSymbol",
126
+ "sympy_to_sbml_math",
127
+ "sbml_math_to_sympy",
128
+ *csymbol.__all__,
129
+ *cfunction.__all__,
130
+ ]
sbmlmath/cfunction.py ADDED
@@ -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")
sbmlmath/csymbol.py ADDED
@@ -0,0 +1,134 @@
1
+ """Handling of <csymbol> constants"""
2
+
3
+ from __future__ import annotations
4
+
5
+ import sympy as sp
6
+
7
+ __all__ = ["CSymbol", "TimeSymbol", "avogadro"]
8
+
9
+
10
+ #: The `Avogadro constant <https://en.wikipedia.org/wiki/Avogadro_constant>`_
11
+ # as defined in SBML L3V2 section 3.4.6.
12
+ SBML_L3V2_AVOGADRO_VALUE = 6.02214179e23
13
+
14
+
15
+ class CSymbol(sp.Dummy):
16
+ """
17
+ Represents a ``<csymbol>`` element.
18
+
19
+ Represents, for example the Avogadro constant, which is defined in SBML as:
20
+
21
+ .. code-block:: xml
22
+
23
+ <csymbol encoding="text" definitionURL="http://www.sbml.org/sbml/symbols/avogadro"> avogadro </csymbol>
24
+
25
+ and can be generated by:
26
+
27
+ >>> CSymbol("avogadro", definition_url="http://www.sbml.org/sbml/symbols/avogadro")
28
+ <avogadro(http://www.sbml.org/sbml/symbols/avogadro)>
29
+ >>> float(CSymbol("avogadro", definition_url="http://www.sbml.org/sbml/symbols/avogadro"))
30
+ 6.02214179e+23
31
+
32
+ See also https://www.w3.org/TR/MathML2/chapter4.html#contm.csymbol.
33
+ """
34
+
35
+ DEFINITION_URL = None
36
+ _cache = {}
37
+ _definition_url_to_derived_class = {}
38
+
39
+ def __new__(
40
+ cls,
41
+ *args,
42
+ definition_url: str,
43
+ encoding: str = "text",
44
+ **kwargs,
45
+ ):
46
+ # Cache instances.
47
+ # If not done: (CSymbol("A") == CSymbol("A")) == False
48
+ if not (name := kwargs.get("name")):
49
+ name = args[0]
50
+ cache_key = (name, definition_url, encoding)
51
+ if cached := cls._cache.get(cache_key):
52
+ return cached
53
+
54
+ # return the matching subtype, depending on the definition URL
55
+ obj = super().__new__(
56
+ cls._definition_url_to_derived_class.get(definition_url, cls),
57
+ *args,
58
+ **kwargs,
59
+ )
60
+
61
+ # ensure there are no collisions with super() attributes
62
+ assert not hasattr(obj, "definition_url")
63
+ assert not hasattr(obj, "encoding")
64
+ obj.definition_url = definition_url
65
+ obj.encoding = encoding
66
+
67
+ cls._cache[cache_key] = obj
68
+
69
+ return obj
70
+
71
+ def __repr__(self):
72
+ return f"<{self.name}({self.definition_url})>"
73
+
74
+ def __eq__(self, other):
75
+ if not isinstance(other, CSymbol):
76
+ return False
77
+
78
+ # if they represent the same value, they are equal
79
+ return self.definition_url == other.definition_url
80
+
81
+ def __hash__(self):
82
+ # if we define __eq__, we also need __hash__ to use instances in sympy
83
+ # expressions
84
+ return hash(self.definition_url)
85
+
86
+ def __float__(self):
87
+ if self.definition_url == "http://www.sbml.org/sbml/symbols/avogadro":
88
+ return SBML_L3V2_AVOGADRO_VALUE
89
+ return super().__float__()
90
+
91
+ def _eval_evalf(self, prec):
92
+ if self.definition_url == "http://www.sbml.org/sbml/symbols/avogadro":
93
+ return sp.Float(SBML_L3V2_AVOGADRO_VALUE)
94
+ return super()._eval_evalf()
95
+
96
+ @classmethod
97
+ def register_subclass(cls, derived_class: type[CSymbol]):
98
+ cls._definition_url_to_derived_class[derived_class.DEFINITION_URL] = (
99
+ derived_class
100
+ )
101
+
102
+
103
+ #: SBML's `Avogadro constant <https://en.wikipedia.org/wiki/Avogadro_constant>`_
104
+ avogadro = CSymbol(
105
+ "avogadro", definition_url="http://www.sbml.org/sbml/symbols/avogadro"
106
+ )
107
+
108
+
109
+ class TimeSymbol(CSymbol):
110
+ """The current internal simulation time.
111
+
112
+ This symbol represents the current simulation time inside the model.
113
+
114
+ >>> TimeSymbol("t")
115
+ <t(http://www.sbml.org/sbml/symbols/time)>
116
+
117
+ Args:
118
+ name: The name of the symbol.
119
+ """
120
+
121
+ DEFINITION_URL = "http://www.sbml.org/sbml/symbols/time"
122
+
123
+ def __new__(
124
+ cls,
125
+ name: str,
126
+ ):
127
+ return super().__new__(
128
+ cls,
129
+ name=name,
130
+ definition_url=cls.DEFINITION_URL,
131
+ )
132
+
133
+
134
+ CSymbol.register_subclass(TimeSymbol)