Skip to content

sensitivities: ExprTk's implicit products are written out before a derived expression or a rate law is scanned or parsed (#1937) - #2152

Merged
wshlavacek merged 3 commits into
lanl:mainfrom
Montana:fix/1937-sens-implicit-products
Dec 4, 2026

Conversation

@Montana

@Montana Montana commented Dec 4, 2026

Copy link
Copy Markdown
Collaborator

Fixes #1937

The engine reads ExprTk's implicit products (2j, 2 j, (1+1)j, (j)2, 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, found none in 2j, and took the expression to name no parameter: a column of exact zeros with no warning.

The issue's model (j 2, A0 2j, A -> 0 at kd = 0.5, sensitivity_params=["j"]):

A0 Atot at t = 0, 1, 2 dAtot/dj on main here
2*j 4, 2.4261, 1.4715 2, 1.2131, 0.7358 2, 1.2131, 0.7358
2j, 2 j, j(2), (j)2, (1+1)j, 2.j, 1e0j*2, 2(j), j[2] 4, 2.4261, 1.4715 0, 0, 0 2, 1.2131, 0.7358

The products are now written out, by the pass the C emitter already uses (_insert_implicit_products, #1212), before a derived parameter's expression is scanned or parsed, and a rate law's lexer-level ones before its parse.

Two more results of the same misreading, on main:

  • A rate law kd*2j failed its sensitivity build: Python reads 2j as an imaginary number, and the generated C had an undeclared I. It builds here, and its column matches kd*2*j's.
  • A plain run stepped over a narrow pulse centred on a product: 0 -> A at 1000*exp(-((time() - c)/0.0005)^2) with c = 2j, j = 2, gave A(10) = 0 for 0.886227. The reader that places a stop at a pulse's centre could not evaluate the centre. Here: 0.886227.

Important

The MIR and Windows legs fire on _codegen.py and run listed test files. test_codegen_sens_fd_oracle.py is on the lists of mir.yml and windows-tail.yml (the three new Terms run there); the new test_sens_implicit_products.py is on none of them, nor on windows-klu.yml's. The change is Python only, and the Ubuntu and macOS suites run both.

The diff (abridged)

python/bngsim/_codegen.py

+def _products_written_out(expr: str, scalars=None) -> str:
+    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

The one way a reader gets the text with its products written: the emitter's pass, with the names that are scalars (so j(2) is a product and exp(2) a call), or with none (the pairs the lexer multiplies). _ScalarNames hands a set to the pass as its lookup without building a dict per expression.

+    diff_names = primary_names | set(derived_names)
+    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)

_prepare_derived_expr, the parse every derived-parameter partial comes from: the products first, then the name scan that decided "names no parameter".

-    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)

compute_ic_param_sens_seed: its own scan for the primaries an expression reaches read 1e0j as the name e0j.

-        elif kind == "sym" and text.lower() in _EXPRTK_RESERVED_WORDS:
+        elif kind == "sym" and text in _EXPRTK_RESERVED_WORDS:

In the pass itself (and one more line like it): the engine builds ExprTk case-sensitive, so In and IF are names, and 2In is twice the parameter. The emitter reads the same line.

+    if _is_truth_value(prep.sym_expr):
+        return None, None

In both twins of the direct partials: a derived parameter that is a logical operation (j and k) is 0 or 1, and sympy's derivative of the bare And is 1.

python/bngsim/_jacobian.py

+    as_written = expr
+    expr = _products_written_out(expr)
+    wrote_products = expr != as_written
 ...
+    if wrote_products and parsed.atoms(sp.core.function.AppliedUndef):
+        return None
+    return parsed

_exprtk_to_sympy, the rate-law parse. It is not told the model's names, so only the lexer's pairs are written and k(x) stays a call. A text it rewrote that then parses with a call of an unknown name (0.5Atot(2), j[2]) declines, as it did when it failed to parse.

python/bngsim/_smooth_pulses.py, python/bngsim/_parameter_kinks.py

-        n: e
+        n: _products_written_out(e, scalars)
 ...
-        expr = _parsed(_inline_derived_param_refs(text, derived))
+        expr = _parsed(_inline_derived_param_refs(_products_written_out(text, scalars), derived))

