From 0e82f44ea806882c2b777df16cbcfbd236d4d332 Mon Sep 17 00:00:00 2001 From: Bill Hlavacek Date: Thu, 3 Dec 2026 15:48:39 -0700 Subject: [PATCH 01/11] wip: ask expression stop conditions during an ODE run (#2018) --- include/bngsim/model.hpp | 5 + include/bngsim/types.hpp | 49 ++++ python/bngsim/_simulator.py | 127 +++++++--- python/bngsim/_stop_in_run.py | 226 +++++++++++++++++ src/_bngsim_core.cpp | 100 ++++++++ src/cvode_simulator.cpp | 445 ++++++++++++++++++++++++++++++++-- src/model.cpp | 8 +- 7 files changed, 910 insertions(+), 50 deletions(-) create mode 100644 python/bngsim/_stop_in_run.py diff --git a/include/bngsim/model.hpp b/include/bngsim/model.hpp index ddab0ea7c..bd1b048d1 100644 --- a/include/bngsim/model.hpp +++ b/include/bngsim/model.hpp @@ -852,6 +852,11 @@ class NetworkModel { // conc is 0-based n_species array. void update_observables(const double *conc); + // Observable `oi`'s (0-based) total at species concentrations `conc`, as + // update_observables() would set it, without setting it: what a stop + // condition's root reads at the times CVODE asks (issue #2018). + double observable_total(size_t oi, const double *conc) const; + // Evaluate all functions (updates variable parameters). The right-hand // side, the event roots and the analytic Jacobian's refresh pass // with_deferred = false: a deferred function is read only by event diff --git a/include/bngsim/types.hpp b/include/bngsim/types.hpp index 11c207875..3af5984d7 100644 --- a/include/bngsim/types.hpp +++ b/include/bngsim/types.hpp @@ -1887,6 +1887,47 @@ struct CrossingStop { bool restart = true; }; +// ─── Stop conditions asked during the run (issue #2018) ────────────────────── +// Asked after each row a run records, with the row's index in the run's grid, +// its time, the state the row holds (every state entry, in the model's order) +// and its observables; true ends the run there, with that row its last. At a +// root of a StopRoot, `at_root` is true, the state and observables are those +// at the root, and the row is the one the run was integrating toward; true +// then makes the root's time that row's, and the run ends there. A condition +// used to be read off the whole result after the run, so a run that failed +// after the condition was met failed, and a long span was paid for in full. +using StopCheck = std::function; + +// One instruction of a StopRoot's program, a stack machine over the run's +// state: a number, an observable, a state entry or the time pushed, or the two +// (one, for Neg) on top replaced by what the operation gives. +struct StopRootOp { + enum Kind : int { + Const = 0, + Observable = 1, // index: the observable's 0-based index + Species = 2, // index: the state entry's 0-based index + Time = 3, + Add = 4, + Sub = 5, + Mul = 6, + Div = 7, + Pow = 8, + Neg = 9, + }; + int kind = Const; + int index = 0; + double value = 0.0; +}; + +// g(t, x) for a stop condition `lhs > rhs` (or <, >=, <=, or a number read as +// met where it is > 0): lhs - rhs, whose sign changes where the condition +// turns. The ODE run finds it as a root, as it finds an event's trigger, and +// asks StopCheck at it; the condition decides, the root only says where. +struct StopRoot { + std::vector program; +}; + // ─── Solver options ────────────────────────────────────────────────────────── struct SolverOptions { double rtol = 1e-8; // relative tolerance @@ -2087,6 +2128,14 @@ struct SolverOptions { // suite / any fit reproducible out of the box; callers that want an // independent random realization pass their own seed. uint64_t event_seed = 0x9E3779B97F4A7C15ULL; + + // Stop conditions asked during the run (issue #2018; see StopCheck). Empty + // and unset by default, which leaves a run as it was. + StopCheck stop_check; + std::vector stop_roots; + // What a run moved onto its own clock (a far run, issue #1681) adds back + // to its time, in this order, where a stop root reads the time. + std::vector stop_time_origins; }; // ─── Time specification ────────────────────────────────────────────────────── diff --git a/python/bngsim/_simulator.py b/python/bngsim/_simulator.py index 2994c25c2..a559bc493 100644 --- a/python/bngsim/_simulator.py +++ b/python/bngsim/_simulator.py @@ -6688,6 +6688,10 @@ def run( ) core_result = None + # The rows the run walks, and whether the engine was given stop + # conditions to ask as it goes (issue #2018). + n_rows = n_grid if sample_times is not None else n_points + stops_given = False # The ∂x(0)/∂θ rows this run seeds, captured where they are built and # stamped onto the Result (issue #155). None ⇒ no parameter-sensitivity # request, so there is no `parameter` axis to describe. @@ -6806,6 +6810,8 @@ def _jax_callback(t, y_arr): opts.set_jax_jac_fn(_jax_callback) + # Issue #2018: the stop conditions the run can ask as it goes. + stops_given = self._give_stops(opts, self._model, n_rows, lead, trail) core_result = self._run_ode_with_jacobian_fallback(times, opts) run_jacobian = self._jacobian_used(opts, self._model._core) elif self._method == "ssa": @@ -6883,6 +6889,7 @@ def _jax_callback(t, y_arr): # writer) holds the same rows. Where the solve left off is read first: # t_span[1], or the row a steady-state stop ended on. left_off: float | None = None + ended = stops_given and _ended_on_a_stop(core_result, n_rows) if lead or trail: left_off = float(core_result.time[-1]) drop_added_rows(core_result, n_grid, lead, trail) @@ -6968,7 +6975,7 @@ def _jax_callback(t, y_arr): # Check stop conditions on the result if self._stop_conditions: - self._check_stop_conditions(result) + self._check_stop_conditions(result, ended=ended) logger.info( "Simulation complete: %d steps, %d RHS evals", @@ -7497,9 +7504,13 @@ def _run_one_here(i: int) -> Result: self._warn_atol_above_scale(results, "ODE batch", per_result=row_atols) # Each row meets the stop conditions as run() does, and one that meets - # one comes back cut there, beside the rest (issue #1369). + # one comes back cut there, beside the rest (issue #1369); an ODE row + # ends there too (issue #2018). if self._stop_conditions: - results = [self._stopped(r) for r in results] + results = [ + self._stopped(r, ended=self._method == "ode" and _ended_on_a_stop(r, n_points)) + for r in results + ] # Each row is stamped already, against its own clone (issues #698, #743). if squeeze: @@ -9150,6 +9161,8 @@ def _run_single_batch( self._apply_state_switch_sens(opts, clone._core, clone, covered, t_span[0]) else: self._apply_state_switch_roots(opts, clone, covered) + # Issue #2018: the row's stop conditions, asked as it goes. + self._give_stops(opts, clone, n_points, 0, 0) # The GH #176 retry, as run() places it. Without it a row raised # where the same run() fell back to FD and returned, which breaks # the GH #203 contract above; issue #867 made a closed form still @@ -12762,32 +12775,51 @@ def _warn_ssa_boundary(result: Result) -> None: stacklevel=3, ) - def _stopped(self, result: Result) -> Result: - """*result* cut at the first registered stop condition it meets, in - the order they were added, with :attr:`Result.stop_condition` naming - it; *result* itself where none is met. One rule for :meth:`run`, which - raises with the cut result, and for the rows of :meth:`run_batch` and - :meth:`run_replicates`, which keep it (issue #1369).""" + def _stopped(self, result: Result, *, ended: bool = False) -> Result: + """*result* cut at the first sample a registered stop condition holds + at, with :attr:`Result.stop_condition` naming it, the one added first + where several hold there; *result* itself where none is met. One rule + for :meth:`run`, which raises with the cut result, and for the rows of + :meth:`run_batch` and :meth:`run_replicates`, which keep it (issue + #1369). A callable is met at the last sample, and is called only where + no condition added before it is met. + + *ended* says the engine ended the run on a stop condition (issue + #2018), at the last sample *result* holds: one is met at a sample, or + the engine and this check read different values, a bug.""" + first: int | None = None + met = None for sc in self._stop_conditions: - trigger_idx = sc.check(result) + trigger_idx = sc.check(result, before=first) if trigger_idx is not None: - trunc = self._truncate_result(result, trigger_idx + 1) - trunc._stop_condition = sc.label or str(sc) - logger.info( - "Stop condition triggered at t=%.6g: %s", - result.time[trigger_idx], - trunc._stop_condition, + first, met = trigger_idx, sc + if met is None: + if ended: + raise BngsimError( + "The run ended on a stop condition at t=" + f"{float(result.time[-1]):.17g}, and none holds at any sample its " + "result reports. This is a bug in bngsim (issue #2018): please " + "report it, with the model and the condition." ) - return trunc - return result + return result + assert first is not None + trunc = self._truncate_result(result, first + 1) + trunc._stop_condition = met.label or str(met) + logger.info( + "Stop condition triggered at t=%.6g: %s", + result.time[first], + trunc._stop_condition, + ) + return trunc - def _check_stop_conditions(self, result: Result) -> None: + def _check_stop_conditions(self, result: Result, *, ended: bool = False) -> None: """Check stop conditions against a completed result. If any condition triggers, raises StopConditionMet with - the result truncated to the trigger point. + the result truncated to the trigger point. *ended* as for + :meth:`_stopped`. """ - stopped = self._stopped(result) + stopped = self._stopped(result, ended=ended) if stopped is not result: label = str(stopped._stop_condition) raise StopConditionMet( @@ -12796,6 +12828,25 @@ def _check_stop_conditions(self, result: Result) -> None: condition=label, ) + def _give_stops(self, opts: Any, model: Model, n_rows: int, lead: int, trail: int) -> bool: + """Hand an ODE run's options the stop conditions the engine can ask + as it goes, at the rows ``lead <= row < n_rows - trail`` the result + reports (issue #2018). True where any was given.""" + if not self._stop_conditions: + return False + from bngsim._stop_in_run import in_run_stops + + got = in_run_stops( + self._stop_conditions, model, first=lead, end=n_rows - trail, roots=True + ) + if got is None: + return False + check, species_cols, obs_cols, roots = got + opts.set_stop_check(check, species_cols, obs_cols) + if roots: + opts.set_stop_roots(roots) + return True + def _refuse_squeeze_with_stop_conditions(self, where: str, squeeze: bool) -> None: """Refuse ``squeeze=True`` on a batch while a stop condition is registered. @@ -13971,6 +14022,18 @@ def _refuse_stop_expression_shape(expression: str, tree: ast.Expression) -> None ) +def _ended_on_a_stop(result: Any, n_rows: int) -> bool: + """Whether the engine ended a run of *n_rows* rows on a stop condition + (issue #2018), from its result (a core result or a :class:`Result`): it + holds fewer, and no steady state ended it, the only other early end.""" + stats = result.solver_stats + if isinstance(stats, dict): + reached = bool(stats.get("steady_state_reached", 0)) + else: + reached = bool(getattr(stats, "steady_state_reached", False)) + return len(result.time) < n_rows and not reached + + def _stop_value_met(value: Any, expression: str, time: np.ndarray, t_idx: int) -> bool: """Whether a stop-condition expression's *value* at sample *t_idx* meets it: a truth value as itself, a real number where it is > 0 (so NaN never does), as @@ -14066,8 +14129,9 @@ class _StopCondition: def __init__(self, label: str = "") -> None: self.label = label - def check(self, result: Result) -> int | None: - """Check condition. Returns time index or None.""" + def check(self, result: Result, before: int | None = None) -> int | None: + """Check condition. Returns time index or None; with *before*, an + index before it or None.""" raise NotImplementedError def record_name(self) -> str: @@ -14095,8 +14159,10 @@ def __init__( self._expression = expression tree = ast.parse(expression, "", mode="eval") _refuse_stop_expression_shape(expression, tree) + self._tree = tree self._code = compile(tree, "", "eval") loads, binds = _expression_names(tree) + self._binds: frozenset[str] = binds # The names the expression loads. Only these are bound at each sample: # binding every observable and species there, for a condition that # reads one, was paid once per row of a batch (issue #1369). One the @@ -14107,8 +14173,9 @@ def __init__( if unknown: raise UsageError(_unreadable_stop_names_message(expression, unknown, names)) - def check(self, result: Result) -> int | None: - """Evaluate expression at each time point.""" + def check(self, result: Result, before: int | None = None) -> int | None: + """Evaluate expression at each time point, or at each before *before*: + the first index it holds at.""" obs_data = np.asarray(result.observables) sp_data = result.species time = result.time @@ -14130,7 +14197,7 @@ def check(self, result: Result) -> int | None: errors = _StopArithmeticErrors() met = None with errors.errstate(): - for t_idx in range(len(time)): + for t_idx in range(len(time) if before is None else min(before, len(time))): # The globals, so a lambda or comprehension inside the expression # sees them too: as locals, only its outermost scope did (#1509). ns = {"__builtins__": {}, "time": time[t_idx], "t": time[t_idx]} @@ -14186,14 +14253,18 @@ def record_name(self) -> str: name = getattr(self._func, "__qualname__", None) or type(self._func).__qualname__ return f"callable {name}" - def check(self, result: Result) -> int | None: + def check(self, result: Result, before: int | None = None) -> int | None: """Call the function; if it returns a true value, the last time index. + Not called where *before* leaves the last index out. An exception the callable raises propagates: swallowing it read as "not met" for a condition that was never evaluated (issue #1509). """ + last = len(result.time) - 1 + if before is not None and before <= last: + return None if self._func(result): - return len(result.time) - 1 + return last return None diff --git a/python/bngsim/_stop_in_run.py b/python/bngsim/_stop_in_run.py new file mode 100644 index 000000000..c538bc8f7 --- /dev/null +++ b/python/bngsim/_stop_in_run.py @@ -0,0 +1,226 @@ +"""Stop conditions asked during an ODE run, at the rows it records and at their +crossings (issue #2018). + +A stop condition used to be asked of the result once the run had gone to its +end time, so a run that failed after the condition held failed, and a long +span was paid for in full. Here an expression condition is asked by the engine +at each row it records, and the run ends at the first row one holds at. One of +the form ``lhs > rhs`` (or ``>=``, ``<``, ``<=``), or a number that is met where +it is > 0, over the observables, the species, the time and arithmetic, is also +a root function for CVODE: where it changes sign the condition is asked again, +and met there, the run ends with a row at that time. + +What the engine asks is a stop. What the result says stopped it is decided +after the run, by :meth:`Simulator._stopped`, from the rows the result reports, +as it always was; this is where the run ends, not what it returns. A condition +is asked here only where the values it reads at a row are the ones the result +reports there: a species whose reported column is remapped after the solve (an +assignment-rule target, a species in a compartment whose size moves) is not, +and a condition that reads one is asked of the result alone. +""" + +from __future__ import annotations + +import ast +from collections.abc import Sequence +from typing import TYPE_CHECKING, Any + +import numpy as np + +if TYPE_CHECKING: + from bngsim._model import Model + +# The operations of a stop root's program, as include/bngsim/types.hpp +# StopRootOp::Kind numbers them. +_CONST, _OBSERVABLE, _SPECIES, _TIME, _ADD, _SUB, _MUL, _DIV, _POW, _NEG = range(10) + +_BINARY = {ast.Add: _ADD, ast.Sub: _SUB, ast.Mult: _MUL, ast.Div: _DIV, ast.Pow: _POW} +_ORDERS = (ast.Lt, ast.LtE, ast.Gt, ast.GtE) + +# The report maps whose species are reported at something other than the +# state entry the run holds (Simulator._stamp), or whose amount is read +# through one; a condition reading one of these species is not asked during +# the run. Each is keyed by the species' name. +_REMAPPING_MAPS = ( + "_ar_report_map", + "_varvol_conc_map", + "_varvol_amount_map", + "_varvol_ar_conc_map", + "_varvol_ar_amount_map", + "_varvol_target_amount_map", + "_varvol_event_resize_map", +) + + +def remapped_species(model: Model) -> frozenset[str]: + """The species of *model* whose reported column a run's report remaps.""" + names: set[str] = set() + for attr in _REMAPPING_MAPS: + names.update(getattr(model, attr, None) or ()) + return frozenset(names) + + +def _program(node: ast.AST, columns: dict[str, tuple[int, int]], out: list) -> bool: + """Append *node*'s value as stack operations to *out*; False where it is + not arithmetic over the columns and real constants.""" + if isinstance(node, ast.Constant): + if isinstance(node.value, bool) or not isinstance(node.value, (int, float)): + return False + out.append((_CONST, 0, float(node.value))) + return True + if isinstance(node, ast.Name): + column = columns.get(node.id) + if column is None: + return False + out.append((column[0], column[1], 0.0)) + return True + if isinstance(node, ast.UnaryOp) and isinstance(node.op, (ast.USub, ast.UAdd)): + if not _program(node.operand, columns, out): + return False + if isinstance(node.op, ast.USub): + out.append((_NEG, 0, 0.0)) + return True + if isinstance(node, ast.BinOp) and type(node.op) in _BINARY: + if not (_program(node.left, columns, out) and _program(node.right, columns, out)): + return False + out.append((_BINARY[type(node.op)], 0, 0.0)) + return True + return False + + +def root_program(tree: ast.Expression, columns: dict[str, tuple[int, int]]) -> list | None: + """The program for g, a function that changes sign where the condition + *tree* starts to hold: ``lhs - rhs`` for ``lhs OP rhs`` with OP one of + ``<``, ``<=``, ``>``, ``>=``, and the value itself for one that is a number. + None where the condition is neither, or reads something other than + *columns* (name -> (operation, index)) and real constants. A root of g is + only where to ask: the condition decides there.""" + body = tree.body + out: list = [] + if isinstance(body, ast.Compare): + if len(body.ops) != 1 or not isinstance(body.ops[0], _ORDERS): + return None + if not (_program(body.left, columns, out) and _program(body.comparators[0], columns, out)): + return None + out.append((_SUB, 0, 0.0)) + return out + return out if _program(body, columns, out) else None + + +class InRunStops: + """The engine's stop check: whether any of the conditions holds at a row. + + *conditions* are ``(code, observable reads, species reads)``: each read a + ``(name, position)`` in the observable or state values the engine hands + over, as :meth:`_ExpressionStopCondition.check` binds them at a sample. The + rows asked are ``first <= row < end``, those a result reports; a root + stands in for its row and is asked only where the row before it is one of + them too. + + An error a condition meets here is not raised: the condition is read as + not met at that row, and the result's own check, which reads the same row, + raises it as it always has. An interrupt is raised. + """ + + def __init__( + self, + conditions: Sequence[tuple[Any, Sequence[tuple[str, int]], Sequence[tuple[str, int]]]], + first: int, + end: int, + ) -> None: + self._conditions = list(conditions) + self._first = first + self._end = end + + def __call__( + self, row: int, t: float, state: np.ndarray, observables: np.ndarray, at_root: bool + ) -> bool: + if not (self._first <= row < self._end) or (at_root and row - 1 < self._first): + return False + tv = np.float64(t) + with np.errstate(all="ignore"): + for code, obs_reads, species_reads in self._conditions: + ns: dict[str, Any] = {"__builtins__": {}, "time": tv, "t": tv} + for name, k in obs_reads: + ns[name] = observables[k] + for name, k in species_reads: + ns[name] = state[k] + try: + val = eval(code, ns) # noqa: S307 + except Exception: + continue + if isinstance(val, (bool, np.bool_)): + if val: + return True + elif isinstance(val, (int, float, np.integer, np.floating)) and val > 0: + return True + return False + + +def in_run_stops( + conditions: Sequence[Any], + model: Model, + *, + first: int, + end: int, + roots: bool, +) -> tuple[InRunStops, list[int], list[int], list[list]] | None: + """The stop check for a run of *model* reporting rows ``first <= row < + end``, the state and observable columns it reads, and the stop roots + (none unless *roots*); None where no condition can be asked during it. + + *conditions* are the Simulator's, in the order added; the expression + conditions whose every name is a column the result reports, the time, or + one the expression binds itself, are asked.""" + from bngsim._simulator import _ExpressionStopCondition, _species_identifier + + core = model._core + raw_species = list(core.species_names) + raw_obs = list(core.observable_names) + remapped = remapped_species(model) + # What a sample binds, in the order check() binds it: the time, then the + # observables, then the species, so that a later one shadows an earlier. + readable: dict[str, tuple[str, int]] = {"t": ("time", 0), "time": ("time", 0)} + for j in core.public_observable_indices: + readable[raw_obs[j]] = ("observable", j) + for i in core.reported_species_indices: + name = raw_species[i] + readable[_species_identifier(name)] = ( + ("remapped", i) if name in remapped else ("species", i) + ) + + species_cols: list[int] = [] + obs_cols: list[int] = [] + asked: list = [] + programs: list[list] = [] + for sc in conditions: + if not isinstance(sc, _ExpressionStopCondition): + continue + reads = {name: readable[name] for name in sc._names if name in readable} + free = sc._names - sc._binds + if any(name not in reads for name in free) or any( + kind == "remapped" for kind, _ in reads.values() + ): + continue + obs_reads: list[tuple[str, int]] = [] + species_reads: list[tuple[str, int]] = [] + columns: dict[str, tuple[int, int]] = {} + for name, (kind, j) in reads.items(): + if kind == "observable": + obs_reads.append((name, len(obs_cols))) + obs_cols.append(j) + columns[name] = (_OBSERVABLE, j) + elif kind == "species": + species_reads.append((name, len(species_cols))) + species_cols.append(j) + columns[name] = (_SPECIES, j) + else: + columns[name] = (_TIME, 0) + asked.append((sc._code, obs_reads, species_reads)) + if roots and not (sc._names & sc._binds): + program = root_program(sc._tree, columns) + if program is not None: + programs.append(program) + if not asked: + return None + return InRunStops(asked, first, end), species_cols, obs_cols, programs diff --git a/src/_bngsim_core.cpp b/src/_bngsim_core.cpp index 67fb2593e..768423cc1 100644 --- a/src/_bngsim_core.cpp +++ b/src/_bngsim_core.cpp @@ -880,6 +880,67 @@ struct CNumericLocaleBlock { }; } // namespace +// Issue #2018: a Python stop check as the engines call it. Python is given +// the row, its time, the state entries and observables at the columns named +// (each a copy, as a numpy array), and whether the row is a stop root's, and +// returns whether a condition is met there. The callable is held through a +// shared pointer whose last owner takes the GIL to drop it, so the options +// can be copied by a run with the GIL released. +static bngsim::StopCheck make_stop_check(py::object fn, std::vector species_cols, + std::vector obs_cols) { + if (fn.is_none()) { + return nullptr; + } + std::shared_ptr held(new py::object(std::move(fn)), [](py::object *p) { + py::gil_scoped_acquire acquire; + delete p; + }); + return [held, species_cols = std::move(species_cols), obs_cols = std::move(obs_cols)]( + int row, double t, const double *x, int n_x, const double *obs, int n_obs, + bool at_root) -> bool { + const auto pick = [](const std::vector &cols, const double *from, int n, + const char *what) { + py::array_t out(static_cast(cols.size())); + double *o = out.mutable_data(); + for (std::size_t k = 0; k < cols.size(); ++k) { + const int j = cols[k]; + if (j < 0 || j >= n) { + throw std::out_of_range(std::string("stop check: ") + what + " column " + + std::to_string(j) + " is outside the run's " + + std::to_string(n) + " (issue #2018)"); + } + o[k] = from[j]; + } + return out; + }; + py::gil_scoped_acquire acquire; + py::array_t xs = pick(species_cols, x, n_x, "state"); + py::array_t os = pick(obs_cols, obs, n_obs, "observable"); + return (*held)(row, t, xs, os, at_root).cast(); + }; +} + +// Issue #2018: stop roots as Python hands them, one list of (kind, index, +// value) operations per root (bngsim._stop_roots). +static std::vector +stop_roots_from(const std::vector>> &roots) { + std::vector out; + out.reserve(roots.size()); + for (const auto &program : roots) { + bngsim::StopRoot root; + root.program.reserve(program.size()); + for (const auto &[kind, index, value] : program) { + bngsim::StopRootOp op; + op.kind = kind; + op.index = index; + op.value = value; + root.program.push_back(op); + } + out.push_back(std::move(root)); + } + return out; +} + PYBIND11_MODULE(_bngsim_core, m) { m.doc() = "bngsim C++ engine bindings (low-level)"; @@ -1080,6 +1141,27 @@ PYBIND11_MODULE(_bngsim_core, m) { .def_readwrite("steady_state_tol", &bngsim::SolverOptions::steady_state_tol) .def_readwrite("carry_sensitivities", &bngsim::SolverOptions::carry_sensitivities) .def_readwrite("event_seed", &bngsim::SolverOptions::event_seed) + .def( + "set_stop_check", + [](bngsim::SolverOptions &self, py::object fn, std::vector species_columns, + std::vector observable_columns) { + self.stop_check = make_stop_check(std::move(fn), std::move(species_columns), + std::move(observable_columns)); + }, + py::arg("fn"), py::arg("species_columns"), py::arg("observable_columns"), + "Issue #2018: fn(row, t, state, observables, at_root) -> bool, asked at each row " + "the run records, and at each stop root, with copies of the state entries and " + "observables at the columns named. True ends the run on that row. None clears it.") + .def( + "set_stop_roots", + [](bngsim::SolverOptions &self, + const std::vector>> &roots) { + self.stop_roots = stop_roots_from(roots); + }, + py::arg("roots"), + "Issue #2018: the stop conditions' root functions, each a list of (kind, index, " + "value) operations on a stack (bngsim._stop_roots); CVODE finds where each " + "changes sign, and the stop check decides there. Needs a stop check.") .def( "set_crossing_stops", [](bngsim::SolverOptions &self, @@ -3243,6 +3325,24 @@ PYBIND11_MODULE(_bngsim_core, m) { // Named lists .def_property_readonly("species_names", &bngsim::NetworkModel::species_names) .def_property_readonly("observable_names", &bngsim::NetworkModel::observable_names) + // Issue #2018: the state entries a result reports as species, and the + // observables it reports, in order, as ResultCore projects them. + .def_property_readonly("reported_species_indices", + [](const bngsim::NetworkModel &self) { + std::vector keep = self.reported_species_indices(); + if (keep.empty()) { + keep.resize(static_cast(self.n_species())); + for (std::size_t i = 0; i < keep.size(); ++i) { + keep[i] = i; + } + } + return keep; + }) + .def_property_readonly("public_observable_indices", + [](const bngsim::NetworkModel &self) { + return bngsim::public_observable_indices( + self.observable_names()); + }) // Issue #74 — 0-based indices of the write-only accumulator species: a // product of some reaction, a reactant of none, read by no other diff --git a/src/cvode_simulator.cpp b/src/cvode_simulator.cpp index 973a46171..cc728031e 100644 --- a/src/cvode_simulator.cpp +++ b/src/cvode_simulator.cpp @@ -1083,6 +1083,14 @@ struct CvodeUserData { bool any_put_below = false; double put_below_tn = std::numeric_limits::quiet_NaN(); double put_below_h = std::numeric_limits::quiet_NaN(); + // Issue #2018: the run's stop roots, after the model's own n_model_roots + // roots in CVODE's root vector (cvode_run_root_fn), the times a far run's + // clock adds back (SolverOptions::stop_time_origins), and the stack their + // programs are evaluated on. Null where the run has none. + const std::vector *stop_roots = nullptr; + const std::vector *stop_time_origins = nullptr; + std::vector *stop_stack = nullptr; + int n_model_roots = 0; }; // CVODE's error-weight callback for the tracking absolute tolerance (issue @@ -3762,6 +3770,148 @@ static int cvode_event_root_fn(sunrealtype t, N_Vector y, sunrealtype *gout, voi [&] { return cvode_event_root_fn_body(t, y, gout, user_data); }); } +// ─── Stop conditions' roots (issue #2018) ──────────────────────────────────── +// +// A stop root is a program for g(t, x) = lhs - rhs of a stop condition (see +// StopRoot), run on a stack. It reads an observable as the row's refresh sums +// it (NetworkModel::observable_total), a state entry as it stands, and the +// time on the clock the condition is written in. +static double stop_root_value(const StopRoot &root, double t, const double *x, + const NetworkModel &model, const std::vector *origins, + std::vector &stack) { + stack.clear(); + for (const StopRootOp &op : root.program) { + switch (op.kind) { + case StopRootOp::Const: + stack.push_back(op.value); + break; + case StopRootOp::Observable: + stack.push_back(model.observable_total(static_cast(op.index), x)); + break; + case StopRootOp::Species: + stack.push_back(x[op.index]); + break; + case StopRootOp::Time: { + double clock = t; + if (origins != nullptr) { + for (double o : *origins) { + clock += o; + } + } + stack.push_back(clock); + break; + } + case StopRootOp::Neg: + stack.back() = -stack.back(); + break; + default: { + const double b = stack.back(); + stack.pop_back(); + double &a = stack.back(); + switch (op.kind) { + case StopRootOp::Add: + a = a + b; + break; + case StopRootOp::Sub: + a = a - b; + break; + case StopRootOp::Mul: + a = a * b; + break; + case StopRootOp::Div: + a = a / b; + break; + default: // StopRootOp::Pow; validate_stop_roots admits nothing else + a = std::pow(a, b); + break; + } + break; + } + } + } + return stack.back(); +} + +// Refuse a stop root whose program would read outside the run's state or +// observables, or leave its stack other than one deep, before CVODE is given +// it. Python compiles them (bngsim._stop_roots), so a refusal here is a bug +// there. +static void validate_stop_roots(const SolverOptions &opts, int n_state, int n_obs) { + if (!opts.stop_roots.empty() && !opts.stop_check) { + throw std::invalid_argument("SolverOptions: stop roots were given without a stop check, " + "which decides at each of them (issue #2018)"); + } + for (std::size_t r = 0; r < opts.stop_roots.size(); ++r) { + long depth = 0; + for (const StopRootOp &op : opts.stop_roots[r].program) { + const bool push = op.kind == StopRootOp::Const || op.kind == StopRootOp::Observable || + op.kind == StopRootOp::Species || op.kind == StopRootOp::Time; + const bool binary = op.kind >= StopRootOp::Add && op.kind <= StopRootOp::Pow; + const bool ok_index = + (op.kind != StopRootOp::Observable || (op.index >= 0 && op.index < n_obs)) && + (op.kind != StopRootOp::Species || (op.index >= 0 && op.index < n_state)); + if ((!push && !binary && op.kind != StopRootOp::Neg) || !ok_index || + (binary && depth < 2) || (op.kind == StopRootOp::Neg && depth < 1)) { + throw std::invalid_argument("SolverOptions: stop root " + std::to_string(r) + + " is not a program over this model's state " + "(issue #2018)"); + } + depth += push ? 1 : (binary ? -1 : 0); + } + if (depth != 1) { + throw std::invalid_argument("SolverOptions: stop root " + std::to_string(r) + + " does not leave one value (issue #2018)"); + } + } +} + +// CVODE's root function on a run with stop roots: the model's own roots +// first, as cvode_event_root_fn gives them, then each stop root's g. +static int cvode_run_root_fn_body(sunrealtype t, N_Vector y, sunrealtype *gout, void *user_data) { + auto *data = static_cast(user_data); + const int off = data->n_model_roots; + if (off > 0) { + const int flag = cvode_event_root_fn_body(t, y, gout, user_data); + if (flag != 0) { + return flag; + } + } + const double *x = N_VGetArrayPointer(y); + const std::vector &roots = *data->stop_roots; + for (std::size_t j = 0; j < roots.size(); ++j) { + gout[static_cast(off) + j] = + stop_root_value(roots[j], static_cast(t), x, *data->model, + data->stop_time_origins, *data->stop_stack); + } + return 0; +} + +static int cvode_run_root_fn(sunrealtype t, N_Vector y, sunrealtype *gout, void *user_data) { + return guard_cvode_callback(user_data, + [&] { return cvode_run_root_fn_body(t, y, gout, user_data); }); +} + +// Where a stop condition not met at its root is asked again (issue #2018). A +// root CVODE finds on the boundary itself, g exactly 0, as it does for a +// condition linear in the time (`t > 5`, a species made at a constant rate), +// is where a strict one (`>`, `<`) is not yet met, and CVODE reports no root +// as g leaves 0. It is asked a few roundings past the root, inside the step +// CVODE has taken and before the next output, which asks it in any case; +// NaN where there is no such time. +static double stop_root_past(void *cvode_mem, double t_root, double t_next_out) { + sunrealtype tn = 0.0; + sunrealtype h = 0.0; + CVodeGetCurrentTime(cvode_mem, &tn); + CVodeGetLastStep(cvode_mem, &h); + const double t_past = + t_root + 16.0 * std::numeric_limits::epsilon() * + (std::fabs(t_root) + std::fabs(static_cast(h))); + if (t_past > t_root && t_past <= static_cast(tn) && t_past < t_next_out) { + return t_past; + } + return std::numeric_limits::quiet_NaN(); +} + // ─── Forward-sensitivity run state ─────────────────────────────────────────── // // Everything Impl::setup_forward_sensitivities() resolves for one run(): the @@ -4600,7 +4750,8 @@ struct CvodeSimulator::Impl { // Attach cvode_event_root_fn as CVODE's root function, and silence the // benign tiny-step warning a discontinuity root provokes. - void register_roots(void *cvode_mem, SUNContext ctx, int n_roots, int n_restart_roots); + void register_roots(void *cvode_mem, SUNContext ctx, int n_roots, int n_restart_roots, + int n_stop_roots = 0); // Size the Result and its (optional) sensitivity blocks, and name every axis. void allocate_run_result(Result &result, const SolverOptions &opts, int n_out, int n_sens_p, @@ -6198,6 +6349,47 @@ Result CvodeSimulator::Impl::run_warm(const TimeSpec ×, const SolverOptions } } + // Issue #2018: stop conditions, asked at each row recorded, and their + // roots, registered on this run alone and taken off again before the + // memory is kept warm, so that the next run has none. A root does not move + // a step: a run whose condition is never met takes the steps it took + // without one. + validate_stop_roots(opts, ns, n_obs); + const int n_stop_roots = static_cast(opts.stop_roots.size()); + std::vector stop_stack; + std::vector stop_state(static_cast(ns)); + bool stop_met = false; + struct StopRootsOff { + CvodeUserData &data; + void *mem; + bool on = false; + ~StopRootsOff() { + if (on) { + CVodeRootInit(mem, 0, nullptr); + } + data.stop_roots = nullptr; + data.stop_time_origins = nullptr; + data.stop_stack = nullptr; + } + } stop_roots_off{w.user_data, cvode_mem}; + if (n_stop_roots > 0) { + w.user_data.stop_roots = &opts.stop_roots; + w.user_data.stop_time_origins = &opts.stop_time_origins; + w.user_data.stop_stack = &stop_stack; + w.user_data.n_model_roots = 0; + stop_roots_off.on = true; + int rf = CVodeRootInit(cvode_mem, n_stop_roots, cvode_run_root_fn); + if (rf != CV_SUCCESS) { + throw std::runtime_error("CVodeRootInit for the stop conditions failed: " + + std::to_string(rf)); + } + CVodeSetNoInactiveRootWarn(cvode_mem); + } + if (opts.stop_check && + opts.stop_check(0, times.t_start, y_data, ns, obs_buf.data(), n_obs, false)) { + stop_met = true; + } + // Issue #710 — what a time course's early stop tests is ‖f(t, y)‖ at an // output point, which says the trajectory has settled only for a model // whose right-hand side does not read the time: a rate that starts at @@ -6219,7 +6411,7 @@ Result CvodeSimulator::Impl::run_warm(const TimeSpec ×, const SolverOptions bool ss_reached = false; double ss_residual_last = 0.0; - for (int i = 1; i < n_out; ++i) { + for (int i = 1; i < n_out && !stop_met; ++i) { if (budget.active()) budget.check(); @@ -6246,6 +6438,49 @@ Result CvodeSimulator::Impl::run_warm(const TimeSpec ×, const SolverOptions if (budget.active()) budget.check(); }); + // A stop condition's root (issue #2018): asked there, of the + // row's values as recorded below. Met, the row is the root's and + // the run ends on it; not met, the run goes on to the output. + const auto ask = [&](double t_ask) { + const double *fv = fill_row(t_ask); + std::copy(y_data, y_data + ns, stop_state.begin()); + for (const auto &[fi, si] : ar_copyback) { + stop_state[static_cast(si)] = fv[fi]; + } + return opts.stop_check(i, t_ask, stop_state.data(), ns, obs_buf.data(), n_obs, + /*at_root=*/true); + }; + while (flag == CV_ROOT_RETURN) { + const double t_root = static_cast(t_ret); + bool met = ask(t_root); + if (!met) { + const double t_past = stop_root_past(cvode_mem, t_root, t_out[i]); + if (std::isfinite(t_past) && CVodeGetDky(cvode_mem, t_past, 0, w.y) == 0) { + met = ask(t_past); + if (met) { + t_ret = static_cast(t_past); + } else { + CVodeGetDky(cvode_mem, t_ret, 0, w.y); // the root's state back + } + } + } + if (met) { + t_out[i] = static_cast(t_ret); + stop_met = true; + break; + } + if (budget.active()) + budget.check(); + flag = CVode(cvode_mem, t_out[i], w.y, &t_ret, CV_NORMAL); + if (flag >= 0) + refuse_a_clock_past_the_doubles(cvode_mem); // issue #1838 + retry_while_advancing(cvode_mem, t_out[i], w.y, &t_ret, flag, + "while integrating to the next output point", w.user_data, + [&budget] { + if (budget.active()) + budget.check(); + }); + } if (flag < 0) { rethrow_pending_callback_error(w.user_data); throw SolverFailure(cvode_failure_message(t_out[i], flag, w.user_data), @@ -6287,6 +6522,12 @@ Result CvodeSimulator::Impl::run_warm(const TimeSpec ×, const SolverOptions break; } } + // A root's row was asked at the root; any other, here (issue #2018). + if (!stop_met && opts.stop_check && + opts.stop_check(i, static_cast(t_ret), y_data, ns, obs_buf.data(), n_obs, + false)) { + stop_met = true; + } } // ─── Solver statistics ─────────────────────────────────────────────────── @@ -6299,7 +6540,7 @@ Result CvodeSimulator::Impl::run_warm(const TimeSpec ×, const SolverOptions result.solver_stats().steady_state_residual = ss_residual_last; } - if (check_ss && ss_reached && last_recorded_index + 1 < n_out) { + if (((check_ss && ss_reached) || stop_met) && last_recorded_index + 1 < n_out) { result.truncate(last_recorded_index + 1); } @@ -6309,7 +6550,8 @@ Result CvodeSimulator::Impl::run_warm(const TimeSpec ×, const SolverOptions for (int i = 0; i < ns; ++i) { species[i].concentration = y_data[i]; } - const double final_t = (check_ss && ss_reached) ? t_out[last_recorded_index] : times.t_end; + const double final_t = + ((check_ss && ss_reached) || stop_met) ? t_out[last_recorded_index] : times.t_end; model.set_current_time(final_t); // The functions, and the parameters assignment rules set, at the state // the run ends on, as run() leaves them by its refresh at each row @@ -7601,12 +7843,20 @@ void CvodeSimulator::Impl::refresh_sens_error_floor(void *cvode_mem, double t, N // ─── Event rootfinding registration ────────────────────────────────────────── void CvodeSimulator::Impl::register_roots(void *cvode_mem, SUNContext ctx, int n_roots, - int n_restart_roots) { - // Root function callback: see cvode_event_root_fn. - int flag = CVodeRootInit(cvode_mem, n_roots, cvode_event_root_fn); + int n_restart_roots, int n_stop_roots) { + // Root function callback: see cvode_event_root_fn. A run with stop roots + // (issue #2018) has them after the model's, in cvode_run_root_fn. + int flag = CVodeRootInit(cvode_mem, n_roots + n_stop_roots, + n_stop_roots > 0 ? cvode_run_root_fn : cvode_event_root_fn); if (flag != CV_SUCCESS) { throw std::runtime_error("CVodeRootInit failed: " + std::to_string(flag)); } + // A stop condition that holds on its surface from the start (`t > 0` at + // t = 0) is a root CVODE leaves inactive there, and says so on standard + // error; the condition is still asked at every row. + if (n_stop_roots > 0) { + CVodeSetNoInactiveRootWarn(cvode_mem); + } if (n_restart_roots > 0) { // A discontinuity root makes CVODE restart at each pulse edge, @@ -9306,6 +9556,10 @@ void CvodeSimulator::Impl::confirm_orders(const TimeSpec ×, const SolverOpt tight.sensitivity = std::move(plain); tight.carry_sensitivities = false; tight.steady_state = false; + // A stop condition is the run's, which is over (issue #2018). + tight.stop_check = nullptr; + tight.stop_roots.clear(); + tight.stop_time_origins.clear(); // A compiled right-hand side is loaded again as it is; one compiled in // process would be compiled again for one run, and the interpreter // reads the same model. @@ -17943,11 +18197,33 @@ Result CvodeSimulator::run(const TimeSpec ×, const SolverOptions &opts) { t += *o; return t; }; + // A stop condition reads the time asked for (issue #2018): its roots + // add the origins back in the order back() does, and its check is + // given each row's time as the row reports it. A root's row reports + // the root's time, moved back. + int root_row = -1; + if (opts.stop_check) { + moved.stop_time_origins.assign(origins.rbegin(), origins.rend()); + moved.stop_time_origins.insert(moved.stop_time_origins.end(), + opts.stop_time_origins.begin(), + opts.stop_time_origins.end()); + moved.stop_check = [&opts, &back, &root_row](int row, double t, const double *x, + int n_x, const double *obs, int n_o, + bool at_root) { + const bool met = opts.stop_check(row, back(t), x, n_x, obs, n_o, at_root); + if (met && at_root) { + root_row = row; + } + return met; + }; + } try { Result result = run(elapsed, moved); - // A run to a steady state stops early and keeps the rows it reached. + // A run to a steady state, or to a stop condition, stops early and + // keeps the rows it reached. for (int i = 0; i < result.n_times(); ++i) - result.set_time(i, asked[static_cast(i)]); + result.set_time(i, i == root_row ? back(result.time()[static_cast(i)]) + : asked[static_cast(i)]); // Both ODE paths leave the model at the run's last time, on the // run's clock. model.set_current_time(back(model.current_time())); @@ -19079,6 +19355,34 @@ Result CvodeSimulator::run(const TimeSpec ×, const SolverOptions &opts) { user_data.held_on_y = &held_on_y; } const int n_roots = n_events + n_disc + n_state_switch + n_held_equality; + // Issue #2018: the stop conditions' roots, after the model's in CVODE's + // root vector. n_roots stays the model's own: every path that asks whether + // a run has roots asks it of those, and a run whose condition is never met + // takes the steps it took without one. + validate_stop_roots(opts, ns, n_obs); + // A run that steps over a state switch's surface can go back and record + // rows again once a later return finds a window the step crossed + // (retake_from_row, below). A row asked of a stop condition there is not + // yet the row the run returns, so such a run takes a stop only at a row + // whose step has been screened to its end, and finds no crossing: a root's + // row would be read off a step not screened. + const bool ss_checked = + opts.steady_state && !(model.state_reads_clock() || model.n_events() > 0); + const bool rows_retaken = n_state_switch > 0 && !ss_checked; + const int n_stop_roots = rows_retaken ? 0 : static_cast(opts.stop_roots.size()); + std::vector stop_stack; + std::vector stop_state(static_cast(ns)); + std::vector stop_obs(static_cast(n_obs)); + // Whether the run met a stop condition at the last row recorded, and + // whether that row is a root's. + bool stop_met = false; + bool stop_row_at_root = false; + if (n_stop_roots > 0) { + user_data.stop_roots = &opts.stop_roots; + user_data.stop_time_origins = &opts.stop_time_origins; + user_data.stop_stack = &stop_stack; + user_data.n_model_roots = n_roots; + } // Issue #545: comoving sensitivity columns, for a run nothing restarts off the // clock. Before the first step, which is the first sensitivity RHS call. @@ -20736,11 +21040,15 @@ Result CvodeSimulator::run(const TimeSpec ×, const SolverOptions &opts) { std::vector land_g_after(land_g_before.size()); const RootSignWatch root_watch{n_roots, &user_data, &land_g_before, &land_g_after}; + // A run whose only roots are its stop conditions' (issue #2018). + if (n_roots == 0 && n_stop_roots > 0) { + impl_->register_roots(cvode_mem, ctx, 0, 0, n_stop_roots); + } if (n_roots > 0) { // Register the event, discontinuity and state-switch roots // (Impl::register_roots). The last two restart CVODE at a crossing // alike, so they share its warning filter. - impl_->register_roots(cvode_mem, ctx, n_roots, n_disc + n_state_switch); + impl_->register_roots(cvode_mem, ctx, n_roots, n_disc + n_state_switch, n_stop_roots); // Two-phase t=0 trigger initialization (SBML L3 §3.4.5): // @@ -21041,7 +21349,7 @@ Result CvodeSimulator::run(const TimeSpec ×, const SolverOptions &opts) { // good as in a model without it, and the stop is kept (issue #961). One a // species or a compartment size is reported through does not: what is // reported still moves where ‖f(y)‖ has settled. - const bool check_ss = opts.steady_state && !(model.state_reads_clock() || model.n_events() > 0); + const bool check_ss = ss_checked; const double ss_tol = (opts.steady_state_tol > 0.0) ? opts.steady_state_tol : atol; std::vector ss_derivs; if (check_ss) { @@ -21980,7 +22288,12 @@ Result CvodeSimulator::run(const TimeSpec ×, const SolverOptions &opts) { } return went_back; }; - for (int i = 1; i < n_out; ++i) { + // Issue #2018: a stop condition met at the start ends the run there. + if (opts.stop_check && + opts.stop_check(0, times.t_start, y_data, ns, obs_buf.data(), n_obs, false)) { + stop_met = true; + } + for (int i = 1; i < n_out && !stop_met; ++i) { // Loop until we've reached t_out[i] (within numerical tolerance). while (true) { // Wall-clock budget check (no-op when disabled). Placed at the @@ -22788,7 +23101,8 @@ Result CvodeSimulator::run(const TimeSpec ×, const SolverOptions &opts) { std::fabs(static_cast(h_last))); std::vector info; if (flag == CV_ROOT_RETURN && n_roots > 0) { - info.assign(static_cast(n_roots), 0); + // Room for the stop roots after the model's (issue #2018). + info.assign(static_cast(n_roots + n_stop_roots), 0); CVodeGetRootInfo(cvode_mem, info.data()); } NVectorGuard at(N_VClone(y)); @@ -23010,7 +23324,7 @@ Result CvodeSimulator::run(const TimeSpec ×, const SolverOptions &opts) { // out of the batch. std::vector equality_left; if (flag == CV_ROOT_RETURN && n_held_equality > 0) { - std::vector info(static_cast(n_roots), 0); + std::vector info(static_cast(n_roots + n_stop_roots), 0); CVodeGetRootInfo(cvode_mem, info.data()); const int eq_base = n_events + n_disc + n_state_switch; sunrealtype h_last = 0.0; @@ -23036,7 +23350,7 @@ Result CvodeSimulator::run(const TimeSpec ×, const SolverOptions &opts) { // or held equalities' roots. bool only_held_left = !held_left.empty() || !equality_left.empty(); if (only_held_left) { - std::vector info(static_cast(n_roots), 0); + std::vector info(static_cast(n_roots + n_stop_roots), 0); CVodeGetRootInfo(cvode_mem, info.data()); for (int j : held_left) { info[static_cast(n_events + n_disc + j)] = 0; @@ -23044,8 +23358,9 @@ Result CvodeSimulator::run(const TimeSpec ×, const SolverOptions &opts) { for (int r : equality_left) { info[static_cast(r)] = 0; } - only_held_left = - std::all_of(info.begin(), info.end(), [](int r) { return r == 0; }); + // Of the model's roots: a stop root beside them is asked below. + only_held_left = std::all_of(info.begin(), info.begin() + n_roots, + [](int r) { return r == 0; }); // On a stop's instant, the return CVODE makes without that root. if (only_held_left && ((stop_at_crossing && same_instant(static_cast(t_ret), t_crossing)) || @@ -23155,6 +23470,73 @@ Result CvodeSimulator::run(const TimeSpec ×, const SolverOptions &opts) { t_before_step); } + // ─── A stop condition's root (issue #2018) ─────────────────────── + // A return at stop conditions' roots alone. The condition is asked + // there: met, the root's time becomes this row's and the run ends + // on it; not met (the row is one the caller did not ask for, or + // the condition is not true at its own surface), the return is no + // event of the model's and the run goes on from it, as from a + // step. A return that also holds a root of the model's is the + // model's, handled below as it always was, and the condition is + // asked at the next row recorded. + if (flag == CV_ROOT_RETURN && n_stop_roots > 0) { + std::vector info(static_cast(n_roots + n_stop_roots), 0); + CVodeGetRootInfo(cvode_mem, info.data()); + for (int j : held_left) { + info[static_cast(n_events + n_disc + j)] = 0; + } + for (int r : equality_left) { + info[static_cast(r)] = 0; + } + const auto found = [](int r) { return r != 0; }; + if (std::none_of(info.begin(), info.begin() + n_roots, found) && + std::any_of(info.begin() + n_roots, info.end(), found)) { + // Asked of the row's values as the row below records them, + // so the condition is asked of what the run would return. + const auto ask = [&](double t_ask) { + if (model.uses_rateof()) { + model.refresh_rateof_derivs(static_cast(t_ask), y_data); + } + model.update_observables(y_data); + model.evaluate_functions(t_ask); + std::copy(y_data, y_data + ns, stop_state.begin()); + if (!ar_copyback.empty()) { + const auto &fvals = model.function_value_cache(); + for (const auto &[fi, si] : ar_copyback) { + stop_state[static_cast(si)] = fvals[fi]; + } + } + for (int j = 0; j < n_obs; ++j) { + stop_obs[static_cast(j)] = model.observables()[j].total; + } + return opts.stop_check(i, t_ask, stop_state.data(), ns, stop_obs.data(), + n_obs, /*at_root=*/true); + }; + const double t_root = static_cast(t_ret); + double t_stop = t_root; + bool met = ask(t_root); + if (!met) { + const double t_past = stop_root_past(cvode_mem, t_root, t_out[i]); + if (std::isfinite(t_past) && CVodeGetDky(cvode_mem, t_past, 0, y) == 0) { + met = ask(t_past); + if (met) { + t_stop = t_past; + } else { + CVodeGetDky(cvode_mem, t_ret, 0, y); // the root's state back + } + } + } + if (met) { + t_ret = static_cast(t_stop); + t_now = t_ret; + t_out[i] = t_stop; + stop_row_at_root = true; + break; + } + continue; + } + } + // ─── Event handling: CV_ROOT_RETURN ─────────────────────────────── // CVODE stopped at a root (event trigger zero-crossing). // Identify which events fired, apply assignments, reinit integrator. @@ -23168,7 +23550,9 @@ Result CvodeSimulator::run(const TimeSpec ×, const SolverOptions &opts) { // threshold so the solver cannot step over a narrow pulse. That // restart is skipped only for a plain run's lone state-switch // roots that the flow does not clearly carry (issue #897, below). - std::vector root_info(n_roots); + // A stop root found with the model's (issue #2018) is left + // alone: the condition is asked at the next row recorded. + std::vector root_info(n_roots + n_stop_roots); CVodeGetRootInfo(cvode_mem, root_info.data()); // Issue #908: a held residual's root is its band running out. for (int j : held_left) { @@ -24674,6 +25058,25 @@ Result CvodeSimulator::run(const TimeSpec ×, const SolverOptions &opts) { break; } } + + // ─── Stop conditions (issue #2018) ─────────────────────────────────── + // Asked at each row recorded, and the run ends at the first that + // meets one. A root's row was asked above, at the root. A run whose + // rows can be recorded again stops only at a row no later return can + // go back past: its step screened to its end. + if (stop_row_at_root) { + stop_met = true; + } else if (opts.stop_check && + opts.stop_check(i, t_row, y_data, ns, obs_buf.data(), n_obs, false)) { + if (!rows_retaken) { + stop_met = true; + } else { + sunrealtype tn_s = 0.0; + CVodeGetCurrentTime(cvode_mem, &tn_s); + stop_met = std::isfinite(screen_t) && screen_reinits == impl_->reinits && + screen_t >= static_cast(tn_s); + } + } } // ─── Solver statistics ─────────────────────────────────────────────────── @@ -24690,7 +25093,8 @@ Result CvodeSimulator::run(const TimeSpec ×, const SolverOptions &opts) { // pre-allocated rows past ``last_recorded_index`` were never integrated // and still hold the zero-initialized values from ``allocate()``. Drop // them so the caller sees only the rows we actually integrated. - if (check_ss && ss_reached && last_recorded_index + 1 < n_out) { + // A stop condition met ends the run the same way (issue #2018). + if (((check_ss && ss_reached) || stop_met) && last_recorded_index + 1 < n_out) { result.truncate(last_recorded_index + 1); } @@ -24709,7 +25113,8 @@ Result CvodeSimulator::run(const TimeSpec ×, const SolverOptions &opts) { // "final time" is the last sample we actually integrated to, not the // originally requested ``t_end``. { - const double final_t = (check_ss && ss_reached) ? t_out[last_recorded_index] : times.t_end; + const double final_t = + ((check_ss && ss_reached) || stop_met) ? t_out[last_recorded_index] : times.t_end; // Issue #545: the carry-over seed is S. impl_->comoving_finish(sens, ns, final_t, y_data); impl_->write_final_state_back(opts, ns, y_data, final_t, sens); diff --git a/src/model.cpp b/src/model.cpp index 23be408a8..def5dac36 100644 --- a/src/model.cpp +++ b/src/model.cpp @@ -4582,8 +4582,12 @@ void NetworkModel::update_observables(const double *conc) { // both take it (issue #1278): a read-ahead that summed it its own way would // read a trigger at a value the row's refresh never gives. void NetworkModel::update_observable_(size_t oi, const double *conc) { + impl_->observables[oi].total = observable_total(oi, conc); +} + +double NetworkModel::observable_total(size_t oi, const double *conc) const { const auto &species_list = impl_->species; - auto &obs = impl_->observables[oi]; + const auto &obs = impl_->observables[oi]; double total = 0.0; for (const auto &entry : obs.entries) { // species_index is 1-based, conc array is 0-based @@ -4608,7 +4612,7 @@ void NetworkModel::update_observable_(size_t oi, const double *conc) { total += entry.factor * v; } } - obs.total = total; + return total; } void NetworkModel::evaluate_functions(double t, bool with_deferred) { From e549d622ccd2a060b51732ff6d8cec07493418d5 Mon Sep 17 00:00:00 2001 From: Bill Hlavacek Date: Thu, 3 Dec 2026 16:00:30 -0700 Subject: [PATCH 02/11] wip: SSA and PSA runs end at a stop condition's row; tests follow the new stop (#2018) --- include/bngsim/simulator.hpp | 12 ++- python/bngsim/_simulator.py | 57 +++++++++---- python/tests/test_cli_run_calls.py | 26 +++--- .../test_run_until_clock_tracks_state.py | 43 +++++++--- .../test_stop_condition_numpy_warnings.py | 12 +-- ...t_stop_condition_reads_only_what_it_can.py | 49 ++++++----- .../test_stop_condition_result_fields.py | 76 +++++++++++++++-- .../tests/test_stop_conditions_in_batches.py | 11 ++- src/_bngsim_core.cpp | 35 +++++--- src/cvode_simulator.cpp | 2 +- src/ssa_simulator.cpp | 81 ++++++++++++++++--- 11 files changed, 310 insertions(+), 94 deletions(-) diff --git a/include/bngsim/simulator.hpp b/include/bngsim/simulator.hpp index 50092fe09..de88ed0b7 100644 --- a/include/bngsim/simulator.hpp +++ b/include/bngsim/simulator.hpp @@ -90,13 +90,19 @@ class SsaSimulator { // `timeout_seconds <= 0` (default) disables the wall-clock budget; a // positive value causes the loop to throw `bngsim::TimeoutError` once // elapsed time exceeds the limit. - Result run(const TimeSpec ×, uint64_t seed = 42, double timeout_seconds = 0.0); + // + // `stop` (issue #2018), when set, is asked at each row the run records, + // with the row as the result holds it; where it holds, the run ends + // there: the result is cut after that row and the model is left at its + // state and time. + Result run(const TimeSpec ×, uint64_t seed = 42, double timeout_seconds = 0.0, + const StopCheck &stop = StopCheck()); // Run PSA (Partial Scaling Algorithm) simulation. // poplevel = N_c, the critical population size (must be > 1). // Lin, Feng, Hlavacek, J. Chem. Phys. 150, 244101 (2019). Result run_psa(const TimeSpec ×, uint64_t seed, double poplevel, - double timeout_seconds = 0.0); + double timeout_seconds = 0.0, const StopCheck &stop = StopCheck()); // GH #190 — supply the path to a cc-compiled value-specialized propensity // .so (symbol bngsim_ssa_propensities), produced by the Python codegen @@ -142,7 +148,7 @@ class SsaSimulator { // Internal: shared SSA/PSA simulation loop Result run_internal(const TimeSpec ×, uint64_t seed, double poplevel, - double timeout_seconds); + double timeout_seconds, const StopCheck &stop); }; } // namespace bngsim diff --git a/python/bngsim/_simulator.py b/python/bngsim/_simulator.py index a559bc493..005b901ad 100644 --- a/python/bngsim/_simulator.py +++ b/python/bngsim/_simulator.py @@ -6816,10 +6816,16 @@ def _jax_callback(t, y_arr): run_jacobian = self._jacobian_used(opts, self._model._core) elif self._method == "ssa": self._apply_ssa_breakpoints([self._sim], self._model, t_start, t_end) - core_result = self._sim.run(times, used_seed, timeout_seconds) + stops = self._ssa_stops(self._model, n_rows, lead, trail) + stops_given = bool(stops) + core_result = self._sim.run(times, used_seed, timeout_seconds, **stops) elif self._method == "psa": self._apply_ssa_breakpoints([self._sim], self._model, t_start, t_end) - core_result = self._sim.run_psa(times, used_seed, self._poplevel, timeout_seconds) + stops = self._ssa_stops(self._model, n_rows, lead, trail) + stops_given = bool(stops) + core_result = self._sim.run_psa( + times, used_seed, self._poplevel, timeout_seconds, **stops + ) elif self._method == "nfsim" or self._method == "rulemonkey": from bngsim._network_free_params import parameter_overrides, species_amounts @@ -7504,13 +7510,10 @@ def _run_one_here(i: int) -> Result: self._warn_atol_above_scale(results, "ODE batch", per_result=row_atols) # Each row meets the stop conditions as run() does, and one that meets - # one comes back cut there, beside the rest (issue #1369); an ODE row - # ends there too (issue #2018). + # one comes back cut there, beside the rest (issue #1369); an ODE, SSA + # or PSA row's run ends there too (issue #2018). if self._stop_conditions: - results = [ - self._stopped(r, ended=self._method == "ode" and _ended_on_a_stop(r, n_points)) - for r in results - ] + results = [self._stopped(r, ended=_ended_on_a_stop(r, n_points)) for r in results] # Each row is stamped already, against its own clone (issues #698, #743). if squeeze: @@ -7661,6 +7664,9 @@ def _make_times() -> Any: # One set of parameters for every replicate, for each one's record # (issue #1703). start_params = _record.parameter_values(self._model) + # The stop conditions each replicate's run can ask as it goes (issue + # #2018); a clone has the same columns as the model it was made from. + stops = self._ssa_stops(self._model, n_points, 0, 0) @_notices.collected def _run_one(sim: Any, model: Model, times: Any, i: int) -> Result: @@ -7677,9 +7683,9 @@ def _run_one(sim: Any, model: Model, times: Any, i: int) -> Result: # sees a refusal on the sequential path as it does on the threaded one. try: if self._method == "psa": - cr = sim.run_psa(times, used, self._poplevel, eff_timeout) + cr = sim.run_psa(times, used, self._poplevel, eff_timeout, **stops) else: - cr = sim.run(times, used, eff_timeout) + cr = sim.run(times, used, eff_timeout, **stops) except SimulationTimeout: raise except RuntimeError as e: @@ -7753,9 +7759,9 @@ def _worker(i: int) -> Result: # ...and the species set in it (issue #2014). self._model._conc_set = None if start_held is None else dict(start_held) - # As run_batch's rows (issue #1369). + # As run_batch's rows (issues #1369, #2018). if self._stop_conditions: - results = [self._stopped(r) for r in results] + results = [self._stopped(r, ended=_ended_on_a_stop(r, n_points)) for r in results] # Every row is stamped already; stamping the stack again would replace # the rows' own report metadata with the parent's (issue #743). @@ -9182,10 +9188,13 @@ def restore() -> None: sim = self._new_ssa_engine(clone._core) # This row's parameters place its crossings, so resolve on the clone. self._apply_ssa_breakpoints([sim], clone, t_span[0], t_span[1]) + stops = self._ssa_stops(clone, n_points, 0, 0) if self._method == "psa": - core_result = sim.run_psa(times, row_seed, self._poplevel, timeout_seconds) + core_result = sim.run_psa( + times, row_seed, self._poplevel, timeout_seconds, **stops + ) else: - core_result = sim.run(times, row_seed, timeout_seconds) + core_result = sim.run(times, row_seed, timeout_seconds, **stops) else: raise ValueError(f"Unknown method: {self._method}") except _ConditionReadOtherwise as e: @@ -12847,6 +12856,26 @@ def _give_stops(self, opts: Any, model: Model, n_rows: int, lead: int, trail: in opts.set_stop_roots(roots) return True + def _ssa_stops(self, model: Model, n_rows: int, lead: int, trail: int) -> dict[str, Any]: + """The keywords that hand an SSA or PSA run the stop conditions it can + ask at each row it records, those ``lead <= row < n_rows - trail`` the + result reports (issue #2018); none where it can ask none.""" + if not self._stop_conditions: + return {} + from bngsim._stop_in_run import in_run_stops + + got = in_run_stops( + self._stop_conditions, model, first=lead, end=n_rows - trail, roots=False + ) + if got is None: + return {} + check, species_cols, obs_cols, _ = got + return { + "stop": check, + "stop_species_columns": species_cols, + "stop_observable_columns": obs_cols, + } + def _refuse_squeeze_with_stop_conditions(self, where: str, squeeze: bool) -> None: """Refuse ``squeeze=True`` on a batch while a stop condition is registered. diff --git a/python/tests/test_cli_run_calls.py b/python/tests/test_cli_run_calls.py index 1de52ed06..ebc04c99e 100644 --- a/python/tests/test_cli_run_calls.py +++ b/python/tests/test_cli_run_calls.py @@ -73,9 +73,10 @@ def test_run_until_a_condition_met_exits_0_with_the_result_it_cut(): assert d["stop_condition"] == met.value.condition == "C > 50" assert d["digest"] == _plain(met.value.result.digest()) assert d["digest"]["t_end"] == float(met.value.result.time[-1]) < 50.0 - # Cut at the first output point where the condition holds: on the default - # grid of one point per unit of time, C passes 50 between t = 2 and t = 3. - assert d["digest"]["t_end"] == 3.0 + # Ended where C passes 50, between the default grid's t = 2 and t = 3: + # the run finds the crossing as it goes (issue #2018). + assert 2.0 < d["digest"]["t_end"] < 3.0 + assert met.value.result.observables["C"][-1] == pytest.approx(50.0, rel=1e-6) assert d["record"]["run"]["timeout"] is None # run_until takes none: the command's own @@ -90,9 +91,10 @@ def test_run_until_with_no_condition_met_is_the_whole_run(): assert text.returncode == 0 and "stopped" not in text.stdout -def test_run_until_conditions_are_checked_in_order_and_seeded(): - # Two conditions: the first one added that holds cuts the run, even where - # a later one held earlier; and a stochastic run takes its seed. +def test_run_until_conditions_end_the_run_at_the_first_row_one_holds_and_seeded(): + # Two conditions: the run ends at the first row either holds at, even where + # the one that holds there was added later (issue #2018); where both hold, + # the one added first names it. And a stochastic run takes its seed. args = ("run-until", BIRTH_DEATH, "--method", "ssa", "--t-end", "20", "--seed", "5") d = _json(_bngsim(*args, "--stop-when", "A > 9000", "--stop-when", "A > 10", "--json")) sim = Simulator(Model.load(BIRTH_DEATH), method="ssa") @@ -100,9 +102,13 @@ def test_run_until_conditions_are_checked_in_order_and_seeded(): sim.add_stop_condition("A > 10") with pytest.raises(StopConditionMet) as met: sim.run_until(20.0, seed=5) - assert d["stop_condition"] == met.value.condition == "A > 9000" + assert d["stop_condition"] == met.value.condition == "A > 10" assert d["digest"] == _plain(met.value.result.digest()) assert d["record"]["run"]["seed"] == 5 + # A count is a whole number: A >= 11 holds where A > 10 does. + tie = _json(_bngsim(*args, "--stop-when", "A >= 11", "--stop-when", "A > 10", "--json")) + assert tie["stop_condition"] == "A >= 11" + assert tie["digest"]["t_end"] == d["digest"]["t_end"] text = _bngsim(*args, "--stop-when", "A > 9000") assert text.returncode == 0 and "stopped: A > 9000 held at t=" in text.stdout @@ -697,11 +703,11 @@ def steady_state(self, **kw): def test_run_until_and_steady_state_are_bounded_too(): - # run_until integrates the whole span before a condition cuts it, so a - # condition met early does not shorten it: the span counts. + # A condition never met: the run goes the whole span, which the limit + # bounds. (One met early ends the run there, issue #2018.) start = time.monotonic() run = _bngsim("run-until", BIRTH_DEATH, "--method", "ssa", "--set", "ksyn=1e6", "--t-end", - "1000", "--stop-when", "A > 1", "--timeout", "0.5", "--json") # fmt: skip + "1000", "--stop-when", "A < 0", "--timeout", "0.5", "--json") # fmt: skip error = _error(run, _cli.EXIT_TIMEOUT, "run.timeout") assert error["message"].startswith("run_until took longer than 0.5 s") run = _bngsim("steady-state", CHAIN, "--timeout", "0.5", "--json", script=_SLOW_STEADY_STATE) diff --git a/python/tests/test_run_until_clock_tracks_state.py b/python/tests/test_run_until_clock_tracks_state.py index 7023aba56..49b99f213 100644 --- a/python/tests/test_run_until_clock_tracks_state.py +++ b/python/tests/test_run_until_clock_tracks_state.py @@ -11,6 +11,10 @@ ``run()`` now advances the clock itself, the moment the backend writes the state back, so every post-solve raise leaves the two agreeing. + +Since issue #2018 an expression condition is asked during the run, which ends +where it holds: the model is left at the stop's state and the clock at its time. +A condition the run cannot ask (a callable) is still asked of the whole span. """ from __future__ import annotations @@ -99,21 +103,40 @@ def _analytic(t: float) -> float: return DECAY_A0 * np.exp(-DECAY_K * t) +# Where A_tot = 50 and 5 on the closed form, which an expression condition's +# run now ends at (issue #2018). +HALF_AT = np.log(DECAY_A0 / 50.0) / DECAY_K +TWENTIETH_AT = np.log(DECAY_A0 / 5.0) / DECAY_K + + class TestClockAfterStopCondition: def test_current_time_is_where_the_backend_left_the_state(self, data_dir: Path) -> None: - """The reported stop time and the clock differ, and the clock is the honest one.""" + """The run ends at the stop: the model holds its state, the clock its time.""" sim = _decay(data_dir) sim.add_stop_condition("A_tot < 50", label="half") with pytest.raises(StopConditionMet) as excinfo: sim.run_until(t=100) - assert excinfo.value.result.time[-1] == pytest.approx(7.0) - # The model holds the end-of-interval state, not the trigger-point one. + stop = excinfo.value.result.time[-1] + assert stop == pytest.approx(HALF_AT, rel=1e-5) + assert sim.model.get_state()[0] == pytest.approx(50.0, rel=1e-5) + assert sim.model.get_state()[0] == excinfo.value.result.species[-1, 0] + assert sim.current_time == stop + + def test_a_callable_condition_still_runs_the_whole_span(self, data_dir: Path) -> None: + """Control. A callable is asked of the whole result, so the run goes to + its end, and the clock says so.""" + sim = _decay(data_dir) + sim.add_stop_condition(lambda r: r.observables["A_tot"][-1] < 50, label="half") + with pytest.raises(StopConditionMet) as excinfo: + sim.run_until(t=100) + + assert excinfo.value.result.time[-1] == 100.0 assert sim.model.get_state()[0] == pytest.approx(_analytic(100.0), rel=1e-4) assert sim.current_time == 100.0 def test_next_leg_time_axis_matches_its_own_first_row(self, data_dir: Path) -> None: - """The headline symptom: a Result labelled t=0 whose first row was the t=100 state.""" + """The headline symptom: a Result labelled t=0 whose first row was a later state.""" sim = _decay(data_dir) sim.add_stop_condition("A_tot < 50", label="half") with pytest.raises(StopConditionMet): @@ -121,10 +144,10 @@ def test_next_leg_time_axis_matches_its_own_first_row(self, data_dir: Path) -> N sim.clear_stop_conditions() result = sim.run_until(t=150) - assert result.time[0] == pytest.approx(100.0) + assert result.time[0] == pytest.approx(HALF_AT, rel=1e-5) assert result.time[-1] == pytest.approx(150.0) - # Row 0 is the t=100 state and the axis now says so. - assert result.species[0, 0] == pytest.approx(_analytic(100.0), rel=1e-4) + # Row 0 is the stop's state and the axis says so. + assert result.species[0, 0] == pytest.approx(50.0, rel=1e-5) assert result.species[-1, 0] == pytest.approx(_analytic(150.0), rel=1e-3) assert sim.current_time == 150.0 @@ -136,8 +159,8 @@ def test_a_target_behind_the_advanced_state_is_refused(self, data_dir: Path) -> sim.run_until(t=100) sim.clear_stop_conditions() - with pytest.raises(ValueError, match=r"must be > current time \(100"): - sim.run_until(t=50) + with pytest.raises(ValueError, match=r"must be > current time \(6\.93"): + sim.run_until(t=5) def test_snapshot_restore_still_returns_to_the_leg_start(self, data_dir: Path) -> None: """The documented way to continue from before the stop, clock included.""" @@ -147,7 +170,7 @@ def test_snapshot_restore_still_returns_to_the_leg_start(self, data_dir: Path) - sim.add_stop_condition("A_tot < 5", label="low") with pytest.raises(StopConditionMet): sim.run_until(t=100) - assert sim.current_time == 100.0 + assert sim.current_time == pytest.approx(TWENTIETH_AT, rel=1e-5) sim.restore(snap) assert sim.current_time == 10.0 diff --git a/python/tests/test_stop_condition_numpy_warnings.py b/python/tests/test_stop_condition_numpy_warnings.py index 8937c4673..ff62a5314 100644 --- a/python/tests/test_stop_condition_numpy_warnings.py +++ b/python/tests/test_stop_condition_numpy_warnings.py @@ -19,6 +19,7 @@ from __future__ import annotations +import math import subprocess import sys import warnings @@ -81,8 +82,9 @@ def _told(caught: list[warnings.WarningMessage], condition: str) -> list[str]: # 1/(t - 50) is negative before t = 50 and 1/0 = +inf there: met at 50. ("1 / (t - 50) > 0", 50.0, "divide by zero"), # A_tot**1000 overflows to +inf while A_tot > 2.03 (t < 39), and is < 1 - # once A_tot < 1 (t > 10 ln 100 = 46.05): 1.005**1000 = 175 at t = 46. - ("A_tot ** 1000 < 1", 47.0, "overflow"), + # once A_tot < 1, past t = 10 ln 100 = 46.05, where the run ends: a + # comparison's crossing is found as it goes (issue #2018). + ("A_tot ** 1000 < 1", pytest.approx(10 * math.log(100), rel=1e-5), "overflow"), ], ) def test_an_arithmetic_error_is_read_as_its_value_and_told_from_outside( @@ -226,11 +228,11 @@ def test_a_kind_set_to_call_or_log_with_nowhere_to_go_refuses_the_run_as_numpy_r def test_a_clean_condition_warns_nothing_and_leaves_numpys_state_alone(net): - """A_tot < 10 meets no error: met at t = 24, nothing told, and numpy's - modes and callback are what they were before the run.""" + """A_tot < 10 meets no error: met where it crosses, t = 10 ln 10, nothing + told, and numpy's modes and callback are what they were before the run.""" before = (np.geterr(), np.geterrcall()) got, caught = _run(net, "A_tot < 10") - assert got == 24.0 + assert got == pytest.approx(10 * math.log(10), rel=1e-5) assert [str(w.message) for w in caught if issubclass(w.category, RuntimeWarning)] == [] assert (np.geterr(), np.geterrcall()) == before # And after a run that met errors, too. diff --git a/python/tests/test_stop_condition_reads_only_what_it_can.py b/python/tests/test_stop_condition_reads_only_what_it_can.py index 2dad43a38..4e49e9fa0 100644 --- a/python/tests/test_stop_condition_reads_only_what_it_can.py +++ b/python/tests/test_stop_condition_reads_only_what_it_can.py @@ -17,6 +17,8 @@ import re from pathlib import Path +import math + import bngsim import pytest @@ -29,6 +31,9 @@ ) KW = dict(t_span=(0, 100), n_points=101) MET_AT = 24.0 # the first sample where 100*exp(-0.1 t) < 10 +# Where it crosses 10, which a run ends at for a comparison or a number it can +# find the crossing of (issue #2018). +CROSSING = math.log(10.0) / 0.1 # S := 2*A by an SBML assignment rule, which loads as a model function. SBML = """ @@ -141,9 +146,10 @@ def test_an_sbml_assignment_rule_is_refused_as_a_function(tmp_path): sim = bngsim.Simulator(bngsim.Model.from_sbml(str(path)), method="ode") with pytest.raises(ValueError, match="S is a function of the model"): sim.add_stop_condition("S < 5") - # Control: the species reads as before. A(t) = 10*exp(-t) < 5 past t = ln 2. + # Control: the species reads as before. A(t) = 10*exp(-t) < 5 past t = ln 2, + # where the run ends (issue #2018). sim.add_stop_condition("A < 5") - assert _stop_time(sim, t_span=(0, 2), n_points=21) == pytest.approx(0.7) + assert _stop_time(sim, t_span=(0, 2), n_points=21) == pytest.approx(math.log(2.0), rel=1e-5) def test_caret_is_refused_with_the_power_spelled(net): @@ -165,7 +171,7 @@ def test_a_number_is_met_where_it_is_positive(net): Any nonzero value met it, so 10 - A_tot (-90 at t = 0) was met at t = 0.""" sim = _sim(net) sim.add_stop_condition("10 - A_tot") - assert _stop_time(sim) == MET_AT + assert _stop_time(sim) == pytest.approx(CROSSING, rel=1e-5) def test_a_number_that_is_nan_does_not_meet_the_condition(net): @@ -302,26 +308,29 @@ def test_a_species_is_refused_on_a_network_free_run(method): @pytest.mark.parametrize( - "condition", + "condition, at", [ - "A_tot < 10", - "A__ < 10", - "t >= 24", - "time >= 24", - "A_tot**2 < 100", - "(lambda x: x < 10)(A_tot)", - "[x < 10 for x in (A_tot,)][0]", - "(a := A_tot) < 10 and a >= 0", - "A_tot.real < 10", + ("A_tot < 10", CROSSING), + ("A__ < 10", CROSSING), + ("t >= 24", MET_AT), + ("time >= 24", MET_AT), + ("A_tot**2 < 100", CROSSING), + ("(lambda x: x < 10)(A_tot)", MET_AT), + ("[x < 10 for x in (A_tot,)][0]", MET_AT), + ("(a := A_tot) < 10 and a >= 0", MET_AT), + ("A_tot.real < 10", MET_AT), # A name the expression binds in an inner scope and reads outside it. - "(lambda A_tot: A_tot < 10)(A_tot)", - "(A_tot := A_tot) < 10", + ("(lambda A_tot: A_tot < 10)(A_tot)", MET_AT), + ("(A_tot := A_tot) < 10", MET_AT), ], ) -def test_the_names_a_condition_can_read_read_as_before(net, condition): - """Control: the observables, a species by its identifier spelling, the time, a - power spelled **, names the expression binds itself and an attribute are read, - and each condition is met at t = 24.""" +def test_the_names_a_condition_can_read_read_as_before(net, condition, at): + """The observables, a species by its identifier spelling, the time, a power + spelled **, names the expression binds itself and an attribute are read. A + comparison of arithmetic over what a sample binds ends the run where it + starts to hold, at the crossing; any other form at the first sample it holds + at, t = 24 (issue #2018).""" sim = _sim(net) sim.add_stop_condition(condition) - assert _stop_time(sim) == MET_AT + got = _stop_time(sim) + assert got == MET_AT if at == MET_AT else got == pytest.approx(at, rel=1e-5) diff --git a/python/tests/test_stop_condition_result_fields.py b/python/tests/test_stop_condition_result_fields.py index 017cb7a73..624172069 100644 --- a/python/tests/test_stop_condition_result_fields.py +++ b/python/tests/test_stop_condition_result_fields.py @@ -17,6 +17,11 @@ The last test here is the one that keeps this fixed: it walks every field a Result holds rather than the handful this bug happened to cover, so a field added later cannot go missing from the truncated copy unnoticed. + +Since issue #2018 the run itself ends where an expression condition holds, so +the copy is made of a result that ends there. The cut made after a whole run, +which a condition the run cannot ask still takes, is the one these tests make, +through ``Simulator._stopped``; the run that ends itself is tested at the end. """ from __future__ import annotations @@ -61,19 +66,35 @@ def _model(net): return bngsim.Model.from_net(net) -def _stopped(net, **kw): - """Run until the stop condition fires; return (partial, full) results.""" - sim = bngsim.Simulator(_model(net), **kw) - sim.add_stop_condition(STOP, label="half") +def _run(kw): run = {"t_span": (0.0, 10.0), "n_points": 11} if kw.get("method") == "ssa": run["seed"] = 7 + return run + + +def _stopped(net, **kw): + """A whole run, and the copy the stop condition cuts of it after the run: + (partial, full).""" + sim = bngsim.Simulator(_model(net), **kw) + sim.add_stop_condition(STOP, label="half") + with contextlib.redirect_stderr(io.StringIO()): + full = bngsim.Simulator(_model(net), **kw).run(**_run(kw)) + partial = sim._stopped(full) + # The cut is a real one: some of the run survives, and some is gone. + assert 0 < partial.time.shape[0] < full.time.shape[0] + return partial, full + + +def _ended(net, **kw): + """A run the stop condition ends, and the whole run: (partial, full).""" + sim = bngsim.Simulator(_model(net), **kw) + sim.add_stop_condition(STOP, label="half") with contextlib.redirect_stderr(io.StringIO()): - full = bngsim.Simulator(_model(net), **kw).run(**run) + full = bngsim.Simulator(_model(net), **kw).run(**_run(kw)) with pytest.raises(bngsim.StopConditionMet) as exc: - sim.run(**run) + sim.run(**_run(kw)) partial = exc.value.result - # The cut is a real one: some of the run survives, and some is gone. assert 0 < partial.time.shape[0] < full.time.shape[0] return partial, full @@ -139,7 +160,9 @@ def test_the_value_blocks_are_the_full_run_s_prefix(net, block): # `_core` is deliberately absent (a truncated result owns no C++ handle, which # is why the fields above have to be forwarded by hand in the first place). -_NOT_FORWARDED = {"_core"} +# `_species_view` is a cache the species accessor fills on its first read (of +# the whole run here, by the stop check), keyed to the arrays it was made of. +_NOT_FORWARDED = {"_core", "_species_view"} # The one field a stop sets rather than carries: the condition the result was # cut at, None on the full run (issue #1369). Checked on its own below. _SET_BY_THE_STOP = {"_stop_condition"} @@ -190,3 +213,40 @@ def test_every_field_is_carried_over(net, kw): if not _same(got, want): missing.append(name) assert not missing, f"truncated result lost or changed: {missing}" + + +# ── The run the stop ends (issue #2018) ────────────────────────────────────── + +# 100*exp(-0.3 t) = 50, where an ODE run now ends. +HALF_AT = float(np.log(2.0) / 0.3) + + +@pytest.mark.parametrize("kw", [{"method": "ode", "sensitivity_params": ["k"]}, {"method": "ssa"}]) +def test_a_run_the_stop_ends_is_the_whole_run_s_prefix(net, kw): + """The rows before the stop's are the whole run's, to the bit: asking the + condition as the run goes changes no step. An ODE run ends at the crossing, + with the state and its sensitivity there; an SSA run at the first sample the + condition holds at, the whole run's row.""" + partial, full = _ended(net, **kw) + n = partial.time.shape[0] + assert partial.stop_condition == "half" and full.stop_condition is None + assert partial.seed == full.seed + if kw["method"] == "ssa": + for block in ("time", "species", "observables"): + assert np.array_equal( + np.asarray(getattr(partial, block)), np.asarray(getattr(full, block))[:n] + ) + assert partial.ssa_diagnostics["propensity_backend"] == ( + full.ssa_diagnostics["propensity_backend"] + ) + return + for block in ("time", "species", "observables", "sensitivities"): + assert np.array_equal( + np.asarray(getattr(partial, block))[: n - 1], np.asarray(getattr(full, block))[: n - 1] + ) + assert full.time[n - 2] < partial.time[-1] == pytest.approx(HALF_AT, rel=1e-6) + assert partial.time[-1] < full.time[n - 1] + assert partial.species[-1, 0] == pytest.approx(50.0, rel=1e-6) + # d/dk 100*exp(-k t) = -t * A. + assert partial.sensitivities[-1].ravel()[0] == pytest.approx(-HALF_AT * 50.0, rel=1e-6) + assert partial.output_sensitivities("A_tot").shape[0] == n diff --git a/python/tests/test_stop_conditions_in_batches.py b/python/tests/test_stop_conditions_in_batches.py index 86339321f..196d3069f 100644 --- a/python/tests/test_stop_conditions_in_batches.py +++ b/python/tests/test_stop_conditions_in_batches.py @@ -173,11 +173,18 @@ def test_to_xarray_carries_the_condition(net): @pytest.mark.parametrize("condition", ["A__ < 10", "A_tot < 10 and t > 0"]) def test_an_expression_reads_species_and_time_as_before(net, condition): """An expression is evaluated against the names it reads only; a species, by - its sanitized name, and the time still read as they did.""" + its sanitized name, and the time still read as they did. Each stops where + A_tot < 10 does: a comparison at the crossing, the run finds it as it goes; + the conjunction, which it cannot, at the first sample past it (issue + #2018).""" want = _sim(net, "ode").run_batch(params=[{"k": 0.1}], **KW)[0] got = _sim(net, "ode", condition=condition).run_batch(params=[{"k": 0.1}], **KW)[0] assert got.stop_condition == "low" - np.testing.assert_array_equal(got.time, want.time) + np.testing.assert_array_equal(got.time[:-1], want.time[:-1]) + if condition == "A__ < 10": + assert got.time[-1] == want.time[-1] + else: + assert want.time[-2] < want.time[-1] < got.time[-1] == want.time[-2] + 1.0 def test_a_condition_on_the_time_alone_cuts_there(net): diff --git a/src/_bngsim_core.cpp b/src/_bngsim_core.cpp index 768423cc1..0650e9d2b 100644 --- a/src/_bngsim_core.cpp +++ b/src/_bngsim_core.cpp @@ -921,7 +921,7 @@ static bngsim::StopCheck make_stop_check(py::object fn, std::vector species } // Issue #2018: stop roots as Python hands them, one list of (kind, index, -// value) operations per root (bngsim._stop_roots). +// value) operations per root (bngsim._stop_in_run). static std::vector stop_roots_from(const std::vector>> &roots) { std::vector out; @@ -1160,7 +1160,7 @@ PYBIND11_MODULE(_bngsim_core, m) { }, py::arg("roots"), "Issue #2018: the stop conditions' root functions, each a list of (kind, index, " - "value) operations on a stack (bngsim._stop_roots); CVODE finds where each " + "value) operations on a stack (bngsim._stop_in_run); CVODE finds where each " "changes sign, and the stop check decides there. Needs a stop check.") .def( "set_crossing_stops", @@ -3555,38 +3555,55 @@ PYBIND11_MODULE(_bngsim_core, m) { .def( "run", [](bngsim::SsaSimulator &self, const bngsim::TimeSpec ×, uint64_t seed, - double timeout_seconds) { + double timeout_seconds, py::object stop, std::vector stop_species_columns, + std::vector stop_observable_columns) { + const bngsim::StopCheck check = + make_stop_check(std::move(stop), std::move(stop_species_columns), + std::move(stop_observable_columns)); // Release GIL during simulation bngsim::Result result; { py::gil_scoped_release release; - result = self.run(times, seed, timeout_seconds); + result = self.run(times, seed, timeout_seconds, check); } return result; }, py::arg("times"), py::arg("seed") = 42, py::arg("timeout_seconds") = 0.0, + py::arg("stop") = py::none(), py::arg("stop_species_columns") = std::vector(), + py::arg("stop_observable_columns") = std::vector(), "Run exact SSA simulation with deterministic seed (releases GIL). " "timeout_seconds > 0 enables a wall-clock budget; on overrun, " - "raises bngsim.SimulationTimeout.") + "raises bngsim.SimulationTimeout. stop (issue #2018), when given, is " + "called as stop(row, t, species, observables, at_root) at each row " + "recorded, with the stop_species_columns of the state and the " + "stop_observable_columns of the observables; where it returns True " + "the run ends at that row.") .def( "run_psa", [](bngsim::SsaSimulator &self, const bngsim::TimeSpec ×, uint64_t seed, - double poplevel, double timeout_seconds) { + double poplevel, double timeout_seconds, py::object stop, + std::vector stop_species_columns, std::vector stop_observable_columns) { + const bngsim::StopCheck check = + make_stop_check(std::move(stop), std::move(stop_species_columns), + std::move(stop_observable_columns)); // Release GIL during simulation bngsim::Result result; { py::gil_scoped_release release; - result = self.run_psa(times, seed, poplevel, timeout_seconds); + result = self.run_psa(times, seed, poplevel, timeout_seconds, check); } return result; }, py::arg("times"), py::arg("seed") = 42, py::arg("poplevel") = 100.0, - py::arg("timeout_seconds") = 0.0, + py::arg("timeout_seconds") = 0.0, py::arg("stop") = py::none(), + py::arg("stop_species_columns") = std::vector(), + py::arg("stop_observable_columns") = std::vector(), "Run PSA (Partial Scaling Algorithm) simulation.\n" "Lin, Feng, Hlavacek, J. Chem. Phys. 150, 244101 (2019).\n" "poplevel = N_c (critical population size, must be > 1). Releases GIL. " "timeout_seconds > 0 enables a wall-clock budget; on overrun, " - "raises bngsim.SimulationTimeout.") + "raises bngsim.SimulationTimeout. stop, stop_species_columns and " + "stop_observable_columns as for run().") .def("set_propensity_library", &bngsim::SsaSimulator::set_propensity_library, py::arg("so_path"), "GH #190: supply a cc-compiled value-specialized propensity .so " diff --git a/src/cvode_simulator.cpp b/src/cvode_simulator.cpp index cc728031e..18290e8d9 100644 --- a/src/cvode_simulator.cpp +++ b/src/cvode_simulator.cpp @@ -3834,7 +3834,7 @@ static double stop_root_value(const StopRoot &root, double t, const double *x, // Refuse a stop root whose program would read outside the run's state or // observables, or leave its stack other than one deep, before CVODE is given -// it. Python compiles them (bngsim._stop_roots), so a refusal here is a bug +// it. Python compiles them (bngsim._stop_in_run), so a refusal here is a bug // there. static void validate_stop_roots(const SolverOptions &opts, int n_state, int n_obs) { if (!opts.stop_roots.empty() && !opts.stop_check) { diff --git a/src/ssa_simulator.cpp b/src/ssa_simulator.cpp index f25e83286..6c73cb968 100644 --- a/src/ssa_simulator.cpp +++ b/src/ssa_simulator.cpp @@ -587,21 +587,23 @@ template static Result restoring_on_raise(NetworkModel &model, Run & } } -Result SsaSimulator::run(const TimeSpec ×, uint64_t seed, double timeout_seconds) { +Result SsaSimulator::run(const TimeSpec ×, uint64_t seed, double timeout_seconds, + const StopCheck &stop) { // poplevel = 0.0 means no scaling (exact SSA) - return restoring_on_raise(impl_->model, - [&] { return run_internal(times, seed, 0.0, timeout_seconds); }); + return restoring_on_raise( + impl_->model, [&] { return run_internal(times, seed, 0.0, timeout_seconds, stop); }); } Result SsaSimulator::run_psa(const TimeSpec ×, uint64_t seed, double poplevel, - double timeout_seconds) { + double timeout_seconds, const StopCheck &stop) { if (!(poplevel > 1.0)) { // NaN too: it read as no scaling, exact SSA throw std::invalid_argument( "PSA poplevel (N_c) must be > 1. Got " + std::to_string(poplevel) + ". For exact stochastic simulation, use run() instead of run_psa()."); } - return restoring_on_raise(impl_->model, - [&] { return run_internal(times, seed, poplevel, timeout_seconds); }); + return restoring_on_raise(impl_->model, [&] { + return run_internal(times, seed, poplevel, timeout_seconds, stop); + }); } // ─── Unified SSA/PSA simulation loop ───────────────────────────────────────── @@ -625,7 +627,7 @@ Result SsaSimulator::run_psa(const TimeSpec ×, uint64_t seed, double poplev // - Sum tree: O(log N) reaction selection + O(log N) propensity updates Result SsaSimulator::run_internal(const TimeSpec ×_in, uint64_t seed, double poplevel, - double timeout_seconds) { + double timeout_seconds, const StopCheck &stop) { // Issue #1504 — a last time of inf ran a birth-death model until the budget // and for ever without one, and a NaN came back as a row at t = nan. times_in.require_walkable("SsaSimulator::run"); @@ -759,7 +761,9 @@ Result SsaSimulator::run_internal(const TimeSpec ×_in, uint64_t seed, doubl // Output time points std::vector t_out = times.output_times(); - const int n_out = static_cast(t_out.size()); + // Not const: a stop (issue #2018) ends the run at the row it holds at by + // making that row the last, so every loop below ends as at the last row. + int n_out = static_cast(t_out.size()); // Working arrays: species populations (0-based). conc[] holds each species // in its storage units, n/V, which is what rate laws, observables and the @@ -2316,6 +2320,30 @@ Result SsaSimulator::run_internal(const TimeSpec ×_in, uint64_t seed, doubl int next_output = 1; long total_steps = 0; + // Issue #2018: the stop, asked of each row once it is recorded, as the + // result holds it (a resized compartment's observables re-read by + // relive_row included), at the time the row reports. Where it holds, that + // row is the run's last: n_out comes down to it, and every loop below + // ends as it does at the last row. + bool stop_met = false; + const std::vector t_reported = + (stop && origin != 0.0) ? times_in.output_times() : std::vector(); + auto ask_stop = [&]() { + if (!stop || stop_met) + return; + const int k = next_output - 1; + const double tk = origin != 0.0 ? t_reported[k] : t_out[k]; + const double *xs = result.species_data().data() + static_cast(k) * ns; + const double *os = n_obs > 0 ? result.observable_data().data() + + static_cast(k) * n_obs + : obs_buf.data(); + if (stop(k, tk, xs, ns, os, n_obs, false)) { + stop_met = true; + n_out = next_output; + } + }; + ask_stop(); + // Times at which a rate or a trigger may jump: those the caller resolved // (set_breakpoints, from the model's time conditions) and the knots of every // time-indexed table function, whose value or slope breaks there. Sorted and @@ -2675,6 +2703,7 @@ Result SsaSimulator::run_internal(const TimeSpec ×_in, uint64_t seed, doubl if (live_tags) relive_row(next_output, t_out[next_output], conc.data()); ++next_output; + ask_stop(); } break; } @@ -2716,6 +2745,7 @@ Result SsaSimulator::run_internal(const TimeSpec ×_in, uint64_t seed, doubl if (live_tags) relive_row(next_output, t_out[next_output], conc.data()); ++next_output; + ask_stop(); } if (next_output >= n_out) break; @@ -3107,6 +3137,7 @@ Result SsaSimulator::run_internal(const TimeSpec ×_in, uint64_t seed, doubl if (live_tags) relive_row(next_output, tk, conc.data()); ++next_output; + ask_stop(); }; // The triggers the panel's probe watches: with rate rules any trigger @@ -3169,7 +3200,7 @@ Result SsaSimulator::run_internal(const TimeSpec ×_in, uint64_t seed, doubl constexpr long MAX_TINY_PANELS = 1000000; long tiny_panels = 0; - while (t < times.t_end) { + while (t < times.t_end && !stop_met) { if (budget.active() && ++steps_since_timeout_check >= TIMEOUT_CHECK_STRIDE) { budget.check(); steps_since_timeout_check = 0; @@ -3614,6 +3645,15 @@ Result SsaSimulator::run_internal(const TimeSpec ×_in, uint64_t seed, doubl break; record_at(tk, (tk - tp) / hh); } + if (stop_met) { + // The run ends at the row the stop held at, inside the panel: + // its state, which record_at loaded, is the one the model is + // left at (issue #2018). The diagnostics' integrals run to it. + bank_dyn((t_out[n_out - 1] - tp) / hh); + if (m > 0) + y = ytmp; + break; + } // The hazard to where the loop goes on from. A firing goes on from // th_cut, in the panel's θ, where the solve above put the hazard at // E: the static part is counted in θ too, as the solve counts it; @@ -3840,6 +3880,7 @@ Result SsaSimulator::run_internal(const TimeSpec ×_in, uint64_t seed, doubl if (live_tags) relive_row(next_output, t_out[next_output], conc.data()); ++next_output; + ask_stop(); } if (next_output >= n_out) break; @@ -3872,6 +3913,7 @@ Result SsaSimulator::run_internal(const TimeSpec ×_in, uint64_t seed, doubl if (live_tags) relive_row(next_output, t_out[next_output], conc.data()); ++next_output; + ask_stop(); } if (next_output >= n_out) break; @@ -3907,6 +3949,7 @@ Result SsaSimulator::run_internal(const TimeSpec ×_in, uint64_t seed, doubl if (live_tags) relive_row(next_output, t_out[next_output], conc.data()); ++next_output; + ask_stop(); } break; } @@ -3978,6 +4021,7 @@ Result SsaSimulator::run_internal(const TimeSpec ×_in, uint64_t seed, doubl if (live_tags) relive_row(next_output, t_out[next_output], conc.data()); ++next_output; + ask_stop(); } if (next_output >= n_out) @@ -4035,14 +4079,27 @@ Result SsaSimulator::run_internal(const TimeSpec ×_in, uint64_t seed, doubl recompute_all_propensities(); } + // A stop ends the result at its row (issue #2018). + if (stop_met && n_out < result.n_times()) + result.truncate(n_out); + // ─── Write final state back to model ───────────────────────────────────── // // The discrete loop ends at the last firing it took, somewhere before t_end; // nothing fires in (t, t_end], so every count is already its t_end value. The // continuous loop runs to t_end itself, rate-rule targets and the events // they trigger included (issues #718, #751). - if (t < times.t_end) + // + // A stop ends the run at its row, whose state the counts hold: no firing + // was taken past it (issue #2018). + if (stop_met) + t = t_out[n_out - 1]; + else if (t < times.t_end) t = times.t_end; + // The time the last row reports, which the next run continues from. + const double t_last_abs = stop_met && origin != 0.0 ? t_reported[n_out - 1] + : t == times.t_end ? times_in.t_end + : origin + t; { auto &species = const_cast &>(model.species()); for (int i = 0; i < ns; ++i) { @@ -4063,12 +4120,12 @@ Result SsaSimulator::run_internal(const TimeSpec ×_in, uint64_t seed, doubl model.clear_pending_sens_seed(); // t_end itself: the next run continues from the time the last row // reports (issue #693). - model.set_current_time(t == times.t_end ? times_in.t_end : origin + t); + model.set_current_time(t_last_abs); // ...and the event state that goes with it (issue #693), with the // executions still waiting (issue #526). NetworkModel::EventCarry carry; carry.valid = true; - carry.t = t == times.t_end ? times_in.t_end : origin + t; + carry.t = t_last_abs; carry.trigger.assign(trigger_was_true.begin(), trigger_was_true.end()); for (auto &pe : pending) carry.pending.push_back(NetworkModel::CarriedEventExecution{ From 279ba08032de8934d85357a52bc1c3cc35359793 Mon Sep 17 00:00:00 2001 From: Bill Hlavacek Date: Thu, 3 Dec 2026 16:19:54 -0700 Subject: [PATCH 03/11] Stop conditions end the run where they hold: tests, docs, a root on an output (#2018) A strict condition whose root CVODE landed on an output time exactly was not met there, and the warm path asked CVODE for the same output again, which returned the same root, for ever; the cold path skipped it and ended at the next output. A root on the output is now the output's row, and the time a few roundings past it stands in for the row up to the next output. New tests in test_stop_condition_during_the_run.py (34 of 53 fail on main; the rest are controls). Docs, CLI help, the add_stop_condition docstring and the stubs say where a run ends. --- changelog.d/2018.fixed.md | 1 + docs/reference/api.md | 2 +- docs/reference/command-line.md | 2 +- docs/user-guide/simulation.md | 27 +- python/bngsim/_bngsim_core.pyi | 26 +- python/bngsim/_cli.py | 9 +- python/bngsim/_simulator.py | 50 +- .../test_stop_condition_during_the_run.py | 466 ++++++++++++++++++ ...t_stop_condition_reads_only_what_it_can.py | 3 +- .../test_stop_condition_result_fields.py | 5 +- src/_bngsim_core.cpp | 33 +- src/cvode_simulator.cpp | 32 +- src/ssa_simulator.cpp | 11 +- 13 files changed, 599 insertions(+), 68 deletions(-) create mode 100644 changelog.d/2018.fixed.md create mode 100644 python/tests/test_stop_condition_during_the_run.py diff --git a/changelog.d/2018.fixed.md b/changelog.d/2018.fixed.md new file mode 100644 index 000000000..dea386126 --- /dev/null +++ b/changelog.d/2018.fixed.md @@ -0,0 +1 @@ +- **A stop condition now ends the run where it holds; it was asked only after the run had gone to its end.** `A' = A²` from A = 1 passes 10 at t = 0.9 and blows up at t = 1: with `add_stop_condition("Atot > 10")` over (0, 2) the run raised `SimulationError`, and now returns `StopConditionMet` at t = 0.9 (0.8999993). An ODE, SSA or PSA run asks an expression condition at each sample and ends at the first it holds at; an ODE run ends where a comparison (`<`, `<=`, `>`, `>=`) or a number starts to hold, at the crossing, not the next sample. The model is left at the stop, with `current_time` its time, where it was left at the span's end. A long span met early costs the short run: an SSA run of A → 2A to `Atot > 1e4` over (0, 30) ran to its timeout, and ends at t ≈ 7. The first sample any condition holds at ends the run, named by the first condition added that holds there. A callable, a condition on a species reported after the run, and a network-free run are still asked of the whole run. A condition never met gives the same run, bit for bit. diff --git a/docs/reference/api.md b/docs/reference/api.md index 1ecaa01f1..5af9b0b1d 100644 --- a/docs/reference/api.md +++ b/docs/reference/api.md @@ -108,7 +108,7 @@ Interactive: - **`set_time(t)`** — Set `current_time` (finite, else `ValueError`); the next `run_until` integrates from there Stop conditions: -- **`add_stop_condition(condition, *, label)`** — `str` expression or `callable`. `run` raises `StopConditionMet` with the result cut at the first sample a condition holds at; `run_batch`, `run_replicates` and `parameter_scan` return each row that meets one cut there, with `Result.stop_condition` set, and refuse `squeeze=True` while one is registered (issue #1369). An expression reads the observables, a species by its name with `(` and `)` written as `_`, and `t`/`time`; a name it cannot read, `^` or a tuple is refused with `ValueError` where it is added (issue #1509) +- **`add_stop_condition(condition, *, label)`** — `str` expression or `callable`. An ODE, SSA or PSA run asks an expression at each sample and ends at the first it holds at, the model left at that sample's state and time; an ODE run ends where a comparison (`lhs < rhs`, `<=`, `>`, `>=`) or a number starts to hold, at the crossing; a callable, an expression reading a species reported after the run (an assignment-rule target, a species in a compartment that resizes) and a network-free run are asked of the whole result, which is then cut (issue #2018). Where several hold at a sample, the one added first names it. `run` raises `StopConditionMet` with the result cut at the first sample a condition holds at; `run_batch`, `run_replicates` and `parameter_scan` return each row that meets one cut there, with `Result.stop_condition` set, and refuse `squeeze=True` while one is registered (issue #1369). An expression reads the observables, a species by its name with `(` and `)` written as `_`, and `t`/`time`; a name it cannot read, `^` or a tuple is refused with `ValueError` where it is added (issue #1509) - **`clear_stop_conditions()`** Steady-state (`method` ∈ `"integration"` (default), `"newton"`, `"kinsol"` alias): diff --git a/docs/reference/command-line.md b/docs/reference/command-line.md index 305087cd6..17e1f524f 100644 --- a/docs/reference/command-line.md +++ b/docs/reference/command-line.md @@ -182,7 +182,7 @@ bngsim steady-states model.xml --n-starts 200 --seed 1 --json bngsim run-bngl model.bngl --out runs/ --json ``` -- **`run-until`** registers each `--stop-when EXPR` (repeatable, checked in order; the expression reads the observables, a species as its name with `(` and `)` written `_`, and `t`) and runs from the model's initial state to `--t-end`. `run_until` integrates the whole span, then cuts the run at the first output point where a condition holds, so `--n-points` sets how finely the cut falls, and the whole span counts against `--timeout`. A condition met is the answer asked for, not an error: the command exits 0 and prints the cut run, as the `StopConditionMet` carries it, with `"stop_condition"` naming it (`null` when none held). It takes `--n-points` (default one per unit of time), `--seed`, `--rtol` and `--atol`, as `run_until` does, and no `--t-start`, `--sample-times` or `--steady-state`. Its `--method` is `ode`, `ssa` or `psa`, as for `run-batch` and `parameter-scan`: those calls run no network-free engine. +- **`run-until`** registers each `--stop-when EXPR` (repeatable, checked in order; the expression reads the observables, a species as its name with `(` and `)` written `_`, and `t`) and runs from the model's initial state to `--t-end`. The run ends at the first output point where a condition holds, where the first one added names it if several do; an ODE run ends where a comparison (`lhs < rhs`, `<=`, `>`, `>=`) starts to hold between two output points, at that time, and any other condition at the output point, so there `--n-points` sets how finely the stop falls. What runs counts against `--timeout` (issue #2018). A condition met is the answer asked for, not an error: the command exits 0 and prints the cut run, as the `StopConditionMet` carries it, with `"stop_condition"` naming it (`null` when none held). It takes `--n-points` (default one per unit of time), `--seed`, `--rtol` and `--atol`, as `run_until` does, and no `--t-start`, `--sample-times` or `--steady-state`. Its `--method` is `ode`, `ssa` or `psa`, as for `run-batch` and `parameter-scan`: those calls run no network-free engine. - **`run-batch`** runs once per row of `--params`, each from the initial state, and **`parameter-scan`** once per value of `--parameter` (`--par-scan-vals 1,2,5`, or all of `--par-min`, `--par-max` and `--n-scan-pts`, with `--log-scale` to space them geometrically; not both; `--no-reset-conc` starts each value where the last ended). Both print what `run --replicates` prints: the record and digest of the rows stacked (`Result.squeeze`), with `"seeds"` for a stochastic method, and for a scan `"parameter"` and `"values"`. `--out` takes `.npz` or `.h5`, one file for every row. They take no `--sample-times` or `--steady-state`: rows a steady state cuts at their own times do not stack, and `steady-state-batch` is the steady state per parameter set. A species `--set` before a scan is the state each value starts from, so a parameter that seeds another species still doses it; a scan of a parameter that seeds a species the `--set` holds is refused, since no value would move it. - **`--params ROWS`** is JSON, a list of `{name: value}` objects, or a `.json`, `.csv` or `.tsv` file: a header of names, then a row of numbers per set. A name the model does not have is a usage error, as in `--set`, and so is a name given twice in one row. A species `--set` becomes the initial state every row starts from, so it is refused beside a row whose parameters set a species' starting value: that row's dose would be dropped. - **`steady-state`** prints `{"model", "source", "call", "parameters", "result", "out", "set"}`: `source` is where the model came from (`Model.describe()["source"]`), `call` is the call's name and the keywords given, `parameters` the model's at the call, and `result` the solver's verdict (`converged`, `criterion`, `method_used`, `residual`, `newton_distance`, `continued_run_distance`, `root_stability`, the largest real part of the eigenvalues, the steps) and the values at the state returned: the observables, and with `--species` the species, the largest `--max-columns` of each (default 20), listed in the model's order. It takes `--method integration` or `newton` (the call's `method`, not the simulation method: a steady state is of the ODEs), `--criterion`, `--tol`, `--max-time`, `--max-steps`, `--rtol` and `--atol`. **It exits 7 when the solve did not converge**, with the same output on standard output: `converged` is `false`, and the values are where the solve stopped, which are not the steady state. diff --git a/docs/user-guide/simulation.md b/docs/user-guide/simulation.md index 1817c4a5a..4461c07de 100644 --- a/docs/user-guide/simulation.md +++ b/docs/user-guide/simulation.md @@ -248,12 +248,23 @@ except bngsim.StopConditionMet as e: partial = e.result # the result cut at the stop ``` -A condition is met at the first sample where it is true. It is checked on the -finished run, so it does not interrupt the solve. The run covers the whole -interval and leaves the model at its end. `e.result` is that run cut at the -first row where the condition held, and `sim.current_time` is the end of the -interval, not the stop time. A following `run_until` continues from the end of -the interval. +A condition is met at the first sample where it is true. An ODE, SSA or PSA +run asks an expression condition at each sample as it goes and ends at the +first one it holds at, so a long interval met early costs only the run to the +stop, and a model that would fail later stops before it fails. An ODE run also +finds where a comparison (`lhs < rhs`, `<=`, `>`, `>=`) or a number starts to +hold between two samples, and ends at that time: here `e.result.time[-1]` is +where `Bound_hot` falls through 10000, not the sample after it. `e.result` +ends at the stop, the model is left at its state, and `sim.current_time` is its +time, so a following `run_until` continues from the stop. + +A callable is called with the whole result, so a run with one goes to the end +of the interval and is then cut, and leaves the model at the end. So does a +condition that reads a species whose reported value is set after the run (an +assignment rule's target, or a species in a compartment whose size changes), and +any condition on a network-free run. Where several conditions hold at the same +sample, the one added first names the stop; one added later that holds earlier +ends the run first. To continue from where a step started instead, take a snapshot first: @@ -297,8 +308,8 @@ propagates. `run_batch`, `run_replicates`, `parameter_scan` and `bifurcate` check every row and raise nothing when a condition is met. A row that meets one comes back cut there, next to the rows that ran to the end. `Result.stop_condition` names -the condition it met, or is `None`. Conditions are checked in the order they -were added, and the first one met cuts the row. An expression that raises at a +the condition it met, or is `None`. Each row ends as a `run` does, at the first +sample any condition holds at, named by the first one added that holds there. An expression that raises at a sample still raises `ValueError` from these calls. `squeeze=True` is refused while a condition is registered, since a cut row is diff --git a/python/bngsim/_bngsim_core.pyi b/python/bngsim/_bngsim_core.pyi index 805a7d1eb..dff80de25 100644 --- a/python/bngsim/_bngsim_core.pyi +++ b/python/bngsim/_bngsim_core.pyi @@ -564,11 +564,21 @@ class NetworkModel: Parameter names labeling the columns of pending_sensitivity_seed() (GH #210). """ @property + def public_observable_indices(self) -> list[int]: + """ + Issue #2018: the 0-based observables a result reports, in their order (the internal __bngsim_ ones left out). + """ + @property def rate_laws_read_clock(self) -> bool: """ Whether a reaction's rate reads the clock, through time, a time-indexed table, or a function or derived parameter that does; a rate accessor is not the clock (issue #961). A model whose rates read none has a steady state to solve for. """ @property + def reported_species_indices(self) -> list[int]: + """ + Issue #2018: the 0-based state entries a result reports as its species columns, in their order. + """ + @property def rhs_eval_count(self) -> int: """ Number of RHS (compute_derivs_core) evaluations so far. @@ -1073,6 +1083,14 @@ class SolverOptions: """ Parallel to set_state_switch_conditions: the 0-based reactions whose rate law reads each condition. The sensitivity jump reads what a crossing changes from these reactions' flux alone, so no other species can hide or fake a jump (issue #763). A condition with no entry is judged over the whole right-hand side, as before; an empty entry means no listed rate law reads it, so the crossing is continuous. A jump the listed reactions do not account for is judged as before. """ + def set_stop_check(self, fn: typing.Any, species_columns: collections.abc.Sequence[typing.SupportsInt | typing.SupportsIndex], observable_columns: collections.abc.Sequence[typing.SupportsInt | typing.SupportsIndex]) -> None: + """ + Issue #2018: fn(row, t, state, observables, at_root) -> bool, asked at each row the run records, and at each stop root, with copies of the state entries and observables at the columns named. True ends the run on that row. None clears it. + """ + def set_stop_roots(self, roots: collections.abc.Sequence[collections.abc.Sequence[tuple[typing.SupportsInt | typing.SupportsIndex, typing.SupportsInt | typing.SupportsIndex, typing.SupportsFloat | typing.SupportsIndex]]]) -> None: + """ + Issue #2018: the stop conditions' root functions, each a list of (kind, index, value) operations on a stack (bngsim._stop_in_run); CVODE finds where each changes sign, and the stop check decides there. Needs a stop check. + """ def set_switch_pinned_params(self, param_idx0: collections.abc.Sequence[typing.SupportsInt | typing.SupportsIndex]) -> None: """ Hold these parameters (0-based indices) at their nominal value against CVODES' internal finite-difference sensitivity probe (issue #48). A switch-time parameter enters the RHS only through an `if()` condition, so ∂f/∂p is 0 in every branch interior — but an FD probe of it MOVES the switch, dragging the kink into the approach to the crossing and stalling the solver at mxstep. Pinning returns the correct (zero) source term and leaves the switch where the model puts it. Set only for parameters bngsim._switch_sensitivity has verified appear solely in conditions. @@ -1317,15 +1335,15 @@ class SsaSimulator: """ Create a stochastic simulator (SSA/PSA) for the given model """ - def run(self, times: TimeSpec, seed: typing.SupportsInt | typing.SupportsIndex = 42, timeout_seconds: typing.SupportsFloat | typing.SupportsIndex = 0.0) -> ResultCore: + def run(self, times: TimeSpec, seed: typing.SupportsInt | typing.SupportsIndex = 42, timeout_seconds: typing.SupportsFloat | typing.SupportsIndex = 0.0, stop: typing.Any = None, stop_species_columns: collections.abc.Sequence[typing.SupportsInt | typing.SupportsIndex] = [], stop_observable_columns: collections.abc.Sequence[typing.SupportsInt | typing.SupportsIndex] = []) -> ResultCore: """ - Run exact SSA simulation with deterministic seed (releases GIL). timeout_seconds > 0 enables a wall-clock budget; on overrun, raises bngsim.SimulationTimeout. + Run exact SSA simulation with deterministic seed (releases GIL). timeout_seconds > 0 enables a wall-clock budget; on overrun, raises bngsim.SimulationTimeout. stop (issue #2018), when given, is called as stop(row, t, species, observables, at_root) at each row recorded, with the stop_species_columns of the state and the stop_observable_columns of the observables; where it returns True the run ends at that row. """ - def run_psa(self, times: TimeSpec, seed: typing.SupportsInt | typing.SupportsIndex = 42, poplevel: typing.SupportsFloat | typing.SupportsIndex = 100.0, timeout_seconds: typing.SupportsFloat | typing.SupportsIndex = 0.0) -> ResultCore: + def run_psa(self, times: TimeSpec, seed: typing.SupportsInt | typing.SupportsIndex = 42, poplevel: typing.SupportsFloat | typing.SupportsIndex = 100.0, timeout_seconds: typing.SupportsFloat | typing.SupportsIndex = 0.0, stop: typing.Any = None, stop_species_columns: collections.abc.Sequence[typing.SupportsInt | typing.SupportsIndex] = [], stop_observable_columns: collections.abc.Sequence[typing.SupportsInt | typing.SupportsIndex] = []) -> ResultCore: """ Run PSA (Partial Scaling Algorithm) simulation. Lin, Feng, Hlavacek, J. Chem. Phys. 150, 244101 (2019). - poplevel = N_c (critical population size, must be > 1). Releases GIL. timeout_seconds > 0 enables a wall-clock budget; on overrun, raises bngsim.SimulationTimeout. + poplevel = N_c (critical population size, must be > 1). Releases GIL. timeout_seconds > 0 enables a wall-clock budget; on overrun, raises bngsim.SimulationTimeout. stop, stop_species_columns and stop_observable_columns as for run(). """ def set_breakpoints(self, times: collections.abc.Sequence[typing.SupportsFloat | typing.SupportsIndex]) -> None: """ diff --git a/python/bngsim/_cli.py b/python/bngsim/_cli.py index 6af64968e..76bb28e65 100644 --- a/python/bngsim/_cli.py +++ b/python/bngsim/_cli.py @@ -634,10 +634,11 @@ def _add_run_calls(sub: Any, common: argparse.ArgumentParser) -> None: help="run a model to a time, cut where a condition holds (Simulator.run_until)", description="Run a model from its initial state to --t-end " "(Simulator.add_stop_condition, then Simulator.run_until(T)), and print the " - "run's record and a digest of its values. The run goes to --t-end, and is then " - "cut at the first output point where a --stop-when condition holds: a " - "condition met is an answer, not an error, exit 0, with `stop_condition` " - "naming it. The whole span counts against --timeout.", + "run's record and a digest of its values. The run ends at the first output " + "point where a --stop-when condition holds, and an ODE run where a comparison " + "starts to hold between two of them: a condition met is an answer, not an " + "error, exit 0, with `stop_condition` naming it. What runs counts against " + "--timeout.", ) _model_arguments(until) _engine_arguments(until, xml=False) diff --git a/python/bngsim/_simulator.py b/python/bngsim/_simulator.py index 005b901ad..7fa76b153 100644 --- a/python/bngsim/_simulator.py +++ b/python/bngsim/_simulator.py @@ -8905,9 +8905,10 @@ def point_starts() -> list[np.ndarray]: ) from None except StopConditionMet as stop: # One point's stop is not the scan's (issue #1369): the point - # comes back cut, as a run_batch row does. run() integrated the - # whole span and left the model at its end, so a continuation - # point (reset_conc=False) starts from there, as it would have. + # comes back cut, as a run_batch row does. run() left the model + # where the run ended, at the stop where it asked the condition + # as it went (issue #2018), else at the span's end, so a + # continuation point (reset_conc=False) starts from there. if not isinstance(stop.result, Result): # pragma: no cover raise result = stop.result @@ -12579,7 +12580,7 @@ def add_stop_condition( *, label: str = "", ) -> None: - """Add a stop condition checked after each simulation. + """Add a stop condition, which ends a simulation where it holds. Parameters ---------- @@ -12594,8 +12595,8 @@ def add_stop_condition( NaN is not met, and one RuntimeWarning names it (issue #1556). Example: ``"A_tot < 10"`` - **callable**: A function ``f(result) -> bool`` called - after the simulation. If it returns a true value (in - Python's sense), the stop condition is triggered. + after the simulation, with its whole result. If it returns a + true value (in Python's sense), the stop condition is triggered. label : str Human-readable label for the condition. @@ -12614,19 +12615,38 @@ def add_stop_condition( Notes ----- - A result that meets a condition is cut at the first sample it holds - at, and :attr:`Result.stop_condition` names the condition (its label, + An ODE, SSA or PSA run asks an expression condition at each sample + it records, and ends at the first one it holds at: the result ends + there, and the model is left at that sample's state, with + :attr:`current_time` its time. An ODE run also ends where a condition + of the form ``lhs < rhs`` (or ``<=``, ``>``, ``>=``), or a number, + starts to hold between two samples, over arithmetic of what it + reads: the crossing is found as an event's trigger is, and the + result's last row is at its time (issue #2018). A long span met early + costs the short run, and a model that fails after the condition holds + stops before it fails. + + A callable, a condition that reads a species whose reported value is + set after the run (an assignment rule's target, a species in a + compartment whose size changes), and a network-free run's + conditions are asked of the whole result instead: that run goes to + its end, the model is left there, and the result is cut at the first + sample a condition holds at. + + A result that meets a condition is cut at the first sample any + condition holds at; where several hold there, the one added first + names it, so a condition added later that holds earlier ends the + run. :attr:`Result.stop_condition` names the condition (its label, else its expression). :meth:`run` raises :class:`StopConditionMet` with that result. :meth:`run_batch`, :meth:`run_replicates` and - :meth:`parameter_scan` (and so :meth:`bifurcate`) check every row the + :meth:`parameter_scan` (and so :meth:`bifurcate`) end every row the same way and return the cut rows in their list, beside the rest, raising nothing; they refuse ``squeeze=True`` while a condition is - registered (issue #1369). Conditions are checked in the order they - were added, and the first one met cuts the row where it first holds, - even where a condition added later held earlier. A callable - is met at the last sample, so the row it cuts keeps every sample. A cut - result carries the reported blocks only, as the one :meth:`run` raises - with always has: :attr:`Result.state` refuses on it. + registered (issue #1369). A callable is met at the last sample, so + the row it cuts keeps every sample, and is called only where no + condition added before it is met. A cut result carries the reported + blocks only, as the one :meth:`run` raises with always has: + :attr:`Result.state` refuses on it. Examples -------- diff --git a/python/tests/test_stop_condition_during_the_run.py b/python/tests/test_stop_condition_during_the_run.py new file mode 100644 index 000000000..24b80457b --- /dev/null +++ b/python/tests/test_stop_condition_during_the_run.py @@ -0,0 +1,466 @@ +"""A stop condition ends the run where it holds (issue #2018). + +A condition used to be asked of the result once the run had gone to its end +time. So a run that failed after the condition held failed: ``A' = A**2`` from +A = 1 passes 10 at t = 0.9 and blows up at t = 1, and with ``Atot > 10`` over +(0, 2) the run raised ``SimulationError`` at t = 1. A long span was integrated +in full, and the stop time was the first sample past the crossing. + +An ODE, SSA or PSA run now asks an expression condition at each sample it +records and ends at the first one it holds at, the model left there; an ODE run +finds where a comparison starts to hold between two samples and ends at that +time. A condition never met gives the run it gave before, to the bit. +""" + +from __future__ import annotations + +import math +import time +from pathlib import Path + +import bngsim +import numpy as np +import pytest +from bngsim import StopConditionMet + +BLOW = """begin parameters + 1 k 1.0 +end parameters +begin species + 1 A() 1 +end species +begin reactions + 1 1,1 1,1,1 k +end reactions +begin groups + 1 Atot 1 +end groups +""" + +DECAY = """begin parameters + 1 k 0.1 +end parameters +begin species + 1 A() 100 +end species +begin reactions + 1 1 0 k +end reactions +begin groups + 1 A_tot 1 +end groups +""" + +# A -> 2A at rate 1 from 10: the population grows as 10 e^t, and an SSA run +# over (0, 30) takes about 10 e^30 firings. +GROW = """begin parameters + 1 k 1.0 +end parameters +begin species + 1 A() 10 +end species +begin reactions + 1 1 1,1 k +end reactions +begin groups + 1 Atot 1 +end groups +""" + +# 0 -> A at rate 1: A = t exactly, which an ODE run lands on to the bit. +LINEAR = """begin parameters + 1 k 1.0 +end parameters +begin species + 1 A() 0 +end species +begin reactions + 1 0 1 k +end reactions +begin groups + 1 A_tot 1 +end groups +""" + +# Lotka-Volterra around (10, 10), period about 2 pi: every unit of time costs +# steps, so a long span costs in proportion. +CYCLE = """begin parameters + 1 a 1.0 + 2 b 0.1 + 3 c 1.0 +end parameters +begin species + 1 X() 10 + 2 Y() 5 +end species +begin reactions + 1 1 1,1 a + 2 1,2 2,2 b + 3 2 0 c +end reactions +begin groups + 1 Xtot 1 + 2 Ytot 2 +end groups +""" + +HALF_AT = math.log(2.0) / 0.1 # where the decay's A_tot = 50 +TENTH_AT = math.log(10.0) / 0.1 # where it is 10 + + +@pytest.fixture +def nets(tmp_path: Path) -> dict[str, str]: + out = {} + for name, text in { + "blow": BLOW, + "decay": DECAY, + "grow": GROW, + "linear": LINEAR, + "cycle": CYCLE, + }.items(): + path = tmp_path / f"{name}.net" + path.write_text(text) + out[name] = str(path) + return out + + +def _sim(net: str, method: str = "ode", *conditions: str, **kw) -> bngsim.Simulator: + sim = bngsim.Simulator(bngsim.Model.from_net(net), method=method, **kw) + for c in conditions: + sim.add_stop_condition(c) + return sim + + +def _stop(sim: bngsim.Simulator, **kw) -> StopConditionMet: + with pytest.raises(StopConditionMet) as met: + sim.run(**kw) + return met.value + + +# ── The issue's model ──────────────────────────────────────────────────────── + + +def test_a_blow_up_past_the_condition_stops_at_the_crossing(nets): + """A = 1/(1 - t) is 10 at t = 0.9 and infinite at t = 1: the run ends at 0.9.""" + met = _stop(_sim(nets["blow"], "ode", "Atot > 10"), t_span=(0, 2), n_points=201) + r = met.result + assert r.stop_condition == "Atot > 10" + assert r.time[-1] == pytest.approx(0.9, abs=1e-5) + assert r.observables["Atot"][-1] > 10.0 + assert r.observables["Atot"][-1] == pytest.approx(10.0, rel=1e-5) + # The samples before it are the grid's, to 0.89. + np.testing.assert_array_equal(r.time[:-1], np.linspace(0, 2, 201)[:90]) + + +def test_a_condition_with_no_crossing_ends_at_the_first_sample_past_it(nets): + """A conjunction is not one the run can find the crossing of: it is asked at + the samples, and A = 9.5 at t = 0.8947 ends the run at the sample t = 0.90.""" + met = _stop(_sim(nets["blow"], "ode", "Atot > 9.5 and t > 0"), t_span=(0, 2), n_points=201) + assert met.result.time[-1] == pytest.approx(0.90, abs=1e-12) + assert len(met.result.time) == 91 + + +def test_a_crossing_at_a_time_ends_there_before_the_blow_up(nets): + """t > 0.55 changes sign at 0.55 exactly, where the run lands on it and it + does not hold yet: the run ends a few roundings past it.""" + met = _stop(_sim(nets["blow"], "ode", "t > 0.55"), t_span=(0, 2), n_points=21) + assert 0.55 < met.result.time[-1] < 0.55 + 1e-12 + + +# ── Where it ends ──────────────────────────────────────────────────────────── + + +@pytest.mark.parametrize("warm", ["1", "0"]) +@pytest.mark.parametrize("n_points", [8, 21]) +@pytest.mark.parametrize( + "condition, strict", + [("A_tot > 5", True), ("A_tot >= 5", False), ("5 < A_tot", True), ("A_tot - 5", True)], +) +def test_a_crossing_the_run_lands_on_exactly_is_still_met( + nets, monkeypatch, condition, strict, n_points, warm +): + """A = t exactly, so A - 5 is 0 at a root CVODE lands on, where a strict + condition does not hold yet and no further root follows: the run ends just + past it, a non-strict one there. It was the first sample past, 5.71 or 5.5. + + With 21 points the root is on the output at 5.0, where CVODE asked for the + same output again returns the same root: the warm path went round that for + ever, and the cold one skipped the root and ended at 5.5. Control for + ``A_tot >= 5`` with 21 points: it holds at that output, and main ended there.""" + if warm == "0": + monkeypatch.setenv("BNGSIM_NO_WARM_CVODE", "1") + met = _stop(_sim(nets["linear"], "ode", condition), t_span=(0, 10), n_points=n_points) + t_stop = met.result.time[-1] + assert 5.0 <= t_stop < 5.0 + 1e-9 + a = met.result.observables["A_tot"][-1] + assert a > 5.0 if strict else a >= 5.0 + + +@pytest.mark.parametrize("warm", ["1", "0"]) +def test_a_root_on_the_last_output_ends_the_run_there(nets, monkeypatch, warm): + """A strict condition whose root is the span's last output is not met in + the span: the run is the one without it, and it ends (the warm path went + round the root for ever). Control: main ran it whole.""" + if warm == "0": + monkeypatch.setenv("BNGSIM_NO_WARM_CVODE", "1") + plain = _sim(nets["linear"]).run(t_span=(0, 5), n_points=11) + got = _sim(nets["linear"], "ode", "A_tot > 5").run(t_span=(0, 5), n_points=11) + assert got.stop_condition is None + np.testing.assert_array_equal(got.time, plain.time) + np.testing.assert_array_equal(got.species, plain.species) + + +def test_a_long_span_met_early_costs_the_short_run(nets): + """A Lotka-Volterra cycle over (0, 1e4) met at t = 5 takes the steps a run to + 5 takes, not the 1e4 of cycles after it.""" + short = _sim(nets["cycle"]).run(t_span=(0, 5), n_points=6) + met = _stop( + _sim(nets["cycle"], "ode", "t > 5"), t_span=(0, 1e4), n_points=101, max_steps=10**7 + ) + assert 5.0 < met.result.time[-1] < 5.0 + 1e-9 + steps = met.result.solver_stats["n_steps"] + assert steps <= short.solver_stats["n_steps"] + 2 + + +def test_the_model_and_the_clock_are_left_at_the_stop(nets): + sim = _sim(nets["decay"], "ode", "A_tot < 50") + met = _stop(sim, t_span=(0, 100), n_points=101) + assert met.result.time[-1] == pytest.approx(HALF_AT, rel=1e-6) + assert sim.current_time == met.result.time[-1] + assert sim.model.get_state()[0] == met.result.species[-1, 0] + sim.clear_stop_conditions() + after = sim.run_until(20.0, n_points=3) + assert after.time[0] == met.result.time[-1] + assert after.species[0, 0] == met.result.species[-1, 0] + + +def test_the_first_row_any_condition_holds_at_ends_the_run(nets): + """Row by row: A_tot < 50 is added second and holds first, so it ends the run. + It used to be the first one added that held anywhere, A_tot < 10 at t = 24.""" + met = _stop(_sim(nets["decay"], "ode", "A_tot < 10", "A_tot < 50"), t_span=(0, 100)) + assert met.condition == "A_tot < 50" + assert met.result.time[-1] == pytest.approx(HALF_AT, rel=1e-6) + + +def test_where_two_hold_at_one_row_the_first_added_names_it(nets): + """Control. Both hold first at t = 24.""" + met = _stop( + _sim(nets["decay"], "ode", "A_tot < 10 and t > 0", "A_tot < 9.5 or A_tot < 10"), + t_span=(0, 100), + n_points=101, + ) + assert met.condition == "A_tot < 10 and t > 0" + assert met.result.time[-1] == 24.0 + + +def test_a_callable_is_asked_of_the_result_the_run_ends_with(nets): + """A callable added first is called with the result an expression ended, + met at its last row, which is the expression's too: the first added names it.""" + seen = [] + + def low(r): + seen.append(float(r.time[-1])) + return True + + sim = _sim(nets["decay"], "ode") + sim.add_stop_condition(low, label="callable") + sim.add_stop_condition("A_tot < 50") + met = _stop(sim, t_span=(0, 100), n_points=101) + assert met.condition == "callable" + assert seen == [met.result.time[-1]] + assert met.result.time[-1] == pytest.approx(HALF_AT, rel=1e-6) + + +def test_sample_times_end_at_the_crossing_between_two_of_them(nets): + """The rows reported are 5, 10 and 30; A_tot = 50 at 6.93, between 5 and 10.""" + met = _stop( + _sim(nets["decay"], "ode", "A_tot < 50"), t_span=(0, 30), sample_times=[5.0, 10.0, 30.0] + ) + assert met.result.time[0] == 5.0 + assert met.result.time[-1] == pytest.approx(HALF_AT, rel=1e-6) + assert len(met.result.time) == 2 + + +def test_a_row_sample_times_do_not_report_is_not_asked(nets): + """Control. A_tot > 50 holds from t = 0, which the run starts at but does not + report, to 6.93; it holds at the first row reported, t = 5, and there only.""" + met = _stop( + _sim(nets["decay"], "ode", "A_tot > 50"), t_span=(0, 30), sample_times=[5.0, 10.0, 30.0] + ) + np.testing.assert_array_equal(met.result.time, [5.0]) + + +@pytest.mark.parametrize("warm", ["0", "1"]) +def test_a_later_leg_ends_at_its_crossing(nets, monkeypatch, warm): + """The second leg of run_until, on the warm path and the cold one.""" + if warm == "0": + monkeypatch.setenv("BNGSIM_NO_WARM_CVODE", "1") + sim = _sim(nets["decay"]) + sim.run_until(5.0, n_points=6) + sim.add_stop_condition("A_tot < 10") + with pytest.raises(StopConditionMet) as met: + sim.run_until(100.0, n_points=96) + assert met.value.result.time[0] == 5.0 + assert met.value.result.time[-1] == pytest.approx(TENTH_AT, rel=1e-6) + assert sim.current_time == met.value.result.time[-1] + + +def test_a_start_far_from_zero_ends_at_its_crossing(nets): + """From t = 1e12 the run keeps its own clock; the crossing is reported on the + caller's, 1e12 + 6.93, and the clock is left there.""" + t0 = 1e12 + sim = _sim(nets["decay"], "ode", "A_tot < 50") + met = _stop(sim, t_span=(t0, t0 + 100), n_points=101) + assert met.result.time[-1] - t0 == pytest.approx(HALF_AT, abs=1e-3) + assert sim.current_time == met.result.time[-1] + + +def test_a_sensitivity_run_ends_at_the_crossing_with_its_sensitivity(nets): + """dA/dk = -t A, -6.93 * 50 at the crossing.""" + met = _stop( + _sim(nets["decay"], "ode", "A_tot < 50", sensitivity_params=["k"]), + t_span=(0, 100), + n_points=101, + ) + assert met.result.time[-1] == pytest.approx(HALF_AT, rel=1e-6) + assert met.result.sensitivities[-1].ravel()[0] == pytest.approx(-HALF_AT * 50.0, rel=1e-5) + + +# ── Stochastic runs ────────────────────────────────────────────────────────── + + +def test_an_ssa_run_past_its_condition_ends_where_it_holds(nets): + """10 e^t passes 1e4 near t = 6.9; the run over (0, 30) used to go on to its + timeout, ~10 e^30 firings away.""" + began = time.perf_counter() + met = _stop( + _sim(nets["grow"], "ssa", "Atot > 1e4"), t_span=(0, 30), n_points=301, seed=1, timeout=10 + ) + assert time.perf_counter() - began < 10 + obs = met.result.observables["Atot"] + assert obs[-1] > 1e4 >= obs[-2] + assert 5.0 < met.result.time[-1] < 9.0 + + +@pytest.mark.parametrize("method", ["ssa", "psa"]) +def test_a_stochastic_run_ends_on_the_whole_runs_row_and_stays_there(nets, method): + """The rows up to the stop are the whole run's, to the bit, and the model is + left at the last one's state and time.""" + kw = {"poplevel": 10} if method == "psa" else {} + run = dict(t_span=(0, 100), n_points=101, seed=7) + full = _sim(nets["decay"], method, **kw).run(**run) + sim = _sim(nets["decay"], method, "A_tot < 10", **kw) + met = _stop(sim, **run) + n = len(met.result.time) + first = int(np.argmax(np.asarray(full.observables["A_tot"]) < 10)) + assert n == first + 1 < len(full.time) + np.testing.assert_array_equal(met.result.species, full.species[:n]) + np.testing.assert_array_equal(met.result.time, full.time[:n]) + assert sim.current_time == met.result.time[-1] + assert sim.model.get_state()[0] == met.result.species[-1, 0] + + +def test_replicates_and_batch_rows_end_where_they_hold(nets): + run = dict(t_span=(0, 30), n_points=301, timeout=10) + reps = _sim(nets["grow"], "ssa", "Atot > 1e4").run_replicates(3, seed=1, **run) + assert all(r.stop_condition == "Atot > 1e4" and r.time[-1] < 10 for r in reps) + reps = _sim(nets["grow"], "ssa", "Atot > 1e4").run_replicates( + 3, seed=1, num_processors=2, **run + ) + assert all(r.stop_condition == "Atot > 1e4" and r.time[-1] < 10 for r in reps) + rows = _sim(nets["grow"], "ssa", "Atot > 1e4").run_batch(params=[{"k": 1.0}], seed=1, **run) + assert rows[0].stop_condition == "Atot > 1e4" and rows[0].time[-1] < 10 + rows = _sim(nets["blow"], "ode", "Atot > 10").run_batch( + params=[{"k": 1.0}, {"k": 0.25}], t_span=(0, 2), n_points=201 + ) + assert rows[0].time[-1] == pytest.approx(0.9, abs=1e-5) + # k = 0.25: A = 1/(1 - t/4) is 2 at t = 2, short of 10. + assert rows[1].stop_condition is None and rows[1].time[-1] == 2.0 + + +def test_a_parameter_scan_point_ends_at_its_crossing(nets): + rows = _sim(nets["blow"], "ode", "Atot > 10").parameter_scan( + "k", [1.0, 2.0], t_span=(0, 2), n_points=201 + ) + assert rows[0].time[-1] == pytest.approx(0.9, abs=1e-5) + # k = 2: A = 1/(1 - 2t) is 10 at t = 0.45. + assert rows[1].time[-1] == pytest.approx(0.45, abs=1e-5) + + +# ── A condition never met: the run it was, to the bit ──────────────────────── + + +def _same(a, b) -> bool: + return ( + np.array_equal(a.time, b.time) + and np.array_equal(a.species, b.species) + and np.array_equal(np.asarray(a.observables), np.asarray(b.observables)) + ) + + +@pytest.mark.parametrize( + "method, kw, run", + [ + ("ode", {}, {}), + ("ode", {"sensitivity_params": ["k"]}, {}), + ("ode", {}, {"t_span": (1e12, 1e12 + 100)}), + ("ode", {}, {"sample_times": [5.0, 10.0, 30.0]}), + ("ssa", {}, {"seed": 3}), + ("psa", {"poplevel": 10}, {"seed": 3}), + ], +) +@pytest.mark.parametrize("condition", ["A_tot < -1", "A_tot > 1e9 and t > 0"]) +def test_a_condition_never_met_gives_the_run_without_it(nets, method, kw, run, condition): + """Control. Asked at every row and at no crossing, the run is the one it was.""" + run = {"t_span": (0, 100), "n_points": 101, **run} + if "sample_times" in run: + run["t_span"] = (0, 30) + del run["n_points"] + want = _sim(nets["decay"], method, **kw).run(**run) + got = _sim(nets["decay"], method, condition, **kw).run(**run) + assert got.stop_condition is None + assert _same(got, want) + if "sensitivity_params" in kw: + np.testing.assert_array_equal(got.sensitivities, want.sensitivities) + + +def test_a_crossing_where_the_condition_does_not_hold_changes_nothing(nets): + """Control. A_tot > 50 holds from the start, which sample_times does not + report, and stops holding at 6.93: a root the run asks at, and goes on from.""" + run = {"t_span": (0, 30), "sample_times": [10.0, 20.0, 30.0]} + want = _sim(nets["decay"]).run(**run) + got = _sim(nets["decay"], "ode", "A_tot > 50").run(**run) + assert got.stop_condition is None + assert _same(got, want) + + +# ── What the engine asks and what the result says ──────────────────────────── + + +def test_a_stop_the_result_does_not_hold_is_a_bug_said_aloud(nets, monkeypatch): + """The engine ends a run where the check it is given says so; the result is + then asked again. Were the two to differ, the run would end with no + condition met: that is refused, not returned as a run that ended early.""" + from bngsim import _stop_in_run + + monkeypatch.setattr(_stop_in_run.InRunStops, "__call__", lambda self, row, *a: row == 3) + with pytest.raises(bngsim.BngsimError, match="issue #2018"): + _sim(nets["decay"], "ode", "A_tot < 10").run(t_span=(0, 100), n_points=101) + + +@pytest.mark.parametrize("method", ["ode", "ssa"]) +def test_an_interrupt_in_the_check_reaches_the_caller(nets, monkeypatch, method): + from bngsim import _stop_in_run + + def interrupt(self, row, *a): + if row == 3: + raise KeyboardInterrupt + return False + + monkeypatch.setattr(_stop_in_run.InRunStops, "__call__", interrupt) + sim = _sim(nets["decay"], method, "A_tot < 10") + before = sim.model.get_state().copy() + with pytest.raises(KeyboardInterrupt): + sim.run(t_span=(0, 100), n_points=101, seed=1) + assert sim.current_time == 0.0 + np.testing.assert_array_equal(sim.model.get_state(), before) diff --git a/python/tests/test_stop_condition_reads_only_what_it_can.py b/python/tests/test_stop_condition_reads_only_what_it_can.py index 4e49e9fa0..102ea8d00 100644 --- a/python/tests/test_stop_condition_reads_only_what_it_can.py +++ b/python/tests/test_stop_condition_reads_only_what_it_can.py @@ -14,11 +14,10 @@ from __future__ import annotations +import math import re from pathlib import Path -import math - import bngsim import pytest diff --git a/python/tests/test_stop_condition_result_fields.py b/python/tests/test_stop_condition_result_fields.py index 624172069..25d4b2d61 100644 --- a/python/tests/test_stop_condition_result_fields.py +++ b/python/tests/test_stop_condition_result_fields.py @@ -236,8 +236,9 @@ def test_a_run_the_stop_ends_is_the_whole_run_s_prefix(net, kw): assert np.array_equal( np.asarray(getattr(partial, block)), np.asarray(getattr(full, block))[:n] ) - assert partial.ssa_diagnostics["propensity_backend"] == ( - full.ssa_diagnostics["propensity_backend"] + assert ( + partial.ssa_diagnostics["propensity_backend"] + == (full.ssa_diagnostics["propensity_backend"]) ) return for block in ("time", "species", "observables", "sensitivities"): diff --git a/src/_bngsim_core.cpp b/src/_bngsim_core.cpp index 0650e9d2b..fc5b0d385 100644 --- a/src/_bngsim_core.cpp +++ b/src/_bngsim_core.cpp @@ -895,9 +895,9 @@ static bngsim::StopCheck make_stop_check(py::object fn, std::vector species py::gil_scoped_acquire acquire; delete p; }); - return [held, species_cols = std::move(species_cols), obs_cols = std::move(obs_cols)]( - int row, double t, const double *x, int n_x, const double *obs, int n_obs, - bool at_root) -> bool { + return [held, species_cols = std::move(species_cols), + obs_cols = std::move(obs_cols)](int row, double t, const double *x, int n_x, + const double *obs, int n_obs, bool at_root) -> bool { const auto pick = [](const std::vector &cols, const double *from, int n, const char *what) { py::array_t out(static_cast(cols.size())); @@ -3329,20 +3329,23 @@ PYBIND11_MODULE(_bngsim_core, m) { // observables it reports, in order, as ResultCore projects them. .def_property_readonly("reported_species_indices", [](const bngsim::NetworkModel &self) { - std::vector keep = self.reported_species_indices(); - if (keep.empty()) { - keep.resize(static_cast(self.n_species())); - for (std::size_t i = 0; i < keep.size(); ++i) { - keep[i] = i; - } - } - return keep; - }) + std::vector keep = self.reported_species_indices(); + if (keep.empty()) { + keep.resize(static_cast(self.n_species())); + for (std::size_t i = 0; i < keep.size(); ++i) { + keep[i] = i; + } + } + return keep; + }, + "Issue #2018: the 0-based state entries a result reports as " + "its species columns, in their order.") .def_property_readonly("public_observable_indices", [](const bngsim::NetworkModel &self) { - return bngsim::public_observable_indices( - self.observable_names()); - }) + return bngsim::public_observable_indices(self.observable_names()); + }, + "Issue #2018: the 0-based observables a result reports, in " + "their order (the internal __bngsim_ ones left out).") // Issue #74 — 0-based indices of the write-only accumulator species: a // product of some reaction, a reactant of none, read by no other diff --git a/src/cvode_simulator.cpp b/src/cvode_simulator.cpp index 18290e8d9..8a1723d6d 100644 --- a/src/cvode_simulator.cpp +++ b/src/cvode_simulator.cpp @@ -3896,17 +3896,20 @@ static int cvode_run_root_fn(sunrealtype t, N_Vector y, sunrealtype *gout, void // condition linear in the time (`t > 5`, a species made at a constant rate), // is where a strict one (`>`, `<`) is not yet met, and CVODE reports no root // as g leaves 0. It is asked a few roundings past the root, inside the step -// CVODE has taken and before the next output, which asks it in any case; +// CVODE has taken and before the row's output (t_row), which asks it in any +// case. A root on that output itself, which CVODE returns again each time it +// is asked for the same output, is the output's row, and the time past it +// stands in for the row up to the next output (t_after; none past the last); // NaN where there is no such time. -static double stop_root_past(void *cvode_mem, double t_root, double t_next_out) { +static double stop_root_past(void *cvode_mem, double t_root, double t_row, double t_after) { sunrealtype tn = 0.0; sunrealtype h = 0.0; CVodeGetCurrentTime(cvode_mem, &tn); CVodeGetLastStep(cvode_mem, &h); - const double t_past = - t_root + 16.0 * std::numeric_limits::epsilon() * - (std::fabs(t_root) + std::fabs(static_cast(h))); - if (t_past > t_root && t_past <= static_cast(tn) && t_past < t_next_out) { + const double t_past = t_root + 16.0 * std::numeric_limits::epsilon() * + (std::fabs(t_root) + std::fabs(static_cast(h))); + const double t_limit = t_root < t_row ? t_row : t_after; + if (t_past > t_root && t_past <= static_cast(tn) && t_past < t_limit) { return t_past; } return std::numeric_limits::quiet_NaN(); @@ -6454,7 +6457,8 @@ Result CvodeSimulator::Impl::run_warm(const TimeSpec ×, const SolverOptions const double t_root = static_cast(t_ret); bool met = ask(t_root); if (!met) { - const double t_past = stop_root_past(cvode_mem, t_root, t_out[i]); + const double t_past = stop_root_past(cvode_mem, t_root, t_out[i], + i + 1 < n_out ? t_out[i + 1] : t_out[i]); if (std::isfinite(t_past) && CVodeGetDky(cvode_mem, t_past, 0, w.y) == 0) { met = ask(t_past); if (met) { @@ -6469,6 +6473,13 @@ Result CvodeSimulator::Impl::run_warm(const TimeSpec ×, const SolverOptions stop_met = true; break; } + // A root on the output is the output's row, recorded and asked + // below: asked for the same output again, CVODE returns the + // same root, and the run went round that for ever. + if (!(t_root < t_out[i])) { + flag = CV_SUCCESS; + break; + } if (budget.active()) budget.check(); flag = CVode(cvode_mem, t_out[i], w.y, &t_ret, CV_NORMAL); @@ -23359,8 +23370,8 @@ Result CvodeSimulator::run(const TimeSpec ×, const SolverOptions &opts) { info[static_cast(r)] = 0; } // Of the model's roots: a stop root beside them is asked below. - only_held_left = std::all_of(info.begin(), info.begin() + n_roots, - [](int r) { return r == 0; }); + only_held_left = + std::all_of(info.begin(), info.begin() + n_roots, [](int r) { return r == 0; }); // On a stop's instant, the return CVODE makes without that root. if (only_held_left && ((stop_at_crossing && same_instant(static_cast(t_ret), t_crossing)) || @@ -23516,7 +23527,8 @@ Result CvodeSimulator::run(const TimeSpec ×, const SolverOptions &opts) { double t_stop = t_root; bool met = ask(t_root); if (!met) { - const double t_past = stop_root_past(cvode_mem, t_root, t_out[i]); + const double t_past = stop_root_past( + cvode_mem, t_root, t_out[i], i + 1 < n_out ? t_out[i + 1] : t_out[i]); if (std::isfinite(t_past) && CVodeGetDky(cvode_mem, t_past, 0, y) == 0) { met = ask(t_past); if (met) { diff --git a/src/ssa_simulator.cpp b/src/ssa_simulator.cpp index 6c73cb968..fa3f05811 100644 --- a/src/ssa_simulator.cpp +++ b/src/ssa_simulator.cpp @@ -601,9 +601,8 @@ Result SsaSimulator::run_psa(const TimeSpec ×, uint64_t seed, double poplev "PSA poplevel (N_c) must be > 1. Got " + std::to_string(poplevel) + ". For exact stochastic simulation, use run() instead of run_psa()."); } - return restoring_on_raise(impl_->model, [&] { - return run_internal(times, seed, poplevel, timeout_seconds, stop); - }); + return restoring_on_raise( + impl_->model, [&] { return run_internal(times, seed, poplevel, timeout_seconds, stop); }); } // ─── Unified SSA/PSA simulation loop ───────────────────────────────────────── @@ -2334,9 +2333,9 @@ Result SsaSimulator::run_internal(const TimeSpec ×_in, uint64_t seed, doubl const int k = next_output - 1; const double tk = origin != 0.0 ? t_reported[k] : t_out[k]; const double *xs = result.species_data().data() + static_cast(k) * ns; - const double *os = n_obs > 0 ? result.observable_data().data() + - static_cast(k) * n_obs - : obs_buf.data(); + const double *os = + n_obs > 0 ? result.observable_data().data() + static_cast(k) * n_obs + : obs_buf.data(); if (stop(k, tk, xs, ns, os, n_obs, false)) { stop_met = true; n_out = next_output; From 7c992e9f7dfbfd0dcdf5593dcfb6b2a97243f0f6 Mon Sep 17 00:00:00 2001 From: Bill Hlavacek Date: Thu, 3 Dec 2026 17:19:14 -0700 Subject: [PATCH 04/11] Stop conditions: rows a re-take rewrites, a far start's time, a screen (#2018) - A run whose rows a state-switch re-take can record again (an ODE run of a .net model with a state switch) asks its conditions of the result alone: a stop on a row the re-take later rewrote returned Y = 9.4e-134 where the run holds 0.0063. - A run integrated on the time since a start far from zero drops the stop roots that read the time and asks those conditions at its rows: the root there was quantized and CVODE failed with CV_ILL_INPUT at 1e12. - The engine decides a comparison it can compute as numpy does (no power of a column) without calling Python at each row; Python is asked where one may hold. A condition never met cost 2 us a row, 0.2 s over 1e5 rows. - Constants that read no column are folded as Python computes them. - The SSA run's clock write-back drops a branch that could not change it. - Tests for each, and for the rows before the first and after the last sample time, PSA integrals and rate-rule targets at a stop, a far-start stochastic clock, and the safety net on run_batch and run_replicates. --- changelog.d/2018.fixed.md | 2 +- docs/reference/api.md | 2 +- docs/user-guide/simulation.md | 11 +- include/bngsim/types.hpp | 3 - python/bngsim/_simulator.py | 15 +- python/bngsim/_stop_in_run.py | 106 ++++- .../test_stop_condition_during_the_run.py | 382 +++++++++++++++++- src/_bngsim_core.cpp | 117 +++++- src/cvode_simulator.cpp | 80 ++-- src/ssa_simulator.cpp | 9 +- 10 files changed, 646 insertions(+), 81 deletions(-) diff --git a/changelog.d/2018.fixed.md b/changelog.d/2018.fixed.md index dea386126..5fb707095 100644 --- a/changelog.d/2018.fixed.md +++ b/changelog.d/2018.fixed.md @@ -1 +1 @@ -- **A stop condition now ends the run where it holds; it was asked only after the run had gone to its end.** `A' = A²` from A = 1 passes 10 at t = 0.9 and blows up at t = 1: with `add_stop_condition("Atot > 10")` over (0, 2) the run raised `SimulationError`, and now returns `StopConditionMet` at t = 0.9 (0.8999993). An ODE, SSA or PSA run asks an expression condition at each sample and ends at the first it holds at; an ODE run ends where a comparison (`<`, `<=`, `>`, `>=`) or a number starts to hold, at the crossing, not the next sample. The model is left at the stop, with `current_time` its time, where it was left at the span's end. A long span met early costs the short run: an SSA run of A → 2A to `Atot > 1e4` over (0, 30) ran to its timeout, and ends at t ≈ 7. The first sample any condition holds at ends the run, named by the first condition added that holds there. A callable, a condition on a species reported after the run, and a network-free run are still asked of the whole run. A condition never met gives the same run, bit for bit. +- **A stop condition now ends the run where it holds; it was asked only after the run had gone to its end.** `A' = A²` from A = 1 passes 10 at t = 0.9 and blows up at t = 1: with `add_stop_condition("Atot > 10")` over (0, 2) the run raised `SimulationError`, and now returns `StopConditionMet` at t = 0.9 (0.8999993). An ODE, SSA or PSA run asks an expression condition at each sample and ends at the first it holds at; an ODE run ends where a comparison (`<`, `<=`, `>`, `>=`) or a number starts to hold, at the crossing, not the next sample. The model is left at the stop, with `current_time` its time, where it was left at the span's end. A long span met early costs the short run: an SSA run of A → 2A to `Atot > 1e4` over (0, 30) ran to its timeout, and ends at t ≈ 7. The first sample any condition holds at ends the run, named by the first condition added that holds there. A callable, a condition on a species reported after the run, a network-free run and a `.net` model whose rate law switches on its state are still asked of the whole run. A condition never met gives the same run, bit for bit. diff --git a/docs/reference/api.md b/docs/reference/api.md index 5af9b0b1d..0de3d042a 100644 --- a/docs/reference/api.md +++ b/docs/reference/api.md @@ -108,7 +108,7 @@ Interactive: - **`set_time(t)`** — Set `current_time` (finite, else `ValueError`); the next `run_until` integrates from there Stop conditions: -- **`add_stop_condition(condition, *, label)`** — `str` expression or `callable`. An ODE, SSA or PSA run asks an expression at each sample and ends at the first it holds at, the model left at that sample's state and time; an ODE run ends where a comparison (`lhs < rhs`, `<=`, `>`, `>=`) or a number starts to hold, at the crossing; a callable, an expression reading a species reported after the run (an assignment-rule target, a species in a compartment that resizes) and a network-free run are asked of the whole result, which is then cut (issue #2018). Where several hold at a sample, the one added first names it. `run` raises `StopConditionMet` with the result cut at the first sample a condition holds at; `run_batch`, `run_replicates` and `parameter_scan` return each row that meets one cut there, with `Result.stop_condition` set, and refuse `squeeze=True` while one is registered (issue #1369). An expression reads the observables, a species by its name with `(` and `)` written as `_`, and `t`/`time`; a name it cannot read, `^` or a tuple is refused with `ValueError` where it is added (issue #1509) +- **`add_stop_condition(condition, *, label)`** — `str` expression or `callable`. An ODE, SSA or PSA run asks an expression at each sample and ends at the first it holds at, the model left at that sample's state and time; an ODE run ends where a comparison (`lhs < rhs`, `<=`, `>`, `>=`) or a number starts to hold, at the crossing; a callable, an expression reading a species reported after the run (an assignment-rule target, a species in a compartment that resizes), a network-free run and an ODE run of a `.net` model whose rate law switches on its state (an `if` reading a species or an observable) are asked of the whole result, which is then cut (issue #2018). Where several hold at a sample, the one added first names it. `run` raises `StopConditionMet` with the result cut at the first sample a condition holds at; `run_batch`, `run_replicates` and `parameter_scan` return each row that meets one cut there, with `Result.stop_condition` set, and refuse `squeeze=True` while one is registered (issue #1369). An expression reads the observables, a species by its name with `(` and `)` written as `_`, and `t`/`time`; a name it cannot read, `^` or a tuple is refused with `ValueError` where it is added (issue #1509) - **`clear_stop_conditions()`** Steady-state (`method` ∈ `"integration"` (default), `"newton"`, `"kinsol"` alias): diff --git a/docs/user-guide/simulation.md b/docs/user-guide/simulation.md index 4461c07de..f78920574 100644 --- a/docs/user-guide/simulation.md +++ b/docs/user-guide/simulation.md @@ -254,15 +254,20 @@ first one it holds at, so a long interval met early costs only the run to the stop, and a model that would fail later stops before it fails. An ODE run also finds where a comparison (`lhs < rhs`, `<=`, `>`, `>=`) or a number starts to hold between two samples, and ends at that time: here `e.result.time[-1]` is -where `Bound_hot` falls through 10000, not the sample after it. `e.result` +where `Bound_hot` falls through 10000, not the sample after it. (A condition +that reads the time, in a run integrated on the time since a start far from +zero, is asked at the samples alone.) `e.result` ends at the stop, the model is left at its state, and `sim.current_time` is its time, so a following `run_until` continues from the stop. A callable is called with the whole result, so a run with one goes to the end of the interval and is then cut, and leaves the model at the end. So does a condition that reads a species whose reported value is set after the run (an -assignment rule's target, or a species in a compartment whose size changes), and -any condition on a network-free run. Where several conditions hold at the same +assignment rule's target, or a species in a compartment whose size changes), +any condition on a network-free run, and any on an ODE run of a `.net` model +whose rate law switches on its state (an `if` that reads a species or an +observable), which can record a sample again once it finds the switch's +crossing. Where several conditions hold at the same sample, the one added first names the stop; one added later that holds earlier ends the run first. diff --git a/include/bngsim/types.hpp b/include/bngsim/types.hpp index 3af5984d7..391db4c23 100644 --- a/include/bngsim/types.hpp +++ b/include/bngsim/types.hpp @@ -2133,9 +2133,6 @@ struct SolverOptions { // and unset by default, which leaves a run as it was. StopCheck stop_check; std::vector stop_roots; - // What a run moved onto its own clock (a far run, issue #1681) adds back - // to its time, in this order, where a stop root reads the time. - std::vector stop_time_origins; }; // ─── Time specification ────────────────────────────────────────────────────── diff --git a/python/bngsim/_simulator.py b/python/bngsim/_simulator.py index 7fa76b153..f9b8006a7 100644 --- a/python/bngsim/_simulator.py +++ b/python/bngsim/_simulator.py @@ -12622,16 +12622,21 @@ def add_stop_condition( of the form ``lhs < rhs`` (or ``<=``, ``>``, ``>=``), or a number, starts to hold between two samples, over arithmetic of what it reads: the crossing is found as an event's trigger is, and the - result's last row is at its time (issue #2018). A long span met early + result's last row is at its time (issue #2018); one that reads the + time, in a run integrated on the time since a start far from zero, is + asked at the samples alone. A long span met early costs the short run, and a model that fails after the condition holds stops before it fails. A callable, a condition that reads a species whose reported value is set after the run (an assignment rule's target, a species in a - compartment whose size changes), and a network-free run's - conditions are asked of the whole result instead: that run goes to - its end, the model is left there, and the result is cut at the first - sample a condition holds at. + compartment whose size changes), and the conditions of a network-free + run, and of an ODE run of a ``.net`` model whose rate law switches on + its state (an ``if`` that reads a species or an observable; such a + run can record a sample again once it finds the switch's crossing), + are asked of the whole result instead: that run goes to its end, the + model is left there, and the result is cut at the first sample a + condition holds at. A result that meets a condition is cut at the first sample any condition holds at; where several hold there, the one added first diff --git a/python/bngsim/_stop_in_run.py b/python/bngsim/_stop_in_run.py index c538bc8f7..e6fcd4507 100644 --- a/python/bngsim/_stop_in_run.py +++ b/python/bngsim/_stop_in_run.py @@ -60,13 +60,55 @@ def remapped_species(model: Model) -> frozenset[str]: return frozenset(names) -def _program(node: ast.AST, columns: dict[str, tuple[int, int]], out: list) -> bool: - """Append *node*'s value as stack operations to *out*; False where it is - not arithmetic over the columns and real constants.""" +_PY_BINARY = { + ast.Add: lambda a, b: a + b, + ast.Sub: lambda a, b: a - b, + ast.Mult: lambda a, b: a * b, + ast.Div: lambda a, b: a / b, + ast.Pow: lambda a, b: a**b, +} + + +def _constant(node: ast.AST) -> int | float | None: + """The value of *node* where it is arithmetic over real constants alone, + as Python reckons it in the condition (its ints exact); None where it is + not, or the arithmetic fails.""" if isinstance(node, ast.Constant): if isinstance(node.value, bool) or not isinstance(node.value, (int, float)): + return None + return node.value + if isinstance(node, ast.UnaryOp) and isinstance(node.op, (ast.USub, ast.UAdd)): + v = _constant(node.operand) + if v is None: + return None + return -v if isinstance(node.op, ast.USub) else +v + if isinstance(node, ast.BinOp) and type(node.op) in _PY_BINARY: + a, b = _constant(node.left), _constant(node.right) + if a is None or b is None: + return None + try: + v = _PY_BINARY[type(node.op)](a, b) + except (ArithmeticError, ValueError): + return None + return v if isinstance(v, (int, float)) else None + return None + + +def _program(node: ast.AST, columns: dict[str, tuple[int, int]], out: list) -> bool: + """Append *node*'s value as stack operations to *out*; False where it is + not arithmetic over the columns and real constants. + + A part that reads no column is folded to the one number it is, as Python + computes it there and numpy then takes it (``float()``): ``2**53 + 1 - + 2**53`` is 1, which a double at each step would make 0.""" + if not any(isinstance(n, ast.Name) for n in ast.walk(node)): + value = _constant(node) + if value is None: + return False + try: + out.append((_CONST, 0, float(value))) + except OverflowError: return False - out.append((_CONST, 0, float(node.value))) return True if isinstance(node, ast.Name): column = columns.get(node.id) @@ -107,6 +149,41 @@ def root_program(tree: ast.Expression, columns: dict[str, tuple[int, int]]) -> l return out if _program(body, columns, out) else None +def screen_program( + tree: ast.Expression, columns: dict[str, tuple[int, int]] +) -> tuple[list, bool] | None: + """The condition *tree* as the engine can decide it without Python: + ``(program, strict)``, for a g the condition holds exactly where g > 0 + (strict) or g >= 0, wherever g is not NaN (where it is, Python decides). + ``lhs - rhs`` for ``>`` and ``>=``, its negation for ``<`` and ``<=``, the + value itself for a number. The program does the arithmetic the + condition's own evaluation does, in its order, on the values it reads, so + g is the double numpy computes; and ``lhs - rhs``, rounded, has the sign + of the exact difference, infinities included (``inf - inf``, whose + comparison it cannot tell, is NaN). None where the condition is neither, + or raises a column to a power (which one platform's numpy and its C++ + need not round alike).""" + body = tree.body + out: list = [] + if isinstance(body, ast.Compare): + if len(body.ops) != 1 or not isinstance(body.ops[0], _ORDERS): + return None + if not (_program(body.left, columns, out) and _program(body.comparators[0], columns, out)): + return None + out.append((_SUB, 0, 0.0)) + op = body.ops[0] + if isinstance(op, (ast.Lt, ast.LtE)): + out.append((_NEG, 0, 0.0)) + strict = isinstance(op, (ast.Lt, ast.Gt)) + elif _program(body, columns, out): + strict = True + else: + return None + if any(kind == _POW for kind, _, _ in out): + return None + return out, strict + + class InRunStops: """The engine's stop check: whether any of the conditions holds at a row. @@ -120,6 +197,11 @@ class InRunStops: An error a condition meets here is not raised: the condition is read as not met at that row, and the result's own check, which reads the same row, raises it as it always has. An interrupt is raised. + + *screens*, where every condition has one (:func:`screen_program`), are read + by the engine's side of the check before it calls this one: a row at which + each is on its side that does not hold is not met, and Python is not asked + there. """ def __init__( @@ -127,10 +209,12 @@ def __init__( conditions: Sequence[tuple[Any, Sequence[tuple[str, int]], Sequence[tuple[str, int]]]], first: int, end: int, + screens: Sequence[tuple[list, bool]] = (), ) -> None: self._conditions = list(conditions) self._first = first self._end = end + self.screens = list(screens) def __call__( self, row: int, t: float, state: np.ndarray, observables: np.ndarray, at_root: bool @@ -193,6 +277,7 @@ def in_run_stops( obs_cols: list[int] = [] asked: list = [] programs: list[list] = [] + screens: list[tuple[list, bool]] | None = [] for sc in conditions: if not isinstance(sc, _ExpressionStopCondition): continue @@ -214,13 +299,20 @@ def in_run_stops( species_reads.append((name, len(species_cols))) species_cols.append(j) columns[name] = (_SPECIES, j) - else: + elif kind == "time": columns[name] = (_TIME, 0) asked.append((sc._code, obs_reads, species_reads)) - if roots and not (sc._names & sc._binds): + if screens is not None: + screen = screen_program(sc._tree, columns) + # One condition the engine cannot decide asks Python at each row. + screens = None if screen is None else [*screens, screen] + if roots: + # A name the expression binds itself (a lambda's, a + # comprehension's, a walrus's) is never read by a root: a program + # is arithmetic alone, which binds nothing. program = root_program(sc._tree, columns) if program is not None: programs.append(program) if not asked: return None - return InRunStops(asked, first, end), species_cols, obs_cols, programs + return InRunStops(asked, first, end, screens or ()), species_cols, obs_cols, programs diff --git a/python/tests/test_stop_condition_during_the_run.py b/python/tests/test_stop_condition_during_the_run.py index 24b80457b..e0f67a83a 100644 --- a/python/tests/test_stop_condition_during_the_run.py +++ b/python/tests/test_stop_condition_during_the_run.py @@ -104,6 +104,92 @@ end groups """ +# A threshold that falls past S = 1.2 closes the window S < thr() at t_close; +# Y integrates a Gaussian pulse while it is open (test_net_state_switch_stepping). +# The step that crosses t_close reads the closed side's rate, and a row inside +# it reads Y = 0 until the run re-takes the step up to the crossing. +CLOSING_PULSE = """\ +begin parameters + 1 k 10.0 + 2 A 0.5 + 3 tp 30.05 + 4 sig 0.001 + 5 tz {tz!r} + 6 wz 0.003 + 7 one 1.0 +end parameters +begin functions + 1 thr() 1+A*(1+tanh(-(time()-tp)/sig))/2 + 2 z() exp(-((time()-tz)/wz)^2) + 3 r() if(Sobs20,10,0) +end functions +begin reactions + 1 0 1 kon +end reactions +begin groups + 1 A_tot 1 +end groups +""" + +TIMED_DECAY = """begin parameters + 1 k 0.05 +end parameters +begin species + 1 A() 100 +end species +begin functions + 1 kt() k*time() +end functions +begin reactions + 1 1 0 kt +end reactions +begin groups + 1 A_tot 1 +end groups +""" + HALF_AT = math.log(2.0) / 0.1 # where the decay's A_tot = 50 TENTH_AT = math.log(10.0) / 0.1 # where it is 10 @@ -117,6 +203,7 @@ def nets(tmp_path: Path) -> dict[str, str]: "grow": GROW, "linear": LINEAR, "cycle": CYCLE, + "timed_decay": TIMED_DECAY, }.items(): path = tmp_path / f"{name}.net" path.write_text(text) @@ -152,9 +239,13 @@ def test_a_blow_up_past_the_condition_stops_at_the_crossing(nets): np.testing.assert_array_equal(r.time[:-1], np.linspace(0, 2, 201)[:90]) -def test_a_condition_with_no_crossing_ends_at_the_first_sample_past_it(nets): +@pytest.mark.parametrize("warm", ["1", "0"]) +def test_a_condition_with_no_crossing_ends_at_the_first_sample_past_it(nets, monkeypatch, warm): """A conjunction is not one the run can find the crossing of: it is asked at - the samples, and A = 9.5 at t = 0.8947 ends the run at the sample t = 0.90.""" + the samples, and A = 9.5 at t = 0.8947 ends the run at the sample t = 0.90, + on the warm path and the cold one.""" + if warm == "0": + monkeypatch.setenv("BNGSIM_NO_WARM_CVODE", "1") met = _stop(_sim(nets["blow"], "ode", "Atot > 9.5 and t > 0"), t_span=(0, 2), n_points=201) assert met.result.time[-1] == pytest.approx(0.90, abs=1e-12) assert len(met.result.time) == 91 @@ -196,6 +287,20 @@ def test_a_crossing_the_run_lands_on_exactly_is_still_met( assert a > 5.0 if strict else a >= 5.0 +@pytest.mark.parametrize("warm", ["1", "0"]) +def test_a_root_on_a_row_it_cannot_stand_for_keeps_the_row_s_state(nets, monkeypatch, warm): + """Control. A - 5 is 0 at the output 5.0, whose row stands after one the + result does not report (t = 0): the root is not asked, nor the time past + it, and the row is recorded at the root's state, A = 5, not the state + asked past it, where A > 5 holds and the run ended with A = 5 + 1.2e-13 at + t = 5. The run ends at the next sample, 10, as main's did.""" + if warm == "0": + monkeypatch.setenv("BNGSIM_NO_WARM_CVODE", "1") + met = _stop(_sim(nets["linear"], "ode", "A_tot > 5"), t_span=(0, 10), sample_times=[5.0, 10.0]) + assert list(met.result.time) == [5.0, 10.0] + assert list(met.result.observables["A_tot"]) == [5.0, 10.0] + + @pytest.mark.parametrize("warm", ["1", "0"]) def test_a_root_on_the_last_output_ends_the_run_there(nets, monkeypatch, warm): """A strict condition whose root is the span's last output is not met in @@ -234,6 +339,48 @@ def test_the_model_and_the_clock_are_left_at_the_stop(nets): assert after.species[0, 0] == met.result.species[-1, 0] +@pytest.mark.parametrize( + "net, method, warm, kw", + [ + ("decay", "ode", "1", {}), + ("decay", "ode", "0", {}), + ("decay", "ssa", "1", {"seed": 3}), + ("decay", "psa", "1", {"seed": 3}), + ("timed_decay", "ssa", "1", {"seed": 3}), + ("timed_decay", "psa", "1", {"seed": 3}), + ], +) +def test_a_condition_held_at_the_start_takes_no_step(nets, monkeypatch, net, method, warm, kw): + """A_tot < 1000 holds at t = 0: the run ends there, its one row the start, + and the model and the clock stay where they were. The whole span was run, + and the clock left at 100. A rate that reads the time puts a stochastic run + on its continuous loop, which ends there too.""" + if warm == "0": + monkeypatch.setenv("BNGSIM_NO_WARM_CVODE", "1") + extra = {"poplevel": 10} if method == "psa" else {} + sim = _sim(nets[net], method, "A_tot < 1000", **extra) + start = sim.model.get_state().copy() + met = _stop(sim, t_span=(0, 100), n_points=101, **kw) + assert list(met.result.time) == [0.0] + assert sim.current_time == 0.0 + np.testing.assert_array_equal(sim.model.get_state(), start) + + +@pytest.mark.parametrize("warm", ["1", "0"]) +def test_a_rule_the_model_holds_is_read_at_the_stop(monkeypatch, warm): + """p := time, read at the crossing the run ends at, 6.93: it was read at + the span's end, 100.""" + pytest.importorskip("antimony") + if warm == "0": + monkeypatch.setenv("BNGSIM_NO_WARM_CVODE", "1") + model = bngsim.Model.from_antimony_string("model m\n A' = -0.1*A\n A = 100\n p := time\nend\n") + sim = bngsim.Simulator(model, method="ode") + sim.add_stop_condition("A < 50") + met = _stop(sim, t_span=(0, 100), n_points=101) + assert met.result.time[-1] == pytest.approx(HALF_AT, rel=1e-6) + assert sim.model.get_param("p") == met.result.time[-1] + + def test_the_first_row_any_condition_holds_at_ends_the_run(nets): """Row by row: A_tot < 50 is added second and holds first, so it ends the run. It used to be the first one added that held anywhere, A_tot < 10 at t = 24.""" @@ -290,6 +437,34 @@ def test_a_row_sample_times_do_not_report_is_not_asked(nets): np.testing.assert_array_equal(met.result.time, [5.0]) +@pytest.mark.parametrize("warm", ["1", "0"]) +def test_a_crossing_before_the_first_sample_time_ends_the_run_there(nets, monkeypatch, warm): + """A_tot passes 90 at t = 1.05, before the first sample time, 5: the run + ends at the sample, the first row it reports, and the model is left there. + The whole span was run.""" + if warm == "0": + monkeypatch.setenv("BNGSIM_NO_WARM_CVODE", "1") + sim = _sim(nets["decay"], "ode", "A_tot < 90") + met = _stop(sim, t_span=(0, 10), sample_times=[5, 10]) + assert list(met.result.time) == [5.0] + assert sim.current_time == 5.0 + assert sim.model.get_state()[0] == met.result.species[-1, 0] + + +@pytest.mark.parametrize("warm", ["1", "0"]) +def test_a_crossing_past_the_last_sample_time_is_not_a_stop(nets, monkeypatch, warm): + """Control. A_tot passes 30 at t = 12.04, after the last sample time, 10, + and before the span's end, 20: the result reports no row it holds at, and + the run goes on to 20, where the model is left.""" + if warm == "0": + monkeypatch.setenv("BNGSIM_NO_WARM_CVODE", "1") + sim = _sim(nets["decay"], "ode", "A_tot < 30") + r = sim.run(t_span=(0, 20), sample_times=[0, 5, 10]) + assert list(r.time) == [0.0, 5.0, 10.0] + assert sim.current_time == 20.0 + assert sim.model.get_state()[0] == pytest.approx(100 * math.exp(-2), rel=1e-5) + + @pytest.mark.parametrize("warm", ["0", "1"]) def test_a_later_leg_ends_at_its_crossing(nets, monkeypatch, warm): """The second leg of run_until, on the warm path and the cold one.""" @@ -305,13 +480,18 @@ def test_a_later_leg_ends_at_its_crossing(nets, monkeypatch, warm): assert sim.current_time == met.value.result.time[-1] -def test_a_start_far_from_zero_ends_at_its_crossing(nets): +@pytest.mark.parametrize("condition, at", [("A_tot < 50", HALF_AT), ("t > 1000000000005.5", 6.0)]) +def test_a_start_far_from_zero_ends_at_its_crossing(nets, condition, at): """From t = 1e12 the run keeps its own clock; the crossing is reported on the - caller's, 1e12 + 6.93, and the clock is left there.""" + caller's, 1e12 + 6.93, and the clock is left there. A condition on the time + is asked at the samples alone, and ends the run at the one past it, 6: on + the caller's clock the time moves in steps of 1.2e-4 there, which the root + search, on the run's, took for flat, and the run failed (CV_ILL_INPUT). + Control for that one: main ended at the same sample.""" t0 = 1e12 - sim = _sim(nets["decay"], "ode", "A_tot < 50") + sim = _sim(nets["decay"], "ode", condition) met = _stop(sim, t_span=(t0, t0 + 100), n_points=101) - assert met.result.time[-1] - t0 == pytest.approx(HALF_AT, abs=1e-3) + assert met.result.time[-1] - t0 == pytest.approx(at, abs=1e-3) assert sim.current_time == met.result.time[-1] @@ -360,6 +540,94 @@ def test_a_stochastic_run_ends_on_the_whole_runs_row_and_stays_there(nets, metho assert sim.model.get_state()[0] == met.result.species[-1, 0] +@pytest.mark.parametrize( + "case, method, condition, at", + [ + ("extinct", "ssa", "t > 50", 51.0), + ("extinct", "psa", "t > 50", 51.0), + ("switched_on", "ssa", "t > 5", 6.0), + ("timed_decay", "ssa", "A_tot < 50", None), + ("event", "ssa", "t > 5", 6.0), + ], +) +def test_each_place_a_stochastic_run_records_a_row_asks_it(tmp_path, case, method, condition, at): + """Rows held still after the last firing, held still before a breakpoint + or an event, and read on the continuous loop: the run ends at the row met, + and the model, and the clock its rules read, are left there. They were left + at the span's end, 100, past firings the result does not show.""" + if case == "event": + pytest.importorskip("antimony") + model = bngsim.Model.from_antimony_string( + "model m\n J0: A -> ; k*A\n k = 1\n A = 0\n E1: at (time > 20): A = 10\nend\n" + ) + else: + text = {"extinct": EXTINCT, "switched_on": SWITCHED_ON, "timed_decay": TIMED_DECAY}[case] + path = tmp_path / f"{case}.net" + path.write_text(text) + model = bngsim.Model.from_net(str(path)) + sim = bngsim.Simulator(model, method=method, **({"poplevel": 10} if method == "psa" else {})) + sim.add_stop_condition(condition) + met = _stop(sim, t_span=(0, 100), n_points=101, seed=3) + r = met.result + if at is not None: + assert r.time[-1] == at + else: + assert r.observables["A_tot"][-1] < 50 <= r.observables["A_tot"][-2] + np.testing.assert_array_equal(sim.model.get_state(), r.species[-1]) + assert sim.model._core.current_time == r.time[-1] + + +def test_a_stopped_psa_run_banks_its_integrals_to_the_stop(tmp_path): + """A PSA run on the continuous loop (a rate that reads the time) stopped at + a row reports the event integrals of the run up to that row: those of a + plain run over the same rows with the same seed. They took in the run to + the span's end, 100.""" + path = tmp_path / "timed_decay.net" + path.write_text(TIMED_DECAY) + + def psa(): + return bngsim.Simulator(bngsim.Model.from_net(str(path)), method="psa", poplevel=10) + + sim = psa() + sim.add_stop_condition("A_tot < 50") + r = _stop(sim, t_span=(0, 100), n_points=101, seed=3).result + plain = psa().run(t_span=(0, r.time[-1]), n_points=len(r.time), seed=3) + np.testing.assert_array_equal(r.species, plain.species) + for key in ("exact_event_integral", "scaled_event_integral", "qexc_integral", "time"): + assert r.psa_diagnostics[key] == pytest.approx(plain.psa_diagnostics[key], rel=1e-12) + + +@pytest.mark.parametrize("method", ["ssa", "psa"]) +@pytest.mark.parametrize("condition, at", [("t > 7", 8.0), ("p < 1", 0.0)]) +def test_a_rate_rule_target_is_read_at_the_stop(method, condition, at): + """A species a rate rule moves (``p' = 1``, so p = t) on a stochastic run's + continuous loop is left at the row the run stopped at, 8, or the start + where the condition holds there: it was left at the span's end, 100.""" + pytest.importorskip("antimony") + model = bngsim.Model.from_antimony_string( + "model m\n J0: A -> ; k*A\n k = 0.1\n A = 100\n p' = 1\n p = 0\nend\n" + ) + sim = bngsim.Simulator(model, method=method, **({"poplevel": 10} if method == "psa" else {})) + sim.add_stop_condition(condition) + r = _stop(sim, t_span=(0, 100), n_points=101, seed=3).result + assert r.time[-1] == at + assert sim.model.get_concentration("p") == pytest.approx(at, rel=1e-12, abs=0.0) + np.testing.assert_array_equal(sim.model.get_state(), r.species[-1]) + + +@pytest.mark.parametrize("method", ["ssa", "psa"]) +def test_a_stochastic_run_far_from_zero_reads_the_time_its_rows_report(nets, method): + """A run from 1e12 counts its clock from there; a condition on the time is + asked of the time the row reports, 1e12 + 51, and the model's clock is left + there. It was left at the span's end, 1e12 + 100.""" + extra = {"poplevel": 10} if method == "psa" else {} + sim = _sim(nets["decay"], method, "t > 1000000000050.5", **extra) + r = _stop(sim, t_span=(1e12, 1e12 + 100), n_points=101, seed=3).result + assert r.time[-1] == 1e12 + 51 + assert sim.model._core.current_time == r.time[-1] + np.testing.assert_array_equal(sim.model.get_state(), r.species[-1]) + + def test_replicates_and_batch_rows_end_where_they_hold(nets): run = dict(t_span=(0, 30), n_points=301, timeout=10) reps = _sim(nets["grow"], "ssa", "Atot > 1e4").run_replicates(3, seed=1, **run) @@ -437,15 +705,111 @@ def test_a_crossing_where_the_condition_does_not_hold_changes_nothing(nets): # ── What the engine asks and what the result says ──────────────────────────── -def test_a_stop_the_result_does_not_hold_is_a_bug_said_aloud(nets, monkeypatch): +def test_a_row_a_re_take_records_again_is_not_asked_before_it(tmp_path): + """Control. A row read off a step that crossed a state switch before the + output is recorded again once the run finds the crossing: Y reads 9e-134 + there first, and 0.0063 after. A condition that holds only on the first + reading stopped the run on it. Such a run asks its conditions after the + run, as main did, and gives the run without them.""" + t_close = 30.05 + 0.001 * math.atanh(0.2) + path = tmp_path / "pulse.net" + path.write_text(CLOSING_PULSE.format(tz=t_close + 0.0015)) + kw = {"sample_times": [30.0, t_close - 0.001, 31.0], "rtol": 1e-6, "atol": 1e-8} + plain = bngsim.Simulator(bngsim.Model.from_net(str(path))).run(**kw) + assert plain.species[1, 1] == pytest.approx(0.00634, rel=1e-2) + sim = bngsim.Simulator(bngsim.Model.from_net(str(path))) + sim.add_stop_condition("Y__ < 0.001 and time > 30.04") + got = sim.run(**kw) + assert got.stop_condition is None + np.testing.assert_array_equal(got.species, plain.species) + + +@pytest.mark.filterwarnings("ignore:divide by zero encountered in stop condition") +@pytest.mark.parametrize("method", ["ode", "ssa", "psa"]) +@pytest.mark.parametrize( + "condition, calls", + [ + # Decided by the engine: Python is asked only where it may hold. + ("A_tot < 10", 1), + ("10 > A_tot", 1), + ("A_tot <= 10", 1), + ("-(A_tot - 10) > 0", 1), + ("10 - A_tot", 1), + ("A_tot / 2 < 2**53 + 1 - 2**53 + 4", 1), + # inf >= inf holds, and its g is inf - inf, NaN: Python decides it. + ("A_tot / 0 >= A_tot / 0", 1), + # Not decided by it: a conjunction and a power of a column are asked + # of Python at every row. + ("A_tot < 10 and t > 0", None), + ("A_tot**2 < 100", None), + ], +) +def test_a_condition_the_engine_can_decide_is_not_asked_of_python_at_each_row( + nets, monkeypatch, method, condition, calls +): + """A comparison the engine can compute as numpy does is decided there at a + row it does not hold at, and Python is asked only at the rows it may: the + run, and where it ends, are the ones every row asked gives.""" + from bngsim import _stop_in_run + + asked: list[int] = [] + call = _stop_in_run.InRunStops.__call__ + + def counted(self, row, *a): + asked.append(row) + return call(self, row, *a) + + extra = {"poplevel": 10} if method == "psa" else {} + kw = {} if method == "ode" else {"seed": 3} + run = dict(t_span=(0, 100), n_points=101, **kw) + with monkeypatch.context() as m: + # Python asked at every row. + m.setattr(_stop_in_run, "screen_program", lambda *a: None) + reference = _stop(_sim(nets["decay"], method, condition, **extra), **run) + monkeypatch.setattr(_stop_in_run.InRunStops, "__call__", counted) + met = _stop(_sim(nets["decay"], method, condition, **extra), **run) + np.testing.assert_array_equal(met.result.species, reference.result.species) + np.testing.assert_array_equal(met.result.time, reference.result.time) + n = len(met.result.time) + if calls is None: + assert len(asked) >= n + else: + # The row it holds at, and on the ODE run the root before it. + assert len(asked) <= calls + (method == "ode") + + +@pytest.mark.parametrize("method", ["ode", "ssa"]) +def test_a_condition_the_engine_cannot_decide_is_asked_beside_one_it_can(nets, method): + """A_tot < -1, which the engine decides, never holds; the conjunction + beside it, which it cannot, holds from A_tot < 10, and ends the run there. + The run went on to its end.""" + kw = {} if method == "ode" else {"seed": 3} + sim = _sim(nets["decay"], method, "A_tot < -1", "A_tot < 10 and t > 0") + met = _stop(sim, t_span=(0, 100), n_points=101, **kw) + assert met.condition == "A_tot < 10 and t > 0" + assert met.result.observables["A_tot"][-1] < 10 <= met.result.observables["A_tot"][-2] + assert sim.current_time == met.result.time[-1] + + +@pytest.mark.parametrize("entry", ["run", "run_batch", "run_replicates"]) +def test_a_stop_the_result_does_not_hold_is_a_bug_said_aloud(nets, monkeypatch, entry): """The engine ends a run where the check it is given says so; the result is then asked again. Were the two to differ, the run would end with no condition met: that is refused, not returned as a run that ended early.""" from bngsim import _stop_in_run monkeypatch.setattr(_stop_in_run.InRunStops, "__call__", lambda self, row, *a: row == 3) + run = dict(t_span=(0, 100), n_points=101) + # A conjunction, which the engine asks Python of at every row. + condition = "A_tot < 10 and t > 0" with pytest.raises(bngsim.BngsimError, match="issue #2018"): - _sim(nets["decay"], "ode", "A_tot < 10").run(t_span=(0, 100), n_points=101) + if entry == "run": + _sim(nets["decay"], "ode", condition).run(**run) + elif entry == "run_batch": + params = [{"k": 0.1}, {"k": 0.2}] + _sim(nets["decay"], "ode", condition).run_batch(params=params, **run) + else: + _sim(nets["decay"], "ssa", condition).run_replicates(2, seed=3, **run) @pytest.mark.parametrize("method", ["ode", "ssa"]) @@ -458,7 +822,7 @@ def interrupt(self, row, *a): return False monkeypatch.setattr(_stop_in_run.InRunStops, "__call__", interrupt) - sim = _sim(nets["decay"], method, "A_tot < 10") + sim = _sim(nets["decay"], method, "A_tot < 10 and t > 0") before = sim.model.get_state().copy() with pytest.raises(KeyboardInterrupt): sim.run(t_span=(0, 100), n_points=101, seed=1) diff --git a/src/_bngsim_core.cpp b/src/_bngsim_core.cpp index fc5b0d385..d6aaa9d5d 100644 --- a/src/_bngsim_core.cpp +++ b/src/_bngsim_core.cpp @@ -29,6 +29,7 @@ #include #include // uintptr_t (_MirJit.address, issue #1575) #include +#include #include #include #include @@ -880,24 +881,134 @@ struct CNumericLocaleBlock { }; } // namespace +// Issue #2018: a stop condition the engine decides without Python, as +// bngsim._stop_in_run.screen_program writes it: a program for g, which the +// condition holds exactly where g > 0 (strict) or g >= 0, wherever g is not +// NaN (where it is, Python decides). +struct StopScreen { + std::vector program; + bool strict = true; +}; + +// g at a row, from the time and the state and observables the check is handed, +// by the operations the condition's own evaluation does, in its order. NaN, +// which leaves the row to Python, where the program reads a column the row +// does not have or does anything a screen does not (a power). +static double screen_value(const StopScreen &screen, double t, const double *x, int n_x, + const double *obs, int n_obs, std::vector &stack) { + constexpr double kNaN = std::numeric_limits::quiet_NaN(); + stack.clear(); + for (const bngsim::StopRootOp &op : screen.program) { + switch (op.kind) { + case bngsim::StopRootOp::Const: + stack.push_back(op.value); + break; + case bngsim::StopRootOp::Observable: + if (op.index < 0 || op.index >= n_obs) + return kNaN; + stack.push_back(obs[op.index]); + break; + case bngsim::StopRootOp::Species: + if (op.index < 0 || op.index >= n_x) + return kNaN; + stack.push_back(x[op.index]); + break; + case bngsim::StopRootOp::Time: + stack.push_back(t); + break; + case bngsim::StopRootOp::Neg: + if (stack.empty()) + return kNaN; + stack.back() = -stack.back(); + break; + case bngsim::StopRootOp::Add: + case bngsim::StopRootOp::Sub: + case bngsim::StopRootOp::Mul: + case bngsim::StopRootOp::Div: { + if (stack.size() < 2) + return kNaN; + const double b = stack.back(); + stack.pop_back(); + double &a = stack.back(); + if (op.kind == bngsim::StopRootOp::Add) + a = a + b; + else if (op.kind == bngsim::StopRootOp::Sub) + a = a - b; + else if (op.kind == bngsim::StopRootOp::Mul) + a = a * b; + else + a = a / b; + break; + } + default: + return kNaN; + } + } + return stack.size() == 1 ? stack.back() : kNaN; +} + +// The screens a check carries (its `screens` attribute: (program, strict) +// pairs, one per condition it asks), or none, where any is not one a screen +// can be. +static std::vector stop_screens_of(const py::object &fn) { + std::vector out; + if (!py::hasattr(fn, "screens")) { + return out; + } + for (const py::handle item : fn.attr("screens")) { + const auto [program, strict] = + item.cast>, bool>>(); + StopScreen screen; + screen.strict = strict; + for (const auto &[kind, index, value] : program) { + if (kind < bngsim::StopRootOp::Const || kind > bngsim::StopRootOp::Neg) { + return {}; + } + bngsim::StopRootOp op; + op.kind = kind; + op.index = index; + op.value = value; + screen.program.push_back(op); + } + out.push_back(std::move(screen)); + } + return out; +} + // Issue #2018: a Python stop check as the engines call it. Python is given // the row, its time, the state entries and observables at the columns named // (each a copy, as a numpy array), and whether the row is a stop root's, and // returns whether a condition is met there. The callable is held through a // shared pointer whose last owner takes the GIL to drop it, so the options // can be copied by a run with the GIL released. +// +// Where the check carries a screen for each condition it asks, a row at which +// every screen is on its side that does not hold is not met, and Python is not +// called: the GIL, two arrays and an eval per row were 2 us, a +// run of 1e5 rows 0.2 s, for a condition that held at none of them. static bngsim::StopCheck make_stop_check(py::object fn, std::vector species_cols, std::vector obs_cols) { if (fn.is_none()) { return nullptr; } + std::vector screens = stop_screens_of(fn); std::shared_ptr held(new py::object(std::move(fn)), [](py::object *p) { py::gil_scoped_acquire acquire; delete p; }); - return [held, species_cols = std::move(species_cols), - obs_cols = std::move(obs_cols)](int row, double t, const double *x, int n_x, - const double *obs, int n_obs, bool at_root) -> bool { + return [held, species_cols = std::move(species_cols), obs_cols = std::move(obs_cols), + screens = std::move(screens)](int row, double t, const double *x, int n_x, + const double *obs, int n_obs, bool at_root) -> bool { + if (!screens.empty()) { + thread_local std::vector stack; + const bool may_hold = std::any_of(screens.begin(), screens.end(), [&](const auto &s) { + const double g = screen_value(s, t, x, n_x, obs, n_obs, stack); + return !(s.strict ? g <= 0.0 : g < 0.0); // NaN: may hold + }); + if (!may_hold) { + return false; + } + } const auto pick = [](const std::vector &cols, const double *from, int n, const char *what) { py::array_t out(static_cast(cols.size())); diff --git a/src/cvode_simulator.cpp b/src/cvode_simulator.cpp index 8a1723d6d..4abf81774 100644 --- a/src/cvode_simulator.cpp +++ b/src/cvode_simulator.cpp @@ -1084,11 +1084,9 @@ struct CvodeUserData { double put_below_tn = std::numeric_limits::quiet_NaN(); double put_below_h = std::numeric_limits::quiet_NaN(); // Issue #2018: the run's stop roots, after the model's own n_model_roots - // roots in CVODE's root vector (cvode_run_root_fn), the times a far run's - // clock adds back (SolverOptions::stop_time_origins), and the stack their + // roots in CVODE's root vector (cvode_run_root_fn), and the stack their // programs are evaluated on. Null where the run has none. const std::vector *stop_roots = nullptr; - const std::vector *stop_time_origins = nullptr; std::vector *stop_stack = nullptr; int n_model_roots = 0; }; @@ -3775,10 +3773,10 @@ static int cvode_event_root_fn(sunrealtype t, N_Vector y, sunrealtype *gout, voi // A stop root is a program for g(t, x) = lhs - rhs of a stop condition (see // StopRoot), run on a stack. It reads an observable as the row's refresh sums // it (NetworkModel::observable_total), a state entry as it stands, and the -// time on the clock the condition is written in. +// time, on the run's clock: a far run, on a clock of its own, has no root +// that reads the time (CvodeSimulator::run). static double stop_root_value(const StopRoot &root, double t, const double *x, - const NetworkModel &model, const std::vector *origins, - std::vector &stack) { + const NetworkModel &model, std::vector &stack) { stack.clear(); for (const StopRootOp &op : root.program) { switch (op.kind) { @@ -3791,16 +3789,9 @@ static double stop_root_value(const StopRoot &root, double t, const double *x, case StopRootOp::Species: stack.push_back(x[op.index]); break; - case StopRootOp::Time: { - double clock = t; - if (origins != nullptr) { - for (double o : *origins) { - clock += o; - } - } - stack.push_back(clock); + case StopRootOp::Time: + stack.push_back(t); break; - } case StopRootOp::Neg: stack.back() = -stack.back(); break; @@ -3880,8 +3871,7 @@ static int cvode_run_root_fn_body(sunrealtype t, N_Vector y, sunrealtype *gout, const std::vector &roots = *data->stop_roots; for (std::size_t j = 0; j < roots.size(); ++j) { gout[static_cast(off) + j] = - stop_root_value(roots[j], static_cast(t), x, *data->model, - data->stop_time_origins, *data->stop_stack); + stop_root_value(roots[j], static_cast(t), x, *data->model, *data->stop_stack); } return 0; } @@ -6371,13 +6361,11 @@ Result CvodeSimulator::Impl::run_warm(const TimeSpec ×, const SolverOptions CVodeRootInit(mem, 0, nullptr); } data.stop_roots = nullptr; - data.stop_time_origins = nullptr; data.stop_stack = nullptr; } } stop_roots_off{w.user_data, cvode_mem}; if (n_stop_roots > 0) { w.user_data.stop_roots = &opts.stop_roots; - w.user_data.stop_time_origins = &opts.stop_time_origins; w.user_data.stop_stack = &stop_stack; w.user_data.n_model_roots = 0; stop_roots_off.on = true; @@ -9570,7 +9558,6 @@ void CvodeSimulator::Impl::confirm_orders(const TimeSpec ×, const SolverOpt // A stop condition is the run's, which is over (issue #2018). tight.stop_check = nullptr; tight.stop_roots.clear(); - tight.stop_time_origins.clear(); // A compiled right-hand side is loaded again as it is; one compiled in // process would be compiled again for one run, and the interpreter // reads the same model. @@ -18208,16 +18195,25 @@ Result CvodeSimulator::run(const TimeSpec ×, const SolverOptions &opts) { t += *o; return t; }; - // A stop condition reads the time asked for (issue #2018): its roots - // add the origins back in the order back() does, and its check is - // given each row's time as the row reports it. A root's row reports - // the root's time, moved back. + // A stop condition reads the time asked for (issue #2018): its check + // is given each row's time as the row reports it, and a root's row + // reports the root's time, moved back. A root that reads the time + // would read it on the caller's clock, which this far from zero moves + // in steps CVODE's root search, on the run's own clock, takes for + // flat: from 1e12, `t > 1e12 + 5.5` read 0 at the root and just past + // it, and the run failed with CV_ILL_INPUT. The run has none, and such + // a condition is asked at the rows alone. int root_row = -1; if (opts.stop_check) { - moved.stop_time_origins.assign(origins.rbegin(), origins.rend()); - moved.stop_time_origins.insert(moved.stop_time_origins.end(), - opts.stop_time_origins.begin(), - opts.stop_time_origins.end()); + moved.stop_roots.erase(std::remove_if(moved.stop_roots.begin(), moved.stop_roots.end(), + [](const StopRoot &r) { + return std::any_of( + r.program.begin(), r.program.end(), + [](const StopRootOp &op) { + return op.kind == StopRootOp::Time; + }); + }), + moved.stop_roots.end()); moved.stop_check = [&opts, &back, &root_row](int row, double t, const double *x, int n_x, const double *obs, int n_o, bool at_root) { @@ -19372,11 +19368,14 @@ Result CvodeSimulator::run(const TimeSpec ×, const SolverOptions &opts) { // takes the steps it took without one. validate_stop_roots(opts, ns, n_obs); // A run that steps over a state switch's surface can go back and record - // rows again once a later return finds a window the step crossed - // (retake_from_row, below). A row asked of a stop condition there is not - // yet the row the run returns, so such a run takes a stop only at a row - // whose step has been screened to its end, and finds no crossing: a root's - // row would be read off a step not screened. + // rows again once a later return finds the crossing, or a window, the + // step that read them took (retake_from_row, below). A row asked of a stop + // condition there is not yet the row the run returns, and a crossing past + // the output is found only on the call after it: a step screened to its + // end for windows still had one, and the run stopped on a row read off it, + // Y = 9e-134 where it is 0.0063. Such a run asks no stop condition after + // its first row, which no re-take reaches, and its result is cut after the + // run, as it was before. const bool ss_checked = opts.steady_state && !(model.state_reads_clock() || model.n_events() > 0); const bool rows_retaken = n_state_switch > 0 && !ss_checked; @@ -19390,7 +19389,6 @@ Result CvodeSimulator::run(const TimeSpec ×, const SolverOptions &opts) { bool stop_row_at_root = false; if (n_stop_roots > 0) { user_data.stop_roots = &opts.stop_roots; - user_data.stop_time_origins = &opts.stop_time_origins; user_data.stop_stack = &stop_stack; user_data.n_model_roots = n_roots; } @@ -25074,20 +25072,12 @@ Result CvodeSimulator::run(const TimeSpec ×, const SolverOptions &opts) { // ─── Stop conditions (issue #2018) ─────────────────────────────────── // Asked at each row recorded, and the run ends at the first that // meets one. A root's row was asked above, at the root. A run whose - // rows can be recorded again stops only at a row no later return can - // go back past: its step screened to its end. + // rows can be recorded again asks none (rows_retaken, above). if (stop_row_at_root) { stop_met = true; - } else if (opts.stop_check && + } else if (opts.stop_check && !rows_retaken && opts.stop_check(i, t_row, y_data, ns, obs_buf.data(), n_obs, false)) { - if (!rows_retaken) { - stop_met = true; - } else { - sunrealtype tn_s = 0.0; - CVodeGetCurrentTime(cvode_mem, &tn_s); - stop_met = std::isfinite(screen_t) && screen_reinits == impl_->reinits && - screen_t >= static_cast(tn_s); - } + stop_met = true; } } diff --git a/src/ssa_simulator.cpp b/src/ssa_simulator.cpp index fa3f05811..9e16aabd7 100644 --- a/src/ssa_simulator.cpp +++ b/src/ssa_simulator.cpp @@ -4095,10 +4095,11 @@ Result SsaSimulator::run_internal(const TimeSpec ×_in, uint64_t seed, doubl t = t_out[n_out - 1]; else if (t < times.t_end) t = times.t_end; - // The time the last row reports, which the next run continues from. - const double t_last_abs = stop_met && origin != 0.0 ? t_reported[n_out - 1] - : t == times.t_end ? times_in.t_end - : origin + t; + // The time the last row reports, which the next run continues from: a + // row's time on the run's clock is the time it reports less the origin, + // which is exact (both are on the reported time's spacing), so adding the + // origin back gives the reported time. + const double t_last_abs = t == times.t_end ? times_in.t_end : origin + t; { auto &species = const_cast &>(model.species()); for (int i = 0; i < ns; ++i) { From 60ac4f03636bc5d87040edd7f3b366f9fab3bd96 Mon Sep 17 00:00:00 2001 From: Bill Hlavacek Date: Thu, 3 Dec 2026 17:34:21 -0700 Subject: [PATCH 05/11] test: a screened stop ends the run there, and Python is asked where it holds (#2018) Two screen mutants left every result array right: a NaN read as not met (inf >= inf), and a folded constant reckoned in doubles (2**53 + 1 - 2**53). The engine then ran past the stop and the result was cut after the run, leaving the clock at the end of the span. The test now holds the clock at the stop and asks that Python saw the row. --- python/tests/test_stop_condition_during_the_run.py | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/python/tests/test_stop_condition_during_the_run.py b/python/tests/test_stop_condition_during_the_run.py index e0f67a83a..04d2b1926 100644 --- a/python/tests/test_stop_condition_during_the_run.py +++ b/python/tests/test_stop_condition_during_the_run.py @@ -767,15 +767,19 @@ def counted(self, row, *a): m.setattr(_stop_in_run, "screen_program", lambda *a: None) reference = _stop(_sim(nets["decay"], method, condition, **extra), **run) monkeypatch.setattr(_stop_in_run.InRunStops, "__call__", counted) - met = _stop(_sim(nets["decay"], method, condition, **extra), **run) + sim = _sim(nets["decay"], method, condition, **extra) + met = _stop(sim, **run) np.testing.assert_array_equal(met.result.species, reference.result.species) np.testing.assert_array_equal(met.result.time, reference.result.time) + # The run ended where the condition held, not at the end of its span + # with the result cut after it. + assert sim.current_time == met.result.time[-1] < 100 n = len(met.result.time) if calls is None: assert len(asked) >= n else: # The row it holds at, and on the ODE run the root before it. - assert len(asked) <= calls + (method == "ode") + assert 1 <= len(asked) <= calls + (method == "ode") @pytest.mark.parametrize("method", ["ode", "ssa"]) From f38dc467b6974bdd87c664a58dcbf8d8f3fc36f7 Mon Sep 17 00:00:00 2001 From: Bill Hlavacek Date: Thu, 3 Dec 2026 18:30:57 -0700 Subject: [PATCH 06/11] fix: stop roots read 0 on the condition's side; an event at the stop (#2018) A stop root's g of exactly 0 now reads as the smallest number on the side the condition is on at equality, so CVODE sees g change sign where the condition does and returns the root where it already holds. The probe past the root is gone. A conserved total compared with its own value no longer parks g at 0, which CVODE refused to go on from (CV_ILL_INPUT). A crossing at the instant an event's trigger rises is not taken as the stop: the row there holds the state after the event. The condition is asked at the next row recorded, as on main. A crossing on the last sample of a longer span belongs to no reported row and is not a stop. run_batch and run_replicates take a row's early end for a stop only where the engine was given conditions to ask, as run() does. Docs: a callable beside an expression is asked of the result up to the stop; conditions that only rounding decides; a crossing at an event. Run-time messages cite no issue numbers. --- changelog.d/2018.fixed.md | 2 +- docs/user-guide/simulation.md | 38 ++-- include/bngsim/types.hpp | 8 + python/bngsim/_bngsim_core.pyi | 4 +- python/bngsim/_simulator.py | 17 +- python/bngsim/_stop_in_run.py | 28 ++- python/bngsim/kernel.py | 7 +- .../test_stop_condition_during_the_run.py | 190 ++++++++++++++++-- src/_bngsim_core.cpp | 30 ++- src/cvode_simulator.cpp | 125 ++++++------ 10 files changed, 328 insertions(+), 121 deletions(-) diff --git a/changelog.d/2018.fixed.md b/changelog.d/2018.fixed.md index 5fb707095..a5f55b40f 100644 --- a/changelog.d/2018.fixed.md +++ b/changelog.d/2018.fixed.md @@ -1 +1 @@ -- **A stop condition now ends the run where it holds; it was asked only after the run had gone to its end.** `A' = A²` from A = 1 passes 10 at t = 0.9 and blows up at t = 1: with `add_stop_condition("Atot > 10")` over (0, 2) the run raised `SimulationError`, and now returns `StopConditionMet` at t = 0.9 (0.8999993). An ODE, SSA or PSA run asks an expression condition at each sample and ends at the first it holds at; an ODE run ends where a comparison (`<`, `<=`, `>`, `>=`) or a number starts to hold, at the crossing, not the next sample. The model is left at the stop, with `current_time` its time, where it was left at the span's end. A long span met early costs the short run: an SSA run of A → 2A to `Atot > 1e4` over (0, 30) ran to its timeout, and ends at t ≈ 7. The first sample any condition holds at ends the run, named by the first condition added that holds there. A callable, a condition on a species reported after the run, a network-free run and a `.net` model whose rate law switches on its state are still asked of the whole run. A condition never met gives the same run, bit for bit. +- **A stop condition now ends the run where it holds; it was asked only after the run had gone to its end.** `A' = A²` from A = 1 passes 10 at t = 0.9 and blows up at t = 1: with `add_stop_condition("Atot > 10")` over (0, 2) the run raised `SimulationError`, and now returns `StopConditionMet` at t = 0.9 (0.8999993). An ODE, SSA or PSA run asks an expression condition at each sample and ends at the first it holds at; an ODE run ends where a comparison (`<`, `<=`, `>`, `>=`) or a number starts to hold, at the crossing, not the next sample. The model is left at the stop, with `current_time` its time, where it was left at the span's end. A long span met early costs the short run: an SSA run of A → 2A to `Atot > 1e4` over (0, 30) ran to its timeout, and ends at t ≈ 7. The first sample any condition holds at ends the run, named by the first condition added that holds there. A callable, a condition on a species reported after the run, a network-free run and a `.net` model whose rate law switches on its state are still asked after the run. A condition never met gives the same run, bit for bit, unless it crosses where an event fires, which can then move within the root tolerance. diff --git a/docs/user-guide/simulation.md b/docs/user-guide/simulation.md index f78920574..5ee7e361f 100644 --- a/docs/user-guide/simulation.md +++ b/docs/user-guide/simulation.md @@ -254,20 +254,30 @@ first one it holds at, so a long interval met early costs only the run to the stop, and a model that would fail later stops before it fails. An ODE run also finds where a comparison (`lhs < rhs`, `<=`, `>`, `>=`) or a number starts to hold between two samples, and ends at that time: here `e.result.time[-1]` is -where `Bound_hot` falls through 10000, not the sample after it. (A condition -that reads the time, in a run integrated on the time since a start far from -zero, is asked at the samples alone.) `e.result` -ends at the stop, the model is left at its state, and `sim.current_time` is its -time, so a following `run_until` continues from the stop. - -A callable is called with the whole result, so a run with one goes to the end -of the interval and is then cut, and leaves the model at the end. So does a -condition that reads a species whose reported value is set after the run (an -assignment rule's target, or a species in a compartment whose size changes), -any condition on a network-free run, and any on an ODE run of a `.net` model -whose rate law switches on its state (an `if` that reads a species or an -observable), which can record a sample again once it finds the switch's -crossing. Where several conditions hold at the same +where `Bound_hot` falls through 10000, not the sample after it. Two cases are +asked at the samples alone: a condition that reads the time, in a run +integrated on the time since a start far from zero; and a crossing at the +instant an event fires, since a sample there holds the state after the event, +so the run ends at the next sample that holds the condition. `e.result` ends at +the stop, the model is left at its state, and `sim.current_time` is its time, +so a following `run_until` continues from the stop. + +A comparison that only rounding decides, such as a conserved total compared +with its own value or a decaying species compared with 0, is met wherever +rounding puts it past the value. An ODE run asks it between samples too, so +where it is met depends on the solver's steps as well as on the samples. +Compare with a margin (`Tot < 10 - 1e-6`) instead. + +A callable is called with the result after the run, and is met at its last +sample. A run with one goes to the end of the interval and leaves the model +there, unless an expression condition ends it first; the callable is then +asked of the result up to that stop. These are also asked only after the run, +which goes to the end: a condition that reads a species whose reported value +is set after the run (an assignment rule's target, or a species in a +compartment whose size changes), any condition on a network-free run, and any +on an ODE run of a `.net` model whose rate law switches on its state (an `if` +that reads a species or an observable), which can record a sample again once +it finds the switch's crossing. Where several conditions hold at the same sample, the one added first names the stop; one added later that holds earlier ends the run first. diff --git a/include/bngsim/types.hpp b/include/bngsim/types.hpp index 391db4c23..0066c1c6f 100644 --- a/include/bngsim/types.hpp +++ b/include/bngsim/types.hpp @@ -1924,8 +1924,16 @@ struct StopRootOp { // met where it is > 0): lhs - rhs, whose sign changes where the condition // turns. The ODE run finds it as a root, as it finds an event's trigger, and // asks StopCheck at it; the condition decides, the root only says where. +// +// at_zero is what a g of exactly 0 reads as: a number too small to be any +// other g, on the side the condition is on at equality (`>`: not met, `>=`: +// met). CVODE then sees g change sign exactly where the condition does, and +// returns the root where it already holds; and it never sees a g parked at 0, +// which it refuses to go on from ("root found at and very near t") where a +// conserved total is compared with its own value. 0 reads 0 as 0. struct StopRoot { std::vector program; + double at_zero = 0.0; }; // ─── Solver options ────────────────────────────────────────────────────────── diff --git a/python/bngsim/_bngsim_core.pyi b/python/bngsim/_bngsim_core.pyi index dff80de25..9947cc473 100644 --- a/python/bngsim/_bngsim_core.pyi +++ b/python/bngsim/_bngsim_core.pyi @@ -1087,9 +1087,9 @@ class SolverOptions: """ Issue #2018: fn(row, t, state, observables, at_root) -> bool, asked at each row the run records, and at each stop root, with copies of the state entries and observables at the columns named. True ends the run on that row. None clears it. """ - def set_stop_roots(self, roots: collections.abc.Sequence[collections.abc.Sequence[tuple[typing.SupportsInt | typing.SupportsIndex, typing.SupportsInt | typing.SupportsIndex, typing.SupportsFloat | typing.SupportsIndex]]]) -> None: + def set_stop_roots(self, roots: collections.abc.Sequence[tuple[collections.abc.Sequence[tuple[typing.SupportsInt | typing.SupportsIndex, typing.SupportsInt | typing.SupportsIndex, typing.SupportsFloat | typing.SupportsIndex]], typing.SupportsFloat | typing.SupportsIndex]]) -> None: """ - Issue #2018: the stop conditions' root functions, each a list of (kind, index, value) operations on a stack (bngsim._stop_in_run); CVODE finds where each changes sign, and the stop check decides there. Needs a stop check. + Issue #2018: the stop conditions' root functions, each (program, side): the program a list of (kind, index, value) operations on a stack (bngsim._stop_in_run), and the side (+1, -1 or 0) a value of exactly 0 reads as. CVODE finds where each changes sign, and the stop check decides there. Needs a stop check. """ def set_switch_pinned_params(self, param_idx0: collections.abc.Sequence[typing.SupportsInt | typing.SupportsIndex]) -> None: """ diff --git a/python/bngsim/_simulator.py b/python/bngsim/_simulator.py index f9b8006a7..f1acbacda 100644 --- a/python/bngsim/_simulator.py +++ b/python/bngsim/_simulator.py @@ -7511,9 +7511,14 @@ def _run_one_here(i: int) -> Result: # Each row meets the stop conditions as run() does, and one that meets # one comes back cut there, beside the rest (issue #1369); an ODE, SSA - # or PSA row's run ends there too (issue #2018). + # or PSA row's run ends there too (issue #2018), where its engine was + # given any to ask, as for run(). Every row was given the same ones: a + # clone reports the columns of the model it was made from. if self._stop_conditions: - results = [self._stopped(r, ended=_ended_on_a_stop(r, n_points)) for r in results] + given = bool(self._ssa_stops(self._model, n_points, 0, 0)) + results = [ + self._stopped(r, ended=given and _ended_on_a_stop(r, n_points)) for r in results + ] # Each row is stamped already, against its own clone (issues #698, #743). if squeeze: @@ -7761,7 +7766,10 @@ def _worker(i: int) -> Result: # As run_batch's rows (issues #1369, #2018). if self._stop_conditions: - results = [self._stopped(r, ended=_ended_on_a_stop(r, n_points)) for r in results] + results = [ + self._stopped(r, ended=bool(stops) and _ended_on_a_stop(r, n_points)) + for r in results + ] # Every row is stamped already; stamping the stack again would replace # the rows' own report metadata with the parent's (issue #743). @@ -12829,10 +12837,11 @@ def _stopped(self, result: Result, *, ended: bool = False) -> Result: first, met = trigger_idx, sc if met is None: if ended: + # Issue #2018: the engine and this check ask the same rows. raise BngsimError( "The run ended on a stop condition at t=" f"{float(result.time[-1]):.17g}, and none holds at any sample its " - "result reports. This is a bug in bngsim (issue #2018): please " + "result reports. This is a bug in bngsim: please " "report it, with the model and the condition." ) return result diff --git a/python/bngsim/_stop_in_run.py b/python/bngsim/_stop_in_run.py index e6fcd4507..6c336c0ea 100644 --- a/python/bngsim/_stop_in_run.py +++ b/python/bngsim/_stop_in_run.py @@ -130,13 +130,19 @@ def _program(node: ast.AST, columns: dict[str, tuple[int, int]], out: list) -> b return False -def root_program(tree: ast.Expression, columns: dict[str, tuple[int, int]]) -> list | None: - """The program for g, a function that changes sign where the condition - *tree* starts to hold: ``lhs - rhs`` for ``lhs OP rhs`` with OP one of - ``<``, ``<=``, ``>``, ``>=``, and the value itself for one that is a number. - None where the condition is neither, or reads something other than - *columns* (name -> (operation, index)) and real constants. A root of g is - only where to ask: the condition decides there.""" +def root_program( + tree: ast.Expression, columns: dict[str, tuple[int, int]] +) -> tuple[list, float] | None: + """``(program, side)``: the program for g, a function that changes sign + where the condition *tree* starts to hold, ``lhs - rhs`` for ``lhs OP rhs`` + with OP one of ``<``, ``<=``, ``>``, ``>=``, and the value itself for one + that is a number; and the side, +1 or -1, a g of exactly 0 is read on: the + one the condition is on at equality (``>=`` met, so +1; ``>`` not, so -1; + ``<=`` met, so -1; ``<`` not, so +1; a number is met where it is > 0, so + -1). The engine then finds a root where the condition already holds, and + no g parked at 0. None where the condition is neither, or reads something + other than *columns* (name -> (operation, index)) and real constants. A + root of g is only where to ask: the condition decides there.""" body = tree.body out: list = [] if isinstance(body, ast.Compare): @@ -145,8 +151,8 @@ def root_program(tree: ast.Expression, columns: dict[str, tuple[int, int]]) -> l if not (_program(body.left, columns, out) and _program(body.comparators[0], columns, out)): return None out.append((_SUB, 0, 0.0)) - return out - return out if _program(body, columns, out) else None + return out, (1.0 if isinstance(body.ops[0], (ast.GtE, ast.Lt)) else -1.0) + return (out, -1.0) if _program(body, columns, out) else None def screen_program( @@ -248,7 +254,7 @@ def in_run_stops( first: int, end: int, roots: bool, -) -> tuple[InRunStops, list[int], list[int], list[list]] | None: +) -> tuple[InRunStops, list[int], list[int], list[tuple[list, float]]] | None: """The stop check for a run of *model* reporting rows ``first <= row < end``, the state and observable columns it reads, and the stop roots (none unless *roots*); None where no condition can be asked during it. @@ -276,7 +282,7 @@ def in_run_stops( species_cols: list[int] = [] obs_cols: list[int] = [] asked: list = [] - programs: list[list] = [] + programs: list[tuple[list, float]] = [] screens: list[tuple[list, bool]] | None = [] for sc in conditions: if not isinstance(sc, _ExpressionStopCondition): diff --git a/python/bngsim/kernel.py b/python/bngsim/kernel.py index d403b682d..90be60bf1 100644 --- a/python/bngsim/kernel.py +++ b/python/bngsim/kernel.py @@ -259,9 +259,10 @@ def advance( target = self._sim.current_time + dt # The state is about to move. A run_until that raises can still have - # moved it — StopConditionMet is raised after the whole interval was - # integrated and written back — and then neither the previous step's - # result nor a cached probe describes it. + # moved it — StopConditionMet is raised with the model left at the stop + # (or at the interval's end, for a condition asked after the run) — and + # then neither the previous step's result nor a cached probe describes + # it. self._last_result_is_current = False self._state_observables = None self._last_result = self._sim.run_until(target, n_points=n_points, seed=seed, **run_kwargs) diff --git a/python/tests/test_stop_condition_during_the_run.py b/python/tests/test_stop_condition_during_the_run.py index 04d2b1926..04a086caf 100644 --- a/python/tests/test_stop_condition_during_the_run.py +++ b/python/tests/test_stop_condition_during_the_run.py @@ -276,8 +276,8 @@ def test_a_crossing_the_run_lands_on_exactly_is_still_met( With 21 points the root is on the output at 5.0, where CVODE asked for the same output again returns the same root: the warm path went round that for - ever, and the cold one skipped the root and ended at 5.5. Control for - ``A_tot >= 5`` with 21 points: it holds at that output, and main ended there.""" + ever, and the cold one skipped the root and ended at 5.5. Control. With 21 + points ``A_tot >= 5`` holds at that output, and main ended there.""" if warm == "0": monkeypatch.setenv("BNGSIM_NO_WARM_CVODE", "1") met = _stop(_sim(nets["linear"], "ode", condition), t_span=(0, 10), n_points=n_points) @@ -288,24 +288,31 @@ def test_a_crossing_the_run_lands_on_exactly_is_still_met( @pytest.mark.parametrize("warm", ["1", "0"]) -def test_a_root_on_a_row_it_cannot_stand_for_keeps_the_row_s_state(nets, monkeypatch, warm): - """Control. A - 5 is 0 at the output 5.0, whose row stands after one the - result does not report (t = 0): the root is not asked, nor the time past - it, and the row is recorded at the root's state, A = 5, not the state - asked past it, where A > 5 holds and the run ended with A = 5 + 1.2e-13 at - t = 5. The run ends at the next sample, 10, as main's did.""" +def test_a_crossing_on_an_output_is_taken_past_it_in_the_next_row_s_interval( + nets, monkeypatch, warm +): + """A - 5 is 0 at the output 5.0, where ``A_tot > 5`` does not hold yet. The + row at 5.0 is recorded with A = 5, and the crossing belongs to the next + row's interval: the run ends just past 5, where the condition holds. It + ended at the next sample, 10, on main; and an earlier form of the fix + recorded the row at 5.0 with A = 5 + 1.2e-13, the state asked past it.""" if warm == "0": monkeypatch.setenv("BNGSIM_NO_WARM_CVODE", "1") - met = _stop(_sim(nets["linear"], "ode", "A_tot > 5"), t_span=(0, 10), sample_times=[5.0, 10.0]) - assert list(met.result.time) == [5.0, 10.0] - assert list(met.result.observables["A_tot"]) == [5.0, 10.0] + sim = _sim(nets["linear"], "ode", "A_tot > 5") + met = _stop(sim, t_span=(0, 10), sample_times=[5.0, 10.0]) + time = met.result.time + a = met.result.observables["A_tot"] + assert len(time) == 2 + assert time[0] == 5.0 and a[0] == 5.0 + assert 5.0 < time[1] < 5.0 + 1e-9 and a[1] > 5.0 + assert sim.current_time == time[1] @pytest.mark.parametrize("warm", ["1", "0"]) def test_a_root_on_the_last_output_ends_the_run_there(nets, monkeypatch, warm): """A strict condition whose root is the span's last output is not met in the span: the run is the one without it, and it ends (the warm path went - round the root for ever). Control: main ran it whole.""" + round the root for ever). Control. Main ran it whole.""" if warm == "0": monkeypatch.setenv("BNGSIM_NO_WARM_CVODE", "1") plain = _sim(nets["linear"]).run(t_span=(0, 5), n_points=11) @@ -315,6 +322,161 @@ def test_a_root_on_the_last_output_ends_the_run_there(nets, monkeypatch, warm): np.testing.assert_array_equal(got.species, plain.species) +@pytest.mark.parametrize("condition", ["A_tot > 5", "time > 5"]) +@pytest.mark.parametrize("warm", ["1", "0"]) +def test_a_crossing_on_the_last_sample_of_a_longer_span_is_not_a_stop( + nets, monkeypatch, warm, condition +): + """Control. The condition starts to hold at t = 5, the last of the sample + times, and the span goes on to 10: no reported row holds it, and the run + is the one without it, clock at 10. An earlier form of the fix ended the + run on a row at 5.000000000000018 the caller never asked for.""" + if warm == "0": + monkeypatch.setenv("BNGSIM_NO_WARM_CVODE", "1") + kw = dict(t_span=(0, 10), sample_times=[1.0, 5.0]) + plain_sim = _sim(nets["linear"]) + plain = plain_sim.run(**kw) + sim = _sim(nets["linear"], "ode", condition) + got = sim.run(**kw) + assert got.stop_condition is None + np.testing.assert_array_equal(got.time, plain.time) + np.testing.assert_array_equal(got.species, plain.species) + assert sim.current_time == plain_sim.current_time == 10.0 + + +# An event whose trigger is the condition's threshold, and which undoes the +# crossing: A rises at rate 1 and is reset to 0 as it passes 5, or falls and is +# refilled to 20 as it passes 5. +_RESET = """ +model m + species A, B; compartment c; c = 1; A in c; B in c; + A = 0; B = 0; k = 1; + J0: -> A; k; + E1: at (A > 5): A = 0; +end +""" +_REFILL = """ +model m + species A, B; compartment c; c = 1; A in c; B in c; + A = 10; B = 0; k = 0.2; + J0: A -> B; k*A; + E1: at (A < 5): A = 20; +end +""" + + +@pytest.mark.parametrize("n_points", [8, 11, 21]) +@pytest.mark.parametrize( + "model, condition", + [("reset", "A > 5"), ("reset", "A >= 5"), ("refill", "A < 5"), ("refill", "A <= 5")], +) +def test_a_crossing_an_event_undoes_is_not_a_stop(model, condition, n_points): + """Control. The condition starts to hold where the event fires, and the + event puts it back: no row holds it, and the run is the one without it, as + on main. An earlier form of the fix took the crossing for the stop and then + found no row holding it: "This is a bug in bngsim". The event fires where + CVODE finds its trigger after the stop root's return, which can move it + within the root tolerance, so the refill's values agree to rounding.""" + pytest.importorskip("antimony") + text = _RESET if model == "reset" else _REFILL + + def sim_of(*conditions): + sim = bngsim.Simulator(bngsim.Model.from_antimony_string(text), method="ode") + for c in conditions: + sim.add_stop_condition(c) + return sim + + plain = sim_of().run(t_span=(0, 10), n_points=n_points) + sim = sim_of(condition) + got = sim.run(t_span=(0, 10), n_points=n_points) + assert got.stop_condition is None + np.testing.assert_array_equal(got.time, plain.time) + np.testing.assert_allclose(got.species, plain.species, rtol=1e-12, atol=1e-12) + assert sim.current_time == 10.0 + + +@pytest.mark.parametrize("n_points, t_stop", [(8, 40 / 7), (11, 5.0)]) +def test_a_stop_where_an_event_fires_is_asked_at_the_next_row(n_points, t_stop): + """``A > 5`` starts to hold where the event sets B = 7. The row a stop + there would end on holds the state after the event, which the condition + was not asked of, so the stop is not taken there: the condition is asked at + the next row recorded, which holds it with B = 7, as main's did. The model + is left at that row (main left it at 10).""" + pytest.importorskip("antimony") + text = """ +model m + species A, B; compartment c; c = 1; A in c; B in c; + A = 0; B = 0; k = 1; + J0: -> A; k; + E1: at (A > 5): B = 7; +end +""" + sim = bngsim.Simulator(bngsim.Model.from_antimony_string(text), method="ode") + sim.add_stop_condition("A > 5") + met = _stop(sim, t_span=(0, 10), n_points=n_points) + assert met.result.time[-1] == pytest.approx(t_stop, abs=1e-12) + assert met.result.species[-1][1] == 7.0 + assert met.result.species[-1][0] > 5.0 + assert sim.current_time == met.result.time[-1] + + +# A <-> B conserves A + B = 10: compared with 10, the total is met or not by +# rounding. D and E decay, so the solver keeps stepping. +_CONSERVED = """begin parameters + 1 kf 1.0 + 2 kr 0.5 +end parameters +begin species + 1 A() 10 + 2 B() 0 + 3 D() 3 + 4 E() 3 +end species +begin reactions + 1 1 2 kf + 2 2 1 kr + 3 3 0 kf + 4 4 0 kf +end reactions +begin groups + 1 Atot 1 + 2 Btot 2 + 3 Tot 1,2 +end groups +""" + + +@pytest.mark.parametrize( + "condition, t_end, n_points", + [("Tot < 10", 2000, 11), ("Tot > 10", 20, 41), ("A__ + B__ < 10", 2000, 11)], +) +def test_a_total_compared_with_its_own_value_does_not_fail_the_run( + tmp_path, condition, t_end, n_points +): + """The total sits at 10 to rounding, so ``Tot - 10`` is 0 at and near + roots CVODE finds: an earlier form of the fix failed the run there with + CV_ILL_INPUT ("root found at and very near t"). Whether the condition is + met is rounding, here as on main (which stopped ``Tot > 10`` at t = 0.5); + where it stops, it holds at the row it stops on and the model is left + there. Control. Main ran ``Tot < 10`` and ``A__ + B__ < 10`` whole.""" + net = tmp_path / "conserved.net" + net.write_text(_CONSERVED) + sim = _sim(str(net), "ode", condition) + try: + result = sim.run(t_span=(0, t_end), n_points=n_points) + except StopConditionMet as met: + result = met.result + assert result.stop_condition == condition + obs = result.observables + tot = ( + obs["Tot"][-1] if "Tot" in condition else result.species[-1][0] + result.species[-1][1] + ) + assert tot < 10 if "<" in condition else tot > 10 + assert sim.current_time == result.time[-1] + else: + assert sim.current_time == t_end + + def test_a_long_span_met_early_costs_the_short_run(nets): """A Lotka-Volterra cycle over (0, 1e4) met at t = 5 takes the steps a run to 5 takes, not the 1e4 of cycles after it.""" @@ -487,7 +649,7 @@ def test_a_start_far_from_zero_ends_at_its_crossing(nets, condition, at): is asked at the samples alone, and ends the run at the one past it, 6: on the caller's clock the time moves in steps of 1.2e-4 there, which the root search, on the run's, took for flat, and the run failed (CV_ILL_INPUT). - Control for that one: main ended at the same sample.""" + Control. Main ended the time condition at the same sample.""" t0 = 1e12 sim = _sim(nets["decay"], "ode", condition) met = _stop(sim, t_span=(t0, t0 + 100), n_points=101) @@ -806,7 +968,7 @@ def test_a_stop_the_result_does_not_hold_is_a_bug_said_aloud(nets, monkeypatch, run = dict(t_span=(0, 100), n_points=101) # A conjunction, which the engine asks Python of at every row. condition = "A_tot < 10 and t > 0" - with pytest.raises(bngsim.BngsimError, match="issue #2018"): + with pytest.raises(bngsim.BngsimError, match="none holds at any sample its result reports"): if entry == "run": _sim(nets["decay"], "ode", condition).run(**run) elif entry == "run_batch": diff --git a/src/_bngsim_core.cpp b/src/_bngsim_core.cpp index d6aaa9d5d..90733b4f1 100644 --- a/src/_bngsim_core.cpp +++ b/src/_bngsim_core.cpp @@ -1031,14 +1031,23 @@ static bngsim::StopCheck make_stop_check(py::object fn, std::vector species }; } -// Issue #2018: stop roots as Python hands them, one list of (kind, index, -// value) operations per root (bngsim._stop_in_run). -static std::vector -stop_roots_from(const std::vector>> &roots) { +// Issue #2018: stop roots as Python hands them, one (program, side) per root: +// the program a list of (kind, index, value) operations, and the side, +1 or +// -1, a g of exactly 0 reads as (StopRoot::at_zero), or 0 for none +// (bngsim._stop_in_run). +using StopRootSpec = std::tuple>, double>; + +static std::vector stop_roots_from(const std::vector &roots) { std::vector out; out.reserve(roots.size()); - for (const auto &program : roots) { + for (const auto &[program, side] : roots) { bngsim::StopRoot root; + if (side != 0.0 && side != 1.0 && side != -1.0) { + throw std::invalid_argument("set_stop_roots: a root's side is +1, -1 or 0, not " + + std::to_string(side)); + } + // The least normal double: below any g that is not 0 but a denormal. + root.at_zero = side * std::numeric_limits::min(); root.program.reserve(program.size()); for (const auto &[kind, index, value] : program) { bngsim::StopRootOp op; @@ -1265,14 +1274,15 @@ PYBIND11_MODULE(_bngsim_core, m) { "observables at the columns named. True ends the run on that row. None clears it.") .def( "set_stop_roots", - [](bngsim::SolverOptions &self, - const std::vector>> &roots) { + [](bngsim::SolverOptions &self, const std::vector &roots) { self.stop_roots = stop_roots_from(roots); }, py::arg("roots"), - "Issue #2018: the stop conditions' root functions, each a list of (kind, index, " - "value) operations on a stack (bngsim._stop_in_run); CVODE finds where each " - "changes sign, and the stop check decides there. Needs a stop check.") + "Issue #2018: the stop conditions' root functions, each (program, side): the " + "program a list of (kind, index, value) operations on a stack " + "(bngsim._stop_in_run), and the side (+1, -1 or 0) a value of exactly 0 reads as. " + "CVODE finds where each changes sign, and the stop check decides there. Needs a " + "stop check.") .def( "set_crossing_stops", [](bngsim::SolverOptions &self, diff --git a/src/cvode_simulator.cpp b/src/cvode_simulator.cpp index 4abf81774..a9cfcc65c 100644 --- a/src/cvode_simulator.cpp +++ b/src/cvode_simulator.cpp @@ -3823,14 +3823,14 @@ static double stop_root_value(const StopRoot &root, double t, const double *x, return stack.back(); } -// Refuse a stop root whose program would read outside the run's state or +// Refuse a stop root (issue #2018) whose program would read outside the run's state or // observables, or leave its stack other than one deep, before CVODE is given // it. Python compiles them (bngsim._stop_in_run), so a refusal here is a bug // there. static void validate_stop_roots(const SolverOptions &opts, int n_state, int n_obs) { if (!opts.stop_roots.empty() && !opts.stop_check) { throw std::invalid_argument("SolverOptions: stop roots were given without a stop check, " - "which decides at each of them (issue #2018)"); + "which decides at each of them"); } for (std::size_t r = 0; r < opts.stop_roots.size(); ++r) { long depth = 0; @@ -3844,14 +3844,13 @@ static void validate_stop_roots(const SolverOptions &opts, int n_state, int n_ob if ((!push && !binary && op.kind != StopRootOp::Neg) || !ok_index || (binary && depth < 2) || (op.kind == StopRootOp::Neg && depth < 1)) { throw std::invalid_argument("SolverOptions: stop root " + std::to_string(r) + - " is not a program over this model's state " - "(issue #2018)"); + " is not a program over this model's state"); } depth += push ? 1 : (binary ? -1 : 0); } if (depth != 1) { throw std::invalid_argument("SolverOptions: stop root " + std::to_string(r) + - " does not leave one value (issue #2018)"); + " does not leave one value"); } } } @@ -3870,8 +3869,12 @@ static int cvode_run_root_fn_body(sunrealtype t, N_Vector y, sunrealtype *gout, const double *x = N_VGetArrayPointer(y); const std::vector &roots = *data->stop_roots; for (std::size_t j = 0; j < roots.size(); ++j) { - gout[static_cast(off) + j] = + double g = stop_root_value(roots[j], static_cast(t), x, *data->model, *data->stop_stack); + if (g == 0.0 && roots[j].at_zero != 0.0) { + g = roots[j].at_zero; // StopRoot::at_zero + } + gout[static_cast(off) + j] = g; } return 0; } @@ -3881,30 +3884,6 @@ static int cvode_run_root_fn(sunrealtype t, N_Vector y, sunrealtype *gout, void [&] { return cvode_run_root_fn_body(t, y, gout, user_data); }); } -// Where a stop condition not met at its root is asked again (issue #2018). A -// root CVODE finds on the boundary itself, g exactly 0, as it does for a -// condition linear in the time (`t > 5`, a species made at a constant rate), -// is where a strict one (`>`, `<`) is not yet met, and CVODE reports no root -// as g leaves 0. It is asked a few roundings past the root, inside the step -// CVODE has taken and before the row's output (t_row), which asks it in any -// case. A root on that output itself, which CVODE returns again each time it -// is asked for the same output, is the output's row, and the time past it -// stands in for the row up to the next output (t_after; none past the last); -// NaN where there is no such time. -static double stop_root_past(void *cvode_mem, double t_root, double t_row, double t_after) { - sunrealtype tn = 0.0; - sunrealtype h = 0.0; - CVodeGetCurrentTime(cvode_mem, &tn); - CVodeGetLastStep(cvode_mem, &h); - const double t_past = t_root + 16.0 * std::numeric_limits::epsilon() * - (std::fabs(t_root) + std::fabs(static_cast(h))); - const double t_limit = t_root < t_row ? t_row : t_after; - if (t_past > t_root && t_past <= static_cast(tn) && t_past < t_limit) { - return t_past; - } - return std::numeric_limits::quiet_NaN(); -} - // ─── Forward-sensitivity run state ─────────────────────────────────────────── // // Everything Impl::setup_forward_sensitivities() resolves for one run(): the @@ -6431,7 +6410,10 @@ Result CvodeSimulator::Impl::run_warm(const TimeSpec ×, const SolverOptions }); // A stop condition's root (issue #2018): asked there, of the // row's values as recorded below. Met, the row is the root's and - // the run ends on it; not met, the run goes on to the output. + // the run ends on it; not met, the run goes on to the output. A + // root is where g reads on the condition's new side + // (StopRoot::at_zero), so a condition that starts to hold there + // holds at it. const auto ask = [&](double t_ask) { const double *fv = fill_row(t_ask); std::copy(y_data, y_data + ns, stop_state.begin()); @@ -6443,20 +6425,7 @@ Result CvodeSimulator::Impl::run_warm(const TimeSpec ×, const SolverOptions }; while (flag == CV_ROOT_RETURN) { const double t_root = static_cast(t_ret); - bool met = ask(t_root); - if (!met) { - const double t_past = stop_root_past(cvode_mem, t_root, t_out[i], - i + 1 < n_out ? t_out[i + 1] : t_out[i]); - if (std::isfinite(t_past) && CVodeGetDky(cvode_mem, t_past, 0, w.y) == 0) { - met = ask(t_past); - if (met) { - t_ret = static_cast(t_past); - } else { - CVodeGetDky(cvode_mem, t_ret, 0, w.y); // the root's state back - } - } - } - if (met) { + if (ask(t_root)) { t_out[i] = static_cast(t_ret); stop_met = true; break; @@ -21774,6 +21743,46 @@ Result CvodeSimulator::run(const TimeSpec ×, const SolverOptions &opts) { // one buffer for the run rather than one allocated for each row. NVectorGuard row_ahead; + // Whether an event's trigger rises half a root tolerance past t, read as + // the row read-ahead below reads it at an output CVODE has stepped to + // (issue #2018): a row a stop root ends on there is recorded after that + // event fires. The model's species are put back. + auto trigger_rises_past = [&](double t) -> bool { + if (n_events == 0) { + return false; + } + sunrealtype t_step_end = static_cast(t); + CVodeGetCurrentTime(cvode_mem, &t_step_end); + sunrealtype h_last = 0.0; + CVodeGetLastStep(cvode_mem, &h_last); + const double t_ahead = t + 50.0 * std::numeric_limits::epsilon() * + (std::fabs(static_cast(t_step_end)) + + std::fabs(static_cast(h_last))); + if (!row_ahead) { + row_ahead = NVectorGuard(N_VClone(y)); + } + if (CVodeGetDky(cvode_mem, static_cast(t_ahead), 0, row_ahead) != CV_SUCCESS) { + return false; // the row's read-ahead reads none either + } + const double *x_ahead = row_ahead.data(); + if (trigger_plan.full) { + impl_->sync_model_at(t, x_ahead, ns); + } else { + for (int si = 0; si < ns; ++si) { + sp_vec_outer[si].concentration = x_ahead[si]; + } + model.evaluate_read_plan(t, x_ahead, trigger_plan); + } + bool rises = false; + for (int ei = 0; ei < n_events && !rises; ++ei) { + rises = !trigger_was_true[ei] && event_dormant[ei] == 0 && read_trigger(ei, t); + } + for (int si = 0; si < ns; ++si) { + sp_vec_outer[si].concentration = y_data[si]; + } + return rises; + }; + // A step that crossed a state switch's surface, re-taken from its start // up to the crossing (kCrossingStepShare). CVODE's history at the step's // start is the state it stepped from: BDF's correction vanishes at the @@ -23521,25 +23530,17 @@ Result CvodeSimulator::run(const TimeSpec ×, const SolverOptions &opts) { return opts.stop_check(i, t_ask, stop_state.data(), ns, stop_obs.data(), n_obs, /*at_root=*/true); }; + // A root is where g reads on the condition's new side + // (StopRoot::at_zero), so one that starts to hold there + // holds at it. Where a trigger rises there too, the row + // the stop would end on holds the state after the event + // (the row's read-ahead below fires it), not the state + // the condition was asked of: that row is not the stop, + // and the condition is asked at the next row recorded. const double t_root = static_cast(t_ret); - double t_stop = t_root; - bool met = ask(t_root); - if (!met) { - const double t_past = stop_root_past( - cvode_mem, t_root, t_out[i], i + 1 < n_out ? t_out[i + 1] : t_out[i]); - if (std::isfinite(t_past) && CVodeGetDky(cvode_mem, t_past, 0, y) == 0) { - met = ask(t_past); - if (met) { - t_stop = t_past; - } else { - CVodeGetDky(cvode_mem, t_ret, 0, y); // the root's state back - } - } - } - if (met) { - t_ret = static_cast(t_stop); + if (ask(t_root) && !trigger_rises_past(t_root)) { t_now = t_ret; - t_out[i] = t_stop; + t_out[i] = t_root; stop_row_at_root = true; break; } From 3c7b089643df917289194cd9ba61336f6d0aca14 Mon Sep 17 00:00:00 2001 From: Bill Hlavacek Date: Thu, 3 Dec 2026 18:32:45 -0700 Subject: [PATCH 07/11] test: a stop root's side is checked when set; batch rows keep the safety net (#2018) run_batch and run_replicates take any short row for a stop, as before: a row ends short only on a stop or a steady state (a timeout raises), so a short row no condition holds at is a bug, and the check says so rather than returning the row. --- python/bngsim/_simulator.py | 16 +++++----------- .../tests/test_stop_condition_during_the_run.py | 11 +++++++++++ 2 files changed, 16 insertions(+), 11 deletions(-) diff --git a/python/bngsim/_simulator.py b/python/bngsim/_simulator.py index f1acbacda..de4c62bef 100644 --- a/python/bngsim/_simulator.py +++ b/python/bngsim/_simulator.py @@ -7511,14 +7511,11 @@ def _run_one_here(i: int) -> Result: # Each row meets the stop conditions as run() does, and one that meets # one comes back cut there, beside the rest (issue #1369); an ODE, SSA - # or PSA row's run ends there too (issue #2018), where its engine was - # given any to ask, as for run(). Every row was given the same ones: a - # clone reports the columns of the model it was made from. + # or PSA row's run ends there too (issue #2018). A row ends short only + # there or at a steady state (a timeout raises), so a short row no + # condition holds at is a bug, and _stopped says so. if self._stop_conditions: - given = bool(self._ssa_stops(self._model, n_points, 0, 0)) - results = [ - self._stopped(r, ended=given and _ended_on_a_stop(r, n_points)) for r in results - ] + results = [self._stopped(r, ended=_ended_on_a_stop(r, n_points)) for r in results] # Each row is stamped already, against its own clone (issues #698, #743). if squeeze: @@ -7766,10 +7763,7 @@ def _worker(i: int) -> Result: # As run_batch's rows (issues #1369, #2018). if self._stop_conditions: - results = [ - self._stopped(r, ended=bool(stops) and _ended_on_a_stop(r, n_points)) - for r in results - ] + results = [self._stopped(r, ended=_ended_on_a_stop(r, n_points)) for r in results] # Every row is stamped already; stamping the stack again would replace # the rows' own report metadata with the parent's (issue #743). diff --git a/python/tests/test_stop_condition_during_the_run.py b/python/tests/test_stop_condition_during_the_run.py index 04a086caf..a84ccfb3a 100644 --- a/python/tests/test_stop_condition_during_the_run.py +++ b/python/tests/test_stop_condition_during_the_run.py @@ -994,3 +994,14 @@ def interrupt(self, row, *a): sim.run(t_span=(0, 100), n_points=101, seed=1) assert sim.current_time == 0.0 np.testing.assert_array_equal(sim.model.get_state(), before) + + +@pytest.mark.parametrize("side", [2.0, 0.5, -0.0001, float("nan")]) +def test_a_stop_root_s_side_is_one_of_three(side): + """A stop root's side says which way an exact 0 reads, +1, -1 or 0; any + other value is refused when the roots are set, not read as a scale.""" + from bngsim._bngsim_core import SolverOptions + + with pytest.raises(ValueError, match="side is"): + SolverOptions().set_stop_roots([([(0, 0, 1.0)], side)]) + SolverOptions().set_stop_roots([([(0, 0, 1.0)], s) for s in (1.0, -1.0, 0.0)]) From 7f409653ab81ce7f61977599bcfda9f02ce7b0f5 Mon Sep 17 00:00:00 2001 From: Bill Hlavacek Date: Thu, 3 Dec 2026 18:40:10 -0700 Subject: [PATCH 08/11] test: a trigger already true at the crossing does not hold the stop back (#2018) --- .../test_stop_condition_during_the_run.py | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/python/tests/test_stop_condition_during_the_run.py b/python/tests/test_stop_condition_during_the_run.py index a84ccfb3a..dac1af3aa 100644 --- a/python/tests/test_stop_condition_during_the_run.py +++ b/python/tests/test_stop_condition_during_the_run.py @@ -420,6 +420,29 @@ def test_a_stop_where_an_event_fires_is_asked_at_the_next_row(n_points, t_stop): assert sim.current_time == met.result.time[-1] +@pytest.mark.parametrize("trigger", ["time > 1", "A < 90"]) +def test_a_trigger_already_true_at_the_crossing_does_not_hold_the_stop_back(trigger): + """The event fired near t = 1 and its trigger stays true: none rises at + the crossing of ``A < 50``, so the row there holds the condition and the + run ends at the crossing, 6.93, with B = 7. Main ended at the sample + after it, 7.""" + pytest.importorskip("antimony") + text = f""" +model m + species A, B; compartment c; c = 1; A in c; B in c; + A = 100; B = 0; k = 0.1; + J0: A -> ; k*A; + E1: at ({trigger}): B = 7; +end +""" + sim = bngsim.Simulator(bngsim.Model.from_antimony_string(text), method="ode") + sim.add_stop_condition("A < 50") + met = _stop(sim, t_span=(0, 100), n_points=101) + assert met.result.time[-1] == pytest.approx(HALF_AT, rel=1e-6) + assert met.result.species[-1][1] == 7.0 + assert sim.current_time == met.result.time[-1] + + # A <-> B conserves A + B = 10: compared with 10, the total is met or not by # rounding. D and E decay, so the solver keeps stepping. _CONSERVED = """begin parameters From 4c702ed5a703d6697bd35d6be30d7df248ebe71e Mon Sep 17 00:00:00 2001 From: Bill Hlavacek Date: Thu, 3 Dec 2026 18:47:57 -0700 Subject: [PATCH 09/11] test: a root on an output the check declines lets the run go on (#2018) --- .../test_stop_condition_during_the_run.py | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/python/tests/test_stop_condition_during_the_run.py b/python/tests/test_stop_condition_during_the_run.py index dac1af3aa..5cb8401fb 100644 --- a/python/tests/test_stop_condition_during_the_run.py +++ b/python/tests/test_stop_condition_during_the_run.py @@ -1028,3 +1028,38 @@ def test_a_stop_root_s_side_is_one_of_three(side): with pytest.raises(ValueError, match="side is"): SolverOptions().set_stop_roots([([(0, 0, 1.0)], side)]) SolverOptions().set_stop_roots([([(0, 0, 1.0)], s) for s in (1.0, -1.0, 0.0)]) + + +@pytest.mark.parametrize("side", [0.0, -1.0, 1.0]) +@pytest.mark.parametrize("warm", ["1", "0"]) +def test_a_root_on_an_output_the_check_declines_lets_the_run_go_on(nets, monkeypatch, warm, side): + """Through the engine's own options: g = A - 5 with A = t is 0 at the + output 5.0, and the check says no at every row and root. Read as 0 there + (side 0, which Python never sends), CVODE asked for the same output again + returns the same root, and the warm path went round it for ever; it takes + the output's row and goes on. Read on a side, the root is where g changes + sign, at 5.0 or just past it, and the run goes on from it.""" + from bngsim._bngsim_core import CvodeSimulator, SolverOptions, TimeSpec + from bngsim._stop_in_run import _CONST, _SPECIES, _SUB + + if warm == "0": + monkeypatch.setenv("BNGSIM_NO_WARM_CVODE", "1") + else: + monkeypatch.delenv("BNGSIM_NO_WARM_CVODE", raising=False) + asked = [] + + def check(row, t, x, obs, at_root): + asked.append((row, t, at_root)) + return False + + opts = SolverOptions() + opts.set_stop_check(check, [0], []) + opts.set_stop_roots([([(_SPECIES, 0, 0.0), (_CONST, 0, 5.0), (_SUB, 0, 0.0)], side)]) + times = TimeSpec() + times.t_start, times.t_end, times.n_points = 0.0, 10.0, 21 + model = bngsim.Model.from_net(nets["linear"]) + result = CvodeSimulator(model._core).run(times, opts) + assert len(result.time) == 21 + roots = [(row, t) for row, t, at_root in asked if at_root] + assert len(roots) == 1 + assert 5.0 <= roots[0][1] < 5.0 + 1e-9 From 3f58a4db688a48b17ac66bf827ef964f23070b3b Mon Sep 17 00:00:00 2001 From: Bill Hlavacek Date: Thu, 3 Dec 2026 19:33:45 -0700 Subject: [PATCH 10/11] fix: a far root that rounds onto the row before it is not the stop (#2018) A run far from zero keeps its own clock, and a stop root lies past the row before it by about its root tolerance. Moved back to the caller's clock it can round onto that row's time: from 1e9, A = t crossing 5 on the sample at +5 returned a second row at 1e9 + 5, and a condition met just past the start returned two rows at the start with the clock left there. Such a root is now declined, and the condition is asked at the next sample, the row main stopped at. Tests for that, and for a strict condition on its threshold at the start, which now ends the run within the root tolerance of the start. The user guide says both, and that a delayed event is not looked ahead to. The changelog no longer says a condition only rounding decides gives main's run. Two stale comments; a run-time message no longer cites the issue. --- changelog.d/2018.fixed.md | 2 +- docs/user-guide/simulation.md | 16 ++++--- .../test_stop_condition_during_the_run.py | 45 +++++++++++++++++++ src/_bngsim_core.cpp | 2 +- src/cvode_simulator.cpp | 31 +++++++++---- 5 files changed, 81 insertions(+), 15 deletions(-) diff --git a/changelog.d/2018.fixed.md b/changelog.d/2018.fixed.md index a5f55b40f..bf117423f 100644 --- a/changelog.d/2018.fixed.md +++ b/changelog.d/2018.fixed.md @@ -1 +1 @@ -- **A stop condition now ends the run where it holds; it was asked only after the run had gone to its end.** `A' = A²` from A = 1 passes 10 at t = 0.9 and blows up at t = 1: with `add_stop_condition("Atot > 10")` over (0, 2) the run raised `SimulationError`, and now returns `StopConditionMet` at t = 0.9 (0.8999993). An ODE, SSA or PSA run asks an expression condition at each sample and ends at the first it holds at; an ODE run ends where a comparison (`<`, `<=`, `>`, `>=`) or a number starts to hold, at the crossing, not the next sample. The model is left at the stop, with `current_time` its time, where it was left at the span's end. A long span met early costs the short run: an SSA run of A → 2A to `Atot > 1e4` over (0, 30) ran to its timeout, and ends at t ≈ 7. The first sample any condition holds at ends the run, named by the first condition added that holds there. A callable, a condition on a species reported after the run, a network-free run and a `.net` model whose rate law switches on its state are still asked after the run. A condition never met gives the same run, bit for bit, unless it crosses where an event fires, which can then move within the root tolerance. +- **A stop condition now ends the run where it holds; it was asked only after the run had gone to its end.** `A' = A²` from A = 1 passes 10 at t = 0.9 and blows up at t = 1: with `add_stop_condition("Atot > 10")` over (0, 2) the run raised `SimulationError`, and now returns `StopConditionMet` at t = 0.9. An ODE, SSA or PSA run asks an expression condition at each sample and ends at the first it holds at; an ODE run ends where a comparison or a number starts to hold, at the crossing. The model is left at the stop, with `current_time` its time. An SSA run of A → 2A to `Atot > 1e4` over (0, 30) ran to its timeout, and ends at t ≈ 7. Where several hold at one sample, the first added names it. Callables, conditions on species reported after the run, network-free runs and `.net` models whose rate law switches on its state are still asked after the run. A condition that never holds gives the same run, bit for bit, unless it meets its threshold where an event fires: the event, or the stop, can then move within the root tolerance. A comparison only rounding decides (a total against its own value) can now stop a run main ran whole; compare with a margin. diff --git a/docs/user-guide/simulation.md b/docs/user-guide/simulation.md index 5ee7e361f..4cf34bb08 100644 --- a/docs/user-guide/simulation.md +++ b/docs/user-guide/simulation.md @@ -254,11 +254,17 @@ first one it holds at, so a long interval met early costs only the run to the stop, and a model that would fail later stops before it fails. An ODE run also finds where a comparison (`lhs < rhs`, `<=`, `>`, `>=`) or a number starts to hold between two samples, and ends at that time: here `e.result.time[-1]` is -where `Bound_hot` falls through 10000, not the sample after it. Two cases are -asked at the samples alone: a condition that reads the time, in a run -integrated on the time since a start far from zero; and a crossing at the -instant an event fires, since a sample there holds the state after the event, -so the run ends at the next sample that holds the condition. `e.result` ends at +where `Bound_hot` falls through 10000, not the sample after it. A strict +comparison that sits on its threshold at the start and leaves it at once +(`Ctot > 0` with C made from 0) ends the run just after the start, within the +solver's root tolerance of it. Three cases are asked at the samples alone, so +the run ends at the next sample that holds the condition: a condition that +reads the time, in a run integrated on the time since a start far from zero; a +crossing that, in such a run, rounds onto the time of the sample before it; and +a crossing at the instant an event's trigger rises, since a sample there holds +the state after the event. A delayed event is not looked ahead to: a crossing +within the root tolerance before its assignments are made ends the run with +the state before them, as a sample there would record it. `e.result` ends at the stop, the model is left at its state, and `sim.current_time` is its time, so a following `run_until` continues from the stop. diff --git a/python/tests/test_stop_condition_during_the_run.py b/python/tests/test_stop_condition_during_the_run.py index 5cb8401fb..36224a836 100644 --- a/python/tests/test_stop_condition_during_the_run.py +++ b/python/tests/test_stop_condition_during_the_run.py @@ -551,6 +551,27 @@ def test_a_condition_held_at_the_start_takes_no_step(nets, monkeypatch, net, met np.testing.assert_array_equal(sim.model.get_state(), start) +@pytest.mark.parametrize("warm", ["1", "0"]) +@pytest.mark.parametrize("net, condition", [("linear", "A_tot > 0"), ("decay", "A_tot < 100")]) +def test_a_strict_condition_on_its_threshold_at_the_start_ends_just_after_it( + nets, monkeypatch, warm, net, condition +): + """A_tot starts on the threshold, where the strict condition does not hold, + and leaves it at once: the run ends at the crossing, within the root + tolerance of the start, and the condition holds at the row it ends on. Main + ended it at the first sample, t = 1.""" + if warm == "0": + monkeypatch.setenv("BNGSIM_NO_WARM_CVODE", "1") + sim = _sim(nets[net], "ode", condition) + met = _stop(sim, t_span=(0, 10), n_points=11) + assert met.result.time[0] == 0.0 + assert len(met.result.time) == 2 + assert 0.0 < met.result.time[-1] < 1e-12 + a = met.result.species[-1, 0] + assert a > 0.0 if net == "linear" else a < 100.0 + assert sim.current_time == met.result.time[-1] + + @pytest.mark.parametrize("warm", ["1", "0"]) def test_a_rule_the_model_holds_is_read_at_the_stop(monkeypatch, warm): """p := time, read at the crossing the run ends at, 6.93: it was read at @@ -680,6 +701,30 @@ def test_a_start_far_from_zero_ends_at_its_crossing(nets, condition, at): assert sim.current_time == met.result.time[-1] +@pytest.mark.parametrize("t0", [1e9, 1e12]) +@pytest.mark.parametrize("condition, rows", [("A_tot > 5", 7), ("A_tot > 0", 2)]) +def test_a_root_that_rounds_onto_the_row_before_it_is_asked_at_the_next_row( + nets, t0, condition, rows +): + """Far from zero the run keeps its own clock, and a root lies past the row + before it by about its root tolerance: moved back to the caller's clock, it + rounds onto that row's time. A_tot = t crosses 5 on the sample at +5, and 0 + just past the start; each returned a second row with the time of the one + before it (+5 twice; the start twice, with the clock left there). Such a + root is not the stop, and the condition is asked at the next sample, +6 or + +1, the row main stopped at. Through run_batch too.""" + kw = dict(t_span=(t0, t0 + 10), n_points=11) + sim = _sim(nets["linear"], "ode", condition) + met = _stop(sim, **kw) + batch = _sim(nets["linear"], "ode", condition).run_batch(params=[{"k": 1.0}], **kw)[0] + for r in (met.result, batch): + assert len(r.time) == rows + assert np.all(np.diff(r.time) > 0) + assert r.time[-1] == t0 + (rows - 1) + assert r.species[-1, 0] == pytest.approx(rows - 1, rel=1e-9) + assert sim.current_time == met.result.time[-1] + + def test_a_sensitivity_run_ends_at_the_crossing_with_its_sensitivity(nets): """dA/dk = -t A, -6.93 * 50 at the crossing.""" met = _stop( diff --git a/src/_bngsim_core.cpp b/src/_bngsim_core.cpp index 90733b4f1..c3d712d03 100644 --- a/src/_bngsim_core.cpp +++ b/src/_bngsim_core.cpp @@ -1018,7 +1018,7 @@ static bngsim::StopCheck make_stop_check(py::object fn, std::vector species if (j < 0 || j >= n) { throw std::out_of_range(std::string("stop check: ") + what + " column " + std::to_string(j) + " is outside the run's " + - std::to_string(n) + " (issue #2018)"); + std::to_string(n)); } o[k] = from[j]; } diff --git a/src/cvode_simulator.cpp b/src/cvode_simulator.cpp index a9cfcc65c..eaee40ea7 100644 --- a/src/cvode_simulator.cpp +++ b/src/cvode_simulator.cpp @@ -7819,9 +7819,11 @@ void CvodeSimulator::Impl::register_roots(void *cvode_mem, SUNContext ctx, int n if (flag != CV_SUCCESS) { throw std::runtime_error("CVodeRootInit failed: " + std::to_string(flag)); } - // A stop condition that holds on its surface from the start (`t > 0` at - // t = 0) is a root CVODE leaves inactive there, and says so on standard - // error; the condition is still asked at every row. + // A stop root reads an exact 0 on the side its condition is on there + // (StopRoot::at_zero), so CVODE never finds one on its surface at the + // start. One given side 0, through the engine's own options (Python always + // gives a side), can sit there: CVODE leaves it inactive and says so on + // standard error, and the condition is still asked at every row. if (n_stop_roots > 0) { CVodeSetNoInactiveRootWarn(cvode_mem); } @@ -18183,9 +18185,21 @@ Result CvodeSimulator::run(const TimeSpec ×, const SolverOptions &opts) { }); }), moved.stop_roots.end()); - moved.stop_check = [&opts, &back, &root_row](int row, double t, const double *x, - int n_x, const double *obs, int n_o, - bool at_root) { + // A root lies past the row before it on the run's clock, but by + // about its root tolerance, and moved back it can round onto that + // row's time: from 1e9, `Ctot > 5` crossing on the sample at +5 + // returned a second row at 1e9 + 5, and a condition met just past + // the start returned two rows at the start. Such a root is not the + // stop, and the condition is asked at the next row, as on main. + moved.stop_check = [&opts, &back, &root_row, &asked, t_first = times.t_start]( + int row, double t, const double *x, int n_x, const double *obs, + int n_o, bool at_root) { + if (at_root) { + const double before = + row >= 1 ? asked[static_cast(row - 1)] : t_first; + if (!(back(t) > before)) + return false; + } const bool met = opts.stop_check(row, back(t), x, n_x, obs, n_o, at_root); if (met && at_root) { root_row = row; @@ -23491,8 +23505,9 @@ Result CvodeSimulator::run(const TimeSpec ×, const SolverOptions &opts) { // ─── A stop condition's root (issue #2018) ─────────────────────── // A return at stop conditions' roots alone. The condition is asked // there: met, the root's time becomes this row's and the run ends - // on it; not met (the row is one the caller did not ask for, or - // the condition is not true at its own surface), the return is no + // on it; not met (the row is one the caller did not ask for, the + // condition stops holding there rather than starts, or, far from + // zero, the root rounds onto the row before it), the return is no // event of the model's and the run goes on from it, as from a // step. A return that also holds a root of the model's is the // model's, handled below as it always was, and the condition is From 0f5c4edb24d22bc29857dbfb83ece3738e41315f Mon Sep 17 00:00:00 2001 From: Bill Hlavacek Date: Fri, 4 Dec 2026 09:04:38 -0700 Subject: [PATCH 11/11] fix: the stop screen builds with MSVC (#2018) MSVC failed on the stop check with an internal compiler error (C1001) at the std::any_of whose generic lambda read a thread_local declared in the check's own lambda; every Windows leg stopped there. The screen loop is now a plain function holding its own thread_local stack, and asks the screens in the same order, stopping at the first that may hold. The least normal double at a stop root's side is written (std::numeric_limits::min)(), safe from a min macro. --- src/_bngsim_core.cpp | 29 +++++++++++++++++++---------- 1 file changed, 19 insertions(+), 10 deletions(-) diff --git a/src/_bngsim_core.cpp b/src/_bngsim_core.cpp index 2c3e02c95..5b5718d29 100644 --- a/src/_bngsim_core.cpp +++ b/src/_bngsim_core.cpp @@ -975,6 +975,22 @@ static std::vector stop_screens_of(const py::object &fn) { return out; } +// Whether any screen is on the side its condition may hold on at this row (a +// NaN may). A plain function, not a lambda inside the check: MSVC failed with +// an internal compiler error (C1001) on a thread_local inside the check's +// lambda read from a generic lambda nested in it. +static bool a_screen_may_hold(const std::vector &screens, double t, const double *x, + int n_x, const double *obs, int n_obs) { + thread_local std::vector stack; + for (const StopScreen &s : screens) { + const double g = screen_value(s, t, x, n_x, obs, n_obs, stack); + if (!(s.strict ? g <= 0.0 : g < 0.0)) { + return true; + } + } + return false; +} + // Issue #2018: a Python stop check as the engines call it. Python is given // the row, its time, the state entries and observables at the columns named // (each a copy, as a numpy array), and whether the row is a stop root's, and @@ -999,15 +1015,8 @@ static bngsim::StopCheck make_stop_check(py::object fn, std::vector species return [held, species_cols = std::move(species_cols), obs_cols = std::move(obs_cols), screens = std::move(screens)](int row, double t, const double *x, int n_x, const double *obs, int n_obs, bool at_root) -> bool { - if (!screens.empty()) { - thread_local std::vector stack; - const bool may_hold = std::any_of(screens.begin(), screens.end(), [&](const auto &s) { - const double g = screen_value(s, t, x, n_x, obs, n_obs, stack); - return !(s.strict ? g <= 0.0 : g < 0.0); // NaN: may hold - }); - if (!may_hold) { - return false; - } + if (!screens.empty() && !a_screen_may_hold(screens, t, x, n_x, obs, n_obs)) { + return false; } const auto pick = [](const std::vector &cols, const double *from, int n, const char *what) { @@ -1047,7 +1056,7 @@ static std::vector stop_roots_from(const std::vector::min(); + root.at_zero = side * (std::numeric_limits::min)(); // (): a Windows min macro root.program.reserve(program.size()); for (const auto &[kind, index, value] : program) { bngsim::StopRootOp op;