Skip to main content

tpt_sci_ode/
lib.rs

1//! # tpt-sci-ode
2//!
3//! ODE/DAE solving substrate for the `tpt-science` pillar.
4//!
5//! This crate implements its own ODE integrators **from scratch** — no
6//! [`diffsol`](https://crates.io/crates/diffsol), `nalgebra`, or `faer` in the
7//! shipped dependency graph — so the whole crate is TPT-owned code under
8//! `MIT OR Apache-2.0`. It carries its own dual-licensed dense linear algebra
9//! (`DMat` + LU with partial pivoting, in `linalg`) for the implicit-method
10//! linear solves, and depends on `tpt-math-numeric` only for the `Scalar`
11//! numeric trait.
12//!
13//! Four methods are provided (see [`Method`]):
14//! * [`Method::Tsit45`] — explicit Runge–Kutta 5(4), non-stiff.
15//! * [`Method::TrBdf2`] — 2-stage SDIRK (TR-BDF2), A-stable, stiff.
16//! * [`Method::Esdirk34`] — 4-stage ESDIRK order 3(4), A-/L-stable, stiff.
17//! * [`Method::Bdf`] — variable-order (1–5) backward differentiation, stiff.
18//!
19//! All use a shared adaptive-step driver with Hermite dense output, so
20//! [`OdeProblem::solve_dense`] returns exact states at the requested times.
21//! For systems with at least 64 states, the implicit methods build their
22//! Newton matrices through the in-crate sparse CSR/LU path ([`sparse`]),
23//! never materialising a dense Jacobian.
24//! `diffsol` is retained only as an optional, dev-only verification oracle
25//! (feature `verify-diffsol`, excluded from license scanning).
26//!
27//! ## Example
28//!
29//! ```rust
30//! use tpt_sci_ode::{OdeProblem, Method};
31//!
32//! // dy/dt = -y,  y(0) = 1  ->  y(1) = e^-1
33//! let prob = OdeProblem::new(
34//!     |_t, y, dydt| { dydt[0] = -y[0]; },
35//!     vec![1.0],
36//!     0.0,
37//! ).unwrap();
38//! let y = prob.solve(Method::Tsit45, 1.0).unwrap();
39//! assert!((y[0] - std::f64::consts::E.recip()).abs() < 1e-5);
40//! ```
41
42pub mod error;
43
44pub mod events;
45#[cfg(feature = "cranelift-jit")]
46pub mod jit;
47pub mod linalg;
48pub mod problem;
49pub mod scalar;
50pub mod sensitivity;
51pub mod solver;
52pub mod sparse;
53/// Named, time-indexed output with CSV export.
54pub mod trajectory;
55
56pub use error::OdeError;
57#[cfg(feature = "cranelift-jit")]
58pub use jit::{JitRhs, JitRhsBuilder, compile_rhs};
59pub use problem::{OdeProblem, OdeProblemBuilder, Rhs};
60pub use sensitivity::{SensitivityResult, forward_sensitivities};
61pub use solver::Method;
62pub use trajectory::Trajectory;
63
64/// A callable right-hand side for the ODE solvers.
65///
66/// This is implemented automatically for any `Fn(f64, &[f64], &mut [f64])`
67/// closure (the common way to define a problem, e.g. `|t, y, dydt| { .. }`),
68/// and explicitly for `JitRhs` (feature `cranelift-jit`) so a Cranelift
69/// JIT-compiled right-hand side can be used interchangeably with a plain
70/// closure.
71///
72/// [`OdeProblem`] and the integrators store the RHS behind an `Rc<dyn
73/// RhsCallable>`, so both representations share the exact same solving
74/// pipeline.
75pub trait RhsCallable {
76    /// Number of state variables this RHS operates on.
77    fn nstates(&self) -> usize;
78
79    /// Evaluate `dy/dt = f(t, y)` into `dydt`.
80    ///
81    /// # Errors
82    ///
83    /// Returns [`OdeError`] if the evaluation fails (e.g. the RHS reports an
84    /// invalid state). The in-house closure-backed implementation never fails.
85    fn call(&self, t: f64, y: &[f64], dydt: &mut [f64]) -> Result<(), OdeError>;
86}
87
88impl<F> RhsCallable for F
89where
90    F: Fn(f64, &[f64], &mut [f64]),
91{
92    fn nstates(&self) -> usize {
93        // A bare closure does not carry its dimension; the problem size is
94        // taken from `y0` instead.
95        0
96    }
97
98    fn call(&self, t: f64, y: &[f64], dydt: &mut [f64]) -> Result<(), OdeError> {
99        self(t, y, dydt);
100        Ok(())
101    }
102}
103
104// Re-export the numeric scalar trait from the tpt-math substrate that this
105// crate depends on, so downstream science crates share one scalar vocabulary.
106pub use tpt_math_numeric::Scalar;