|
| 1 | +"""A PEtab-compatible sympy string-printer.""" |
| 2 | + |
| 3 | +from itertools import chain, islice |
| 4 | + |
| 5 | +import sympy as sp |
| 6 | +from sympy.printing.str import StrPrinter |
| 7 | + |
| 8 | + |
| 9 | +class PetabStrPrinter(StrPrinter): |
| 10 | + """A PEtab-compatible sympy string-printer.""" |
| 11 | + |
| 12 | + #: Mapping of sympy functions to PEtab functions |
| 13 | + func_map = { |
| 14 | + "asin": "arcsin", |
| 15 | + "acos": "arccos", |
| 16 | + "atan": "arctan", |
| 17 | + "acot": "arccot", |
| 18 | + "asec": "arcsec", |
| 19 | + "acsc": "arccsc", |
| 20 | + "asinh": "arcsinh", |
| 21 | + "acosh": "arccosh", |
| 22 | + "atanh": "arctanh", |
| 23 | + "acoth": "arccoth", |
| 24 | + "asech": "arcsech", |
| 25 | + "acsch": "arccsch", |
| 26 | + "Abs": "abs", |
| 27 | + } |
| 28 | + |
| 29 | + def _print_BooleanTrue(self, expr): |
| 30 | + return "true" |
| 31 | + |
| 32 | + def _print_BooleanFalse(self, expr): |
| 33 | + return "false" |
| 34 | + |
| 35 | + def _print_Pow(self, expr: sp.Pow): |
| 36 | + """Custom printing for the power operator""" |
| 37 | + base, exp = expr.as_base_exp() |
| 38 | + return f"{self._print(base)} ^ {self._print(exp)}" |
| 39 | + |
| 40 | + def _print_Infinity(self, expr): |
| 41 | + """Custom printing for infinity""" |
| 42 | + return "inf" |
| 43 | + |
| 44 | + def _print_NegativeInfinity(self, expr): |
| 45 | + """Custom printing for negative infinity""" |
| 46 | + return "-inf" |
| 47 | + |
| 48 | + def _print_Function(self, expr): |
| 49 | + """Custom printing for specific functions""" |
| 50 | + |
| 51 | + if expr.func.__name__ == "Piecewise": |
| 52 | + return self._print_Piecewise(expr) |
| 53 | + |
| 54 | + if func := self.func_map.get(expr.func.__name__): |
| 55 | + return f"{func}({', '.join(map(self._print, expr.args))})" |
| 56 | + |
| 57 | + return super()._print_Function(expr) |
| 58 | + |
| 59 | + def _print_Piecewise(self, expr): |
| 60 | + """Custom printing for Piecewise function""" |
| 61 | + # merge the tuples and drop the final `True` condition |
| 62 | + str_args = map( |
| 63 | + self._print, |
| 64 | + islice(chain.from_iterable(expr.args), len(expr.args) - 1), |
| 65 | + ) |
| 66 | + return f"piecewise({', '.join(str_args)})" |
| 67 | + |
| 68 | + def _print_Min(self, expr): |
| 69 | + """Custom printing for Min function""" |
| 70 | + return f"min({', '.join(map(self._print, expr.args))})" |
| 71 | + |
| 72 | + def _print_Max(self, expr): |
| 73 | + """Custom printing for Max function""" |
| 74 | + return f"max({', '.join(map(self._print, expr.args))})" |
| 75 | + |
| 76 | + |
| 77 | +def petab_math_str(expr: sp.Expr) -> str: |
| 78 | + """Convert a sympy expression to a PEtab-compatible math expression string. |
| 79 | +
|
| 80 | + :example: |
| 81 | + >>> expr = sp.sympify("x**2 + sin(y)") |
| 82 | + >>> petab_math_str(expr) |
| 83 | + 'x ^ 2 + sin(y)' |
| 84 | + """ |
| 85 | + |
| 86 | + return PetabStrPrinter().doprint(expr) |
0 commit comments