CRN-craft
CRN-craft simulates chemical reaction networks stochastically, from Python, with a native engine.
pip install crn-craft
This example builds a model, runs 1,000 trajectories and prints their means:
import crn_craft as crn
model = crn.Model("immigration_death")
model.add_species("A", 0)
model.add_reaction(4.0, [], ["A"], name="birth") # molecules arrive at rate 4
model.add_reaction(0.2, ["A"], [], name="death") # each one decays at rate 0.2
run = crn.ensemble(model, end=10.0, report_times=[0.0, 5.0, 10.0],
replicates=1000, seed=1, threads=2, method="static_direct")
result = run.simulate()
print(result.statistics["mean"]) # exact: 20 * (1 - exp(-0.2 t)) = 0, 12.64, 17.29
A
time
0.0 0.000
5.0 12.623
10.0 17.305
The 1,000 trajectories ran on two threads in one call, and the same seed gives the same numbers on any number of threads.
Why CRN-craft
- Many trajectories in one call. An ensemble runs on native threads, and the same seed gives the same result on any number of threads (chapter 3).
- Compiled models from Python.
crn.compile_loop(model)compiles a model’s event loop, and the results stay byte-identical. On 12 November 2026 the compiled mtDNA model ran 2.1 times as fast as the interpreted one (chapter 5). - Exact methods and exact distributions. Static Direct with five selectors, next reaction and finite state projection; approximate methods are labeled as approximate (chapter 7).
- More than reaction networks. Continuous variables (chapter 9) and species with attributes, such as clones, sizes and lineages (chapter 12).
- Runs that can be checked. Strict input checks, explicit budgets, and sealed archives with a verifier (chapter 10).
Coming from GillesPy2 or rebop? See how CRN-craft compares.
Where to start
- New here: read chapters 1 to 4 in order.
- A question: the task index links fifty tasks to their answers.
- Tutorials: the tutorials page lists all of them in two groups. Simulation tutorials rebuild published stochastic models and compare the simulations with the papers. Optimization tutorials put an fcmaes optimizer around a simulation to fit, select, design or search.
- mtDNA models: the case study, the re-creation of a published study, the comparison of three mechanisms from two 2014 studies, and the inference of takeover times from cell snapshots from a 2026 study.
- Code of an earlier release: Migrating from earlier releases.
What is included
| Part | What it does |
|---|---|
| Model input | the builder crn.Model; JSON model files; strict SBML and BioNetGen subsets (chapter 11) |
| Exact methods | Static Direct with five selectors, next reaction, the tree method for species that appear and disappear |
| Approximate methods | tau leaping, binomial splitting, hybrid for continuous variables |
| Distributions | finite state projection with separate error terms |
| Results | pandas and xarray; mean, variance, standard error, quantiles; trackers, event logs and callbacks; reports in markdown or JSON |
| Reproducibility | one random stream per replicate, results independent of the thread count, model and request named by SHA-256 |
| Interfaces | Python, the crn-craft command line, Rust; R through reticulate |
| Analysis | conservation laws and structure, GillesPy2 export; ODE right-hand sides and Jacobians in Rust |
The rest of the site
- Reference: the model language, methods, the Python API, contracts, results, archives and diagnostics.
- Developer: the architecture, the Rust API, extending and checking the project.
- Evidence: the technical report, measurements and comparisons.
- History: plans, decisions and campaign logs.
Release 0.7.0 merged two earlier engines into one; the changelog says what changed and how to migrate. CRN-craft is one of 18 related repositories; the repository overview shows how they connect.
Tutorials
The tutorials come in two groups. Pick the group by what you want to do.
- Simulation tutorials build a model from a paper or a question, simulate it and compare the outcome with a published figure, an exact law or archived data. No optimizer is needed to follow them.
- Optimization tutorials put an optimizer from fcmaes around a simulation: they fit parameters to data, select models, design experiments or search for a trade-off, and then check what the optimizer returned.
The user guide, chapters 1 to 13, explains the interface that both groups use. Read chapters 1 to 4 first.
Every tutorial is runnable from this repository, saves the tables behind its figures, and says which of its numbers agree with the source, which are inconclusive and which disagree. A tutorial that misses a published value reports the miss; none is tuned until it matches.
Simulation tutorials
| Tutorial | Source | What it does | Outcome |
|---|---|---|---|
| S1. mtDNA mutants | a teaching model | Takeover of a cell by mutant mtDNA: ensembles, trackers, event logs, a continuous ATP variable, methods and large studies | a worked example, not a reproduction |
| S2. Random drift of mtDNA mutants | Kowald & Kirkwood 2013, Aging Cell | Re-creates Figure 1A–D: COX-negative cells over 120 years, the mutation rate for 5, 10 and 15%, clones per cell | contributed by an author of the paper |
| S3. Three mtDNA mechanisms | Kowald & Kirkwood 2014, PNAS; Kowald, Dawson & Kirkwood 2014, J. Theor. Biol. | Drift, size advantage and transcription-linked replication, each calibrated to 10% affected cells, then compared by mutant lineages per cell | 1.26 lineages at three years, as published; two unstated model points confirmed by an author |
| S4. Spatial spread of mtDNA deletions | Insalata et al. 2022, PNAS | Two coupled regions and a traveling wave along a muscle fiber; an extension with de novo deletions | Figure 1C agrees; the wave speed is an unresolved discrepancy (0.13–0.16 against 0.190 µm/day) |
| S5. Mitochondrial networks and drift | Aryaman et al. 2019, Genetics | Variance of the mutant fraction under fusion and fission, against Equation 13 and the archived simulations | agreement in 38 of 39 conditions, the 39th after a rerun |
| S6. The mtDNA bottleneck | Johnston et al. 2015, eLife | Six developmental phases with divisions; approximate Bayesian computation against copy numbers and variances | Figure 3 reproduced up to 50 days; the copy number at day 100 is 23 times below the published curve |
| S7. Protein distributions | Shahrezaei & Swain 2008, PNAS | Exact stationary laws of two-stage expression against the negative-binomial approximation | Figure 1D matches if its unit is bits, not nats; the paper does not state the unit |
Optimization tutorials
Three tutorials fit models to data with fcmaes:
| Tutorial | Source | What is optimized | Outcome |
|---|---|---|---|
| O1. Fitting parameters to data | the model of tutorial S1 | Two rates of a stochastic model against single-cell data: Monte Carlo noise, common random numbers, staged refinement, held-out checks | a worked example |
| O2. Inferring mtDNA takeover times | Kowald & Kirkwood 2026, npj Aging | Mutation probability, selection advantage and advantageous fraction from cell snapshots | every true value inside its 95% interval; the baseline intervals are narrower than published, cause unknown |
| O3. Fitting single-cell RNA distributions | Munsky et al. 2018, PNAS | A four-state gene model against 59,557 yeast cells, by means and by whole histograms | the published scores reproduce; the searches start near the published vector, so they test the route, not a blind fit |
Ten lessons live with their code in
tutorials/optimization and run
through one command, python tutorials/optimization/run.py C1 … C10.
The lessons page introduces them. C1 to C4
teach the route on synthetic data; C5 to C10 each reconstruct a published
optimization study.
| Lesson | Source | What is optimized | Outcome |
|---|---|---|---|
| C1. Calibration | synthetic data | Rates of a stochastic model, with reusable preparation | method lesson |
| C2. Sensitivities | synthetic data | Rates of an ODE model with derivatives, then transferred to the stochastic model | method lesson |
| C3. Oscillators | synthetic circuits | Several objectives and a diversity archive over oscillating circuits | method lesson |
| C4. Rules | exact aggregation laws | Kernels of a rule-based model from finite samples | method lesson |
| C5. RNA count calibration | Poovathingal & Gunawan 2010, BMC Bioinformatics | Three rates from count distributions | the three rates are recovered within 3% from 10,000 trajectories; from 100 trajectories two of four data sets miss one rate by a factor 1.7 along a flat valley of the score |
| C6. Stimulus model selection | Gómez-Schiavon et al. 2017, Genome Biology | Seven hypotheses fitted to 376 measured cells, ranked by AIC and BIC | both criteria select the published model; the fitted rates lie within one posterior standard deviation of the paper’s |
| C7. Virtual reactor design | Felton et al. 2021, Chemistry–Methods | Yield and waste of a reactor in 50 evaluations | at 50 evaluations MODE is no better than random search and far below the paper’s best strategy; with 500 it passes that strategy’s median |
| C8. Sampling design | Fox & Munsky 2019, PLoS Comput. Biol. | Sampling times and a stimulus pulse by Fisher information | the sampling optimum and the ranking of the two published designs in 97 of 100 parameter samples are reproduced, the archived matrices entry by entry |
| C9. STAT5 calibration | Boehm et al. 2014, J. Proteome Res. | Nine parameters of a signaling model against a PEtab problem | the native model reproduces the archived likelihood within 2e-6 nats; a search with profiled noise scales reaches it in three of five seeds, plain retries stop 9 nats above |
| C10. Pathway calibration | Moles, Mendes & Banga 2003, Genome Research | Thirty-six parameters over sixteen experiments | the objective is verified; searches of up to 20,000 evaluations reach costs of 62 to 667 against a published 0.0013 after 2.8 million |
How the tutorials were made
Tutorial S2 was contributed by an author of the paper it re-creates. The other tutorials were written by AI agents directed by the maintainer: an agent read the paper, rebuilt the model, ran it and compared the numbers; other agents then reviewed the work without having seen it made. Unless a tutorial says otherwise, the papers’ authors did not write or review it. The README describes this way of working and the two others the project is built for.
How do I …?
Fifty common tasks, one per line, each with links to the sections of the guide that answer it.
Getting started
- How do I install CRN-craft and check that it works? 1, Install the Python package; Check the installation
- How does CRN-craft compare with GillesPy2 or rebop? How CRN-craft compares
- How do I write a reaction network in Python? 2, Species, parameters and reactions
- How do I write a rate that is not mass action, such as Michaelis–Menten or Hill? 2, Rates as numbers and as strings
- How do I get the rate constant right for
A + A → B? 2, Rates as numbers and as strings; 8, Reproducing a published simulation, step 1 - How do I check a model without running it, and read the error? 2, Checking a model; Diagnostics
Running
- How do I run 1,000 replicates on 8 threads? 3, Many trajectories in one call; Seeds and threads; 5, Threads
- How do I get the same result again? 3, Seeds and threads
- How do I see whether a run finished, and how do I limit its events or its wall time? 3, Check the termination; Budgets; Troubleshooting, Runs that end early
- How do I stop a long run and keep what is done? 3, Stopping a run; 10, Stop a run with a cancel file
Results
- How do I get the mean and the variance of a species over time, as a data frame or a NumPy array? 4, What a result holds; Select by name; Mean, variance and standard error
- How do I get the median or a 95% band? 4, Quantiles and the median
- How do I keep single trajectories and read them? 4, Single trajectories
- How do I export results for plotting, or plot them in Python? 4, Export and plot
- How do I save a run with its model and settings in one file? 4, Save a run in one file
Speed
- How do I run one model for many parameter values? 5, Parameter sweeps
- How do I compile a model to make it faster? 5, Compiled models
- My model has hundreds of reactions. Which selector is fastest? 7, Static Direct and its selectors; Larger models
Events
- How do I stop a replicate when a condition holds, such as extinction or a threshold? 6, Stop conditions
- How do I get the exact time at which a threshold is first reached, the peak of a species, or how often it appears and dies out? 6, Trackers; 11, First passage from saved paths
- How do I record the single events of a run? 6, Event logs
- How do I run my own Python code at every event? 6, Callbacks
Methods
- Which method should I use? 7, Which method for which model
- How do I get the exact distribution instead of samples? 7, Exact distributions with finite state projection
- When can I trust tau leaping? 7, Approximate leaping
Reproducing
- How do I reproduce a simulation from a published paper? 8, Reproducing a published simulation
- The paper gives its seed. Can I get the same trajectories? No: 8, Reproducing a published simulation, step 2
- How do I compare my ensemble with published means and variances, and how many replicates do I need? 8, Reproducing a published simulation, steps 3 and 4; 4, Mean, variance and standard error
- The paper used a fixed time step. How do I match it? 7, Approximate leaping; S1d, Matching an hourly scheme
- What do I report so that others can reproduce my run? 8, What to record for a paper
- Why do I get other numbers with another method, selector, thread count or release? 7, Same law, different random numbers; 8, What does not reproduce bit for bit
More kinds of models, and fitting
- How do I couple a continuous quantity, such as ATP or a drug level, to the reactions? 9, A variable between events
- How do I add a time-dependent forcing, such as a daily rhythm or a decaying dose? 9, Independent variables
- How do I fit parameters to data? O1, Fitting parameters to data; the optimization tutorials
Command line, files and other formats
- How do I run a model from the command line or on a cluster? 10, A request file; Run, archive and verify
- How do I archive a run so that it can be verified later? 10, Run, archive and verify; Replay
- How do I import an SBML or BioNetGen model? 11, Import SBML and BioNetGen
- How do I convert a model file of release 0.6.0? 11, Convert a network model of release 0.6.0; Migrating from earlier releases
- How do I find the conservation laws of a network? 11, Conservation laws and structure
- How do I check a model against another simulator? 11, Export to GillesPy2; 8, Reproducing a published simulation
- How do I load a model from a JSON file, or save one? 12, Save and load a model file
- How do I model molecules that carry a property, such as a clone, a size or an age? 12, Species with attributes in the builder; as a document
- How do I give every new mutant its own identity? 12, Species with attributes in the builder; New identities and random attributes; 12a, Every lineage with the clone model
- How do I count clones, or follow the size of the largest one? 12, Observables
mtDNA models
- How do I simulate mutant takeover in single cells? S1, The model; S1a, A first ensemble; Takeover fraction and time to threshold
- How do I change copy number, half-life, initial heteroplasmy or the threshold? S1a, Variants
- How do I follow mutant classes, and single lineages? S1b, Mutant classes; 12a, Every lineage with the clone model
- How do I re-create the figures of a published simulation study? S2, Case study: re-creating a published study
- How do I count the clones of a cell and the size of the largest one? S2c, Reading the results
- How do I find the parameter that gives a target fraction of cells (sweep and logistic regression)? S2b, A sweep and a logistic regression
- How do I let the population size vary with ATP? S1c, Variable population: ATP
- How do I use the fast path
mtdna_direct, and why is it not faster on my model? S1d, The fast path; 12a, The fast path; Troubleshooting, Methods and models
Other languages and older code
- How do I use CRN-craft from R? 13, Using CRN-craft from R
- My script was written for 0.6.0 (
crn_craft.rules,run_spec,crn-craft ssa). What do I change? Migrating from earlier releases
How CRN-craft compares
This page compares CRN-craft 0.7.0 with GillesPy2 1.8.3 and rebop 0.10.0, the Python packages a newcomer most likely knows, and names a few other tools. Statements about other tools were checked against their documentation, package pages or source on 13 November 2026 (Sources). Speed numbers come only from measurements committed to this repository.
In short
CRN-craft fits a study that needs many replicates per run, reproducible ensembles, long exact runs, a model worth compiling, species with attributes, or a continuous variable that rates read. Another tool is the better choice for full SBML with events and rules, ODE or hybrid ODE–stochastic solvers, spatial models or a graphical interface (GillesPy2 with StochSS), rule-based models with very many states (BioNetGen and NFsim), or a model compiled into your own Rust program (rebop’s macro). GillesPy2 and BioNetGen have long histories; CRN-craft’s first release was in November 2026.
Features
| CRN-craft 0.7.0 | GillesPy2 1.8.3 | rebop 0.10.0 | |
|---|---|---|---|
| Model input in Python | a builder: add_species, add_parameter, add_reaction, set_stop, add_ode; a rate is a number (mass action) or an expression string (chapter 2) | Model with Species, Parameter and Reaction; a rate constant (mass action) or a propensity string | Gillespie().add_reaction(rate, reactants, products); a number (mass action) or an expression string, with parameters passed to run |
| Model input from files | its own JSON model files; a strict subset of SBML Level 3 Version 2 and of BioNetGen .net that refuses what it cannot represent exactly (chapters 11, 12) | SBML import and export (needs libSBML); JSON | none; SBML is on its list of planned features |
| Exact methods | Static Direct with five selectors (linear, composition_rejection, sorting, rssa_cr, auto), next reaction, a tree method for species that appear and disappear (chapter 7) | the direct method, in C++ (SSACSolver) and NumPy (NumPySSASolver) | one SSA; other SSA algorithms are planned |
| Approximate methods | tau leaping and binomial splitting; the sampler name of the result says “approximate” | tau leaping (C++ and NumPy); chemical Langevin (CLESolver) | none; tau leaping is planned |
| Deterministic and hybrid | hybrid for models with continuous variables; no ODE solver for the network in the wheel (chapter 9) | ODE solvers (C++ and NumPy); TauHybridSolver, with species that switch between discrete and continuous | none; hybrid models are planned |
| Exact distributions | finite state projection with separate error terms (chapter 7) | not documented | not documented |
| Ensembles and parallelism | one call for any number of replicates on native threads; statistics and quantiles as pandas data frames (chapter 3) | number_of_trajectories in one run; the C++ SSA runs them one after another in one process; ensemble mean and standard deviation | one trajectory per run call; parallelization is planned |
| Reproducibility | one ChaCha8 stream per replicate, results independent of the thread count, model and request named by SHA-256, sealed archives with a verifier (chapters 8, 10) | a seed argument | a seed or NumPy generator per call |
| Compilation from Python | crn.compile_loop(model), opt-in; needs a Rust toolchain; cached; byte-identical results (chapter 5) | the C++ solvers compile each model with g++ and SCons; NumPy solvers otherwise | the Python API compiles nothing; the Rust macro define_system! compiles a mass-action model into a Rust program |
| Species with attributes | in model files and, since 0.8.0, in the builder, with new identities at run time (chapter 12) | not documented | not documented; rule modeling is listed as “probably not to come” |
| Continuous variables | ODEs between events that rates read; independent variables integrated once per run | rate rules and assignment rules (hybrid solver) | not documented |
| Event-level output | stop conditions, trackers (first passage, extremes, integrals), bounded event logs, Python callbacks (chapter 6) | SBML-style events with triggers, delays and assignments; live output during a run | every reaction with nb_steps=0; events are listed as “probably not to come” |
| Results | pandas and xarray; mean, variance, standard error, quantiles; markdown and JSON reports (chapter 4) | trajectories as NumPy arrays; matplotlib and Plotly plots; CSV | an xarray dataset per run |
| Languages | Python, a command line, Rust; R through reticulate (R) | Python | Python and Rust |
Numeric rate on A + A | k·n(n−1)/2 (model reference); exports GillesPy2 source with the constant halved | k·n(n−1) at volume 1 | k·n(n−1) |
| License | MIT | GPL-3.0 | MIT |
| What it has that CRN-craft lacks | SBML events and rules, ODE, hybrid and Langevin solvers, the StochSS web interface, spatial models through the sibling project SpatialPy | a Rust macro that compiles a model into your program |
Two things to try first
Many trajectories as one ensemble. crn.ensemble(model, ...).simulate()
runs any number of replicates on native threads and returns their means,
variances and quantiles; you write no loop (chapter 3).
Results do not depend on the thread count; two threads ran 2,000 mtDNA cells
2.1 times as fast as one (release 0.2.0, see Speed).
A compiled model while you stay in Python. loop = crn.compile_loop(model)
builds a native event loop once and caches it; run.simulate(compiled=loop)
gives byte-identical results (chapter 5).
On the mtDNA model it ran 2.14 times as fast as the interpreter (12 November
2026). It needs a Rust toolchain; the gain depends on the model.
Speed
All runs: a shared two-CPU cloud host, under a CPU lock. Timings vary (with GillesPy2: most runs within 10% of their median, single CRN-craft runs up to 34%; with rebop: repeats of one row differ by up to 2.0 times), so this page quotes ratios of medians: other tool over CRN-craft.
GillesPy2, current engine (12 November 2026; unified engine of 0.7.0 at
cec91ed, whose build reports 0.6.0; GillesPy2 1.8.3, Python 3.12.3, g++ 13.3;
64 paths to t = 100, one thread, medians of five runs). SSACSolver against
CRN-craft’s default on the networks W1 to W4: 2.9, 10.6, 3.6, 9.3; against the
linear scan with inverse waits: 2.8, 5.6, 3.7, 1.3. NumPySSASolver: 134 to
358. With the selectors composition_rejection and sorting, which auto
does not pick there, CRN-craft was slower on W4 (0.88, 0.93). The C++ compile
(2.1 to 2.9 s per model) is excluded; 28 of 28 agreement tests passed. Not measured:
tau, ODE and hybrid solvers, threads (evidence).
rebop, Python API, current engine (13 November 2026; crn-craft 0.7.0 and
rebop 0.10.0 from PyPI, Python 3.12.3, Rust 1.97.0; 64 paths to t = 100, one
thread, medians of three repeats; 8 of 8 agreement tests passed). W1, two
reactions: 1.21 against the default, 1.50 against the compiled loop; these
two are not resolved against each other. W2, 66 reactions: 25.0 against the
default, 13.4 against the linear scan; the compiled loop, linear scan only, ran
0.95 times as fast as the interpreted one. Not measured: rebop’s macro,
W3 and W4 (rates that are not mass action), threads
(validation/merge/rebop-comparison-0.7.json; RESULTS.md, “rebop on 0.7.0”).
rebop’s macro, removed engine (2 November 2026; CRN-craft 0.2.0.dev1, the network engine that 0.7.0 removed; rebop 0.10.0; 54 optimization runs). rebop was faster: its macro beat CRN-craft by 3.44 times on birth–death and 1.72 on binding12, and tied on sparse33 (0.94 to 1.00); with one build the totals differed by 2.5%. rebop’s Python expression route took 15 times as long as CRN-craft on birth–death. Not repeated on 0.7.0 (evidence).
Compiled models (12 November 2026). mtDNA three-class model file, 200 cells, two threads:
compiled 2.14 times as fast as interpreted Static Direct, mtdna_direct 2.84 times
(validation/merge/manual-ratios/timings.json).
Twelve networks, linear scan: compiled over interpreted time 0.61 to 0.90 on
eight, 1.15 on W7; W4 to W6 refused (source over 1 MiB). First build 49.3 s,
later 0.1 to 6.4 s (RESULTS.md, “Compiled event loops”).
Threads (release 0.2.0): mtdna_direct, 2,000 cells, two threads 2.1 times as fast as one;
Static Direct, next reaction and the tree method, 20 threads on eight CPUs, 5.8 to 6.1 times
(analysis).
Julia (Catalyst.jl, JumpProcesses.jl): compared only with the 0.6.0 engine; Julia was not on the
0.7.0 host (comparison, ten iterations, eight threads).
Other tools
StochPy 2.5 (BSD-3-Clause) has the direct, first reaction and next reaction
methods and tau leaping, reads its own .psc files and SBML (optional
libSBML), and ships DSMTS models with a test call. BioNetGen and NFsim are
the reference for rule-based models; NFsim simulates models with very many or
unbounded states without generating the network. They are the nearest
relatives of species with attributes, and CRN-craft imports a subset of
expanded .net files (chapter 11).
JumpProcesses.jl (Julia, SciML) provides SSAs and couples jumps to ODEs and
SDEs. There is no measurement against StochPy or NFsim.
Where CRN-craft is weaker
- No deterministic ODE solver for a network in the wheel; no spatial models; no graphical interface.
- SBML and BioNetGen import cover a strict subset: no events, rules, fast reactions or non-integer stoichiometry.
- A compiled model needs a Rust toolchain, runs the linear scan only, refuses
sources over 1 MiB, and can be slower than interpreted
rssa_cr. - Tau leaping is far slower than Static Direct on networks with about a
thousand reactions;
bind_parametersprepares the model again per candidate. - In the one measured optimization, rebop’s macro was faster. First release: November 2026. (Up to 0.7.1 the builder could not write species with attributes; 0.8.0 adds them.)
Sources
Checked on 13 November 2026. CRN-craft cells: run or read on the 0.7.0 wheel.
- GillesPy2 1.8.3 (19 September 2024, current): PyPI,
documentation, README;
source of the 1.8.3 package:
core/model.py(SBML,get_best_solver),core/reaction.py(A + A),core/results.py,solvers/cpp,solvers/numpy,ssa_cpp_solver/SSASolver.cpp(trajectory loop). StochSS and SpatialPy: stochss.org. - rebop 0.10.0 (24 August 2026): PyPI (README with planned
and “probably not to come” features), crates.io; source of the
0.10.0 package:
gillespie.py(add_reaction,run, theA + Aconvention). - StochPy 2.5 (18 June 2025): PyPI. BioNetGen, NFsim: READMEs of bionetgen and nfsim. JumpProcesses.jl: README.
1. Install
CRN-craft simulates chemical reaction networks stochastically, from Python, with a native engine. This chapter installs it and says how the guide is organized.
Install the Python package
python -m pip install crn-craft
The package contains the engine, so nothing has to be compiled. It installs
the module crn_craft and two commands, crn-craft and crn-craft-import.
pip also installs NumPy, pandas and xarray, because results are pandas data
frames and xarray arrays. Wheels exist for CPython 3.10 and newer on Linux
x86_64, Windows x64 and macOS (x86_64 and arm64). Other platforms build from
the source distribution with a Rust toolchain.
Check the installation
One call shows the version, and a second one shows that the engine answers:
import crn_craft as crn
print(crn.__version__)
print(crn.describe()["schema"])
0.10.1
crn-craft.describe/1.0
Coming from another tool
Two things are worth trying first. Many trajectories run as one ensemble in one call, on native threads (chapter 3). A model can be compiled from Python, with the same results in less time (chapter 5). How CRN-craft compares puts CRN-craft beside GillesPy2 and rebop, with features and measured speed.
The command-line tool is optional
The wheel already has the command crn-craft, so this guide needs no other
tool. A native tool with the same commands and reports installs with Rust
1.85 or newer: cargo install crn-craft-cli --locked. If both are installed,
the one that comes first on your PATH runs, and crn-craft --version tells
them apart: the Python command prints "interface": "python".
Chapter 10 uses either.
Build from source
To use the current source instead of a release, clone the repository, build the command-line tool with cargo and the wheel with maturin:
git clone https://github.com/dietmarwo/CRN-craft
cd CRN-craft
cargo build --release --workspace --locked
./target/release/crn-craft --help
python -m pip install maturin==1.9.6
maturin build --release --locked --out dist
python -m pip install --force-reinstall dist/*.whl
Optional extras
- Plots. The plotting example of chapter 4 needs
matplotlib:
python -m pip install matplotlib. - Fitting.
python -m pip install "crn-craft[fit]"adds the pinned SciPy, fcmaes-rust and SQP-craft versions of the fitting examples (tutorial O1). - Optimization lessons.
python -m pip install "crn-craft[publications]"adds fcmaes, SciPy, matplotlib, PyYAML and libSBML for lessons C5 to C10 (the lessons page). - Likelihood readouts.
python -m pip install "crn-craft[likelihood]"adds SciPy for the binomial-detection and fluorescence readouts ofcrn_craft.likelihood(experiments). Projections and stationary laws need no extra. - Compiled models.
crn.compile_loopneeds a Rust toolchain, 1.85 or newer, from rustup (chapter 5). - R. The Python package works from R through reticulate (chapter 13).
How to read this guide
Read chapters 1 to 4 in order. After them you can build a model, run an ensemble and inspect, plot and save the result. The later chapters can be read in any order, and each assumes only chapters 1 to 4.
- Every chapter starts with a setup block that imports the package as
import crn_craft as crnand builds the chapter’s model. The blocks of a section continue from the setup block and from earlier blocks of the same section, so the setup block and one section are a complete program. - Work in an empty folder. A chapter writes every file it reads, or names the repository file to copy.
- A checker runs every block and compares each printed output with the block before it. For a single question, start from the task index.
See also: A first model, Troubleshooting, Migrating from earlier releases.
2. A first model
A model has species, parameters and reactions. This chapter builds one in Python, runs it once, and shows what happens when a model has a mistake.
Species, parameters and reactions
The builder crn.Model writes a model call by call. In this one, molecules
of A arrive at rate 4, and each molecule decays at rate 0.2. It is called
immigration–death, and it is the running example of this guide:
import numpy as np
import crn_craft as crn
model = crn.Model("immigration_death")
model.add_parameter({"birth": 4.0, "death": 0.2})
model.add_species("A", 0)
model.add_reaction("birth", [], ["A"], name="birth")
model.add_reaction("death * A", ["A"], [], name="death")
print(model)
print(model.reaction_names)
Model('immigration_death': 1 species, 2 reactions)
('birth', 'death')
add_species(name, initial) declares a species and its count at time 0.
add_reaction(rate, reactants, products) takes the species of each side as
lists. An empty list means that nothing is consumed or produced. The blocks
of this chapter continue from this one.
A first run
crn.ensemble prepares a run and simulate() executes it. Here 400
independent trajectories run to time 30, and the result holds their mean at
three report times. method="static_direct" names the exact method for a
reaction network, Gillespie’s direct method. Pass it in every call, as this
guide does; chapter 3 says
why:
result = crn.ensemble(
model, end=30.0, report_times=[0.0, 10.0, 30.0], replicates=400, seed=42,
method="static_direct",
).simulate()
print(result.statistics["mean"])
print("exact:", (20 * (1 - np.exp(-0.2 * np.array([0.0, 10.0, 30.0])))).round(2))
A
time
0.0 0.0000
10.0 17.2450
30.0 20.0925
exact: [ 0. 17.29 19.95]
The count of A has a known law: it is Poisson with mean
20 (1 - exp(-0.2 t)). The simulated means agree with it within their
sampling error, which chapter 4 shows how to read. An ensemble is one call
for any number of trajectories (chapter 3), and threads and
compiled models make it fast (chapter 5).
Rates as numbers and as strings
The first argument of add_reaction is the rate, and it has two forms.
- A number is a mass-action constant. The reaction fires at the constant
times the number of distinct combinations of reactant molecules:
Aatk * A,A + Batk * A * B, andA + Aatk * A * (A - 1) / 2. Write a repeated species once per molecule:["A", "A"]is2 A. - A string is the whole propensity. It is an expression over parameters
and species counts, with the operators
+ - * / ^, comparisons, and the functionsmin max exp log sqrt abs floor ceil if. Michaelis–Menten kinetics is"vmax * S / (Km + S)"on["S"]. A string rate applies while each reactant has enough molecules and is 0 otherwise.
So model.add_reaction(0.2, ["A"], []) is the same reaction as the death
reaction above. A third form, crn.mass_action("death"), is an expression
used like a number: the reaction fires at its value times the number of
combinations of reactant molecules. It matters for species whose molecules
carry attributes (chapter 12). Counts are integers. A reaction may take any number of
reactant molecules: ["A", "A", "A"] is a third-order reaction. Tools differ
in how they count A + A, which matters when you take a rate constant from
a paper or from another program
(chapter 8).
Checking a model
crn.check validates a model without running it. It returns a report with
the field valid and a list of diagnostics:
report = crn.check(model)
print(report["valid"], report["diagnostics"])
True []
Every problem is a diagnostic with a stable code, the path of the field in
the model or the request, a message and a hint. A function that cannot go on
raises crn.CrnError, a ValueError that carries the diagnostics. Here a
report time lies after the end of the run:
try:
crn.ensemble(model, end=1.0, report_times=[0.0, 2.0], method="static_direct")
except crn.CrnError as error:
print(error)
print(error.diagnostics[0]["path"])
print(error.diagnostics[0]["hint"])
CRN-R020: report times must be strictly increasing within [0, end] at /time/report_times/1
/time/report_times/1
Sort the grid and keep it inside the horizon.
Validation is strict. A misspelled parameter in a string rate, an unknown field and a duplicate key are errors, never warnings, and nothing is guessed. Diagnostics lists every code.
A second model with two reactants
The SIR model of an epidemic has what immigration–death lacks: a reaction of
two molecules. A susceptible S meets an infected I and becomes infected,
and an infected recovers to R. Time is in days. The model is the second
example of this guide:
sir = crn.Model("sir")
sir.add_species({"S": 490, "I": 10, "R": 0}) # or one at a time: add_species("S", 490)
sir.add_parameter("gamma", 0.1)
# A number is a mass-action constant: S + I fires at 5e-4 * S * I.
sir.add_reaction(5e-4, ["S", "I"], ["I", "I"], name="infection")
# A string is the whole propensity, over parameters and species counts.
sir.add_reaction("gamma * I", ["I"], ["R"], name="recovery")
print(sir)
run = crn.ensemble(
sir,
end=60.0,
report_times=[0.0, 20.0, 40.0, 60.0],
replicates=1000,
seed=1,
threads=2,
method="static_direct",
)
result = run.simulate()
print(result.statistics["mean"].round(1)) # species columns, sorted by name
print("events per replicate:", result.rule_events.mean().to_dict())
Model('sir': 3 species, 2 reactions)
I R S
time
0.0 10.0 0.0 490.0
20.0 90.9 86.1 323.0
40.0 87.4 295.0 117.6
60.0 28.7 404.4 66.9
events per replicate: {'infection': 423.065, 'recovery': 404.412}
The epidemic peaks near day 20 and has infected most of the population by day 60. Each replicate fires about 423 infections and 404 recoveries.
The builder calls
| Call | Effect |
|---|---|
crn.Model(name="model") | a new, empty model |
add_parameter(name, value) or add_parameter(mapping) | parameters that string rates may read |
add_species(name, initial=0) or add_species(mapping) | species and their initial counts |
set_initial(mapping) or set_initial(S=490, I=10) | new initial counts of declared species |
add_reaction(rate, reactants, products, name=None) | a reaction; names default to r0, r1, … |
add_species(name, attributes=[...]) and add_initial(name, count, **attributes) | a species whose molecules carry attributes, and its molecules at time 0 (chapter 12) |
add_observable(name, species, where=None, weight=None, reduce="sum") | a filtered, weighted or reduced count (chapter 12) |
set_stop(condition) | a condition that ends a replicate (chapter 6) |
add_ode(name, initial, derivative) | a continuous variable (chapter 9) |
The add_* calls return the model, so they can be chained. A mapping, as in
add_parameter({"gamma": 0.1, "beta": 5e-4}), declares its entries in order.
If one entry is invalid, the call raises and declares none of them. Species
that a reaction names without a declaration start at 0.
A Model is not a dictionary: model["stop"] = ... raises TypeError, and
set_stop is the call to use. crn.ensemble and crn.check take the
Model itself. What the builder writes, and how to save and load a model as
a file, is the subject of chapter 12.
See also: Running ensembles, Model language, Diagnostics.
3. Running ensembles
An ensemble is a set of independent trajectories of one model, called replicates. This chapter runs ensembles, makes them reproducible, and shows how a run can end. The setup block builds the immigration–death model of chapter 2. The blocks of this chapter continue from it:
import numpy as np
import crn_craft as crn
model = crn.Model("immigration_death")
model.add_parameter({"birth": 4.0, "death": 0.2})
model.add_species("A", 0)
model.add_reaction("birth", [], ["A"], name="birth")
model.add_reaction("death * A", ["A"], [], name="death")
Many trajectories in one call
One call runs any number of independent trajectories on native threads and
returns their statistics. There is no loop to write and no result to collect
by hand. crn.ensemble builds a run request, checks it and prepares it.
simulate() then runs the replicates:
run = crn.ensemble(
model, end=30.0, report_times=list(np.linspace(0, 30, 31)),
replicates=400, seed=42, keep_paths=8, method="static_direct",
)
result = run.simulate()
assert result.metadata["termination"] == "completed"
t = np.array(result.metadata["report_times"])
mean = result.statistics["mean"]["A"].to_numpy()
exact = 20 * (1 - np.exp(-0.2 * t))
print(result.metadata["events"], "events")
print(f"mean at t=30: {mean[-1]:.2f}, exact {exact[-1]:.2f}")
assert abs(mean[-1] - exact[-1]) < 4 * np.sqrt(exact[-1] / 400)
88037 events
mean at t=30: 20.09, exact 19.95
The immigration–death law is Poisson with mean 20 (1 - exp(-0.2 t)), so
the mean and the variance agree:

method="static_direct" is the exact method for a reaction network
(Gillespie’s direct method). Name it in every call: without method, a
slower exact method for models with changing species runs
(chapter 7).
The everyday arguments
| Argument | Meaning |
|---|---|
end | the time at which every replicate ends |
report_times | increasing times in [0, end] at which the state is recorded |
replicates | the number of trajectories; 1 by default |
seed | the root seed; 0 by default |
threads | 1 to 64 native threads; 1 by default |
keep_paths | how many replicates keep their whole series: a count, or "all" (chapter 4) |
method | a method name, or a dictionary with options (chapter 7) |
quantiles | probabilities for the quantile statistics (chapter 4) |
Report times are right-continuous: an event exactly at a report time is included. Statistics exist only at the report times, so choose them for the question. Python API lists every argument.
Seeds and threads
Every replicate draws from its own random stream, keyed by the root seed and the replicate’s index. A result therefore depends on the seed and the method, and not on the number of threads:
def run(seed, threads, replicates=64):
return crn.ensemble(
model, end=30.0, report_times=[0.0, 10.0, 20.0, 30.0],
replicates=replicates, seed=seed, threads=threads, keep_paths="all",
method="static_direct",
).simulate()
one, two, other = run(7, 1), run(7, 2), run(8, 2)
same = one.records.equals(two.records) and one.rule_events.equals(two.rule_events)
print("1 and 2 threads, same seed, identical records:", same)
print("identical statistics:", one.statistics["mean"].equals(two.statistics["mean"]))
print("identical paths:", one.paths.equals(two.paths))
print("seeds 7 and 8, identical events:", one.records["events"].equals(other.records["events"]))
# Replicate i always uses the same stream, whatever the size of the ensemble.
small = run(7, 1, replicates=8)
print("first 8 of 64 equal an 8-replicate run:",
small.records["events"].equals(one.records["events"].head(8)))
1 and 2 threads, same seed, identical records: True
identical statistics: True
identical paths: True
seeds 7 and 8, identical events: False
first 8 of 64 equal an 8-replicate run: True
The same seed gives the same result again, on any machine and any number of threads. Replicate i is the same trajectory in a larger ensemble, so a run can be extended without changing what it already gave. Another seed gives other trajectories of the same law. Chapter 5 times the threads.
Check the termination
A run does not always complete. result.metadata["termination"] says how
the ensemble ended, and result.records["termination"] says it for every
replicate, with one of nine names:
| Termination | Meaning |
|---|---|
completed | the replicate reached end |
stopped | a stop condition ended it (chapter 6); this counts as complete |
event_limit, sampling_limit, instance_limit, wall_time_limit, output_limit | a budget was reached (next section) |
cancelled | the run was stopped from outside (last section) |
failed | a rate or a stop could not be evaluated; result.record_diagnostics says why |
Always check the termination before using statistics. If any replicate ended
on a budget, was canceled or failed, result.statistics is None: a
partial ensemble is never averaged as if it were complete.
Budgets
Every run has explicit limits. A replicate that reaches one stops there.
| Limit | Argument | Default | Termination | Code |
|---|---|---|---|---|
| events per replicate | max_events | 100,000,000 | event_limit | CRN-R040 |
| random numbers per replicate | max_sampling_steps | 16 × max_events | sampling_limit | CRN-R041 |
| live instances per replicate, for species with attributes (chapter 12) | max_instances | 100,000 | instance_limit | CRN-R042 |
| wall time of the whole run | wall_time_s | none | wall_time_limit | CRN-R043 |
| size of the result | max_output_bytes | 64 MiB | output_limit | CRN-R045 |
The event and sampling limits are a safety net against a model that runs
away, for example a rate with a sign error that makes the population
explode. They count work, not seconds, so a run stops at the same event on
every machine. The default lets a replicate run 10⁸ events, about ten
seconds of work at ten million events per second. max_sampling_steps follows max_events unless you give
it: an event draws one to about three random numbers, so 16 per event leaves
room, and a long run needs only max_events raised.
Here 50 events are too few for a run to time 30:
short = crn.ensemble(model, end=30.0, report_times=[0.0, 30.0], replicates=8,
seed=1, max_events=50, method="static_direct").simulate()
print(short.metadata["termination"], short.statistics)
print(short.records["termination"].value_counts()["event_limit"], "replicates hit the limit")
event_limit None
8 replicates hit the limit
A replicate that ends early is not an error, but simulate() warns with
crn.IncompleteEnsembleWarning, which Python prints on stderr, every time,
also for each batch of a loop. Here the warning is caught to show its
message:
import warnings
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always")
crn.ensemble(model, end=30.0, report_times=[0.0, 30.0], replicates=8, seed=1,
max_events=50, method="static_direct").simulate()
print(caught[0].category.__name__)
print(caught[0].message)
IncompleteEnsembleWarning
8 of 8 replicates ended early: 8 event_limit (raise max_events); result.statistics is None. result.records["termination"] gives the termination of every replicate. Pass strict=True to raise IncompleteEnsembleError instead.
The message counts the replicates per termination and names the argument
to raise for each. strict=True turns the warning into an error,
crn.IncompleteEnsembleError, whose result still holds the records:
try:
crn.ensemble(model, end=30.0, report_times=[0.0, 30.0], replicates=8, seed=1,
max_events=50, method="static_direct", strict=True).simulate()
except crn.IncompleteEnsembleError as error:
print(error)
print(error.counts, len(error.result.records))
8 of 8 replicates ended early: 8 event_limit (raise max_events); result.statistics is None. result.records["termination"] gives the termination of every replicate.
{'event_limit': 8} 8
The remedy is a larger limit, not an average over cut-off replicates.
max_events=None removes the event and sampling limits: the request then
records the largest possible value, 2⁶⁴ − 1, so it still replays exactly.
Without a limit, a runaway model runs until it exhausts memory, so give such
a run a wall-time limit. It ends a run that takes longer than planned, at a
point that depends on the machine:
slow = crn.ensemble(model, end=1e7, report_times=[0.0, 1e7], replicates=4,
seed=1, threads=2, max_events=None, wall_time_s=0.2,
method="static_direct").simulate()
print(slow.metadata["termination"], slow.statistics)
print([d["code"] for d in slow.metadata["diagnostics"]])
print(sorted(set(slow.records["termination"])))
wall_time_limit None
['CRN-R050']
['wall_time_limit']
The warning CRN-R050 in the result says that the ensemble is incomplete
and its statistics are withheld. The records still account for every
replicate. A study that expects early ends, such as a parameter search that
gives up on extreme candidates, can silence the Python warning with
warnings.simplefilter("ignore", crn.IncompleteEnsembleWarning). A
canceled run (next section) and a replicate that a stop
condition ended are not reported.
Stopping a run
A long run can be stopped from outside by creating a file. The run ends with
the termination cancelled:
import pathlib
pathlib.Path("stop").touch()
long_run = crn.ensemble(model, end=1e6, report_times=[0.0, 1e6], replicates=8,
max_events=None, method="static_direct")
stopped = long_run.simulate(cancel_file="stop")
print(stopped.metadata["termination"], stopped.statistics)
cancelled None
Here the file exists before the run starts, so the run ends at once. On a
batch system, another job or a time limit creates the file. The engine looks
for it every 1,024 events. Ctrl-C cancels a running call in the same
way and raises KeyboardInterrupt within about 50 ms.
See also: Results, Speed, Troubleshooting.
4. Results
simulate() returns a Result. This chapter reads it: statistics, single
trajectories, exports, plots and a file that holds a whole run. The setup
block runs the ensemble of chapter 3, and every section
reads its result:
import pathlib
import numpy as np
import crn_craft as crn
model = crn.Model("immigration_death")
model.add_parameter({"birth": 4.0, "death": 0.2})
model.add_species("A", 0)
model.add_reaction("birth", [], ["A"], name="birth")
model.add_reaction("death * A", ["A"], [], name="death")
result = crn.ensemble(
model, end=30.0, report_times=list(np.linspace(0, 30, 31)),
replicates=400, seed=42, keep_paths=8, method="static_direct",
).simulate()
What a result holds
A Result holds pandas data frames and xarray arrays, indexed by name:
| Attribute | Content |
|---|---|
records | one row per replicate: termination, stop_time, events, rng_words, … |
rule_events | events per replicate, one column per reaction |
statistics | a dictionary of data frames indexed by report time: mean, sample_variance, mean_standard_error, median, quantiles; and samples, the number of replicates |
paths | the kept trajectories, with dimensions replicate, time, variable |
metadata | the whole result document: sampler, termination, totals, hashes |
model, request | the documents that ran, as dictionaries |
print(result.records["termination"].value_counts()["completed"], "completed replicates")
print(result.rule_events.mean().round(1).to_dict())
print(result.statistics["sample_variance"]["A"].iloc[-1].round(2))
print(result.statistics["mean_standard_error"]["A"].iloc[-1].round(3))
print(result.paths.dims, result.paths.shape)
400 completed replicates
{'birth': 120.1, 'death': 100.0}
18.92
0.217
('replicate', 'time', 'variable') (8, 31, 1)
Select by name
Columns carry the species names, so select by name, never by position:
result.statistics["mean"]["A"] is the mean of A at every report time, and
result.paths.sel(variable="A") is A in the kept trajectories. Species are
sorted by name, with continuous variables after them. .to_numpy() turns
any frame, column or array into a NumPy array.
Mean, variance and standard error
At each report time, mean is the average over the replicates,
sample_variance their variance with the divisor n − 1, and
mean_standard_error the square root of the variance over n. The mean plus
and minus 1.96 standard errors is a 95% confidence interval. At t = 30 the
block above gives 20.09 ± 0.43, which contains the exact 19.95. Four times
the replicates halve the standard error.
Quantiles and the median
crn.ensemble asks for the 2.5%, 50% and 97.5% quantiles by default:
statistics["quantiles"] is a dictionary from each probability to a data
frame shaped like mean, and statistics["median"] is the median:
quantiles = result.statistics["quantiles"]
print(sorted(quantiles))
print(result.statistics["median"]["A"].iloc[-1], quantiles[0.025]["A"].iloc[-1], quantiles[0.975]["A"].iloc[-1])
[0.025, 0.5, 0.975]
20.0 12.0 30.0
These are NumPy’s default quantiles (linear interpolation) of the replicate
values at each report time. Pass quantiles=[0.1, 0.9] to choose others, up
to 16 probabilities in (0, 1), and quantiles=() to ask for none. The
median appears whenever 0.5 is among them:

A mean can mislead: when most replicates stay near zero and a few grow large, almost no replicate is near the mean (an example).
Single trajectories
keep_paths decides which replicates keep their series at the report times:
a count keeps replicates 0, 1, … and "all" keeps every one, in paths:
paths = result.paths
print(dict(paths.sizes))
print(paths.sel(replicate=3, variable="A").to_numpy()[:6]) # one trajectory
print(paths.sel(time=30.0, variable="A").to_numpy()) # every kept replicate at t = 30
print(paths.sel(variable="A").mean("replicate").to_numpy()[-2:]) # mean of the kept ones
{'replicate': 8, 'time': 31, 'variable': 1}
[0. 1. 2. 5. 9. 9.]
[20. 21. 18. 13. 20. 24. 20. 19.]
[19.25 19.375]
result.paths_frame() gives the same values as a data frame indexed by
replicate and time, and result.to_xarray() as a dataset with one variable
per species. A replicate that ended on a budget has NaN after its last
report time.
The statistics are per species. A statistic of a sum of species, such as a
quantile of M + A, comes from the kept paths: run with keep_paths="all"
and reduce result.paths.sel(variable=["M", "A"]).sum("variable") with
NumPy. Kept paths cost memory (chapter 5).
Export and plot
Every statistic is a data frame, so pandas writes it. This block writes the
mean with its band and the kept paths to CSV files and plots them. The plot
needs matplotlib (python -m pip install matplotlib); the two CSV files do
not:
import matplotlib
matplotlib.use("Agg") # draw into files, without a window
import matplotlib.pyplot as plt
band = result.statistics["quantiles"]
table = result.statistics["mean"].join(band[0.025].add_suffix("_low")).join(band[0.975].add_suffix("_high"))
table.to_csv("mean.csv")
result.paths_frame().to_csv("paths.csv")
print(pathlib.Path("mean.csv").read_text().splitlines()[:3])
figure, axis = plt.subplots(figsize=(6, 3.5))
axis.fill_between(table.index, table["A_low"], table["A_high"], alpha=0.2, label="2.5% to 97.5%")
axis.plot(table.index, table["A"], label="mean of 400 replicates")
axis.step(table.index, result.paths.sel(variable="A").to_numpy()[:3].T, where="post", lw=0.8)
axis.set(xlabel="time", ylabel="A")
axis.legend()
figure.savefig("mean.png", dpi=150)
print(pathlib.Path("mean.png").stat().st_size > 10_000)
['time,A,A_low,A_high', '0.0,0.0,0.0,0.0', '1.0,3.5325,0.0,7.0']
True
Save a run in one file
Result.save writes the model, the request and the results to one file:
.md gives a markdown report to read, .json one that crn.load_report
reads back:
markdown = result.save("immigration-death.md")
result.save("immigration-death.json", paths=False)
report = crn.load_report("immigration-death.json")
print(report["schema"], sorted(report))
print("same sampler:", report["result"]["sampler"] == result.metadata["sampler"])
text = markdown.read_text() # the markdown report has one section per statistic
print(text[text.index("### median") : text.index("### 97.5% percentile")].rstrip())
crn-craft.report/1.0 ['crn_craft_version', 'model', 'request', 'result', 'schema']
same sampler: True
### median
```text
A: 0, 3, 6, 9, 11, 12, 14, 15, 16, 16.5, 17, 18, 18, 18, 18, 19, 19, 19, 19, 19, 19, 20, 19, 19, 19, 20, 20, 20, 20, 20, 20
```
paths=False leaves the single trajectories out. The report starts like this:
print("\n".join(pathlib.Path("immigration-death.md").read_text().splitlines()[:23]))
# Model
Name: immigration_death
## Reactions
```text
0 -> A, birth
A -> 0, death * A
```
## Start values
```text
A = 0
```
## Parameter values
```text
birth = 4
death = 0.2
```
The same result always gives the same bytes: a report holds no timestamp, host name or timing. It names the package version and the SHA-256 hashes of the model and the request, so it identifies what ran. A report is a readable record. An archive is the sealed record that can be verified later (chapter 10).
See also: Results reference, chapter 6, chapter 8.
5. Speed: threads, parameter sweeps and compiled models
Three tools make a study fast: threads for one ensemble, parameter binding for many ensembles of one model, and a compiled event loop for a model that runs often. None of them changes a result. The setup block builds the SIR model of chapter 2 with 10,000 individuals. The blocks of this chapter continue from it:
import time
import crn_craft as crn
sir = crn.Model("sir")
sir.add_species({"S": 9_990, "I": 10, "R": 0})
sir.add_parameter({"beta": 0.3, "gamma": 0.1, "N": 10_000.0})
sir.add_reaction("beta * S * I / N", ["S", "I"], ["I", "I"], name="infection")
sir.add_reaction("gamma * I", ["I"], ["R"], name="recovery")
Threads
threads=n divides the replicates among n native threads. Every replicate
has its own random stream, so the result is the same for any number of
threads:
def timed(threads):
run = crn.ensemble(
sir, end=400.0, report_times=[0.0, 100.0, 200.0, 400.0], replicates=500,
seed=3, threads=threads, method="static_direct",
)
start = time.perf_counter()
result = run.simulate()
return result, time.perf_counter() - start
one, seconds_one = timed(1)
two, seconds_two = timed(2)
assert one.statistics["mean"].equals(two.statistics["mean"])
print(f"1 thread {seconds_one:5.2f} s {one.metadata['events']:,} events")
print(f"2 threads {seconds_two:5.2f} s identical statistics")
1 thread 0.77 s 9,400,096 events
2 threads 0.39 s identical statistics
The timings are from a host with two CPUs. Use as many threads as the machine has free CPUs, up to 64. More threads than CPUs give nothing. The performance analysis has measurements on up to 20 threads.
What output costs
Simulation time grows with the number of events. Output adds to it:
- Kept paths take memory for species × report times × kept replicates. Keep the paths of a few replicates to look at, and all of them only for a statistic that needs them.
- Quantiles hold one value per replicate, report time and species while the
run lasts.
quantiles=()turns them off. - Every report time is a row in every statistic. A fine grid for a plot is cheap. A grid of 100,000 times for a million replicates is not.
A result larger than max_output_bytes, 64 MiB by default, ends as
output_limit without statistics and paths: raise the limit or keep less.
The performance analysis
sizes a large study.
Parameter sweeps
A sweep runs one model for many parameter values. Prepare the run once, then
bind new values with bind_parameters. Here the infection rate beta
varies:
template = crn.ensemble(
sir, end=400.0, report_times=[0.0, 400.0], replicates=200, seed=3,
threads=2, method="static_direct",
)
for beta in (0.08, 0.15, 0.2, 0.3, 0.5):
result = template.bind_parameters({"beta": beta}).simulate()
recovered = result.statistics["mean"]["R"].iloc[-1]
print(f"beta {beta:4.2f} mean final R {recovered:7.1f} "
f"model {result.metadata['model_sha256'][:8]}")
beta 0.08 mean final R 45.5 model 50926733
beta 0.15 mean final R 5752.8 model 35da249c
beta 0.20 mean final R 7964.3 model a1fcd763
beta 0.30 mean final R 9404.3 model 52d43047
beta 0.50 mean final R 9930.9 model 212bd588
Below beta = gamma = 0.1 the epidemic dies out. Above it, most of the
population is infected.
bind_parameters takes a mapping from parameter names to numbers and
returns a new prepared run. Only the named parameters change. The request,
the seed, the method, the initial counts and the reactions stay as they are;
to change one of those, prepare a new run. The template and earlier
candidates stay intact. An unknown name or a value that is not a finite
number is refused with CRN-R020. Each candidate has its own model hash, so
every result names its parameters.
Common random numbers
The same seed gives every candidate the same random streams. Differences
between two candidates then come from the parameters and not from different
random numbers, which makes a sweep smoother and helps an optimizer that
compares candidates. For an independent evaluation, such as a final check of
a fitted value, prepare a run with another seed.
Compiled models
crn.compile_loop(model) compiles the event loop of one model into a small
native program. The results are byte-identical to the interpreted run, the
run is faster, and you stay in Python:
loop = crn.compile_loop(sir) # about a minute the first time, then cached
run = crn.ensemble(
sir, end=400.0, report_times=[0.0, 100.0, 200.0, 400.0], replicates=500,
seed=3, threads=2, method="static_direct",
)
for label, compiled in (("interpreted", None), ("compiled", loop)):
start = time.perf_counter()
result = run.simulate(compiled=compiled)
seconds = time.perf_counter() - start
print(f"{label:12s} {seconds:5.2f} s {result.metadata['events']:>11,} events")
loop.verify(run) # runs both ways; raises unless the results are byte-identical
print("byte-identical")
# Without a build: loop_source says whether a model can be compiled.
dosed = crn.Model("dosed")
dosed.add_species("A", 10)
dosed.add_ode("drug", 1.0, "-0.1 * drug")
dosed.add_reaction("drug * A", ["A"], [], name="death")
try:
crn.loop_source(dosed)
except crn.CrnError as error:
print(error.diagnostics[0]["code"], error.diagnostics[0]["message"])
interpreted 0.45 s 9,400,096 events
compiled 0.29 s 9,400,096 events
byte-identical
CRN-R020 continuous variables require the hybrid method
A loop can be given in two places. run.simulate(compiled=loop) uses it for
one call, as above. crn.ensemble(..., compiled=loop) attaches it to the
prepared run, and every simulate() then runs compiled; use this when code
that knows nothing of loops calls simulate().
What a compiled model needs:
- A Rust toolchain, 1.85 or newer, from rustup, and access to crates.io for the first build.
- Time for the first build, about a minute. Builds are cached, and a cached call returns in a fraction of a second.
method="static_direct". A model that another method must run, such as one with continuous variables, is refused, as the last lines show.
The gain depends on the model. On 12 November 2026, on a two-CPU host, the compiled mtDNA model of tutorial S1, in its file form, ran 2.1 times as fast as the interpreted one (measurement). A network with many constant-rate reactions can run slower compiled, so time both. Methods and their options has the cache, the options and every limit.
Limits
- Binding prepares each candidate again. This takes about 0.2 ms for a small model. On very short runs it can be a visible share of a sweep.
- A candidate runs interpreted. A loop is compiled for one parameter
set, so
bind_parametersreturns a run without it. Compiling pays for many runs with fixed parameters, not for a sweep. - Compiled models use the linear scan only. For a model whose
autochoice is another selector (chapter 7), nameselector="linear"together withcompiled=. - Very large models are refused. A loop whose source would exceed 1 MiB is not generated.
- No callbacks. A compiled run takes no Python callback. Trackers and event logs work.
See also: Choosing a method, Fitting parameters to data, mtDNA performance analysis.
6. Stop conditions, trackers and event logs
Statistics at report times do not answer every question. When did the epidemic end? How high was its peak? When was a threshold first reached? These need what happens between report times. This chapter shows four tools that watch every event. The setup block builds the SIR model of chapter 2 with both rates as strings. The blocks of this chapter continue from it:
from collections import Counter
import crn_craft as crn
sir = crn.Model("sir")
sir.add_species({"S": 490, "I": 10, "R": 0})
sir.add_parameter({"beta": 5e-4, "gamma": 0.1})
sir.add_reaction("beta * S * I", ["S", "I"], ["I", "I"], name="infection")
sir.add_reaction("gamma * I", ["I"], ["R"], name="recovery")
Stop conditions
set_stop gives the model a condition over parameters and species counts.
It is checked at time 0 and after every event. The first time it is true,
the replicate ends: its termination is stopped, and its stop_time is the
time of that event. Here an epidemic is over when nobody is infected:
sir.set_stop("I == 0") # the epidemic is over
result = crn.ensemble(
sir,
end=1000.0,
report_times=[0.0, 1000.0],
replicates=1000,
seed=1,
threads=2,
method="static_direct",
).simulate()
print(result.records["termination"].value_counts().to_dict())
print(f"mean end of the epidemic: day {result.records['stop_time'].mean():.1f}")
print(result.statistics["mean"].round(1))
over = result.records["termination"] == "stopped"
print("over by day 100:", (over & (result.records["stop_time"] <= 100.0)).mean())
print(result.records.loc[over, "stop_time"].quantile([0.05, 0.5, 0.95]).round(1).to_dict())
{'stopped': 1000, 'completed': 0, 'event_limit': 0, 'sampling_limit': 0, 'instance_limit': 0, 'wall_time_limit': 0, 'cancelled': 0, 'failed': 0, 'output_limit': 0}
mean end of the epidemic: day 110.5
I R S
time
0.0 10.0 0.0 490.0
1000.0 0.0 446.1 53.9
over by day 100: 0.3
{0.05: 85.8, 0.5: 107.2, 0.95: 143.2}
A stopped replicate keeps its state to the end of the report times, so the means at day 1000 are the final sizes of the epidemics. The last two lines are the two usual outputs of a stop: the share of replicates stopped by a given time, and the distribution of the stop times.
Any expression can be a stop, for example "I >= 100" or
"R > 0.5 * (S + I + R)". A stopped replicate counts as complete, so the
statistics are there. set_stop(None) removes the condition. To record a
threshold without ending the replicate, use a tracker.
Trackers
A tracker follows one species at every event, at native speed, and reports per replicate:
appearancesandextinctions: how often the count rose from 0 or fell to 0, andlast_appearanceandlast_extinction: when it last did;minimumandmaximum;integral: the time integral of the count up to the stop or the end;first_passage: the first time an optional condition was true;- with
keep_episodes, the first excursions above zero, each with start, end, peak and duration. Later excursions are summarized: their number inomitted_episodes, their total duration inomitted_durationand their highest peak inomitted_peak.
run = crn.ensemble(
sir, end=1000.0, report_times=[0.0, 1000.0], replicates=1000, seed=1,
threads=2, method="static_direct",
trackers=[{"observable": "I", "first_passage": "I >= 100"}],
)
result = run.simulate()
tracker = result.tracker_columns(0) # tracker 0: one row per replicate
print(tracker[["maximum", "integral", "first_passage", "last_extinction"]].head(3).round(1))
print("mean peak of I:", tracker["maximum"].mean())
print("mean infected days per epidemic:", tracker["integral"].mean().round(1))
reached = tracker["first_passage"].dropna() # NaN: never reached 100
print(f"reached 100 infected: {len(reached) / 1000:.3f}, median day {reached.median():.1f}")
maximum integral first_passage last_extinction
replicate
0 115.0 4336.9 29.3 119.5
1 133.0 5046.4 14.7 107.4
2 122.0 4529.4 14.9 89.4
mean peak of I: 128.23
mean infected days per epidemic: 4457.5
reached 100 infected: 0.948, median day 20.7
The peak is exact, where the mean at report times would miss it. The
integral of I is the total time spent infected, so the integral over the
observed time is the time-averaged count. first_passage is the exact time
of the event that made the condition true. last_extinction equals the stop
time of the section before: the same seed gives the same replicates, and a
tracker does not change them.
Event logs
An event log keeps, for every replicate, up to max_entries events of the
listed reactions, or of all reactions if the list is empty. Each entry holds
the time, the reaction and the species counts after the event. This log
keeps the first five infections of every replicate:
run = crn.ensemble(
sir, end=1000.0, report_times=[0.0, 1000.0], replicates=200, seed=1,
threads=2, method="static_direct",
event_log={"max_entries": 5, "rules": ["infection"]},
)
result = run.simulate()
print(result.event_frame(0)) # the log of replicate 0 as a data frame
log = result.event_columns() # every log as one array
print(dict(log.sizes))
fifth = log["time"].sel(entry=4).to_series()
print(f"fifth infection: median day {fifth.median():.2f}")
print("later infections, not logged:", sum(o["omitted_log_entries"] for o in result.observations))
time rule rule_name I R S
entry
0 1.859423 0 infection 9.0 2.0 489.0
1 2.095936 0 infection 9.0 3.0 488.0
2 2.139428 0 infection 10.0 3.0 487.0
3 2.653214 0 infection 11.0 3.0 486.0
4 3.866311 0 infection 9.0 6.0 485.0
{'replicate': 200, 'entry': 5, 'variable': 3}
fifth infection: median day 1.88
later infections, not logged: 86268
result.event_frame() without an argument gives all logs as one frame,
indexed by replicate and entry. result.event_columns() gives them as an
xarray array with the dimensions replicate, entry and variable and the
coordinates time, rule and rule_name. A replicate with fewer events is
padded with NaN.
Logs reserve their space before the run: entries × replicates count against
max_output_bytes. A request that does not fit is refused with CRN-R020.
The message itemizes the reservation, and its hint names the smallest
max_output_bytes that admits the request. Use few entries, few replicates
or a larger limit.
Callbacks
A callback is a Python function that the engine calls for every event of a
replicate, in order. Returning False stops that replicate. This one stops
each epidemic at its 50th infection:
run = crn.ensemble(sir, end=1000.0, report_times=[0.0, 1000.0], replicates=20,
seed=1, method="static_direct")
infections = Counter()
def watch(replicate, event):
"""Count the infections of each replicate; stop it at the 50th."""
if run.rule_names[event["rule"]] == "infection":
infections[replicate] += 1
return infections[replicate] < 50
result = run.simulate(callback=watch)
stopped = result.records["termination"] == "stopped"
print("stopped at the 50th infection:", stopped.sum(), "of 20")
print("mean day of the 50th infection:", result.records.loc[stopped, "stop_time"].mean().round(2))
stopped at the 50th infection: 20 of 20
mean day of the 50th infection: 9.81
The event is a dictionary with the time, the index of the reaction in
rule and the species counts after the event in observables, sorted by
name. Three rules apply:
- A callback reads and may stop. It never changes the state or draws random numbers, so a run with a callback has the same events as one without.
- It is slow. Every event crosses into Python and holds the interpreter lock, which costs about a hundred times the simulation itself and makes the threads take turns. Use it on a few replicates.
- An exception in the callback cancels the run and is raised by
simulate(). The order of calls across replicates is not fixed.
Which one to use
| Question | Tool | Cost | Result |
|---|---|---|---|
| When does a condition first hold, if the replicate may end there? | stop condition | none | exact event time |
| Peak, time integral, first passage, appearances and extinctions | tracker | small | exact, one row per replicate |
| Which events happened, when, and what was the state after each? | event log | memory per entry, reserved before the run | exact, up to max_entries |
| Anything that needs Python code at every event | callback | slow, one thread at a time | exact |
| The state at chosen times | report times and kept paths (chapter 4) | memory per report time | exact at those times; what happens between them is not seen |
A first passage read from saved paths is a bound, not the time itself (chapter 11).
See also: Results, Methods and their options, trackers and logs on the mtDNA model.
7. Choosing a method
Every method reads the same model, and the argument method of
crn.ensemble selects one. This chapter says which method fits which model
and shows the exact and the approximate ones at work. The setup block builds
the immigration–death model of chapter 2. The blocks of
this chapter continue from it:
import time
import numpy as np
import crn_craft as crn
model = crn.Model("immigration_death")
model.add_parameter({"birth": 4.0, "death": 0.2})
model.add_species("A", 0)
model.add_reaction("birth", [], ["A"], name="birth")
model.add_reaction("death * A", ["A"], [], name="death")
Which method for which model
| Question | Model | Method | Exact? |
|---|---|---|---|
| Ensembles of a reaction network | any model built with crn.Model | "static_direct" | exact |
| A second exact method, as a cross-check | the same | "next_reaction" | exact |
| The whole distribution of a small system | few species, bounded counts | model.fsp(...) | exact up to reported error terms |
| Large populations, where exact events are too many | reaction networks | {"kind": "tau", "epsilon": ...} | approximate |
| Rates that read a continuous variable | built with add_ode | "hybrid" (chapter 9) | approximate at its tolerances |
| Species that appear during a run, each with its own identity | a model file with attributes | no method: the tree method (chapter 12) | exact |
| The three-class mtDNA model | built with crn.Model, or a model file | "mtdna_direct", a fast path (page S1d, page 12a) | exact |
| A stored model with an ATP block | a model file | "thinning" (page 12a) | exact |
For a model built with the builder, the answer is "static_direct" unless
one of the other rows applies. crn.describe()["methods"] lists the names.
Same law, different random numbers
Exact methods sample the same process, but each uses the random stream in its own way. The same seed therefore gives different trajectories under another method or selector. Results agree in distribution, not path by path: compare means and variances within their sampling error.
Every result names what ran in result.metadata["sampler"], for example
chacha8-u53-ziggurat/rules-static-direct/1: the random generator, the
method and the selector. An approximate method has approximate in its
sampler, so it cannot be mistaken for an exact one.
Static Direct and its selectors
Static Direct is Gillespie’s direct method: draw the time to the next event,
then select the reaction that fires. A selector decides how the reaction
is selected, selector= in crn.ensemble. All selectors sample the same
law:
| Selector | How it selects |
|---|---|
linear | a scan of the reactions in order |
composition_rejection | reactions grouped by the binary exponent of their rate |
sorting | a scan in an order that moves each fired reaction forward |
rssa_cr | candidates from rate bounds over population intervals, then an acceptance test |
auto | one of the others, chosen when the run is prepared (the default) |
rows = []
for selector in ["linear", "composition_rejection", "sorting", "rssa_cr", "auto"]:
result = crn.ensemble(model, end=30.0, report_times=[0.0, 30.0], replicates=400,
seed=42, method="static_direct", selector=selector).simulate()
rows.append((selector, result.metadata["sampler"].split("/")[1]))
for selector, sampler in rows:
print(f"{selector:22} {sampler}")
print(crn.describe()["selectors"]["auto"])
linear rules-static-direct
composition_rejection rules-static-direct-cr
sorting rules-static-direct-sorting
rssa_cr rules-static-direct-rssa-cr
auto rules-static-direct
{'composition_rejection_from_channels': 128, 'population_cut': 8.0, 'rssa_cr_from_channels': {'otherwise': 8, 'population_below_cut': 128}}
auto picks the linear scan for a small network such as this one. It picks
RSSA-CR from 8 reactions when no rate reads two or more species, and from
128 reactions when the species that start with molecules average fewer than
8; otherwise composition–rejection from 128 reactions. The last output line
holds these thresholds. auto decides from the initial counts, so a model
whose populations move far from them can get a slower selector.
For a network of some size, time the selectors on a short run before a long one. This model has twenty strains that compete for room. Each strain grows into the free room, dies, and gives rise to the next strain:
def strains(count):
"""Strains S0, S1, ... share room K; strain i gives rise to strain i + 1."""
names = [f"S{i}" for i in range(count)]
model = crn.Model(f"strains_{count}")
model.add_parameter({"K": 500.0, "g": 0.02, "mu": 0.001})
model.add_species({name: 200 if i == 0 else 0 for i, name in enumerate(names)})
free = f"max(0, K - ({' + '.join(names)})) / K"
for i, name in enumerate(names):
model.add_reaction(f"g * {name} * {free}", [name], [name, name], f"grow_{i}")
model.add_reaction(0.01, [name], [], f"die_{i}")
if i + 1 < count:
model.add_reaction(f"mu * {name}", [name], [name, names[i + 1]], f"mutate_{i}")
return model
twenty = strains(20)
for selector in ("linear", "composition_rejection", "sorting", "rssa_cr", "auto"):
run = crn.ensemble(
twenty,
end=300.0,
report_times=[0.0, 300.0],
replicates=200,
seed=1,
threads=2,
method="static_direct",
selector=selector,
)
start = time.perf_counter()
result = run.simulate()
seconds = time.perf_counter() - start
total = result.statistics["mean"].iloc[-1].sum()
print(
f"{selector:22s} {seconds:5.2f} s {result.metadata['events']:>9,} events "
f"molecules {total:6.1f} {result.metadata['sampler']}"
)
linear 0.15 s 312,169 events molecules 270.5 chacha8-u53-ziggurat/rules-static-direct/1
composition_rejection 0.21 s 313,771 events molecules 270.8 chacha8-u53-ziggurat/rules-static-direct-cr/1
sorting 0.14 s 312,179 events molecules 270.7 chacha8-u53-ziggurat/rules-static-direct-sorting/1
rssa_cr 0.20 s 313,771 events molecules 270.8 chacha8-u53-ziggurat/rules-static-direct-rssa-cr/1
auto 0.10 s 312,169 events molecules 270.5 chacha8-u53-ziggurat/rules-static-direct/1
The molecule counts agree within sampling error, and each selector names
itself in the sampler. Every rate here reads all strains, so auto runs the
linear scan on these 59 reactions, and RSSA-CR draws the same events as
composition–rejection. With 59 reactions no selector beats the scan by more
than the timing noise of such a short run: auto and linear are the same
computation, so any difference between their two times is noise.
Larger models
The same function builds a hundred strains. With 299 reactions, auto runs
composition–rejection:
hundred = strains(100)
print("schema:", hundred.to_dict()["schema"])
result = crn.ensemble(hundred, end=100.0, report_times=[0.0, 100.0], replicates=20,
seed=1, threads=2, method="static_direct").simulate()
print(result.metadata["sampler"], result.metadata["termination"])
print(f"{result.metadata['events']:,} events;", len(result.rule_names), "reactions")
schema: crn-craft.model/1.0
chacha8-u53-ziggurat/rules-static-direct-cr/1 completed
10,163 events; 299 reactions
Selectors pay off on large networks in which an event changes few rates. In this model every event changes every rate, so recomputing the rates costs more than selecting, and the choice of selector matters little. A model takes up to 4,096 species, 16,384 parameters and 65,536 reactions (limits). Methods and their options describes the selectors and their sources.
Exact distributions with finite state projection
For a small state space the chemical master equation can be solved directly. Finite state projection (FSP) lists the states within bounds that you give per species, sends every transition out of the bounds to a sink, and computes the probability of every state at every report time. Probability that leaves the bounds is reported, not hidden:
projection = model.fsp(end=20.0, report_times=[0.0, 2.0, 5.0, 20.0],
bounds={"A": 80}, max_states=81, tolerance=1e-10)
print(projection)
last_mean = projection.mean["A"].iloc[-1]
print(float(last_mean), float(projection.truncation["mass_defect"].iloc[-1]))
assert abs(last_mean - 20 * (1 - np.exp(-4))) < 1e-8
FspResult(81 states of A, 4 report times)
19.633687221220555 5.08937336718418e-11
Model.fsp returns an FspResult with the states, the probabilities
(a time by state array), the mean and the truncation error terms per
report time. mass_defect is the probability that is not on the projected
states. The other terms say where it went:
| Field | Meaning |
|---|---|
physical_leakage_estimate | probability that left the bounds, in the sink |
series_tail_upper_bound | upper bound on the truncated series of the time stepping |
discarded_weight_estimate | the series weight actually omitted |
roundoff_mass_residual | the remaining floating-point imbalance |
Here the projection matches the exact Poisson law to about 1e-12 and agrees with a histogram of 2,000 sampled paths:

FSP is for small systems with a fixed list of species (CRN-R017
otherwise). A projection that leaks needs wider bounds.
Approximate leaping
Tau leaping fires many reactions in one step. Each reaction fires a Poisson
number of times over a leap whose length keeps the relative change of every
rate below epsilon (Cao, Gillespie and Petzold 2006). A leap that would
make a count negative is rejected and halved, and a reaction that is close
to using up a reactant is simulated exactly:
approx = crn.ensemble(model, end=10.0, report_times=[0.0, 10.0], replicates=200,
seed=1, method={"kind": "tau", "epsilon": 0.01}).simulate()
exact = crn.ensemble(model, end=10.0, report_times=[0.0, 10.0], replicates=200,
seed=1, method="static_direct").simulate()
print(approx.metadata["sampler"])
print(approx.metadata["events"], "leaps and exact steps;", exact.metadata["events"], "exact events")
chacha8-u53/rules-approximate-cgp-poisson/2
12477 leaps and exact steps; 12153 exact events
For this small system, leaping does no less work than the exact method: with about 20 molecules a leap holds roughly one firing. It pays off only when populations are large.
How small must epsilon be? The figure compares 1,000 tau paths of a
birth–death process with mean 1,000 against 1,000 exact paths. The mean is
right at every epsilon. At epsilon = 0.1, three times the relative
standard deviation of the state (1/sqrt(1000) = 0.032), each leap moves
the state by more than its own fluctuations, and the variance is 83% too
large. For smaller epsilon the variance ratio stays within about two
standard errors of 1, which is the resolution of this experiment.

Rule of thumb: keep epsilon below the relative fluctuation of the species
you care about, and compare with an exact method on a reduced case before
you trust a large run.
{"kind": "binomial", "step": 1.0} is a second approximate method, with
fixed time steps. It runs only models in which every reaction is a birth or
a death of one molecule with one parent, and it serves to match a fixed-step
scheme (an example).
Other methods
"next_reaction" is the exact method of Gibson and Bruck, with one clock
per reaction. It samples the same law as Static Direct from other random
numbers, which makes it the natural cross-check of an exact result.
"hybrid"runs models with continuous variables (chapter 9).- The tree method runs when
methodis absent. It is exact, slower, and needed only for species with attributes that appear during a run (chapter 12). "mtdna_direct"serves one structure, the three-class mtDNA model, built with the builder or as a model file (page S1d)."thinning"serves one structure of model file (page 12a).- The Static Direct options
waiting_timeandsparse_trackersreproduce results of older releases (reference).
Performance notes
- Threads divide the replicates without changing results, and a compiled model gives byte-identical results in less time (chapter 5).
- Output costs memory: keep
keep_pathsand the number of report times as small as the question allows. - FSP costs states times series terms. Tighter bounds and a shorter end time help more than a looser tolerance.
- Tau leaping evaluates every reaction in every leap. On a network with
about a thousand reactions, Static Direct with
autois much faster.
See also: Methods and their options, Speed, Technical report.
8. Reproducing runs and published results
Two questions come up in every study. Can I get my own result again, and can I get the result of a paper? The first has a strict answer: the same model, request and seed give the same bytes. The second is statistical, and this chapter gives a recipe for it. The setup block builds the immigration–death model of chapter 2. The blocks of this chapter continue from it:
import json
import numpy as np
import crn_craft as crn
model = crn.Model("immigration_death")
model.add_parameter({"birth": 4.0, "death": 0.2})
model.add_species("A", 0)
model.add_reaction("birth", [], ["A"], name="birth")
model.add_reaction("death * A", ["A"], [], name="death")
What makes a run reproducible
Replicate i of a run draws from its own ChaCha8 random stream, keyed by the root seed, with i as the stream number. Replicates never share random numbers, and their results are combined in replicate order. So the numbers do not depend on the number of threads or on the machine:
digests = set()
for threads in [1, 2, 8]:
result = crn.ensemble(model, end=50.0, report_times=[0.0, 50.0], replicates=64,
threads=threads, keep_paths=4, seed=42,
method="static_direct").simulate()
numbers = dict(result.metadata)
numbers.pop("run_sha256") # the run's own hash covers `threads`
digests.add(json.dumps(numbers, sort_keys=True))
assert len(digests) == 1
print("identical across 1, 2 and 8 threads")
identical across 1, 2 and 8 threads
Sums of rates are computed in a fixed order, so there is no rounding that depends on scheduling. A result also names its model and its request by the SHA-256 of their exact bytes. If either changes by one character, the hash changes, and a result cannot be attributed to a model that was edited later.
What to record for a paper
Five items identify a run: the package version, the model hash, the request hash, the seed and the sampler. The result holds them all:
result = crn.ensemble(model, end=30.0, report_times=[0.0, 30.0], replicates=400,
seed=42, method="static_direct").simulate()
for key in ("sampler", "root_seed", "model_sha256", "run_sha256"):
print(f"{key:13s} {result.metadata[key]}")
saved = result.save("run.json", paths=False)
print(sorted(crn.load_report(saved)))
sampler chacha8-u53-ziggurat/rules-static-direct/1
root_seed 42
model_sha256 9977266823169a5efba1fd1937ade26f112c0f46ae6eb39f751e1bb2c8fa4168
run_sha256 03716d632059085bc23c578c4bc4146183120b1ef2f5c935f3ed0e7f234ced88
['crn_craft_version', 'model', 'request', 'result', 'schema']
result.save("run.json") writes one file with the model, the request, the
results and the package version, which is what a supplement needs
(chapter 4). Anyone with that file
and the same release can run the model again and compare. An archive goes
one step further and seals the files with a manifest that a verifier checks
(chapter 10). In the text of a
paper, name the release, the method and the seed.
Reproducing a published simulation
A paper reports a model and summary numbers: means, standard deviations,
perhaps a figure. The worked example is model 001-01 of the SBML discrete
stochastic models test suite (Evans, Gillespie and Wilkinson, Bioinformatics
24, 285–286, 2008, doi:10.1093/bioinformatics/btm566).
It is a birth–death process: X → 2 X at rate 0.1 per molecule and X → 0
at rate 0.11, starting from 100 molecules. Its mean is 100 exp(-0.01 t)
and its variance 2100 exp(-0.01 t) (1 - exp(-0.01 t)).
published = crn.Model("birth_death")
published.add_species("X", 100)
published.add_reaction(0.1, ["X"], ["X", "X"], name="birth")
published.add_reaction(0.11, ["X"], [], name="death")
n, times = 10_000, [10.0, 20.0, 30.0, 40.0, 50.0]
result = crn.ensemble(published, end=50.0, report_times=times, replicates=n,
seed=1, threads=2, method="static_direct").simulate()
t = np.array(times)
mu = 100 * np.exp(-0.01 * t) # the published mean
var = 2100 * np.exp(-0.01 * t) * (1 - np.exp(-0.01 * t)) # the published variance
mean = result.statistics["mean"]["X"].to_numpy()
s2 = result.statistics["sample_variance"]["X"].to_numpy()
z = np.sqrt(n) * (mean - mu) / np.sqrt(var)
y = np.sqrt(n / 2) * (s2 / var - 1)
for row in zip(t, mu, mean, z, var, s2, y):
print("t {:2.0f} mean {:5.2f} simulated {:5.2f} Z {:5.2f} "
"variance {:5.1f} simulated {:5.1f} Y {:5.2f}".format(*row))
t 10 mean 90.48 simulated 90.48 Z -0.01 variance 180.8 simulated 180.3 Y -0.22
t 20 mean 81.87 simulated 81.64 Z -1.34 variance 311.7 simulated 310.6 Y -0.25
t 30 mean 74.08 simulated 74.00 Z -0.40 variance 403.2 simulated 399.6 Y -0.64
t 40 mean 67.03 simulated 67.09 Z 0.26 variance 464.1 simulated 462.7 Y -0.21
t 50 mean 60.65 simulated 60.82 Z 0.75 variance 501.2 simulated 497.7 Y -0.50
The steps, for any paper:
- Translate the model. Check what a rate constant means in the source.
CRN-craft counts distinct combinations of molecules, so
A + Awith constantkfires atk A (A - 1) / 2. A source whose propensity isk A (A - 1), or whose deterministic rate isk A², corresponds to2 khere. Convert concentrations to molecule counts with the volume. If in doubt, write the rate as a string, which is the whole propensity (chapter 2). - Do not expect the paths. A seed does not carry over between tools, and not between methods or selectors of one tool. Reproduce the distribution: the same means and variances within sampling error.
- Compare with standard errors. With the published mean μ and standard
deviation σ,
Z = sqrt(n) (mean - μ) / σis close to a standard normal number if the simulation samples the published law.Y = sqrt(n/2) (s² / σ² - 1)does the same for the variance, less sharply, because counts are not normally distributed. The test suite’s user guide defines these two statistics. It treatsZbeyond ±3 as evidence of an error, and, becauseYrests on a normal approximation, onlyYbeyond ±5. Above, everyZandYlies well within ±3. A value beyond the range at one of many report times happens by chance now and then; a row of them is a discrepancy. - Choose the number of replicates. The standard error of the mean is
σ / sqrt(n). To see a differencedat three standard errors you needn = (3 σ / d)²: about 12,000 replicates to resolve 1% of the mean at t = 50 here, where σ is 22.4. - Cross-check. Run a second exact method (
method="next_reaction"). For a small system, compare with the exact distribution fromModel.fsp(chapter 7), which has no sampling error. Or export the model to another simulator (chapter 11). - Plot beside the published figure. Export the statistics as in chapter 4.
If the paper used an approximate method with a fixed time step, an exact run will differ from it by the error of that method. Compare with the exact law first; chapter 7 and the case study show how to match such a scheme.
What does not reproduce bit for bit
- Another method or selector. Each has its own sampler name and uses the random numbers differently. The law is the same, the paths are not.
- Another release with a new sampler name. A release that changes how
random numbers are used changes the sampler name, so old seeds are never
silently reused for other paths. Two cases exist: results that releases
before 0.7.0 computed for plain reaction networks, and requests of 0.7.0
that named
mtdna_directfor a model built withcrn.Model(Migrating). - Another request. Report times and kept paths do not change the trajectories, but they change the request hash.
What a run does not show
A check against an exact law, a published table or a second simulator confirms that the simulator solves the model. It does not confirm that the model describes the biology. Results and claims says what a result does and does not claim.
See also: Results, The command line, request files and archives, Technical report.
9. Continuous variables
Some quantities are not counts of molecules: an energy level, a drug
concentration, a temperature, a hazard that grows with age. A model can
carry such a quantity as a continuous variable. It follows an ordinary
differential equation between the events, and reaction rates may read it.
The setup block builds a population W whose replication is slowed by a
resource ATP that the population itself produces and uses. The blocks of
this chapter continue from it:
import math
import crn_craft as crn
cell = crn.Model("resource")
cell.add_parameter({"f": 0.1, "v1": 0.2, "v2": 0.01, "c": 1.3034153747670567})
cell.add_species("W", 1000)
cell.add_ode("ATP", 450.0, "f * W - v1 * ATP - v2 * W", lower_bound=0)
cell.add_reaction("c / (c + ATP) * W", ["W"], ["W", "W"], name="replication")
cell.add_reaction(0.0028881132523331052, ["W"], [], name="degradation")
A variable between events
add_ode(name, initial, derivative) declares the variable. Above, ATP
starts at 450 and changes at the rate f * W - v1 * ATP - v2 * W, which
reads the count W. The replication rate reads ATP in turn. A model with
a continuous variable runs under the method hybrid:
result = crn.ensemble(
cell,
end=2_400.0,
report_times=[0.0, 1_200.0, 2_400.0],
replicates=16,
seed=3,
threads=2,
method={"kind": "hybrid", "rtol": 1e-7, "atol": 1e-9},
).simulate()
print("method:", result.metadata["method"])
print(result.statistics["mean"].round(2))
method: {'atol': 1e-09, 'kind': 'hybrid', 'rtol': 1e-07}
W ATP
time
0.0 1000.00 450.00
1200.0 1000.06 449.55
2400.0 1005.75 452.43
Results report the variable as a column after the species. The arguments of
add_ode:
| Argument | Meaning |
|---|---|
name | the name; rates and derivatives read it like a species count |
initial | the value at time 0, a number or an expression over parameters |
derivative | dx/dt between events, an expression over parameters, species counts and continuous variables |
lower_bound, on_bound | optional: a bound, and "stop" (the default) or "clamp" |
independent | True for a variable that does not depend on the molecules (below) |
The hybrid method
Only method="hybrid" runs a model with continuous variables. The other
methods refuse it with CRN-R020. Between events, hybrid integrates the
variables together with the total rate, with an adaptive Runge–Kutta method
(Dormand–Prince 5(4)), and places the next event where the integrated rate
reaches an exponentially distributed threshold.
The method is approximate at its tolerances. method="hybrid" uses
rtol=1e-6 and atol=1e-9, and the dictionary form above sets others. The
result records them in metadata["method"], and its sampler has
approximate in its name. To see whether the tolerances matter, run again
with tighter ones and compare. Each event costs an integration step, so
hybrid is slower than Static Direct: use it when a rate reads a continuous
variable, not otherwise.
Methods and their options has the algorithm.
Bounds
A variable may have a lower bound, and on_bound says what happens there:
"stop"ends the replicate asstoppedwhen the variable reaches the bound while its derivative there is not positive. The variable reads the bound at every later report time, and the species keep their counts. In the model above, a population that runs out ofATPends."clamp"holds the variable at the bound and lets it follow the equation again once its derivative turns positive.
A bound is the way to stop on a continuous variable. The stop condition of
set_stop reads species counts only.
Independent variables
Some variables do not depend on the molecules at all: a daily rhythm, a dose
that decays on its own, a hazard that grows with age. Declare such a
variable with independent=True. Its initial and derivative may then
read only parameters and other independent variables. hybrid integrates
it once for the whole run, and every replicate reads that one solution. In
this model the death rate m grows as dm/dt = g m, whatever the molecules
do (Gompertz mortality):
gompertz = crn.Model("gompertz")
gompertz.add_parameter({"g": 0.5, "m0": 0.1})
gompertz.add_species({"A": 20})
gompertz.add_ode("m", "m0", "g * m", independent=True)
gompertz.add_reaction("m * A", ["A"], [], name="death")
result = crn.ensemble(
gompertz,
end=4.0,
report_times=[0.0, 2.0, 4.0],
replicates=4000,
seed=1,
threads=2,
method="hybrid",
).simulate()
print(result.metadata["continuous"], result.metadata["sampler"])
print(result.statistics["mean"].round(3))
survival = math.exp(-0.1 * (math.exp(2.0) - 1.0) / 0.5)
print(f"exact mean at t = 4: {20 * survival:.3f}")
# An independent derivative may read only parameters and independent variables.
wrong = crn.Model("wrong")
wrong.add_parameter("g", 0.5)
wrong.add_species("A", 20)
wrong.add_ode("m", 0.1, "g * m * A", independent=True)
wrong.add_reaction("m * A", ["A"], [], name="death")
try:
crn.ensemble(wrong, end=4.0, report_times=[4.0], method="hybrid")
except crn.CrnError as error:
print(error.diagnostics[0]["code"], error.diagnostics[0]["path"])
print(error.diagnostics[0]["message"])
['m'] chacha8-u53/rules-approximate-hybrid-dopri54/1
A m
time
0.0 20.000 0.100
2.0 14.154 0.272
4.0 5.585 0.739
exact mean at t = 4: 5.573
CRN-R012 /continuous/0/derivative
the derivative of independent variable `m` reads observable `A`
Each molecule survives to time t with probability exp(−∫m), so the count at t = 4 is binomial with mean 20 × 0.2786 = 5.573. The 4,000 replicates give 5.585.
An independent variable costs one integration per run, not one per
replicate, which matters when the forcing is large or stiff. A bound keeps
its meaning: with "stop", every replicate that is still running stops at
the same time, because the variable is the same in all of them.
Rules for continuous variables
- Rates may read them. The stop condition of
set_stopmay not (CRN-R012): stop on a variable with itslower_bound. - Trackers follow species only (
CRN-R020for a continuous variable). Event logs and callbacks see the variables’ values at each event. - A bound is checked along the integration steps. A variable that dips below its bound and returns within one step can be missed, and tighter tolerances shorten the steps.
- Compiled models and finite state projection do not take continuous variables.
See also: Choosing a method, Variable population: ATP, Model language.
10. The command line, request files and archives
Everything that Python does can also be done from a shell, with a model file and a request file. This is the way to run on a batch system or without Python, and to seal a run in an archive that can be verified later. The setup block builds the immigration–death model, writes it to a file and makes a folder for archives. The sections of this chapter build on each other’s files, so run them in order:
import hashlib
import json
import pathlib
import crn_craft as crn
model = crn.Model("immigration_death")
model.add_parameter({"birth": 4.0, "death": 0.2})
model.add_species("A", 0)
model.add_reaction("birth", [], ["A"], name="birth")
model.add_reaction("death * A", ["A"], [], name="death")
model_file = pathlib.Path("immigration-death.model.json")
model_file.write_text(model.to_json())
pathlib.Path("runs").mkdir(exist_ok=True)
The crn-craft command
The Python package installs the command crn-craft. The native tool from
cargo has the same name, the same commands and the same reports
(chapter 1). Every
command reads and writes JSON and exits 0 on success:

| Command | What it does | In Python |
|---|---|---|
crn-craft describe [KIND] | lists commands, methods and limits, or prints the JSON Schema of a document | crn.describe(), crn.describe("run-1.0") |
crn-craft check MODEL [REQUEST] | validates without running | crn.check(model, request) |
crn-craft run MODEL REQUEST | runs a request and prints the result | crn.prepare(model, request).simulate() |
crn-craft run ... --archive DIR | writes the run as a sealed archive | run.archive(directory) |
crn-craft verify DIR | checks an archive | crn.verify_archive(directory) |
crn-craft analyze MODEL | structure and conservation laws | Model.analyze() (chapter 11) |
crn-craft convert MODEL | converts a model of release 0.6.0 | crn.convert(data) (chapter 11) |
crn-craft export MODEL gillespy2 | writes GillesPy2 source | Model.to_gillespy2() (chapter 11) |
crn-craft-import | imports SBML and BioNetGen files | crn.read_sbml, crn.read_bngl (chapter 11) |
crn-craft describe run-1.0 prints the JSON Schema of a request, and
model-1.0, result-1.0 and fsp-result-1.0 those of the other documents.
A request file
A request says what to compute: the method, the report times, the
replicates, the seed and the budgets. crn.ensemble writes one from its
arguments; here you write it yourself. (To repeat from the shell a run that
crn.ensemble prepared, archive it in Python and replay the archive:
Replay.) It names its model by path and by
the SHA-256 of the file’s exact bytes, so a result can never be attributed
to a model that was edited afterwards:
request = {
"schema": "crn-craft.run/1.0",
"model": {
"path": model_file.name,
"sha256": hashlib.sha256(model_file.read_bytes()).hexdigest(),
},
"method": {"kind": "static_direct"},
"time": {"end": 10.0, "report_times": [0.0, 1.0, 2.0, 5.0, 10.0]},
"ensemble": {"replicates": 64, "root_seed": 42},
"outputs": {"statistics": ["mean", "variance"], "keep_paths": 2, "keep_instances": 0},
"budget": {
"max_events_per_replicate": 1_000_000,
"max_sampling_steps_per_replicate": 8_000_000,
"max_instances": 100_000,
"wall_time_s": 60.0,
"threads": 1,
"max_output_bytes": 1_048_576,
},
}
pathlib.Path("immigration-death.run.json").write_text(json.dumps(request, indent=2) + "\n")
print(crn.check(model_file.read_bytes(), request)["valid"])
True
| Field | Meaning |
|---|---|
model | path and SHA-256 of the model file |
method | static_direct, next_reaction, tau, fsp, … (chapter 7) |
time | the end and strictly increasing report_times in [0, end] |
ensemble | the number of replicates and the root_seed |
outputs | which statistics to compute, quantiles, and how many paths to keep |
budget | the limits of chapter 3, all explicit |
Check a model and a request
check takes a model file and an optional request and runs nothing:
sha256sum immigration-death.model.json
crn-craft check immigration-death.model.json immigration-death.run.json

Every problem is a diagnostic with a stable code, a JSON pointer to the field, a message and a hint. This block writes two broken files: a model whose rate reads a parameter that does not exist, and a request with the hash of some other model:
broken = crn.Model("immigration_death")
broken.add_species("A", 0)
broken.add_reaction("missing", [], ["A"], name="birth")
broken.add_reaction(0.2, ["A"], [], name="death")
pathlib.Path("missing-parameter.model.json").write_text(broken.to_json())
stale = json.loads(pathlib.Path("immigration-death.run.json").read_text())
stale["model"]["sha256"] = "0" * 64
pathlib.Path("stale-hash.run.json").write_text(json.dumps(stale, indent=2) + "\n")
crn-craft check missing-parameter.model.json || echo "exit status $?"
crn-craft check immigration-death.model.json stale-hash.run.json || echo "exit status $?"

Commands exit 1 for invalid input. Warnings (CRN-W...) do not change the
exit status. Diagnostics lists every code.
Run, archive and verify
run prints the result as JSON and exits 0 only when every replicate
completed. With --archive it writes a new directory instead: the exact
model and request bytes, the result, a manifest with the SHA-256 and length
of each file, and a COMPLETE marker that holds the manifest’s hash:
crn-craft run immigration-death.model.json immigration-death.run.json --archive runs/first
crn-craft verify runs/first

verify reads everything again, checks every hash and length, validates
the inputs and the result’s accounting, and exits 0 for a valid archive
(Archives). Change one byte and it fails:

The same from Python, on a prepared run. The result file has the same bytes as the one the command wrote:
request_file = pathlib.Path("immigration-death.run.json")
run = crn.prepare(model_file.read_bytes(), request_file.read_bytes(), quantiles=())
run.archive("runs/python")
print(crn.verify_archive("runs/python")["valid"])
print(pathlib.Path("runs/python/result.json").read_bytes() == pathlib.Path("runs/first/result.json").read_bytes())
True
True
Replay
The same request gives the same bytes in a second run. The result of an archived run is a file, so two runs can be compared with a hash:
crn-craft run immigration-death.model.json immigration-death.run.json --archive runs/replay-a > /dev/null
crn-craft run immigration-death.model.json immigration-death.run.json --archive runs/replay-b > /dev/null
sha256sum runs/replay-a/result.json runs/replay-b/result.json

An archive can be replayed later, on any host. It stores the model as
model.json, and its request.json still names the model by the original
path. So copy the model next to the request under the name that the request
gives in model.path, run the two, and compare the new result.json with
the old one:
mkdir replay
cp runs/first/request.json replay/request.json
cp runs/first/model.json replay/immigration-death.model.json
crn-craft run replay/immigration-death.model.json replay/request.json --archive runs/replayed > /dev/null
cmp runs/first/result.json runs/replayed/result.json && echo "same bytes"
same bytes
Nothing in a result depends on timing, on the number of threads or on the
host. An archive that Python wrote replays in the same way, also one of a
run that crn.ensemble prepared: crn.ensemble(model, ...).archive(directory)
writes the model and the request that the call made.
Python and the command line give the same result
crn.prepare takes the same two files as bytes. quantiles=() keeps the
request as written: by default Python adds quantiles, which changes the
request hash. The result then agrees with the one that crn-craft run
prints, apart from the per-replicate records, which Python moves into
result.records:
crn-craft run immigration-death.model.json immigration-death.run.json > cli-result.json
request_file = pathlib.Path("immigration-death.run.json")
same = crn.prepare(model_file.read_bytes(), request_file.read_bytes(), quantiles=()).simulate()
cli = json.load(open("cli-result.json"))
keys = ["run_sha256", "model_sha256", "sampler", "events", "statistics", "paths"]
print(all(same.metadata[key] == cli[key] for key in keys))
print(same.metadata["run_sha256"][:16], cli["run_sha256"][:16])
True
99145aac9340522c 99145aac9340522c
Requests for fsp and tau
Another method is another method field in the same request. Finite state
projection (chapter 7)
names its bounds and has no ensemble or outputs: nothing is sampled.
request = json.loads(pathlib.Path("immigration-death.run.json").read_text())
tau = dict(request, method={"kind": "tau", "epsilon": 0.03})
pathlib.Path("tau.run.json").write_text(json.dumps(tau, indent=2) + "\n")
fsp = {
"schema": request["schema"],
"model": request["model"],
"method": {"kind": "fsp", "bounds": {"A": 100}, "max_states": 102, "tolerance": 1e-10},
"time": request["time"],
"budget": {"wall_time_s": 60.0, "max_output_bytes": 1_048_576},
}
pathlib.Path("immigration-death.fsp.run.json").write_text(json.dumps(fsp, indent=2) + "\n")
for field, value in fsp.items():
print(f"{field}: {json.dumps(value)}")
schema: "crn-craft.run/1.0"
model: {"path": "immigration-death.model.json", "sha256": "4dc25f88b622851e185ec632149d2ade39aa9b47e6f60b9c8ba0c5f8c870e988"}
method: {"kind": "fsp", "bounds": {"A": 100}, "max_states": 102, "tolerance": 1e-10}
time: {"end": 10.0, "report_times": [0.0, 1.0, 2.0, 5.0, 10.0]}
budget: {"wall_time_s": 60.0, "max_output_bytes": 1048576}
The result of an fsp request is a crn-craft.fsp-result/1.0 document with
one snapshot per report time:
crn-craft run immigration-death.model.json immigration-death.fsp.run.json > fsp.json
python3 -c "import json; print(json.load(open('fsp.json'))['snapshots'][-1]['mass_defect'])"

The tau request runs like any other, and its result names an approximate sampler:
crn-craft run immigration-death.model.json tau.run.json > tau-result.json

Stop a run with a cancel file
A long run can be stopped by creating a file. This request would run for a very long time:
long = json.loads(pathlib.Path("immigration-death.run.json").read_text())
long["time"] = {"end": 1e6, "report_times": [0.0, 1e6]}
long["budget"]["max_events_per_replicate"] = 10**12
del long["budget"]["wall_time_s"]
pathlib.Path("long.run.json").write_text(json.dumps(long, indent=2) + "\n")
touch stop
crn-craft run immigration-death.model.json long.run.json --archive runs/stopped --cancel-file stop || echo "exit status $?"
crn-craft verify runs/stopped > /dev/null && echo "partial archive verifies"

run exits 1 for an incomplete ensemble. The stopped archive is still
sealed and verifiable: it says cancelled and withholds the statistics.
Chapter 3 does the same from Python.
Versions of requests and models
This chapter writes crn-craft.run/1.0 requests for crn-craft.model/1.0
models, the current versions. Documents of earlier releases are still read
(Contracts and versions).
See also: Archives, chapter 8, chapter 11.
11. Analysis, import and export
This chapter collects what surrounds a simulation: the structure of a network, two diagnostics of saved paths, and the exchange of models with other formats and tools. The setup block builds the immigration–death model. The blocks of this chapter continue from it:
import json
import pathlib
import numpy as np
import crn_craft as crn
model = crn.Model("immigration_death")
model.add_parameter({"birth": 4.0, "death": 0.2})
model.add_species("A", 0)
model.add_reaction("birth", [], ["A"], name="birth")
model.add_reaction("death * A", ["A"], [], name="death")
Two sections read a repository file:
models/legacy/immigration-death.model.json
and examples/guide/dimer.xml.
Copy them under the same paths, or work in the root of a clone.
Conservation laws and structure
Model.analyze reports structure without simulating: the stoichiometry, a
basis of conservation laws in exact integer arithmetic, the bounds they
imply for the initial state, and complexes, linkage classes and deficiency.
The example is an enzyme mechanism, S + E <-> ES -> E + P:
enzyme = crn.Model("enzyme_mechanism")
enzyme.add_species({"S": 50, "E": 10, "ES": 0, "P": 0})
enzyme.add_reaction(0.01, ["S", "E"], ["ES"], name="bind")
enzyme.add_reaction(0.1, ["ES"], ["S", "E"], name="unbind")
enzyme.add_reaction(0.5, ["ES"], ["E", "P"], name="catalysis")
report = enzyme.analyze()["analysis"]
print(report["species"])
print(report["conservation"]["basis"]) # E + ES and S + ES + P
print(report["initial_class_upper_bounds"]) # S, E, ES, P cannot exceed these
print("deficiency", report["linkage"]["deficiency"])
pathlib.Path("enzyme-mechanism.model.json").write_text(enzyme.to_json()) # for the last section
['S', 'E', 'ES', 'P']
[{'coefficients': ['0', '1', '1', '0'], 'initial_total': '10'}, {'coefficients': ['1', '0', '1', '1'], 'initial_total': '50'}]
['50', '10', '10', '50']
deficiency 0
The laws are E + ES = 10 and S + ES + P = 50, so every count is bounded,
and the deficiency is zero. The limits of the analysis are explicit: when
one is reached, the report says unavailable and never implies that no law
exists. A model with continuous variables has no such report (CRN-R017).
crn-craft analyze MODEL prints the same report for a model file
(Analysis report).
Oscillations
observables.oscillation classifies one time series. The example is a
repressilator: three genes that repress each other in a ring, with Hill
repression, built in a loop over the genes:
from crn_craft.observables import oscillation
circuit = crn.Model("repressilator")
circuit.add_parameter({"alpha0": 0.216, "alpha": 216.0, "K": 40.0, "n": 2.0})
circuit.add_parameter({"beta": 5.0, "gamma_m": 1.0, "gamma_p": 0.2})
circuit.add_species("p1", 5)
for gene, repressor in ((1, 3), (2, 1), (3, 2)):
mrna, protein = f"m{gene}", f"p{gene}"
hill = f"alpha0 + alpha / (1 + (p{repressor} / K)^n)"
circuit.add_reaction(hill, [], [mrna], name=f"tx{gene}")
circuit.add_reaction(f"beta * {mrna}", [mrna], [mrna, protein], name=f"tl{gene}")
circuit.add_reaction(f"gamma_m * {mrna}", [mrna], [], name=f"dm{gene}")
circuit.add_reaction(f"gamma_p * {protein}", [protein], [], name=f"dp{gene}")
grid = list(np.linspace(0, 200, 1001))
path = crn.ensemble(circuit, end=200.0, report_times=grid, replicates=1,
keep_paths=1, method="static_direct").simulate()
p1 = path.paths.isel(replicate=0).sel(variable="p1").to_numpy()
verdict = oscillation(grid, p1)
print(verdict["classification"], round(verdict["period"], 1))
oscillatory 40.1
A single exact path oscillates, with amplitudes that vary between cycles:

oscillation drops a burn-in (20% by default), removes the mean, and calls
a series oscillatory only when the dominant Fourier peak holds at least
30% of the power, spans at least three cycles, and the autocorrelation at
that period is at least 0.2. Fewer than three cycles is ambiguous. It is a
diagnostic of one trajectory, not a validated biological detector.
First passage from saved paths
sampled_first_passage estimates when paths first reach a threshold, from
saved states only. A path can cross and fall back between two report times,
so the first saved hit is an upper bound on the passage time, and the
detected fraction is a lower bound on the probability of a passage:
from crn_craft.observables import sampled_first_passage
fine = list(np.linspace(0, 10, 201))
paths = crn.ensemble(model, end=10.0, report_times=fine, replicates=500, seed=42,
keep_paths=500, method="static_direct").simulate()
counts = list(paths.paths.sel(variable="A").to_numpy())
for step in [1, 20]:
bound = sampled_first_passage(fine[::step], [c[::step] for c in counts], 15)
print(step * 0.05, bound["detected_fraction"], bound["restricted_mean_upper"])
0.05 0.928 6.075
1.0 0.88 6.878

A finer grid gives tighter bounds. For the exact time, use a tracker with a first-passage condition, which sees every event (chapter 6).
Convert a network model of release 0.6.0
Release 0.6.0 had a second model format for reaction networks,
crn-craft.model/0.1. check, analyze, convert and export read it.
crn-craft convert prints it as a current model:
crn-craft convert models/legacy/immigration-death.model.json > converted.model.json
crn-craft check converted.model.json > /dev/null && echo "the converted model is valid"

crn.convert does the same in Python, from bytes to bytes:
legacy = pathlib.Path("models/legacy/immigration-death.model.json")
converted = crn.Model.from_dict(json.loads(crn.convert(legacy.read_bytes())))
print(converted)
Model('immigration_death': 1 species, 2 reactions)
A network without reactions, or with population limits, is refused with
CRN-R016. Migrating has the other changes since 0.6.0.
Import SBML and BioNetGen
crn.read_sbml, crn.read_bngl and the command crn-craft-import convert
an explicit subset of SBML Level 3 Version 2 and of expanded BioNetGen
.net files. They reject what they cannot represent exactly (events, rules,
fast reactions, non-integer stoichiometry, unit ambiguity) instead of
guessing. The rate convention must be stated. This block writes a BioNetGen
network of the dimerization 2 A -> B:
pathlib.Path("dimer.net").write_text(
"begin parameters\n1 k 0.1\nend parameters\n"
"begin species\n1 A() 20\n2 B() 0\nend species\n"
"begin reactions\n1 1,1 2 k\nend reactions\n"
)
crn-craft-import bng-net dimer.net dimer.import.json --convention binomial

The command writes a crn-craft.import/1.0 report with the provenance and
the model. In Python the import returns a Model with an import_report:
dimer = crn.read_bngl("dimer.net", convention="binomial")
print(dimer, dimer.import_report["source_format"])
sbml = crn.read_sbml("examples/guide/dimer.xml", convention="stochastic_count_propensity")
print(sbml, sbml.import_report["source_format"])
means = crn.ensemble(sbml, end=50.0, report_times=[0.0, 50.0], replicates=100,
seed=1, method="static_direct").simulate().statistics["mean"]
print(means.iloc[-1].to_dict())
Model('ImportedBioNetGen': 2 species, 1 reactions) bionetgen_expanded_net_subset
Model('Dimer': 2 species, 1 reactions) sbml_l3v2_core_subset
{'A': 0.0, 'B': 10.0}
The 20 molecules of A pair up into 10 of B. An imported model runs under
every method, like a built one.
Export to GillesPy2
crn-craft export MODEL gillespy2 writes GillesPy2 1.8.3 source for a model
file, here the enzyme mechanism that the first section wrote. It is meant
for a cross-check with another simulator
(chapter 8). The
command never runs the source:
crn-craft export enzyme-mechanism.model.json gillespy2 > export.json

In Python, enzyme.to_gillespy2() returns the gillespy2.Model when
GillesPy2 is installed. GillesPy2 export
says which models can be exported.
See also: Analysis report, Comparison with GillesPy2.
12. Model files and species with attributes
Every model so far had species that are plain counts. Some models need
more: each molecule carries attributes, such as the clone a mutant belongs
to, and new kinds of molecules appear during the run. This chapter builds
such a model with crn.Model, then turns to the model as a JSON document:
what the builder writes, model files, and documents written by hand, which
are the special case. The setup block builds the immigration–death model of
chapter 2. The blocks of this chapter continue from it:
import copy
import json
import math
import pathlib
import time
import crn_craft as crn
model = crn.Model("immigration_death")
model.add_parameter({"birth": 4.0, "death": 0.2})
model.add_species("A", 0)
model.add_reaction("birth", [], ["A"], name="birth")
model.add_reaction("death * A", ["A"], [], name="death")
When species are not a fixed list
Some models cannot list their species in advance: every new mutant is its
own clone, a polymer has a length, a cell carries a lineage. For such
systems a species type carries numeric attributes. An instance is a
type with one value per attribute and a count. Instances appear when a rule
produces a new combination of values and disappear when their count reaches
zero. A reaction is then a pattern: it stands for the reactions of every
instance that matches. The builder declares such a species with
add_species(name, attributes=[...]); the
model language describes the document it
writes.
Species with attributes in the builder
A cell holds 1000 mtDNA molecules. Each molecule degrades with a half-life
of ten days, free places are refilled by copies of a random survivor, and a
copy is a new mutant with probability pmut. Every mutation founds its own
clone, so the number of clones is not known in advance. The molecules carry
the attribute clone, with 0 for the wild type, and time is in hours:
clones = crn.Model("mtdna_clones")
clones.add_parameter({"K": 1000, "delta": math.log(2) / 240, "pmut": 1e-3, "r": 10.0})
clones.add_species("mtDNA", attributes=["clone"]) # molecules carry a clone id
clones.add_initial("mtDNA", 1000, clone=0) # 1000 molecules of clone 0, the wild type
clones.add_observable("mutants", "mtDNA", where="x.clone > 0")
clones.add_observable("types", "mtDNA", reduce="distinct")
clones.add_observable("mutant_types", "mtDNA", where="x.clone > 0", reduce="distinct")
clones.add_observable("largest", "mtDNA", where="x.clone > 0", reduce="max_count")
refill = "r * max(0, K - mtDNA) / mtDNA" # per survivor; mtDNA is the total count
clones.add_reaction(crn.mass_action("delta"), ["mtDNA"], [], name="degradation")
clones.add_reaction(crn.mass_action(f"{refill} * (1 - pmut)"), ["mtDNA"],
[crn.copy("x"), crn.copy("x")], name="replication")
clones.add_reaction(crn.mass_action(f"{refill} * pmut"), ["mtDNA"],
[crn.copy("x"), crn.new("mtDNA", clone="new_id()")], name="mutation")
print(clones, crn.check(clones)["valid"])
year = 24 * 360.0
result = crn.ensemble(clones, end=year, report_times=[0.0, year / 2, year],
replicates=100, seed=1, threads=2).simulate()
print(result.metadata["sampler"])
print(result.statistics["mean"].round(2))
Model('mtdna_clones': 1 species, 3 reactions) True
chacha8-u53/rules-direct/2
largest mtDNA mutant_types mutants types
time
0.0 0.00 1000.00 0.00 0.00 1.00
4320.0 7.47 999.54 2.35 11.25 3.35
8640.0 12.82 999.67 3.15 20.26 4.15
After a year a cell holds about 20 mutant molecules in three clones, and its largest clone has about 13 molecules. The calls:
add_species("mtDNA", attributes=["clone"])declares the species and its attribute. Its molecules at time 0 come fromadd_initial("mtDNA", 1000, clone=0), one call per combination of attribute values.- A reactant given as a species name is any molecule of it, labeled
x(the second reactant isy). A replication consumesxand gives two copies of it,crn.copy("x"), so the clone keeps its identity. A mutation gives one copy and a molecule with every attribute set,crn.new("mtDNA", clone="new_id()");new_id()is an identity no molecule has had in this run. crn.mass_action(expression)is a rate per reactant molecule, as a number is: the degradation fires atdeltatimes the number of molecules, and each molecule is equally likely to be the one degraded. The refill divides by the count of survivors, so all replications together fill the free places at rater * (K - mtDNA).
The exact tree method runs the model, which happens when method is left
out, because the set of clones changes during the run. Each cell had about
50,000 events in the year.
Observables
Every species has an observable under its own name, its count: here
mtDNA. add_observable(name, species, where=None, weight=None, reduce="sum") adds others. where selects instances by their attributes,
weight gives each instance a number (both read the instance as x), and
reduce says how the matching instances become one number:
reduce | Value |
|---|---|
"sum" (default) | the sum of weight × count: with no weight, the number of matching molecules (mutants) |
"distinct" | the sum of the weights, each instance once: with no weight, the number of matching instances (types, mutant_types) |
"max", "min" | the largest or smallest weight; 0 when no instance matches |
"max_count" | the largest count among the matching instances, times the weight; 0 when none matches (largest, the size of the largest mutant clone) |
Observables are columns of the results, and rates, the stop condition and
trackers read them by name, as the refill rate reads mtDNA.
Reactants, products and rates
In add_reaction | Meaning |
|---|---|
"mtDNA" as a reactant | any molecule of the species; labeled x, the second y |
crn.pattern("mtDNA", where="x.clone > 0", factor="x.size") | the molecules that satisfy where, each counted factor times |
crn.copy("x"), crn.copy("x", size="x.size + 1") | a product with the attributes of reactant x, some of them overridden |
crn.new("mtDNA", clone="new_id()") | a product with every attribute given |
a number, or crn.mass_action("expression") | a rate per combination of reactant molecules |
| a plain string | the reaction’s whole propensity |
Attribute values are numbers or expressions over parameters, the reactants’
attributes (x.clone) and random draws such as new_id() or
choice(p, a, b). A product of a species with attributes must say where
its attributes come from, so a bare species name is refused:
try:
clones.add_reaction(0.01, ["mtDNA"], ["mtDNA", "mtDNA"])
except ValueError as error:
print(error)
species 'mtDNA' has attributes, so a product of it says where they come from: crn_craft.copy(label) copies a reactant, crn_craft.new('mtDNA', clone=...) gives every attribute
A plain string rate keeps its meaning from chapter 2:
the whole propensity. On a species with attributes the reaction then fires
at that rate and takes a molecule uniformly, whatever its clone, so
"delta * mtDNA" and crn.mass_action("delta") give the same degradation.
Only mass_action (or a number) combines with a pattern’s where or
factor, and the static methods accept a whole propensity only over a
species with a single instance. Use mass_action for rates per molecule.
What the builder writes
The builder writes a crn-craft.model/1.0 document. Every species is a
type, here one without attributes, and every reaction is a rule over
the types:
document = model.to_dict()
print(document["schema"])
print(json.dumps(document["rules"][1]))
crn-craft.model/1.0
{"name": "death", "reactants": [{"label": "x", "type": "A"}], "propensity": "death * A", "products": []}
A string rate becomes a propensity, the whole expression. A number or
crn.mass_action becomes a rate, the factor that multiplies the count of
each reactant. A species with attributes becomes a type with attributes,
add_initial an entry of initial, add_observable an entry of
observables, crn.copy("x") the product {"type": "mtDNA", "copy": "x"}
and crn.new a product with attributes.
Save and load a model file
model.to_json() is the text of a model file. crn.load(path) reads a
file, checks it, and returns its exact bytes. crn.ensemble takes those
bytes, a dictionary or a Model:
path = pathlib.Path("immigration-death.model.json")
path.write_text(model.to_json())
data = crn.load(path) # checked; raises crn.CrnError for an invalid file
loaded = crn.Model.from_dict(json.loads(data))
print(type(data).__name__, loaded)
settings = dict(end=30.0, report_times=[0.0, 30.0], replicates=400, seed=42,
method="static_direct")
built = crn.ensemble(model, **settings).simulate()
from_file = crn.ensemble(data, **settings).simulate()
print("same numbers:", built.statistics["mean"].equals(from_file.statistics["mean"]))
print("same hash:", built.metadata["model_sha256"] == from_file.metadata["model_sha256"])
document = json.loads(data) # a dictionary can be edited like any JSON
document["parameters"]["birth"] = 8.0
print(crn.ensemble(document, **settings).simulate().statistics["mean"]["A"].iloc[-1])
bytes Model('immigration_death': 1 species, 2 reactions)
same numbers: True
same hash: False
39.61500000000001
The file and the built model give the same numbers. Their hashes differ,
because a hash names exact bytes and the file is indented. Model.from_dict
wraps a document as a Model, with fsp, analyze and to_gillespy2. The
add_* calls work on it when the builder could have written it, which
includes documents with attributes, filtered observables and the rules of
any of these sections.
Packaged examples
The package holds five example models: immigration-death,
michaelis-menten, enzyme-mechanism, repressilator and vilar-noise.
crn.load_example returns one as a Model. The packaged immigration–death
model runs the same paths as the model built above:
example = crn.load_example("immigration-death")
for candidate in (model, example):
result = crn.ensemble(
candidate, end=30.0, report_times=[0.0, 30.0], replicates=400, seed=42,
method="static_direct",
).simulate()
print(result.metadata["events"], result.statistics["mean"]["A"].iloc[-1])
88037 20.092500000000012
88037 20.092500000000012
A model document for three strains
A model can also be written as a document by hand, in Python as a
dictionary; model files from other tools and earlier releases look like
this. Three strains of cells share room places. The resident strain 0
gives rise to two variants, every strain dies at one rate, and strain 2
grows twice as fast into the free room. Each cell is an instance of the type
Cell with the attribute strain:
grow = "max(0, room - total) / crowding"
twin = {"type": "Cell", "copy": "c"}
strains = {
"schema": "crn-craft.model/1.0",
"name": "three_strains",
"parameters": {"room": 200, "loss": 0.01, "g": 0.5, "eps": 0.0002},
"types": [{"name": "Cell", "attributes": ["strain"]}],
"initial": [{"type": "Cell", "attributes": {"strain": 0}, "count": 200}],
"observables": {
"total": {"type": "Cell"},
"crowding": {"type": "Cell", "weight": "1 + (x.strain == 2)"},
"variants": {"type": "Cell", "where": "x.strain > 0"},
},
"stop": "total > 0 && variants >= 0.5 * total",
"rules": [],
}
for strain, rate in ((0, "g"), (1, "g"), (2, "2 * g")):
cell = [{"label": "c", "type": "Cell", "where": f"c.strain == {strain}"}]
strains["rules"] += [
{"name": f"die_{strain}", "reactants": cell, "rate": "loss", "products": []},
{"name": f"grow_{strain}", "reactants": cell, "rate": f"{grow} * {rate}",
"products": [twin, twin]},
]
for strain in (1, 2):
resident = [{"label": "c", "type": "Cell", "where": "c.strain == 0"}]
variant = {"type": "Cell", "attributes": {"strain": strain}}
strains["rules"].append({"name": f"switch_to_{strain}", "reactants": resident,
"rate": f"{grow} * eps", "products": [twin, variant]})
print(crn.check(strains)["valid"], len(strains["rules"]), "rules")
pathlib.Path("three-strains.model.json").write_text(json.dumps(strains, indent=2) + "\n")
True 8 rules
The parts of the document, and the builder calls that write them:
initiallists instances: 200 cells withstrain0 (add_initial("Cell", 200, strain=0)).observablesreduce the instances of one type to a number.whereselects instances (variants), andweightweighs them (crowdingcounts a cell of strain 2 twice);add_observabletakes the same fields. Results have one column per observable, and rates and thestopread observables by name. This document has no count observable named after the type, which the builder would add.- A reactant is a pattern: a
label, atypeand an optionalwhereover the attributes (crn.pattern("Cell", where="c.strain == 0", label="c")). Therateis per matching cell, as a mass-action constant is (crn.mass_action). - A product copies a reactant (
copy,crn.copy("c")), gives all attributes (attributes,crn.new), or copies and overrides some.
Run it
The three strains are a closed set of attribute values, so the model runs under the static methods like a reaction network. This block loads the file of the section before:
strains = json.loads(crn.load("three-strains.model.json"))
def run(model, method):
start = time.perf_counter()
result = crn.ensemble(model, end=2000.0, report_times=[0.0, 2000.0], replicates=4000,
seed=1, threads=2, method=method).simulate()
seconds = time.perf_counter() - start
taken = (result.records["termination"] == "stopped").mean()
print(f"{method:14s} {seconds:5.2f} s variants took over: {taken:.3f} "
f"{result.metadata['sampler']}")
return result
run(strains, "static_direct")
run(strains, "mtdna_direct")
# A strain that dies faster breaks the shared death rate, so the run
# falls back to Static Direct and says why.
faster = copy.deepcopy(strains)
next(r for r in faster["rules"] if r["name"] == "die_1")["rate"] = "2 * loss"
result = run(faster, "mtdna_direct")
print([d["message"] for d in result.metadata["diagnostics"]])
static_direct 3.22 s variants took over: 0.421 chacha8-u53-ziggurat/rules-static-direct/1
mtdna_direct 0.97 s variants took over: 0.427 chacha8-u53-ziggurat/rules-mtdna-direct/1
mtdna_direct 3.00 s variants took over: 0.434 chacha8-u53/rules-static-direct/1
['mtdna_direct ran Static Direct: degradation is not one constant rate shared by all classes']
mtdna_direct is an exact fast path for one structure: three classes in a
fixed room, one shared death rate, and growth into the free room. It reads
the structure from the rules, whatever the names, and certifies each model
before it runs. The first two runs agree within sampling error (with 4,000
replicates each, the standard error of their difference is about 0.011). A
model that does not fit runs Static Direct instead, and a CRN-R051 warning
names the failed check: read metadata["sampler"] to see what ran. The
certificate also reads whole-rule propensities, as the builder writes them,
when the request is crn-craft.run/1.0, which crn.ensemble writes; so
the builder form of the three-class mtDNA model runs the fast path too
(page S1d).
Page 12a uses the fast path on the
mtDNA model files.
New identities and random attributes
A product attribute may be a random draw: new_id() returns an identity
that no instance has had, and choice(p, a, b) is a with probability p,
else b. Here a growing cell sometimes founds a new strain with its own
identity and a drawn weight w. The observable strains counts distinct
instances:
grow = "max(0, room - total) / crowding * g"
cell = {"label": "c", "type": "Cell"}
weighted = dict(cell, factor="c.w") # the rate counts a cell w times
twin = {"type": "Cell", "copy": "c"}
founder = {"type": "Cell", "attributes": {"strain": "new_id()", "w": "choice(0.2, 2, 1)"}}
founders = {
"schema": "crn-craft.model/1.0",
"name": "founders",
"parameters": {"room": 200, "loss": 0.01, "g": 0.5, "eps": 0.002},
"types": [{"name": "Cell", "attributes": ["strain", "w"]}],
"initial": [{"type": "Cell", "attributes": {"strain": 0, "w": 1}, "count": 200}],
"observables": {
"total": {"type": "Cell"},
"crowding": {"type": "Cell", "weight": "x.w"},
"strains": {"type": "Cell", "reduce": "distinct"},
},
"rules": [
{"name": "die", "reactants": [cell], "rate": "loss", "products": []},
{"name": "grow", "reactants": [weighted], "rate": grow, "products": [twin, twin]},
{"name": "found", "reactants": [weighted], "rate": f"{grow} * eps",
"products": [twin, founder]},
],
}
result = crn.ensemble(founders, end=2000.0, report_times=[0.0, 1000.0, 2000.0],
replicates=200, seed=1, threads=2).simulate()
print(result.metadata["sampler"])
print(result.statistics["mean"].round(2))
print("strains founded per replicate:", result.rule_events["found"].mean())
print("most strains alive at once:", result.records["peak_instances"].max())
try:
crn.ensemble(founders, end=2000.0, report_times=[0.0, 2000.0], method="static_direct")
except crn.CrnError as error:
print(error)
chacha8-u53/rules-direct/2
crowding strains total
time
0.0 200.00 1.00 200.00
1000.0 224.12 2.07 196.12
2000.0 270.94 2.27 196.27
strains founded per replicate: 7.435
most strains alive at once: 8
CRN-R020: random product attributes require the dynamic engine at /method
One grow rule now serves every strain. The set of instances changes
during the run, so the static methods refuse the model, and the exact tree
method, which runs when method is absent, takes it. With the builder the
weighted reactant is crn.pattern("Cell", factor="c.w", label="c") and the
founder crn.new("Cell", strain="new_id()", w="choice(0.2, 2, 1)").
Page 12a
follows every mutant lineage of the mtDNA model in this way.
Limits and versions
A crn-craft.model/1.0 document takes up to 4,096 types, 16,384 parameters
and 65,536 rules (limits). Model
files of earlier releases (crn-craft.rules-model/0.x) are still read
(Contracts and versions).
See also: Model language, Fig 1C/1D of a published study, built with the builder, The mtDNA model files.
The mtDNA model files: clones, the fast path and stored models
The case study built its model in Python. The repository also has the mtDNA
models as JSON files, in which every molecule is an instance of the type
mtDNA with attributes (chapter 12). Two things need
those files: following every mutant lineage, and the stored form of the ATP
model. The fast path mtdna_direct runs the file and the builder model. To
run this page, copy the folder models/rules/ of the repository into your
working folder. The setup block is the model of the
index page, for comparison with the files. The
blocks of this page continue from it:
import math
import numpy as np
import crn_craft as crn
END = 25_920.0 # three years (1,080 days), in hours
def three_class(K=1000, w0=1000, m0=0, mu=3e-5, sm=1.5, half_life_days=10, takeover=None):
"""The three-class mtDNA model: wild type W, neutral M, advantaged A."""
model = crn.Model("mtdna_three_class")
model.add_parameter({"K": K, "delta": math.log(2) / (24 * half_life_days),
"sw": 1.0, "sm": sm, "mu": mu, "fracAdv": 0.2})
model.add_species({"W": w0, "M": m0, "A": 0})
free = "max(0, K - W - M - A) / (W + sm * (M + A))"
model.add_reaction(f"{free} * sw * (1 - mu) * W", ["W"], ["W", "W"], "replication_wt")
model.add_reaction(f"{free} * sw * mu * (1 - fracAdv) * W", ["W"], ["W", "M"], "mutation_mt")
model.add_reaction(f"{free} * sw * mu * fracAdv * W", ["W"], ["W", "A"], "mutation_mtAdv")
model.add_reaction(f"{free} * sw * M", ["M"], ["M", "M"], "replication_mt")
model.add_reaction(f"{free} * sm * A", ["A"], ["A", "A"], "replication_mtAdv")
for label, species in (("wt", "W"), ("mt", "M"), ("mtAdv", "A")):
model.add_reaction(f"delta * {species}", [species], [], f"degradation_{label}")
if takeover is not None:
model.set_stop(f"W + M + A > 0 && M + A >= {takeover} * (W + M + A)")
return model
The five model files
Applies: chapter 12, When species are not a fixed list.
File in models/rules/ | What it models | Methods |
|---|---|---|
mtdna-three-class.rules.json | the model of the index page, as three classes of one type | every generic method, and the fast path mtdna_direct |
mtdna-three-class-cme.rules.json | the same with K = 20 and fast rates, for exact checks against the master equation | as above |
mtdna-three-class-atp-continuous.rules.json | the ATP model of page S1c, with ATP as a continuous variable | hybrid |
mtdna-three-class-atp.rules.json | the same in the stored form, with a fixed atp block | thinning |
mtdna-fixed.rules.json | every new mutant is its own clone with an identity | the tree method |
Each molecule has three attributes: clone (0 for wild type, 1 and 2 for
the two mutant classes, or an identity in the clone model), s (its
replication weight) and wt (1 for wild type, 0 for mutants). The files
declare observables that the builder model writes as sums: N is
W + M + A, wild_type is W, mutants is M + A, neutral_mutants and
advantaged_mutants are M and A, and D is the competition
denominator. The parameters are those of the index page, with w0 as a
parameter. The files have no stop; the blocks below add the takeover stop
N > 0 && mutants >= 0.9 * N.
The fast path
Applies: chapter 12, Run it, and page S1d.
mtdna_direct is an exact method fused for one structure: three classes in
a fixed population. At preparation it certifies the model:
- three classes and eight channels, with the roles of degradation, replication and mutation read from the channels;
- one constant degradation rate shared by all classes;
- every replication and mutation rate is
max(0, K - N) / Dtimes constant factors, with one integerKof at most 1,000,000; - every observable is a weighted sum over the three classes;
- no stop, or the guarded fraction
N > 0 && mutants >= f * N; - every positive hazard stays finite and resolvable in every reachable state.
The builder model writes whole-rule propensities. Since release 0.7.1 the
certificate reads them too when the request is crn-craft.run/1.0, which
crn.ensemble writes: each propensity must be the vacancy law times
constants and the parent’s count, with the same K, degradation rate and
weights in every reaction, and the stop must be the takeover fraction
written over the three species
(methods). The same
64 cells under the fast path and under Static Direct, for the file and the
builder model:
import json
import time
document = json.loads(crn.load("models/rules/mtdna-three-class.rules.json"))
document["stop"] = "N > 0 && mutants >= 0.9 * N"
arms = (("file", document, "mtdna_direct"), ("file", document, "static_direct"),
("builder", three_class(takeover=0.9), "mtdna_direct"),
("builder", three_class(takeover=0.9), "static_direct"))
for label, model, method in arms:
run = crn.ensemble(model, end=END, report_times=[0.0, 12_960.0, END], replicates=64,
seed=5, threads=2, method=method)
start = time.perf_counter()
result = run.simulate()
seconds = time.perf_counter() - start
stopped = (result.records["termination"] == "stopped").sum()
print(f"{label:8s} {method:14s} {seconds:5.2f} s {result.metadata['events']:>10,} events "
f"taken over {stopped:2d} {result.metadata['sampler']}")
file mtdna_direct 0.16 s 8,969,870 events taken over 8 chacha8-u53-ziggurat/rules-mtdna-direct/1
file static_direct 0.63 s 8,861,769 events taken over 10 chacha8-u53-ziggurat/rules-static-direct/1
builder mtdna_direct 0.16 s 8,969,870 events taken over 8 chacha8-u53-ziggurat/rules-mtdna-direct/1
builder static_direct 0.56 s 9,231,158 events taken over 7 chacha8-u53-ziggurat/rules-static-direct/1
The fast path samples the same process as Static Direct from other random numbers, so the results agree in distribution, not cell by cell. The builder model under the fast path makes the same draws as the file: the same events and takeovers. On 12 November 2026, on a two-CPU host, the fast path took 2.8 times less time than Static Direct on the file. On 13 November 2026, the builder model under the fast path took 0.97 times the file’s time, under Static Direct 3.6 times as long as the fast path, and its compiled loop 1.4 times as long (measurements).
A model the certificate does not accept still runs: as Static Direct with
inverse waits, with a CRN-R051 warning that names the failed check. Read
metadata["sampler"] to see what ran. The file with another stop falls
back; the builder model is certified:
odd = dict(document, stop="mutants > 250") # not the guarded fraction
for model in (odd, three_class(takeover=0.9)):
result = crn.ensemble(model, end=100.0, report_times=[0.0, 100.0], replicates=2,
method="mtdna_direct").simulate()
print(result.metadata["sampler"])
print([d["message"] for d in result.metadata["diagnostics"]])
chacha8-u53/rules-static-direct/1
['mtdna_direct ran Static Direct: stop is neither absent nor the guarded mutant fraction']
chacha8-u53-ziggurat/rules-mtdna-direct/1
[]
To record another threshold at the full speed of the fast path, keep the guarded stop and add a first-passage tracker (page S1b). Methods and their options has the full certificate.
Every lineage with the clone model
Applies: chapter 12, New identities and random attributes.
In mtdna-fixed.rules.json every new mutant gets its own clone identity
(new_id()) and a drawn weight (choice(fracAdv, sm, sw)). The set of
instances changes during a run, so only the tree method runs it. The
observable mutant_clones counts distinct mutant clones, and a complete
event log gives every lineage’s birth, death and largest size. A small cell
(K = 100) with a high mutation probability keeps every event in the log:
import json
model = json.loads(crn.load("models/rules/mtdna-fixed.rules.json"))
model["parameters"].update({"K": 100, "w0": 100, "mu": 0.01, "delta": 0.05})
result = crn.ensemble(
model, end=400.0, report_times=[0.0, 100.0, 200.0, 400.0], replicates=20,
seed=6, threads=2, keep_instances=3, trackers=[{"observable": "mutant_clones"}],
event_log={"max_entries": 5000, "rules": []}, max_output_bytes=1 << 30,
).simulate()
print("sampler:", result.metadata["sampler"])
print("mean distinct mutant clones:", result.statistics["mean"]["mutant_clones"].to_numpy())
print("peak instances, max over cells:", result.records["peak_instances"].max())
print("instances created per cell:", result.records["created_instances"].mean())
print("log entries omitted:", sum(o["omitted_log_entries"] for o in result.observations))
# Lineages from the full log: replay each cell's net changes per clone id.
born, died, peak = {}, {}, {}
for observation in result.observations:
counts = {}
for entry in observation["log"]:
change = {}
for sign, records in ((-1, entry["reactants"]), (1, entry["products"])):
for record in records:
clone, _, wt = record["attributes"]
if wt == 0: # mutant clones only
key = (observation["id"], clone)
change[key] = change.get(key, 0) + sign * record["count"]
for key, delta in change.items():
counts[key] = counts.get(key, 0) + delta
born.setdefault(key, entry["time"])
peak[key] = max(peak.get(key, 0), counts[key])
if counts[key] == 0:
died[key] = entry["time"]
life = np.array([died[k] - born[k] for k in born if k in died])
print(f"{len(born)} clones born, {len(life)} lost within the horizon")
print("median lifetime of lost clones (h):", round(float(np.median(life)), 2))
print("largest clone ever (molecules):", max(peak.values()))
sampler: chacha8-u53/rules-direct/2
mean distinct mutant clones: [0. 1.9 2.6 1.85]
peak instances, max over cells: 7
instances created per cell: 10.1
log entries omitted: 0
202 clones born, 165 lost within the horizon
median lifetime of lost clones (h): 18.43
largest clone ever (molecules): 100
Most lineages are lost within a day of their birth; a few grow. For
K = 1000 over three years, a cell has about 150,000 events, too many to
log whole. Follow lineages there with mutant_clones, peak_instances and
created_instances, and log only the mutation and degradation rules of a
few cells.
The stored ATP block and thinning
Applies: chapter 7, Other methods, and page S1c.
mtdna-three-class-atp.rules.json writes the ATP model of page S1c with a
fixed atp block, a form of an earlier release. method="thinning"
samples it exactly, against a bound on each interval. Stored files and
requests of this form keep working and replay byte for byte. For new
models, use a continuous variable (page S1c):
import json
data = crn.load("models/rules/mtdna-three-class-atp.rules.json")
print("ATP block:", json.loads(data)["atp"])
result = crn.ensemble(data, end=END, report_times=[0.0, END], replicates=64, seed=7,
threads=2, method="thinning").simulate()
print("sampler:", result.metadata["sampler"])
print("stopped (ATP exhausted):", (result.records["termination"] == "stopped").sum())
print(result.statistics["mean"][["N", "mutants", "ATP"]].round(2))
ATP block: {'wild_type': 'wild_type', 'total': 'N', 'initial': 450.0, 'production': 0.1, 'decay': 0.2, 'maintenance': 0.01, 'scale': 1.3034153747670567, 'replication_rules': ['replication_wt', 'mutation_mt', 'mutation_mtAdv', 'replication_mt', 'replication_mtAdv']}
sampler: chacha8-u53/rules-atp-thinning/1
stopped (ATP exhausted): 8
N mutants ATP
time
0.0 1000.00 0.00 450.00
25920.0 5919.92 4587.14 394.85
The final means of this run and of page S1c differ. Mutant expansion is
rare and lets the population grow, so the final population is
heavy-tailed, and 64 cells are too few to compare methods.
validation/check_hybrid.py
compares hybrid with thinning on 400 cells each, with declared tests.
See also: Model files and species with attributes, Methods and their options.
13. Using CRN-craft from R
CRN-craft has no native R package. From R, call the Python package through
reticulate: models, ensembles and
results work as in Python, and pandas results arrive as R data frames. The
example
examples/r/sir.R
was run on 13 November 2026 with:
- R 4.3.3 and reticulate 1.35.0
- crn-craft 0.7.0, imported as
crn_craft - Python 3.12.3 with NumPy 1.26.4, pandas 2.3.3 and xarray 2026.9.0
The R blocks of this page are not run by the guide’s checker, because CI has no R. The outputs below are those of that run.
One-time setup
install.packages("reticulate")
reticulate::virtualenv_create("crn-craft", packages = "crn-craft")
Use a current reticulate from CRAN with NumPy 2 and pandas 3. reticulate
1.35, the version of Ubuntu’s r-cran-reticulate package, failed on this
host with NumPy 2.3 and pandas 3.1 (“C stack usage is too close to the
limit”) and worked with NumPy 1.26 and pandas 2.3. The test of release
0.6.0 found that reticulate 1.47 converts results from NumPy 2 and pandas 3
to data frames and arrays.
Example: SIR model
The model is built with the builder calls of chapter 2,
written with $ instead of .:
library(reticulate)
use_virtualenv("crn-craft", required = TRUE)
crn <- import("crn_craft")
# Counts must be R integers (999L); rates and parameters are doubles.
sir <- crn$Model("sir")
invisible(sir$add_species(list(S = 999L, I = 1L, R = 0L)))
invisible(sir$add_parameter(list(beta = 2e-4, gamma = 0.01)))
invisible(sir$add_reaction("beta * S * I", list("S", "I"), list("I", "I"), name = "infection"))
invisible(sir$add_reaction("gamma * I", list("I"), list("R"), name = "recovery"))
invisible(sir$set_stop("I == 0")) # a replicate stops when the epidemic is over
# Vectors go in as list(...): a length-1 R vector would become a scalar.
result <- crn$ensemble(
sir, end = 200, report_times = list(0, 50, 100, 200),
replicates = 200L, seed = 1L, threads = 2L,
method = "static_direct", keep_paths = "all"
)$simulate()
# pandas results arrive as data.frames (rows = report times or replicates).
mean <- result$statistics$mean
records <- result$records
# Kept paths: an xarray DataArray -> R array with named dimensions,
# [replicate, time, variable].
paths <- result$paths
dims <- unlist(paths$dims)
arr <- paths$values
coord <- function(name) as.vector(paths$coords$get(name)$values)
dimnames(arr) <- setNames(lapply(dims, coord), dims)
long <- as.data.frame.table(arr, responseName = "count") # tidy data.frame
print(mean)
print(table(records$termination))
print(arr[1:3, , "I"])
print(head(long, 3))
I R S
0 1.000 0.000 999.000
50 675.960 99.960 224.080
100 538.365 431.440 30.195
200 197.345 772.695 29.960
completed stopped event_limit sampling_limit instance_limit
194 6 0 0 0
wall_time_limit cancelled failed output_limit
0 0 0 0
time
replicate 0 50 100 200
0 1 705 583 218
1 1 825 511 176
2 1 802 500 185
replicate time variable count
1 0 0 I 1
2 1 0 I 1
3 2 0 I 1
Six of the 200 epidemics die out within the first 24 days, five of them
before any infection. There the stop condition I == 0 holds, and these
replicates are recorded as stopped. result$statistics also holds
median and quantiles (chapter 4).
Event logs
event_columns() returns a DataArray with the dimensions
[replicate, entry, variable], so result$event_columns()$values is an R
array in that order. Its coordinates time, rule and rule_name are
matrices over replicate and entry (chapter 6):
log <- result$event_columns() # with event_log = list(max_entries = 5L)
values <- log$values # [replicate, entry, variable]
times <- log$coords$get("time")$values # [replicate, entry]
names <- log$coords$get("rule_name")$values # [replicate, entry]
one <- result$event_frame(0L) # one replicate's log as a data.frame
Pitfalls
- Counts must be R integers. Write
999L,replicates = 200L,seed = 1Landthreads = 2L. A plain200is a double, and it is rejected with “‘float’ object cannot be interpreted as an integer”, or, for a species count, “must be an integer, not float”. - Pass vectors as
list(...). reticulate turns a length-1 R vector into a single number, soreport_times = c(10)fails with “‘float’ object is not iterable”. Writereport_times = list(10)instead. The same applies to reactant and product lists: writelist("I"), not"I". - Read multi-indexed frames as arrays. reticulate drops the two-level
index (replicate, time) of
paths_frame(), and the (replicate, entry) index ofevent_frame(). Useresult$pathsandresult$event_columns(), as above;event_frame(id)for one replicate is fine. - Read coordinates with
coords$get(...).paths$variablereturns the whole data array instead, because the name clashes with an attribute that xarray defines itself. - A model is not a list. Set a stop with
model$set_stop("..."); chapter 2 lists the other builder calls. - Large seeds. R integers are 32-bit, so seeds above 2,147,483,647 cannot
be written as
Lliterals.
Without Python
The crn-craft command line reads and writes JSON, which R can handle with
jsonlite. A model file and a request file then replace the Python calls;
chapter 10 has everything about them.
See also: A first model, The command line, request files and archives.
Troubleshooting
Symptoms, causes and where the guide explains them.
Runs that end early
statisticsisNone. A replicate ended on a budget, was canceled or failed, so the statistics are withheld (CRN-R050). Look atresult.records["termination"](chapter 3).IncompleteEnsembleWarningaftersimulate(). Some replicates ended early; the message counts them per termination and names the argument to raise.strict=Truemakes it anIncompleteEnsembleError(chapter 3).event_limitorsampling_limitin every replicate. Raisemax_events;max_sampling_stepsfollows it unless you set it yourself, in which case raise it too.max_events=Noneremoves both limits; pair it withwall_time_s(chapter 3).observation reservation exceeds budget. An event log reserves space for every replicate before the run. The hint of the error names the smallestmax_output_bytesthat admits the request; or use fewer replicates or entries (chapter 6).
Methods and models
- A run is much slower than expected. Name
method="static_direct": withoutmethodthe tree method runs (chapter 7). - Different results with another method or selector. Each uses the random numbers differently. Compare distributions, not paths (chapter 7).
CRN-R020at/methodfor a model with continuous variables. Onlymethod="hybrid"runs them (chapter 9).CRN-R031. A rate is below 2⁻⁵³ of the total rate, for example a tiny mutation probability in a huge population. Rescale the model, or run withoutmethod: the tree method resolves rules and instances separately.mtdna_directis not faster. Readmetadata["sampler"]and theCRN-R051warning, which names the check that failed (page 12a).
Python results
'Model' object does not support item assignment. Acrn.Modelis not a dictionary. Usemodel.set_stop(...), or editmodel.to_dict()and pass the dictionary (chapter 12).- No replicate stopped, though some should have. Compare the termination
with a name:
records["termination"] == "stopped". - A column holds another species than expected. Select columns by name.
Species are sorted by name, also in the raw matrices of
result.metadata(chapter 4). - A Python callback is slow. It holds the interpreter lock. Use trackers or event logs for whole ensembles (chapter 6).
Compiled models
crn.compile_loopraisesCompiledLoopError. Itsreasonsays why:"cargo_missing"(install Rust with rustup),"build_failed"(readerror.log; for a version that is not on crates.io, passsource=a checkout), or"mismatch".CRN-R020at/methodor/method/selector. The model needs another method, orautochose another selector than the linear scan: nameselector="linear"(chapter 5).
Frequent diagnostic codes
| Code | Meaning |
|---|---|
CRN-R012 | an expression error or an unknown name |
CRN-R020 | an invalid request: hash, budget, method, tracker, log or version |
CRN-R030 | an invalid rate, an overflow or an undefined stop in a replicate |
CRN-R031 | a positive rate too small to select; see above |
CRN-R040 to CRN-R045 | a budget was reached |
CRN-R050 | an incomplete ensemble; statistics withheld |
CRN-R051 | a requested fast path did not apply; the message says why |
Diagnostics lists every code.
Migrating from earlier releases
This page is for code, models and results of earlier releases. A new user can skip it. The setup block builds the strain model of chapter 7. The blocks of this page continue from it:
import crn_craft as crn
def strains(count, builder=crn.Model):
"""Strains S0, S1, ... share room K; strain i gives rise to strain i + 1."""
names = [f"S{i}" for i in range(count)]
model = builder(f"strains_{count}")
model.add_parameter({"K": 500.0, "g": 0.02, "mu": 0.001})
model.add_species({name: 200 if i == 0 else 0 for i, name in enumerate(names)})
free = f"max(0, K - ({' + '.join(names)})) / K"
for i, name in enumerate(names):
model.add_reaction(f"g * {name} * {free}", [name], [name, name], f"grow_{i}")
model.add_reaction(0.01, [name], [], f"die_{i}")
if i + 1 < count:
model.add_reaction(f"mu * {name}", [name], [name, names[i + 1]], f"mutate_{i}")
return model
Tutorials renumbered in 0.10.0
Release 0.10.0 moved the tutorials out of the user guide into two groups and renumbered them. The user guide is chapters 1 to 13. The old paths in the repository are stubs that name the new page, and the old addresses of the site redirect.
| Until 0.9.0 | From 0.10.0 |
|---|---|
| Chapter 12, case study: mtDNA mutants | Tutorial S1 |
| Chapter 13, fitting parameters to data | Tutorial O1 |
| Chapter 14, model files and species with attributes | Chapter 12 |
| Chapter 15, using CRN-craft from R | Chapter 13 |
| Chapter 16, re-creating a published study | Tutorial S2 |
| Chapter 17, comparing mtDNA mechanisms | Tutorial S3 |
| Chapter 18, inferring mtDNA takeover times | Tutorial O2 |
| Chapter 19, spatial spread of mtDNA deletions | Tutorial S4 |
| Chapter 20, mitochondrial networks and drift | Tutorial S5 |
| Chapter 21, the mtDNA bottleneck | Tutorial S6 |
| Chapter 22, protein distributions | Tutorial S7 |
| Chapter 23, fitting single-cell RNA distributions | Tutorial O3 |
| Chapter 24, optimization lessons | The lessons page |
A page keeps its letter: 19b is S4b, 14a is 12a. Lessons C1 to C10 keep
their names. Records of earlier work keep the old numbers: changelog
entries before 0.10.0, the logs under docs/campaign, docs/decisions and
docs/evidence, and the merge records under validation/merge.
One engine since 0.7.0
Releases up to 0.6.0 had two engines: a network engine for fixed reaction
networks, at the top level of the Python package, and a rules engine for
models whose species carry attributes, in crn_craft.rules. Release 0.7.0
merged them into one engine, which runs every model of both. Network models
of 0.6.0 convert with crn-craft convert, and code written for
crn_craft.rules keeps running: that module keeps the API and the defaults
of release 0.6.0 under its old name. The
changelog
has the full account.
From the 0.6.0 module to the top level
Code written for 0.6.0 with from crn_craft import rules runs unchanged:
the same names, defaults, documents, hashes and numbers. Code that moves to
import crn_craft as crn changes as follows:
crn.rules (0.6.0) | crn (0.7.0) |
|---|---|
rules.Model writes rules-model/0.3 (since 0.8.0 crn-craft.model/1.0 for the calls new in 0.8.0: species with attributes, add_observable, crn.pattern, crn.copy, crn.new) | crn.Model writes crn-craft.model/1.0: larger limits, three or more reactant molecules |
rules.ensemble writes the lowest rules-run version, and Static Direct scans | crn.ensemble writes crn-craft.run/1.0; Static Direct uses the selector auto, so its paths can differ for models with many reactions (selector="linear" keeps them) |
statistics has mean, sample_variance and mean_standard_error | also median and quantiles by default |
result.metadata["schema"] is crn-craft.rules-result/0.x | crn-craft.result/1.0, with new hashes |
crn_craft.rules.describe() | crn.describe(): crn-craft.describe/1.0; the 0.6.0 fields are under legacy.rules |
The old module always scans, whatever the size of the model, so adding
quantiles= to a 0.6.0 script never changes its paths. Its models keep the
limits of rules-model, which a hundred strains exceed:
settings = dict(end=300.0, report_times=[0.0, 300.0], replicates=200, seed=1, threads=2)
old = crn.rules.ensemble(strains(20), method="static_direct", **settings).simulate()
print("crn.rules:", old.metadata["sampler"], sorted(old.statistics))
new = crn.ensemble(strains(20), method="static_direct", **settings).simulate()
print("crn: ", new.metadata["sampler"], sorted(new.statistics))
big = strains(100, crn.rules.Model)
print("rules.Model schema:", big.to_dict()["schema"])
try:
crn.rules.ensemble(big, method="static_direct", **settings)
except crn.CrnError as error:
print("refused:", error.diagnostics[0]["code"], error.diagnostics[0]["path"])
result = crn.ensemble(strains(100), method="static_direct", **settings).simulate()
print("Model:", result.metadata["sampler"], len(result.rule_names), "reactions")
crn.rules: chacha8-u53-ziggurat/rules-static-direct/1 ['mean', 'mean_standard_error', 'sample_variance', 'samples']
crn: chacha8-u53-ziggurat/rules-static-direct/1 ['mean', 'mean_standard_error', 'median', 'quantiles', 'sample_variance', 'samples']
rules.Model schema: crn-craft.rules-model/0.3
refused: CRN-R015 /types
Model: chacha8-u53-ziggurat/rules-static-direct-cr/1 299 reactions
On twenty strains auto also picks the linear scan, so the two modules
give the same paths; the top level adds median and quantiles. On a
hundred strains the old module refuses the model, and the top level runs it
with composition–rejection. To lift the limits of an old model file, change
its schema string to
crn-craft.model/1.0: the two mean the same thing.
From the network engine of 0.6.0, in Python
The network functions of the top level were removed. Each has a successor:
| 0.6.0 | 0.7.0 |
|---|---|
crn.load_example(name) (network bytes) | crn.load_example(name) returns a crn.Model of the converted model |
crn.run_spec(...) + crn.simulate(model, run) | crn.ensemble(model, end=..., report_times=..., replicates=..., method="static_direct").simulate() |
crn.prepare(model, run, cached=...) | crn.prepare(model, request) with a rules or run/1.0 request |
crn.ssa_spec, crn.simulate_ssa, crn.prepare_ssa | crn.ensemble(..., method="static_direct", selector=...) or method="next_reaction" |
aggregator: "direct", "cached_direct", "direct_cr", "sorting_direct", "rssa_cr" | selector: "linear", "linear", "composition_rejection", "sorting", "rssa_cr" |
aggregator: "next_reaction" | method="next_reaction" |
fast: true or false | no such switch |
crn.prepare_parameters(model, request), ParameterTemplate.bind(values) | crn.ensemble(...), then run.bind_parameters({name: value}) (chapter 5) |
template.parameter_names | the model’s parameters |
crn.mass_action_kernel_source(model) | crn.loop_source(model), crn.compile_loop(model) (chapter 5) |
crn.fsp(model, run) | model.fsp(end=..., report_times=..., bounds={...}) |
crn.tau(model, request) | crn.ensemble(..., method={"kind": "tau", "epsilon": ...}) |
crn.analyze(model) | crn.Model(...).analyze() or crn.load_example(name).analyze() (analysis/1.0) |
crn.check(model, run) (check/0.1) | crn.check(model, request) (check/1.0) |
crn.model_bytes(document) | crn.rules.model_bytes(document) |
From the network engine, on the command line
| 0.6.0 | 0.7.0 |
|---|---|
crn-craft simulate MODEL RUN DIR, simulate-cached | crn-craft convert MODEL > model.json, then crn-craft run model.json request.json --archive DIR |
crn-craft ssa MODEL REQUEST | crn-craft run with "method": {"kind": "static_direct", "selector": ...} or next_reaction |
crn-craft tau MODEL REQUEST | crn-craft run with "method": {"kind": "tau", "epsilon": ...} |
crn-craft fsp MODEL RUN | crn-craft run MODEL REQUEST with the method fsp |
crn-craft check MODEL [RUN] (check/0.1) | crn-craft check MODEL [REQUEST] (check/1.0) |
crn-craft verify DIR of an archive/0.1 | rerun with crn-craft run ... --archive DIR; verify reads archive/1.0 |
crn-craft rules, rules-check | crn-craft run, check (the old names are kept as aliases) |
Chapter 11
shows crn-craft convert and crn.convert.
What replays and what does not
- Rules documents and
crn_craft.rulescode of 0.6.0 run unchanged with the same results, byte for byte, apart from the budgets of the next item. - Default budgets since 0.8.0.
crn.ensembleandcrn.rules.ensemblewritemax_events10⁸ (it was 10⁶) and amax_sampling_stepsof 16 ×max_events(it was 8 × 10⁶) unless you give them. A run that completed before gives the same numbers, with a newrun_sha256, because the request states other budgets; a run that ended on a budget now goes further.max_events=1_000_000, max_sampling_steps=8_000_000writes the request of 0.7.1 again.simulate()now warns withcrn.IncompleteEnsembleWarningwhen replicates end early (chapter 3). - Network-engine results of 0.6.0 do not replay byte for byte. The network loops and their random stream (xoshiro256++) are gone. The one engine samples the same laws: a law gate checked it over 4,814 comparisons on twelve models, including references from finite state projection, with no failure, for every selector.
- The top level and the old module differ in paths for models on which
autopicks a selector other than the linear scan, and every result of the top level has new hashes, because its request and result documents are new versions. - Results of 0.7.0 replay byte for byte in 0.7.1, with one exception.
In 0.7.0,
crn.ensemble(model, method="mtdna_direct")on a three-class model built withcrn.Modelran Static Direct and said so: the sampler waschacha8-u53/rules-static-direct/1, with the warningCRN-R051. From 0.7.1 the same request runs the fast path (chacha8-u53-ziggurat/rules-mtdna-direct/1): other paths of the same law. To get the 0.7.0 numbers again, namemethod={"kind": "static_direct", "waiting_time": "inverse", "sparse_trackers": False}(the fast path).
Contracts
model/0.1 → model/1.0 (by crn-craft convert); run/0.1,
ssa-run/0.1–0.4, tau-request/0.1 → run/1.0; result/0.1 and 0.2,
ssa-result/0.1–0.4, tau-result/0.1 → result/1.0; fsp-result/0.1
→ fsp-result/1.0; check/0.1 → check/1.0; analysis/0.1 and 0.2 →
analysis/1.0; archive/0.1, archive-check/0.1 → archive/1.0,
archive-check/1.0; describe/0.11 → describe/1.0. The rules-*
contracts are unchanged, and model/1.0 means what rules-model/0.4 means.
Contracts and versions lists every version
that is still read.
Older releases
Python packages: pandas is required since 0.3.0 and xarray since 0.5.0. The
extra crn-craft[xarray] still installs.
Code written for release 0.5.0:
| 0.5.0 | Now |
|---|---|
result.paths with dimensions (time, variable, replicate) | dimensions (replicate, time, variable); result.paths.transpose("time", "variable", "replicate") gives the old order |
result.paths.values[t, v, r] | result.paths.values[r, t, v]; code that selects by name (sel, mean("replicate")) is unchanged |
R code written for 0.5.0 that indexes paths by position must use the new
order; code that reads the dimension names, as in
chapter 13, works with both.
Code written for release 0.4.0:
| 0.4.0 | Now |
|---|---|
result.paths, a DataFrame | result.paths_frame(); result.paths is a DataArray |
result.paths.loc[3] | result.paths.sel(replicate=3), or result.paths_frame().loc[3] |
result.paths["mutants"].unstack("time") | result.paths.sel(variable="mutants").to_pandas() |
result.event_columns(), result.event_columns(id), DataFrames | result.event_frame(), result.event_frame(id); event_columns returns DataArrays |
pip install "crn-craft[xarray]" | pip install crn-craft: xarray is required; the extra still installs |
Model.add_continuous(...) | Model.add_ode(...) with the same arguments; add_continuous and the alias add_ODE still work, and add_continuous emits a DeprecationWarning |
Code written for the NumPy results of release 0.2.0:
| 0.2.0 | Now |
|---|---|
records["termination"] == crn.rules.TERMINATIONS.index("stopped") | records["termination"] == "stopped"; the old form is silently all False |
records["id"] | records.index |
records["rule_events"] | result.rule_events |
records[name] (an array) | records[name].to_numpy(); integer termination codes are records["termination"].cat.codes |
statistics["mean"][:, names.index("N")] | statistics["mean"]["N"] |
statistics["mean"] (an array) | statistics["mean"].to_numpy() |
metadata["paths"] rows | result.paths_frame(), or result.paths_frame().to_numpy() |
tracker_columns(i)["id"] and fields | tracker_columns(i).index and its columns |
event_columns(id)["observables"] | event_columns(id).to_numpy() |
keep_paths=True (one cell) | keep_paths=1; True now keeps every cell |
Rust
The Rust changes of 0.7.0 (the crate path crn_craft::rules, new struct
fields, Kinetics::from_bytes, parameter binding) are in
Rust API.
See also: Contracts and versions, Convert a network model.
S1. Case study: mtDNA mutants
What this case study covers
Applies: chapter 1, How to read this guide.
A cell holds about a thousand copies of its mitochondrial DNA. Copies degrade and are replaced by replication, and a replication can produce a mutant. Some mutants replicate faster than the wild type. Over years, a mutant class can take over a cell. The case study asks the questions a researcher asks of such a model and answers each with a chapter of this guide. It explains no API a second time: each section names the chapter it applies.
| Page | Question | Applies |
|---|---|---|
| Takeover in a fixed population | How many cells are taken over, and when? | chapters 3, 4, 6 |
| Mutant classes | How often do mutant classes appear and vanish? Which mutations happened when? | chapter 6 |
| Variable population: ATP | What if an energy balance, not a fixed target, limits replication? | chapter 9 |
| Methods and speed | Which method, and how fast? | chapters 5, 7 |
| Large studies | How do parameters change takeover? How to run a study as files? | chapters 3, 5, 8, 10 |
| Fitting parameters to data | Which mutation probability and advantage explain measured cells? | chapter 5 |
| The mtDNA model files | How to follow every lineage, and run the fast path? | chapter 12 |
The model
Applies: chapter 2, Species, parameters and reactions.
One cell has a copy-number target K. Every molecule degrades at a
constant rate. Every molecule replicates into the free places below K:
the fewer free places, the slower. When a wild-type molecule replicates,
the copy is a mutant with a small probability mu. A share fracAdv of new
mutants is advantaged: it replicates with the weight sm instead of 1.
The model has three species: W (wild type), M (neutral mutants) and A
(advantaged mutants). The function three_class builds it with the builder
(chapter 2). Every page of the case study starts with
this block:
import math
import numpy as np
import crn_craft as crn
END = 25_920.0 # three years (1,080 days), in hours
def three_class(K=1000, w0=1000, m0=0, mu=3e-5, sm=1.5, half_life_days=10, takeover=None):
"""The three-class mtDNA model: wild type W, neutral M, advantaged A."""
model = crn.Model("mtdna_three_class")
model.add_parameter({"K": K, "delta": math.log(2) / (24 * half_life_days),
"sw": 1.0, "sm": sm, "mu": mu, "fracAdv": 0.2})
model.add_species({"W": w0, "M": m0, "A": 0})
free = "max(0, K - W - M - A) / (W + sm * (M + A))"
model.add_reaction(f"{free} * sw * (1 - mu) * W", ["W"], ["W", "W"], "replication_wt")
model.add_reaction(f"{free} * sw * mu * (1 - fracAdv) * W", ["W"], ["W", "M"], "mutation_mt")
model.add_reaction(f"{free} * sw * mu * fracAdv * W", ["W"], ["W", "A"], "mutation_mtAdv")
model.add_reaction(f"{free} * sw * M", ["M"], ["M", "M"], "replication_mt")
model.add_reaction(f"{free} * sm * A", ["A"], ["A", "A"], "replication_mtAdv")
for label, species in (("wt", "W"), ("mt", "M"), ("mtAdv", "A")):
model.add_reaction(f"delta * {species}", [species], [], f"degradation_{label}")
if takeover is not None:
model.set_stop(f"W + M + A > 0 && M + A >= {takeover} * (W + M + A)")
return model
A hundred cells for three years. The method is mtdna_direct, an exact
fast path for this model, where the chapters before name static_direct
(Conventions says why):
model = three_class()
print(model)
result = crn.ensemble(model, end=END, report_times=[0.0, END], replicates=100,
seed=1, threads=2, method="mtdna_direct").simulate()
final = result.statistics["mean"].loc[END]
print(result.metadata["sampler"], result.metadata["termination"])
print(f"mean mutant fraction after three years: {(final['M'] + final['A']) / final.sum():.4f}")
Model('mtdna_three_class': 3 species, 8 reactions)
chacha8-u53-ziggurat/rules-mtdna-direct/1 completed
mean mutant fraction after three years: 0.1111
Parameters and rates
Applies: chapter 2, Rates as numbers and as strings.
Argument of three_class | Parameter | Default | Meaning |
|---|---|---|---|
K | K | 1000 | copy-number target |
half_life_days | delta | ln 2 / 240 h⁻¹ | degradation rate per molecule (half-life 10 days) |
sw | 1.0 | replication weight of wild type and neutral mutants | |
sm | sm | 1.5 | replication weight of advantaged mutants |
mu | mu | 3·10⁻⁵ | mutation probability per wild-type replication |
fracAdv | 0.2 | share of new mutants that are advantaged | |
w0, m0 | 1000, 0 | initial wild-type and neutral-mutant molecules | |
takeover | none | the takeover threshold, a fraction of all molecules |
Every class degrades at rate delta. A molecule of weight s replicates
at rate max(0, K − N) / D · s, where N = W + M + A counts all molecules
and D = W + sm (M + A) is the competition denominator. A wild-type
replication yields an unchanged copy with probability 1 − mu, a neutral
mutant with probability mu (1 − fracAdv) and an advantaged mutant with
probability mu · fracAdv. The eight reactions write this out channel by
channel.
Totals are sums of columns. The builder gives one column per species
and no other observable. All molecules are W + M + A, all mutants
M + A. Write them out in stop conditions and first-passage predicates,
and add the columns in pandas for means. The variance or a quantile of a
total needs the kept paths (chapter 4).
Takeover is the stop condition that takeover=0.9 sets: a cell is
taken over when 90% of its molecules are mutants,
W + M + A > 0 && M + A >= 0.9 * (W + M + A). Other thresholds are other
values of takeover.
Conventions
Applies: chapter 7, Which method for which model.
- Time is in hours.
END, 25,920 hours, is 1,080 days, about three years. Report times are written as24.0 * days. - One replicate is one cell. A cell at
K = 1000has about 150,000 events in three years. - The case study runs the fast path,
method="mtdna_direct", an exact method for the three-class model. Since release 0.7.1 it certifies the builder model when the request iscrn-craft.run/1.0, whichcrn.ensemblewrites (page S1d). It runs with trackers, event logs, callbacks, kept paths, quantiles,bind_parametersand the takeover stop at any threshold. A page that runs another method says so and why: the ATP model is not the three-class structure, compiled loops run Static Direct, and page S1d compares the methods. On 13 November 2026, on a two-CPU host, the builder model under the fast path took the time of the model file under it (0.97 times). Under Static Direct it took 3.6 times as long as under the fast path (measurement). Given a variant outside that structure that Static Direct can run, such as another stop,mtdna_directruns Static Direct and reportsCRN-R051inmetadata["diagnostics"]. A model with a continuous variable is refused withCRN-R020.
The model as a file
Applies: chapter 12, Save and load a model file.
The repository also has this model as JSON files, in which every molecule carries attributes. Those files add a model that follows every mutant lineage and a stored form of the ATP model; page 12a, after the chapter on model files, shows them.
See also: Takeover in a fixed population, mtDNA performance analysis.
Continue with the three-mechanism comparison to fit the same affected-cell fraction under neutral drift, size advantage and transcription-linked replication.
Takeover in a fixed population
How many cells are taken over by mutants, and when? This page runs the three-class model of the index page with a fixed copy-number target. The setup block is that model. The blocks of this page continue from it:
import math
import numpy as np
import crn_craft as crn
END = 25_920.0 # three years (1,080 days), in hours
def three_class(K=1000, w0=1000, m0=0, mu=3e-5, sm=1.5, half_life_days=10, takeover=None):
"""The three-class mtDNA model: wild type W, neutral M, advantaged A."""
model = crn.Model("mtdna_three_class")
model.add_parameter({"K": K, "delta": math.log(2) / (24 * half_life_days),
"sw": 1.0, "sm": sm, "mu": mu, "fracAdv": 0.2})
model.add_species({"W": w0, "M": m0, "A": 0})
free = "max(0, K - W - M - A) / (W + sm * (M + A))"
model.add_reaction(f"{free} * sw * (1 - mu) * W", ["W"], ["W", "W"], "replication_wt")
model.add_reaction(f"{free} * sw * mu * (1 - fracAdv) * W", ["W"], ["W", "M"], "mutation_mt")
model.add_reaction(f"{free} * sw * mu * fracAdv * W", ["W"], ["W", "A"], "mutation_mtAdv")
model.add_reaction(f"{free} * sw * M", ["M"], ["M", "M"], "replication_mt")
model.add_reaction(f"{free} * sm * A", ["A"], ["A", "A"], "replication_mtAdv")
for label, species in (("wt", "W"), ("mt", "M"), ("mtAdv", "A")):
model.add_reaction(f"delta * {species}", [species], [], f"degradation_{label}")
if takeover is not None:
model.set_stop(f"W + M + A > 0 && M + A >= {takeover} * (W + M + A)")
return model
A first ensemble
Applies: chapter 3, Many trajectories in one call, and chapter 4, What a result holds.
Two hundred cells for three years, with the takeover stop at 90% mutants. Every cell is one replicate, so one call runs them all:
import time
model = three_class(takeover=0.9)
days = np.arange(0, 1081, 90)
run = crn.ensemble(model, end=END, report_times=24.0 * days, replicates=200,
seed=1, threads=2, method="mtdna_direct")
start = time.perf_counter()
result = run.simulate()
seconds = time.perf_counter() - start
meta = result.metadata
records = result.records # one row per cell
stopped = records["termination"] == "stopped"
print(meta["sampler"], meta["termination"])
print(f"{meta['events']:,} events in {seconds:.2f} s")
print(f"taken over: {stopped.sum()} of {len(records)} cells")
print(records[["termination", "stop_time", "events"]].head(3))
first = records.loc[stopped, "stop_time"].nsmallest(5)
print("takeover days (first five):", (first.to_numpy() / 24).round(1))
mean = result.statistics["mean"] # one row per report time
fraction = (mean["M"] + mean["A"]) / mean.sum(axis=1)
for hours, value in fraction.items():
print(f"day {hours / 24:5.0f}: mean mutant fraction {value:.4f}")
chacha8-u53-ziggurat/rules-mtdna-direct/1 completed
28,536,814 events in 0.50 s
taken over: 23 of 200 cells
termination stop_time events
replicate
0 completed 25920.0 148726
1 completed 25920.0 149476
2 completed 25920.0 150111
takeover days (first five): [272.7 300.8 304.3 358.8 426. ]
day 0: mean mutant fraction 0.0000
day 90: mean mutant fraction 0.0004
day 180: mean mutant fraction 0.0055
day 270: mean mutant fraction 0.0156
day 360: mean mutant fraction 0.0242
day 450: mean mutant fraction 0.0384
day 540: mean mutant fraction 0.0460
day 630: mean mutant fraction 0.0516
day 720: mean mutant fraction 0.0620
day 810: mean mutant fraction 0.0838
day 900: mean mutant fraction 0.1011
day 990: mean mutant fraction 0.1065
day 1080: mean mutant fraction 0.1097
A cell has about 150,000 events in three years. The cells that were taken
over stopped early and hold their state at every later report time. The
mean mutant fraction is the mean of M + A over the mean of all molecules
at each report time.
The mean hides the typical cell
Applies: chapter 4, Quantiles and the median, and Single trajectories.
Most cells stay near zero mutants, while a few are taken over. The mean then
sits far from the typical cell. The quantiles of one species come from
statistics. The quantiles of all mutants, M + A, are quantiles of a sum,
so they come from the kept paths:
days = np.arange(0, 1081, 360)
result = crn.ensemble(
three_class(), end=END, report_times=24.0 * days, replicates=200, seed=1,
threads=2, method="mtdna_direct",
quantiles=[0.025, 0.25, 0.5, 0.75, 0.975], keep_paths="all",
).simulate()
statistics = result.statistics
mean = statistics["mean"]
print("quantile levels:", list(statistics["quantiles"]))
print("mean mutants: ", (mean["M"] + mean["A"]).round(1).tolist())
print("median advantaged:", statistics["median"]["A"].tolist())
paths = result.paths # cells x report times x species
mutants = (paths.sel(variable="M") + paths.sel(variable="A")).to_numpy()
print("median mutants: ", np.median(mutants, axis=0).tolist())
print("97.5% of mutants: ", np.quantile(mutants, 0.975, axis=0).round(1).tolist())
last = paths.sel(time=END, variable="A").to_numpy()
print("equal to numpy:", np.quantile(last, 0.975) == statistics["quantiles"][0.975]["A"].iloc[-1])
quantile levels: [0.025, 0.25, 0.5, 0.75, 0.975]
mean mutants: [0.0, 25.2, 67.0, 120.7]
median advantaged: [0.0, 0.0, 0.0, 0.0]
median mutants: [0.0, 0.0, 0.0, 0.0]
97.5% of mutants: [0.0, 336.4, 995.0, 998.0]
equal to numpy: True
The median is zero at every report time, while the mean rises: the typical cell has no mutant, and the mean is carried by the cells that were taken over. The 97.5% quantile shows how far a cell can go. The quantiles that the run computes equal NumPy’s over the kept paths, so both routes give the same numbers.
Takeover fraction and time to threshold
Applies: chapter 6, Stop conditions.
Two outputs of a stop condition answer the question of this page: the share of cells whose stop time lies before an age, and the distribution of the stop times:
result = crn.ensemble(three_class(takeover=0.9), end=END, report_times=[0.0, END],
replicates=200, seed=1, threads=2, method="mtdna_direct").simulate()
stopped = result.records["termination"] == "stopped"
for age in (360, 720, 1080):
taken = (stopped & (result.records["stop_time"] <= 24.0 * age)).mean()
print(f"taken over by day {age:4d}: {taken:.3f}")
days = result.records.loc[stopped, "stop_time"] / 24
print(f"days to 90% mutants: first {days.min():.0f}, median {days.median():.0f}")
taken over by day 360: 0.020
taken over by day 720: 0.055
taken over by day 1080: 0.115
days to 90% mutants: first 273, median 726
These are the 200 cells of the first ensemble: the same seed gives the same
cells, whatever the report times. Another threshold is another value of
takeover, for example 0.6 for a 60% deficiency threshold. To record when a
threshold is passed without ending the cell, use a first-passage tracker
(page S1b).
Variants
Applies: chapter 2, The builder calls, and Checking a model.
A variant of the model is a call of three_class with other arguments:
copy number K, half-life, initial heteroplasmy (w0 wild-type and m0
neutral-mutant molecules) and the threshold. Here a smaller cell with a
longer half-life starts with 20% neutral mutants, and a cell counts as taken
over at 60%:
model = three_class(K=500, w0=400, m0=100, half_life_days=20, takeover=0.6)
result = crn.ensemble(model, end=END, report_times=[0.0, 8640.0, 17_280.0, END],
replicates=300, seed=9, threads=2, method="mtdna_direct").simulate()
stopped = result.records["termination"] == "stopped"
print(f"cells past 60% within three years: {stopped.mean():.2%}")
# A misspelled name is reported with a code and a path before anything runs.
broken = three_class()
broken.add_reaction("delta * WW", ["W"], [], "extra_loss")
try:
crn.ensemble(broken, end=1.0, report_times=[0.0, 1.0])
except crn.CrnError as error:
print("rejected:", error)
cells past 60% within three years: 4.33%
rejected: CRN-R012: unknown name `WW`; expected a parameter or observable in `delta * WW` at /rules/8/propensity
A builder model is checked when it is used, and a mistake raises
crn.CrnError with a code, a path and the offending expression. To change a
parameter of many runs without building the model again, bind it
(page S1e).
See also: Mutant classes, Large studies.
Mutant classes: trackers, event logs and callbacks
How often does a mutant class appear and vanish in a cell? When did the mutations happen? These questions are about events between report times. This page answers them with the tools of chapter 6. The setup block is the model of the index page. The blocks of this page continue from it:
import math
import numpy as np
import crn_craft as crn
END = 25_920.0 # three years (1,080 days), in hours
def three_class(K=1000, w0=1000, m0=0, mu=3e-5, sm=1.5, half_life_days=10, takeover=None):
"""The three-class mtDNA model: wild type W, neutral M, advantaged A."""
model = crn.Model("mtdna_three_class")
model.add_parameter({"K": K, "delta": math.log(2) / (24 * half_life_days),
"sw": 1.0, "sm": sm, "mu": mu, "fracAdv": 0.2})
model.add_species({"W": w0, "M": m0, "A": 0})
free = "max(0, K - W - M - A) / (W + sm * (M + A))"
model.add_reaction(f"{free} * sw * (1 - mu) * W", ["W"], ["W", "W"], "replication_wt")
model.add_reaction(f"{free} * sw * mu * (1 - fracAdv) * W", ["W"], ["W", "M"], "mutation_mt")
model.add_reaction(f"{free} * sw * mu * fracAdv * W", ["W"], ["W", "A"], "mutation_mtAdv")
model.add_reaction(f"{free} * sw * M", ["M"], ["M", "M"], "replication_mt")
model.add_reaction(f"{free} * sm * A", ["A"], ["A", "A"], "replication_mtAdv")
for label, species in (("wt", "W"), ("mt", "M"), ("mtAdv", "A")):
model.add_reaction(f"delta * {species}", [species], [], f"degradation_{label}")
if takeover is not None:
model.set_stop(f"W + M + A > 0 && M + A >= {takeover} * (W + M + A)")
return model
Class appearances and extinctions
Applies: chapter 6, Trackers.
One tracker follows the neutral class M, one the advantaged class A.
A third records the first time mutants reach 60% of the molecules, written
over the three species, without stopping the cell:
sixty = "W + M + A > 0 && M + A >= 0.6 * (W + M + A)"
result = crn.ensemble(
three_class(takeover=0.9), end=END, report_times=[0.0, END], replicates=500,
seed=3, threads=2, method="mtdna_direct",
trackers=[
{"observable": "M", "keep_episodes": 3},
{"observable": "A", "keep_episodes": 3},
{"observable": "W", "first_passage": sixty},
],
).simulate()
neutral, advantaged, passage = (result.tracker_columns(i) for i in range(3))
print(advantaged[["appearances", "extinctions", "maximum", "integral"]].head(3))
print("neutral classes arising per cell:", neutral["appearances"].mean())
print("neutral classes lost per cell: ", neutral["extinctions"].mean())
print("advantaged arising/lost: ",
advantaged["appearances"].mean(), advantaged["extinctions"].mean())
print("largest advantaged class seen: ", advantaged["maximum"].max())
# The integral runs until the cell's stop or the horizon.
load = advantaged["integral"] / result.records["stop_time"]
print("time-averaged advantaged count, mean over cells:", round(load.mean(), 3))
reached = passage["first_passage"].dropna() # NaN: never reached 60%
print(f"cells reaching 60% mutants: {len(reached)}; median day {reached.median() / 24:.0f}")
first = next(o for o in result.observations if o["trackers"][1]["episodes"])
for episode in first["trackers"][1]["episodes"]:
print("cell", first["id"], "advantaged episode:", episode)
appearances extinctions maximum integral
replicate
0 0 0 0.0 0.000000
1 1 1 1.0 64.109016
2 0 0 0.0 0.000000
neutral classes arising per cell: 1.566
neutral classes lost per cell: 1.472
advantaged arising/lost: 0.404 0.266
largest advantaged class seen: 900.0
time-averaged advantaged count, mean over cells: 17.69
cells reaching 60% mutants: 52; median day 494
cell 1 advantaged episode: {'duration': 64.10901603704042, 'end': 5246.85151399302, 'peak': 1.0, 'start': 5182.742497955979}
An appearance of a class is the birth of a mutant lineage while its class is absent. A new mutant that arises while its class is present merges into it, so a class count is not a lineage count. The integral divided by the observed time is the time-averaged count: here the average number of advantaged molecules per hour lived. The first passage at 60% is recorded for cells that went on to 90% as well as for cells that stayed below it.
Mutation events in a log
Applies: chapter 6, Event logs.
An event log keeps up to max_entries events of the listed reactions for
every cell, with the species counts after each event. The two mutation
reactions are the ones to keep:
result = crn.ensemble(
three_class(), end=END, report_times=[0.0, END], replicates=100, seed=4,
threads=2, method="mtdna_direct",
event_log={"max_entries": 50, "rules": ["mutation_mt", "mutation_mtAdv"]},
).simulate()
log = result.event_columns() # cells x entries x species, NaN-padded
names = log["rule_name"].to_series().dropna() # padding has no name
print("logged mutation events:", names.value_counts().sort_index().to_dict())
print("omitted (log full):", sum(o["omitted_log_entries"] for o in result.observations))
print(result.event_frame(0)[["time", "rule_name", "W", "M", "A"]])
days = result.event_columns(0)["time"] / 24 # cell 0, without padding
print("cell 0 mutation days:", days.round(1).values.tolist())
logged mutation events: {'mutation_mt': 158, 'mutation_mtAdv': 39}
omitted (log full): 0
time rule_name W M A
entry
0 1442.924093 mutation_mt 994.0 1.0 0.0
1 7746.367689 mutation_mt 996.0 1.0 0.0
2 17740.279613 mutation_mtAdv 997.0 0.0 1.0
3 21692.680185 mutation_mt 744.0 1.0 252.0
cell 0 mutation days: [60.1, 322.8, 739.2, 903.9]
No log was full: 50 entries per cell are more than three years of mutations
at mu = 3·10⁻⁵. Each entry holds the time, the reaction and the counts of
W, M and A after the event.
Stop at the first advantaged mutant
Applies: chapter 6, Callbacks.
A callback sees every event of a cell in order and may end the cell. This one counts events by reaction and stops a cell at its first advantaged mutation. A callback holds Python’s interpreter lock, so it suits a few cells:
from collections import Counter
run = crn.ensemble(three_class(), end=END, report_times=[0.0, END], replicates=20,
seed=4, threads=1, method="mtdna_direct")
seen = Counter()
def watch(replicate, event):
"""Count events by reaction; stop a cell at its first advantaged mutant."""
name = run.rule_names[event["rule"]]
seen[name] += 1
return name != "mutation_mtAdv"
result = run.simulate(callback=watch)
stopped = result.records["termination"] == "stopped"
print("events seen by the callback:", sum(seen.values()))
print("cells stopped at their first advantaged mutation:", stopped.sum())
days = result.records.loc[stopped, "stop_time"] / 24
print("their stop days:", days.round(1).to_numpy())
events seen by the callback: 2675817
cells stopped at their first advantaged mutation: 5
their stop days: [739.2 672.8 574.3 938.7 230.9]
Both this run and the log above use the fast path with seed 4, so their first 20 cells are the same cells. The advantaged mutation of cell 0 on day 739.2 in the log reappears here as the first stop day: an observer reads the events, it does not change them.
Single lineages
Applies: chapter 12, New identities and random attributes.
A class is not a lineage. Following every mutant lineage, with its birth, its death and its largest size, needs every new mutant to carry its own identity. That is a species with attributes, which the builder cannot write. Page 12a runs the clone model, in which every lineage has its own identity.
See also: Stop conditions, trackers and event logs, Methods and speed.
Variable population: ATP
In the model of the index page a fixed target K limits replication. In
this variant an energy balance limits it: a pool of ATP, which wild-type
molecules produce and every molecule consumes. The population is then free
to grow or shrink. The setup block is the model of the
index page; this page builds its variant from the
same parts. The blocks of this page continue from it:
import math
import numpy as np
import crn_craft as crn
END = 25_920.0 # three years (1,080 days), in hours
def three_class(K=1000, w0=1000, m0=0, mu=3e-5, sm=1.5, half_life_days=10, takeover=None):
"""The three-class mtDNA model: wild type W, neutral M, advantaged A."""
model = crn.Model("mtdna_three_class")
model.add_parameter({"K": K, "delta": math.log(2) / (24 * half_life_days),
"sw": 1.0, "sm": sm, "mu": mu, "fracAdv": 0.2})
model.add_species({"W": w0, "M": m0, "A": 0})
free = "max(0, K - W - M - A) / (W + sm * (M + A))"
model.add_reaction(f"{free} * sw * (1 - mu) * W", ["W"], ["W", "W"], "replication_wt")
model.add_reaction(f"{free} * sw * mu * (1 - fracAdv) * W", ["W"], ["W", "M"], "mutation_mt")
model.add_reaction(f"{free} * sw * mu * fracAdv * W", ["W"], ["W", "A"], "mutation_mtAdv")
model.add_reaction(f"{free} * sw * M", ["M"], ["M", "M"], "replication_mt")
model.add_reaction(f"{free} * sm * A", ["A"], ["A", "A"], "replication_mtAdv")
for label, species in (("wt", "W"), ("mt", "M"), ("mtAdv", "A")):
model.add_reaction(f"delta * {species}", [species], [], f"degradation_{label}")
if takeover is not None:
model.set_stop(f"W + M + A > 0 && M + A >= {takeover} * (W + M + A)")
return model
ATP as a continuous variable
Applies: chapter 9, A variable between events.
ATP is a continuous quantity. Between events it follows
dATP/dt = f · W − v1 · ATP − v2 · (W + M + A),
and every replication rate is multiplied by c / (c + ATP) instead of the
free places below K. add_ode declares the variable with a lower bound of
0, and the string rates read it. Only the method hybrid runs such a model.
The fast path of the other pages does not apply, because this model is not
the three-class structure:
def atp_cell(f=0.1, v1=0.2, v2=0.01, c=1.3034153747670567, atp0=450.0):
"""The three-class model with replication limited by an ATP balance."""
model = crn.Model("mtdna_three_class_atp")
model.add_parameter({"delta": math.log(2) / 240, "sw": 1.0, "sm": 1.5, "mu": 3e-5,
"fracAdv": 0.2, "f": f, "v1": v1, "v2": v2, "c": c})
model.add_species({"W": 1000, "M": 0, "A": 0})
model.add_ode("ATP", atp0, "f * W - v1 * ATP - v2 * (W + M + A)", lower_bound=0)
energy = "c / (c + ATP)"
model.add_reaction(f"{energy} * sw * (1 - mu) * W", ["W"], ["W", "W"], "replication_wt")
model.add_reaction(f"{energy} * sw * mu * (1 - fracAdv) * W", ["W"], ["W", "M"], "mutation_mt")
model.add_reaction(f"{energy} * sw * mu * fracAdv * W", ["W"], ["W", "A"], "mutation_mtAdv")
model.add_reaction(f"{energy} * sw * M", ["M"], ["M", "M"], "replication_mt")
model.add_reaction(f"{energy} * sm * A", ["A"], ["A", "A"], "replication_mtAdv")
for label, species in (("wt", "W"), ("mt", "M"), ("mtAdv", "A")):
model.add_reaction(f"delta * {species}", [species], [], f"degradation_{label}")
return model
result = crn.ensemble(atp_cell(), end=END, report_times=24.0 * np.arange(0, 1081, 180),
replicates=64, seed=7, threads=2, method="hybrid").simulate()
meta = result.metadata
print("columns:", list(result.statistics["mean"].columns))
print("sampler:", meta["sampler"], "method:", meta["method"])
print("stopped (ATP exhausted):", (result.records["termination"] == "stopped").sum())
for hours, row in result.statistics["mean"].iterrows():
print(f"day {hours / 24:4.0f}: molecules {row['W'] + row['M'] + row['A']:7.1f} "
f"mutants {row['M'] + row['A']:6.1f} ATP {row['ATP']:7.2f}")
columns: ['A', 'M', 'W', 'ATP']
sampler: chacha8-u53/rules-approximate-hybrid-dopri54/1 method: {'atol': 1e-09, 'kind': 'hybrid', 'rtol': 1e-06}
stopped (ATP exhausted): 10
day 0: molecules 1000.0 mutants 0.0 ATP 450.00
day 180: molecules 1006.8 mutants 4.5 ATP 450.32
day 360: molecules 1826.1 mutants 771.8 ATP 438.88
day 540: molecules 2963.6 mutants 1835.6 ATP 424.91
day 720: molecules 4570.4 mutants 3328.0 ATP 409.96
day 900: molecules 5191.7 mutants 3908.4 ATP 402.75
day 1080: molecules 7011.7 mutants 5611.1 ATP 379.08
ATP is a column after the species. The population is no longer held near
1,000: where mutants expand, it grows, because mutants consume ATP but do
not produce it, and the replication factor c / (c + ATP) rises as ATP falls.
metadata["method"] records the tolerances of hybrid, which is
approximate at them.
What ends a cell
Applies: chapter 9, Bounds.
lower_bound=0 with the default on_bound="stop" ends a cell when ATP
reaches 0 while its derivative there is not positive: the energy of the cell
is exhausted. The cell is then stopped, ATP reads 0 at every later report
time, and the species keep their counts. With on_bound="clamp" ATP would
instead stay at 0 until its derivative turns positive, and the cell would
live on. On the stored form of this model, hybrid took about eleven times
as long as exact thinning, because every event needs an integration step;
its error has not been measured as a function of the tolerances
(validation).
The stored form
Applies: chapter 7, Other methods.
The repository also has this model as a stored file with an older atp
block. Such files run exactly under the method thinning;
page 12a
shows it.
See also: Continuous variables, Methods and speed.
Methods and speed
Which method should run the mtDNA model, and how fast can it run? This page runs the same cells under every method that takes the builder model, runs the fast path, and then compiles the model. The setup block is the model of the index page. The blocks of this page continue from it:
import math
import numpy as np
import crn_craft as crn
END = 25_920.0 # three years (1,080 days), in hours
def three_class(K=1000, w0=1000, m0=0, mu=3e-5, sm=1.5, half_life_days=10, takeover=None):
"""The three-class mtDNA model: wild type W, neutral M, advantaged A."""
model = crn.Model("mtdna_three_class")
model.add_parameter({"K": K, "delta": math.log(2) / (24 * half_life_days),
"sw": 1.0, "sm": sm, "mu": mu, "fracAdv": 0.2})
model.add_species({"W": w0, "M": m0, "A": 0})
free = "max(0, K - W - M - A) / (W + sm * (M + A))"
model.add_reaction(f"{free} * sw * (1 - mu) * W", ["W"], ["W", "W"], "replication_wt")
model.add_reaction(f"{free} * sw * mu * (1 - fracAdv) * W", ["W"], ["W", "M"], "mutation_mt")
model.add_reaction(f"{free} * sw * mu * fracAdv * W", ["W"], ["W", "A"], "mutation_mtAdv")
model.add_reaction(f"{free} * sw * M", ["M"], ["M", "M"], "replication_mt")
model.add_reaction(f"{free} * sm * A", ["A"], ["A", "A"], "replication_mtAdv")
for label, species in (("wt", "W"), ("mt", "M"), ("mtAdv", "A")):
model.add_reaction(f"delta * {species}", [species], [], f"degradation_{label}")
if takeover is not None:
model.set_stop(f"W + M + A > 0 && M + A >= {takeover} * (W + M + A)")
return model
The same cells under every method
Applies: chapter 7, Which method for which model.
Sixty-four cells with the takeover stop, under eight methods. The tree
method runs when method is None:
import time
model = three_class(takeover=0.9)
methods = {
"tree": None,
"static_direct": "static_direct",
"static_direct, inverse": {"kind": "static_direct", "waiting_time": "inverse",
"sparse_trackers": False},
"mtdna_direct": "mtdna_direct",
"next_reaction": "next_reaction",
"tau (epsilon 0.03)": {"kind": "tau", "epsilon": 0.03},
"binomial (1 h steps)": {"kind": "binomial", "step": 1.0},
"hybrid": "hybrid",
}
for label, method in methods.items():
run = crn.ensemble(model, end=END, report_times=[0.0, 12_960.0, END], replicates=64,
seed=5, threads=2, method=method)
start = time.perf_counter()
result = run.simulate()
seconds = time.perf_counter() - start
stopped = (result.records["termination"] == "stopped").sum()
final = result.statistics["mean"].iloc[-1] # the means at the last report time
fraction = (final["M"] + final["A"]) / final.sum()
print(f"{label:22s} {seconds:6.2f} s {result.metadata['events']:>10,} events "
f"taken over {stopped:2d} mutant fraction {fraction:.3f} "
f"{result.metadata['sampler']}")
tree 3.04 s 9,234,548 events taken over 7 mutant fraction 0.130 chacha8-u53/rules-direct/2
static_direct 0.55 s 9,231,158 events taken over 7 mutant fraction 0.113 chacha8-u53-ziggurat/rules-static-direct/1
static_direct, inverse 0.62 s 9,120,187 events taken over 6 mutant fraction 0.092 chacha8-u53/rules-static-direct/1
mtdna_direct 0.16 s 8,969,870 events taken over 8 mutant fraction 0.122 chacha8-u53-ziggurat/rules-mtdna-direct/1
next_reaction 0.83 s 9,329,541 events taken over 4 mutant fraction 0.059 chacha8-u53/rules-next-reaction/1
tau (epsilon 0.03) 3.95 s 9,080,008 events taken over 8 mutant fraction 0.155 chacha8-u53/rules-approximate-cgp-poisson/2
binomial (1 h steps) 0.61 s 9,158,734 events taken over 6 mutant fraction 0.088 chacha8-u53/rules-approximate-binomial-split/2
hybrid 2.58 s 9,123,754 events taken over 6 mutant fraction 0.092 chacha8-u53/rules-approximate-hybrid-dopri54/1
The takeover counts differ because each method uses the random numbers in
its own way (chapter 7).
With 64 cells, 4 to 8 takeovers are within sampling error of each other. The approximate methods, tau and binomial, are labeled as
approximate in their sampler names. hybrid integrates between events even
without a continuous variable, so it costs more per event. At K = 1000 the
free places below K are few, so tau finds no safe leap and runs exact
events, at a higher cost per event; leaping pays off when every rate changes
slowly. mtdna_direct, the fast path, is the fastest exact method for this
model, and the other pages of the case study run it; Static Direct is the
method for every other variant (the next section).
The fast path
Applies: chapter 7, Which method for which model, and page 12a, The fast path.
mtdna_direct is an exact method fused for this one structure: three
classes in a fixed population, eight reactions, one degradation rate, the
vacancy law of the index page, and no
stop or the takeover stop. At preparation it certifies that the model has
this form. Since release 0.7.1 it reads the propensities that the builder
writes, when the request is crn-craft.run/1.0; crn.ensemble writes
that version, and its result says crn-craft.result/1.0. The builder
model then makes the same draws as the model file
(page 12a). The same 200 cells
under Static Direct and the fast path:
import time
model = three_class(takeover=0.9)
for method in ("static_direct", "mtdna_direct"):
run = crn.ensemble(model, end=END, report_times=[0.0, 12_960.0, END], replicates=200,
seed=5, threads=2, method=method)
start = time.perf_counter()
result = run.simulate()
seconds = time.perf_counter() - start
stopped = (result.records["termination"] == "stopped").sum()
print(f"{method:14s} {seconds:5.2f} s {result.metadata['events']:>11,} events "
f"taken over {stopped:2d} {result.metadata['sampler']}")
print(result.metadata["schema"], "warnings:", result.metadata["diagnostics"])
static_direct 1.80 s 28,452,894 events taken over 26 chacha8-u53-ziggurat/rules-static-direct/1
mtdna_direct 0.51 s 28,979,424 events taken over 13 chacha8-u53-ziggurat/rules-mtdna-direct/1
crn-craft.result/1.0 warnings: []
The sampler name confirms that the fast path ran; a model that it cannot
certify runs Static Direct with a CRN-R051 warning in
metadata["diagnostics"] (page 12a).
The two methods sample the same process from other random numbers, so they
agree in distribution, not cell by cell. The two takeover counts, 26 and 13,
are within sampling error of each other: at a takeover probability of 10.8%
(4,000 cells in tutorial O1),
200 cells give 21.6 takeovers on average, with a standard deviation of 4.4.
In the measurement of 13 November
2026 on a two-CPU host, the builder model took 3.6 times as long under
Static Direct as under the fast path, and the fast path took the time of
the model file under it (0.97 times)
(measurement).
The fast path also serves sweeps and fits, where every candidate has new
parameters (tutorial O1). Variants outside the structure,
such as the ATP model of page S1c or a stop at another
expression, run Static Direct.
Matching an hourly scheme
Applies: chapter 7, Approximate leaping, and chapter 8, Reproducing a published simulation.
Many published mtDNA simulations advance the cell in fixed steps of one
hour. To compare with such a result, run the model exactly first, on the
fast path, and compare the distributions, not single cells. The method
{"kind": "binomial", "step": 1.0} then imitates the hourly scheme: in
each step it removes degraded molecules, freezes the replication rates, and
splits every parent’s outcomes by their competing-risk probabilities. Its
steps lie on a fixed lattice, so the report times do not change a path.
Frozen rates can put the population a few molecules above K. A difference
between the binomial and the exact results above is the error of the step,
and a difference between the binomial result and the published one is a
difference of the schemes, such as how simultaneous new mutants are
grouped.
A compiled model
Applies: chapter 5, Compiled models.
crn.compile_loop(model) compiles the event loop of the builder model. The
results stay byte-identical, and the run takes a fraction of the time.
Compiled loops run Static Direct, so this block does not use the fast path.
The
first build takes about a minute and needs a Rust toolchain; later calls
read the cache:
import time
model = three_class(takeover=0.9)
loop = crn.compile_loop(model) # about a minute the first time, then cached
run = crn.ensemble(model, end=END, report_times=[0.0, 12_960.0, END], replicates=200,
seed=5, threads=2, method="static_direct",
trackers=[{"observable": "M"}, {"observable": "A"}])
for label, compiled in (("interpreted", None), ("compiled", loop)):
start = time.perf_counter()
result = run.simulate(compiled=compiled)
seconds = time.perf_counter() - start
stopped = (result.records["termination"] == "stopped").sum()
print(f"{label:12s} {seconds:5.2f} s {result.metadata['events']:>11,} events "
f"taken over {stopped:2d} {result.metadata['sampler']}")
loop.verify(run) # runs the request both ways; raises unless byte-identical
print("byte-identical")
interpreted 1.71 s 28,452,894 events taken over 26 chacha8-u53-ziggurat/rules-static-direct-sparse-trackers/1
compiled 0.75 s 28,452,894 events taken over 26 chacha8-u53-ziggurat/rules-static-direct-sparse-trackers/1
byte-identical
For this model the compiled loop pays off more than for most: the builder writes every rate as an expression, which the interpreter runs as a small program after every event that changes its species, and the compiled loop computes it natively. In the measurement of 13 November 2026 on a two-CPU host, the compiled builder model ran 2.6 times as fast as the interpreted one, and took 1.4 times as long as the model file under the fast path (measurement). A loop is compiled for one parameter set, so it does not speed up a sweep or a fit (chapter 5, Limits); the fast path does.
See also: Choosing a method, The fast path, mtDNA performance analysis.
Large studies: sweeps, budgets and the command line
A study runs the model many times: for many parameter values, for long cells, or as a batch of files on a cluster. The setup block is the model of the index page. The blocks of this page continue from it:
import math
import numpy as np
import crn_craft as crn
END = 25_920.0 # three years (1,080 days), in hours
def three_class(K=1000, w0=1000, m0=0, mu=3e-5, sm=1.5, half_life_days=10, takeover=None):
"""The three-class mtDNA model: wild type W, neutral M, advantaged A."""
model = crn.Model("mtdna_three_class")
model.add_parameter({"K": K, "delta": math.log(2) / (24 * half_life_days),
"sw": 1.0, "sm": sm, "mu": mu, "fracAdv": 0.2})
model.add_species({"W": w0, "M": m0, "A": 0})
free = "max(0, K - W - M - A) / (W + sm * (M + A))"
model.add_reaction(f"{free} * sw * (1 - mu) * W", ["W"], ["W", "W"], "replication_wt")
model.add_reaction(f"{free} * sw * mu * (1 - fracAdv) * W", ["W"], ["W", "M"], "mutation_mt")
model.add_reaction(f"{free} * sw * mu * fracAdv * W", ["W"], ["W", "A"], "mutation_mtAdv")
model.add_reaction(f"{free} * sw * M", ["M"], ["M", "M"], "replication_mt")
model.add_reaction(f"{free} * sm * A", ["A"], ["A", "A"], "replication_mtAdv")
for label, species in (("wt", "W"), ("mt", "M"), ("mtAdv", "A")):
model.add_reaction(f"delta * {species}", [species], [], f"degradation_{label}")
if takeover is not None:
model.set_stop(f"W + M + A > 0 && M + A >= {takeover} * (W + M + A)")
return model
Parameter sweeps
Applies: chapter 5, Parameter sweeps.
How does the takeover fraction depend on the mutation probability mu and
the advantage sm? One prepared run serves as the template, and
bind_parameters gives each candidate its values:
import time
template = crn.ensemble(three_class(takeover=0.9), end=END, report_times=[0.0, END],
replicates=200, seed=8, threads=2, method="mtdna_direct")
start = time.perf_counter()
print("takeover fraction after three years")
print(" mu \\ sm " + "".join(f"{sm:8.2f}" for sm in (1.0, 1.25, 1.5, 2.0)))
for mu in (1e-5, 3e-5, 1e-4):
row = []
for sm in (1.0, 1.25, 1.5, 2.0):
result = template.bind_parameters({"mu": mu, "sm": sm}).simulate()
row.append((result.records["termination"] == "stopped").mean())
print(f"{mu:9.0e} " + "".join(f"{v:8.3f}" for v in row))
print(f"12 candidates in {time.perf_counter() - start:.1f} s")
takeover fraction after three years
mu \ sm 1.00 1.25 1.50 2.00
1e-05 0.000 0.025 0.040 0.075
3e-05 0.000 0.040 0.110 0.190
1e-04 0.000 0.155 0.325 0.510
12 candidates in 6.1 s
With equal weights (sm = 1), drift alone is too slow for a takeover
within three years at K = 1000. The takeover fraction grows roughly in
proportion to mu and steeply with sm. The same seed gives every
candidate the same random streams
(common random numbers), so the
differences between the cells of the table come from the parameters, not
from different seeds. With 200 cells, a fraction has a standard error of up
to 0.035; use more cells for a table to publish. Every candidate runs on
the fast path. Under Static Direct the sweep takes about 3.6 times as long
(page S1d). A compiled loop does not
help here: it serves one parameter set. Tutorial O1 turns
the sweep into a fit.
Budgets for long cells
Applies: chapter 3, Budgets.
The default event budget is 100,000,000 events per cell, and the budget of
random numbers follows it. A cell at K = 1000 has about 150,000 events in
three years, and two to three times more with a doubled K or horizon, so
the defaults cover long horizons. A study that sets max_events lower, to
stop runaway candidates early, should check that ordinary cells stay below
it: an ensemble in which a cell ended on a budget withholds its statistics,
and simulate() warns with IncompleteEnsembleWarning (an error with
strict=True). The
performance analysis
sizes studies by events, cells and threads.
From the command line
Applies: chapter 10, A request file, and Run, archive and verify.
On a cluster, a study is often a set of files: a model file, a request per
job and an archive per result. This block writes the model with to_json()
and a request that binds it by path and SHA-256:
import hashlib
import json
import pathlib
data = three_class(takeover=0.9).to_json().encode()
pathlib.Path("takeover.model.json").write_bytes(data)
request = {
"schema": "crn-craft.run/1.0",
"model": {"path": "takeover.model.json", "sha256": hashlib.sha256(data).hexdigest()},
"method": {"kind": "mtdna_direct"},
"time": {"end": END, "report_times": [0.0, 8640.0, 17_280.0, END]},
"ensemble": {"replicates": 200, "root_seed": 11},
"outputs": {"statistics": ["mean", "variance"], "quantiles": [0.5],
"keep_paths": 0, "keep_instances": 0},
"budget": {"threads": 2, "max_events_per_replicate": 10_000_000,
"max_sampling_steps_per_replicate": 100_000_000,
"max_instances": 10, "max_output_bytes": 64 << 20},
"trackers": [{"observable": "A"}],
}
pathlib.Path("takeover.run.json").write_text(json.dumps(request, indent=2) + "\n")
print("model sha256:", request["model"]["sha256"])
model sha256: 6bfa75e9f57beb6c5489e2d81c889c1100e9b10091d246a9ba1da037ee3376cc
The crn-craft command of the Python package, or the native tool, checks
the two files, runs them into a sealed archive, and verifies the archive:
crn-craft check takeover.model.json takeover.run.json > check.json
crn-craft run takeover.model.json takeover.run.json --archive takeover-archive > run.json
crn-craft verify takeover-archive > verify.json
Each command writes a JSON document. With --archive, run writes the
result into the archive and prints a short check of it:
def read(name):
return json.loads(pathlib.Path(name).read_text())
check, archived, verify = read("check.json"), read("run.json"), read("verify.json")
result = read("takeover-archive/result.json")
print("check:", check["valid"], " archive:", archived["archive_complete"],
" verify:", verify["valid"])
print(result["termination"], result["sampler"])
print("cells:", result["completed_replicates"], "stopped:", result["stopped_replicates"])
print("events:", result["events"])
check: True archive: True verify: True
completed chacha8-u53-ziggurat/rules-mtdna-direct/1
cells: 200 stopped: 20
events: 28757292
A result names its model and request by hash, and the archive holds the exact bytes of both, so a job can be checked and replayed later on any host (chapter 10, Replay).
Checks behind these results
Applies: chapter 8, What a run does not show.
- Every exact method, the fast path included, agrees with an exact solution
of the master equation for the model at
K = 20(validation/check_mtdna.py). - The selectors and the quantiles are checked against exact laws and NumPy
(
validation/merge/RESULTS.md). - Trackers equal their recomputation from complete event logs, and results with and without observers are byte-identical.
- On 10,000 cells, the fast path agreed with an independent Java
implementation of the model
(
validation/mtdna/java-gap.json).
A numerical check confirms that the simulator solves the model. It does not validate the model against biology.
See also: Fitting parameters to data, Re-creating a published study, The command line, request files and archives.
S2. Case study: re-creating a published study (Kowald & Kirkwood 2013)
Author: Axel Kowald
This tutorial re-creates all four panels of Figure 1 of a published stochastic simulation study with the Python interface of CRN-craft (0.8):
Kowald A., Kirkwood T.B.L. (2013). Mitochondrial mutations and aging: random drift is insufficient to explain the accumulation of mitochondrial deletion mutants in short-lived animals. Aging Cell 12(4):728–731. doi:10.1111/acel.12098 (open access)
The tutorial was written for CRN-craft 0.7.1. The maintainers adapted the text and the code to CRN-craft 0.8 (this version is a draft for the author’s review); the last page lists what that changed.
The tutorial is a worked example of how to take a model from a paper’s Methods section and turn it into CRN-craft simulations, and how to check the result against the published numbers. It covers several features:
| Panel | Question | CRN-craft features | Page |
|---|---|---|---|
| 1A | Fraction of COX-negative cells over 120 years | crn.Model builder, static_direct, compile_loop, batched ensembles | Fig 1A |
| 1B | Mutation rate needed for 5/10/15 % COX-negative cells | parameter sweep with independent seeds, logistic regression | Fig 1B |
| 1C/1D | Number of mtDNA types and size of the largest clone | species with attributes (add_species(attributes=)), crn.copy, crn.new with new_id(), reduce="distinct" and reduce="max_count" observables, tree method | Fig 1C/1D |
The last page explains the limits (event, sampling, instance, memory and output budgets) that a long run like this one meets, which of them still need attention in 0.8, and the lessons of the study.
The biological model
The paper asks whether pure random drift of mtDNA deletion mutants, with no selective advantage, can explain why COX-negative cells (cells without functional respiratory chains) accumulate during aging. Its model of a post-mitotic cell is:
- A cell holds N = 1000 mtDNA molecules.
- Every molecule is degraded with a half-life of 10 days. Degradation is first order with δ = ln 2 / 240 h⁻¹.
- After each degradation a randomly chosen survivor replicates, so N stays constant (a Moran process).
- Every replication, of a wild-type or of a mutant template, produces a new deletion mutant with probability P_mut. The copy of a mutant is always a mutant.
- A cell is COX-negative when more than 60 % of its mtDNA is mutant.
The paper advances time in hourly steps. We simulate the same process exactly in continuous time (Gillespie), with time measured in hours and a 360-day year. Every page of the case study starts with these constants:
import math
import os
import numpy as np
import crn_craft as crn
nMolecules = 1000
halfLifeDays = 10.0
degRate = math.log(2)/(24.0*halfLifeDays) # 1/h
coxThreshold = 0.6
hoursPerYear = 24.0 * 360.0
nThreads = max(1, (os.cpu_count() or 1) - 2)
A result does not depend on the number of threads
(chapter 3), so nThreads only sets the
speed.
The script
The complete script is
examples/kk13/kowald_kirkwood_2013.py.
Each figure has its own function: KowaldKirkwood13Fig1A(),
KowaldKirkwood13Fig1B() and KowaldKirkwood13Fig1CD(). The model
functions of the pages, buildModel(pmut) and buildCloneModel(pmut), are
those of the script. Run it from the repository root:
python examples/kk13/kowald_kirkwood_2013.py --size quick # all parts, small cell counts
python examples/kk13/kowald_kirkwood_2013.py --size draft # the 0.8 tables of these pages
python examples/kk13/kowald_kirkwood_2013.py --size full # the author's cell counts
python examples/kk13/kowald_kirkwood_2013.py --size full --part 1A # one part: 1A, 1B or 1CD
python examples/kk13/kowald_kirkwood_2013.py --size draft --figures # plots from the stored results
| Size | Fig 1A cells | Fig 1B fine sweep | Fig 1C/1D cells per combination |
|---|---|---|---|
quick | 200 per P_mut, 10 years | 200 per point, lifespans 3 and 10 y | 100, 3 years only |
draft | 3,000 / 3,000 / 15,000 | 1,000 per point | 200 |
full | 3,000 / 3,000 / 15,000 | 3,000 per point | 3,000 |
The result files of a run go to examples/kk13/results/<size>/, one file
per P_mut, lifespan or combination, together with a JSON file that records
the cell counts, seeds, events, run time and CRN-craft version. A unit that
already has its file is skipped, so a long run can be stopped and
continued. --figures writes the figures to docs/guide/img/kk13/, and
examples/kk13/make_tables.py fills the 0.8 tables of these pages from
the result files.
Each result page shows two runs: the author’s run with CRN-craft 0.7.1 and
the full cell counts, and a draft run with CRN-craft 0.8 and the draft
sizes (about 25 minutes on two cores). The draft run has larger
statistical errors for Fig 1C/1D; its purpose is to show that 0.8 gives the
same results.
The code blocks of the pages are reduced versions of the script’s code: a few hundred cells and short horizons, so that each runs in seconds. Each page says which script call gives the full result.
See also: Fig 1A, Case study: mtDNA mutants (a different mtDNA model, with mutant classes and a replication advantage), Reproducing a published simulation.
Tutorial S3 reuses the drift baseline to compare fixed replication delays and transcription-linked replication. Tutorial O2 fits a Moran model of the same fixed copy number to cell snapshots.
Fig 1A: COX-negative cells over time
Author: Axel Kowald
Part of tutorial S2. Every section of this page starts from these definitions:
import math
import os
import numpy as np
import crn_craft as crn
nMolecules = 1000
halfLifeDays = 10.0
degRate = math.log(2)/(24.0*halfLifeDays) # 1/h
coxThreshold = 0.6
hoursPerYear = 24.0 * 360.0
nThreads = max(1, (os.cpu_count() or 1) - 2)
def buildModel(pmut) -> crn.Model:
model = crn.Model("mtdna_random_drift")
model.add_reaction("delta*wt * ((wt-1) * pmut + mt) / (wt+mt-1)", ["wt"], ["mt"], "wt_to_mt")
model.add_reaction("delta*mt * wt * (1 - pmut) / (wt+mt-1)", ["mt"], ["wt"], "mt_to_wt")
model.add_species({"wt": nMolecules, "mt": 0})
model.add_parameter({"delta": degRate, "pmut": pmut})
checkReport = crn.check(model) # validate before simulating
assert checkReport["valid"], checkReport["diagnostics"]
return model
Lumping the model into two reactions
Fig 1A needs only the number of wild-type (wt) and mutant (mt)
molecules. A degradation followed by a replacement is one event, and only
two kinds of event change the state:
| Event | What happens | Propensity |
|---|---|---|
| wt → mt | a wt is degraded and replaced by a mutant copy, made either by another wt that mutates or by any mt | δ·wt·((wt−1)·P_mut + mt)/(N−1) |
| mt → wt | an mt is degraded and replaced by an unmutated wt copy | δ·mt·wt·(1−P_mut)/(N−1) |
The other replacements (wt by wt, mt by mt) leave the counts unchanged and
need not be simulated. This makes the network exact and very small.
CRN-craft accepts the full propensity as an expression string, so
non-mass-action kinetics like these can be written directly: that is
buildModel above.
Validation tip. Before trusting a lumped model, compare it with an explicit “degrade, then replicate” model over a short horizon. At 3 years the two gave 10.85 % and 11.25 % COX-negative cells in the author’s run, which agree within sampling error.
Fast ensembles: static_direct and batches
A 120-year cell has millions of events and the rare-mutation scenario needs
15,000 cells. Gillespie’s direct method for a fixed set of species,
method="static_direct", makes this cheap. The script runs the cells in
batches of 1,000, one seed per batch, and counts the COX-negative cells at
every monthly report time. Here is one batch of 200 cells at
P_mut = 10⁻⁴, which runs in a few seconds:
endTime = 120 * hoursPerYear
reportTimes = np.linspace(0.0, endTime, 120 * 12 + 1) # monthly, 1441 points
run = crn.ensemble(buildModel(1e-4),
end = endTime,
report_times = reportTimes.tolist(),
replicates = 200,
seed = 1000, # one seed per batch -> reproducible
threads = nThreads,
method = "static_direct",
keep_paths = "all", # keep every cell's trajectory
strict = True) # an incomplete cell is an error
result = run.simulate()
mt = result.paths.sel(variable="mt").to_numpy() # (cells x times)
nNegative = (mt > coxThreshold * nMolecules).sum(axis=0)
print(f"COX-negative at 120 years: {100 * nNegative[-1] / 200:.1f} %")
COX-negative at 120 years: 24.0 %
Two habits are worth copying:
- Batching.
keep_paths="all"stores cells × report times values. Running batches of 1,000 cells bounds the memory used. - Checking that every cell completed. A cell that stops early because
it hit a budget would silently bias the statistics. With
strict=Truean incomplete ensemble raisescrn.IncompleteEnsembleError; without it,simulate()warns (crn.IncompleteEnsembleWarning) and names the limit to raise. Since 0.8 the default limits are large enough for these runs, so no limit needs raising (see limits).
Result
The author’s run with CRN-craft 0.7.1:
| P_mut | Cells | COX-negative at 120 y (author’s run) | Paper |
|---|---|---|---|
| 10⁻⁴ | 3,000 | 22.6 % | 22.3 % |
| 10⁻⁵ | 3,000 | 2.4 % | 2.7 % |
| 10⁻⁶ | 15,000 | 0.20 % | ≈ 0.25 % |
The draft run with CRN-craft 0.8 (--size draft, the same cell counts;
the ± is one binomial standard error):
| P_mut | Cells | COX-negative at 120 y (this run) | Author’s run (0.7.1) | Paper |
|---|---|---|---|---|
| 10^-4 | 3,000 | 23.63 % ± 0.78 | 22.6 % | 22.3 % |
| 10^-5 | 3,000 | 2.20 % ± 0.27 | 2.4 % | 2.7 % |
| 10^-6 | 15,000 | 0.24 % ± 0.04 | 0.20 % | ≈ 0.25 % |

Compiling the event loop
crn.compile_loop(model) compiles the event loop of this model into
native code, which needs a Rust toolchain
(chapter 5). A compiled loop is specific to one parameter
set; it is built once per P_mut and cached. The script uses it for the
120-year batches of Fig 1A:
model = buildModel(1e-4)
modelComp = crn.compile_loop(model) # about a minute the first time
run = crn.ensemble(model, end=120 * hoursPerYear, report_times=[0.0, 120 * hoursPerYear],
replicates=200, seed=2000, threads=nThreads,
method="static_direct", keep_paths="all", strict=True)
result = run.simulate(compiled=modelComp)
mt = result.paths.sel(variable="mt").isel(time=-1).to_numpy()
print("COX-negative cells:", int((mt > coxThreshold * nMolecules).sum()), "of 200")
COX-negative cells: 50 of 200
The full Fig 1A: python examples/kk13/kowald_kirkwood_2013.py --size full --part 1A.
Next: Fig 1B.
Fig 1B: which mutation rate gives 5, 10 or 15 % COX-negative cells?
Author: Axel Kowald
Part of tutorial S2. Every section of this page starts from the definitions of Fig 1A and the regression functions of the script:
import math
import os
import numpy as np
import crn_craft as crn
nMolecules = 1000
degRate = math.log(2)/(24.0*10.0) # 1/h
coxThreshold = 0.6
hoursPerYear = 24.0 * 360.0
nThreads = max(1, (os.cpu_count() or 1) - 2)
def buildModel(pmut) -> crn.Model:
model = crn.Model("mtdna_random_drift")
model.add_reaction("delta*wt * ((wt-1) * pmut + mt) / (wt+mt-1)", ["wt"], ["mt"], "wt_to_mt")
model.add_reaction("delta*mt * wt * (1 - pmut) / (wt+mt-1)", ["mt"], ["wt"], "mt_to_wt")
model.add_species({"wt": nMolecules, "mt": 0})
model.add_parameter({"delta": degRate, "pmut": pmut})
return model
def fitLogistic(x, k, n):
"""Binomial GLM logit(f) = b0 + b1*x by iteratively reweighted least squares."""
X = np.column_stack([np.ones_like(x), x])
b = np.zeros(2)
for _ in range(100):
p = 1.0 / (1.0 + np.exp(-(X @ b)))
w = n * p * (1.0 - p)
z = X @ b + (k - n * p) / np.maximum(w, 1e-300)
bNew = np.linalg.solve(X.T @ (w[:, None] * X), X.T @ (w * z))
converged = np.max(np.abs(bNew - b)) < 1e-12
b = bNew
if converged:
break
p = 1.0 / (1.0 + np.exp(-(X @ b)))
cov = np.linalg.inv(X.T @ ((n * p * (1.0 - p))[:, None] * X))
chi2 = float(np.sum((k - n * p) ** 2 / (n * p * (1.0 - p))))
return b, cov, chi2
def invertLogistic(b, cov, target):
"""log10 P_mut for a target fraction, with a 95 % CI by the delta method."""
logit = math.log(target / (1.0 - target))
x = (logit - b[0]) / b[1]
grad = np.array([-1.0 / b[1], -x / b[1]])
se = math.sqrt(float(grad @ cov @ grad))
return x, x - 1.96 * se, x + 1.96 * se
A sweep and a logistic regression
Fig 1B inverts the question: for lifespans of 3, 10, 40, 80 and 120 years, which P_mut produces 5, 10 or 15 % COX-negative cells at the end of life? The output is a binary outcome per cell (COX-negative or not), so optimizing a trajectory loss as in the fitting chapter is not needed. A sweep plus logistic regression is statistically more natural and very robust:
- Pilot sweep. A coarse grid of 17 points (log₁₀ P_mut from −6 to −2, 500 cells each) brackets the region where the COX-negative fraction passes 5 % and 15 %.
- Fine sweep. 13 log-spaced points cover that region plus a margin of 0.2 decades, with 3,000 cells each (1,000 in the draft run).
- Binomial GLM. Fit logit f = b0 + b1·log10(P_mut) by iteratively
reweighted least squares (
fitLogistic). Invert it for each target p: log10 P_mut = (logit p − b0)/b1. Get a 95 % CI by the delta method (invertLogistic), and check the fit with the Pearson χ².
Independent seeds per grid point
The regression assumes independent binomial counts at the grid points.
PreparedEnsemble.bind_parameters(...) can re-use one prepared ensemble
with new parameters, but it keeps the seed. That gives common random
numbers and correlated counts across the grid. Each grid point therefore
gets its own ensemble and seed. Only the start and end states are
reported. A small version for a 3-year lifespan, 7 grid points of 300
cells:
endT = 3 * hoursPerYear
log10Grid = np.linspace(-2.35, -1.95, 7)
counts = np.zeros(len(log10Grid))
for i, x in enumerate(log10Grid):
run = crn.ensemble(buildModel(10.0**x), end=endT, report_times=[0.0, endT], replicates=300,
seed=500 + i, threads=nThreads, method="static_direct",
keep_paths="all", strict=True)
result = run.simulate() # no compile_loop: every grid point has a new parameter
mtEnd = result.paths.sel(variable="mt").isel(time=-1).to_numpy()
counts[i] = int((mtEnd > coxThreshold * nMolecules).sum())
b, cov, chi2 = fitLogistic(log10Grid, counts, np.full(len(log10Grid), 300.0))
x, lo, hi = invertLogistic(b, cov, 0.10)
print(f"10 % COX-negative at 3 years: P_mut = {10**x:.2e} (95 % CI {10**lo:.2e} to {10**hi:.2e})")
print(f"Pearson chi2 = {chi2:.1f} on {len(log10Grid) - 2} degrees of freedom")
10 % COX-negative at 3 years: P_mut = 7.76e-03 (95 % CI 7.48e-03 to 8.05e-03)
Pearson chi2 = 2.1 on 5 degrees of freedom
Here compiling the loop does not pay off, because each compiled loop would be used for only one grid point.
Exact alternative? CRN-craft also has a finite-state-projection solver (
Model.fsp), which would give f(P_mut) without sampling noise. For N = 1000 over years it stopped withCRN-E070(work limit exceeded) even at 3 years in the author’s run, so sampling was the practical route.
Result
The author’s run with CRN-craft 0.7.1, against Table 1 of the paper:
| Lifespan | 5 % (author / paper) | 10 % | 15 % |
|---|---|---|---|
| 3 y | 6.41e-3 / 6.5e-3 | 7.53e-3 / 7.6e-3 | 8.32e-3 / 8.5e-3 |
| 10 y | 9.69e-4 / 9.5e-4 | 1.39e-3 / 1.45e-3 | 1.74e-3 / 1.8e-3 |
| 40 y | 8.77e-5 / 9e-5 | 1.69e-4 / 1.7e-4 | 2.53e-4 / 2.7e-4 |
| 80 y | 3.38e-5 / 3e-5 | 6.55e-5 / 7e-5 | 9.86e-5 / 1.1e-4 |
| 120 y | 1.97e-5 / 2e-5 | 4.03e-5 / 4e-5 | 6.27e-5 / 8e-5 |
Fourteen of the 15 values agree with Table 1 of the paper. The exception, 120 y / 15 %, is inconsistent with the paper’s own Fig 1A: P_mut = 8·10⁻⁵ yields about 18.5 % COX-negative cells.
The draft run with CRN-craft 0.8 (--size draft: pilot sweeps of 500
cells, fine sweeps of 1,000 cells per point):
| Lifespan | 5 % (this run / author / paper) | 10 % | 15 % |
|---|---|---|---|
| 3 y | 6.50e-3 / 6.41e-3 / 6.5e-3 | 7.59e-3 / 7.53e-3 / 7.6e-3 | 8.34e-3 / 8.32e-3 / 8.5e-3 |
| 10 y | 1.04e-3 / 9.69e-4 / 9.5e-4 | 1.43e-3 / 1.39e-3 / 1.45e-3 | 1.74e-3 / 1.74e-3 / 1.8e-3 |
| 40 y | 8.87e-5 / 8.77e-5 / 9e-5 | 1.65e-4 / 1.69e-4 / 1.7e-4 | 2.43e-4 / 2.53e-4 / 2.7e-4 |
| 80 y | 3.33e-5 / 3.38e-5 / 3e-5 | 6.50e-5 / 6.55e-5 / 7e-5 | 9.83e-5 / 9.86e-5 / 1.1e-4 |
| 120 y | 2.16e-5 / 1.97e-5 / 2e-5 | 4.23e-5 / 4.03e-5 / 4e-5 | 6.43e-5 / 6.27e-5 / 8e-5 |
fig1b_fits.png shows the sweeps with the fitted logistic curves and is a
useful diagnostic:

The full Fig 1B: python examples/kk13/kowald_kirkwood_2013.py --size full --part 1B. Its result file fig1b.csv is the input of Fig 1C/1D.
Next: Fig 1C/1D.
Fig 1C/1D: how many different mutants are in a COX-negative cell?
Author: Axel Kowald
Part of tutorial S2. Every section of this page
starts from these definitions; buildCloneModel is explained below:
import math
import os
import numpy as np
import crn_craft as crn
nMolecules = 1000
degRate = math.log(2)/(24.0*10.0) # 1/h
coxThreshold = 0.6
hoursPerYear = 24.0 * 360.0
nThreads = max(1, (os.cpu_count() or 1) - 2)
def buildCloneModel(pmut) -> crn.Model:
model = crn.Model("mtdna_clones")
model.add_parameter({"K": nMolecules, "delta": degRate, "pmut": pmut, "r": 10.0})
model.add_species("mtDNA", attributes=["clone"]) # observable "mtDNA" = all molecules
model.add_initial("mtDNA", nMolecules, clone=0) # clone 0 = wild type
model.add_observable("mutants", "mtDNA", where="x.clone > 0")
model.add_observable("types", "mtDNA", reduce="distinct")
model.add_observable("mutTypes", "mtDNA", where="x.clone > 0", reduce="distinct")
model.add_observable("largest", "mtDNA", where="x.clone > 0", reduce="max_count")
refill = "r * max(0, K - mtDNA) / mtDNA" # per molecule: free places shared by survivors
model.add_reaction(degRate, ["mtDNA"], [], name="degradation")
model.add_reaction(crn.mass_action(f"{refill} * (1 - pmut)"), ["mtDNA"],
[crn.copy("x"), crn.copy("x")], name="replication")
model.add_reaction(crn.mass_action(f"{refill} * pmut"), ["mtDNA"],
[crn.copy("x"), crn.new("mtDNA", clone="new_id()")], name="mutation")
return model
The difficult part
Fig 1C counts the number of different mtDNA types per COX-negative cell,
wild type included. Fig 1D gives the copy number of the most frequent
mutant as a percentage of all mtDNA. Every mutation event founds a new
mutant lineage (a clone), and its descendants must be told apart from those
of every other mutation. The two-species model of Fig 1A
cannot do this, because all mutants are lumped into mt.
In a classic reaction network this would need one species per clone. The number of clones is unknown in advance: at 3 years a COX-negative cell holds about 35 of them, and over a lifetime thousands arise and go extinct. Such a network cannot be written down beforehand.
The solution: species with attributes, new_id() and the tree method
CRN-craft solves this directly (chapter 12):
add_species("mtDNA", attributes=["clone"]): every molecule carries an attributeclone. Molecules with equal attribute values form one instance, that is, one species created during the run.clone = 0is the wild type (add_initial).- A product can copy a reactant (
crn.copy("x")), so a faithful replication keeps the clone id. - A product attribute can be set to
new_id()(crn.new("mtDNA", clone="new_id()")), an identifier never used before in that run. A mutation therefore founds a brand-new clone. - Observables summarize the instances.
reduce="distinct"counts how many different instances match, which is exactly the number of types. Awherefilter restricts an observable to mutants.reduce="max_count"is the largest copy number among the matching instances: the largest clone. Every species also has an observable under its own name, its total count (mtDNA). crn.mass_action(expression)gives a rate per molecule, like a number does (degRateabove). A plain string would be the whole propensity of the reaction.- Only the tree method (the default when no method is given) supports
species that are created during the run.
static_directandcompile_looprequire a fixed species set.
Why degradation and replication are separate here. The lumped “degrade one, replicate another” event of Fig 1A could also be written as a rule over pairs of molecules (see the last section). The model of the author’s run keeps the two steps separate: every molecule degrades at rate δ. Free places (K − N) are refilled at total rate r·(K − N), and each survivor is equally likely to be the template, hence the factor 1/N in the per-molecule rate. With r = 10 h⁻¹ a free place is refilled within about 6 minutes, so the mean N is 999.7 instead of exactly 1000, a negligible difference.
The same model as a model document, the form the tutorial used with
CRN-craft 0.7.1 (crn.Model.to_json() writes an equivalent one, and a run
with the same seed gives the same paths):
The clone model as a crn-craft.model/1.0 document (P_mut = 7.5·10⁻³)
{
"schema": "crn-craft.model/1.0",
"name": "mtdna_clones",
"parameters": {"K": 1000, "delta": 0.0028881132523331052, "pmut": 0.0075, "r": 10.0},
"types": [{"name": "mtDNA", "attributes": ["clone"]}],
"initial": [{"type": "mtDNA", "attributes": {"clone": 0}, "count": 1000}],
"observables": {
"N": {"type": "mtDNA"},
"mutants": {"type": "mtDNA", "where": "x.clone > 0"},
"types": {"type": "mtDNA", "reduce": "distinct"},
"mutTypes": {"type": "mtDNA", "where": "x.clone > 0", "reduce": "distinct"},
"largest": {"type": "mtDNA", "where": "x.clone > 0", "reduce": "max_count"}
},
"rules": [
{"name": "degradation", "reactants": [{"label": "x", "type": "mtDNA"}],
"rate": "delta", "products": []},
{"name": "replication", "reactants": [{"label": "x", "type": "mtDNA"}],
"rate": "r * max(0, K - N) / N * (1 - pmut)",
"products": [{"type": "mtDNA", "copy": "x"}, {"type": "mtDNA", "copy": "x"}]},
{"name": "mutation", "reactants": [{"label": "x", "type": "mtDNA"}],
"rate": "r * max(0, K - N) / N * pmut",
"products": [{"type": "mtDNA", "copy": "x"},
{"type": "mtDNA", "attributes": {"clone": "new_id()"}}]}
]
}
Reading the results
The observables mutants, types, mutTypes and largest appear in
result.paths like ordinary species. The P_mut values come from Fig 1B
(fig1b.csv); each of the 15 (lifespan, target) combinations is simulated
separately, and only the COX-negative cells enter the statistics. Here are
200 cells for 3 years at the 10 % rate:
endT = 3 * hoursPerYear
run = crn.ensemble(buildCloneModel(7.5e-3), end=endT, report_times=[0.0, endT], replicates=200,
seed=3000, threads=nThreads, keep_paths="all",
keep_instances=200, # only for the cross-check below
strict=True) # no method -> tree method
result = run.simulate()
final = result.paths.isel(time=-1)
total = final.sel(variable="mtDNA").to_numpy()
neg = final.sel(variable="mutants").to_numpy() > coxThreshold * total
types = final.sel(variable="types").to_numpy()[neg]
largest = final.sel(variable="largest").to_numpy()[neg]
print(f"{neg.sum()} COX-negative cells: {types.mean():.1f} types, "
f"largest clone {100 * (largest / total[neg]).mean():.1f} % of all mtDNA")
# Cross-check: the largest clone from the final instances (needs keep_instances)
for cell in result.metadata["final_instances"]:
counts = [inst["count"] for inst in cell["instances"] if inst["attributes"][0] > 0]
assert (max(counts) if counts else 0) == final.sel(variable="largest").to_numpy()[cell["id"]]
19 COX-negative cells: 35.3 types, largest clone 16.3 % of all mtDNA
Before 0.8 the largest clone could only be read from the final instances,
as in the cross-check; reduce="max_count" makes it an observable, so the
full runs need neither keep_instances nor raised memory limits.
Result
The author’s run with CRN-craft 0.7.1 (3,000 cells per combination). Number of mtDNA types per COX-negative cell (Fig 1C):
| Lifespan | 5 % | 10 % | 15 % | Paper | Mutant types only |
|---|---|---|---|---|---|
| 3 y | 31.3 | 35.9 | 38.4 | 31.5 / 35.7 / 38.7 | 30.3 / 34.9 / 37.4 |
| 10 y | 8.45 | 10.34 | 12.02 | 7.8 / 10.4 / 12.2 | 7.46 / 9.35 / 11.04 |
| 40 y | 2.25 | 2.95 | 3.29 | 2.3 / 2.8 / 3.5 | 1.66 / 2.29 / 2.69 |
| 80 y | 1.56 | 1.78 | 2.06 | 1.44 / 1.75 / 2.08 | 1.19 / 1.46 / 1.75 |
| 120 y | 1.31 | 1.51 | 1.66 | 1.35 / 1.46 / 1.61 | 1.13 / 1.29 / 1.45 |
Most frequent mutant in % of all mtDNA (Fig 1D):
| Lifespan | 5 % | 10 % | 15 % | Paper |
|---|---|---|---|---|
| 3 y | 17.3 | 15.6 | 14.3 | 17 / 16 / 15 |
| 10 y | 44.9 | 38.9 | 36.7 | 44 / 40 / 37 |
| 40 y | 80.2 | 76.4 | 74.4 | 81 / 76 / 72 |
| 80 y | 90.1 | 88.1 | 87.2 | 92 / 90 / 86 |
| 120 y | 95.5 | 92.3 | 91.6 | 95 / 93 / 92 |
Having both types and mutTypes as observables settled an ambiguity in
the paper. Table 1 speaks of “types of mutants”, but only the count
including the wild type matches at every lifespan. With mutants only, the
40-year values of the author’s run fall about 10 standard errors below the
paper. In long-lived cells the wild type is often lost entirely (≈ 80 % of
COX-negative cells at 120 years), so including it adds less than 1 there.
The biology is clear-cut. Short-lived COX-negative cells contain many small clones, while long-lived ones are taken over by one clone. That is the signature of random drift, and the paper uses it as an argument against drift as the mechanism in short-lived animals.
The draft run with CRN-craft 0.8 (--size draft: 200 cells per
combination, so only 10 to 30 COX-negative cells per entry; mean ±
standard error):
| Lifespan | 5 % (this run) | 10 % | 15 % | COX-negative cells | Author’s run | Paper | Mutant types only (this run) |
|---|---|---|---|---|---|---|---|
| 3 y | 29.67 ± 1.72 | 35.59 ± 0.97 | 37.14 ± 0.93 | 12 / 17 / 28 | 31.3 / 35.9 / 38.4 | 31.5 / 35.7 / 38.7 | 28.67 / 34.59 / 36.14 |
| 10 y | 6.75 ± 1.25 | 10.91 ± 0.61 | 10.66 ± 0.44 | 4 / 23 / 32 | 8.45 / 10.34 / 12.02 | 7.8 / 10.4 / 12.2 | 5.75 / 9.91 / 9.69 |
| 40 y | 2.00 ± 0.19 | 2.79 ± 0.29 | 3.34 ± 0.23 | 8 / 19 / 29 | 2.25 / 2.95 / 3.29 | 2.3 / 2.8 / 3.5 | 1.50 / 2.05 / 2.83 |
| 80 y | 1.50 ± 0.17 | 2.00 ± 0.20 | 2.11 ± 0.18 | 10 / 18 / 27 | 1.56 / 1.78 / 2.06 | 1.44 / 1.75 / 2.08 | 1.30 / 1.67 / 1.81 |
| 120 y | 1.58 ± 0.19 | 1.52 ± 0.18 | 1.54 ± 0.13 | 12 / 23 / 28 | 1.31 / 1.51 / 1.66 | 1.35 / 1.46 / 1.61 | 1.33 / 1.39 / 1.39 |
| Lifespan | 5 % (this run) | 10 % | 15 % | COX-negative cells | Author’s run | Paper |
|---|---|---|---|---|---|---|
| 3 y | 16.6 ± 2.2 | 14.2 ± 1.0 | 14.6 ± 0.9 | 12 / 17 / 28 | 17.3 / 15.6 / 14.3 | 17 / 16 / 15 |
| 10 y | 47.6 ± 8.3 | 34.2 ± 2.4 | 37.9 ± 2.9 | 4 / 23 / 32 | 44.9 / 38.9 / 36.7 | 44 / 40 / 37 |
| 40 y | 87.1 ± 5.0 | 77.6 ± 4.1 | 74.3 ± 3.5 | 8 / 19 / 29 | 80.2 / 76.4 / 74.4 | 81 / 76 / 72 |
| 80 y | 93.9 ± 3.4 | 90.3 ± 3.8 | 87.1 ± 3.0 | 10 / 18 / 27 | 90.1 / 88.1 / 87.2 | 92 / 90 / 86 |
| 120 y | 92.4 ± 3.7 | 96.8 ± 1.3 | 95.6 ± 1.7 | 12 / 23 / 28 | 95.5 / 92.3 / 91.6 | 95 / 93 / 92 |


The full run (python examples/kk13/kowald_kirkwood_2013.py --size full --part 1CD) took about 2.6 hours on 18 threads (12–14 M events/s) in the
author’s run. Most of that time goes to the 80- and 120-year cells, which
have about 6 million events each.
The exact Moran step as a pair rule
Two identical reactants over one species form unordered pairs of distinct
molecules. Since CRN-craft 0.8 the two molecules of a pair get the labels
x and y at random, so “y is degraded and replaced by a copy of x” is
one rule, and N stays exactly 1000. Each unordered pair fires at
2δ/(N − 1) in total, so every molecule is degraded at rate δ, as in the
paper:
def buildPairModel(pmut) -> crn.Model:
model = crn.Model("mtdna_clones_pairs")
model.add_parameter({"delta": degRate, "pmut": pmut})
model.add_species("mtDNA", attributes=["clone"])
model.add_initial("mtDNA", nMolecules, clone=0)
model.add_observable("mutants", "mtDNA", where="x.clone > 0")
model.add_observable("types", "mtDNA", reduce="distinct")
model.add_observable("largest", "mtDNA", where="x.clone > 0", reduce="max_count")
pairRate = "2 * delta / (mtDNA - 1)"
model.add_reaction(crn.mass_action(f"{pairRate} * (1 - pmut)"), ["mtDNA", "mtDNA"],
[crn.copy("x"), crn.copy("x")], name="x_replaces_y")
model.add_reaction(crn.mass_action(f"{pairRate} * pmut"), ["mtDNA", "mtDNA"],
[crn.copy("x"), crn.new("mtDNA", clone="new_id()")], name="x_mutant_replaces_y")
return model
endT = 3 * hoursPerYear
for build in (buildCloneModel, buildPairModel):
run = crn.ensemble(build(7.5e-3), end=endT, report_times=[0.0, endT], replicates=200,
seed=3000, threads=nThreads, keep_paths="all", strict=True)
result = run.simulate()
final = result.paths.isel(time=-1)
total = final.sel(variable="mtDNA").to_numpy()
neg = final.sel(variable="mutants").to_numpy() > coxThreshold * total
types = final.sel(variable="types").to_numpy()[neg]
print(f"{build.__name__}: N = {total.min():.0f}..{total.max():.0f}, {neg.sum()} COX-negative, "
f"{types.mean():.1f} types, {result.records['events'].mean() / 1e3:.0f} k events per cell")
buildCloneModel: N = 998..1000, 19 COX-negative, 35.3 types, 150 k events per cell
buildPairModel: N = 1000..1000, 15 COX-negative, 36.5 types, 75 k events per cell
The pair form keeps N constant and needs half the events, because a replacement is one event instead of two. Both models describe the same biology; the tables above come from the separate rules of the author’s run.
Next: limits and lessons.
Limits in CRN-craft, and the lessons of the study
Author: Axel Kowald
Part of tutorial S2.
import math
import crn_craft as crn
degRate = math.log(2) / 240.0
Limits and when to raise them
CRN-craft puts explicit budgets on every run. A buggy or explosive model
then stops with a clear reason instead of exhausting memory or running
forever. The defaults suit typical models, and since 0.8 they also suit
long horizons like the ones of this study. A replicate that hits a budget
stops, and its reason is recorded in result.records["termination"]
(completed, stopped, event_limit, sampling_limit, instance_limit,
wall_time_limit, cancelled, failed).
Always make sure that every replicate completed before computing
statistics. An early stop leaves truncated paths, and dropping those cells
silently biases the result towards fast-ending, often atypical,
trajectories. simulate() warns when a replicate did not complete
(crn.IncompleteEnsembleWarning), and with strict=True it raises
instead:
model = crn.Model("decay")
model.add_reaction(degRate, ["mtDNA"], [], name="degradation")
model.add_species({"mtDNA": 1000})
run = crn.ensemble(model, end=1e6, report_times=[0.0, 1e6], replicates=4, seed=1,
max_events=100, strict=True)
try:
run.simulate()
except crn.IncompleteEnsembleError as error:
print(error.counts)
{'event_limit': 4}
| Limit (keyword) | What it bounds | In this study |
|---|---|---|
max_events | reaction events per replicate; default 10⁸ | a 120-year clone cell has about 6·10⁶ events; the default is enough (0.7.1 needed 5·10⁷) |
max_sampling_steps | random-number draws per replicate; by default 16 × max_events | follows max_events, nothing to set (0.7.1 needed 5·10⁸) |
max_instances | instances (here clones) alive at the same time in one replicate; default 100,000 | the default is enough: about 40 clones at most (0.7.1 needed 5,000 because of the memory reservation of keep_instances) |
max_output_bytes | size of the returned result; default 64 MiB | keep_paths="all" with 1,441 monthly report times for 1,000 cells is about 23 MB |
| batch size (script) | memory held by kept trajectories | 1,000 cells per crn.ensemble call |
wall_time_s | wall-clock time per run | not needed; use it as the guard when max_events=None |
FSP work limit (CRN-E070) | state-space work of Model.fsp | the state space was too large, so sampling was used instead |
How to choose the limits:
- Estimate the event count from the model: total propensity × simulated
time. The default
max_eventsof 10⁸ covers about 15 seconds of simulation per replicate at typical speeds. - Run a prototype with a few hundred replicates at the longest horizon
and the highest rate, then inspect
records["termination"],records["peak_instances"]andrecords["events"]. - Raise only the limit that was hit, and keep it finite. A finite budget
still guards against a model error that makes the event rate or the
number of instances explode.
max_events=Noneremoves the event limit; combine it withwall_time_s. - If a reservation error mentions bytes (
CRN-R020), its message lists the parts of the reservation and its hint names the largest one; reduce that one, for example the replicates per call. Do not raise memory limits blindly.
What changed since 0.7.1
The tutorial was first written for CRN-craft 0.7.1. Version 0.8 changed:
max_eventsdefaults to 10⁸, andmax_sampling_stepsfollows it, so the long runs need no raised limits.keep_instancesno longer reserveskeep_instances × max_instancesinstances before the run, somax_instancesneed not be lowered.simulate()warns about incomplete replicates;strict=Truemakes it an error.- The builder writes species with attributes,
crn.copy,crn.new,crn.mass_actionandadd_observable, so the clone model needs no JSON. reduce="max_count"gives the largest clone as an observable.- Pair rules give the labels
xandyat random, so the exact Moran step can be one rule.
Summary of lessons
- Lump when you can. If only counts matter, an exact two-reaction model
with expression propensities plus
static_directandcompile_loopis fastest. - Use one seed per grid point in parameter sweeps that feed a statistical model, so the samples stay independent.
- Use species with attributes and
new_id()when individual lineages matter, together withreduce="distinct"andreduce="max_count"observables and the tree method. Usekeep_instancesandmetadata["final_instances"]only for quantities that observables cannot express. - Check every replicate’s termination status (or use
strict=True), and raise budgets deliberately, after a prototype run at the hardest settings. - Record alternative definitions as separate observables (here types with and without wild type). They are cheap, and they can resolve ambiguities in a paper’s text.
Back to the start of the chapter.
S3. Case study: comparing mtDNA mechanisms
What this chapter reproduces
Old post-mitotic cells such as muscle fibers and neurons accumulate mtDNA deletion mutants. In an affected cell, the mutant copies usually descend from a single deletion. Two papers from 2014 used this observation to test three candidate mechanisms. Each mechanism was given the mutation rate that makes 10% of simulated cells COX-negative at the end of a virtual lifespan of 3, 10, 40 or 80 years of 360 days. Each mechanism was then asked how many different mutants an affected cell contains:
Kowald A., Kirkwood T.B.L. (2014). Transcription could be the key to the selection advantage of mitochondrial deletion mutants in aging. PNAS 111(8):2972–2977. doi:10.1073/pnas.1314970111 (PMC3939916, Figures 2 and 3)
Kowald A., Dawson M., Kirkwood T.B.L. (2014). Mitochondrial mutations and ageing: Can mitochondrial deletion mutants accumulate via a size based replication advantage? Journal of Theoretical Biology 340:111–118. doi:10.1016/j.jtbi.2013.09.009 (Figures 2 to 7)
The drift baseline comes from the study re-created in tutorial S2 (Kowald & Kirkwood 2013, Aging Cell 12:728–731). This chapter is a reconstruction from the published text and figures. The original programs were not available to it. The papers’ authors did not write or review it.
The result in three lines:
- At three years, an affected cell holds 34.7 mutant lineages under neutral drift, 29.3 under the size advantage and 1.26 under transcription-linked replication (20,000 new cells per mechanism after the fit). The PNAS paper reports 1.26 for the transcription mechanism and about 30 for the others.
- The difference shrinks with lifespan. At 80 years, every mechanism gives 1.0 to 1.5 lineages per affected cell.
- The transcription result depends on two points that the papers do not state and that an author of the papers confirmed (personal communication, November 2026): a cell whose ATP runs out stays as it is for the rest of the simulation and is counted, and mutant templates mutate too. Both, and the 360-day year, are explained on the last page.
Words used in this chapter
- COX-negative (or affected): a cell whose respiratory chain fails
because too much of its mtDNA is mutant. Both papers use 60% mutant
copies as the threshold. A cell with
Mmutant andWwild-type copies is affected whenM >= 0.6 * (W + M), computed in integers as5*M >= 3*(W+M). A cell with no copies at all is not classified. - Lineage: all descendants of one simulated deletion event. Every deletion creates a new lineage, also when the template was already a mutant. A faithful copy belongs to its template’s lineage.
- Types: the papers count “different mtDNAs” or “different mutants” per affected cell. This chapter reports the number of surviving mutant lineages. The drift table of the 2013 paper also counts the wild type as one type when any wild-type copy survives (tutorial S2c settled this). Where a published number uses that convention, the comparison uses it too, and the result files give both counts.
The three mechanisms in plain words
| Mechanism | What makes a deletion mutant spread | Page |
|---|---|---|
| Neutral drift | Nothing. Copies degrade at random and survivors replace them, so a mutant spreads only by chance. | S3a |
| Size advantage | A half-size mutant spends 1 h instead of 2 h being copied. Only free copies can start a new replication, so the mutant is available more often. | S3a |
| Transcription-linked replication | Mutants start replication 1.5 times as often as wild type. ATP that only wild-type copies produce slows all replication. | S3a |
The pages of the chapter:
| Page | Question |
|---|---|
| The three models | What exactly is simulated, and how does CRN-craft express it? |
| Fitting and the comparison | How is the 10% target fitted, and what do new cells show? How close are the published values? |
| Choices, checks and limits | What did the reconstruction have to decide, how was it checked, and what does it not show? |
CRN-craft and the reference sampler
The single-cell models run on CRN-craft: the drift pair rule on the
tree method, a staged version of the size model on static_direct, and
the ATP model on hybrid and thinning (the
ATP chapter introduces both). The tissue study, about
420,000 simulated cells, runs on a small C++17 sampler local to the
example (examples/kk14/reference.cpp). It changes nothing in CRN-craft.
The reference sampler exists for two reasons:
- Two of the published programs are hourly loops, not reaction networks. In the size model a copy is busy for exactly 2 h; a reaction network can only approximate a fixed delay with a chain of exponential stages. The transcription program applies degradation, replication, mutation and ATP production once per hour. The sampler follows those loops, so its differences from the papers are differences in the reconstructed model, not in the time stepping.
- Speed. On a two-core x86-64 host, a three-year drift cell took about
16 ms on CRN-craft’s
treemethod (76,000 events) and 0.75 ms in the reference sampler. A three-year ATP cell took about 15 ms onthinningand 1 ms in the hourly sampler. The calibration needs mostly 10- to 80-year cells. The full study took 136 minutes of sampling with one thread on a two-core Intel x86-64 host with the reference sampler, and would take roughly 20 times as long natively.
For neutral drift both run the same continuous-time process, and the validation script checks both against its exact count law (checks).
Running the example
You need Python 3.10 or newer, CRN-craft 0.8.0, SciPy, Matplotlib and a
C++17 compiler (set CXX to choose one). The compiler builds the reference
sampler in a temporary directory the first time a command needs it. Run
the commands from the repository root:
python -m pip install 'crn-craft==0.8.0' scipy matplotlib
python examples/kk14/study.py single-cell --size quick
python examples/kk14/study.py compare --size quick --ages 3 --threads 2
python examples/kk14/study.py figures --results examples/kk14/results/reconstruction
single-cell solves the two deterministic single-cell models in a few
seconds. compare --size quick simulates 128 new cells per mechanism at
the saved three-year mutation rates; its intervals are wide. figures
redraws the saved comparison without simulating. The
example README lists all commands and
output files; the results page
gives the commands of the full study.
See also: Case study: mtDNA mutants, Variable population: ATP, Re-creating a published study.
Continue with tutorial O2 to infer mutation and selection parameters and estimate takeover times from cell snapshots.
The three models
Part of tutorial S3.
All three models describe one post-mitotic cell with about 1,000 mtDNA
copies, a half-life of 10 days (delta = ln(2)/240 per hour) and time in
hours. The tissue study counts a year as 360 days, so its lifespans of 3,
10, 40 and 80 years are 1,080, 3,600, 14,400 and 28,800 days. Every
tissue simulation starts with 1,000 wild-type copies and no mutant. A new
deletion appears on a daughter copy with probability p per
replication, whether the template is a wild-type or a mutant copy: mutants
can mutate. p is the parameter that the
fit adjusts. The three models differ
in what decides which copy replicates. The 360-day year, the mutation of
mutant templates and the fate of a cell whose ATP runs out (below) were
confirmed by an author of the papers (personal communication, November
2026).
Neutral drift
Applies: tutorial S2c, The exact Moran step as a pair rule.
Every copy degrades at rate delta. Each degradation is followed at once
by the replication of one of the other 999 copies, chosen at random, so the
cell always holds exactly 1,000 copies. The daughter is a new mutant with
probability p, whatever its template; otherwise it copies the template.
No genotype has an advantage. This is the model of
tutorial S2, with its pair rule.
To fit p only the mutant count matters. With M mutants and W = N - M
wild-type copies (N = 1000), the count falls by one at rate
delta * M * W * (1-p) / (N-1) (a mutant dies, a wild type is copied
faithfully) and rises by one at rate delta * W * (M*(1-p) + (N-1)*p) / (N-1)
(a wild type dies and is replaced by a mutant copy or a new deletion). The
reference sampler draws these two transitions. When lineages are needed,
a second sampler follows every lineage; it skips replacements inside one
lineage, which change nothing.
Size advantage
The size paper models a copy as either free or busy. Only free copies can start a replication. A busy copy stays busy for its copying time, 2 h for wild type and 1 h for a mutant half its size, and then returns to the free pool together with its daughter. Every copy, free or busy, degrades. A free copy starts replicating with probability
r * C / (C + N)
per hour, where N counts all copies, free and busy. C is set so that a
wild-type cell holds 1,000 copies at equilibrium (C = 2.93 for
r = 1 per hour). The paper names r but gives no value; the
reconstruction uses 1 per hour and checks 0.1 per hour
(choices).
The stochastic program of the paper repeats three tasks every hour, and the reference sampler follows them in this order:
- Copies whose copying time is over return to the free pool, each with
one daughter. The daughter is a new deletion mutant with probability
p, also when the template is a mutant. - Every free or busy copy degrades with probability
ln(2)/240. A busy copy that degrades loses its daughter. - Free copies start replicating with the probability above.
A copy that starts in hour h completes at the start of hour h + 1 (a
mutant) or h + 2 (wild type). A mutant therefore never meets a
degradation trial while busy, and a wild-type copy meets one.
The paper’s deterministic version is a delay differential equation. For
each genotype with free copies F and busy copies B, starts have flux
J(t) = r*C*F(t)/(C+N(t)), and the copies that survive their copying time
tau return with flux Q(t) = exp(-delta*tau)*J(t-tau):
F' = 2*Q - J - delta*F
B' = J - Q - delta*B
The size model in CRN-craft
Applies: chapter 2, Rates as numbers and as strings.
A reaction network has no fixed delay. It can replace the busy state by a
chain of k stages, each left at rate k/tau. The time in the chain then
has mean tau and variance tau²/k, and the chain approaches a fixed delay
as k grows. Degradation applies in every stage. staged_size(k) in
examples/kk14/native.py builds this model for a small cell of 100 copies
(10 mutants, half-life 48 h): species W, W1, ..., Wk and
M, M1, ..., Mk, a start reaction with the whole propensity
C * W / (C + total), k stage reactions and degradation of every
species. Count a genotype as the sum of its free and busy species. The
four-stage model at time zero and after four hours:
import sys
import crn_craft as crn
sys.path.insert(0, "examples/kk14")
from native import staged_size
run = crn.ensemble(
staged_size(4), end=4, report_times=[0, 4], replicates=16, seed=12,
method="static_direct", strict=True,
)
mutant = run.simulate().statistics["mean"][["M", "M1", "M2", "M3", "M4"]].sum(axis=1)
print(mutant.round(2).tolist())
[10.0, 9.88]
python examples/kk14/study.py native runs the staged model for 120
days with 1, 4 and 16 stages next to the hourly sampler, 320 cells each.
At that size the endpoint mutant fraction has a standard error of about
0.017, and the four-stage value (0.171) lies 1.6 combined standard errors
below the others (0.210 to 0.211). A rerun with 4,000 cells per choice
(native --cells 4000) gives:
| Copying time | Mean mutant fraction at 120 days | Standard error |
|---|---|---|
| Hourly fixed delay (reference sampler) | 0.193 | 0.005 |
| 1 exponential stage | 0.185 | 0.005 |
| 2 stages | 0.194 | 0.005 |
| 4 stages | 0.191 | 0.005 |
| 8 stages | 0.195 | 0.005 |
| 16 stages | 0.197 | 0.005 |
No two choices differ by more than 1.8 standard errors. In this small cell the advantage of a 1-h copying time is too weak for the shape of the delay distribution to show in the endpoint at this sample size. The staged model is an exercise in expressing a delay; the tissue study uses the hourly sampler.
Transcription-linked replication
Applies: chapter 9, A variable between events.
The PNAS paper proposes that deletion mutants gain their advantage through the link between transcription and replication. Its model represents this with three rules, all rates per hour (PNAS Table 1):
- Wild-type copies are synthesized at a maximal rate of 1, mutants at 1.5.
Both rates are multiplied by
c/(c+ATP), which is one half atATP = c. - Both genotypes degrade with a half-life of 240 h.
- Wild-type copies produce ATP at rate 0.1 each, every copy costs 0.01 for maintenance, and other processes consume ATP at rate 0.2 per unit.
As equations, with W wild-type and M mutant copies:
W' = (1.0*c/(c+ATP) - delta) * W
M' = (1.5*c/(c+ATP) - delta) * M
ATP' = 0.1*W - 0.01*(W+M) - 0.2*ATP
With 1,000 wild-type copies and no mutant the ATP equilibrium is 450, and
c = 450*delta/(1-delta) = 1.303 keeps that cell at 1,000 copies. A mutant
copy consumes ATP without producing it. As mutants spread, ATP falls,
replication speeds up for both genotypes, and the mutants, which start 1.5
times as often, outgrow the wild type until ATP runs out.
The tissue simulation of the paper is an hourly Java program that
applies degradation, replication, mutation and ATP production. The
reference sampler does this per hour: degrade each copy with probability
1 - exp(-delta); let each survivor replicate with probability
1 - exp(-rate) for its rate above; make each daughter a new deletion with
probability p, from either genotype; then relax ATP for one hour with the
new counts held fixed. A cell whose ATP reaches zero stays in that state
for the rest of the simulation: its ATP stays at zero and its wild-type
and mutant counts stay fixed. The sampler therefore stops the cell at that
moment and keeps its counts and lineages; at the end of the lifespan it
is classified like any other cell
(choices).
The ATP model in CRN-craft
Applies: tutorial S1c, Variable population: ATP.
coupled_atp in native.py builds the same rules as a continuous-time
model: ATP as a continuous variable with add_ode(..., lower_bound=0)
for hybrid, and as the stored atp block for exact thinning. Both stop
a cell when ATP reaches zero, as the reference sampler does: the cell is
stopped, ATP reads 0 at every later report time, and the counts stay as
they were at the stop. A deletion is a separate reaction (mutate_W,
mutate_M) with rate p times the replication rate, so wild-type and
mutant templates both produce new mutants.
The hybrid solver tracks counts, not lineages. marked_hybrid recovers
lineages in a small run with a callback: a mutation event opens a new
lineage, and a faithful mutant birth or death picks a lineage in
proportion to its count, from the callback’s own random stream. The
callback checks after every event that the lineage counts add up to the
mutant count, and the run with the callback has the same trajectories as
the run without it.
In a small test cell (100 copies, one founder mutant, half-life 120 h, 8,760 h, a fixed test horizon rather than a year of the study), hybrid and thinning gave 121 and 139 COX-negative cells of 320 (z = −1.45); with 4,000 cells each, 1,690 and 1,639 (z = 1.16). The hourly sampler gave 131 and 1,663. The continuous-time and the hourly versions agree at this precision.
One cell, deterministic
Both papers start with a deterministic single cell: 1,000 wild-type copies (999 in the size paper) and one mutant.

study.py single-cell integrates the ATP equations with Radau and the delay
equations with Heun’s method on a 0.25-h mesh. Both programs work in
hours, so the times are reported in hours or days; the size paper reports
its times in years:
| Quantity | Reconstruction | In years of 365 / 360 days | Paper |
|---|---|---|---|
| ATP reaches zero | 247.406 days, mutants 10.07 times the wild type | — | about 250 days, mutants about ninefold (PNAS Figure 2) |
| Wild type below one copy, size model | 831,783 h (34,658 days) | 94.952 / 96.271 | about 95 years (size paper, Figure 2) |
| Same, 2-day half-life | 33,867 h (1,411 days) | 3.866 / 3.920 | about 3.9 years (Figure 3) |
| Same, 10-h wild-type copying time | 169,333 h (7,056 days) | 19.330 / 19.599 | 19.33 years (Figure 4) |
| Same, mutant 70% of wild-type size | 1,386,983 h (57,791 days) | 158.331 / 160.530 | almost 160 years (Figure 5) |
| Busy fraction, wild-type cell and mutant cell | 0.579% and 0.289% | — | 0.58% and 0.29% (Figure 2) |
The printed 19.33 years matches the 365-day conversion and not the
360-day one (19.60 years). The other three values fit 365 days at least
as well: about 95, about 3.9 (both conversions round to it) and almost
160 (158.3 is below 160, 160.5 above). The tissue study of the PNAS paper
uses 360 days, so the size paper’s deterministic program may have used a
365-day year. This is an open question for the authors
(limits). Meshes of 0.5 h and
0.125 h give the same 831,783 h, and r = 0.1 per hour with C
recomputed gives 831,793 h. All values are in
examples/kk14/results/reconstruction/single-cell.json.
Next: Fitting and the comparison.
Fitting and the comparison
Part of tutorial S3.
Both papers ran 1,000 cells per lifespan and adjusted the mutation rate until 10 ± 0.5% of them were COX-negative at the end. A year has 360 days, so the lifespans of 3, 10, 40 and 80 years are 25,920, 86,400, 345,600 and 691,200 hours. Then they reported the number of types in the affected cells. This page does the same with a fit on one set of cells and the reported numbers from a second, independent set, so that the fitted rate is not judged on the cells it was fitted to.
The protocol
Applies: chapter 8, Reproducing a published simulation.
Everything below is fixed in examples/kk14/campaign.py and recorded in
results/reconstruction/manifest.json (seed 20261121, tier full):
- Target: 10% COX-negative cells, inclusive 60% threshold. A prevalence interval is called within the band if it lies inside 9.5–10.5%, compatible if it intersects the band, and outside otherwise.
- Fit, for each of the 12 mechanism–lifespan cases (and the 2-day
sensitivity case): start from a bracket around the published rate,
halve or double it until 400-cell runs at the two ends enclose 10%,
run 1,600 cells at a logistic interpolation, 1,600 cells each at 1/1.2
and 1.2 times the resulting rate, and 4,800 cells at the local
interpolation. The final rate inverts a logistic regression of the
affected fraction on
log10(p)through the local and confirmation points at 10%; its 95% interval comes from the regression (delta method). Only the affected fraction enters the fit, never a lineage count. - Separation: the runner fits all 13 rates and writes
rates.csvbefore it simulates any validation cell. Every batch of cells has its own seed base, a hash of the run seed, the sampler code, the full configuration (including the fitted rate) and the phase name, so fit cells and validation cells come from different streams. - Validation: 20,000 new cells per case at the frozen rate, and a 1,000-cell repeat at the papers’ sample size. Prevalence gets a 95% Wilson interval; lineage means get a 95% percentile bootstrap interval (1,999 resamples of whole cells).
- Decision rule for the main question: the three-year transcription
interval must lie below both other intervals, and all three three-year
prevalence intervals must be compatible with the band. The manifest
records the outcome,
separated.
Results

Solid symbols are this reconstruction; open symbols are values read from PNAS Figure 3. Panel B shows mutant lineages; for drift the open symbols are the 2013 counts, which include the wild type. Published figure
The validation cohorts (the table is generated from
results/reconstruction/comparison.csv and checked by
validation/check_kk14.py):
| Age | Mechanism | Affected / cells | Prevalence (95% Wilson) | Mutant lineages (95% bootstrap) | Target band |
|---|---|---|---|---|---|
| 3 y | Neutral drift | 2122 / 20000 | 10.61% (10.19–11.04%) | 34.72 (34.51–34.93) | compatible |
| 3 y | Faster copying of shorter mtDNA | 1994 / 20000 | 9.97% (9.56–10.39%) | 29.30 (29.11–29.51) | within |
| 3 y | Transcription-linked replication | 1976 / 20000 | 9.88% (9.47–10.30%) | 1.26 (1.24–1.28) | compatible |
| 10 y | Neutral drift | 1953 / 20000 | 9.77% (9.36–10.18%) | 9.46 (9.35–9.57) | compatible |
| 10 y | Faster copying of shorter mtDNA | 1831 / 20000 | 9.16% (8.76–9.56%) | 4.92 (4.84–5.01) | compatible |
| 10 y | Transcription-linked replication | 2049 / 20000 | 10.24% (9.83–10.67%) | 1.07 (1.06–1.08) | compatible |
| 40 y | Neutral drift | 1945 / 20000 | 9.72% (9.32–10.14%) | 2.21 (2.16–2.25) | compatible |
| 40 y | Faster copying of shorter mtDNA | 2125 / 20000 | 10.62% (10.21–11.06%) | 1.26 (1.24–1.28) | compatible |
| 40 y | Transcription-linked replication | 1966 / 20000 | 9.83% (9.43–10.25%) | 1.01 (1.01–1.01) | compatible |
| 80 y | Neutral drift | 1935 / 20000 | 9.68% (9.27–10.09%) | 1.50 (1.47–1.53) | compatible |
| 80 y | Faster copying of shorter mtDNA | 2009 / 20000 | 10.04% (9.64–10.47%) | 1.10 (1.08–1.11) | within |
| 80 y | Transcription-linked replication | 1985 / 20000 | 9.93% (9.52–10.35%) | 1.01 (1.00–1.01) | within |
How to read the prevalence column:
- All 12 intervals intersect 9.5–10.5%, and three lie inside it (size
advantage at 3 and 80 years, transcription at 80 years). So the data are
compatible with the band everywhere but confirm it only for those three.
9 of the 12 point estimates lie in the band. The exceptions are drift at
3 years (10.61%, interval from 10.19%), the size advantage at 10 years
(9.16%, interval up to 9.56%) and at 40 years (10.62%, interval from
10.21%); exact binomial tests against 10% give p = 0.004, 0.00006 and
0.003. These misses come from the fits, not from the validation cells:
the 95% intervals of the fitted rates in
rates.csvare ±1.5% to ±7% of the rate at three years and up to ±14% at 10 and 40 years. - At the papers’ sample size the criterion is much weaker than it looks. With 1,000 cells at 10% the binomial standard error is 0.95 percentage points, so a ±0.5-point band is narrower than one standard error. The 1,000-cell repeats at the fitted rates gave 84, 96, 92 (3 y), 95, 113, 123 (10 y), 90, 105, 102 (40 y) and 108, 110, 100 (80 y) affected cells, in the order drift, size, transcription. Seven of the twelve, 84, 92, 113, 123, 90, 108 and 110, are outside 95–105 although the rates are the same as above.
How to read the lineage column: at three years the transcription
interval (1.24–1.28) lies far below drift (34.5–34.9) and size advantage
(29.1–29.5), so the decision rule gives separated. 77% of the affected
transcription cells hold a single mutant lineage, 20% two, and none more
than four, while drift and size cells hold between 14 and 54.

Under the transcription mechanism almost every affected cell is a cell whose ATP ran out: 1,904 of the 1,976 at three years, and 2,031, 1,959 and 1,983 of the affected cells at 10, 40 and 80 years. Such a cell keeps zero ATP and its wild-type and mutant counts for the rest of the simulation, and at the end of the lifespan it is classified and its lineages are counted like those of any other cell, as an author of the papers confirmed (personal communication, November 2026). Only 72 of the 18,096 three-year cells that kept their ATP are affected (0.40%), with 1.03 lineages each (choices).
An extension in tutorial S4c applies this protocol to a fourth mechanism, stochastic survival of the densest in a spatial chain, with de novo deletions added: at 3 years an affected region of that model holds about 1,460 mutant types.
Comparison with the published values
results/reconstruction/reference-differences.csv compares the
reconstruction with 42 published values: 23 read from PNAS Figure 3 and
the 1.26 printed in its text, 9 read from Figures 6 and 7 of the size
paper and the 1.16 printed in its text, and the 8 values of the 2013
Table 1 at 10% (as transcribed in tutorial S2). Values read from a figure carry an interval of ±2 pixels; a printed
value is exact to its last digit. Neither includes the papers’ own
sampling error, which they do not report: a published mean of types rests
on about 100 affected cells, and a published rate on a ±0.5-point band at
1,000 cells.
Most values agree within a few percent. These do not, judged by the two intervals (a printed value is taken as exact to half its last digit):
| Published value | Published | Reconstruction | Difference |
|---|---|---|---|
| PNAS Fig 3A, transcription, 10 y, rate | 1.16e-6 (1.08–1.25) | 1.42e-6 (1.25–1.61) | +22% |
| Size paper Fig 6A, size, 80 y, rate | 1.00e-5 (0.96–1.04) | 1.13e-5 (1.06–1.22) | +13% |
| Size paper Fig 7A, 2-day half-life, 3 y, rate | 1.79e-5 (1.74–1.85) | 1.46e-5 (1.37–1.55) | −19% |
| Size paper Fig 6B, size, 3 y, types | 29.8 (29.7–30.0) | 29.30 (29.11–29.51) | −1.8% |
| 2013 Table 1, drift, 80 y, types with wild type | 1.75 | 1.81 (1.78–1.85) | +3.7% |
| Size paper Fig 7B, 2-day half-life, types | 1.16 | 1.117 (1.102–1.134) | −3.7% |
Against PNAS Figure 3 itself, every interval of the reconstruction overlaps the reading interval except for the 10-year transcription rate. At three years the reconstruction is close to every published value: rates differ by +0.8% (drift), −1.4% (size) and −5.6% (transcription), lineage counts by 0.0% (drift, with the wild type), −1.5% (size) and 0.0% (transcription, 1.26 printed). At 10 to 80 years the other rates differ by −9% to +12% and the lineage counts by −13% to +4%; there the fitted rates have 95% intervals of ±4% to ±14%, so differences of that size are within the fit’s own uncertainty.
The same quantity can appear in two sources. The PNAS figure takes its drift and size values from the two earlier papers, and the readings agree with them: 35.7 and 29.7 at three years against the printed 35.7 of the 2013 table and the 29.8 read from the size paper’s Figure 6B. At 40 and 80 years the markers of PNAS Figure 3B overlap, so those readings are coarse: the 80-year size-advantage marker reads 1.26 (1.01–1.52), the size paper’s own bar 1.12, the reconstruction 1.10. The drift rows depend on the counting convention: with mutant lineages only, every drift count would be about one lower at three years. The 2013 drift model uses the same 360-day year; it differs from this one in its strict 60% threshold (choices).
None of these differences changes the comparison between the mechanisms: at three years the transcription mechanism gives about one lineage and the two others about 30.
Rerunning the study
python examples/kk14/study.py compare --size full --ages 3 10 40 80 --threads 8 --resume --seed 20261121
python examples/kk14/study.py figures --results examples/kk14/results/full
python validation/check_kk14.py --output kk14-validation.json
The full tier writes its tables and figures to
examples/kk14/results/full/; the saved tables under
results/reconstruction/ are copies of that output. With one thread on a
two-core Intel x86-64 host shared with another job it took 2 hours 19
minutes (136 minutes of sampling); thread count does not change the
result, and --resume continues an interrupted run from its saved
batches. The draft tier (--size draft) runs the same steps with 240
and 800 calibration cells, no local refinement and 1,000 validation
cells.
The draft run came first (seed 20261120), on a 365-day year. Its fits
were not precise enough: 4 of its 24 primary rows have prevalence
intervals outside the band (10-year size advantage, validation, 133 of
1,000; and the 1,000-cell repeats of 40-year size advantage, 127; 40-year
transcription, 129; 80-year drift, 134). The full tier, with its local
refinement and confirmation points and a new seed, was set up after that
run. The draft results are kept in results/reconstruction/draft-*.csv
and draft-manifest.json as the record of that run; the band rule is the
same in both tiers, and a rerun of --size draft uses the 360-day year.
Next: Choices, checks and limits.
Choices, checks and limits
Part of tutorial S3.
Reconstruction choices
The papers describe their models in words, equations and figures. Where
they leave something open, the reconstruction had to choose. Three points
that the papers leave open were confirmed by an author of the papers
(personal communication, November 2026): mutant templates can mutate, a
year has 360 days, and a cell whose ATP reaches zero remains in that state
for the rest of the simulation, with fixed ATP, wild-type and mutant
counts. All choices are listed here; the sensitivity runs keep the fitted
rate and change one choice (1,000 new cells each, in
results/reconstruction/comparison.csv); for a confirmed point the
sensitivity shows what the other convention would give.
| Choice | What the papers say | Reconstruction | Effect where measured |
|---|---|---|---|
Maximal start probability r of the size model | Named (replS), no value | 1 per hour; C recomputed so the wild-type cell holds 1,000 copies | r = 0.1: wild type displaced after 831,793 instead of 831,783 h; 97 of 1,000 cells affected at 3 years, 30.41 lineages (29.30 with 20,000 cells at r = 1) |
| Copy count in the size model’s start probability | All copies | Free plus busy copies after that hour’s degradation, one probability per hour | not varied |
| Degradation probability per hour | Size paper: ln(2)/halfL. PNAS: not stated | Size model ln(2)/240; ATP model 1 - exp(-ln(2)/240) | 0.14% apart, not varied |
| Order within the ATP model’s hour | Lists degradation, replication, mutation and ATP production | In that order: replication only by copies that survived the hour; ATP relaxes for one hour with the new counts held fixed | 0.5-h step: 92 of 1,000 affected, 1.27 lineages |
| A cell whose ATP reaches zero | PNAS: “The system collapses”. Confirmed by an author: the cell remains in that state for the rest of the simulation, with fixed ATP, wild-type and mutant counts | The sampler stops the cell at that moment and keeps its counts and lineages; at the end of the lifespan it is classified and its lineages counted like any other cell. CRN-craft’s lower_bound=0 (stopped, counts kept, ATP 0 at later reports) does the same | Nearly all affected transcription cells are such cells (1,904 of 1,976 at 3 years). Without them only 72 of 18,096 cells are affected, with 1.03 lineages |
| Which templates can produce a deletion | Not stated in the papers. Confirmed by an author: mutants can mutate | Daughters of wild-type and mutant templates, in all three mechanisms (drift, size, transcription), in the reference sampler and in the native models (new_lineage, mutate_M) | Only wild-type templates (ATP model): 92 of 1,000 affected and 1.04 lineages instead of 1.26 |
| Year length | Not stated in the papers. Confirmed by an author: 360 days; tutorial S2 uses 360 days too. The size paper’s printed 19.33 years fits 365 days (open question, see limits) | 360 days: lifespans of 1,080, 3,600, 14,400 and 28,800 days | 365 days, 3 years: 108, 109 and 111 affected; 34.44, 29.59 and 1.32 lineages. 80 years: 111, 97 and 80; 1.51, 1.04 and 1.01 (drift, size, transcription) |
| 60% threshold | Text of both papers: “at least 60%”. Size paper figure captions and tutorial S2: more than 60% | At least 60% (5*M >= 3*(W+M)); the strict count is saved as well | The strict rule removes 38 drift and 2 size cells at 3 years, no transcription cell |
| What a “type” is | PNAS: different mutants. Size paper text: different mtDNAs. 2013 table: matches with wild type included | Mutant lineages; the wild type is added for the 2013 and PNAS drift values | Adds one type to almost every affected 3-year cell |
| Drift time course | 2013 program steps hourly | Continuous time, the exact pair rule of tutorial S2c | not varied |
| How the rate is adjusted | Adjusted until 10 ± 0.5% of 1,000 cells are affected | Logistic fit, then an independent 20,000-cell cohort (protocol) | — |
The ATP equations themselves are not a choice. They are Equations 1 to 3
of the PNAS paper, and the formula for c in its Table 1 evaluates to the
same 1.303.
Two of these points carry the transcription result, and an author of the papers confirmed both (personal communication, November 2026): a cell whose ATP runs out keeps its counts and is counted at the end of the lifespan, and mutant templates produce new deletions. With both, the reconstruction gives 1.26 lineages at three years, the value printed in the PNAS paper. With mutations from wild-type templates only it would give 1.04 (1,000 cells), and the affected cells would still be almost all cells that ran out of ATP.
How the reconstruction was checked
validation/check_kk14.py runs in CI and in a few seconds:
- Endpoints: the inclusive and strict threshold in integers, empty cells, and both type counts on hand-made endpoints.
- Deterministic targets: the ATP collapse (247.41 days ± 0.1), the wild-type displacement in hours (94.95 ± 0.05 printed years, converted with 365 days), the busy fractions, mesh convergence, and the 2-day, 10-h and 70% cases of the size paper’s Figures 3 to 5.
- Exact count law of drift: 16,000 eight-copy cells from the count
sampler, the lineage sampler and CRN-craft’s
treepair rule, each against the exact distribution from the matrix exponential. The largest empirical CDF gap must stay below the Dvoretzky–Kiefer–Wolfowitz bound for 16,000 cells at error probability 0.001 (0.0154). Observed: 0.0038, 0.0039 and 0.0069. - Hourly size queue: 16,000 eight-copy cells from the sampler against 16,000 from an independent per-copy Python implementation of the three hourly tasks, for wild-type count, mutant count and lineage count. The two-sample bound is twice the one-sample bound at 0.0005 (0.0322). Observed: 0.0081, 0.0077 and 0.0071.
- Replay and marking: the same cells with one and three threads, and with and without lineage marking, are identical; the native hybrid run with the lineage callback matches the run without it.
- Saved evidence: the sampler hash in the manifest matches
reference.cpp, all 12 fits are refitted on the 360-day year and the six 365-day sensitivity rows are present, the 42 reference rows are present, the three-year decision rule replays, the table of the results page equals the table generated from the saved CSV files, and the deterministic size rows on the models page equalsingle-cell.json.
The check does not rerun the tissue study and compares no simulated cell
with a saved value; its sampling checks use bounds. The saved results were
produced on one Intel Xeon x86-64 host (2.30 GHz, two cores) with GCC
13.3.0 and Python 3.13. They have not been replayed on a second host. A
byte-for-byte replay needs the same C++ standard
library and C math library: std::uniform_int_distribution and
std::binomial_distribution are implementation-defined, so libc++ (macOS)
draws different, equally valid cells.
Limits
- The original programs (Mathematica for the size paper, Java for the PNAS paper) were not available. Where the text is silent and no author confirmed the point, the table above is a choice, not a fact about the published runs.
- Open question for the authors: the size paper prints 19.33 years for a 10-h wild-type copying time. The reconstruction gives 169,333 h, which is 19.33 years of 365 days but 19.60 years of 360 days, and its other three deterministic times also fit 365 days at least as well (models). Perhaps the size paper’s deterministic program used 365 days while the PNAS tissue program used 360. The tissue comparison with the size paper’s Figures 6 and 7 assumes 360 days; the 365-day sensitivity above shows how much that matters.
- The values of PNAS Figure 3 and the size paper’s Figures 6 and 7 were read from the figures with an interval of ±2 pixels. In panel B of the PNAS figure the markers at 40 and 80 years overlap; they are read from their visible edges, and ±2 pixels is a quarter of a type there. The size paper has an erratum (doi:10.1016/j.jtbi.2014.02.008); its text was not available to the reconstruction.
- The size paper is not self-consistent in one place: its Results give almost 160 years for the 70%-size mutant, its Discussion almost 150 years for a mutant 30% shorter. The reconstruction gives 158 years.
- The published values have sampling errors that the papers do not report. The reconstruction’s intervals describe its own cells only.
- The full tier ran with one seed schedule; the draft tier with another, and on a 365-day year. Both are kept.
- Matching the published numbers does not validate a mechanism biologically. It shows that the models as reconstructed behave as the papers report.
Exercises
- Switch from the inclusive to the strict 60% boundary. Compare the
affected counts and lineage means in the saved
comparison.csv(columnsstrict_negativeandstrict_mutant_types). - Fit the size model again at a 2-day half-life. Predict the direction of the change in lineage diversity before viewing the fit. Figure 7 of the size paper reports 1.16 types per affected cell at this turnover. The saved refit gives 1.12 mutant lineages and 1,850 affected cells out of 20,000 (9.25%, an interval of 8.86–9.66%).
- Compare results with a 365-day year at 3 and 80 years, at the same
mutation probability. In the ATP model, check what happens when
mutations are permitted only from wild-type templates or when the
time step is halved.
compare --size quick --ages 3 --sensitivitiesruns all of these with 128 cells each in seconds,--size draftwith 1,000.
See also: Reproducing a published simulation, Limits and lessons of tutorial S2.
S4. Case study of spatial spread of mtDNA deletions
What this chapter reproduces
Tutorial O2 follows the takeover of a single cell. A skeletal muscle fiber is long and holds many local populations of mitochondrial DNA (mtDNA), each around its own nucleus. In aged fibers, regions full of one deletion mutant grow along the fiber. A 2022 paper asks whether such a mutant can spread even when it replicates no faster than the wild type:
Insalata F., Hoitzing H., Aryaman J., Jones N.S. (2022). Stochastic survival of the densest and mitochondrial DNA clonal expansion in aging. PNAS 119(49), e2122073119. doi:10.1073/pnas.2122073119 (Figures 1C, 2B and 2E)
The authors published their simulation outputs by figure, in a repository at revision 45462390. This chapter reads those files, simulates the model again, and compares. The paper’s authors did not write or review this chapter. The published supplement could not be opened for this review; the model details come from the paper, the headers of the archived files and the supplement of the first preprint (arXiv:2009.00403).
The paper’s model has no de novo mutations. Its reactions are birth, death and hopping of wild-type and mutant copies; no reaction makes a new mutant. Every simulation starts with mutants already present and follows their spread: the two-region runs of Figure 1C start both regions at a mutant fraction of 0.5, the wave of Figure 2E starts from a sigmoid front, and the founder simulations behind the paper’s Figure 4 start from one mutant copy (described in the supplement of the preprint as having “no additional mutational events”). The paper states that it focuses on “the mechanism by which a preexisting mutation reaches high heteroplasmy through clonal expansion”. Its estimate of a de novo mutation rate for human fibers (4.1 · 10⁻⁸ to 1.6 · 10⁻⁶ per replication) is derived from the founder’s takeover probability, not from simulations in which mutations keep arising, and the paper does not count mutant types. Pages 19b and 19c add de novo deletions to the model and count the types; they are an extension made in this guide, not a result of the paper. At 3 years an affected region then holds well over a thousand mutant types, with or without the density difference, about 820 at 10 years and about 110 at 80 years, at deletion rates far above the paper’s estimate; at 40 years the calibration failed.
The result in three lines:
- Figure 1C, two connected regions: fresh runs with 2,000 paths per condition reproduce all three neutral day-700 means within simultaneous 99% intervals, and the denser mutant gains 0.040 in mean mutant fraction.
- Figure 2E, the wave: the authors’ two archived profiles give 0.18973 µm/day. Every approximate cohort, from four step sizes and two copy numbers, gives 0.126 to 0.163 µm/day, and every 99% interval excludes 0.18973. This is an unresolved discrepancy.
- Most fresh wave runs use an approximate time-stepping scheme. A pilot of eight exact fibers gives 0.160 µm/day with a 99% interval of 0.064 to 0.199: with eight fibers this is inconclusive. The exact 800-fiber run (about 5 CPU-minutes per fiber with the local sampler) is outstanding. Copy number, boundaries, the birth-rate clipping and the step size were tested as causes and do not explain the gap (limits).
The model
Each region i holds W_i wild-type and M_i mutant copies. Every copy
dies at rate mu per day. Every copy of either type is copied at the same
per-copy rate
lambda_i = max(0, mu + c * (Nss - W_i - delta * M_i)),
so the region settles where W_i + delta * M_i = Nss. With delta < 1 a
region of mutants holds Nss / delta copies, more than a region of wild
types: the mutant is denser, not faster. Each copy hops to each neighbor at
rate gamma per day (a central copy leaves at 2 * gamma in total). A
hop is one reaction per genotype and directed edge, so it removes a copy at
the source and adds it at the destination. Here is that reaction alone.
import crn_craft as crn
model = crn.Model("one_hop")
model.add_species({"M0": 1, "M1": 0})
model.add_reaction(0.2, ["M0"], ["M1"], name="hop")
run = crn.ensemble(model, end=10, report_times=[0, 10], method="static_direct")
mean = run.simulate().statistics["mean"]
print(mean[["M0", "M1"]].sum(axis=1).astype(int).tolist())
[1, 1]
| Symbol | Figure 1C | Figure 2E | Source |
|---|---|---|---|
mu | 0.07/day | 0.07/day | paper, archive code |
c | 0.001/day | 0.0002/day | choice (value in the archived C code); Fig. 2 caption |
Nss | 150 copies | 3,500 copies | choice, matched to the archived spread; Fig. 2 caption |
delta | 0.5 (1 for equal density) | 0.2 | archive file headers; Fig. 2 caption |
gamma | 0.035/day (0 isolated) | 0.1/day | archive file headers; Fig. 2 caption |
| extra mutant death | 0.00007/day | none | header: 0.001 of mu |
| regions, spacing | 1 or 2 | 500, 30 µm | preprint supplement |
The mutant fraction of a region is h_i = M_i / (W_i + M_i). As in the
archive, it is computed in each path and region first, then averaged over
regions and paths with equal weight. No region became empty in the
Figure 1C runs.
Figure 1C: two connected regions
Each stochastic condition starts both regions at h = 0.5 on their steady
state (100 + 100 copies for delta = 0.5, 75 + 75 for delta = 1) and runs
2,000 paths for 700 days. The deterministic control has a closed form:
with equal per-copy birth rates, M / W decays as exp(-0.00007 t).
Rules fixed in the plan before the runs: compare the three neutral day-700 means with the archive using simultaneous 99% intervals (Bonferroni over four comparisons); require a positive contrast between higher and equal mutant density. The archive gives one standard error per region but not their covariance, so the archived error of the two-region mean is bounded above by the average of the two regional errors.
| Condition at day 700 | Archived mean | Fresh mean | Fresh minus archive | Simultaneous 99% interval |
|---|---|---|---|---|
| Isolated, neutral | 0.50300 | 0.50570 | +0.00269 | -0.02653 to +0.03192 |
| Equal density, neutral | 0.49944 | 0.49654 | -0.00290 | -0.02863 to +0.02283 |
| Higher mutant density, neutral | 0.54026 | 0.53652 | -0.00374 | -0.02589 to +0.01840 |
| Deterministic, mutants degraded faster | 0.49300 | 0.48775 | -0.00525 | not tested |
| Isolated, mutants degraded faster | 0.48246 | 0.48876 | +0.00630 | not tested |
| Equal density, mutants degraded faster | 0.48493 | 0.49461 | +0.00968 | not tested |
| Higher mutant density, mutants degraded faster | 0.52123 | 0.51653 | -0.00470 | not tested |
All three neutral intervals contain zero. This is a failure to find a difference, and the test is coarse: it would detect only differences larger than about 0.022 to 0.032. The higher-density mean exceeds the equal-density mean by 0.0400, with a simultaneous lower bound of 0.0161. That is stochastic survival of the densest: the denser mutant gains without a replicative advantage, even when it is degraded faster.
The archived deterministic curve with faster mutant degradation falls on a
straight line, 0.5 - 0.00001 t. The stated model gives
1 / (1 + exp(0.00007 t)), 0.48775 at day 700. The cause of this
difference of 0.00525 is unknown.
The figure overlays two sources in each panel:
- Lines are computed here: the mean mutant fraction over the 2,000 paths of the saved draft run at days 0, 140, …, 700, joined by straight segments. In the deterministic panel the line is the closed form, not a simulation.
- Points are the authors’ archived curves, the data behind the paper’s Figure 1C. Each bar is the upper bound of the archived standard error described above; the fresh runs carry no bars.
Blue is the neutral case, red the case with mutants degraded faster. A point away from its line of the same color is therefore a difference between this reconstruction and the archive, and the table gives its size at day 700.

Figure 2E: the traveling front
The archive holds the ensemble-mean profile at day 0 and day 1,480 over a window of 139 and 140 regions. Find the descending crossing of 0.5 in each, interpolating linearly between neighboring regions, and divide the displacement by 1,480 days. The crossing moves from 1,695.52 to 1,976.33 µm, 280.80 µm in all, giving 0.18973 µm/day. At 0.4 and 0.6 the same profiles give 0.20354 and 0.17469 µm/day; the profile flattens as it moves.

The archived day-0 profile is exactly the supplement’s start,
h(x) = 1 / (1 + exp(0.000715 x - 3.915)), shifted by 3,780 µm (126
regions). The fresh chain uses that start over 500 regions, holds the
leftmost region at h = 1 as a fixed reservoir, and sets h < 0.005 to
zero. A diffusing copy travels about 520 µm in 1,480 days, far less than
the 5,475 µm from the front to the reservoir, so the boundaries cannot
shape the front.
The plan fixed an equivalence margin of ±0.03 µm/day around the archived speed and a bootstrap over whole fibers. An interval inside the margin is numerical agreement; an interval that excludes the archived speed is an unresolved discrepancy; anything else is inconclusive.
| Source of the profiles | Fibers | Half-height speed (µm/day) | 99% interval | Label |
|---|---|---|---|---|
| Authors’ archive, days 0 and 1,480 | 800 | 0.18973 | not available | reference |
| Same chain without noise (Nss = 3,500) | none | 0.04199 | none | deterministic part |
| Approximate, 0.5-day step, Nss = 3,500 | 48 | 0.12753 | 0.10504–0.15397 | unresolved discrepancy |
| Approximate, 0.25-day step, Nss = 3,500 | 48 | 0.16271 | 0.13014–0.18822 | unresolved discrepancy |
| Approximate, 0.125-day step, Nss = 3,500 | 96 | 0.14617 | 0.13016–0.16360 | unresolved discrepancy |
| Approximate, 0.0625-day step, Nss = 3,500 | 32 | 0.14921 | 0.12571–0.17367 | unresolved discrepancy |
| Approximate, 0.5-day step, Nss = 3,500, second cohort | 32 | 0.12579 | 0.09678–0.15338 | unresolved discrepancy |
| Approximate, 0.125-day step, Nss = 3,000 | 96 | 0.14293 | 0.12424–0.16245 | unresolved discrepancy |
| Exact (local sampler), Nss = 3,500, pilot | 8 | 0.15951 | 0.06445–0.19865 | inconclusive |
The approximate rows come from the scheme of wave.py. The last row
comes from eight exact fibers of the local sampler (spatial_turnover),
fibers 0 to 7 of the 800-fiber design, with the same estimator: the
three-bin smoother and 700 whole-fiber resamples. Its interval contains
the archived speed and is wider than the ±0.03 µm/day margin, so eight
fibers cannot decide between the approximate cohorts and the archive.
Averaged over the whole profile, the eight exact fibers gain
0.148 µm/day (99% interval 0.097 to 0.198, t with 7 degrees of
freedom), close to the approximate cohorts’ 0.128 to 0.141. The
two 0.5-day cohorts agree (0.128 and 0.126). Averaged
over the whole profile, the step effect between 0.5 and 0.0625 days is
−0.013 µm/day (99% interval −0.027 to +0.000). The last three rows are review runs; the limits page
gives their targets, which were fixed before the runs. Even without noise
the chain moves its half-height crossing by 0.042 µm/day: mutant copies
diffuse out of the denser region. Noise adds the rest.

The paper also fits the lengths of abnormal fiber regions against age in rhesus monkeys (Figure 2B) and reports 0.131 ± 0.025 µm/day from that linear fit. The paper does not say whether ± is a standard error. That number is an observation, not a simulation, and nothing here is fitted to it. The paper reports its simulated speed as about 0.2 µm/day.
Running the example
| Size | Command | What it does | Time on one core |
|---|---|---|---|
| quick | python examples/mtdna_spread/study.py --size quick | 128 two-region paths, short chain, archived crossings | 2 s |
| draft | python examples/mtdna_spread/study.py --size draft | Figure 1C with 2,000 paths per condition | 1 min |
| wave | python examples/mtdna_spread/wave.py --fibers 96 --step 0.125 | approximate fiber cohort | 7 to 12 min |
| full | python examples/mtdna_spread/study.py --source-chain --wave-sampler local --fibers 800 --threads N | exact fibers, checkpointed | about 55 to 65 CPU-hours (estimate) |
A run writes tables, not figures. Drawing is a second command, and it
reads the tables saved in examples/mtdna_spread/results unless
--output names the folder of a run:
# the figures of this page, from the saved tables
python examples/mtdna_spread/study.py --figures examples/mtdna_spread/runs/figures
# the same figures from a run of your own
python examples/mtdna_spread/study.py --size draft --output examples/mtdna_spread/runs/draft
python examples/mtdna_spread/study.py --figures examples/mtdna_spread/runs/figures --output examples/mtdna_spread/runs/draft
python validation/check_mtdna_spread.py checks the laws, the archive
reader and the tables of this page. The
example README lists the files.
Choices, checks and limits lists every reconstruction choice and the review experiments. De novo deletions and mutant types and its results are the extension of this guide described above. Tutorial S5 uses the same mutant fraction to measure how different cells become over time.
Choices, checks and limits
This page belongs to tutorial S4. It lists what the paper and the authors’ files leave open, the checks that guard the example, and the review experiments on the Figure 2E speed.
Reconstruction choices
| Choice | Value used | Alternative | Measured effect |
|---|---|---|---|
Figure 1C Nss and c (not in the archive headers) | 150 and 0.001/day in every panel | equal density with Nss = 200 | with 200, the per-region spread at day 700 is 15% below the archive’s; with 150 it is within 2% |
| Figure 1C start | h = 0.5 on the steady state | other copy numbers | not run |
| Faster mutant degradation | 0.07 * 0.001 per day extra | header “0.001 µ” read otherwise | the archived deterministic curve is not reproduced (−0.005 at day 700) |
| Hop rate | gamma per copy and directed edge | gamma in total | the archived C code and notebook use per edge |
| Birth-rate clipping | max(0, …) | the archived C code never clips | none: the clip needs a fluctuation of about 9 (Figure 1C) or 40 (Figure 2E) standard deviations |
Figure 2E Nss | 3,500 (Figure 2 caption) | 3,000 (preprint supplement) | 0.143 vs 0.146 µm/day, within cohort noise |
| Chain length and spacing | 500 regions of 30 µm | not stated in the paper | the archived day-0 window matches this geometry |
| Left boundary | fixed reservoir at h = 1 | dynamic region held at h = 1 | none expected: diffusion reaches about 520 µm |
| Window alignment | both archive files start at the same region | shifted by one region | one region moves the archived speed by 0.020 µm/day; not testable from the files |
| Wave estimator | crossing of the ensemble-mean profile, three-point smoother | no smoother | at most 0.004 µm/day |
| Wave simulator | approximate steps of 0.0625 to 0.5 days | exact path simulation | eight exact fibers: 0.160 µm/day (99% interval 0.064–0.199), inconclusive; 800 fibers outstanding |
The approximate wave scheme
wave.py advances all regions in steps of dt. Within a step it holds
the birth rate of each region at its start-of-step value. Births are
Poisson draws from the start-of-step counts. Deaths and hops compete for
the same start-of-step copies, so each copy leaves at most once per step,
and copies born in the step can neither die nor hop. Counts cannot become
negative. The scheme is first order in dt.
Review experiments on the speed gap
Targets and decision rules were written down before each run. The rows are
in results/review-experiments.csv; review.py reruns them.
-
Deterministic part (
review.py deterministic). The noise-free chain moves its half-height crossing at 0.04199 µm/day forNss = 3,500and 0.04196 for 3,000. The mean of the step scheme gives 0.03932 at a 0.5-day step and 0.04130 at 0.125 days. Step bias in the mean is therefore at most 0.003 µm/day. -
Copy number (
review.py cohort, 96 fibers, 0.125-day step).Nss = 3,000gives 0.14293 µm/day (99% interval 0.12424–0.16245). The interval excludes 0.18973, so the copy number alone does not explain the gap. Label: unresolved discrepancy. -
Smaller step (32 fibers, 0.0625-day step). 0.14921 µm/day (0.12571–0.17367): the gap persists at half the smallest delivered step. Label: unresolved discrepancy.
-
Step effect on the whole profile (32 fibers at 0.5 and 0.0625 days). The mean area gained by the mutant, divided by 1,480 days, is 0.12816 and 0.14140 µm/day. The difference, −0.0132 (99% interval −0.0266 to +0.0002), includes zero but is not shown to be below 0.02. Label: inconclusive.
-
Noise of the scheme against the exact simulator (
review.py noise; 16 exact fibers, 64 approximate fibers per step, 20 days, full geometry). The variance of the regional mutant fraction over the 274 front regions has a ratio approximate/exact of 0.987 (99% interval 0.949–1.189) at 0.125 days and 0.981 (0.940–1.178) at 0.5 days. The scheme shows no sign of distorting the local noise that drives the spread. -
Equal-density setting (
review.py equal). See the first row of the choices table; the shipped Figure 1C results useNss = 150. -
Exact pilot (
study.py --source-chain --wave-sampler local --fibers 8). Eight exact fibers of the full chain, fibers 0 to 7 of the 800-fiber design. Half-height speed 0.15951 µm/day (99% interval 0.06445–0.19865, no ambiguous resample). Label: inconclusive. Without the smoother, the eight-fiber mean profile crosses 0.5 twice (at 5,699 and 5,731 µm), and 100 of 500 resamples are ambiguous. The fibers are inresults/exact-wave-fibers.csv.
What remains: the exact simulator over 1,480 days was run for eight fibers, not 800, and the authors’ Figure 2E run itself is not documented in the archive (no run time, no step, no window position). Before the full exact run, the most informative check is whether the authors’ two profile windows start at the same region.
Checks
validation/check_mtdna_spread.py runs in a few seconds without network
access. It checks:
- the reference reader: 48 Figure 1C rows and the three day-700 means; 139 + 140 Figure 2E rows, the crossings 1,695.52 and 1,976.33 µm, and the speeds 0.18973, 0.2035 and 0.1747 µm/day at 0.5, 0.4 and 0.6;
- the exact law of one copy hopping between two regions (finite state
projection,
(1 - exp(-0.8)) / 2at day 2) and conservation of each genotype under migration alone; - the row counts of every saved result table;
- that both tables of tutorial S4 equal the saved results;
- for the extension of pages 19b and 19c: the exact bookkeeping laws of the lineage sampler, a moment law, the quick calibration, the saved tables and the two generated tables of page S4c.
Limits
- The paper’s model has no de novo mutations: every run starts with mutants present. Pages S4b and S4c add them as an extension of this guide.
- The published supplement was not reachable for this review. Chain length, spacing, initial profile and boundary handling come from the first preprint’s supplement; they match the archived day-0 profile exactly.
- The archive’s Figure 1C files do not state
Nssorc. The values used reproduce the archived means and per-region spread, but they are inferred. - The archived speed has its own sampling error from 800 fibers, which the archive does not report. From the spread of the fresh fibers it is about 0.002 µm/day, too small to close the gap.
- The upstream repository has no license file. The two reference tables
are short numerical extracts of its data. They are not covered by this
repository’s MIT license and stay under the authors’ terms
(notice);
fetch.pyregenerates them from the pinned revision. - The rhesus speed of Figure 2B is an observation from another study. The data are not in the archive and were not refitted.
Exercises
- Change
--stepinwave.pyand plot the half-height speed against the step. How many fibers do you need before the step effect is larger than the cohort noise? - Remove the noise:
review.py deterministicgives the speed without survival of the densest. Why does the crossing at 0.4 move faster than the crossing at 0.6? - Run
study.py --source-chain --wave-sampler local --fibers 1(about 5 minutes) and compare the single fiber’s crossing with the spread of the approximate fibers.
De novo deletions and the number of mutant types
Part of tutorial S4.
This page is an extension made in this guide. It is not a result of the paper, and no author of any of the papers cited here wrote or reviewed it. The question was suggested by an author of the papers behind tutorials S2 and S3 (personal communication, November 2026).
The question
The paper of tutorial S4 starts every simulation with mutants already present and follows their spread; it has no de novo mutations (tutorial S4). Tutorials S2c and S3 rest on an argument that needs de novo mutations. In a short-lived animal, a mechanism of clonal expansion must take over an affected cell within the lifespan. If it needs a high deletion rate to do so, the affected cells hold many different mutants, whereas the experiments these papers cite find essentially one deletion type per affected cell. Kowald & Kirkwood (2013, Aging Cell 12:728–731, doi:10.1111/acel.12098) and (2014, PNAS 111:2972–2977, doi:10.1073/pnas.1314970111) used this to compare mechanisms: tutorial S3b finds about 35 mutant types per affected cell for neutral drift at 3 years and about 1.26 for transcription-linked replication. The paper of tutorial S4 uses the same argument against neutral models: their high de novo rates “produce an unrealistically high mutational diversity, at odds with the observed clonality” (section “Low Mutation Rates Can Yield Large Mutant Loads”). It does not simulate the diversity of its own model.
This page asks the same question of stochastic survival of the densest: with the paper’s Figure 2 parameters, no mutants at the start and new deletions at replication, how many different mutant types does an affected region hold after 3 years, and after a human lifespan?
The model
The chain of tutorial S4 with the Figure 2
parameters: death rate mu = 0.07/day, feedback c = 0.0002/day, Nss =
3,500 copies, delta = 0.2, hop rate gamma = 0.1/day per copy and
directed edge, regions of 30 µm. One reaction is added:
- De novo deletion. At every replication, of a wild-type or a mutant
template, the daughter is a new deletion type with probability
m; otherwise it copies its template’s type. Every new type gets a label never used before (infinite alleles). A deletion of a mutant is a new type. - All mutant types are alike. Each has the paper’s density parameter
delta= 0.2. The model does not know which part of the genome a deletion removes.
Every region starts with 3,500 wild-type copies and no mutant. Time runs in days; a year has 360 days, as in tutorial S2. The protocol named 3 years (1,080 days), the case of a short-lived animal, as the essential lifespan, and 10, 40 and 80 years as lifespans to add if the compute budget allowed. All three cases are run at 3 years; the denser mutant is also run at 10, 40 and 80 years (3,600, 14,400 and 28,800 days).
Geometry. A fiber is a chain of 32 regions (960 µm) with closed ends: a copy in an end region has one neighbor and hops only inward, as in the authors’ archived C code. A copy hops at 0.2 per day in total, so over 1,080 days its position spreads with a standard deviation of about √(0.2 × 1,080) ≈ 15 regions: within 3 years, the copies of one region mix with about half the chain. A longer fiber would add regions whose neighborhoods are like those of the central regions here; it would change little per region, add more regions per fiber, and raise the number of types in a whole segment roughly in proportion to its length. A run with 64 regions tests this on the results page. At 40 and 80 years the spread is √(0.2 × 14,400) ≈ 54 and √(0.2 × 28,800) ≈ 76 regions, longer than the chain: the copies of every region mix with the whole fiber, and the fiber, not the region, becomes the unit that varies. The results page shows what this does to the calibration.
Units. A region is affected when at least 60% of its copies are
mutants (5*M >= 3*(W+M), as in tutorial S3); its types are the different
mutant labels among its copies. A zone is a maximal run of adjacent
affected regions in one fiber; its types are counted among all copies of
the zone. A segment is the whole 32-region fiber; its types are counted
among all its copies. The 10% target applies to regions. A region is not a
cell in the sense of tutorials S2 and S3: it is the domain of one nucleus in
a long fiber, it holds 3,500 copies instead of 1,000, and it exchanges
copies with its neighbors.
Three cases. Denser mutant is the model above. Equal density sets
delta = 1, the neutral control: same chain, same hopping, no survival of
the densest. Isolated regions sets gamma = 0: every region is a closed
population of 3,500 copies, the closest analog of a cell in tutorials S2
and S3.
The simulator
Every copy in region i, wild type or mutant, of any type, is copied at
the same rate lambda_i = max(0, mu + c * (Nss - W_i - delta * M_i)), dies
at mu and hops at gamma per neighbor. The type only matters for the
counts that set lambda_i. So an exact path needs no rate per type: pick a
region with probability proportional to its total rate, pick one of its
copies uniformly, and let that copy be copied, die or hop. mutations.py
does exactly this (Gillespie’s direct method over regions) and keeps one
label per copy. It stores the labels of a region with the mutants first,
so the run without labels draws the same random numbers and gives the same
counts; the check compares both runs exactly.
CRN-craft can write this model directly: one species mtDNA with the
attributes clone and region, new_id() for a new deletion, a hop rule
that changes region, and per-region observables with reduce="distinct"
for the types (crn_model in mutations.py). Only the tree method runs
species created during a run, and it recomputes every rule after every
event. With 32 regions of 3,500 copies it took 9.6 µs per event on the
two-core host of this study; the example-local sampler takes about 0.12 µs
with Numba. A 3-year fiber has about 56 million events: about 9 minutes on
CRN-craft, 7 seconds in the sampler. The CRN-craft model serves as the
reference for the sampler on a small chain.
How the sampler was checked
Targets and pass rules were written down before these runs; the rows are
in results/de-novo-sampler.csv.
- Against CRN-craft. A small chain (3 regions,
Nss= 20,c= 0.01/day,m= 0.02, 60 days, the other rates as above): 20,000 paths from the sampler and 20,000 from the CRN-craft model ontree. The largest gap between the two empirical distribution functions must stay below the two-sample Dvoretzky–Kiefer–Wolfowitz bound at error probability 0.001, 0.0288, as in tutorial S3c. Observed: 0.0068 (wild type in region 0), 0.0042 and 0.0047 (mutants in regions 0 and 1), 0.0041 (types in region 0) and 0.0023 (types in the fiber). Types in the fiber are counted from CRN-craft’s final instances: itsdistinctobservable counts instances, that is pairs of type and region. - A moment law. With
c= 0 every copy is copied at exactlymu, so a copy is replaced by a new type at ratem * muand the expected mutant count isL * Nss * (1 - exp(-m * mu * t)); the expected number of deletions ism * mu * L * Nss * t. 4,000 paths of 4 regions of 50 copies (m= 0.05, 100 days): z = −0.41 and −0.01. - Exact laws in the check. Labels on and off give identical counts and event totals; each region holds one label per mutant copy, every label is a type that was made; births minus deaths equal the change of the copy number; hops alone change nothing.
The sampler has no time step, so the stepping error of wave.py does not
arise here.
The protocol
Written down before any calibration run (and recorded in the example’s
manifest.json, entry de_novo), in the order of tutorial S3b,
with fewer units because a fiber costs seconds rather than a millisecond:
- Target: 10% of regions affected at the end of the lifespan (1,080 days for 3 years). A prevalence interval is within the band if it lies inside 9.5–10.5%, compatible if it intersects it, and outside otherwise.
- Fit: a start value of
mfrom one probe fiber, then 4 fibers (128 regions) at 0.9, 0.97, 1.04 and 1.12 times it, extended until the points enclose 10%; then 8 fibers (256 regions) at 1/1.02, 1 and 1.02 times the logistic inverse at 10%. The fittedminverts a logistic regression of the affected indicator onlog10(m)through all fit regions. Only the affected indicator enters the fit, never a type count. - Validation: 32 new fibers (1,024 regions) at the frozen
m, with their own seeds (a hash of the manifest seed, case, size, lifespan, phase,mand fiber index). Prevalence gets a 95% Wilson interval, which treats regions as independent, and a 95% percentile bootstrap interval over whole fibers (1,999 resamples), which does not. Means per region, zone and segment get the fiber bootstrap. - Refit rule: a validation outside the band is kept. One refit is
allowed: stage 2 again with new seeds around the first
m, a fit through all fit points, and a second validation cohort. Both are reported. - Statement rule: a 95% interval of the mean types per affected region below 2 reads “about one type, like the transcription mechanism”; above 10 reads “many types, like drift”; otherwise “intermediate”. Fewer than 20 affected regions: no statement.
Regions of one fiber share copies, so they are far from independent. The Wilson interval is therefore too narrow, and with only 32 fibers the prevalence of a cohort scatters more than the band allows; the bootstrap over fibers shows by how much. The same holds for the fit, whose logistic regression also treats regions as independent. The longer the lifespan, the stronger the effect: at 40 and 80 years whole fibers are affected or not, and the protocol, written for 3 years, no longer pins the prevalence.
A design for long lifespans
At 40 and 80 years the first protocol has about as many independent units
as fibers, 32 per cohort, while its fit and its band count 1,024 regions
(results page).
A second design, mutations.py run --design fibers, makes the fiber the
sampling unit everywhere. It was written down before any run of it, in
manifest.json (entry de_novo_fibers) and here. The first design, its
code path (the default, --design regions) and its saved tables stay as
they are.
What stays the same. The target is still 10% of regions with at least 60% mutants at the end of the lifespan, so the rows of both designs can be compared. The model, the parameters, the 32-region chain with closed ends, the three cases, the year of 360 days, the units, the statement rule and the seed rule are those above.
Fit. Stage 1 simulates 16 fibers at each of 0.92, 0.97, 1.03 and 1.09
times a start value of m. At a logistic slope of 20 to 30 per decade of
m this spans about 5% to 19% affected regions. The grid is extended by
factors of 1.25, as above, until it encloses 10%. Stage 2 simulates 32
fibers at 1/1.03, 1 and 1.03 times the stage-1 estimate. The start value
is the last fitted m of the first design for the same case and lifespan
(results/de-novo-rates.csv) where there is one, and otherwise the probe
fiber of the first design. The point estimate is the same logistic
regression of the region indicator on log10(m). Its 95% interval comes
from a bootstrap over fibers: within each fit point, whole fibers are
resampled, the curve is refitted and inverted at 10%, 1,999 times. A
resample whose fit has no positive slope counts at both ends of the
interval, so it can only widen it. A fit through all points without a
positive slope, or whose inverse lies outside the range of the fit points,
ends the calibration as failed; at stage 1 such a fit puts stage 2 at the
geometric mean of the stage-1 values. (This rule was added after a run of
the small quick-size model extrapolated far beyond its fit points, before
any run of the draft or full size.)
Validation. 128 new fibers at the frozen m. The cohort is
compatible if the 95% bootstrap interval over fibers of the share of
affected regions contains 10% and at least 10 fibers hold an affected
region. Otherwise it is outside (the interval excludes 10%) or has too
few affected fibers. There is no band of ±0.5 points: with 128 fibers that
behave as single units, the prevalence of a cohort cannot be pinned that
closely. The Wilson interval is still reported, and it assumes independent
regions. The statement on the number of types needs at least 20 affected
regions in at least 10 fibers; otherwise none is made. This excludes the
one-fiber case of the first design at 40 years.
Refit. One refit is allowed if the first cohort is not compatible:
three new stage-2 points of 32 fibers around the m fitted through all
points, a fit through all points, and a new cohort of 128 fibers. If that
one is not compatible either, the calibration failed. All rows are kept.
Fallback cohort. A calibration that ends with a failed fit (at the
first or the second attempt) has no validation cohort and so no count of
types. Such a run still simulates one cohort of 128 fibers, at the fit
point of the last stage 2 whose observed share of affected regions is
closest to 10% (on a tie, the smaller m), with its own phase
(fibers-fallback) and seeds. Its summary row reads “calibration failed,
fallback cohort” and reports the same measures as a validation cohort; the
statement rule applies unchanged. The calibration stays failed, and the row
is never compatible: a fallback cohort measures the types at whatever
prevalence it happens to have, not at a calibrated 10%. (This was added
before any run of the draft or full size.)
Seeds and tables. The phases have their own names (fibers-stage1,
fibers-validation and so on), so no fiber of the first design is reused
and no checkpoint is shared. The tables are de-novo-fibers-*.csv, with
the columns of the first design and, in addition, the fibers with an
affected region (fibers_affected), the fibers affected along their whole
length (fibers_full), the bootstrap interval of m over fibers
(m_boot_low95, m_boot_high95) and the label of the cohort
(decision). The columns m_low95, m_high95 (regression, regions
independent) and band (the first design’s rule) are kept for comparison
only.
Size and cost. Without a refit the design simulates 4 × 16 + 3 × 32 + 128 = 288 fibers, with one 512. A 32-region fiber costs about 170 CPU-seconds at 40 years and 330 at 80 years with Numba on the machine that made the first 40- and 80-year runs. That is about 13 to 24 CPU-hours at 40 years and 27 to 47 at 80 years. A fallback cohort takes the place of a validation cohort and adds no fibers to these counts. The quick size (4, 8 and 32 fibers of the small model, at least 3 affected fibers) runs in seconds in pure Python; the draft size (2, 4 and 16 fibers, at least 3) takes minutes at 3 years.
Longer-chain control. Whether 32 regions are long enough is tested
once: 32 fibers of 128 regions at the m of the fiber design, 80 years,
the denser mutant (mutations.py length, about 12 CPU-hours). If the 95%
intervals of types per affected region of the 32- and the 128-region
cohorts do not overlap, the result reads “chain length matters”, otherwise
“no difference seen”. If either cohort has fewer than 10 affected fibers,
no statement is made.
How well the design calibrates: synthetic fibers
Before any simulated run, the fit and the validation rule were tried on
fibers drawn from a known curve, with no simulation
(mutations.py coverage, about 3 minutes; targets and rules written
down first). The share of affected regions follows a logistic curve in
log10(m) with a slope of 25 per decade and 10% at a true m. In the
whole fibers scenario a fiber is affected along all 32 regions or not at
all, as at 40 and 80 years. In the partly clustered scenario the regions
of a fiber share a random probability (intra-fiber correlation 0.2, a
design effect of about 7, as at 3 and 10 years). Every repetition runs the
design’s own code at the full size: 16 and 32 fibers per fit point, 128 per
cohort, 1,999 resamples, a start value up to 7% from the true m. 400
repetitions per scenario; the intervals are 95% Wilson intervals of the
shares (results/review-fiber-fit-coverage.csv):
| Experiment, quantity | Whole fibers | Partly clustered |
|---|---|---|
| T4 fit interval: coverage of true m, fiber bootstrap | 0.810 (0.769–0.845), undercovers | 0.907 (0.875–0.932) |
| T4 fit interval: coverage of true m, regions independent | 0.235 (0.196–0.279) | 0.560 (0.511–0.608) |
| T4 fit interval: median width / true m, fiber bootstrap | 0.126 | 0.0498 |
| T4 fit interval: median width / true m, regions independent | 0.0158 | 0.0178 |
| T4 fit interval: failed point fits (no positive slope or inverse outside the fit points) | 43 | 10 |
| T4 fit interval: share of failed bootstrap refits | 0.0193 | 0.0016 |
| T5 validation rule at the true m: fiber interval of prevalence contains 0.10 | 0.943 (0.915–0.961) | 0.935 (0.906–0.955) |
| T5 validation rule at the true m: at least 10 affected fibers | 0.838 (0.798–0.870) | 1.000 (0.990–1.000) |
| T5 validation rule at the true m: compatible | 0.820 (0.779–0.855) | 0.935 (0.906–0.955) |
| T6 end to end, R0: done at attempt 1 | 0.660 (0.612–0.705) | 0.858 (0.820–0.888) |
| T6 end to end, R0: done at attempt 2 | 0.180 (0.145–0.221) | 0.117 (0.090–0.153) |
| T6 end to end, R0: failed calibrations | 0.160 (0.127–0.199) | 0.025 (0.014–0.045) |
| T6 end to end, R0: coverage of true m, fiber bootstrap of the last fit | 0.848 (0.809–0.879) | 0.948 (0.921–0.965) |
| T6 end to end, R0: median error of m in done calibrations (%) | 1.52 | 0.79 |
| T6 end to end, R1: done at attempt 1 | 0.660 (0.612–0.705) | 0.858 (0.820–0.888) |
| T6 end to end, R1: done at attempt 2 | 0.212 (0.175–0.255) | 0.120 (0.092–0.156) |
| T6 end to end, R1: failed calibrations | 0.128 (0.098–0.164) | 0.022 (0.012–0.042) |
| T6 end to end, R1: coverage of true m, fiber bootstrap of the last fit | 0.897 (0.864–0.924) | 0.950 (0.924–0.967) |
| T6 end to end, R1: median error of m in done calibrations (%) | 1.52 | 0.788 |
| T6 decision: R1 replaces R0 (last-fit coverage >= 0.90, no more failures) | 0, R0 kept | – |
| T7 fallback cohort, R0: fit-failed calibrations with a fallback cohort | 40 | 1 |
| T7 fallback cohort, R0: true prevalence at the fallback point, median | 0.0893 | 0.095 |
| T7 fallback cohort, R0: true prevalence at the fallback point, 2.5% quantile | 0.0436 | 0.095 |
| T7 fallback cohort, R0: true prevalence at the fallback point, 97.5% quantile | 0.218 | 0.095 |
| T7 fallback cohort, R0: share of fallback cohorts with at least 10 affected fibers | 0.750 (0.598–0.858) | 1.000 (0.207–1.000) |
The fit interval (T4). When whole fibers are affected or not, the
interval of the first design’s regression, which treats regions as
independent, contains the true m in only 23.5% of the repetitions; its
median width is 1.6% of m. The bootstrap over fibers is eight times
wider and contains the true m in 81%. That is below the 90% the rule
asked for, so by the rule declared before the run it undercovers. Most of
the gap comes from the 43 repetitions (11%) whose fit through all points
fails, counted as not covered: in 39 of them the inverse lies just outside
the range of the fit points. Among the other 357, the interval covers in
324 (91%); this split was not declared in advance. With partial clustering
the bootstrap covers in 91%, the regression in 56%.
The validation rule at the true m (T5). With whole fibers, a cohort
of 128 fibers at exactly the right m is compatible in 82% of the
repetitions: its prevalence interval contains 10% in 94%, but in 16% fewer
than 10 fibers hold an affected region (12.8 are expected). So about one
cohort in five triggers the refit even at the right m.
End to end (T6). The whole procedure, fit, validation and refit, ends
with a compatible cohort in 84% of the repetitions with whole fibers (66%
at the first cohort) and in 97.5% with partial clustering. A done
calibration misses the true m by 1.5% (median) with whole fibers and 0.8%
with partial clustering. After the result of T4, one change was tested,
written down before its run: revision R1 lets a failed fit at attempt 1
lead to the refit instead of ending the calibration. R1 lowers the failed
calibrations with whole fibers from 16% to 13% and raises the coverage of
the last fit from 85% to 90% (0.8975). The rule asked for at least 0.90, so
R1 was not adopted, and the full runs use the design as declared (R0). Its
interval of m is honest only to about 85% with whole fibers; the
validation cohort, not the fit interval, decides whether m is accepted.
What a fallback cohort is worth (T7). In the same end-to-end runs of R0 (rule written down before the run), 40 of the 400 calibrations with whole fibers end with a failed fit and get a fallback cohort; the other 24 failures have two cohorts that are not compatible. At the fallback points the true share of affected regions has a median of 8.9% (2.5% to 97.5% range: 4.4% to 21.8%), and 75% of the fallback cohorts have at least 10 affected fibers, so the statement rule can apply to them. With partial clustering one calibration ends this way. A fallback cohort therefore measures the types at a prevalence near, but not at, 10%.
Next: results and limits.
De novo deletions: results and limits
Part of tutorial S4; the model and the protocol are on page S4b.
This page is an extension made in this guide. It is not a result of the paper, and no author of any of the papers cited here wrote or reviewed it.
Results
The validation cohorts, 32 fibers of 32 regions each, at 1,080 days (3
years) and, for the denser mutant only, at 3,600, 14,400 and 28,800 days
(10, 40 and 80 years). The 40- and 80-year rows come from a second machine
(below); at 40 years the calibration failed.
Tutorial S3’s rows are its 20,000-cell validation cohorts at the same ages
of 360 days, for comparison of the layout and the order of magnitude only (the
table is generated from results/de-novo-summary.csv and tutorial S3’s
comparison.csv, and checked by validation/check_mtdna_spread.py):
| Age | Mechanism and unit | m per replication | Affected / units | Prevalence (95% Wilson) | Mutant types (95% bootstrap) | Target band |
|---|---|---|---|---|---|---|
| 3 y | Survival of the densest, 32 regions (this guide), first fit | 0.0113 | 232 / 1024 regions | 22.66% (20.20–25.32%) | 1487 (1445–1516) | outside |
| 3 y | Survival of the densest, 32 regions (this guide), refit | 0.01117 | 82 / 1024 regions | 8.01% (6.50–9.83%) | 1456 (1418–1487) | compatible |
| 3 y | Equal density, 32 regions (this guide), first fit | 0.01133 | 146 / 1024 regions | 14.26% (12.25–16.53%) | 798 (778–813) | outside |
| 3 y | Equal density, 32 regions (this guide), refit | 0.01133 | 114 / 1024 regions | 11.13% (9.35–13.21%) | 816 (795–832) | compatible |
| 3 y | Survival of the densest, isolated regions (this guide), first fit | 0.009855 | 104 / 1024 regions | 10.16% (8.45–12.16%) | 271 (267–275) | compatible |
| 10 y | Survival of the densest, 32 regions (this guide), first fit | 0.002966 | 37 / 1024 regions | 3.61% (2.63–4.94%) | 849 (763–866) | outside |
| 10 y | Survival of the densest, 32 regions (this guide), refit | 0.003 | 83 / 1024 regions | 8.11% (6.59–9.94%) | 817 (767–856) | compatible |
| 40 y | Survival of the densest, 32 regions (this guide), first fit | 0.0004732 | 0 / 1024 regions | 0.00% (0.00–0.37%) | – | outside |
| 40 y | Survival of the densest, 32 regions (this guide), refit | 0.0004663 | 32 / 1024 regions | 3.12% (2.22–4.38%) | 266 (one fiber, no interval) | outside |
| 80 y | Survival of the densest, 32 regions (this guide), first fit | 0.0001375 | 152 / 1024 regions | 14.84% (12.80–17.15%) | 114 (106–121) | outside |
| 80 y | Survival of the densest, 32 regions (this guide), refit | 0.000134 | 111 / 1024 regions | 10.84% (9.08–12.89%) | 108 (95–119) | compatible |
| 3 y | Neutral drift, one cell (tutorial S3) | 0.00758 | 2122 / 20000 cells | 10.61% (10.19–11.04%) | 34.72 (34.51–34.93) | compatible |
| 3 y | Faster copying of shorter mtDNA, one cell (tutorial S3) | 0.00608 | 1994 / 20000 cells | 9.97% (9.56–10.39%) | 29.30 (29.11–29.51) | within |
| 3 y | Transcription-linked replication, one cell (tutorial S3) | 5.1e-06 | 1976 / 20000 cells | 9.88% (9.47–10.30%) | 1.26 (1.24–1.28) | compatible |
| 10 y | Neutral drift, one cell (tutorial S3) | 0.00142 | 1953 / 20000 cells | 9.77% (9.36–10.18%) | 9.46 (9.35–9.57) | compatible |
| 10 y | Faster copying of shorter mtDNA, one cell (tutorial S3) | 0.000599 | 1831 / 20000 cells | 9.16% (8.76–9.56%) | 4.92 (4.84–5.01) | compatible |
| 10 y | Transcription-linked replication, one cell (tutorial S3) | 1.42e-06 | 2049 / 20000 cells | 10.24% (9.83–10.67%) | 1.07 (1.06–1.08) | compatible |
| 40 y | Neutral drift, one cell (tutorial S3) | 0.000171 | 1945 / 20000 cells | 9.72% (9.32–10.14%) | 2.21 (2.16–2.25) | compatible |
| 40 y | Faster copying of shorter mtDNA, one cell (tutorial S3) | 3.25e-05 | 2125 / 20000 cells | 10.62% (10.21–11.06%) | 1.26 (1.24–1.28) | compatible |
| 40 y | Transcription-linked replication, one cell (tutorial S3) | 3.23e-07 | 1966 / 20000 cells | 9.83% (9.43–10.25%) | 1.01 (1.01–1.01) | compatible |
| 80 y | Neutral drift, one cell (tutorial S3) | 6.78e-05 | 1935 / 20000 cells | 9.68% (9.27–10.09%) | 1.50 (1.47–1.53) | compatible |
| 80 y | Faster copying of shorter mtDNA, one cell (tutorial S3) | 1.13e-05 | 2009 / 20000 cells | 10.04% (9.64–10.47%) | 1.10 (1.08–1.11) | within |
| 80 y | Transcription-linked replication, one cell (tutorial S3) | 1.57e-07 | 1985 / 20000 cells | 9.93% (9.52–10.35%) | 1.01 (1.00–1.01) | within |

The fit. The share of affected regions rises from 0 to 1 over a narrow
range of m: for the denser mutant from 0 of 128 regions at m = 0.0102
to 128 of 128 at 0.0127. The regression’s 95% interval for the refit m
is 0.01112–0.01121, but it treats regions as independent and is too narrow
for the same reason as the Wilson interval below. The rise is steep
because the mutant fraction of a region is set mostly by mutation
pressure, which is nearly the same everywhere. Without selection, a wild-type copy is replaced by a new
deletion at rate m * mu, so after time t the expected mutant fraction
is about 1 - exp(-m * mu * t). With equal density at m = 0.01133 this
gives 0.575, and the refit cohort’s mean is 0.576. With the denser mutant
at m = 0.01117 it gives 0.570, and the cohort’s mean is 0.581: survival
of the densest raises the mutant fraction by about 0.01 in 3 years. The
regions scatter around the mean with a standard deviation of about 0.011
within a fiber (0.014 with equal density), and the fiber means scatter by
about 0.008 (0.014). 10% of regions above 0.6 is a tail of this narrow
distribution.
The 10% target. At 3 years, the first validation cohorts of the two coupled cases
were outside the band (22.7% and 14.3% affected), and the predeclared
refit was used for both. The refit cohorts are compatible with the band
(8.0% and 11.1%), and so is the isolated case (10.2%). None lies within
it. The Wilson interval treats the 1,024 regions as independent; the
bootstrap over fibers, below, is two to three times wider, and it is the
honest one: with 32 fibers the prevalence of a cohort cannot be pinned to
±0.5 percentage points. The mean number of types hardly moves between
first fit and refit (1,487 and 1,456; 798 and 816), because it depends on
m smoothly, not through the 60% threshold.
The number of types. At 3 years, every case gives many types per affected region: about 1,460 for the denser mutant, about 820 with equal density and about 270 in isolated regions, against 35 for neutral drift and 1.26 for transcription-linked replication in one cell of tutorial S3. By the predeclared rule all three read “many types, like drift”. No affected region held fewer than 230 types. The largest single type held 0.4% of the copies of an affected region with the denser mutant, 0.6% with equal density and 3.8% in isolated regions; in tutorial S2’s drift cells it is about 16%.
What density contributes. The denser mutant gives 1.78 times as many types per affected region as equal density (95% bootstrap 1.73–1.84), but the cause is the copy number, not clonal expansion. An affected region of the denser mutant holds about 6,760 copies instead of 3,500, and the number of mutant copies per type is about the same in both cases (2.85 and 2.64). Within 3 years, survival of the densest does not make any one type large: it acts on the mutant as a whole, and all mutant types share its density.
What hopping contributes. Isolated regions need a lower m (0.0099
instead of 0.0112), because without exchange between neighbors the regions
scatter more (standard deviation 0.056 instead of 0.011 within a fiber),
and they hold fewer, larger types (16 copies per type). Hopping spreads every lineage
over about 15 regions in 3 years, which mixes many small lineages into
each region.
Zones and segments.
| Case, cohort | Fiber 95% interval of prevalence | Fibers with affected regions (all 32 affected) | Mutant copies per type | Largest type, share of copies | Zones | Types per zone | Types per 32-region segment |
|---|---|---|---|---|---|---|---|
| Denser mutant, 3 y, first fit | 14.7–31.4% | 26 (0) | 2.83 (2.78–2.90) | 0.39% (0.37–0.41%) | 73 | 2174 (1980–2391) | 9095 (9034–9161) |
| Denser mutant, 3 y, refit | 4.6–11.9% | 19 (0) | 2.85 (2.77–2.93) | 0.41% (0.38–0.44%) | 49 | 1741 (1601–1871) | 8937 (8882–8990) |
| Equal density, 3 y, first fit | 8.3–20.3% | 21 (0) | 2.71 (2.66–2.78) | 0.62% (0.59–0.67%) | 63 | 1058 (944–1190) | 5061 (5037–5084) |
| Equal density, 3 y, refit | 6.3–17.0% | 19 (0) | 2.64 (2.58–2.71) | 0.59% (0.55–0.63%) | 53 | 1056 (949–1172) | 5049 (5028–5071) |
| Isolated, 3 y, first fit | 8.7–11.7% | 32 (0) | 16.32 (16.11–16.50) | 3.77% (3.53–4.02%) | 95 | 297 (282–314) | 7401 (7357–7449) |
| Denser mutant, 10 y, first fit | 0.6–7.5% | 6 (0) | 4.87 (4.76–5.54) | 0.72% (0.68–0.77%) | 16 | 1007 (817–1095) | 3035 (2999–3070) |
| Denser mutant, 10 y, refit | 3.4–13.8% | 13 (0) | 5.13 (4.89–5.42) | 0.82% (0.76–0.88%) | 34 | 990 (888–1101) | 3107 (3077–3139) |
| Denser mutant, 40 y, first fit | 0.0–0.0% | 0 (0) | – | – | 0 | – | 611 (598–623) |
| Denser mutant, 40 y, refit | 0.0–9.4% | 1 (1) | 16.37 (one fiber, no interval) | 4.10% (one fiber, no interval) | 1 | 688 (one fiber, no interval) | 590 (575–606) |
| Denser mutant, 80 y, first fit | 4.9–26.5% | 8 (2) | 38.87 (36.73–40.91) | 10.41% (7.28–14.41%) | 17 | 148 (127–196) | 202 (192–212) |
| Denser mutant, 80 y, refit | 1.9–22.3% | 7 (2) | 44.01 (35.72–48.58) | 6.93% (5.34–9.20%) | 14 | 141 (110–189) | 202 (194–211) |
The fiber column counts the fibers with at least one affected region and, in brackets, those affected along all 32 regions. An affected zone holds more types than one of its regions (about 1,740 for the denser mutant at 3 years), and a whole 32-region segment holds about 8,900 mutant types. No 3-year segment was affected as a whole (its pooled mutant fraction stayed below 60%), so the segment rows describe all segments, not affected ones. In isolated regions a zone is only a run of neighbors that share no copies.
Ten years. For the denser mutant the same protocol at 3,600 days needed
a refit as well (first cohort 3.6%, refit 8.1% affected). The fitted m
is 0.0030, about a quarter of the 3-year value, and an affected region
holds about 820 mutant types (95% bootstrap 767–856; no affected region
fewer than 628), with 5.1 mutant copies per type and a largest type of
0.8% of the copies (at most 1.4%). Over 10 years survival of the densest
raises the mean mutant fraction more than over 3: the refit cohort’s mean
is 0.568, while mutation pressure alone, 1 - exp(-m * mu * t), gives
0.530. That gain is spread over hundreds of types. Tutorial S3’s drift cell
holds 9.5 types at 10 years. Each copy now travels about 27 regions, so a
32-region segment mixes almost completely; its 3,100 types are about 4
times the count of one region.
Chain length. Eight fibers of 64 regions at the refit m (0.01117,
results/de-novo-length.csv) gave 79 of 512 regions affected, with 1,558
types per affected region (95% bootstrap over fibers 1,509–1,599) and 2.65
mutant copies per type. The prevalence differs from the 32-region refit
cohort (8.0%), within the scatter between cohorts seen above; the number of
types stays in the same range. The end regions of the 32-region chains had
the same mean mutant fraction as the central ones (0.581 for regions 0 and
31, 0.581 for regions 8 to 23 in the refit cohort of the denser mutant), so
the closed ends do not shape the result.
Forty and eighty years
The 40- and 80-year runs of the denser mutant were run on a second machine
by a reader of the guide with the command of
Running the experiment (run --size full --years 40 and --years 80, --case main, with several workers), from this
repository at or after the commit that added --workers. The operating
system and package versions of that machine are not known. The six
tables of each run are appended unchanged to the saved tables. Two of their fibers
were simulated again on the review host (Linux x86-64, Python 3.13, NumPy
2.3.5, Numba 0.68.1) and agree bit for bit: fiber 28 of the second 80-year
validation cohort (15 affected regions in 6 zones) and fiber 21 of the
second 40-year validation cohort, the one with affected regions. Their 32
region rows (wild type, mutants, types, largest type), their zones and
their segment rows are identical. The 40-year m is stored with six
digits only; its full value was rebuilt from the run’s probe fiber,
simulated again here, and the saved fit counts, and every fit value of m
it implies equals the saved one to the six digits stored. The other fibers were not rerun.
80 years. The first cohort was outside the band (152 of 1,024 regions,
14.8%). The refit is compatible with it: at m = 1.34 · 10⁻⁴, 111 of 1,024
regions are affected (10.8%, Wilson 9.1–12.9%). An affected region holds
108 mutant types (95% bootstrap over fibers 95–119; no affected region
fewer than 81), with 44 mutant copies per type and a largest type of 6.9%
of its copies (at most 11.6%). By the predeclared rule this reads “many
types, like drift”. Tutorial S3’s drift cell holds 1.50 types at 80 years,
the transcription cell 1.01. Four of the 32 segments have a pooled mutant
fraction of at least 60%, and a segment holds about 200 types.
40 years: the calibration failed. Both cohorts lie outside the band
after the one allowed refit: 0 of 1,024 regions are affected at m =
4.73 · 10⁻⁴, and 32 of 1,024 (3.1%, Wilson 2.2–4.4%) at 4.66 · 10⁻⁴. By the
predeclared rule the 40-year run does not reach the target, so it says
nothing about regions at a prevalence of 10%. The 32 affected regions of
the second cohort are one whole fiber. They hold 266 types each (214 to
297), 16 mutant copies per type, and a largest type of 4.1% of their
copies. With one fiber there is no interval: a bootstrap resample either
contains that fiber or has no affected region. This guide therefore makes
no statement on the number of types at 40 years. The saved summary row
reads “many types” only because the run applies the rule to that
degenerate interval.
Why the calibration breaks down. At these ages a fiber is affected
more or less as a whole. Within a fiber the mutant fractions of the regions
scatter with a standard deviation of 0.011 to 0.015 at every age, while the
fiber means scatter by 0.008 at 3 years, 0.019 at 10, 0.045 at 40 and
0.075 at 80 years (refit cohorts). The copies of a region spread over the
whole chain (page S4b), and a
front of the denser mutant, once formed, travels 1.9 to 2.7 mm in 40 years
at the 0.13 to 0.19 µm/day of tutorial S4, more than
the 960 µm of a fiber. Of the 32 fibers of the 80-year refit, 2 are
affected along all 32 regions, 5 in part (1, 1, 2, 15 and 28 regions) and
25 not at all; no 3- or 10-year cohort has a fiber affected along its whole
length. The prevalence of a cohort is then close to a count of fibers. Its
variance over fibers is 26 to 33 times the binomial variance of 1,024
independent regions at 40 and 80 years, against 5 to 11 times at 3 and 10
years: the effective sample is about 31 to 39 units, the number of fibers,
not regions. So the fiber interval of the 80-year refit (1.9–22.3%) is
five times wider than its Wilson interval. The fit points are not even
ordered in m: at 40 years, 77 of 256 regions are affected at m =
4.78 · 10⁻⁴, 0 at 4.88 · 10⁻⁴ and 39 at 4.98 · 10⁻⁴; the 80-year refit
points give 44, 4 and 63 of 256 at 1.348, 1.375 and 1.402 · 10⁻⁴. Each
point is 8 fibers, and the logistic regression, which treats the 256
regions as independent, is far too confident: its 95% interval for the
refit m is about ±1% at 40 and ±2% at 80 years, no wider than the 2% step
between fit points whose prevalences differ tenfold.
Expansion on top of mutation pressure. Mutation pressure alone,
1 - exp(-m * mu * t), gives a mean mutant fraction of 0.375 at 40 years
and 0.237 at 80 years at the refit m, against 0.57 at 3 years. The refit
cohorts’ means over all regions are 0.504 and 0.513. At these ages a region
reaches 60% only through the expansion of the denser mutant on top of
mutation pressure. The types grow larger with age: 2.9 mutant copies per
type at 3 years, 5.1 at 10, 16 at 40 (one fiber) and 44 at 80. Their
number per affected region falls, from about 1,460 to 820, 270 (one fiber)
and 110, but stays far above one.
The rate this needs. Page 19
quotes the paper’s estimate of the de novo rate for human fibers, 4.1 · 10⁻⁸
to 1.6 · 10⁻⁶ per replication. The 80-year m that brings 10% of regions to
60% mutants, 1.34 · 10⁻⁴, is about 84 to 3,300 times that (the failed
40-year values, about 4.7 · 10⁻⁴, about 290 to 11,000 times). The
10%-of-regions target forces a rate far above the paper’s estimate, so the
many types at 80 years partly reflect the target. With the paper’s rate,
affected regions would be much rarer, and this experiment does not show how
many types they would hold.
What this shows and what it does not
What follows, for this model with these parameters: at 3 years, de novo deletions bring 10% of regions to at least 60% mutants only at a deletion probability of about 0.011 per replication, and then an affected region holds well over a thousand mutant types, none of which exceeds 1% of its copies. Survival of the densest does not change this: the neutral control gives as many types per mutant copy. The affected regions of this experiment look like the drift cells of tutorials S2 and S3, only more so, and unlike the essentially clonal affected cells found in experiments. In 3 years the mechanism has no time to act on a single new deletion: a new type starts as one copy among 3,500 to 6,800 and, in about 75 copy generations, grows only by drift. At 10 years the picture is the same with about 820 types per affected region. At 80 years an affected region holds about 110 types of about 44 copies each, none above 12% of its copies: survival of the densest makes the types larger and lifts the mutant fraction well above mutation pressure, but no single type takes over. This needs a deletion probability 84 to 3,300 times the paper’s estimate.
What the experiment does not show:
- Not a test of the paper. The paper makes no claim about short-lived
animals at 3 years. Its estimate of the de novo rate concerns human fibers
over decades, and it is based on the takeover probability of one founder
copy. The Figure 2 parameters were chosen by the authors to model the
wave in rhesus monkey fibers, not for a short-lived animal. Other
parameters, in particular a smaller
Nss(the paper’s Figure 4 shows that a founder’s takeover probability depends onNss), could change the result. - A region is not a cell. Tutorials S2 and S3 classify cells of 1,000 copies; here a region of 3,500 to 6,800 copies exchanges copies with its neighbors. A muscle fiber section classified as COX-negative in an experiment may cover one region or many. The zone and segment rows show how the count grows with the unit.
- 10, 40 and 80 years only for the denser mutant, and no result at 40 years. Tutorial S3’s drift cells hold 2.2 and 1.5 mutant types at 40 and 80 years. The long lifespans show that survival of the densest makes the types larger (2.9, 5.1, 16 and 44 mutant copies per type at 3, 10, 40 and 80 years) while their number stays far above one; whether equal density or isolated regions would differ there is not run. At 40 years the calibration failed, and at 80 years the refit is compatible with the band only by the Wilson interval, which treats regions as independent.
- The protocol does not suit long lifespans. At 40 and 80 years whole fibers are affected or not, so 32 fibers are about 32 units. A design with fibers as the sampling unit, 128 fibers per cohort and a 128-region control is declared on page S4b. Its 40- and 80-year runs and the control are outstanding; this page has no result from them.
- The rate is far above the paper’s estimate. The 10% target sets
m; at 80 years it is 84 to 3,300 times the paper’s estimate for human fibers. The number of types at the paper’s rate is not known from this experiment. - All deletion types are alike. Real deletions differ in size and perhaps in density; one with a larger density advantage than the others would not be modeled here.
- The 10% target is met only loosely. The prevalence scatters between
cohorts more than the ±0.5-point band, because regions in a fiber are
correlated. At 3 years the type count barely depends on this (1,456 to
1,487 types for
mbetween 0.01117 and 0.01130); at 80 years the two cohorts give 114 and 108. - Fewer units than the papers. 1,024 regions in 32 fibers per cohort, instead of 1,000 independent cells per run in the papers and 20,000 in tutorial S3. The intervals above account for the clustering by resampling fibers.
The parameters, the boundary conditions, the chain length, the unit definitions, the year of 360 days and the treatment of mutant templates are choices of this guide, given with their reasons on page S4b.
Running the experiment
| Size | Command | What it does | Time on one core |
|---|---|---|---|
| quick | python examples/mtdna_spread/mutations.py run --size quick | the whole protocol on a small model (4 regions of 20 copies, 120 days), pure Python | 3 s |
| sampler | python examples/mtdna_spread/mutations.py sampler | the sampler against CRN-craft and the moment law | 30 s with Numba |
| draft | python examples/mtdna_spread/mutations.py run --size draft | the Figure 2 parameters, 2 fibers per fit point and 8 validation fibers per case | not run; about 6 to 10 min with Numba (estimate from the full run) |
| full | python examples/mtdna_spread/mutations.py run --size full --output examples/mtdna_spread/results | the 3-year runs of this page, with the refits | 28 CPU-minutes with Numba (main 15, equal density 10, isolated 3) |
| full, 10 years | python examples/mtdna_spread/mutations.py run --size full --years 10 --case main | the 10-year runs (133 fibers with the refit) | 50 CPU-minutes with Numba |
| full, 40 years | python examples/mtdna_spread/mutations.py run --size full --years 40 --case main --workers N | the 40-year runs (133 fibers with the refit); the saved rows were run on a second machine by a reader of the guide | about 3 CPU-hours with Numba (estimate: 84 to 106 s per fiber on the review host) |
| full, 80 years | python examples/mtdna_spread/mutations.py run --size full --years 80 --case main --workers N | the 80-year runs (141 fibers with the refit); the saved rows were run on a second machine by a reader of the guide | about 6.5 CPU-hours with Numba (estimate: 164 s for one fiber on the review host) |
| length | python examples/mtdna_spread/mutations.py length --m 0.01116696641687773 --regions 64 | eight 64-region fibers | 2 min |
| fiber design, quick | python examples/mtdna_spread/mutations.py run --size quick --design fibers | the fiber design on the small model, pure Python | 9 s |
| coverage | python examples/mtdna_spread/mutations.py coverage --output examples/mtdna_spread/results | the fiber design on synthetic fibers (page S4b) | 3 min |
| fiber design, 40 years | python examples/mtdna_spread/mutations.py run --size full --years 40 --case main --design fibers --workers 16 --work DIR --output DIR | 288 fibers, 512 with the refit; outstanding | 13 to 24 CPU-hours (estimate) |
| fiber design, 80 years | python examples/mtdna_spread/mutations.py run --size full --years 80 --case main --design fibers --workers 16 --work DIR --output DIR | 288 fibers, 512 with the refit; outstanding | 27 to 47 CPU-hours (estimate) |
| 128-region control | python examples/mtdna_spread/mutations.py length --years 80 --regions 128 --fibers 32 --m-from DIR/de-novo-fibers-rates.csv --reference DIR/de-novo-fibers-summary.csv --workers 16 --output DIR2 | 32 fibers of 128 regions after the 80-year fiber run; outstanding | about 12 CPU-hours (estimate) |
The draft and full sizes need Numba in practice: without it the same
sampler runs in pure Python, roughly 100 times slower. Every fiber is
checkpointed under runs/de-novo/<size>/ (--work), so an interrupted run
continues where it stopped. Add --workers N to run to simulate up to
N fibers at the same time in separate processes, for example
run --size full --years 80 --case main --workers 16; every fiber has its
own seed, so the tables do not depend on N, apart from the measured
seconds. The times in the table are
CPU time on one core. mutations.py figure --figures FOLDER redraws the
figure from the saved tables; add --results RUN_FOLDER to draw it from
the tables of a run of your own (the folder given to run --output).
The run command writes the tables of one lifespan; the saved tables hold
the 3-, 10-, 40- and 80-year rows in this order. A 10-year fiber has about
185 million events and took 23 s; a 40-year fiber has 730 to 890 million
and an 80-year fiber about 1.4 billion. Outstanding: equal density and
isolated regions at 10, 40 and 80 years (at 10 years about 35 and 15
CPU-minutes, at 40 and 80 years a few CPU-hours each), and the fiber-design
runs at 40 and 80 years with the 128-region control (no results yet).
The cost of the fiber design is an estimate of 0.13 CPU-seconds per region
and year with Numba, from the machine that made the first 40- and 80-year
runs (about 170 and 330 s per 32-region fiber). One 40-year fiber took 83
s on the two-core review host, about half of that. run --design fibers
prints the number of fibers and this estimate at its start. With
--workers 16 the stages run in 18 rounds of 16 fibers without a refit and
32 with it, about 1.7 and 3 hours at 80 years.
Exercises
- Run
mutations.py run --size quickand openruns/de-novo/quick/de-novo-summary.csv. Then make the regions larger: passnss=200inSIZES["quick"]["model"]. How do the fittedmand the number of types per affected region change? - From
results/de-novo-regions.csv, compute for each case the share of the largest type,largest / (wild + mutant), in affected regions. Why is it about ten times larger in isolated regions than in the chain, although the deletion probability is almost the same?
See also: tutorial S3b, tutorial S2c.
S5. Mitochondrial networks and the rate of drift
What this chapter reproduces
A cell holds hundreds to thousands of mtDNA copies. When some copies carry a mutation, the mutant fraction (heteroplasmy) of a cell drifts at random as copies are degraded and replicated, and cells that started alike become different. Mitochondria also fuse into networks and split again. A 2019 paper asks how this network state changes the speed of the drift:
Aryaman J., Bowles C., Jones N.S., Johnston I.G. (2019). Mitochondrial network state scales mtDNA genetic dynamics. Genetics 212(4), 1429–1443. doi:10.1534/genetics.119.302423 (Equations 1–10 and 13, Figure 2E–H, Figure S3D)
Its answer, Equation 13, is that the variance of the mutant fraction between cells grows at a rate proportional to the fraction of copies that are not fused. Fused copies are protected from degradation, so they do not take part in the turnover that drives the drift.
The authors published their simulator, parameter tables and the variance
summaries of their simulations
(MitoNetworksGenetics,
revision 8f158fb). This chapter takes the parameter tables and the
summaries from there, writes the model in CRN-craft, and simulates it
afresh. No code was copied or translated from the authors’ repository; it
is licensed under GPL-3.0 and was read for facts only. The paper’s authors
did not write or review this chapter.
The result in three lines:
- In the three conditions chosen before the runs (E:0, F:0, H:60), the measured early slope divided by the Equation 13 slope is 0.986, 0.986 and 1.010; all three 99% simultaneous intervals lie inside the declared band 0.80–1.20 (numerical agreement). In all 39 source conditions, 38 intervals lie inside the band; the 39th (H:65) was rerun with a fresh seed and gave 1.042 (0.925–1.187), so the first value was sampling noise.
- Over the first two days, this agreement does not test the network assumption of Equation 13: at time zero the slope equals Equation 13 exactly for any fusion and fission rate. The archived 0–500 day simulations are the test; there the slowest switching case deviates by 7%, and a fresh 2,000-path run cannot resolve a deviation of that size.
- Fresh simulations agree with the authors’ archived variance series within their 99% intervals (slow switching, 0–500 days; nominal, 0–100 days).
Words used in this chapter
- Singleton: a copy in an unfused mitochondrion. Fused: a copy in a
network. Every copy is wild type (
W) or mutant (M), so a cell has four counts:WS,MS,WF,MF. - Heteroplasmy
h: the mutant fraction(MS + MF) / n, withnthe total copy number. - Singleton fraction
f_s:(WS + MS) / n. - Condition: one row of the authors’ parameter tables, named by figure
panel and row index, for example
H:60(the nominal parameters). - Slope ratio: the measured growth rate of
Var(h)divided by the Equation 13 rate.
The model
Time is in days. The reactions and their hazards (rates per day of the whole cell) are those of the paper’s Equations 1–10 and of the authors’ simulator, with fused copies never degraded (the paper’s nominal case):
| Process | Reaction | Hazard |
|---|---|---|
| Fusion of two identical singletons | WS + WS -> WF + WF | γ·WS·(WS−1)/2 |
| Fusion of a singleton with a fused copy | WF + WS -> WF + WF, MF + WS -> MF + WF | γ·WF·WS, γ·MF·WS |
| Fusion of two different singletons | WS + MS -> WF + MF | γ·WS·MS |
| Fission | WF -> WS | β·WF |
| Replication of a singleton | WS -> WF + WF | λ·WS |
| Replication of a fused copy | WF -> WF + WF | λ·WF |
| Degradation (mitophagy), singletons only | WS -> ∅ | μ·WS |
The mutant reactions are the same with W and M exchanged, including
MS + MS, MF + MS and WF + MS; there are 15 reactions in total. The
replication rate per copy has linear feedback on the copy number
(Equation 10):
$$\lambda = \max{0,\ \mu + b,[\kappa - (WS + WF) - \delta,(MS + MF)]}.$$
μ is the mitophagy rate (nominal 0.023 per day, a half-life of 30 days),
β the fission rate (33.12 per day), γ the fusion rate per pair
(0.0379 per day), b the feedback strength (1.24e-5 per day per copy),
κ sets the target copy number, and δ weights mutants in the feedback.
The model is neutral: mutants and wild type behave alike.
Equation 13 gives the variance after a short time t, starting at the
deterministic steady state with copy number n, singleton fraction f_s
and heteroplasmy h:
$$\mathrm{Var}(h) \simeq \frac{2\mu f_s}{n},h(1-h),t.$$
The paper derives it assuming many copies and fusion and fission much
faster than turnover. For the nominal state (n = 1,001, h = 0.300,
f_s = 0.467) it gives 4.50e-6 per day.
import crn_craft as crn
model = crn.Model("identical_fusion")
model.add_species({"WS": 3, "WF": 0})
model.add_reaction(0.4, ["WS", "WS"], ["WF", "WF"], name="fusion")
law = model.fsp(1e-7, [1e-7], {"WS": 3, "WF": 4}, tolerance=1e-14).metadata
p = dict(zip(map(tuple, law["states"]), law["snapshots"][0]["probabilities"]))
print(round(p[(1, 2)] / 1e-7, 4))
1.2
Three singletons form three unordered pairs, so the fusion hazard is
0.4 × 3 = 1.2 per day; CRN-craft’s mass action counts a pair of identical
reactants once, as the authors’ simulator does.
What is taken from the authors and what is simulated
| Item | Source |
|---|---|
Parameters and initial counts of 39 conditions (conditions.csv) | the authors’ parameter tables, read by fetch.py |
Archived variance series, 10,000 paths each, every 10 days to day 500 (reference-variance.csv) | the authors’ online_stats_<index>.csv files |
| Equation 13 slope | computed here from the initial counts, as the authors’ analysis does |
| All slope ratios, intervals and fresh variance series | simulated here with CRN-craft 0.8.0, Static Direct |
The 39 conditions are all rows of Figure 2E (mitophagy rate, 4 rows), 2F
(copy number, 5), 2G (mutant weight δ, 9), the fusion-to-fission ratio
R at magnitude M = 1 (Figure 2H, 11 rows) and the magnitude M at
R = 1 (Figure S3D, 11 rows); H:60 belongs to both sweeps.
The protocol
Declared in manifest.json before the runs:
- Primary conditions E:0, F:0 and H:60; 2,000 independent paths each, seed
200521 +row number. - Report times 0, 0.5, 1, 1.5 and 2 days. The slope is the variance of
hover paths regressed on time through the origin. - Interval: whole-path bootstrap of the slope ratio, two-sided 99% with a Bonferroni split over the three conditions (tails 0.01/6).
- Decision: agreement if all three intervals lie inside 0.80–1.20.
- The other 36 conditions are descriptive. For the four fastest switching
magnitudes (
β≥ 100 per day, H:62–H:65) the window is shortened by100/βand the cohort is 1,024 paths, to bound the event count.
The results page shows the outcome, the review runs, the reconstruction choices and the limits.
Running the example
You need CRN-craft 0.8.0, NumPy, pandas and Matplotlib. Run from the repository root:
python examples/mtdna_network/study.py --size quick
python examples/mtdna_network/study.py --size full
python examples/mtdna_network/review.py --size full
python examples/mtdna_network/study.py --figures docs/guide/img/mtdna_network
python examples/mtdna_network/review.py --figures docs/guide/img/mtdna_network
--size quick runs 256 paths of H:60 over 0.25 days in about one second.
--size draft runs the three primary and four more conditions (about three
minutes on one core). --size full runs all 39 conditions with
checkpoints; it was not timed for this page, and its event count suggests
20–30 minutes on one core. review.py --size full repeats the review runs
of the results page (about 11 minutes on one core). The
--figures commands redraw the plots from the saved CSV files. The
example README lists the files.
Tutorial S6 follows variance across scheduled cell divisions.
S5a. Network state and drift: results, choices and limits
This page belongs to tutorial S5. All tables are
generated from the CSV files in examples/mtdna_network/results/, and
validation/check_mtdna_network.py compares them with this page.
The primary check
The three conditions fixed in manifest.json before the runs: turnover
E:0 (μ = 0.01725 per day), copy number F:0 and the nominal H:60. Each
has 2,000 paths over 0–2 days. The ratio is the measured slope of Var(h)
divided by the Equation 13 slope.
| Condition | Paths | Ratio | 99% simultaneous, 600 replicates | Same, 20,000 replicates | Inside 0.80–1.20 |
|---|---|---|---|---|---|
| E:0 | 2,000 | 0.986 | 0.904–1.074 | 0.903–1.073 | yes |
| F:0 | 2,000 | 0.986 | 0.903–1.062 | 0.904–1.065 | yes |
| H:60 | 2,000 | 1.010 | 0.935–1.084 | 0.929–1.096 | yes |
All three intervals lie inside the declared band: numerical agreement.
The shipped intervals used 600 bootstrap replicates, so each end rests on
about one replicate (tail 0.01/6). Rerunning the same paths (identical
seeds give identical paths) with 20,000 replicates moves the ends by up to
0.012; five other 600-replicate seeds differ from the 20,000-replicate
ends by up to 0.017 (review-primary-intervals.csv). The decision is the same either way.

Every source condition
The same estimator for all 39 conditions. Intervals use the same Bonferroni tails as the primary check and are descriptive. “Archive” is the authors’ 10,000-path variance series regressed through the origin over 0–100 days, divided by the same Equation 13 slope.
| Condition | Varied | Paths | Window (days) | f_s | Eq. 13 (1e-6/day) | Ratio | 99% interval | Archive 0–100 d / Eq. 13 |
|---|---|---|---|---|---|---|---|---|
| E:0 | μ = 0.01725/day | 2,000 | 2 | 0.466 | 3.385 | 0.986 | 0.904–1.074 | 1.004 |
| E:1 | μ = 0.0345/day | 2,000 | 2 | 0.466 | 6.770 | 1.042 | 0.965–1.130 | 1.041 |
| E:2 | μ = 0.04025/day | 2,000 | 2 | 0.466 | 7.878 | 1.010 | 0.930–1.091 | 1.005 |
| E:3 | μ = 0.046/day | 2,000 | 2 | 0.466 | 9.003 | 0.955 | 0.888–1.051 | 1.007 |
| F:0 | κ = 0 | 2,000 | 2 | 0.472 | 4.653 | 0.986 | 0.903–1.062 | 1.011 |
| F:1 | κ = 583 | 2,000 | 2 | 0.322 | 1.694 | 1.005 | 0.929–1.080 | 1.020 |
| F:2 | κ = 1166 | 2,000 | 2 | 0.256 | 0.970 | 0.985 | 0.910–1.058 | 0.994 |
| F:3 | κ = 2333 | 2,000 | 2 | 0.186 | 0.467 | 1.047 | 0.960–1.126 | 0.997 |
| F:4 | κ = 3499 | 2,000 | 2 | 0.147 | 0.280 | 1.067 | 0.987–1.155 | 1.000 |
| G:0 | δ = -5 | 2,000 | 2 | 0.189 | 0.208 | 1.018 | 0.933–1.090 | 0.990 |
| G:1 | δ = -1 | 2,000 | 2 | 0.189 | 0.484 | 1.005 | 0.923–1.084 | 1.011 |
| G:2 | δ = -0.1 | 2,000 | 2 | 0.239 | 0.974 | 1.015 | 0.937–1.116 | 1.019 |
| G:3 | δ = -0.01 | 2,000 | 2 | 0.257 | 1.163 | 0.982 | 0.907–1.056 | 0.996 |
| G:4 | δ = 0.01 | 2,000 | 2 | 0.262 | 1.209 | 0.995 | 0.922–1.073 | 1.001 |
| G:5 | δ = 0.1 | 2,000 | 2 | 0.281 | 1.427 | 1.021 | 0.950–1.104 | 1.017 |
| G:6 | δ = 1 | 2,000 | 2 | 0.471 | 4.652 | 1.012 | 0.943–1.090 | 0.976 |
| G:7 | δ = 1.5 | 2,000 | 2 | 0.578 | 10.320 | 0.980 | 0.900–1.062 | 1.019 |
| G:8 | δ = 2 | 2,000 | 2 | 0.567 | 6.240 | 1.028 | 0.955–1.106 | 0.993 |
| H:5 | R = 0.01, M = 1 | 2,000 | 2 | 0.987 | 9.520 | 1.027 | 0.946–1.120 | 1.010 |
| H:16 | R = 0.0251, M = 1 | 2,000 | 2 | 0.971 | 9.380 | 1.018 | 0.947–1.110 | 1.008 |
| H:27 | R = 0.0631, M = 1 | 2,000 | 2 | 0.932 | 8.999 | 0.982 | 0.901–1.060 | 0.986 |
| H:38 | R = 0.158, M = 1 | 2,000 | 2 | 0.846 | 8.172 | 0.994 | 0.916–1.082 | 0.992 |
| H:49 | R = 0.398, M = 1 | 2,000 | 2 | 0.687 | 6.636 | 1.013 | 0.940–1.090 | 1.015 |
| H:55 | R = 1, M = 0.01 | 2,000 | 2 | 0.446 | 4.319 | 1.009 | 0.943–1.080 | 1.023 |
| H:56 | R = 1, M = 0.0251 | 2,000 | 2 | 0.458 | 4.416 | 0.944 | 0.880–1.015 | 1.004 |
| H:57 | R = 1, M = 0.0631 | 2,000 | 2 | 0.463 | 4.473 | 1.008 | 0.920–1.091 | 0.998 |
| H:58 | R = 1, M = 0.158 | 2,000 | 2 | 0.465 | 4.512 | 1.035 | 0.949–1.117 | 0.990 |
| H:59 | R = 1, M = 0.398 | 2,000 | 2 | 0.466 | 4.513 | 1.011 | 0.940–1.086 | 1.006 |
| H:60 | R = 1, M = 1 | 2,000 | 2 | 0.467 | 4.500 | 1.010 | 0.935–1.084 | 0.996 |
| H:61 | R = 1, M = 2.51 | 2,000 | 2 | 0.467 | 4.511 | 1.016 | 0.938–1.098 | 1.016 |
| H:62 | R = 1, M = 6.31 | 1,024 | 0.957 | 0.467 | 4.511 | 0.996 | 0.883–1.117 | 0.990 |
| H:63 | R = 1, M = 15.8 | 1,024 | 0.381 | 0.467 | 4.511 | 0.998 | 0.896–1.094 | 1.022 |
| H:64 | R = 1, M = 39.8 | 1,024 | 0.152 | 0.467 | 4.511 | 1.028 | 0.909–1.180 | 1.002 |
| H:65 | R = 1, M = 100 | 1,024 | 0.0604 | 0.467 | 4.511 | 0.879 | 0.755–1.033 | 1.021 |
| H:71 | R = 2.51, M = 1 | 2,000 | 2 | 0.258 | 2.483 | 0.984 | 0.912–1.071 | 0.995 |
| H:82 | R = 6.31, M = 1 | 2,000 | 2 | 0.122 | 1.187 | 0.965 | 0.895–1.040 | 1.001 |
| H:93 | R = 15.8, M = 1 | 2,000 | 2 | 0.052 | 0.508 | 1.038 | 0.936–1.130 | 1.008 |
| H:104 | R = 39.8, M = 1 | 2,000 | 2 | 0.022 | 0.204 | 0.971 | 0.872–1.081 | 0.981 |
| H:115 | R = 100, M = 1 | 2,000 | 2 | 0.009 | 0.093 | 0.905 | 0.819–1.028 | 0.945 |
38 of the 39 intervals lie inside 0.80–1.20. The exception is H:65, the
fastest switching magnitude (β = 3,312 per day). Its window is 0–0.060
days, in which a path sees about 1.3 births or deaths, so its interval is
0.28 wide, against 0.13–0.21 for the 2,000-path rows over 2 days. Its rerun is below.
What the two-day window can and cannot show
At time zero every path is in the same state, and the variance grows only
through births and deaths. A birth or death changes h by about h/n or
(1−h)/n. If the singletons have the same mutant fraction as the whole
cell and births balance deaths (λn = μ·n·f_s), the sum of hazard times
squared jump is exactly 2μ f_s h(1−h)/n, Equation 13, whatever the
fusion and fission rates are. So the early ratios check the hazards and
the estimator. They cannot show the failure of Equation 13 when fusion and
fission are slow; that failure builds up over many turnover times, as the
singleton and fused pools drift apart.
The authors’ archived runs cover 500 days (about 17 half-lives). By their
own estimator (the mean finite-difference gradient of Var(h) over
0–500 days), the largest deviation in the whole 121-condition network
sweep is 9% (magnitude 0.01, ratio 0.063, a row not among the 39);
H:55 (magnitude 0.01, ratio 1) deviates by 7%. No path reaches fixation by
day 500 in any of the 39 archived conditions.
Review runs
Four runs, each declared with its decision rule before it ran
(review.py, results/review-*.csv):
- H:65 again, same window, fresh seed, 2,000 paths. Rule: a single 99% interval containing 1 means the shipped 0.879 is sampling noise.
- H:55, the slowest switching magnitude of Figure S3D, 2,000 paths over 0–500 days, and H:60 (nominal), 400 paths over 0–100 days, on the archive’s 10-day grid with the authors’ estimator. Rule: the 99% interval of fresh/archived containing 1 means numerical agreement.
| Run | Paths | Days | Quantity | Value (99% interval) |
|---|---|---|---|---|
| H:65 again, fresh seed | 2,000 | 0–0.060 | fresh / Equation 13 | 1.042 (0.925–1.187) |
| H:55 fresh vs archive | 2,000 | 0–500 | fresh / archived | 0.938 (0.864–1.016) |
| H:55 vs Equation 13 | 2,000 | 0–500 | fresh / Equation 13 | 1.004 (0.925–1.088); archived 1.070 |
| H:60 fresh vs archive | 400 | 0–100 | fresh / archived | 0.879 (0.720–1.063) |
| H:60 vs Equation 13 | 400 | 0–100 | fresh / Equation 13 | 0.885 (0.725–1.070); archived 1.007 |
- H:65: the interval contains 1. The shipped 0.879 was sampling noise of the short window, not a loss of accuracy.
- Both fresh-versus-archive intervals contain 1: numerical agreement with the authors’ simulations. The nominal run is small (400 paths), so its interval, 0.72–1.06, is wide.
- H:55 against Equation 13: inconclusive. The fresh interval contains both 1 and the archive’s 1.070, so this run cannot tell whether slow switching makes the drift 7% faster.

results/nominal-long.csv holds the smaller H:60 run of the full
campaign (96 paths to day 50); its variance at day 50, 2.40e-4, is close
to the Equation 13 value 2.25e-4.
Reconstruction choices
| Choice | Alternative | Measured effect |
|---|---|---|
| Equation 13 evaluated at the integer initial counts, as the authors’ analysis does | the floating-point deterministic steady state reached from them | ≤ 0.2% in all rows except H:93 (0.5%), H:104 (2.2%) and H:115 (3.6%), where only 9–22 copies are singletons |
| Slope from 0–2 days, through the origin | the authors’ mean gradient over 0–500 days | changes the question (see above); archive ratios are 0.96–1.07 over 0–500 days and 0.94–1.04 over 0–100 days |
Window 2·100/β days and 1,024 paths for H:62–H:65 | 2 days and 2,000 paths | interval widths 0.20–0.28, against 0.13–0.21 for the 2-day rows |
Bootstrap of the variance with divisor n | divisor n − 1, as in the archive | 0.05% |
| 600 bootstrap replicates | 20,000 | interval ends move by up to 0.017 |
| Fused copies never degraded | the authors’ xi > 0 variant | not run; outside Figure 2 |
Pair hazard γ·k(k−1)/2 for identical singletons | γ·k²/2 | identical to the authors’ simulator; the check would catch either factor-two error |
What the check guards
validation/check_mtdna_network.py runs in under a second and offline. It
compares hand-computed hazards with finite state projection over one tiny
time step: identical-singleton fusion at 0, 1, 2 and 3 copies, all
13 one-event destinations of a mixed state with feedback b > 0, the clamp
of a negative replication rate at zero, and that fused copies are never
degraded. It checks that a single-genotype cell never gains a mutant, the
Equation 13 value for one state, the row and value counts of the
reference files, the structure of the saved results, and that the three
tables above equal the saved CSV files.
Limits and what was not verified
- The supplement (Table S2) was not read; parameter values come from the
authors’ parameter tables at the pinned revision, which match
conditions.csvexactly. - Figure S4A (the error heatmap over the full network grid) is not reproduced; only the archive was read for it.
- The review reran only the three primary conditions of the full campaign (bit-identical to the shipped rows; one and two threads give identical paths). The other 36 rows were not rerun.
- The early-window ratios do not test the fast-switching assumption of Equation 13, and the slow-switching deviation in the archive (7% for H:55) is not resolved by the fresh runs.
conditions.csvandreference-variance.csvare derived from the data files of a GPL-3.0 repository. They are not covered by this repository’s MIT license and stay under the terms of their source (notice);fetch.pyregenerates both from the pinned revision.
Exercises
- Multiply
early_daysinmanifest.jsonby 400 and runstudy.py --size quick(a 0–100 day window, about two minutes). Does the ratio for H:60 stay near 1? - Change the fusion hazard in
study.pyto count ordered pairs (γ·k(k−1)) and run the check. Which line fails? - Raise the H:55 path count in
review.pyfrom 2,000 to 8,000 (about seven minutes). Does the interval against Equation 13 still contain 1?
S6. Inheriting an mtDNA bottleneck
What this chapter reproduces
A fertilized mouse egg holds about 200,000 copies of mitochondrial DNA (mtDNA). Over the next week the copy number per cell falls to about 1,000, and it recovers only in the developing egg cells of the next generation. Cells that start with the same mutant fraction end up with different mutant fractions. This chapter asks what copy numbers and the spread of mutant fractions, measured together, reveal about how that spread arises:
Johnston I.G., Burgstaller J.P., Havlicek V., Kolbe T., Rülicke T., Brem G., Poulton J., Jones N.S. (2015). Stochastic modelling, Bayesian inference, and new in vivo measurements elucidate the debated mtDNA bottleneck mechanism. eLife 4:e07464. doi:10.7554/eLife.07464 (Table 1, Figure 3A–B, Figure 4 source data)
The paper is open access under the Creative Commons Attribution license. The chapter takes the measurements of Table 1 and the individual cell measurements of Figure 4 from the paper. It reads the published Figure 3 curves from the figure by eye. Everything else is simulated or calculated here. The authors’ programs were not used. The paper’s authors did not write or review this chapter.
The result in three lines:
- Approximate Bayesian computation at the paper’s distance threshold 40 reproduces Figure 3 up to 50 days post-conception (dpc). There, every reconstructed median lies inside the published outer envelope.
- After 50 dpc the data constrain copy number weakly. The reconstructed copy-number band at 100 dpc spans more than three orders of magnitude, and its median is 23 times below the published curve. Results
- The fitted model, which never sees the 15 new mouse groups of Figure 4, puts 12 of their 15 measured variances inside the range that a sample of that group’s size would show.
Words used in this chapter
- Heteroplasmy
h: the mutant fraction of the mtDNA in one cell. - Normalized variance
V'(h) = Var(h) / (E(h) (1 - E(h))): the variance ofhacross cells, divided by its largest possible value for that mean. It does not depend on the mean to first order. - dpc: days post-conception.
- Phase: one of six stretches of development with its own replication and degradation rates.
One division, by hand
At a division each copy enters the tracked daughter with probability one half, independently of the others. A mother with two mutant copies therefore passes on zero, one or two of them with these probabilities:
from math import comb
probabilities = [comb(2, copies) * 0.5**2 for copies in range(3)]
print(probabilities)
[0.25, 0.5, 0.25]
Between divisions each copy is copied at rate λ and removed at rate
ν. Thirty-six such divisions, with turnover in between, produce the
bottleneck. The model and the inference
Run it
| Size | What it runs | Time, one core with Numba |
|---|---|---|
quick | one ensemble, 16 walkers, 200 sweeps | about 9 s |
draft | four ensembles, 15,000 sweeps each | about 15 s |
full | four ensembles, 360,000 sweeps each (the stored results) | about 1 min |
python examples/mtdna_bottleneck/study.py --size quick
python examples/mtdna_bottleneck/study.py --size full
python examples/mtdna_bottleneck/study.py --size full --free-final-degradation
python examples/mtdna_bottleneck/review.py
python examples/mtdna_bottleneck/study.py --figures docs/guide/img/mtdna_bottleneck
python validation/check_mtdna_bottleneck.py
Numba is optional. Without it the quick size runs in about the same time, but the draft and full sizes are too slow to be practical. The check needs neither Numba nor a stored run. It verifies the exact laws, the reference files, and that every table on the results page equals the stored result files.
The chapter has three parts:
Example and result files · Tutorial S7 turns to the shape of a different stochastic count distribution.
The model and the inference
Six phases, 36 divisions
The model follows one cell lineage from the fertilized egg (time 0) to a
mature egg cell. Wild-type copies W and mutant copies M follow the
same reactions, because the paper’s fitted model has no selection:
| Reaction | Rate per copy (per hour) |
|---|---|
W -> 2 W, M -> 2 M (replication) | λ_i |
W -> ∅, M -> ∅ (degradation) | ν_i |
Here i is the phase. Times are in hours inside the code and in dpc in
the tables and plots.
| Phase | Time | Divisions | Free parameters |
|---|---|---|---|
| 1 | 0 to 203 h (8.46 dpc) | 29, every 7 h | λ_1, ν_1 |
| 2 | 203 to 315 h (13.125 dpc) | 7, every 16 h | λ_2, ν_2 |
| 3, 4, 5 | lengths τ_3, τ_4, τ_5 in days | none | λ_i, ν_i, τ_i |
| 6 | until the end | none | none (λ_6 = 0; ν_6 = 0 in the stored run) |
At each division the tracked daughter receives each copy with
probability one half: W' ~ Binomial(W, 1/2) and M' ~ Binomial(M, 1/2).
An observation made exactly at a division time sees the daughter. The
initial copy number m_0 is free, and the initial heteroplasmy is fixed
at h_0 = 0.2, as in the paper.
The example runs one lineage by joining CRN-craft segments
(native_lineage in model.py): it simulates a phase with
static_direct, draws the binomial partition in Python, and starts the
next segment from the sampled counts.
The same module also defines protocol_lineages. It runs all phases and
partitions of a lineage in one native scheduled run and reports the
daughter’s counts right after each partition. The results in this chapter
do not use it. The bottleneck check compares its means and variances after
each phase with the phase and division recurrences on a small test
vector. Scheduled experiments
Moments without simulation
The inference never simulates. Within a phase the expected copy number
grows as exp((λ - ν) t), and a division halves it. So the log mean
copy number is exact and piecewise linear in time.
For the spread, let z be the squared coefficient of variation of the
total copy number. Within a phase z grows by (λ + ν) ∫ dt / E(m).
A binomial division adds 1 / (2 E(m')), where m' is the daughter’s
count. Both formulas are exact for this linear model. If wild-type and
mutant copies are independent, expanding h = M / (W + M) to first
order around its mean gives V'(h) ≈ z. The appendix of the paper also
truncates its heteroplasmy variance at first order. The review measured
the error of this approximation against exact simulation (see
Results).
The distance and the priors
The paper’s appendix defines the distance between a parameter set θ
and the data D as the sum of two parts:
Σ_i [log E_θ(m, t_i) - log E_D(m, t_i)]²over copy-number rows;1000 Σ_j [V'_θ(h, t_j) - V'_D(h, t_j)]²over heteroplasmy rows.
The first sum runs over the 34 copy-number rows of Table 1, the second
over its 40 heteroplasmy rows. The example uses natural logarithms; the
paper does not name the base. A parameter set is accepted when
ρ ≤ 40, the Figure 3 threshold. Parameter sets whose mean copy number
reaches 500,000 at any time are rejected, as in the paper. The priors
are uniform, as in the appendix:
| Parameter | Prior |
|---|---|
λ_i, ν_i, phases 1–5 | each in [0, 1] per hour |
m_0 | (0, 1,000,000] copies |
τ_3, τ_4, τ_5 | each in [0, 50] days |
The code stores the net growth λ_i - ν_i and ν_i. This linear change
of variables has Jacobian one, so the prior stays uniform.
Observation ages
Table 1 gives the earliest ages from the number of cells, using the 7 h and 16 h division times (its footnote 1). It prints 7 h, 14 h and 21 h as 0.29, 0.58 and 0.88 dpc. Read literally, 0.29 dpc (6.96 h) lies just before the first division. These six rows (three each from two studies) count cells that have already divided, so the example places them at 7/24, 14/24 and 21/24 dpc, where the model sees the daughter. The mature egg cells of the next generation have no age in Table 1. The paper models them at 100 dpc, and so does the example.
The sampler
The paper runs a Metropolis chain with small normal steps and accepts a
step when its distance is at most the threshold. The example targets the
same posterior, the prior restricted to ρ ≤ 40, with a different
proposal:
- A differential evolution search (SciPy, seed 61 + ensemble) finds a
starting point with
ρ ≤ 40. - A single-coordinate random walk of 160,000 steps spreads 16 starting points around it.
- Sixteen walkers then move by differential evolution Markov chain
steps: walker
iproposesx_i + γ (x_a - x_b) + ε, withaandbtwo other walkers,γfrom a fixed cycle of eight values, andεsmall normal noise. The proposal is symmetric, so the Metropolis–Hastings ratio is the prior ratio times the indicator. With a uniform prior the step is accepted exactly when it stays inside the prior box and below the threshold.
The first quarter of each ensemble is discarded. The plan’s target was at
least 1,000 effective draws across four independent ensembles. For each
ensemble the effective size is computed for eight observables: log copy
number and V' at 10, 35, 70 and 100 dpc. Each uses the walker-averaged
series, with autocorrelation summed to the first negative pair, scaled by
the ratio of the variance over all walkers to the variance of that
average. The smallest of the eight counts per ensemble, and the four
counts are summed. The stored files do not show whether the run length
of 360,000 sweeps was fixed before the run.
The independent mouse groups
Figure 4 of the paper reports 339 new single-cell heteroplasmy
measurements in 15 groups (9 litters, 24 to 61 dpc) from a mouse line
that carries two mtDNA types. The example recomputes each group’s mean,
variance and V' from the cell values and checks them against the
spreadsheet’s summary rows. It does not fit them. For each group it
predicts two ranges at the group’s age:
- the 95% posterior range of the population
V'; - the 95% range of the sample
V'of a group of that size. For this it draws cells from a zero-or-geometric founder law matched to the exact mean and the first-order variance, starting at the group’s observed mean heteroplasmy.
The paper did something different. It fitted half of the groups (every other group ordered by age) with a distance weight of 3,000. It then compared transformed single-cell values of the other half with a 95% range. Neither the transformation nor that split is reconstructed here. All 15 groups are therefore a new validation of the Table 1 fit. The manifest flags litters 1424 and 1406, but the fit uses no group, so the flag does not separate training from test data.
Results
All numbers on this page come from the stored files in
examples/mtdna_bottleneck/results/. validation/check_mtdna_bottleneck.py
regenerates the tables and lists from those files and fails if the page
differs.
In numbers
- Run: 4 ensembles x 16 walkers x 360,000 sweeps = 23,040,000 proposals; acceptance 5.68% to 9.95%; largest stored distance 39.99999.
- Effective size: sum over ensembles of the smallest of eight monitored observables, 1,191 (target 1,000).
- Figure 3: all 12 of 12 digitized central values inside the reconstructed 95% bands; median absolute difference 0.424 in natural-log copies and 0.00455 in V’(h).
- Figure 3 discrepancy: at 100 dpc the reconstructed median is 6,562 copies against 151,572 digitized (log ratio -3.14); reconstructed medians outside the digitized outer envelope: 1 of 12.
- HB groups: 12 of 15 inside their group-sized 95% bands; 3 of 5 for the two flagged litters; 7 of 15 inside the population band.
- First-order V’(h) against exact lineages: median relative error 0.60%, largest 3.4%; 27 of 28 draws stay below 40, all 28 within two Monte Carlo errors.
- Division timing: with the rounded labels 0.29, 0.58 and 0.88 dpc only 49.5% of 20,000 stored states stay below 40.
- Ensemble agreement: largest R-hat 1.29 over parameters and 1.08 over the monitored observables.
Figure 3: copy number and normalized variance

The dots are the Table 1 measurements. The crosses are the published central curve, read from the figure. The shaded region is the 95% range of the population statistic over 6,400 accepted parameter sets (1,600 drawn from each ensemble). It is not a range for individual measurements. The figure caption of the paper says the same of its own band.
The published curve and its two shaded envelopes were read from a
1,000-pixel render of Figure 3 (digitize.py). The axis calibration is
written into that script. The only uncertainty recorded is ±3 pixels on
each central value. The paper does not say which posterior ranges its
two envelopes show.
| Day | Observable | Digitized center | Digitized outer envelope | Reconstructed median | Reconstructed 95% band |
|---|---|---|---|---|---|
| 10 | copies | 1,829 | 1,405 to 2,668 | 1,483 | 1,096 to 1,885 |
| 20 | copies | 6,856 | 3,475 to 11,199 | 5,779 | 3,743 to 8,395 |
| 35 | copies | 41,971 | 10,385 to 116,298 | 22,176 | 11,860 to 44,838 |
| 50 | copies | 85,986 | 18,293 to 220,934 | 72,504 | 19,942 to 207,114 |
| 70 | copies | 120,772 | 28,775 to 310,315 | 46,586 | 166 to 209,496 |
| 100 | copies | 151,572 | 29,730 to 406,992 | 6,562 | 75 to 282,709 |
| 10 | V’(h) | 0.0156 | 0.0101 to 0.0232 | 0.0164 | 0.0109 to 0.0228 |
| 20 | V’(h) | 0.0259 | 0.0181 to 0.0337 | 0.0262 | 0.0192 to 0.0319 |
| 35 | V’(h) | 0.0322 | 0.0223 to 0.0434 | 0.0300 | 0.0210 to 0.0387 |
| 50 | V’(h) | 0.0387 | 0.0265 to 0.0547 | 0.0318 | 0.0216 to 0.0441 |
| 70 | V’(h) | 0.0463 | 0.0333 to 0.0648 | 0.0394 | 0.0247 to 0.0746 |
| 100 | V’(h) | 0.0559 | 0.0394 to 0.0766 | 0.0673 | 0.0503 to 0.0871 |
How to read the agreement
The plan asked how often the published central value falls inside the
reconstructed 95% band. All 12 do, but at 70 and 100 dpc that test cannot
fail. There, the reconstructed copy-number band is about 3 times
wider in log units than the published outer envelope. From 10 to 50 dpc
it is 0.55 to 0.94 times as wide. The stricter reverse test asks whether
each reconstructed median lies inside the published outer envelope. It
fails once: copy number at 100 dpc. That case is an unresolved
discrepancy. Table 1 has no copy-number measurement after 46 dpc, and
the fit lets the late phases lower the copy number to raise V' toward
the large mature-egg values (up to 0.144). The paper’s narrower band at
100 dpc may come from a constraint this reconstruction lacks; the review
could not find one in the paper. Up to 50 dpc the result is
numerical agreement within the published envelopes.
How good is the first-order variance
The distance uses the first-order V'. The review drew 24 accepted
parameter sets at random, plus the 4 with the lowest copy number at
100 dpc. It simulated 20,000 exact lineages for each: per phase the exact
birth–death law for every founder copy, and the binomial draw at every
division (review.py, results/review-vprime.csv). The copy-number
minimum lies at 8.5 dpc for all 28 sets, with 481 to 1,200 copies on
average. No lineage died out there. The largest errors occur at 100 dpc
in the sets with about 20 copies, where 6% of lineages have lost or fixed
the mutant. The headline list gives the counts. The approximation does
not change which draws are accepted beyond the Monte Carlo error of the
check. One draw, at distance 39.994, crosses the threshold by 0.006,
far less than one Monte Carlo standard error (0.21).
The independent mouse groups
* marks the two litters flagged in the manifest. The population band is
the 95% posterior range of the population V'. The group-sized band adds
the sampling spread of that many cells. Only the group-sized band is a
fair test for a single group.
| Group | Litter | Day | Cells | Observed V’(h) | Population band | Group-sized band | Inside |
|---|---|---|---|---|---|---|---|
| 1 | 1551 | 24 | 25 | 0.0102 | 0.0201 to 0.0341 | 0.0140 to 0.0455 | no |
| 2 | 1425 | 24 | 30 | 0.0147 | 0.0201 to 0.0341 | 0.0145 to 0.0444 | yes |
| 3 | 1424* | 25 | 21 | 0.0551 | 0.0202 to 0.0347 | 0.0126 to 0.0473 | no |
| 4 | 1424* | 25 | 13 | 0.0585 | 0.0202 to 0.0347 | 0.0103 to 0.0567 | no |
| 5 | 1554 | 25 | 13 | 0.0387 | 0.0202 to 0.0347 | 0.0095 to 0.0571 | yes |
| 6 | 1554 | 25 | 11 | 0.0202 | 0.0202 to 0.0347 | 0.0086 to 0.0549 | yes |
| 7 | 1424* | 29 | 30 | 0.0167 | 0.0206 to 0.0366 | 0.0150 to 0.0505 | yes |
| 8 | 1424* | 29 | 34 | 0.0256 | 0.0206 to 0.0366 | 0.0159 to 0.0460 | yes |
| 9 | 1550 | 30 | 20 | 0.0262 | 0.0207 to 0.0370 | 0.0132 to 0.0561 | yes |
| 10 | 1550 | 30 | 17 | 0.0163 | 0.0207 to 0.0370 | 0.0127 to 0.0570 | yes |
| 11 | 1550 | 30 | 36 | 0.0210 | 0.0207 to 0.0370 | 0.0156 to 0.0471 | yes |
| 12 | 1197 | 45 | 25 | 0.0252 | 0.0214 to 0.0419 | 0.0151 to 0.0585 | yes |
| 13 | 1403 | 58 | 24 | 0.0407 | 0.0222 to 0.0607 | 0.0159 to 0.0715 | yes |
| 14 | 1406* | 58 | 20 | 0.0457 | 0.0222 to 0.0607 | 0.0148 to 0.0722 | yes |
| 15 | 1422 | 61 | 20 | 0.0364 | 0.0226 to 0.0634 | 0.0153 to 0.0674 | yes |
Two groups of litter 1424 at 25 dpc have twice the predicted variance.
Group 1 has less than predicted. The sample band depends on a founder law
fitted to two moments, not on the exact six-phase law. That band starts
from the group’s own observed mean. This conditioning matters little,
because V' does not depend on the mean to first order. Together with
the missing transformation and split of the paper, this makes the
comparison a new validation, not a reproduction of Figure 4D.
Sampler diagnostics
results/abc.csv holds acceptance, distances and effective sizes per
ensemble. results/review-ensembles.csv adds, per ensemble, the 2.5%,
50% and 97.5% quantiles of each free parameter and of the eight monitored
observables, and a rank-normalized R-hat that treats each walker as a
chain. Medians of the monitored observables agree across ensembles. The
tails of weakly identified parameters do not. They include the growth
rates of phases 4 and 5 and the lengths of the quiescent phases. The
review declared R-hat below 1.05 as the bound before computing it; the
parameters exceed it, so the ensembles disagree on those tails. The
summed effective size of 1,191 refers to the eight observables only. If
the minimum is taken after summing over ensembles, it is 1,376.
Final-phase degradation
The appendix fixes replication in phase 6 to zero, and its prior covers
degradation in every phase. The stored run also fixes the phase-6
degradation at zero. The sensitivity run frees it (--free-final-degradation, same seeds and size):
| Phase-six degradation | Acceptance | Effective size | MAD log copies | MAD V’(h) | Copies at 100 dpc, median (95%) | HB inside |
|---|---|---|---|---|---|---|
| fixed at 0 | 5.7% to 9.9% | 1191 | 0.424 | 0.00455 | 6,562 (75 to 282,709) | 12 of 15 |
| free on [0, 1] per hour | 9.9% to 20.0% | 1706 | 0.418 | 0.00461 | 7,096 (30 to 221,885) | 12 of 15 |
The Figure 3 comparison and the group comparison barely change. In about half of the accepted sets (more when the rate is free) phase 6 starts after 100 dpc, so the final-phase rate is not identified by the data. The 100 dpc discrepancy remains.
Choices, checks and limits
Reconstruction choices
The paper leaves these points open, or the example departs from it. The measured effect comes from the stored review files.
| Choice | Paper | Example | Measured effect |
|---|---|---|---|
| Ages of the cell-count rows at 7, 14 and 21 h | printed as 0.29, 0.58, 0.88 dpc | 7/24, 14/24, 21/24 dpc, after the division | Large: with the printed values about half of the accepted states leave the threshold (review-age-shift.csv) |
| Observation exactly at a division | not stated | sees the daughter | part of the row above |
| Degradation in phase 6 | replication fixed at 0; degradation under the [0, 1] prior | fixed at 0 | Small on Figure 3 and the groups (review-final-degradation.csv) |
| Log base in the distance | not stated | natural | not measured; base 10 would weight copy number 5.3 times less |
| Variance term in the distance | written V(h) in the appendix formula, normalized variance in the text and Table 1 | V'(h) | not measured |
| Heteroplasmy variance in the distance | first-order expansion | first-order expansion of exact count moments | below 3.4% relative error (review-vprime.csv) |
| Sampler | Metropolis chain, small normal steps | 4 ensembles of 16 differential evolution walkers | same target; ensembles disagree in parameter tails |
| First division | not stated | at 7 h | not measured |
| Extra rejection | none | first-order V' above 1 at a data age | not measured |
| Figure 3 reference | the published figure | central curve and two envelopes read by eye at 6 ages | ±3 pixels on the center only |
| Figure 4 comparison | half of the groups fitted, transformed single cells of the other half against a 95% range | no group fitted; group V' against a sample-size range | a new validation, not Figure 4D |
What the check guards
validation/check_mtdna_bottleneck.py runs in about a second without
Numba and without a stored run. It checks:
- the binomial partition law;
- the founder-family law of the descendant sampler against the CRN-craft finite state projection;
- the native lineage driver;
- the mean recurrence across all six phases and 36 divisions, and the first-order variance added by divisions;
- the reference files: 74 Table 1 rows and their count per study, the four
division-timed ages, 339 cells in 15 groups, and group means and
V'against the spreadsheet summary; - the structure of the stored results and their distances;
- every table, list and quoted number on these pages against the stored result files.
--write regenerates the tables after a new run.
What was not verified
- The 74 Table 1 values, sample sizes and studies were compared with the first published version of the paper. Table 2 of the final version and the Figure 4 source spreadsheet could not be opened during the review. The HB cell values were checked only against the summary rows of the same spreadsheet.
- The Figure 3 image could not be viewed during the review. The digitized values and their calibration are unchecked.
- The paper does not state the width of its two Figure 3 envelopes or the number of accepted parameter sets behind them.
- The cause of the 100 dpc copy-number discrepancy is not found. Freeing the phase-6 degradation and the first-order variance are ruled out.
- The draft and full sizes were not timed without Numba.
Data and license
The paper, its tables and its source data are published under the
Creative Commons Attribution 4.0 license. The reference CSV files are
derived from them and keep that license; cite the paper when reusing
them. fetch.py downloads and converts the sources again. No code of the
authors was used.
Exercises
- Run
study.py --size draftand compare its effective sizes with the stored full run. Why does the effective size per sweep drop for the longer run? - Change the three early ages back to 0.29, 0.58 and 0.88 dpc in
reference-table1.csvand rerun the draft size. Which part of Figure 3 moves? - Add a copy-number constraint at 100 dpc (for example, the published
central value with a factor-two error) and see whether the late
V'values can still be fitted. - Replace the group-sized band with exact lineages from
review.pyand count the groups again.
S7. Protein distributions from four reactions
What this chapter reproduces
An mRNA arrives at a constant rate, each mRNA translates proteins independently, and both species decay. How well does a negative-binomial law describe the protein count of these four reactions, and when does it fail? The chapter reconstructs Figure 1B–D of
Shahrezaei V., Swain P.S. (2008). Analytical distributions for stochastic gene expression. PNAS 105, 17256–17261. doi:10.1073/pnas.0803850105 (Equation 9 and Figure 1; author manuscript arXiv:0812.3344)
The paper publishes no data or code for Figure 1. Everything here is
computed from the reactions; the only values taken from the paper are the
18 marker heights of Figure 1D, read from the figure image
(reference-figure1d.csv, digitize.py). The paper’s authors did not
write or review this chapter.
The result in three lines:
- Two protein distributions with the same mean of 50 copies: one peaks at 47–48 copies, the other at zero and puts 5–8% of its mass above 150 copies. Four ensembles of 10,000 cells agree with the computed laws within a 99% simultaneous band.
- The negative-binomial law of Equation 9 becomes exact as mRNA lifetimes shrink (γ large). At γ = 0.063 its Kullback–Leibler divergence from the reaction law is 0.22 nats for the narrow and 0.97 nats for the broad regime.
- The published Figure 1D values are 1.45–1.52 times these numbers in both regimes. In bits (logarithm base 2) they agree within 0.024, about the reading error of the figure. The paper does not state the unit, and the review could not inspect the figure’s axis labels, so this is the likely cause, not a confirmed one.
The model
Time is measured in protein lifetimes, so the protein decay rate is one.
The paper writes transcription rate v0, translation rate v1 per mRNA,
and decay rates d0 (mRNA) and d1 (protein). It sets a = v0/d1,
b = v1/d0 and γ = d0/d1.
| Reaction | Propensity | Meaning |
|---|---|---|
| ∅ → M | a | transcription, a mRNAs per protein lifetime |
| M → M + P | b·γ·M | translation, b proteins per mRNA lifetime on average |
| M → ∅ | γ·M | mRNA decay |
| P → ∅ | P | protein decay |
The stationary protein law has mean a·b and Fano factor (variance over
mean) 1 + b·γ/(1 + γ) for every γ. For γ → ∞, Equation 9 of the paper
gives the negative-binomial law with shape a and success probability
1/(1 + b), which is SciPy’s nbinom(a, 1/(1 + b)). The paper gives no
physical rate for Figure 1; the results here hold for any d1.
The two regimes are a = 20, b = 2.5 (narrow) and a = 0.5, b = 100
(broad). The caption of Figure 1 gives the mean mRNA number a/γ as 2 or
20 in panel B and 0.05 or 0.5 in panel C, which fits these a at γ = 10
and 1. The values of b and the use of the same a, b across the
γ sweep of panel D come from the study plan; the caption does not state
them.
A small model checks CRN-craft’s finite state projection (FSP). The printed number is the probability that neither an mRNA nor a protein is present after one protein lifetime.
import crn_craft as crn
model = crn.Model("two_stage")
model.add_species({"M": 0, "P": 0})
model.add_reaction(0.7, [], ["M"], name="transcription")
model.add_reaction(2.4, ["M"], ["M", "P"], name="translation")
model.add_reaction(2.0, ["M"], [], name="mrna_decay")
model.add_reaction(1.0, ["P"], [], name="protein_decay")
result = model.fsp(end=1.0, report_times=[1.0], bounds={"M": 5, "P": 8})
print(f"{result.metadata['snapshots'][0]['probabilities'][0]:.4f}")
0.6637
How the distributions are computed
Three independent calculations are compared.
- Native FSP. On the small model above it agrees with SciPy’s matrix
exponential of the same truncated generator to 1.9e-13 in every state
probability. On the narrow regime at γ = 1 and three protein lifetimes
(box M ≤ 50, P ≤ 106), its protein marginal differs from the
generating function below by 5.1e-8 in the cumulative distribution
function (CDF), with 7.3e-8 probability leaving the box. The sweep
needs 32 lifetimes of the slower species (below). With this box the
native solver still runs to 6 protein lifetimes but stops before 12
with
CRN-E070, because it caps a projection at 200,000,000 work units. FSP is therefore not used for the sweep. - Generating function (production). mRNAs arrive as a Poisson
process. An mRNA of age
sthat is still alive has left a Poisson number of surviving proteins; one that died has left a Poisson number that decays further. Integrating over arrival times and lifetimes gives the probability generating function of the protein count at timeTfrom zero counts. It is inverted on 2,048 or 4,096 roots of unity.Tis 32 lifetimes of the slower species: 507 protein lifetimes at γ = 0.063. DoublingTchanges no CDF by more than 1.4e-12; doubling the support and refining the quadrature by no more than 1.1e-7. The mass above 2,047 copies is at most 2.5e-13. - Stationary master equation (review).
review.pysolves the truncated joint master equation for its stationary vector with a sparse LU factorization. It shares no code with the production solver. At all 20 parameter rows the two agree within 1.5e-12 in divergence, and within 2.4e-10 in the CDF of the four tabulated cases. Both reproduce the exact mean and Fano factor within 1.1e-9 (relative).stationary_check.pysolves the same 20 rows with CRN-craft’sstationary_fsp(closed classes and a sparse LU in the native engine) and agrees with this solver within 1e-13 in the CDF.
Exact stochastic simulation (Gillespie’s direct method) gives 10,000
independent cells per Figure 1B–C case, each started from zero and read
once at time T.
The protocol
The targets in manifest.json were fixed before the runs: numerical tail
below 1e-6, CDF change below 0.001 when T doubles, mean and Fano factor
within 1% of the exact values. The four simulated CDFs are compared with
the computed laws by the Dvoretzky–Kiefer–Wolfowitz (DKW) inequality,
two-sided, at 99% simultaneous over the four panels:
sqrt(ln(2·4/0.01)/(2·10,000)) = 0.0183. The divergence convention was
fixed as the reaction law relative to the negative-binomial law, counts
0–150 and one bin above 150. The review’s convention tests and their
decision rules were declared before the review run (see the limits
below).
Two distributions with mean 50

Lines: computed laws. Dots: every fifth count of the 10,000 simulated cells.
| a, b | γ | Mean mRNA a/γ | Most likely count | P(0) | Mass above 150: reaction law / NB / sample | Sample CDF gap | DKW bound |
|---|---|---|---|---|---|---|---|
| 20, 2.5 | 1 | 20 | 48 | 0.0000 | 0.0000 / 0.0000 / 0.0000 | 0.0062 | 0.0183 |
| 20, 2.5 | 10 | 2 | 47 | 0.0000 | 0.0000 / 0.0000 / 0.0000 | 0.0107 | 0.0183 |
| 0.5, 100 | 1 | 0.5 | 0 | 0.0749 | 0.0491 / 0.0833 / 0.0486 | 0.0059 | 0.0183 |
| 0.5, 100 | 10 | 0.05 | 0 | 0.0971 | 0.0830 / 0.0833 / 0.0799 | 0.0066 | 0.0183 |
All four sample gaps lie inside the bound: numerical agreement. The broad regime puts 5–8% of the cells beyond the plotted axis; a fit or a divergence that drops them misses that mass.
Approximation error across lifetime ratios

Solid lines: the divergence of the exact reaction law from Equation 9, in bits. Dashed lines: the same divergence estimated from 10,000 draws of the reaction law (mean of 20 repeats, ± standard deviation in the table), which is what a divergence from a simulated histogram measures. Open circles: the digitized paper values; their reading error is 0.017.
| γ | a=20: published | a=20: bits | a=20: bits, 10,000 draws | a=0.5: published | a=0.5: bits | a=0.5: bits, 10,000 draws |
|---|---|---|---|---|---|---|
| 0.0631 | 0.327 | 0.319 | 0.324 ± 0.006 | 1.417 | 1.400 | 1.409 ± 0.009 |
| 0.126 | 0.269 | 0.268 | 0.275 ± 0.008 | 0.978 | 0.961 | 0.975 ± 0.011 |
| 0.251 | 0.203 | 0.198 | 0.203 ± 0.006 | 0.551 | 0.538 | 0.549 ± 0.009 |
| 0.501 | 0.128 | 0.122 | 0.125 ± 0.005 | 0.240 | 0.228 | 0.237 ± 0.006 |
| 1 | 0.058 | 0.060 | 0.067 ± 0.005 | 0.091 | 0.070 | 0.081 ± 0.005 |
| 2 | 0.012 | 0.024 | 0.031 ± 0.002 | 0.037 | 0.014 | 0.024 ± 0.002 |
| 3.98 | 0.000 | 0.008 | 0.015 ± 0.001 | 0.017 | 0.003 | 0.014 ± 0.002 |
| 7.94 | 0.000 | 0.002 | 0.010 ± 0.001 | 0.004 | 0.001 | 0.012 ± 0.001 |
| 15.8 | 0.000 | 0.001 | 0.008 ± 0.001 | 0.004 | 0.000 | 0.011 ± 0.001 |
The paper says only that it plots “the Kullback–Leibler divergence between the analytical and simulated protein distributions”. Direction, binning, tail handling, logarithm base and sample size are open. The review computed each choice at all 18 digitized points:
| Convention | Published / candidate, 8 values ≥ 0.1 | Largest gap, 18 values |
|---|---|---|
| Reaction law vs NB, nats, 0–150 + tail (shipped) | 1.45–1.52 | 0.447 |
| Reversed direction, nats | 0.52–1.45 | 1.296 |
| No tail bin, nats | 1.28–1.52 | 0.447 |
| 0–150 renormalized, nats | 1.45–1.85 | 0.534 |
| All counts, nats | 1.42–1.52 | 0.447 |
| Tail bin above 100, nats | 1.45–1.89 | 0.458 |
| Tail bin above 300, nats | 1.42–1.52 | 0.447 |
| Bins of width 5, nats | 1.47–1.57 | 0.451 |
| Shipped convention in bits | 1.00–1.05 | 0.024 |
| Bits, 1,000 simulated draws | 0.70–0.95 | 0.118 |
| Bits, 10,000 simulated draws | 0.98–1.02 | 0.018 |
Reversing the direction or changing the bins changes the ratio from point to point, so neither explains a common factor. The ratio in nats is nearly constant at 1.47, close to 1/ln 2 = 1.443, and the bits convention matches every point within 1.5 reading errors. Estimating the divergence from 10,000 simulated cells adds a small positive bias. That bias also explains why the published broad-regime values stay above zero at γ = 4–16, where the exact divergence is below 0.003 bits.
One alternative remains open: if the figure’s top tick were 1.0 instead
of the 1.5 used in digitize.py, the published values would shrink by
1.5 and agree with nats within 0.026. The review could not see the
figure image to rule this out. The result is therefore labeled
unresolved between logarithm base and axis calibration, with bits the
better fit. The paper’s statement that the two laws become almost
indistinguishable for γ above 1 is reproduced.
Reconstruction choices
| Choice | Value here | Paper | Measured effect |
|---|---|---|---|
b in both regimes, same a, b along the γ sweep | 2.5 and 100, fixed | not stated in the text | not testable without the figure |
| Divergence direction | reaction law relative to NB | not stated | reversing: ratio 0.52–1.45 instead of 1.45–1.52 |
| Logarithm base | nats in divergence.csv, bits in the figure | not stated | factor 1.443 |
| Bins and tail | 0–150 and one tail bin | not stated | narrow: at most 4% (width-5 bins); broad: 9–13% at γ ≤ 0.13, up to a factor 3 at γ ≥ 2 |
| Reference law | exact stationary law | finite simulation | +0.003 to +0.014 bits at 10,000 cells |
| Initial state of simulated cells | zero counts, read at T | not stated | CDF change below 1.4e-12 when T doubles |
| γ grid | 0.3-decade steps, 10^-1.2 to 10^1.2 | read from figure | none |
Limits
- The figure image was not available to the review: the arXiv PDF could
not be downloaded and the text versions carry no image. Axis
calibration, the values of
band the marker assignment indigitize.pyare unchecked. - The digitized values have a reading error of 0.017 in the plotted unit; zero readings at large γ only mean “below about 0.02”.
- The simulated checks cover the four Figure 1B–C cases; the sweep rows rely on the two solvers and the moment identities.
- The paper’s simulation sample size is unknown; the 10,000-cell bias column shows its size for one choice.
Running the example
| Size | What it does | Cost |
|---|---|---|
--size quick | small FSP and matrix-exponential check, 1,000 cells | 2 s |
--size draft | the four Figure 1B–C cases with 10,000 cells each | 30 s |
--size full | all 20 rows of the sweep and the four ensembles | 90 s |
review.py | stationary master equation and the convention table | 90 s |
study.py --figures docs/guide/img/two_stage_expression redraws both
figures from the stored results. The draft size uses other seeds than the
full run, so its sample gaps differ. Example and result
files
Exercises
- Compute the stationary Fano factor at γ = 1 for both regimes from the
formula and check it against
divergence.csv. - Put the tail bin above count 50 (
binned(pmf, 50)inreview.py) and recompute the broad regime. Which γ changes most, and why? - Draw 1,000 instead of 10,000 cells. How large does the bias of the divergence become at γ = 16?
What carries over to tutorial O3
The two regimes have the same mean and very different shapes, so a fit to means alone cannot tell them apart. A distribution comparison has to fix its direction, binning, tail handling, unit and sample size before the fit, because each choice changes the number. Tutorial O3 fits the mean and the count distribution of a real experiment.
O1. Fitting parameters to data
This chapter estimates two parameters of the three-class mtDNA model of
tutorial S1: the mutation probability mu and the
replication advantage sm of advantaged mutants. They are fitted to
single-cell data with the derivative-free optimizers of
fcmaes. The objective is a
stochastic simulation, so the chapter also covers what that changes: Monte
Carlo noise, common random numbers, staged refinement, held-out checks and
how to spend the cores of a machine. The fitting scripts need two more
packages:
pip install crn-craft fcmaes scipy
Each block of this chapter is a complete script, the file named above it in
examples/mtdna/.
Run it from that folder or from the repository root. The outputs are from
one full run on 13 November 2026 on a two-CPU host. The guide’s checker runs the
scripts in a short form, with few cells and three evaluations, when
CRN_CRAFT_SMOKE=1 is set; the full run takes about thirteen minutes (4, 7
and 2 minutes for the three scripts).
The problem
Applies: tutorial S1, The model.
Single-cell measurements, such as COX staining or single-cell sequencing,
give the mutant fraction of individual cells at a few ages. The model
predicts, for any mu and sm, the distribution of mutant fractions
across cells at each age. Fitting means finding the parameters whose
predicted distributions match the observed ones.
Each prediction is an ensemble of simulated cells. A three-year cell at
K = 1000 has about 150,000 events. Each script builds the model with the
three_class function of tutorial S1 and runs it on the fast path,
method="mtdna_direct", which certifies the builder model
(page S1d). One objective evaluation
with 800 cells then takes about 2 s on two cores, so a hundred evaluations
take between three and four minutes. Under Static Direct, the same
evaluation takes about 3.6 times as long
(tutorial S1, Conventions).
To be able to check the answer, the chapter makes its own data from known
parameters (mu = 3·10⁻⁵, sm = 1.5), with a seed that the fit never sees.
With real data, replace the observations by the measured fractions.
A first attempt with takeover fractions
Applies: page S1a, Takeover fraction and time to threshold.
Takeover data are often all that is available: the fraction of cells past a
threshold, for example 90% mutants, at a few ages. The first script fits
mu and sm to the takeover fractions at 360, 720 and 1080 days, plus the
mean mutant fraction. It runs 100 BiteOpt evaluations:
"""Fit the mutation probability and the replication advantage to takeover data."""
import math
import os
import sys
import time
import numpy as np
import crn_craft as crn
from fcmaes import bitecpp
from scipy.optimize import Bounds
SMOKE = os.environ.get("CRN_CRAFT_SMOKE") == "1" # CI: few cells, 3 evaluations
def cells(count):
return max(count // 100, 16) if SMOKE else count
def three_class(
K=1000, w0=1000, m0=0, mu=3e-5, sm=1.5, half_life_days=10, takeover=None
):
"""The three-class mtDNA model: wild type W, neutral M, advantaged A."""
model = crn.Model("mtdna_three_class")
model.add_parameter(
{
"K": K,
"delta": math.log(2) / (24 * half_life_days),
"sw": 1.0,
"sm": sm,
"mu": mu,
"fracAdv": 0.2,
}
)
model.add_species({"W": w0, "M": m0, "A": 0})
free = "max(0, K - W - M - A) / (W + sm * (M + A))"
model.add_reaction(
f"{free} * sw * (1 - mu) * W", ["W"], ["W", "W"], "replication_wt"
)
model.add_reaction(
f"{free} * sw * mu * (1 - fracAdv) * W", ["W"], ["W", "M"], "mutation_mt"
)
model.add_reaction(
f"{free} * sw * mu * fracAdv * W", ["W"], ["W", "A"], "mutation_mtAdv"
)
model.add_reaction(f"{free} * sw * M", ["M"], ["M", "M"], "replication_mt")
model.add_reaction(f"{free} * sm * A", ["A"], ["A", "A"], "replication_mtAdv")
for label, species in (("wt", "W"), ("mt", "M"), ("mtAdv", "A")):
model.add_reaction(f"delta * {species}", [species], [], f"degradation_{label}")
if takeover is not None:
model.set_stop(f"W + M + A > 0 && M + A >= {takeover} * (W + M + A)")
return model
DAYS = np.array([360, 720, 1080])
MODEL = three_class(takeover=0.9)
def template(count, seed, threads=2):
return crn.ensemble(
MODEL,
end=25_920.0,
report_times=24.0 * np.concatenate(([0], DAYS)),
replicates=cells(count),
seed=seed,
threads=threads,
method="mtdna_direct", # the fast path (page S1d)
)
def summaries(result):
"""Fraction of cells taken over by each age, and mean mutant fraction."""
stop = result.records["stop_time"]
stopped = result.records["termination"] == "stopped"
taken = np.array([(stopped & (stop <= 24.0 * d)).mean() for d in DAYS])
mean = result.statistics["mean"].iloc[1:] # the report times after day 0
load = ((mean["M"] + mean["A"]) / mean.sum(axis=1)).to_numpy()
return taken, load
# 1. Synthetic observations from known parameters and an independent seed.
TRUE = {"mu": 3e-5, "sm": 1.5}
if __name__ == "__main__":
start = time.perf_counter()
observed = summaries(template(4000, seed=2024).bind_parameters(TRUE).simulate())
print("observed takeover:", np.round(observed[0], 4))
print("observed mutant fraction:", np.round(observed[1], 4))
print(f"data: {time.perf_counter() - start:.1f} s")
SEARCH = template(800, seed=7) # fixed seed: common random numbers
def objective(x, prepared=SEARCH, observed_data=None):
mu, sm = 10.0 ** x[0], x[1]
taken, load = summaries(prepared.bind_parameters({"mu": mu, "sm": sm}).simulate())
taken_obs, load_obs = observed_data or OBSERVED
# Binomial standard errors of the observed takeover fractions; a floor
# keeps empty early bins from dominating.
se = np.sqrt(np.maximum(taken_obs * (1 - taken_obs), 0.01) / 800)
return float(
np.sum(((taken - taken_obs) / se) ** 2)
+ np.sum(((load - load_obs) / (0.1 * load_obs + 1e-3)) ** 2)
)
if __name__ == "__main__":
OBSERVED = observed
evaluations = int(sys.argv[1]) if len(sys.argv) > 1 else 100
evaluations = 3 if SMOKE else evaluations
bounds = Bounds([-5.5, 1.0], [-3.5, 2.5])
start = time.perf_counter()
found = bitecpp.minimize(
objective,
bounds=bounds,
max_evaluations=evaluations,
rg=np.random.default_rng(42),
)
seconds = time.perf_counter() - start
mu, sm = 10.0 ** found.x[0], found.x[1]
print(
f"BiteOpt: {found.nfev} evaluations in {seconds:.0f} s, "
f"loss {found.fun:.2f}, mu {mu:.2e}, sm {sm:.3f}"
)
# 2. Held out: the fitted and the true parameters with fresh cells.
check = template(4000, seed=99)
for label, values in (("fitted", {"mu": mu, "sm": sm}), ("true", TRUE)):
taken, load = summaries(check.bind_parameters(values).simulate())
print(
f"{label:6s} held-out takeover {np.round(taken, 4)} load {np.round(load, 4)}"
)
observed takeover: [0.0125 0.062 0.1078]
observed mutant fraction: [0.0254 0.0675 0.1119]
data: 10.2 s
BiteOpt: 100 evaluations in 202 s, loss 0.90, mu 1.87e-05, sm 2.269
fitted held-out takeover [0.0335 0.083 0.133 ] load [0.0374 0.0823 0.1264]
true held-out takeover [0.0112 0.0605 0.1078] load [0.0226 0.0682 0.1097]
The fit reaches a low loss on its own 800 cells, with mu more than a
third too small (1.9·10⁻⁵) and sm far too large (2.27). On 4000 fresh
cells its parameters predict 13.3% of cells taken over by day 1080, where
the data and the true parameters have 10.8%. Two things went wrong:
- Confounding. Takeover fractions mainly measure how many lineages succeed per unit time. Fewer mutations with a larger advantage give nearly the same curve as more mutations with a smaller one.
- Overfitting to noise. With one fixed set of 800 cells, the optimizer can find parameters that fit those cells’ accidents. The held-out check shows it: the fit was best on its own cells, not on fresh ones.
The remedy for the first is more informative data. The remedy for the second is more cells in a second stage and an independent check.
A better objective with heteroplasmy distributions
Applies: chapter 4, Single trajectories.
The distribution of mutant fractions separates the two parameters:
musets how many cells carry any mutants at all;smsets how fast they move toward high mutant fractions.
The objective compares, at each age, the fraction of cells whose mutant
fraction reaches 1%, 10%, 50% and 90%. The mutant fraction of a cell is
(M + A) / (W + M + A), read from the kept paths. Each difference is scaled
by its binomial standard error:
"""Fit the mutation probability and the replication advantage to
single-cell heteroplasmy distributions at three ages."""
import math
import os
import sys
import time
import numpy as np
import crn_craft as crn
from fcmaes import bitecpp
from scipy.optimize import Bounds
SMOKE = os.environ.get("CRN_CRAFT_SMOKE") == "1" # CI: few cells, 3 evaluations
def cells(count):
return max(count // 100, 16) if SMOKE else count
def three_class(
K=1000, w0=1000, m0=0, mu=3e-5, sm=1.5, half_life_days=10, takeover=None
):
"""The three-class mtDNA model: wild type W, neutral M, advantaged A."""
model = crn.Model("mtdna_three_class")
model.add_parameter(
{
"K": K,
"delta": math.log(2) / (24 * half_life_days),
"sw": 1.0,
"sm": sm,
"mu": mu,
"fracAdv": 0.2,
}
)
model.add_species({"W": w0, "M": m0, "A": 0})
free = "max(0, K - W - M - A) / (W + sm * (M + A))"
model.add_reaction(
f"{free} * sw * (1 - mu) * W", ["W"], ["W", "W"], "replication_wt"
)
model.add_reaction(
f"{free} * sw * mu * (1 - fracAdv) * W", ["W"], ["W", "M"], "mutation_mt"
)
model.add_reaction(
f"{free} * sw * mu * fracAdv * W", ["W"], ["W", "A"], "mutation_mtAdv"
)
model.add_reaction(f"{free} * sw * M", ["M"], ["M", "M"], "replication_mt")
model.add_reaction(f"{free} * sm * A", ["A"], ["A", "A"], "replication_mtAdv")
for label, species in (("wt", "W"), ("mt", "M"), ("mtAdv", "A")):
model.add_reaction(f"delta * {species}", [species], [], f"degradation_{label}")
if takeover is not None:
model.set_stop(f"W + M + A > 0 && M + A >= {takeover} * (W + M + A)")
return model
DAYS = np.array([360, 720, 1080])
EDGES = np.array([0.01, 0.1, 0.5, 0.9]) # mutant fraction thresholds
MODEL = three_class(takeover=0.9)
TRUE = {"mu": 3e-5, "sm": 1.5}
def template(count, seed, threads=2):
return crn.ensemble(
MODEL,
end=25_920.0,
report_times=24.0 * DAYS,
replicates=cells(count),
seed=seed,
threads=threads,
method="mtdna_direct", # the fast path (page S1d)
keep_paths="all",
max_output_bytes=256 << 20,
)
def heteroplasmy(result):
"""Fraction of cells whose mutant fraction reaches each edge, per age."""
paths = result.paths # cells x report times x species
mutants = paths.sel(variable="M") + paths.sel(variable="A")
fraction = (mutants / paths.sum("variable")).to_numpy()
return (fraction[:, :, None] >= EDGES).mean(axis=0) # ages x edges
def loss(simulated, observed, count):
# Binomial standard errors of the observed fractions, with a floor.
se = np.sqrt(np.maximum(observed * (1 - observed), 0.005) / count)
return float(np.sum(((simulated - observed) / se) ** 2))
SEARCH_CELLS = cells(800)
SEARCH = template(800, seed=7) # one seed for every candidate
def objective(x):
candidate = SEARCH.bind_parameters({"mu": 10.0 ** x[0], "sm": x[1]})
return loss(heteroplasmy(candidate.simulate()), OBSERVED, SEARCH_CELLS)
if __name__ == "__main__":
start = time.perf_counter()
OBSERVED = heteroplasmy(template(4000, seed=2024).bind_parameters(TRUE).simulate())
print(f"observed ({time.perf_counter() - start:.0f} s), rows are days {DAYS}:")
print(np.round(OBSERVED, 4))
evaluations = int(sys.argv[1]) if len(sys.argv) > 1 else 100
evaluations = 3 if SMOKE else evaluations
start = time.perf_counter()
found = bitecpp.minimize(
objective,
bounds=Bounds([-5.5, 1.0], [-3.5, 2.5]),
max_evaluations=evaluations,
rg=np.random.default_rng(42),
)
mu, sm = 10.0 ** found.x[0], found.x[1]
print(
f"stage 1: {found.nfev} evaluations in {time.perf_counter() - start:.0f} s, "
f"loss {found.fun:.1f}, mu {mu:.2e}, sm {sm:.3f}"
)
# Stage 2: more cells and a new seed in a box around the first estimate.
SEARCH_CELLS = cells(2400)
SEARCH = template(2400, seed=8)
start = time.perf_counter()
lower = [found.x[0] - 0.2, max(1.0, found.x[1] - 0.3)]
upper = [found.x[0] + 0.2, found.x[1] + 0.3]
refined = bitecpp.minimize(
objective,
bounds=Bounds(lower, upper),
x0=found.x,
max_evaluations=max(evaluations // 3, 1),
rg=np.random.default_rng(43),
)
first = {"mu": mu, "sm": sm}
mu, sm = 10.0 ** refined.x[0], refined.x[1]
print(
f"stage 2: {refined.nfev} evaluations in {time.perf_counter() - start:.0f} s, "
f"loss {refined.fun:.1f}, mu {mu:.2e}, sm {sm:.3f}"
)
check = template(4000, seed=99)
for label, values in (
("stage 1", first),
("stage 2", {"mu": mu, "sm": sm}),
("true", TRUE),
):
held = heteroplasmy(check.bind_parameters(values).simulate())
print(f"{label:7s} held-out loss {loss(held, OBSERVED, cells(4000)):7.1f}")
observed (10 s), rows are days [ 360 720 1080]:
[[0.0648 0.036 0.025 0.0125]
[0.122 0.0828 0.0712 0.062 ]
[0.1798 0.1352 0.1212 0.1078]]
stage 1: 100 evaluations in 200 s, loss 1.5, mu 2.99e-05, sm 1.601
stage 2: 33 evaluations in 201 s, loss 5.7, mu 3.06e-05, sm 1.475
stage 1 held-out loss 68.6
stage 2 held-out loss 9.8
true held-out loss 6.8
How the script is built:
- One prepared template.
template(cells, seed)prepares the ensemble once. Every candidate isSEARCH.bind_parameters({...}).simulate(), which binds new values without rebuilding the request (chapter 5). - Common random numbers. All candidates of a stage share one seed, so every candidate sees the same random streams. Differences between candidates are then due to the parameters, not to different random cells (chapter 5).
- A log scale for
mu. The optimizer works onlog10(mu)in [−5.5, −3.5], which spans two orders of magnitude evenly. - Two stages. Stage 1 (800 cells, 100 evaluations) finds the region.
Stage 2 (2400 cells, a new seed, 33 evaluations) refines inside a box
around it: ±0.2 in
log10(mu)and ±0.3 insm. - A held-out check. 4000 fresh cells with a third seed score stage 1, stage 2 and the true parameters. Only this number says how good a fit is.
Stage 2 recovers mu = 3.06·10⁻⁵ and sm = 1.475, against the true
3·10⁻⁵ and 1.5. Stage 1 found mu already, but sm too large (1.60). Its
held-out loss (68.6) shows it, while stage 2 scores 9.8, close to the true
parameters’ 6.8. Even the true parameters do not reach a loss of zero: the
data are themselves a sample of 4000 cells, and the held-out cells are
another.
Noise and the shape of the objective
Applies: chapter 8, What makes a run reproducible.
The third script imports the second and looks at its objective:
"""Monte Carlo noise of the objective, and parallel evaluation with fcmaes."""
import time
import numpy as np
from fcmaes import de
from loguru import logger
from scipy.optimize import Bounds
import fit_heteroplasmy as fit
fit.OBSERVED = fit.heteroplasmy(
fit.template(4000, seed=2024).bind_parameters(fit.TRUE).simulate()
)
x_true = np.array([np.log10(3e-5), 1.5])
# 1. The same parameters under five search seeds: the loss is noisy.
values = []
for seed in range(5):
fit.SEARCH = fit.template(800, seed=seed)
values.append(fit.objective(x_true))
print("loss at the true parameters, five seeds:", np.round(values, 1))
# 2. With one fixed seed the loss is a deterministic function of the
# parameters: a scan over sm is repeatable, but not smooth.
fit.SEARCH = fit.template(800, seed=7)
for sm in np.linspace(1.3, 1.7, 9):
print(f"sm {sm:.2f}: loss {fit.objective([x_true[0], sm]):6.1f}")
# 3. Parallel candidates: each process prepares its own template once.
_LOCAL = {}
def parallel_objective(x):
if "search" not in _LOCAL:
_LOCAL["search"] = fit.template(800, seed=7, threads=1)
fit.SEARCH = _LOCAL["search"]
return fit.objective(x)
if __name__ == "__main__":
logger.remove() # fcmaes logs every improvement through loguru
start = time.perf_counter()
found = de.minimize(
parallel_objective,
bounds=Bounds([-5.5, 1.0], [-3.5, 2.5]),
popsize=8,
max_evaluations=3 if fit.SMOKE else 32,
workers=2,
rg=np.random.default_rng(5),
)
print(
f"DE, 2 workers x 1 thread: {found.nfev} evaluations in "
f"{time.perf_counter() - start:.0f} s, best loss {found.fun:.1f}"
)
loss at the true parameters, five seeds: [24.1 3.5 6.2 10.6 15.5]
sm 1.30: loss 166.5
sm 1.35: loss 101.1
sm 1.40: loss 68.1
sm 1.45: loss 32.3
sm 1.50: loss 20.9
sm 1.55: loss 4.9
sm 1.60: loss 1.7
sm 1.65: loss 10.5
sm 1.70: loss 16.3
DE, 2 workers x 1 thread: 32 evaluations in 65 s, best loss 263.0
The first line shows the Monte Carlo noise. At the true parameters, five sets of 800 cells give losses between 3.5 and 24.1. A difference of that size between two candidates means nothing unless both used the same cells.
With one fixed seed the loss is a deterministic function of the parameters.
The scan over sm is repeatable and has a valley. It is not smooth,
though: a small parameter change can move an event and change a cell’s
fate. This is why the chapter uses derivative-free optimizers. BiteOpt and
differential evolution handle such objectives; gradient methods and tight
convergence tolerances do not.
Two consequences:
- Do not trust the minimum of one seed. Refine with more cells, and check on a seed the optimizer never saw.
- With few cells, the minimum sits near the truth but where that seed’s
cells happen to fit best: with
muat its true value, this seed’s scan is lowest atsm = 1.60, not 1.50. Stage 1 of the second script, with the same seed, landed there too.
Using all cores
Applies: chapter 5, Threads.
An evaluation can use cores in two ways:
- Threads inside one simulation.
threads=kincrn.ensembleruns the cells of one evaluation in parallel. It needs nothing from the optimizer, and results do not depend onk. - Parallel candidates. fcmaes evaluates several candidates at once in
worker processes:
de.minimize(..., workers=k), or parallel restarts withretry.minimize. Each worker runs its simulations withthreads=1.
On this two-CPU host both gave about the same throughput: about 2 s per evaluation with 2 threads in sequence (stage 1 above), and 32 evaluations in 65 s with 2 workers × 1 thread. The DE run only measures throughput: 32 evaluations are far too few for DE to converge, hence its best loss of 263.0. A real DE fit needs a few thousand evaluations. On a larger machine the choice depends on the cells per evaluation:
- With thousands of cells, threads inside the simulation scale well.
- With a few hundred cells, the fixed costs of preparing and collecting an ensemble weigh more, and parallel candidates scale better.
- The two can be mixed, for example 4 workers × 4 threads on 16 cores.
Each worker process prepares its own template on first use, through the
cached _LOCAL dictionary in the script, because prepared ensembles cannot
be sent between processes. The script relies on Linux’s fork to give the
workers the observed data. On macOS and Windows, which spawn workers, load
the data from a file inside the worker instead. fcmaes logs improvements
through loguru; logger.remove() silences it.
Choosing an optimizer and a budget
Applies: chapter 3, Budgets.
fcmaes offers, among others:
- BiteOpt (
bitecpp.minimize): robust with few evaluations and noisy objectives. A good default for 2–6 parameters and 100–500 evaluations. - Differential evolution (
de.minimize): parallel population evaluation withworkers. Suited to larger budgets. - CMA-ES (
cmaescpp.minimize) and parallel restarts (retry.minimize): for more parameters or multimodal problems.
Practical sizes for this model:
- Start with 100 evaluations per parameter pair at a few hundred cells. Refine with 3–4 times the cells and a third of the evaluations.
- Use enough cells that a bin’s expected count is at least about 10. For a bin holding 1% of cells, that means 1000 cells.
- Put an event budget on candidates (
max_eventsincrn.ensemble) and awall_time_son the whole run. Extreme parameters, such as a very largeKormu, can otherwise make one evaluation very long. Treat a candidate that hits a budget as a high loss.simulate()warns withcrn.IncompleteEnsembleWarningfor such a candidate; silence it withwarnings.simplefilter("ignore", crn.IncompleteEnsembleWarning), or passstrict=Trueand catchcrn.IncompleteEnsembleError.
Making each evaluation cheap
Applies: chapter 5, What output costs.
- Keep only what the loss needs. Here that is three report times of three species per cell. Avoid event logs and callbacks inside an objective.
- Stop cells early. A takeover stop ends a cell’s simulation and saves its remaining events.
- Reuse the template, so that every candidate uses exactly the same settings (page S1e).
- A compiled model does not help here. A loop is compiled for one parameter set, and every candidate has new parameters (chapter 5, Limits).
- The fast path does. The scripts pass
method="mtdna_direct"with the builder model; it ran about 3.6 times as fast as Static Direct on the same model in the measurement of 13 November 2026 (page S1d). It serves only the three-class structure: for another model, or a stop that the fast path does not certify, use Static Direct and checkmetadata["sampler"].
Beyond this example
Applies: chapter 5, Parameter sweeps.
- More parameters. Add
fracAdv,Kor the half-life (delta) to the vector:bind_parametersaccepts any parameter of the model. Expect more confounding, and plan for more data summaries. - Likelihoods. With counts of cells per heteroplasmy bin, a multinomial log-likelihood replaces the scaled squares. The same noise rules apply.
- Other models. The same loop works for the ATP model of
page S1c, at the cost of
hybrid. - Generic lessons. Four optimization tutorials calibrate other models with the same tools.
- Rust. For very large studies, an optimizer in Rust can call the engine directly (Rust API).
Checklist
Applies: chapter 8, What to record for a paper.
- Simulate the data first. Fit to data simulated with parameters you know, before fitting real data.
- Use summaries that separate the parameters. Distributions separate them better than takeover curves alone.
- Fix the seed within a stage. Change it between stages.
- Refine, then hold out. Refine with more cells, then score on a held-out seed.
- Report the held-out loss. Report it with the estimate, along with the spread of the loss at the estimate over a few seeds.
See also: Speed, Large studies, mtDNA performance analysis.
O2. Case study: inferring mtDNA takeover times
What this chapter reproduces
A single-cell experiment sees each cell once. It cannot follow how fast a deletion mutant takes over a cell; it only sees, at each age, how many cells carry how much mutant mtDNA. A 2026 paper asks whether such snapshots are enough to estimate the mutation probability and the selection advantage of the mutants, and then turns the advantage into the time a mutant needs to take over a cell:
Kowald A., Kirkwood T.B.L. (2026). Inferring accumulation times of mitochondrial DNA deletion mutants from cross-sectional single-cell data: methodological framework and validation. npj Aging 12. doi:10.1038/s41514-026-00431-4 (Equation 7, Figures 5 and 6, Tables 2 and 3)
This chapter is a reconstruction from the published text and figures. The authors’ programs and data were not available to it (their repository returned server errors). The printed values of Tables 1 to 3 and the readings of Figures 5 and 6 were checked against the preprint of the paper (bioRxiv 10.64898/2026.01.30.702736, version 1); the review did not have the journal PDF. The paper’s authors did not write or review this chapter.
The result in three lines:
- With 40 synthetic cohorts of 10,000 cells per regime, the fit recovers the mutation probability within 7%, the selection advantage within 20% and the fraction of advantageous mutants within 18% of the truth (95% percentile intervals); every true value lies inside its interval. The fits search a box around the true values, which a real application would not know (what that means).
- In the baseline regime the reconstructed intervals are narrower than the published ones and the published means are shifted (selection advantage +7%, advantageous fraction +9%); in the strong regime both agree more closely. The cause is not known. The optimizer budget, the search box and the surrogate of the forward law are ruled out.
- At selection advantage 0.10, 9.1% of single founder mutants ever reach 90% of the copies, and those that do need a median of 1,038 days. Only 58% of them get there within the three years the data cover.
Words used in this chapter
- Snapshot: the mutant fraction of each cell at one age, without knowing the same cell’s past or future.
- Threshold: the paper summarizes a snapshot by the fraction of cells
with more than 0%, 5%, 20% and 50% mutant copies. A cell with
Mmutants amongNcopies is above 5% when20*M > N, above 20% when5*M > Nand above 50% when2*M > N; a cell exactly at a threshold is not above it. - Cohort: one synthetic data set, 10,000 cells observed at the 37 ages 0, 30, …, 1,080 days. In this reconstruction the same 10,000 cells are followed through all ages.
- Takeover: a mutant lineage reaching 90% of the copies of its cell (900 of 1,000, at least).
- Regime: one set of true parameters. Baseline is
p = 6.8e-6,s = 0.10,f = 0.80(Figure 6, Table 2); strong isp = 3e-5,s = 0.50,f = 0.20(Table 3).
The model in plain words
A cell holds a fixed number of mtDNA copies, 1,000. Copies are replaced one
at a time: one copy is degraded and one copy is replicated, so the number
stays the same. The copy that replicates is chosen in proportion to its
fitness, 1 + s for an advantageous mutant and 1 for the others; the copy
that is degraded is chosen at random, independently. When a wild-type copy
replicates, its daughter is a new deletion mutant with probability p; a
fraction f of new mutants is advantageous, the others are neutral.
Mutants do not mutate again. With a half-life of 10 days, one day is 69.3
such replacements. This is the Moran model of the paper’s Equation 7.
The pages of the chapter:
| Page | Question |
|---|---|
| The model and Figure 6 | What exactly is simulated, how does CRN-craft express it, and how close are the published curves? |
| Fitting snapshots and takeover times | How are the parameters fitted, how well are they recovered, and what does that mean for takeover times? |
| Choices, checks and limits | What did the reconstruction have to decide, how was it checked, and what does it not show? |
CRN-craft and the local solver
The Moran step is six reactions that move one copy between the wild type
W, the neutral mutant U and the advantageous mutant A. CRN-craft
runs them with Static Direct and solves their probability law with finite
state projection (FSP); the model page
runs a seven-copy cell both ways and the check compares them with exact
matrix calculations.
The study itself runs on a small C++17 library local to the example
(examples/kk26/moran.cpp). It changes nothing in CRN-craft. It exists
for two reasons:
- The fit needs the full probability law of a 1,000-copy cell, 501,501 joint count states, at 37 ages, for every parameter set the optimizer tries. A specialized lattice solver does this in about three seconds.
- The paper counts time in Moran steps, a discrete clock, while CRN-craft runs in continuous time. The library has both: the exact discrete law as reference and synthetic data, and a continuous-time solver for the fit. The two agree to 1.2e-5 in probability.
Running the example
You need Python 3.10 or newer, CRN-craft 0.8.0, fcmaes, SciPy, Matplotlib
and a C++17 compiler (set CXX to choose one). The library is built in a
temporary directory the first time a command needs it. Run the commands
from the repository root:
python -m pip install 'crn-craft==0.8.0' 'fcmaes==2.2.0' scipy matplotlib
python examples/kk26/study.py bootstrap --size quick --threads 2
python examples/kk26/study.py fit examples/kk26/results/reconstruction/snapshots-baseline.csv
python examples/kk26/study.py figures
bootstrap --size quick simulates and fits four baseline cohorts of 2,000
cells in about ten seconds. fit fits the first saved baseline cohort and
prints the result as JSON. figures redraws the two figures from the
saved results without simulating. The
example README lists all commands and
output files; the results page
gives the commands of the full study.
See also: Re-creating a published study (the same fixed copy number, with a pair rule), Comparing mtDNA mechanisms (the ATP model that generates panel A of Figure 6), Fitting.
Tutorial S4 follows mtDNA expansion along a muscle fiber.
The model and Figure 6
Part of tutorial O2.
One Moran step
Write W, U and A for the wild-type, neutral-mutant and
advantageous-mutant copies of a cell, N = W + U + A = 1000. One Moran
step draws a daughter type and, independently, a degraded copy:
- The daughter comes from a parent chosen with weights
W,Uand(1+s)*A. A wild-type parent gives a wild-type daughter with probability1-p, a neutral mutant with probabilityp*(1-f)and an advantageous mutant with probabilityp*f. Mutant parents give their own type. - The degraded copy is
W,UorAwith probabilityW/N,U/NandA/N.
The step adds the daughter and removes the degraded copy. When both are of
the same type nothing changes, and the step still counts. This is the
paper’s Equation 7: the probability of a birth of type γ and a death of
type δ is the fitness-weighted share of parents giving rise to γ times
m_δ/N. It differs from the pair rule of
tutorial S2c, where the
parent is chosen among the copies that survive the degradation.
The paper converts days to steps with the replication rate
ln(2)/halfLife: Δt days are about N*ln(2)/halfLife*Δt steps, 69.3
steps per day for a 10-day half-life. The reconstruction uses
floor(days*N*ln(2)/halfLife) steps, 74,860 for 1,080 days.
Snapshots as five bins
At each age a cell falls into one of five bins of its mutant count
M = U + A. A cell exactly at a threshold goes into the lower bin.
| Bin | Mutant fraction | Integer test |
|---|---|---|
| 0 | exactly zero | M == 0 |
| 1 | above 0%, at most 5% | M > 0 and 20*M <= N |
| 2 | above 5%, at most 20% | 20*M > N and 5*M <= N |
| 3 | above 20%, at most 50% | 5*M > N and 2*M <= N |
| 4 | above 50% | 2*M > N |
The four curves of Figure 6, the fractions of cells above 0%, 5%, 20% and 50%, are the sums of bins 1–4, 2–4, 3–4 and 4 divided by the number of cells. The fit uses only these four fractions at each age.
The Moran step in CRN-craft
Applies: chapter 2, Rates as numbers and as strings.
Six reactions move one copy from one type to another, for example
W_to_A (a wild-type copy degraded, an advantageous daughter born). Each
has the probability of its Moran step times the step rate
N*ln(2)/halfLife. native_model in examples/kk26/model.py builds them.
With these rates the steps arrive as a Poisson process instead of a fixed
clock: the count law is the paper’s step law with a random number of steps.
Static Direct samples that continuous-time law; FSP computes it. A
seven-copy cell after 12 days:
import sys
sys.path.insert(0, "examples/kk26")
from model import Model, native_model
seven_copies = native_model(Model(0.05, 0.27, 0.7, copies=7))
result = seven_copies.fsp(
end=12, report_times=[0.0, 12.0], bounds={"W": 7, "U": 7, "A": 7},
max_states=36, tolerance=1e-10,
)
states = result.metadata["states"]
last = result.metadata["snapshots"][-1]["probabilities"]
mutant_fraction = sum(p for state, p in zip(states, last, strict=True) if state[0] < 7)
print(f"{mutant_fraction:.4f}")
0.2017
The printed value is the probability that the cell holds at least one
mutant. validation/check_kk26.py compares this FSP law with the matrix
exponential of the step chain (largest difference 2e-12) and 16,000 Static
Direct cells with it (see checks).
The full-size forward law
A 1,000-copy cell has 501,501 states (U, A). The example’s C++ library
computes their probabilities in two ways:
- Discrete reference: the paper’s law, step by step, including the steps that change nothing. It is exact up to rounding and takes about a minute for 1,080 days.
- Continuous-time solver for the fit: the Poisson-clock law above,
advanced in 5-day steps. Each step splits the moves into three
directions on the
(U, A)lattice (Uup or down,Aup or down, a copy moving betweenUandA) and solves each direction implicitly (Crank–Nicolson, Strang splitting). It takes about three seconds.
To save time both may cap the neutral count, at 192 copies for the baseline and 320 for the strong regime. Probability that would cross the cap is counted as escaped and never put back, so a reported tail fraction is a lower bound and the tail plus the escaped mass an upper bound. The escaped mass is at most 3.2e-4 at the grid nodes of the fit’s search box; at the true baseline parameters the capped law differs from the full lattice by 5.6e-5.
The two clocks give almost the same curves because a cell changes slowly compared with its 69 steps per day. At the true parameters the continuous-time solver differs from the discrete reference by at most 2.6e-6 (baseline) and 1.2e-5 (strong); at two corners of each search box by at most 3.4e-5.
Figure 6

Lines are this reconstruction, open circles every third value read from the paper’s Figure 6. Both panels use the baseline parameters.
Panel B is the Moran law of this page, propagated with the discrete reference. All 144 published points at 30 to 1,080 days are matched to 0.038 percentage points or better. The difference is systematic in one curve: the reconstructed fraction above 0% lies 0.016 to 0.038 points below the published one at every age (the published value at 1,080 days reads 5.361%, the reconstruction gives 5.332%). The other three curves agree within 0.026 points. The cause is not known; a 0.03-point difference is a seventh of the sampling error of a 10,000-cell cohort, so it does not matter for the fit.
Panel A comes from a different model, the paper’s Model-1: wild-type and mutant copies whose replication is slowed by ATP, which only wild-type copies produce. The paper uses it to make synthetic data that are not drawn from the Moran model. Its equations are
wt' = wt/(1+ATP/c) - ln(2)/halfL*wt
mt' = (1+s)*mt/(1+ATP/c) - ln(2)/halfL*mt
ATP' = f_ATP*wt - v2*(wt+mt) - v1*ATP
with a stochastic version in one-hour steps in which only wild-type
replication produces mutants. This is the transcription model of
tutorial S3,
and the reconstruction reuses its hourly scheme and its choices: degrade,
replicate the survivors, mutate, then relax ATP for one hour with the new
counts; constants from the 2014 PNAS Table 1 (f_ATP = 0.1, v2 = 0.01,
v1 = 0.2, c = 1.303 from the steady state of 1,000 wild-type copies);
a cell whose ATP reaches zero keeps its counts. Three things differ from
tutorial S3, as the 2026 paper prescribes: mutants replicate 1+s times as
fast as wild type instead of 1.5 times, a fraction 1-f of new mutants is
neutral and replicates like wild type, and only wild-type daughters
mutate (in tutorial S3 mutant templates mutate too).
The figure shows 100,000 such cells (examples/kk26/moran.cpp,
sample_atp). The largest difference from the 144 published points is
0.158 percentage points; the paper’s curve also comes from about 100,000
cells, so two sampling errors of about 0.07 points meet here. A second run
of 30,000 cells with half-hour steps differs from the hourly run by at
most 0.28 points, and by at most 2.3 standard errors over the 122 points
where the fraction is not zero; a pure sampling difference gives such a
maximum as often as not. The comparison cannot detect a step-size effect
smaller than about 0.3 points. The hourly ATP cells and the Moran law of
panel B differ by at most 2.5 standard errors of the ATP cohort (6 of 144
points beyond 2): at this baseline the two models make indistinguishable
snapshots.
How the published curves were read
The paper’s Figure 6 was digitized from the article PDF: the axes are
calibrated on the 0–1,000 day and 0.01–0.05 ticks of each panel, the
curves read at the 30-day ages with a reading interval of 3 to 5 pixels
(examples/kk26/paper-figure6.csv, 296 points). The review checked panel
B against an independent image: a companion preprint of the same authors
(bioRxiv 10.64898/2026.01.30.702741,
Figure 4B) reproduces Figure 6B with the same axes and curves ending at
1,080 days. Read there by pixel analysis, 132 of the 148 points are
readable (the others lie under another curve near zero), and all agree
with the saved readings within 1.05 pixels of that image, 0.017
percentage points; on the steep start of the 0% curve within 0.42 pixels.
The same image also shows the 0% curve 1.2 to 2 pixels above the
reconstruction.
Both panels were then read again from the figure in the preprint of the paper itself (bioRxiv 10.64898/2026.01.30.702736, version 1; an 878 × 321 pixel image, one pixel is 0.022 percentage points). After day 0, 127 of the 144 points of panel A are readable, and all agree with the saved readings within 1.05 pixels, 0.023 percentage points. In panel B the same number is readable; the largest difference is 1.7 pixels, on the steep start of the 0% curve, where one pixel along the time axis already moves the curve by 0.04 percentage points.
Next: Fitting snapshots and takeover times.
Fitting snapshots and takeover times
Part of tutorial O2.
The paper tests its method on synthetic data with known parameters: it simulates cohorts, fits each one, and reports the spread of the 40 fits as a 95% interval (its Tables 2 and 3, a parametric bootstrap). This page does the same with new cohorts and compares the intervals.
The protocol
Applies: chapter 8, Reproducing a published simulation.
The targets were written in a plan before any run; everything below is
fixed in examples/kk26/fitting.py and recorded in
results/reconstruction/manifest.json (root seed 20261120):
- Data: 40 cohorts per regime, 10,000 cells each, simulated with the exact discrete Moran law (a sampler that skips unchanged steps with geometric waiting times). Every cohort has its own seed, a hash of the root seed, the regime and the cohort number. Cohort and optimizer seeds come from different labels, so data and search are independent.
- Objective: the paper’s unweighted sum of squared differences between the observed and predicted fractions above 0%, 5%, 20% and 50%, over all 37 ages.
- Search: fcmaes differential evolution (
fcmaes.decpp), population 32, 1,800 evaluations requested (1,801 to 1,848 used, as a generation finishes), overlog10(p),sandfin the box of the table below. - Forward law in the search: a tensor-product cubic spline through precomputed curves of the continuous-time solver (model page) at 192 (baseline) and 216 (strong) parameter points. The search box is the extent of this grid.
- Acceptance targets (from the plan): the forward solver and the spline within 0.001 in probability of their references; all 40 fits per regime completed; mean, coefficient of variation and the 2.5th and 97.5th percentiles reported, with whether the truth lies inside.
The grid nodes, the same in every cohort:
| Regime | p nodes | s nodes | f nodes |
|---|---|---|---|
| Baseline | 3.8e-6, 4.9e-6, 6.1e-6, 7.5e-6, 9.1e-6, 1.12e-5 | 0.052, 0.072, 0.086, 0.100, 0.115, 0.136, 0.166, 0.210 | 0.32, 0.54, 0.77, 1.00 |
| Strong | 1.65e-5, 2.08e-5, 2.63e-5, 3.30e-5, 4.15e-5, 5.2e-5 | 0.26, 0.35, 0.415, 0.465, 0.515, 0.57, 0.64, 0.73, 0.87 | 0.065, 0.15, 0.295, 0.47 |
The nodes were placed around the true values and the published intervals by the contributor; they are denser near the truth.
Results
The table is generated from results/reconstruction/parameter-differences.csv
and checked by validation/check_kk26.py. Percentiles use linear
interpolation between order statistics (NumPy’s default); with 40 fits the
2.5th and 97.5th percentiles lie close to the second smallest and second
largest fit. The paper names its percentiles but not their definition.
| Regime | Parameter | Truth | Search box | Mean (CV) | 2.5–97.5% | Published mean (CV) | Published 2.5–97.5% | Truth inside: here / paper |
|---|---|---|---|---|---|---|---|---|
| Baseline | Mutation probability p | 6.80e-6 | 3.80e-6–1.12e-5 | 6.76e-6 (3.2%) | 6.43e-6–7.25e-6 | 6.65e-6 (4.2%) | 6.11e-6–7.22e-6 | yes / yes |
| Baseline | Selection advantage s | 0.100 | 0.052–0.210 | 0.101 (5.8%) | 0.092–0.112 | 0.107 (9.7%) | 0.089–0.125 | yes / yes |
| Baseline | Advantageous fraction f | 0.800 | 0.320–1.000 | 0.786 (9.7%) | 0.654–0.927 | 0.870 (13.0%) | 0.650–1.000 | yes / yes |
| Strong | Mutation probability p | 3.00e-5 | 1.65e-5–5.20e-5 | 3.02e-5 (1.6%) | 2.91e-5–3.10e-5 | 2.90e-5 (1.8%) | 2.80e-5–2.99e-5 | yes / no |
| Strong | Selection advantage s | 0.500 | 0.260–0.870 | 0.509 (9.3%) | 0.445–0.601 | 0.538 (8.1%) | 0.461–0.628 | yes / yes |
| Strong | Advantageous fraction f | 0.200 | 0.065–0.470 | 0.198 (9.0%) | 0.172–0.235 | 0.210 (8.1%) | 0.180–0.240 | yes / yes |
All six reconstructed intervals contain the true value. The published interval of the strong-regime mutation probability, 2.80e-5–2.99e-5, does not: its upper end lies just below the true 3.0e-5, which the paper itself remarks on.
How to read the recovery
The search box. The optimizer can only return values inside the box, and the box was centered on the true parameters: about 0.56 to 1.7 times the true mutation probability and 0.5 to 2 times the true selection advantage. A real application does not know where the truth is. So the results above measure how precisely the snapshots pin the parameters down near the truth; they do not show that a search over all plausible values would find it. Three review checks bear on this:
- No fit lies within 1% of the box width of a bound except one: the
largest baseline advantageous fraction, 0.996, at the upper bound 1.0,
which the paper imposes too. In parameter units the fits use 0.94 to
1.07 times the true
pand 0.83 to 1.26 times the trues, well inside the box. - Four cohorts (baseline 0 and 8, strong 0 and 2, the latter two holding
the largest
fand the largests) were refitted without the spline, with the continuous-time solver itself, by the same optimizer over much wider boxes: baselinep2e-6–3e-5,s0.01–0.5,f0.05–1; strongp8e-6–1e-4,s0.1–2,f0.02–1. All four returned the saved fit within 0.2% inpandsand 0.004 inf(examples/kk26/review.py wide-box). The local box did not hide a better optimum in these cohorts. - The fixed-
fprofile of the first strong cohort (fraction-profile.csv) runs into the box: belowf= 0.12 the refittedssits at the upper bound 0.87, above 0.43 at the lower bound 0.26. Lowerfand higherstrade against each other along a ridge that leaves the box, but the objective there is 4 to 110 times the minimum.
The surrogate. The spline was compared with the continuous-time solver
at 16 points spread over each whole box (a scrambled Sobol sequence), at
3 fixed points near the truth and at 3 of the fitted points per regime.
The largest difference is 1.1e-4 in probability, at a strong-regime point
far from the truth, and at most 1.2e-6 at the fitted points
(grid-checks.csv).
Convergence. Refitting all 80 cohorts with ten times the budget, and
with a second set of optimizer seeds, changed no parameter by more than
2e-6 relative (review.py budget). The intervals are not optimizer noise.
The baseline intervals are narrower than the published ones. The
reconstructed coefficients of variation are 3.2%, 5.8% and 9.7% for p,
s and f; Table 2 gives 4.2%, 9.7% and 13.0%. The published means are
also shifted: s 0.107 and f 0.87 against the truth 0.10 and 0.80,
while the reconstruction’s means are 0.101 and 0.786. The paper’s Table 1,
which is not reproduced here, shows the same shift with 100,000 cells
per cohort (s 0.108, f 0.87), so it is not sampling noise. Something
systematic differs between the published experiment and this one. The
review tested two candidates:
- Data from Model-1. The paper’s Methods say the bootstrap cohorts were
simulated with the Moran model, its Results describe the synthetic data
as output of the ATP model (Model-1) or a fixed-copy-number model
(Model-2). The 100,000 hourly ATP cells of Figure 6A, fitted with the
Moran law, give
p= 6.77e-6,s= 0.104 andf= 0.757 (review.py atp-fit, the same with four optimizer seeds):smoves toward the published mean,faway from it. By the rule fixed before the run this is inconclusive. Model-2 could not be reconstructed. - Cohort design. The reconstruction follows the same 10,000 cells
through all 37 ages, so a chance early mutation in one cell shows up at
every later age. With a new set of 10,000 cells at every age, as in real
cross-sectional data, the 40 fits are two to three times as precise: CVs of
1.2%, 2.0% and 4.5% in the baseline, with means within 0.1% of the truth
(
review.py design,review-design.csv). The rule fixed before the run asked whether the intervals become at least 25% wider; they became 50% to 65% narrower, which the rule’s categories did not foresee (it classifies this as “partial”). Either way the design does not explain wider published intervals, unless the published cohorts were correlated across ages in some stronger way. It does show that the saved intervals are wider than real snapshot data of the same size would give.
The optimizer settings, search bounds and percentile definition of the paper are not published. In the strong regime the reconstructed and published coefficients of variation agree within 1.3 percentage points.
The advantageous fraction near 1. The published baseline interval of
f reaches the imposed maximum 1.00. The reconstructed one ends at 0.927;
only one of 40 fits comes close to 1. The objective is flat in this
direction: for the first baseline cohort the best objective with f
fixed changes by at most 13% between f = 0.75 and 0.95
(fraction-profile.csv), while p and s adjust along with it.
From a selection advantage to a takeover time
The paper’s Figure 5 turns a selection advantage into the time a single
advantageous mutant needs to reach 90% of the copies. The reconstruction
starts with one advantageous copy among 999 wild-type copies, switches off
further mutation, and follows the exact probability law of the Moran
chain until the mutant is lost or reaches at least 900 copies. Dividing the
probability of having reached 900 copies by day t by the eventual
success probability gives the distribution of takeover times among the
mutants that succeed.
The success probability is the gambler’s-ruin result for a birth–death
chain whose up and down probabilities have the constant ratio 1+s:
(1 - 1/(1+s)) / (1 - (1+s)^-900), which is s/(1+s) to many digits.
The computed absorption agrees with it to 1e-12.

From results/reconstruction/takeover-summary.csv (days; the modal bin is
the 30-day bin with the most probability, named by its first day):
| Selection advantage | Success probability | Median | 95% interval | Modal bin | Reached by day 1,080 |
|---|---|---|---|---|---|
| 0.10 | 9.09% | 1,038 | 737–1,553 | 990 | 58.4% |
| 0.20 | 16.67% | 584 | 438–834 | 540 | 99.9% |
| 0.30 | 23.08% | 416 | 319–584 | 390 | 100.0% |
| 0.50 | 33.33% | 275 | 214–376 | 240 | 100.0% |
| 0.101 (baseline mean fit) | 9.18% | 1,029 | 732–1,539 | 960 | 60.1% |
| 0.509 (strong mean fit) | 33.73% | 270 | 213–370 | 240 | 100.0% |
Quantiles are interpolated linearly in a CDF reported every 30 days. The modal bins 990, 540, 390 and 240 days are the four labels printed in the paper’s Figure 5.
The bars of that figure were read from the preprint of the paper (bioRxiv 10.64898/2026.01.30.702736, version 1;
examples/kk26/paper-figure5.csv, 60 bars, one pixel is 0.0009 in
probability) and compared with the reconstruction’s probability of the
same 30-day bin (fig5-differences.csv):
| Selection advantage | Bars | Largest difference | Sum of the published bars | Sum of the same bins here |
|---|---|---|---|---|
| 0.10 | 15 | 0.0021 | 0.562 | 0.582 |
| 0.20 | 21 | 0.0037 | 0.982 | 0.997 |
| 0.30 | 15 | 0.0057 | 0.987 | 0.998 |
| 0.50 | 9 | 0.0085 | 0.992 | 0.998 |
The shapes agree within 0.0085 per bin, and the comparison settles two
choices of the reconstruction. A bar labeled L is the takeover
probability in the 30 days from L on; with the 30 days up to L the
largest difference would be 0.19. And the bars are probabilities among all
founders that ever take over: at s = 0.10 the published bars up to day
1,080 sum to 0.56, as the 58% of the table above, where a distribution of
the takeovers inside the window would sum to 1.
The agreement is not complete: 35 of the 60 bars differ by more than the reading interval of one pixel, and the reconstruction’s bars sum to 0.6% to 3.6% more. Moving the published distributions 1.5 to 3 days earlier brings every bar within 0.0015. This was found after the comparison and is a description, not a tested explanation; such a shift is 0.3% to 0.6% of the median times.
Two cautions follow from the first row. Most single founders, 91% at
s = 0.10, are lost, so a takeover time describes only the successful
ones. And with weak selection a three-year window sees only part of the
distribution: a founder present from day 0 that will succeed has reached
90% by day 1,080 with probability 58%. Keeping only takeovers seen inside
the window, as panel B shows, makes takeover look faster than it is.
Rerunning the study
python examples/kk26/study.py bootstrap --size full --threads 8
python examples/kk26/study.py evidence --threads 8 --complete-grid --results examples/kk26/results/local/full
python examples/kk26/study.py figures --results examples/kk26/results/local/full
python validation/check_kk26.py --output kk26-validation.json
bootstrap --size full builds the two forward grids if they are not
cached (about 10 minutes on two x86-64 cores), simulates the 800,000 cells
of the 80 cohorts (about 10 seconds) and fits them (a few seconds). Its
results go to examples/kk26/results/local/full/. evidence computes the
discrete reference curves, the solver and corner checks, the complete
lattice and the 130,000 ATP cells, and the takeover tables (about 11
minutes on two cores). The saved results under results/reconstruction/
are the output of these two commands, copied together with the two grids.
The review checks of the previous section are rerun with
python examples/kk26/review.py budget|wide-box|atp-fit|design.
Next: Choices, checks and limits.
Choices, checks and limits
Part of tutorial O2.
Reconstruction choices
The paper describes its method in words, equations and figures. Where it leaves something open, the reconstruction had to choose. All choices are listed here, with their effect where it was measured.
| Choice | What the paper says | Reconstruction | Effect where measured |
|---|---|---|---|
| Days to Moran steps | Δt days are about N*ln(2)/halfL*Δt steps | floor(days*1000*ln(2)/10): 74,860 steps for 1,080 days | Less than one step; not varied |
| Report ages | Three years, exported every 30 days | 0, 30, …, 1,080 days (37 ages); the companion preprint’s copy of Figure 6B ends at 1,080 days | — |
| Forward law in the fit | Forward master equation of the Moran process (discrete steps) | Continuous-time (Poisson-clock) law, 5-day implicit split steps | At most 1.2e-5 from the discrete law at the true values, 3.4e-5 at the box corners |
| Neutral-count cap | Not stated | 192 (baseline), 320 (strong); escaped probability recorded, never renormalized | 5.6e-5 against the complete lattice at the baseline truth; escaped mass at most 3.2e-4 at any grid node |
| Spline surrogate | The fit evaluates the forward law | Cubic spline through 192 / 216 precomputed parameter points | At most 1.1e-4 over the whole box, 1.3e-6 at the fits |
| Search box | Only the bound f ≤ 1 is stated (the companion preprint fits s in 0–2) | A box around the truth, the extent of the spline grid (table) | Four refits in much wider boxes without the spline: same fits within 0.2% |
| Optimizer settings | fcmaes differential evolution | Population 32, 1,800 evaluations, one seed per cohort | Ten times the budget or other seeds: parameters change by at most 2e-6 relative |
| How synthetic cohorts are made | Methods: simulations of the Moran model. Results: output of Model-1 and Model-2 | The exact discrete Moran law | Model-1 data fitted once: s 0.104, f 0.757 (inconclusive) |
| Same or different cells across ages | Not stated | The same 10,000 cells at every age | A new set of cells at every age: intervals 50% to 65% narrower, CV of s 2.0% instead of 5.8% (baseline) |
| Percentile definition | 2.5th and 97.5th percentiles of 40 fits | Linear interpolation (NumPy default) | Other definitions widen the intervals toward the extremes, e.g. baseline s 0.088–0.114 (Hazen) or 0.083–0.115 (Weibull) instead of 0.092–0.112 |
| Takeover | Reaching 90% mutant copies | At least 900 of 1,000 copies of the founder’s type | — |
| Start of a takeover | A single advantageous mutant in a wild-type cell | One A copy, 999 W, no neutral mutants, mutation switched off | — |
| Figure 5 bins | Histograms of accumulation times | 30-day bins named by their first day, among all founders that ever take over | The published bars agree within 0.0085 per bin; the other bin naming would differ by up to 0.19 (takeover times) |
| Model-1 time stepping | Stochastic simulation in one-hour steps | Tutorial S3’s order: degrade, replicate survivors, mutate wild-type daughters, relax ATP for one hour with the new counts | Half-hour steps: at most 0.28 percentage points, 2.3 standard errors |
| Model-1 constants | Equations without values in the text read by the review | 2014 PNAS Table 1: f_ATP = 0.1, v2 = 0.01, v1 = 0.2; c from the 1,000-copy steady state | Not varied |
| Model-1 neutral mutants | A fraction fracAdv of mutants is advantageous | Neutral mutants replicate like wild type | Not varied |
| Model-1 cell whose ATP reaches zero | Takeover coincides with ATP collapse | The cell keeps its counts from that hour on (tutorial S3’s choice) | 394 of 100,000 cells collapse by day 1,080 |
How the reconstruction was checked
validation/check_kk26.py runs in CI, normally and under python -O, in
a few seconds:
- Exact laws in a seven-copy cell: the discrete forward solver against matrix powers of an independently built Equation 7 chain (within 1e-11); the strict thresholds; a neutral cap of one copy that must bound the exact tails from below and, with the escaped mass, from above; CRN-craft’s FSP against the matrix exponential (within 1e-10); 16,000 Static Direct cells and 16,000 cells of the geometric-skip sampler against the exact law, with the Dvoretzky–Kiefer–Wolfowitz bound for error probability 0.001 (0.0154).
- Replay and takeover: the same cohort with one and four threads is identical; a neutral and a selected ten-copy takeover chain match the gambler’s-ruin probabilities.
- Optimizer: fcmaes differential evolution recovers a known target of a small artificial problem.
- Saved evidence: the solver hash and build flags in the manifest match
moran.cppandmodel.py; the five review files are complete; all 80 fits are present and the summary statistics replay from them; all 44 interpolation checks and the 9 forward checks are within 0.001; the Figure 6 differences use the digitized values; the modal bins and the order of the medians of Figure 5 hold; the table of the results page equals the table generated from the saved files.
The check does not rerun the study and compares no simulated cell, curve
or fit with a saved value: those depend on the platform. The forward grids
and the 80 fits change when a single bit of the grids changes (a 6e-15
change of the grid values moved the fits by up to 3e-8 relative). The
library is therefore built with -ffp-contract=off and without
-march=native, so that compilers do not fuse multiply-adds on CPUs that
support them. The grid solver then uses only IEEE arithmetic; the one
math-library result it depends on is 10**x for the mutation probability
of each node, computed in Python. The cohort sampler uses the C math library (log1p) and
the ATP model std::binomial_distribution, whose results can differ
between standard libraries.
The saved results were produced on an Intel x86-64 host with GCC 13.3, Python 3.13, NumPy 2.3.5, SciPy 1.18.1 and fcmaes 2.2.0. fcmaes 2.1.0 reproduces all 80 fits byte for byte on the same grids and cohorts; other versions may give statistically equivalent, not identical, fits.
Limits
- Each saved cohort follows the same cells through all ages. Real snapshots see different cells at every age and, with the same number of cells, pin the parameters down two to three times more precisely.
- The cohorts are simulated with the Moran model and fitted with the Moran model. The recovery shows that the method is consistent when its model is right; it says nothing about data from cells that do not follow it. The paper’s misspecification experiments (wrong turnover or copy number, its Tables 4 and 5) and its 100,000-cell Table 1 are not reproduced.
- The fits search a box around the true values on a spline of precomputed curves. The review’s wider refits cover four of 80 cohorts.
- The published intervals are wider in the baseline regime and the published means are shifted; the reason is not known (see the results page).
- The authors’ scripts and data (linked from the paper) could not be reached, so their optimizer settings, bounds and data generation are unknown.
- The published values and figures were checked against the preprint of the paper, not the journal article: the printed values of Tables 1 to 3 all agree, as do the labels of Figure 5 and the readings of both panels of Figure 6. The published takeover distributions of Figure 5 lie 1.5 to 3 days later than the reconstruction’s; the cause is not known.
- The Model-1 reconstruction inherits tutorial S3’s choices and constants; the 2026 paper’s own constants were not available to the review.
- Matching the published curves and intervals does not show that real cells follow the Moran model; the companion preprint finds that measured curves do not fully fit it.
Exercises
- Fit the saved first cohort (
study.py fit examples/kk26/results/reconstruction/snapshots-baseline.csv) and then the same counts with bins 1 and 2 merged into bin 1 (drop the 5% threshold). Which parameter loses most precision? - Rerun
bootstrap --size quickwith--cells 100000. Predict, before you run it, how the spread of the four fits compares with 2,000 cells. - Compute the takeover table for a half-life of 20 or 30 days (the
paper’s sensitivity values) with
model.passage(Model(0, 0.1, 1, half_days=20)). How do the success probability and the median scale? - Fit the 30,000 half-hour ATP cells of
fig6-curves.csvthe wayreview.py atp-fitfits the hourly ones and compare the two estimates.
See also: Reproducing a published simulation, Choices, checks and limits of tutorial S3.
O3. Case study: fitting yeast single-cell RNA distributions with fcmaes
What this chapter reproduces
Cells sampled at the same time after a stress do not all hold the same number of RNA molecules. Some hold none, others hold a hundred. A 2018 paper asks what a model learns when it is fitted to these whole count distributions instead of only to their averages:
Munsky B., Li G., Fox Z.R., Shepherd D.P., Neuert G. (2018). Distribution shapes govern the discovery of predictive models for gene regulation. PNAS 115(29):7533–7538. doi:10.1073/pnas.1804060115 (Figure 2A–D and Figure 4D–E)
The measurements are described in a data paper:
Li G., Neuert G. (2019). Multiplex RNA single molecule FISH of inducible mRNAs in single yeast cells. Scientific Data 6:94. doi:10.1038/s41597-019-0106-6
The study uses the processed count arrays and the fitted parameter vectors that the authors published in their repository (MunskyGroup/Munsky_et_al_2018 at revision 1aa0b5c). Their MATLAB code was read for facts only: which replicates and time points the fit used, how the parameter vector is laid out. Nothing was copied or translated from it. The equations were checked against the bioRxiv version of the paper and the first part of its supplement (10.1101/154401); the journal supplement was not reachable. The paper’s authors did not write or review this chapter.
The result in four lines:
- The same four-state model was fitted to the measured means and to the measured count histograms. Scored on whole histograms, the fit to means costs 2.39690 nats per cell and the fit to histograms 2.03845 (59,557 cells). Both scores reproduce from the saved parameters.
- Both fits searched a box centered on the authors’ published histogram fit. The histogram fit stays close to that vector; the mean fit ends at the box edge. So the comparison shows how the two objectives rank models near the published one. It does not show what each objective finds from no prior knowledge, and the held-out scores are not clean held-out tests (why).
- The spatial model was not refitted. The best point of its 3 × 3 check grid is the authors’ published vector.
- The transcription-site prediction recomputes the authors’ prediction from their published vector. It agrees with their model curve to 0.0024 in active fraction. Against the measured traces it misses by up to 0.42 at 0.4 M.
Words used in this chapter
- Count distribution, histogram: for one dose, replicate and sampling time, the number of cells with 0, 1, 2, … RNA molecules.
- Nats per cell: the negative log likelihood of a histogram divided by its number of cells. Smaller is better. A difference of 0.01 nats per cell over 59,557 cells is 596 nats.
- Archived vector: a parameter vector saved in the authors’ repository
(
Fit_Results/.../Best_Pars_AC.mat). There are four: means and histogram fits of the nonspatial and of the spatial model. - Replicate: one biological time course, named by its date. 0.2 M has two (20140425, 20140429), 0.4 M has three (201301004, 20131022, 20160509).
Score a distribution
A count histogram keeps the cells without RNA as well as the cells with
many. If a bin holds n_k cells and the model gives it probability p_k,
the bin adds -n_k log p_k to the negative log likelihood.
from math import log
counts = [7, 2, 1]
probabilities = [0.6, 0.3, 0.1]
score = -sum(n * log(p) for n, p in zip(counts, probabilities, strict=True))
print(f"{score / sum(counts):.4f} nats per cell")
0.8286 nats per cell
A fit to means sees only the average of each histogram. Two models with the same means can give very different histograms, and the histogram score tells them apart.
The pages of the chapter:
| Page | Question |
|---|---|
| Data and model | Which cells are used, what is the model, and how is it solved? |
| Fits and predictions | What do the two fits give, what does the optimizer comparison show, and how good is the transcription-site prediction? |
| Choices, checks and limits | What did the reconstruction have to decide, how was it checked, and what is not verified? |
Running the example
You need Python 3.11 or newer, CRN-craft 0.8.0, NumPy, SciPy, pandas,
fcmaes 2.2.0, Matplotlib and a C++17 compiler for the fits (set CXX to
choose one). The compiled solver is cached in the system’s temporary
directory. Run the commands from the repository root:
python examples/yeast_rna_fit/study.py --size quick
python examples/yeast_rna_fit/study.py --figures docs/guide/img/yeast_rna_fit
python validation/check_yeast_rna_fit.py
--size quick fits 0.2 M at five sampling times with 80 evaluations per objective in
about three seconds; it shows the workflow, not a result. --figures
redraws the three figures from the saved result files. The check needs
about a second and no network. The larger runs and their cost are listed
on the results page;
the example README lists the
files.
See also: Protein distributions from four reactions (the count distribution of a simpler model), Fitting (fcmaes with CRN-craft).
O3a. Data and model
Tutorial O3 · Data and model · Fits and predictions · Choices, checks and limits
The cells
Yeast cells were shocked with 0.2 M or 0.4 M NaCl and fixed at 0, 1, 2,
4, 6, 8, 10, 15, 20, 25, 30, 35, 40, 45, 50 and 55 minutes. Single-molecule
FISH counted the STL1 RNA in the nucleus and in the cytoplasm of each cell.
fetch.py reads the authors’ array Hog_Data/Analyzed_FISH_Data_2016_06.mat
(the file their fitting code loads) and writes one row per distinct
(dose, replicate, minute, total, nuclear, cytoplasmic) tuple with its cell
count to source-counts.csv (7,374 rows). It records the SHA-256 of every
file it reads.
| Dose | Replicate | Cells | Cells after time zero | In the authors’ fit |
|---|---|---|---|---|
| 0.2 M | 20140425 | 14,382 | 12,452 | yes |
| 0.2 M | 20140429 | 11,129 | 9,101 | yes |
| 0.4 M | 201301004 | 18,471 | 17,544 | yes |
| 0.4 M | 20131022 | 7,457 | 7,089 | no |
| 0.4 M | 20160509 (no 1-minute sample) | 14,204 | 13,371 | yes |
| All | 65,643 | 59,557 |
Three facts about these rows:
- Cell totals. The paper reports 65,454 cells, 25,511 at 0.2 M and
39,943 at 0.4 M. The mature-RNA array holds 25,511 and 40,132. The
authors’ transcription-site array (
RNA_TS_Brian.mat) holds the paper’s totals. The two arrays agree cell for cell in 0.2 M and in 20160509. The other two 0.4 M replicates differ at almost every time point: 20131022 has 1,051 more cells in the site array, 201301004 has 1,240 fewer. The 189 cells are the net of these two differences, not one duplicated sample. The example uses the mature-RNA array, as the authors’ fitting code does. - Replicates in the fit. The authors’ fitting code
(
Process_Hog_Data_Class.m, option_AC) pools both 0.2 M replicates but only the first and third 0.4 M replicate. Replicate 20131022 is not in their fit. This example fits all five replicates (see the choices). - Totals. In 235 cells (228 rows) the recorded total is one or two smaller than nuclear plus cytoplasmic. The total-RNA fits use the recorded total; the authors’ code uses nuclear plus cytoplasmic. The difference changes the scores by 0.0002 nats per cell.
Time zero is shown in the figures and left out of both objectives. The authors’ likelihood code also sums from the second time point on; the paper does not say so. All fitted models start with no RNA in promoter state 1; 99.0% of the 6,086 time-zero cells have no RNA.
The paper calls a cell ON when it has more than three RNAs (its Methods
also say “three or more”). The example uses X > 3. Recounted from the
rows, the ON fraction peaks at 0.699 at 15 minutes for 0.2 M and at 0.897
at 20 minutes for 0.4 M.
The model
The STL1 promoter switches between four states S1 to S4. In state
Si it starts new RNAs at rate k_i (per second). In the nonspatial
model an RNA decays at rate γ:
S1 <-> S2 <-> S3 <-> S4 rates k12, k21(t), k23, k32, k34, k43 [1/s]
Si -> Si + RNA rate k_i, i = 1..4 [1/s]
RNA -> 0 rate γ per molecule [1/s]
Only the switch from S2 back to S1 depends on the stress. It falls as
the nuclear Hog1 kinase signal rises, after a delay t0:
k21(t) = max(0, k21⁰ − k21¹ · H(t − t0))
H(s) = A · [ u(s) / (1 + u(s)/M) ]^η, u(s) = (1 − e^(−r1·s)) · e^(−r2·s), s ≥ 0
H is dimensionless. Its constants were fitted by the authors to measured
Hog1 nuclear enrichment and are the same for both doses except r2:
r1 = 6.09e-3 /s, r2 = α/(c + 0.0410) with α = 1.68e-3 M/s and the
NaCl concentration c in M (so r2 = 6.97e-3 /s at 0.2 M and
3.81e-3 /s at 0.4 M), η = 5.89, M = 0.0215, A = 9.32e9. These
match Table S2 of the supplement to its two printed digits; the example
uses the full-precision values of the authors’ parameter file. The
nonspatial model has 13 free coefficients: six switching rates and
k21¹, four initiation rates, γ and t0.
The spatial model splits RNA into nuclear N and cytoplasmic C.
Initiation makes N, export N -> C has rate k_exp, and the two
compartments decay at γ_nuc and γ_cyt. That is 15 coefficients.
fetch.py maps the authors’ 39-entry parameter vector to these names by
the layout of their PARS_Definition_Connected_Models.m. Free entries 1,
4, 5, 8, 9, 12 (switching), 16 (signal on k21, stored with a negative
sign), 25–28 (initiation), 33 (decay) and 39 (delay); the spatial model
adds 35 and 37. source-parameters.json holds the four archived vectors.
How it is solved
The time-varying rate rules out a single matrix exponential. The example uses three local solvers; none is part of CRN-craft.
- Total RNA (
cme.cpp): the master equation of the 4 × (cap + 1) states of promoter and count, integrated with fixed-step BDF2 (one backward-Euler start step) and a banded direct solve, withk21set at the end of each step. Initiation at the cap leaves the domain. Nothing is stored as a separate sink; the leakage is1 − Σp, which is the mass that crossed the cap because BDF2 conserves the sum of a conservative system. The fits use steps of 12 s (draft) or 6 s (full) and caps of 250 or 280 RNAs. Every reported score is recomputed with a 1.5 s step and the cap doubled from 360 until the leakage is below 1e-5. - Means: the first moments close exactly (all rates are linear in the counts). The fit integrates them with the same BDF2; the reported mean costs use SciPy’s adaptive BDF with relative tolerance 1e-7.
- Joint nuclear and cytoplasmic RNA: SciPy’s sparse BDF on the 4 × 22 × 241 joint states (relative tolerance 2e-6), checked with 4 × 29 × 306 states and tolerance 4e-7.
The library is built with -std=c++17 -O3 -ffp-contract=off and no
-march=native, so compilers do not fuse multiply-adds differently on
different machines.
The reusable projection in native_fit.py reads the same model and
prescribed rate through CRN-craft. Its checks compare it with the two
original solvers. Both share the input waveform function. Each original
solver has its own integrator: the total-RNA one fixed-step BDF2, the
joint one SciPy’s sparse BDF, while the projection uses CRN-craft’s
native variable-order integrator (solver="bdf"). Prepared probability laws
What the check verifies about these solvers:
- With a constant signal the model is an ordinary reaction network. The
check builds it with
crn_craft.Model, solves it with CRN-craft’s finite state projection, and compares with an explicit generator and SciPy’sexpm_multiply, for total RNA (cap 5) and for the joint model (caps 3 and 4), to 5e-10 in probability and leakage. - The BDF2 solver with 0.05 s steps agrees with that law to 2e-5 after one minute, and the BDF2 means agree with the adaptive moment equations to a relative 1e-4.
- The histogram score of a three-bin example equals the hand calculation above to 1e-12.
The two objectives
Both objectives use the same groups: one dose, one replicate, one time after zero (79 − 5 = 74 groups).
- Means. For group
gwithn_gcells, sample meanx̄_gand sample variances_g², the cost isΣ_g (x̄_g − μ_g(θ))² / (2 v_g)withv_g = s_g²/n_g + 1/(12 n_g).μ_gis the model mean. The paper’s Equation 23 usess²/Nwithout the last term; the term keeps groups with zero variance finite. The joint model uses the 2 × 2 covariance. The paper pools the replicates of one time into one group; the example keeps them separate. - Histograms.
−Σ_g Σ_x n_gx log p_g(x; θ)over the observed countsx. Each count below the cap is its own bin, including zero; cells above the cap form one tail bin with probability1 − Σp. If an occupied bin gets probability zero, or a tail bin is occupied and no mass left the cap, the candidate is rejected as invalid (cost +∞) and counted. In the saved full fits no candidate was invalid; in the draft fits at most 2 of about 500 evaluations per restart were.
Scores are divided by the number of cells to give nats per cell.
O3b. Fits and predictions
Tutorial O3 · Data and model · Fits and predictions · Choices, checks and limits
The protocol
The plan for this chapter fixed, before the runs: the same model, data,
box and evaluation budget for both objectives; a fit with all replicates;
refits with one replicate per dose held out; scores in nats per cell on
whole histograms; and a refinement target of less than 0.01 nats per cell
between the fit’s solver settings and refined ones
(manifest.json). The held-out replicates, 20140429 for 0.2 M and
20160509 for 0.4 M, are named in manifest.json; why these two was not
recorded.
Both fits use fcmaes.decpp (differential evolution, population 26). The
search runs in the logarithm of each coefficient, in a box around the
authors’ archived histogram fit: a factor 3 each way for most rates, 4
for k21, k21¹, k_1, k_3 and k_4, and 1.6 for the delay (0.41 to
1.20 decades wide). The signal coefficient keeps its sign. Each restart
first evaluates the archived vector itself and returns it if the search
does not beat it.
The full run made eight restarts of 2,000 requested evaluations and one of 8,000 per objective. The actual counts, 24,174 and 24,175, include one evaluation of the archived vector per restart. The held-out refits are draft size: four restarts of 500 and one of 2,000.
Results
All scores are histogram negative log likelihoods in nats per cell, recomputed with the refined solver. Smaller is better.
| Evaluation set | Cells | Run size | Mean fit | Histogram fit | Archived histogram vector |
|---|---|---|---|---|---|
| All usable cells, both doses (in sample) | 59,557 | full | 2.39690 | 2.03845 | 2.04126 |
| 0.2 M replicate 20140429, held out | 9,101 | draft | 1.41756 | 1.33373 | 1.32248 |
| 0.4 M replicate 20160509, held out | 13,371 | draft | 2.38211 | 2.17447 | 2.14287 |


The mean fit reproduces the means but not the shape. During the response (15 minutes at both doses, 30 minutes at 0.4 M) it puts too much probability on cells with few RNAs and too little on the broad arm of cells with 20 to 100. The histogram fit follows both arms.
Numerical quality of the full fits:
- Changing the solver from the fit’s settings to a 1.5 s step and a larger cap changes the scores by at most 0.00278 nats per cell (mean fit, cap 360 → 720; almost all of it is RNA beyond 360 copies). The target was 0.01. The review reproduced 2.396902 and 2.038454 with its own scoring code; halving the step again and doubling the cap moves them by 2.4e-4 and 2.4e-5.
- The largest refined leakage of a nonspatial fit is 6.57e-6 (the draft mean fit with all replicates). The full fits leak 7.5e-10 and 2.5e-7.
- The eight histogram restarts end between 2.03822 and 2.04050 nats per cell (fit settings), the archived vector scores 2.04113, and the 8,000 evaluation run ends at 2.03838. The eight mean restarts end between cost 3,234.1 and 3,292.2 and the long run at 3,237.9.
What the comparison shows
It shows that, among models close to the authors’ published histogram fit, the one that matches the means best predicts the histograms much worse than the one that matches the histograms best: 0.36 nats per cell over all cells, 0.08 and 0.21 on the two held-out replicates. It also shows that the means do not pin the distribution down. The draft mean fit, with a slightly worse mean cost (3,285.5 against 3,252.5), scores 2.14495 on histograms, against 2.39690 for the full mean fit.
It does not show what either objective finds without knowing the answer, for three reasons:
- The box favors the archived vector. It is centered on the authors’
histogram fit, and the archived vector is evaluated first. The
histogram fit stays within 0.23 of the half-width of that center in
every coefficient (
k3moved by a factor 1.37,k34by 1.22,k21by 0.74). It improves on the archived vector by 0.0028 nats per cell. On the authors’ own data selection (no 20131022, total = nuclear + cytoplasmic) the archived vector is better: 2.01804 against 2.02052 (results/review-data-choices.csv). The change is a shift toward replicate 20131022, which the authors did not fit. - The mean fit is held by the box. It ends near the upper edge in
k21(0.995 of the half-width),k43(0.95) andk2(0.95). The authors’ own fit to means lies far outside this box (up to 25 half-widths away). The mean fit here is therefore the best mean fit near the histogram answer, not the best mean fit. - The held-out replicates were not held out from the box center. The authors fitted their archived vector to data that include both held-out replicates. The archived vector scores 1.32248 on 20140429 and 2.14287 on 20160509, better than the refits without these replicates (1.33373 and 2.17447). The held-out scores therefore measure the refits’ distance from a vector that has seen the test data.
Only two of the five replicates were held out. The plan asked for a held-out score for each biological replicate; the other three refits were not run.
Does the search find this level from a wider box?
A small review experiment, declared before it ran (question, runs and rule below), asks whether the optimizer reaches the archived level when the box does not favor it. It fits the histogram objective to the 0.2 M data only, at draft solver settings, with four restarts of 2,000 evaluations in two boxes, never evaluating the archived vector: narrow, the box of the fits; and wide, two decades each way for the rates and a factor two for the delay, centered up to one decade (random, seed 4242) away from the archived vector. Rule: if the best wide restart is within 0.01 nats per cell of the archived vector’s score, it “reaches the archived level at this budget”.
| Box | Seed | Evaluations | Invalid | Change vs archived (nats/cell) | Farthest parameter (decades) |
|---|---|---|---|---|---|
| narrow | 7001 | 2,019 | 0 | -0.0228 | 0.47 |
| narrow | 7002 | 2,016 | 0 | -0.0221 | 0.41 |
| narrow | 7003 | 2,023 | 0 | -0.0229 | 0.50 |
| narrow | 7004 | 2,039 | 0 | -0.0228 | 0.45 |
| wide | 7001 | 2,037 | 57 | -0.0218 | 0.80 |
| wide | 7002 | 2,001 | 9 | -0.0229 | 0.75 |
| wide | 7003 | 2,036 | 26 | -0.0076 | 1.74 |
| wide | 7004 | 2,026 | 113 | -0.0158 | 1.89 |
Result: reaches the archived level at this budget. Two of four wide
restarts end as low as the narrow ones, 0.022 nats per cell below the
archived vector (fitting one dose alone leaves more freedom than fitting
both). Two stop 0.007 and 0.015 above the best. The good solutions differ
from the archived vector by up to 0.8 decades in one coefficient
(k21¹), and the two others lie up to 1.9 decades away: very different
parameter sets give similar scores. This is one dose, one budget and one
set of seeds; it shows search behavior, not identifiability, and it does
not repeat the mean-versus-histogram comparison from a wide box. Rerun
with python examples/yeast_rna_fit/review.py start (about four minutes).
The spatial model
The spatial model was not refitted. Only k_3 and γ_cyt were varied, on
a 3 × 3 grid of full sparse solves, a factor 1.35 each way around the
authors’ archived spatial histogram fit. An interpolated surface was then
searched with fcmaes. For both objectives the interpolated optimum was
worse when solved directly than the best grid point, so the grid point was
kept (results/spatial-fits.csv).
- For the histogram objective, the best grid point is the center: the authors’ published vector. It scores 2.65027 nats per cell on the joint nuclear and cytoplasmic counts; the refinement changes this by 2.6e-7.
- For the mean objective, the best grid point is a corner of the grid
(
k_3divided by 1.35,γ_cytmultiplied by 1.35), at the edge of the searched range. It scores 2.93792. - Leakage of the joint solves is below 3.9e-13 at every time
(
results/spatial-accounting.csv); the smallest probability of any state is positive.
The transcription-site prediction
Figure 4D–E of the paper predicts, from the fitted spatial model, the fraction of cells with an active STL1 transcription site and the brightness of active sites. The example recomputes this prediction from the authors’ archived spatial histogram vector. It does not test a model fitted here.
The observation model follows the paper’s supplement. A polymerase is
visible for L/v = 1630/63 = 25.9 s, where L = 1630 nt is the distance
from the first FISH probe to the end of the gene (Table S1) and v = 63 nt/s is the elongation rate the authors fitted to CTT1. The promoter
is propagated to the start of this window and new initiations are counted
within it. Each unfinished RNA adds a Uniform(0, 1) intensity, so k
polymerases give an Irwin–Hall intensity. A site counts as active above 2
mature-RNA equivalents. The forcing delay, 226.86 s, comes from the
archived vector.
The reference curves are the numerical series saved in the authors’
figure files (Figures/1_TS_Figures/STL1_*_Spatial_TS_*.fig): their model
curve and the measured points they plotted. They were read from the
files, not digitized from images. The measured points in these files do
not equal the activity computed from the authors’ raw site array
(RNA_TS_Brian.mat, shipped as source-sites.csv): per replicate the
largest difference is 0.09 to 0.27. The cause is not known.

- Against the authors’ model curve, the mean absolute difference in active fraction is 0.0014 at 0.2 M and 0.0024 at 0.4 M (largest 0.0075): numerical agreement of the reimplementation.
- Against the measured points, the mean absolute difference is 0.027 to 0.029 per replicate at 0.2 M and 0.018 to 0.088 at 0.4 M; the largest single misses are 0.28 (0.2 M, 15 minutes) and 0.42 (0.4 M, 25 minutes). This is the model’s error, the same as in the paper’s figure.
- The paper reports 7.0 full-length RNA equivalents per active site for this model, and 4.2–7.5 measured. Weighted over sampling times with bin midpoints, the recomputed prediction gives 7.3 at 0.2 M and 7.5 at 0.4 M; the raw site array gives 3.9 to 6.3 per replicate (bins of one equivalent, so ±0.5). These are approximate and not checked by the validation script.
Rerunning the study
| Command | What it does | Cost here |
|---|---|---|
study.py --size quick | 0.2 M, five times, 80 evaluations per objective | 3 s |
study.py --size draft --cross-validate --budget-check | all fits at draft size, two held-out refits | 9.5 min, one worker |
study.py --size full --budget-check | the full fits of the table, then the spatial evaluation | not timed by the review |
study.py --size full --spatial-only --spatial-fit | the spatial grid | not timed by the review |
review.py start, review.py choices | the review files of this page | 4 min, 5 s |
All commands take --workers N (one thread per restart) and write to
examples/yeast_rna_fit/runs/SIZE/ unless --output is given. Results do
not depend on the worker count. The review reran the draft command; every
score and restart value equals the saved draft rows to a relative 2e-7.
The full and spatial runs were not rerun. The shipped scores.csv and
optimizer-work.csv combine the full and draft runs with a preset
column; study.py writes them per run as scores.csv and restarts.csv.
O3c. Choices, checks and limits
Tutorial O3 · Data and model · Fits and predictions · Choices, checks and limits
Reconstruction choices
The paper and the authors’ files leave these points open, or the example
decided differently from the authors’ code. “Effect” is measured where a
number is given (results/review-data-choices.csv scores the saved
vectors with both variants); otherwise it was not measured.
| Choice | Paper / authors’ code | This example | Effect |
|---|---|---|---|
| Count array | Paper: 39,943 cells at 0.4 M; code: mature array with 40,132 | mature array | 189 cells, two replicates; not measured |
| 0.4 M replicates fitted | code: 201301004 and 20160509 only | all three | archived vector 2.01804 on the authors’ cells; the fit here moves toward 20131022 (see 23b) |
| Total RNA | code: nuclear + cytoplasmic | recorded total (235 cells differ) | +0.0002 nats per cell |
| Time zero | code: excluded from both objectives; paper silent | excluded | not measured |
| Mean likelihood groups | code: replicates pooled per time | one group per replicate and time | not measured |
| Mean variance | paper Eq. 23: s²/N | s²/N + 1/(12N) | not measured |
| Histogram tail | no tail bin; cap large enough | one tail bin above the cap | leakage ≤ 6.6e-6 |
| ON fraction | “more than three” and “three or more” | X > 3 | figure only |
| Search box | authors: MCMC and several fit stages | one box around the archived histogram fit | see 23b |
| Held-out replicates | not in the paper | 20140429 and 20160509, refitted at draft size | two of five |
| Spatial fit | 15 coefficients fitted | 2 varied on a 3 × 3 grid; result is the archived vector | not a refit |
| Site prediction | elongation 63 nt/s, L from Table S1, active above 2 | same; L = 1630 nt; delay from the archived vector | agrees with the authors’ curve to 0.0024 |
| Site reference | Figure 4D–E | the numerical series in the authors’ figure files | differ from the raw site array by up to 0.27 |
The bioRxiv supplement (Table S3) prints the nonspatial histogram fit
with k_3 = 1.1e2 /s; the archived vector at the pinned revision has
564 /s. The other printed entries agree with the archive to their two
digits. The journal version of the tables was not reachable.
What the check verifies
validation/check_yeast_rna_fit.py runs in about a second, offline:
- the constant-signal law of CRN-craft’s FSP against an explicit generator for the total and the joint model, the BDF2 solver against that law and the BDF2 means against the moment equations (skipped with a message if no C++ compiler is found; everything else runs without one);
- the hand-calculated histogram score;
- the shipped rows: cells per dose (25,511 and 40,132), usable cells after time zero (59,557), the 235 cells whose total differs from the compartment sum, and the site array totals (25,511 and 39,943);
- the archived spatial delay and the site detection threshold;
- that the result files have the expected rows and that the two tables of
page O3b equal what
render.pymakes from them.
It does not refit anything. The scores themselves depend on the platform’s floating point and are not compared bit for bit.
Limits
- The mean-versus-histogram comparison is made near the authors’ answer; see what it shows.
- The held-out scores are not clean: the box center was fitted by the authors to data that include the held-out replicates. Three of five replicates were never held out.
- The spatial model and the transcription-site prediction use the authors’ archived vector. The site prediction is a reimplementation, not a forecast from a model fitted here.
- The fourfold budget check ran once per objective (one 8,000-evaluation restart); it did not improve on the best 2,000-evaluation restart.
- The full-size and spatial runs were not repeated by the review; the draft runs were, and reproduce.
- The measured site traces of the figure files and the raw site array disagree; which one the paper’s Figure 4D shows was not resolved.
Data and license
The authors’ repository is licensed GPL-3.0; it has no separate license
for its data. source-counts.csv, source-sites.csv,
reference-site-*.csv and source-parameters.json are tables derived
from its MATLAB arrays and figure files. They are not covered by this
repository’s MIT license and stay under the terms of their source
(notice);
fetch.py rebuilds all of them from the pinned revision. The underlying
images are deposited at the BioImage Archive (S-BIAD1) and the Image Data
Resource (idr0047).
Exercises
- Refit with the authors’ replicate selection (drop 20131022) and the total as nuclear plus cytoplasmic. Does the fit still move away from the archived vector?
- Hold out each of the other three replicates in turn
(
manifest.json,holdouts). Does the histogram fit win on every one? - Fit the mean objective in the wide box of
review.py. Where does it end, and how does that fit score on the histograms? - Change the ON threshold to
X ≥ 3and redraw the summary figure.
Ten optimization lessons with fcmaes
Tutorials O1, O2 and
O3 fit one model each. The ten lessons of
tutorials/optimization cover the
other things an optimizer does with a simulation: calibration with
reusable preparation, derivatives, several objectives, model selection,
experiment design and fits over many conditions. They run through one
command and keep their code, saved tables and figures next to the lesson
pages.
python tutorials/optimization/run.py C7 --output /tmp/crn-c7-smoke
Every lesson has a smoke preset that runs the whole route in seconds and
a study preset with the budgets of its page. A run writes the model, the
numerical checks, every proposal the optimizer made and a summary.json.
passed in that file means that the lesson’s declared checks passed. It
does not mean that the optimizer found the true parameters.
Method lessons
| Lesson | Question |
|---|---|
| C1. Calibration | Does reusable preparation preserve a complete fit? |
| C2. Sensitivities | Are derivatives correct, rates identifiable and ODE fits transferable to the stochastic model? |
| C3. Oscillators | Which trade-offs and behaviors survive independent paths? |
| C4. Rules | Can finite-path fits of exact aggregation laws tell kernels apart? |
Publication studies
Each study checks its objective against the paper or the paper’s archive before any search, then runs fcmaes and verifies the finalists.
| Lesson | Paper | Objective | Outcome |
|---|---|---|---|
| C5. RNA count calibration | Poovathingal & Gunawan 2010, doi:10.1186/1471-2105-11-414 | weighted distance of cumulative count distributions | recovered within 3% from 10,000 trajectories; a flat valley of the score limits recovery from 100 |
| C6. Stimulus model selection | Gómez-Schiavon et al. 2017, doi:10.1186/s13059-017-1297-9 | joint count likelihood of seven hypotheses, AIC and BIC | the published model is selected |
| C7. Virtual reactor design | Felton et al. 2021, doi:10.1002/cmtd.202000051 | space–time yield against E-factor, by hypervolume | at 50 evaluations no better than random search; ahead of the paper’s best strategy with 500 |
| C8. Sampling design | Fox & Munsky 2019, doi:10.1371/journal.pcbi.1006365 | smallest eigenvalue of the Fisher information | the sampling optimum and the 97-of-100 design ranking are reproduced |
| C9. STAT5 calibration | Boehm et al. 2014, doi:10.1021/pr5006923 | Gaussian likelihood with fitted noise scales | the archived likelihood is reproduced; a search with profiled noise scales reaches it in three of five seeds |
| C10. Pathway calibration | Moles, Mendes & Banga 2003, doi:10.1101/gr.1262503 | weighted residuals over 16 experiments, 36 parameters | objective verified; the searches stay far from the published value at 0.7% of its budget |
Three of these outcomes are misses or partial results, and the lessons say why. In C7 the paper’s protocol of 50 evaluations leaves an evolutionary optimizer four selection steps. In C10 the published value took 2.8 million evaluations; a local least-squares fit from a perturbed start reaches the integration floor, so the objective is right and the gap is budget. In C5 the generating rates are recovered when the search runs long enough and the data are plentiful, and the remaining error at 100 trajectories follows a valley of the objective.
Engine features the studies use
- Probability sensitivities.
crn_craft.sensitivities.forward_sensitivitiesadvances a projected law and its derivatives with respect to parameters together, including the sink, andfisher_informationforms the Fisher matrix over observed bins (reference). C8 uses them. - Retained state sets.
prepare_fsp(model, bounds, retained=states)keeps a chosen set of count tuples; transitions to other states go to the sink (reference). - Concentration trajectories. The optional
crn-diffsol concentrationscommand prepares a deterministic model with real-valued states, compartment volumes and time-dependent inputs once and then solves batches of candidates read from standard input (interface). C7, C9 and C10 use it.
Model reference: crn-craft.model/1.0
This file keeps its former name, “rules language”, so that old links resolve. It is the reference for the model contract
crn-craft.model/1.0, and for the olderrules-modelversions that mean the same thing.
Contracts. The model is crn-craft.model/1.0 (crn-craft describe model-1.0). The versions crn-craft.rules-model/0.1 to 0.4 are still read
and run; a rules-model/0.4 document means what a model/1.0 document means,
with smaller limits (limits). The request is crn-craft.run/1.0
or rules-run/0.1 to 0.6, and the result crn-craft.result/1.0 or
rules-result/0.1 to 0.3 (contracts). The crate is
crn-craft (module crn_craft::rules), the command line crn-craft check
and crn-craft run, and the Python package crn_craft. This page describes
the language, starting from the tree method; methods reference
covers the other methods. Protocol and
gates: docs/decisions/rules-k0-k1-2026-11-02.md.
Species are not a fixed list. Some models cannot list their species in
advance: each new mitochondrial mutant is its own clone, polymers have a
length, clusters have a size, cells carry a lineage. The engine simulates
such systems exactly. Species types carry numeric attributes; an
instance is a type plus one value per attribute and a copy number.
Instances appear when a rule produces a new attribute vector and disappear
when their count reaches zero. Rules are schemata: one rule stands for the
reactions of every matching instance. A model whose types have no attributes
is an ordinary reaction network, written with crn_craft.Model, and a network
model/0.1 file converts to one with crn-craft convert.
A first model
the fixed-population mtDNA model: molecules degrade, replicate into the
vacancies below a copy-number target K, and a wild-type replication can
produce a new mutant clone, advantaged (sm) with probability fracAdv.
{
"schema": "crn-craft.rules-model/0.1",
"name": "mtdna_fixed_population",
"parameters": {"K": 20, "delta": 1.0, "sw": 1.0, "sm": 1.5, "mu": 0.1, "fracAdv": 0.5, "w0": 20},
"types": [{"name": "mtDNA", "attributes": ["clone", "s", "wt"]}],
"initial": [{"type": "mtDNA", "attributes": {"clone": 0, "s": "sw", "wt": 1}, "count": "w0"}],
"observables": {
"N": {"type": "mtDNA"},
"D": {"type": "mtDNA", "weight": "x.wt + sm * (1 - x.wt)"},
"mutants": {"type": "mtDNA", "where": "x.wt == 0"},
"mutant_clones": {"type": "mtDNA", "where": "x.wt == 0", "reduce": "distinct"}
},
"rules": [
{"name": "degradation", "reactants": [{"label": "x", "type": "mtDNA"}], "rate": "delta", "products": []},
{"name": "replication",
"reactants": [{"label": "x", "type": "mtDNA", "factor": "x.s * (1 - mu * x.wt)"}],
"rate": "max(0, K - N) / D",
"products": [{"type": "mtDNA", "copy": "x"}, {"type": "mtDNA", "copy": "x"}]},
{"name": "mutation",
"reactants": [{"label": "x", "type": "mtDNA", "where": "x.wt == 1", "factor": "x.s * mu"}],
"rate": "max(0, K - N) / D",
"products": [{"type": "mtDNA", "copy": "x"},
{"type": "mtDNA", "attributes": {"clone": "new_id()", "s": "choice(fracAdv, sm, sw)", "wt": 0}}]}
]
}
The full file is models/rules/mtdna-fixed.rules.json; the aggregation,
immigration–death and immigration–dimerization models sit beside it.
crn-craft check models/rules/mtdna-fixed.rules.json
crn-craft run MODEL REQUEST [--archive NEW_DIRECTORY] [--cancel-file PATH]
crn-craft describe model-1.0 # JSON Schema; also run-1.0, result-1.0, check-1.0
The file above is a rules-model/0.1 document. Writing its schema as
crn-craft.model/1.0 gives the same model. rules-check and rules are
aliases of check and run.
Model
| Field | Meaning |
|---|---|
parameters | Finite numbers by name. Parameters and observables share one namespace. |
types | {name, attributes}. Attribute values are finite f64; -0 is stored as 0. |
initial | {type, attributes, count}: every attribute, and a nonnegative integer count, as numbers or parameter expressions. Equal attribute vectors merge. |
observables | Named reductions over the instances of one type (below). |
rules | {name, reactants, rate, products} with reactant patterns; in 0.3 propensity may replace rate. Up to rules-model/0.4, at most two patterns. In model/1.0, any number, and a pattern may carry a count (higher-order rules). |
stop | Optional condition over parameters and observables. Once true, the state is held to the end of the report grid and the replicate is stopped. |
continuous | rules-model/0.3: continuous variables, ODEs between events that rates may read (below); rules-model/0.4 adds independent variables. |
Names, including the model’s name, are ASCII identifiers
([A-Za-z_][A-Za-z0-9_]*, at most 64 bytes) and cannot be function names. Unknown fields and duplicate keys are rejected.
Observables
{type, label?, where?, weight?, reduce?}. The label defaults to x, the
weight to 1. Over the present instances of type that satisfy where:
reduce | Value |
|---|---|
sum (default) | Σ weight × count |
distinct | Σ weight, each instance once (weight 1 counts distinct instances, e.g. clones) |
max, min | largest or smallest weight; 0 when no instance matches |
max_count (crn-craft.model/1.0) | largest weight × count, for example the size of the largest clone; 0 when no instance matches |
Weights must be finite; they may be negative. Older model versions refuse
max_count with CRN-E003.
Rules and propensities
A reactant pattern is {label, type, where?, factor?}. factor is a local
factor h(x) ≥ 0 (default 1); an instance that fails where has h = 0. The
rule’s rate is a global factor g ≥ 0 over parameters and observables. With
n_x the count of instance x:
| Reactants | Propensity |
|---|---|
| none | g |
| one pattern | g × Σ_x h(x) n_x |
two identical patterns (same type, where and factor) | g × Σ over unordered pairs of distinct molecules h(x) h(y) = g × ½[(Σ h n)² − Σ h² n] |
| two patterns over different types | g × (Σ h_x n_x)(Σ h_y n_y) |
For one instance this is the stochastic mass-action convention n(n−1)/2 (a
2A channel with coefficient c). Two different patterns over the same type
are rejected in 0.1. Patterns are compared after their
labels are resolved, so a.size and b.size are identical factors.
Which molecule of a pair is x. Under crn-craft.run/1.0 the two
molecules of an unordered pair get the labels x and y at random, each
assignment with probability 1/2. So a rule “x replaces y” (products
[{"copy": "x"}, {"copy": "x"}]) is neutral: either molecule of the pair
can be the one replaced. Requests before run/1.0 keep the order of 0.7:
for two molecules from different instances, x is the one whose instance
came earlier in the engine’s internal order, which makes such a rule favor
older instances. Rules whose products do not depend on the labels, such as
x.size + y.size, are unaffected either way; for them the engine keeps the
fixed order, which then shows only in event logs and observers (the first
reactant listed is not random). See
methods for the sampler identities.
Counting identical reactants, and rebop
A rate counts distinct combinations of reactant molecules, Gillespie’s
h_μ (Gillespie 1977, DOI
10.1021/j100540a008): with rate k,
A fires at k·n, A + B at k·n_A·n_B and A + A at k·n(n−1)/2. rebop 0.10
uses the same expression for distinct species but leaves out the 1/m! for m
identical reactants: its numeric rate k on ["A", "A"] fires at k·n(n−1)
(its documentation equates 4.2 with "4.2 * A * (A-1)"). A rebop model
with a numeric rate k on A + A corresponds to rate 2k here; models without
identical reactants agree. String rates are full propensities in both. The
Python builder crn_craft.Model follows the convention of this
engine, so its JSON equals a hand-written model; see
validation/check_builder.py for the statistical comparison with rebop.
Whole-rule propensities (rules-model/0.3)
A rule may give propensity, its total rate P as an expression over
parameters and observables, instead of rate. Exactly one of the two is
present (CRN-R013); propensity in 0.1 or 0.2 is CRN-R015, and a 0.1 or
0.2 rule without rate stays CRN-E003.
| Reactants | Propensity |
|---|---|
| none | P |
| one pattern of type T | P if T has a molecule, else 0 |
| two patterns of type T | P if T has two molecules, else 0 |
| patterns of types T and U | P if T and U each have a molecule, else 0 |
The reactant patterns take no where or factor (CRN-R013), and P cannot
read their labels (CRN-R012): the expression already says how the rate
depends on the state, for example "vmax * S / (Km + S)" over an observable
S. P is evaluated only while it applies; a negative or non-finite value
fails the replicate (CRN-R030 at /rules/i/propensity). A firing picks
reactant molecules uniformly: one of the type’s molecules, or an unordered
pair of distinct molecules, whatever their attributes. The tree method
samples this for any type. The static methods lower each pattern to its
tuples, so they accept a propensity rule only when each reactant type has a
single tuple, as for attribute-free species (CRN-R020 at /method
otherwise); mtdna_direct falls back to Static Direct with CRN-R051
(except for the builder form of the three-class model under run/1.0,
which it certifies: methods), and
generated rates kernels refuse such models (CRN-R020), while generated
event loops emit them with the interpreter’s arithmetic. For one
reactant, propensity: "k * A" and rate: "k" give the same floating-point
value, so they reproduce each other’s trajectories exactly.
g is evaluated only when the reactant weight is positive, so a rate such as
(K - N) / D is never evaluated after extinction. A negative or non-finite
rate or factor fails the replicate (CRN-R030).
Reactants are consumed. A product is {type, copy?, attributes}: copy names
a reactant of the same type whose attributes are copied, and attributes
overrides some (with copy) or gives all (without). A product equal to a
reactant cancels its consumption, so x → x + x only adds one copy.
Higher-order rules (model/1.0)
A reactant pattern of an attribute-free type may carry count, an integer
from 1 to 2,147,483,647 (default 1). It stands for count molecules of that
type. A rule has any number of patterns, so A + A + A → ... is a pattern with
count: 3, or three identical patterns, which means the same. Patterns with
count take no where or factor, and their type has no attributes
(CRN-R013). The rule’s rate gives
rate × Π C(n, k)
over the patterns, with n the count of the type’s molecules and k the pattern’s
count; this is the combinatorial convention of every other rate. For a
whole-rule propensity, the value applies while every pattern has enough
molecules. A product list may be any length up to 64 molecules.
Which methods run higher-order rules:
| Method | Higher-order rules |
|---|---|
static_direct, next_reaction, tau, hybrid, generated event loops | yes |
tree (the default when method is absent), mtdna_direct, binomial, generated rates kernels | refused: CRN-R020 at /method |
crn_craft.Model.add_reaction takes three or more reactant molecules and
writes the count for you. crn-craft convert writes a network reaction of
three or more molecules the same way, with labels x, y or x1, x2, ….
Expressions
Operators, loosest first: ||, &&, == !=, < <= > >=, + -, * /,
unary - !, ^ (right associative; -x^2 is -(x^2)). Comparisons and
logic return 1 or 0; nonzero is true; &&, ||, if and choice
short-circuit. An undefined (NaN) operand of !, &&, ||, if, min or
max gives NaN, and a NaN where or stop fails the replicate (CRN-R030)
instead of counting as true; comparisons with NaN are false (IEEE). Functions:
min max exp log sqrt abs floor ceil if(c, a, b). Numbers are decimal with an
optional exponent; only ASCII whitespace separates tokens.
| Field | Names it may use |
|---|---|
initial attributes and counts | parameters |
pattern where, factor; observable where, weight | parameters, label.attribute of that instance |
rule rate, stop | parameters, observables |
product attributes | parameters, label.attribute of the rule’s reactants, random draws |
Random draws exist only in product attributes: bernoulli(p),
choice(p, a, b) (a with probability p; only the chosen branch is evaluated),
uniform(a, b), normal(m, s) (Box–Muller) and new_id(). new_id()
returns 1 + max(0, largest initial attribute value), floored, on its first call
and counts up by one, so new clones never reuse an identity of the initial
state or of each other. Values written by constants or parameters in products
are not tracked: keep such identities below the initial maximum. Identities
must stay below 2⁵³: a model that calls new_id() with an initial attribute of
2⁵³ − 1 or more is rejected (CRN-R014), and reaching 2⁵³ during a run fails
the replicate (CRN-R030).
Continuous variables (rules-model/0.3)
A model may declare continuous variables in continuous, each
{name, initial, derivative, lower_bound?, on_bound?}:
{
"continuous": [
{"name": "ATP", "initial": "ATP0",
"derivative": "f * wild_type - v1 * ATP - v2 * N",
"lower_bound": 0, "on_bound": "stop"}
]
}
| Field | Meaning |
|---|---|
name | shares one namespace with parameters and observables (CRN-R010); also the result column |
initial | number or parameter expression, finite and not below the bound (CRN-R014) |
derivative | dx/dt between events, over parameters, observables and continuous variables; a non-finite value fails the replicate (CRN-R030 at /continuous/i/derivative) |
lower_bound, on_bound | together or not at all (CRN-R013): a number or parameter expression, and stop or clamp |
Rule rates and propensities may read the variables, so rates change between
events. The model’s stop, observable filters and weights, reactant
patterns and products cannot read them (CRN-R012; a stop is checked at
events only), and neither can run-request trackers (CRN-R020). Results
list the variables as observable columns after the model’s observables, in
declaration order, and rules-result/0.3 names them in continuous.
At a lower bound, stop ends the replicate as stopped when the variable
reaches the bound while its derivative there is not positive (also at time 0
and after an event); the variable reads the bound on every later report and
the other observables hold their values. This is the rule of the legacy ATP
block at zero. clamp holds the variable at the bound while its derivative
there is negative, and it follows the ODE again once the derivative is
positive; rates and reports never read it below the bound.
models/rules/mtdna-three-class-atp-continuous.rules.json is the ATP model
of mtdna-three-class-atp.rules.json written this way: the parameters f,
v1, v2, c and ATP0 replace the atp block, and each coupled
replication rate is multiplied by c / (c + ATP) in its expression. A model
cannot have both atp and continuous (CRN-R015); the legacy block and
thinning keep working unchanged.
Independent variables (rules-model/0.4)
crn-craft.rules-model/0.4 is 0.3 plus one optional field of a continuous
variable, "independent": true (default false; null is rejected with
CRN-E003, and the field in 0.1–0.3 with CRN-R015 at
/continuous/i/independent). An independent variable’s ODE does not depend
on the stochastic state: its derivative may read only parameters and
other independent variables. A read of an observable or of a variable
without independent: true is refused with CRN-R012 at
/continuous/i/derivative. initial and lower_bound read parameters, as
for every variable. Rule rates and propensities, and the derivatives of the
other (dependent) variables, read independent variables like any continuous
variable, and results report them like the others.
{
"continuous": [
{"name": "m", "initial": "m0", "derivative": "g * m", "independent": true},
{"name": "x", "initial": 0, "derivative": "m * A - x"}
]
}
Without independent, a rules-model/0.4 document means exactly what the
same document means as 0.3. Stored 0.1–0.3 documents are unchanged.
Bounds keep their meaning. clamp holds an independent variable at its
bound as above. stop ends the replicate when the variable reaches its
bound with a derivative that is not positive; because the variable does not
depend on the replicate, that happens at the same time in every replicate
that has not stopped, failed or reached the horizon before.
The hybrid method
Only hybrid runs a model with continuous variables; every other method
refuses one with CRN-R020 at /method. Its tolerances rtol and atol,
its integration scheme and its error control are in the
methods reference.
Run request and result
The request (crn-craft.run/1.0 and the rules-run versions) is in the
contracts, with its budgets and the admission
rule. The result is in the results reference. The numerical
policy of the tree method is in the
methods reference.
Diagnostics
Every code has an entry in the diagnostics reference, which
also has a table of the CRN-R codes of models and run requests.
Validation
validation/check_rules.py compares the engine with exact laws. The results
are in validation/rules/RESULTS.md, and the
technical report has the account.
Limits
rules-model/0.1 to 0.4 | crn-craft.model/1.0 | |
|---|---|---|
| Types | 64 | 4,096 |
| Parameters | 1,024 | 16,384 |
| Observables | 256 | 4,096 |
| Rules | 1,024 | 65,536 |
| Instance tuples (static methods) | 256 | 4,096 |
| Channels (static methods) | 4,096 | 65,536 |
Both versions share the other limits: 64 attributes per type, 64 products
per rule, expressions of at most 4,096 bytes, 100,000 initial entries,
documents of at most 16 MiB and JSON nesting of at most 48
(describe()["limits"]). Exceeding a model limit is CRN-R015. To use the
larger limits, change only the schema string to crn-craft.model/1.0.
What is not supported
- ODE coupling: rules-model/0.2 adds one fixed case, the ATP flow of
the variable-population mtDNA model, solved with exact thinning
(ATP and thinning); rules-model/0.3 adds general
continuous variables, simulated approximately by
hybrid, and rules-model/0.4 independent variables, whichhybridintegrates once per run. An independent variable can carry explicit time dependence (a clockt' = 1, or a forcing such as a seasonal oscillator). No compartments. - Two different patterns over one type, higher-order rules over attributed
types, and counts inside expressions are not supported yet. The size of
the largest clone is an observable:
reduce: "max_count"(crn-craft.model/1.0). - Models are JSON.
crn_craftprepares and runs ensembles from Python (Python API), andcrn_craft.Modelbuildsmodel/1.0documents:add_species(withattributesfor an attributed type) andadd_initialwritetypesandinitial,add_observablean observable, andadd_reaction(rate, reactants, products)a rule. A numeric rate orcrn_craft.mass_action(expression)is the rule’srate, with the counting above, and a plain string its wholepropensity; reactants are type names orcrn_craft.pattern(...), products type names,crn_craft.copy(label, ...)orcrn_craft.new(type, ...)(chapter 12). - The tree method recomputes the propensities of all rules after every
event, which suits models with few rules. Closed models can use the
static methods; benchmarks are in
validation/mtdna/.
Methods and their options
This page describes every simulation method: the exact
methods and their event selectors, the approximate methods, the fast path
mtdna_direct, the ATP block, the hybrid method and the compiled event
loops. It also has the options of Static Direct, the random stream and the
numerical policy. The model language is in the model reference,
the request and model versions are in the contracts, and the
cost of each method is in the
performance analysis. The guide
teaches the choice of a method in
chapter 7. An exact method samples the model’s
process with finite-precision arithmetic and Monte Carlo uncertainty. It is
not a biological validation claim.
The methods
method | Exact | Scope | Sampler identity (prefix chacha8-u53/ or chacha8-u53-ziggurat/) |
|---|---|---|---|
static_direct | yes | closed models: a fixed set of attribute vectors, any number of reactant molecules in model/1.0 | rules-static-direct, with a suffix for the selector and the trackers |
next_reaction | yes | the same models | rules-next-reaction/1 |
tree (the default) | yes | every model without an ATP block or continuous variables; instances may change identity | rules-direct/2, or rules-direct/3 with random pair labels |
mtdna_direct | yes | the fixed three-class vacancy model, with a fallback to Static Direct | rules-mtdna-direct/1 (the fast path) |
thinning | yes | models with an ATP block, and only those | its own identity (ATP and thinning) |
tau with epsilon | no | closed models: adaptive Poisson leaps with competing critical events and exact fallback | its own identity (leaping) |
binomial with step | no | closed models of single-parent unit reactions: death-then-birth splitting | its own identity |
hybrid | no | models with continuous variables, and models without; piecewise-deterministic at declared tolerances | rules-approximate-hybrid-dopri54/1 (hybrid) |
Static Direct lowers the model to channels once, at preparation: species, channels, the changes each channel makes and the channels whose rates each change affects. Each event then recomputes only the affected rates, draws a waiting time and selects a channel. A zero total rate is absorbing: the state is held to the horizon without consuming random numbers. Report values are right-continuous, so an event exactly at a report time is included.
Three rules hold for every selector:
- A positive channel must be at least 2⁻⁵³ of the total rate. Below that, a
53-bit uniform cannot select it exactly, and the replicate fails with
CRN-R031rather than dropping the channel. - A non-finite or negative rate fails the replicate (
CRN-R030). There is no fallback to the last channel. - Under
run/1.0a positive wait too small to move the clock is accepted; 1,000,000 such steps in a row fail withCRN-R030. Everyrules-runversion fails at the first one.
The third rule is the clock of every event-driven method: the next-reaction
method, the exact steps of tau-leaping, thinning, mtdna_direct and the
hybrid method follow it too. At a time t a wait is below half a rounding
unit of t with a probability near the total rate times half that unit, so
about one event in 10⁹ at t = 1000 and a total rate of 10⁴. Such an event
happens at the same representable time, an error below half a rounding
unit, as for any other event. Rescaling time does not change how often
this happens.
Selectors
Under crn-craft.run/1.0, method.selector of static_direct chooses how
the next channel is selected. Every selector samples the same law; each uses
the random stream differently, so the same seed gives different paths, and the
sampler identity names the selector.
selector | How it selects | Sampler suffix |
|---|---|---|
linear | a scan of the channels in order, as in every rules-run version | none |
composition_rejection | channels grouped by the binary exponent of their rate; a group by its mass, a member by rejection | -cr |
sorting | a scan in an order that moves each fired channel one place forward | -sorting |
rssa_cr | candidates by composition–rejection from upper bounds of the rates over population intervals, accepted against lower bounds or the exact rate | -rssa-cr |
auto (the default in run/1.0) | one of the others, chosen at preparation | the chosen one |
auto chooses RSSA-CR from 8 channels when no rate reads two or more
species, and from 128 channels when the species that start with molecules
average fewer than 8 molecules. Otherwise it chooses composition–rejection
from 128 channels, and otherwise the linear scan. It never chooses sorting.
It decides from the initial counts: a model whose populations later grow or
shrink far from them can end up with a slower selector. The thresholds are in
describe()["selectors"]["auto"].
The rules-run versions run the linear scan and refuse the field
(CRN-R020 at /schema). A request that the Python helpers write as
run/1.0 for a crn_craft.rules call names "selector": "linear", so
adding quantiles never changes the paths. The top-level crn_craft.ensemble
leaves the choice to auto. Generated event loops and rates kernels run the
linear scan only, and refuse any other selector, also when auto would pick
one (CRN-R020 at /method/selector).
Selectors are ports of published algorithms: composition–rejection (Slepoy, Thompson and Plimpton, J. Chem. Phys. 128, 205101 (2008)), sorting direct (McCollum et al., Comput. Biol. Chem. 30 (2006), 39–49) and RSSA-CR (Thanh, Priami and Zunino, J. Chem. Phys. 141, 134116 (2014), with composition–rejection for the candidate draw).
Waiting times and the options of Static Direct
Static Direct has two options in the method object, from rules-run/0.4:
{
"kind": "static_direct",
"waiting_time": "ziggurat",
"sparse_trackers": true
}
waiting_timeis"inverse"or"ziggurat". The inverse transform inverts one uniform per wait. Ziggurat draws the wait with the Ziggurat sampler, which consumes the seeded stream differently, so the numbers differ cell by cell but not in distribution.sparse_trackersistrueorfalse.trueintegrates each eligible tracker, an unweighted single-class count without a first-passage predicate, over its constant spans. The integral can differ in the last bits from per-event integration. First-passage predicates and other projection families keep per-event observation. Without an eligible tracker, an explicittruechanges nothing and reports the per-event sampler identity with aCRN-R051warning.
What an absent option means depends on the request version:
| Request | Absent waiting_time | Absent sparse_trackers |
|---|---|---|
| rules-run/0.2 to 0.5 | "inverse" | false |
rules-run/0.6 and crn-craft.run/1.0 | "ziggurat" | sparse where a tracker is eligible, otherwise per-event integration without a warning |
Under run/1.0 the method object also takes selector (above); absent means
auto. So {"kind": "static_direct"} in rules-run/0.6 runs
chacha8-u53-ziggurat/rules-static-direct-sparse-trackers/1 with eligible
trackers and chacha8-u53-ziggurat/rules-static-direct/1 without, and
{"kind": "static_direct", "waiting_time": "inverse", "sparse_trackers": false} runs the earlier default with its numbers. The Python rules helper
selects rules-run/0.6 for every static_direct method. Rust callers that
construct Method::StaticDirect with waiting_time: None, sparse_trackers: None, selector: None get the defaults of their request’s
version. Attaching a Continue observer or an event log leaves the tracker
policy consistent. The fallback of mtdna_direct keeps inverse waits and
per-event trackers in every version.
Ziggurat draws exponential waits from tables adapted from the Julia ecosystem
(see THIRD_PARTY_NOTICES.md). The inverse
transform is -ln(1 - u) / total, with u a 53-bit uniform in [0, 1) that is
drawn again when it is 0.
The random stream
Every replicate draws from its own ChaCha8 stream. The key is the SHA-256 of
the domain crn-craft.rules/0.1 and the root seed; the replicate
index is the stream id. A 53-bit uniform is the high 53 bits of a 64-bit word
times 2⁻⁵³. Results therefore depend on the seed and the method, never on the
thread count, and a replicate’s path is the same in a larger ensemble.
Statistical equivalence of the selectors is checked against exact
distributions: master-equation solutions and the finite state projection, with
predeclared tests and a recorded family error rate (validation/merge/).
Next reaction
Gibson–Bruck next reaction updates the fired channel and the channels that its count changes affect. Active clocks are rescaled when their rates change. Sparse networks can benefit when few clocks change at each event (DOI 10.1021/jp993732q).
Approximate methods: tau and binomial
Tau follows the step selection of Cao, Gillespie and Petzold (DOI 10.1063/1.2159468). The species drift and variance bound uses g=2 for expression rates and falls back to exact steps for a submolecule allowance. A propensity condition bounds the mean and spread of every rate change by ε·a_j, using first differences a_j(x + ν_k) − a_j(x), so rates that read global observables such as the vacancy K − N are controlled directly. If one firing moves a rate by more than ε·a_j, the step is exact. Low populations, creation into a rare class and channels that ten firings could switch off are critical and fire at most once per leap. Unacceptable proposals halve the step before an exact fallback. The cost per step grows with the square of the channel count. In the fixed-population mtDNA model at K = 1000 the vacancy holds only a few places, so this rule runs exact events and tau gives no speedup there; the review gate at K = 1000 found no multi-firing leaps. Leaps occur when every rate changes slowly, as in the high-copy immigration/death gate.
Binomial splitting recomputes the replication rates after degradation and groups competing replication outcomes per parent. Each parent’s outcome probabilities are the competing-risk values (a/Λ)(1 − e^(−Λ·dt/n)) with rates frozen over the step. Steps lie on the fixed lattice k·step; reports between lattice points hold the last step’s state, so the report grid does not change the path. Frozen rates can put N a few molecules above K. The hourly implementation of the Java reference groups simultaneous new mutants differently and keeps clone identities.
Both methods report aggregate firings at leap boundaries, each with its own sampler identity. For both, the sampling-step budget bounds the random words and the leap iterations, including iterations with zero firings.
Higher-order rules and static lowering
crn-craft.model/1.0 and crn-craft.run/1.0 mean what rules-model/0.4 and
rules-run/0.6 mean, plus the features that arrived with them: Static Direct
selectors, quantile statistics, the fsp method, higher-order rules and
larger limits (model reference). The versions are in
contracts.
Higher-order rules of model/1.0 (a pattern count above one, or more than
two patterns) run on static_direct, next_reaction, tau and hybrid.
tree, mtdna_direct and binomial refuse them with CRN-R020 at
/method.
Whole-rule propensities (rules-model/0.3, which crn_craft.Model writes for
string rates; see the model reference)
are sampled by every method. The static methods need each reactant type of
such a rule to lower to one tuple, as for attribute-free species, and refuse
other models with CRN-R020 at /method; tree has no such limit.
mtdna_direct certifies them only in the builder form of the three-class
model under crn-craft.run/1.0 (the fast path);
otherwise it runs Static Direct with a CRN-R051 warning. The generated
rates kernels refuse them. Generated event loops
emit them, as they emit every rate expression and observable that Static
Direct runs (checklist).
Static lowering evaluates local predicates and factors once and compiles
constant and vacancy-rate kernels. It accepts up to 256 tuples and 4,096
channels for the rules-model versions, and 4,096 tuples and 65,536 channels
for model/1.0. Static Direct and the leap fallbacks select among all
channels in one level, so every positive channel must be at least 2⁻⁵³ of the
total (CRN-R031); the tree method resolves rules and instances separately
and can run such models. Random product attributes use the tree method.
Identical pairs in the static path require a single matching tuple.
Models with changing instance identities use tree. The legacy ATP block
requires thinning, and continuous variables require hybrid.
The tree method and its numerical policy
- The tree method is Gillespie’s direct method. Rule selection scans the rule propensities in order; instance selection descends a pairwise sum tree per distinct pattern. Tree totals are recomputed from their children on each update (no accumulated drift); their rounding depends on the slot layout, which is a deterministic function of the replicate’s history.
- Identical-pattern pairs use a pair tree: each node stores its pattern
weight S and the weight P of pairs of distinct molecules inside it,
P = P_left + P_right + S_left·S_right (a leaf holds h²·n(n−1)/2). The
propensity is g × P at the root, a sum of nonnegative terms without the
cancellation of ½[(Σ h n)² − Σ h² n]. Selection descends by P into a child or
stops at the cross term, then picks one molecule on each side by S; no
rejection (sampler
chacha8-u53/rules-direct/2; version 1, used only for the first K1 gate run, drew two molecules and rejected the same one). - Under
crn-craft.run/1.0, a pair rule whose products can depend on which molecule isxdraws one more uniform when the two molecules come from different instances and swaps the labels with probability 1/2 (samplerchacha8-u53/rules-direct/3). Version 2 gavexto the instance on the left of the tree, so “x replaces y” favored older instances. The products count as label-independent only when every product attribute is deterministic and swappingxandymaps the product list onto itself (for examplex.size + y.size, or keeping both molecules); such rules, pairs over a type without attributes (which has one instance), and requests beforerun/1.0keep version 2 and its streams. This classification, with+,*,==,!=and two-argumentminandmaxas the commutative operations, is part of version 3; a change to it needs a new identity. Exact-law check:validation/merge/RESULTS.md, “0.8 pair labels”. - A positive rule propensity or instance weight below 2⁻⁵³ of its total cannot
be selected exactly by a 53-bit uniform and fails with
CRN-R031. For pair rules the check is conservative: the smallest factor squared must reach 2⁻⁵³ of the pair total. - Overflowing weights, pair totals and observable totals fail the replicate
(
CRN-R030) rather than becoming 0 ornull. - Each replicate draws from its own ChaCha8 stream keyed by SHA-256 of the
domain
crn-craft.rules/0.1and the root seed, with the replicate index as stream id. Results do not depend on the thread count. - Counts stay at most 2⁵³ (
CRN-R042otherwise) and identities below 2⁵³.
The fast path mtdna_direct
mtdna_direct is an exact direct method fused for one model structure: three
classes in a fixed population. It reads that structure from the lowered rules;
the model file and its names do not matter. Select it with method set to
{"kind": "mtdna_direct"} in a request of version rules-run/0.3 or later
(run/1.0 included), or with method="mtdna_direct" in crn.ensemble. The
guide shows it in chapter 12a.
At preparation it lowers the model to a fixed network, as Static Direct does, and certifies six points:
- Three classes, eight channels. The network has exactly three attribute vectors (classes) and eight channels. Each channel consumes one molecule and changes one class by one molecule: every class degrades and replicates, and one class, the wild type, also yields one molecule of each other class (the two mutation channels). The roles are read from the channels.
- Degradation. All three classes degrade at one constant rate.
- Replication. Every replication and mutation rate is
max(0, K - N) / Dtimes constant factors. All five share oneK, an expression of parameters whose value is an integer from 1 to 1,000,000 and at least the initial population.Nis an observable that counts every molecule, andDan observable that sums the classes with finite positive weights. - Observables. Every observable is a finite weighted sum over the three classes.
- Stop. The stop is absent, or
N > 0 && mutants >= f * Nwith a numberfin [0, 1], wheremutantscounts the two classes other than the wild type. - Resolution. Bounds from
K, the weights and the rate constants show that every hazard stays finite, and every positive hazard at least 16 · 2⁻⁵³ of the total, in every reachable state (evaluated at the worst state: one vacancy, one molecule of the class).
The certificate holds for one model and one parameter set: bind_parameters
certifies each candidate again. If a check fails, the run uses generic Static
Direct with inverse waits and per-event trackers. metadata["sampler"] is
then chacha8-u53/rules-static-direct/1, the numbers equal those of
{"kind": "static_direct", "waiting_time": "inverse", "sparse_trackers": false}, and a CRN-R051 warning in metadata["diagnostics"] names the
failed check. A model that cannot be lowered at all, such as the clone model,
is rejected with CRN-R020, as by every method except the tree.
The builder form (run/1.0 requests only, from 0.7.1). A model written
with the builder, such as three_class() of tutorial S1, has three
attribute-free species and whole-rule propensities instead. Under a
run/1.0 request the certificate reads each propensity as a law and
accepts the model when the laws are the ones above:
- a degradation is one constant times the count of its species, the same constant for all three;
- a replication or mutation is
max(0, L)divided byD, times constants, times the count of its parent species, in any order and association, whereLisKminus the three counts andDis a weighted sum of the three counts with finite positive weights, the sameKandDin all five rules (parameters may be named or written as numbers, and observables may be counts or weighted sums of the species); - the stop is absent, the form of point 5, or
T > 0 && P >= f * T(orT * f), whereTandPare sums of observables with integer weights that equal the total count and the count of the two mutant species.
Every sum and coefficient in these forms is checked to be exact, and the
stop’s sums are integers below 2⁵³, so the propensities equal the fast
path’s hazards as functions of the counts, and the stop holds in the same
states. Points 1, 4 and 6 are checked as above. The kernel of the builder
form of the guide’s model equals the file form’s to the bit, so a cell makes
the same draws under both forms: same events, and M + A equals the file
form’s mutants at every report time. The sampler identity is therefore the
same, chacha8-u53-ziggurat/rules-mtdna-direct/1. Requests of the
rules-run versions keep the fallback with CRN-R051 (“the model has
whole-rule propensities”). Release 0.7.0 ran that fallback for run/1.0
requests too. Such a request therefore gives another result from 0.7.1 on:
the same law under the fast path’s sampler, where 0.7.0 reported
chacha8-u53/rules-static-direct/1 and the warning.
mtdna_direct samples the same process as Static Direct with a different
random stream: each cell’s ChaCha8 words go to Ziggurat waiting times and to
a selection over grouped hazards. Its sampler identity is
chacha8-u53-ziggurat/rules-mtdna-direct/1, which confirms that the
specialization ran. Results agree with Static Direct in distribution, not
cell by cell, and the same seed gives a different trajectory under the two
samplers. Each sampler keeps its own completed numerical results across
worker counts.
How it works: the kernel tracks the total population directly and computes the common vacancy factor once per event. It groups degradations and wild-type birth outcomes into cumulative intervals with each original reaction’s hazard, so it computes the eight hazards from three counts with one division and reads its stop from the counts. Report observables are evaluated on demand. Simple single-class count trackers integrate between changes in that class; the integral can differ in the last bits from integration across every event. First-passage expressions, event logs and live callbacks keep the general observation path. The unit exponential uses the Julia-derived Ziggurat sampler. ChaCha8 streams, accounting and work budgets stay in use.
What it gains, measured on 12 November 2026 on the file form of the model on
the two-CPU host (medians of three runs, validation/merge/manual-ratios/):
about 2.8 times less time per event than Static Direct with its default
Ziggurat waits and sparse trackers, and 3.1 times less than Static Direct with
inverse waits and per-event trackers. The performance
analysis has older
measurements. It is the fastest route for the fixed three-class topology and
the only fast one from the command line.
A prepared run can bind an independent candidate without writing the request
again: each candidate validates and lowers the new parameter values once,
since the parameters of an attributed model can change attributes and
topology. A candidate’s model_sha256 and run_sha256 hash the re-serialized
bound model and request, not a file on disk; even an empty override changes
them.
The ATP block and thinning
The legacy ATP fixture is a rules-model/0.2 document with an atp block, and
thinning is the exact method that runs it. Between events the solver
integrates dA/dt = f × wt − v1 × A − v2 × N analytically. Selected
replication rules are multiplied by c/(c+A). The minimum ATP over the
fixed-count interval gives the thinning envelope: it limits each interval
using the current ATP derivative and half the replication denominator. The
derivative magnitude shrinks while counts stay fixed, which keeps the
envelope tight near rapid changes and advances the analytic flow at each
interval boundary. The solver reports ATP on the grid and stops at its zero
crossing. ATP at zero counts as depleted only if the forcing f × wt − v2 × N
is not positive; with positive forcing it rises again. An ATP stop and a
model stop both report stopped; ATP is zero on every report after an ATP
stop. The additional ATP column is continuous. Event trackers are restricted
to discrete observables and predicates that read those observables. The
supplied Java SSA uses the same ATP flow but freezes rates over its sampled
waiting interval.
models/rules/mtdna-three-class-atp-continuous.rules.json writes the same
model with a continuous variable ATP (rules-model/0.3): its derivative is
the expression f * wild_type - v1 * ATP - v2 * N, each coupled rate ends in
* c / (c + ATP), and lower_bound: 0 with on_bound: "stop" keeps the
depletion rule above. The hybrid method integrates it with Dormand–Prince
5(4) at the request’s tolerances
(continuous variables);
validation/hybrid/RESULTS.md compares it with thinning on the legacy file.
The legacy file and thinning are unchanged.
The hybrid method
Only hybrid runs a model with continuous variables; every other method
refuses one with CRN-R020 at /method. The request gives its tolerances in the method object:
{"kind": "hybrid", "rtol": 1e-6, "atol": 1e-9}
with rtol in [1e-12, 1e-2] and atol in (0, 1e-2] (CRN-R020 at
/method/rtol or /method/atol); hybrid needs rules-run/0.5 (CRN-R020
at /schema). The Python helper writes these values for method="hybrid".
The model is a piecewise-deterministic Markov process (Davis 1984, DOI 10.1111/j.2517-6161.1984.tb01308.x), simulated by integrated propensities (Alfonsi et al. 2005, DOI 10.1051/proc:2005001):
- After each event draw a unit exponential threshold E from one open uniform, E = −ln u.
- Integrate the variables and the integrated total propensity
Λ(t) = ∫ a₀ ds, with Λ = 0 at the event, by the Dormand–Prince 5(4)
pair (DOI 10.1016/0771-050X(80)90013-3).
Steps follow the standard error control of Hairer, Nørsett and Wanner
(Solving Ordinary Differential Equations I, 2nd ed., 1993, II.4): the
root-mean-square of the error estimate over all components, each scaled
by
atol + rtol·max(|y₀|, |y₁|), must not exceed 1; the next step is h·min(10, max(0.2, 0.9·err^(−1/5))). The first step uses their starting rule, later ones the previous prediction, and each step is at most four times (E − Λ)/a₀ at its start (but not below 16 rounding units of the time). - The event happens where Λ reaches E, located by the Illinois method on
the fourth-order dense output (II.6, after Shampine 1986, DOI
10.1090/S0025-5718-1986-0815836-3).
It selects channel j with probability a_j/a₀ evaluated at that point,
from one uniform, with the resolution rule of Static Direct
(
CRN-R031). - Report values and bound crossings come from the same dense output; a bound crossing that comes first ends the step there.
Rates that do not read a variable are computed once per interval.
Independent variables (rules-model/0.4) are integrated once per prepared
run, by the same Dormand–Prince pair, step control and bound handling,
over [0, end] at the request’s rtol and atol, with their own error
norm. The accepted steps and their fourth-order dense output are kept, and
every replicate and worker reads the variables from them, so results stay
independent of threads. Per replicate, the method then integrates only
the dependent variables and Λ, reading the independent variables from the
dense output at each stage time; the error norm covers those components
only. A stop bound of an independent variable ends the shared solution, and
every replicate that reaches its time stops there (a tie with the
threshold goes to the stop, as above). If the shared solve fails (a
non-finite derivative, a step that underflows, or more attempted steps than
max_sampling_steps_per_replicate), it ends at the start of the failing
step, and every replicate that reaches that time fails with the solve’s
diagnostic (CRN-R030, or CRN-R041 for the step budget). The solve runs
in prepare (and again for every bind_parameters candidate); the step
budget bounds it.
The method lowers the model like the static methods, so it refuses models with
dynamic instances; it refuses ATP models (use thinning); and it also runs
models without continuous variables, as an exact jump process up to
rounding. It is approximate at its tolerances. Its sampler is
chacha8-u53/rules-approximate-hybrid-dopri54/1; rules-result/0.3 records
the request’s method, tolerances included. Integration steps, accepted or
rejected, count against max_sampling_steps_per_replicate like leap
iterations (CRN-R041), and a step below four rounding units of the time
fails the replicate (CRN-R030). Under run/1.0 the last step to the
horizon is exempt, since the horizon can lie that close to an event, and an
event whose wait is below the clock’s resolution happens at the same time
(the clock rule of Static Direct). Validation:
validation/hybrid/RESULTS.md.
Compiled event loops
crn.compile_loop builds the Static Direct event loop of one model and
parameter set into a separate program that compiled= then runs. The loop is
opt-in, and it needs a Rust toolchain. It gives byte-identical results to the
interpreter. The guide teaches when to use it in
chapter 5; the Rust side is in the
Rust API.
Where compiled= goes. A loop can be given in two places, and both run
the same program with the same results.
crn.ensemble(..., compiled=loop), orcrn.prepare(model, request, compiled=loop), attaches the loop to the prepared run. Preparation checks once that the loop was compiled for these model bytes and that the request selectsstatic_direct, and raisescrn.CrnErrorCRN-R020(at/modelor/method) otherwise, before anything runs. Everyrun.simulate()then uses the loop.run.simulate(compiled=loop)uses the loop for that call only, on a run prepared without one; the first such call makes the same checks. The same prepared run can then also run interpreted.
A run with an attached loop always runs compiled: simulate(callback=...)
raises ValueError, so prepare the request without compiled to watch
events. run.bind_parameters(...) returns a candidate without the loop,
which runs interpreted, since a loop serves only the parameter set it was
compiled for.
Requirements. Rust 1.85 or newer, the MSRV of the crates (install it with
rustup), and network access to crates.io: the program
depends on crn-craft at exactly the installed version. Offline, or with a
version that is not on crates.io (a wheel built from a clone), pass source=
a CRN-craft checkout of that version, or set CRN_CRAFT_SOURCE. cargo=
names another cargo executable.
Build time and cache. The first build compiles crn-craft and its
dependencies: about 40 s on the two-CPU host after the downloads, several
minutes on slower machines. compile_loop prints cargo’s progress and the
path of the build log to stderr (progress=False silences it). Builds are
cached in the user cache directory (~/.cache/crn-craft/rules-loops on
Linux; cache_dir= or CRN_CRAFT_CACHE_DIR choose another), keyed by the
loop’s fingerprint, the installed version, rustc -vV, the target and the
Rust flags. A cached call took 0.06 s. All builds share one Cargo target
directory (CARGO_TARGET_DIR if set), so a second model built in 3 s. The
cache takes about 160 MB; delete the directory to reclaim it. Loops cached by
release 0.6.0 are built again once on first use, with the same results, and
their entries stay in the cache until you delete it.
Limitations.
- Only
method="static_direct", with any options, and only the linear scan.crn.ensembleleaves the selector toauto, so for a model whoseautochoice is another selector, nameselector="linear"together withcompiled=(CRN-R020at/method/selectorotherwise). Other methods are refused withCRN-R020at/method. - The generator emits every model that
method="static_direct"runs: constant, vacancy and expression rates, string rates (propensityrules) andsum,distinct,maxandminobservables. It refuses, withCRN-R020at/methodand before cargo runs, models that only another method runs (continuous variables, ATP blocks, instances that change identity), and loops that would exceed 1 MiB of source, which densely coupled networks with many channels reach.crn.loop_source(model)returns the source, or that error, without cargo. - The loop is compiled for the exact model bytes.
crn.compile_loopbuilds for the documentcrn.ensembleruns (model/1.0), so the same dictionary orcrn.Modelworks for both calls.crn.rules.compile_loopbuilds for the bytes as given, whichcrn.rules.ensembleruns; a loop compiled for other bytes is refused withCRN-R020at/model. - Parameters are compiled in, so another parameter set needs another loop. A
loop passed for other model bytes, or for a
bind_parameterscandidate, is refused withCRN-R020at/model; candidates run interpreted. callbackandbatch_callbackare refused withValueError: the loop runs in its own process. Trackers and event logs work.- Threads, report times, stops, budgets,
wall_time_sandcancel_filework as interpreted. Ctrl-C stops the program and raisesKeyboardInterrupt. - On networks with many constant-rate channels the loop can be slower than the interpreter (details).
- Missing cargo, a failed build (
error.logis the build log) and a result that differs raisecrn.CompiledLoopError, whosereasonis"cargo_missing","build_failed"or"mismatch".
Confirming identity. Every compile_loop call, cached or not, runs short
requests through the program and the interpreter, with both waiting times,
both tracker policies and an event log, and returns the loop only if the
metadata and every record column are byte-identical. loop.verify(run) does
the same for your own request and returns the result. On a mismatch both
results are saved next to the build for inspection.
Speed. Measured from Python including the subprocess, on 12 November
2026, a compiled loop ran the three-class model about 2.1 times as fast as
interpreted Static Direct with its defaults. On a susceptible-infected-removed
model with 2,000 replicates (37.6 million events) the loop took 1.64 s
against 3.35 s with inverse waits (2.00 times) and 1.36 s against 2.97 s with
Ziggurat waits (2.18 times), medians of three on the two-CPU host
(validation/rules/compiled-loop-string-rates.json). Release 0.7.0 made
interpreted Static Direct faster (0.72 times the time on the three-class
workload). Cached
rates and dependency-aware projection refresh apply to the default path;
potentially overflowing report-only projections keep their eager checks. The
rules kernel review checklist has the
conditional Rust generator and its adoption gate.
Reproducible stochastic experiments
A protocol gives the time and conditions of an experiment. A count model
describes the reactions. Timed interventions and reaction completions use
the native count scheduler. Prepared projections and stationary laws run
on the native engine; the binomial-detection and fluorescence readouts of
crn_craft.likelihood need the optional crn-craft[likelihood]
dependency (SciPy).
Scheduled stochastic simulation
import crn_craft as crn
model = crn.Model("timed_birth")
model.add_species("X", 0)
model.add_parameter("birth", 2.0)
model.add_reaction(crn.mass_action("birth"), [], ["X"], name="arrival")
protocol = crn.Protocol(time_unit="hour")
protocol.at(3.0, parameters={"birth": 4.0}, partition={"X": 0.5})
run = crn.ensemble(
model, end=5, report_times=[0, 3, 5], protocol=protocol,
seed=123, replicates=20_000, threads=4,
)
result = run.simulate()
At hour three the daughter count is Poisson with mean 3. At hour five it is Poisson with mean 11. Reports are right-continuous. Completions due at a boundary precede external action groups. Equal-time action groups follow their order in the protocol. Each group reads its pre-group counts. Groups at time zero apply before the initial report. The stop predicate is tested after each group, and a stopped trajectory retains its counts. With no reaction possible, the trajectory waits for the next group.
The methods are linear static_direct and next_reaction for closed
attribute-free count models. Other methods, and a Static Direct selector
other than linear, are refused with CRN-R020 at /method. At each
boundary the engine updates the counts and switches to rate constants
that were compiled during preparation for every group that changes
parameters. Static Direct discards a wait that passes the boundary and
draws a new one under the new rates. Next Reaction draws fresh clocks for
all channels at every boundary. Both are exact because the exponential
waits are memoryless. A reaction drawn at exactly the time of a boundary
fires after it. Reports between boundaries draw no random numbers. Each
replicate keeps one random stream across all phases, so results do not
depend on threads or on the report grid.
Count actions include signed increments (change), absolute assignments
(set) and partitions. A partition independently retains each molecule
with the given probability. A group may hold at most one count operation
per species, and every operation reads the counts before the group.
Parameter values replace the current values until a later group changes
them. A parameter that sets an initial count cannot be changed. The
time_unit field is a label. The engine does not convert units: action
times, durations, the horizon and the model’s rates must use the same
unit.
A request is refused with CRN-R020 at /protocol/... for an unknown
species or parameter, conflicting operations on one species, a
probability outside [0, 1], or action times that decrease, are negative,
or lie after end. A protocol holds at most 4,096 action groups and
4,096 delays. A count change that would leave a species negative, or
above the count limit, fails the replicate with CRN-R030 at
/protocol/actions/i. The message names the group, its time, the species
and its count.
crn-craft.run/1.1 is a versioned request with required protocol. A
crn-craft.run/1.0 request with protocol is refused with CRN-R020, and
1.0 requests without it run as before. The native CLI supports its usual
check, run, --archive and verify commands. crn-craft.result/1.1
logs calendar events with kind, pending and cancelled. An unfiltered
event log stores changed counts before and after a deterministic event in
its participant fields. Report events and rule_events count
stochastic reaction events. Interventions and completions consume work
from the same replicate event budget. To migrate a 1.0 count request,
change its version and add protocol, then choose linear Static Direct
or Next Reaction.
Protocol runs have their own sampler identities:
chacha8-u53-ziggurat/rules-protocol-direct/1 (Static Direct with the
default Ziggurat waits), chacha8-u53/rules-protocol-direct/1 (inverse
waits) and chacha8-u53/rules-protocol-next-reaction/1. The Rust tests in
crates/crn-craft/tests/protocol.rs check exact laws for all three: a
rate change and a channel that is switched on, the moments across a
binomial division, and the fixed-delay laws below.
validation/check_paper_capabilities.py checks the example above against
its two Poisson laws.
Fixed-delay completion
Protocol.delay(reaction, duration, products=..., owner=...) adds a
fixed-time completion to a reaction. The named reaction still applies
its immediate stoichiometry at initiation. The duration is a positive
number in the run’s time unit. An optional owner is a busy count species
that starts at zero, and only that initiation reaction may create it,
one copy per firing. Busy copies are exchangeable. When a reaction, a
partition or a count action removes k busy copies, the engine cancels k
pending completions of that owner, chosen uniformly at random from the
replicate’s stream. An action that would increase a busy count fails the
replicate with CRN-R030. A completion that comes due consumes one busy
copy and creates the specified products. Pending completions are ordered
by due time, then by creation. At an exact tie, due completions run
first, then action groups in their declared order, then the report. The
queue holds at most max_pending entries (1 to 4,096, default 4,096). A
replicate that needs more fails with CRN-R030. Pending completions
survive parameter changes. prepare_fsp raises ValueError for a
protocol with delays, because a count state cannot represent the pending
history.
The delayed-reaction implementation follows the event-queue semantics
of the modified next-reaction method.
crates/crn-craft/tests/protocol.rs checks three laws for each sampler.
Products completed by time t from Poisson starts at rate r with delay τ
are Poisson with mean r max(0, t − τ). With owner loss at rate δ that
mean is multiplied by exp(−δτ). When a partition keeps one of two busy
owners, each owner is kept with probability 1/2.
The delayed feedback example compares the first power-spectrum peak and the autocorrelation at twice the delay with an independent delayed direct method written in Python. With 12 paths per sampler, the peaks were 0.15390 (native) and 0.12877 (independent) rad per time unit, within the 0.03 tolerance. Over six batches of 12 paths, the peak varied with a standard deviation of 0.0051 (native) and 0.0097 (independent). The tolerance is about ten frequency bins, so the check detects only large changes of the period. The batch means, 0.1487 and 0.1392, differ by 2.1 standard errors. This is inconclusive, and more paths would be needed to resolve it. The example is not run in CI.
For a paper specifying hourly degradation trials, model that discrete sequence separately from the continuous-time degradation hazard. Fixed replication-time example
Prepared probability laws
projection = crn.prepare_fsp(model, bounds={"X": 48}, protocol=protocol)
law = projection.solve(5, [0, 3, 5], tolerance=1e-12)
daughter = law.marginal("X", at=1)
continued = projection.solve(5, [5], initial=law.snapshots[1],
tolerance=1e-12)
The native engine lowers the model, evaluates the rates (including
count-dependent rates and stop conditions), enumerates the states,
assembles the sparse generator, applies interventions and propagates the
law by uniformization, by an implicit variable-order integrator
(solver="bdf") and by the exponential midpoint rule; it also solves
stationary laws. Sparse LU factorizations use the Rust library faer,
compiled into the extension. SciPy is used only by the binomial-detection
and Gaussian fluorescence readouts of crn_craft.likelihood
(count_probability with detection below 1, binned_probability with a
gain and noise). Install it with the likelihood extra
(pip install "crn-craft[likelihood]"); those two readouts raise
ModuleNotFoundError naming the extra without it. The existing Model.fsp (the fsp method of
crn-craft.run/1.0) is a separate native solver. Use it for one fixed
model from one initial state. Use prepare_fsp for protocols, prescribed
signals, initial mixtures, checkpoints or many parameter vectors on one
graph.
Prepare with initial={(0,): 0.25, (1,): 0.75} to seed a distribution.
The labels are count tuples in the order of projection.species. The
probabilities must be finite, nonnegative and sum to one within 1e-12.
Preparation enumerates every transition whose reactants are present,
whatever its rate, and every state an action can reach. So a rule with
zero rate at preparation can be switched on later. solve(parameters=...)
reuses this graph and only re-evaluates the rates. A binding that changes
the topology or the initial counts raises ValueError; prepare a new
projection for new bounds or initial support. A prepared projection
keeps no per-solve state, so threads can share it. It cannot be pickled;
prepare one per process.
An action maps the retained law through its count kernel, one species at
a time; a partition is binomial. Escaped probability stays in the
absorbing sink; an action can add to it but never returns it. Previously stopped
probability carries forward. A snapshot from law.snapshots continues a
solve under the same parameters and signals. To change parameters at a
time point, use a protocol action.
Pass signals={"arrival": crn.Signal.table(times, rates)} to replace
the count-independent rate constant of a named rule by a prescribed time
series in the rule’s rate units and the model’s time unit. Tables use
linear interpolation or an explicit right-continuous step curve and hold
their end values outside the table. Step times split the integration;
the knots of a linear table do not. Signal(function, change_times=...)
accepts a Python rate function; list its discontinuities in
change_times. Python callables are supplied by the caller when
rerunning the experiment. Both forced-segment solvers evaluate tables
natively and call a Python function from the native step loop; an interval is
integrated with the value just before its end, so a discontinuity at a
boundary is approached from the left and the next interval starts with
the right-continuous value.
Constant segments use uniformization with a truncated Poisson series:
an interval of length t splits into ceil(λt/16) pieces (λ the largest
exit rate), and each piece stops the series once the omitted Poisson
weight is at most its share of the tolerance. Smoothly forced segments
use the implicit integrator (solver="bdf", the default) or an adaptive
exponential midpoint rule (solver="midpoint").
The implicit integrator uses the numerical differentiation formulas
(NDF) of orders 1 to 5 of Shampine and Reichelt (“The MATLAB ODE Suite”,
1997) in backward-difference form, with a quasi-constant step size. Each
step’s local error estimate is held to rtol = tolerance and
atol = 1e-4 · tolerance in the root-mean-square norm. Step size and
order change only after k + 1 equal steps of order k; steps are at
most max_step, land exactly on segment ends, and reports inside a
segment come from the interpolating polynomial of the last step. The
problem is linear, so the iteration matrix I − c Q(t) is exact when it
is factorized at the step’s own time: it is factorized when the step
size or order changes, and during a run of equal steps the factorization
of an earlier time is reused with up to four simplified Newton iterations
before refactorizing. One symbolic analysis of the matrix pattern serves
every factorization of a generator. Before the first factorization the
analysis bounds the memory of the factorization and its workspace; above
max_factor_bytes (default 2 GiB) the solve stops with CRN-E070. The
joint nuclear and cytoplasmic RNA projection of tutorial O3 (35,496
states) needs a bound of about 0.26 GB; 99,856 states need about 1.1 GB.
The midpoint rule compares one step
exp(h Q(t + h/2)) with two half steps and accepts when their L1 gap is
at most tolerance · h / (end − start); each matrix exponential action
is a uniformization of the frozen generator whose omitted Poisson weight
is at most 1/1024 of that step goal. result.solver names the method
used. Each snapshot reports the absorbing sink, the Poisson series-tail
bound, the mass defect and the minimum probability. The series-tail bound
covers the uniformization of constant segments only. It excludes rounding
and adds nothing for BDF or midpoint segments, which report no
integration error estimate (the midpoint rule’s truncation shows in the
mass defect). BDF can return slightly negative probabilities; check
minimum_probability. The midpoint rule stops with an error when its
tolerance is below the rounding level of its step estimate. max_work
counts series terms, intervention outcomes, matrix exponential actions
and, for BDF, each product of the generator with a vector, each solve
and each numeric factorization. Check tolerance refinement on the
selected observable for a smooth signal. See the
RNA fit replay.
Use stationary_fsp(model, bounds) for one finite closed communicating
class or specify class_state. With a return_state, escaped rates
redirect to a retained state. The native engine enumerates the states,
builds the generator, finds the closed communicating classes (an
iterative strongly-connected-components pass; a class is closed when no
transition leaves it), anchors the largest state of the class (or the
return state) at probability 1 and solves the balance equations of the
others with one sparse LU factorization, bounded by max_factor_bytes
like the BDF. The law is clipped at zero and normalized; the result
reports its L1 residual, which must be at most 1e-9 times the largest
exit rate (at least 1). Successive enlargements
compare marginal CDFs and outward flux. These diagnostics are empirical
on unbounded networks. Certified error bounds require additional
recurrence evidence. result.method separates the exact finite law
(finite-closed-class) from the redirected approximation
(stationary-fsp-return-state).
Stationary FSP method
Retained state sets
prepare_fsp(model, bounds, retained=states) restricts a projection to a
finite set of count tuples inside the bounds, for example the hyperbolic
cut (x - 4)(y - 4) < 2500 of a toggle switch. Enumeration starts from the
initial law and keeps only retained states; every transition to another
state flows to the absorbing sink, so the sink probability measures the
truncation. The initial law must lie in the set. Duplicates count once; an
empty set, negative counts, tuples of another length, tuples outside the
bounds and more than max_states tuples raise ValueError. Scheduled
count interventions are refused with a retained set. Without retained
the states, their order and the prepared id are those of the box.
Probability sensitivities and Fisher information
from crn_craft.sensitivities import fisher_information, forward_sensitivities
graph = crn.prepare_fsp(model, {"on": 1, "off": 1, "rna": 215})
segments = [(60.0, {"kon": 0.05, "koff": 0.15}),
(120.0, {"kon": 0.10, "koff": 0.15})]
result = forward_sensitivities(graph, segments, [30.0, 60.0, 120.0],
["koff", "kon"], logarithmic=True,
tolerance=1e-9)
bins, p, g = result.observed(["rna"])
matrix, excluded = fisher_information(p, g, cells=1000)
forward_sensitivities integrates the law p' = Q p and its parameter
derivatives s_j' = Q s_j + (dQ/dθ_j) p on the prepared graph through
piecewise-constant segments (end_time, bindings). The law and the
derivatives pass continuously across segment ends. dQ/dθ_j is the
centered difference of the generator at θ_j (1 ± 10⁻⁴) (or
θ_j e^{±10⁻⁴} with logarithmic=True, which differentiates in
natural-log coordinates): exact up to roundoff for rates linear in the
parameter and second-order accurate for any other rate expression, such
as a Hill function. The augmented system is integrated by the implicit
integrator above, with the derivatives in the error norm (rtol = tolerance, atol = 10⁻⁴ tolerance); the iteration matrix is block lower
triangular with identical diagonal blocks, so one sparse factorization of
I − c Q serves the law and every direction. The initial law is the one
given to prepare_fsp unless initial replaces it; it does not depend on
the parameters unless initial_derivatives says so. The last column of
probabilities and derivatives is the sink: each row of the law sums to
one and each derivative row to zero, sink included; a loss above 1e-7
raises ValueError. At most 16 directions; signals, stop states and count
interventions are outside this interface. max_work counts augmented
solves.
result.observed(axes) sums states and derivatives into the bins of the
measured species before any score: a Fisher matrix of hidden states
overstates what a measurement holds. fisher_information(p, g, cells)
returns Σ_t n_t Σ_b g gᵀ / p over bins with p > 0, exactly symmetric
and positive semidefinite up to roundoff, and the probability of the
excluded bins per time. A bin with p = 0 is unreachable or has
underflowed and carries no information; probability_floor reproduces a
published convention that drops rare bins. The run of chapter C8 of the
optimization tutorials checks the derivatives against a closed form and
centered differences and reproduces published Fisher matrices.
Verification. validation/check_projection_native.py compares the
native engine with an independent Python and SciPy implementation
(validation/reference_projection.py, not shipped, with SciPy’s BDF and
sparse LU) on a declared case set: identical states and prepared ids,
laws within the solve tolerance (twice it for forced segments, including
BDF against SciPy’s BDF), identical errors on budget and input failures,
and stationary laws within 1e-10 on chains with two closed classes and
transient states, an absorbing state, a nearly decomposable stiff block
structure and redirected expansions. Forced laws are also compared with
closed-form Poisson laws. It also checks the binomial and Poisson-tail kernels against
SciPy and, where SciPy loses accuracy for large counts, against a
60-digit evaluation. It also compares forward sensitivities with a closed
form and with centered differences of uniformization solves through a
parameter switch, and checks retained sets against the ordinary box.
Spatial models
SpatialModel(name, volumes) expands named, well-mixed compartments to an
ordinary count model. volumes maps region IDs (letters, digits and _)
to positive, fixed volumes. Each species gets one count per region,
labeled <species>_<region>; label(species, region) returns that name
and profile(run.paths, species) selects the region columns in region
order. Ensemble means of a profile are the means of those columns. There
is no separate helper for conserved totals; sum the region columns.
add_species(name, initial, reservoirs=())takes one count for every region or a mapping by region.local(name, rate, reactants, products, combinatorial=False, regions=None)adds one reaction per region. A string rate may name the local species as{X}and the region volume as{volume}. Volumes are not applied automatically: write a second-order rate constant as, for example,"k / {volume}". A local reaction may not change a reservoir species, so passregionsto leave reservoir regions out.transport(species, origin, target, rate)adds a directed hop atrateper copy and day. Volumes do not enter the rate. For detailed balance between unequal volumes choose rates withV_i * k_ij = V_j * k_ji.diffusion(species, first, second, diffusivity, spacing)adds both directions atdiffusivity / spacing**2per copy. It requires equal volumes.
A region without an edge is a reflecting end. A reservoir is a species
whose region count never changes. A hop out of it fires at
rate * initial count and adds one copy to the target. A hop into it
removes the copy from the origin; the copy is absorbed.
spatial_turnover(initial, end=, target=, feedback=, mutant_weight=, death=, hop=, seed=0, mutation=0.0, fixed_left=False, labels=False, max_events=3_000_000_000) samples the endpoint of one exact path of the
two-genotype chain of the spatial spread study.
initial lists (wild, mutant) counts by region, at most 4,096 regions.
Every copy is born at max(0, death + feedback * (target - W - mutant_weight * M)),
dies at death and hops to each nearest neighbor at hop per day. With
mutation > 0 a birth makes a new mutant clone with that probability.
With labels=True the result lists the clone ID of every mutant copy by
region: 0 for initial mutants, then 1, 2, … in order of creation. Labels
do not change the hazards. With fixed_left=True region 0 is a reservoir
with the same semantics as above. The result holds wild, mutant,
labels, events, mutations and the sampler identity
chacha8-u53-ziggurat/spatial-turnover/2. Seed s uses the same ChaCha8
stream as replicate 0 of a generic run with root seed s; do not use
equal seeds for a comparison between the two. The sampler raises CrnError
with CRN-R030 for invalid input, CRN-R031 for a positive weight below
16 × 2⁻⁵³ of its total (the resolution of the selection draw), CRN-R040
when the event budget is reached, and CRN-R044 when the run is cancelled.
The sampler keeps the region weights in a binary sum tree that recomputes
each parent from its children, so no running total drifts. It updates the
event’s region and the destination of a hop. Against the generic engine on
a four-region chain with the clamp and the reservoir, five count CDFs over
20,000 paths each differed by at most 0.0099, against a simultaneous 99%
bound of 0.0276. On the 500-region chain it took about 150 ns per event,
4 to 7 times less than Next Reaction. Use it through
study.py --source-chain --wave-sampler local; fiber i uses seed
seed + 1000 + i and its own checkpoint.
Observation models
crn_craft.likelihood maps states to counts, sums, joint measurements
and intervals. It implements binomial detection and binned Gaussian
fluorescence. Fluorescence bins integrate the Gaussian over the bin
edges. histogram_score returns the negative log likelihood in nats per
cell and the contribution of each group. Empty bins contribute zero. An
occupied bin with zero retained probability makes the score infinite
and is counted in impossible_bins. The optimistic score adds the
missing probability of a group to each occupied bin. mean_score takes
a symmetric positive definite covariance. The RNA example binds
candidates to the prepared projection and supplies the score to fcmaes.
The example’s legacy_tail argument reproduces the guide’s coarse
overflow convention.
Published experiment files
Use crn.read_experiment(path, convention="stochastic_count_propensity")
and then preflight() or run(). path is a COMBINE/OMEX archive
(.omex or .zip) or a SED-ML file whose models lie in its folder. The
wheel also installs
crn-craft-experiment EXPERIMENT --convention stochastic_count_propensity,
with --check (preflight only), --seed, --replicates, --threads and
--archive DIRECTORY. DIRECTORY must not exist; it receives one sealed
native run per task, named by the task ID, and experiment.json with the
source member hashes, parameter changes, effective rates, events and
output mappings; preflight() returns the same without simulating. Task i
in document order uses seed seed + i. A refused input raises
ImportFailure (CRN-E090); the command prints CRN-E090: message and
exits with status 2.
| Format | Supported subset |
|---|---|
| SBML L3V1 and L3V2 Core | Fixed compartments of any size and dimension; species with item amount units, as amounts or as concentrations in a sized compartment; an explicit time unit; acyclic scalar parameter assignment rules, recalculated after each edit; time triggers time >= t with a literal t, instantaneous assignments to non-constant independent parameters or species counts, literal priorities |
| SED-ML L1V3 and L1V4 | Local SBML models and #model references; changeAttribute of a parameter value given as the absolute path /sbml/model/listOfParameters/parameter[@id='…']/@value (namespace prefixes allowed and not resolved); uniform time courses with Gillespie direct (KISAO:0000029) and no algorithm parameters; repeated tasks with one subtask, one uniform range and resetModel="true", which add replicates; data generators that select one time or species variable; reports and 2D plots |
| COMBINE/OMEX | One master SED-ML document from the manifest; members read from the archive, never extracted |
Rate convention. A kinetic law is read as the jump hazard in items per
model time unit, with species amounts in items and concentrations as items
per compartment size. A law must equal c × Π C(n, k) for the reactants of
its reaction, the convention of every native rate, so k*A*(A - 1) for
2 A → … is accepted with c = 2k, and k*A*A is refused. The explicit
split_signed_mass_action convention also accepts a law
u × Π C(n_reactant, k) − v × Π C(n_product, k) with u, v ≥ 0, found by
exact rational arithmetic; it becomes a forward and a reverse jump, both
nonnegative in every state. This handles the two signed promoter-binding
laws in the published oscillator archive.
Every law of that model is multiplied by the size of compartment cell
(4.18879), so its rates are those of the paper times 4.18879 per archive
time unit. Use the strict count convention for ordinary irreversible laws.
Grid and events. numberOfPoints (L1V3) or numberOfSteps (L1V4)
counts intervals: 400 gives 401 report times from outputStartTime to
outputEndTime. The model starts at initialTime. Reports at an event
time show the state after the event. An event whose trigger is true at
time 0 with initialValue="true" never fires; with initialValue="false"
it fires at time 0. Events at the same time need distinct priorities and
run from the highest; their assignments read the state before that time
unless useValuesFromTriggerTime="false". State triggers, delays,
assignments that read species, and events before initialTime are
refused.
Input safety and limits. Every XML document the package reads (SED-ML,
SBML, the archive manifest, and the SBML of crn.importers.import_sbml)
goes through one guard. It refuses a document that is not bytes, is larger
than 16 MiB, contains NUL bytes (UTF-16 and UTF-32, with or without a byte
order mark), declares an encoding other than UTF-8, is not valid UTF-8,
nests elements deeper than 256 levels or is not well-formed XML. It also
refuses <!DOCTYPE and <!ENTITY in any letter case anywhere in the
bytes, including inside a comment or a CDATA section, so an internal
subset, a parameter entity, an external entity and an entity-expansion
document are never parsed, and no entity is expanded or external resource
opened. A byte order mark, processing instructions, comments and CDATA are
otherwise read as XML. Model sources must be relative paths inside the
archive or the SED-ML folder; .., absolute paths, URLs, URNs and links
are refused. Limits: 16 MiB per XML document, 64 MiB per archive and for
its declared uncompressed members, 256 members, 64 species, 4,096
parameters and compartments, 1,024 reactions, 256 events, and 16,777,216
returned values (paths × report times × species) per run.
Not supported: SBML Level 2 (the official L1V3_repeated-stochastic-runs.omex
is refused), local functions, algebraic and rate rules, other KiSAO
methods, seeds or other algorithm parameters, data generator expressions,
setValue in repeated tasks, and report labels (the series are keyed by
data set ID). Unsupported constructs and unresolved units produce a
diagnostic during translation. SBML · SED-ML
Verification. validation/check_paper_capabilities.py runs offline in
CI: a two-compartment pulse with a non-unit volume against the same native
protocol (32 paths, identical counts), the pair hazard (survival 0.3535 at
4,000 paths against e^−1 = 0.3679), derived rates after an edit, event
timing, and 33 refused inputs. CI also downloads the oscillator archive and
SBML Test Suite stochastic case 00001 by commit and checks their SHA-256.
Both oscillator tasks give 401 report times; the decay rate of R is
0.837758 and 0.209440 per archive time unit. validation/check_public_experiments.py
compares the counts of A and R at times 0.5, 1 and 2 with a separately
written direct SSA of the same reactions: at 512 paths per task the largest
of 12 two-sample CDF gaps was 0.066 against a simultaneous bound of 0.123,
which detects an edit that is not applied but not a 10% change of one rate.
With --vilar-paths 8704 (about 3 minutes on one core) the largest gap was
0.023 against 0.030. In a review run with a reference SSA changed on
purpose, 512 paths missed a 10% change of the R decay rate or of the
promoter unbinding rate (largest gaps 0.086 and 0.057), and 8,704 paths
caught both (0.062 and 0.038). Case 00001 at 5,000 paths and 50
report times gave |Z| ≤ 1.71 and |Y| ≤ 2.73, within the suite’s ranges of 3
and 5. These runs exercise the two 2-unit tasks of the deposited
experiment, not the paper’s long oscillation.
Python API
The public names of crn_craft 0.10.1: everything in crn_craft.__all__, the methods of Model, PreparedEnsemble, Result, FspResult and CompiledLoop, and the modules crn_craft.importers, crn_craft.likelihood and crn_craft.sensitivities. The page is generated from the signatures and docstrings of the installed package, so it lists what the package does. Examples are in the guide; this page has none.
Import the package as import crn_craft as crn. crn_craft.rules is the API of release 0.6.0 under its old name. It has the same names with the defaults and document versions of 0.6.0; the migration page lists the differences. Code written for it keeps running.
crn_craft.rules.ensemble takes the arguments of ensemble below. Its quantiles defaults to None (no quantiles), and an absent selector means the linear scan.
Contents: Models, Running, Experiments and probability laws, Likelihoods and sensitivities, Results, Files and archives, Analysis and import/export, Compiled loops.
Models
Build a model in Python, or take a packaged one. Model writes crn-craft.model/1.0. The language of the document is in the model reference; chapter 2 of the guide teaches the builder, and chapter 12 species with attributes.
Model
class Model(name='model')
A model built call by call, written as crn-craft.model/1.0.
| Argument | Default | Meaning |
|---|---|---|
name | 'model' | The model’s name. |
The builder of crn_craft.rules.Model (the same methods: add_species,
add_initial, add_parameter, add_reaction, add_observable,
set_initial, set_stop, add_ode, to_dict, to_json,
from_dict, fsp, analyze, to_gillespy2), whose documents
are always crn-craft.model/1.0. Species are plain counts, or carry
attributes (add_species(name, attributes=[...])), whose molecules
reactions match with pattern and create with copy and
new. add_reaction accepts any number of reactant molecules
of attribute-free species; ["A", "A", "A"] is a third-order
reaction.
Model.add_species
Model.add_species(name, initial=0, attributes=None)
Declare species with initial counts (default 0), or with attributes.
| Argument | Default | Meaning |
|---|---|---|
name | required | A species name, or a mapping from names to initial counts. |
initial | 0 | Initial count. Not allowed with a mapping; 0 for a species with attributes. |
attributes | None | Attribute names, for example ["clone"], or None for a plain count. |
add_species("S", 999) declares one; add_species({"S": 999, "I": 1}) declares every entry of a mapping, in its order, as one
call each would. A mapping takes no other argument (TypeError).
If an entry is invalid, nothing is declared. A species that a
reaction already introduced keeps its position and takes the count.
attributes, a list of attribute names, declares a species whose
molecules carry numeric attributes, for example
add_species("mtDNA", attributes=["clone"]): each attribute
vector is an instance with its own count, and the run creates and
removes instances. Its molecules at time 0 come from
add_initial, so initial must stay 0, and each such
species is declared in its own call (a mapping with attributes
raises TypeError). Declare it before the reactions that use it.
Every species, with attributes or not, has an observable under its
own name: its total count of molecules.
Model.add_initial
Model.add_initial(name, count, /, **attributes)
Add count molecules of species name at time 0.
| Argument | Default | Meaning |
|---|---|---|
name | required | A declared species. |
count | required | A nonnegative integer, or a parameter expression for a species with attributes. |
**attributes | none | Every attribute of the species, as a number or a parameter expression. |
For a species with attributes every attribute is a keyword, for
example add_initial("mtDNA", 1000, clone=0): the molecules of one
instance. Values are numbers or parameter expressions, and count
is a nonnegative integer or a parameter expression such as "K".
Call it once per attribute vector; a second call with the same
values adds to the count. For a species without attributes it adds
count, an integer, to the initial count.
Model.add_parameter
Model.add_parameter(name, value=<required>)
Declare parameters that string rates may read.
| Argument | Default | Meaning |
|---|---|---|
name | required | A parameter name, or a mapping from names to values. |
value | required | The value. Not allowed with a mapping. |
add_parameter("gamma", 0.01) declares one;
add_parameter({"gamma": 0.01, "beta": 2e-4}) declares every
entry of a mapping, in its order, as one call each would. A mapping
takes no other argument (TypeError). If an entry is invalid,
nothing is declared. add_parameters is the same method.
Model.add_parameters
Model.add_parameters(name, value=<required>)
Declare parameters that string rates may read.
| Argument | Default | Meaning |
|---|---|---|
name | required | A parameter name, or a mapping from names to values. |
value | required | The value. Not allowed with a mapping. |
add_parameter("gamma", 0.01) declares one;
add_parameter({"gamma": 0.01, "beta": 2e-4}) declares every
entry of a mapping, in its order, as one call each would. A mapping
takes no other argument (TypeError). If an entry is invalid,
nothing is declared. add_parameters is the same method.
Model.add_reaction
Model.add_reaction(rate, reactants, products, name=None)
Add a reaction reactants -> products.
| Argument | Default | Meaning |
|---|---|---|
rate | required | A number (a mass-action constant), mass_action(expression) (the same, as an expression) or a string (the whole propensity). |
reactants | required | Species names, repeated for multiplicity: ["A", "A"]; pattern(...) or pattern dictionaries. |
products | required | Species names, repeated for multiplicity; copy(...), new(...) or product dictionaries. |
name | None | The rule’s name. Default r<index>. |
rate is a number (a mass-action constant k: the reaction fires
at k times the number of distinct combinations of reactant
molecules, so ["A", "A"] fires at k·A(A−1)/2), a string (the
whole propensity) or mass_action (an expression that a
reaction multiplies by the number of combinations, like a number).
Species are lists of names, repeated for multiplicity, for example
["A", "A"]. Three or more reactant molecules, such as
["A", "A", "A"] or ["A", "A", "B"], are written with the
pattern field count of crn-craft.model/1.0 (a numeric k
fires at k·C(A, 2)·B for ["A", "A", "B"]; a string propensity
applies while each species has its count). Species not yet declared
are declared with count 0, as in rebop. name defaults to
r<index>.
For species with attributes, a reactant is a species name (any
molecule; the first is labeled x, the second y) or a
pattern with a where condition or factor; a product
is copy (copy("x") keeps the attributes of reactant
x) or new (every attribute given), never a bare name.
The pattern and product dictionaries of the model document are
accepted too. A reaction with where or factor takes a number
or mass_action as its rate. A plain string stays the whole
propensity: for a species with attributes the reaction fires at that
rate and takes a molecule uniformly, whatever its attributes, and
only the tree method (method=None) runs it unless the species
has a single instance. Reactions over species with attributes take
at most two reactant molecules.
pattern
pattern(species, where=None, factor=None, label=None)
A reactant of add_reaction: the molecules of species that match.
| Argument | Default | Meaning |
|---|---|---|
species | required | A species name. |
where | None | A condition over parameters and the molecule’s attributes, or None. |
factor | None | A weight per molecule (a number or an expression), or None for 1. |
label | None | The molecule’s label; None means x for the first reactant and y for the second. |
where is a condition over parameters and the molecule’s attributes,
for example "x.clone > 0"; factor is a weight h ≥ 0 per
molecule over the same names (a number or an expression), so the
reaction fires at its rate times the sum of h over the matching
molecules. label names the molecule in where, factor,
product attributes and copy; it defaults to x for the first
reactant and y for the second, so a condition on the second
reactant reads y.clone (or give label). A plain species name is
the pattern without where and factor. A reaction with a
where or factor takes a rate per combination of molecules, a
number or mass_action, not a whole-propensity string. The
model document writes it as {"label", "type", "where", "factor"};
such a dictionary is accepted as a reactant too.
copy
copy(label, /, **attributes)
A product of add_reaction: a copy of the reactant labeled label.
| Argument | Default | Meaning |
|---|---|---|
label | required | The label of the reactant to copy. |
**attributes | none | Attributes to override, as numbers or expressions. |
The product has the reactant’s species and attribute values, except the
attributes given as keywords, which it overrides: for example
copy("x", size="x.size + 1"). Values are numbers or expressions over
parameters, the reactants’ attributes (x.clone) and random draws
(new_id(), bernoulli(p), choice(p, a, b), uniform(a, b),
normal(m, s)). Reactants are consumed, so ["mtDNA"] -> [copy("x"), copy("x")] is a replication that keeps the clone (one
molecule more), and [copy("x")] alone gives the molecule back. The
model document writes {"type": ..., "copy": label, "attributes": {...}}; such a dictionary is accepted as a product too.
new
new(species, /, **attributes)
A product of add_reaction: a molecule of species with the given
attributes.
| Argument | Default | Meaning |
|---|---|---|
species | required | A species name. |
**attributes | none | Every attribute of the species, as numbers or expressions. |
Every attribute of the species is given as a keyword; values are numbers
or expressions over parameters, the reactants’ attributes and random
draws, for example new("mtDNA", clone="new_id()"), which founds a
new clone, or new("Cluster", size="x.size + y.size"). A species
without attributes takes none: new("A") is the same as "A". The
model document writes {"type": species, "attributes": {...}}; such a
dictionary is accepted as a product too.
mass_action
mass_action(expression)
A rate for add_reaction: expression per combination of molecules.
| Argument | Default | Meaning |
|---|---|---|
expression | required | An expression over parameters and observables, or a number. |
The reaction fires at the expression’s value g times the number of
distinct combinations of reactant molecules, as a numeric rate does: one
reactant x of a species with N molecules fires at g·N, and with a
pattern at g times the sum of factor over the matching
molecules. The expression reads parameters and observables, for example
mass_action("r * max(0, K - N) / N"), and is written as the rule’s
rate. A plain string rate is different: it is the reaction’s whole
propensity (the rule’s propensity), and a firing then takes
reactant molecules uniformly. For one reactant without where or
factor the two describe the same process: mass_action("delta")
and "delta * N" (with N the count) on ["mtDNA"] both fire at
δN and take a molecule uniformly. A whole propensity cannot be combined
with where or factor, and the static methods run it only over a
species with a single instance, so a per-molecule rate on a species
with attributes is mass_action. A number is accepted too and
means what it means as a rate.
Model.add_observable
Model.add_observable(
name,
species,
where=None,
weight=None,
reduce='sum',
label=None,
)
Declare an observable: a number reduced from the molecules of species.
| Argument | Default | Meaning |
|---|---|---|
name | required | The observable’s name; it shares a namespace with parameters and species. |
species | required | A declared species. |
where | None | A condition over parameters and the instance’s attributes, or None for every instance. |
weight | None | A number or an expression per instance; None means 1. |
reduce | 'sum' | "sum", "distinct", "max", "min" or "max_count". |
label | None | The instance’s name in where and weight; None means x. |
Over the present instances of species that satisfy where (a
condition over parameters and the instance’s attributes, for example
"x.clone > 0"), with weight per instance (a number or an
expression over the same names, default 1), reduce gives:
"sum"(default): the sum of weight × count, so withoutweightthe number of matching molecules;"distinct": the sum of the weights, each instance once, so withoutweightthe number of distinct matching instances (for example clones);"max","min": the largest or smallest weight, 0 when no instance matches;"max_count": the largest copy number among the matching instances, times the weight, 0 when none matches (for example the size of the largest clone); it exists only incrn-craft.model/1.0.
A model with an observable of this call is written as
crn-craft.model/1.0, also by crn_craft.rules.Model.
label names the instance in where and weight (default
x). Rates (strings and mass_action), the stop condition
and trackers read observables by name, and results have a column for
each. The name shares one namespace with parameters, species and
continuous variables; every species already has an observable under
its own name, its count.
Model.set_initial
Model.set_initial(counts=None, /, **kwargs)
Set initial counts of declared species, from a mapping or keywords.
| Argument | Default | Meaning |
|---|---|---|
counts | None | A mapping from species names to counts. |
**kwargs | none | The same, as keywords: set_initial(S=990, I=10). |
model.set_initial({"S": 990, "I": 10}) and
model.set_initial(S=990, I=10) are equivalent. A species with
attributes takes its molecules from add_initial instead.
Model.set_stop
Model.set_stop(condition)
Set the stop condition, or remove it with None.
| Argument | Default | Meaning |
|---|---|---|
condition | required | An expression over parameters and species counts, or None to remove the stop. |
condition is an expression over parameters and species counts,
for example "I == 0" or "N > 0 && mutants >= 0.9 * N". Once
it is true (it is checked at time 0 and after every event), a
replicate keeps its state to the end of the report grid and is
recorded as "stopped", with its stop_time. It cannot read
continuous variables; a bound of add_ode stops on those.
Model.add_ode
Model.add_ode(
name,
initial,
derivative,
independent=False,
lower_bound=None,
on_bound='stop',
)
Declare a continuous variable dx/dt = derivative between events.
| Argument | Default | Meaning |
|---|---|---|
name | required | The variable’s name. |
initial | required | A number or a parameter expression. |
derivative | required | An expression over parameters, species counts and continuous variables. |
independent (keyword only) | False | True if initial and derivative read only parameters and other independent variables. |
lower_bound (keyword only) | None | A number or a parameter expression, or None. |
on_bound (keyword only) | 'stop' | "stop" ends the replicate at the bound, "clamp" holds the variable there. |
initial and lower_bound are numbers or parameter expressions;
derivative is an expression over parameters, species counts and
continuous variables. String rates may read the variable. With a
lower_bound, on_bound is "stop" (end the replicate when
the variable reaches the bound) or "clamp" (hold it there). Run
such a model with method="hybrid".
independent=True declares that initial and derivative
read only parameters and other independent variables, never species
counts, so the ODE can be solved once for the whole run instead of
per replicate. It writes "independent": true on the variable and
makes to_dict write crn-craft.rules-model/0.4; the engine
refuses an independent variable that reads anything else. Without
independent variables the document is rules-model/0.3, as before.
add_ODE is the same method.
Model.add_ODE
Model.add_ODE(
name,
initial,
derivative,
independent=False,
lower_bound=None,
on_bound='stop',
)
Declare a continuous variable dx/dt = derivative between events.
| Argument | Default | Meaning |
|---|---|---|
name | required | The variable’s name. |
initial | required | A number or a parameter expression. |
derivative | required | An expression over parameters, species counts and continuous variables. |
independent (keyword only) | False | True if initial and derivative read only parameters and other independent variables. |
lower_bound (keyword only) | None | A number or a parameter expression, or None. |
on_bound (keyword only) | 'stop' | "stop" ends the replicate at the bound, "clamp" holds the variable there. |
initial and lower_bound are numbers or parameter expressions;
derivative is an expression over parameters, species counts and
continuous variables. String rates may read the variable. With a
lower_bound, on_bound is "stop" (end the replicate when
the variable reaches the bound) or "clamp" (hold it there). Run
such a model with method="hybrid".
independent=True declares that initial and derivative
read only parameters and other independent variables, never species
counts, so the ODE can be solved once for the whole run instead of
per replicate. It writes "independent": true on the variable and
makes to_dict write crn-craft.rules-model/0.4; the engine
refuses an independent variable that reads anything else. Without
independent variables the document is rules-model/0.3, as before.
add_ODE is the same method.
Model.add_continuous
Model.add_continuous(
name,
initial,
derivative,
lower_bound=None,
on_bound='stop',
)
Deprecated since 0.5.0: use add_ode, which takes the same
arguments and independent=. Writes the same document as before.
| Argument | Default | Meaning |
|---|---|---|
name | required | The variable’s name. |
initial | required | A number or a parameter expression. |
derivative | required | An expression over parameters, species counts and continuous variables. |
lower_bound (keyword only) | None | A number or a parameter expression, or None. |
on_bound (keyword only) | 'stop' | "stop" ends the replicate at the bound, "clamp" holds the variable there. |
Model.from_dict
Model.from_dict(document)
A model of a complete model document.
| Argument | Default | Meaning |
|---|---|---|
document | required | A model document: crn-craft.model/1.0, a rules-model or a network model/0.1. |
document is a dictionary, JSON text or bytes: any rules-model
version, crn-craft.model/1.0 or a network crn-craft.model/0.1,
which is converted first (crn_craft.convert). The engine
checks it (CrnError with its diagnostics if invalid).
to_dict returns the document as given, key order included,
so its hash is that of the document; crn_craft.Model.from_dict
writes it as crn-craft.model/1.0, changing only the schema
string of a rules-model.
A document the builder could have written stays editable: the
add_* and set_* methods work, and after the first edit
to_dict writes the builder’s document (explicit default values
such as "attributes": [] are then left out, and the entries of
initial and observables are grouped by species, which changes
the bytes but not the meaning). That is a rules-model/0.3, 0.4 or
model/1.0 document (for crn_craft.Model also rules-model/0.1 and
0.2 without an ATP block) whose types, initial entries and
observables have the fields of add_species,
add_initial and add_observable, with one numeric
initial count per species without attributes; every converted
network model, the packaged examples and documents that
to_dict wrote are such documents. A species whose count
observable (an observable named after it, over all its molecules) is
missing in the document keeps it missing. Any other document (an
ATP block, two initial entries of one species without attributes,
…) is kept whole and cannot be edited: those methods raise
ValueError; edit the dictionary and call from_dict again.
Model.to_dict
Model.to_dict()
Return the document as a new dictionary.
It is rules-model/0.3, or rules-model/0.4 if a continuous variable
is independent (see add_ode), or crn-craft.model/1.0 if
a reaction takes three or more molecules or a call of release 0.8.0
(a species with attributes, add_observable, pattern,
copy, new) changed the model; a rules-model document
of from_dict keeps its version unless such a call edits it.
crn_craft.Model writes
crn-craft.model/1.0 always. A model from from_dict
returns its document until it is edited.
Model.to_json
Model.to_json(*, indent=2)
Return the document as JSON text with a trailing newline.
| Argument | Default | Meaning |
|---|---|---|
indent (keyword only) | 2 | JSON indentation. |
Model.name
Model.name
Read-only property.
The model’s name.
Model.species
Model.species
Read-only property.
Species (type) names in declaration order.
Model.parameters
Model.parameters
Read-only property.
A copy of the parameter values by name.
Model.reaction_names
Model.reaction_names
Read-only property.
Reaction (rule) names in declaration order.
load_example
load_example(name)
One of the packaged example models as a Model.
| Argument | Default | Meaning |
|---|---|---|
name | required | "enzyme-mechanism", "immigration-death", "michaelis-menten", "repressilator" or "vilar-noise". |
name is one of "enzyme-mechanism",
"immigration-death", "michaelis-menten", "repressilator"
and "vilar-noise". The packaged files are the converted
crn-craft.model/1.0 documents of models/examples/ in the
repository (crn_craft.convert of each); to_dict() returns that
document until the model is edited.
Running
Prepare a request and simulate it, check documents without running them, ask for the finite state projection, and read the discovery document. ensemble builds the request from keyword arguments; prepare takes a request you wrote. Both return a PreparedEnsemble. The guide teaches this in chapters 3 and 5.
ensemble
ensemble(
model,
end,
report_times,
replicates=1,
seed=0,
threads=1,
keep_paths=0,
keep_instances=0,
max_events=100000000,
max_sampling_steps=None,
max_instances=100000,
max_output_bytes=67108864,
wall_time_s=None,
trackers=(),
event_log=None,
method=None,
compiled=None,
quantiles=(0.025, 0.5, 0.975),
selector=None,
strict=False,
protocol=None,
)
Build and prepare a crn-craft.run/1.0 request; simulate() runs it.
| Argument | Default | Meaning |
|---|---|---|
model | required | A model: bytes from load, a JSON string, a dictionary or a Model. |
end (keyword only) | required | Horizon of the run. Report times lie in [0, end]. |
report_times (keyword only) | required | Increasing report times in [0, end]. |
replicates (keyword only) | 1 | Number of replicates. |
seed (keyword only) | 0 | Root seed. Replicate i draws from its own stream, so results do not depend on threads. |
threads (keyword only) | 1 | Native worker threads, 1 to 64. |
keep_paths (keyword only) | 0 | How many replicates, from replicate 0, keep their full observable series (result.paths). "all" or True keeps every replicate. |
keep_instances (keyword only) | 0 | How many replicates keep their final instances (metadata["final_instances"]). |
max_events (keyword only) | 100000000 | Event budget per replicate. None means no limit (the request records 2**64 - 1). |
max_sampling_steps (keyword only) | None | Budget per replicate for random words and leap iterations. None means 16 × max_events (2**64 - 1 when max_events is None). |
max_instances (keyword only) | 100000 | Most instances alive at once, per replicate. |
max_output_bytes (keyword only) | 67108864 | Budget for the size of the result. Event logs reserve space for every replicate before the run. |
wall_time_s (keyword only) | None | Wall-clock limit of the whole run in seconds, or None. |
trackers (keyword only) | () | A list of {"observable", "first_passage"?, "keep_episodes"?}. |
event_log (keyword only) | None | {"max_entries": n, "rules": [...]}, or None. |
method (keyword only) | None | A method name or a dictionary such as {"kind": "tau", "epsilon": 0.03}; None runs the tree method. See methods. |
compiled (keyword only) | None | A loop from compile_loop for this model. Checked at preparation and used by every simulate(). |
quantiles (keyword only) | (0.025, 0.5, 0.975) | Probabilities for statistics["quantiles"] and statistics["median"]. () or None asks for none. |
selector (keyword only) | None | The event selector of static_direct: "linear", "composition_rejection", "sorting", "rssa_cr" or "auto". See methods. |
strict (keyword only) | False | True: replicates that end early raise IncompleteEnsembleError in simulate() instead of warning with IncompleteEnsembleWarning. |
protocol (keyword only) | None | An ordered Protocol describing count operations and delays. |
The arguments are those of crn_craft.rules.ensemble, with two
differences: the documents are always crn-craft.model/1.0 (a
rules-model gets that schema string, a network crn-craft.model/0.1
is converted) and crn-craft.run/1.0, and quantiles defaults to
(0.025, 0.5, 0.975), so result.statistics has "median" and
"quantiles"; quantiles=() or None asks for none.
selector chooses the event selector of method="static_direct"
(absent means "auto"). method=None runs the exact tree method;
higher-order reactions (count) need "static_direct",
"next_reaction", "tau" or "hybrid".
A Protocol selects the run/1.1 count scheduler. Supply
linear Static Direct (the default with a protocol) or Next Reaction.
Budgets: max_events defaults to 108 events per replicate, and
max_sampling_steps=None follows it (16 random words per event), so
a long run needs only max_events raised. max_events=None means
no event and sampling limit (the request records 264 - 1); guard
such a run with wall_time_s. If replicates end early (a budget, or
failed), simulate() warns with
IncompleteEnsembleWarning, naming the count per termination
and the keyword to raise; strict=True raises
IncompleteEnsembleError instead.
prepare
prepare(
model,
request,
compiled=None,
quantiles=<unset>,
selector=None,
strict=False,
)
Prepare a request you wrote, as crn-craft.run/1.0.
| Argument | Default | Meaning |
|---|---|---|
model | required | A model: bytes from load, a JSON string, a dictionary or a Model. |
request | required | A request you wrote: bytes, a JSON string or a dictionary. |
compiled (keyword only) | None | A loop from compile_loop for this model. Checked at preparation and used by every simulate(). |
quantiles (keyword only) | unset | Unset: (0.025, 0.5, 0.975) unless the request states outputs.quantiles itself. () asks for none. |
selector (keyword only) | None | The event selector of static_direct: "linear", "composition_rejection", "sorting", "rssa_cr" or "auto". See methods. |
strict (keyword only) | False | True: replicates that end early raise IncompleteEnsembleError in simulate() instead of warning with IncompleteEnsembleWarning. |
As crn_craft.rules.prepare, but the documents are always the
1.0 contracts: a rules-run request is rewritten as crn-craft.run/1.0
with the defaults of its version written out (so it runs the same
paths), a rules-model gets the schema crn-craft.model/1.0 and a
network crn-craft.model/0.1 is converted; the request’s model hash
follows when it was the hash of the supplied model. quantiles
defaults to (0.025, 0.5, 0.975) unless the request states
outputs.quantiles itself; quantiles=() asks for none. A
crn-craft.run/1.0 request for crn-craft.model/1.0 bytes that
needs no change keeps its exact bytes. strict is that of
ensemble; the request’s budgets are used as written.
PreparedEnsemble
class PreparedEnsemble
Created by the functions of this page, not by calling it.
A prepared request, returned by ensemble and prepare.
simulate() runs it, bind_parameters makes a candidate with other
parameter values, and archive seals a run. It can be simulated again
with independent execution state. strict (from ensemble or
prepare) decides whether a run with replicates that ended early
warns (IncompleteEnsembleWarning) or raises
(IncompleteEnsembleError); candidates keep it.
PreparedEnsemble.simulate
PreparedEnsemble.simulate(
cancel_file=None,
callback=None,
batch_callback=None,
batch_size=256,
compiled=None,
)
Run native workers.
| Argument | Default | Meaning |
|---|---|---|
cancel_file (keyword only) | None | Path of a file; the run is cancelled when the file exists. |
callback (keyword only) | None | callback(id, event) on the native workers; returning False stops that replicate. Needs the interpreter. |
batch_callback (keyword only) | None | batch_callback(id, events) receives the retained log after the run. |
batch_size (keyword only) | 256 | Entries per call of batch_callback. |
compiled (keyword only) | None | A CompiledLoop for this call only. None uses the loop attached at preparation, if any. |
A live callback(id, event) returning False stops that replicate; any
other return value continues. event is a log entry: time,
rule (an index into rule_names, None for a leap),
reactants, products, observables (in the result’s column
order) and firings. Workers preserve per-replicate order, and
calls from different replicates interleave. An exception in the
callback cancels the run and is raised here; partial results are
discarded. A callback that blocks also blocks Ctrl-C. A
batch_callback(id, events) replays the retained log after execution
and cannot affect the run.
compiled, a CompiledLoop for this model, runs this
call in the compiled program instead of the interpreter, with
byte-identical results. The request must select static_direct
(CrnError CRN-R020 at /method otherwise) and use this
loop’s model bytes (CRN-R020 at /model); the first call
checks this. None, the default, means the loop attached with
compiled= on ensemble or prepare, and the interpreter
if none was attached. So a run prepared without a loop can be
simulated either way, call by call, while a run with an attached
loop always runs compiled. Callbacks need the interpreter and are
refused with ValueError whenever a loop runs the call.
PreparedEnsemble.bind_parameters
PreparedEnsemble.bind_parameters(overrides)
Prepare an independent candidate with the same ensemble settings.
| Argument | Default | Meaning |
|---|---|---|
overrides | required | A mapping from parameter names to new finite values. |
The candidate’s model and run hashes cover the re-serialized bound model and request, not the original file. It runs interpreted: a compiled loop serves only the model bytes it was compiled for.
Its results’ model is this run’s model with the bound values,
and their request this run’s request bound to it (see
Result.model).
PreparedEnsemble.rule_names
PreparedEnsemble.rule_names
Read-only property.
Rule names in declaration order.
Callback events and log entries carry a rule index into this tuple,
so run.rule_names[event["rule"]] names the rule that fired.
Model.fsp
Model.fsp(end, report_times, bounds, *, max_states=None, tolerance=None)
The exact distribution of the counts by finite state projection.
| Argument | Default | Meaning |
|---|---|---|
end | required | Horizon of the run. Report times lie in [0, end]. |
report_times | required | Increasing report times in [0, end]. |
bounds | required | A mapping from every species label to its largest count. |
max_states (keyword only) | None | Cap on the enumerated states. None means 100,000. |
tolerance (keyword only) | None | Truncation budget of the series. None means 1e-12. |
bounds maps every species label to its largest count (a type
name for a type without attributes, for example {"S": 999, "I": 1000, "R": 1000}); end and report_times are as in
ensemble. max_states (default 100,000) caps the enumerated
states and tolerance (default 1e-12) is the truncation
budget of the series. The model must be closed (CrnError
CRN-R017 otherwise). Returns an FspResult; see
crn_craft.rules.fsp for the method and its error terms.
check
check(model, request=None)
Check a model, and optionally a request for it, without running anything.
| Argument | Default | Meaning |
|---|---|---|
model | required | A model: bytes, text, a dictionary or a Model. |
request | None | A request for the model, or None to check the model alone. |
model and request are bytes, text, dictionaries or a
Model. Returns the report crn-craft check MODEL [REQUEST]
prints, as a dictionary; read valid and diagnostics:
- a
crn-craft.model/1.0model, with or without a request, and a rules-model with a request:crn-craft.check/1.0; with a request, the report says whetherrunwould accept the two documents (simulation andfsprequests) and addsrun_sha256; - a rules-model alone:
crn-craft.rules-check/0.1, as release 0.6.0; - a network
crn-craft.model/0.1alone:crn-craft.check/1.0of the conversion (CRN-R016and validation diagnostics if it cannot be converted).
describe
describe(kind=None)
The discovery document, or the JSON Schema of one contract.
| Argument | Default | Meaning |
|---|---|---|
kind | None | A contract name such as "model-1.0" or "run-1.0". None returns the discovery document. |
Without kind: crn-craft.describe/1.0, as crn-craft describe
prints it, with the commands, the 1.0 contracts, methods, selectors,
quantiles and limits first and the older contracts that are still read
under legacy. With kind (for example "model-1.0" or
"run-1.0"), the schema crn-craft describe KIND prints;
ValueError for an unknown kind.
CrnError
class CrnError(diagnostics)
A request the native core rejected.
| Argument | Default | Meaning |
|---|---|---|
diagnostics | required | The list of diagnostics. |
diagnostics is the list of CRN-craft diagnostics (dictionaries with
code, path, message and hint). It is a ValueError, so
existing except ValueError handlers keep working.
IncompleteEnsembleWarning
class IncompleteEnsembleWarning(message, counts=None)
Some replicates of a run ended early, on a budget or by failing.
| Argument | Default | Meaning |
|---|---|---|
message | required | The message. |
counts | None | Replicates per termination. |
simulate() warns with it when a replicate’s termination is neither
completed nor stopped (a cancelled run is not reported: it
was stopped on purpose). The message gives the count per termination and
the keyword that raises each budget. counts maps each such
termination to its number of replicates. strict=True raises
IncompleteEnsembleError instead. The package registers the
filter "always" for this category at import, after any other
filter, so every run that ends early is reported, also in a loop;
warnings.simplefilter("ignore", IncompleteEnsembleWarning) silences
it.
IncompleteEnsembleError
class IncompleteEnsembleError(message, counts=None, result=None)
The error of strict=True for an ensemble that did not complete.
| Argument | Default | Meaning |
|---|---|---|
message | required | The message. |
counts | None | Replicates per termination. |
result | None | The result of the run. |
It carries the message and counts of
IncompleteEnsembleWarning, and result, the
crn_craft.rules.Result of the run, so the records can still be
read.
Experiments and probability laws
Declare scheduled experiments, prepare a probability projection, build spatial compartments and import an experiment bundle.
Protocol
class Protocol(*, time_unit=None, max_pending=4096)
An ordered calendar in the time unit of the model’s rates.
| Argument | Default | Meaning |
|---|---|---|
time_unit (keyword only) | None | A label for the time unit of the model and the protocol. |
max_pending (keyword only) | 4096 | Per-replicate cap on pending reaction completions. |
Use at for external interventions and delay to attach
completions to the firings of a reaction. Equal times preserve insertion
order. Reports see the state after actions and due completions.
Protocol.at
Protocol.at(
time,
parameters=None,
change=None,
set_counts=None,
partition=None,
)
Add an atomic group of rate edits and count operations.
| Argument | Default | Meaning |
|---|---|---|
time | required | Timestamp in the same time unit as the model. |
parameters (keyword only) | None | Named kinetic parameters to replace at this time. |
change (keyword only) | None | Map species names to signed count increments. |
set_counts (keyword only) | None | Map species names to absolute counts. |
partition (keyword only) | None | Map species names to independent retention probabilities. |
Count increments may be negative. Counts assigned or partitioned in the same group use their pre-group values. Give at most one count operation per species. Return the protocol for chaining.
Protocol.delay
Protocol.delay(reaction, duration, *, products=None, owner=None)
Add fixed delayed products to a named initiation reaction.
| Argument | Default | Meaning |
|---|---|---|
reaction | required | Name of the reaction. |
duration | required | Positive time from initiation to completion. |
products (keyword only) | None | Count increments made by a successful completion. |
owner (keyword only) | None | Optional busy species whose removal cancels the completion. |
When supplied, the owner is a busy species created once per initiation. Its loss cancels the completion; a completion consumes one surviving owner.
Protocol.to_dict
Protocol.to_dict()
Return a detached copy of the protocol payload for run/1.1.
Signal
class Signal(function, *, change_times=())
A real-time rate input. Tables use linear or right-continuous steps.
| Argument | Default | Meaning |
|---|---|---|
function | required | Prescribed time-dependent rate function. |
change_times (keyword only) | () | Times where the rate can change discontinuously. |
Tables are evaluated natively by both forced-segment solvers. Callables are a Python-only option, called from the native step loop. Provide their change points and a reproducible description of their parameters in the calling experiment.
Signal.table
Signal.table(times, values, *, interpolation='linear')
Create a table with held endpoint values outside its range.
| Argument | Default | Meaning |
|---|---|---|
times | required | Increasing times at which the rate is tabulated. |
values | required | Values in the same order as times. |
interpolation (keyword only) | 'linear' | Linear interpolation or a right-continuous step curve. |
prepare_fsp
prepare_fsp(
model,
bounds,
protocol=None,
initial=None,
retained=None,
max_states=100000,
max_edges=2000000,
)
Prepare a reusable projection for a closed model.
| Argument | Default | Meaning |
|---|---|---|
model | required | A model: bytes from load, a JSON string, a dictionary or a Model. |
bounds | required | Mapping of species labels to inclusive upper counts. |
protocol (keyword only) | None | An ordered Protocol describing count operations and delays. |
initial (keyword only) | None | Optional mapping of count tuples to probabilities. |
retained (keyword only) | None | Optional iterable of count tuples, in lowered species order, that restrict the state space; transitions that leave the set flow to the absorbing sink. Not available with scheduled interventions. |
max_states (keyword only) | 100000 | Reachable-state limit. |
max_edges (keyword only) | 2000000 | Sparse edge limit. |
The native engine lowers the model, enumerates the states, builds the
generator and propagates the law; no solve needs SciPy.
Existing Model.fsp is the native uniformization for one fixed
model without protocols, signals or initial mixtures. A prepared
projection holds no per-solve state, so threads can share it. It cannot
be pickled; prepare one per process.
retained optionally restricts the projection to a finite set of
count tuples in the order of the projection’s species, inside
bounds (for example a hyperbolic cut (x - 4) (y - 4) < c). Only
retained states reachable from the initial law are enumerated; a
transition to any other state flows to the absorbing sink, so the sink
probability measures the truncation. The initial law must lie in the
set; duplicates count once; an empty set, negative counts, tuples of
another length and more than max_states tuples are refused. A
retained set cannot be combined with scheduled count interventions.
stationary_fsp
stationary_fsp(
model,
bounds,
return_state=None,
class_state=None,
parameters=None,
expansions=0,
tolerance=1e-06,
flux_tolerance=1e-06,
max_states=100000,
max_factor_bytes=2147483648,
)
Solve a finite stationary law or an outward-flux-redirected FSP.
| Argument | Default | Meaning |
|---|---|---|
model | required | A model: bytes from load, a JSON string, a dictionary or a Model. |
bounds | required | Mapping of species labels to inclusive upper counts. |
return_state (keyword only) | None | Retained count tuple to which stationary FSP redirects escaping rates. |
class_state (keyword only) | None | State identifying the selected finite closed class. |
parameters (keyword only) | None | Numeric model parameter overrides. |
expansions (keyword only) | 0 | Maximum number of additional projection enlargements. |
tolerance (keyword only) | 1e-06 | Target maximum marginal CDF change after refinement. |
flux_tolerance (keyword only) | 1e-06 | Target outward rate after projection refinement. |
max_states (keyword only) | 100000 | Reachable-state limit. |
max_factor_bytes (keyword only) | 2147483648 | Memory budget, in bytes, of the sparse LU factorization and its workspace; a larger bound is refused (CRN-E070). |
With a return state, expand faces according to boundary flux exposure
and compare marginal CDFs across successive bounds. The resulting
convergence indication is empirical for an infinite network. A finite
generator with several closed classes needs an explicit class state.
The native engine builds the generator, finds the closed communicating
classes and solves the anchored balance equations of one class with a
sparse LU, refused when its bound exceeds max_factor_bytes. Without
a return state, every transition must stay inside the bounds.
SpatialModel
class SpatialModel(name, volumes)
Build an ordinary reaction network from named well-mixed compartments.
| Argument | Default | Meaning |
|---|---|---|
name | required | A name. |
volumes | required | Mapping of compartment names to their positive fixed volumes. |
The graph uses directed per-molecule transport hazards. Compartment volumes are fixed. Rate templates can interpolate local species names and the fixed volume.
SpatialModel.add_species
SpatialModel.add_species(name, initial=0, *, reservoirs=())
Add a species in every compartment, with optional fixed counts.
| Argument | Default | Meaning |
|---|---|---|
name | required | A name. |
initial | 0 | Initial count or a mapping from compartments to counts. |
reservoirs (keyword only) | () | Compartments that keep this species at its initial count. |
SpatialModel.label
SpatialModel.label(species, region)
Return the species label used by the lowered model.
| Argument | Default | Meaning |
|---|---|---|
species | required | A species name. |
region | required | Compartment name. |
SpatialModel.local
SpatialModel.local(
name,
rate,
reactants,
products,
combinatorial=False,
regions=None,
)
Instantiate a local reaction template in the selected regions.
| Argument | Default | Meaning |
|---|---|---|
name | required | A name. |
rate | required | Numeric rate or expression with local substitution fields. |
reactants | required | Species consumed by the local reaction. |
products | required | Species produced by the local reaction. |
combinatorial (keyword only) | False | Multiply an expression by the available reactant combinations. |
regions (keyword only) | None | Compartments receiving the local reaction template. |
SpatialModel.transport
SpatialModel.transport(species, origin, target, rate)
Add a directed, per-copy first-order hop.
| Argument | Default | Meaning |
|---|---|---|
species | required | A species name. |
origin | required | Source compartment of a directed hop. |
target | required | Destination compartment or reference copy count, depending on the model. |
rate | required | First-order hop rate per copy. |
SpatialModel.diffusion
SpatialModel.diffusion(species, first, second, diffusivity, spacing)
Add both directions on a uniform lattice at rate D / spacing².
| Argument | Default | Meaning |
|---|---|---|
species | required | A species name. |
first | required | One region of the lattice pair. |
second | required | The other region of the lattice pair. |
diffusivity | required | Diffusion coefficient per distance unit squared per time unit. |
spacing | required | Distance between lattice neighbors. |
SpatialModel.profile
SpatialModel.profile(values, species)
Select region columns from a trajectory/report array.
| Argument | Default | Meaning |
|---|---|---|
values | required | A trajectory array with a variable axis. |
species | required | A species name. |
spatial_turnover
spatial_turnover(
initial,
end,
target,
feedback,
mutant_weight,
death,
hop,
seed=0,
mutation=0.0,
fixed_left=False,
labels=False,
max_events=3000000000,
)
Sample the endpoint of a two-genotype nearest-neighbor turnover chain.
| Argument | Default | Meaning |
|---|---|---|
initial | required | Per-region sequence of initial wild and mutant count pairs. |
end (keyword only) | required | Horizon of the run. Report times lie in [0, end]. |
target (keyword only) | required | Destination compartment or reference copy count, depending on the model. |
feedback (keyword only) | required | Coefficient of linear birth feedback. |
mutant_weight (keyword only) | required | Relative contribution of a mutant to copy-count feedback. |
death (keyword only) | required | Loss rate per molecule. |
hop (keyword only) | required | Hopping rate per molecule in each available direction. |
seed (keyword only) | 0 | Root seed. Replicate i draws from its own stream, so results do not depend on threads. |
mutation (keyword only) | 0.0 | Probability of a new mutant clone at birth. |
fixed_left (keyword only) | False | Use the first compartment as a fixed reservoir. |
labels (keyword only) | False | Return clone labels by region. |
max_events (keyword only) | 3000000000 | Event budget per replicate. None means no limit (the request records 2**64 - 1). |
Each copy has birth rate max(0, death + feedback * (target - W - weight*M)). Death and migration have constant per-copy rates. New mutations are marked at birth, and labels have no effect on subsequent hazards.
read_experiment
read_experiment(path, *, convention)
Read an OMEX or SED-ML path and resolve its local stochastic experiment.
| Argument | Default | Meaning |
|---|---|---|
path | required | A file path. |
convention (keyword only) | required | The rate convention. The importer refuses an absent or other value. |
The caller explicitly confirms stochastic count propensity semantics. Exact polynomial conversion verifies the falling-factorial reactants.
Likelihoods and sensitivities
Turn the law of a prepared projection into the probability of what was measured, score it against counted cells, and differentiate it with respect to parameters. crn_craft.likelihood and crn_craft.sensitivities are modules: call their names as crn.likelihood.histogram_score(...). Binomial detection and fluorescence bins need SciPy (pip install "crn-craft[likelihood]"); everything else runs without it. Tutorial O3 and optimization lesson C8 use these names.
likelihood.measured_counts
likelihood.measured_counts(states, species, observable)
Map projected states to one count, a species sum, or a joint readout.
| Argument | Default | Meaning |
|---|---|---|
states | required | Count states, one row per state, as PreparedFsp.states gives them. |
species | required | The species labels of the columns of states. |
observable | required | A species name, or a tuple with one entry per measured axis: a name or a list of names to sum. |
A string names one species. Each entry in a tuple is one measured axis. An axis can be a string or a list of species to sum.
likelihood.count_probability
likelihood.count_probability(states, probabilities, values, *, detection=1.0)
Compute the probability of each requested count or joint count.
| Argument | Default | Meaning |
|---|---|---|
states | required | Measured counts of every state: one column per measured axis, or a vector for one axis. |
probabilities | required | One probability per state, without the sink. |
values | required | The counts or joint counts whose probabilities are wanted, in the layout of states. |
detection (keyword only) | 1.0 | Probability that one molecule is detected, a number or one per axis; below 1 each count is thinned binomially (needs SciPy). |
likelihood.binned_probability
likelihood.binned_probability(
counts,
probabilities,
edges,
gain=None,
background=0.0,
sigma=None,
)
Map one count to intervals or to Gaussian fluorescence bins.
| Argument | Default | Meaning |
|---|---|---|
counts | required | The measured count of every state, one axis. |
probabilities | required | One probability per state, without the sink. |
edges | required | Strictly increasing bin edges; -inf and inf are allowed. |
gain (keyword only) | None | Fluorescence per molecule. With sigma, the bins are of fluorescence, not of counts (needs SciPy). |
background (keyword only) | 0.0 | Fluorescence of a cell without molecules. |
sigma (keyword only) | None | Standard deviation of the Gaussian measurement noise. |
Edges are increasing and bins are left-closed, right-open. Infinite edges represent underflow or overflow. Fluorescence has mean background + gain * count and standard deviation sigma.
likelihood.HistogramGroup
class likelihood.HistogramGroup(
condition,
replicate,
time,
counts,
probabilities,
missing_mass=0.0,
time_unit='',
readout='',
)
Counts and predicted observed bin probabilities for one sample group.
| Argument | Default | Meaning |
|---|---|---|
condition | required | Label of the experimental condition. |
replicate | required | Label of the replicate. |
time | required | Observation time, a finite number. |
counts | required | Observed cells per bin, nonnegative integers. |
probabilities | required | Predicted probability of every bin, in the order of counts. |
missing_mass | 0.0 | Probability that the prediction does not capture (sink and truncated bins), in [0, 1]. |
time_unit | '' | Unit of time, kept as a label. |
readout | '' | Name of the readout, kept as a label. |
likelihood.histogram_score
likelihood.histogram_score(groups)
Score grouped histograms and expose the cost uncertainty due to leakage.
| Argument | Default | Meaning |
|---|---|---|
groups | required | An iterable of HistogramGroup. |
likelihood.HistogramScore
class likelihood.HistogramScore
Created by the functions of this page, not by calling it.
Negative log likelihood and a bound allowing for uncaptured mass.
impossible_bins counts occupied bins with zero retained probability.
nats_per_cell is infinite exactly when it is positive. Each entry
of groups is (condition, replicate, time, cells, nats, optimistic
nats).
likelihood.mean_score
likelihood.mean_score(observed, predicted, covariance)
Return the quadratic mean objective for a group covariance.
| Argument | Default | Meaning |
|---|---|---|
observed | required | Observed means, a number or a vector. |
predicted | required | Predicted means of the same shape. |
covariance | required | Covariance of the observed means, symmetric positive definite. |
The value is delta’ V^-1 delta / 2 without the log-determinant term. The covariance must be symmetric positive definite.
sensitivities.forward_sensitivities
sensitivities.forward_sensitivities(
graph,
segments,
times,
parameters,
initial=None,
initial_derivatives=None,
logarithmic=False,
difference=0.0001,
tolerance=1e-06,
max_work=300000,
max_factor_bytes=536870912,
)
Solve p’=Qp and s’=Qs+(dQ/dtheta)p over piecewise-constant bindings.
| Argument | Default | Meaning |
|---|---|---|
graph | required | A prepared projection from prepare_fsp. |
segments | required | Sequence of (end_time, bindings) with increasing ends. |
times | required | Strictly increasing report times in [0, last end]. |
parameters | required | Names of the parameters to differentiate, at most 16. |
initial (keyword only) | None | Initial law; by default the one given to prepare_fsp. |
initial_derivatives (keyword only) | None | Derivatives of the initial law, one row per parameter; by default zero. |
logarithmic (keyword only) | False | Differentiate with respect to the natural logarithm of each parameter. |
difference (keyword only) | 0.0001 | Relative step of the centered difference of the generator. |
tolerance (keyword only) | 1e-06 | Relative tolerance of the integration; the absolute one is 1e-4 tolerance. |
max_work (keyword only) | 300000 | Largest number of augmented implicit solves. |
max_factor_bytes (keyword only) | 536870912 | Largest memory of one sparse factorization, in bytes. |
segments is a sequence of (end_time, bindings), measured from
time zero, with strictly increasing ends; each binding maps parameter
names to values for that segment and must bind every name in
parameters (at most 16 names). times increase strictly, lie in
[0, last end]; time zero returns the initial state. The law and its
derivatives pass continuously across segment ends, where the integrator
restarts.
dQ/dtheta is the centered difference of the generator at
theta (1 +- difference) (or theta exp(+-difference) with
logarithmic=True, which differentiates in natural-log coordinates)
on the same state graph. It is exact up to roundoff for rates linear in
the parameter and second-order accurate otherwise, so parameters inside
any rate expression, Hill functions included, can be differentiated;
the time integration is the implicit variable-order BDF of the prepared
projection with the derivatives inside its error norm (relative
tolerance, absolute 1e-4 tolerance), and one sparse
factorization serves the law and every direction.
initial is a law as in PreparedFsp.solve; by default the
initial law given to crn_craft.prepare_fsp. It does not depend
on the parameters unless initial_derivatives (one row per parameter,
one column per state in graph order, no sink column, rows summing to
zero) says so. Scheduled count interventions, stop states and
continuously varying signals are outside this interface.
Raises ValueError for invalid arguments, a lost probability or
derivative mass above 1e-7 or a negative probability beyond the
integration tolerance, and the errors of the prepared projection for
budgets (max_work augmented solves, max_factor_bytes) and
interruption. The caller chooses the truncation: read the sink.
sensitivities.ProjectionSensitivities
class sensitivities.ProjectionSensitivities
Created by the functions of this page, not by calling it.
Laws and their parameter derivatives at the requested times.
probabilities has shape (times, states + 1) and derivatives
(times, parameters, states + 1), in the order of states; the last
column is the absorbing sink. Each row of probabilities sums to one
and each derivative row to zero, sink included. work counts the
augmented implicit solves.
sensitivities.ProjectionSensitivities.observed
sensitivities.ProjectionSensitivities.observed(axes)
Sum states and derivatives into the bins of the measured counts.
| Argument | Default | Meaning |
|---|---|---|
axes | required | The measured species, as the observable of likelihood.measured_counts. |
axes names the measured species. Returns the distinct measured
count tuples, their probabilities (times, bins) and derivatives
(times, parameters, bins); the sink is not a bin.
sensitivities.fisher_information
sensitivities.fisher_information(
probabilities,
derivatives,
cells,
probability_floor=0.0,
)
Fisher information of independent snapshots of measured bins.
| Argument | Default | Meaning |
|---|---|---|
probabilities | required | Probabilities of the measured bins, shape (times, bins). |
derivatives | required | Their derivatives, shape (times, parameters, bins). |
cells | required | Cells measured at each time: a number or one per time. |
probability_floor (keyword only) | 0.0 | Bins with a smaller probability are left out. |
probabilities (times, bins) and derivatives
(times, parameters, bins) describe MEASURED bins (aggregate hidden
states first). cells is the number of cells measured at each time, a
number or one per time. Returns (matrix, excluded): the symmetric
positive semidefinite matrix sum_t n_t sum_b g g^T / p over bins with
p > 0 and p >= probability_floor, and per time the probability of
the excluded bins. A bin with p = 0 is unreachable or has underflowed
and carries no information; a positive floor reproduces a published
convention that drops rare bins and lowers the information.
Results
What simulate() and Model.fsp return. The fields of the result document and the terminations are in the results reference. Result.save is under files and archives. Chapter 4 of the guide teaches the data frames.
Result
class Result
Created by the functions of this page, not by calling it.
The result of a rules ensemble.
records: one row per replicate, indexed by replicate id. Columnsstarted,termination(categorical over the values ofcrn_craft.rules.TERMINATIONS:completed,stoppedand the reasons a replicate ended early),stop_time,events,rng_words,peak_instances,created_instancesandsaved_points.rule_events: events per replicate (rows) and rule (columns, in declaration order).statistics: None if withheld, else a dict withsamples(the number of replicates included) and one DataFrame per statistic (mean,sample_variance,mean_standard_error), indexed by report time with one column per observable. A statistic that was not computed is None. A run withquantiles=also hasquantiles, a dict from each requested probability to a DataFrame of that shape, and, when 0.5 was requested,median, the DataFrame ofquantiles[0.5](seeensemble).paths: the kept series as an xarray DataArray with dimensions (replicate,time,variable);paths_frame()gives the DataFrame of release 0.4.0,to_xarray()a Dataset.event_columns(): event logs as a DataArray with dimensions (replicate,entry,variable);event_frame()gives the DataFrame of release 0.4.0.tracker_columns(i): a tracker’s fields as a DataFrame.metadata: the full result document;observationsits trackers and logs;record_diagnosticsreplicate errors by id.modelandrequest: the model and request documents that ran, andsave(path), which writes them with the results to one markdown or JSON report.
Observables are in result order: sorted by name, then any continuous
variable such as ATP. Use .to_numpy() on any frame, column or
array for NumPy arrays.
Result.paths
Result.paths
Kept series as a DataArray: replicates x report times x variables.
Dimensions are ("replicate", "time", "variable"), the order of
event_columns(), with the coordinates replicate (the kept
replicate ids, int64), time (the report times) and variable
(the observables in result order: sorted names, then continuous
variables). Values
are float64. attrs holds the result’s sampler, method
(the method object of rules-result/0.3 as JSON text, "null"
for older results), root_seed, model_sha256 and
run_sha256; netCDF can store all of them.
keep_paths decides which replicates are kept ("all" keeps
every one). A replicate that ended on a budget has values only up
to its last saved report time and NaN after it. For example
paths.sel(variable="mutants") is a replicate x time array and
paths.sel(replicate=3) one replicate’s series. Release 0.5.0
ordered the dimensions ("time", "variable", "replicate");
paths.transpose("time", "variable", "replicate") gives that
order. paths_frame() returns the DataFrame of release 0.4.0.
Result.paths_frame
Result.paths_frame()
Kept series as a DataFrame: (replicate, time) rows.
One column per observable, in result order; this is paths of
release 0.4.0. A replicate that ended on a budget has rows only up
to its last saved report time.
Result.to_xarray
Result.to_xarray()
Return the kept paths as an xarray Dataset.
Dimensions are replicate and time (the report times), with
one variable per observable; rows a replicate did not save are NaN.
It holds the values of paths: paths.to_dataset("variable").
attrs holds sampler, model_sha256, run_sha256 and
root_seed, all of which netCDF can store.
Result.tracker_columns
Result.tracker_columns(index=0)
Return a tracker’s scalar fields, one row per observed replicate.
| Argument | Default | Meaning |
|---|---|---|
index | 0 | The index of the tracker in the request’s trackers. |
Indexed by replicate id. Counts (appearances, extinctions,
omitted_episodes) are unsigned integers; times and values are
floats, NaN where absent (for example first_passage of a
replicate that never met the predicate). Replicates that failed
before tracking began carry no observation. Episodes are in
observations.
Result.event_columns
Result.event_columns(replicate=None)
Return retained event logs as a DataArray.
| Argument | Default | Meaning |
|---|---|---|
replicate | None | A replicate id, or None for every log. |
Without a replicate id the dimensions are ("replicate", "entry", "variable"): one row per observed replicate (int64 ids), entries
0, 1, … in event order, and the observables after each event
(result order), NaN past a replicate’s last entry. Coordinates over
(replicate, entry): time (float64, NaN as padding),
rule (the rule index, -1 for a leap, -2 as padding) and
rule_name (the name; NaN for a leap and as padding); over
replicate: length, the number of logged entries. With a
replicate id the dimensions are ("entry", "variable"), exactly
length entries, with scalar replicate and length
coordinates. attrs is that of paths.
A replicate without logged events has length 0. Participant
instances and leap firings are in the observation entries.
event_frame() returns the DataFrame of release 0.4.0.
Result.event_frame
Result.event_frame(replicate=None)
Return retained event logs as a DataFrame (release 0.4.0’s form).
| Argument | Default | Meaning |
|---|---|---|
replicate | None | A replicate id, or None for every logged event. |
With a replicate id, that replicate’s log, indexed by entry;
without one, every logged event, indexed by (replicate,
entry). Rows are in event order: time, rule (the rule
index, -1 for a leap), rule_name (categorical, missing for a
leap), then one column per observable after the event. Participant
instances and leap firings are in the observation entries.
Result.model
Result.model
Read-only property.
The model document that ran, as a new dictionary.
For a run from ensemble or prepare (also with a compiled
loop) it is the parsed model bytes whose SHA-256 is
metadata["model_sha256"]. For a bind_parameters candidate
it is the template’s model with the bound parameter values, all
parameters as floats in name order: the document the engine
re-serialized and ran, apart from fields that serialization adds
with their default values. None for a Result built directly from
a metadata document and columns.
Result.request
Result.request
Read-only property.
The request document that ran, as a new dictionary.
For a bind_parameters candidate it is the template’s request
bound to the candidate’s model: model.sha256 is
metadata["model_sha256"]. None for a Result built directly from
a metadata document and columns.
FspResult
class FspResult
Created by the functions of this page, not by calling it.
A finite state projection as pandas and xarray objects.
Model.fsp returns it; crn_craft.rules.fsp returns the document
it wraps.
states: the projected states, a DataFrame indexed bystate(0 is the initial state) with one int64 column per species label.probabilities: a DataArray with dimensions("time", "state"), the probability of each state at each report time (the mass that left the bounds is not in it; seetruncation).mean: the projected first moment of each species at each report time, a DataFrame indexed bytime: Σ p(x)·x over the retained states, not renormalized, so it is the mean of the full process only up to the leaked mass.truncation: the error terms per report time, a DataFrame with the columnsphysical_leakage_estimate(mass that left the bounds),series_tail_upper_bound,discarded_weight_estimate,mass_defectandroundoff_mass_residual.species: the species labels;metadata: thecrn-craft.fsp-result/1.0document.
Files and archives
Read model and report files, write reports, and seal a run in an archive directory that can be verified later. The formats are in the archive reference and the contracts.
load
load(path)
Read a model file and check it; return its exact bytes.
| Argument | Default | Meaning |
|---|---|---|
path | required | A model file. |
Every model version is read: crn-craft.model/1.0, the rules-model
versions and the network crn-craft.model/0.1. An invalid model
raises CrnError with the diagnostics of check. Pass the
bytes to ensemble or prepare, or to
Model.from_dict.
load_report
load_report(path)
Read a JSON report written by Result.save.
| Argument | Default | Meaning |
|---|---|---|
path | required | A JSON file written by Result.save. |
Returns the parsed crn-craft.report/1.0 document as a dictionary:
schema, crn_craft_version, model and request (the
documents that ran) and result. Non-finite numbers in it are the
strings "nan", "inf" and "-inf". Raises ValueError for
a file that is not strict JSON (including duplicate keys) or whose
schema is not crn-craft.report/1.0.
Result.save
Result.save(path, *, paths=True)
Write the model, the request and the results to one report file.
| Argument | Default | Meaning |
|---|---|---|
path | required | The file. .md or .markdown writes markdown, .json writes crn-craft.report/1.0. |
paths (keyword only) | True | False leaves the single trajectories out. |
The extension of path decides the format: .md or
.markdown for markdown, .json for JSON (schema
crn-craft.report/1.0, read back with load_report), in
any case; another extension raises ValueError. paths=False
leaves the single trajectories out. An existing file is replaced;
the report is written to a temporary file in the same directory and
renamed, so a failed write (OSError) leaves no partial file.
Returns path as a pathlib.Path.
The same result always gives the same bytes: there is no timestamp,
host name or timing. The markdown report lists the model (reactions,
start values, parameters, stop condition, continuous variables),
the simulation settings with the sampler, the package version and
both hashes, and the results: terminations, mean events per rule,
the kept trajectories and the summary statistics (quantiles, when
the result has them, in ascending order). Observables follow the
model’s species declaration order when every observable is named
after a species type, then continuous variables; otherwise result
order. Each section’s lines are in a fenced text block, so a
markdown renderer keeps one line per entry. Numbers are written in
shortest round-trip form, integral values without .0.
A report is a readable record of a run; an archive is the sealed,
verifiable record of a run for replay. save changes nothing
about the result.
archive
archive(model, request, directory, *, cancel_file=None)
Run a request and seal the run in a new archive directory.
| Argument | Default | Meaning |
|---|---|---|
model | required | A model: bytes from load, a JSON string, a dictionary or a Model. |
request | required | A request: bytes, a JSON string or a dictionary. |
directory | required | The new archive directory. It must not exist; its parent must. |
cancel_file (keyword only) | None | Path of a file; the run is cancelled when the file exists. |
model is model bytes, a JSON string, a dictionary or a
Model; request is request bytes, a JSON string or a
dictionary: any rules-run version, or crn-craft.run/1.0 with any
method, fsp included. The request must bind the exact model bytes
(model.sha256); its model.path is kept but not resolved.
directory must not exist; its parent must.
The directory gets model.json and request.json (the exact
bytes), result.json (the result as crn-craft rules prints it),
manifest.json (crn-craft.archive/1.0: length and SHA-256 of the
three) and, written last, COMPLETE. This is
crn-craft rules MODEL REQUEST --archive NEW_DIRECTORY without files
for the inputs; PreparedEnsemble.archive archives a prepared
run.
Returns the crn-craft.archive-check/1.0 report as a dictionary,
also when the run or the write failed: read valid (the archive was
written), simulation_complete (the run completed) and
termination together, and diagnostics for the reason of a
failure. Input errors create no directory. Check an archive later with
verify_archive. Ctrl-C cancels the run, which is archived as
cancelled before KeyboardInterrupt is raised.
An archive is the sealed, verifiable record of a run for replay; a
report written by Result.save is a readable record.
PreparedEnsemble.archive
PreparedEnsemble.archive(directory, *, cancel_file=None)
Run this request once more and seal the run in directory.
| Argument | Default | Meaning |
|---|---|---|
directory | required | The new archive directory. Its parent must exist. |
cancel_file (keyword only) | None | Path of a file; the run is cancelled when the file exists. |
As archive with the exact model and request bytes this run
was prepared from: the archived result equals the result of
simulate() (completed runs replay byte for byte; a compiled loop
gives the interpreter’s result, which the archive holds). Returns
the crn-craft.archive-check/1.0 report. A bind_parameters
candidate has no original bytes and raises ValueError: archive
its model with the bound values and a request bound to it with
archive.
verify_archive
verify_archive(directory)
Check an archive directory without running anything.
| Argument | Default | Meaning |
|---|---|---|
directory | required | The archive directory to check. |
Reads crn-craft.archive/1.0 directories (written by archive
and crn-craft run ... --archive) and returns the report of
crn-craft verify DIRECTORY as a dictionary
(crn-craft.archive-check/1.0): valid is true for an intact,
consistent archive, also of an incomplete run (simulation_complete
false); diagnostics names the first inconsistency otherwise. The
network engine’s crn-craft.archive/0.1 directories are no longer
read (release 0.7.0).
Analysis and import/export
Analyze the structure of a network, export it, and import SBML and BioNetGen files. The reports are described in the analysis reference and the GillesPy2 export. Chapter 11 of the guide teaches this.
Model.analyze
Model.analyze()
The network analysis of this model (crn-craft.analysis/1.0).
Returns the report as a dictionary, as crn-craft analyze MODEL
prints it: species and reactions of the lowered network, their
dependencies, conservation laws, the cone of reachable directions,
the complex graph and warnings. Read success first: a model
without a flat view (continuous variables, ATP, products that
create new attribute tuples) gives success false with
CRN-R017.
Model.to_gillespy2
Model.to_gillespy2()
This model as a gillespy2.Model.
GillesPy2 must be installed, in the version the export names
(crn-craft describe lists it; another version raises
RuntimeError). A rule with a constant rate and at most two molecules becomes a
mass-action reaction, any other rule a custom propensity, as
crn-craft export MODEL gillespy2 writes them. A model the export
refuses raises CrnError (CRN-E050 for what GillesPy2 cannot
evaluate, such as a stop condition or exp).
convert
convert(model)
Convert a network model (crn-craft.model/0.1) into crn-craft.model/1.0.
| Argument | Default | Meaning |
|---|---|---|
model | required | A model: bytes from load, a JSON string, a dictionary or a Model. |
model is bytes, text or a dictionary. Returns the converted model’s
exact bytes (pretty-printed JSON with a trailing newline), the same
bytes crn-craft convert MODEL prints. Every species becomes a type
and an observable of the same name, every reaction a rule with the same
propensity; reactions of any order use the pattern field count. A
model the converter cannot hold (a population limit, a network without
reactions, …) raises CrnError with CRN-R016; an invalid
network model raises CrnError with its validation diagnostics.
Model.from_dict(json.loads(convert(m))) gives a Model.
read_sbml
read_sbml(path, *, convention)
Import an SBML file as a Model.
| Argument | Default | Meaning |
|---|---|---|
path | required | An SBML file. |
convention (keyword only) | required | Must be "stochastic_count_propensity". |
The SBML subset and the required convention
("stochastic_count_propensity") are those of
crn_craft.importers.import_sbml. The network is converted to
crn-craft.model/1.0; model.import_report keeps the import
report’s provenance (source_format, source_sha256, the
convention and parameter policy) without the model. Unsupported input
raises crn_craft.importers.ImportFailure (a ValueError).
read_bngl
read_bngl(path, *, convention)
Import an expanded BioNetGen network (.net) as a Model.
| Argument | Default | Meaning |
|---|---|---|
path | required | An expanded .net file. |
convention (keyword only) | required | "binomial" or "falling_factorial". |
convention is the rate convention of
crn_craft.importers.import_bng_net ("binomial" or
"falling_factorial"). The network is converted to
crn-craft.model/1.0; model.import_report keeps the import
report’s provenance (species patterns, groups, the convention) without
the model. Unsupported input raises
crn_craft.importers.ImportFailure (a ValueError).
importers.import_sbml
importers.import_sbml(raw, *, convention)
L3V2 Core, one fixed unit compartment, integer item amounts, polynomial jumps.
| Argument | Default | Meaning |
|---|---|---|
raw | required | The SBML document’s bytes. |
convention (keyword only) | required | Must be "stochastic_count_propensity". |
convention must be explicitly ‘stochastic_count_propensity’. Parameters are
folded into reaction coefficients; the report names that import-time choice.
Returns a crn-craft.import/1.0 report as a dictionary:
report["model"] is the converted crn-craft.model/1.0 model, beside
the source format and its SHA-256. Unsupported input raises
crn_craft.importers.ImportFailure.
The document is read by the package’s one XML guard: at most 16 MiB of well-formed UTF-8 (UTF-16 and UTF-32 are refused, and so is a declared encoding other than UTF-8) without a document type or entity declaration anywhere in its bytes, so nothing is expanded or fetched, and with elements nested at most 256 levels deep.
importers.import_bng_net
importers.import_bng_net(raw, *, rate_convention)
Expanded numeric .net only; explicit binomial or falling_factorial convention.
| Argument | Default | Meaning |
|---|---|---|
raw | required | The .net file’s bytes. |
rate_convention (keyword only) | required | "binomial" or "falling_factorial". |
Returns a crn-craft.import/1.0 report as a dictionary:
report["model"] is the converted crn-craft.model/1.0 model, beside
the source format and its SHA-256. Unsupported input raises
crn_craft.importers.ImportFailure.
importers.ImportFailure
class importers.ImportFailure
Raised by an importer for input it does not support.
A ValueError with the attribute code "CRN-E090".
Compiled loops
Build the Static Direct event loop of a model into a program and run requests with it. This needs a Rust toolchain; the requirements, the cache and the limits are in the methods reference. Chapter 5 of the guide teaches when to use it.
compile_loop
compile_loop(
model,
cache_dir=None,
cargo='cargo',
source=None,
progress=True,
)
Compile the Static Direct event loop of a model; opt-in, needs Rust.
| Argument | Default | Meaning |
|---|---|---|
model | required | A model: bytes from load, a JSON string, a dictionary or a Model. |
cache_dir (keyword only) | None | Where to keep builds. Default: the user cache directory, or CRN_CRAFT_CACHE_DIR. |
cargo (keyword only) | 'cargo' | The cargo executable. |
source (keyword only) | None | A CRN-craft checkout of the installed version, for an offline build or a version that is not on crates.io. Default: CRN_CRAFT_SOURCE. |
progress (keyword only) | True | False silences cargo’s progress on stderr. |
As crn_craft.rules.compile_loop, for the document that
ensemble runs: a rules-model gets the schema string
crn-craft.model/1.0 and a network crn-craft.model/0.1 is
converted. So ensemble(model, ..., compiled=compile_loop(model))
works for the same model argument. Generated loops run the linear
scan: pass selector="linear" to ensemble unless "auto"
picks it for the model.
loop_source
loop_source(model)
Return the generated Static Direct event loop of a model as Rust.
| Argument | Default | Meaning |
|---|---|---|
model | required | A model: bytes, text, a dictionary or a Model. |
As crn_craft.rules.loop_source, for the document that
ensemble runs: a rules-model gets the schema string
crn-craft.model/1.0 and a network crn-craft.model/0.1 is
converted, so the loop’s fingerprint is that of the model/1.0 bytes.
CompiledLoop
class CompiledLoop
Created by the functions of this page, not by calling it.
A compiled Static Direct event loop for one model and parameter set.
Returned by compile_loop. Pass it as compiled= to
rules.ensemble, rules.prepare or PreparedEnsemble.simulate
to run Static Direct requests for exactly this model with it.
fingerprint: the generated loop’s fingerprint, which covers the emitted source and the model bytes;model_sha256: SHA-256 of the model bytes it was compiled for;version: thecrn-craftversion it was built against;path: the program;directoryits cache entry with the Cargo project andlogthe build log;cached: whether a cached build was reused;build_secondsthe cargo time of a new build, else None.
CompiledLoop.execute
CompiledLoop.execute(request, *, cancel_file=None)
Run a rules-run request for this loop’s model in its program.
| Argument | Default | Meaning |
|---|---|---|
request | required | A rules-run request for this loop’s model. |
cancel_file (keyword only) | None | Path of a file; the run is cancelled when the file exists. |
Returns the metadata text and the record columns, as the extension
does. A rejected request raises CrnError.
CompiledLoop.verify
CompiledLoop.verify(run)
Run a prepared ensemble interpreted and compiled, and compare.
| Argument | Default | Meaning |
|---|---|---|
run | required | A PreparedEnsemble for this loop’s model. |
Raises CompiledLoopError (reason "mismatch") unless the
metadata and every record column are byte-identical. Returns the
result; replicates that ended early warn or raise as in
run.simulate().
CompiledLoopError
class CompiledLoopError(message, reason, log=None)
A compiled event loop could not be built, or it disagreed with the interpreter.
| Argument | Default | Meaning |
|---|---|---|
message | required | The message. |
reason | required | "cargo_missing", "build_failed" or "mismatch". |
log | None | The path of the build log, if a build started. |
reason is "cargo_missing", "build_failed" or "mismatch";
log is the path of the build log, if a build started.
The importers module
Explicit finite-network import subsets. No silent SBML/rule expansion.
The importers build a network model (crn-craft.model/0.1) exactly as in
0.6.0, validate it, and return it converted to crn-craft.model/1.0 by
crn_craft.convert, inside a crn-craft.import/1.0 report that keeps
the source’s provenance. report["model"] is the converted model as a
dictionary, ready for the unified API (a later read_sbml/read_bngl
wraps it in a Model).
Contracts
Every document that CRN-craft reads or writes is versioned JSON with a
schema field. The Rust types define the shapes. The files in schemas/ and
crn-craft describe KIND are generated from them, so they cannot disagree.
crn-craft describe without a kind prints the discovery document
(crn-craft.describe/1.0): commands, contracts, methods, selectors,
quantiles and limits. The Python call crn_craft.describe() returns the same
document.
Current contracts
| Contract | Role | describe kind |
|---|---|---|
crn-craft.model/1.0 | the model: model reference | model-1.0 |
crn-craft.run/1.1 | a simulation with scheduled interventions or fixed-delay completions | run-1.1 |
crn-craft.result/1.1 | protocol simulation result and optional queue log | result-1.1 |
crn-craft.run/1.0 | the request: simulation methods, or fsp | run-1.0 |
crn-craft.result/1.0 | the result of a simulation request (results) | result-1.0 |
crn-craft.fsp-result/1.0 | the result of an fsp request | fsp-result-1.0 |
crn-craft.check/1.0 | the report of check: whether run would accept the documents | check-1.0 |
crn-craft.analysis/1.0 | structure, conservation laws and bounds of a model | analysis-1.0 |
crn-craft.archive/1.0, crn-craft.archive-check/1.0 | a sealed run and its verification (archive contract) | archive-1.0, archive-check-1.0 |
crn-craft.import/1.0 | the report of the SBML and BioNetGen importers; its model is a model/1.0 document | none |
crn-craft.export/0.1 | the report of export MODEL gillespy2 | export |
crn-craft.state/0.1 | an optional state for analyze MODEL STATE, by species label | state |
crn-craft.report/1.0 | the JSON file written by Result.save: model, request and result in one document. Written and read by Python only, so it has no schema file | none |
crn-craft.describe/1.0 | the discovery document | none |
Contracts that are still read
| Contract | How it is read |
|---|---|
crn-craft.rules-model/0.1 to 0.4 | as before. A rules-model/0.4 document means what model/1.0 means, with the older limits. |
crn-craft.rules-run/0.1 to 0.6 | as before; the results are rules-result/0.1 to 0.3 and replay byte for byte. |
crn-craft.rules-check/0.1 | the report of check MODEL for a rules model alone |
network crn-craft.model/0.1 | through the converter: check, analyze, convert and export read it, and convert writes it as model/1.0. run refuses it with CRN-E033. |
A 1.0 model needs a 1.0 request: a model/1.0 model with a rules-run
request is refused (CRN-R020 at /schema). A rules-model model runs
under either request family. The rules-* request versions refuse the
fields that arrived with 1.0 (method.selector, outputs.quantiles, the
fsp method), also with CRN-R020 at /schema.
Documents of the removed network engine are not read any more: network
run/0.1, ssa-run/0.1 to 0.4, tau-request/0.1, result/0.1,
ssa-result, tau-result, fsp-result/0.1, analysis/0.1 and 0.2,
archive/0.1 and archive-check/0.1. Their schema files are gone. The
changelog has the migration tables.
Contracts of the optional crn-diffsol workspace
integrations/diffsol has its own lockfile and schemas
(integrations/diffsol/schemas/). validation/check_contracts.py covers only
the schemas of the main workspace; the cargo tests of the diffsol workspace
compare these files with the generated ones.
| Contract | Role |
|---|---|
crn-craft.ode-request/0.1, crn-craft.ode-result/0.1 | ODE integration of count kinetics: the request and its result (crn-diffsol MODEL REQUEST) |
crn-craft.concentration-model/0.1 | a concentration model: ordered parameters and states, initial expressions, assignments, derivatives and observations (concentration interface) |
crn-craft.concentration-request/0.1 | one request line of crn-diffsol concentrations MODEL: up to 32 cases with parameters, times and tolerances |
crn-craft.concentration-result/0.1 | one result line: state and observation matrices per case, or its numerical diagnostic |
Versions of the request and the model
The request version decides which fields are allowed:
| Version | Adds |
|---|---|
crn-craft.run/1.0 | method.selector for static_direct, outputs.quantiles, the method fsp; Static Direct defaults to the selector auto; the result is crn-craft.result/1.0 |
crn-craft.run/1.1 | the required protocol (scheduled action groups and fixed-delay completions) for linear static_direct or next_reaction; the result is crn-craft.result/1.1, whose event log entries may carry protocol. A 1.0 request with protocol is refused (CRN-R020); to migrate, change the version, add protocol and choose one of the two methods (scheduled experiments) |
crn-craft.rules-run/0.1 | the tree method only |
crn-craft.rules-run/0.2 | method, trackers, event_log; the result is rules-result/0.2, with a sampler identity and optional ordered observations |
crn-craft.rules-run/0.3 | mtdna_direct |
crn-craft.rules-run/0.4 | Static Direct waiting_time and sparse_trackers |
crn-craft.rules-run/0.5 | hybrid with its rtol and atol; the result is rules-result/0.3, which adds method and continuous |
crn-craft.rules-run/0.6 | no field; Static Direct defaults to Ziggurat waits and sparse trackers; the result is rules-result/0.3 |
crn-craft.run/1.0 has the shape of rules-run/0.6 and means what it means,
plus the features of 1.0. Python writes the versions as follows.
crn.ensemble always writes run/1.0. crn.rules.ensemble picks the lowest
rules-run version that fits its arguments, and rules-run/0.6 for
static_direct; it writes run/1.0 only when an argument needs it
(quantiles=, selector=) or the model is crn-craft.model/1.0.
crn.prepare(model, request) takes a request you wrote yourself.
Model files carry their own version:
| Version | Adds |
|---|---|
crn-craft.rules-model/0.1 | the base language |
crn-craft.rules-model/0.2 | the legacy atp block |
crn-craft.rules-model/0.3 | whole-rule propensity and continuous variables; from 0.3 a rule gives exactly one of rate and propensity |
crn-craft.rules-model/0.4 | "independent": true for continuous variables whose derivative reads only parameters and other independent variables; hybrid integrates them once per prepared run and shares the solution among all replicates |
crn-craft.model/1.0 | what 0.4 means, with larger limits and the pattern count |
A 0.4 document without the field means what it means as 0.3. crn.Model
writes model/1.0, and crn.rules.Model writes 0.3 (0.4 with an independent
ODE). A rules-model file runs under either request family. Stored
rules-model 0.1 to 0.3 files and rules-run 0.1 to 0.6 requests keep their
meaning and replay byte for byte. Each backend has its own replay identity.
The worker count preserves a completed numerical payload apart from its
request hash.
The run request
crn-craft.run/1.0 has the shape of rules-run/0.6 and adds three things:
method.selector for static_direct (linear, composition_rejection,
sorting, rssa_cr or auto, the default; see exact methods),
outputs.quantiles (up to 16 probabilities in (0, 1); the result’s
statistics.quantiles holds the quantile of every report time and observable,
and the median is the quantile at 0.5; see the result contract)
and the method fsp (finite state projection: bounds, max_states and
tolerance; the result is crn-craft.fsp-result/1.0). Its result is
crn-craft.result/1.0. A rules-run request refuses these fields (CRN-R020
at /schema) and keeps its meaning, its numbers and its hashes. The rest of
this section describes the common core, starting with
crn-craft.rules-run/0.1, which binds the model by relative path and SHA-256 and
gives time.end, strictly increasing time.report_times in [0, end],
ensemble.replicates and root_seed, outputs (statistics from mean and
variance, keep_paths, keep_instances) and an explicit budget
(max_events_per_replicate, max_sampling_steps_per_replicate counting every
random word, max_instances alive at once, threads 1–64,
max_output_bytes, optional wall_time_s). Before running, the request is
admitted only if a conservative reservation for records, in-flight and kept
series and observations stays below 2 GiB, and if max_output_bytes can hold
at least 160 bytes per replicate record (CRN-R020); the error itemizes the
reservation and its hint names the largest part. Requests before
crn-craft.run/1.0 also reserve kept final instances as keep_instances × max_instances instances. Under run/1.0 they are not reserved in advance:
the run estimates them (8 bytes per attribute plus 48 per instance, less than
twice their JSON) as replicates finish and drops them early, ending the
result as output_limit (CRN-R045), only once the estimate passes twice
max_output_bytes, when they cannot fit; otherwise the exact size check at
the end decides, as for every result. max_instances then bounds only the
instances alive in one replicate.
Trackers and event logs (rules-run/0.2 and later) reserve output per
replicate: 256 bytes per tracker plus 64 per kept episode, and max_entries
times a bound on one log entry. The entry bound counts every number at its
longest compact JSON form (25 bytes with its comma) and uses the model’s own
sizes: 160 bytes for the keys, time and rule, 25 per observable column, and
per participant of an exact step 62 bytes plus 25 per attribute, where the
participants are the largest number of reactant patterns plus products of
any rule. Leap entries (tau, binomial) list firings instead, 45 bytes per
lowered channel. Up to 0.2.0 the bound assumed two reactants and 64 products
for every rule; the smaller of the two bounds applies, so no request admitted
before is refused now. For the three-class mtDNA model an entry reserves 721
bytes, so 50 entries for 1,000 cells take 36 MB of the 64 MiB Python default.
Replicates times this reservation must fit max_output_bytes (and 2 GiB). The
CRN-R020 message at /budget itemizes the reservation, and its hint names
the smallest max_output_bytes that admits the request.
Strict input
- A file is at most 16 MiB. JSON nesting is at most 48 deep, with the root at depth 0.
- Duplicate keys are rejected, also when JSON escapes give two spellings of
one key. Unknown fields are rejected at every depth.
NaNandInfinityare not JSON, and a literal such as1e400fails with a numeric diagnostic. - Decimal literals parse to the correctly rounded double, as Rust’s
str::parseand Python’sjsondo, so the shortest round-trip text of a double reads back to the same bits. - Syntax and shape are checked first. Semantic checks follow and report every error they find, each with a stable code and a JSON path (diagnostics).
- Hashes are SHA-256 of the exact bytes consumed, never of re-serialized
JSON. Line endings are part of the bytes:
.gitattributeskeeps LF endings in every checkout, and CI runs the contract suite on a checkout made withcore.autocrlf=true. - A request names its model by a path relative to the request’s directory
and by the model’s SHA-256. The path must stay inside that directory after
resolving symbolic links: no empty components, absolute paths,
.,.., drive prefixes, backslashes or NUL bytes.
Limits
describe()["limits"] lists the limits of the current contracts. Models of
model/1.0 accept 4,096 types, 16,384 parameters, 4,096 observables and
65,536 rules; the static methods accept 4,096 instance tuples and 65,536
channels. The rules-model versions keep 64, 1,024, 256, 1,024, 256 and
4,096. See the model reference.
Changing a contract
A change to the shape of a delivered contract needs a new version, and the old version keeps its meaning. A new field in a new version is refused by the versions before it. Schemas are generated, never edited by hand.
Where the old pages went
The earlier pages on the network model, its run request, the reserved result envelope and the separate analysis reports described contracts that the unified engine replaced. Their successors are:
| Earlier topic | Now |
|---|---|
network model/0.1, run/0.1 | model reference; crn-craft convert writes an old model as model/1.0. state/0.1 stays current (above) |
analysis/0.1, 0.2 and analyze-v1 | crn-craft.analysis/1.0 (network analysis) |
result/0.1 and 0.2, archive/0.1 | result contract, archive contract |
ssa-run, tau-request | crn-craft.run/1.0 methods static_direct, next_reaction and tau (methods) |
Results and claims
A simulation request (crn-craft.run/1.0, or an older rules-run version)
produces one result document. crn-craft.result/1.0 has the shape of
rules-result/0.3 plus statistics.quantiles. A request with method fsp
produces crn-craft.fsp-result/1.0 instead (below). crn-craft check
produces crn-craft.check/1.0, a preflight report: valid: true means no
input diagnostic of severity error, and nothing was simulated.
The schemas are crn-craft describe result-1.0, fsp-result-1.0 and
check-1.0. The Python object Result (crn_craft.rules.Result) wraps the document: see the
Python API.
What a result holds
| Field | Content |
|---|---|
schema, sampler | the contract, and the sampler identity of the method that ran. A replay compares equal only under the same identity. |
model_sha256, run_sha256, root_seed | provenance: the hashes of the exact bytes consumed |
types, rules, observables, report_times | names and grid; observables are sorted by name, continuous variables follow |
requested_replicates, completed_replicates, stopped_replicates, events | totals |
termination | completed when every replicate completed or stopped; otherwise the most severe replicate termination |
replicates | one record per replicate: whether it started, termination, events, stop time, events per rule, random words, peak and created instances, optional diagnostic. A replicate that a cancellation or the wall-time limit kept from starting has started: false and zero counters. A cancellation or wall-time limit that comes before the run can still start one replicate per worker thread: such a replicate is recorded as started, ends at its first poll (cancelled or wall_time_limit) and has 0 events and 0 random words |
paths, final_instances, observations | kept series, kept final instances, and tracker and log results |
statistics | mean, sample_variance, mean_standard_error, samples and quantiles (below). Withheld unless every replicate completed or stopped. |
method, continuous | the request’s method with its tolerances, and the names of the continuous columns |
diagnostics | ensemble-level diagnostics (CRN-R050, CRN-R051, CRN-R045) |
The terminations, in the order of crn_craft.rules.TERMINATIONS, are completed,
stopped, event_limit, sampling_limit, instance_limit,
wall_time_limit, cancelled, failed and output_limit.
In Python, simulate() warns with crn_craft.IncompleteEnsembleWarning
when a replicate’s termination is neither completed, stopped nor
cancelled, or when the result ended as output_limit; with
strict=True it raises crn_craft.IncompleteEnsembleError instead
(Python API).
Quantiles
A request may list up to 16 probabilities in outputs.quantiles, strictly
increasing, each in (0, 1). The result’s statistics.quantiles then holds,
for each probability in request order, {"p": ..., "values": ...}: the
quantile over all replicates for every report time and observable, indexed
like mean. The definition is NumPy’s default (linear interpolation,
Hyndman and Fan type 7), and the values equal numpy.quantile bit for bit.
The median is the quantile at 0.5. Quantiles are withheld with the other
statistics. They keep one value per replicate, report time and observable in
memory during the run, which counts against the 2 GiB workspace limit.
The Python helpers write the request field. crn_craft.ensemble asks for
0.025, 0.5 and 0.975 unless quantiles= says otherwise, and the result’s
statistics["median"] and statistics["quantiles"] hold DataFrames. Earlier
request versions refuse outputs.quantiles (CRN-R020 at /schema).
Claims
- A result states what the engine computed, with Monte Carlo error. An exact
method samples the model’s process; it does not remove sampling error.
tau,binomialandhybridare approximate at their declared parameters, and their sampler identities say so. - Statistics describe all requested replicates or none. A truncated or
failed ensemble withholds them (
CRN-R050), because state-dependent truncation biases the completed subset. Report censored paths as such. - Timings, thread counts and file paths are not part of numerical comparisons. For a fixed request and sampler identity the numbers are byte-identical for every thread count.
- A successful numerical run is not biological validation.
Finite state projection
fsp-result/1.0 holds the probability distribution of the model’s species
over the states the projection enumerated: species (the flat species
labels), states, the snapshots per report time, the work and sparse edge
counts, the uniformization rate and numerical_error_certified, which is
false: the tolerance bounds the Poisson-series truncation, not
floating-point error. A snapshot has its time, the probabilities of the
states, the error terms mass_defect, physical_leakage_estimate,
series_tail_upper_bound, discarded_weight_estimate and
roundoff_mass_residual
(chapter 7),
and projected_first_moment and projected_second_raw_moment, the moments
of each species over the projected states only. See Model.fsp in the
Python API.
Saved reports
Result.save("name.md") writes a markdown report and Result.save("name.json")
writes crn-craft.report/1.0, a JSON document with the model, the request and
the results. crn_craft.load_report(path) reads the JSON form back. The
guide teaches both (chapter 4),
and the Python API lists the arguments.
The metadata of the Python result
result.metadata is the result document. Its keys:
| Key | Content |
|---|---|
sampler, termination, diagnostics | what ran, how the ensemble ended, warnings and errors |
events, completed_replicates, stopped_replicates | totals |
rules, observables, types, report_times | names and grid, in result order; rule names also as run.rule_names and result.rule_names |
statistics | mean, sample_variance, mean_standard_error, samples and, when asked, quantiles as a list of {p, values} (in result.statistics, quantiles is a dictionary from probability to DataFrame) |
paths, final_instances, observations | kept series, kept instances, and (with trackers or a log) trackers and logs |
model_sha256, run_sha256, root_seed | provenance |
method, continuous | the request’s method, with the tolerances of hybrid, and the names of the continuous columns (rules-result/0.3 and later) |
In the raw matrices of result.metadata, observables are sorted by name; use
metadata["observables"].index(name). Select the columns of a DataFrame by
observable name instead. The attributes and methods of the Python object are
in the Python API.
Accumulation and report values
Report values are right-continuous: an event at a report time is included.
crn-craft.rules-result/0.1 holds the type, rule and observable names, one
record per replicate (termination, events, stop time, events per rule, random
words, peak instances (including the one that exceeded max_instances) and
created instances, diagnostic), the
observable series of the kept paths, final instances of the kept replicates
(sorted by type and attributes) and, when every replicate completed or
stopped, the mean, sample variance and standard error per report time and
observable. Statistics are accumulated in replicate order (Welford) while the
ensemble runs; only kept series stay in memory. A path’s random words include
product draws, so the event that hits the sampling budget can take
rng_words slightly past it. Terminations: completed, stopped, event_limit,
sampling_limit, instance_limit, wall_time_limit, cancelled, failed,
output_limit; the ensemble reports completed when every replicate completed
or stopped.
Event logs and tracker columns
result.event_columns(replicate) returns the bounded log of one replicate as
an xarray DataArray with dimensions (entry, variable): the observables
after each event, and the coordinates time, rule (the index, -1 for a
leap) and rule_name. Without an argument it returns every log with
dimensions (replicate, entry, variable), padded with NaN (and rule -2)
past each replicate’s length. result.event_frame() returns the DataFrames
of earlier releases: one row per logged event, indexed by entry or by
(replicate, entry). result.tracker_columns(index) returns the scalar
tracker summaries as a DataFrame indexed by replicate id, with NaN for
missing times or peaks. Ragged participant identities, leap multiplicities
and episodes remain in result.observations.
Semantics of observation. Trackers capture zero crossings, last crossing
times, extrema, time integrals and first passage. A tracked interval runs
until the replicate’s stop or horizon. A predicate that evaluates to NaN does
not count as a hit. Episodes keep the configured prefix and summarize omitted
duration and peak. An event log retains up to max_entries selected events
per path and counts omissions; its entries include the rule index,
participant type and attributes, and the post-event observables. Retention
counts enter the admission checks, so use small cohorts for long logs.
A live callback receives fn(replicate_id, event) on native workers.
Returning False stops that replicate. Each path preserves event order.
Callbacks acquire the interpreter lock, and the interleaving across
replicates depends on the scheduler. An exception cancels the run and
propagates. A batch_callback receives chunks of the retained log after the
simulation. The Rust execute_with_observer entry point exposes the same
committed events and supports a per-path stop; the default observer is
compiled away. Ctrl-C and cancel files use cooperative cancellation, and an
interrupted ensemble withholds its statistics.
Archives
An archive is the sealed record of one run: the exact documents consumed and
the result, with hashes. crn-craft run MODEL REQUEST --archive NEW_DIRECTORY
and PreparedEnsemble.archive (Python) write one. crn-craft verify DIRECTORY
and crn_craft.verify_archive check one without simulating. The contracts
are crn-craft.archive/1.0 (the manifest) and crn-craft.archive-check/1.0
(the report of writing or verifying). The schemas are crn-craft describe archive-1.0 and archive-check-1.0.
Archives of the removed network engine (archive/0.1, from simulate) are
not read by this release. Verify them with the release that wrote them.
Files and completion
| File | Content |
|---|---|
model.json | the exact model bytes |
request.json | the exact request bytes, with their original model.path |
result.json | the result as crn-craft run prints it: compact JSON with sorted keys and a trailing newline. It is crn-craft.result/1.0 (or rules-result) for a simulation, and crn-craft.fsp-result/1.0 for an fsp request |
manifest.json | crn-craft.archive/1.0: length and SHA-256 of the three payloads |
COMPLETE | the SHA-256 of the manifest bytes and a line feed, written last |
The output is a new directory, never an overwrite or a merge. Each file is created exclusively. The verifier rejects extra or missing files, duplicates, unknown fields or versions, mismatched lengths or digests, an invalid completion marker and oversized content. Input documents keep the 16 MiB limit of every contract.
The marker certifies that the write finished. A canceled or budget-limited simulation can have a complete archive. If a process is killed before the marker, the directory is not an archive. There is no resume. Integrity checks are not signatures; they do not prove authenticity or protect against a hostile process that replaces files concurrently.
What verification checks
verify checks that the directory has exactly these regular files, that the
marker matches the manifest, the lengths and digests, that the model and
request still prepare, that the result parses strictly and is the engine’s
own serialization, the hashes inside the result, and the relations between
request and result: identity, replicate accounting, terminations, kept
paths and statistics. It does not run the simulation again. To check that a
run reproduces, run the archived request and compare the result bytes.
The report
archive-check/1.0 has these fields, to be read together.
| Field | Meaning |
|---|---|
valid | the archive was written, or verified, without error |
archive_complete | every file, the manifest and the marker are present and consistent |
simulation_complete | the archived result is complete: a simulation that ended completed, or a finite state projection |
termination | the ensemble termination; null for a projection and for an invalid archive |
result | the result’s schema, for example crn-craft.result/1.0 |
model_sha256, run_sha256 | the hashes of the archived bytes |
diagnostics | why the archive is invalid (CRN-E065) |
crn-craft run --archive exits 0 only for a completed simulation.
verify exits 0 for any valid archive, including one that records an
incomplete simulation. Input or preflight failures create no archive. A
failure while writing returns a coded diagnostic and may leave a directory
without a marker, which must not be read as a result.
Replaying an archive
request.json keeps its original model.path, which need not equal the
archive file name model.json. To replay, copy model.json next to a request
whose model.path names it and whose model.sha256 is unchanged, or build a
new request and say that it is new. Numerical comparisons use result.json;
nothing in it depends on timing, thread count or the host.
Provenance
The archive format adapts the durable-write and checksum conventions of
optimization-jobs at cc6b03d594f73d1f3b38f088e7e3bd8663814d75
(crates/optimization-job-api/src/storage.rs). No job protocol or worker
dependency is involved, and no implementation code was copied.
Diagnostics
Every diagnostic contains severity, code, path, message and hint.
Paths use RFC 6901 (~1 for a slash, ~0 for a tilde); the empty path
denotes the root. A type error may name the containing object when the parser
cannot name a missing or unknown child. Messages give detail; the code and the
path are the machine contract. Codes are stable: a number is never reused for
another meaning.
Codes with the prefix CRN-E belong to documents, files, the sampler and the
tools around the engine. Codes with the prefix CRN-R belong to models and
run requests; they are listed below the first tables. A failed check
reports every error it finds. Parsing stops at the first syntax or type error
of a document, and semantic validation accumulates.
Documents, files and tools (CRN-E…)
| Code | Meaning | Typical repair |
|---|---|---|
| CRN-E001 | Invalid JSON, encoding or trailing content | Supply one UTF-8 JSON document |
| CRN-E002 | Duplicate JSON key at any depth | Keep one value per decoded key |
| CRN-E003 | Wrong type, unknown or missing field, schema version or enum variant | Use the generated schema (crn-craft describe KIND) |
| CRN-E004 | Input depth or size limit, or a model collection limit | Reduce size or depth |
| CRN-E015 | Non-finite or out-of-domain number | Use the required finite domain |
| CRN-E030 | Input or output filesystem or stream failure | Supply a readable regular file or a writable stream |
| CRN-E031 | Unsupported command or wrong arguments | Use --help |
| CRN-E033 | A network model (crn-craft.model/0.1) given where a rules or 1.0 model is read (run, check MODEL REQUEST, crn_craft.rules.prepare, finite state projection), reported at /schema | Convert it with crn-craft convert MODEL or crn_craft.convert; crn_craft.ensemble, crn_craft.prepare and Model.from_dict convert it themselves |
| CRN-E041 | Invalid state for analyze or the projection: a missing or extra name, or an invalid count | Name every species with a valid count |
| CRN-E044 | crn-diffsol only: the ODE trajectory of a network model passes a species’ population_limit | Stop earlier or revise the limit; the ODE never clips a state |
| CRN-E050 | The export target cannot preserve a requested feature | Keep to the documented subset |
| CRN-E051 | An exported coefficient cannot be halved exactly in f64, reported at /rules/i/rate | Rescale the model; no source is emitted |
| CRN-E065 | Archive I/O, integrity, size or relational failure | Keep the evidence; use a new directory and verify the complete file set |
| CRN-E070 | Finite state projection: capacity, work, normalization, output or interruption; for a prepared projection (crn_craft.prepare_fsp) also its state, edge, rate-table and intervention budgets, max_work, the midpoint rule’s stall, a BDF step that cannot advance the clock, a sparse LU factorization whose memory bound exceeds max_factor_bytes (at /projection/memory), a factorization failure (/projection/solver) and a stationary law with invalid probabilities or a residual above its tolerance (raised in Python as RuntimeError); for forward sensitivities (crn_craft.sensitivities) also an augmented generator above 250,000 rows or 2,000,000 entries | Lower the bounds or raise max_states within the cap; raise max_factor_bytes within the memory of the machine |
| CRN-E071 | Prepared projection input it cannot represent: an initial law outside the bounds, a decrement below zero, an outcome outside the prepared states, reactant combinatorics beyond the solver range, a signal on a count-dependent rule, a negative or non-finite rate, a stationary law asked of a generator with another number of closed communicating classes than one or of a state outside every closed class, a retained state set that is empty, larger than max_states or has a tuple of another length or outside the bounds, and for forward sensitivities generator bindings of another size, with signals or stop states, more than 16 directions, a nonpositive or nonfinite difference step, or an invalid initial state, report time or tolerance (at /projection/sensitivities) (raised in Python as ValueError, or OverflowError for a multiplicity above the largest double) | Revise the bounds, the initial law, the protocol or the rates |
| CRN-E080 | ODE right-hand side: domain, unsupported smooth extension or solver failure; a negative propensity | Revise the model; see crn-diffsol |
| CRN-E090 | Importer: syntax, unsupported semantics, missing explicit convention or resource failure | Follow the message; pass convention= |
None of these codes denotes biological validation or a certified floating-point error bound.
Reading a network model
crn-craft check, analyze, convert and export read a network
crn-craft.model/0.1 through the converter. Its checks report these codes:
| Code | Meaning |
|---|---|
| CRN-E010 | Invalid identifier |
| CRN-E011 | Duplicate name, or a species and parameter with one name |
| CRN-E012 | Unknown species name |
| CRN-E013 | Stoichiometry outside 1 to 2147483647 |
| CRN-E014 | Unknown parameter name |
| CRN-E016 | Negative population or insufficient population limit |
| CRN-E032 | The document given to the converter (crn-craft convert, crn_craft.convert) is a crn-craft.model/1.0 or crn-craft.rules-* document, which needs no conversion; reported at /schema |
The converter reports a model that the unified model cannot hold with
CRN-R016.
Warnings of analysis
| Code | Meaning |
|---|---|
| CRN-W001 | A species has a net-producing reaction and no net-consuming one (at /species/i); analyze drops it for a species with a proven conservation bound. It does not prove unboundedness |
| CRN-W002 | A reaction’s rate is the constant 0 (at /reactions/i) |
| CRN-W003 | A reaction has no net population effect (at /reactions/i) |
| CRN-W010 | Exact conservation analysis exceeds 64 species or 256 reactions: no laws are claimed or excluded |
| CRN-W011 | Checked i128 conservation arithmetic exceeds its range: no partial basis is reported |
| CRN-W012 | The nonnegative cone exceeds 64 species or 256 reactions |
| CRN-W013 | The cone exhausts its intermediate-ray or work cap: only sound basis bounds remain |
| CRN-W014 | Checked i128 cone arithmetic overflows: no partial rays or bounds are emitted |
| CRN-W015 | Internal verification of the cone failed: report a defect, no cone result is trusted |
Retired codes
The network engine is gone, and so are the codes that only it reported. They
are not reused: CRN-E020, CRN-E021, CRN-E022, CRN-E023, CRN-E040,
CRN-E042, CRN-E043, CRN-E060, CRN-E061, CRN-E062, CRN-E064,
CRN-E067 and CRN-E085. CRN-E044 is left only in crn-diffsol. Their
replacements are the CRN-R codes: a run request, budget or method problem is CRN-R020, a
numerical failure CRN-R030 and CRN-R031, a budget stop CRN-R040 to
CRN-R045, and a document of the wrong family CRN-E033 or CRN-R020 at
/schema.
Models and run requests (CRN-R…)
The engine for dynamic, attributed species (model reference)
shares CRN-E001–CRN-E004 for JSON input and the read error CRN-E030, and
has its own codes: CRN-R010 names,
CRN-R011 unknown types, CRN-R012 expressions and scopes, CRN-R013 rule
shapes and product attributes (in crn-craft.model/1.0 also a pattern
count outside 1 to 2,147,483,647 and a higher-order pattern over an
attributed type or with where or factor), CRN-R014 initial state, CRN-R015 model
limits (64 types, 1,024 parameters, 256 observables and 1,024 rules up to
rules-model/0.4; 4,096 types, 16,384 parameters, 4,096 observables and
65,536 rules in crn-craft.model/1.0), CRN-R016 a network model that the
converter (crn-craft convert, crn_craft.convert) cannot write as a rules
model yet (no reaction, more than 64 product molecules in a reaction, an
initial count above 2^53, or a population limit; the path points into the
network model), CRN-R017 a model that has no flat view, which finite
state projection (and from 0.7.0 analysis, ODE and export) needs: a model
whose products can create attribute tuples during a run, with random
product attributes, a whole-rule propensity over a type with several tuples
or above the static lowering limits (at /rules), with an atp block (at
/atp) or with continuous variables (at /continuous),
CRN-R020 run requests (including method, tracker, log and version
gates, a request with method fsp where a simulation is expected (at
/method), the fsp request’s version (at /schema), max_states,
tolerance and bounds (a missing bound, a bound below the initial count,
or an unknown species label, at /method/bounds/LABEL), a crn-craft.model/1.0 model with a rules-run request, a
higher-order rule with tree, mtdna_direct, binomial or a generated
rates kernel, outputs.quantiles in a request before crn-craft.run/1.0
(at /schema), more than 16 or not strictly increasing quantile
probabilities in (0, 1), a quantile buffer above the 2 GiB workspace limit
(at /outputs/quantiles), method.selector in a request before
crn-craft.run/1.0 (at /schema), a generated event loop or rates kernel
with a Static Direct selector other than linear, also when auto picks one
(at /method/selector), and a generated-kernel fingerprint mismatch),
CRN-R030 numerical
failures during a replicate (with the selectors of crn-craft.run/1.0 also
a non-finite total, a composition or acceptance draw rounded to its bound,
and a propensity outside its RSSA-CR bounds; at /time a clock that fails to
advance: every rules-run version fails at the first positive wait below
half an ulp of the time, every method under crn-craft.run/1.0 accepts such
a wait and fails only after 1,000,000 consecutive steps without an advance), CRN-R031 weights below
53-bit resolution (in the tree a rule or instance weight; in Static Direct
and its fallbacks, with every selector, a channel below 2⁻⁵³ of the total or
lost in the total’s pairwise sums; with RSSA-CR the smallest positive
propensity of a channel’s population box, so use tree or rescale),
CRN-R040–CRN-R045 event, sampling, instance, wall-time, cancellation and
output limits, and the warnings CRN-R050 for an incomplete ensemble and
CRN-R051 for a requested specialization that did not apply (an
mtdna_direct fallback, or an explicit sparse_trackers: true without an
eligible tracker; the rules-run/0.6 default does not warn).
The CRN-R codes at a glance
| Code | Meaning |
|---|---|
| CRN-E001–E004 | malformed JSON, duplicate keys, unknown fields or wrong types (E003), size limits |
| CRN-R010 | invalid, reserved or duplicate name; observable shadowing a parameter |
| CRN-R011 | unknown type |
| CRN-R012 | expression syntax, unknown name, out-of-scope name or random draw outside products; an independent variable’s derivative that reads an observable or a dependent variable |
| CRN-R013 | unsupported rule shape, missing or unknown attribute, bad copy; both or neither of rate and propensity, where or factor on a propensity rule’s reactant; lower_bound without on_bound or the reverse |
| CRN-R014 | invalid initial count or attribute; a continuous variable’s initial value or bound that is not finite, or an initial value below its bound |
| CRN-R013 and R020 | for model/1.0: a pattern count outside 1 to 2,147,483,647, or on an attributed type or with where or factor (R013); a higher-order rule under a method that refuses it (R020 at /method) |
| CRN-R015 | model size limit (the limits; also 64 continuous variables); a field used before its model version (atp in 0.1, propensity and continuous in 0.1 or 0.2, independent before 0.4); atp together with continuous |
| CRN-R016, R017 | a network model the converter cannot write (R016); a model without a flat view, which finite state projection, analysis, ODE export and GillesPy2 export need (R017) |
| CRN-R020 | invalid run request (hash, path, grid, ensemble, budget, method, selector, quantiles, tracker, log or version gate; generated-kernel fingerprint mismatch); under run/1.1, an invalid protocol (fields, times, probabilities, conflicting assignments) or a method that does not accept a protocol (at /method) |
| CRN-R030 | negative or non-finite rate, factor, weight or product attribute; overflow; under run/1.0, 1,000,000 consecutive waits that do not advance the clock; under run/1.1, a protocol count change below 0 or above the count limit (at /protocol/actions/i) and more pending completions than the budget; an invalid spatial_turnover setup |
| CRN-R031 | weight below 53-bit resolution (Static Direct: a channel below 2⁻⁵³ of the total; spatial_turnover: a positive weight below 16 × 2⁻⁵³ of its total) |
| CRN-R040–R045 | event, sampling, instance (including a count above 2⁵³), wall-time, cancellation and output limits |
| CRN-R050 | warning: incomplete ensemble, statistics withheld |
| CRN-R051 | warning: a requested specialization did not apply (mtdna_direct could not certify the model and ran Static Direct, or an explicit sparse_trackers: true found no eligible tracker; the rules-run/0.6 default does not warn); the message gives the reason |
Network analysis
Every closed model has a flat view: its species, its channels, the change
each channel makes and the channels whose rates each change affects.
crn-craft analyze MODEL [STATE] and Model.analyze() (Python) report the
structure of that view as crn-craft.analysis/1.0 and run no simulation.
Finite state projection, the ODE right-hand sides of crn-diffsol and the
GillesPy2 export read the same view. A model has a flat view when its set of
species is closed: no product creates a new attribute tuple during a run, no
product attribute is random, and there is no atp block or continuous
variable. Any other model is refused with CRN-R017.
This page replaces the former description of compiled network models, which
were removed with the network engine in release 0.7.0. Network models of
crn-craft.model/0.1 are still read: they are converted first
(crn-craft convert), and then every statement below applies to the converted
model.
Indices and labels
Species and channels are indexed from zero. The species are the labels of the
flat view: the declared name of an attribute-free type, and T{a=1,b=0.5}
for an attributed type. For a converted network model they are the network’s
species in declaration order, and the channels are its reactions in
declaration order.
Every reaction lists sorted sparse reactants, products and net_changes,
each term {species, coefficient}. Net coefficients are products minus
reactants with zeros omitted. They are the columns of the stoichiometric
matrix N (species by reactions), not rows and not propensity multipliers.
reads lists the species that the channel’s rate reads. dependencies[j]
is the sorted, unique list of the channels whose rates can change when channel
j fires: the channels that read a species j changes. It describes rate
invalidation only; a scheduler must also redraw the channel that fired.
The report
crn-craft.analysis/1.0 has success, simulation_available (always
false), model_sha256, an optional state_sha256, analysis and
diagnostics. An input or numerical failure has success: false and
analysis: null. A successful analysis holds:
| Field | Content |
|---|---|
species, reactions, dependencies | the structure above |
initial_counts, evaluation_counts, propensities | the propensity of every channel, evaluated at the evaluation state: the initial counts, or the counts of a supplied crn-craft.state/0.1 document, which names species by label |
conservation | the linear conservation laws (below) |
nonnegative_conservation | the nonnegative conservation cone: extreme rays, work and limits |
linkage | complexes, linkage classes, deficiency and weak reversibility |
initial_class_upper_bounds | the best available bound of each species in the initial conservation class |
model_sha256 and state_sha256 hash the raw supplied bytes. The evaluation
state need not lie in the initial conservation class, and the report makes no
reachability claim.
Linear conservation laws
The analyzer computes the rational left nullspace of N by checked integer row elimination with gcd reduction, then checked rational back substitution. Each primitive integer basis row l satisfies lᵀN = 0 and is verified against the sparse columns. A limited sequence of elementary combinations exposes nonnegative rows where available. The rows span the rational conservation space, not necessarily the integer lattice of laws. Coefficients and the initial total lᵀx₀ are decimal strings, so 128-bit integers survive JSON readers that use doubles.
| Status | Meaning |
|---|---|
exact | a complete rational basis, with exact residuals and totals in checked i128 arithmetic |
size_limit | more than 64 species or 256 channels: no basis or rank is computed (CRN-W010) |
arithmetic_overflow | a checked i128 operation overflowed: nothing partial is kept (CRN-W011) |
A size or overflow status leaves the structure and the propensities
available, and success stays true. It does not mean that no law exists.
A model without reactions has the identity basis, and a full-rank network
an empty one.
For a nonnegative row, each positive coefficient gives
floor(initial_total / coefficient) as an upper bound for that species in the
initial class. A signed row gives no count bound. A null bound means
“not proved”, not “unbounded”. The enzyme example has the laws E + ES and
S + ES + P, which bound all four species.
The nonnegative cone
The cone of nonnegative conservation laws is computed separately, by exact
extreme-ray enumeration with limits of 64 species, 256 channels, 4,096
intermediate rays and 2,000,000 work units. Its status, limits and work count
are in the report. When the cone is exact, initial_class_upper_bounds
uses its bounds, and otherwise the sound bounds of the basis.
conservation.initial_class_upper_bounds keeps the basis-only meaning.
Exhausting a limit is CRN-W012 to CRN-W014, and a failed internal check
CRN-W015. The linkage analysis adds the deficiency of the network; see
the analysis notes.
Moved
| Earlier | Now |
|---|---|
CompiledNetwork::compile, analyze_bytes on a network model | crn_craft::analyze_bytes and analyze_files read every model version; the analysis functions take a &crn_craft::rules::FlatView |
crn-craft analyze-v1, analysis/0.1 and 0.2 | crn-craft analyze, analysis/1.0 |
topology_sha256, mass_action_coefficient, propensity_in_scheduler_state, generated kernels | parameter sweeps; crn_craft.compile_loop |
| the validation of the conservation analysis | validation/check_structure.py and validation/merge/check_analysis_references.py |
GillesPy2 reference export
M1b exports model source for GillesPy2 1.8.3, with a runtime version guard. It is an optional reference tool; the Rust core does not import, link or execute GillesPy2.
cargo build --release --workspace --locked
./target/release/crn-craft export models/examples/enzyme-mechanism.model.json gillespy2 > export.json
python3 -c 'import json; from pathlib import Path; r=json.loads(Path("export.json").read_text()); Path("reference.py").write_text(r["artifact"]["source"])'
python3 -m venv .venv-reference
.venv-reference/bin/pip install -r validation/reference-requirements.txt
.venv-reference/bin/python -c 'from reference import build_model; print(build_model())'
The JSON envelope contains success, raw model SHA-256, diagnostics and an optional artifact. The artifact has generated Python source, target/version, original-to-target species and reaction aliases, and numerical limitations. A failure never emits a partial source file. build_model() constructs the model; it does not choose a solver, seed or time grid. Use GillesPy2’s NumPySSASolver for the tested reference path.
Supported semantics
The input is any model version that has a flat view (a closed model; CRN-R017 otherwise): crn-craft.model/1.0, a rules-model, or a network crn-craft.model/0.1 through the converter. Each species label becomes one target species and each channel one reaction. A channel whose rule has a constant rate (reading no observable) and takes at most two molecules is GillesPy2 mass action, including catalysts and zero coefficients; the constant, times the pattern factor, is one frozen target rate parameter per channel. Any other channel (a rate that reads an observable, a whole-rule propensity, more than two molecules) is a custom propensity string: the rule’s expression with parameter values inlined, each observable as the weighted sum of its species and ^ as **, times the falling factorial n(n − 1)…/k! per reactant for a rate rule, or times one availability factor x/(x + 1e-300) per molecule taken for a whole-rule propensity. Product stoichiometry retains its integer values. Species become S0, S1, …; parameters become K0, K1, …; reactions become R0, R1, …, avoiding target/Python reserved-name collisions; the aliases name the rules (rule[j] for the channels of a rule with several).
| Source propensity | Target rate constant at volume 1 |
|---|---|
| c | c |
| c × A | c |
| c × A × B | c |
| c × A × (A−1) / 2 | c / 2 |
CRN-craft’s coefficients already use stochastic counts. Target volume is deliberately fixed at one even when source Omega differs; Omega does not automatically rescale source coefficients. GillesPy2 1.8.3’s elementary homodimer expression omits the factorial divisor, so its rate constant must be halved. This convention was checked in the installed package’s gillespy2/core/reaction.py and against its actually generated propensity expressions. Package provenance is recorded with the validation evidence. The GillesPy2 project and basic usage documentation describe the target API.
Rejected with CRN-E050, without a partial source: comparisons, logic and functions in an expression (GillesPy2’s Python solvers have no exp, its C++ solver no min, max or abs, and its expression printer drops comparisons), observables reduced other than by sum, more than 64 molecules of one species in a custom propensity, a negative constant rate, and a stop condition, which GillesPy2 cannot apply. Population limits of a network model are refused by the converter (CRN-R016). Homodimer coefficients whose halving would underflow or round inexactly are rejected with CRN-E051. No model feature is silently removed. Until release 0.6.0 the exporter refused the Hill and Michaelis–Menten laws; since 0.7.0 they are custom propensities.
Numerical boundary
This is a stochastic-propensity translation, not an ODE exporter or a complete execution-contract translation. Target ODE coefficients, live event/output/time budgets, checked i64 updates, underflow diagnostics and cross-runtime bit identity are not preserved. The target solver uses floating-point populations; subsequent counts can leave its exact range even if initial counts are supported. Extreme target expressions can overflow or underflow differently from CRN-craft’s scaled evaluator. Use representable reference fixtures and inspect target results; do not infer universal equivalence from successful source generation.
The exporter intentionally creates no run document or simulation result. Additional targets need separate reference fixtures and explicit convention and limit checks.
Validation
validation/check_export.py compiles and imports the generated source, constructs actual pinned GillesPy2 models and checks initial counts, stoichiometry, alias mappings and target volume. It evaluates the package’s own generated propensities for all 51×51 small-count pairs on a fixture covering every supported order, a catalyst, zero rates, parameter substitution, symbol collisions and non-unit Omega. It compares them with exact integer combinations and CRN-craft CLI evaluation. The shipped example models are also checked, including the custom propensities of the Michaelis–Menten and repressilator examples against the exact rate laws and the engine’s rates, and a rate with a function and a stop condition must be refused with CRN-E050.
A two-trajectory seeded immigration–death run is a reference SSA smoke test only. It establishes that generated source works with the tested target solver; it does not validate or benchmark CRN-craft simulation. Normal and Python -O reports must match byte-for-byte. See the iteration evidence for comparison counts and errors.
CRN-craft architecture
CRN-craft has one engine for well-mixed stochastic chemistry, in the crate
crn-craft. A model declares species types, with or without attributes,
rules, observables and an optional stop expression. An ordinary reaction
network is a model whose types have no attributes. One model format, one
request and result contract, one expression language, one random number
generator (ChaCha8) and one set of diagnostics serve every method. A request
is bound to the exact bytes of its model, and every result carries its
termination, its sampler identity and the hashes of what it consumed. The
technical report covers the numerical methods and the
validation evidence.
Up to release 0.6.0 there were two engines: a network engine with fixed species lists and a rules engine for attributed species. Release 0.7.0 merged them into the one engine described here. The merge plan and the implementation log record how.
Package boundaries
flowchart TB
CLI["crates/crn-craft-cli: the crn-craft command"] --> Engine
Py["bindings/python and python/crn_craft"] --> Engine
Facade["crates/crn-craft-rules: deprecated facade"] -.->|"pub use crn_craft::rules::*"| Engine
Loops["generated event loops, compiled by the user"] -.-> Engine
Ext["integrations: jobs, diffsol; parameter worker"] -.-> Engine
subgraph Engine["crate crn-craft"]
Rules["rules: model, expressions, methods, results"]
View["rules::FlatView"]
Tools["fsp, analysis, kinetics, export"]
Archive["archive"]
Base["strict_json, diagnostic, sampling, unified"]
Rules --> View
View --> Tools
Rules --> Archive
end
| Component | Responsibility |
|---|---|
crates/crn-craft | The engine. crn_craft::rules holds the model contract, the expression language, preparation, every simulation method, observation and the result contract. Around it: the flat view and the features that read it (finite state projection, network analysis, ODE kinetics, GillesPy2 export), sealed archives, the converter for network models, strict JSON, diagnostics, samplers and the discovery and check entry points. |
crates/crn-craft-cli | The crn-craft command: reads files, calls the engine, prints JSON and schemas. |
crates/crn-craft-rules | A deprecated facade: pub use crn_craft::rules::*;, so code written for 0.6.0 against crn_craft_rules::X still compiles. It also holds the generator examples generate_rules_kernel, generate_rules_loop and benchmark_rules. |
bindings/python, python/crn_craft | The Python package: builder, prepared ensembles, pandas and xarray results, reports, importers, the experiment reader, the single XML guard (_xml.py, the only module that parses XML), the compiled-loop driver and python -m crn_craft. The numerical loops run in Rust. |
integrations/jobs, integrations/diffsol, validation/parameter-optimization/worker | Optional fcmaes job objectives, BDF integration with forward sensitivities, and a benchmark worker. Each has its own workspace and lockfile. |
The engine has no dependency on Python, job infrastructure or diffsol, and it forbids unsafe code.
Contracts
Rust types define every JSON schema. crn-craft describe KIND prints one,
and the files in schemas/ are generated from the same types.
Contracts lists them all; in short:
| Contract | Role | Read by |
|---|---|---|
crn-craft.model/1.0 | the model (model reference) | every command |
crn-craft.run/1.0 | the request: a simulation method, or fsp | run, check |
crn-craft.result/1.0 | the result of a simulation request (result contract) | written by run |
crn-craft.fsp-result/1.0 | the result of an fsp request | written by run |
crn-craft.check/1.0 | whether run would accept the documents | written by check |
crn-craft.analysis/1.0 | structure, conservation laws and bounds | written by analyze |
crn-craft.archive/1.0, archive-check/1.0 | a sealed run and its verification (archive contract) | run --archive, verify |
crn-craft.import/1.0, export/0.1, state/0.1, report/1.0, describe/1.0 | importer report, GillesPy2 export, a state for analyze, the file of Result.save, discovery | see contracts |
Still read, unchanged:
crn-craft.rules-model/0.1to0.4andcrn-craft.rules-run/0.1to0.6. Their results arerules-result/0.1to0.3and replay byte for byte (crates/crn-craft/tests/stored_requests.rsandstatic_direct_defaults.rscheck the stored requests on every build). Arules-model/0.4document means whatmodel/1.0means, with the smaller limits of therules-modelversions.checkreportsrules-check/0.1for arules-modelalone.- The network
crn-craft.model/0.1, through the converter (below).
No longer read: the network engine’s requests and results (run/0.1,
ssa-run, tau-request, result/0.1 and 0.2, ssa-result,
tau-result, fsp-result/0.1), analysis/0.1 and 0.2, check/0.1, and
archive/0.1 with its check report. Their schema files are gone.
Version dispatch follows the schema string. A model/1.0 model needs a
run/1.0 request; a rules-model model runs under either request family.
The rules-run versions refuse every field that arrived with 1.0
(method.selector, outputs.quantiles, the fsp method) with CRN-R020 at
/schema. Inside the engine, 1.0 is the last variant of each ordered version
enum, so every version test gives a 1.0 document the meaning of the newest
rules-* version.
Strict parsing rejects duplicate keys, unknown fields, null for a present
optional field, and documents over 16 MiB or 48 levels deep. Syntax and shape
errors stop parsing; semantic validation reports every error it finds, each
with a stable code and a JSON path (diagnostics). Hashes
are SHA-256 of the exact bytes consumed.
From documents to results
flowchart TB M["model bytes"] --> C["compile: types, patterns, classes, expressions, observables, stop"] R["request bytes"] --> P["prepare: method, budgets, outputs, admission"] C --> P P --> T["tree: dynamic instances"] P --> L["lower to a flat network: species, channels, changes, dependencies"] L --> SD["static_direct with a selector"] L --> NR["next_reaction"] L --> MD["mtdna_direct, certified at preparation"] L --> AP["tau, binomial, hybrid, thinning"] T --> O["observation and reduction in replicate order"] SD --> O NR --> O MD --> O AP --> O O --> Res["result/1.0, or rules-result for a rules-run request"]
crn_craft::rules::prepare validates exact model and request bytes and
builds an immutable Prepared run; execute runs it. Preparation parses
the expressions, resolves patterns into classes, compiles stop and
first-passage predicates into bytecode and checks the memory reservation of
the request. A closed model, one whose set of attribute vectors cannot grow
during a run, is lowered to a flat network: species, channels, the count
change of each channel, the species each rate reads and the channels each
firing affects. The rates of the lowered network are compiled into flat
programs with the parameters folded in. A subexpression that several rate
programs of one model share (the vacancy term of a builder model’s
whole-rule propensities, for example) is computed once per state, by the
same operations in the same order, so every rate keeps its bits.
| Method | Execution and scope |
|---|---|
tree | Exact Direct over dynamic attributed instances; the default method. Instances may change identity and product attributes may be random. Refuses higher-order rules. |
static_direct | Exact Direct on the lowered network, with a selector (below). The generic exact method for closed models. |
next_reaction | Exact Gibson–Bruck clocks on the lowered network; the dependency lists name the clocks to update. |
mtdna_direct | Opt-in exact specialization for the fixed three-class mtDNA structure. If preparation cannot certify the model, Static Direct runs and a CRN-R051 warning says why. Refuses higher-order rules. |
thinning | Exact thinning for models with the ATP block. |
tau, binomial, hybrid | Approximate methods with their own sampler identities: adaptive Poisson leaps (Cao–Gillespie–Petzold) with exact fallback; binomial splitting for single-parent unit births and deaths on a fixed step; piecewise-deterministic simulation of continuous variables. |
fsp | Not a simulation: the finite state projection of a closed model, in a run/1.0 request (below). |
Exact methods describe the methods; the model reference the language.
Static Direct and its selectors
Each Static Direct event recomputes only the rates the last firing affects,
draws a waiting time and selects a channel. Rates are compiled programs
with dedicated forms for the converted Hill and Michaelis–Menten laws and
for products of a value with constants and counts; a stop of the form
T > 0 && P >= f * T over sums of observables has its own form too; count
factors are precomputed per channel; count updates apply in one pass and undo
themselves on an error. A positive channel below 2⁻⁵³ of the total fails the
replicate (CRN-R031), and a negative or non-finite rate fails it
(CRN-R030). Under run/1.0 a positive wait too small to move the clock is
accepted, and 1,000,000 such steps in a row fail with CRN-R030; every
rules-run version fails at the first.
The selector chooses how the next channel is found. Every selector samples the same law and uses the random stream in its own way, so the sampler identity names it.
selector | Selection |
|---|---|
linear | a scan in channel order over running totals that resume at the first changed channel. The only selector of the rules-run versions. |
composition_rejection | groups by the binary exponent of the rate, a group by mass, a member by rejection |
sorting | a scan in a learned order |
rssa_cr | candidates from upper bounds of the rates over population intervals, accepted against lower bounds or the exact rate |
auto | the default of run/1.0: RSSA-CR from 8 channels when no rate reads two or more species (from 128 channels when the populations start small), composition–rejection from 128 channels, otherwise the linear scan |
auto decides at preparation from the initial counts, and
describe()["selectors"]["auto"] lists its thresholds. The selector tables
are reused between the replicates of a worker thread.
The flat view
crn_craft::rules::FlatView is a read-only view of a lowered model, built
with the same lowering that the static methods run. Its species are labels:
the type name for an attribute-free type, T{a=1,b=0} for an attributed
one; for a converted network model they are the network’s species in order,
and the channels are its reactions. FlatView::propensity evaluates a
channel with the engine’s own arithmetic, so a feature that reads the view
sees the rates that Static Direct samples. A model without a closed set of
species (products that create attribute vectors, random product attributes,
an ATP block, continuous variables) has no view and is refused with
CRN-R017.
flowchart LR Bytes["any model version"] --> V["FlatView"] V --> FSP["fsp::v1: run/1.0 with method fsp, fsp-result/1.0"] V --> AN["analysis: conservation, cone, linkage, analysis/1.0"] V --> KI["kinetics: ODE right-hand side and Jacobians"] V --> EX["export: GillesPy2 source"]
- Finite state projection (
fsp.rs, modulefsp::v1): enumerates the states within per-species bounds, propagates the distribution by uniformization and reports leakage and error terms separately. A state where the model’sstopholds is absorbing. - Prepared projections (module
projection): the engine of the Pythonprepare_fsp. It enumerates the states reachable inside the bounds from an initial law, with scheduled interventions, once per topology; builds the generator per parameter binding in compressed sparse column form; applies interventions; propagates by uniformization, the exponential midpoint rule and a variable-order implicit integrator (NDF orders 1 to 5,bdf); and solves stationary laws per closed communicating class (stationary). It shares the flat view withfsp::v1but not its enumeration, budgets or result contract. The implicit integrator and the stationary solve reach their sparse direct solver through the traitSparseLinearSolver(symbolic analysis with a memory bound, numeric factorization, solve); no implementation lives in the crate, whose tests use a dense test double. The Python binding (bindings/python) implements it on faer’s sparse LU, so faer is a dependency of the extension module only, not of the engine crates. - Analysis (
analysis.rs,conservation.rs,cone.rs,linkage.rs): exact conservation laws, the nonnegative conservation cone, linkage classes and deficiency, and the propensities at a state (network analysis). - Kinetics (
kinetics.rs): the right-hand side of the macroscopic ODE and its state and parameter Jacobians, from dual-number evaluation of the rule expressions.crn-diffsolintegrates them. At most 64 species, 32 parameters and 256 channels. - Export (
export.rs): GillesPy2 source. A constant rate of at most two molecules is mass action; anything else is a custom propensity string. What GillesPy2 cannot evaluate is refused withCRN-E050.
Analysis and export build the view with every attribute-free type present, so a species that starts at zero and is never produced keeps its channels.
Network models and the converter
crn_craft::rules::convert::from_network (crn-craft convert,
crn_craft.convert) turns a network crn-craft.model/0.1 into
model/1.0. Each species becomes an attribute-free type with a count
observable of the same name; each reaction becomes one rule; mass action
becomes a rate; Hill and Michaelis–Menten laws become whole-rule
propensity expressions in a stable form; stoichiometry above one becomes a
pattern count. Names that collide with function names are renamed, and the
model’s description lists the renamings. Population limits and networks
without reactions are refused with CRN-R016. The network model’s own
validation runs inside the converter, so an invalid network keeps its
diagnostics. check, analyze and export convert on the fly; run
refuses a network model with CRN-E033.
Random streams and reproducibility
Every replicate draws from its own ChaCha8 stream. The key is SHA-256 of the
domain crn-craft.rules/0.1 and the root seed; the replicate index is the
stream id. A 53-bit uniform is the high 53 bits of a 64-bit word times 2⁻⁵³.
The exponential waits use the inverse transform or the Ziggurat sampler
(tables adapted from the Julia ecosystem), and the leap methods share one
Poisson sampler (sampling.rs). A completed numerical result depends on the
input bytes, the sampler identity and the seed, never on the thread count.
A changed request changes its hash. Timing, cancellation and wall-time
limits can change which work completes, and are outside fixed-work
reproducibility.
Parallelism and observation
An ensemble claims replicate ids from a shared counter. A window of four replicates per worker limits how far workers run ahead, and results reduce in ascending id order, also the per-replicate values that quantiles need. Trackers, event logs and Rust observers run on the native workers. Events of one replicate are ordered; callbacks from different replicates can interleave. An observer that always continues leaves the result byte-identical. Reports are right-continuous: an event at a report time contributes the post-event state.
Budgets, cancellation and errors
A request states its budgets: events, sampling steps and instances per replicate, threads, output bytes and an optional wall time. Admission reserves the memory a request can need, within a 2 GiB workspace, before anything runs. Workers poll cooperatively every 1,024 events: the cancellation flag, the cancel file and the wall clock. The finite state projection polls the flag at every poll and the file and the clock at the first and every 1,024th.
Each replicate records how it ended: completed, stopped, event_limit,
sampling_limit, instance_limit, wall_time_limit, cancelled, failed
or output_limit. Ensemble statistics, quantiles included, are withheld
unless every replicate completed or stopped (CRN-R050). A result over its
output budget drops kept paths, statistics, observations and kept instances
but keeps the replicate accounting; if that still does not fit, the call
fails with a coded error.
Errors are Diagnostic { severity, code, path, message, hint } values with
stable codes (diagnostics). They stay structured through
Rust, the CLI and Python, where they surface as CrnError. Python runs
native calls off the GIL and checks for signals every 50 ms, so Ctrl-C
cancels through the same control. A callback that blocks also blocks Ctrl-C.
Archives
crn-craft run MODEL REQUEST --archive NEW_DIRECTORY seals a run as
crn-craft.archive/1.0: the exact model and request bytes, the result as
run prints it, a manifest with the length and SHA-256 of each file, and a
completion marker written last. crn-craft verify DIRECTORY checks the files
and digests, prepares the inputs again and checks the relations between
request and result: identity, every record, the aggregates and the
statistics, which are recomputed bit for bit when every path is kept. A
complete archive can hold an incomplete simulation. Integrity checks are not
signatures. Archive contract
Command line and Python
crn-craft describe [KIND]
crn-craft check MODEL [REQUEST]
crn-craft run MODEL REQUEST [--archive NEW_DIRECTORY] [--cancel-file PATH]
crn-craft verify DIRECTORY
crn-craft analyze MODEL [STATE]
crn-craft convert MODEL
crn-craft export MODEL gillespy2
rules and rules-check are aliases of run and check. describe
prints crn-craft.describe/1.0; the fields of 0.6.0’s rules discovery are
under legacy.rules. python -m crn_craft has the same commands.
import crn_craft as crn gives the API: Model, ensemble, prepare,
load, check, convert, describe, load_example, read_sbml,
read_bngl, compile_loop, loop_source, archive, verify_archive,
load_report, CrnError and CompiledLoopError. These names write the 1.0
contracts, ask for the quantiles 0.025, 0.5 and 0.975 by default and leave
the selector to auto. crn_craft.rules is the 0.6.0 module under its old
name: the same names with the 0.6.0 defaults, the rules-* documents and the
linear scan. It writes a 1.0 document only when a call asks for a 1.0
feature, and a Static Direct request written that way names
"selector": "linear", so 0.6.0 code keeps its documents, hashes and
results. The
Migrating lists the differences.
Prepared runs, parameter binding and generated code
| Route | Reuse |
|---|---|
Prepared::bind_parameters (Python run.bind_parameters) | A new prepared run with other parameter values and the same request and seed. It serializes and prepares the bound model again, because parameters can change attributes, projections and topology. Its hashes cover the bound documents. Parameter sweeps |
| Generated rates kernel | Rust source for the rates and projections of one lowered Static Direct model (constant and vacancy rates, weighted sums), run by the engine’s scheduler. Rust only. |
| Generated event loop | Rust source for the whole Static Direct event of one model, up to 1 MiB of source: rates and their updates, the total, the resolution check, selection, count updates, projections and the stop predicate. LoopHost supplies waits, uniforms, reports, budgets, trackers and event logs, so one loop serves every Static Direct request for its model bytes. |
Generated code names crn_craft::rules:: paths. Its fingerprint is the
SHA-256 of the emitted source keyed by the model bytes, so other model bytes,
another parameter set or another generator version are refused with
CRN-R020. Generated kernels and loops run the linear scan only and refuse
any other selector, also one that auto would pick (CRN-R020 at
/method/selector); results are byte-identical to the interpreter.
crn.compile_loop(model) writes a small Cargo project around the generated
loop, depending on crn-craft at exactly the installed version (from
crates.io, or from a checkout named by source= or CRN_CRAFT_SOURCE), and
runs the built program as a subprocess, so no Rust ABI is shared with the
extension. Builds are cached by fingerprint, version, toolchain and driver;
loops cached by 0.6.0 are rebuilt once. Measure before adopting a generated
route (checklist).
Changing the architecture
Start from the contract. Keep numerical execution independent of optional
integrations. A change that keeps a sampler identity must keep its replay
byte for byte; the stored rules-run requests must replay unchanged. A
change to a delivered request shape or to sampler semantics needs a new
version. Use independent law checks for new numerical policies and matched
workloads for performance claims. Extension guide
Rust API
The crate crn-craft is the engine behind the Python package and the command
line. Its module crn_craft::rules holds the functions below. The minimum
supported Rust version is 1.85. The crate crn-craft-rules is a deprecated
facade that re-exports the module, so crn_craft_rules::X still compiles
(see Migrating from 0.6.0). The documentation of every
public item is in the crate’s rustdoc, which CI builds with warnings denied;
this page is the map.
Entry points
| Task | API |
|---|---|
| Check a model | rules::check_model, rules::check_model_file |
| Check any document, with a request | check_any, check_any_files |
| Prepare and run | rules::prepare, rules::execute, rules::solve, rules::solve_files |
| Observe events | rules::execute_with_observer, rules::observe::EventObserver |
| Parameter sweeps | Prepared::bind_parameters |
| Generated event loops | rules::generate_rules_loop, rules::execute_with_rules_loop |
| Convert a network model | rules::convert::from_network |
| Analysis | analyze_bytes, analyze_files, rules::FlatView |
| Sealed archives | archive::v1::run_files, archive::v1::write, archive::v1::verify |
| Finite state projection | fsp::v1::solve, fsp::v1::solve_files |
| GillesPy2 export | export::export_gillespy2 |
| Deterministic kinetics | kinetics::Kinetics |
| Concentration right-hand sides with formulas and readouts | concentration::Concentration |
| Discovery | describe, schema, rules::schema |
Report-style functions never fail: they return a report with a valid or
success flag. In a stochastic simulation, event, sampling, instance and
wall-time limits and cancellation are typed outcomes in each replicate’s
record, not errors. Cancel a running call through rules::Control.
Prepare and execute
prepare validates exact model and request bytes, and execute runs them.
The request binds the model by the SHA-256 of its exact bytes. A prepared run
can be executed again with independent execution state, and
Prepared::bind_parameters derives a candidate with other parameter values
for a sweep or an optimizer. A candidate is prepared again from the
re-serialized bound model and request, so its hashes differ from those of the
files.
The program below is complete. It builds the model and the request as bytes, runs the ensemble and runs two candidates of a parameter sweep.
use crn_craft::rules::{Control, Termination, execute, prepare};
use std::collections::BTreeMap;
fn main() -> Result<(), String> {
// Immigration at rate k_in, and death at rate k_out per molecule.
let model = br#"{
"schema": "crn-craft.model/1.0", "name": "immigration_death",
"parameters": {"k_in": 10.0, "k_out": 1.0},
"types": [{"name": "X"}], "initial": [],
"observables": {"X": {"type": "X"}},
"rules": [
{"name": "immigration", "reactants": [], "rate": "k_in",
"products": [{"type": "X"}]},
{"name": "death", "reactants": [{"label": "x", "type": "X"}],
"rate": "k_out", "products": []}]}"#;
let request = format!(
r#"{{
"schema": "crn-craft.run/1.0",
"model": {{"path": "model.json", "sha256": "{}"}},
"method": {{"kind": "static_direct"}},
"time": {{"end": 5.0, "report_times": [0.0, 5.0]}},
"ensemble": {{"replicates": 200, "root_seed": 7}},
"outputs": {{"statistics": ["mean", "variance"], "keep_paths": 0, "keep_instances": 0}},
"budget": {{"max_events_per_replicate": 100000,
"max_sampling_steps_per_replicate": 1000000, "max_instances": 1,
"threads": 2, "max_output_bytes": 1048576}}}}"#,
crn_craft::sha256(model)
);
let prepared = prepare(model, request.as_bytes()).map_err(|d| format!("{d:?}"))?;
let result = execute(&prepared, &Control::default()).map_err(|d| format!("{d:?}"))?;
assert_eq!(result.termination, Termination::Completed);
let mean = result.statistics.as_ref().and_then(|s| s.mean.as_ref()).unwrap();
// The exact law at t = 5 is Poisson with mean 10 (1 - e^-5), about 9.93.
assert!((mean[1][0] - 9.93).abs() < 1.5);
println!("{} events, mean X at t = 5: {:.2}", result.events, mean[1][0]);
// A sweep: the same request and seed with another k_in.
let values = BTreeMap::from([("k_in".to_string(), 20.0)]);
let candidate = prepared.bind_parameters(&values).map_err(|d| format!("{d:?}"))?;
let swept = execute(&candidate, &Control::default()).map_err(|d| format!("{d:?}"))?;
let swept_mean = swept.statistics.as_ref().and_then(|s| s.mean.as_ref()).unwrap();
assert!(swept_mean[1][0] > mean[1][0]);
Ok(())
}
Observing events
execute_with_observer(&prepared, &control, &observer) calls an
EventObserver for every committed event on the native workers, concurrently
for different replicates, so the observer must be Sync. It returns
ObserverAction::Stop to end that replicate: the replicate is recorded as
stopped at the event’s time and holds its state to the end of the report
grid. An observer that sets ENABLED to false compiles away, and results stay
byte-identical to those of execute. An observer must not panic.
use crn_craft::rules::observe::{Event, EventObserver, ObserverAction};
use crn_craft::rules::{Control, execute_with_observer, prepare};
use std::sync::atomic::{AtomicU64, Ordering};
/// Counts events and stops a replicate once X reaches 5 copies.
struct StopAtFive {
events: AtomicU64,
}
impl EventObserver for StopAtFive {
fn on_event(&self, event: &Event<'_>) -> ObserverAction {
self.events.fetch_add(1, Ordering::Relaxed);
if event.observables[0] >= 5.0 {
ObserverAction::Stop
} else {
ObserverAction::Continue
}
}
}
fn main() -> Result<(), String> {
let model = br#"{
"schema": "crn-craft.model/1.0", "name": "immigration_death",
"parameters": {"k_in": 10.0, "k_out": 1.0},
"types": [{"name": "X"}], "initial": [],
"observables": {"X": {"type": "X"}},
"rules": [
{"name": "immigration", "reactants": [], "rate": "k_in",
"products": [{"type": "X"}]},
{"name": "death", "reactants": [{"label": "x", "type": "X"}],
"rate": "k_out", "products": []}]}"#;
let request = format!(
r#"{{
"schema": "crn-craft.run/1.0",
"model": {{"path": "model.json", "sha256": "{}"}},
"method": {{"kind": "static_direct"}},
"time": {{"end": 5.0, "report_times": [0.0, 5.0]}},
"ensemble": {{"replicates": 16, "root_seed": 1}},
"outputs": {{"statistics": ["mean"], "keep_paths": 0, "keep_instances": 0}},
"budget": {{"max_events_per_replicate": 100000,
"max_sampling_steps_per_replicate": 1000000, "max_instances": 1,
"threads": 2, "max_output_bytes": 1048576}}}}"#,
crn_craft::sha256(model)
);
let prepared = prepare(model, request.as_bytes()).map_err(|d| format!("{d:?}"))?;
let observer = StopAtFive { events: AtomicU64::new(0) };
let result = execute_with_observer(&prepared, &Control::default(), &observer)
.map_err(|d| format!("{d:?}"))?;
assert_eq!(observer.events.load(Ordering::Relaxed), result.events);
assert_eq!(result.stopped_replicates, result.requested_replicates);
Ok(())
}
Generated event loops
Opt-in. generate_rules_loop(&prepared) emits Rust source for the whole
Static Direct event of one prepared model, for every model that Static Direct
runs (expression and string rates included). It requires a static_direct
request and at most 1 MiB of source, and refuses anything else with
CRN-R020. Parameters are compiled in, so another parameter set needs another
loop. Compile the source into your program and run it with
execute_with_rules_loop, which runs only a loop generated for the same model
bytes. Results are byte-identical to those of execute. Observers are not
supported on this path.
On the three-class example it is about 2.1 times as fast as interpreted Static
Direct (timed from Python with compile_loop, 12 November 2026). On networks
with many constant-rate channels it can be slower, so measure first
(details). From Python,
crn.compile_loop builds such a loop into a separate program and runs it
(methods reference).
Migrating from 0.6.0
The two engines of 0.6.0 became one in 0.7.0. For Rust:
crn_craft_rules::Xis nowcrn_craft::rules::X. The old paths still compile through the deprecated facade crate.- Struct literals gain fields:
Method::StaticDirect { .., selector: None },Outputs { .., quantiles: None },Statistics { .., quantiles: None }andRulesCheck { .., run_sha256: None }. crn_craft::describe()isdescribe/1.0.Kinetics::compile(&contracts::Model)is nowKinetics::from_bytes, which reads every model version. The public fieldsKinetics::modelandKinetics::networkare gone; usespecies(),initial()andparameter_values().- The analysis functions take a
&crn_craft::rules::FlatView. parameters::ParameterTemplateis nowrules::prepare(model, request)?.bind_parameters(&values).crn_craft::tau::poisson_withis nowcrn_craft::sampling::poisson_with.
The contracts that changed are in contracts, and the Python side of the migration is in the migration page.
How the examples on this page are checked
The rust blocks of this page are complete programs. They are checked as
doctest-style examples: validation/check_rust_docs.py writes each block as
the main.rs of a scratch crate that depends on the workspace crate
crn-craft by path, builds it with cargo and runs it, so a block that no
longer compiles or whose assertions fail is reported. The scratch crate is
kept outside the repository. Run it under the CPU lock on the shared host.
Extending the project
- State the supported mathematical and contract scope and the milestone. Read the architecture and the plan of the task, and write a model card before implementing a numerical algorithm.
- Add typed input fields or variants with strict unknown-field handling, validation, codes and field paths. New fields go into
crn-craft.model/1.0orcrn-craft.run/1.0(or a later version); therules-*versions refuse them withCRN-R020at/schema. Update a delivered schema version when its shape changes. Generate snapshots fromcrn-craft describe KIND; do not hand-edit JSON Schema. - Add an independently justified acceptance fixture, including failure cases. A parser change must keep the duplicate-key, numeric and depth checks. A rate change must cover unavailable reactants, dependency reads and the flat view (
FlatView::propensityreturns the engine’s value), so that FSP, analysis, kinetics and export see the same rates. - Keep numerical compilation and algorithms in the
crn-craftcrate (crates/crn-craft/src/rules/for the engine); the CLI handles files and JSON output, and Python and the job adapters call the same core. - Keep the stored requests replaying:
crates/crn-craft/tests/stored_requests.rsandstatic_direct_defaults.rsmust pass unchanged, andcrates/crn-craft/tests/generated/changes only with the generators (regenerate with the facade crate’s examplesgenerate_rules_kernelandgenerate_rules_loop). - Run the documented checks and retain evidence with toolchain identity. Never introduce a reference simulator as a core dependency.
For a new rate form, add exact small-count checks against hand-computed propensities and overflow and domain tests (CRN-R030). For a new exact method or Static Direct selector, give it a sampler identity, then add stream vectors, analytic marginal tests, report-time boundaries, absorbing states and budget and cancellation tests, and run the law gate (validation/merge/check_laws.py) and the exact-law checks (validation/check_alternative_ssa.py, validation/check_cme.py) before interpreting performance.
The dependency policy is intentionally closed: a new transitive package fails check_dependencies.py until reviewed and listed. Check package sources and links metadata before updating the allowlist. This gate is a review aid, not a comprehensive supply-chain audit.
Checks
CI (.github/workflows/ci.yml) is the complete list. The core of it:
cargo fmt --all -- --check
cargo clippy --workspace --all-targets --locked -- -D warnings
cargo test --release --workspace --locked
cargo build --release --locked -p crn-craft-cli
python3 -m pip install -r validation/requirements.txt
python3 -m ruff format --check validation python
python3 -m ruff check validation python
python3 validation/check_contracts.py
python3 validation/check_ssa.py --output ssa.json
python3 -O validation/check_ssa.py --output ssa-optimized.json
diff ssa.json ssa-optimized.json
python3 validation/check_cme.py --output cme.json
python3 validation/check_rules.py --output rules.json
python3 validation/check_mtdna.py --binary target/release/crn-craft --output mtdna.json
python3 validation/check_links.py
python3 validation/check_rust_docs.py
# After installing the wheel (maturin build --release --locked --out dist; pip install dist/*.whl):
python3 validation/check_python.py --binary target/release/crn-craft --output python.json
python3 validation/check_rules_python.py --output rules-python.json
python3 validation/check_guide.py --binary target/release/crn-craft --require-cargo --output guide.json
python3 validation/check_manual.py --binary target/release/crn-craft --manual validation/compat/manual-0.6.0.md --output manual-0.6.0.json
(cd /tmp && python3 -I "$OLDPWD/validation/check_installed.py" --output installed.json)
python3 validation/mutation_check.py
Each Python check also runs under python -O, and CI compares the two
reports.
check_guide.py runs every page of docs/guide/, the two READMEs and
docs/index.md; its docstring gives the rules for blocks. A new page needs
an entry in validation/guide-blocks.json, the least number of runnable
blocks it has. After a change, --write replaces each shown output by the
real one; never type an output by hand. The fitting page runs in smoke mode
in CI; --long runs it in full (over two hours) before a release. The Rust
blocks of developer/rust-api.md and the crate READMEs are checked by
check_rust_docs.py; a block that is not a complete program is marked
<!-- check: fragment -->. The engine-merge gates (validation/merge/check_laws.py, the speed
gate and the worker comparison) are run by hand and recorded in
validation/merge/RESULTS.md. GitHub
Actions runs fmt, clippy and release tests on Rust 1.85.0, 1.88.0 and
stable, and the installed-wheel acceptance on Linux, Windows and macOS. The
default build has no C/C++ simulator, Julia or Python runtime dependency; it
pins pure-Rust libm for rate evaluation.
Optional integrations have their own lockfiles and minimum Rust versions. Release wheels pass the installed-package acceptance on Linux, Windows and macOS (RELEASING.md). A Julia reference run and broad biological validation remain open work for the owner’s platforms. The circuit demonstrations are synthetic, and detector diagnostics do not establish universal sensitivity. The ecosystem boundary: CRN-craft supplies numerical models, fcmaes searches parameters, optimization-jobs executes jobs, and experiment-craft coordinates campaigns.
Rules kernel review checklist
Use the generic Static Direct path first. Measure its default, which since
rules-run/0.6 uses Ziggurat waits and sparse count trackers, and inverse
waits with per-event trackers where the earlier replay identity is needed.
Under crn-craft.run/1.0 also measure the selectors (linear,
composition_rejection, sorting, rssa_cr) and the auto default
(exact methods): on large networks a selector
often closes the gap that a kernel would. Compare the generic engine with
the candidate on the same model, output contract, workload and hardware. Try
the ahead-of-time generated event loop when its supported rate and
projection families cover the model.
The timings on this page were measured on releases 0.4.0 to 0.6.0, before
release 0.7.0 tuned the interpreted Static Direct loop (compiled rate
programs, running totals resumed at the first changed channel). The
interpreted rows are therefore slower than in 0.7.0; on the three-class
workload of validation/merge/mtdna-workload/summary.json, one thread,
0.7.0’s Static Direct took 0.72 times the time of 0.6.0’s. Measure again
before relying on a ratio below.
Use the following checklist when the remaining measured gap warrants a hand-written kernel.
- Profile the generic path. Record the profile and the bottleneck the candidate addresses beyond shared rates, dependency updates, deferred reports, bytecode, incremental counts and optional sampling policies.
- Recognize the lowered network at preparation. Check channel shapes, rate kernels and observables. Model and rule names are user labels.
- Certify exactness for reachable states. Bound each positive hazard against the total in the same state. Require at least 16 × 2⁻⁵³ of that total for a 53-bit grouped selector. Account for arithmetic order, zero hazards, threshold rounding and representability.
- Expose fallback explicitly. Return Static Direct and include
CRN-R051with the reason for an unsupported specialization. Exercise parameter sweeps throughbind_parametersand check sampler and warning. - Version replay. Give the kernel its own sampler identity. Verify completed outputs at one and several workers, excluding request identity fields when worker count is part of the request.
- Preserve the scheduler contract. An infinite wait reaches the horizon. Fill reports strictly before the next event with the pre-event state. At an exact tie, the existing right-continuous contract includes the event. Check the stop after each committed event and hold the stopped state. Match budgets, cancellation and polling.
- Keep observers out of the numbers. A Continue observer must leave serialized simulation results identical. An observer or retained log must use the same tracker integration policy as a run without either.
- Run law gates. Use an independent chemical master equation where a small fixture exists. Compare production distributions with Static Direct under a predeclared bound and keep any failed rows.
- Add Rust regressions. Cover reports exactly at an event, fallback, threads, Continue observer identity and overflow.
- Request independent review before merging. Include the recognition proof, numerical gate and timing evidence in the review.
Ahead-of-time generated rules kernels
A Rust caller can generate a kernel from a prepared Static Direct request. The generator covers constant and recognized vacancy rates and weighted sum projections. It emits shared vacancy expressions, per-channel arithmetic, static dependency sets, projection sums and a fingerprint: the SHA-256 of the emitted source, keyed by the model bytes. Floating-point products and sums keep the interpreter’s order. The Static Direct scheduler handles state changes, selection, waits, budgets, reports and observation.
cargo run --release --locked -p crn-craft-rules --example generate_rules_kernel -- MODEL REQUEST > kernel.rs
The generator examples (generate_rules_kernel, generate_rules_loop,
benchmark_rules) live in the deprecated facade crate crn-craft-rules;
the code they emit needs only crn-craft.
Compile the resulting module into the Rust application and use
execute_with_rules_kernel(&prepared, &control, &GeneratedRulesKernel).
execute_with_rules_kernel regenerates the source and refuses a kernel
whose fingerprint differs. That covers other model bytes, including parameter
rebinding, and kernels compiled from an older generator. A request may select inverse or Ziggurat waits using
the same compiled kernel. Build and benchmark each generated kernel against
the interpreter under the same sampler. Python use would require a wheel
built with the generated module and a binding to dispatch it.
crates/crn-craft/tests/generated_kernel.rs runs a checked-in kernel
for the three-class fixture under cargo test. It checks the generator’s
output against that source, byte-identical replay with both waiting-time
policies and rejection of a kernel for other model bytes. After a generator
change, regenerate the fixture with the example above. Run
validation/check_generated_rules.py for a fresh build and timed
comparisons.
On a two-CPU host, profiling the generic path with Ziggurat waits and sparse
trackers (128 cells, one worker, 18.4 million events) attributed 33% of the
time to rate evaluation, 18% to selection with the per-event resolution check
and 11% to observable refresh. That path took 2.07 s, against 0.76 s for
mtdna_direct, whose resolution is certified once at preparation and whose
selection is grouped.
A later loop of structural changes to the interpreter tried inline rate
factors, a fused total and resolution check, exact incremental sum
projections and a grouped evaluator that selects a group and then a
channel. None gained 5% on that path, and the grouped evaluator gained
1.04× there and 1.12× with inverse waits and per-event trackers (the
Static Direct default before rules-run/0.6). The cost is spread over
rate evaluation, selection, random words, projection maintenance and the
stop predicate. mtdna_direct fuses all of them and refreshes no
projections between reports. Closing the gap therefore needs generated
code for the whole event, not only for the rates. The
decision record has
the measurements, the profile and that next step. The generated event loop
below implements it.
Generated rules event loops
The loop generator emits the whole Static Direct event for every model
that Static Direct runs: constant, vacancy and expression rates, whole-rule
propensity expressions (the string rates of crn_craft.Model),
higher-order rules (through crn_craft::rules::combination_rate, the
interpreter’s combination count), and sum, distinct, max and min
projections. The loop runs the linear scan: a request whose selector, or
the selector that auto picks, is another one is refused with CRN-R020
at /method/selector, so name "selector": "linear" in a run/1.0
request for a loop. The emitted
GeneratedRulesLoop holds the rates in a fixed-size array and, after each
event, updates the channels that the fired channel affects. It sums the
total in channel order, checks resolution, scans for the next channel,
validates and applies the count changes and refreshes the projections the
channel changes. It also evaluates the model’s stop predicate. A guarded
fraction such as N > 0 && mutants >= 0.9 * N keeps the interpreter’s
fused form. Any other predicate is emitted from its expression with the
bytecode’s semantics: NaN propagation, short-circuit && and ||, and
the same libm functions. An undefined value is passed back to the host
for the interpreter’s diagnostic. Rate and propensity expressions are
emitted the same way, with parameters compiled in as exact bit patterns and
observables read from the current values. The global factor is multiplied
by the reactant weight times the lowered channel factor, as in the
interpreter; for a whole-rule propensity the weight is 1 while every
pattern can take a distinct molecule and 0 otherwise, and the expression is
not evaluated at weight 0. A rate expression shared by several channels of
one rule is evaluated once per dependency row, as the interpreter’s
per-event cache does. Projections use the interpreter’s reductions over
the same terms in the same order. All of it is straight-line code with the
interpreter’s operation order. LoopHost supplies the rest at run time:
polling, inverse or Ziggurat waits, uniforms, reports and the horizon, the
event, instance and sampling budgets, tracker observation and event logs.
cargo run --release --locked -p crn-craft-rules --example generate_rules_loop -- MODEL REQUEST > loop.rs
Compile the module into the Rust application and run it with
execute_with_rules_loop(&prepared, &control, &GeneratedRulesLoop).
Results are byte-identical to execute for the same request. Request
settings are not compiled in, so one loop serves every Static Direct
request for its model bytes: either waiting time, either tracker policy,
any report grid, budget or worker count. As for the rates kernel, the
fingerprint is the SHA-256 of the emitted source keyed by the model bytes,
and a loop for other model bytes or from another generator version is
refused with CRN-R020. The generator refuses, with CRN-R020 at
/method, exactly two kinds of request. One selects a method other than
static_direct; models with ATP, continuous variables or instances that
change identity need another method, so they never reach the generator.
The other is a loop whose source would exceed 1 MiB: the rate code is repeated in every dependency
row, so densely coupled networks grow with the square of their channel
count. A 64-channel network with one shared vacancy base emits about
0.8 MB, and 128 channels would exhaust a 7 GB build host. Such networks use
the rates kernel or the interpreter. A table-driven compact layout was tried
for them, but it gained only 1.15× over the interpreter on a 256-channel
dense network
(record).
Observers are not supported on this path; trackers and event logs are.
The loop refreshes every projection the fired channel changes. The interpreter, without an observer, refreshes only the projections that rates, the stop predicate or trackers read, and recomputes the rest before each report. The extra values depend only on the counts and are recomputed before every report, so outputs do not change. Projections that could overflow are refreshed by both. A deferred projection cannot overflow: the interpreter defers a projection only when each weight is at most f64::MAX / (max(1024, terms) · 2⁵³), with 2⁵³ the largest count, so a sum over its terms stays finite.
crates/crn-craft/tests/generated_loop.rs runs checked-in loops for
nineteen fixtures under cargo test (crates/crn-craft/tests/generated/):
- the three-class model with its takeover stop;
- identical and distinct pairs with extinction and a general stop predicate;
- the same pairs with a stop that uses every operator and function a stop may use;
- a channel below 53-bit resolution, with an influx;
- an invalid vacancy rate;
- vacancy rates shared by several channels, with a fraction stop or with a stop that becomes undefined;
- a count that leaves its range;
- a projection that overflows;
- a network without channels;
- the SIR model as
rules.Modelwrites it, with the string rates"beta * S * I / N"and"gamma * I", and the same model with a stop; - Michaelis–Menten conversion
V * A / (Km + A)beside constant rates; - the three-class model with degradation rates
delta * (1 + mutants / K)and anifin a replication rate; - rates and propensities with every operator and function a rate may use,
distinct,maxandminobservables and a whole-rule identical pair; - expression rates that become negative or undefined;
- higher-order rules of a
crn-craft.model/1.0model; - a wait too small to move the clock, once and a million times in a row,
under
run/1.0and therules-runversions.
The tests replay every Static Direct policy and the event, sampling-step
and instance limits. They also cover trackers, first-passage trackers,
event logs, reports close together, a horizon before the first event, the
stops and the errors. They check that cancellation is polled inside the
loop, and that other model bytes, other methods and oversized networks are
refused. choice and the other random functions never reach a rate: a rate
that uses one is invalid (CRN-R012), and a model that draws product
attributes is open, so Static Direct refuses it before a loop exists. The
string-rate fixtures run every Static Direct policy with one and two
threads, trackers, first-passage trackers, an event log and the model’s
stop, and the event, sampling and instance limits.
validation/check_generated_loop.py generates loops for thirteen replay
cases, among them a stop outside the fused form and a closed aggregation
model with a max projection. It replays them against the CLI with one and
eight workers. It checks that an oversized dense network is refused, and
it times the probes.
On the two-CPU host, the 128-cell probe took about 48 ns per event with the
generated loop under Ziggurat waits and sparse trackers. That is 2.4× faster
than the interpreter (112 ns) and 1.25–1.34× the cost of mtdna_direct
(36–38 ns across runs). With inverse waits and per-event trackers (the
default before rules-run/0.6) the loop took 69 ns, against 135 ns. The rates-only kernel took 94 ns and 122 ns. With the stop
written as N > 0 && mutants / N >= 0.9, the loop took 48 ns against
138 ns.
Benchmark before adopting the loop for networks with many channels,
constant rates and short dependency rows. There, every event’s work is the
total, the resolution check and the scan over all channels, and both paths
do that work in the same order. On the 96-channel sparse network the
unrolled loop was no faster than the interpreter (0.85–1.03× across runs).
On a 512-channel network it was clearly slower: 950 against 630 ns per
event. See the
decision record,
the follow-ups
and validation/mtdna/generated-loop.json.
From Python: compile_loop
Opt-in, off by default, for users with a Rust toolchain at least at the
MSRV (1.85). crn_craft.compile_loop(model) (also
crn_craft.rules.compile_loop) takes the loop source from the extension
(loop_source(model), which needs no cargo and raises the generator’s
CRN-R020 for unsupported models) and writes a small Cargo project: the
generated loop, the exact model bytes, a driver
(bindings/python/src/rules_loop_main.rs) and the result encoder that the
extension compiles itself (bindings/python/src/rules_payload.rs). The
project depends on crn-craft at exactly the installed version, from
crates.io or from a checkout (source= or CRN_CRAFT_SOURCE, a tree with
crates/crn-craft/Cargo.toml), and builds a standalone program. Generated
code names crn_craft::rules:: paths, so a Rust project that compiles it
depends on crn-craft directly; code generated by 0.6.0 named
crn_craft_rules:: and is refused by its fingerprint until it is
regenerated. simulate(compiled=loop) sends the request to it on
standard input and reads the metadata and record columns in the
extension’s own form. No Rust value crosses a library boundary, so the
program’s toolchain need not match the wheel’s.
Builds are cached in the user cache directory, keyed by the loop
fingerprint, the installed version, rustc -vV, the target and Rust
flags, the driver and, for a checkout, its engine sources; one Cargo target
directory serves every model. Loops cached by release 0.6.0 are rebuilt
once, into new cache entries, with the same results. Every compile_loop call runs short requests
through the program and the interpreter and returns the loop only if the
result bytes are identical; CompiledLoop.verify(run) checks a user’s
request the same way. Methods other than static_direct, other model
bytes, bound candidates and callbacks are refused.
On the 1000-cell three-class workload with two threads, end to end from
Python, the compiled loop took 2.6 s against 5.8 s for interpreted Static
Direct with its rules-run/0.6 defaults, Ziggurat waits and sparse trackers
(2.21×), and 3.8 s against 7.0 s with inverse waits and per-event trackers
(1.86×; declared target 1.5×). The first build took 42 s on the two-CPU
host, a second model 3 s and a cached call 0.06 s
(record,
validation/mtdna/compiled-loop-python.json).
For string rates the declared target was the same 1.5×, on the SIR model
as rules.Model writes it, scaled to N = 10,000 (2,000 replicates to time
400, two threads, 37.6 million events). The compiled loop took 1.64 s
against 3.35 s with inverse waits (2.00×) and 1.36 s against 2.97 s with
Ziggurat waits (2.18×), medians of three alternating runs end to end from
Python (validation/benchmark_compiled_string_rates.py,
validation/rules/compiled-loop-string-rates.json).
validation/check_compiled_loop.py checks identity over threads, waiting
times, tracker policies, event logs, stops, budgets and cancellation, on
the three-class model and on four string-rate models (the builder SIR,
Michaelis–Menten, expression rates that read observables, and max, min
and if over distinct, max and min observables), and the refusals;
it runs in CI against the checkout. See the
guide, chapter 5 and the method reference for usage.
Agent context: CRN-craft
Start with README.md, architecture, crn-craft describe
(crn-craft.describe/1.0) and the contracts. Release 0.7.0
merged the former network engine and rules engine into one; its
implementation log records every step and
deviation. Older campaign logs describe the engines as they were then.
The one engine
- One crate,
crn-craft; the engine is the modulecrn_craft::rules. The cratecrn-craft-rulesis a deprecated facade (pub use crn_craft::rules::*) that keeps 0.6.0 paths compiling. The command line iscrn-craft-cli; Python isbindings/pythonpluspython/crn_craft. Default engine MSRV 1.85.integrations/jobs(1.88),integrations/diffsol(1.89) andvalidation/parameter-optimization/workerare separate workspaces with their own lockfiles; keep them out of the default dependency gate. - One model format:
crn-craft.model/1.0. Attribute-free types are ordinary species; attributed types, patterns withwhereandfactor, observables, whole-rulepropensityexpressions, continuous variables and a patterncountfor higher-order reactions are in the model reference. A networkcrn-craft.model/0.1is read only through the converter (crn-craft convert,crn_craft.convert). - One request and result:
crn-craft.run/1.0andcrn-craft.result/1.0;fsprequests givecrn-craft.fsp-result/1.0. Therules-model0.1–0.4 andrules-run0.1–0.6 documents are still read and replay byte for byte. Amodel/1.0model needs arun/1.0request. - Methods:
tree(the default),static_direct,next_reaction,mtdna_direct,thinning,tau,binomial,hybrid, andfsp. Static Direct has the selectorslinear,composition_rejection,sorting,rssa_crandauto(therun/1.0default) (exact methods). One random number generator: ChaCha8, one stream per replicate. - Features on the flat view of a closed model (
crn_craft::rules::FlatView): finite state projection, analysis (analysis/1.0), ODE kinetics forcrn-diffsol, GillesPy2 export. Models without a closed set of species are refused withCRN-R017. - Python:
import crn_craft as crnwrites the 1.0 contracts, asks for the quantiles 0.025, 0.5 and 0.975 and leaves the selector toauto.crn_craft.rulesis the 0.6.0 API with its defaults (therules-*versions, the linear scan, no quantiles).Result.savewrites markdown orcrn-craft.report/1.0. Parameter sweeps usebind_parameters(parameter sweeps). The buildercrn.Modelwrites species with attributes too (add_species(..., attributes=[...]),add_initial,add_observable,crn.pattern,crn.copy,crn.new,crn.mass_action).ensembledefaults tomax_events=10**8with the sampling budget following it, andsimulate()warns withIncompleteEnsembleWarning(or raises withstrict=True) when replicates end early.
Where things are
- Engine sources:
crates/crn-craft/src/rules/(model, expressions, lowering, methods, selectors, flat view, converter, generators) andcrates/crn-craft/src/(FSP, analysis, kinetics, export, archives, strict JSON, diagnostics, samplers, discovery and check). - Tests:
crates/crn-craft/tests/. Stored requests undertests/stored/(invariant I1) and generated-code fixtures undertests/generated/(I3); never edit either by hand. - Schemas:
schemas/, written fromcrn-craft describe KIND. - Validation scripts:
validation/. The merge gates, the 0.6.0 references and their declarations:validation/merge/(RESULTS.md). - The frozen 0.6.0 user manual, run in CI:
validation/compat/manual-0.6.0.md.
Rules for changes
- Strict input everywhere: unknown fields and duplicate keys are errors; diagnostic codes are stable. A new code takes the next free number and goes into diagnostics.
- Schemas come from Rust types. A change to a delivered contract’s shape needs a new version, and the older versions keep their meaning.
- A new feature goes behind
model/1.0orrun/1.0; the storedrules-runrequests must keep replaying byte for byte (stored_requests.rs,static_direct_defaults.rs). - A new numerical policy or selector gets its own sampler identity and an
exact-law check before any timing.
validation/merge/check_laws.pyruns the law gate against the committed references. - Declare targets, sizes, seeds and tolerances before running; keep failed rows; never loosen a rule after seeing a result.
- Profile with Static Direct, then the generated event loop, before adding a specialized kernel (checklist).
- Run
cargo fmt, clippy with-D warnings,cargo test --release --workspace --locked, rustdoc with-D warnings, ruff, and the validation scripts that CI names, each normally and underpython -Owith identical reports.
Approximate methods (tau, binomial, hybrid) carry their own sampler
identities; FSP reports leakage and error terms and never renormalizes.
Importers accept explicit subsets and conventions only. Incomplete ensembles
withhold statistics; wall time and cancellation are outside fixed-work
reproducibility. A successful run is not biological validation.
The Python package is on PyPI (pip install crn-craft) and the crates
crn-craft, crn-craft-rules and crn-craft-cli (cargo install crn-craft-cli --locked) are on crates.io; the diffsol integration and the
job worker build from the repository.
Optimization lessons
Use C1–C4 for runnable calibration,
optional BDF and SQP fitting, MODE and MAP-Elites oscillator searches, and
bounded rules inference. They call the library and the command line. Their
SSA runs use Static Direct with its default selector; C1’s
--include-next-reaction adds a second exact method with its own stream.
Validation separates completed
checks from fitted-model quality.
C5–C10
reconstruct published studies with Python fcmaes ask/tell on the same engine:
count-distribution fitting, joint-count model selection, a virtual reactor,
Fisher experiment design, a PEtab calibration and a 36-parameter fit. Run them
with tutorials/optimization/run.py C5 to C10 (--help lists a chapter’s
options); the shared driver is tutorials/optimization/publications/search.py
(proposal traces, --resume-from replay), the fixtures are pinned in
examples/publication_tutorials/sources.json, and
crn_craft.sensitivities.forward_sensitivities and the retained argument of
crn_craft.prepare_fsp are the engine features they use. C7, C9 and C10 need
the optional crn-diffsol concentrations interface
(contracts).
Releasing
The release procedure for all registries is in RELEASING.md.
CRN-craft technical report
Version: 0.7.0, source of 12 November 2026: the release that merged
the network engine and the rules engine into one engine.
Scope: design, numerical methods, validation evidence and measured
performance of the one engine. Companion documents: the
architecture overview, the contracts, the
exact methods, the model reference and
the merge implementation log.
Evidence: every gate below was declared in
validation/merge/RESULTS.md before it
ran, and its report is committed under validation/merge/. Failed rows are
kept there.
History: the report of release 0.6.0 described the network engine of
releases 0.2.0 to 0.6.0. Its numbers are summarized, and marked, in
section 9.
1. Summary
CRN-craft is a Rust library and command-line tool, with a Python package, for stochastic simulation and analysis of well-mixed chemical reaction networks, including networks whose species carry attributes and appear during a run. One engine provides exact simulation (Direct with four event selectors, next reaction, a dynamic tree method, thinning and a certified specialization), approximate tau leaping, binomial and hybrid methods, a finite state projection solver for the chemical master equation, exact conservation and graph analysis, ODE right-hand sides with Jacobians, and strict importers and exporters.
- Reproducible to the bit. A result depends only on the exact input
bytes, the sampler identity and the seed. Replicate i draws from its own
keyed ChaCha8 stream, sums are formed in a fixed order with explicit
resolution checks, and ensembles reduce in replicate order, so one, two or
eight threads give identical results. Every stored request of the former
rules engine (
rules-run0.1 to 0.6) replays byte for byte, checked on every build. - Honest outputs. Incomplete ensembles withhold statistics; FSP reports leakage, series truncation and roundoff separately and never renormalizes; approximate methods carry their own sampler identities.
- One engine, the same laws. Results of the former network engine do not replay: its loops and its xoshiro256++ stream are gone. Its models convert, and the unified engine samples the same laws: the law gate of 4,814 comparisons over twelve models passed with 0 failures for every selector and for the default (section 6.2). The features the network engine had alone (FSP, analysis, kinetics, export) were ported to a view of the lowered model and checked against references recorded from release 0.6.0 (section 6.3).
- Speed. The declared speed gate allowed the best unified method 1.25 times the time of the best of 21 methods of release 0.6.0 on each of twelve models. Its rerun passed, with ratios from 0.66 to 1.20; the margins of five models lie within this host’s run-to-run noise (section 7.1). On the mtDNA workload, 0.7.0 takes 0.72 to 1.00 times the time of 0.6.0, with identical results (section 7.2).
2. Design goals
- Exactness is a contract. A method called exact samples the stochastic process up to floating-point arithmetic whose order is fixed and whose failure modes (lost increments, unresolvable rates, stalled clocks) are detected, not hidden. Two implementations that claim one sampler identity must agree bit for bit.
- Traceability. Every result names the SHA-256 of the exact model and request bytes and its sampler identity; archives seal a run with a manifest and a completion marker.
- Explicit limits. Every algorithm has published size, work, memory and output limits. A run is admitted only if its memory reservation fits. Exceeding a limit produces a diagnostic, never a truncated result presented as complete.
- Small trusted core. The engine has no Python, job or ODE dependency, forbids unsafe code, pins every dependency, and uses no GPL code. Optional integrations live in separate workspaces.
3. Architecture
The architecture overview describes the layers. In brief:
versioned JSON documents are parsed strictly into Rust types that also
generate the JSON Schemas; the model is compiled (patterns into classes,
predicates into bytecode); a request is validated and admitted against its
memory reservation; a closed model is lowered to a flat network of species
and channels whose rates are compiled into programs with folded parameters;
and one of the methods runs the ensemble. The flat view of the lowered model serves
FSP, analysis, kinetics and export. The command-line tool and the PyO3
binding are thin layers over the same crate, crn-craft. After the merge,
crates/*/src holds 29,372 lines of Rust: 28,492 in crn-craft (48
files), 788 in the command-line crate and 92 in the facade, whose crate
documentation the final review shortened. Before the network engine was
deleted it held 37,157 (M8b log of the
implementation log).
4. Numerical methods
4.1 Models, lowering and propensities
A model declares types with numeric attributes, rules whose reactant
patterns match instances, observables (weighted sums, counts of distinct
instances, maxima and minima) and an optional stop expression. A rule’s
rate is per combination of reactant molecules: a rule with patterns of
counts k₁, …, k_m over species with counts n₁, …, n_m has propensity
rate · factor · ∏ C(nᵢ, kᵢ), the combinatorial mass action of the
stochastic convention (A + A gives c·n(n − 1)/2). A whole-rule
propensity is used as written while every pattern can take its molecules.
Higher-order products (a pattern count above one, or more than two
patterns) are evaluated as a scaled mantissa–exponent product that does not
overflow before the result does (crn_craft::rules::combination_rate).
A closed model is lowered once, at preparation: species (attribute
vectors), channels (one per choice of matching instances), the count
changes of each channel, the species each rate reads, and for each channel
the sorted list of channels whose rates its firing can change. Lowering is
index-based and accepts 4,096 instance tuples and 65,536 channels in
model/1.0. Rates are compiled into flat programs; the converted Hill and
Michaelis–Menten forms have dedicated programs. A randomized test compares
9,000 compiled programs, and the two law shapes at 2,000 points each, with
the expression tree evaluator: the values are equal.
4.2 Static Direct
For state x with channel propensities a_j(x) and total a₀, the Direct method (Gillespie 1977) draws a waiting time and a channel with probability a_j/a₀.
- Random words. Replicate i uses ChaCha8 (
rand_chacha) keyed by SHA-256 of the domaincrn-craft.rules/0.1and the root seed as eight little-endian bytes, with stream number i. A uniform is the high 53 bits of a 64-bit word times 2⁻⁵³. - Waiting time. The inverse transform τ = −ln(1 − u)/a₀, with u
redrawn when it is 0, or the Ziggurat exponential (tables adapted from the
Julia ecosystem, see THIRD_PARTY_NOTICES.md).
Ziggurat waits are the default from
rules-run/0.6and inrun/1.0. - Selection with the linear scan. The total is the sequential sum of the rates in channel order. After an event only the affected channels change, so the sum resumes at the first of them with the same additions. The channel is found by subtracting rates from u·a₀ in channel order.
- Resolution and failures. A positive rate below 2⁻⁵³ of the total
cannot be selected by a 53-bit uniform and fails the replicate
(
CRN-R031); a lower bound on the smallest positive rate avoids the exact check on most events. A negative or non-finite rate fails it (CRN-R030). A zero total is absorbing: the state is held to the horizon. - Time. Reports are filled before an event that would pass them, with
the pre-event state; an event exactly at a report time is included. Under
run/1.0a positive wait too small to move the clock is accepted, and 1,000,000 consecutive such steps fail withCRN-R030; a step then leaves the clock unchanged with probability about 1 − exp(−a₀·ulp(t)/2), so the limit is reached only when about 22 or more events are expected per representable step of the clock. Everyrules-runversion fails at the first stalled step. - Updates. Count updates are checked and applied in one pass that undoes itself on a range or instance error. Observables are refreshed along dependencies; report-only observables that cannot overflow are computed at report times.
4.3 Selectors
Under run/1.0 Static Direct takes a selector. Every selector samples the
same law; each consumes the random stream differently and has its own
sampler identity (exact methods).
- Composition–rejection (Slepoy, Thompson and Plimpton 2008): channels grouped by the binary exponent of their rate, a group drawn by its mass from pairwise sums with the strictness of the linear scan, a member by rejection with Lemire’s joint member-and-acceptance draw.
- Sorting (McCollum et al. 2006): the linear scan in an order that moves each fired channel one place forward; a threshold at or above the sequential sum is redrawn.
- RSSA-CR (Thanh, Priami and Zunino 2014): each species has an interval around its count; each channel has lower and upper bounds of its rate over the box. A rule whose rate reads one species is evaluated at every count of that species’ interval with the engine’s arithmetic, so its range is exact for any expression; a rule that reads two or more species pins them, and its bounds are its exact value. A candidate drawn by composition–rejection from the upper bounds is accepted below its lower bound, otherwise against its exact rate, reusing the composition’s accepting threshold. So RSSA-CR runs every model that Static Direct runs.
auto, the default ofrun/1.0: RSSA-CR from 8 channels when no rate reads two or more species (from 128 channels when the species that start with molecules average fewer than 8), composition–rejection from 128 channels, otherwise the linear scan. The rule was fitted by declared criteria to a benchmark of eight synthetic families and the twelve gate models; every pick on the gate models is the fastest selector except michaelis-menten (linear, 1.08 times sorting).
4.4 Other exact methods
- Next reaction (Gibson and Bruck 2000) keeps one clock per channel in an indexed heap and rescales the clocks of the affected channels.
- Tree recomputes rule propensities over sum trees of instances. It runs models whose instances change identity or draw random product attributes, and refuses higher-order rules.
mtdna_directis a grouped Direct method for the fixed three-class mtDNA structure. Preparation certifies the model and each parameter set: in every reachable state each positive hazard is at least 16 × 2⁻⁵³ of the total. Otherwise Static Direct runs with aCRN-R051warning.- Thinning integrates the analytic ATP flow of models with the ATP block between events and thins against a checked intensity envelope.
4.5 Approximate methods
- Tau leaping follows the step selection of Cao, Gillespie and Petzold (2006): the species bound uses g = 2 for expression rates, and a propensity condition bounds the mean and spread of every rate change by ε·a_j through first differences, so rates that read global observables are controlled directly. Channels that ten firings could switch off are critical and fire at most once per leap; unacceptable proposals halve the step before an exact fallback. Poisson variates with mean at most 16 use the multiplication method, larger means Hörmann’s PTRS (1993). The leap condition costs O(channels²) per attempted leap (section 6.6).
- Binomial splitting resolves fixed steps by competing-risk probabilities (a/Λ)(1 − e^(−Λ·dt/n)) per parent for single-parent unit births and deaths.
- Hybrid integrates continuous variables with Dormand–Prince 5(4) at the request’s tolerances between stochastic events.
Their results are approximate at their declared parameters, and their sampler identities say so.
4.6 Ensembles, statistics and quantiles
Workers claim replicate ids from a shared counter; a window of four
replicates per worker bounds how far they run ahead, and results reduce in
ascending id order, so statistics do not depend on the thread count.
Quantiles keep one value per replicate, report time and observable, and
use NumPy’s default definition (Hyndman and Fan type 7) evaluated as NumPy
evaluates it, so the values equal numpy.quantile bit for bit. Admission
counts that buffer against the 2 GiB workspace limit. Statistics,
quantiles included, are withheld unless every replicate completed or
stopped.
4.7 Finite state projection
Following Munsky and Khammash (2006), an fsp request enumerates the
reachable states of the flat view within per-species bounds by breadth-first
search (up to max_states), with every transition leaving the box sent to
an absorbing sink. A state where the model’s stop holds is absorbing as
well. The probability vector is propagated by uniformization, each interval
split so that ΛΔ ≤ 16, and each series truncated when its geometric tail
majorant falls below the step’s share of the tolerance. Leakage, the series
tail bounds, the omitted series weight, the total mass defect and the
roundoff residual are reported separately per snapshot, and probabilities
are never renormalized. The generator is stored by column and each series
term gathers in ascending state order.
4.8 Analysis, kinetics and export
- Conservation computes an exact rational basis of the left nullspace of the stoichiometric matrix with checked i128 arithmetic; the cone enumerates the extreme rays of the nonnegative conservation cone by a bounded double description method (after Burton) and bounds every species of the initial class; linkage computes complexes, linkage classes, deficiency and weak reversibility. Each stops at explicit limits.
- Kinetics gives the right-hand side rate · factor · ∏ yᵢ^kᵢ/kᵢ! (or a whole-rule propensity without its availability gate, accepted only where the expression vanishes structurally when a taken species is zero) and its state and parameter Jacobians, from dual-number evaluation of the rule expressions. At most 64 species, 32 parameters and 256 channels.
- Export writes GillesPy2 source: mass action for constant rates of at
most two molecules, custom propensity strings otherwise, and refusals
(
CRN-E050) for what GillesPy2 cannot evaluate in both of its solvers.
4.9 Conversion of network models
The converter writes each species as an attribute-free type, mass action
as a rate, Hill laws as basal + vmax / (1 + (k / R)^n) and
basal + vmax / (1 + (R / k)^n), and Michaelis–Menten laws as
vmax * (S / (km + S)). Against the network engine’s own evaluation
(crates/crn-craft/src/rules/convert.rs tests): mass action of order 0
and 1 and Michaelis–Menten are bit-identical, pairs within 4 ε, Hill laws
within 1e-14 · max(1, n) relative, and 116 of 5,880 Hill cases where the
induced term is below vmax · 2⁻¹⁰²⁰ give the basal rate.
5. Interfaces and contracts
The command line is crn-craft describe, check, run (with --archive
and --cancel-file), verify, analyze, convert and export; all
output is JSON with documented exit codes. The contracts are
crn-craft.model/1.0, run/1.0, result/1.0, fsp-result/1.0,
check/1.0, analysis/1.0 and archive/1.0, with the rules-* versions
still read (contracts). Contract types generate JSON
Schemas (crn-craft describe KIND), and any shape change gets a new
version.
The Python package (ABI3 wheel for Python 3.10 and later) exposes the
builder, prepared ensembles, pandas and xarray results, Result.save, FSP
and analysis on models, importers and compiled event loops. Native calls run
off the GIL, so Ctrl-C cancels them within about 50 ms; rejected inputs raise
CrnError with parsed diagnostics. crn_craft.rules keeps the 0.6.0 API
with its defaults.
6. Validation
6.1 Test suites and invariants
| Gate | Content |
|---|---|
| Rust tests | cargo test --release --workspace --locked: 397 tests (29 of them doctests) on the merged tree (final review, 12 November 2026; 538 before M8b removed the network engine’s tests); contracts, conversion, limits, higher-order rules, selectors, quantiles, the clock rule, FSP, analysis, kinetics, export, archives, generated code and the CLI |
| I1: stored requests | crates/crn-craft/tests/stored_requests.rs and static_direct_defaults.rs: every stored rules-run request replays byte for byte; the same requests as run/1.0 give the rules-run/0.6 result apart from schema and hashes |
| I2, I2b: manuals | check_manual.py runs every block of the user manual (26) and of the frozen 0.6.0 manual (22), normally and under python -O, with identical reports |
| I3: generated code | 20 checked-in generated sources (19 event loops, 1 rates kernel) equal the generators’ output and replay the interpreter byte for byte |
| Mutation gate | mutation_check.py: 47 source mutants, each turning a passing suite into named failures; 47 of 47 caught on the unified code (M8a and M8b logs, and again in the final review) |
| Exact laws | check_ssa.py (analytic campaigns, an independent Python oracle that reproduces the engine’s paths, thread identity, cancellation latency), check_cme.py (exact master-equation checks), check_alternative_ssa.py (168 DKW tests: 4 selectors × 2 waiting times, N = 100,000, family α = 0.001) |
| Features | check_fsp.py (including the DSMTS suite), check_tau.py, check_network.py, check_structure.py, check_export.py, check_importers.py, check_contracts.py |
| Python and documents | check_python.py, check_rules_python.py, check_builder.py, check_hybrid.py, check_installed.py, check_tutorial.py, check_compiled_loop.py, check_links.py |
| Dependency gate | the default build’s dependency set and licenses |
Every Python checker runs normally and under python -O, and CI diffs the
reports.
6.2 The law gate (N = 4,814)
Declared before the first run (“Law gate” in RESULTS.md): twelve models
(the five examples and the workloads W1 to W7, up to 256 species, 992
reactions and order 8), each simulated with 200,000 replicates in chunks
with declared seeds, and compared per species and report time with
references recorded from release 0.6.0 (200,000 replicates of its cached
Direct method) and, for five models, with FSP laws. A comparison fails when
a mean or a variance differs by more than five standard errors of the
difference. Of the 4,814 comparisons, 940 are at time 0 and must be equal;
about 0.002 failures are expected per run of a correct engine, so 0 are
expected.
| Engine configuration | Report | Comparisons | Failures | Largest |z| |
|---|---|---|---|---|
linear | laws/m4c-linear.json | 4,814 | 0 | 3.88 |
composition_rejection | laws/m4c-composition_rejection.json | 4,814 | 0 | 3.83 |
sorting | laws/m4c-sorting.json | 4,814 | 0 | 3.51 |
rssa_cr, first run | laws/m4c-rssa_cr.json, laws/m4c-rssa_cr-vilar-noise-failure.json | 4,724 (11 models) | vilar-noise failed | 3.94 |
rssa_cr, after the clock rule | laws/m4f-rssa_cr.json | 4,814 | 0 | 3.88 |
auto, the run/1.0 default | laws/m4d-auto.json | 4,814 | 0 | 3.88 |
Report paths are under validation/merge/. The first RSSA-CR run failed on
vilar-noise: a replicate stopped at t = 7.16 because a trial’s wait was
below half an ulp of t (CRN-R030, clock failed to advance), as the 0.6.0
engine also did. The clock rule of section 4.2 accepts such steps under
run/1.0; the rerun with the declared seeds passed. The auto gate gave
event counts and power sums equal to the gates of the selectors it picked.
Earlier runs on subsets passed as well (laws/static_direct.json: 1,102
comparisons before the higher limits; laws/m4-static_direct.json: all
twelve models after the higher limits and higher-order rules, 4,814, 0
failures).
6.3 References of the ported features
| Feature | Report (validation/merge/) | Result |
|---|---|---|
| FSP against the 0.6.0 solver | fsp/references.json | 11,278 checks, 0 failures; largest probability difference 1.4e-17, six of seven models bit-identical |
| Analysis of the twelve models against 0.6.0 | analysis/references.json | 194,388 leaves, 0 failures |
| Kinetics against 0.6.0 | kinetics/references.json | 6,252 values and 12 acceptance checks, 0 failures; 6,192 bit-identical, largest relative difference 2.6e-16 |
| GillesPy2 export against 0.6.0 | export/references.json | 9 artifacts byte-identical, 160 custom-propensity evaluations equal, 0 failures |
| Higher-order rules against FSP laws | laws/higher-order.json | 272 comparisons, 0 failures |
| Tau envelopes | tau/check_tau_rules.json | 3 rows (ε = 0.1, 0.05, 0.025; 10,000 paths each), 0 failures |
| Quantiles against the Poisson law | laws/quantiles-immigration-death.json | 9 comparisons, 0 failures |
| Selector laws | laws/selectors-exact-m4f.json | 168 of 168 DKW tests, 16 of 16 power checks |
6.4 Limitations
- Validation uses analytic and master-equation references for small networks and synthetic circuits; it does not establish biological validity of any model.
- The law gate compares marginal means and variances, not covariances or whole distributions; FSP references exist for five of the twelve models.
- Tau leaping is approximate, its envelopes cover immigration–death controls only, and on the gate model most of its steps are exact fallbacks.
- Timings come from one shared two-CPU host; absolute numbers vary by machine.
- The optional integrations (
crn-diffsol, the job worker) are built and checked locally, not in CI.check_ode.pyis not a CI step. - macOS and Windows wheels are built by a manual workflow and are not executed here.
7. Performance
7.1 Speed gate
Declared before any measurement (“Speed gate (M4d)” in RESULTS.md):
twelve models (W1 to W7 at the workload sizes, the five examples), the wall
time of one CLI process, median of three after a warm-up, one thread. The
0.6.0 best is the smallest median over 21 methods of release 0.6.0 (five
aggregators with the fast policy on and off and both waiting times, and
next reaction), rerun in the same session with the kept 0.6.0 build. The
unified best is the smallest median over linear, composition_rejection,
sorting, rssa_cr, auto and next_reaction. Gate: unified best at most
1.25 times the 0.6.0 best on each model.
The first run failed on W5 (1.28; validation/merge/speed-m4d-run1.json).
After the one allowed fix round, the rerun passed
(validation/merge/speed-m4d.json):
| Model | 0.6.0 best | s | Unified best | s | Ratio |
|---|---|---|---|---|---|
| W1 | direct/ziggurat/fast | 0.0482 | auto (linear) | 0.0511 | 1.06 |
| W2 | direct_cr/ziggurat/fast | 0.0906 | rssa_cr | 0.1031 | 1.14 |
| W3 | cached_direct/ziggurat/fast | 0.2248 | auto (linear) | 0.2707 | 1.20 |
| W4 | rssa_cr/ziggurat/fast | 0.1119 | auto (rssa_cr) | 0.1084 | 0.97 |
| W5 | direct_cr/ziggurat/fast | 0.0614 | auto (rssa_cr) | 0.0685 | 1.12 |
| W6 | rssa_cr/inverse/fast | 0.0639 | auto (rssa_cr) | 0.0599 | 0.94 |
| W7 | cached_direct/ziggurat/fast | 0.0185 | rssa_cr | 0.0216 | 1.17 |
| enzyme-mechanism | cached_direct/ziggurat/fast | 0.0731 | sorting | 0.0622 | 0.85 |
| immigration-death | cached_direct/ziggurat/fast | 0.0687 | auto (linear) | 0.0474 | 0.69 |
| michaelis-menten | direct/ziggurat/fast | 0.0561 | auto (linear) | 0.0368 | 0.66 |
| repressilator | cached_direct/ziggurat/fast | 0.2809 | linear | 0.3178 | 1.13 |
| vilar-noise | cached_direct/ziggurat/fast | 1.0514 | auto (linear) | 0.9451 | 0.90 |
Noise. auto runs the same computation as the selector it picks, so
each model has two timings of one computation; in the rerun they differ by
up to 1.55 times (W6: 0.0599 against 0.0930 s). With the slower of the two,
the ratios of W1 to W7 would be 1.21 to 1.46. Pooled over both runs (each
side’s smaller median), the ratios are W1 1.05, W2 1.15, W3 1.18, W4 1.04,
W5 1.14, W6 0.94, W7 1.05, repressilator 1.18 and 0.66 to 0.90 for the other
examples. The 0.6.0 side, a minimum over 21 close variants, profits from the
same effect. So the gate passes by its declared rule, but for W2, W3, W5, W7
and the repressilator (1.12 to 1.20) the margin lies within this host’s
run-to-run noise, and W5’s move from 1.28 to 1.12 is mostly noise.
Where the time goes (callgrind of the rerun’s CLI, M4d log): on W1 the two ChaCha8 words per event (about 3.7 ns per word against 1.5 ns for 0.6.0’s xoshiro256++) and the Ziggurat wait; on W3 and the repressilator one mispredicted scan exit per event and the Hill programs; on the RSSA-CR models the trials per event and the exact evaluation of candidates. The unified engine runs fewer instructions than 0.6.0’s best on every profiled model (0.63 to 0.99 times, M4f log), but not always less wall time.
Compiled event loops, timed at the Python boundary (informative, same
section of RESULTS.md), took 0.61 to 0.90 times the interpreted linear
scan on eight models and 1.15 times on W7; W4 to W6 exceed the 1 MiB
source limit.
7.2 mtDNA workload
Measured on 12 November 2026 with no declared target
(validation/merge/mtdna-workload/, results section in RESULTS.md): the
three-class model models/rules/mtdna-three-class-cme.rules.json, a
37-point grid from 0 to 25,920 h, seed 1, wall time of
crn_craft.rules.ensemble(...).simulate(), medians of five runs alternating
0.6.0 and 0.7.0 under a CPU lock. Statistics and records hash identically
between the versions.
| Method | Cells | Threads | 0.6.0 s | 0.7.0 s | Ratio |
|---|---|---|---|---|---|
mtdna_direct | 1000 | 1 | 10.67 | 10.27 | 0.96 |
mtdna_direct | 1000 | 2 | 5.42 | 5.26 | 0.97 |
static_direct | 400 | 1 | 13.20 | 9.49 | 0.72 |
static_direct | 400 | 2 | 6.70 | 5.63 | 0.84 |
tree | 100 | 1 | 10.04 | 9.94 | 0.99 |
tree | 100 | 2 | 5.46 | 5.45 | 1.00 |
Static Direct’s linear scan runs a tuned loop in 0.7.0 (compiled rate programs, running totals, precomputed count factors) with byte-identical results. The performance analysis sizes mtDNA studies.
7.3 Other measurements
- Parameter workers. Binding parameters on a prepared run, against the
0.6.0 templates in one session (
validation/merge/parameter-workers-m4d.json, declared target 1.25): five of six ratios between 1.04 and 1.15;binding12with reuse failed at 1.55, becausebind_parametersprepares the whole model again on each call (about 0.1 ms on that 12-species model). - Tau leaping on large networks (
validation/merge/tau/leap-condition-cost.json): on W5 and W6 (510 and 992 channels)tautook 14.1 and 12.9 times as long as Static Direct; neither model leaps at the declared ε, so this is the cost of its exact fallback. Each attempted leap evaluates every channel after one firing of each enabled channel. Use Static Direct there. - GillesPy2 1.8.3 (comparison,
validation/merge/gillespy2-comparison-0.7.json, protocol declared inRESULTS.md): on the four frozen workloads (64 paths, one thread) its compiled C++ solver took 2.9, 10.6, 3.6 and 9.3 times as long as CRN-craft’s default request (auto, Ziggurat waits), and 2.8, 5.6, 3.7 and 1.3 times as long as the linear scan with inverse waits; it needs 2.1 to 2.9 s to compile each model. Its NumPy solver took 134 to 358 times as long as the default. All 28 agreement tests passed the declared rule. - Julia (Catalyst and JumpProcesses). Not repeated for 0.7.0: Julia is not available on this host. The comparisons measured the 0.6.0 network engine and carry a note saying so.
8. Reproducing
cargo build --release --workspace --locked
cargo test --release --workspace --locked
python validation/merge/check_laws.py --help # the law gate
python validation/merge/compare_speed.py --help # the speed gate
python validation/compare_gillespy2.py --binary target/release/crn-craft \
--output gillespy2.json --figure gillespy2.png
python validation/merge/mtdna-workload/bench.py \
models/rules/mtdna-three-class-cme.rules.json static_direct 1 400 timings.jsonl
The speed gate needs the kept 0.6.0 build; validation/merge/RESULTS.md
names the commands, sizes and seeds of every gate.
9. History: the network engine of releases 0.2.0 to 0.6.0
The report of release 0.6.0 (git show v0.6.0:docs/technical-report.md)
describes the network engine and its performance campaign; the numbers below
come from it and from the campaign files it cites, and none of them was
measured on 0.7.0.
- The network engine had two Direct implementations,
simulateand the dependency-cachedsimulate-cached, with byte-identical results, a separate stream domain (crn-craft.chacha8/0.1), FSP, tau leaping with its own request and result contracts, and sealed archives with provenance. Thessacommand added DirectCR, SortingDirect, RSSA-CR and next reaction, and thefastpolicy with xoshiro256++. - Its performance campaign P01–P20 (P01–P10,
P11–P20) brought
simulate-cachedto 48, 152, 151 and 553 ns per event on the four frozen workloads (two channels, sparse 66 reactions, a 12-reaction circuit, dense 66 reactions), on the same kind of shared two-CPU host. - Against GillesPy2 1.8.3 on those workloads, its compiled C++ solver took
1.1 to 3.3 times as long as
simulate-cached.
References
- D. T. Gillespie (1977). Exact stochastic simulation of coupled chemical reactions. J. Phys. Chem. 81, 2340–2361.
- M. A. Gibson and J. Bruck (2000). Efficient exact stochastic simulation of chemical systems with many species and many channels. J. Phys. Chem. A 104, 1876–1889.
- A. Slepoy, A. P. Thompson and S. J. Plimpton (2008). A constant-time kinetic Monte Carlo algorithm for simulation of large biochemical reaction networks. J. Chem. Phys. 128, 205101.
- J. M. McCollum, G. D. Peterson, C. D. Cox, M. L. Simpson and N. F. Samatova (2006). The sorting direct method for stochastic simulation of biochemical systems with varying reaction execution behavior. Comput. Biol. Chem. 30, 39–49.
- V. H. Thanh, C. Priami and R. Zunino (2014). Efficient rejection-based simulation of biochemical reactions with stochastic noise and delays. J. Chem. Phys. 141, 134116.
- B. Munsky and M. Khammash (2006). The finite state projection algorithm for the solution of the chemical master equation. J. Chem. Phys. 124, 044104.
- Y. Cao, D. T. Gillespie and L. R. Petzold (2006). Efficient step size selection for the tau-leaping simulation method. J. Chem. Phys. 124, 044109.
- W. Hörmann (1993). The transformed rejection method for generating Poisson random variables. Insurance: Mathematics and Economics 12, 39–45.
- R. J. Hyndman and Y. Fan (1996). Sample quantiles in statistical packages. The American Statistician 50, 361–365.
- B. A. Burton (2010). Optimizing the double description method for normal surface enumeration. Mathematics of Computation 79, 453–484; arXiv:0808.4050.
- D. J. Bernstein (2008). ChaCha, a variant of Salsa20.
- A. Dvoretzky, J. Kiefer and J. Wolfowitz (1956), with Massart’s constant (1990): the DKW band used by the statistical checks.
mtDNA simulations: performance analysis
This analysis answers four questions for studies of mtDNA mutant accumulation with CRN-craft:
- How long does a study take?
- Which method should it use?
- What do observation and the interfaces cost?
- How does the engine compare with other implementations?
It combines measurements on a two-CPU host with the earlier recorded
measurements in validation/mtdna/. Read the
case study of the user guide for the models and methods.
Sections 1 to 8 were measured on release 0.2.0 and later releases up to
0.6.0, as each section says. Release 0.7.0 merged the network engine into
the engine these sections measure; the methods for mtDNA models are the
same, and release 0.7.0 compares their speed with 0.6.0 on
one workload. There mtdna_direct and tree run as fast as before and
Static Direct is faster, so the Static Direct rows of the older sections
overstate its cost on 0.7.0.
Summary
- Cost model. A three-year cell at K = 1000 has about 150,000 events (2 · δ · K · T). Run time is close to cells × events per cell × cost per event ÷ cores.
- Release 0.7.0. On the three-class workload, one thread, 0.7.0’s
Static Direct takes 0.72 times the time of 0.6.0’s, with identical
results;
mtdna_direct(0.96) andtree(0.99) are unchanged (release 0.7.0). - The generic methods (release 0.2.0). Static Direct, the generic exact method for closed models, took about 134 ns of CPU time per event on the two-CPU host with its default since rules-run/0.6, Ziggurat waits and sparse trackers, and 156 ns with inverse waits and per-event trackers, its default up to release 0.3.0. Next reaction took 214 ns and the tree method, which also runs models whose instances change identity, 561 ns.
- The opt-in fast path.
mtdna_direct, certified at preparation for the three-class fixed-population structure only, took about 40 ns per event: 3.3× less than Static Direct (3.9× less than with inverse waits). Other models fall back to Static Direct with inverse waits andCRN-R051. The numbers markedmtdna_directbelow hold only for that structure; multiply them by about 3.3 for Static Direct. - A full study is short. 10,000 cells for three years with the takeover
stop take about 8.6 s on eight CPUs with
mtdna_directand 43 s with Static Direct. A supplied Java implementation took 14.9 s on the same host. - Threads scale almost linearly. Results do not depend on the thread count.
- Most bookkeeping is cheap. Measured under
mtdna_direct:- count trackers cost nothing measurable;
- a first-passage tracker doubles the run time;
- a bounded event log adds 70%.
- A Python callback costs about 14 µs per event, a hundred times the simulation itself, so it is for a few cells only.
- The approximate methods are not faster here.
- Tau leaping cannot take multi-event leaps at K = 1000, because the
vacancy
K − Nholds only a few places. It ran 6.6× slower than Static Direct. - Hourly binomial steps cost about as much as exact Static Direct.
- Tau leaping cannot take multi-event leaps at K = 1000, because the
vacancy
- Interfaces add little. The command line and Python took the same time, binding new parameters costs 0.3 ms per candidate, and the pandas and xarray results add at most 3% to a simulation.
Release 0.7.0
Measured on 12 November 2026 on the two-CPU host, with no declared target
(validation/merge/mtdna-workload/, described in
validation/merge/RESULTS.md). The workload is
models/rules/mtdna-three-class-cme.rules.json with a 37-point report grid
from 0 to 25,920 h, seed 1, run through crn_craft.rules.ensemble(...);
the times are the wall time of simulate(), medians of five runs that
alternate 0.6.0 and 0.7.0 under a CPU lock. The statistics and records of
both versions hash identically for every row.
| Method | Cells | Threads | 0.6.0 s | 0.7.0 s | Ratio |
|---|---|---|---|---|---|
mtdna_direct | 1000 | 1 | 10.67 | 10.27 | 0.96 |
mtdna_direct | 1000 | 2 | 5.42 | 5.26 | 0.97 |
static_direct | 400 | 1 | 13.20 | 9.49 | 0.72 |
static_direct | 400 | 2 | 6.70 | 5.63 | 0.84 |
tree | 100 | 1 | 10.04 | 9.94 | 0.99 |
tree | 100 | 2 | 5.46 | 5.45 | 1.00 |
0.7.0 runs Static Direct’s linear scan in a tuned loop: compiled rate
programs, running totals resumed at the first changed channel and
precomputed count factors, with byte-identical results. mtdna_direct and
tree are essentially unchanged. Per cell, one thread, Static Direct took
23.7 ms and mtdna_direct 10.3 ms on 0.7.0 (9.49 s for 400 cells against
10.27 s for 1000), about 2.3 times as long; the 0.2.0 measurements below,
on another workload, give 3.3. On the user manual’s section 3 example (200
cells, two threads), Static Direct took 2.8 times as long as mtdna_direct
(3.1 with inverse waits and per-event trackers), and the compiled loop 0.47
times as long as interpreted Static Direct (validation/merge/manual-ratios/,
12 November 2026). Where the sections below multiply by 3.3 or 3.9 for
Static Direct, 0.7.0 needs about 2.8 or 3.1. For the three-class model crn.ensemble’s default
selector auto picks the linear scan, because its replication rates read
several species; the other selectors are for large networks
(exact methods).
Measurement setup
Measurements of sections 1 to 8 (release 0.2.0 unless a section says otherwise):
- Host. Linux, two CPUs, Python 3.13,
crn-craftbuilt frommainatac91628; its Python API and engine are those of release 0.2.0. - Script.
examples/mtdna/performance.py. Raw timings are invalidation/mtdna/user-scenarios-timing.json. - Workload. Unless stated, the three-class model with
N > 0 && mutants >= 0.9 * N, three years (25,920 h), monthly reports, seed 17 and two threads. - Repeats. Medians of three runs, or a single run for the slow methods.
- Fast path. Most tables time the opt-in
mtdna_direct, which applies only to the three-class structure (guide, page 14a). Their headers say so. Section 2 gives the factor for every other method. - Metrics. Wall ns per event divides wall time by all events of the ensemble. With two busy threads, the CPU time per event is twice that.
- Static Direct defaults. Rows labeled 0.3.0 default ran inverse
waits and per-event trackers, which
method="static_direct"selected up to release 0.3.0. Rows labeled 0.6 default ran Ziggurat waits and sparse trackers, which it selects now. Section 2 gives a separate, alternating measurement of the two (validation/mtdna/static-direct-defaults-timing.json).
Recorded measurements, cited where used:
validation/mtdna/java-gap.jsonandtiming.json: an eight-CPU quota, the supplied Java implementation, 10,000 cells.validation/mtdna/generated-loop.json: the Rust generated loop.
Timing is host-specific. Ratios between methods carry over better than absolute times.
1. The cost model
Events per cell are set by the turnover. In the fixed-population model degradations and replications balance, each at about δ · K per hour, so a cell sees about 2 · δ · K · T events. For K = 1000, half-life 10 days and three years, that is 2 × 0.00289 × 1000 × 25,920 ≈ 150,000 events. A takeover stop ends about a tenth of the cells early. That brought 1000 cells to 143.8 million events instead of 150 million.
K (500 cells, mtdna_direct) | Events | Wall s | Wall ns per event |
|---|---|---|---|
| 250 | 18.4 M | 0.33 | 17.8 |
| 500 | 36.7 M | 0.84 | 22.8 |
| 1000 | 72.4 M | 1.61 | 22.2 |
| 2000 | 139.4 M | 3.15 | 22.6 |
The time grows linearly with K, and the cost per event stays flat. The
same holds for the horizon and the half-life: the cost is in the number of
events, not in the size of the state.
So, on this host:
time ≈ cells × 2 · δ · K · T × cost per event ÷ cores
with a CPU cost per event of about 40 ns for mtdna_direct and 134 ns for
Static Direct (156 ns with inverse waits; section 2).
2. Methods
1000 cells (200 for the tree method and tau), two count trackers, two threads:
| Method | Kind | Wall s per 1000 cells | Wall ns per event | Relative to Static Direct, 0.3.0 default |
|---|---|---|---|---|
| Static Direct, 0.3.0 default (inverse waits, per-event trackers) | exact | 11.2 | 78.2 | 1.00 |
| Static Direct, 0.6 default (Ziggurat waits, sparse trackers) | exact | 9.6 | 66.9 | 0.86 |
| next reaction | exact | 15.4 | 107.2 | 1.37 |
| tree | exact | 40 (8.1 for 200) | 280.5 | 3.59 |
| binomial, 1 h steps | approximate | 11.3 | 79.0 | 1.01 |
| tau, ε = 0.03 | approximate | 75 (15.1 for 200) | 519.3 | 6.64 |
mtdna_direct, opt-in fast path | exact | 2.9 | 20.3 | 0.26 (3.9× faster) |
The 0.6 default. rules-run/0.6 made the faster row the default of
static_direct; Python’s method="static_direct" selects it. Measured on
6 November 2026 on another two-CPU host (Python 3.12.3, commit 099c08d,
validation/benchmark_static_direct_defaults.py), the same 1000 cells
with three runs of each request in alternating order took:
| Static Direct request | Median wall s | Median wall ns per event | Speedup |
|---|---|---|---|
| rules-run/0.5 default (0.3.0 default) | 7.00 | 48.8 | 1.00 |
| rules-run/0.6 default | 5.99 | 41.6 | 1.17 |
The declared target was 1.10×. The table above gives the same ratio,
1.17×, on its slower host. The new default samples the same process with
another use of the random stream, so its numbers differ cell by cell; it
passed the master-equation gate of the Ziggurat sampler
(log).
{"kind": "static_direct", "waiting_time": "inverse", "sparse_trackers": False}
reproduces the numbers of release 0.3.0.
Why the methods differ:
-
Static Direct evaluates the eight channels from a data-driven plan, checks resolution and refreshes the observables at every event. A profile of 18.4 million events put:
- 33% in rate evaluation;
- 19% in the event loop;
- 18% in selection with the waiting time;
- 13% in random words;
- the rest in state updates, observable refresh and the stop predicate.
No part dominates. That is why interpreted rewrites could not close the gap (record) and a generated loop could (section 6).
-
Next reaction keeps one clock per channel. Every event changes
NandD, so every replication clock must be rescaled. That is more work than Direct’s fresh draw. -
The tree method recomputes every rule over a sum tree of instances. It is needed only for models whose instances change identity, such as the clone model.
-
Tau controls every rate’s change within a leap. The vacancy term changes by a large relative amount with each event when only a few places are free, so tau runs exact events at extra cost. It pays off only where every rate changes slowly.
-
Binomial steps resolve each hour by competing-risk probabilities per parent. That is about as much work as exact simulation at this event density, and the result is approximate.
-
mtdna_direct, the opt-in fast path, fuses the whole event into fixed code for the three-class structure.- It computes the eight hazards from three counts with one division.
- It certifies resolution once at preparation instead of at every event.
- Its stop and count trackers read the counts directly.
It is the only route that refreshes no observables between reports. It samples the same process as Static Direct with a different use of the random stream, so results agree in distribution, not cell by cell.
For a model with the three-class structure, opt in with mtdna_direct and
check that metadata["sampler"] names it. Preparation certifies the model
and each parameter set; if a check fails, the run is Static Direct and a
CRN-R051 warning says why. The
method reference lists
the checks. Every other closed model runs on the generic methods above.
3. Threads
Threads (2000 cells, mtdna_direct) | Wall s | Speedup |
|---|---|---|
| 1 | 12.47 | 1.0 |
| 2 | 5.87 | 2.1 |
Recorded with an eight-CPU quota and 20 threads, against one thread (Static Direct with its 0.3.0 default):
| Method (200 cells, no stop) | 1 thread | 20 threads on 8 CPUs | Speedup |
|---|---|---|---|
| Static Direct | 4.63 s | 0.78 s | 5.9 |
| next reaction | 5.55 s | 0.96 s | 5.8 |
| tree | 13.84 s | 2.35 s | 5.9 |
| Static Direct from Python, 10,000 cells | 219.3 s | 35.7 s | 6.1 |
Cells are independent, so threads scale until the CPUs are busy. Each cell has its own random stream, so results are identical for any thread count. Use as many threads as CPUs.
4. Observation
1000 cells, mtdna_direct:
| Observation | Wall s | Relative |
|---|---|---|
| none | 3.00 | 1.00 |
two count trackers (neutral_mutants, advantaged_mutants) | 2.90 | 0.97 |
a first-passage tracker (N > 0 && mutants >= 0.6 * N) | 6.01 | 2.0 |
| an event log of mutation events, 50 per cell | 5.19 | 1.7 |
Static Direct, 0.3.0 default, 20 cells, one thread:
| Observation | Wall s | Wall ns per event |
|---|---|---|
| none | 0.37 | 127 |
| a Python callback that always continues | 39.5 | 13,550 |
Under mtdna_direct, plain count trackers integrate only when their class
changes, so they are free; Static Direct does the same by default since
rules-run/0.6 (sparse_trackers). A first-passage predicate or an event log needs the general
observation path, which refreshes the observables and evaluates the
predicate after every event. That costs about the same again as the
simulation.
A Python callback receives every event as a parsed JSON document and holds the interpreter lock, which serializes the threads. At 14 µs per event, one three-year cell costs about 2 s. It suits exploring a handful of cells. For whole ensembles, use trackers, event logs or a Rust observer.
5. Interfaces and parameter binding
| Operation | Time |
|---|---|
CLI crn-craft rules (in 0.7.0 crn-craft run; rules is an alias), 1000 cells, mtdna_direct | 2.90 s |
Python rules.prepare(...).simulate(), the same request | 2.81 s |
template.bind_parameters({...}) per candidate | 0.28 ms |
a fresh rules.ensemble(...) per candidate | 0.29 ms |
Both front ends run the same native engine. Preparing a candidate is
negligible next to its simulation either way. bind_parameters is
preferred because it keeps the settings identical, not because it is
faster.
Python parses the result document and returns pandas DataFrames, and
xarray DataArrays for kept paths and event logs. The tables below are for
4000 cells with every path kept (keep_paths="all", mtdna_direct, two
threads; NumPy 2.3.5, pandas 3.1.1, xarray 2026.9.0; medians of three;
validation/mtdna/python-results-timing.json, measured for 0.6.0). This
host ran the simulation about 1.3× slower than the host of the other
tables, so compare the steps with each other:
| Step | 37 monthly reports | 155 weekly reports |
|---|---|---|
| simulation (native) | 9.6 s | 9.8 s |
| parsing the result JSON | 0.11 s | 0.43 s |
| records, rule counts and statistics as DataFrames | 0.0016 s | 0.0018 s |
result.paths, a cell × time × variable DataArray | 0.046 s | 0.21 s |
then result.paths_frame() (148,000 or 620,000 rows) | 0.006 s | 0.023 s |
then result.to_xarray() | 0.004 s | 0.017 s |
result.paths_frame() alone, as paths in 0.4.0 | 0.047 s | 0.23 s |
The first of paths, paths_frame() and to_xarray() reads the kept
rows out of the parsed document, which is most of the cost; the others
reuse them. A DataArray therefore costs about as much as the DataFrame of
release 0.4.0 did, and both add at most 3% to the simulation. The cell-first
order of 0.6.0 fills the array in the order of the kept rows; with the
time-first order of 0.5.0, paths took 1.02 and 1.15 times as long as
paths_frame() alone in the 0.5.0 measurement, against 0.98 and 0.93
times here. Memory, as
the peak of traced allocations during the conversion and the size of what
it returns:
| Conversion | Peak, monthly | Returned, monthly | Peak, weekly | Returned, weekly |
|---|---|---|---|---|
result.paths | 16.7 MB | 7.1 MB | 69.5 MB | 29.8 MB |
result.paths_frame() | 16.5 MB | 7.6 MB | 67.9 MB | 32.3 MB |
The DataArray holds cells × report times × observables × 8 bytes, NaN after a budget stop; the frame stores the same values with a (replicate, time) index. Event logs of at most 50 entries per cell, monthly reports:
| Log | Entries | event_columns() | event_frame() |
|---|---|---|---|
| the two mutation rules (at most 10 per cell here) | 8,626 | 0.023 s, 2.9 MB | 0.013 s, 0.6 MB |
| every rule, so every cell logs 50 | 200,000 | 0.23 s, 14.5 MB | 0.19 s, 13.6 MB |
The DataArray pads every cell to the longest log, so a sparse log takes
more memory as an array than as a frame; a full log takes about the same.
Parsing the full log’s JSON took 1.2 s, more than either conversion. The
peak traced allocation was 5.2 MB and 32 MB for event_columns(), against
1.4 MB and 30 MB for event_frame().
6. Other models and routes
| Workload | Wall s | Events | Wall ns per event |
|---|---|---|---|
| clone model, tree, K = 1000, 100 cells, no stop | 2.65 | 14.9 M | 177.6 |
| three-class model, tree, the same | 4.63 | 14.9 M | 310.2 |
| ATP model, thinning, 512 cells | 13.18 | 77.8 M | 169.3 |
-
Clone model. At K = 1000 the clone model is cheap: it has three rules instead of eight, and at this mutation probability few clones are alive at once. The tree method recomputes every rule per event, so fewer rules mean less work. Exact per-lineage bookkeeping is therefore affordable for thousands of cells. Event logs for it are limited by memory, not time.
-
ATP model. Thinning integrates the ATP flow between events and rejects a share of candidate events. Recorded on eight CPUs, 512 cells took 2.8 s, against 3.9 s for the Java implementation of the same model.
-
Generated loop. Opt-in. From Rust, the generated event loop runs Static Direct requests with byte-identical results. It covers every model that Static Direct runs (expression and string rates since 0.5.0) and is compiled for one model and parameter set; other requests are refused with
CRN-R020. On the 128-cell probe, with one thread, Ziggurat waits and sparse trackers (validation/mtdna/generated-loop.json), the costs per event were:Route ns per event interpreted Static Direct 112 Static Direct with the generated rates kernel 94 generated event loop 48 mtdna_direct38 It brings Static Direct’s identity close to the specialized sampler’s speed. It also works for models
mtdna_directdoes not certify, such as other stop conditions. From Python,crn.compile_loopbuilds the same loop with a local Rust toolchain (new in 0.4.0; user manual, section 8). The loop runs the linear scan, the selectorautopicks for this model. On the 1000-cell workload of section 2, end to end from Python, it took 18.1 against 40.1 ns per event under the Static Direct default (Ziggurat waits, sparse trackers; 2.21×) and 26.4 against 49.1 ns with inverse waits and per-event trackers (1.86×), on the two-CPU host (validation/mtdna/compiled-loop-python.json). Both routes were timed together on 6 November 2026, at a later commit than the table of section 2, so compare the ratio, not the absolute times.
7. Comparison with other implementations
Recorded on the same eight-CPU host, 10,000 cells, three years, takeover
stop, eight workers, two runs each
(validation/mtdna/java-gap.json):
| Implementation | Median wall s |
|---|---|
| CRN-craft Static Direct, 0.3.0 default | 43.40 |
| supplied Java SSA | 14.86 |
CRN-craft mtdna_direct | 8.62 |
The specialized sampler ran 1.72× faster than the Java SSA. The timings include each program’s own output: CRN-craft serialized about 20.9 MB of JSON with two class trackers, and Java wrote about 6.9 MB of reports.
The cross-checks agreed:
- Takeover counts: 1008 of 10,000 cells for CRN-craft, 1016 for Java.
- Takeover-time distributions: a distance of 0.003, within the declared bound of 0.041.
- Mutation counts: within 1% for both classes (17,030 and 4,236 against 16,975 and 4,277).
- Against Static Direct: every observable and the first passage of
mtdna_directagreed in distribution within the family bound.
The checks are in the same file.
Earlier recorded rows with 20 threads on the eight-CPU quota show the other methods:
- the Java hourly binomial scheme took 46.6 s;
- Static Direct with the takeover stop took 54.2 s before tuning and 48.4 s after.
A rebop implementation of the three-class model was reported to take 480 s
for 10,000 cells, because it computes trajectories one after another. It
was not rerun here. At its reported 11 s with 20 threads, the Java version
was 44× faster than that. mtdna_direct on eight CPUs is faster than both.
8. Sizing a study
Every column is for the fast path mtdna_direct. The two-CPU column uses
40 ns of CPU time per event, as measured here. The eight-CPU column uses
48 ns, as recorded for the 10,000-cell run on that host.
| Study | Events | mtdna_direct, 2 CPUs | mtdna_direct, 8 CPUs |
|---|---|---|---|
| 1,000 cells, 3 years, K = 1000 | 0.14 G | 3 s | 1 s |
| 10,000 cells, 3 years | 1.4 G | 29 s | 8.6 s (measured) |
| 10,000 cells, 30 years | at most 15 G | 5 min | 1.5 min |
| 100,000 cells, 3 years, K = 2000 | 29 G | 10 min | 2.9 min |
| the tutorial’s two-stage fit (100 × 800 and 33 × 2400 cells) | 23 G | 7.5 min (measured) | 2.3 min |
Static Direct, for any other closed model, takes about 3.3× these times
(3.9× with inverse waits), and the tree method about 14×.
Add the observation costs of section 4. Long horizons need a larger event
budget: max_events is per cell and must exceed 2 · δ · K · T.
Output and memory grow with what is kept, not with the events:
- Kept paths: cells × report times × observables × 8 bytes. For example,
10,000 cells × 37 reports × 6 observables is 18 MB, the size of
result.paths; converting it needs about 2.3 times that at its peak (section 5). - Event-log arrays:
result.event_columns()takes cells × the longest log × (observables + 3) × 8 bytes;event_frame()only the logged entries. - Event logs: up to
max_entriesper cell. A request is admitted only if its worst-case reservation fitsmax_output_bytes(default 64 MiB). For large logs, raise it or log fewer cells. - Statistics and records: small. Statistics accumulate while the ensemble runs.
9. Recommendations
- Pick the method by model.
- Any closed model: Static Direct,
method="static_direct", whose default uses Ziggurat waits and sparse trackers. Add"waiting_time": "inverse", "sparse_trackers": Falseto a method dictionary only to reproduce results of release 0.3.0. - Lineage identities: the clone model with the tree method.
- Variable population:
thinning. - The three-class structure: opt in with
mtdna_direct, with the stop absent or written asN > 0 && mutants >= f * N, and check the sampler. Record other thresholds with first-passage trackers, or kept paths, so that the stop keeps the certified form.
- Any closed model: Static Direct,
- Use as many threads as CPUs. Results do not change.
- Use exact methods at K = 1000. The approximate methods do not save time there.
- Choose observation by cost. Count trackers are free; a first-passage tracker or an event log doubles the cost; a Python callback is for a few cells.
- Optimize with
bind_parameterson a prepared run. Use evaluations of a few hundred to a few thousand cells, withmtdna_directwhere the model has its structure (optimization tutorial). - For the largest studies, use Rust. Call the engine directly, or use
the opt-in generated loop for closed models that
mtdna_directdoes not certify.
Reproducing
python examples/mtdna/performance.py all target/release/crn-craft
python validation/benchmark_mtdna.py --binary target/release/crn-craft --output mtdna-timing.json
python validation/check_generated_loop.py target/release/crn-craft target/release/examples --output generated-loop.json
The Java comparison needs the supplied Java sources, which are not part of the repository. The notes follow.
The Java comparison
Commands to rerun the checks, with the release binary and the wheel built and installed first:
cargo build --release --workspace --locked
python validation/check_mtdna.py --binary target/release/crn-craft --output mtdna-gates.json
python validation/check_rules_python.py --output mtdna-python.json
python validation/benchmark_mtdna.py --binary target/release/crn-craft --output mtdna-timing.json
The optional Java comparison accepts --java, --java-classpath and
--java-source. Use JDK 25 and Apache Commons RNG 1.6, compile the supplied
source locally, and supply a classpath containing its compiled classes and
the four Commons RNG jars. The benchmark writes only summaries to the
patch. The original Java material and per-trajectory output stay local.
For the eight-worker comparison, build the optional phase-timing example with
cargo build --release --locked -p crn-craft-rules --example benchmark_rules.
The baseline,
candidate and Java inputs are named in validation/benchmark_mtdna_gap.py. The saved evidence is
validation/mtdna/java-gap.json. The Java phase probe was built locally by
timing from before pool creation to after all futures were collected. The
end-to-end comparison used the original Java classes.
How the engine differs from the Java model. Java’s hourly implementation
groups simultaneous new mutants differently and keeps clone identities. The
supplied Java SSA uses the same ATP flow as the thinning method but freezes
rates over its sampled waiting interval. On 10,000 cells mtdna_direct agreed
with the Java implementation of the fixed-population model: the takeover-time
distributions were within the declared bound and the mutation counts within
1%.
CRN-craft compared with GillesPy2
Measured on 12 November 2026 with the unified engine of release 0.7.0
(branch merge/M10c at cec91ed, before the release commit, so the build
still reports the version string 0.6.0) and GillesPy2 1.8.3, Python 3.12.3
and g++ 13.3, on one shared two-CPU cloud host, every run under a CPU lock.
The protocol and the agreement rule were declared before the first run
(validation/merge/RESULTS.md, “M10c (GillesPy2 comparison on the unified
engine): declaration”). Script:
validation/compare_gillespy2.py;
raw report:
validation/merge/gillespy2-comparison-0.7.json.
An earlier comparison measured the network engine of release 0.2.0; it is
kept, separately, under History.
Summary
On these four networks GillesPy2’s compiled Direct-method solver
(SSACSolver) takes longer than CRN-craft on every network, with every
CRN-craft configuration except two selectors on the dense network:
- with CRN-craft’s default request (Static Direct, the
autoselector, Ziggurat waits), 2.9 times as long on a two-channel network, 10.6 times on a sparse 66-reaction network, 3.6 times on the 12-reaction repressilator and 9.3 times on a dense 66-reaction Michaelis–Menten network; - with the linear scan and inverse waits, the configuration closest to GillesPy2’s algorithm, 2.8, 5.6, 3.7 and 1.3 times as long.
GillesPy2’s pure Python solver (NumPySSASolver) takes 134 to 358 times as
long as CRN-craft’s default. Its C++ solver compiles each model before the
first run, which took 2.1 to 2.9 seconds. Both simulators sample the same
process: all 28 agreement tests passed the declared rule.

What was measured
| ID | Network | Reactions | Rate laws |
|---|---|---|---|
| W1 | immigration–death | 2 | mass action |
| W2 | 33 independent immigration–death species | 66 | mass action |
| W3 | three-gene repressilator | 12 | Hill repression and mass action |
| W4 | eight species born and removed together | 66 | mass action and gated Michaelis–Menten |
Each run simulates 64 paths over t from 0 to 100, with output at 0 and 100,
on one thread, root seed 4242. These are the frozen workloads of the earlier
performance campaigns. The network models are converted with
crn_craft.convert and run as crn-craft.run/1.0 requests. Each row is the
median of five interleaved runs (three for the NumPy solver).
How each row was timed:
- CRN-craft CLI: the wall time of one
crn-craft run MODEL REQUESTprocess for the default request, from start to exit, output included. - CRN-craft Python: the wall time of
crn.ensemble(...)and.simulate(), preparation, the native run and the pandas result included. Rows: the default request (autopicks the linear scan on W1 and W3 and RSSA-CR on W2 and W4), the linear scan with inverse waits (the checked configuration of release 0.6.0), and each selector with Ziggurat waits. - GillesPy2: the wall time of
model.run(solver=..., number_of_trajectories=64)with a solver object built beforehand. For the C++ solver this excludes the one-time compilation, reported separately.
Time per event divides by each CRN-craft row’s own event count, and for GillesPy2 by the event count of CRN-craft’s linear scan with inverse waits (1,274,177, 1,236,808, 3,648,339 and 1,228,794 events on W1 to W4). Both simulate the same process, so the expected number of events is the same.
Results
Median seconds for 64 paths:
| W1 | W2 | W3 | W4 | |
|---|---|---|---|---|
CRN-craft CLI run, default | 0.049 | 0.099 | 0.269 | 0.107 |
CRN-craft default (auto, Ziggurat) | 0.048 | 0.102 | 0.260 | 0.118 |
CRN-craft linear, inverse waits | 0.051 | 0.194 | 0.257 | 0.843 |
CRN-craft linear, Ziggurat | 0.049 | 0.208 | 0.262 | 0.789 |
CRN-craft composition_rejection, Ziggurat | 0.087 | 0.133 | 0.511 | 1.240 |
CRN-craft sorting, Ziggurat | 0.069 | 0.156 | 0.375 | 1.172 |
CRN-craft rssa_cr, Ziggurat | 0.066 | 0.103 | 0.406 | 0.113 |
GillesPy2 SSACSolver (C++) | 0.141 | 1.080 | 0.945 | 1.096 |
GillesPy2 NumPySSASolver | 6.50 | 31.95 | 37.41 | 42.30 |
| GillesPy2 C++ compile (once per model) | 2.85 | 2.14 | 2.07 | 2.29 |
Time per event, in nanoseconds:
| W1 | W2 | W3 | W4 | |
|---|---|---|---|---|
CRN-craft CLI run, default | 38 | 80 | 72 | 87 |
| CRN-craft default | 38 | 83 | 70 | 96 |
CRN-craft linear, inverse waits | 40 | 157 | 70 | 686 |
CRN-craft composition_rejection | 69 | 108 | 124 | 1,008 |
CRN-craft rssa_cr | 52 | 83 | 107 | 92 |
| GillesPy2 C++ | 111 | 873 | 259 | 892 |
| GillesPy2 NumPy | 5,098 | 25,834 | 10,255 | 34,423 |
How many times longer GillesPy2’s C++ solver takes than CRN-craft:
| W1 | W2 | W3 | W4 | |
|---|---|---|---|---|
CRN-craft CLI run, default | 2.90 | 10.86 | 3.51 | 10.23 |
| CRN-craft default | 2.91 | 10.56 | 3.63 | 9.27 |
CRN-craft linear, inverse waits | 2.78 | 5.57 | 3.68 | 1.30 |
CRN-craft composition_rejection | 1.61 | 8.14 | 1.85 | 0.88 |
CRN-craft sorting | 2.04 | 6.92 | 2.52 | 0.93 |
CRN-craft rssa_cr | 2.13 | 10.54 | 2.33 | 9.67 |
Run-to-run spread: most timed runs lie within 10% of their median. Single
CRN-craft runs deviated by up to 34% (rssa_cr on W2) and GillesPy2’s C++
solver by up to 7%; the medians are robust to these outliers. On W1 and W3
the default and the linear scan with Ziggurat waits are the same computation,
so their difference is noise.
Reading the results
-
The per-event strategies differ. In GillesPy2 1.8.3 (
SSASolver.cpp), after each event the C++ solver:- recomputes only the propensities the fired reaction affects;
- sums all propensities again;
- picks the reaction by a linear scan;
- loops over all species to apply the update.
CRN-craft’s linear scan also recomputes only the affected rates, but it resumes its running total at the first changed channel and changes only the species the channel changes. On the sparse network (W2), where each reaction changes one species and one rate, that makes it 5.6 times faster.
-
The selector matters most on W2 and W4. The default
autopicks RSSA-CR there. On W4 every event changes all 33 Michaelis–Menten death rates; RSSA-CR keeps bounds on them and evaluates a rate only when a bound cannot decide, so it needs far fewer rate evaluations than any Direct scan. With the linear scan W4 is 1.3 times faster than GillesPy2; with RSSA-CR 9.3 times. Composition–rejection and sorting are slower than GillesPy2 on W4 and are not whatautopicks there. -
Every configuration keeps CRN-craft’s checks. On every event it checks that no positive rate is lost to rounding or too small to be selected, draws from a ChaCha8 stream per path, polls for cancellation, and gives byte-identical results for every thread count. GillesPy2 makes none of these checks. Release 0.6.0 had an opt-in
fastpolicy that dropped the per-event checks; the unified engine has no such switch, so these rows are the checked engine. -
Compilation matters for short jobs. GillesPy2’s C++ solver compiles each model before its first run, in 2.1 to 2.9 seconds, about 20 times the W1 run itself. CRN-craft needs no per-model compilation.
-
The NumPy solver evaluates propensities in Python and takes 134 to 358 times as long as CRN-craft’s default.
The two tools simulate the same process
Before timing, both simulators ran 512 paths of each network with fixed, different seeds, twice: once with CRN-craft’s linear scan and inverse waits, once with its default. The declared rule: with a family-wise error rate of 0.01 over the 28 tests below (Bonferroni), a p-value below 3.6e-4 is a failure; on W4 every species must stay equal within each path.
- Final counts agree. Two-sample Kolmogorov–Smirnov tests compared the final counts of up to three species per network: 20 tests, smallest p-value 0.209. Every mean z-score is at most 1.47 in absolute value.
- The exact law agrees. W1 and W2 have Poisson laws at t = 100, with means 100 and 15. Pooled chi-square tests against them: 8 tests (both simulators, both CRN-craft configurations), smallest p-value 0.044 (GillesPy2 on W2).
- W4: all eight species stay equal in every path of both simulators, as the network’s structure requires.
No test failed.
How the models were translated
- Mass action: as GillesPy2 mass-action reactions. W1–W4 have only zeroth- and first-order reactants, so no combinatorial convention differs.
- Hill repression: as the propensity expression
basal + vmax / (1 + pow(x/K, n)). - Michaelis–Menten: as
vmax * S / (Km + S). - Reactant gates. CRN-craft fires a whole-rule propensity only when its
reactants are present. GillesPy2 expressions have no comparisons, so a gate
is written as
x / (x + 1e-300), which is exactly 0 for x = 0 and 1 otherwise. - W4 is timed without gates. Its eight species always stay equal, so the gates on its Michaelis–Menten deaths never change a propensity. The validation confirms this. With the gates, GillesPy2’s C++ solver took 9.32 seconds instead of 1.10, about 8.5 times longer. That cost belongs to the translation rather than to GillesPy2, so the comparison uses the faster form; the gated time is in the raw report.
Limitations
- Host: one shared two-CPU cloud host. Absolute times differ on other machines, and the ratios may too.
- Random streams are independent, so this compares cost for the same process, not identical paths.
- Event counts: GillesPy2’s are not instrumented. Its time per event uses CRN-craft’s count, and the 64-path counts of the two tools differ by sampling noise.
- What the timings include: GillesPy2’s include building its result objects and, for the C++ solver, launching its compiled program and parsing its output. CRN-craft’s Python rows include preparation and the conversion of the result into pandas objects.
- Scope: only exact SSA on one thread. CRN-craft can also divide replicates among threads without changing results. GillesPy2 also offers tau-leaping, hybrid and ODE solvers, which are not compared here.
- Workload size: the networks are small to medium (up to 66 reactions).
- Build: measured on a tree that still contained the network engine’s code, before its deletion; the methods measured here do not call it.
Reproducing
python -m pip install -r validation/reference-requirements.txt
maturin build --release --locked --out dist && python -m pip install dist/*.whl
cargo build --release --workspace --locked
python validation/compare_gillespy2.py --binary target/release/crn-craft \
--output gillespy2.json --figure gillespy2.png
GillesPy2 builds its C++ solver with SCons through python3 on the PATH,
so SCons must be importable there; with the virtual environment’s bin
first on the PATH that is the environment’s own Python. The script needs a
C++ compiler and takes about ten minutes, mostly in the NumPy solver.
--only W1 measures one workload; the report above merges four such runs.
History: the network engine of 0.2.0
These numbers were measured on 2 November 2026 with CRN-craft
0.2.0-dev.1, the network engine that release 0.7.0 replaced, and are not
comparable with the tables above: another engine, another random stream,
Python 3.13, and the fast policy, which dropped the per-event checks.
Raw report: validation/fast/gillespy2-comparison-fast.json;
the first comparison (1 November, checked policy only) is in
validation/campaign/gillespy2-comparison.json.
Median seconds for 64 paths, 2 November 2026 (0.2.0-dev.1):
| W1 | W2 | W3 | W4 | |
|---|---|---|---|---|
CRN-craft fast cached Direct | 0.039 | 0.083 | 0.179 | 0.498 |
CRN-craft fast DirectCR | 0.057 | 0.075 | 0.273 | 0.647 |
CRN-craft fast SortingDirect | 0.046 | 0.102 | 0.193 | 0.639 |
CRN-craft fast RSSACR | 0.058 | 0.083 | 0.309 | 0.083 |
CRN-craft simulate-cached (checked) | 0.062 | 0.190 | 0.284 | 0.678 |
CRN-craft simulate (checked) | 0.065 | 0.586 | 0.415 | 0.821 |
GillesPy2 SSACSolver (C++) | 0.113 | 0.681 | 0.646 | 0.761 |
GillesPy2 NumPySSASolver | 4.42 | 24.4 | 27.5 | 31.5 |
| GillesPy2 C++ compile (once per model) | 4.7 | 1.7 | 1.6 | 1.8 |

CRN-craft compared with Catalyst.jl and JumpProcesses.jl
Measured with the 0.6.0 network engine (note of 12 November 2026). The CRN-craft numbers on this page come from the network engine of releases 0.2.0 to 0.6.0 (its
simulate,simulate-cachedandssaroutes). Release 0.7.0 replaced that engine with one engine, whose selectors are ports of the methods measured here. Julia is not available on the host of the 0.7.0 measurements, so these comparisons were not repeated, and the tables below are left as measured. For the 0.7.0 engine against the 0.6.0 network engine on the same host, see the speed gate andvalidation/merge/RESULTS.md(“M4d (speed gate): results”).
Measured before the 0.2.0 release. These measurements come from development builds of 2 November 2026 and have not been repeated on release 0.2.0 (4 November 2026). The network SSA engine changed in between:
fastbecame the default ofssarequests (crn-craft.ssa-run/0.3), the Ziggurat waiting-time sampler was refactored so the rules engine can share it, andcrn-craft.ssa-run/0.4added thenext_reactionaggregator, which this comparison does not include. Requests of the measured versions return the same results as before; their timings on 0.2.0 may differ.
Updated 2 November 2026, after the five-step exact-SSA acceleration campaign.
CRN-craft 0.2.0-dev.1 now has DirectCR, SortingDirect, RSSACR, reusable Python
preparation and a separately versioned exponential Ziggurat sampler. Julia remains
1.13.3, Catalyst 17.0.0, and
JumpProcesses 10.0.1. Exact source hashes are
retained in the measurement report. The implementation was then an unpushed
patch over GitHub base baed0e4590f93e4c1dcc77cd7f039a2604a1594c; it has since
been merged and released in 0.2.0.
The largest measured improvement over legacy cached Direct is 6.71× on W6; W4 improves 4.04×. Julia’s fastest measured method remains 1.54–2.39× faster than the fastest CRN option across these seven workloads. The fastest observed CRN prepared median beats Julia on 0 of 7 workloads. All slower variants and timing observations remain in the tables and raw evidence. The rightmost column compares the current legacy cached solver with the best CRN option at the same prepared boundary. Ratios use unrounded medians; CRN / Julia above 1 means Julia was faster.
| Workload | Fastest CRN prepared | Seconds | Fastest Julia | Seconds | CRN / Julia | Cached / best CRN |
|---|---|---|---|---|---|---|
| W1 | CRN Legacy cached | 0.0785 | Julia Direct | 0.0511 | 1.54× | 1.00× |
| W2 | CRN SortingDirect · ziggurat | 0.1827 | Julia DirectCR | 0.0968 | 1.89× | 1.19× |
| W3 | CRN Legacy cached | 0.7048 | Julia SortingDirect | 0.2944 | 2.39× | 1.00× |
| W4 | CRN RSSACR · ziggurat | 0.2379 | Julia RSSACR | 0.1061 | 2.24× | 4.04× |
| W5 | CRN RSSACR · ziggurat | 0.1051 | Julia DirectCR | 0.0477 | 2.20× | 2.39× |
| W6 | CRN RSSACR · ziggurat | 0.0874 | Julia RSSACR | 0.0396 | 2.21× | 6.71× |
| W7 | CRN RSSACR · ziggurat | 0.0238 | Julia RSSACR | 0.0133 | 1.79× | 1.63× |
Measured with fast (2 November 2026). A direct same-host rerun with
fast engines and five Julia methods at one and eight workers is in
fast mode versus Julia at one and eight threads.
Geometric mean of the best fast method’s time over Julia’s best: 0.69× at
eight workers and 1.15× at one worker on the original batches; 1.04× and 1.12×
on 256-path batches. It supersedes the projection below, which is kept as
recorded.
Update with fast (projected, not remeasured). Comparisons now time
CRN-craft with the fast switch (then opt-in), which emulates JumpProcesses’ policy
(Xoshiro256++, running totals without loss or resolution checks, batched stop
polls; see the 0.6.0 README).
Julia’s package hosts were again unreachable, so this table scales the CRN
prepared medians of Astra’s same-host rerun
(gap10 comparison, validation/julia-gap10/comparison.json)
by the paired fast/default speedups measured on a different host
(validation/fast/fast-vs-default.json). It is a projection, not a Julia
measurement.
| Workload | Fastest projected CRN with fast | Projected seconds | Fastest Julia | Julia seconds | CRN / Julia |
|---|---|---|---|---|---|
| W1 | cached Direct | 0.0493 | Direct | 0.0506 | 0.97× |
| W2 | cached Direct | 0.0849 | RSSACR | 0.0980 | 0.87× |
| W3 | cached Direct | 0.2322 | SortingDirect | 0.2920 | 0.80× |
| W4 | RSSACR | 0.1137 | RSSACR | 0.1072 | 1.06× |
| W5 | DirectCR | 0.0580 | DirectCR | 0.0484 | 1.20× |
| W6 | RSSACR | 0.0544 | RSSACR | 0.0388 | 1.40× |
| W7 | cached Direct | 0.0133 | RSSACR | 0.0138 | 0.96× |
Projected geometric mean 1.02× (checked default, measured by Astra on the same
host: 1.44×). A direct rerun with fast engines remains the authoritative check.
Update after the Julia-gap campaign (projected, not remeasured). A follow-up campaign (protocol, log) kept five of ten iterations under predeclared rules: AVX2 ChaCha8 dispatch, an exact Hill-rate memo, a cached composition envelope, a sums-only lazily checked rate tree and a joint member/acceptance word. Julia’s package hosts were unreachable from that session, so the table multiplies the CRN medians above by the paired speedups measured on another host; it is not a Julia measurement, and the tables below remain the measured comparison.
| Workload | Fastest projected CRN | Projected seconds | Fastest Julia | CRN / Julia |
|---|---|---|---|---|
| W1 | Legacy cached | 0.0749 | Direct | 1.47× |
| W2 | DirectCR | 0.1272 | DirectCR | 1.31× |
| W3 | SortingDirect | 0.3278 | SortingDirect | 1.11× |
| W4 | RSSACR | 0.1946 | RSSACR | 1.83× |
| W5 | DirectCR | 0.0768 | DirectCR | 1.61× |
| W6 | RSSACR | 0.0614 | RSSACR | 1.55× |
| W7 | RSSACR | 0.0187 | RSSACR | 1.41× |
The projected geometric-mean gap is 1.46× (measured 2.02× before). A direct
rerun of validation/compare_julia_accelerated.py remains the authoritative
check.

The earlier comparison is preserved. Its absolute times are historical, not observations combined with this rerun. The GillesPy2 report uses the same W1–W4 models but was not rerun here, so this is not a three-way timing comparison.
What was implemented
| Step | Delivered change | What the evidence supports |
|---|---|---|
| 1 | Component profiling and immutable prepare / prepare_ssa handles | Preparation is a small fraction of the original W1–W4 batches; reusable calls preserve results and support concurrent reuse |
| 2 | DirectCR with dependency updates and power-of-two composition/rejection | Removes ordered-prefix maintenance; balanced-tree and rejection costs can dominate small/dense workloads |
| 3 | SortingDirect and a versioned Ziggurat wait sampler | Both execute and replay; changing only the wait sampler does not guarantee an end-to-end gain |
| 4 | RSSACR with certified integer-box bounds, exact point fallbacks and explicit rejected-work limits | Avoids many actual-rate evaluations while preserving gates, absorption and checked state updates |
| 5 | Fresh Julia rerun and three larger connected networks | Shows where algorithm choice pays and where a measured gap remains |
This reimplements relevant algorithmic techniques in Rust; it does not recreate
Julia’s compiler, symbolic model generator or complete solver ecosystem.
Implementation details and API examples explain the
published algorithm families, numerical policy and new contracts. The old
Direct/cached interfaces, schemas and byte identities are preserved. New methods
return ssa-result/0.1 JSON, not a legacy sealed archive.
Models and timing boundaries
| ID | Network | Species | Reactions | Paths | Horizon |
|---|---|---|---|---|---|
| W1 | Immigration–death | 1 | 2 | 64 | 100.0 |
| W2 | Sparse independent channels | 33 | 66 | 64 | 100.0 |
| W3 | Repressilator | 6 | 12 | 64 | 100.0 |
| W4 | Dense synchronized custom rates | 8 | 66 | 64 | 100.0 |
| W5 | Diffusion chain | 256 | 510 | 16 | 20.0 |
| W6 | Dense conversion | 32 | 992 | 16 | 20.0 |
| W7 | Compartment binding/diffusion | 96 | 126 | 16 | 20.0 |
W1–W4 are unchanged. W5 has 256 species, four initial molecules each, and
nearest-neighbor conversion at rate 0.5 in each direction. W6 has 32 species,
32 initial molecules each, with heterogeneous pairwise conversion rates
0.005 * (1 + (7*i + 11*j) % 8). W7 has 32 compartments, each initially
A=24, B=12, C=4; A+B binds at 0.015, C dissociates at 0.5, and A diffuses
between adjacent compartments at 0.1. Frozen JSON and hashes accompany the
report. All channels remain separate.
All batches use one numerical worker, seed 4242 and saves at 0 and the horizon. Julia uses one advancing Xoshiro stream per batch; CRN uses its pinned per-path ChaCha8 streams. Matching seed numbers do not imply matching paths. Five rounds use a deterministic shuffled order, then rotate/reverse it. No build or heavy validation runs during the final warm rounds. No outlier is removed.
| Boundary | Included | Outside the warm timer |
|---|---|---|
| CRN one-shot | Request encoding, native validation/model preparation, simulation, standard metadata/statistics, result encoding and Python decoding | Model bytes/request dictionary creation; archive I/O |
| CRN prepared | Simulation, standard metadata/statistics, result encoding and Python decoding | Validation and preparation; archive I/O |
| Julia | Serial solve calls with SSAStepper, per-path initialization, saved-time/count checks, final statistics reduction | Catalyst construction/JIT setup, copy of pristine batch problem, JSON IPC |
These are application-level boundaries with different result/allocation policies, not isolated equal-instruction kernels. Julia reuses its problem within each batch, including SortingDirect’s learned order, and starts each batch from a pristine copy [1]. CRN resets ordering per replicate to retain worker-count replay. Prepared calls produce identical results to one-shot calls.
Host: AMD EPYC 9V74 80-Core Processor, Linux x86-64, affinity
9 logical CPUs and cgroup quota
800000 100000. Release Rust 1.88.0, Python 3.12.14,
NumPy 2.5.4; Julia and BLAS each use one thread.
This shared-host study has five observations per row, not confidence intervals.
Warm results
Seconds per batch: median [minimum–maximum]. CRN rows below use prepared calls.
| Implementation | W1 | W2 | W3 | W4 |
|---|---|---|---|---|
| CRN Legacy Direct | 0.0969 [0.0846–0.1024] | 0.7687 [0.7063–0.8075] | 1.7306 [1.6950–1.7531] | 1.0605 [0.9925–1.0956] |
| CRN Legacy cached | 0.0785 [0.0773–0.0877] | 0.2172 [0.1983–0.2383] | 0.7048 [0.6622–0.7436] | 0.9617 [0.8796–1.0463] |
| CRN Direct · inverse | 0.0974 [0.0909–0.1394] | 0.7595 [0.6941–0.9150] | 1.7668 [1.7016–1.9261] | 0.9886 [0.9325–1.0286] |
| CRN Direct · ziggurat | 0.0840 [0.0755–0.1115] | 0.7304 [0.6974–0.8393] | 1.7824 [1.7421–2.0256] | 0.9909 [0.9107–1.0264] |
| CRN Cached · inverse | 0.0932 [0.0872–0.0982] | 0.2252 [0.2117–0.2634] | 0.7225 [0.6641–0.7381] | 0.9167 [0.8924–0.9607] |
| CRN Cached · ziggurat | 0.0790 [0.0718–0.0926] | 0.2305 [0.2128–0.2476] | 0.7105 [0.6834–0.7723] | 0.9101 [0.8855–0.9507] |
| CRN DirectCR · inverse | 0.1591 [0.1433–0.1644] | 0.2037 [0.1885–0.2754] | 1.1336 [1.0082–1.2327] | 2.0358 [2.0132–2.1290] |
| CRN DirectCR · ziggurat | 0.1423 [0.1205–0.1516] | 0.1831 [0.1809–0.1881] | 1.0168 [1.0017–1.0350] | 2.0256 [1.8392–2.0796] |
| CRN SortingDirect · inverse | 0.0972 [0.0914–0.1194] | 0.1914 [0.1748–0.2126] | 0.8591 [0.7733–0.8979] | 1.8645 [1.8236–2.0355] |
| CRN SortingDirect · ziggurat | 0.0869 [0.0805–0.0903] | 0.1827 [0.1615–0.1978] | 0.7638 [0.7404–0.7645] | 1.8914 [1.6817–1.9740] |
| CRN RSSACR · inverse | 0.1624 [0.1429–0.1742] | 0.2001 [0.1885–0.2201] | 0.9058 [0.8826–0.9628] | 0.2494 [0.2271–0.2621] |
| CRN RSSACR · ziggurat | 0.1253 [0.1235–0.1293] | 0.1951 [0.1750–0.2486] | 0.8548 [0.8259–0.8794] | 0.2379 [0.2124–0.2434] |
| Julia Direct | 0.0511 [0.0507–0.0589] | 0.2014 [0.1897–0.2072] | 0.4299 [0.3952–0.4665] | 0.2576 [0.2488–0.3090] |
| Julia SortingDirect | 0.0593 [0.0537–0.0649] | 0.1354 [0.1281–0.1421] | 0.2944 [0.2653–0.3124] | 0.5682 [0.5081–0.6299] |
| Julia DirectCR | 0.0824 [0.0798–0.1071] | 0.0968 [0.0924–0.1012] | 0.4201 [0.4050–0.4772] | 0.7665 [0.7599–0.8674] |
| Julia NRM | 0.0688 [0.0663–0.0744] | 0.1293 [0.1127–0.1408] | 0.3564 [0.3458–0.4121] | 1.0269 [0.9296–1.1018] |
| Julia RSSACR | 0.0699 [0.0687–0.0897] | 0.1087 [0.1015–0.1119] | 0.3355 [0.3292–0.3662] | 0.1061 [0.0965–0.1126] |
| Implementation | W5 | W6 | W7 |
|---|---|---|---|
| CRN Legacy Direct | 1.6425 [1.6100–1.8219] | 2.1672 [2.1203–2.5283] | 0.1472 [0.1382–0.1606] |
| CRN Legacy cached | 0.2506 [0.2408–0.2798] | 0.5858 [0.5500–0.6724] | 0.0387 [0.0370–0.0415] |
| CRN Direct · inverse | 1.4742 [1.3870–1.4846] | 2.1579 [1.9829–2.4537] | 0.1313 [0.1257–0.1503] |
| CRN Direct · ziggurat | 1.4967 [1.4352–1.6837] | 2.1055 [1.9690–2.3088] | 0.1312 [0.1295–0.1383] |
| CRN Cached · inverse | 0.2583 [0.2453–0.2818] | 0.5452 [0.5036–0.6125] | 0.0389 [0.0382–0.0448] |
| CRN Cached · ziggurat | 0.2543 [0.2410–0.2778] | 0.5779 [0.4825–0.6720] | 0.0382 [0.0373–0.0396] |
| CRN DirectCR · inverse | 0.1167 [0.1098–0.1260] | 0.8003 [0.7205–0.9128] | 0.0352 [0.0336–0.0414] |
| CRN DirectCR · ziggurat | 0.1158 [0.1149–0.1259] | 0.7796 [0.7275–1.0170] | 0.0365 [0.0342–0.0424] |
| CRN SortingDirect · inverse | 0.2026 [0.1843–0.2657] | 0.8717 [0.8162–0.9171] | 0.0363 [0.0337–0.0463] |
| CRN SortingDirect · ziggurat | 0.2184 [0.1924–0.2381] | 0.8177 [0.7745–0.9597] | 0.0325 [0.0314–0.0344] |
| CRN RSSACR · inverse | 0.1064 [0.1056–0.1176] | 0.0936 [0.0833–0.0991] | 0.0273 [0.0252–0.0283] |
| CRN RSSACR · ziggurat | 0.1051 [0.0925–0.1209] | 0.0874 [0.0794–0.0989] | 0.0238 [0.0226–0.0249] |
| Julia Direct | 0.4734 [0.4393–0.5122] | 0.6984 [0.5991–0.7322] | 0.0404 [0.0389–0.0414] |
| Julia SortingDirect | 0.1238 [0.1167–0.1451] | 0.2185 [0.2134–0.2302] | 0.0152 [0.0144–0.0176] |
| Julia DirectCR | 0.0477 [0.0462–0.0614] | 0.2286 [0.1975–0.2290] | 0.0143 [0.0139–0.0155] |
| Julia NRM | 0.0648 [0.0606–2.1120] | 0.3065 [0.2801–0.3471] | 0.0182 [0.0172–0.0215] |
| Julia RSSACR | 0.0551 [0.0534–0.0652] | 0.0396 [0.0381–0.0447] | 0.0133 [0.0127–0.0134] |
The best-new-method boundary comparison is below. All one-shot/prepared observations for every method are in the raw report, including slower choices.
| Workload | Best new method | One-shot seconds | Prepared seconds | One-shot / prepared |
|---|---|---|---|---|
| W1 | CRN Cached · ziggurat | 0.0763 | 0.0790 | 0.97× |
| W2 | CRN SortingDirect · ziggurat | 0.1745 | 0.1827 | 0.96× |
| W3 | CRN Cached · ziggurat | 0.7494 | 0.7105 | 1.05× |
| W4 | CRN RSSACR · ziggurat | 0.2220 | 0.2379 | 0.93× |
| W5 | CRN RSSACR · ziggurat | 0.1047 | 0.1051 | 1.00× |
| W6 | CRN RSSACR · ziggurat | 0.1141 | 0.0874 | 1.31× |
| W7 | CRN RSSACR · ziggurat | 0.0260 | 0.0238 | 1.09× |
Event normalization is secondary. Julia event counts were not instrumented: its following values use the legacy CRN count as an explicitly labelled proxy.
| Workload | Best CRN ns / its event | Julia ns / CRN-event proxy |
|---|---|---|
| W1 | 62 | 40 |
| W2 | 148 | 78 |
| W3 | 192 | 80 |
| W4 | 193 | 87 |
| W5 | 322 | 146 |
| W6 | 379 | 173 |
| W7 | 221 | 123 |
Why the results change
The first-step component measurements found roughly 3 ns per random word and 16–18 ns per inverse exponential draw, but preparation savings were small on the original W1–W4 batches. On W6, RSSACR/Ziggurat took 0.1141 s one-shot versus 0.0874 s prepared, but RSSACR/inverse moved only from 0.1076 s to 0.0936 s, and one-shot calls were faster than prepared ones on W1, W2 and W4; with five shared-host observations per row, the reuse benefit is not resolved. These diagnostic component timings include their own API overhead; they are not additive percentages of total simulation time.
The new selectors use checked balanced sums and bounded sampling. They pay for tree maintenance, accounting and rejection draws, so replacing a compact prefix scan can make a small or dense model slower. RSSACR instead changes how often actual propensities are evaluated. The following measured work counts compare cached inverse sampling with RSSACR/Ziggurat at the same batch size; their random paths and accepted event counts differ.
| Workload | Cached rate evaluations | RSSACR rate evaluations | RSSACR bound updates | Rejected RSSA candidates | Accepted RSSACR events |
|---|---|---|---|---|---|
| W1 | 1,268,293 | 156,153 | 11,635 | 61,800 | 1,274,865 |
| W2 | 1,238,800 | 478,052 | 51,718 | 165,599 | 1,238,950 |
| W3 | 7,327,468 | 3,586,831 | 113,798 | 737,179 | 3,861,776 |
| W4 | 40,459,683 | 3,358,943 | 91,311 | 2,641 | 1,230,636 |
| W5 | 1,308,542 | 709,855 | 21,215 | 351,266 | 326,332 |
| W6 | 14,196,140 | 1,710,433 | 551,087 | 28,824 | 230,450 |
| W7 | 514,625 | 155,348 | 20,308 | 49,808 | 108,043 |
W4 is a particularly favorable RSSA case: every event changes all eight species and all 33 custom death propensities, while bounded rejection can reuse their envelopes. It is deliberately synthetic and has an equal-count invariant; its behavior does not predict arbitrary dense-network performance. W5–W7 add connected sparse, densely connected and compartmental structures but remain synthetic. The full median tables, not an algorithm name alone, determine the measured winner for each model.
No compiler-level attribution follows from these timings. Remaining differences can include selection/summation design, bounds, checked count updates, RNG and wait generation, generated rate code, metadata and API costs. This campaign does not isolate the individual contribution of each difference.
Correctness before speed
The protocol was committed before experiments. The final engine passed 181 release tests, strict clippy/fmt, legacy path/CME gates, 69 schema/CLI checks, normal/-O native/Python/prepared/concurrent checks, and the unchanged default dependency gate. Rust 1.85 MSRV results are retained separately.
Every one of the ten method/wait combinations ran 100,000 paths on each of the three linear and four nonlinear fixtures: 7,000,000 paths per full pass. All 210 marginal comparisons passed. With family alpha 0.001, the frozen DKW limit is 0.00804612; the largest observed error is 0.00491533. Wrong homodimer conventions were rejected. Normal and Python -O final reports are byte-identical. Additional million-sample categorical/exponential gates passed, as did forced tail/rejection limits and independent enumeration of gated integer boxes. No tolerance was relaxed after a failure.
The Julia comparison ran 512 validation paths per engine/model: 60,928 paths
across 17 engines and seven workloads. W1/W2 use exact Poisson terminal laws;
other species are checked against legacy cached SSA. With K=6,946 and family
alpha 0.01, the one-sample bound is sqrt(log(2K/alpha)/(2N)), and the conservative
two-sample bound is 2*sqrt(log(4K/alpha)/(2N)). This latter bound applies the
one-sample inequality to both empirical CDFs and uses the triangle inequality.
No independence between species is assumed for the union bound.
| Workload | Checks | Largest CDF distance | Bound | Result |
|---|---|---|---|---|
| W1 | 17 | 0.05650 | 0.11753 | Pass |
| W2 | 561 | 0.06452 | 0.11753 | Pass |
| W3 | 96 | 0.07812 | 0.24075 | Pass |
| W4 | 128 | 0.06250 | 0.24075 | Pass |
| W5 | 4096 | 0.12109 | 0.24075 | Pass |
| W6 | 512 | 0.10742 | 0.24075 | Pass |
| W7 | 1536 | 0.12500 | 0.24075 | Pass |
The “Checks” column counts every engine/species comparison, including rows that
cannot fail. On W3–W7, three CRN engines (legacy_direct, direct/inverse and
cached_direct/inverse) reproduce the legacy cached reference sample exactly at
the shared seed, and direct/ziggurat reproduces cached_direct/ziggurat; their
distance is 0 by construction (W3 18 of 96 rows, W4 24 of 128, W5 768 of 4096,
W6 96 of 512, W7 288 of 1536). All engines also share the legacy random streams
at that seed, so even different methods are correlated with the reference, which
weakens a two-sample test that assumes independent samples. With N=512 the
two-sample gate detects only CDF differences above 0.24. For W3–W7 these checks
are therefore translation checks of Julia against legacy cached SSA; the
100,000-path exact-law gate above is the evidence for the new methods’ laws.
Future runs should use distinct seeds per engine and report distinct-sample
comparisons separately.
Propensity and stoichiometry probes passed on all seven models. W5/W6 preserve total molecule count; W7 preserves global A+C and each compartment’s B+C; W4 retains equal counts. Every timed batch reproduces its own numerical digest. Compressed sample files retain all individual terminal counts. These conservative terminal checks are useful translation checks, not proofs about rare tails or arbitrary model equivalence; the larger 100,000-path laws provide a separate gate.
Catalyst uses ordinary mass-action arrows with the combinatorial convention and full-rate arrows for custom laws. As in the original comparison, W4’s redundant Julia availability gates are omitted only on its equal-count reachable class. The Hill and Michaelis–Menten reference bounds are valid for these translated single-variable monotone laws [2]. CRN’s new bounds also handle the distinct-gate and consumed-repressor cases tested separately. Arbitrary nonmonotone Julia rates need sound user-supplied bounds; this benchmark does not authorize endpoint-only bounds for them.
Startup, scope and retained evidence
The fresh timing process took 71.91 s to its ready response, including 9.65 s of package imports and 52.36 s of setup for all seven models and five algorithms. These nested figures are not additive and are not per-model startup costs. Installation/precompilation and Rust/wheel builds are excluded. A long-lived Julia process amortizes setup. Individual setup/first-use observations are retained.
Catalyst/JumpProcesses still offers a richer symbolic/programmatic modeling interface and additional exact algorithms such as NRM and Coevolve [2]. This patch focuses on CRN-craft’s four existing built-in rate laws and strict JSON execution contracts. It does not add arbitrary time-dependent rates, hybrid jump–ODE models, spatial solvers, distributed execution, GPU support or new FSP/ ODE algorithms. Existing CRN FSP, approximate leaps and optional fitting/ODE integrations are outside these timings.
One shared host, one worker, seven models and five rounds cannot establish a universal ranking, parallel scaling, memory scaling or production workload result. Algorithm choice and bracket tuning can change outcomes. Ziggurat changes paths and must keep its separate sampler identity. New exact-method JSON has no sealed archive wrapper yet. Other-platform wheels were not tested.
Reproduce with validation/ssa-acceleration/README.md.
The raw timing report
contains 1,015 observations; the validation report
contains all 6,946 checks and hashes of the sample files, sources and pinned Julia
environment. The implementation log
retains development failures and the absorption follow-up. The intentionally
interrupted validation is kept separately and is not used for these conclusions.
The figure and this document can be regenerated with
python validation/render_acceleration_report.py.
Sources checked 2 November 2026; timing and validation values are our measurements:
- JumpProcesses problem reuse and SortingDirect replay.
- Jump types, exact algorithms, dependency graphs, rate bounds and original papers.
- Catalyst model semantics and full-rate DSL arrows.
- Julia 1.13.3 exponential sampler source; adapted MIT notices accompany the patch.
CRN-craft compared with Catalyst.jl and JumpProcesses.jl
Measured with the 0.6.0 network engine (note of 12 November 2026). The CRN-craft numbers on this page come from the network engine of releases 0.2.0 to 0.6.0 (its
simulate,simulate-cachedandssaroutes). Release 0.7.0 replaced that engine with one engine, whose selectors are ports of the methods measured here. Julia is not available on the host of the 0.7.0 measurements, so these comparisons were not repeated, and the tables below are left as measured. For the 0.7.0 engine against the 0.6.0 network engine on the same host, see the speed gate andvalidation/merge/RESULTS.md(“M4d (speed gate): results”).
Historical snapshot. This is the comparison before the exact-SSA acceleration campaign, kept as measured on a development build. For later results see the updated comparison and fast mode versus Julia; none of them has been repeated on release 0.2.0.
Measured on 2 November 2026 with CRN-craft 0.2.0-dev.1, commit
baed0e4,
Julia 1.13.3, Catalyst 17.0.0 and JumpProcesses 10.0.1.
This repeats the four frozen workloads of the
GillesPy2 comparison,
with fresh measurements of both engines on the same host.
Harness: validation/compare_julia.py.
Raw measurements and final samples:
validation/campaign/julia-comparison.json.
Pinned Julia environment and reproduction notes:
validation/julia/.
Summary
The fastest measured Julia algorithm beats CRN-craft’s cached Direct solver on all four networks in warm, single-worker execution. The advantage ranges from 1.67× to 8.23×, but the winning Julia algorithm changes with the model.
| Network | Fastest observed Julia median | CRN cached / Julia time |
|---|---|---|
| W1: immigration–death | Direct | 1.67× |
| W2: sparse 66 reactions | DirectCR | 2.25× |
| W3: repressilator | SortingDirect | 2.57× |
| W4: dense 66 reactions | RSSACR | 8.23× |
These are ratios of medians, calculated from unrounded measurements. They do
not mean every Julia algorithm wins: on W4, SortingDirect and NRM are
slower than CRN-craft cached Direct, while DirectCR is effectively tied.
The five tested Julia algorithms all passed the declared model and
distribution checks.
Catalyst supplies the symbolic reaction model and generates jump problems;
JumpProcesses supplies the SSA algorithms and SSAStepper. This comparison
uses that actual stack, including its mass-action specialization and generated
dependency information. It does not substitute a hand-written Julia SSA.

What was measured
| ID | Network | Species | Reactions | Propensities |
|---|---|---|---|---|
| W1 | Immigration–death, initially zero | 1 | 2 | Birth 100; death X |
| W2 | Independent immigration–death species, initially zero | 33 | 66 | Each birth 3; death 0.2 Xᵢ |
| W3 | Three-gene repressilator | 6 | 12 | Hill repression and mass action |
| W4 | Species born and removed together, initially 20 each | 8 | 66 | 33 births of rate 3; 33 deaths of rate 3 X₀/(20 + X₀) |
Each timed batch runs 64 paths, from t = 0 to 100, saving at 0 and 100, with one numerical worker. All five Julia algorithms are exact jump-process methods for these models; no approximate leap method is timed. All 66 W4 channels remain separate in both implementations.
The host was shared Linux x86-64 on an AMD EPYC 9V74, with nine logical CPUs in its affinity mask and an eight-CPU cgroup quota. Only one numerical worker was used, and Julia’s BLAS thread count was also one. CRN-craft was built in release mode with Rust 1.88.0; its Python API used Python 3.12.14 and NumPy 2.5.4. Validation used SciPy 1.17.0. No other builds or heavy project checks ran during the timed rounds.
Five rounds rotated the order of all seven implementations within each
workload. Warm-up and distribution checks preceded timing. The workload seed
was 4242; validation used 777. CRN-craft uses its pinned ChaCha8 streams;
Julia used one advancing Xoshiro stream per batch. Matching seed numbers
do not imply matching paths between different generators or SSA algorithms.
Timing boundaries
| CRN-craft Python API | Julia batch |
|---|---|
Times crn.simulate(model_bytes, run, cached=...) | Times serial solve(problem, SSAStepper(); rng, saveat=[0,100]) calls and final mean/sample-variance reduction |
| Includes run JSON encoding, native input parsing/validation and model compilation, simulation, result encoding and Python decoding | Includes per-path solver initialization, simulation, solution objects, saved-time/final-state checks and reduction |
| Model bytes and the run dictionary are prepared before timing; trajectory retention is disabled | Catalyst model/problem construction, copying a pristine batch problem and JSON IPC are outside the warm timer |
Julia uses save_positions=(false,false) so it does not save every jump;
this follows the documented performance guidance [1]. A typed function
specializes the solve loop on each problem type. Both sides compute ensemble
statistics; CRN-craft also returns its standard result metadata and statistics
at the initial save time. These are comparable application workloads, not
identical allocation or serialization pipelines. Archive writing is not
included in the timed CRN-craft API call.
SortingDirect retains learned reaction ordering across solves. Each Julia batch therefore starts from a copy of an unsolved problem, made outside its timer; the problem is reused within that batch. This permits both efficient serial reuse and repeatable batches [2]. No hand tuning of bracket widths, channel order or low-level state representation was performed.
Warm results
Seconds for 64 paths: median [minimum–maximum] of five runs.
| Implementation | W1 | W2 | W3 | W4 |
|---|---|---|---|---|
| CRN-craft cached Direct | 0.089 [0.083–0.104] | 0.210 [0.200–0.245] | 0.708 [0.639–0.754] | 0.857 [0.820–1.003] |
| CRN-craft Direct | 0.084 [0.083–0.093] | 0.778 [0.745–0.877] | 1.757 [1.680–1.882] | 0.971 [0.909–1.034] |
Julia Direct | 0.054 [0.048–0.056] | 0.195 [0.182–0.221] | 0.399 [0.389–0.414] | 0.255 [0.252–0.268] |
Julia SortingDirect | 0.059 [0.055–0.060] | 0.122 [0.119–0.130] | 0.275 [0.267–0.280] | 1.185 [1.163–1.260] |
Julia DirectCR | 0.086 [0.081–0.087] | 0.094 [0.089–0.110] | 0.409 [0.393–0.432] | 0.853 [0.838–0.968] |
Julia NRM | 0.073 [0.067–0.077] | 0.110 [0.108–0.154] | 0.351 [0.349–0.363] | 1.039 [1.014–1.124] |
Julia RSSACR | 0.074 [0.068–0.082] | 0.101 [0.100–0.131] | 0.325 [0.318–0.345] | 0.104 [0.099–0.106] |
Bold denotes the lowest observed median per column. Five observations on a shared host are not enough to establish a precise ranking between close options. One W2 NRM observation was approximately 40% above its median; the ranges retain this observation. No outlier was removed.
For continuity with the GillesPy2 report, the following normalizes time by CRN-craft’s event count. The Julia values are proxies, not measured Julia nanoseconds per event: its actual event counts were not instrumented, and its sampled paths differ. Ensemble seconds above are the primary result.
| Quantity | W1 | W2 | W3 | W4 |
|---|---|---|---|---|
| CRN-craft events | 1,268,165 | 1,234,576 | 3,663,350 | 1,225,923 |
| CRN cached, ns/event | 70 | 170 | 193 | 699 |
| Fastest Julia, ns/CRN-event proxy | 42 | 76 | 75 | 85 |
Startup and first execution
The full benchmark used a fresh Julia process after package precompilation:
| Measured phase | Seconds | Scope |
|---|---|---|
| Package imports | 9.17 | Catalyst, JumpProcesses and harness dependencies |
| Model/problem setup | 49.21 | All four workloads plus the homodimer control, five aggregators each |
| Process launch to ready response | 67.65 | Includes the preceding two phases and other startup/JIT/harness work; do not add these three rows |
| First two-path batch per model/algorithm | 0.24–0.69 | Observed range of 20 calls after setup; includes remaining first-use compilation |
This is a whole-comparison setup measurement, not a 67.65-second cost for every Julia model or every subsequent batch. Construction shares compiled methods, so individual setup entries depend on construction order. Package installation/precompilation, CRN-craft’s Rust build and Python wheel build are excluded from these timings. CRN-craft accepts these JSON models without a separate per-model code-generation/JIT phase. Long-lived Julia sessions amortize their setup over repeated solves.
Reading the algorithm differences
Inspection of the pinned JumpProcesses 10.0.1 source and CRN-craft’s base commit shows different event-selection strategies; the measured effects below are consistent with them, but are not a component-level profiling attribution.
| Solver | Relevant strategy |
|---|---|
| CRN Direct | Re-evaluates every propensity; builds cumulative sums and selects by binary search |
| CRN cached Direct | Updates affected propensities; resumes cumulative summation at the earliest invalidated channel; binary-search selection |
Julia Direct | Re-evaluates propensities into cumulative sums and binary-searches them, with specialized mass-action handling |
Julia SortingDirect | Dependency-based updates; linear selection through an adaptively reordered channel list |
Julia DirectCR | Dependency-based updates with composition–rejection selection |
Julia NRM | Next Reaction Method with dependency-based propensity/time updates and an indexed priority queue |
Julia RSSACR | Rejection SSA with propensity bounds and composition–rejection; can avoid recomputing actual rates after every event |
On W1, the small direct method wins among the measured Julia medians; more elaborate selection machinery does not pay off here. On W2, sparse dependencies favor DirectCR: Julia Direct alone is only 1.08× faster than CRN cached, while DirectCR is 2.25× faster. On W3, SortingDirect is the fastest observed option, and caching also helps CRN-craft substantially.
On W4, every event changes all eight species and affects all 33 custom death rates. Dependency updates alone offer limited relief. RSSACR can use bounds between updates and is much faster, whereas SortingDirect and NRM are slower than CRN cached. W4 is deliberately synthetic: repeated channels and an equal-count invariant reduce its effective state dimension to one. Its large RSSACR advantage should not be generalized to arbitrary dense CRNs.
RSSACR requires valid propensity bounds. The tested custom laws depend monotonically on a single species: Hill repression decreases and Michaelis–Menten increases. Their endpoint bounds are valid. This benchmark does not authorize using inferred endpoint bounds for arbitrary nonmonotone or mixed-dependency rate functions [3].
Model equivalence and validation
The acceptance protocol was committed before measurements. Validation precedes performance interpretation.
Model translation. Native CRN-craft and Catalyst agree on all stoichiometric updates and 2,325 propensity values at selected zero, low and higher-count states. The largest relative difference is 8.3 × 10⁻¹⁶, below the declared 2 × 10⁻¹² tolerance.
- Mass-action reactions use Catalyst’s normal
-->arrow and default combinatorial convention, matchingc × ∏ binomial(Xᵢ, νᵢ). A separate2X → 0, c = 0.25 control verifies the factorial divisor [4]. - Hill repression and Michaelis–Menten use the full-propensity
=>arrow, avoiding an extra reactant-count multiplier [5]. - W4’s Julia law omits the availability gates, as in the GillesPy2 comparison. This is justified only on its reachable class: all eight counts start equal, every reaction changes them equally, and the death rate is zero when all are zero. Thus omitting the gates leaves this process unchanged. Unequal-state equivalence is neither asserted nor tested.
Distribution checks. Each of CRN cached and the five Julia algorithms ran 512 paths per workload, for 12,288 validation paths. W1 has the exact terminal law Poisson(100 × (1 − exp(−100))); each W2 species has Poisson(15 × (1 − exp(−20))). All 34 linear-model species were checked for all six engines. The six W3 species and W4’s one independent coordinate were compared between CRN-craft and each Julia algorithm.
The 239 comparisons use conservative Dvoretzky–Kiefer–Wolfowitz empirical-CDF
envelopes [9] with a union-bound family error probability of 0.01. For n = 512,
K = 239 and α = 0.01, the one-sample bound is
sqrt(log(2K/α)/(2n)) = 0.10258; the two-sample bound is
2 sqrt(log(4K/α)/(2n)) = 0.21165. No independence between species is required
for this multiplicity correction.
The two-sample threshold here follows by applying the one-sample bound to
each empirical CDF and using the triangle inequality; it is not the sharper
two-sample result studied in [9].
| Workload | Comparisons | Largest observed CDF distance | Declared bound | Result |
|---|---|---|---|---|
| W1: all engines versus exact law | 6 | 0.04808 | 0.10258 | Pass |
| W2: all engines/species versus exact laws | 198 | 0.06452 | 0.10258 | Pass |
| W3: Julia versus CRN, all six species | 30 | 0.07422 | 0.21165 | Pass |
| W4: Julia versus CRN, one coordinate | 5 | 0.06250 | 0.21165 | Pass |
All simulations completed. Julia checked saved times and nonnegative integer terminal counts; CRN-craft reported completed ensembles. All eight W4 terminal coordinates were equal in every retained validation path. Repeated timed batches reproduced their own final-statistics/result digests, and CRN Direct and cached Direct produced identical result digests. Cross-engine path identity was not expected.
These checks support the translation and sampled terminal distributions. Their deliberately conservative bounds do not prove equivalence of arbitrary models, rare tails, transient distributions or extreme numerical inputs. The full final samples and all individual distances are retained for review.
Capabilities beyond these timings
| Area | CRN-craft at the tested commit | Catalyst / JumpProcesses ecosystem |
|---|---|---|
| Model interface | Native Rust library/CLI and optional Python; strict versioned JSON contracts | Symbolic Julia DSL and programmatic reaction systems [6] |
| Exact stochastic simulation | Direct and dependency-cached Direct | Several exact aggregators; five tested here [3] |
| Rate laws | Validated mass action, Hill activation/repression and Michaelis–Menten; explicit availability gates | General symbolic/function-based rates; users must supply correct semantics and any required bounds [3,5] |
| Other dynamics | Sparse FSP; explicitly approximate Poisson leaping; optional diffsol BDF/sensitivities integration | ODE, SDE, hybrid and spatial workflows through SciML; separate packages provide FSP and other stochastic extensions [6] |
| Analysis and fitting | Conservation/graph analysis and optional optimization/job integrations | Symbolic analysis and wider sensitivity, parameter-estimation and bifurcation tooling [6] |
| Ensembles | Replicate parallelism with pinned streams and ordered reduction; documented thread-count identity contract | Serial, threaded and distributed ensemble workflows; mutable jump state must be copied appropriately [2] |
| Evidence and execution contracts | Explicit budgets/diagnostics; CLI archives with hashes, input snapshots and verifier | Julia problems/solutions, return codes and callbacks; the user assembles persistence and workflow policy |
The present measurements do not compare FSP, ODE accuracy, parameter fitting, parallel scaling or archive/diagnostic behavior. CRN-craft’s contracts are a separate reason to choose it; this benchmark does not quantify their runtime cost or show that Julia cannot implement comparable policies.
Limitations
- One shared host, four networks with at most 66 reactions, one numerical worker and five timing repetitions. No dedicated-core, large-network, multi-thread, GPU or memory-scaling claim follows.
- The fastest Julia option is selected from these observed medians. A new model needs its own algorithm comparison; closely spaced medians can swap.
- Equivalent processes use different random paths. Julia event-normalized numbers are explicitly CRN-count proxies.
- Warm timing boundaries and result representations differ. Julia problem reuse is intentional, while CRN’s API parses/compiles the model per call.
- W4’s redundant gates are omitted only in the Julia translation. Its speed ratio combines algorithm, rate-evaluation, checks and interface differences.
- Package versions are pinned. Different Julia/compiler/package versions, bracket tuning or model representations can change results.
- The earlier GillesPy2 report used a different host/runtime environment. Its absolute times must not be combined with this table into a three-way benchmark. GillesPy2 was not remeasured in this run.
Reproducing and retained evidence
The complete instructions are in validation/julia/README.md.
Build the tested CRN-craft source and Python wheel, install the pinned Python
requirements, and instantiate the retained Julia Project.toml/Manifest.toml.
Then, from the repository root:
export JULIA_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1
julia --startup-file=no --project=validation/julia -e 'using Pkg; Pkg.instantiate(); Pkg.precompile()'
python validation/compare_julia.py \
--julia "$(command -v julia)" \
--binary target/release/crn-craft \
--output validation/campaign/julia-comparison-rerun.json
The raw report contains 140 timing observations, all 239 statistical checks,
terminal samples, per-engine replay hashes, model hashes and six hashes of
the exact benchmark sources/environment. They matched the delivered files.
Julia’s full-run stderr was empty. runtime-provenance.json records the
official Julia archive and its verified SHA-256. The plot can be regenerated
with validation/plot_julia_comparison.py and matplotlib 3.11.2.
The unmodified native engine passed 166 release tests, clippy with warnings denied, formatting, 67 contract checks in both normal and optimized Python, and the default dependency gate. The Python benchmark/plot scripts passed ruff. Two preliminary harness failures, an unsupported solver keyword and an overly narrow result-dictionary type, are retained with their corrections described in the environment README. The subsequent smoke and full runs passed; no acceptance threshold changed.
Sources
Retrieved 2 November 2026. Performance numbers above are measurements from this comparison; documentation supports API and capability descriptions.
- JumpProcesses FAQ: saving, algorithms and RNGs.
- JumpProcesses: ensembles, problem reuse and SortingDirect reproducibility.
- JumpProcesses: jump types, exact aggregators, dependency graphs and rate bounds.
- Catalyst: mathematical models and combinatorial jump-rate convention.
- Catalyst: advanced DSL and full-rate arrows.
- Catalyst: supported workflows and ecosystem.
- CRN-craft source at the measured commit.
- JumpProcesses 10.0.1 installed package source, pinned by the retained Manifest:
src/aggregators/{direct,sortingdirect,directcr,nrm,rssacr,bracketing}.jl. - Wei and Dudley: Two-sample Dvoretzky–Kiefer–Wolfowitz inequalities, original manuscript, including the one-sample inequality with constant 2.
Ten further CRN-craft / Julia-gap iterations
Measured with the 0.6.0 network engine (note of 12 November 2026). The CRN-craft numbers on this page come from the network engine of releases 0.2.0 to 0.6.0 (its
simulate,simulate-cachedandssaroutes). Release 0.7.0 replaced that engine with one engine, whose selectors are ports of the methods measured here. Julia is not available on the host of the 0.7.0 measurements, so these comparisons were not repeated, and the tables below are left as measured. For the 0.7.0 engine against the 0.6.0 network engine on the same host, see the speed gate andvalidation/merge/RESULTS.md(“M4d (speed gate): results”).
Measured before the 0.2.0 release. These measurements come from development builds of 2 November 2026 and have not been repeated on release 0.2.0 (4 November 2026). The network SSA engine changed in between:
fastbecame the default ofssarequests (crn-craft.ssa-run/0.3), the Ziggurat waiting-time sampler was refactored so the rules engine can share it, andcrn-craft.ssa-run/0.4added thenext_reactionaggregator, which this comparison does not include. Requests of the measured versions return the same results as before; their timings on 0.2.0 may differ.
Measured 2 November 2026. GitHub base: add6cca0fb146e8a40418432e963219514086024
(merged PR #7). Julia 1.13.3, Catalyst
17.0.0, JumpProcesses
10.0.1. This is a direct same-host rerun,
including a separately built GitHub-main Python wheel; it replaces no historical
measurement and uses no cross-host projection.
Ten candidates were implemented and tested in sequence. 3 were kept: C05, C06, C09. The fastest final CRN median improves by up to 1.350× over the fastest baseline choice. The geometric-mean CRN/fastest-Julia gap is 1.441×, versus 1.540× for GitHub main on this same host. The aspirational 1.25× target was missed.
| Model | Baseline best | s | Final best | s | Gain | Julia best | s | Final / Julia |
|---|---|---|---|---|---|---|---|---|
| W1 | cached Direct/ziggurat | 0.07541 | cached Direct/ziggurat | 0.07084 | 1.065× | Direct | 0.05061 | 1.400× |
| W2 | RSSACR/ziggurat | 0.13661 | DirectCR/ziggurat | 0.13414 | 1.018× | RSSACR | 0.09802 | 1.369× |
| W3 | SortingDirect/ziggurat | 0.36009 | SortingDirect/ziggurat | 0.35007 | 1.029× | SortingDirect | 0.29200 | 1.199× |
| W4 | RSSACR/ziggurat | 0.19371 | RSSACR/ziggurat | 0.14345 | 1.350× | RSSACR | 0.10719 | 1.338× |
| W5 | RSSACR/ziggurat | 0.08091 | RSSACR/ziggurat | 0.08233 | 0.983× | DirectCR | 0.04840 | 1.701× |
| W6 | RSSACR/inverse | 0.06830 | RSSACR/inverse | 0.06263 | 1.091× | RSSACR | 0.03883 | 1.613× |
| W7 | RSSACR/inverse | 0.02083 | RSSACR/inverse | 0.02112 | 0.986× | RSSACR | 0.01380 | 1.531× |

Ratios use unrounded medians. Final / Julia >1 means Julia was faster. Best methods are selected from twelve prepared CRN options and five Julia algorithms. These are five observations on one shared host; small differences are not a precise ranking. All methods, including slower variants, are retained in the complete timing CSV and raw report. The fastest W5 and W7 choices were respectively 1.7% and 1.4% slower than baseline in this run. Julia remained faster on every workload.
Exposed regressions and follow-up
The all-method run exposed six prepared rows with original baseline/final ratios below 0.95. A separate diagnostic used five fresh alternating pairs, two repeats per side, after warmup. It did not replace any primary observation or change an iteration decision. Original ratios below use the ratio of the original medians; diagnostic ratios use the median paired speedup.
| Prepared row | Original baseline / final | Diagnostic paired gain |
|---|---|---|
| W3/RSSACR/inverse | 0.944× | 0.987× |
| W4/cached Direct/ziggurat | 0.943× | 1.014× |
| W4/DirectCR/inverse | 0.907× | 0.990× |
| W4/DirectCR/ziggurat | 0.940× | 0.878× |
| W5/cached Direct/inverse | 0.919× | 0.996× |
| W7/legacy cached | 0.916× | 0.977× |
Five of six drops did not reproduce at the 5% level. W4 DirectCR/Ziggurat did: 0.878× throughput, approximately 13.9% more elapsed time. This is a retained tradeoff outside the declared eleven-row gate, even though W4’s best RSSACR choice improved by 1.350×. Choose RSSACR for the tested W4 workload; these changes do not establish a win for every algorithm or wait sampler.
To investigate attribution, the same W4 DirectCR paths were run through the native prepared benchmark at the base and each retained commit (three samples per binary, median below; inverse and Ziggurat tested separately):
| Native build | DirectCR / inverse seconds | DirectCR / Ziggurat seconds |
|---|---|---|
| base | 1.36985 | 1.51546 |
| C05 | 1.35537 | 1.33345 |
| C06 | 1.34268 | 1.52697 |
| C09 | 1.35862 | 1.37652 |
These sequential native samples do not reproduce a final/base slowdown, and the exact path digest and event count are identical across builds. The main and diagnostic Python measurements include serialization and decoding, unlike this native boundary. Generated-code layout, allocation and host variability are possible explanations, not measured causes. Without a profiler, the persistent Python-boundary regression remains unattributed. The patch retains it explicitly; the original complete CSV includes every slower row.
Diagnostic code (validation/diagnose_gap10_regressions.py, deleted in 0.7.0 with the
other gap-10 drivers; see release 0.6.0) and
all diagnostic observations
are included. They are follow-up evidence, not extra attempts to satisfy the
fixed candidate acceptance rule.
Ten measured iterations
The protocol was committed before candidate measurements. Each candidate passed the Rust suite and 35 numerical-identity checks, then five paired rounds on eleven representative workload/method rows. Targets and thresholds were not changed after seeing timings. Rejected changes were reverted, with their diffs and observations kept.
| Iteration | Decision | Target gain | All-row gain |
|---|---|---|---|
| C01 | Revert | 0.9880× | 0.9880× |
| C02 | Revert | 1.0060× | 1.0207× |
| C03 | Revert | 0.9898× | 0.9891× |
| C04 | Revert | 1.0138× | 1.0167× |
| C05 | Keep | 1.0448× | 1.0147× |
| C06 | Keep | 1.3568× | 1.0312× |
| C07 | Revert | 0.9927× | 0.9924× |
| C08 | Revert | 1.0156× | 1.0085× |
| C09 | Keep | 1.0254× | 1.0135× |
| C10 | Revert | 0.9817× | 0.9817× |
C05 avoids a third mass-action bound evaluation when the enabled lower corner already gives the minimum positive rate. C06 shares successful custom-law ranges only for bit-identical law parameters, regulator identity and feasible integer interval; distinct availability gates are still checked. C09 compiles elementary shapes into enum payloads, retaining the original rounded arithmetic and checked general fallback. All existing stream/sampler identities remain in place. C01/C02 polling changes, C03/C04 tree changes, C07 bucket lookup, C08 contiguous SortingDirect and C10 Thin LTO did not satisfy the fixed rule on this host.
Why Julia is faster
The source investigation cites the locally inspected pinned sources and their recorded hashes. Julia uses compact mutable group sums, typed inlined mass-action loops, endpoint bounds for appropriate laws, Xoshiro/Ziggurat, and learned SortingDirect order retained between solves. CRN retains checked population updates, canonical sums and resolution checks, cooperative stops, counted sampling budgets and worker-count replay. Some mechanisms can be adopted without changing those guarantees; source inspection alone does not establish that an implementation is faster. The seven reverted experiments demonstrate that distinction.
No instruction profiler is installed here. Old callgrind percentages in the attached log describe another host; they are not claimed as current attribution. This campaign measures end-to-end effects and records evaluation/work counters.
Validation before timing
The final engine passed 188 release tests on Rust 1.88 and the Rust1.85 minimum, core/binding clippy with warnings denied, formatting, strict contract and installed-package checks, legacy SSA/CME identities, and the dependency gate. All 210 independent exact-law marginal comparisons passed at 100,000 paths per fixture/variant (7 million paths per full pass). Normal/-O reports match byte for byte. The fixed family alpha is .001, epsilon 0.00804612; largest observed error 0.00491533. Power checks reject the wrong homodimer convention. No acceptance tolerance was relaxed.
The Julia translation ran 512 paths per final engine/model with distinct seeds, 17 engines and seven workloads: 60,928 validation paths, 6,946 fixed comparisons. W1/W2 use exact Poisson laws; other marginals use the legacy cached reference. The same family-alpha .01 DKW rules are retained, including the conservative two-sample triangle bound. Every timed baseline/final method also returns identical numerical results; saved work counters are allowed to fall when work is genuinely avoided.
| Model | Checks | Largest CDF distance | Fixed bound | Result |
|---|---|---|---|---|
| W1 | 17 | 0.05570 | 0.11753 | Pass |
| W2 | 561 | 0.07004 | 0.11753 | Pass |
| W3 | 96 | 0.09375 | 0.24075 | Pass |
| W4 | 128 | 0.10156 | 0.24075 | Pass |
| W5 | 4096 | 0.12695 | 0.24075 | Pass |
| W6 | 512 | 0.09961 | 0.24075 | Pass |
| W7 | 1536 | 0.10938 | 0.24075 | Pass |
All model propensity/stoichiometric probes and conservation checks passed. Compressed terminal samples and their hashes are retained. These finite checks support the tested models; they do not establish arbitrary-model or rare-tail accuracy. Known steep-Hill RSSACR precision limitations remain documented.
Timing boundaries and limitations
The run includes 1,435 timing observations: 24 final Rust API rows (one-shot and prepared), twelve prepared baseline rows, and five Julia rows on each of seven workloads over five rotated/reversed rounds. All builds and heavy checks finished before warm timing; no observation was removed. Each engine’s replay digest remained stable. Baseline/final prepared calls include native simulation, result serialization and Python decoding. The baseline lives in an isolated process; its IPC is outside its own timer. Julia times serial solves, saved-state checks and final reduction; problem construction, pristine batch copy and IPC are outside its warm timer. No archive writing is timed.
One numerical worker; seed4242; original frozen W1–W4 (64 paths,t100) and larger
W5–W7 (16 paths,t20), saving initial/final states. These are application boundaries,
not identical allocation/check pipelines. Julia starts each batch from a pristine
problem and keeps its learned order inside the batch; CRN resets per replicate.
The host is AMD EPYC 9V74 80-Core Processor, affinity
9, quota 800000 100000.
Julia’s fresh timing-process setup took 67.68s
for all seven models/five aggregators, not a per-model charge. Compiler/package
installation costs are outside warm timing. No multithread, GPU, other-host or
memory-scaling claim is made.
Reproduction and raw evidence, implementation log, and all final gate outputs accompany the patch. At import, no remote had been pushed and no package published; the kept candidates were released in 0.2.0.
CRN-craft fast mode versus Julia: eight threads
Measured with the 0.6.0 network engine (note of 12 November 2026). The CRN-craft numbers on this page come from the network engine of releases 0.2.0 to 0.6.0 (its
simulate,simulate-cachedandssaroutes). Release 0.7.0 replaced that engine with one engine, whose selectors are ports of the methods measured here. Julia is not available on the host of the 0.7.0 measurements, so these comparisons were not repeated, and the tables below are left as measured. For the 0.7.0 engine against the 0.6.0 network engine on the same host, see the speed gate andvalidation/merge/RESULTS.md(“M4d (speed gate): results”).
Measured before the 0.2.0 release. These measurements come from development builds of 2 November 2026 and have not been repeated on release 0.2.0 (4 November 2026). The network SSA engine changed in between:
fastbecame the default ofssarequests (crn-craft.ssa-run/0.3), the Ziggurat waiting-time sampler was refactored so the rules engine can share it, andcrn-craft.ssa-run/0.4added thenext_reactionaggregator, which this comparison does not include. Requests of the measured versions return the same results as before; their timings on 0.2.0 may differ.
Import note (2 November 2026). This report was integrated as delivered. Its harness (
validation/compare_eight_threads.py,validation/eight-thread/) and raw evidence (validation/eight-thread/evidence/comparison.json) were not part of the delivery; the hashes under Provenance identify them. On import, every summary median, range and 1→8 ratio (224 rows) was recomputed from the individual observations, as were the selected methods, the fast/Julia ratios, the 6/7 and 3/7 counts, the geometric means 0.69× and 1.04× and the client latency ratios; all matched. The one-worker comparison at the end is derived from the same observations on import.
Measured 2 November 2026 (UTC), on the same host. CRN-craft GitHub main c16fcc55654d0867a58af48d48a8e860efce8896; numerical engine unchanged.
At eight numerical workers, across seven equally weighted workloads, the geometric mean of fast-mode time / Julia time is 0.69× for the original batches and 1.04× for 256-path batches. Fast mode has the lower best median on 6/7 and 3/7 workloads respectively. A ratio above 1 means Julia is faster; below 1 means CRN-craft is faster. This compares CRN’s prepared Python API with Julia’s prepared ensemble solve; the Julia boundary omits some result-contract work. These are fresh measurements, not extrapolations from serial results.
Each workload selects the lowest median among ten CRN fast configurations (five aggregators × inverse/Ziggurat waiting times) and five Julia algorithms. This describes the best observed choices on these fixtures, not an automatic method selector or a universal speedup. Lower-median counts include near ties; small differences are within the observed timing variation. All measurements are retained below.
Original batches
Times are batch milliseconds, median of five warm observations. The 1→8 column compares the same selected algorithm, batch and seed at one and eight workers. Higher scaling is better.
| Model | Paths | Fast choice | Fast 8 ms | Fast 1→8 | Julia choice | Julia 8 ms | Julia 1→8 | Fast / Julia |
|---|---|---|---|---|---|---|---|---|
| W1 | 64 | cached_direct/ziggurat | 11.799 | 5.14× | Direct | 9.481 | 5.56× | 1.24× |
| W2 | 64 | direct_cr/ziggurat | 19.584 | 5.42× | DirectCR | 22.115 | 4.49× | 0.89× |
| W3 | 64 | cached_direct/ziggurat | 50.042 | 5.12× | SortingDirect | 51.929 | 5.78× | 0.96× |
| W4 | 64 | rssa_cr/ziggurat | 23.506 | 5.86× | RSSACR | 23.538 | 4.41× | 1.00× |
| W5 | 16 | direct_cr/ziggurat | 11.027 | 5.07× | RSSACR | 26.200 | 2.19× | 0.42× |
| W6 | 16 | rssa_cr/ziggurat | 9.428 | 6.13× | RSSACR | 26.748 | 1.51× | 0.35× |
| W7 | 16 | direct_cr/ziggurat | 3.902 | 5.48× | DirectCR | 8.511 | 2.06× | 0.46× |
256-path throughput batches
Times are batch milliseconds, median of five warm observations. The 1→8 column compares the same selected algorithm, batch and seed at one and eight workers. Higher scaling is better.
| Model | Paths | Fast choice | Fast 8 ms | Fast 1→8 | Julia choice | Julia 8 ms | Julia 1→8 | Fast / Julia |
|---|---|---|---|---|---|---|---|---|
| W1 | 256 | cached_direct/ziggurat | 44.973 | 4.98× | Direct | 34.044 | 6.32× | 1.32× |
| W2 | 256 | direct_cr/ziggurat | 79.099 | 5.79× | DirectCR | 79.466 | 4.69× | 1.00× |
| W3 | 256 | cached_direct/ziggurat | 187.343 | 5.70× | SortingDirect | 202.774 | 5.86× | 0.92× |
| W4 | 256 | rssa_cr/ziggurat | 92.985 | 5.28× | RSSACR | 86.834 | 4.88× | 1.07× |
| W5 | 256 | direct_cr/ziggurat | 161.852 | 5.67× | DirectCR | 174.464 | 4.80× | 0.93× |
| W6 | 256 | rssa_cr/ziggurat | 143.023 | 5.37× | RSSACR | 141.267 | 4.74× | 1.01× |
| W7 | 256 | rssa_cr/ziggurat | 46.370 | 6.36× | RSSACR | 41.810 | 5.27× | 1.11× |
What eight threads means here
| Setting | Value |
|---|---|
| CPU | AMD EPYC 9V74 80-Core Processor |
| Platform | Linux-6.18.57-x86_64-with-glibc2.39 |
| CPU affinity | 0, 1, 2, 3, 4, 5, 6, 7, 8 |
| Cgroup CPU quota | 800000/100000 µs = 8 CPU equivalents |
| CRN-craft | 0.2.0.dev1; Rust 1.88.0 release, maturin wheel |
| Python | 3.12.14 (main, Aug 25 2026, 14:00:49) [Clang 22.1.3 ] |
| NumPy | 2.3.5 |
| Julia / Catalyst / JumpProcesses / SciMLBase | 1.13.3 / 17.0.0 / 10.0.1 / 3.58.0 |
| BLAS / OMP threads | 1 / 1 |
| Julia numerical threads, serial / parallel | 1 / 8 |
| Julia GC threads, serial / parallel | 1 / 8 |
Both implementations parallelize independent trajectories, not the reaction loop of one trajectory. CRN-craft creates eight scoped native workers per prepared batch and combines results in trajectory order. Julia uses EnsembleThreads() with eight numerical threads; the serial baseline uses EnsembleSerial(). Mutable JumpProblem state belongs to a task, with safetycopy=false and the pinned SciMLBase task-copy implementation. Each Julia trajectory receives an indexed Xoshiro RNG. BLAS is not the source of SSA parallelism. A matching runtime probe also finds one Julia interactive thread; it coordinates requests and is not a ninth numerical worker. The quota is eight CPU equivalents; dedicated physical cores and an otherwise idle host are not guaranteed.
The concurrency setup follows the JumpProcesses ensemble guidance and SciMLBase ensemble interface, with behavior checked against the pinned installed source.
Julia output callbacks observed thread IDs [2, 3, 4, 5, 6, 7, 8, 9]. Across the eight-worker observations, individual batches used 8–8 distinct output threads. These are measured callback thread IDs, not CPU indices; no reaction-loop instrumentation was added.
Workloads and timing boundaries
| Model | Network | Species | Reactions | Horizon | Original paths |
|---|---|---|---|---|---|
| W1 | Birth/death | 1 | 2 | 100.0 | 64 |
| W2 | 33 independent birth/death pairs | 33 | 66 | 100.0 | 64 |
| W3 | Repressilator | 6 | 12 | 100.0 | 64 |
| W4 | Dense shared-species Michaelis–Menten | 8 | 66 | 100.0 | 64 |
| W5 | 256-species diffusion chain | 256 | 510 | 20.0 | 16 |
| W6 | Dense 32-species conversion | 32 | 992 | 20.0 | 16 |
| W7 | 32-compartment binding/diffusion | 96 | 126 | 20.0 | 16 |
Models, initial populations, rate conventions, horizons and save times [0, end] are identical across implementations. W4 uses the existing Catalyst translation valid on its equal-population invariant; explicit propensity and stoichiometry probes check that mapping. Timed output keeps means/variances and no retained trajectory history. Different RNGs and algorithmic random-number consumption mean event histories differ between implementations; this is equal simulation specification, not equal event traces.
CRN timing wraps the prepared Python call, including native worker creation, simulation, checks, statistics, result serialization and Python decoding. Julia timing wraps the prepared ensemble solve, including task problem copies, scheduling, trajectory completion/save/nonnegativity checks and ordered terminal statistics. It excludes IPC, final JSON serialization, replay digest calculation and the initial pristine batch deepcopy. Julia therefore has a narrower timing boundary; the table below also reports its measured client latency and pristine-copy cost for the selected methods. Both exclude model construction, installation, compilation and JIT warmup.
CRN’s public result additionally carries per-trajectory event/work records, standard errors, and statistics at both saved times. The Julia driver reduces terminal counts to means/variances and checks the two saved times; it does not construct the full CRN result contract. Read the primary comparison as prepared API latency versus prepared Julia solve latency, rather than an isolated kernel speed measurement.
| Batch | Julia choice | Solve ms | Client ms | Pristine copy ms | Fast / Julia client |
|---|---|---|---|---|---|
| W1/original | Direct | 9.481 | 10.743 | 0.643 | 1.10× |
| W1/throughput | Direct | 34.044 | 35.761 | 0.645 | 1.26× |
| W2/original | DirectCR | 22.115 | 25.500 | 2.301 | 0.77× |
| W2/throughput | DirectCR | 79.466 | 81.994 | 2.175 | 0.96× |
| W3/original | SortingDirect | 51.929 | 53.668 | 1.259 | 0.93× |
| W3/throughput | SortingDirect | 202.774 | 204.381 | 1.038 | 0.92× |
| W4/original | RSSACR | 23.538 | 25.379 | 1.552 | 0.93× |
| W4/throughput | RSSACR | 86.834 | 89.246 | 1.852 | 1.04× |
| W5/original | RSSACR | 26.200 | 37.908 | 9.967 | 0.29× |
| W5/throughput | DirectCR | 174.464 | 190.148 | 10.500 | 0.85× |
| W6/original | RSSACR | 26.748 | 35.431 | 8.053 | 0.27× |
| W6/throughput | RSSACR | 141.267 | 149.295 | 9.044 | 0.96× |
| W7/original | DirectCR | 8.511 | 12.927 | 3.581 | 0.30× |
| W7/throughput | RSSACR | 41.810 | 47.382 | 3.576 | 0.98× |
Every configuration was warmed before timing. The two Julia processes received one full garbage collection after all warmups; no forced collections occurred between observations. Five rounds rotated method order and reversed it on alternate rounds. Numerical work ran sequentially between configurations; no build, package installation or validation job overlapped measured rounds. There are 2,240 timed observations: seven models × two batch sizes × two worker counts × sixteen configurations × five rounds. Timing seed is 4242.
| Julia workers | Process to all problems ready (s) | Package load (s) | Model/problem setup (s) |
|---|---|---|---|
| 1 | 67.776 | 8.263 | 50.181 |
| 8 | 63.524 | 7.026 | 48.703 |
These setup observations come from an already installed and precompiled Julia environment, once per worker configuration. They are excluded from warm times and do not constitute a cold-start or complete optimization-run comparison.
Numerical checks and replay
All 6,514 predeclared terminal-marginal checks passed, using 512 paths per model/engine for ten fast variants, five Julia algorithms and a legacy cached reference. Propensity/stoichiometry probes passed (8,870 rate values). Population checks and model-specific conservation checks passed. The baseline release suite passed 192 tests; formatting, warnings-denied Clippy, CLI/schema and alternative contract checks, and the dependency gate passed. Python contract/dependency checks also passed under -O with matching reports.
Family alpha is 0.01. W1/W2 compare against exact Poisson CDFs with bound 0.117261; other models compare against the independent reference using the conservative two-sample triangle bound 0.240224. These are finite-sample marginal checks with broad simultaneous bounds, not proof of joint trajectory-law equivalence, rare-event accuracy or optimization quality. No statistical thresholds were changed after observing samples.
| Model | CRN 1/8 replay | Julia 1/8 differing methods | Julia warm replay differences | Fresh SortingDirect |
|---|---|---|---|---|
| W1 | 10/10 equal | none | none | equal / stable |
| W2 | 10/10 equal | SortingDirect | none | equal / stable |
| W3 | 10/10 equal | SortingDirect | none | equal / stable |
| W4 | 10/10 equal | SortingDirect | none | equal / stable |
| W5 | 10/10 equal | SortingDirect | none | equal / stable |
| W6 | 10/10 equal | SortingDirect | none | equal / stable |
| W7 | 10/10 equal | SortingDirect | none | equal / stable |
CRN one/eight validation compared full numerical results after removing only the run-spec hash; all timed CRN configurations replayed their warmup results. Julia one/eight replay checks compare the ordered terminal-count digest for 32 indexed paths per method/model. Standard SortingDirect may retain its learned reaction order within task-owned problems, so task partitioning or thread count can change seeded paths while preserving the intended distribution. SortingDirect-fresh sets safetycopy=true, creates fresh per-trajectory state and passed both cross-thread and warm replay. Its measurements are a diagnostic, excluded from best-method selection.
Fast mode was explicitly enabled with method.fast=true / fast=True. It uses per-replicate Xoshiro256++, running totals, and batched stop polling, while omitting the default lost-increment and 53-bit resolution checks. It retains checked state updates and budgets. These results do not extend validation to arbitrary population/rate scales. See the fast-mode documentation.
Interpretation limits
Use the same-method scaling columns to judge whether a workload benefits from eight workers. Short batches can be dominated by worker creation, problem copies, reduction and serialization. Larger batches amortize some of that cost. The measurements alone do not isolate compiler code generation, sampling, cache behavior or scheduling as the cause of an implementation gap. Five observations on one shared host do not establish statistical significance for small differences. This report measures prepared SSA ensembles; it does not measure model recompilation for new parameters, full objective evaluation, optimizer convergence, final solution quality, or rebop.
All measured configurations
Milliseconds below are median [minimum–maximum] across all five observations. A speedup below 1 means eight workers were slower than one. No observations were trimmed. fresh marks the excluded replay diagnostic.
W1/original
| Engine / waiting time | 1 worker ms | 8 workers ms | 1→8 |
|---|---|---|---|
| direct/inverse | 80.954 [74.912–94.353] | 15.935 [15.481–23.950] | 5.08× |
| direct/ziggurat | 63.484 [59.435–77.177] | 12.568 [12.368–23.017] | 5.05× |
| cached_direct/inverse | 81.267 [73.612–93.709] | 15.116 [14.660–18.048] | 5.38× |
| cached_direct/ziggurat | 60.695 [55.351–68.692] | 11.799 [11.282–15.845] | 5.14× |
| direct_cr/inverse | 101.320 [94.607–106.293] | 19.759 [19.142–27.631] | 5.13× |
| direct_cr/ziggurat | 87.349 [74.736–98.297] | 16.278 [15.705–18.323] | 5.37× |
| sorting_direct/inverse | 75.618 [75.003–101.359] | 16.715 [16.021–19.850] | 4.52× |
| sorting_direct/ziggurat | 72.643 [64.856–75.517] | 13.088 [13.001–13.525] | 5.55× |
| rssa_cr/inverse | 101.751 [93.114–111.089] | 20.387 [20.201–20.651] | 4.99× |
| rssa_cr/ziggurat | 94.638 [79.089–108.786] | 17.179 [16.850–18.581] | 5.51× |
| Julia/Direct | 52.742 [50.477–58.265] | 9.481 [9.201–10.079] | 5.56× |
| Julia/SortingDirect | 58.351 [56.086–69.194] | 11.037 [10.794–11.173] | 5.29× |
| Julia/DirectCR | 86.247 [82.329–103.597] | 16.851 [16.462–17.462] | 5.12× |
| Julia/NRM | 72.144 [69.735–108.252] | 14.692 [14.568–14.908] | 4.91× |
| Julia/RSSACR | 74.628 [73.433–90.386] | 15.660 [14.624–17.838] | 4.77× |
| Julia/SortingDirect-fresh | 80.201 [78.782–86.060] | 20.229 [13.974–22.554] | 3.96× |
W1/throughput
| Engine / waiting time | 1 worker ms | 8 workers ms | 1→8 |
|---|---|---|---|
| direct/inverse | 298.025 [286.303–330.424] | 67.952 [61.509–71.396] | 4.39× |
| direct/ziggurat | 238.679 [221.187–264.554] | 50.429 [49.545–77.067] | 4.73× |
| cached_direct/inverse | 292.005 [261.971–344.110] | 57.513 [57.007–70.551] | 5.08× |
| cached_direct/ziggurat | 223.838 [214.892–267.852] | 44.973 [44.827–51.277] | 4.98× |
| direct_cr/inverse | 397.518 [386.730–429.807] | 76.287 [75.353–80.478] | 5.21× |
| direct_cr/ziggurat | 332.934 [318.577–362.558] | 67.897 [62.568–79.558] | 4.90× |
| sorting_direct/inverse | 336.422 [303.272–395.037] | 65.222 [63.168–78.238] | 5.16× |
| sorting_direct/ziggurat | 268.671 [257.594–289.461] | 51.100 [50.348–62.867] | 5.26× |
| rssa_cr/inverse | 420.210 [390.921–439.156] | 79.575 [77.579–82.567] | 5.28× |
| rssa_cr/ziggurat | 400.485 [331.324–437.591] | 65.767 [64.306–66.666] | 6.09× |
| Julia/Direct | 215.211 [208.528–246.471] | 34.044 [34.004–37.760] | 6.32× |
| Julia/SortingDirect | 262.414 [234.518–272.975] | 41.163 [40.758–42.583] | 6.37× |
| Julia/DirectCR | 368.628 [338.852–421.025] | 64.062 [62.037–69.221] | 5.75× |
| Julia/NRM | 304.348 [280.861–342.737] | 55.158 [54.088–57.357] | 5.52× |
| Julia/RSSACR | 311.750 [298.391–326.129] | 55.828 [55.135–87.053] | 5.58× |
| Julia/SortingDirect-fresh | 344.062 [305.034–433.895] | 57.470 [54.547–61.608] | 5.99× |
W2/original
| Engine / waiting time | 1 worker ms | 8 workers ms | 1→8 |
|---|---|---|---|
| direct/inverse | 572.165 [523.126–612.134] | 111.587 [109.712–115.599] | 5.13× |
| direct/ziggurat | 590.295 [516.710–604.992] | 111.165 [110.052–116.201] | 5.31× |
| cached_direct/inverse | 130.101 [127.839–142.111] | 23.048 [22.156–54.547] | 5.64× |
| cached_direct/ziggurat | 120.474 [115.122–123.578] | 20.266 [19.655–22.289] | 5.94× |
| direct_cr/inverse | 120.838 [110.662–131.004] | 22.577 [22.176–25.566] | 5.35× |
| direct_cr/ziggurat | 106.051 [97.625–137.387] | 19.584 [18.937–20.622] | 5.42× |
| sorting_direct/inverse | 165.169 [140.257–193.711] | 28.614 [28.315–40.088] | 5.77× |
| sorting_direct/ziggurat | 138.583 [132.705–150.330] | 25.601 [25.289–28.649] | 5.41× |
| rssa_cr/inverse | 139.690 [123.040–140.697] | 25.323 [24.511–33.459] | 5.52× |
| rssa_cr/ziggurat | 128.365 [122.270–133.848] | 22.760 [21.275–40.978] | 5.64× |
| Julia/Direct | 205.645 [190.967–256.647] | 50.342 [41.165–66.287] | 4.08× |
| Julia/SortingDirect | 129.163 [122.701–141.296] | 23.966 [20.192–45.983] | 5.39× |
| Julia/DirectCR | 99.262 [92.566–122.535] | 22.115 [20.050–43.076] | 4.49× |
| Julia/NRM | 114.280 [108.142–136.043] | 24.671 [21.987–36.127] | 4.63× |
| Julia/RSSACR | 107.166 [103.257–109.688] | 22.231 [20.769–25.328] | 4.82× |
| Julia/SortingDirect-fresh | 229.476 [203.791–247.889] | 46.731 [40.418–49.338] | 4.91× |
W2/throughput
| Engine / waiting time | 1 worker ms | 8 workers ms | 1→8 |
|---|---|---|---|
| direct/inverse | 2320.830 [2180.435–2380.459] | 434.318 [424.954–437.646] | 5.34× |
| direct/ziggurat | 2436.165 [2158.145–2499.327] | 438.808 [403.194–454.907] | 5.55× |
| cached_direct/inverse | 519.580 [476.185–553.623] | 88.120 [86.794–142.378] | 5.90× |
| cached_direct/ziggurat | 500.682 [465.967–518.147] | 82.042 [75.982–128.663] | 6.10× |
| direct_cr/inverse | 458.670 [434.271–493.370] | 94.898 [86.208–154.906] | 4.83× |
| direct_cr/ziggurat | 458.207 [426.062–527.904] | 79.099 [75.463–96.195] | 5.79× |
| sorting_direct/inverse | 669.654 [605.892–826.487] | 115.100 [110.997–278.435] | 5.82× |
| sorting_direct/ziggurat | 587.029 [558.809–624.147] | 105.664 [98.310–116.815] | 5.56× |
| rssa_cr/inverse | 551.550 [521.507–571.079] | 141.512 [95.834–154.844] | 3.90× |
| rssa_cr/ziggurat | 501.758 [484.040–547.626] | 91.237 [83.294–104.877] | 5.50× |
| Julia/Direct | 838.674 [783.512–900.645] | 154.630 [152.778–180.921] | 5.42× |
| Julia/SortingDirect | 512.266 [490.753–585.900] | 83.752 [71.995–92.328] | 6.12× |
| Julia/DirectCR | 372.578 [369.521–439.800] | 79.466 [72.230–94.287] | 4.69× |
| Julia/NRM | 453.420 [437.986–520.169] | 87.215 [81.695–125.280] | 5.20× |
| Julia/RSSACR | 438.853 [411.715–486.784] | 80.515 [74.374–90.538] | 5.45× |
| Julia/SortingDirect-fresh | 927.311 [803.925–1047.520] | 173.269 [155.051–338.024] | 5.35× |
W3/original
| Engine / waiting time | 1 worker ms | 8 workers ms | 1→8 |
|---|---|---|---|
| direct/inverse | 472.270 [457.364–511.499] | 101.999 [96.921–106.373] | 4.63× |
| direct/ziggurat | 419.119 [403.721–477.100] | 85.954 [84.409–90.764] | 4.88× |
| cached_direct/inverse | 290.885 [279.293–305.084] | 60.146 [59.207–63.383] | 4.84× |
| cached_direct/ziggurat | 256.420 [245.701–285.889] | 50.042 [43.735–52.354] | 5.12× |
| direct_cr/inverse | 427.373 [401.752–432.322] | 79.163 [76.899–91.561] | 5.40× |
| direct_cr/ziggurat | 412.854 [389.483–428.905] | 71.757 [70.659–74.255] | 5.75× |
| sorting_direct/inverse | 336.652 [321.559–357.900] | 64.919 [60.942–66.481] | 5.19× |
| sorting_direct/ziggurat | 292.186 [259.686–321.060] | 53.175 [50.194–55.657] | 5.49× |
| rssa_cr/inverse | 474.321 [445.618–523.088] | 85.057 [83.522–86.852] | 5.58× |
| rssa_cr/ziggurat | 479.083 [441.011–507.199] | 76.166 [73.912–79.718] | 6.29× |
| Julia/Direct | 443.516 [407.789–469.969] | 69.508 [68.415–73.123] | 6.38× |
| Julia/SortingDirect | 300.133 [270.360–314.997] | 51.929 [50.441–54.402] | 5.78× |
| Julia/DirectCR | 395.661 [375.732–428.115] | 71.970 [71.323–74.649] | 5.50× |
| Julia/NRM | 381.132 [358.005–441.471] | 76.915 [72.023–79.952] | 4.96× |
| Julia/RSSACR | 379.205 [351.623–411.250] | 61.329 [59.835–62.973] | 6.18× |
| Julia/SortingDirect-fresh | 338.162 [315.548–356.086] | 64.637 [56.038–96.438] | 5.23× |
W3/throughput
| Engine / waiting time | 1 worker ms | 8 workers ms | 1→8 |
|---|---|---|---|
| direct/inverse | 1842.459 [1759.199–1879.961] | 392.099 [388.085–528.601] | 4.70× |
| direct/ziggurat | 1741.494 [1686.435–1791.829] | 337.265 [329.128–531.352] | 5.16× |
| cached_direct/inverse | 1249.766 [1173.299–1330.890] | 236.564 [233.404–335.546] | 5.28× |
| cached_direct/ziggurat | 1067.678 [974.582–1124.629] | 187.343 [185.956–277.186] | 5.70× |
| direct_cr/inverse | 1727.498 [1681.933–1784.405] | 326.516 [315.127–469.107] | 5.29× |
| direct_cr/ziggurat | 1652.911 [1621.978–1698.224] | 276.381 [270.891–384.750] | 5.98× |
| sorting_direct/inverse | 1276.874 [1216.977–1317.687] | 245.149 [244.572–346.535] | 5.21× |
| sorting_direct/ziggurat | 1172.548 [1083.649–1237.483] | 197.438 [194.547–265.565] | 5.94× |
| rssa_cr/inverse | 1851.137 [1775.213–1883.202] | 339.725 [337.309–455.825] | 5.45× |
| rssa_cr/ziggurat | 1742.077 [1642.443–1829.561] | 301.170 [287.773–375.351] | 5.78× |
| Julia/Direct | 1611.122 [1593.749–1838.227] | 259.779 [253.190–402.829] | 6.20× |
| Julia/SortingDirect | 1187.266 [1120.678–1358.255] | 202.774 [200.047–309.377] | 5.86× |
| Julia/DirectCR | 1705.417 [1591.585–1932.849] | 295.789 [277.339–400.562] | 5.77× |
| Julia/NRM | 1571.560 [1491.267–1799.565] | 279.431 [252.743–421.117] | 5.62× |
| Julia/RSSACR | 1498.597 [1446.717–1875.385] | 237.277 [225.971–348.195] | 6.32× |
| Julia/SortingDirect-fresh | 1380.642 [1286.240–1572.524] | 240.013 [235.046–373.029] | 5.75× |
W4/original
| Engine / waiting time | 1 worker ms | 8 workers ms | 1→8 |
|---|---|---|---|
| direct/inverse | 812.878 [797.700–882.319] | 173.169 [146.493–238.427] | 4.69× |
| direct/ziggurat | 858.210 [751.395–889.787] | 170.916 [104.245–182.933] | 5.02× |
| cached_direct/inverse | 795.386 [717.028–821.848] | 146.720 [123.478–203.348] | 5.42× |
| cached_direct/ziggurat | 810.445 [716.843–884.282] | 141.278 [139.612–165.646] | 5.74× |
| direct_cr/inverse | 1074.184 [953.655–1194.969] | 202.392 [201.930–208.014] | 5.31× |
| direct_cr/ziggurat | 970.552 [948.843–1183.686] | 207.066 [203.813–222.372] | 4.69× |
| sorting_direct/inverse | 865.321 [823.182–999.286] | 169.527 [167.192–174.155] | 5.10× |
| sorting_direct/ziggurat | 863.109 [789.953–920.647] | 169.655 [144.761–171.021] | 5.09× |
| rssa_cr/inverse | 140.960 [128.243–175.097] | 27.541 [25.998–27.656] | 5.12× |
| rssa_cr/ziggurat | 137.658 [119.995–158.589] | 23.506 [23.143–23.979] | 5.86× |
| Julia/Direct | 247.168 [241.236–288.927] | 45.396 [42.672–47.401] | 5.44× |
| Julia/SortingDirect | 566.217 [552.531–724.941] | 121.305 [113.553–125.910] | 4.67× |
| Julia/DirectCR | 801.354 [723.940–951.448] | 168.183 [149.605–168.999] | 4.76× |
| Julia/NRM | 1037.474 [949.384–1083.842] | 196.516 [176.464–199.115] | 5.28× |
| Julia/RSSACR | 103.908 [100.921–124.085] | 23.538 [22.111–29.721] | 4.41× |
| Julia/SortingDirect-fresh | 662.319 [634.707–683.184] | 134.234 [127.129–136.447] | 4.93× |
W4/throughput
| Engine / waiting time | 1 worker ms | 8 workers ms | 1→8 |
|---|---|---|---|
| direct/inverse | 3126.339 [3015.438–3347.120] | 678.070 [587.788–794.662] | 4.61× |
| direct/ziggurat | 3191.541 [3052.029–3348.195] | 690.657 [665.669–756.440] | 4.62× |
| cached_direct/inverse | 2977.135 [2955.794–3083.202] | 594.954 [557.450–623.817] | 5.00× |
| cached_direct/ziggurat | 3121.211 [2924.573–3281.113] | 559.079 [548.105–576.783] | 5.58× |
| direct_cr/inverse | 4066.863 [3937.939–4351.458] | 802.278 [740.044–859.246] | 5.07× |
| direct_cr/ziggurat | 4195.910 [4044.492–4289.080] | 798.160 [772.981–1127.049] | 5.26× |
| sorting_direct/inverse | 3393.164 [3284.807–3669.903] | 678.617 [624.548–763.259] | 5.00× |
| sorting_direct/ziggurat | 3396.561 [3285.756–3544.152] | 648.994 [632.675–921.376] | 5.23× |
| rssa_cr/inverse | 553.429 [530.155–592.078] | 106.506 [103.135–138.682] | 5.20× |
| rssa_cr/ziggurat | 490.796 [480.887–549.170] | 92.985 [90.088–145.587] | 5.28× |
| Julia/Direct | 1046.119 [974.380–1108.285] | 166.007 [163.185–234.393] | 6.30× |
| Julia/SortingDirect | 2335.999 [2143.770–2466.221] | 449.218 [446.947–457.666] | 5.20× |
| Julia/DirectCR | 3062.097 [3035.156–3475.544] | 663.218 [644.750–681.355] | 4.62× |
| Julia/NRM | 4015.300 [3854.586–4352.540] | 778.242 [774.178–827.711] | 5.16× |
| Julia/RSSACR | 423.411 [394.148–474.138] | 86.834 [83.932–114.270] | 4.88× |
| Julia/SortingDirect-fresh | 2703.768 [2645.240–3053.327] | 580.121 [491.468–703.275] | 4.66× |
W5/original
| Engine / waiting time | 1 worker ms | 8 workers ms | 1→8 |
|---|---|---|---|
| direct/inverse | 1051.411 [1000.010–1097.007] | 219.799 [217.625–300.741] | 4.78× |
| direct/ziggurat | 1111.479 [1033.144–1212.513] | 228.820 [227.645–382.563] | 4.86× |
| cached_direct/inverse | 115.454 [107.813–128.873] | 16.978 [16.184–38.376] | 6.80× |
| cached_direct/ziggurat | 112.192 [105.466–124.260] | 17.691 [15.539–31.599] | 6.34× |
| direct_cr/inverse | 60.058 [57.004–72.017] | 11.830 [11.473–26.998] | 5.08× |
| direct_cr/ziggurat | 55.878 [54.709–71.778] | 11.027 [10.574–20.615] | 5.07× |
| sorting_direct/inverse | 170.129 [152.750–173.730] | 32.625 [31.863–53.617] | 5.21× |
| sorting_direct/ziggurat | 158.652 [152.148–164.855] | 32.137 [31.541–54.486] | 4.94× |
| rssa_cr/inverse | 71.492 [68.322–79.436] | 14.950 [13.773–22.311] | 4.78× |
| rssa_cr/ziggurat | 70.110 [64.212–72.232] | 14.326 [12.096–15.317] | 4.89× |
| Julia/Direct | 469.923 [440.595–508.824] | 140.542 [118.923–258.331] | 3.34× |
| Julia/SortingDirect | 127.806 [123.473–139.393] | 36.485 [33.110–45.197] | 3.50× |
| Julia/DirectCR | 49.409 [46.742–55.143] | 33.030 [26.306–53.661] | 1.50× |
| Julia/NRM | 69.215 [61.336–78.956] | 34.719 [28.417–38.105] | 1.99× |
| Julia/RSSACR | 57.335 [55.042–65.860] | 26.200 [25.065–50.266] | 2.19× |
| Julia/SortingDirect-fresh | 282.239 [265.175–354.841] | 61.662 [44.610–76.972] | 4.58× |
W5/throughput
| Engine / waiting time | 1 worker ms | 8 workers ms | 1→8 |
|---|---|---|---|
| direct/inverse | 17148.952 [16484.494–18924.126] | 3335.624 [3306.018–3670.297] | 5.14× |
| direct/ziggurat | 18224.624 [17647.814–20280.132] | 3325.778 [3076.151–3615.691] | 5.48× |
| cached_direct/inverse | 1797.787 [1767.735–2028.849] | 254.835 [251.551–289.002] | 7.05× |
| cached_direct/ziggurat | 1811.226 [1720.067–2104.612] | 240.795 [234.199–330.670] | 7.52× |
| direct_cr/inverse | 965.080 [939.026–1128.173] | 177.015 [172.073–225.676] | 5.45× |
| direct_cr/ziggurat | 916.916 [869.939–1075.984] | 161.852 [160.176–204.097] | 5.67× |
| sorting_direct/inverse | 2713.174 [2490.487–2946.069] | 504.841 [500.666–531.835] | 5.37× |
| sorting_direct/ziggurat | 2586.358 [2449.080–3186.939] | 493.193 [460.602–542.000] | 5.24× |
| rssa_cr/inverse | 1211.469 [1169.686–1327.753] | 204.495 [203.182–206.794] | 5.92× |
| rssa_cr/ziggurat | 1104.397 [1014.532–1198.051] | 179.080 [178.604–183.785] | 6.17× |
| Julia/Direct | 7923.723 [7736.687–8878.019] | 1637.255 [1485.677–1668.184] | 4.84× |
| Julia/SortingDirect | 2182.426 [2087.607–2363.903] | 316.065 [282.214–354.406] | 6.90× |
| Julia/DirectCR | 837.709 [769.941–944.504] | 174.464 [158.855–195.796] | 4.80× |
| Julia/NRM | 1094.790 [1048.696–1206.486] | 202.204 [191.999–208.721] | 5.41× |
| Julia/RSSACR | 934.645 [917.701–1128.010] | 182.887 [178.984–208.638] | 5.11× |
| Julia/SortingDirect-fresh | 5166.795 [4830.355–5419.928] | 1030.794 [974.345–1073.831] | 5.01× |
W6/original
| Engine / waiting time | 1 worker ms | 8 workers ms | 1→8 |
|---|---|---|---|
| direct/inverse | 1389.729 [1361.097–1529.029] | 299.093 [295.821–307.794] | 4.65× |
| direct/ziggurat | 1508.031 [1491.958–1532.563] | 315.587 [309.059–329.014] | 4.78× |
| cached_direct/inverse | 253.063 [230.001–273.744] | 40.939 [38.053–60.199] | 6.18× |
| cached_direct/ziggurat | 269.512 [234.324–299.174] | 39.260 [37.772–48.324] | 6.86× |
| direct_cr/inverse | 237.090 [223.370–313.615] | 48.103 [45.283–59.406] | 4.93× |
| direct_cr/ziggurat | 225.828 [214.504–244.112] | 45.029 [44.322–46.010] | 5.02× |
| sorting_direct/inverse | 306.652 [292.046–350.999] | 63.112 [61.463–67.005] | 4.86× |
| sorting_direct/ziggurat | 302.396 [294.576–325.262] | 62.245 [61.537–64.469] | 4.86× |
| rssa_cr/inverse | 51.035 [46.310–57.059] | 10.522 [9.723–16.662] | 4.85× |
| rssa_cr/ziggurat | 57.787 [46.288–70.613] | 9.428 [9.251–12.026] | 6.13× |
| Julia/Direct | 653.915 [644.351–790.811] | 155.618 [147.644–163.657] | 4.20× |
| Julia/SortingDirect | 227.661 [215.778–252.367] | 57.732 [42.335–177.664] | 3.94× |
| Julia/DirectCR | 217.342 [205.346–253.546] | 65.939 [53.219–70.338] | 3.30× |
| Julia/NRM | 314.898 [304.588–349.043] | 78.281 [68.848–160.226] | 4.02× |
| Julia/RSSACR | 40.381 [36.747–48.212] | 26.748 [18.763–39.494] | 1.51× |
| Julia/SortingDirect-fresh | 388.452 [381.743–599.450] | 78.991 [59.731–213.077] | 4.92× |
W6/throughput
| Engine / waiting time | 1 worker ms | 8 workers ms | 1→8 |
|---|---|---|---|
| direct/inverse | 23066.909 [22747.589–24430.257] | 4450.573 [4129.645–4934.719] | 5.18× |
| direct/ziggurat | 24733.992 [23867.859–24976.558] | 4628.570 [4464.662–4711.015] | 5.34× |
| cached_direct/inverse | 4101.410 [3962.707–4285.939] | 603.424 [599.921–606.470] | 6.80× |
| cached_direct/ziggurat | 4170.929 [3896.213–4408.966] | 598.074 [587.916–617.313] | 6.97× |
| direct_cr/inverse | 3588.430 [3459.692–4052.781] | 722.429 [676.790–725.295] | 4.97× |
| direct_cr/ziggurat | 3457.772 [3443.194–4271.307] | 701.049 [666.472–707.462] | 4.93× |
| sorting_direct/inverse | 5064.538 [4924.830–5772.261] | 971.630 [919.457–1002.133] | 5.21× |
| sorting_direct/ziggurat | 5036.879 [4664.121–5458.743] | 978.483 [965.366–992.857] | 5.15× |
| rssa_cr/inverse | 833.940 [742.565–880.976] | 158.430 [147.932–164.519] | 5.26× |
| rssa_cr/ziggurat | 768.128 [747.057–922.326] | 143.023 [138.828–238.696] | 5.37× |
| Julia/Direct | 10502.531 [10256.248–11356.974] | 2184.773 [2000.755–2232.516] | 4.81× |
| Julia/SortingDirect | 3140.812 [2793.272–3487.370] | 503.036 [486.744–527.647] | 6.24× |
| Julia/DirectCR | 3414.713 [3219.504–4096.317] | 689.957 [632.817–702.828] | 4.95× |
| Julia/NRM | 5009.541 [4852.382–5708.608] | 929.535 [890.018–947.584] | 5.39× |
| Julia/RSSACR | 669.604 [622.152–887.396] | 141.267 [134.222–150.260] | 4.74× |
| Julia/SortingDirect-fresh | 6109.619 [5590.521–7738.590] | 1379.807 [1294.531–1490.332] | 4.43× |
W7/original
| Engine / waiting time | 1 worker ms | 8 workers ms | 1→8 |
|---|---|---|---|
| direct/inverse | 95.632 [87.647–145.431] | 21.192 [20.288–21.725] | 4.51× |
| direct/ziggurat | 109.406 [107.508–120.743] | 21.948 [21.491–24.596] | 4.98× |
| cached_direct/inverse | 19.316 [19.138–28.348] | 4.285 [3.774–4.902] | 4.51× |
| cached_direct/ziggurat | 21.267 [20.454–23.346] | 4.115 [3.865–6.278] | 5.17× |
| direct_cr/inverse | 20.711 [17.719–30.119] | 4.308 [4.015–5.804] | 4.81× |
| direct_cr/ziggurat | 21.401 [19.828–25.307] | 3.902 [3.766–4.017] | 5.48× |
| sorting_direct/inverse | 23.096 [20.344–26.156] | 5.221 [4.586–5.523] | 4.42× |
| sorting_direct/ziggurat | 20.179 [18.544–25.568] | 5.568 [4.294–7.490] | 3.62× |
| rssa_cr/inverse | 19.753 [18.818–23.499] | 4.853 [3.807–43.302] | 4.07× |
| rssa_cr/ziggurat | 19.572 [18.260–22.470] | 5.185 [3.476–8.084] | 3.77× |
| Julia/Direct | 46.777 [40.204–48.099] | 15.582 [15.064–16.222] | 3.00× |
| Julia/SortingDirect | 18.697 [16.502–19.920] | 11.252 [8.572–22.865] | 1.66× |
| Julia/DirectCR | 17.517 [14.574–22.118] | 8.511 [8.074–14.465] | 2.06× |
| Julia/NRM | 19.446 [17.318–22.509] | 9.016 [8.248–11.077] | 2.16× |
| Julia/RSSACR | 14.018 [13.567–15.959] | 9.007 [7.513–17.389] | 1.56× |
| Julia/SortingDirect-fresh | 84.236 [62.668–130.362] | 19.974 [12.127–24.424] | 4.22× |
W7/throughput
| Engine / waiting time | 1 worker ms | 8 workers ms | 1→8 |
|---|---|---|---|
| direct/inverse | 1502.941 [1399.340–1652.365] | 310.496 [305.444–325.811] | 4.84× |
| direct/ziggurat | 1643.409 [1538.161–1681.217] | 317.432 [313.481–318.978] | 5.18× |
| cached_direct/inverse | 322.512 [312.802–393.356] | 55.061 [53.173–55.961] | 5.86× |
| cached_direct/ziggurat | 322.623 [308.883–347.994] | 51.299 [49.936–60.843] | 6.29× |
| direct_cr/inverse | 320.264 [294.758–348.507] | 58.583 [57.143–59.107] | 5.47× |
| direct_cr/ziggurat | 310.143 [269.870–392.506] | 52.971 [52.705–55.625] | 5.85× |
| sorting_direct/inverse | 360.961 [320.789–392.935] | 67.013 [66.398–68.462] | 5.39× |
| sorting_direct/ziggurat | 332.116 [301.374–342.315] | 64.514 [62.931–92.456] | 5.15× |
| rssa_cr/inverse | 293.791 [270.086–310.602] | 52.416 [51.878–55.258] | 5.60× |
| rssa_cr/ziggurat | 294.754 [266.006–352.016] | 46.370 [46.086–52.984] | 6.36× |
| Julia/Direct | 697.242 [666.690–861.538] | 165.367 [159.013–169.905] | 4.22× |
| Julia/SortingDirect | 266.245 [257.731–286.625] | 44.608 [43.801–49.602] | 5.97× |
| Julia/DirectCR | 248.936 [230.685–255.264] | 54.135 [50.518–62.756] | 4.60× |
| Julia/NRM | 302.200 [292.814–310.942] | 59.799 [58.917–63.999] | 5.05× |
| Julia/RSSACR | 220.198 [209.275–227.299] | 41.810 [41.517–43.022] | 5.27× |
| Julia/SortingDirect-fresh | 1041.442 [978.436–1195.435] | 245.708 [236.191–381.871] | 4.24× |
Individual observations
Ordered milliseconds for rounds 1–5. These values make every summary median and range independently checkable without an accompanying file.
W1/original
| Engine / waiting time | 1 worker, five observations (ms) | 8 workers, five observations (ms) |
|---|---|---|
| direct/inverse | 80.954, 83.251, 74.912, 77.021, 94.353 | 15.935, 15.481, 16.690, 15.768, 23.950 |
| direct/ziggurat | 59.435, 63.484, 60.710, 72.876, 77.177 | 12.568, 13.117, 12.559, 12.368, 23.017 |
| cached_direct/inverse | 81.267, 93.709, 78.922, 73.612, 81.822 | 15.116, 15.203, 14.776, 14.660, 18.048 |
| cached_direct/ziggurat | 68.692, 62.492, 55.351, 59.273, 60.695 | 12.940, 11.282, 11.433, 11.799, 15.845 |
| direct_cr/inverse | 103.208, 101.320, 106.293, 99.472, 94.607 | 26.762, 19.142, 19.759, 19.689, 27.631 |
| direct_cr/ziggurat | 92.373, 74.736, 84.453, 98.297, 87.349 | 16.278, 16.720, 16.246, 15.705, 18.323 |
| sorting_direct/inverse | 75.239, 88.112, 75.003, 75.618, 101.359 | 16.859, 16.021, 16.715, 16.413, 19.850 |
| sorting_direct/ziggurat | 73.233, 75.517, 66.356, 64.856, 72.643 | 13.525, 13.088, 13.442, 13.065, 13.001 |
| rssa_cr/inverse | 93.114, 111.089, 109.656, 101.751, 93.383 | 20.455, 20.201, 20.254, 20.651, 20.387 |
| rssa_cr/ziggurat | 95.100, 108.786, 89.606, 79.089, 94.638 | 17.179, 18.581, 17.049, 17.333, 16.850 |
| Julia/Direct | 53.351, 50.725, 52.742, 50.477, 58.265 | 9.481, 9.271, 10.079, 9.201, 9.664 |
| Julia/SortingDirect | 58.351, 56.086, 62.398, 58.200, 69.194 | 10.794, 11.173, 11.037, 10.828, 11.147 |
| Julia/DirectCR | 86.247, 83.723, 89.460, 82.329, 103.597 | 16.951, 17.462, 16.770, 16.851, 16.462 |
| Julia/NRM | 71.502, 72.144, 75.918, 69.735, 108.252 | 14.568, 14.649, 14.716, 14.908, 14.692 |
| Julia/RSSACR | 85.722, 73.433, 74.628, 74.339, 90.386 | 14.624, 17.838, 14.661, 16.608, 15.660 |
| Julia/SortingDirect-fresh | 78.782, 80.201, 78.937, 81.691, 86.060 | 13.974, 22.409, 20.229, 22.554, 18.634 |
W1/throughput
| Engine / waiting time | 1 worker, five observations (ms) | 8 workers, five observations (ms) |
|---|---|---|
| direct/inverse | 329.415, 298.025, 292.548, 286.303, 330.424 | 61.509, 71.396, 67.952, 64.371, 68.215 |
| direct/ziggurat | 241.255, 222.129, 238.679, 221.187, 264.554 | 49.545, 50.219, 59.972, 77.067, 50.429 |
| cached_direct/inverse | 344.110, 319.964, 281.189, 261.971, 292.005 | 57.007, 57.513, 57.453, 59.267, 70.551 |
| cached_direct/ziggurat | 227.723, 216.131, 267.852, 223.838, 214.892 | 51.277, 44.930, 44.827, 47.268, 44.973 |
| direct_cr/inverse | 429.807, 397.518, 386.730, 387.375, 412.028 | 80.478, 75.474, 75.353, 76.287, 79.435 |
| direct_cr/ziggurat | 327.214, 318.577, 332.934, 362.558, 350.123 | 67.897, 62.568, 64.772, 68.006, 79.558 |
| sorting_direct/inverse | 303.272, 336.422, 332.617, 340.938, 395.037 | 65.454, 63.266, 65.222, 63.168, 78.238 |
| sorting_direct/ziggurat | 285.377, 268.671, 257.594, 263.523, 289.461 | 51.100, 50.348, 59.247, 50.732, 62.867 |
| rssa_cr/inverse | 390.921, 420.210, 394.539, 424.345, 439.156 | 81.308, 77.579, 78.788, 79.575, 82.567 |
| rssa_cr/ziggurat | 412.920, 400.485, 331.324, 437.591, 395.817 | 66.666, 64.306, 66.043, 65.145, 65.767 |
| Julia/Direct | 208.528, 215.211, 210.410, 237.619, 246.471 | 34.031, 34.004, 34.044, 34.643, 37.760 |
| Julia/SortingDirect | 251.924, 234.518, 272.975, 272.018, 262.414 | 41.163, 40.775, 40.758, 41.786, 42.583 |
| Julia/DirectCR | 368.628, 342.998, 338.852, 421.025, 371.525 | 64.062, 62.037, 63.780, 68.000, 69.221 |
| Julia/NRM | 296.874, 280.861, 304.348, 342.737, 330.549 | 55.139, 55.158, 54.088, 57.357, 56.959 |
| Julia/RSSACR | 310.484, 298.391, 326.129, 318.882, 311.750 | 55.828, 55.479, 55.135, 87.053, 66.573 |
| Julia/SortingDirect-fresh | 344.062, 335.182, 350.031, 305.034, 433.895 | 54.547, 58.684, 54.998, 57.470, 61.608 |
W2/original
| Engine / waiting time | 1 worker, five observations (ms) | 8 workers, five observations (ms) |
|---|---|---|
| direct/inverse | 612.134, 604.697, 564.000, 523.126, 572.165 | 109.712, 111.983, 111.587, 115.599, 110.321 |
| direct/ziggurat | 590.295, 592.542, 516.710, 604.992, 570.581 | 110.052, 111.165, 113.654, 116.201, 111.069 |
| cached_direct/inverse | 142.111, 127.839, 130.101, 130.733, 129.680 | 22.156, 22.878, 23.048, 54.547, 25.776 |
| cached_direct/ziggurat | 115.122, 121.539, 119.658, 123.578, 120.474 | 19.655, 19.918, 20.724, 22.289, 20.266 |
| direct_cr/inverse | 110.662, 112.573, 131.004, 120.838, 123.286 | 22.176, 22.229, 25.566, 23.266, 22.577 |
| direct_cr/ziggurat | 105.079, 97.625, 118.234, 106.051, 137.387 | 18.937, 19.584, 19.781, 19.171, 20.622 |
| sorting_direct/inverse | 165.169, 140.257, 168.220, 193.711, 162.069 | 28.315, 28.614, 35.466, 28.496, 40.088 |
| sorting_direct/ziggurat | 150.330, 138.583, 143.683, 132.705, 134.477 | 25.289, 28.649, 25.479, 25.601, 28.550 |
| rssa_cr/inverse | 139.926, 123.040, 140.697, 139.690, 136.228 | 24.511, 25.031, 25.323, 25.596, 33.459 |
| rssa_cr/ziggurat | 122.270, 125.648, 133.848, 128.365, 131.116 | 21.275, 40.978, 22.521, 22.760, 33.607 |
| Julia/Direct | 190.967, 197.457, 256.647, 205.645, 215.759 | 41.165, 66.287, 64.019, 50.342, 49.794 |
| Julia/SortingDirect | 122.701, 129.163, 123.328, 131.529, 141.296 | 23.966, 20.192, 42.615, 45.983, 21.371 |
| Julia/DirectCR | 99.262, 101.697, 92.566, 97.200, 122.535 | 20.581, 22.115, 23.590, 43.076, 20.050 |
| Julia/NRM | 108.142, 114.280, 111.531, 136.043, 119.196 | 23.498, 28.900, 36.127, 24.671, 21.987 |
| Julia/RSSACR | 107.166, 109.688, 104.993, 109.428, 103.257 | 20.769, 25.328, 24.530, 21.598, 22.231 |
| Julia/SortingDirect-fresh | 203.791, 247.889, 213.750, 229.476, 243.312 | 40.418, 43.539, 48.312, 46.731, 49.338 |
W2/throughput
| Engine / waiting time | 1 worker, five observations (ms) | 8 workers, five observations (ms) |
|---|---|---|
| direct/inverse | 2180.435, 2270.905, 2320.830, 2336.408, 2380.459 | 435.766, 434.318, 437.646, 427.604, 424.954 |
| direct/ziggurat | 2436.165, 2442.797, 2499.327, 2253.095, 2158.145 | 438.808, 435.803, 443.525, 403.194, 454.907 |
| cached_direct/inverse | 553.623, 519.580, 520.843, 482.469, 476.185 | 88.120, 86.794, 142.378, 106.269, 87.630 |
| cached_direct/ziggurat | 506.034, 518.147, 500.682, 482.879, 465.967 | 82.042, 76.646, 128.663, 92.913, 75.982 |
| direct_cr/inverse | 458.670, 443.129, 469.970, 493.370, 434.271 | 98.331, 86.208, 154.906, 94.898, 90.444 |
| direct_cr/ziggurat | 426.062, 501.137, 458.207, 527.904, 444.166 | 77.806, 75.463, 96.195, 83.816, 79.099 |
| sorting_direct/inverse | 669.654, 608.074, 688.135, 826.487, 605.892 | 118.346, 110.997, 114.748, 115.100, 278.435 |
| sorting_direct/ziggurat | 624.147, 584.452, 587.029, 591.405, 558.809 | 116.815, 98.310, 98.367, 105.664, 106.597 |
| rssa_cr/inverse | 560.797, 521.507, 571.079, 551.550, 541.776 | 124.308, 95.834, 154.844, 141.512, 148.925 |
| rssa_cr/ziggurat | 495.834, 484.040, 541.181, 547.626, 501.758 | 104.877, 83.294, 90.270, 91.237, 92.650 |
| Julia/Direct | 795.845, 783.512, 900.645, 847.562, 838.674 | 180.921, 157.453, 152.778, 154.630, 153.543 |
| Julia/SortingDirect | 498.145, 490.753, 585.900, 512.266, 517.574 | 92.328, 74.392, 71.995, 86.804, 83.752 |
| Julia/DirectCR | 385.948, 372.578, 439.800, 369.521, 372.017 | 94.287, 72.230, 79.466, 73.049, 87.950 |
| Julia/NRM | 453.420, 437.986, 520.169, 480.355, 439.803 | 125.280, 87.215, 87.646, 81.695, 82.396 |
| Julia/RSSACR | 441.014, 411.715, 486.784, 438.853, 416.395 | 90.538, 74.374, 76.378, 85.391, 80.515 |
| Julia/SortingDirect-fresh | 933.174, 803.925, 1047.520, 869.297, 927.311 | 183.518, 164.702, 173.269, 155.051, 338.024 |
W3/original
| Engine / waiting time | 1 worker, five observations (ms) | 8 workers, five observations (ms) |
|---|---|---|
| direct/inverse | 482.953, 468.070, 511.499, 457.364, 472.270 | 98.526, 106.373, 102.201, 96.921, 101.999 |
| direct/ziggurat | 438.240, 419.119, 419.037, 403.721, 477.100 | 84.409, 90.764, 85.954, 85.797, 86.263 |
| cached_direct/inverse | 305.084, 290.885, 298.394, 279.293, 290.419 | 59.207, 60.146, 59.926, 61.308, 63.383 |
| cached_direct/ziggurat | 253.141, 256.420, 285.889, 270.277, 245.701 | 43.735, 52.354, 49.214, 50.042, 50.307 |
| direct_cr/inverse | 401.752, 431.596, 407.720, 427.373, 432.322 | 78.393, 79.163, 80.911, 76.899, 91.561 |
| direct_cr/ziggurat | 389.483, 412.854, 416.412, 428.905, 404.653 | 74.255, 74.001, 70.659, 70.885, 71.757 |
| sorting_direct/inverse | 321.559, 325.509, 357.900, 336.652, 348.350 | 64.146, 64.919, 66.481, 65.623, 60.942 |
| sorting_direct/ziggurat | 295.577, 259.686, 321.060, 292.186, 266.240 | 53.193, 55.657, 51.778, 50.194, 53.175 |
| rssa_cr/inverse | 474.321, 445.618, 475.917, 469.166, 523.088 | 85.246, 86.852, 83.522, 85.057, 84.883 |
| rssa_cr/ziggurat | 507.199, 468.797, 494.536, 479.083, 441.011 | 79.718, 77.224, 73.912, 75.730, 76.166 |
| Julia/Direct | 427.019, 443.516, 407.789, 463.938, 469.969 | 73.123, 69.069, 70.834, 69.508, 68.415 |
| Julia/SortingDirect | 298.933, 300.133, 314.997, 270.360, 301.426 | 50.441, 51.929, 51.608, 52.668, 54.402 |
| Julia/DirectCR | 395.661, 428.115, 410.991, 375.732, 389.894 | 71.970, 71.323, 74.649, 72.769, 71.965 |
| Julia/NRM | 383.664, 441.471, 381.132, 367.221, 358.005 | 76.915, 79.952, 73.964, 72.023, 77.022 |
| Julia/RSSACR | 379.205, 411.250, 370.922, 351.623, 381.136 | 62.907, 61.088, 61.329, 62.973, 59.835 |
| Julia/SortingDirect-fresh | 335.214, 356.086, 338.162, 315.548, 343.550 | 60.235, 64.637, 96.438, 66.823, 56.038 |
W3/throughput
| Engine / waiting time | 1 worker, five observations (ms) | 8 workers, five observations (ms) |
|---|---|---|
| direct/inverse | 1879.961, 1842.459, 1801.748, 1759.199, 1854.965 | 528.601, 399.766, 391.455, 388.085, 392.099 |
| direct/ziggurat | 1791.829, 1763.248, 1735.978, 1741.494, 1686.435 | 531.352, 337.265, 329.962, 329.128, 339.952 |
| cached_direct/inverse | 1318.244, 1249.766, 1198.997, 1173.299, 1330.890 | 335.546, 287.523, 236.564, 233.404, 234.359 |
| cached_direct/ziggurat | 1124.629, 1118.854, 974.582, 1064.670, 1067.678 | 277.186, 252.385, 186.227, 187.343, 185.956 |
| direct_cr/inverse | 1690.561, 1764.283, 1784.405, 1727.498, 1681.933 | 469.107, 385.928, 322.184, 326.516, 315.127 |
| direct_cr/ziggurat | 1675.009, 1649.329, 1652.911, 1621.978, 1698.224 | 384.750, 296.902, 276.381, 273.671, 270.891 |
| sorting_direct/inverse | 1317.687, 1258.763, 1276.874, 1216.977, 1289.176 | 328.130, 346.535, 244.661, 244.572, 245.149 |
| sorting_direct/ziggurat | 1229.747, 1083.649, 1172.548, 1095.165, 1237.483 | 264.058, 265.565, 197.438, 195.871, 194.547 |
| rssa_cr/inverse | 1822.453, 1883.202, 1879.859, 1851.137, 1775.213 | 432.753, 455.825, 337.309, 339.725, 337.592 |
| rssa_cr/ziggurat | 1829.561, 1742.077, 1642.443, 1764.126, 1662.603 | 375.351, 368.833, 287.773, 301.170, 287.977 |
| Julia/Direct | 1838.227, 1593.749, 1754.430, 1602.574, 1611.122 | 402.829, 253.190, 259.779, 313.700, 258.433 |
| Julia/SortingDirect | 1358.255, 1279.171, 1187.266, 1120.678, 1136.286 | 309.377, 226.125, 202.774, 200.047, 202.754 |
| Julia/DirectCR | 1932.849, 1705.417, 1720.363, 1629.758, 1591.585 | 327.000, 400.562, 295.789, 277.339, 287.013 |
| Julia/NRM | 1799.565, 1571.560, 1491.267, 1556.519, 1572.658 | 295.591, 421.117, 279.431, 252.743, 273.454 |
| Julia/RSSACR | 1875.385, 1535.817, 1498.597, 1476.284, 1446.717 | 247.746, 348.195, 237.277, 225.971, 231.902 |
| Julia/SortingDirect-fresh | 1572.524, 1371.952, 1384.064, 1286.240, 1380.642 | 247.648, 373.029, 235.046, 240.013, 235.788 |
W4/original
| Engine / waiting time | 1 worker, five observations (ms) | 8 workers, five observations (ms) |
|---|---|---|
| direct/inverse | 860.449, 882.319, 797.700, 812.878, 811.956 | 177.734, 238.427, 173.169, 146.493, 170.926 |
| direct/ziggurat | 862.799, 889.787, 751.395, 858.210, 797.016 | 177.082, 182.933, 170.916, 168.414, 104.245 |
| cached_direct/inverse | 795.386, 821.848, 786.809, 798.062, 717.028 | 203.348, 149.935, 146.720, 145.044, 123.478 |
| cached_direct/ziggurat | 884.282, 871.490, 810.445, 800.314, 716.843 | 139.612, 165.646, 142.094, 139.710, 141.278 |
| direct_cr/inverse | 1108.697, 1194.969, 953.655, 1074.184, 960.960 | 201.930, 204.695, 208.014, 202.392, 202.167 |
| direct_cr/ziggurat | 1039.634, 1183.686, 970.552, 948.843, 954.403 | 207.066, 222.372, 206.036, 210.773, 203.813 |
| sorting_direct/inverse | 999.286, 938.718, 826.900, 865.321, 823.182 | 167.934, 169.527, 167.192, 170.421, 174.155 |
| sorting_direct/ziggurat | 920.647, 909.582, 863.109, 821.326, 789.953 | 169.333, 171.021, 169.655, 170.943, 144.761 |
| rssa_cr/inverse | 175.097, 140.960, 142.263, 128.243, 131.985 | 27.656, 27.566, 26.884, 27.541, 25.998 |
| rssa_cr/ziggurat | 158.589, 138.052, 137.658, 119.995, 122.727 | 23.979, 23.506, 23.143, 23.539, 23.416 |
| Julia/Direct | 288.927, 253.783, 247.168, 244.939, 241.236 | 45.700, 44.608, 47.401, 42.672, 45.396 |
| Julia/SortingDirect | 724.941, 561.291, 588.844, 566.217, 552.531 | 125.910, 123.901, 121.305, 113.960, 113.553 |
| Julia/DirectCR | 951.448, 809.815, 767.910, 801.354, 723.940 | 168.909, 168.183, 168.999, 166.498, 149.605 |
| Julia/NRM | 1083.842, 1050.093, 972.925, 1037.474, 949.384 | 199.115, 177.762, 196.516, 176.464, 196.805 |
| Julia/RSSACR | 117.885, 124.085, 100.921, 103.908, 101.880 | 29.721, 29.289, 22.111, 23.538, 22.637 |
| Julia/SortingDirect-fresh | 662.319, 683.184, 679.118, 634.707, 648.295 | 127.129, 127.481, 136.447, 134.234, 136.414 |
W4/throughput
| Engine / waiting time | 1 worker, five observations (ms) | 8 workers, five observations (ms) |
|---|---|---|
| direct/inverse | 3347.120, 3037.279, 3126.339, 3015.438, 3128.129 | 768.544, 794.662, 587.788, 678.070, 658.123 |
| direct/ziggurat | 3348.195, 3107.707, 3248.738, 3191.541, 3052.029 | 756.440, 665.669, 682.770, 690.657, 727.306 |
| cached_direct/inverse | 2955.794, 3083.202, 2987.839, 2977.135, 2957.929 | 623.817, 557.450, 596.086, 587.942, 594.954 |
| cached_direct/ziggurat | 3281.113, 3234.772, 3121.211, 2924.573, 3002.283 | 576.783, 559.472, 559.079, 557.959, 548.105 |
| direct_cr/inverse | 4255.426, 4351.458, 4066.863, 3937.939, 4066.511 | 859.246, 743.342, 802.278, 808.588, 740.044 |
| direct_cr/ziggurat | 4195.910, 4244.088, 4289.080, 4044.492, 4072.561 | 1127.049, 772.981, 798.160, 832.171, 780.556 |
| sorting_direct/inverse | 3669.903, 3565.583, 3284.807, 3393.164, 3392.770 | 763.259, 624.548, 678.617, 681.275, 636.183 |
| sorting_direct/ziggurat | 3544.152, 3396.561, 3326.028, 3285.756, 3459.254 | 921.376, 632.675, 640.196, 657.044, 648.994 |
| rssa_cr/inverse | 592.078, 555.164, 530.155, 549.611, 553.429 | 138.682, 106.840, 103.135, 103.148, 106.506 |
| rssa_cr/ziggurat | 549.170, 526.877, 482.383, 480.887, 490.796 | 145.587, 91.276, 90.088, 94.333, 92.985 |
| Julia/Direct | 1108.285, 977.775, 1046.119, 974.380, 1104.679 | 234.393, 198.564, 163.185, 164.293, 166.007 |
| Julia/SortingDirect | 2466.221, 2266.400, 2335.999, 2143.770, 2337.716 | 457.666, 451.160, 446.947, 448.434, 449.218 |
| Julia/DirectCR | 3475.544, 3037.023, 3062.097, 3323.763, 3035.156 | 671.748, 653.935, 644.750, 681.355, 663.218 |
| Julia/NRM | 4352.540, 4289.458, 3951.394, 3854.586, 4015.300 | 793.681, 774.467, 827.711, 778.242, 774.178 |
| Julia/RSSACR | 474.138, 458.755, 403.683, 423.411, 394.148 | 85.523, 86.926, 114.270, 83.932, 86.834 |
| Julia/SortingDirect-fresh | 3053.327, 2857.223, 2663.403, 2645.240, 2703.768 | 580.121, 703.275, 583.761, 515.908, 491.468 |
W5/original
| Engine / waiting time | 1 worker, five observations (ms) | 8 workers, five observations (ms) |
|---|---|---|
| direct/inverse | 1092.152, 1097.007, 1000.010, 1051.411, 1002.745 | 300.741, 220.211, 219.799, 218.954, 217.625 |
| direct/ziggurat | 1212.513, 1113.177, 1111.479, 1096.414, 1033.144 | 382.563, 228.820, 227.645, 229.973, 228.562 |
| cached_direct/inverse | 128.873, 115.454, 107.813, 116.952, 110.559 | 38.376, 16.978, 16.184, 16.609, 18.372 |
| cached_direct/ziggurat | 112.192, 124.260, 111.845, 120.872, 105.466 | 31.599, 18.461, 15.539, 16.349, 17.691 |
| direct_cr/inverse | 66.820, 57.004, 72.017, 60.058, 58.663 | 26.998, 11.862, 11.473, 11.676, 11.830 |
| direct_cr/ziggurat | 70.141, 54.912, 54.709, 71.778, 55.878 | 20.615, 14.538, 10.574, 10.913, 11.027 |
| sorting_direct/inverse | 170.129, 171.742, 157.649, 173.730, 152.750 | 53.617, 32.115, 31.863, 33.887, 32.625 |
| sorting_direct/ziggurat | 161.653, 164.855, 152.148, 158.652, 152.563 | 54.486, 31.590, 32.137, 32.479, 31.541 |
| rssa_cr/inverse | 72.162, 68.322, 79.436, 71.492, 68.680 | 22.311, 20.939, 14.360, 14.950, 13.773 |
| rssa_cr/ziggurat | 72.232, 72.015, 65.282, 70.110, 64.212 | 15.317, 15.181, 12.096, 14.326, 12.170 |
| Julia/Direct | 508.824, 440.595, 475.868, 469.923, 457.628 | 206.123, 140.542, 121.751, 258.331, 118.923 |
| Julia/SortingDirect | 139.393, 123.473, 127.806, 130.635, 127.090 | 40.050, 36.485, 33.110, 33.125, 45.197 |
| Julia/DirectCR | 55.143, 46.742, 49.085, 49.755, 49.409 | 53.661, 33.030, 37.916, 30.910, 26.306 |
| Julia/NRM | 71.284, 62.230, 61.336, 69.215, 78.956 | 36.499, 33.685, 28.417, 34.719, 38.105 |
| Julia/RSSACR | 63.371, 55.042, 56.608, 65.860, 57.335 | 50.266, 25.065, 37.990, 26.200, 26.032 |
| Julia/SortingDirect-fresh | 354.841, 282.239, 267.607, 321.156, 265.175 | 76.972, 54.467, 61.662, 44.610, 62.969 |
W5/throughput
| Engine / waiting time | 1 worker, five observations (ms) | 8 workers, five observations (ms) |
|---|---|---|
| direct/inverse | 18924.126, 16484.494, 17148.952, 17299.481, 16863.756 | 3670.297, 3335.624, 3474.705, 3306.018, 3324.641 |
| direct/ziggurat | 20280.132, 17780.667, 17647.814, 18541.195, 18224.624 | 3615.691, 3510.829, 3325.778, 3311.795, 3076.151 |
| cached_direct/inverse | 2028.849, 1767.735, 1797.787, 1782.159, 1879.937 | 289.002, 257.029, 251.700, 254.835, 251.551 |
| cached_direct/ziggurat | 2104.612, 1744.337, 1811.226, 1817.207, 1720.067 | 330.670, 263.367, 240.795, 238.167, 234.199 |
| direct_cr/inverse | 1128.173, 967.675, 965.080, 952.121, 939.026 | 225.676, 178.462, 172.073, 173.040, 177.015 |
| direct_cr/ziggurat | 1075.984, 885.467, 963.331, 916.916, 869.939 | 204.097, 164.229, 161.852, 161.638, 160.176 |
| sorting_direct/inverse | 2946.069, 2490.487, 2731.070, 2713.174, 2516.185 | 531.835, 513.533, 504.841, 501.184, 500.666 |
| sorting_direct/ziggurat | 3186.939, 2449.080, 2601.046, 2586.358, 2577.897 | 542.000, 506.158, 493.193, 460.602, 487.954 |
| rssa_cr/inverse | 1327.753, 1228.588, 1194.885, 1169.686, 1211.469 | 205.335, 204.199, 204.495, 203.182, 206.794 |
| rssa_cr/ziggurat | 1198.051, 1169.128, 1014.532, 1104.397, 1060.407 | 180.460, 178.604, 179.080, 178.673, 183.785 |
| Julia/Direct | 8878.019, 8114.480, 7923.723, 7736.687, 7854.520 | 1546.674, 1637.255, 1485.677, 1668.184, 1653.600 |
| Julia/SortingDirect | 2363.903, 2115.525, 2182.426, 2305.897, 2087.607 | 354.406, 282.214, 321.569, 294.654, 316.065 |
| Julia/DirectCR | 944.504, 837.709, 796.891, 928.585, 769.941 | 195.796, 158.855, 190.169, 163.009, 174.464 |
| Julia/NRM | 1206.486, 1048.696, 1094.790, 1180.285, 1058.193 | 195.178, 202.204, 191.999, 208.721, 203.117 |
| Julia/RSSACR | 1064.052, 928.396, 934.645, 1128.010, 917.701 | 208.638, 178.984, 188.823, 179.031, 182.887 |
| Julia/SortingDirect-fresh | 5419.928, 5166.795, 4830.355, 5267.615, 4859.569 | 1009.524, 1067.981, 1030.794, 974.345, 1073.831 |
W6/original
| Engine / waiting time | 1 worker, five observations (ms) | 8 workers, five observations (ms) |
|---|---|---|
| direct/inverse | 1369.111, 1529.029, 1361.097, 1389.729, 1430.517 | 295.821, 303.626, 307.794, 296.333, 299.093 |
| direct/ziggurat | 1508.031, 1491.958, 1532.563, 1510.545, 1507.257 | 309.499, 329.014, 317.753, 309.059, 315.587 |
| cached_direct/inverse | 273.744, 230.001, 253.063, 253.332, 249.816 | 40.939, 60.199, 39.694, 38.053, 42.013 |
| cached_direct/ziggurat | 269.512, 234.324, 299.174, 284.027, 263.122 | 39.260, 42.941, 48.324, 37.772, 37.999 |
| direct_cr/inverse | 226.424, 248.809, 313.615, 237.090, 223.370 | 48.103, 45.283, 59.406, 49.698, 45.427 |
| direct_cr/ziggurat | 225.828, 214.504, 240.710, 219.149, 244.112 | 45.214, 44.322, 46.010, 44.356, 45.029 |
| sorting_direct/inverse | 350.999, 331.642, 306.652, 292.046, 304.598 | 67.005, 61.463, 63.112, 64.359, 62.316 |
| sorting_direct/ziggurat | 325.262, 302.396, 294.576, 296.351, 318.431 | 62.245, 61.537, 64.469, 63.365, 61.907 |
| rssa_cr/inverse | 51.035, 47.708, 57.059, 46.310, 54.390 | 9.981, 9.723, 10.536, 10.522, 16.662 |
| rssa_cr/ziggurat | 57.828, 46.288, 57.787, 70.613, 54.102 | 9.345, 9.251, 9.428, 10.377, 12.026 |
| Julia/Direct | 650.715, 644.351, 790.811, 653.915, 692.799 | 155.618, 156.948, 148.153, 163.657, 147.644 |
| Julia/SortingDirect | 215.778, 219.712, 252.367, 229.460, 227.661 | 57.732, 48.967, 177.664, 42.335, 170.535 |
| Julia/DirectCR | 207.726, 217.342, 253.546, 205.346, 219.487 | 66.488, 53.219, 65.510, 65.939, 70.338 |
| Julia/NRM | 304.588, 344.930, 349.043, 313.741, 314.898 | 91.717, 160.226, 72.232, 78.281, 68.848 |
| Julia/RSSACR | 40.381, 43.108, 48.212, 40.120, 36.747 | 18.763, 39.494, 32.478, 21.495, 26.748 |
| Julia/SortingDirect-fresh | 388.452, 395.423, 599.450, 381.743, 386.877 | 168.831, 78.991, 68.959, 213.077, 59.731 |
W6/throughput
| Engine / waiting time | 1 worker, five observations (ms) | 8 workers, five observations (ms) |
|---|---|---|
| direct/inverse | 24430.257, 23066.909, 22747.589, 24018.344, 22939.256 | 4934.719, 4450.573, 4129.645, 4473.062, 4259.901 |
| direct/ziggurat | 24509.848, 24830.829, 24976.558, 23867.859, 24733.992 | 4711.015, 4595.102, 4628.570, 4665.154, 4464.662 |
| cached_direct/inverse | 4285.939, 4101.410, 4039.155, 3962.707, 4219.454 | 606.470, 603.424, 604.130, 601.021, 599.921 |
| cached_direct/ziggurat | 4408.966, 4170.929, 3896.213, 3967.140, 4306.827 | 587.916, 598.074, 617.313, 596.220, 606.071 |
| direct_cr/inverse | 4052.781, 3692.933, 3526.067, 3459.692, 3588.430 | 676.790, 722.892, 715.855, 725.295, 722.429 |
| direct_cr/ziggurat | 4271.307, 3446.370, 3443.194, 3457.772, 3516.931 | 666.472, 703.189, 696.955, 707.462, 701.049 |
| sorting_direct/inverse | 5772.261, 4964.496, 5451.818, 4924.830, 5064.538 | 919.457, 941.506, 980.308, 1002.133, 971.630 |
| sorting_direct/ziggurat | 5335.212, 4664.121, 5036.879, 4784.073, 5458.743 | 978.483, 977.330, 992.857, 978.827, 965.366 |
| rssa_cr/inverse | 880.976, 759.408, 833.940, 742.565, 865.508 | 148.199, 162.033, 164.519, 158.430, 147.932 |
| rssa_cr/ziggurat | 879.845, 768.128, 922.326, 747.057, 767.220 | 141.634, 238.696, 147.402, 143.023, 138.828 |
| Julia/Direct | 11356.974, 10645.830, 10502.531, 10256.248, 10295.594 | 2223.903, 2184.773, 2232.516, 2089.236, 2000.755 |
| Julia/SortingDirect | 3140.812, 3487.370, 3222.931, 2793.272, 2990.835 | 503.036, 486.744, 526.778, 527.647, 496.463 |
| Julia/DirectCR | 4096.317, 3751.743, 3345.109, 3219.504, 3414.713 | 688.795, 632.817, 693.694, 702.828, 689.957 |
| Julia/NRM | 5708.608, 5009.541, 4852.382, 5055.557, 4968.774 | 947.584, 924.323, 938.048, 929.535, 890.018 |
| Julia/RSSACR | 887.396, 692.599, 664.428, 622.152, 669.604 | 141.267, 135.583, 144.496, 134.222, 150.260 |
| Julia/SortingDirect-fresh | 7738.590, 5919.567, 6300.938, 5590.521, 6109.619 | 1413.107, 1344.340, 1379.807, 1294.531, 1490.332 |
W7/original
| Engine / waiting time | 1 worker, five observations (ms) | 8 workers, five observations (ms) |
|---|---|---|
| direct/inverse | 100.339, 145.431, 87.845, 95.632, 87.647 | 21.343, 21.725, 20.766, 20.288, 21.192 |
| direct/ziggurat | 109.406, 120.743, 109.872, 107.508, 107.959 | 24.596, 22.039, 21.948, 21.829, 21.491 |
| cached_direct/inverse | 28.348, 19.233, 19.138, 23.942, 19.316 | 4.317, 3.791, 4.902, 4.285, 3.774 |
| cached_direct/ziggurat | 21.267, 23.346, 20.913, 22.100, 20.454 | 6.278, 3.865, 4.115, 4.628, 3.895 |
| direct_cr/inverse | 30.119, 26.058, 17.719, 20.711, 17.768 | 4.559, 4.066, 4.308, 5.804, 4.015 |
| direct_cr/ziggurat | 23.891, 20.950, 25.307, 21.401, 19.828 | 3.902, 3.766, 4.017, 3.845, 4.004 |
| sorting_direct/inverse | 26.139, 23.096, 26.156, 20.344, 21.987 | 5.523, 4.789, 5.221, 5.468, 4.586 |
| sorting_direct/ziggurat | 25.568, 19.484, 18.544, 20.179, 21.319 | 6.429, 4.294, 7.490, 5.568, 4.623 |
| rssa_cr/inverse | 23.499, 19.753, 22.331, 18.818, 19.126 | 10.056, 3.828, 4.853, 43.302, 3.807 |
| rssa_cr/ziggurat | 19.845, 22.470, 19.572, 18.260, 19.526 | 8.084, 3.641, 5.185, 6.225, 3.476 |
| Julia/Direct | 48.099, 47.116, 46.777, 42.157, 40.204 | 15.597, 15.064, 16.222, 15.582, 15.372 |
| Julia/SortingDirect | 19.920, 19.892, 18.697, 16.634, 16.502 | 10.347, 8.572, 22.865, 17.244, 11.252 |
| Julia/DirectCR | 19.729, 22.118, 17.517, 16.963, 14.574 | 8.074, 8.511, 8.387, 10.123, 14.465 |
| Julia/NRM | 22.509, 20.188, 17.318, 18.151, 19.446 | 11.077, 8.539, 9.016, 10.411, 8.248 |
| Julia/RSSACR | 15.561, 15.959, 13.567, 14.018, 13.597 | 9.939, 17.389, 8.889, 9.007, 7.513 |
| Julia/SortingDirect-fresh | 72.825, 90.554, 62.668, 84.236, 130.362 | 19.974, 13.863, 23.076, 24.424, 12.127 |
W7/throughput
| Engine / waiting time | 1 worker, five observations (ms) | 8 workers, five observations (ms) |
|---|---|---|
| direct/inverse | 1590.762, 1470.634, 1502.941, 1652.365, 1399.340 | 310.096, 325.811, 311.579, 310.496, 305.444 |
| direct/ziggurat | 1643.409, 1661.368, 1574.602, 1681.217, 1538.161 | 318.978, 315.927, 313.481, 317.432, 318.402 |
| cached_direct/inverse | 353.182, 322.512, 312.802, 393.356, 320.747 | 55.961, 53.173, 55.535, 54.515, 55.061 |
| cached_direct/ziggurat | 308.883, 330.629, 312.776, 347.994, 322.623 | 60.843, 49.936, 59.098, 50.765, 51.299 |
| direct_cr/inverse | 348.507, 320.264, 294.758, 329.843, 306.123 | 59.107, 57.817, 58.583, 57.143, 58.632 |
| direct_cr/ziggurat | 310.143, 326.710, 269.870, 392.506, 290.371 | 53.595, 52.705, 52.971, 52.827, 55.625 |
| sorting_direct/inverse | 392.935, 348.159, 320.789, 383.987, 360.961 | 67.013, 66.398, 66.633, 67.173, 68.462 |
| sorting_direct/ziggurat | 301.374, 342.315, 319.813, 332.116, 340.081 | 92.456, 62.931, 64.514, 63.587, 66.728 |
| rssa_cr/inverse | 270.086, 293.791, 283.164, 310.602, 309.850 | 52.223, 53.065, 55.258, 51.878, 52.416 |
| rssa_cr/ziggurat | 294.754, 304.037, 266.006, 352.016, 279.748 | 46.144, 46.370, 47.671, 46.086, 52.984 |
| Julia/Direct | 697.242, 666.690, 687.416, 779.787, 861.538 | 169.905, 159.013, 165.367, 164.232, 169.113 |
| Julia/SortingDirect | 260.325, 257.731, 266.245, 277.927, 286.625 | 44.608, 49.602, 46.549, 43.942, 43.801 |
| Julia/DirectCR | 254.485, 238.716, 248.936, 230.685, 255.264 | 54.135, 51.757, 62.756, 62.310, 50.518 |
| Julia/NRM | 302.200, 310.942, 292.814, 303.731, 297.659 | 62.430, 59.799, 59.716, 58.917, 63.999 |
| Julia/RSSACR | 224.408, 214.461, 227.299, 209.275, 220.198 | 41.571, 41.810, 42.331, 43.022, 41.517 |
| Julia/SortingDirect-fresh | 1041.442, 978.436, 1195.435, 1008.967, 1063.807 | 245.605, 253.987, 245.708, 381.871, 236.191 |
Provenance and implementation log
- Fetched GitHub main and created an isolated worktree. Built the current fast-mode release wheel and CLI without changing the numerical engine.
- Installed official Julia 1.13.3 with SHA-256 verification, instantiated the repository’s pinned Catalyst/JumpProcesses environment, and completed precompilation.
- Declared models, methods, thread counts, sample sizes, statistical bounds, timing boundaries and replay requirements before experiments.
- Added a persistent Julia ensemble driver and Python comparison harness; ran the baseline gates, rate probes, distribution/conservation checks and replay checks.
- Warmed all configurations, collected five rotated rounds and generated this Markdown directly from complete evidence. No remote push or publication was performed.
Evidence SHA-256 (validation/eight-thread/evidence/comparison.json): 611b0a0d78ac2b567bf148094139a0ab5a2147952783d1e8b355faf8f89c646f.
| Model | Frozen JSON SHA-256 |
|---|---|
| W1 | d2fa8a1f5bdc9976c0bce4f36e8e472690f2ecd1ca3c0f3a4cf642059a37b61e |
| W2 | d0f6a86b31cd697b821b5ed2bf384323c8eb1328868fe2274777bac0f5e73355 |
| W3 | 69f9ff6bfec8a473b70111caf6ba2d57e9ce6d363f537eac185f0f88097c8637 |
| W4 | fb9204e42395eb3eeef76de4e2d54bf33611bdd43435eb7a4eb8fda652df8715 |
| W5 | c8c2671550a2c67562262f1c2ea22da468bf5acbce6a21309094db3e9aba2681 |
| W6 | 4333e9086f36c5d713c16e7f8f12b43ff9163d2709459820bd92161a9c28f7e0 |
| W7 | 5b6c5f5e329e9fe7146b68cb0ac7d54ee503b64b0e91c6d796c438575edf7ca1 |
| Source | SHA-256 |
|---|---|
| Cargo.lock | 6e58d9e3d1c2e2bd36cbe37f30cfe1b98ea287a368fc50f13cbe920db993cc4b |
| bindings/python/Cargo.lock | 9999d565a026401d196860ef5a23b2066e085bc0bb946ae0186033609538cab8 |
| validation/acceleration_workloads.py | 82a6479d06e61dd7b8c674cc876eea17b453b058e2709cdc29339bcb65540a9e |
| validation/compare_eight_threads.py | 7437610e5a9bd84cf6e0652123758da1d59d81a6b9491d290115eb561e787e47 |
| validation/compare_julia.py | 24897a366971d2bc8746d507f348d32f7cca242303bf3ef0cfb9dd48e19a5524 |
| validation/eight-thread/ensemble_server.jl | 0f45d8ba29cc9b6127173cc7e744a795ed2823cb41406b6f239e6fa0015ce78a |
| validation/eight-thread/generated_models.jl | 5caeb8a25625cccd4d0c56b185e6bf5002002e40f676452a37c1caf6dd6de8ee |
| validation/ssa-acceleration/julia/Manifest.toml | 2b7c9970e8bce9f1ca0c8f322ca7e4c20869aa4ec1f67c3a89d9b9df16b54655 |
| validation/ssa-acceleration/julia/Project.toml | 4721301b2e017a177b376b00765982bf67a1e98beadf1b1ce6862fb38e904885 |
Reference API documentation: JumpProcesses ensemble/problem reuse, SciMLBase ensembles. Thread-copy and RNG behavior was also checked against the installed pinned SciMLBase 3.58.0 source, not inferred from elapsed time.
One worker, derived on import
The one-worker observations above also give a serial comparison, measured on the same host and with the same boundaries. For each workload the lowest one-worker median is selected independently (it can differ from the eight-worker choice). This replaces the earlier serial projection of 1.02× in the Catalyst/JumpProcesses comparison, which scaled checked-default timings by fast/default speedups from another host.
| Batch | Fast choice | Fast 1 ms | Julia choice | Julia 1 ms | Fast / Julia |
|---|---|---|---|---|---|
| W1/original | cached_direct/ziggurat | 60.695 | Direct | 52.742 | 1.15× |
| W2/original | direct_cr/ziggurat | 106.051 | DirectCR | 99.262 | 1.07× |
| W3/original | cached_direct/ziggurat | 256.420 | SortingDirect | 300.133 | 0.85× |
| W4/original | rssa_cr/ziggurat | 137.658 | RSSACR | 103.908 | 1.32× |
| W5/original | direct_cr/ziggurat | 55.878 | DirectCR | 49.409 | 1.13× |
| W6/original | rssa_cr/inverse | 51.035 | RSSACR | 40.381 | 1.26× |
| W7/original | cached_direct/inverse | 19.316 | RSSACR | 14.018 | 1.38× |
| W1/throughput | cached_direct/ziggurat | 223.838 | Direct | 215.211 | 1.04× |
| W2/throughput | direct_cr/ziggurat | 458.207 | DirectCR | 372.578 | 1.23× |
| W3/throughput | cached_direct/ziggurat | 1067.678 | SortingDirect | 1187.266 | 0.90× |
| W4/throughput | rssa_cr/ziggurat | 490.796 | RSSACR | 423.411 | 1.16× |
| W5/throughput | direct_cr/ziggurat | 916.916 | DirectCR | 837.709 | 1.09× |
| W6/throughput | rssa_cr/ziggurat | 768.128 | RSSACR | 669.604 | 1.15× |
| W7/throughput | rssa_cr/inverse | 293.791 | RSSACR | 220.198 | 1.33× |
Geometric mean of fast / Julia at one worker: 1.15× for the original batches (fast lower on 1/7; range 0.85–1.38×) and 1.12× for 256-path batches (fast lower on 1/7; range 0.90–1.33×). With one worker Julia’s best method is faster on six of seven workloads. On the short original batches the selected fast methods scale 5.07–6.13× from one to eight workers and Julia’s 1.51–5.78×, which reverses the order; the 256-path batches are close to parity. The measurements do not isolate the cause. The same limits apply as above: five observations per configuration on one shared host, different timing boundaries, and best observed choices rather than an automatic selector.
Reusable parameters, generated kernels and rebop: full optimization
Measured with the 0.6.0 network engine (note of 12 November 2026). The CRN-craft routes on this page (
ParameterTemplate, generated propensity kernels, thefastpolicy) belong to the network engine of releases 0.2.0 to 0.6.0, which release 0.7.0 replaced with one engine. The full optimization run was not repeated, and the tables below are left as measured. In 0.7.0 a parameter search binds values on a prepared run (bind_parameters, see parameter sweeps), and the benchmark worker has the routesfreshandreuse. Their worker calls were timed against the 0.6.0 workers in one session (validation/merge/parameter-workers-m4d.json, declared and reported invalidation/merge/RESULTS.md, “M4d (law gate of the run/1.0 default, worker speed rerun)”), with a declared target of 1.25 times the 0.6.0 time. Newreuseagainst oldreusetook 1.10 (birth_death) and 1.05 (sparse33) times as long, and 1.55 times on binding12, which failed the target: therebind_parametersprepares the whole model again on each call. Both routes of each engine returned identical moments.
Measured before the 0.2.0 release. These measurements come from the import commit
85a085bof 2 November 2026 and have not been repeated on release 0.2.0 (4 November 2026). Review fixes since the import (fdfd3d8) changed the fallback that generated kernels use for rates they do not specialize (other laws than mass action, reactions above second order) and for values that are not normal floats; the three mass-action models here have no reaction above second order.fastalso became the default ofssarequests (crn-craft.ssa-run/0.3), and the Ziggurat waiting-time sampler was refactored so the rules engine can share it. Results are unchanged; the timings on 0.2.0 may differ.
Measured 2 November 2026, America/La_Paz. Base GitHub main c16fcc5, including
PR #8’s optional method.fast. Actual engine versions: CRN-craft 0.2.0.dev1,
rebop 0.10.0, fcmaes-rust 0.2.1.
This is a same-host experiment; it does not project the previous Julia timings.
All 54 complete optimization runs finished: three fixed models, six execution routes and three optimizer seeds. There were 6,912 actual objective evaluations. All nine three-route CRN optimizer trace comparisons were identical, point for point and loss for loss. Compiled code reused each topology across all candidates; coefficients remained runtime data.
The reusable interface reduced total optimizer time by about 7% on sparse33 and 1.73× on binding12 (per seed 1.69–1.77×); birth/death was essentially flat. Three seeds with one repetition each cannot resolve smaller effects: on birth/death, where fresh and reusable CRN simulate identical paths, their ratio still ranged 0.85–1.16× across seeds. Generated propensities gave a median 1.18× on birth/death (per seed 0.99–1.27×), 0.92–0.97× on sparse33 (median about 8.5% slower) and 0.73–1.01× on binding12; none of these is resolved. Generation did not repay its bundle compilation in these 128-evaluation runs. Rebop macros were faster than reusable CRN by 3.44× on birth/death (per seed 2.99–4.35×) and 1.72× on binding12 (1.64–1.77×), and approximately tied on sparse33 (0.94–1.00×), using optimizer time. Across all nine runs per route, complete cost including one build was 13.21s for reusable CRN, 17.53s for generated CRN and 12.88s for rebop macros; the 2.5% difference between reusable CRN and rebop macros is within the run-to-run variation. These aggregated results also include different cross-engine search paths and final points.
The new parameter interface and optional generator are runnable. Numerical speed and optimization quality are reported separately below; the generated backend specializes propensities and retains the core solver.
birth_death
| Route | Optimizer s | Held-out s | First-run total s | Exact loss | Held-out loss |
|---|---|---|---|---|---|
| CRN fresh, fast | 0.1246 | 0.0831 | 2.0171 | 0.000776 | 0.000878 |
| CRN reusable, fast | 0.1272 | 0.0829 | 2.0069 | 0.000776 | 0.000878 |
| CRN generated, fast | 0.1078 | 0.0739 | 6.0127 | 0.000776 | 0.000878 |
| rebop expression | 1.8624 | 1.8965 | 3.7032 | 0.002768 | 0.003229 |
| rebop rebuilt LMA | 2.1787 | 2.0818 | 4.1188 | 0.002768 | 0.003229 |
| rebop macro | 0.0370 | 0.0195 | 2.2970 | 0.002768 | 0.003229 |
sparse33
| Route | Optimizer s | Held-out s | First-run total s | Exact loss | Held-out loss |
|---|---|---|---|---|---|
| CRN fresh, fast | 1.9365 | 1.6922 | 5.4477 | 0.001761 | 0.001885 |
| CRN reusable, fast | 1.8080 | 1.6751 | 5.2956 | 0.001761 | 0.001885 |
| CRN generated, fast | 1.9626 | 1.6901 | 9.3571 | 0.001761 | 0.001885 |
| rebop expression | 44.6813 | 45.4836 | 90.1658 | 0.003450 | 0.003648 |
| rebop rebuilt LMA | 23.6343 | 24.4120 | 49.9980 | 0.003450 | 0.003648 |
| rebop macro | 1.8018 | 1.6212 | 5.6664 | 0.003450 | 0.003648 |
binding12
| Route | Optimizer s | Held-out s | First-run total s | Exact loss | Held-out loss |
|---|---|---|---|---|---|
| CRN fresh, fast | 0.0453 | 0.0121 | 1.8642 | 0.001000 | 0.001132 |
| CRN reusable, fast | 0.0262 | 0.0126 | 1.8465 | 0.001000 | 0.001132 |
| CRN generated, fast | 0.0266 | 0.0113 | 5.8652 | 0.001000 | 0.001132 |
| rebop expression | 3.3750 | 3.3818 | 6.5518 | 0.000559 | 0.000765 |
| rebop rebuilt LMA | 3.3178 | 3.2864 | 6.6262 | 0.000559 | 0.000765 |
| rebop macro | 0.0153 | 0.0034 | 2.2617 | 0.000559 | 0.000765 |
Binding cost
The following per-candidate native preparation costs are medians of each run’s mean; the optimizer tables also include simulation and application overhead.
| Case | Fresh preparation µs | Reusable binding µs | Preparation gain |
|---|---|---|---|
| birth_death | 90.2 | 12.2 | 7.42× |
| sparse33 | 1003.6 | 150.8 | 6.65× |
| binding12 | 105.4 | 10.4 | 10.18× |
Times/losses are medians over the three declared optimizer seeds. Lower is better. “Optimizer s” includes all objective calls, transport, reduction and optimizer overhead. “First-run total” includes process setup/teardown, source generation, the entire relevant bundle’s dependency-cache-warm compilation, optimizer time, exact-oracle assessment and 4096-path held-out validation. It excludes dependency installation/compilation. Every seed and timing observation remains in the raw report.
Repeated-use cost
The following totals cover all nine runs per route, charging the bundle’s build once. They illustrate reuse across models/seeds; they are not per-model compiler cost estimates. Existing applications can also amortize the generic Rust worker build over arbitrary later models.
| Route | Generation + build s | Nine optimizations s | Nine complete runs + one build s |
|---|---|---|---|
| CRN fresh, fast | 1.7608 | 6.3143 | 13.6324 |
| CRN reusable, fast | 1.7608 | 5.8928 | 13.2068 |
| CRN generated, fast | 5.7806 | 6.1865 | 17.5279 |
| rebop expression | 0.0000 | 146.1770 | 289.9288 |
| rebop rebuilt LMA | 0.0000 | 89.6286 | 180.5700 |
| rebop macro | 2.1944 | 5.7772 | 12.8773 |
Quality and evaluation accounting
Targets use independent Poisson moments for the two linear systems and a 13-state generator/matrix exponential for reversible binding. Each objective uses 32 trajectories with a fixed training seed; each final point receives 4096 new trajectories on an independent held-out seed. Exact loss evaluates the fitted point’s mathematical moments, without simulation noise. The objective normalizes squared mean/variance residuals and excludes t=0. Parameter errors below are the largest relative error over parameters and optimizer seeds. A small moment loss does not guarantee parameter identifiability.
| Case | Route | Exact loss range | Largest parameter error | Actual objective calls |
|---|---|---|---|---|
| birth_death | CRN fresh, fast | 0.000471–0.008478 | 24.8% | 384 |
| birth_death | CRN reusable, fast | 0.000471–0.008478 | 24.8% | 384 |
| birth_death | CRN generated, fast | 0.000471–0.008478 | 24.8% | 384 |
| birth_death | rebop expression | 0.001464–0.013255 | 91.2% | 384 |
| birth_death | rebop rebuilt LMA | 0.001464–0.013255 | 91.2% | 384 |
| birth_death | rebop macro | 0.001464–0.013255 | 91.2% | 384 |
| sparse33 | CRN fresh, fast | 0.000857–0.002384 | 23.2% | 384 |
| sparse33 | CRN reusable, fast | 0.000857–0.002384 | 23.2% | 384 |
| sparse33 | CRN generated, fast | 0.000857–0.002384 | 23.2% | 384 |
| sparse33 | rebop expression | 0.002739–0.006245 | 34.8% | 384 |
| sparse33 | rebop rebuilt LMA | 0.002739–0.006245 | 34.8% | 384 |
| sparse33 | rebop macro | 0.002739–0.006245 | 34.8% | 384 |
| binding12 | CRN fresh, fast | 0.000859–0.001132 | 51.9% | 384 |
| binding12 | CRN reusable, fast | 0.000859–0.001132 | 51.9% | 384 |
| binding12 | CRN generated, fast | 0.000859–0.001132 | 51.9% | 384 |
| binding12 | rebop expression | 0.000376–0.000939 | 56.9% | 384 |
| binding12 | rebop rebuilt LMA | 0.000376–0.000939 | 56.9% | 384 |
| binding12 | rebop macro | 0.000376–0.000939 | 56.9% | 384 |
All route/model median exact losses met the predeclared <=.05 aspiration. Parameter recovery was less precise: worst errors reached 51.9% for CRN binding and 91.2% for a rebop birth/death run. These are finite-budget fits to noisy 32-path moments; a low moment loss is insufficient evidence of accurate rate identification. Held-out loss and parameter error remain separate results.
The exact-loss <=.05 aim was aspirational, not a reason to repeat or drop runs. Cross-engine streams differ, so different final points need not imply a solver bias or a superior optimizer. Three search seeds and these three synthetic models support only the reported scope.
Compilation and boundaries
| Worker bundle | Measured rebuild s |
|---|---|
| dynamic | 1.7608 |
| generated | 5.7786 |
| rebop_macro | 2.1933 |
Model-independent dependencies were primed consistently. Each worker package was cleaned and rebuilt separately, with the same standard Cargo release profile. The generated bundle contains the three model kernels and an arithmetic guard. A single-model production build could have a different cost. No clean-machine installation, LTO tuning or other-platform claim is made.
CRN fresh/reusable/generated all use cached Direct, Ziggurat and fast=True, one numerical worker. Fast’s state checks, work budgets, stop polling and accounting remain. Rebop macros use generated model-specific state/reaction code; rebop dynamic uses runtime expressions or rebuilt mass-action definitions. Rebop macros specialize the full reaction code and state representation; our AOT route specializes propensity evaluation within the existing checked solver. Native startup also includes the common worker framework/reference seed-list preparation; it is not the minimum overhead of an in-process Rust application. Dynamic rebop explicitly uses sparse storage on the 33-species model. Both Python routes construct per-trajectory xarray outputs; native routes communicate with a persistent worker and return reduced moments. These are complete application costs with different allocation/check pipelines. Native bind and simulation times are retained for CRN; event counts are not, so the engines’ different search paths cannot be normalized by work. The CRN worker also serializes and hashes each result. Ratios of optimization times are not isolated event-kernel throughput measurements.
The host is AMD EPYC 9V74 80-Core Processor, affinity allowance
9, CPU quota 800000 100000.
All builds and heavy gates finished before optimizer timing. No multithread,
GPU, biological-network generalization or Julia performance claim is made.
Validation and reproduction
The final engine passed 196 release tests on Rust 1.88 and 1.85,
core/binding/worker clippy with warnings denied, strict schema/CLI, installed
Python, legacy SSA/CME and dependency gates. Both the checked-default and fast
families passed 210 exact-law comparisons each, 100,000 paths per
fixture/variant, with the existing .001 family alpha and .008046120180018303
DKW epsilon unchanged. Normal/-O outputs match. Independent generated checks
cover 180 bindings/executions, 3150 arithmetic evaluations, cache refresh,
invalid inputs, cancellation, concurrency, worker replay and wrong topology.
The final gate logs record check_parameter_interface.py with SHA-256
9f08cca6…; the committed file (8ee7cc7f…) was edited afterwards and only
parameter-validation.json was refreshed with it. The evidence describes the
import commit 85a085b; later commits change hashed sources.
API guide,
fixed protocol,
reproduction instructions and
implementation log
accompany the patch. Failed development outputs remain separate. At import,
the checked mode was the default and nothing had been pushed or published.
Since crn-craft.ssa-run/0.3, fast is the default of ssa requests, and
the interface was released in 0.2.0.
Model/algorithm card template
Every numerical extension should record:
- Name, implementation status and supported method/version.
- Mathematical definition and primary references.
- Assumptions, units, domains, reactant gating and unsupported cases.
- Numerical strategy, overflow/dynamic-range handling and error reporting.
- Seed/reproducibility scope where relevant.
- Independent fixtures, predeclared tolerances and mutation tests.
- Performance workload and hardware when measured.
- Known limitations and untested conditions.
The two initial cards document contracts and plans. They do not imply implemented rate evaluation or SSA.
Direct SSA
History (note of 12 November 2026). This card describes the network engine’s Direct method of releases 0.1.0 to 0.6.0, which release 0.7.0 removed with its codes
CRN-E042,CRN-E061andCRN-E062. The one engine’s Static Direct, its selectors and its numerical failures (CRN-R030,CRN-R031) are described in exact methods.
Status: implemented in M2 (0.1.0-dev.4).
Gillespie’s Direct method for a time-homogeneous, well-mixed count process. Existing mass-action/Hill/MM propensities and availability gates are reused; count changes are checked and atomic. The solver recomputes ordered rates, uses a positive exponential wait and a separate categorical draw, and treats zero total propensity as absorption. It includes events exactly on save times.
Random streams: pinned rand_chacha 0.3.1 / rand_core 0.6.4, root-seed key and replicate-index stream; owned 53-bit mappings and libm 0.2.15 inversion. No clipped rates, lost positive channels or last-channel selection fallback. CRN-E042 underflow and CRN-E061/E062 resolution/time errors remain explicit.
Completed fixed-work outputs use ordered reduction and are checked at 1/2/8 threads. Incomplete ensembles have accounting and partial retained paths, but no unconditional mean/variance. Limits and cancellation do not prove non-explosion. Exact-method sampling still has Monte Carlo and floating-point limitations. Cross-platform numerical identity and comparative throughput are not established by this iteration.
See Direct SSA details, archive contracts and M2 acceptance targets. Reference: Gillespie (1977).
Rate-law contracts
History (note of 12 November 2026). This card describes the rate laws of the network model
crn-craft.model/0.1as the network engine of releases 0.1.0 to 0.6.0 evaluated them. Since release 0.7.0 such a model is read through the converter: mass action becomes a rulerate, and the Hill and Michaelis–Menten laws become whole-rulepropensityexpressions in a stable form (architecture). A negative or non-finite rate isCRN-R030;CRN-E042is retired.
Status: argument validation and numerical evaluation implemented in M1a (0.1.0-dev.2). No stochastic time integration is implemented.
| Kind | Complete propensity a(x) | Argument domains |
|---|---|---|
| mass_action | c × product binomial(xᵢ, νᵢ) | c ≥ 0; finite |
| hill_activation | basal + vmax × xⁿ/(kⁿ+xⁿ) | basal,vmax ≥ 0; k,n > 0; finite |
| hill_repression | basal + vmax × kⁿ/(kⁿ+xⁿ) | basal,vmax ≥ 0; k,n > 0; finite |
| michaelis_menten | vmax × x/(km+x) | vmax ≥ 0; km > 0; finite |
All custom laws denote full channel propensities. Reactant availability is a separate gate; no reaction may consume unavailable particles. Counts and regulatory thresholds are in molecule counts, time in seconds. Hill/MM are effective models, not elementary reaction mechanisms. The explicit enzyme example uses three elementary mass-action channels and is distinct from the reduced Michaelis–Menten example.
At fixed Ω, stored coefficients do not rescale automatically. The mass-action ODE/Ω convention is specified in the revised plan. A 2A channel uses c*x*(x-1)/2, including its factorial divisor. Empty reactant sides have an empty product of one. If any reactant is unavailable, every law returns zero before evaluating its formula. Catalysts with equal reactant/product coefficients still gate a reaction.
Numerical implementation and limits
The core pins libm 0.2.15 for pure-Rust scaling and transcendental operations. Mass action combines the coefficient and binomial factors in a scaled mantissa/exponent product, so a large binomial need not overflow before multiplication by a tiny coefficient. Hill fractions use logarithms and a stable logistic form, with log1p near x=k. Very small fractions are combined with log(vmax) before exponentiation. Michaelis–Menten evaluates vmax * (x/(km+x)), avoiding an overflowing vmax*x intermediate. Basal terms are added after the induced Hill term.
Evaluated propensities are f64. Overflow, non-finite/negative values and an entirely underflowed strictly positive rate fail with CRN-E042. Exact zero coefficients and unavailable-reactant gates return zero. Subnormal positive rates are allowed. Normal rounding can discard a tiny induced contribution when a positive basal term remains. Integer counts and updates stay exact i64; conversion to f64 for rate formulas can round counts above 2^53. This is not a correctly rounded or cross-platform identity guarantee.
Validation targets were fixed in docs/decisions/iteration-02-validation.md. Tests cover exact homodimer/heterodimer values for counts 0–50, high-count/tiny-coefficient combinations, extreme Hill arguments, steep thresholds, MM overflow avoidance, subnormals, all gates and transactional failures. An independent Python oracle uses integer combinations, Fraction linear algebra and 100-digit Decimal formulas, including 200 seeded networks. See validation/iteration-02/RESULTS.md for results and the retained development failure.
For interoperability, Catalyst’s API documentation describes combinatorial-rate conventions. An exporter must explicitly translate its chosen target convention; matching a law’s name alone does not establish coefficient equivalence. No external simulator code is copied or linked here.
History
Plans and logs of finished work, kept for the record. They describe the state of the project when they were written.
Plans and logs in this folder
- CRN-craft 0.7.0: one engine, one API, execution plan
- CRN-craft 0.3.0: plan for the first user feedback
- CRN-craft: reviewed implementation plan, revision 2
- Iteration 1 implementation log
- Iteration 2 implementation log
- Iteration 3 implementation log
- Iteration 4 implementation log
- M1b: conservation cones and reaction graphs
Campaign logs and decisions
- Campaign logs: dated task and milestone logs, with the acceptance rules
- Merge campaign for 0.7.0
- Decisions: predeclared protocols and acceptance targets
Documentation restructure and release 0.7.1
Task logs of the campaign that merged the two guides into one, sorted
docs/ by reader and made builder-built models faster:
the merged guide,
case study, fitting, R and Migrating,
how-to page, landing page and README,
reference pages,
one checker for the guide,
the engine change E1,
the documentation after E1,
the case study on the fast path and
the review.
Lists by campaign
The functional M3–M10 work and ten performance iterations, with predeclared gates and retained failures under validation/campaign/. Up to release 0.7.0 this list was part of the README.
Campaign M3–M10 and performance iterations
- Campaign guide and acceptance plan
- M3: finite state projection
- M4a: same-host Direct baseline and M4b: dependency-cached Direct
- M5: Python and circuit workflows
- M6: job SDK and optimization studies
- M7 targets and M7: BDF, sensitivities, fitting and screening
- M8: import subsets
- M9 targets and M9: approximate Poisson leaping
- M10: installation and release preparation
- Performance experiments P01–P10 and P11–P20
- Campaign implementation log and review of 1 November 2026
- Exact-SSA acceleration log and Julia-gap campaign log
- Ten further iterations implementation log, fixed protocol and raw evidence
- The
fastswitch: implementation log, with evidence invalidation/fast/ - Reusable parameters: implementation log and protocol
- Rules engine K0/K1: implementation log, protocol and results
- mtDNA A0–A6: implementation log, protocol and review
- Faster generic rules (S1–S6): implementation log and review
Plans and decisions
- Implementation plan, revision 2
- M0 design decisions and statistical verification policy
- Acceptance declared before implementation: iteration 2, iteration 3, iteration 4, iteration 4 CME review check
- Julia comparison and SSA acceleration protocols: first Julia comparison, exact-SSA acceleration, closing the Julia gap
Implementation logs and validation results
- Implementation logs: iteration 1, iteration 2, iteration 3, iteration 4
- Validation results: summary, iteration 2, iteration 3, iteration 4