From f689e6f61e8d328f2b2deddccabe6364a7f260ae Mon Sep 17 00:00:00 2001 From: Montana Date: Thu, 3 Dec 2026 10:05:38 -0800 Subject: [PATCH 1/5] convert: the simulate actions sbml_to_bngl writes for a model's events name their tolerances (#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 --- changelog.d/1830.fixed.md | 1 + docs/user-guide/interchange.md | 4 +- python/bngsim/convert/__init__.py | 6 + python/bngsim/convert/_events.py | 52 +++- python/bngsim/convert/_net_writer.py | 3 +- python/tests/test_sbml_to_bngl_tolerances.py | 252 +++++++++++++++++++ 6 files changed, 312 insertions(+), 6 deletions(-) create mode 100644 changelog.d/1830.fixed.md create mode 100644 python/tests/test_sbml_to_bngl_tolerances.py diff --git a/changelog.d/1830.fixed.md b/changelog.d/1830.fixed.md new file mode 100644 index 000000000..3768cd932 --- /dev/null +++ b/changelog.d/1830.fixed.md @@ -0,0 +1 @@ +- **The `simulate` actions `sbml_to_bngl` writes for a model's fixed-time events named no tolerances, so BNG2.pl ran them at its own `atol = 1e-8`, above the species of a model in molar units (issue #1830).** BIOMD0000000571, converted with `ok=True` and nothing listed as lost, ran under BNG2.pl with 57 of its 76 species over 1e-4 of their peak off the SBML, the worst at 2.6 times its peak. Each phase now names `rtol=>1e-08` and an `atol` taken from the model's scale: `rtol` times the smallest value a species BNG2.pl integrates starts from or an event sets it to, but not under 1e-6 of the largest, and never above `1e-08`. With them BNG2.pl runs that model with no species over 1e-4 off (worst 3.2e-5). A model of counts gets `atol=>1e-08`, what BNG2.pl ran it at before. `sbml_to_net`'s note for the events it drops now names `sbml_to_bngl`, where it said to emit a SED-ML sidecar. An event-free model still gets no actions block, and `sbml_to_bngl` still takes no `sedml=`. diff --git a/docs/user-guide/interchange.md b/docs/user-guide/interchange.md index 652a29650..ee8024a46 100644 --- a/docs/user-guide/interchange.md +++ b/docs/user-guide/interchange.md @@ -83,7 +83,9 @@ What to watch out for: A plain `.net` assumes unit volumes. To keep compartment volumes, convert to compartmental BNGL, a `.bngl` with a `begin compartments` block. It carries fixed compartment volumes, transport between compartments, and SBML events at -fixed times, which become a BNGL actions block. +fixed times, which become a BNGL actions block. Each `simulate` of that block names +its tolerances, with an `atol` taken from the scale of the model's species: +BNG2.pl's own `1e-8` is above the species of a model in molar units. ```python report = bngsim.convert.sbml_to_bngl("model.xml", "model_cbngl.bngl") diff --git a/python/bngsim/convert/__init__.py b/python/bngsim/convert/__init__.py index 21b54a9ac..7d66413c4 100644 --- a/python/bngsim/convert/__init__.py +++ b/python/bngsim/convert/__init__.py @@ -616,6 +616,12 @@ def sbml_to_bngl( t_span, n_points : tuple[float, float], int The horizon for the events→actions ``simulate`` phases (the trailing phase runs to ``t_span[1]``; ignored when the model has no events). + Each phase names its tolerances (issue #1830): ``rtol=>1e-08``, and + an ``atol`` of ``rtol`` times the smallest value a species BNG2.pl + integrates starts from or an event sets it to, but not under 1e-6 of + the largest, and never above BNG2.pl's own ``1e-08``. BNG2.pl runs a + ``simulate`` that names none at ``atol = 1e-08``, above the species of + a model in molar units. A model of counts gets ``atol=>1e-08``. Returns ------- diff --git a/python/bngsim/convert/_events.py b/python/bngsim/convert/_events.py index 4d3610aa2..fca191153 100644 --- a/python/bngsim/convert/_events.py +++ b/python/bngsim/convert/_events.py @@ -1199,6 +1199,7 @@ def _build_protocol( t_end = max_fire total = max(t_end - t_start, 1.0) base_steps = max(n_points - 1, 1) + tolerances = _phase_tolerances(model, fires) # group assignments by fire time, in execution order within a time by_time: dict[float, list[tuple[int, float, str]]] = {} @@ -1210,7 +1211,7 @@ def _build_protocol( first = True for ft in sorted(by_time): if ft > prev: - steps.append(_phase(prev, ft, total, base_steps, first)) + steps.append(_phase(prev, ft, total, base_steps, first, tolerances)) first = False prev = ft for sp_idx, val, _var in by_time[ft]: @@ -1222,14 +1223,57 @@ def _build_protocol( ) ) if t_end > prev: - steps.append(_phase(prev, t_end, total, base_steps, first)) + steps.append(_phase(prev, t_end, total, base_steps, first, tolerances)) return ProtocolSpec(steps=tuple(steps), source=None) -def _phase(a: float, b: float, total: float, base_steps: int, first: bool) -> Experiment: +# BNG2.pl's own ``atol`` and ``rtol``, and the share of the largest species +# below which a species gives no scale: Simulator's (_ATOL_SCALE_RELEVANT). +_BNG_TOLERANCE = 1e-8 +_SCALE_SHARE = 1e-6 + + +def _phase_tolerances(model: Model, fires: list[_Fire]) -> dict[str, float]: + """The ``atol`` and ``rtol`` every ``simulate`` phase is written with. + + BNG2.pl runs a ``simulate`` that names none at ``atol = rtol = 1e-8``, an + absolute tolerance chosen for species held as molecule counts. An SBML + model in molar units holds species below it, and CVODE then controls none + of their error: BIOMD0000000571's actions, as written, put 57 of its 76 + species over 1e-4 of their peak off the SBML, the worst at 2.6 times its + peak, under a report that listed nothing lost. + + BNG2.pl takes one ``atol`` for every species, so it is the scalar the + smallest species needs: ``rtol`` of the smallest value a species the solver + integrates starts from or an event sets it to, but not under 1e-6 of the + largest, and never above 1e-8. That is the floor of the default + :meth:`bngsim.Simulator.run` derives per species. A model of counts, whose + species start at 0 or at least 1, keeps 1e-8, as does one with no positive + value to take a scale from. + """ + import numpy as np + + state = np.abs(np.asarray(model.get_state(), dtype=float)) + fixed = np.asarray(model._core.species_is_fixed, dtype=bool) + values = [float(v) for v in state[~fixed[: len(state)]]] + values += [abs(float(val)) for f in fires for sp, val, _var in f.assigns if not fixed[sp]] + finite = [v for v in values if math.isfinite(v)] + positive = [v for v in finite if v > 0.0] + atol = _BNG_TOLERANCE + if positive: + floor = max(min(positive), _SCALE_SHARE * max(positive)) + atol = min(atol, _BNG_TOLERANCE * floor) + return {"atol": atol, "rtol": _BNG_TOLERANCE} + + +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 return Experiment( kind="simulate", method="ode", diff --git a/python/bngsim/convert/_net_writer.py b/python/bngsim/convert/_net_writer.py index 585fa37b2..b23541b2e 100644 --- a/python/bngsim/convert/_net_writer.py +++ b/python/bngsim/convert/_net_writer.py @@ -153,7 +153,8 @@ def _eg(names: list[str]) -> str: if n_events: dropped.append( f"{n_events} event(s) — events define simulation protocol, not the " - "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" ) # Aggregate per category so a 200-species model yields one readable note, not 200. diff --git a/python/tests/test_sbml_to_bngl_tolerances.py b/python/tests/test_sbml_to_bngl_tolerances.py new file mode 100644 index 000000000..90d4099f0 --- /dev/null +++ b/python/tests/test_sbml_to_bngl_tolerances.py @@ -0,0 +1,252 @@ +"""The ``simulate`` actions ``sbml_to_bngl`` writes for a model's fixed-time +events name their tolerances (issue #1830). + +BNG2.pl runs a ``simulate`` that names none at ``atol = rtol = 1e-8``. A model +in molar units holds species below that absolute tolerance, so the actions as +written ran BIOMD0000000571 with 57 of its 76 species over 1e-4 of their peak +off the SBML, under a report that listed nothing lost. The phases now carry +``rtol`` and an ``atol`` taken from the scale of the model's species. + +The last test runs BNG2.pl and skips without it. +""" + +from __future__ import annotations + +import os +import re +import shutil +import subprocess +import warnings +from pathlib import Path + +import bngsim +import numpy as np +import pytest +from bngsim.convert import sbml_to_bngl, sbml_to_net +from bngsim.convert._bng2 import find_bng2 +from bngsim.convert._protocol import Experiment, parse_bngl_protocol + +pytestmark = pytest.mark.skipif(not bngsim.HAS_LIBSBML, reason="SBML conversion requires libsbml") + +REPO = Path(__file__).resolve().parents[2] +NISHIO = REPO / "benchmarks" / "sbml_events" / "BIOMD0000000571.xml" + +_M = '' +_TIME = ( + 'time' +) + + +def _sbml( + species: dict[str, float], sets: dict[str, float], boundary: tuple[str, ...] = () +) -> str: + """Each of *species* decaying at k = 0.1, and one event at t = 1 that sets + *sets*. A species in *boundary* is a boundary condition and does not decay.""" + listed = "".join( + f'' + for sid, x0 in species.items() + ) + decays = "".join( + f'' + f'' + f"{_M}k{sid}" + "" + for sid in species + if sid not in boundary + ) + assignments = "".join( + f'{_M}{value!r}' + for sid, value in sets.items() + ) + return ( + '\n' + '' + '' + '' + f"{listed}" + '' + f"{decays}" + '' + f'{_M}{_TIME}1' + f"{assignments}" + "" + ) + + +def _convert(tmp_path: Path, xml: str): + path = tmp_path / "m.xml" + path.write_text(xml, encoding="utf-8") + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + return sbml_to_bngl(path, None, strict=True, t_span=(0.0, 3.0), n_points=7) + + +def _phases(report) -> list[Experiment]: + assert report.protocol is not None + phases = [s for s in report.protocol.steps if isinstance(s, Experiment)] + assert len(phases) == 2 # up to the event at t = 1, and on to the horizon + return phases + + +def _tolerances(report) -> tuple[float, float]: + """The ``(atol, rtol)`` the phases name: every phase names the same ones.""" + named = {(p.extra.get("atol"), p.extra.get("rtol")) for p in _phases(report)} + assert len(named) == 1, named + atol, rtol = named.pop() + assert atol is not None and rtol is not None + return float(atol), float(rtol) + + +def test_a_molar_models_phases_name_an_atol_under_its_species(tmp_path): + """Species at 3e-9 and 7e-8: BNG2.pl's own 1e-8 is above one and a seventh + of the other. The phases name rtol of the smaller.""" + report = _convert(tmp_path, _sbml({"A": 3e-9, "B": 7e-8}, {"A": 5e-9})) + atol, rtol = _tolerances(report) + assert rtol == 1e-8 + assert atol == pytest.approx(1e-8 * 3e-9, rel=1e-12) + + +def test_the_tolerances_are_in_the_text_of_every_simulate(tmp_path): + report = _convert(tmp_path, _sbml({"A": 3e-9, "B": 7e-8}, {"A": 5e-9})) + calls = re.findall(r"^simulate\(\{.*\}\)$", report.output_text, flags=re.M) + assert len(calls) == 2 + for call in calls: + assert "atol=>3e-17" in call and "rtol=>1e-08" in call, call + assert "continue=>1" not in calls[0] and "continue=>1" in calls[1] + + +def test_a_model_of_counts_keeps_bng2s_own_tolerances(tmp_path): + """Species at 1 and 2 are above 1e-8: the phases say BNG2.pl's defaults.""" + report = _convert(tmp_path, _sbml({"A": 1.0, "B": 2.0}, {"A": 5.0})) + assert _tolerances(report) == (1e-8, 1e-8) + + +def test_a_value_an_event_sets_gives_the_scale_too(tmp_path): + """The species start at 1e-3 and 2e-3; the event sets A to 5e-7, which the + second phase integrates from.""" + report = _convert(tmp_path, _sbml({"A": 1e-3, "B": 2e-3}, {"A": 5e-7})) + atol, _ = _tolerances(report) + assert atol == pytest.approx(1e-8 * 5e-7, rel=1e-12) + + +def test_a_species_far_below_the_largest_does_not_set_the_scale(tmp_path): + """One species at 1e-12 beside one at 0.5: the scale stops at 1e-6 of the + largest, as the default of Simulator.run does.""" + report = _convert(tmp_path, _sbml({"A": 1e-12, "B": 0.5}, {"B": 0.25})) + atol, _ = _tolerances(report) + assert atol == pytest.approx(1e-8 * 0.5e-6, rel=1e-12) + + +def test_a_boundary_species_gives_no_scale(tmp_path): + """BNG2.pl does not integrate a ``$``-fixed species, so its value, however + small or large, is no scale: A at 1e-9 is fixed, B and D are at 1e-3.""" + xml = _sbml({"A": 1e-9, "B": 1e-3, "D": 1e-3}, {"B": 2e-3}, boundary=("A",)) + atol, _ = _tolerances(_convert(tmp_path, xml)) + assert atol == pytest.approx(1e-8 * 1e-3, rel=1e-12) + + +def test_species_that_all_start_at_zero_keep_bng2s_own_tolerance(tmp_path): + """No positive value to take a scale from, but for the one the event sets.""" + report = _convert(tmp_path, _sbml({"A": 0.0, "B": 0.0}, {"A": 0.0})) + assert _tolerances(report) == (1e-8, 1e-8) + + +def test_the_written_tolerances_read_back(tmp_path): + """The reader of a .bngl's actions keeps what the writer wrote.""" + report = _convert(tmp_path, _sbml({"A": 3e-9, "B": 7e-8}, {"A": 5e-9})) + actions = report.output_text[report.output_text.index("begin actions") :] + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + read = parse_bngl_protocol(actions) + phases = [s for s in read.steps if isinstance(s, Experiment)] + assert len(phases) == 2 + for phase in phases: + assert float(phase.extra["atol"]) == pytest.approx(3e-17, rel=1e-12) + assert float(phase.extra["rtol"]) == 1e-8 + + +def test_the_issues_model_names_a_tolerance_below_its_species(): + """BIOMD0000000571: the species BNG2.pl integrates start between 1.8e-13 and + 1e-4. The scale is 1e-6 of the largest, far under 1e-8.""" + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + report = sbml_to_bngl(NISHIO, None, strict=True, t_span=(0.0, 1000.0), n_points=201) + model = bngsim.Model.from_sbml(NISHIO) + assert report.ok and not report.lossy and not report.dropped + atol, rtol = _tolerances(report) + state = np.asarray(model.get_state())[~np.asarray(model._core.species_is_fixed, dtype=bool)] + assert rtol == 1e-8 + assert atol == pytest.approx(1e-8 * 1e-6 * state.max(), rel=1e-12) + assert atol < 1e-8 * 1e-8 + + +def test_sbml_to_nets_dropped_events_note_names_sbml_to_bngl(tmp_path): + """The note said to "emit them as a SED-ML sidecar", which no converter + does for an event; ``sbml_to_bngl`` carries the fixed-time ones.""" + path = tmp_path / "m.xml" + path.write_text(_sbml({"A": 1.0, "B": 2.0}, {"A": 5.0}), encoding="utf-8") + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + report = sbml_to_net(path, None, strict=False) + notes = [n for n in report.dropped if "event" in n] + assert len(notes) == 1 + assert "sbml_to_bngl" in notes[0] and "SED-ML sidecar" not in notes[0] + + +_BNG2 = find_bng2() + + +@pytest.mark.skipif( + _BNG2 is None or shutil.which("perl") is None, reason="BNG2.pl / perl not available" +) +def test_bng2_runs_the_issues_model_onto_the_sbml(tmp_path): + """BNG2.pl on the actions as written, against bngsim on the SBML at tight + tolerances, at every output time but the event's: no species is over 1e-4 + of its peak off. With no tolerances in the actions, 57 of 76 were, the + worst at 2.6 times its peak.""" + assert _BNG2 is not None + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + sbml_to_bngl( + NISHIO, tmp_path / "nishio.bngl", strict=True, t_span=(0.0, 1000.0), n_points=201 + ) + env = {**os.environ, "BNGPATH": str(_BNG2.parent)} + proc = subprocess.run( + ["perl", str(_BNG2), "--outdir", str(tmp_path), str(tmp_path / "nishio.bngl")], + capture_output=True, + text=True, + timeout=600, + env=env, + ) + gdat = tmp_path / "nishio.gdat" + assert gdat.is_file(), proc.stdout[-1500:] + proc.stderr[-500:] + names = gdat.read_text().splitlines()[0].lstrip("#").split() + rows = np.loadtxt(gdat) + rows = rows[np.r_[True, np.diff(rows[:, 0]) > 0]] # the event's time is written twice + times = rows[:, 0] + assert times[-1] == 1000.0 + + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + model = bngsim.Model.from_sbml(NISHIO) + result = bngsim.Simulator(model, method="ode").run( + sample_times=[float(t) for t in times], rtol=1e-10, atol=1e-14 + ) + species = np.asarray(result.species) + away = np.abs(times - 500.0) > 1e-9 + compared = 0 + off = {} + for j, name in enumerate(result.species_names): + sid = name.split(":")[-1].replace("()", "").lstrip("@") + if sid not in names: + continue + compared += 1 + ours = species[away, j] + peak = float(np.max(np.abs(ours))) or 1.0 + error = float(np.max(np.abs(rows[away, names.index(sid)] - ours))) / peak + if error > 1e-4: + off[sid] = error + assert compared == 76 + assert off == {} From 70978152b12e146078b9db30ff65ef3e2fb982bb Mon Sep 17 00:00:00 2001 From: Montana Date: Thu, 3 Dec 2026 10:17:18 -0800 Subject: [PATCH 2/5] review (#1830): a parameter an event sets gives no scale, and species 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 --- changelog.d/1830.fixed.md | 2 +- python/bngsim/convert/__init__.py | 7 +-- python/bngsim/convert/_events.py | 49 ++++++++++++++------ python/tests/test_sbml_to_bngl_tolerances.py | 40 ++++++++++++++-- 4 files changed, 76 insertions(+), 22 deletions(-) diff --git a/changelog.d/1830.fixed.md b/changelog.d/1830.fixed.md index 3768cd932..2c41d0736 100644 --- a/changelog.d/1830.fixed.md +++ b/changelog.d/1830.fixed.md @@ -1 +1 @@ -- **The `simulate` actions `sbml_to_bngl` writes for a model's fixed-time events named no tolerances, so BNG2.pl ran them at its own `atol = 1e-8`, above the species of a model in molar units (issue #1830).** BIOMD0000000571, converted with `ok=True` and nothing listed as lost, ran under BNG2.pl with 57 of its 76 species over 1e-4 of their peak off the SBML, the worst at 2.6 times its peak. Each phase now names `rtol=>1e-08` and an `atol` taken from the model's scale: `rtol` times the smallest value a species BNG2.pl integrates starts from or an event sets it to, but not under 1e-6 of the largest, and never above `1e-08`. With them BNG2.pl runs that model with no species over 1e-4 off (worst 3.2e-5). A model of counts gets `atol=>1e-08`, what BNG2.pl ran it at before. `sbml_to_net`'s note for the events it drops now names `sbml_to_bngl`, where it said to emit a SED-ML sidecar. An event-free model still gets no actions block, and `sbml_to_bngl` still takes no `sedml=`. +- **The `simulate` actions `sbml_to_bngl` writes for a model's fixed-time events named no tolerances, so BNG2.pl ran them at its own `atol = 1e-8`, above the species of a model in molar units (issue #1830).** BIOMD0000000571, converted with `ok=True` and nothing listed as lost, ran under BNG2.pl with 57 of its 76 species over 1e-4 of their peak off the SBML, the worst at 2.6 times its peak. Each phase now names `rtol=>1e-08` and an `atol` taken from the model's scale: `rtol` times the smallest value a species a reaction or a rate rule changes starts from or an event sets it to, but not under 1e-6 of the largest, and never above `1e-08` (where those all start at 0, the `$`-fixed species' values). With them BNG2.pl runs that model with no species over 1e-4 off (worst 3.2e-5). A model of counts gets `atol=>1e-08`, what BNG2.pl ran it at before. `sbml_to_net`'s note for the events it drops now names `sbml_to_bngl`, where it said to emit a SED-ML sidecar. An event-free model still gets no actions block, and `sbml_to_bngl` still takes no `sedml=`. diff --git a/python/bngsim/convert/__init__.py b/python/bngsim/convert/__init__.py index 7d66413c4..dc821f177 100644 --- a/python/bngsim/convert/__init__.py +++ b/python/bngsim/convert/__init__.py @@ -617,9 +617,10 @@ def sbml_to_bngl( The horizon for the events→actions ``simulate`` phases (the trailing phase runs to ``t_span[1]``; ignored when the model has no events). Each phase names its tolerances (issue #1830): ``rtol=>1e-08``, and - an ``atol`` of ``rtol`` times the smallest value a species BNG2.pl - integrates starts from or an event sets it to, but not under 1e-6 of - the largest, and never above BNG2.pl's own ``1e-08``. BNG2.pl runs a + an ``atol`` of ``rtol`` times the smallest value a species a reaction + or a rate rule changes starts from or an event sets it to, but not + under 1e-6 of the largest, and never above BNG2.pl's own ``1e-08`` + (where those species all start at 0, the ``$``-fixed species' values). BNG2.pl runs a ``simulate`` that names none at ``atol = 1e-08``, above the species of a model in molar units. A model of counts gets ``atol=>1e-08``. diff --git a/python/bngsim/convert/_events.py b/python/bngsim/convert/_events.py index fca191153..95ee341c8 100644 --- a/python/bngsim/convert/_events.py +++ b/python/bngsim/convert/_events.py @@ -1245,25 +1245,44 @@ def _phase_tolerances(model: Model, fires: list[_Fire]) -> dict[str, float]: peak, under a report that listed nothing lost. BNG2.pl takes one ``atol`` for every species, so it is the scalar the - smallest species needs: ``rtol`` of the smallest value a species the solver - integrates starts from or an event sets it to, but not under 1e-6 of the - largest, and never above 1e-8. That is the floor of the default - :meth:`bngsim.Simulator.run` derives per species. A model of counts, whose - species start at 0 or at least 1, keeps 1e-8, as does one with no positive - value to take a scale from. + smallest species needs: ``rtol`` of the smallest value a species a + reaction or a rate rule changes starts from or an event sets it to, but not + under 1e-6 of the largest, and never above 1e-8. That is the floor of the + default :meth:`bngsim.Simulator.run` derives per species. A model of + counts, whose species start at 0 or at least 1, keeps 1e-8. + + A species nothing changes gives no scale. The loader holds a parameter an + event sets as one, so a rate constant of 1e6 beside species at 1e-9 would + put the floor at 1, and a small one would tighten a model of counts. Where + the species that change give no positive value (all start at 0), the + scale is the ``$``-fixed species', as ``Simulator.run``'s is: a stimulus + held at 1e-9 drives species of that size. """ import numpy as np + data = model._core.codegen_data() state = np.abs(np.asarray(model.get_state(), dtype=float)) - fixed = np.asarray(model._core.species_is_fixed, dtype=bool) - values = [float(v) for v in state[~fixed[: len(state)]]] - values += [abs(float(val)) for f in fires for sp, val, _var in f.assigns if not fixed[sp]] - finite = [v for v in values if math.isfinite(v)] - positive = [v for v in finite if v > 0.0] - atol = _BNG_TOLERANCE - if positive: - floor = max(min(positive), _SCALE_SHARE * max(positive)) - atol = min(atol, _BNG_TOLERANCE * floor) + fixed = {i for i, s in enumerate(data["species"]) if s.get("fixed", False)} + changed: set[int] = set() + 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(fixed) + atol = _BNG_TOLERANCE if floor is None else min(_BNG_TOLERANCE, _BNG_TOLERANCE * floor) return {"atol": atol, "rtol": _BNG_TOLERANCE} diff --git a/python/tests/test_sbml_to_bngl_tolerances.py b/python/tests/test_sbml_to_bngl_tolerances.py index 90d4099f0..5a03c288c 100644 --- a/python/tests/test_sbml_to_bngl_tolerances.py +++ b/python/tests/test_sbml_to_bngl_tolerances.py @@ -38,10 +38,18 @@ def _sbml( - species: dict[str, float], sets: dict[str, float], boundary: tuple[str, ...] = () + species: dict[str, float], + sets: dict[str, float], + boundary: tuple[str, ...] = (), + moving: dict[str, float] | None = None, ) -> str: """Each of *species* decaying at k = 0.1, and one event at t = 1 that sets - *sets*. A species in *boundary* is a boundary condition and does not decay.""" + *sets*. A species in *boundary* is a boundary condition and does not decay. + *moving* are parameters that are not constant, which an event may set.""" + moved = "".join( + f'' + for pid, value in (moving or {}).items() + ) listed = "".join( f'' '' f"{listed}" - '' + '' + f"{moved}" f"{decays}" '' f'{_M}{_TIME}1' @@ -153,6 +162,31 @@ def test_species_that_all_start_at_zero_keep_bng2s_own_tolerance(tmp_path): assert _tolerances(report) == (1e-8, 1e-8) +def test_a_parameter_an_event_sets_gives_no_scale(tmp_path): + """The loader holds a parameter an event sets as a species nothing changes. + A rate constant of 1e6 beside species at 1e-9 put the floor, 1e-6 of the + largest, at 1: the phases named ``atol=>1e-08`` and BNG2.pl ran the species + 0.4 to 3.6 times their peak off.""" + xml = _sbml({"A": 1e-9, "B": 2e-9}, {"kon": 2e6}, moving={"kon": 1e6}) + atol, _ = _tolerances(_convert(tmp_path, xml)) + assert atol == pytest.approx(1e-8 * 1e-9, rel=1e-12) + + +def test_a_small_parameter_an_event_sets_leaves_a_model_of_counts_alone(tmp_path): + xml = _sbml({"A": 14.0, "B": 60.0}, {"p": 7e-5}, moving={"p": 4e-5}) + assert _tolerances(_convert(tmp_path, xml)) == (1e-8, 1e-8) + + +@pytest.mark.parametrize(("start", "set_to"), [(1e-9, 0.0), (0.0, 1e-9)]) +def test_species_that_start_at_zero_take_the_scale_of_a_fixed_one(tmp_path, start, set_to): + """A stimulus held at 1e-9, or switched to it by the event, drives species + of that size. They all start at 0, so they give no scale, and at + ``atol=>1e-08`` BNG2.pl ran them a fifth of their peak off.""" + xml = _sbml({"S": start, "A": 0.0, "B": 0.0}, {"S": set_to}, boundary=("S",)) + atol, _ = _tolerances(_convert(tmp_path, xml)) + assert atol == pytest.approx(1e-8 * 1e-9, rel=1e-12) + + def test_the_written_tolerances_read_back(tmp_path): """The reader of a .bngl's actions keeps what the writer wrote.""" report = _convert(tmp_path, _sbml({"A": 3e-9, "B": 7e-8}, {"A": 5e-9})) From 3808dd99a9a7c9122b3bc86aa7903897c7c7fd95 Mon Sep 17 00:00:00 2001 From: Montana Date: Thu, 3 Dec 2026 10:30:57 -0800 Subject: [PATCH 3/5] review (#1830): the tests compare each atol with no absolute slack, 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 --- python/tests/test_sbml_to_bngl_tolerances.py | 42 +++++++++++++++----- 1 file changed, 32 insertions(+), 10 deletions(-) diff --git a/python/tests/test_sbml_to_bngl_tolerances.py b/python/tests/test_sbml_to_bngl_tolerances.py index 5a03c288c..213965519 100644 --- a/python/tests/test_sbml_to_bngl_tolerances.py +++ b/python/tests/test_sbml_to_bngl_tolerances.py @@ -42,10 +42,13 @@ def _sbml( sets: dict[str, float], boundary: tuple[str, ...] = (), moving: dict[str, float] | None = None, + catalyst: str | None = None, ) -> str: """Each of *species* decaying at k = 0.1, and one event at t = 1 that sets *sets*. A species in *boundary* is a boundary condition and does not decay. - *moving* are parameters that are not constant, which an event may set.""" + *moving* are parameters that are not constant, which an event may set. + *catalyst* is a species that does not decay: it is a reactant and a product + of one more reaction, which consumes the first other species.""" moved = "".join( f'' for pid, value in (moving or {}).items() @@ -62,8 +65,19 @@ def _sbml( f"{_M}k{sid}" "" for sid in species - if sid not in boundary + if sid not in boundary and sid != catalyst ) + if catalyst is not None: + first = next(sid for sid in species if sid != catalyst) + decays += ( + '' + f'' + f'' + "" + f'' + f"{_M}k{first}" + f"{catalyst}" + ) assignments = "".join( f'{_M}{value!r}' for sid, value in sets.items() @@ -114,7 +128,7 @@ def test_a_molar_models_phases_name_an_atol_under_its_species(tmp_path): report = _convert(tmp_path, _sbml({"A": 3e-9, "B": 7e-8}, {"A": 5e-9})) atol, rtol = _tolerances(report) assert rtol == 1e-8 - assert atol == pytest.approx(1e-8 * 3e-9, rel=1e-12) + assert atol == pytest.approx(1e-8 * 3e-9, rel=1e-12, abs=0.0) def test_the_tolerances_are_in_the_text_of_every_simulate(tmp_path): @@ -137,7 +151,7 @@ def test_a_value_an_event_sets_gives_the_scale_too(tmp_path): second phase integrates from.""" report = _convert(tmp_path, _sbml({"A": 1e-3, "B": 2e-3}, {"A": 5e-7})) atol, _ = _tolerances(report) - assert atol == pytest.approx(1e-8 * 5e-7, rel=1e-12) + assert atol == pytest.approx(1e-8 * 5e-7, rel=1e-12, abs=0.0) def test_a_species_far_below_the_largest_does_not_set_the_scale(tmp_path): @@ -145,7 +159,7 @@ def test_a_species_far_below_the_largest_does_not_set_the_scale(tmp_path): largest, as the default of Simulator.run does.""" report = _convert(tmp_path, _sbml({"A": 1e-12, "B": 0.5}, {"B": 0.25})) atol, _ = _tolerances(report) - assert atol == pytest.approx(1e-8 * 0.5e-6, rel=1e-12) + assert atol == pytest.approx(1e-8 * 0.5e-6, rel=1e-12, abs=0.0) def test_a_boundary_species_gives_no_scale(tmp_path): @@ -153,7 +167,15 @@ def test_a_boundary_species_gives_no_scale(tmp_path): small or large, is no scale: A at 1e-9 is fixed, B and D are at 1e-3.""" xml = _sbml({"A": 1e-9, "B": 1e-3, "D": 1e-3}, {"B": 2e-3}, boundary=("A",)) atol, _ = _tolerances(_convert(tmp_path, xml)) - assert atol == pytest.approx(1e-8 * 1e-3, rel=1e-12) + assert atol == pytest.approx(1e-8 * 1e-3, rel=1e-12, abs=0.0) + + +def test_a_catalyst_gives_no_scale(tmp_path): + """E is a reactant and a product of its one reaction, so nothing changes + it: at 1e-9 beside species at 1e-3 it does not set the scale.""" + xml = _sbml({"A": 1e-3, "B": 2e-3, "E": 1e-9}, {"A": 2e-3}, catalyst="E") + atol, _ = _tolerances(_convert(tmp_path, xml)) + assert atol == pytest.approx(1e-8 * 1e-3, rel=1e-12, abs=0.0) def test_species_that_all_start_at_zero_keep_bng2s_own_tolerance(tmp_path): @@ -169,7 +191,7 @@ def test_a_parameter_an_event_sets_gives_no_scale(tmp_path): 0.4 to 3.6 times their peak off.""" xml = _sbml({"A": 1e-9, "B": 2e-9}, {"kon": 2e6}, moving={"kon": 1e6}) atol, _ = _tolerances(_convert(tmp_path, xml)) - assert atol == pytest.approx(1e-8 * 1e-9, rel=1e-12) + assert atol == pytest.approx(1e-8 * 1e-9, rel=1e-12, abs=0.0) def test_a_small_parameter_an_event_sets_leaves_a_model_of_counts_alone(tmp_path): @@ -184,7 +206,7 @@ def test_species_that_start_at_zero_take_the_scale_of_a_fixed_one(tmp_path, star ``atol=>1e-08`` BNG2.pl ran them a fifth of their peak off.""" xml = _sbml({"S": start, "A": 0.0, "B": 0.0}, {"S": set_to}, boundary=("S",)) atol, _ = _tolerances(_convert(tmp_path, xml)) - assert atol == pytest.approx(1e-8 * 1e-9, rel=1e-12) + assert atol == pytest.approx(1e-8 * 1e-9, rel=1e-12, abs=0.0) def test_the_written_tolerances_read_back(tmp_path): @@ -197,7 +219,7 @@ def test_the_written_tolerances_read_back(tmp_path): phases = [s for s in read.steps if isinstance(s, Experiment)] assert len(phases) == 2 for phase in phases: - assert float(phase.extra["atol"]) == pytest.approx(3e-17, rel=1e-12) + assert float(phase.extra["atol"]) == pytest.approx(3e-17, rel=1e-12, abs=0.0) assert float(phase.extra["rtol"]) == 1e-8 @@ -212,7 +234,7 @@ def test_the_issues_model_names_a_tolerance_below_its_species(): atol, rtol = _tolerances(report) state = np.asarray(model.get_state())[~np.asarray(model._core.species_is_fixed, dtype=bool)] assert rtol == 1e-8 - assert atol == pytest.approx(1e-8 * 1e-6 * state.max(), rel=1e-12) + assert atol == pytest.approx(1e-8 * 1e-6 * state.max(), rel=1e-12, abs=0.0) assert atol < 1e-8 * 1e-8 From 78c56d12df896f2991b28e9d9da83a6c55cdc687 Mon Sep 17 00:00:00 2001 From: Montana Date: Thu, 3 Dec 2026 10:36:49 -0800 Subject: [PATCH 4/5] review (#1830): species that all start at 0 take their scale from 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 --- python/bngsim/convert/_events.py | 7 ++++--- python/tests/test_sbml_to_bngl_tolerances.py | 8 ++++++++ 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/python/bngsim/convert/_events.py b/python/bngsim/convert/_events.py index 95ee341c8..5c3d22390 100644 --- a/python/bngsim/convert/_events.py +++ b/python/bngsim/convert/_events.py @@ -1255,8 +1255,9 @@ def _phase_tolerances(model: Model, fires: list[_Fire]) -> dict[str, float]: event sets as one, so a rate constant of 1e6 beside species at 1e-9 would put the floor at 1, and a small one would tighten a model of counts. Where the species that change give no positive value (all start at 0), the - scale is the ``$``-fixed species', as ``Simulator.run``'s is: a stimulus - held at 1e-9 drives species of that size. + scale is every species', the ``$``-fixed ones and those parameters too, as + ``Simulator.run``'s is: a stimulus held at 1e-9 drives species of that + size, and nothing else in the model says how large they grow. """ import numpy as np @@ -1281,7 +1282,7 @@ def scale(of: set[int]) -> float | None: floor = scale(changed) if floor is None: - floor = scale(fixed) + 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} diff --git a/python/tests/test_sbml_to_bngl_tolerances.py b/python/tests/test_sbml_to_bngl_tolerances.py index 213965519..5cf6ef7ce 100644 --- a/python/tests/test_sbml_to_bngl_tolerances.py +++ b/python/tests/test_sbml_to_bngl_tolerances.py @@ -209,6 +209,14 @@ def test_species_that_start_at_zero_take_the_scale_of_a_fixed_one(tmp_path, star assert atol == pytest.approx(1e-8 * 1e-9, rel=1e-12, abs=0.0) +def test_species_that_start_at_zero_take_the_scale_of_a_parameter_an_event_sets(tmp_path): + """Nothing else gives one: MODEL7743528808's species all start at 0, and + the parameter its event sets to 0.0025 is what they grow to the size of.""" + xml = _sbml({"A": 0.0, "B": 0.0}, {"p": 2.5e-3}, moving={"p": 0.0}) + atol, _ = _tolerances(_convert(tmp_path, xml)) + assert atol == pytest.approx(1e-8 * 2.5e-3, rel=1e-12, abs=0.0) + + def test_the_written_tolerances_read_back(tmp_path): """The reader of a .bngl's actions keeps what the writer wrote.""" report = _convert(tmp_path, _sbml({"A": 3e-9, "B": 7e-8}, {"A": 5e-9})) From ec0140e9499a308ef3ccb5a92027a8836add9c8e Mon Sep 17 00:00:00 2001 From: Montana Date: Thu, 3 Dec 2026 10:49:17 -0800 Subject: [PATCH 5/5] review (#1830): a test that a held species a reaction consumes gives no scale The one mutant left alive: a fixed species counted among those that change. Signed-off-by: Montana --- python/tests/test_sbml_to_bngl_tolerances.py | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/python/tests/test_sbml_to_bngl_tolerances.py b/python/tests/test_sbml_to_bngl_tolerances.py index 5cf6ef7ce..7225c364b 100644 --- a/python/tests/test_sbml_to_bngl_tolerances.py +++ b/python/tests/test_sbml_to_bngl_tolerances.py @@ -43,12 +43,15 @@ def _sbml( boundary: tuple[str, ...] = (), moving: dict[str, float] | None = None, catalyst: str | None = None, + boundary_reacts: bool = False, ) -> str: """Each of *species* decaying at k = 0.1, and one event at t = 1 that sets *sets*. A species in *boundary* is a boundary condition and does not decay. *moving* are parameters that are not constant, which an event may set. *catalyst* is a species that does not decay: it is a reactant and a product - of one more reaction, which consumes the first other species.""" + of one more reaction, which consumes the first other species. With + *boundary_reacts* a boundary species is its decay's reactant all the same, + and the reaction does not change it.""" moved = "".join( f'' for pid, value in (moving or {}).items() @@ -65,7 +68,7 @@ def _sbml( f"{_M}k{sid}" "" for sid in species - if sid not in boundary and sid != catalyst + if (boundary_reacts or sid not in boundary) and sid != catalyst ) if catalyst is not None: first = next(sid for sid in species if sid != catalyst) @@ -170,6 +173,16 @@ def test_a_boundary_species_gives_no_scale(tmp_path): assert atol == pytest.approx(1e-8 * 1e-3, rel=1e-12, abs=0.0) +def test_a_boundary_species_a_reaction_consumes_gives_no_scale(tmp_path): + """A is the reactant of a reaction and is held all the same: its 1e-9 is + no scale beside species at 1e-3 that move.""" + xml = _sbml( + {"A": 1e-9, "B": 1e-3, "D": 1e-3}, {"B": 2e-3}, boundary=("A",), boundary_reacts=True + ) + atol, _ = _tolerances(_convert(tmp_path, xml)) + assert atol == pytest.approx(1e-8 * 1e-3, rel=1e-12, abs=0.0) + + def test_a_catalyst_gives_no_scale(tmp_path): """E is a reactant and a product of its one reaction, so nothing changes it: at 1e-9 beside species at 1e-3 it does not set the scale."""