A rate law with a % between two number literals gets a wrong forward-sensitivity column: k*((-2.5 % 2)+1) gives dA(1)/dk = -151.63 for -30.33, with no error

Open
#1,815 0 comments 0 reactions 0 assignees View on GitHub

Maintainers usually reply within 1 day

Nobody has claimed this yet.

Assessment

Difficulty
3/5
Estimated time
1-2 days
Newbie friendliness
72/100
Issue type
Bug
Clarity
Clearly specified
Activity status
Active
Tech stack
python

Research direction

Start with _exprtk_to_sympy and _preprocess_exprtk in python/bngsim/_jacobian.py; compare how the rate law and derived parameters handle % and mod. Reproduce with the supplied script, then verify the sensitivity against its closed form or finite-difference result. Done means the % case returns about -30.326532, matching the other equivalent rate laws.

Written by the indexing model from the issue text.

Description

A rate law with a % between two number literals makes a forward-sensitivity column wrong with no error. In k*((-2.5 % 2)+1) the engine computes -2.5 % 2 as ExprTk's fmod, -0.5, so the factor is 0.5 and the trajectory is right. The sensitivity right-hand side reads the same law as 2.5*k: sympy's parser folds -2.5 % 2 as Python's floored %, 1.5, before anything else sees it. dA(1)/dk comes back -151.63 where it is -30.33, five times too large.

With a parameter on either side, k*((p % 2)+1) at p = -2.5, the column is right: there % stays a symbolic Mod until it is evaluated. mod(-2.5, 2), frac(-2.5) and rint(2.5) in the same place are right too.

A -> 0 at f() = kc with A(0) = 100, k = 1, and c written four ways, each equal to 0.5 in the engine. The oracle is the closed form, A(1) = 100exp(-0.5) and dA(1)/dk = -50*exp(-0.5) = -30.326533, and central FD of plain runs.

f() A(1) dA(1)/dk, forward sensitivity FD of plain runs
k*((-2.5 % 2)+1) 60.653063 -151.632668 -30.326531
k*(frac(-2.5)+1) 60.653063 -30.326532 -30.326531
k*(rint(2.5)-2.5) 60.653063 -30.326532 -30.326531
k*0.5 60.653063 -30.326532 -30.326531

Reproduced on main df2821c4 (editable build, macOS arm64, Python 3.13), and the same on dbfdbb0d (#1809, which changes the derived-parameter parse, not this one).

Repro

"""A -> 0 at rate k*c*A, with c a constant written four ways, each 0.5 in the engine.
dA/dk at t = 1 is -c*t*A0*exp(-c*k*t). Oracle: closed form and central FD of plain runs."""
import math, os, tempfile, warnings, logging
import bngsim
logging.disable(logging.WARNING)

def net(law, k):
    d = tempfile.mkdtemp(); f = os.path.join(d, "m.net")
    open(f, "w").write(f"""begin parameters
    1 k {k!r}
end parameters
begin species
    1 A() 100
end species
begin functions
    1 f() {law}
end functions
begin reactions
    1 1 0 f #_R1
end reactions
""")
    return bngsim.Model.from_net(f)

for law in ["k*((-2.5 % 2)+1)", "k*(frac(-2.5)+1)", "k*(rint(2.5)-2.5)", "k*0.5"]:
    with warnings.catch_warnings():
        warnings.simplefilter("ignore")
        a = lambda k: bngsim.Simulator(net(law, k), method="ode").run(sample_times=[0.0, 1.0]).species[-1, 0]
        fd = (a(1 + 1e-6) - a(1 - 1e-6)) / 2e-6
        r = bngsim.Simulator(net(law, 1.0), method="ode", sensitivity_params=["k"]).run(sample_times=[0.0, 1.0])
    print(f"{law:22s} A(1)={a(1.0):.6f}  FD dA/dk={fd:.6f}  sens dA/dk={r.sensitivities[-1, 0, 0]:.6f}")
print("closed form for c = 0.5: A(1) =", round(100*math.exp(-0.5), 6), " dA/dk =", round(-0.5*100*math.exp(-0.5), 6))

Output

k*((-2.5 % 2)+1)       A(1)=60.653063  FD dA/dk=-30.326531  sens dA/dk=-151.632668
k*(frac(-2.5)+1)       A(1)=60.653063  FD dA/dk=-30.326531  sens dA/dk=-30.326532
k*(rint(2.5)-2.5)      A(1)=60.653063  FD dA/dk=-30.326531  sens dA/dk=-30.326532
k*0.5                  A(1)=60.653063  FD dA/dk=-30.326531  sens dA/dk=-30.326532
closed form for c = 0.5: A(1) = 60.653066  dA/dk = -30.326533

Where

_exprtk_to_sympy (python/bngsim/_jacobian.py) hands the rate law to parse_expr with % as written. Python's parser turns -2.5 % 2 into sympy's Mod(-2.5, 2), which is floored and folds at once to 1.5:

>>> from bngsim._jacobian import _exprtk_to_sympy
>>> _exprtk_to_sympy("k*((-2.5 % 2)+1)")
2.5*k
>>> _exprtk_to_sympy("k*((p % 2)+1)")
k*(Mod(p, 2) + 1)

The engine's % on doubles is std::fmod, whose sign follows the first argument (ExprTk's e_mod). The C codegen already reads it so (fmod(...)), and _codegen._spell_mod already rewrites a % b as mod(a, b) with ExprTk's precedence for the stop and root scanners (#1127).

Fix direction: spell % as mod(...) in _preprocess_exprtk before the parse, the way #1809 does for the derived-parameter parse, and bind mod to a function that folds numbers with math.fmod.

Dominant language
Python
Stars
3
Forks
6
Avg merge
1d 1h
Merged PRs (30d)
295

Getting set up

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from lanl/bngsim

All issues in lanl/bngsim

Similar issues

More Python issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.