diff --git a/petab/v1/math/SympyVisitor.py b/petab/v1/math/SympyVisitor.py index c9322308..e1bd3dac 100644 --- a/petab/v1/math/SympyVisitor.py +++ b/petab/v1/math/SympyVisitor.py @@ -99,6 +99,12 @@ def __init__(self, evaluate=True): super().__init__() self.evaluate = evaluate + def _bool2num(self, x: sp.Basic | sp.Expr) -> sp.Basic | sp.Expr: + return bool2num(x, evaluate=self.evaluate) + + def _num2bool(self, x: sp.Basic | sp.Expr) -> sp.Basic | sp.Expr: + return num2bool(x, evaluate=self.evaluate) + def visitPetabExpression( self, ctx: PetabMathExprParser.PetabExpressionContext ) -> sp.Expr | sp.Basic: @@ -120,8 +126,8 @@ def visitMultExpr( ) -> sp.Expr: """Convert multiplication and division expressions to sympy.""" if ctx.getChildCount() == 3: - operand1 = bool2num(self.visit(ctx.getChild(0))) - operand2 = bool2num(self.visit(ctx.getChild(2))) + operand1 = self._bool2num(self.visit(ctx.getChild(0))) + operand2 = self._bool2num(self.visit(ctx.getChild(2))) if ctx.ASTERISK(): return sp.Mul(operand1, operand2, evaluate=self.evaluate) if ctx.SLASH(): @@ -139,8 +145,8 @@ def visitMultExpr( def visitAddExpr(self, ctx: PetabMathExprParser.AddExprContext) -> sp.Expr: """Convert addition and subtraction expressions to sympy.""" - op1 = bool2num(self.visit(ctx.getChild(0))) - op2 = bool2num(self.visit(ctx.getChild(2))) + op1 = self._bool2num(self.visit(ctx.getChild(0))) + op2 = self._bool2num(self.visit(ctx.getChild(2))) if ctx.PLUS(): return sp.Add(op1, op2, evaluate=self.evaluate) if ctx.MINUS(): @@ -168,7 +174,7 @@ def visitFunctionCall( if func_name != "piecewise": # all functions except piecewise expect numerical arguments - args = list(map(bool2num, args)) + args = list(map(self._bool2num, args)) if func_name in _trig_funcs: if len(args) != 1: @@ -213,7 +219,8 @@ def visitFunctionCall( # `else` case args.append(sp.true) sp_args = ( - (true_expr, num2bool(condition)) + # piecewise is float-valued, also for Boolean values + (self._bool2num(true_expr), self._num2bool(condition)) for true_expr, condition in zip( args[::2], args[1::2], strict=True ) @@ -235,8 +242,8 @@ def visitPowerExpr( f"Unexpected number of children: {ctx.getChildCount()} " f"in {ctx.getText()}" ) - operand1 = bool2num(self.visit(ctx.getChild(0))) - operand2 = bool2num(self.visit(ctx.getChild(2))) + operand1 = self._bool2num(self.visit(ctx.getChild(0))) + operand2 = self._bool2num(self.visit(ctx.getChild(2))) return sp.Pow(operand1, operand2, evaluate=self.evaluate) def visitUnaryExpr( @@ -244,7 +251,7 @@ def visitUnaryExpr( ) -> sp.Basic | sp.Expr: """Convert unary expressions to sympy.""" if ctx.getChildCount() == 2: - operand = bool2num(self.visit(ctx.getChild(1))) + operand = self._bool2num(self.visit(ctx.getChild(1))) match ctx.getChild(0).getText(): case "-": return -operand @@ -272,8 +279,8 @@ def visitComparisonExpr( ">=": sp.GreaterThan, } if op in ops: - lhs = bool2num(lhs) - rhs = bool2num(rhs) + lhs = self._bool2num(lhs) + rhs = self._bool2num(rhs) return ops[op](lhs, rhs, evaluate=self.evaluate) raise AssertionError(f"Unexpected operator: {op}") @@ -283,7 +290,7 @@ def visitBooleanNotExpr( ) -> sp.Basic | sp.Expr: """Convert boolean NOT expressions to sympy.""" if ctx.getChildCount() == 2: - return ~num2bool(self.visit(ctx.getChild(1))) + return ~self._num2bool(self.visit(ctx.getChild(1))) raise AssertionError(f"Unexpected expression: {ctx.getText()}") @@ -294,8 +301,8 @@ def visitBooleanAndOrExpr( if ctx.getChildCount() != 3: raise AssertionError(f"Unexpected expression: {ctx.getText()}") - operand1 = num2bool(self.visit(ctx.getChild(0))) - operand2 = num2bool(self.visit(ctx.getChild(2))) + operand1 = self._num2bool(self.visit(ctx.getChild(0))) + operand2 = self._num2bool(self.visit(ctx.getChild(2))) if ctx.BOOLEAN_AND(): return operand1 & operand2 @@ -317,19 +324,38 @@ def visitBooleanLiteral( raise AssertionError(f"Unexpected boolean literal: {ctx.getText()}") -def bool2num(x: sp.Basic | sp.Expr) -> sp.Basic | sp.Expr: - """Convert sympy Booleans to Floats.""" +def bool2num( + x: sp.Basic | sp.Expr, evaluate: bool = True +) -> sp.Basic | sp.Expr: + """Convert sympy Booleans to numeric expressions. + + True is converted to 1.0, false to 0.0. Non-constant Booleans ``b`` are + converted to ``Piecewise((1.0, b), (0.0, True))``. + + :param x: The expression to convert. + :param evaluate: Whether to evaluate the resulting expression. + """ if isinstance(x, BooleanFalse): return sp.Float(0) if isinstance(x, BooleanTrue): return sp.Float(1) + # sp.Symbol is both Boolean and Expr; PEtab symbols are numeric + if isinstance(x, Boolean) and not isinstance(x, sp.Expr): + return sp.Piecewise( + (sp.Float(1), x), (sp.Float(0), True), evaluate=evaluate + ) return x -def num2bool(x: sp.Basic | sp.Expr) -> sp.Basic | sp.Expr: +def num2bool( + x: sp.Basic | sp.Expr, evaluate: bool = True +) -> sp.Basic | sp.Expr: """Convert sympy numeric expressions to booleans. Zero is converted to false, any other value to true. + + :param x: The expression to convert. + :param evaluate: Whether to evaluate the resulting expression. """ # sp.Symbol is both Boolean and Expr; PEtab symbols are numeric if isinstance(x, Boolean) and not isinstance(x, sp.Expr): @@ -337,6 +363,16 @@ def num2bool(x: sp.Basic | sp.Expr) -> sp.Basic | sp.Expr: if isinstance(x, sp.Piecewise): # Boolean-valued pieces have to be converted to numbers first x = sp.Piecewise( - *((bool2num(expr), cond) for expr, cond in x.args), + *((bool2num(expr, evaluate), cond) for expr, cond in x.args), + evaluate=evaluate, ) - return sp.Ne(x, 0) + # Invert `bool2num`: Piecewise((a, c), (0, True)) with a != 0 -> c + if ( + isinstance(x, sp.Piecewise) + and len(x.args) == 2 + and x.args[0].expr.is_zero is False + and x.args[1].expr.is_zero is True + and x.args[1].cond == sp.true + ): + return x.args[0].cond + return sp.Ne(x, 0, evaluate=evaluate) diff --git a/petab/v1/math/printer.py b/petab/v1/math/printer.py index e518459a..b6973ebe 100644 --- a/petab/v1/math/printer.py +++ b/petab/v1/math/printer.py @@ -70,6 +70,10 @@ def _print_Not(self, expr): """Custom printing for logical NOT""" return f"!{self._print_bool_operand(expr.args[0])}" + def _print_ITE(self, expr): + """Custom printing for if-then-else (no equivalent in PEtab)""" + return self._print(expr.to_nnf()) + def _print_Pow(self, expr: sp.Pow): """Custom printing for the power operator""" base, exp = expr.as_base_exp() diff --git a/petab/v1/math/sympify.py b/petab/v1/math/sympify.py index da129e04..a4305755 100644 --- a/petab/v1/math/sympify.py +++ b/petab/v1/math/sympify.py @@ -58,12 +58,15 @@ def sympify_petab( 1.00000000000000 >>> sympify_petab("true", evaluate=False) 1.00000000000000 + >>> # non-constant Booleans are converted to piecewise functions + >>> sympify_petab("x > 0") + Piecewise((1.0, x > 0), (0.0, True)) >>> # ... and integer values are converted to floats >>> sympify_petab("2", evaluate=True) 2.00000000000000 """ if isinstance(expr, sp.Basic): - return sympify_petab(petab_math_str(expr)) + return sympify_petab(petab_math_str(expr), evaluate=evaluate) if isinstance(expr, (int, np.integer)): return sp.Integer(expr) @@ -94,7 +97,7 @@ def sympify_petab( # Convert to sympy expression visitor = MathVisitorSympy(evaluate=evaluate) expr = visitor.visit(tree) - expr = bool2num(expr) + expr = bool2num(expr, evaluate=evaluate) try: # check for `False`, we'll accept both `True` and `None` if expr.is_extended_real is False: diff --git a/tests/v1/math/test_math.py b/tests/v1/math/test_math.py index 47fa596a..03c04ac5 100644 --- a/tests/v1/math/test_math.py +++ b/tests/v1/math/test_math.py @@ -9,6 +9,7 @@ from sympy.logic.boolalg import Boolean, BooleanFalse, BooleanTrue from petab.v1.math import petab_math_str, petab_symbol, sympify_petab +from petab.v1.math.SympyVisitor import num2bool def test_sympify_numpy(): @@ -62,6 +63,9 @@ def test_printer(): ) assert petab_math_str(sp.Eq(a, 1)) == "a == 1" assert petab_math_str(sp.Ne(a, 1)) == "a != 1" + assert petab_math_str(sp.ITE(a > 0, b > 0, c > 0)) == ( + "((a <= 0) || (b > 0)) && ((a > 0) || (c > 0))" + ) # min/max are binary in PEtab assert petab_math_str(sp.Min(a, b, c)) == "min(min(a, b), c)" assert petab_math_str(sp.Max(a, b, c)) == "max(max(a, b), c)" @@ -116,16 +120,16 @@ def test_print_parse_round_trip(expr_str, evaluate): "expr_str, expected", [ # expected values for x = -1, 0, 1 (y = 3) - ("(x + 1) && (y > 2)", [False, True, True]), - ("(x + 1) || (y < 2)", [False, True, True]), - ("!(x + 1)", [True, False, False]), + ("(x + 1) && (y > 2)", [0.0, 1.0, 1.0]), + ("(x + 1) || (y < 2)", [0.0, 1.0, 1.0]), + ("!(x + 1)", [1.0, 0.0, 0.0]), ("piecewise(1, x + 1, 0)", [0.0, 1.0, 1.0]), - ("x && y", [True, False, True]), - ("!x", [False, True, False]), - ("piecewise(1, x > 0, 0) && true", [False, False, True]), - ("!piecewise(1, x < 0, 0)", [False, True, True]), - ("piecewise(true, x > 0, false) && true", [False, False, True]), - ("!piecewise(true, x < 0, false)", [False, True, True]), + ("x && y", [1.0, 0.0, 1.0]), + ("!x", [0.0, 1.0, 0.0]), + ("piecewise(1, x > 0, 0) && true", [0.0, 0.0, 1.0]), + ("!piecewise(1, x < 0, 0)", [0.0, 1.0, 1.0]), + ("piecewise(true, x > 0, false) && true", [0.0, 0.0, 1.0]), + ("!piecewise(true, x < 0, false)", [0.0, 1.0, 1.0]), ("piecewise(1, piecewise(true, x > 0, false), 0)", [0.0, 0.0, 1.0]), ], ) @@ -141,6 +145,8 @@ def test_num2bool(expr_str, expected, evaluate): e.subs({x: sp.Float(x_val), y: sp.Float(3.0)}) for x_val in (-1.0, 0.0, 1.0) ] + # sympy may return Integer(0), which is != Float(0) + actual = [float(a) for a in actual] assert actual == expected, e @@ -197,6 +203,86 @@ def test_parse_cases(expr_str, expected): assert resympified.equals(sym_expr), (sym_expr, resympified) +@pytest.mark.parametrize( + "expr_str, expected", + [ + # expected values for x = -1, 0, 1 (y = 3) + ("x > 0", [0.0, 0.0, 1.0]), + ("1 + (x > 0)", [1.0, 1.0, 2.0]), + ("2 * (x >= 0)", [0.0, 2.0, 2.0]), + ("-(x > 0)", [0.0, 0.0, -1.0]), + ("(x >= 0) ^ 2", [0.0, 1.0, 1.0]), + ("sign(x >= 0)", [0.0, 1.0, 1.0]), + ("(x > 0) && (y > 2)", [0.0, 0.0, 1.0]), + ("!(x > 0)", [1.0, 1.0, 0.0]), + ("(x > 0) == (y > 2)", [0.0, 0.0, 1.0]), + ("piecewise(true, x > 0, false)", [0.0, 0.0, 1.0]), + ("piecewise(true, x > 0, false) + 1", [1.0, 1.0, 2.0]), + ], +) +@pytest.mark.parametrize("evaluate", [True, False]) +def test_bool2num(expr_str, expected, evaluate): + """Non-constant Booleans in numeric context: true is 1, false is 0.""" + x, y = sp.symbols("x y", real=True) + expr = sympify_petab(expr_str, evaluate=evaluate) + reparsed = sympify_petab(petab_math_str(expr), evaluate=evaluate) + for e in (expr, reparsed): + assert {x, y} & e.free_symbols, e + actual = [ + e.subs({x: sp.Float(x_val), y: sp.Float(3.0)}) + for x_val in (-1.0, 0.0, 1.0) + ] + # sympy may return Integer(0), which is != Float(0) + actual = [float(a) for a in actual] + assert actual == expected, e + + +@pytest.mark.parametrize( + "expr_str, expected_str", + [ + ("1 + (1 > 0)", "piecewise(1, 1 > 0, 0) + 1"), + ("piecewise(2, 1, 3)", "piecewise(2, 1 != 0, 3)"), + ], +) +def test_bool_num_conversion_unevaluated(expr_str, expected_str): + """Boolean/numeric conversions respect ``evaluate=False``.""" + expr = sympify_petab(expr_str, evaluate=False) + assert petab_math_str(expr) == expected_str + assert float(expr) == float(sympify_petab(expr_str)) + + +def test_sympify_sympy_input_unevaluated(): + expr = sympify_petab(sp.Gt(1, 0, evaluate=False), evaluate=False) + assert petab_math_str(expr) == "piecewise(1, 1 > 0, 0)" + + +def test_num2bool_returns_boolean(): + x = sp.Symbol("x", real=True) + assert isinstance(num2bool(x + 1), Boolean) + assert num2bool(sp.Float(0)) == sp.false + assert num2bool(sp.Float(2)) == sp.true + # Boolean-valued pieces + pw = sp.Piecewise((sp.true, x > 0), (sp.false, True)) + assert [num2bool(pw).subs(x, v) for v in (-1, 1)] == [sp.false, sp.true] + # inverse of bool2num + assert num2bool(sp.Piecewise((1.0, x > 0), (0.0, True))) == (x > 0) + + +@pytest.mark.parametrize( + "expr_str, expected_str", + [ + ("((x > 0) + 0) && (y > 0)", "piecewise(1, (x > 0) && (y > 0), 0)"), + ( + "piecewise(1, x > 0, 0) && y", + "piecewise(1, (x > 0) && (y != 0), 0)", + ), + ], +) +def test_bool_num_bool_round_trip(expr_str, expected_str): + """Booleans converted to numbers and back are not wrapped further.""" + assert petab_math_str(sympify_petab(expr_str)) == expected_str + + def test_ids(): """Test symbols in expressions.""" assert sympify_petab("bla * 2") == 2.0 * sp.Symbol("bla", real=True)