Skip to main content

tpt_sci_reaction_network/
lib.rs

1//! # tpt-sci-reaction-network
2//!
3//! A **species / rate / stoichiometry DSL for compartmental models** — the
4//! Rust equivalent of Julia's [Catalyst.jl](https://github.com/SciML/Catalyst.jl)
5//! — built from scratch for the `tpt-science` pillar.
6//!
7//! Given a chemical reaction network (species, reactions, and rate laws), the
8//! crate compiles the **law of mass action** into the deterministic ODE
9//!
10//! ```text
11//! dy/dt = S · r(y, p)
12//! ```
13//!
14//! where `S` is the stoichiometry matrix and `r` the per-reaction rate vector,
15//! and hands the result to [`tpt_sci_ode`] for integration. It also exposes the
16//! stoichiometry matrix and rate vector directly for inspection, parameter
17//! estimation, or coupling into a larger multi-scale model.
18//!
19//! In addition to the deterministic mass-action ODE, the crate provides three
20//! stochastic backends operating on the same IR: exact trajectories via
21//! [`ReactionSystem::simulate_ssa`] (Gillespie's direct method), approximate
22//! but much faster trajectories via [`ReactionSystem::simulate_tau_leaping`]
23//! (explicit tau-leaping, Poisson-distributed reaction counts per step), and
24//! the diffusion-limit [`ReactionSystem::simulate_cle`] (the Chemical
25//! Langevin Equation, Euler–Maruyama with Gaussian noise) — see
26//! [`crate::tau_leap`] for the tradeoffs between them.
27//!
28//! Beyond simulation, [`ReactionSystem::conservation_laws`] finds linear
29//! conservation laws (the left null space of the stoichiometry matrix) for
30//! structural analysis of a network, and [`ReactionNetwork::from_sbml`] reads
31//! a practical subset of SBML XML directly into this crate's IR (see
32//! [`crate::sbml`] for exactly what subset).
33//!
34//! This is the **v1** scope from `spec.txt` / `registry.toml`: a CRN IR, a
35//! mass-action ODE builder, exact/tau-leaping/CLE stochastic backends, a
36//! minimal SBML reader, and conservation-law detection. (The previous plan
37//! deferred the stochastic backend to wrapping `rebop`; it is now implemented
38//! from scratch instead.)
39//!
40//! ## Building models
41//!
42//! Two equivalent ways to define a model:
43//!
44//! 1. **Programmatically** with [`ReactionNetwork`], registering species and
45//!    parameters by name and appending reactions with explicit indices.
46//! 2. **Textually** with the Catalyst.jl-style [`ReactionNetwork::from_dsl`],
47//!    e.g. `kB, S + E --> SE`.
48//!
49//! ## Example
50//!
51//! Michaelis–Menten enzyme kinetics (`S + E ⇌ SE → P + E`):
52//!
53//! ```
54//! use tpt_sci_ode::Method;
55//! use tpt_sci_reaction_network::ReactionNetwork;
56//!
57//! let model = ReactionNetwork::from_dsl(
58//!     "kB, S + E --> SE
59//!      kD, SE --> S + E
60//!      kP, SE --> P + E",
61//! ).unwrap();
62//! let mut model = model;
63//! model.set_parameter("kB", 0.01).unwrap();
64//! model.set_parameter("kD", 0.1).unwrap();
65//! model.set_parameter("kP", 0.1).unwrap();
66//!
67//! // E + SE is conserved: total enzyme stays at its initial 10.
68//! let y0 = model.initial_state(&[("S", 50.0), ("E", 10.0)]).unwrap();
69//! let prob = model.to_ode_problem(&y0, 0.0).unwrap();
70//! let y = prob.solve(Method::Bdf, 200.0).unwrap();
71//!
72//! let e = model.species_index("E").unwrap();
73//! let se = model.species_index("SE").unwrap();
74//! assert!((y[e] + y[se] - 10.0).abs() < 1e-6);
75//! ```
76//!
77//! Licensed under either of MIT or Apache-2.0 at your option.
78
79pub mod analysis;
80pub mod error;
81pub mod model;
82pub mod ode;
83pub mod sbml;
84pub mod ssa;
85pub mod tau_leap;
86
87pub use error::ReactionNetworkError;
88pub use model::{RateLaw, Reaction, ReactionNetwork, ReactionSystem, Term};
89pub use sbml::SbmlModel;
90pub use ssa::SsaTrajectory;
91pub use tau_leap::TauLeapConfig;
92
93#[cfg(test)]
94mod tests {
95    use approx::assert_abs_diff_eq;
96
97    use super::*;
98    use tpt_sci_ode::Method;
99
100    fn sir_builder() -> ReactionNetwork {
101        let mut net = ReactionNetwork::new();
102        let s = net.species("S");
103        let i = net.species("I");
104        let r = net.species("R");
105        net.parameter("beta", 0.0);
106        net.parameter("gamma", 0.0);
107        net.reaction(
108            &[(s, 1.0), (i, 1.0)],
109            &[(i, 2.0)],
110            RateLaw::mass_action("beta"),
111        );
112        net.reaction(&[(i, 1.0)], &[(r, 1.0)], RateLaw::mass_action("gamma"));
113        net
114    }
115
116    #[test]
117    fn stoichiometry_matrix_sir() {
118        let sys = sir_builder().build().unwrap();
119        let s = sys.stoichiometry_matrix();
120        // columns are reaction net-change vectors; rows are species S, I, R
121        assert_eq!(s, vec![vec![-1.0, 0.0], vec![1.0, -1.0], vec![0.0, 1.0]]);
122    }
123
124    #[test]
125    fn dsl_matches_builder_sir() {
126        let built = sir_builder().build().unwrap();
127        let dsl = ReactionNetwork::from_dsl(
128            "beta, S + I --> 2 I
129             gamma, I --> R",
130        )
131        .unwrap();
132        assert_eq!(built.species_names(), dsl.species_names());
133        assert_eq!(built.stoichiometry_matrix(), dsl.stoichiometry_matrix());
134        assert_eq!(built.parameter_names(), dsl.parameter_names());
135    }
136
137    #[test]
138    fn mass_action_rates_dimerization() {
139        let mut net = ReactionNetwork::new();
140        let a = net.species("A");
141        let b = net.species("B");
142        net.parameter("kf", 0.5);
143        net.parameter("kr", 0.25);
144        net.reaction(&[(a, 2.0)], &[(b, 1.0)], RateLaw::mass_action("kf"));
145        net.reaction(&[(b, 1.0)], &[(a, 2.0)], RateLaw::mass_action("kr"));
146        let sys = net.build().unwrap();
147        // r_fwd = kf * A^2, r_rev = kr * B
148        let rates = sys.reaction_rates(&[3.0, 4.0]);
149        assert_abs_diff_eq!(rates[0], 0.5 * 9.0, epsilon = 1e-12);
150        assert_abs_diff_eq!(rates[1], 0.25 * 4.0, epsilon = 1e-12);
151    }
152
153    #[test]
154    fn linear_production_decay_analytic() {
155        // dA/dt = k1 - k2 A  ->  A(t) = k1/k2 + (A0 - k1/k2) e^{-k2 t}
156        let mut model = ReactionNetwork::from_dsl(
157            "k1, 0 --> A
158             k2, A --> 0",
159        )
160        .unwrap();
161        model.set_parameter("k1", 2.0).unwrap();
162        model.set_parameter("k2", 1.0).unwrap();
163        let y0 = model.initial_state(&[("A", 0.0)]).unwrap();
164        let prob = model.to_ode_problem(&y0, 0.0).unwrap();
165        // Use Esdirk34 (3rd order, stiff-capable) for better accuracy
166        let y = prob.solve(Method::Esdirk34, 1.0).unwrap();
167        let expected = 2.0 * (1.0 - (-1.0_f64).exp());
168        assert_abs_diff_eq!(y[0], expected, epsilon = 1e-4);
169    }
170
171    #[test]
172    fn reversible_dimer_conserves_a_plus_2b() {
173        let mut model = ReactionNetwork::from_dsl(
174            "kf, 2 A --> B
175             kr, B --> 2 A",
176        )
177        .unwrap();
178        model.set_parameter("kf", 1.0).unwrap();
179        model.set_parameter("kr", 0.5).unwrap();
180        let y0 = model.initial_state(&[("A", 1.0), ("B", 0.0)]).unwrap();
181        let prob = model.to_ode_problem(&y0, 0.0).unwrap();
182        let y = prob.solve(Method::Esdirk34, 5.0).unwrap();
183        assert_abs_diff_eq!(y[0] + 2.0 * y[1], 1.0, epsilon = 1e-5);
184    }
185
186    #[test]
187    fn michaelis_menten_conserves_enzyme_and_substrate() {
188        let mut model = ReactionNetwork::from_dsl(
189            "kB, S + E --> SE
190             kD, SE --> S + E
191             kP, SE --> P + E",
192        )
193        .unwrap();
194        model.set_parameter("kB", 0.01).unwrap();
195        model.set_parameter("kD", 0.1).unwrap();
196        model.set_parameter("kP", 0.1).unwrap();
197        let y0 = model.initial_state(&[("S", 50.0), ("E", 10.0)]).unwrap();
198        let prob = model.to_ode_problem(&y0, 0.0).unwrap();
199        let y = prob.solve(Method::Esdirk34, 200.0).unwrap();
200
201        let e = model.species_index("E").unwrap();
202        let se = model.species_index("SE").unwrap();
203        let s = model.species_index("S").unwrap();
204        let p = model.species_index("P").unwrap();
205        // enzyme conserved
206        assert_abs_diff_eq!(y[e] + y[se], 10.0, epsilon = 1e-6);
207        // substrate conserved
208        assert_abs_diff_eq!(y[s] + y[se] + y[p], 50.0, epsilon = 1e-6);
209        // product was formed
210        assert!(y[p] > 0.0);
211    }
212
213    #[test]
214    fn custom_rate_law_linear() {
215        let mut net = ReactionNetwork::new();
216        let a = net.species("A");
217        net.parameter("k2", 1.0);
218        // constant production via a custom rate law
219        net.reaction(&[], &[(a, 1.0)], RateLaw::custom(|_y, _p| 2.0));
220        net.reaction(&[(a, 1.0)], &[], RateLaw::mass_action("k2"));
221        let sys = net.build().unwrap();
222        let prob = sys.to_ode_problem(&[0.0], 0.0).unwrap();
223        // Use Esdirk34 (3rd order, stiff-capable) for better accuracy
224        let y = prob.solve(Method::Esdirk34, 1.0).unwrap();
225        let expected = 2.0 * (1.0 - (-1.0_f64).exp());
226        assert_abs_diff_eq!(y[0], expected, epsilon = 1e-4);
227    }
228
229    #[test]
230    fn empty_reaction_rejected() {
231        let mut net = ReactionNetwork::new();
232        let a = net.species("A");
233        net.reaction(&[], &[], RateLaw::mass_action("k"));
234        assert!(matches!(
235            net.build(),
236            Err(ReactionNetworkError::EmptyReaction)
237        ));
238        // DSL: empty both sides
239        assert!(ReactionNetwork::from_dsl("k,  --> ").is_err());
240        let _ = a;
241    }
242
243    #[test]
244    fn undefined_rate_constant_rejected() {
245        let mut net = ReactionNetwork::new();
246        let a = net.species("A");
247        net.reaction(&[], &[(a, 1.0)], RateLaw::mass_action("missing"));
248        assert!(matches!(
249            net.build(),
250            Err(ReactionNetworkError::UndefinedRateConstant(_))
251        ));
252    }
253
254    #[test]
255    fn state_dimension_mismatch_rejected() {
256        let mut model = ReactionNetwork::from_dsl("k, A --> B").unwrap();
257        model.set_parameter("k", 1.0).unwrap();
258        // y0 has the wrong length (2 instead of 1 species)
259        assert!(matches!(
260            model.to_ode_problem(&[0.0], 0.0),
261            Err(ReactionNetworkError::StateDimension { .. })
262        ));
263    }
264
265    #[test]
266    fn unknown_species_in_initial_state_rejected() {
267        let model = ReactionNetwork::from_dsl("k, A --> B").unwrap();
268        assert!(matches!(
269            model.initial_state(&[("Z", 1.0)]),
270            Err(ReactionNetworkError::UnknownSpecies(_))
271        ));
272    }
273
274    #[test]
275    fn sir_population_conserved_under_integration() {
276        let mut model = sir_builder().build().unwrap();
277        model.set_parameter("beta", 1e-4).unwrap();
278        model.set_parameter("gamma", 0.01).unwrap();
279        let y0 = model
280            .initial_state(&[("S", 999.0), ("I", 1.0), ("R", 0.0)])
281            .unwrap();
282        let prob = model.to_ode_problem(&y0, 0.0).unwrap();
283        let y = prob.solve(Method::Bdf, 250.0).unwrap();
284        // S + I + R == N is conserved in the closed SIR model
285        assert_abs_diff_eq!(y[0] + y[1] + y[2], 1000.0, epsilon = 1e-6);
286        // susceptibles only ever decrease
287        assert!(y[0] <= 999.0 + 1e-9);
288        // recovered only ever increases
289        assert!(y[2] >= -1e-9);
290    }
291}