sbmlmath 0.5.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,706 @@
1
+ """SBML mathml to sympy."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import contextlib
6
+ import operator as operators
7
+ import sys
8
+ from functools import cache, reduce
9
+ from io import BytesIO
10
+ from typing import TYPE_CHECKING
11
+
12
+ import sympy as sp
13
+ from lxml import etree
14
+ from sympy import Piecewise
15
+ from sympy.logic.boolalg import (
16
+ Boolean,
17
+ BooleanFalse,
18
+ BooleanTrue,
19
+ )
20
+
21
+ from . import _DEFAULT_SBML_LEVEL, _DEFAULT_SBML_VERSION
22
+ from .cfunction import CFunction
23
+ from .csymbol import CSymbol
24
+ from .species_symbol import SpeciesSymbol
25
+
26
+ if TYPE_CHECKING:
27
+ from collections.abc import Collection
28
+
29
+ from pint import UnitRegistry
30
+
31
+ __all__ = ["SBMLMathMLParser"]
32
+
33
+
34
+ mathml_ns = "http://www.w3.org/1998/Math/MathML"
35
+
36
+
37
+ @cache
38
+ def _get_default_ureg() -> UnitRegistry:
39
+ """Get the default unit registry, shared by all parsers.
40
+
41
+ Created lazily, because importing pint and creating a registry is slow.
42
+ """
43
+ from pint import UnitRegistry
44
+
45
+ ureg = UnitRegistry()
46
+ ureg.Quantity.name = property(fget=lambda s: f"({s})")
47
+ ureg.Quantity_sympy_ = lambda s: sp.sympify(f"{s.m}*{s.u:~}")
48
+ return ureg
49
+
50
+
51
+ def _is_quantity(x) -> bool:
52
+ """Check whether `x` is a :class:`pint.Quantity`, without importing pint."""
53
+ pint = sys.modules.get("pint")
54
+ return pint is not None and isinstance(x, pint.Quantity)
55
+
56
+
57
+ # some operator implementations to handle `evaluate`
58
+ # *and* be compatible with non Expr operands
59
+ # (non-Expr is deprecated for Add, Mul, Pow, ...)
60
+ def _divide(*args, evaluate: bool = False):
61
+ with sp.evaluate(evaluate):
62
+ return operators.truediv(*args)
63
+
64
+
65
+ def _mul(*args, evaluate: bool = False):
66
+ with sp.evaluate(evaluate):
67
+ if len(args) >= 2:
68
+ return reduce(operators.mul, args[1:], args[0])
69
+ if len(args) == 1:
70
+ return args[0]
71
+ return sp.Integer(1)
72
+
73
+
74
+ def _pow(base, exponent, evaluate: bool = False):
75
+ # pint can't raise units to a symbolic power. For a dimensionless base,
76
+ # the result is dimensionless, so we can drop the units.
77
+ if _is_quantity(base) and not isinstance(
78
+ _strip_dimensionless(exponent), int | float | sp.Number
79
+ ):
80
+ if not base.dimensionless:
81
+ raise ValueError(
82
+ f"Cannot raise `{base}` to the non-numeric power "
83
+ f"`{exponent}`: the units of the result are undefined."
84
+ )
85
+ base = _strip_dimensionless(base)
86
+ exponent = _strip_dimensionless(exponent)
87
+
88
+ with sp.evaluate(evaluate):
89
+ return base**exponent
90
+
91
+
92
+ def _strip_dimensionless(x):
93
+ """Convert a dimensionless quantity to its plain magnitude."""
94
+ if _is_quantity(x) and x.dimensionless:
95
+ return x.to("dimensionless").magnitude
96
+ return x
97
+
98
+
99
+ def _rem(a, b, evaluate: bool = False):
100
+ # SBML `<rem/>` uses C/truncated-division semantics (sign follows the
101
+ # dividend), unlike sympy.Mod (floored, sign follows the divisor).
102
+ # This matches the piecewise expansion libSBML uses for `%` on SBML
103
+ # levels/versions that don't support `<rem/>` directly, so both
104
+ # encodings of the same operator agree.
105
+ with sp.evaluate(evaluate):
106
+ return sp.Piecewise(
107
+ (a - b * sp.ceiling(a / b), sp.Xor(a < 0, b < 0)),
108
+ (a - b * sp.floor(a / b), True),
109
+ )
110
+
111
+
112
+ mathml_op_sympy_trigonometric = {
113
+ f"{{{mathml_ns}}}sin": sp.sin,
114
+ f"{{{mathml_ns}}}cos": sp.cos,
115
+ f"{{{mathml_ns}}}tan": sp.tan,
116
+ f"{{{mathml_ns}}}sec": sp.sec,
117
+ f"{{{mathml_ns}}}csc": sp.csc,
118
+ f"{{{mathml_ns}}}cot": sp.cot,
119
+ f"{{{mathml_ns}}}sinh": sp.sinh,
120
+ f"{{{mathml_ns}}}cosh": sp.cosh,
121
+ f"{{{mathml_ns}}}tanh": sp.tanh,
122
+ f"{{{mathml_ns}}}sech": sp.sech,
123
+ f"{{{mathml_ns}}}csch": sp.csch,
124
+ f"{{{mathml_ns}}}coth": sp.coth,
125
+ f"{{{mathml_ns}}}arccos": sp.acos,
126
+ f"{{{mathml_ns}}}arcsin": sp.asin,
127
+ f"{{{mathml_ns}}}arctan": sp.atan,
128
+ f"{{{mathml_ns}}}arcsec": sp.asec,
129
+ f"{{{mathml_ns}}}arccsc": sp.acsc,
130
+ f"{{{mathml_ns}}}arccot": sp.acot,
131
+ f"{{{mathml_ns}}}arcsinh": sp.asinh,
132
+ f"{{{mathml_ns}}}arccosh": sp.acosh,
133
+ f"{{{mathml_ns}}}arctanh": sp.atanh,
134
+ f"{{{mathml_ns}}}arcsech": sp.asech,
135
+ f"{{{mathml_ns}}}arccsch": sp.acsch,
136
+ f"{{{mathml_ns}}}arccoth": sp.acoth,
137
+ }
138
+ mathml_op_sympy_boolean = {
139
+ f"{{{mathml_ns}}}and": sp.And,
140
+ f"{{{mathml_ns}}}or": sp.Or,
141
+ f"{{{mathml_ns}}}xor": sp.Xor,
142
+ f"{{{mathml_ns}}}not": sp.Not,
143
+ f"{{{mathml_ns}}}implies": sp.Implies,
144
+ }
145
+
146
+ mathml_op_sympy = {
147
+ # Using non-Expr arguments in Mul and Pow is deprecated
148
+ # and we might use pint.Quantitity, so we use operator.mul
149
+ f"{{{mathml_ns}}}times": _mul,
150
+ f"{{{mathml_ns}}}divide": _divide,
151
+ f"{{{mathml_ns}}}power": _pow,
152
+ f"{{{mathml_ns}}}eq": lambda *args, **kwargs: sp.Equality(*args, **kwargs),
153
+ f"{{{mathml_ns}}}neq": lambda *args, **kwargs: sp.Unequality(
154
+ *args, **kwargs
155
+ ),
156
+ f"{{{mathml_ns}}}lt": lambda *args, **kwargs: sp.StrictLessThan(
157
+ *args, **kwargs
158
+ ),
159
+ f"{{{mathml_ns}}}gt": lambda *args, **kwargs: sp.StrictGreaterThan(
160
+ *args, **kwargs
161
+ ),
162
+ f"{{{mathml_ns}}}geq": lambda *args, **kwargs: sp.GreaterThan(
163
+ *args, **kwargs
164
+ ),
165
+ f"{{{mathml_ns}}}leq": lambda *args, **kwargs: sp.LessThan(
166
+ *args, **kwargs
167
+ ),
168
+ f"{{{mathml_ns}}}max": sp.Max,
169
+ f"{{{mathml_ns}}}min": sp.Min,
170
+ f"{{{mathml_ns}}}abs": sp.Abs,
171
+ f"{{{mathml_ns}}}exp": sp.exp,
172
+ f"{{{mathml_ns}}}ceiling": sp.ceiling,
173
+ f"{{{mathml_ns}}}floor": sp.floor,
174
+ f"{{{mathml_ns}}}factorial": sp.factorial,
175
+ f"{{{mathml_ns}}}ln": sp.log,
176
+ f"{{{mathml_ns}}}rem": _rem,
177
+ **mathml_op_sympy_trigonometric,
178
+ **mathml_op_sympy_boolean,
179
+ }
180
+
181
+ # unary functions
182
+ unary = {
183
+ f"{{{mathml_ns}}}plus",
184
+ f"{{{mathml_ns}}}minus",
185
+ f"{{{mathml_ns}}}times",
186
+ *mathml_op_sympy_boolean,
187
+ f"{{{mathml_ns}}}abs",
188
+ f"{{{mathml_ns}}}exp",
189
+ f"{{{mathml_ns}}}ceiling",
190
+ f"{{{mathml_ns}}}floor",
191
+ f"{{{mathml_ns}}}factorial",
192
+ f"{{{mathml_ns}}}ln",
193
+ f"{{{mathml_ns}}}min",
194
+ f"{{{mathml_ns}}}max",
195
+ f"{{{mathml_ns}}}root",
196
+ *mathml_op_sympy_trigonometric,
197
+ }
198
+ # n-ary functions
199
+ n_ary = {
200
+ f"{{{mathml_ns}}}times",
201
+ f"{{{mathml_ns}}}plus",
202
+ *mathml_op_sympy_boolean,
203
+ f"{{{mathml_ns}}}lt",
204
+ f"{{{mathml_ns}}}gt",
205
+ f"{{{mathml_ns}}}geq",
206
+ f"{{{mathml_ns}}}leq",
207
+ f"{{{mathml_ns}}}eq",
208
+ f"{{{mathml_ns}}}min",
209
+ f"{{{mathml_ns}}}max",
210
+ }
211
+ # MathML-defined constants
212
+ constants = {
213
+ f"{{{mathml_ns}}}exponentiale": sp.E,
214
+ f"{{{mathml_ns}}}true": BooleanTrue(),
215
+ f"{{{mathml_ns}}}false": BooleanFalse(),
216
+ f"{{{mathml_ns}}}notanumber": sp.Float("nan"),
217
+ f"{{{mathml_ns}}}pi": sp.pi,
218
+ f"{{{mathml_ns}}}infinity": sp.Float("inf"),
219
+ }
220
+
221
+
222
+ class SBMLMathMLParser:
223
+ """MathML parser for sympy.
224
+
225
+ Parses the SBML subset of MathML 2.0.
226
+
227
+ For details, see SBML spec section 3.4:
228
+ https://raw.githubusercontent.com/combine-org/combine-specifications/main/specifications/files/sbml.level-3.version-2.core.release-2.pdf.
229
+
230
+ See also: `MathML 2.0 specification <https://www.w3.org/TR/MathML2/>`_.
231
+
232
+ :param sbml_level: SBML level.
233
+ Note that SBML level < 3 has not been thoroughly tested.
234
+ :param sbml_version: SBML version.
235
+ :param ureg:
236
+ Optional :class:`pint.UnitRegistry` to use for unit conversion.
237
+ :param floats_as_rationals:
238
+ Whether to convert floats to :class:`sympy.Rational`.
239
+ Improves precision.
240
+ :param ignore_units:
241
+ Whether to ignore units.
242
+ If ``True``, all units are ignored and all numbers are converted to
243
+ plain numbers.
244
+ If ``False``, all math elements with units are converted to
245
+ :class:`pint.Quantity` objects.
246
+ :param symbol_kwargs:
247
+ Additional keyword arguments for constructing :class:`sympy.Symbol`.
248
+ For example, for passing custom assumptions such as ``real=True``.
249
+ """
250
+
251
+ def __init__(
252
+ self,
253
+ sbml_level: int | str = _DEFAULT_SBML_LEVEL,
254
+ sbml_version: int | str = _DEFAULT_SBML_VERSION,
255
+ ureg: UnitRegistry | None = None,
256
+ floats_as_rationals=True,
257
+ ignore_units=False,
258
+ symbol_kwargs=None,
259
+ evaluate=False,
260
+ ):
261
+ """Constructor"""
262
+ self._ureg = ureg
263
+ self.sbml_core_ns = f"http://www.sbml.org/sbml/level{sbml_level}/version{sbml_version}/core"
264
+ # TODO {prefix=>url}
265
+ self.sbml_multi_ns = (
266
+ # L3V2 doesn't work
267
+ f"http://www.sbml.org/sbml/level{sbml_level}/version1/multi/version1"
268
+ )
269
+ self.floats_as_rationals = floats_as_rationals
270
+ self.ignore_units = ignore_units
271
+ self.symbol_kwargs = (
272
+ {} if symbol_kwargs is None else symbol_kwargs.copy()
273
+ )
274
+ self.evaluate = evaluate
275
+ # bound variables of the <lambda> currently being parsed
276
+ self._bound_symbols = frozenset()
277
+
278
+ def parse_file(self, file_like) -> sp.Expr:
279
+ """Parse a file-like object containing MathML.
280
+
281
+ :param file_like:
282
+ File-like object (file, filename, ...) containing MathML.
283
+ Expected to contain the XML prolog ``<?xml [...]?>``
284
+ and the MathML ``math`` element.
285
+ :return: The sympy representation of the MathML expression.
286
+ """
287
+ # Using `lxml` to parse untrusted data is known to be vulnerable to XML
288
+ # attacks
289
+ element_tree = etree.parse(file_like) # noqa S320
290
+ for element in element_tree.iter():
291
+ if element.tag == f"{{{mathml_ns}}}math":
292
+ continue
293
+
294
+ return self._parse_element(element)
295
+
296
+ @property
297
+ def ureg(self) -> UnitRegistry:
298
+ """The unit registry used for ``sbml:units``."""
299
+ if self._ureg is None:
300
+ self._ureg = _get_default_ureg()
301
+ return self._ureg
302
+
303
+ @ureg.setter
304
+ def ureg(self, ureg: UnitRegistry | None):
305
+ self._ureg = ureg
306
+
307
+ def parse_str(self, mathml: str):
308
+ """Parse a string containing MathML.
309
+
310
+ :param mathml:
311
+ MathML string. Expected to contain the XML prolog ``<?xml [...]?>``
312
+ and the MathML ``math`` element.
313
+ :return: The sympy representation of the MathML expression.
314
+ """
315
+ # (fragile) workaround for libsbml<5.20.0 dropping xmlns declarations
316
+ # for namespaces other than 'sbml'
317
+ if "multi:" in mathml and "xmlns:multi" not in mathml:
318
+ math_element = '<math xmlns="http://www.w3.org/1998/Math/MathML"'
319
+ mathml = mathml.replace(
320
+ math_element,
321
+ f'{math_element} xmlns:multi="{self.sbml_multi_ns}"',
322
+ )
323
+ # end
324
+
325
+ return self.parse_file(file_like=BytesIO(mathml.encode()))
326
+
327
+ def _parse_element(self, element: etree._Element) -> sp.Expr:
328
+ mathml_prefix = f"{{{mathml_ns}}}"
329
+ if not element.tag.startswith(mathml_prefix):
330
+ raise AssertionError(element.tag)
331
+
332
+ stripped_tag = element.tag[len(mathml_prefix) :]
333
+
334
+ handler = f"handle_{stripped_tag}"
335
+ if handler := getattr(self, handler, None):
336
+ try:
337
+ return handler(element)
338
+ except NotImplementedError:
339
+ raise
340
+ except Exception as e:
341
+ raise ValueError(
342
+ f"Failed parsing:\n{etree.tostring(element).decode()}"
343
+ ) from e
344
+ with contextlib.suppress(KeyError):
345
+ return constants[element.tag]
346
+
347
+ raise NotImplementedError(f"Unhandled element: {element.tag}.")
348
+
349
+ def handle_apply(self, element: etree._Element) -> sp.Expr: # noqa C901
350
+ """Handle <apply>"""
351
+ operator, *operands = element
352
+ sym_operands = list(map(self._parse_element, operands))
353
+
354
+ # TODO cleanup; doesn't check properly if compatible with 2 args
355
+ if operator.tag not in (
356
+ f"{{{mathml_ns}}}csymbol",
357
+ f"{{{mathml_ns}}}ci",
358
+ ) and (
359
+ len(operands) == 1
360
+ and operator.tag not in unary
361
+ or len(operands) > 2
362
+ and operator.tag not in n_ary
363
+ ):
364
+ raise AssertionError(
365
+ f"Unknown arity for {operator.tag} ({operands}"
366
+ )
367
+
368
+ if operator.tag.startswith(f"{{{mathml_ns}}}"):
369
+ stripped_tag = operator.tag[len(f"{{{mathml_ns}}}") :]
370
+ if len(operands) == 1 and stripped_tag in {
371
+ "plus",
372
+ "times",
373
+ "min",
374
+ "max",
375
+ }:
376
+ return sym_operands[0]
377
+ if len(operands) == 1 and stripped_tag in {"and", "or", "xor"}:
378
+ return self._num2bool(sym_operands[0])
379
+
380
+ if (
381
+ stripped_tag in ("gt", "lt", "leq", "geq", "eq")
382
+ and len(operands) >= 3
383
+ ):
384
+ # n-ary relational operators:
385
+ # a < b < c cannot directly be represented in sympy.
386
+ # either change to `a < b and b < c`, to be sympy-evaluatable,
387
+ # or to Function('MathML_Lt')(a, b, c), which will cycle
388
+ # (although potentially collide with other functions with
389
+ # that name), but which cannot be evaluated in sympy.
390
+ # The Function-approach won't work when used in piecewise
391
+ # -> "Second argument must be a Boolean, not `lt`"
392
+ # Therefore, chain expressions with `and`.
393
+ sym_operator = mathml_op_sympy[operator.tag]
394
+ expr = True
395
+ for i in range(len(sym_operands) - 1):
396
+ expr = sp.And(
397
+ expr,
398
+ sym_operator(
399
+ sym_operands[i],
400
+ sym_operands[i + 1],
401
+ evaluate=self.evaluate,
402
+ ),
403
+ )
404
+ return expr
405
+
406
+ # explicit boolean->{int,float} conversion for non-boolean functions,
407
+ # since sympy does not do that automatically
408
+ if operator.tag in mathml_op_sympy_boolean:
409
+ sym_operands = list(map(self._num2bool, sym_operands))
410
+ else:
411
+ sym_operands = list(map(_bool2num, sym_operands))
412
+
413
+ with contextlib.suppress(KeyError):
414
+ return mathml_op_sympy[operator.tag](
415
+ *sym_operands, evaluate=self.evaluate
416
+ )
417
+
418
+ if operator.tag == f"{{{mathml_ns}}}plus":
419
+ with sp.evaluate(self.evaluate):
420
+ if len(sym_operands) >= 2:
421
+ return reduce(
422
+ operators.add, sym_operands[1:], sym_operands[0]
423
+ )
424
+ if len(sym_operands) == 1:
425
+ return sym_operands[0]
426
+ if len(sym_operands) == 0:
427
+ return sp.Integer(0)
428
+
429
+ if operator.tag == f"{{{mathml_ns}}}minus":
430
+ with sp.evaluate(self.evaluate):
431
+ if len(sym_operands) == 2:
432
+ return sym_operands[0] - sym_operands[1]
433
+ if len(sym_operands) == 1:
434
+ return -sym_operands[0]
435
+ raise AssertionError(list(element))
436
+
437
+ if operator.tag == f"{{{mathml_ns}}}root":
438
+ assert len(sym_operands) in {1, 2}
439
+ if len(sym_operands) == 1:
440
+ # defaults to sqrt
441
+ degree = 2
442
+ else:
443
+ degree = sym_operands[0]
444
+ assert operands[0].tag == f"{{{mathml_ns}}}degree"
445
+
446
+ with sp.evaluate(self.evaluate):
447
+ return sym_operands[-1] ** (1 / degree)
448
+
449
+ if operator.tag == f"{{{mathml_ns}}}log":
450
+ assert len(operands) == 2
451
+ assert operands[0].tag == f"{{{mathml_ns}}}logbase"
452
+ assert len(operands[0]) == 1
453
+ base, x = sym_operands
454
+ # won't cycle - will be transformed to ``log(x)/log(base)``
455
+ return sp.log(x, base, evaluate=self.evaluate)
456
+
457
+ if operator.tag == f"{{{mathml_ns}}}quotient":
458
+ # there is no direct correspondence for integer division in sympy,
459
+ # so we use modulo instead. this won't cycle.
460
+ # a // b = (a - a mod b) / b
461
+ assert len(operands) == 2
462
+ a, b = sym_operands
463
+ with sp.evaluate(self.evaluate):
464
+ return (a - a % b) / b
465
+
466
+ name = self.preprocess_symbol_name(operator.text.strip(), operator)
467
+
468
+ if operator.tag == f"{{{mathml_ns}}}csymbol":
469
+ # examples: rateOf, delay, distributions from distrib package
470
+ assert operator.attrib["encoding"] == "text"
471
+ return CFunction(
472
+ name,
473
+ definition_url=operator.attrib["definitionURL"],
474
+ )(*sym_operands)
475
+
476
+ if operator.tag == f"{{{mathml_ns}}}ci":
477
+ assert not operator.attrib
478
+ return sp.Function(name, real=True)(*sym_operands)
479
+
480
+ raise NotImplementedError(f"Unsupported operator {operator.tag}.")
481
+
482
+ def handle_ci(self, element: etree._Element) -> sp.Expr:
483
+ """Handle identifiers.
484
+
485
+ See also:
486
+ `numerical constants in MathML <https://www.w3.org/TR/MathML2/chapter4.html#contm.ci>`__.
487
+ """
488
+ handled_attrs = {
489
+ # TODO: remove after fixing xmlns in model
490
+ "multi:representationType",
491
+ "multi:speciesReference",
492
+ f"{{{self.sbml_multi_ns}}}representationType",
493
+ f"{{{self.sbml_multi_ns}}}speciesReference",
494
+ }
495
+ if unhandled_attrs := (set(element.attrib.keys()) - handled_attrs):
496
+ raise NotImplementedError(
497
+ f"Unhandled <ci> attributes: {unhandled_attrs}"
498
+ )
499
+
500
+ representation_type = element.attrib.get(
501
+ f"{{{self.sbml_multi_ns}}}representationType", None
502
+ ) or element.attrib.get("multi:representationType", None)
503
+ species_reference = element.attrib.get(
504
+ f"{{{self.sbml_multi_ns}}}speciesReference", None
505
+ ) or element.attrib.get("multi:speciesReference", None)
506
+ symbol_name = self.preprocess_symbol_name(
507
+ element.text.strip(), element
508
+ )
509
+ if representation_type or species_reference:
510
+ return SpeciesSymbol(
511
+ name=symbol_name,
512
+ representation_type=representation_type,
513
+ species_reference=species_reference,
514
+ **self.symbol_kwargs,
515
+ )
516
+ return sp.Symbol(symbol_name, **self.symbol_kwargs)
517
+
518
+ def handle_cn(self, element: etree._Element) -> sp.Expr:
519
+ """Handle numbers.
520
+
521
+ See also:
522
+ `numerical constants in MathML <https://www.w3.org/TR/MathML2/chapter4.html#contm.cn>`_.
523
+ """
524
+ handled_attrs = {
525
+ "type",
526
+ f"{{{self.sbml_core_ns}}}units",
527
+ }
528
+ if unhandled_attrs := (set(element.attrib.keys()) - handled_attrs):
529
+ raise NotImplementedError(
530
+ f"Unhandled <cn> attributes: {unhandled_attrs}"
531
+ )
532
+ dtype = element.attrib.get("type", "real")
533
+ converter = {
534
+ "real": (lambda element: sp.Rational(element.text))
535
+ if self.floats_as_rationals
536
+ else lambda element: sp.Float(element.text),
537
+ "integer": lambda element: sp.Integer(element.text),
538
+ "rational": lambda element: sp.Rational(
539
+ element.text, element[0].tail
540
+ ),
541
+ "e-notation":
542
+ # this won't cycle. we don't have a corresponding
543
+ # representation in sympy
544
+ lambda element: sp.Float(
545
+ float(element.text) * 10 ** int(element[0].tail)
546
+ ),
547
+ }.get(dtype)
548
+ if not converter:
549
+ raise NotImplementedError(f"Unhandled type: {dtype}")
550
+ obj = converter(element)
551
+
552
+ if not self.ignore_units and (
553
+ units := element.attrib.get(f"{{{self.sbml_core_ns}}}units", None)
554
+ ):
555
+ if units not in self.ureg:
556
+ # TODO fixme: replace rhs by base units
557
+ # this requires access to the underlying SBML model to access
558
+ # unit definitions. they should be parsed during __init__.
559
+ # base units defined in SBML can be handled without a model,
560
+ # as they are not allowed to be redefined (are they?).
561
+ # should start from an empty UnitRegistry, as sbml could
562
+ # redefine any (non-base?)unit to whatever.
563
+ self.ureg.define(f"{units} = {units}")
564
+ # TODO pint.Quantity causes issues with sympy functions:
565
+ # https://docs.sympy.org/latest/explanation/active-deprecations.html#non-expr-args-deprecated
566
+ return self.ureg.Quantity(obj, units)
567
+ return obj
568
+
569
+ def handle_piecewise(self, element: etree._Element) -> sp.Expr:
570
+ expr_cond_pairs = []
571
+ for e in element:
572
+ # TODO: cannot currently handle functions as condition-arguments.
573
+ # they need to be derived from `sympy.BooleanFunction`
574
+ # Nested piecewise functions may work, though, if the inner
575
+ # expressions are all Boolean
576
+ if e.tag == f"{{{mathml_ns}}}piece":
577
+ assert len(e) == 2
578
+ cond = self._parse_element(e[1])
579
+ # Only Boolean conditions are supported
580
+ # -> convert
581
+ # this won't round-trip
582
+ cond = self._num2bool(cond)
583
+ expr_cond_pairs.append(
584
+ (self._parse_element(e[0]), cond),
585
+ )
586
+ elif e.tag == f"{{{mathml_ns}}}otherwise":
587
+ # may occur only as last condition
588
+ assert e is element[-1]
589
+ assert len(e) == 1
590
+ expr_cond_pairs.append(
591
+ (self._parse_element(e[0]), True),
592
+ )
593
+ else:
594
+ raise AssertionError(e.tag)
595
+
596
+ with sp.evaluate(self.evaluate):
597
+ return sp.Piecewise(*expr_cond_pairs)
598
+
599
+ def handle_lambda(self, element: etree._Element) -> sp.Expr:
600
+ # See https://www.w3.org/TR/MathML2/chapter4.html#id.4.2.1.7
601
+ # collect arguments / bound variables
602
+ args = []
603
+ for e in element[:-1]:
604
+ assert e.tag == f"{{{mathml_ns}}}bvar"
605
+ assert len(e) == 1
606
+ args.append(self._parse_element(e[0]))
607
+
608
+ # Bound variables may be Boolean, depending on the call site.
609
+ # Therefore, they must not be converted in Boolean contexts.
610
+ outer_bound_symbols = self._bound_symbols
611
+ self._bound_symbols = outer_bound_symbols | set(args)
612
+ try:
613
+ rhs = self._parse_element(element[-1])
614
+ finally:
615
+ self._bound_symbols = outer_bound_symbols
616
+ return sp.Lambda(tuple(args), rhs)
617
+
618
+ def handle_degree(self, element: etree._Element) -> sp.Expr:
619
+ assert len(element) == 1
620
+ return self._parse_element(element[0])
621
+
622
+ def handle_logbase(self, element: etree._Element) -> sp.Expr:
623
+ assert len(element) == 1
624
+ return self._parse_element(element[0])
625
+
626
+ def handle_csymbol(self, element: etree._Element) -> sp.Expr:
627
+ assert element.attrib["encoding"] == "text"
628
+ return CSymbol(
629
+ self.preprocess_symbol_name(element.text.strip(), element),
630
+ encoding=element.attrib["encoding"],
631
+ definition_url=element.attrib["definitionURL"],
632
+ **self.symbol_kwargs,
633
+ )
634
+
635
+ def _num2bool(self, x: sp.Basic) -> sp.Basic:
636
+ """Convert operands in Boolean contexts to Boolean expressions."""
637
+ return _num2bool(x, boolean_symbols=self._bound_symbols)
638
+
639
+ def preprocess_symbol_name(
640
+ self, name: str, element: etree._Element = None
641
+ ) -> str:
642
+ """Preprocess symbol names.
643
+
644
+ Override this method to preprocess symbol names before parsing.
645
+ For example, to handle reserved names.
646
+
647
+ Does nothing by default.
648
+
649
+ :param name: Symbol name in the MathML element.
650
+ :param element: MathML element.
651
+ :return: Preprocessed symbol name.
652
+ """
653
+ return name
654
+
655
+
656
+ def _bool2num(x: sp.Basic) -> sp.Basic:
657
+ """Convert sympy Booleans to expressions or Integers.
658
+
659
+ Peforms boolean->{int,float} conversion via
660
+ ``Piecewise((1, expr), (0, True))``.
661
+
662
+ Return anything else as is.
663
+ """
664
+ if isinstance(x, BooleanFalse):
665
+ return sp.Integer(0)
666
+ if isinstance(x, BooleanTrue):
667
+ return sp.Integer(1)
668
+ if isinstance(x, Boolean) and not isinstance(x, sp.Symbol):
669
+ # `Piecewise((1, expr),(0,True))`
670
+ return Piecewise((sp.Integer(1), x), (sp.Integer(0), sp.true))
671
+
672
+ return x
673
+
674
+
675
+ def _num2bool(
676
+ x: sp.Basic, boolean_symbols: Collection[sp.Symbol] = ()
677
+ ) -> sp.Basic:
678
+ """Convert non-Booleans to Boolean expressions.
679
+
680
+ ``expr -> Ne(expr, 0)``
681
+
682
+ Symbols are treated as numeric, except for those in `boolean_symbols`.
683
+
684
+ Piecewise expressions are converted to equivalent Boolean expressions:
685
+
686
+ ``Piecewise((v1, c1), (v2, c2), ...)
687
+ -> (c1 & v1) | (~c1 & c2 & v2) | ...``
688
+
689
+ where the values ``v_i`` are converted recursively.
690
+
691
+ Return anything else as is.
692
+ """
693
+ if isinstance(x, Piecewise):
694
+ terms = []
695
+ previous_conds = []
696
+ for expr, cond in x.args:
697
+ terms.append(
698
+ sp.And(*previous_conds, cond, _num2bool(expr, boolean_symbols))
699
+ )
700
+ previous_conds.append(sp.Not(cond))
701
+ return sp.Or(*terms)
702
+ if isinstance(x, sp.Symbol):
703
+ return x if x in boolean_symbols else sp.Ne(x, 0)
704
+ if not isinstance(x, Boolean):
705
+ return sp.Ne(x, 0)
706
+ return x