Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog.d/1830.fixed.md
Original file line number Diff line number Diff line change
@@ -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=`.
4 changes: 3 additions & 1 deletion docs/user-guide/interchange.md
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
7 changes: 7 additions & 0 deletions python/bngsim/convert/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
-------
Expand Down
72 changes: 68 additions & 4 deletions python/bngsim/convert/_events.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]]] = {}
Expand All @@ -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]:
Expand All @@ -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",
Expand Down
3 changes: 2 additions & 1 deletion python/bngsim/convert/_net_writer.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
Loading
Loading