diff --git a/changelog.d/1830.fixed.md b/changelog.d/1830.fixed.md
new file mode 100644
index 000000000..2c41d0736
--- /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 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/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..dc821f177 100644
--- a/python/bngsim/convert/__init__.py
+++ b/python/bngsim/convert/__init__.py
@@ -616,6 +616,13 @@ 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 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``.
Returns
-------
diff --git a/python/bngsim/convert/_events.py b/python/bngsim/convert/_events.py
index 4d3610aa2..5c3d22390 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,77 @@ 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 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 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
+
+ data = model._core.codegen_data()
+ state = np.abs(np.asarray(model.get_state(), dtype=float))
+ 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(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}
+
+
+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..7225c364b
--- /dev/null
+++ b/python/tests/test_sbml_to_bngl_tolerances.py
@@ -0,0 +1,329 @@
+"""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 = '"
+ for sid in species
+ 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)
+ decays += (
+ ''
+ f''
+ f''
+ ""
+ f''
+ f"{_M}k{first}"
+ f"{catalyst}"
+ )
+ assignments = "".join(
+ f'{_M}{value!r}'
+ for sid, value in sets.items()
+ )
+ return (
+ '\n'
+ ''
+ ''
+ ''
+ f"{listed}"
+ ''
+ f"{moved}"
+ 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, abs=0.0)
+
+
+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, abs=0.0)
+
+
+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, abs=0.0)
+
+
+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, 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."""
+ 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):
+ """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_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, abs=0.0)
+
+
+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, 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}))
+ 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, abs=0.0)
+ 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, abs=0.0)
+ 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 == {}