Skip to content

convert: the simulate actions sbml_to_bngl writes for a model's events name their tolerances (#1830) - #2145

Merged
wshlavacek merged 5 commits into
lanl:mainfrom
Montana:fix/1830-bngl-simulate-tolerances
Dec 4, 2026
Merged

wshlavacek merged 5 commits into
lanl:mainfrom
Montana:fix/1830-bngl-simulate-tolerances

Conversation

@Montana

@Montana Montana commented Dec 3, 2026

Copy link
Copy Markdown
Collaborator

Fixes #1830

sbml_to_bngl writes a model's fixed-time events as simulate phases, and wrote them with no tolerances. BNG2.pl then runs them at its own atol = 1e-8, which is above the species of a model in molar units. BIOMD0000000571 converts with ok=True and nothing listed as lost, and BNG2.pl runs the result with 57 of its 76 species over 1e-4 of their peak off the SBML.

Each phase now names rtol and an atol taken from the scale of the model's species.

main:  simulate({method=>"ode",t_start=>0,t_end=>500,n_steps=>100})
       BNG2.pl against bngsim on the SBML: 57 of 76 species over 1e-4 of peak, worst 2.57 (CRPsite_cyaA)
here:  simulate({method=>"ode",t_start=>0,t_end=>500,n_steps=>100,atol=>9.623e-19,rtol=>1e-08})
       BNG2.pl against bngsim on the SBML:  0 of 76 species over 1e-4 of peak, worst 3.2e-05 (IICB_Mlc)

