From cb0cc40afa8e82302cd5f36555bc0419aa6dbf70 Mon Sep 17 00:00:00 2001 From: Yohan Painchaud Date: Wed, 25 Nov 2026 18:58:54 +0100 Subject: [PATCH] feat(GG-3824): Add LogBase and explicit errors for impossible calculations - ["LogBase", x, b]: logarithm in base b, exact for bases 10 and 2. ["Log", x] stays the natural logarithm, whatever its base. - MathJSONDomainError: logarithm of a number <= 0, base <= 0 or equal to 1, even or fractional root of a negative number, power of a negative number with a non-integer exponent. No complex result any more; an odd root of a negative number is real. - MathJSONOverflowError / MathJSONUnderflowError: finite operands giving a non-finite, too large or too small (0.0) result. Infinite and NaN values coming from the parameters raise neither. - MathJSONUnsupportedOperator: in strict mode, a formula whose operator is unknown. Lists given as parameter values stay data. - If and Map let these errors through instead of swallowing them. - Power of integers still gives an integer. Package version 1.14.0.post5, for tag 1.10.0-5. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 20 +++ README.md | 10 +- docs/README.md | 9 +- setup.cfg | 2 +- setup.py | 2 +- src/mathjson_solver/__init__.py | 4 + src/mathjson_solver/__main__.py | 249 ++++++++++++++++++++++++++---- tests/test_with_pytest.py | 262 ++++++++++++++++++++++++++++++++ 8 files changed, 523 insertions(+), 35 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2b5334e..e6457d4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,27 @@ Git tags of this fork (`1.10.0-N`) do not follow the package version declared in | Tag | Package version | Changes | |---|---|---| +| `1.10.0-5` | `1.14.0.post5` | `LogBase` operator. Out-of-domain, overflow and underflow errors; strict mode rejects unsupported operators; `If` and `Map` let these errors through. Details below. | | `1.10.0-4` | `1.14.0` | `create_solver(parameters, strict=True)`: an undefined or `None` parameter raises a `MathJSONException` caused by `MathJSONUnresolvedParameter`. `IsDefined` implemented. `Str` and `Not` keep the `Constants` context. `extract_variables` reads the final expression of `Constants` and ignores `Str` / `Date` literals. | | `1.10.0-3` | `1.14.0` | `Date` operator. | | `1.10.0-2` | `1.14.0` | Comparison operators accept multiple operands. | | `1.10.0-1` | `1.10.0` | `Rational` and `Ln` operators. | + +## 1.10.0-5 (package version 1.14.0.post5) + +### Added +- `["LogBase", x, b]`: logarithm of `x` in base `b`, exact for bases 10 and 2 (`["LogBase", 1000, 10]` is `3.0`, `["LogBase", 8, 2]` is `3.0`). +- Exceptions exported from `mathjson_solver`, found as the `e` of the `MathJSONException`: + - `MathJSONDomainError` (a `ValueError`): logarithm (`Ln`, `Log`, `Log2`, `Log10`, `LogBase`) of a number `<= 0`, base `<= 0` or `== 1`, root (`Sqrt`, `Root`) of a negative number whose exponent `1/n` is not an integer, e.g. `["Root", -16, 4]`, power of a negative number with a non-integer exponent. No result is a complex number any more. + - `MathJSONOverflowError` (an `OverflowError`): a calculation on finite numbers whose result is infinite, NaN or too large for a float, e.g. `["Power", 10, 400]`, `["Exp", 1000]`, `["Multiply", 1e300, 1e300]`. Any other `OverflowError` raised by an operator is converted to it. + - `MathJSONUnderflowError` (an `ArithmeticError`): `Power` or `Exp` of finite numbers whose non-zero result becomes `0.0`, e.g. `["Power", 10, -400]`, `["Exp", -1000]`. + - `MathJSONUnsupportedOperator` (a `NotImplementedError`): in strict mode, a formula whose operator is unknown, e.g. `["Floor", 2.5]`. A list given as a parameter value, at any depth, is data and is still returned as is. +- `Root` of a negative number with an odd index is real: `["Root", -8, 3]` is `-2.0`. + +### Changed +- Infinite and NaN values coming from the parameters raise neither an overflow nor an underflow: only finite operands do. Converting an infinite value to an integer (`Round`, `Int`) still fails, now as a `MathJSONOverflowError`. +- `If` and `Map` let the errors above through instead of falling back to the `else` branch or to the element. Any other `MathJSONException` is still caught. For instance, `["If", [["Greater", ["Log10", "x"], 1], 1], 2]` with `x = 0` gave `2` and now raises a domain error. + +### Unchanged +- `["Log", x]` is still the natural logarithm, whatever its base argument. +- `Power` of integers still gives an integer: `["Power", 2, 3]` is `8`. diff --git a/README.md b/README.md index e91acf1..39dea2d 100644 --- a/README.md +++ b/README.md @@ -43,6 +43,13 @@ except MathJSONException: Left unhandled, the exception will look like `MathJSONException("Problem in Divide. ['Divide', 1, 0]. division by zero")`. +The original error is the exception's `e`. A calculation that cannot be done gives one of these errors: +* `MathJSONDomainError` (a `ValueError`): an argument is outside the domain of the operator, e.g. `["Log10", 0]`, `["Sqrt", -4]`; +* `MathJSONOverflowError` (an `OverflowError`): finite numbers give a result too large for a float, e.g. `["Power", 10, 400]`; +* `MathJSONUnderflowError` (an `ArithmeticError`): `Power`, `Square` or `Exp` of finite numbers gives a non-zero result too small for a float, e.g. `["Exp", -1000]`. + +Infinite and NaN values given as parameters raise neither an overflow nor an underflow: `inf * 100` is `inf`. Converting an infinite value to an integer (`Round`, `Int`) raises a `MathJSONOverflowError`. + ## Strict mode @@ -62,7 +69,8 @@ In strict mode: * a parameter whose value is `None` is unresolved too; * string values of parameters are returned as is, not resolved again as names; * string literals must be written with `Str`: `["Str", "plasma"]` returns `"plasma"` without looking it up. Bare strings anywhere else (`Switch` cases, `In` arrays, `Strptime` formats, ...) are parameter names; -* `If`, `Map` and `HasMatchingSublist` still catch a `MathJSONException` raised by a branch or an element, as they do in the default mode. +* a formula whose operator is unknown raises a `MathJSONException` caused by `MathJSONUnsupportedOperator` (a `NotImplementedError`), instead of being returned unchanged. A list given as a parameter value is data, and is returned as is; +* `If` and `Map` still catch a `MathJSONException` raised by a branch or an element, as they do in the default mode, except the calculation errors above, which they let through in both modes. ## How to run tests diff --git a/docs/README.md b/docs/README.md index 205306a..b4445d7 100644 --- a/docs/README.md +++ b/docs/README.md @@ -19,6 +19,7 @@ * [Log](#exponents-and-logarithms) * [Log2](#exponents-and-logarithms) * [Log10](#exponents-and-logarithms) +* [LogBase](#exponents-and-logarithms) * [Equal](#equality-greater-than-less-than) * [StrictEqual](#equality-greater-than-less-than) * [NotEqual](#equality-greater-than-less-than) @@ -139,25 +140,31 @@ Performs a division. ``` #### Square and Power -`Power` raises a number to given power. `Square` is a special case of `Power`. +`Power` raises a number to given power. `Square` is a special case of `Power`. A negative number with a non-integer exponent raises a `MathJSONDomainError`, a result too large for a float a `MathJSONOverflowError`, and a non-zero result too small for a float a `MathJSONUnderflowError`. ```python ["Power", 2, 3] # 2^3=8 +["Power", 10, -3] # 10^-3=0.001 ["Square", 4] # 4^2=16 ``` #### Root and square root +An odd root of a negative number is real. Any other root of a negative number, whose exponent `1/n` is not an integer, raises a `MathJSONDomainError`. ```python ["Root", 9, 2] # √9=3.0 ["Root", 8, 3] # ∛8=2.0 +["Root", -8, 3] # ∛-8=-2.0 ["Sqrt", 9] # √9=3.0 ``` #### Exponents and logarithms +`Log` is the natural logarithm, like `Ln`, and ignores a second argument: use `LogBase` for another base. The logarithm of a number `<= 0`, or in a base `<= 0` or equal to 1, raises a `MathJSONDomainError`. ```python ["Exp", 2] # e^2≅7.389 ["Log", 2.7183] # ln(2.7183)≅1.0000 +["Ln", 2.7183] # ln(2.7183)≅1.0000 ["Log2", 8] # log2(8)=3.0 ["Log10", 1000] # log10(1000)=3.0 +["LogBase", 8, 2] # log2(8)=3.0 ``` ### Conditionality diff --git a/setup.cfg b/setup.cfg index d8ec57c..4ab1571 100644 --- a/setup.cfg +++ b/setup.cfg @@ -1,6 +1,6 @@ [metadata] name = mathjson-solver -version = 1.14.0 +version = 1.14.0.post5 author = Martins Mednis author_email = mrt@mednis.info description = Utilities for MathJSON evaluation diff --git a/setup.py b/setup.py index 5e32614..0442835 100644 --- a/setup.py +++ b/setup.py @@ -5,7 +5,7 @@ setuptools.setup( name="mathjson-solver", - version="1.14.0", + version="1.14.0.post5", author="Martins Mednis", author_email="mrt@mednis.info", description="Utilities for MathJSON evaluation", diff --git a/src/mathjson_solver/__init__.py b/src/mathjson_solver/__init__.py index 433041e..9b30965 100644 --- a/src/mathjson_solver/__init__.py +++ b/src/mathjson_solver/__init__.py @@ -1,6 +1,10 @@ from .__main__ import create_mathjson_solver as create_solver from .__main__ import ( + MathJSONDomainError, MathJSONException, + MathJSONOverflowError, + MathJSONUnderflowError, MathJSONUnresolvedParameter, + MathJSONUnsupportedOperator, extract_variables, ) diff --git a/src/mathjson_solver/__main__.py b/src/mathjson_solver/__main__.py index 604ac21..87694c7 100644 --- a/src/mathjson_solver/__main__.py +++ b/src/mathjson_solver/__main__.py @@ -36,6 +36,143 @@ def __str__(self): return str(self.args[0]) +class MathJSONDomainError(ValueError): + """The arguments are outside the mathematical domain of the operator""" + + +class MathJSONOverflowError(OverflowError): + """A calculation on finite numbers gives a result too large for a float""" + + +class MathJSONUnderflowError(ArithmeticError): + """A calculation gives a non-zero result too small for a float, so 0""" + + +class MathJSONUnsupportedOperator(NotImplementedError): + """The formula uses an operator the solver does not know""" + + +# Errors of an impossible calculation: `If` and `Map` let them through +CALCULATION_ERRORS = ( + MathJSONDomainError, + MathJSONOverflowError, + MathJSONUnderflowError, + MathJSONUnsupportedOperator, +) + +LARGEST_FLOAT = 1.7976931348623157e308 +# Above this many digits, an integer power is too large for a float: refuse +# it without computing it, which could take forever (10 ** 10 ** 9) +MAX_POWER_DIGITS = 400 + + +def is_calculation_error(exception): + return isinstance(exception.e, CALCULATION_ERRORS) + + +def is_non_finite(x): + """Whether `x` is an infinite or NaN number, or such a number as a string""" + if isinstance(x, bool): + return False + try: + if isinstance(x, str): + x = float(x) + return isinstance(x, numbers.Number) and not math.isfinite(x) + except (TypeError, ValueError, OverflowError): + # OverflowError: an integer too large for a float, still finite + return False + + +def has_fraction(x): + """Whether `x` is a finite number that is not an integer""" + if isinstance(x, str): + return False + try: + x = float(x) + except (TypeError, ValueError, OverflowError): + return False + return math.isfinite(x) and not x.is_integer() + + +def is_negative(x): + try: + return x < 0 + except TypeError: + return False + + +def finite(result, *operands): + """`result`, unless finite operands gave an infinite or NaN result""" + if is_non_finite(result) and not any(is_non_finite(x) for x in operands): + raise MathJSONOverflowError("Result is not a finite number") + return result + + +def not_underflowed(result, *operands): + """`result`, unless finite operands gave 0 instead of a tiny number""" + if ( + result == 0 + and isinstance(result, float) + and not any(is_non_finite(x) for x in operands) + ): + raise MathJSONUnderflowError("Result is too small to be represented") + return result + + +def in_domain(fn, *args): + """`fn(*args)`, a math domain error being a MathJSONDomainError""" + try: + return fn(*args) + except ValueError as e: + raise MathJSONDomainError(str(e)) from e + + +def power(x, y): + """`x ** y` as Python computes it, without complex nor non-finite result""" + if ( + isinstance(x, int) + and isinstance(y, int) + and abs(x) > 1 + and y * math.log10(abs(x)) > MAX_POWER_DIGITS + ): + raise MathJSONOverflowError("Result is too large for a float") + if is_negative(x) and has_fraction(y): + raise MathJSONDomainError( + "Power of a negative number with a non-integer exponent" + ) + result = pow(x, y) + if isinstance(result, int) and abs(result) > LARGEST_FLOAT: + raise MathJSONOverflowError("Result is too large for a float") + if x != 0: + not_underflowed(result, x, y) + return finite(result, x, y) + + +def root(x, n): + """The `n`-th root of `x`: real for an odd root of a negative number""" + exponent = 1.0 / n + is_odd = float(n).is_integer() and int(n) % 2 == 1 + if x < 0 and is_odd: + return -power(-x, exponent) + return power(x, exponent) + + +def log_base(x, base): + if base <= 0 or base == 1: + raise MathJSONDomainError( + "Logarithm base must be positive and not equal to 1" + ) + if base == 10: + return in_domain(math.log10, x) + if base == 2: + return in_domain(math.log2, x) + return in_domain(math.log, x, base) + + +def exp(x): + return not_underflowed(math.exp(x), x) + + def is_numeric(x): try: float(x) @@ -162,6 +299,19 @@ def resolved(name, value): raise MathJSONUnresolvedParameter(f"Parameter '{name}' is None") return value + def list_ids(value, ids): + if isinstance(value, list): + ids[id(value)] = value + for x in value: + list_ids(x, ids) + return ids + + # Lists given as parameter values, at any depth, are data, not formulas. + # Copies of the context keep them as they are, so they stay recognized. + data_lists = {} + for value in solver_parameters.values(): + list_ids(value, data_lists) + def resolve_value(value, c): if strict and isinstance(value, str): return value @@ -169,7 +319,7 @@ def resolve_value(value, c): def f(s, *args): if args: - c = deepcopy(args[0]) + c = deepcopy(args[0], dict(data_lists)) else: c = {} # c = deepcopy(kwargs.get("c", {})) @@ -187,6 +337,7 @@ def Add(s): res = f(x, c) if is_numeric(res): res = float(res) + l_res.append(res) if i == 0: tmp = res else: @@ -200,7 +351,7 @@ def Add(s): # else: # l_res.append(res) - return tmp + return finite(tmp, *l_res) # tmp = 0 # for i, x in enumerate(l): @@ -264,19 +415,16 @@ def Average(s): ] # print(f"{s_} {sum(s_)}/{len(s_)}") try: - return sum(s_) / len(s_) + return finite(sum(s_) / len(s_), *s_) except ZeroDivisionError: return None def Median(s): if isinstance(s[1], str): - return median( - [f(x, c) for x in f(s[1], c) if is_numeric(f(x, c))] - ) + values = [f(x, c) for x in f(s[1], c) if is_numeric(f(x, c))] else: - return median( - [f(x, c) for x in s[1][1:] if is_numeric(f(x, c))] - ) + values = [f(x, c) for x in s[1][1:] if is_numeric(f(x, c))] + return finite(median(values), *values) def Length(s): if isinstance(s[1], str): @@ -340,13 +488,17 @@ def If(s): if f(x[0], c): try: return f(x[1], c) - except MathJSONException: + except MathJSONException as e: + if is_calculation_error(e): + raise logging.error( "MathJSONException: %s", traceback.format_exc(), ) continue - except MathJSONException: + except MathJSONException as e: + if is_calculation_error(e): + raise logging.error( "MathJSONException: %s", traceback.format_exc() ) @@ -435,7 +587,9 @@ def Map(s): the_function_name = s[2][0] ss = [the_function_name, x] + s[3:] retlist.append(f(ss, c)) - except MathJSONException: + except MathJSONException as e: + if is_calculation_error(e): + raise retlist.append(x) return retlist @@ -551,31 +705,40 @@ def safe_float(val): except TypeError: return False + def reduced(operation, s): + values = [f(x, c) for x in s[1:]] + return finite(reduce(operation, values), *values) + + def Divide(s): + x = f(s[1], c) + y = f(s[2], c) + return finite(x / y, x, y) + constructs = { "Sum": Sum, "Add": Add, - "Subtract": lambda s: reduce( - lambda a, b: a - b, [f(x, c) for x in s[1:]] - ), + "Subtract": lambda s: reduced(lambda a, b: a - b, s), "Constants": Constants, "Switch": Switch, "StrictSwitch": StrictSwitch, "If": If, - "Multiply": lambda s: reduce( - lambda a, b: float(a) * float(b), [f(x, c) for x in s[1:]] + "Multiply": lambda s: reduced( + lambda a, b: float(a) * float(b), s ), - "Divide": lambda s: f(s[1], c) / f(s[2], c), - "Rational": lambda s: f(s[1], c) / f(s[2], c), + "Divide": Divide, + "Rational": Divide, "Negate": lambda s: -f(s[1], c), - "Power": lambda s: pow(f(s[1], c), f(s[2], c)), - "Root": lambda s: pow(f(s[1], c), 1.0 / f(s[2], c)), - "Sqrt": lambda s: pow(f(s[1], c), 1.0 / 2), - "Square": lambda s: pow(f(s[1], c), 2), - "Exp": lambda s: math.exp(f(s[1], c)), - "Log": lambda s: math.log(f(s[1], c)), - "Ln": lambda s: math.log(f(s[1], c)), - "Log2": lambda s: math.log2(f(s[1], c)), - "Log10": lambda s: math.log10(f(s[1], c)), + "Power": lambda s: power(f(s[1], c), f(s[2], c)), + "Root": lambda s: root(f(s[1], c), f(s[2], c)), + "Sqrt": lambda s: power(f(s[1], c), 1.0 / 2), + "Square": lambda s: power(f(s[1], c), 2), + "Exp": lambda s: exp(f(s[1], c)), + # Log is the natural logarithm, whatever the base + "Log": lambda s: in_domain(math.log, f(s[1], c)), + "Ln": lambda s: in_domain(math.log, f(s[1], c)), + "Log2": lambda s: in_domain(math.log2, f(s[1], c)), + "Log10": lambda s: in_domain(math.log10, f(s[1], c)), + "LogBase": lambda s: log_base(f(s[1], c), f(s[2], c)), "Less": lambda s: Compare(operator.lt, s, c), "Greater": lambda s: Compare(operator.gt, s, c), "Equal": lambda s: Compare(operator.eq, s, c), @@ -639,12 +802,25 @@ def safe_float(val): raise MathJSONException(e, s, mathjson_construct=s[0]) except ZeroDivisionError as e: raise MathJSONException(e, s, mathjson_construct=s[0]) + except OverflowError as e: + if not isinstance(e, MathJSONOverflowError): + e = MathJSONOverflowError(str(e)) + raise MathJSONException(e, s, mathjson_construct=s[0]) + except MathJSONUnderflowError as e: + raise MathJSONException(e, s, mathjson_construct=s[0]) except MathJSONUnresolvedParameter as e: raise MathJSONException(e, s, mathjson_construct=s[0]) else: - # raise MathJSONException( - # NotImplementedError(f"'{s[0]}' is not supported"), s - # ) + if ( + strict + and isinstance(s[0], str) + and id(s) not in data_lists + ): + raise MathJSONException( + MathJSONUnsupportedOperator(f"'{s[0]}' is not supported"), + s, + mathjson_construct=s[0], + ) return s elif s in solver_parameters: value = resolved(s, solver_parameters[s]) @@ -660,10 +836,20 @@ def safe_float(val): return s def solver(s, *args): + # The lists of a given context are data too, during this call only + context_lists = {} + if args and isinstance(args[0], dict): + for value in args[0].values(): + list_ids(value, context_lists) + added = context_lists.keys() - data_lists.keys() + data_lists.update((k, context_lists[k]) for k in added) try: return f(s, *args) except MathJSONUnresolvedParameter as e: raise MathJSONException(e, s, mathjson_construct="Parameter") + finally: + for k in added: + del data_lists[k] return solver @@ -689,6 +875,7 @@ def extract_variables( "Log", "Log2", "Log10", + "LogBase", "Equal", "Greater", "GreaterEqual", diff --git a/tests/test_with_pytest.py b/tests/test_with_pytest.py index cafaa99..a1eaac7 100644 --- a/tests/test_with_pytest.py +++ b/tests/test_with_pytest.py @@ -1,5 +1,6 @@ import sys import os +import math import pytest import re @@ -9,8 +10,12 @@ from mathjson_solver import ( create_solver, + MathJSONDomainError, MathJSONException, + MathJSONOverflowError, + MathJSONUnderflowError, MathJSONUnresolvedParameter, + MathJSONUnsupportedOperator, extract_variables, ) @@ -773,3 +778,260 @@ def test_is_defined(parameters, expected_result): create_solver(parameters, strict=True)(["IsDefined", "a"]) == expected_result ) + + +@pytest.mark.parametrize( + "expression, expected_result", + [ + (["LogBase", 8, 2], 3.0), + (["LogBase", 1000, 10], 3.0), + (["LogBase", 100, 10], 2.0), + (["LogBase", 0.001, 10], -3.0), + (["LogBase", 81, 3], pytest.approx(4.0)), + # Log is the natural logarithm, whatever the base + (["Log", 100], math.log(100)), + (["Log", 100, 10], math.log(100)), + # The base of Log is not even evaluated + (["Log", 100, "undefined"], math.log(100)), + (["LogBase", 8, 0.5], pytest.approx(-3.0)), + (["Log10", 1000], 3.0), + (["Abs", -3.5], 3.5), + (["Abs", 0], 0), + (["Exp", 1], math.e), + (["Ln", ["Exp", 1]], 1.0), + (["Exp", 0], 1.0), + (["Ln", ["Exp", 2]], 2.0), + (["Root", -8, 3], -2.0), + (["Root", -32, 5], -2.0), + (["Root", -8, -3], -0.5), + (["Root", -8, 3.0], -2.0), + (["Power", 10, 2], 100), + (["Power", 10, 0], 1), + (["Power", 10, -3], 0.001), + (["GreaterEqual", ["Log10", 1000], 3], True), + ], +) +def test_calculator_operations(expression, expected_result): + assert create_solver({}, strict=True)(expression) == expected_result + + +def test_integer_power_stays_an_integer(): + result = create_solver({}, strict=True)(["Power", 2, 3]) + assert result == 8 and isinstance(result, int) + assert create_solver({}, strict=True)(["Square", 3]) == 9 + assert ( + create_solver({}, strict=True)( + ["Switch", ["Power", 2, 3], ["Str", "other"], [8, ["Str", "eight"]]] + ) + == "eight" + ) + + +@pytest.mark.parametrize( + "parameters, expression", + [ + ({}, ["Log10", 0]), + ({}, ["Log10", -5]), + ({}, ["Ln", 0]), + ({}, ["Log", -1]), + ({}, ["Log2", 0]), + ({}, ["LogBase", 10, 1]), + ({}, ["LogBase", 10, 0]), + ({}, ["LogBase", 10, -2]), + ({}, ["LogBase", 0, 10]), + ({}, ["LogBase", -8, 2]), + ({}, ["Sqrt", -4]), + ({}, ["Root", -16, 4]), + ({}, ["Root", -8, 2.5]), + ({}, ["Power", -8, 0.5]), + ({"u": -math.inf}, ["Sqrt", "u"]), + ({"u": -math.inf}, ["Root", "u", 2]), + ({"x": 0}, ["Divide", 1, ["Log10", "x"]]), + ], +) +def test_domain_error(parameters, expression): + with pytest.raises(MathJSONException) as exc_info: + create_solver(parameters, strict=True)(expression) + assert isinstance(exc_info.value.e, MathJSONDomainError) + + +@pytest.mark.parametrize( + "expression", + [ + ["Power", 10, 400], + ["Power", 10, 10**9], + ["Power", 10.0, 400], + ["Exp", 1000], + ["Multiply", 1e300, 1e300], + ["Add", 1e308, 1e308], + ["Subtract", -1e308, 1e308], + ["Divide", 1e308, 1e-10], + ["Average", ["Array", 1e308, 1e308]], + ["Median", ["Array", 1e308, 1e308]], + ["Root", 10, 0.001], + ["Less", ["Multiply", 1e300, 1e300], 1], + ], +) +def test_overflow_error(expression): + with pytest.raises(MathJSONException) as exc_info: + create_solver({}, strict=True)(expression) + assert isinstance(exc_info.value.e, MathJSONOverflowError) + + +@pytest.mark.parametrize( + "expression", + [["Power", 10, -400], ["Power", 0.5, 2000], ["Exp", -1000]], +) +def test_underflow_error(expression): + with pytest.raises(MathJSONException) as exc_info: + create_solver({}, strict=True)(expression) + assert isinstance(exc_info.value.e, MathJSONUnderflowError) + + +@pytest.mark.parametrize( + "parameters, expression, expected_result", + [ + # Crystal Miner gives an infinite relative uncertainty without positives + ({"u": math.inf}, ["Less", ["Multiply", "u", 100], 50], False), + ({"u": math.inf}, ["Multiply", "u", 100], math.inf), + ({"u": math.inf}, ["Add", "u", 1], math.inf), + ({"u": math.inf}, ["Divide", "u", 2], math.inf), + ({"u": math.inf}, ["Power", "u", 2], math.inf), + ({"u": -math.inf}, ["Exp", "u"], 0.0), + ({"u": math.inf}, ["Power", "u", -1], 0.0), + ({"u": 0}, ["Power", "u", 2], 0), + ({"u": "inf"}, ["Multiply", "u", 2], math.inf), + ({"u": -math.inf}, ["Root", "u", 3], -math.inf), + ({"u": 2}, ["LogBase", 8, ["Multiply", "u", math.inf]], 0.0), + # An integer too large for a float stays an exact integer + ({}, ["Subtract", 10**400, 1], 10**400 - 1), + ], +) +def test_non_finite_data_go_through(parameters, expression, expected_result): + assert create_solver(parameters, strict=True)(expression) == expected_result + + +def test_nan_data_go_through(): + result = create_solver({"u": math.nan}, strict=True)(["Multiply", "u", 2]) + assert math.isnan(result) + + +@pytest.mark.parametrize("expression", [["Floor", 2.5], ["Sin", "x"]]) +def test_unsupported_operator_raises_in_strict_mode(expression): + with pytest.raises(MathJSONException) as exc_info: + create_solver({"x": 1}, strict=True)(expression) + assert isinstance(exc_info.value.e, MathJSONUnsupportedOperator) + # The default mode still returns it unchanged + assert create_solver({"x": 1})(expression) == expression + + +@pytest.mark.parametrize( + "parameters, expression, expected_result", + [ + ({"l": ["Array", "plasma", "serum"]}, ["In", ["Str", "plasma"], "l"], True), + ({"l": ["plasma", "serum"]}, ["In", ["Str", "plasma"], "l"], True), + ({"l": ["A1", "B2"]}, "l", ["A1", "B2"]), + ( + {"rows": ["Array", ["plasma", 1]]}, + ["Map", "rows", ["Str"]], + ["Array", "['plasma', 1]"], + ), + ( + {"rows": ["plasma", "serum"]}, + ["Constants", ["l", "rows"], ["In", ["Str", "plasma"], "l"]], + True, + ), + ( + {"rows": ["Array", ["plasma", 1]]}, + ["Constants", ["r", "rows"], ["Map", "r", ["Str"]]], + ["Array", "['plasma', 1]"], + ), + ( + {"rows": ["Array", ["plasma", 1]]}, + ["Constants", ["r", "rows"], ["Map", "r", ["Abs"]]], + ["Array", ["plasma", 1]], + ), + ], +) +def test_list_parameters_are_data_in_strict_mode( + parameters, expression, expected_result +): + assert create_solver(parameters, strict=True)(expression) == expected_result + + +@pytest.mark.parametrize( + "parameters, expression, error", + [ + ( + {"x": 0}, + ["If", [["Greater", ["Log10", "x"], 1], 1], 2], + MathJSONDomainError, + ), + ({"x": 0}, ["If", [True, ["Log10", "x"]], 2], MathJSONDomainError), + ({}, ["If", [True, ["Power", 10, 400]], 2], MathJSONOverflowError), + ({}, ["If", [["Floor", 1], 1], 2], MathJSONUnsupportedOperator), + ({}, ["Map", ["Array", 1, 0], ["Log10"]], MathJSONDomainError), + ({}, ["Map", ["Array", 1, -1000], ["Exp"]], MathJSONUnderflowError), + ({}, ["Map", ["Array", 1, 1000], ["Exp"]], MathJSONOverflowError), + ({}, ["Map", ["Array", 1], ["Floor"]], MathJSONUnsupportedOperator), + ({}, ["If", [True, ["Exp", -1000]], 2], MathJSONUnderflowError), + ], +) +def test_if_and_map_let_calculation_errors_through( + parameters, expression, error +): + with pytest.raises(MathJSONException) as exc_info: + create_solver(parameters, strict=True)(expression) + assert isinstance(exc_info.value.e, error) + + +@pytest.mark.parametrize( + "parameters, expression", + [ + ({"x": 0}, ["If", [["Greater", ["Log10", "x"], 1], 1], 2]), + ({}, ["Map", ["Array", 1, 0], ["Log10"]]), + ], +) +def test_if_and_map_let_calculation_errors_through_by_default( + parameters, expression +): + with pytest.raises(MathJSONException) as exc_info: + create_solver(parameters)(expression) + assert isinstance(exc_info.value.e, MathJSONDomainError) + + +@pytest.mark.parametrize( + "parameters, expression, expected_result", + [ + ({}, ["If", [["Greater", "missing", 1], 1], 2], 2), + ({}, ["If", [True, ["Root", 8, 0]], 2], 2), + ({}, ["Map", ["Array", 1, 2], ["Divide", 0]], ["Array", 1, 2]), + ], +) +def test_if_and_map_still_catch_other_errors( + parameters, expression, expected_result +): + assert create_solver(parameters, strict=True)(expression) == expected_result + + +def test_extract_variables_knows_log_base(): + assert extract_variables(["LogBase", "x", 2], set(), set()) == {"x"} + + +def test_list_in_the_given_context_is_data_in_strict_mode(): + assert ( + create_solver({}, strict=True)( + ["In", ["Str", "plasma"], "l"], {"l": ["plasma", "serum"]} + ) + is True + ) + + +def test_nested_list_in_the_given_context_is_data_in_strict_mode(): + solver = create_solver({}, strict=True) + context = {"r": ["Array", ["plasma", 1]]} + assert solver(["Map", "r", ["Str"]], context) == ["Array", "['plasma', 1]"] + # The context's lists are data for that call only + with pytest.raises(MathJSONException) as exc_info: + solver(["Constants", ["x", context["r"][1]], "x"]) + assert isinstance(exc_info.value.e, MathJSONUnsupportedOperator)