The readers that inline derived parameters into a law before parsing it: the pulse stops (the derived text and the law's own) and the kink check (the derived text).

Review

One round of a whole-branch /code-review on 2fe05755, at high effort, to the bar in "How much to review". It returned two blocking findings, both new with that commit, and four that are wrong on main too. The two are fixed in 2415ea89 with three of the four; I read the fix commits' diff once more, ran the mutants below, and stopped.

Finding Kind Outcome
An expression's output sensitivity came back zeros where main refused: g() = 0.5Atot(2) parsed, once 0.5Atot was written, with Atot(2) a call. wrong result, new Fixed: refused again; test_an_output_expression_with_a_name_against_a_bracket_is_refused
A0 = 2time beside a parameter named time: the engine reads the clock (A0 = 0), and the column was the parameter's, [2, 1.41, 0.77] for zeros. Needs a hand-written .net; BNG2.pl refuses the name. wrong result, new Fixed: left as written; test_a_number_against_a_parameter_named_time_is_read_as_the_engine_reads_it
A0 = 2In, a parameter whose name lower-cased is a reserved word: zeros, as for 2j. wrong result, on main too Fixed; test_a_reserved_word_in_another_case_is_a_name
A0 = j and k: a column of [1, 0.70, 0.39] for zeros; [j and k] joined it with this change. wrong result, on main too Fixed; test_a_derived_parameter_that_is_a_truth_value_has_a_zero_column
A pulse centred on j(2) written in the law itself was still stepped over. wrong result, on main too Fixed; test_a_pulse_centred_on_a_product_is_not_stepped_over
A bump or bend call against a number in a law (1000 - 1000tanh(...), 2time() inside exp, 2abs(j - 1.5)): the pulse is stepped over, the kink is not refused. wrong result, on main too Left alone, below

The round also ran about 24,000 generated derived-parameter texts through the pass against the engine (no change of meaning beyond the time and reserved-word rows), 16 steady-state sensitivity cases (right here; main gave 0 for ks = 2j), and timed the new calls: 12.9 ms of a 7.8 s sensitivity build on Smith2013 (948 parameters) and 57 ms of 60.8 s on BIOMD0000000496.

0b39afbd is from the mutant run and not the review: two write-outs that no test could tell from the raw text were removed (the derived parse writes its own), and the law parse's refusal of square and curly brackets was replaced by the call check above, which already covers j[2].

Left alone

  • A call against a number in a law, in the pulse and kink readers (the last row). Their gates scan the raw function texts with patterns that do not match a call after a digit, and part of the path is _rate_law_flat_parts in _switch_sensitivity.py, the engine refactor's (Tracking: hold each rate-law switch's branch fixed between located crossings, and rebuild the integrator's crossing handling around it #1781). Triggers, the same on main: 0 -> A at 1000*exp(-((2time() - 8)/0.001)^2) gives A(10) = 0 for 0.886227; f() = 2abs(j - 1.5) + 0.5 at j = 1.5 returns a column where 2*abs(...) is refused.
  • A name against a bracket in a law (f() = (j(2))/8*(1 + 0.01*Atot)) is refused, or runs on the difference quotient, as on main: the law parse is not told the names.
  • A law in the kink check with j(2) written in it (abs(j(2) - 3)): not refused, as on main. The derived-parameter spelling is.
  • _translate_expr_jax leaves 2j as written on both builds. jax is not installed here, so whether its check against the engine refuses the model was not run.

Testing

python/tests/test_sens_implicit_products.py, new (135 cases), and three Terms in test_codegen_sens_fd_oracle.py (6 cases), on 0b39afbd. With main's code (and a stand-in for the new helper, so the file imports): 89 failed, 52 passed. Here: all 141 pass. The 52 are controls and refusals: the * spelling, numbers with exponents, names with digits in them, calls, reserved words as written.

How this was checked

  1. Full suite on 0b39afbd (main at 49c19797), macOS arm64, Python 3.13, uv sync --extra test plus h5py, BNGPATH at BioNetGen 2.9.3: 27003 passed, 548 skipped, 151 xfailed, 1 failed. The failure is test_run_tests_sh.py::test_the_script_itself_runs_walk_up_dependent_tests_green, which fails the same way on main in this environment (it counts skips for jax, diffrax, roadrunner and vivarium, which the test extra does not install).
  2. Mutants (mutate.py from bngsim-preflights) on 0b39afbd: 14 of 14 killed: the derived parse writing no products, or given no names; the seed's expressions left raw; the time rule dropped, in either place; reserved words lower-cased; a declined text raising; a logical operation keeping sympy's derivative, or a comparison counted as one; the law parse writing nothing, or keeping a call of an unknown name; the pulse reader's derived text, or its law, left raw; the kink reader's derived text left raw. A first run on 2415ea89 left 4 of 17 alive: one needed a test (the kink refusal, added) and three showed code no result depended on, removed in 0b39afbd.
  3. Every spelling in every place: 14 spellings of 2*j in 7 places an expression can sit (a seed, a rate constant, two chains through another derived parameter, a function, a function over an observable, one over the clock), both sensitivity methods, each column against a central difference of plain runs. Main: 64 of 196 wrong. Here: 0 wrong, 192 right, and the same 4 refused on both (j(2) in a law over the state or the clock).
  4. Cost, medians of 5 passes, five runs a side on 0b39afbd, sides alternated: _exprtk_to_sympy over 2,000 laws written to send every one through the tokenizer (an exponent and a call after a digit in each): main 1288 to 1361 ms, here 1337 to 1457 ms, 3 to 8% of the parse. _prepare_derived_expr over 2,000 derived expressions among 6,000 names: main 1290 to 1383 ms, here 1313 to 1472 ms. A law with nothing that could be a product is one regex search more. On whole builds the review's timing is under Review.
  5. pre-commit run --all-files, ci/changelog.py check, sphinx -W: pass.
  6. Linux (bngsim-docker, bngsim_docker.py test --merge-main --kind debian --arch arm64): 0b39afbd merged with main 49c19797, test_sens_implicit_products.py, test_codegen_sens_fd_oracle.py, test_smooth_pulse_stops.py and test_derived_seed_engine_rounding.py: 311 passed.
  7. Pre-PR gate (prepr_check.py from bngsim-preflights) on 0b39afbd with this description: 0 failed, 8 warnings, 35 passed. The warnings: the changelog fragment is 1,125 of 1,200 characters; the CI legs (above); the callers of the changed functions, to read (they take the parse's result, and a text with no product in it is returned as it was); code changed after the reviewed commit (described under Review); the suite and mutant logs are older than the files' time on disk (item 4 checked main's python/bngsim out and back for each timed side, byte for byte); the Linux run covers this PR's two test files and two neighbours, not every file with sens in its name (CI's legs run them all); claims to recount; the Left alone triggers were rerun on 0b39afbd.
  8. Not run: benchmarks/perf_ab.py (it times runs of models with no implicit product; the pass's cost is item 4).

…rived expression or a rate law is scanned or parsed (lanl#1937)

The engine reads 2j, (1+1)j and j(2) as 2*j. The readers that build
forward sensitivities scanned the text for the word j and found none:
A0 = 2j gave dA/dj = [0, 0, 0] with no warning, a law k*2j failed its
build on Python's imaginary I, and a plain run stepped over a pulse
centred on c = 2j. The pass the C emitter uses (lanl#1212) now runs first
in the derived parse, where derived expressions are collected for the
seeds, the chain rule, the kink check and the pulse stops, and, for
the pairs the lexer multiplies, in the rate-law parse.

Signed-off-by: Montana <montana@linux.com>
…itten declines, a number against a parameter named time is left, reserved words are read as written, and a logical derived parameter has a zero column

0.5Atot(2) parsed with Atot(2) as a call once 0.5Atot was written out,
and its output sensitivity came back zeros where main refused. 2time
beside a parameter named time is the clock to the engine, and was given
the parameter's column. 2In was left unwritten (the engine's ExprTk is
case-sensitive). [j and k] reached sympy's derivative of And, which is
1. A pulse centred on j(2) in the law itself is found.

Signed-off-by: Montana <montana@linux.com>
…aw text, let the law parse group with square and curly brackets, and tests for the kink refusal

The derived parse writes its own products, so the dicts collected for
the chain rule and the pulse gate read the same either way. A law with
j[2] declines through the call it parses to, which leaves [j + 1]2 free
to parse.

Signed-off-by: Montana <montana@linux.com>
@wshlavacek
wshlavacek merged commit ac00740 into lanl:main Dec 4, 2026
24 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

2 participants