(BNG2.pl 2.9.3, t_span=(0, 1000), 201 points, every output time but the event's; bngsim on the SBML at rtol=1e-10, atol=1e-14.)

The rule, since BNG2.pl takes one atol for every species:

the model atol written
species a reaction or a rate rule changes give a positive value (at the start, or set by an event) rtol times the smallest such value, but not under 1e-6 of the largest, and never above 1e-08
those species all start at 0 the same, over every species (the $-fixed ones and the parameters an event sets)
nothing positive anywhere, or a model of counts (species at 0 or at least 1) 1e-08, what BNG2.pl ran it at before

It is the floor of the default Simulator.run derives per species (#1420). rtol is written as 1e-08, BNG2.pl's own.

Important

This closes the wrong result the issue is titled for, and its third point (sbml_to_net's note for dropped events named a SED-ML sidecar; it now names sbml_to_bngl). The issue's other two asks are features and are not here: a sedml= argument, and an actions block for an event-free model. They need an issue of their own before this one closes.

#2139 and #2140 touch the same files (convert/__init__.py, _net_writer.py, interchange.md) in other hunks: this branch merges clean with each, in either order.

The diff (abridged)

python/bngsim/convert/_events.py

+def _phase_tolerances(model: Model, fires: list[_Fire]) -> dict[str, float]:
+    ...
+    for rxn in data["reactions"]:
+        reactants, products = list(rxn["reactants"]), list(rxn["products"])
+        changed.update(
+            i for i in {*reactants, *products} if reactants.count(i) != products.count(i)
+        )
+    changed -= fixed
+
+    def scale(of: set[int]) -> float | None:
+        values = [float(state[i]) for i in of if i < len(state)]
+        values += [abs(float(val)) for f in fires for sp, val, _var in f.assigns if sp in of]
+        positive = [v for v in values if math.isfinite(v) and v > 0.0]
+        if not positive:
+            return None
+        return max(min(positive), _SCALE_SHARE * max(positive))
+
+    floor = scale(changed)
+    if floor is None:
+        floor = scale(set(range(len(data["species"]))))
+    atol = _BNG_TOLERANCE if floor is None else min(_BNG_TOLERANCE, _BNG_TOLERANCE * floor)
+    return {"atol": atol, "rtol": _BNG_TOLERANCE}

The scale. A species nothing changes gives none: the loader holds a parameter an event sets as such a species, and a rate constant is not a concentration.

-def _phase(a: float, b: float, total: float, base_steps: int, first: bool) -> Experiment:
+def _phase(
+    a: float, b: float, total: float, base_steps: int, first: bool, tolerances: dict[str, float]
+) -> Experiment:
     n_steps = max(1, round(base_steps * (b - a) / total))
-    extra: dict[str, Any] = {} if first else {"continue": 1}
+    extra: dict[str, Any] = dict(tolerances)
+    if not first:
+        extra["continue"] = 1

Every phase carries them, in the extra arguments the writer already emits and the reader already keeps.

python/bngsim/convert/_net_writer.py

-            "network channel; emit them as a SED-ML sidecar instead"
+            "network channel; bngsim.convert.sbml_to_bngl carries the ones that fire "
+            "at fixed times, as BNGL actions"

The note sbml_to_net gives for the events it drops.

python/bngsim/convert/__init__.py (the sbml_to_bngl docstring) and docs/user-guide/interchange.md say what the phases name.

Review

One round of a whole-branch /code-review on f689e6f6, at high effort, to the bar in "How much to review". It returned two blocking findings, both the issue's own symptom on inputs the first rule missed. Both are fixed, and I read the fix commits' diff once more and stopped.

Finding Kind Outcome
A parameter an event sets is held as a species, so a rate constant entered the scale: kon = 1e6 beside species at 1e-9 lifted the floor to 1, the phases named atol=>1e-08, and BNG2.pl ran the three species 0.4 to 3.6 times their peak off. A small one tightened a model of counts. wrong result Fixed in 70978152: the scale is taken from species a reaction or a rate rule changes. BNG2.pl on the trigger: under 1e-7. test_a_parameter_an_event_sets_gives_no_scale, test_a_small_parameter_an_event_sets_leaves_a_model_of_counts_alone
Species that all start at 0 beside a $-fixed stimulus at 1e-9 kept atol=>1e-08: BNG2.pl ran them 20 to 26% of peak off. wrong result Fixed in 70978152 and 78c56d12: the scale falls back to every species. BNG2.pl on the trigger: under 1e-7. test_species_that_start_at_zero_take_the_scale_of_a_fixed_one

Commits after the round: 70978152 (those fixes); 3808dd99 (tests only: pytest.approx kept its default absolute tolerance of 1e-12, so every expected atol near 1e-17 passed whatever the code gave, which three surviving mutants showed; a catalyst case added); ec0140e9 (one more test, for the mutant left alive); 78c56d12, from my own rerun of the corpus below and not the review: the fallback of 70978152 read the $-fixed species only and lost MODEL7743528808, whose species start at 0 beside fixed species of order 1.

Left alone

  • A species that starts at 0, or far below the others, and stays small. One scalar from the start cannot scale it, as Simulator.run's default cannot (AtolScaleWarning). MODEL7743444866 gets atol=>1.66e-09 and BNG2.pl runs s195 3.1e-3 of peak off, as it does with no tolerances (3.0e-3).
  • BIOMD0000000918's Myc, whose true value is 0 on an unstable state: BNG2.pl's roundoff grows to 0.02 of the peak with the new atol, 0.0013 without.
  • The actions an OMEX's SED-ML gives (omex_to_net) are written from the document's own protocol and are not changed here.

Testing

python/tests/test_sbml_to_bngl_tolerances.py, new, on ec0140e9: 18 tests. With main's code and BNG2.pl: 18 failed. Here: 18 passed with BNG2.pl, 17 passed and 1 skipped without.

How this was checked

  1. Full suite on ec0140e9 (main at 44e51182), macOS arm64, Python 3.13, uv sync --extra test plus h5py, BNGPATH at BioNetGen 2.9.3: 26671 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 ec0140e9: 15 of 16 killed: no tolerances written, or on the first phase only; atol left at 1e-8 or let above it; the floor dropped, moved to 1e-3, or replaced by the largest; event values giving no scale, or every event's; every species or a catalyst counted as changing; no fallback, or one to the fixed species alone; rtol not written; the note keeping the sidecar. The survivor removes changed -= fixed, and is equivalent for a model the SBML loader builds: it lists no held species among a reaction's reactants or products (test_a_boundary_species_a_reaction_consumes_gives_no_scale is the case). The line stays for a model built another way.

  3. The corpus under BNG2.pl: each of benchmarks/sbml_events' 116 models that converts with actions, as written here and with the tolerances stripped (main's file), BNG2.pl 2.9.3 on both, against bngsim on the SBML at rtol=1e-10, atol=1e-16, worst species over peak away from the event times. 103 could be compared.

    models
    over 1e-4 on main, under it here 9 (BIOMD0000000001, 186, 187, 193, 194, 699, 701, MODEL7743528808, MODEL7743608569)
    over 1e-4 on both, closer here 9 (BIOMD0000000227 from 5.4e5 to 0.93, MODEL7743631122 from 750 to 2.2e-3, ...)
    over 1e-4 on both, the same within 15% 45
    under 1e-4 on both 39
    further off here 1 (BIOMD0000000918, under Left alone)

    The 45 are not a tolerance's: they are equally off with any atol (an event at the end of the default horizon, which BNG2.pl applies after its last row, among them BIOMD0000000571 at the default t_span). No model newly fails under BNG2.pl; BIOMD0000000186, 187 and 193 stopped with an error before and complete now. BNG2.pl's time over the corpus: 49 s here, 46 s without the tolerances.

  4. pre-commit run --all-files, ci/changelog.py check, sphinx -W: pass.

  5. Linux with BNG2.pl (bngsim-docker, bngsim_docker.py test --merge-main --kind bionetgen, amd64 under emulation): ec0140e9 merged with main 44e51182, test_sbml_to_bngl_tolerances.py, test_sbml_to_bngl.py and test_sbml_to_bngl_events.py: 155 passed, 34 skipped. All 18 of this PR's tests pass there, the BNG2.pl run of BIOMD0000000571 among them.

  6. Pre-PR gate (prepr_check.py from bngsim-preflights) on ec0140e9 with this description: 0 failed, 9 warnings, 36 passed. The warnings: convert: a compartment size the SBML model refuses to change is left out or marked, like a frozen parameter (#1992) #2139 on the same files (above); lists of callers and of sites that name the changed functions, to read (read: _build_protocol is the one place events become actions); a writer change wants a corpus comparison (item 3 is it, under BNG2.pl); code changed after the reviewed commit (described under Review); the corpus and mutant logs are older than _net_writer.py's time on disk (a git checkout of main's code and back, to count the tests that fail there, rewrote the file byte for byte); the Linux run covers the three converter test files, not every file with bngl in its name (CI's legs run them all); claims to recount.

  7. Not run: benchmarks/perf_ab.py (no change under src/, the code generator, the loaders or a run's path: sbml_to_bngl gains one pass over the model's reactions).

…s name their tolerances (lanl#1830)

BNG2.pl runs a simulate that names no atol at 1e-8, above the species of
a model in molar units: BIOMD0000000571's actions ran with 57 of 76
species over 1e-4 of their peak off the SBML, under a report that listed
nothing lost. Each phase now names rtol 1e-8 and an atol of rtol times
the smallest value an integrated species starts from or an event sets it
to, floored at 1e-6 of the largest and never above 1e-8.

sbml_to_net's note for dropped events names sbml_to_bngl.

Signed-off-by: Montana <montana@linux.com>
…cies that all start at 0 take a fixed species' scale

A rate constant the loader holds as a species lifted the floor to 1e-6 of
itself (atol 1e-8 beside species at 1e-9), and a model whose integrated
species all start at 0 beside a boundary stimulus at 1e-9 kept 1e-8.

Signed-off-by: Montana <montana@linux.com>
…k, and a catalyst gives no scale

pytest.approx's default absolute tolerance of 1e-12 passed any atol under
it: three mutants survived.

Signed-off-by: Montana <montana@linux.com>
… every species, as Simulator.run does

MODEL7743528808's species start at 0 beside fixed species of order 1; the
parameter its event sets is the only small scale the model holds.

Signed-off-by: Montana <montana@linux.com>
…ves no scale

The one mutant left alive: a fixed species counted among those that change.

Signed-off-by: Montana <montana@linux.com>
@wshlavacek
wshlavacek merged commit 7442636 into lanl:main Dec 4, 2026
17 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