tpt_sci_ode/problem.rs
1use std::rc::Rc;
2
3use crate::RhsCallable;
4use crate::error::OdeError;
5use crate::sparse::JacobianPattern;
6
7/// Right-hand-side closure shape accepted by [`OdeProblemBuilder`].
8///
9/// `f(t, y, dydt)` must write the derivative `dy/dt` into `dydt`, given the
10/// current time `t` and state `y`. The state vectors are plain `f64` slices,
11/// so callers do not need to depend on `diffsol` directly.
12pub type Rhs = dyn Fn(f64, &[f64], &mut [f64]);
13
14/// Builder for an [`OdeProblem`]. Use [`OdeProblem::new`] for the common case
15/// (default tolerances), or configure tolerances/step size here first.
16pub struct OdeProblemBuilder {
17 rhs: Rc<dyn RhsCallable>,
18 y0: Vec<f64>,
19 t0: f64,
20 rtol: f64,
21 atol: f64,
22 h0: Option<f64>,
23 jac_pattern: Option<JacobianPattern>,
24}
25
26impl OdeProblemBuilder {
27 /// Start building a problem for `dy/dt = rhs(t, y)` with initial state
28 /// `y0` at time `t0`. The right-hand side is given as a closure
29 /// `Fn(f64, &[f64], &mut [f64])`, which is the common case.
30 pub fn new<F>(rhs: F, y0: Vec<f64>, t0: f64) -> Self
31 where
32 F: Fn(f64, &[f64], &mut [f64]) + 'static,
33 {
34 Self {
35 rhs: Rc::new(rhs),
36 y0,
37 t0,
38 rtol: 1e-6,
39 atol: 1e-6,
40 h0: None,
41 jac_pattern: None,
42 }
43 }
44
45 /// Start building a problem from any [`RhsCallable`] (e.g. a
46 /// `JitRhs` with the `cranelift-jit` feature, compiled by the Cranelift JIT). Use this instead of
47 /// [`OdeProblemBuilder::new`] when the RHS is not a plain closure.
48 pub fn from_rhs<R: RhsCallable + 'static>(rhs: R, y0: Vec<f64>, t0: f64) -> Self {
49 Self {
50 rhs: Rc::new(rhs),
51 y0,
52 t0,
53 rtol: 1e-6,
54 atol: 1e-6,
55 h0: None,
56 jac_pattern: None,
57 }
58 }
59
60 /// Relative tolerance passed to the solver's adaptive error control.
61 pub fn rtol(mut self, rtol: f64) -> Self {
62 self.rtol = rtol;
63 self
64 }
65
66 /// Absolute tolerance passed to the solver's adaptive error control.
67 pub fn atol(mut self, atol: f64) -> Self {
68 self.atol = atol;
69 self
70 }
71
72 /// Declare the Jacobian's sparsity pattern for the implicit sparse path.
73 ///
74 /// With a pattern, sparse Newton solves (state size at least
75 /// `SPARSE_LU_MIN_N` (a private constant)) build the Jacobian
76 /// with one RHS call per color (see
77 /// [`CsrMatrix::jacobian_colored`](crate::sparse::CsrMatrix::jacobian_colored))
78 /// rather than one per state. The pattern must cover every structural
79 /// nonzero, or the Newton iteration uses an incomplete Jacobian.
80 #[must_use]
81 pub fn jacobian_pattern(mut self, pattern: JacobianPattern) -> Self {
82 self.jac_pattern = Some(pattern);
83 self
84 }
85
86 /// Initial step size. If not set, the solver picks one from the interval
87 /// length. The value is clamped to the solver's step limits.
88 pub fn h0(mut self, h0: f64) -> Self {
89 self.h0 = Some(h0);
90 self
91 }
92
93 /// Finalise the builder into a ready-to-solve [`OdeProblem`].
94 ///
95 /// # Errors
96 ///
97 /// Returns [`OdeError::Invalid`] if `y0` is empty or if `rtol`/`atol` are
98 /// not strictly positive.
99 pub fn build(self) -> Result<OdeProblem, OdeError> {
100 let n = self.y0.len();
101 if n == 0 {
102 return Err(OdeError::Invalid(
103 "initial state y0 must be non-empty".to_string(),
104 ));
105 }
106 if self.rtol <= 0.0 || self.atol <= 0.0 {
107 return Err(OdeError::Invalid(
108 "rtol and atol must be strictly positive".to_string(),
109 ));
110 }
111 Ok(OdeProblem {
112 rhs: self.rhs,
113 y0: self.y0,
114 t0: self.t0,
115 rtol: self.rtol,
116 atol: self.atol,
117 h0: self.h0,
118 jac_pattern: self.jac_pattern,
119 nstates: n,
120 })
121 }
122}
123
124/// A built ODE problem, ready to be integrated to a target time with one of
125/// the available solvers (see [`Method`](crate::Method) and
126/// [`OdeProblem::solve`]).
127pub struct OdeProblem {
128 pub(crate) rhs: Rc<dyn RhsCallable>,
129 pub(crate) y0: Vec<f64>,
130 pub(crate) t0: f64,
131 pub(crate) rtol: f64,
132 pub(crate) atol: f64,
133 pub(crate) h0: Option<f64>,
134 pub(crate) jac_pattern: Option<JacobianPattern>,
135 pub(crate) nstates: usize,
136}
137
138impl OdeProblem {
139 /// Build a problem with default tolerances (`rtol = atol = 1e-6`).
140 ///
141 /// # Errors
142 ///
143 /// Returns [`OdeError::Invalid`] if `y0` is empty (the default tolerances are
144 /// always strictly positive, so they never trigger an error here).
145 pub fn new<F>(rhs: F, y0: Vec<f64>, t0: f64) -> Result<Self, OdeError>
146 where
147 F: Fn(f64, &[f64], &mut [f64]) + 'static,
148 {
149 OdeProblemBuilder::new(rhs, y0, t0).build()
150 }
151
152 /// Build a problem from any [`RhsCallable`] (e.g. a `JitRhs`, with the `cranelift-jit` feature).
153 ///
154 /// # Errors
155 ///
156 /// Returns [`OdeError::Invalid`] if `y0` is empty.
157 pub fn from_rhs<R: RhsCallable + 'static>(
158 rhs: R,
159 y0: Vec<f64>,
160 t0: f64,
161 ) -> Result<Self, OdeError> {
162 OdeProblemBuilder::from_rhs(rhs, y0, t0).build()
163 }
164
165 /// Number of state variables.
166 pub fn nstates(&self) -> usize {
167 self.nstates
168 }
169
170 /// Initial time of the problem (the `t0` passed at construction).
171 pub fn t0(&self) -> f64 {
172 self.t0
173 }
174
175 /// Initial state of the problem (the `y0` passed at construction).
176 pub fn y0(&self) -> &[f64] {
177 &self.y0
178 }
179
180 /// Produce a fresh problem that shares this problem's RHS and tolerances
181 /// but starts from a new initial state `y0` at time `t0`. This is used by
182 /// multi-scale orchestration (see `tpt-sci-sim-core`) to step an ODE
183 /// forward incrementally from its current state rather than re-integrating
184 /// from the original `t0` each time.
185 ///
186 /// # Errors
187 ///
188 /// Returns [`OdeError::Invalid`] if `y0` is empty (the shared tolerances are
189 /// strictly positive, so they never trigger an error here).
190 pub fn respawn(&self, y0: Vec<f64>, t0: f64) -> Result<Self, OdeError> {
191 if y0.is_empty() {
192 return Err(OdeError::Invalid(
193 "initial state y0 must be non-empty".to_string(),
194 ));
195 }
196 Ok(Self {
197 rhs: self.rhs.clone(),
198 y0,
199 t0,
200 rtol: self.rtol,
201 atol: self.atol,
202 h0: self.h0,
203 jac_pattern: self.jac_pattern.clone(),
204 nstates: self.nstates,
205 })
206 }
207}