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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog.d/2018.fixed.md
Original file line number Diff line number Diff line change
@@ -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. 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.
2 changes: 1 addition & 1 deletion docs/reference/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -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), 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):
Expand Down
2 changes: 1 addition & 1 deletion docs/reference/command-line.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
48 changes: 40 additions & 8 deletions docs/user-guide/simulation.md
Original file line number Diff line number Diff line change
Expand Up @@ -248,12 +248,44 @@ 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. 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.

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.

To continue from where a step started instead, take a snapshot first:

Expand Down Expand Up @@ -297,8 +329,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
Expand Down
5 changes: 5 additions & 0 deletions include/bngsim/model.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
12 changes: 9 additions & 3 deletions include/bngsim/simulator.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -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 &times, 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 &times, 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 &times, 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
Expand Down Expand Up @@ -142,7 +148,7 @@ class SsaSimulator {

// Internal: shared SSA/PSA simulation loop
Result run_internal(const TimeSpec &times, uint64_t seed, double poplevel,
double timeout_seconds);
double timeout_seconds, const StopCheck &stop);
};

} // namespace bngsim
54 changes: 54 additions & 0 deletions include/bngsim/types.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -1887,6 +1887,55 @@ 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<bool(int row, double t, const double *state, int n_state,
const double *observables, int n_observables, bool at_root)>;

// 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.
//
// 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<StopRootOp> program;
double at_zero = 0.0;
};

// ─── Solver options ──────────────────────────────────────────────────────────
struct SolverOptions {
double rtol = 1e-8; // relative tolerance
Expand Down Expand Up @@ -2087,6 +2136,11 @@ 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<StopRoot> stop_roots;
};

// ─── Time specification ──────────────────────────────────────────────────────
Expand Down
Loading
Loading