Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions changelog.d/+reject-undefined-math.fix.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Reject NaN and complex infinity when printing PEtab mathematical expressions,
including nested expressions, instead of writing expressions that cannot be
read back. Positive and negative real infinity remain supported
([#613](https://github.com/PEtab-dev/libpetab-python/pull/613)).
14 changes: 14 additions & 0 deletions petab/v1/math/printer.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,16 @@ def _print_NegativeInfinity(self, expr):
"""Custom printing for negative infinity"""
return "-inf"

def _print_NaN(self, expr: sp.Basic) -> typing.NoReturn:
"""Reject undefined values instead of emitting invalid PEtab math."""
raise ValueError("NaN cannot be represented in PEtab.")

def _print_ComplexInfinity(self, expr: sp.Basic) -> typing.NoReturn:
"""Reject complex infinity, which has no PEtab representation."""
raise ValueError(
"Complex infinity (zoo) cannot be represented in PEtab."
)

def _print_Function(self, expr):
"""Custom printing for specific functions"""

Expand Down Expand Up @@ -153,6 +163,10 @@ def _print_Max(self, expr):
def petab_math_str(expr: sp.Basic | sp.Expr | None) -> str:
"""Convert a sympy expression to a PEtab-compatible math expression string.

Raises:
ValueError: If the expression contains NaN or complex infinity, or
a piecewise expression without a default value.

:example:
>>> expr = sp.sympify("x**2 + sin(y)")
>>> petab_math_str(expr)
Expand Down
33 changes: 32 additions & 1 deletion tests/v1/math/test_math.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,45 @@
from sympy.abc import _clash
from sympy.logic.boolalg import Boolean, BooleanFalse, BooleanTrue

from petab.v1.math import petab_math_str, petab_symbol, sympify_petab
from petab.v1.math import (
PetabStrPrinter,
petab_math_str,
petab_symbol,
sympify_petab,
)
from petab.v1.math.SympyVisitor import num2bool


def test_sympify_numpy():
assert sympify_petab(np.float64(1.0)) == sp.Float(1.0)


@pytest.mark.parametrize(
"printer", [petab_math_str, PetabStrPrinter().doprint]
)
@pytest.mark.parametrize(
"expr",
[
sp.nan,
sp.zoo,
sympify_petab("x / 0"),
sp.Add(petab_symbol("x"), sp.nan, evaluate=False),
sp.Piecewise((sp.nan, petab_symbol("x") > 0), (0, True)),
sp.Piecewise((1, petab_symbol("x") > 0), (sp.zoo, True)),
],
)
def test_printer_rejects_undefined_values(printer, expr):
"""Undefined values must not be exported as unreadable PEtab math."""
with pytest.raises(ValueError, match="cannot be represented in PEtab"):
printer(expr)


@pytest.mark.parametrize("expr", [sp.oo, -sp.oo])
def test_printer_infinity_roundtrip(expr):
"""Real infinities remain supported, unlike complex infinity."""
assert sympify_petab(petab_math_str(expr)) == expr


def test_parse_simple():
"""Test simple numeric expressions."""
assert float(sympify_petab("1 + 2")) == 3
Expand Down