diff --git a/changelog.d/1937.fixed.md b/changelog.d/1937.fixed.md new file mode 100644 index 000000000..d9d7257dd --- /dev/null +++ b/changelog.d/1937.fixed.md @@ -0,0 +1 @@ +- **A forward sensitivity through one of ExprTk's implicit products was exact zeros, with no warning, and a plain run stepped over a pulse centred on one (issue #1937).** The engine reads `2j`, `2 j`, `(1+1)j`, `(j)2` and `j(2)` as `2*j`. The Python readers scanned the text for the word `j`, found none, and took the expression to name no parameter: with `A0 = 2j`, dA/dj came back [0, 0, 0] for 2·e^(-t/2); a rate law `k*2j` failed its build on Python's imaginary `I`; and `1000*exp(-((time() - c)/0.0005)^2)` with `c = 2j` gave A(10) = 0 for 0.886. The products are now written out, by the pass the C emitter already uses, before a derived parameter's expression is scanned or parsed (seeds, the chain rule, the kink check, pulse stops), and a rate law's lexer-level ones before its parse. A law with ExprTk's square or curly brackets (`j[2]`), or with a name against a bracket beside another product (`0.5Atot(2)`), declines as before. Also: a reserved word in another case is a name, as it is to the engine (`2In` was zeros too), and a derived parameter that is a logical operation (`j and k`) has a zero column, not 1. diff --git a/docs/development/sensitivity-terms.md b/docs/development/sensitivity-terms.md index cd7c9a951..883e0ce9f 100644 --- a/docs/development/sensitivity-terms.md +++ b/docs/development/sensitivity-terms.md @@ -74,6 +74,11 @@ s' = f_x·s + f_p, f_p = ∂f/∂p + Σ_d (∂f/∂d)·(∂d/∂p) over d - A `%` in a rate law is read as the engine's `fmod`, its `mod()`, and not as sympy's floored `Mod` (#1815). Oracle: `rate-law-mod-of-literals`, `rate-law-mod-of-integer-literals`, `rate-law-mod-negative-divisor`. +- The products ExprTk reads between operands written side by side (`2j`, + `(1+1)j`, `j(2)`) are written out before a derived expression is scanned + for names or parsed, and a rate law's lexer-level ones before its parse + (#1937). Oracle: `ic-seed-derived-implicit-product`, + `rhs-derived-chain-implicit-product`, `rate-law-implicit-product`. - **Open:** a compiled sensitivity RHS that is already attached is reused after `set_param` changes a derived parameter's attachment, so it keeps the old chain rule (#708, `stale-artifact-after-override`). diff --git a/python/bngsim/_codegen.py b/python/bngsim/_codegen.py index 22dd35654..4413b50b8 100644 --- a/python/bngsim/_codegen.py +++ b/python/bngsim/_codegen.py @@ -3181,6 +3181,49 @@ class _PreparedDerivedExpr(NamedTuple): _HAS_NON_WORD_RE = re.compile(r"\W") +class _ScalarNames: + """A set of names as the lookup :func:`_insert_implicit_products` takes, + each one a variable, without a dict built per expression.""" + + __slots__ = ("names",) + + def __init__(self, names): + self.names = names + + def __bool__(self) -> bool: + return bool(self.names) + + def get(self, name: str): + return (name, True) if name in self.names else None + + +def _products_written_out(expr: str, scalars=None) -> str: + """*expr* with the products ExprTk reads between operands written side by + side spelled with ``*`` (:func:`_insert_implicit_products`), for a reader + that scans it for names or hands it to sympy: ``2j`` holds no word ``j``, + and to Python it is an imaginary number. *scalars* are the names that are + variables (a set, or the emitter's lookup); with none, only the pairs the + lexer multiplies are written. A text the pass declines is returned as it + is, for the reader to decline in its own words.""" + if not expr: + return expr + if isinstance(scalars, (set, frozenset)): + scalars = _ScalarNames(scalars) + if scalars and scalars.get("time") is not None and _NUMBER_GLUED_TO_TIME.search(expr): + return expr + try: + return _insert_implicit_products(expr, scalars) + except CodegenDeclined: + return expr + + +# A number written against the name `time`. The engine renames the clock at a +# word boundary before ExprTk splits the pair, so in a model with a scalar +# named `time`, `2time` is twice the clock and `2 time` twice the scalar. +# Written out, both would read as the scalar: such a text is left as it is. +_NUMBER_GLUED_TO_TIME = re.compile(r"[\d.]time\b") + + def _names_referenced_in(text: str, names) -> list[str]: """Sorted members of ``names`` that occur in ``text`` as whole words. @@ -3315,9 +3358,18 @@ def _prepare_derived_expr( # the parse, it is read as fmod (issue #1800). The call is a private name, # so a parameter named `mod` is not called, and only this parse sees it: the # clock parser shares _preprocess_derived_expr and reads `%` as before. + diff_names = primary_names | set(derived_names) + # The products ExprTk reads between operands written side by side (`2j`, + # `(1+1)j`, `j(2)`), written out first, while the text is still the + # model's: the name scan below finds no `j` in `2j`, and the expression + # read as naming no parameter, a zero partial with nothing said. + if not ("time" in diff_names and _NUMBER_GLUED_TO_TIME.search(expr)): + try: + expr = _insert_implicit_products(expr, _ScalarNames(diff_names)) + except CodegenDeclined as exc: + return None, str(exc) s_pre = _spell_mod(_preprocess_derived_expr(expr), call=_ENGINE_ROUNDING_NAMES[1]) - diff_names = primary_names | set(derived_names) referenced = _names_referenced_in(s_pre, diff_names) if not referenced and not allow_no_reference: return None, None # names no parameter — a genuine zero, not a failure @@ -3433,6 +3485,19 @@ def _prepare_derived_expr( ) +def _is_truth_value(sym_expr) -> bool: + """Whether the whole expression is a logical operation (``j and k``, + ``not(j)``). The engine's value is then 0 or 1, constant in every + parameter between its switches: a zero partial, where sympy's derivative + of the unevaluated ``And`` came back 1. A bare comparison is not one of + these: the switch-time scan hands its thresholds through the same parse.""" + import sympy as sp + + return isinstance(sym_expr, sp.logic.boolalg.BooleanFunction) and not isinstance( + sym_expr, sp.core.relational.Relational + ) + + def _derivative_is_unevaluated(deriv) -> bool: """Whether sympy left any part of ``deriv`` as an unevaluated ``Derivative`` (see :data:`_STEP_DERIVATIVE_REASON`).""" @@ -3685,6 +3750,8 @@ def _direct_derived_partials( prep, reason = _prepare_derived_expr(expr, primary_names, derived_names) if prep is None: return None, reason + if _is_truth_value(prep.sym_expr): + return None, None # For round-tripping the ccode output: map each (possibly-aliased) sympy # symbol name back to ``p[idx]`` using the ORIGINAL parameter's index. @@ -3926,6 +3993,8 @@ def _direct_derived_partials_numeric( prep, reason = _prepare_derived_expr(expr, primary_names, derived_names) if prep is None: return None, reason + if _is_truth_value(prep.sym_expr): + return None, None subs = { prep.sym_map[prep.sym_name_of[p]]: param_values[param_idx[p]] @@ -4099,7 +4168,12 @@ def compute_ic_param_sens_seed(core) -> list[tuple[int, int, float]]: values = [core.get_param(n) for n in names] param_idx = {n: i for i, n in enumerate(names)} primary_names = {names[i] for i in range(len(names)) if not is_expr[i]} - derived_exprs = {names[i]: exprs[i] for i in range(len(names)) if is_expr[i] and exprs[i]} + scalars = _ScalarNames(set(names)) + derived_exprs = { + names[i]: _products_written_out(exprs[i], scalars) + for i in range(len(names)) + if is_expr[i] and exprs[i] + } seeds: list[tuple[int, int, float]] = [] for (species_idx0, param_idx0), divisor in zip(refs, ref_divisors, strict=True): @@ -6707,7 +6781,9 @@ def _expr_to_c( ) # fmt: skip # ExprTk's reserved words: never one side of an implicit product (its -# commutative_inserter ignores them; `reserved_words` in exprtk.hpp). +# commutative_inserter ignores them; `reserved_words` in exprtk.hpp). As +# written: the engine builds ExprTk with exprtk_disable_caseinsensitivity, so +# `In`, `Or` and `IF` are names, and `2In` is twice the parameter `In`. _EXPRTK_RESERVED_WORDS = frozenset( { "assert", "break", "case", "continue", "const", "default", "false", "for", @@ -6752,7 +6828,9 @@ def _expr_to_c( _NAME_BEFORE_BRACKET_RE = re.compile("(" + _NAME + r")\s*[(\[{]") -def _insert_implicit_products(expr: str, lookup: dict[str, tuple[str, bool]] | None = None) -> str: +def _insert_implicit_products( + expr: str, lookup: dict[str, tuple[str, bool]] | _ScalarNames | None = None +) -> str: """Write out the ``*`` ExprTk reads between two operands written side by side. ExprTk's lexer multiplies ``2x``, ``2(x + 1)``, ``(a)b`` and ``x y``, so @@ -6800,7 +6878,7 @@ def variable(name: str) -> bool: continue if kind == "other": kind = text - elif kind == "sym" and text.lower() in _EXPRTK_RESERVED_WORDS: + elif kind == "sym" and text in _EXPRTK_RESERVED_WORDS: kind = "word" if kind in _BRACKET_CLOSES: if prev_call is not None: @@ -6824,9 +6902,7 @@ def variable(name: str) -> bool: elif prev_operand or (prev, kind) in _IMPLICIT_PRODUCT_PAIRS: out.append("*") opened.append(None) - elif prev == "sym" or ( - prev == "word" and prev_text.lower() not in _EXPRTK_OPERATOR_WORDS - ): + elif prev == "sym" or (prev == "word" and prev_text not in _EXPRTK_OPERATOR_WORDS): opened.append(prev_text) else: opened.append(None) diff --git a/python/bngsim/_jacobian.py b/python/bngsim/_jacobian.py index 93fa8fd2d..8f474172e 100644 --- a/python/bngsim/_jacobian.py +++ b/python/bngsim/_jacobian.py @@ -835,6 +835,15 @@ def _exprtk_to_sympy(expr: str, *, bends: bool = False, closed_forms: bool = Fal except ImportError: return None + # The products ExprTk's lexer reads between operands written side by side + # (`2j`, `(a)b`, `x y`), written out: Python reads `2j` as an imaginary + # number, and the build failed on its `I`. This parse is not told which + # names are the model's scalars, so `k(x)` stays the call it reads as. + from bngsim._codegen import _products_written_out + + as_written = expr + expr = _products_written_out(expr) + wrote_products = expr != as_written # ExprTk's `%` on doubles is fmod, its `mod()`. Left as written, Python's # parser reads it as sympy's floored Mod, which folds two numbers at once # (`-2.5 % 2` to 1.5 for the engine's -0.5: the law `k*((-2.5 % 2)+1)` was @@ -879,9 +888,17 @@ def _exprtk_to_sympy(expr: str, *, bends: bool = False, closed_forms: bool = Fal s = re.sub(rf"\b{re.escape(ident)}\b", alias_of[ident], s) try: - return parse_expr(s, local_dict=local, evaluate=True) + parsed = parse_expr(s, local_dict=local, evaluate=True) except Exception: return None + # A law that also holds a name against a bracket (`0.5Atot(2)`, `j[2]`) + # did not parse before its other products, or its square brackets, were + # written, and declined. Parsed now, the `Atot(2)` in it is a call of an + # unknown function, a constant to every derivative, where the engine reads + # the product `Atot*2`: it declines still. + if wrote_products and parsed.atoms(sp.core.function.AppliedUndef): + return None + return parsed # ─── Function inlining ───────────────────────────────────────────────────── diff --git a/python/bngsim/_parameter_kinks.py b/python/bngsim/_parameter_kinks.py index 82805ac20..7bf29496b 100644 --- a/python/bngsim/_parameter_kinks.py +++ b/python/bngsim/_parameter_kinks.py @@ -241,6 +241,7 @@ def parameters_on_a_kink( _PY_KEYWORD_PARAM_NAMES, _alias_keyword_param, _inline_derived_param_refs, + _products_written_out, ) from bngsim._jacobian import has_condition_construct from bngsim._switch_sensitivity import _BEND_CALL @@ -248,8 +249,9 @@ def parameters_on_a_kink( all_names = list(core.param_names) # The derived parameters as switch_condition_scope reads them, without its # probe of the right-hand side for the clocks. + scalars = set(all_names) derived = { - n: e + n: _products_written_out(e, scalars) for n, is_e, e in zip( all_names, core.param_is_expression, core.param_expressions, strict=True ) diff --git a/python/bngsim/_smooth_pulses.py b/python/bngsim/_smooth_pulses.py index ca53142ee..ac1806e26 100644 --- a/python/bngsim/_smooth_pulses.py +++ b/python/bngsim/_smooth_pulses.py @@ -283,6 +283,7 @@ def _resolve(core, t_start: float, t_end: float) -> list[Any]: _PY_KEYWORD_PARAM_NAMES, _alias_keyword_param, _inline_derived_param_refs, + _products_written_out, ) from bngsim._jacobian import _TIME_SYM from bngsim._switch_sensitivity import CrossingStop @@ -293,8 +294,11 @@ def spelled(name: str) -> str: return _alias_keyword_param(name) if name in _PY_KEYWORD_PARAM_NAMES else name names = list(core.param_names) + # With the products ExprTk reads written out: `c = j(2)` inlined as it + # was written parsed as a call, and the pulse on it had no centre. + scalars = set(names) derived = { - n: e + n: _products_written_out(e, scalars) for n, is_expr, e in zip( names, core.param_is_expression, core.param_expressions, strict=True ) @@ -303,7 +307,8 @@ def spelled(name: str) -> str: values = {spelled(n): float(core.get_param(n)) for n in names} bumps: list[tuple[str, float, float, float]] = [] for text in texts: - expr = _parsed(_inline_derived_param_refs(text, derived)) + # The law's own products too, with the names: `time() - j(2)`. + expr = _parsed(_inline_derived_param_refs(_products_written_out(text, scalars), derived)) if expr is None: continue subs = {s: values[s.name] for s in expr.free_symbols if s.name in values} diff --git a/python/tests/test_codegen_sens_fd_oracle.py b/python/tests/test_codegen_sens_fd_oracle.py index f4f371ea6..170444ba5 100644 --- a/python/tests/test_codegen_sens_fd_oracle.py +++ b/python/tests/test_codegen_sens_fd_oracle.py @@ -545,6 +545,42 @@ def _chain_after_override(term: Term, method: str) -> np.ndarray: param="k", note="fmod gives 1.5, so c = 2.5; floored, c was 0.5 (#1815)", ), + Term( + "ic-seed-derived-implicit-product", + "net", + _fill(_IC_NET, "R0", Rt="3R0", B0="Rt"), + "R0", + "10", + 10.0, + _T, + ("B()",), + param="R0", + note="ExprTk's 3R0 is 3*R0; a scan for the word R0 found none, a zero seed (#1937)", + ), + Term( + "rhs-derived-chain-implicit-product", + "net", + _fill(_DERIVED_RATE_NET, "k0", kd="(1+1)k0", body="1"), + "k0", + "0.5", + 0.5, + _T, + ("A()",), + param="k0", + note="a bracket against a name is a product too (#1937)", + ), + Term( + "rate-law-implicit-product", + "net", + _fill(_DERIVED_RATE_NET, "k0", kd="2", body="0.5k0"), + "k0", + "0.5", + 0.5, + _T, + ("A()",), + param="k0", + note="in a law Python read 0.5k0 as a syntax error and 2j as imaginary (#1937)", + ), Term( "ic-seed-param", "net", diff --git a/python/tests/test_sens_implicit_products.py b/python/tests/test_sens_implicit_products.py new file mode 100644 index 000000000..cdbeb64ea --- /dev/null +++ b/python/tests/test_sens_implicit_products.py @@ -0,0 +1,397 @@ +"""ExprTk's implicit products are products to the sensitivity readers too +(issue #1937). + +The engine reads ``2j``, ``(1+1)j`` and ``j(2)`` as ``2*j``, so a plain run is +right. The Python readers that build forward sensitivities scanned the text +for the word ``j`` and found none in ``2j``: the expression read as naming no +parameter, and its column came back exact zeros with no warning. In a rate law +Python read ``2j`` as an imaginary number and the build failed on its ``I``. +The same text gave a narrow pulse no centre to stop at, so a plain run stepped +over it. + +``python/tests/test_codegen_sens_fd_oracle.py`` holds three of these against a +central difference (``*-implicit-product``). +""" + +from __future__ import annotations + +import math +import warnings + +import bngsim +import pytest +from bngsim._codegen import ( + _prepare_derived_expr, + _products_written_out, + compute_ic_param_sens_seed, +) +from bngsim._jacobian import _exprtk_to_sympy + +# Every way to write 2*j without the `*`, for a scalar j. +SPELLINGS = [ + "2j", + "2 j", + "j 2", + "j(2)", + "(j)2", + "(1+1)j", + "2.j", + "1e0j*2", + "2(j)", + "j[2]", + "j{2}", + "(2)(j)", + "(j)(2)", +] +# The pairs ExprTk's lexer multiplies, which need no knowledge of the names. +LEXER_SPELLINGS = ["2j", "2 j", "j 2", "(j)2", "(1+1)j", "2.j", "1e0j*2", "2(j)", "(2)(j)"] +T = [0.0, 0.7, 1.9] +J = 1.5 + + +def _net(place: str, s: str) -> str: + params = [("j", repr(J)), ("q", "0.5")] + functions, rate, a0 = "", "kd", "4" + if place == "ic": + params += [("A0", s), ("kd", "0.5")] + a0 = "A0" + elif place == "rate": + params += [("kd", f"({s})/8")] + elif place == "chain": + params += [("m", s), ("kd", "0.125m")] + else: + params += [("kd", "0.5")] + body = {"law": f"({s})/8", "law_obs": f"({s})/8*(1 + 0.01Atot)"}[place] + functions, rate = f"begin functions\n 1 f() {body}\nend functions\n", "f" + rows = "".join(f" {i + 1} {n} {v}\n" for i, (n, v) in enumerate(params)) + return ( + f"begin parameters\n{rows}end parameters\n" + f"begin species\n 1 A() {a0}\nend species\n" + f"{functions}" + f"begin reactions\n 1 1 0 {rate}\nend reactions\n" + "begin groups\n 1 Atot 1\nend groups\n" + ) + + +def _model(tmp_path, text: str) -> bngsim.Model: + path = tmp_path / "m.net" + path.write_text(text, encoding="utf-8") + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + return bngsim.Model.from_net(path) + + +def _column(tmp_path, text: str, param: str = "j") -> list[float]: + model = _model(tmp_path, text) + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + result = bngsim.Simulator(model, method="ode", sensitivity_params=[param]).run( + sample_times=T, rtol=1e-10, atol=1e-12 + ) + return [float(v) for v in result.sensitivities[:, 0, 0]] + + +def _closed_form(place: str) -> list[float]: + """dA(t)/dj for A' = -kd*A: A(0) = 2j at kd = 0.5, or A(0) = 4 at kd = j/4 + (times 1 + 0.01*A in ``law_obs``, which has no closed form here).""" + if place == "ic": + return [2 * math.exp(-0.5 * t) for t in T] + return [-(t / 4) * 4 * math.exp(-(J / 4) * t) for t in T] + + +@pytest.mark.parametrize("place", ["ic", "rate", "chain"]) +@pytest.mark.parametrize("s", SPELLINGS) +def test_a_derived_parameters_product_has_its_column(tmp_path, place, s): + got = _column(tmp_path, _net(place, s)) + assert got == pytest.approx(_closed_form(place), rel=1e-6, abs=1e-9) + assert any(abs(v) > 0.1 for v in got) + + +@pytest.mark.parametrize("s", LEXER_SPELLINGS) +def test_a_rate_laws_product_has_its_column(tmp_path, s): + assert _column(tmp_path, _net("law", s)) == pytest.approx( + _closed_form("law"), rel=1e-6, abs=1e-9 + ) + + +@pytest.mark.parametrize("s", ["2j", "(1+1)j", "2 j"]) +def test_a_law_over_the_state_matches_its_star_spelling(tmp_path, s): + want = _column(tmp_path, _net("law_obs", "2*j")) + assert _column(tmp_path, _net("law_obs", s)) == pytest.approx(want, rel=1e-8, abs=0.0) + assert abs(want[-1]) > 0.1 + + +@pytest.mark.parametrize("s", ["j[2]", "j{2}"]) +def test_a_law_with_exprtks_other_brackets_is_left_to_decline(tmp_path, s): + """The law's parse is not told the model's scalars. Written round, ``j[2]`` + reads as a call of ``j``, a constant: exact zeros for a column the + difference quotient gets right. A parse that calls an unknown name after + the text was rewritten declines.""" + assert _exprtk_to_sympy(f"({s})/8") is None + assert _column(tmp_path, _net("law", s)) == pytest.approx( + _closed_form("law"), rel=1e-5, abs=1e-8 + ) + + +@pytest.mark.parametrize("s", SPELLINGS) +def test_the_seed_names_the_parameter(tmp_path, s): + model = _model(tmp_path, _net("ic", s)) + seeds = {(sp, p): c for sp, p, c in compute_ic_param_sens_seed(model._core)} + assert seeds[(0, 0)] == pytest.approx(2.0, rel=1e-12, abs=0.0) # dA0/dj + + +@pytest.mark.parametrize("s", SPELLINGS) +def test_the_derived_parse_reads_the_product(s): + prep, why = _prepare_derived_expr(s, {"j", "q"}, []) + assert why is None + assert prep.referenced == ["j"] + assert float(prep.sym_expr.diff(prep.sym_map["j"])) == 2.0 + + +# What must stay as it is: an exponent, a name with digits in it, a call, a +# reserved word beside a number. +@pytest.mark.parametrize( + "text", + ["1e5", "2.5E-3", "1.5e+3*j", "k2j", "x2 + j", "exp(2)", "2 and j", "j*2", "if(j > 1, 2, 3)"], +) +def test_what_is_no_product_is_left_as_written(text): + assert _products_written_out(text, {"j", "k2j", "x2"}) == text + + +def test_an_exponent_is_not_split_from_its_number(): + assert _products_written_out("1e0j", {"j"}) == "1e0*j" + assert _products_written_out("2.5E-3j", {"j"}) == "2.5E-3*j" + + +def test_a_name_that_is_no_scalar_keeps_its_call(): + assert _products_written_out("j(2)", {"j"}) == "j*(2)" + assert _products_written_out("exp(2)j", {"j"}) == "exp(2)*j" + assert _products_written_out("j(2)") == "j(2)" # no names given: a call + + +def test_a_text_the_pass_declines_is_returned_and_the_parse_gives_a_reason(): + """After a call, a bracket opens a second statement in ExprTk.""" + text = "j*exp(-q)(j)" + assert _products_written_out(text, {"j", "q"}) == text + prep, why = _prepare_derived_expr(text, {"j", "q"}, []) + assert prep is None + assert why + + +def test_a_parameter_whose_name_ends_in_the_letters_is_not_split(tmp_path): + """``k2j`` is one name: A0 = 2k2j moves with k2j and not with j.""" + text = ( + "begin parameters\n 1 j 1.5\n 2 k2j 3\n 3 A0 2k2j\n 4 kd 0.5\nend parameters\n" + "begin species\n 1 A() A0\nend species\n" + "begin reactions\n 1 1 0 kd\nend reactions\n" + ) + assert _column(tmp_path, text, "k2j") == pytest.approx( + [2 * math.exp(-0.5 * t) for t in T], rel=1e-6 + ) + assert _column(tmp_path, text, "j") == [0.0, 0.0, 0.0] + + +# A pulse 0.0005 wide at t = 4, into A from 0: A(10) = 1000*w*sqrt(pi). A run +# that does not stop at its centre steps over it and returns 0. +_PULSE_AREA = 1000 * 0.0005 * math.sqrt(math.pi) +_PULSES = [ + (" 1 j 2\n 2 c 2j\n", "c"), + (" 1 j 2\n 2 c (1+1)j\n", "c"), + (" 1 j 2\n 2 c j(2)\n", "c"), + (" 1 j 2\n", "2j"), + (" 1 j 2\n", "(j)2"), + (" 1 j 2\n", "j(2)"), # a name against a bracket, in the law itself + (" 1 j 2\n", "(j)(2)"), + (" 1 j 2\n 2 c 2*j\n", "c"), # the control +] + + +@pytest.mark.parametrize(("parameters", "centre"), _PULSES) +def test_a_pulse_centred_on_a_product_is_not_stepped_over(tmp_path, parameters, centre): + text = ( + f"begin parameters\n{parameters}end parameters\n" + "begin species\n 1 A() 0\nend species\n" + f"begin functions\n 1 f() 1000*exp(-((time() - {centre})/0.0005)^2)\nend functions\n" + "begin reactions\n 1 0 1 f #_R1\nend reactions\n" + ) + model = _model(tmp_path, text) + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + result = bngsim.Simulator(model, method="ode").run(sample_times=[0.0, 10.0]) + assert float(result.species[-1, 0]) == pytest.approx(_PULSE_AREA, rel=1e-4) + + +@pytest.mark.parametrize("c", ["2j", "(1+1)j", "j(2)"]) +def test_a_time_switch_on_a_product_has_its_jump(tmp_path, c): + """A' = -f*A, f = 1 until t = c = 2j and 3 after, j = 0.5: dA(2)/dj = 4*A(2).""" + text = ( + f"begin parameters\n 1 j 0.5\n 2 c {c}\nend parameters\n" + "begin species\n 1 A() 4\nend species\n" + "begin functions\n 1 f() if(time() > c, 3, 1)\nend functions\n" + "begin reactions\n 1 1 0 f\nend reactions\n" + ) + model = _model(tmp_path, text) + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + result = bngsim.Simulator(model, method="ode", sensitivity_params=["j"]).run( + sample_times=[0.0, 2.0], rtol=1e-10, atol=1e-12 + ) + a2 = 4 * math.exp(-1 - 3) + assert float(result.species[-1, 0]) == pytest.approx(a2, rel=1e-7) + assert float(result.sensitivities[-1, 0, 0]) == pytest.approx(4 * a2, rel=1e-6) + + +def _fd(tmp_path, make, at: float, h: float = 1e-6) -> list[float]: + runs = [] + for sign in (1, -1): + model = _model(tmp_path, make(at + sign * h)) + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + result = bngsim.Simulator(model, method="ode").run( + sample_times=T, rtol=1e-12, atol=1e-14 + ) + runs.append([float(v) for v in result.species[:, 0]]) + return [(a - b) / (2 * h) for a, b in zip(*runs, strict=True)] + + +def _ic_net(params: str, a0: str = "A0") -> str: + return ( + f"begin parameters\n{params}end parameters\n" + f"begin species\n 1 A() {a0}\nend species\n" + "begin reactions\n 1 1 0 kd\nend reactions\n" + ) + + +@pytest.mark.parametrize("word", ["In", "IF", "Var", "XOR"]) +def test_a_reserved_word_in_another_case_is_a_name(tmp_path, word): + """The engine's ExprTk is case-sensitive: ``2In`` is twice the parameter.""" + assert _products_written_out(f"2{word}", {word}) == f"2*{word}" + + def make(v): + return _ic_net(f" 1 {word} {v!r}\n 2 A0 2{word}\n 3 kd 0.5\n") + + got = _column(tmp_path, make(1.5), word) + assert got == pytest.approx(_fd(tmp_path, make, 1.5), rel=1e-5, abs=1e-7) + assert got[0] == pytest.approx(2.0) + + +@pytest.mark.parametrize("word", ["in", "or", "and", "if", "not"]) +def test_a_reserved_word_as_written_is_never_a_factor(word): + assert _products_written_out(f"2 {word} j", {"j"}) == f"2 {word} j" + + +@pytest.mark.parametrize("a0", ["2time", "2 time", "2*time", "2.5time/3"]) +def test_a_number_against_a_parameter_named_time_is_read_as_the_engine_reads_it(tmp_path, a0): + """The engine renames the clock at a word boundary, so ``2time`` is twice + the clock (0 where a constant is evaluated) and ``2 time`` twice the + parameter. Written out, the first would have the second's column.""" + + def make(v): + return _ic_net(f" 1 time {v!r}\n 2 A0 {a0}\n 3 kd 0.5\n") + + assert _column(tmp_path, make(1.5), "time") == pytest.approx( + _fd(tmp_path, make, 1.5), rel=1e-5, abs=1e-7 + ) + + +def test_a_text_with_a_number_against_time_is_left_as_written(): + assert _products_written_out("2time + 3j", {"j", "time"}) == "2time + 3j" + assert _products_written_out("2time + 3j", {"j"}) == "2*time + 3*j" # no such scalar + + +@pytest.mark.parametrize("a0", ["j and k", "[j and k]", "not(j)", "j > 1", "j or k"]) +def test_a_derived_parameter_that_is_a_truth_value_has_a_zero_column(tmp_path, a0): + """Its value is 0 or 1; sympy's derivative of the bare ``And`` was 1.""" + + def make(v): + return _ic_net(f" 1 j {v!r}\n 2 k 0.7\n 3 A0 {a0}\n 4 kd 0.5\n") + + assert _fd(tmp_path, make, 1.5) == pytest.approx([0.0, 0.0, 0.0], abs=1e-9) + assert _column(tmp_path, make(1.5)) == [0.0, 0.0, 0.0] + + +@pytest.mark.parametrize("g", ["0.5Atot(2)", "2j(3)", "Atot(2) + 0.5kd"]) +def test_an_output_expression_with_a_name_against_a_bracket_is_refused(tmp_path, g): + """The law's parse is not told that ``Atot`` is a scalar: with the other + products written, ``Atot(2)`` parsed as a call, a constant, and the output + sensitivity came back zeros.""" + assert _exprtk_to_sympy(g) is None + text = ( + "begin parameters\n 1 j 1.5\n 2 kd 0.5\nend parameters\n" + "begin species\n 1 A() 4\nend species\n" + f"begin functions\n 1 g() {g}\nend functions\n" + "begin reactions\n 1 1 0 kd\nend reactions\n" + "begin groups\n 1 Atot 1\nend groups\n" + ) + model = _model(tmp_path, text) + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + result = bngsim.Simulator(model, method="ode", sensitivity_params=["kd"]).run( + sample_times=T, rtol=1e-10, atol=1e-12 + ) + with pytest.raises(bngsim.UsageError): + result.output_sensitivities("expression:g") + + +def test_an_output_expression_of_lexer_products_has_its_column(tmp_path): + """g = 0.5Atot 2 = A: d g/d kd = -t*4*exp(-kd*t).""" + text = ( + "begin parameters\n 1 kd 0.5\nend parameters\n" + "begin species\n 1 A() 4\nend species\n" + "begin functions\n 1 g() 0.5Atot 2\nend functions\n" + "begin reactions\n 1 1 0 kd\nend reactions\n" + "begin groups\n 1 Atot 1\nend groups\n" + ) + model = _model(tmp_path, text) + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + result = bngsim.Simulator(model, method="ode", sensitivity_params=["kd"]).run( + sample_times=T, rtol=1e-10, atol=1e-12 + ) + got = [float(v) for v in result.output_sensitivities("expression:g").ravel()] + assert got == pytest.approx([-t * 4 * math.exp(-0.5 * t) for t in T], rel=1e-6, abs=1e-9) + + +@pytest.mark.parametrize("ks", ["2j", "(1+1)j", "j(2)"]) +def test_a_steady_state_column_through_a_product(tmp_path, ks): + """0 -> A at ks = 2j, A -> 0 at kd = 0.5: A* = 4j, dA*/dj = 4.""" + text = ( + f"begin parameters\n 1 j 1.5\n 2 ks {ks}\n 3 kd 0.5\nend parameters\n" + "begin species\n 1 A() 0\nend species\n" + "begin reactions\n 1 0 1 ks\n 2 1 0 kd\nend reactions\n" + ) + model = _model(tmp_path, text) + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + result = bngsim.Simulator(model, method="ode", sensitivity_params=["j"]).run( + sample_times=[0.0, 60.0], rtol=1e-10, atol=1e-12 + ) + assert float(result.species[-1, 0]) == pytest.approx(6.0, rel=1e-8) + assert float(result.sensitivities[-1, 0, 0]) == pytest.approx(4.0, rel=1e-6) + + +@pytest.mark.parametrize("law", ["[j + 1]2", "{2}j + 1", "(1+1)[j]"]) +def test_a_law_grouped_with_exprtks_other_brackets_is_parsed(law): + import sympy as sp + + j = sp.Symbol("j") + parsed = _exprtk_to_sympy(law) + assert parsed is not None + assert float(parsed.diff(j)) == 2.0 + + +@pytest.mark.parametrize( + "kd", ["abs(j(2) - 3) + 0.5", "abs(2j - 3) + 0.5", "abs((1+1)j - 3) + 0.5"] +) +def test_a_parameter_on_a_derived_kink_is_refused(tmp_path, kd): + """j = 1.5 sits on the corner of abs(2j - 3). Read with ``j(2)`` a call, + the kink check saw no parameter in it and the column came back zeros.""" + text = ( + f"begin parameters\n 1 j 1.5\n 2 kd {kd}\nend parameters\n" + "begin species\n 1 A() 4\nend species\n" + "begin reactions\n 1 1 0 kd\nend reactions\n" + ) + model = _model(tmp_path, text) + with warnings.catch_warnings(), pytest.raises(bngsim.SensitivityUnsupportedError): + warnings.simplefilter("ignore") + bngsim.Simulator(model, method="ode", sensitivity_params=["j"]).run(sample_times=T)