Skip to main content

lib_jsl_integration/
stiff_ode.rs

1//! Solvers for stiff systems of ordinary differential equations `y' = f(t, y)`.
2//!
3//! Stiff problems mix fast decaying and slow modes; explicit methods must then take steps set
4//! by the fastest mode even after it has died out. Both solvers here are implicit (linearly or
5//! fully), so their step is limited by accuracy alone:
6//!
7//! * [`rosenbrock23`]: the L-stable Rosenbrock (linearly implicit) pair of Shampine and Reichelt
8//!   (MATLAB's `ode23s`): one LU factorisation and three solves per step, order 2 with an order 3
9//!   error estimate. Robust at loose tolerances.
10//! * [`bdf`]: variable-step, variable-coefficient backward differentiation formulas of order up
11//!   to 5 with Newton iteration, ramping the order up from 1 as history accumulates. More
12//!   efficient at tight tolerances.
13//!
14//! The Jacobian `∂f/∂y` may be supplied; otherwise it is formed by forward differences.
15//!
16//! See the book entry [Stiff ODE solvers](https://jwkunz.github.io/lib_jsl/book/integration/stiff-ode.html).
17
18use lib_jsl_core::ErrorsJSL;
19use std::collections::VecDeque;
20
21/// Tolerances and limits shared by the ODE solvers (stiff and non-stiff). Each step must keep
22/// every component's local error below `absolute_tolerance + relative_tolerance · |yᵢ|`.
23#[derive(Debug, Clone, Copy)]
24pub struct OdeOptions {
25    /// Error target relative to the size of each component.
26    pub relative_tolerance: f64,
27    /// Error target for components near zero.
28    pub absolute_tolerance: f64,
29    /// Initial step; chosen automatically when `None`.
30    pub initial_step: Option<f64>,
31    /// The largest number of steps (accepted and rejected).
32    pub max_steps: usize,
33}
34
35/// The former name of [`OdeOptions`].
36pub type StiffOdeOptions = OdeOptions;
37
38impl Default for OdeOptions {
39    fn default() -> Self {
40        OdeOptions { relative_tolerance: 1e-6, absolute_tolerance: 1e-9, initial_step: None, max_steps: 100_000 }
41    }
42}
43
44/// The accepted steps of a solve.
45#[derive(Debug, Clone)]
46pub struct OdeSolution {
47    /// The times of the accepted steps, starting with `t0` and ending with `t1`.
48    pub t: Vec<f64>,
49    /// The state at each time in `t`.
50    pub y: Vec<Vec<f64>>,
51    /// Steps whose error estimate exceeded the tolerance and were retried with a smaller step.
52    pub rejected_steps: usize,
53    /// Evaluations of `f`.
54    pub nfev: usize,
55    /// Evaluations of the Jacobian (zero for explicit methods).
56    pub jacobian_evaluations: usize,
57}
58
59impl OdeSolution {
60    /// The state at the final time.
61    pub fn last(&self) -> &[f64] {
62        self.y.last().expect("a solution holds at least the initial state")
63    }
64}
65
66/// Dense LU factorisation with partial pivoting, stored in place.
67pub(crate) struct Lu {
68    a: Vec<Vec<f64>>,
69    pivot: Vec<usize>,
70}
71
72impl Lu {
73    pub(crate) fn new(mut a: Vec<Vec<f64>>) -> Result<Self, ErrorsJSL> {
74        let n = a.len();
75        let mut pivot = vec![0; n];
76        for k in 0..n {
77            let p = (k..n).max_by(|&i, &j| a[i][k].abs().total_cmp(&a[j][k].abs())).expect("non-empty");
78            if a[p][k] == 0.0 || !a[p][k].is_finite() {
79                return Err(ErrorsJSL::RuntimeError("The iteration matrix is singular."));
80            }
81            a.swap(k, p);
82            pivot[k] = p;
83            for i in k + 1..n {
84                let m = a[i][k] / a[k][k];
85                a[i][k] = m;
86                let (upper, lower) = a.split_at_mut(i);
87                for (x, &pivot_row) in lower[0][k + 1..].iter_mut().zip(&upper[k][k + 1..]) {
88                    *x -= m * pivot_row;
89                }
90            }
91        }
92        Ok(Lu { a, pivot })
93    }
94
95    pub(crate) fn solve(&self, b: &[f64]) -> Vec<f64> {
96        let n = b.len();
97        let mut x = b.to_vec();
98        for k in 0..n {
99            x.swap(k, self.pivot[k]);
100        }
101        for i in 0..n {
102            for j in 0..i {
103                x[i] -= self.a[i][j] * x[j];
104            }
105        }
106        for i in (0..n).rev() {
107            for j in i + 1..n {
108                x[i] -= self.a[i][j] * x[j];
109            }
110            x[i] /= self.a[i][i];
111        }
112        x
113    }
114}
115
116/// Counts evaluations and supplies the Jacobian (analytic or by forward differences).
117struct System<'a, F, J> {
118    f: &'a F,
119    jacobian: Option<&'a J>,
120    evaluations: usize,
121    jacobians: usize,
122}
123
124impl<F, J> System<'_, F, J>
125where
126    F: Fn(f64, &[f64]) -> Vec<f64>,
127    J: Fn(f64, &[f64]) -> Vec<Vec<f64>>,
128{
129    fn eval(&mut self, t: f64, y: &[f64]) -> Result<Vec<f64>, ErrorsJSL> {
130        self.evaluations += 1;
131        let v = (self.f)(t, y);
132        if v.len() != y.len() {
133            return Err(ErrorsJSL::IncompatibleArraySizes((v.len(), y.len())));
134        }
135        Ok(v)
136    }
137
138    fn jacobian(&mut self, t: f64, y: &[f64], fy: &[f64]) -> Result<Vec<Vec<f64>>, ErrorsJSL> {
139        self.jacobians += 1;
140        if let Some(j) = self.jacobian {
141            return Ok(j(t, y));
142        }
143        let n = y.len();
144        let mut jac = vec![vec![0.0; n]; n];
145        let mut z = y.to_vec();
146        for k in 0..n {
147            let h = f64::EPSILON.sqrt() * y[k].abs().max(1e-5);
148            z[k] = y[k] + h;
149            let fz = self.eval(t, &z)?;
150            z[k] = y[k];
151            for i in 0..n {
152                jac[i][k] = (fz[i] - fy[i]) / h;
153            }
154        }
155        Ok(jac)
156    }
157}
158
159pub(crate) fn weighted_max(v: &[f64], y0: &[f64], y1: &[f64], o: &OdeOptions) -> f64 {
160    v.iter()
161        .enumerate()
162        .map(|(i, e)| e.abs() / (o.absolute_tolerance + o.relative_tolerance * y0[i].abs().max(y1[i].abs())))
163        .fold(0.0, f64::max)
164}
165
166pub(crate) fn validate(y0: &[f64], t0: f64, t1: f64, o: &OdeOptions) -> Result<(), ErrorsJSL> {
167    if y0.is_empty() {
168        return Err(ErrorsJSL::InvalidInputRange("The state must not be empty."));
169    }
170    if !t0.is_finite() || !t1.is_finite() {
171        return Err(ErrorsJSL::InvalidInputRange("The time span must be finite."));
172    }
173    if o.relative_tolerance.is_nan() || o.relative_tolerance <= 0.0 || o.absolute_tolerance.is_nan() || o.absolute_tolerance <= 0.0 {
174        return Err(ErrorsJSL::InvalidInputRange("Tolerances must be positive."));
175    }
176    Ok(())
177}
178
179/// Hairer's starting-step heuristic `0.01 ‖y₀‖ / ‖f₀‖` in the weighted norm, capped by the span.
180pub(crate) fn starting_step(y0: &[f64], f0: &[f64], span: f64, o: &OdeOptions) -> f64 {
181    if let Some(h) = o.initial_step {
182        return h.abs().min(span.abs());
183    }
184    let d0 = weighted_max(y0, y0, y0, o);
185    let d1 = weighted_max(f0, y0, y0, o);
186    let h = if d0 < 1e-5 || d1 < 1e-5 { 1e-6 } else { 0.01 * d0 / d1 };
187    h.min(span.abs()).max(1e-12 * span.abs())
188}
189
190/// Solves `y' = f(t, y)` from `(t0, y0)` to `t1` with the Rosenbrock 2(3) pair of `ode23s`.
191/// `∂f/∂t` is estimated by a forward difference.
192pub fn rosenbrock23<F, J>(f: F, jacobian: Option<J>, t0: f64, y0: &[f64], t1: f64, options: OdeOptions) -> Result<OdeSolution, ErrorsJSL>
193where
194    F: Fn(f64, &[f64]) -> Vec<f64>,
195    J: Fn(f64, &[f64]) -> Vec<Vec<f64>>,
196{
197    validate(y0, t0, t1, &options)?;
198    let n = y0.len();
199    let d = 1.0 / (2.0 + 2f64.sqrt());
200    let e32 = 6.0 + 2f64.sqrt();
201    let mut sys = System { f: &f, jacobian: jacobian.as_ref(), evaluations: 0, jacobians: 0 };
202    let direction = (t1 - t0).signum();
203    let (mut t, mut y) = (t0, y0.to_vec());
204    let mut f0 = sys.eval(t, &y)?;
205    let mut h = starting_step(&y, &f0, t1 - t0, &options);
206    let mut solution = OdeSolution { t: vec![t], y: vec![y.clone()], rejected_steps: 0, nfev: 0, jacobian_evaluations: 0 };
207    let mut steps = 0;
208    while (t1 - t) * direction > 0.0 {
209        steps += 1;
210        if steps > options.max_steps {
211            return Err(ErrorsJSL::RuntimeError("The maximum number of steps was exceeded."));
212        }
213        h = h.min((t1 - t).abs());
214        let hs = h * direction;
215        // ANCHOR: rosenbrock_step
216        let jac = sys.jacobian(t, &y, &f0)?;
217        let dt = f64::EPSILON.sqrt() * t.abs().max(1.0);
218        let f_t = sys.eval(t + dt, &y)?;
219        let dfdt: Vec<f64> = (0..n).map(|i| (f_t[i] - f0[i]) / dt).collect();
220        let w: Vec<Vec<f64>> = (0..n).map(|i| (0..n).map(|k| if i == k { 1.0 } else { 0.0 } - hs * d * jac[i][k]).collect()).collect();
221        let lu = Lu::new(w)?;
222        let k1 = lu.solve(&(0..n).map(|i| f0[i] + hs * d * dfdt[i]).collect::<Vec<_>>());
223        let y_half: Vec<f64> = (0..n).map(|i| y[i] + 0.5 * hs * k1[i]).collect();
224        let f1 = sys.eval(t + 0.5 * hs, &y_half)?;
225        let k2: Vec<f64> = lu.solve(&(0..n).map(|i| f1[i] - k1[i]).collect::<Vec<_>>()).iter().zip(&k1).map(|(a, b)| a + b).collect();
226        let y_new: Vec<f64> = (0..n).map(|i| y[i] + hs * k2[i]).collect();
227        let f2 = sys.eval(t + hs, &y_new)?;
228        let rhs: Vec<f64> = (0..n).map(|i| f2[i] - e32 * (k2[i] - f1[i]) - 2.0 * (k1[i] - f0[i]) + hs * d * dfdt[i]).collect();
229        let k3 = lu.solve(&rhs);
230        let err: Vec<f64> = (0..n).map(|i| hs / 6.0 * (k1[i] - 2.0 * k2[i] + k3[i])).collect();
231        let error = weighted_max(&err, &y, &y_new, &options);
232        // ANCHOR_END: rosenbrock_step
233        if error <= 1.0 && y_new.iter().all(|v| v.is_finite()) {
234            // Land exactly on t1 at the last step: t + (t1 − t) need not equal t1 in floating
235            // point, and a leftover sliver would trip the step-size underflow check.
236            t = if (t1 - t).abs() <= h { t1 } else { t + hs };
237            y = y_new;
238            f0 = f2;
239            solution.t.push(t);
240            solution.y.push(y.clone());
241        } else {
242            solution.rejected_steps += 1;
243        }
244        let factor = if error.is_finite() { 0.8 * error.max(1e-10).powf(-1.0 / 3.0) } else { 0.1 };
245        h *= factor.clamp(0.1, 5.0);
246        if h < 1e-14 * t.abs().max(1.0) {
247            return Err(ErrorsJSL::RuntimeError("The step size underflowed."));
248        }
249    }
250    solution.nfev = sys.evaluations;
251    solution.jacobian_evaluations = sys.jacobians;
252    Ok(solution)
253}
254
255/// Derivative at `nodes[0]` of the Lagrange basis polynomials on `nodes`.
256fn lagrange_derivative_at_first(nodes: &[f64]) -> Vec<f64> {
257    let t0 = nodes[0];
258    let mut weights = vec![0.0; nodes.len()];
259    weights[0] = nodes[1..].iter().map(|&tk| 1.0 / (t0 - tk)).sum();
260    for j in 1..nodes.len() {
261        let product: f64 = (1..nodes.len()).filter(|&k| k != j).map(|k| (t0 - nodes[k]) / (nodes[j] - nodes[k])).product();
262        weights[j] = product / (nodes[j] - t0);
263    }
264    weights
265}
266
267/// Lagrange extrapolation of the points `(times, values)` to `t`.
268fn extrapolate(times: &[f64], values: &[&Vec<f64>], t: f64) -> Vec<f64> {
269    let n = values[0].len();
270    let mut out = vec![0.0; n];
271    for (j, (&tj, vj)) in times.iter().zip(values).enumerate() {
272        let l: f64 = times.iter().enumerate().filter(|&(k, _)| k != j).map(|(_, &tk)| (t - tk) / (tj - tk)).product();
273        out.iter_mut().zip(vj.iter()).for_each(|(o, v)| *o += l * v);
274    }
275    out
276}
277
278/// Solves `y' = f(t, y)` from `(t0, y0)` to `t1` with variable-step BDF formulas of order up to
279/// `max_order` (1 to 5). Orders 1 and 2 are A-stable; higher orders are more efficient at tight
280/// tolerances but only stable in a wedge about the negative real axis (fine for dissipative
281/// problems, less so for lightly damped oscillations). The local error is estimated from the
282/// difference between the Newton-corrected solution and the polynomial predictor.
283pub fn bdf<F, J>(f: F, jacobian: Option<J>, t0: f64, y0: &[f64], t1: f64, max_order: usize, options: OdeOptions) -> Result<OdeSolution, ErrorsJSL>
284where
285    F: Fn(f64, &[f64]) -> Vec<f64>,
286    J: Fn(f64, &[f64]) -> Vec<Vec<f64>>,
287{
288    validate(y0, t0, t1, &options)?;
289    if !(1..=5).contains(&max_order) {
290        return Err(ErrorsJSL::InvalidInputRange("The BDF order must be between 1 and 5."));
291    }
292    let n = y0.len();
293    let mut sys = System { f: &f, jacobian: jacobian.as_ref(), evaluations: 0, jacobians: 0 };
294    let direction = (t1 - t0).signum();
295    let f0 = sys.eval(t0, y0)?;
296    let mut h = starting_step(y0, &f0, t1 - t0, &options);
297    let mut history: VecDeque<(f64, Vec<f64>)> = VecDeque::from([(t0, y0.to_vec())]);
298    let mut f_last = f0;
299    let mut solution = OdeSolution { t: vec![t0], y: vec![y0.to_vec()], rejected_steps: 0, nfev: 0, jacobian_evaluations: 0 };
300    let mut steps = 0;
301    loop {
302        let (t, y) = history.back().cloned().expect("history is never empty");
303        if (t1 - t) * direction <= 0.0 {
304            break;
305        }
306        steps += 1;
307        if steps > options.max_steps {
308            return Err(ErrorsJSL::RuntimeError("The maximum number of steps was exceeded."));
309        }
310        h = h.min((t1 - t).abs());
311        let t_new = if (t1 - t).abs() <= h { t1 } else { t + direction * h };
312        let order = max_order.min(history.len().saturating_sub(1)).max(1);
313        // Predictor: extrapolate the last order+1 points, or an Euler step at start-up.
314        let y_pred = if history.len() >= 2 {
315            let start = history.len() - (order + 1).min(history.len());
316            let times: Vec<f64> = history.range(start..).map(|p| p.0).collect();
317            let values: Vec<&Vec<f64>> = history.range(start..).map(|p| &p.1).collect();
318            extrapolate(&times, &values, t_new)
319        } else {
320            (0..n).map(|i| y[i] + (t_new - t) * f_last[i]).collect()
321        };
322        // ANCHOR: bdf_corrector
323        // Corrector: α₀ y + Σ α_j y_{n+1−j} = f(t_new, y), solved by Newton's method.
324        let mut nodes = vec![t_new];
325        nodes.extend(history.iter().rev().take(order).map(|p| p.0));
326        let alpha = lagrange_derivative_at_first(&nodes);
327        let past: Vec<f64> = (0..n).map(|i| history.iter().rev().take(order).enumerate().map(|(j, p)| alpha[j + 1] * p.1[i]).sum()).collect();
328        let f_pred = sys.eval(t_new, &y_pred)?;
329        let jac = sys.jacobian(t_new, &y_pred, &f_pred)?;
330        let lu = Lu::new((0..n).map(|i| (0..n).map(|k| if i == k { alpha[0] } else { 0.0 } - jac[i][k]).collect()).collect())?;
331        let mut y_new = y_pred.clone();
332        let mut f_new = f_pred;
333        let mut converged = false;
334        for _ in 0..8 {
335            let residual: Vec<f64> = (0..n).map(|i| alpha[0] * y_new[i] + past[i] - f_new[i]).collect();
336            let delta = lu.solve(&residual);
337            y_new.iter_mut().zip(&delta).for_each(|(v, d)| *v -= d);
338            f_new = sys.eval(t_new, &y_new)?;
339            if !y_new.iter().all(|v| v.is_finite()) {
340                break;
341            }
342            if weighted_max(&delta, &y, &y_new, &options) < 1e-3 {
343                converged = true;
344                break;
345            }
346        }
347        if !converged {
348            solution.rejected_steps += 1;
349            h *= 0.25;
350            if h < 1e-14 * t.abs().max(1.0) {
351                return Err(ErrorsJSL::RuntimeError("Newton iteration failed at the minimum step size."));
352            }
353            continue;
354        }
355        // ANCHOR_END: bdf_corrector
356        let scale = if history.len() >= 2 { 1.0 / (order as f64 + 2.0) } else { 0.5 };
357        let err: Vec<f64> = (0..n).map(|i| scale * (y_new[i] - y_pred[i])).collect();
358        let error = weighted_max(&err, &y, &y_new, &options);
359        let growth_limit = if order <= 2 { 2.0 } else { 1.3 };
360        let factor = (0.9 * error.max(1e-10).powf(-1.0 / (order as f64 + 1.0))).clamp(0.2, growth_limit);
361        if error <= 1.0 {
362            history.push_back((t_new, y_new.clone()));
363            if history.len() > max_order + 1 {
364                history.pop_front();
365            }
366            f_last = f_new;
367            solution.t.push(t_new);
368            solution.y.push(y_new);
369        } else {
370            solution.rejected_steps += 1;
371        }
372        h *= factor;
373        if h < 1e-14 * t.abs().max(1.0) {
374            return Err(ErrorsJSL::RuntimeError("The step size underflowed."));
375        }
376    }
377    solution.nfev = sys.evaluations;
378    solution.jacobian_evaluations = sys.jacobians;
379    Ok(solution)
380}
381
382#[cfg(test)]
383mod tests {
384    use super::*;
385
386    type NoJacobian = fn(f64, &[f64]) -> Vec<Vec<f64>>;
387
388    fn robertson(_: f64, y: &[f64]) -> Vec<f64> {
389        vec![
390            -0.04 * y[0] + 1e4 * y[1] * y[2],
391            0.04 * y[0] - 1e4 * y[1] * y[2] - 3e7 * y[1] * y[1],
392            3e7 * y[1] * y[1],
393        ]
394    }
395
396    fn robertson_jacobian(_: f64, y: &[f64]) -> Vec<Vec<f64>> {
397        vec![
398            vec![-0.04, 1e4 * y[2], 1e4 * y[1]],
399            vec![0.04, -1e4 * y[2] - 6e7 * y[1], -1e4 * y[1]],
400            vec![0.0, 6e7 * y[1], 0.0],
401        ]
402    }
403
404    /// Robertson's chemical kinetics at t = 40 (Hairer and Wanner's reference solution).
405    const ROBERTSON_40: [f64; 3] = [0.715_827_068_7, 9.185_534_765e-6, 0.284_163_746_6];
406
407    #[test]
408    fn both_solvers_handle_the_robertson_problem() {
409        let options = OdeOptions { relative_tolerance: 1e-6, absolute_tolerance: 1e-10, ..Default::default() };
410        let y0 = [1.0, 0.0, 0.0];
411        let ros = rosenbrock23(robertson, Some(robertson_jacobian), 0.0, &y0, 40.0, options).unwrap();
412        let bdf5 = bdf(robertson, None::<NoJacobian>, 0.0, &y0, 40.0, 5, options).unwrap();
413        for (name, sol) in [("rosenbrock", &ros), ("bdf", &bdf5)] {
414            let y = sol.last();
415            for i in 0..3 {
416                assert!((y[i] - ROBERTSON_40[i]).abs() < 1e-4 * ROBERTSON_40[i], "{name} component {i}: {y:?}");
417            }
418            // Mass is conserved by the exact flow; both methods preserve linear invariants.
419            assert!((y.iter().sum::<f64>() - 1.0).abs() < 1e-10, "{name}");
420            assert!(sol.t.len() < 2000, "{name} took {} steps", sol.t.len());
421        }
422    }
423
424    #[test]
425    fn stiff_linear_problem_follows_the_slow_manifold_cheaply() {
426        // y' = −1000 (y − cos t) − sin t has solution cos t; explicit methods need h < 2e-3.
427        let f = |t: f64, y: &[f64]| vec![-1000.0 * (y[0] - t.cos()) - t.sin()];
428        let options = OdeOptions { relative_tolerance: 1e-7, absolute_tolerance: 1e-9, ..Default::default() };
429        for order in [1, 2, 3, 5] {
430            let sol = bdf(f, None::<NoJacobian>, 0.0, &[1.0], 10.0, order, options).unwrap();
431            let worst = sol.t.iter().zip(&sol.y).map(|(t, y)| (y[0] - t.cos()).abs()).fold(0.0, f64::max);
432            assert!(worst < 2e-5, "order {order}: {worst}");
433            if order >= 3 {
434                assert!(sol.t.len() < 1500, "order {order}: {} steps", sol.t.len());
435            }
436        }
437        // The second-order Rosenbrock pair suits looser tolerances.
438        let loose = OdeOptions { relative_tolerance: 1e-4, absolute_tolerance: 1e-6, ..Default::default() };
439        let sol = rosenbrock23(f, None::<NoJacobian>, 0.0, &[1.0], 10.0, loose).unwrap();
440        let worst = sol.t.iter().zip(&sol.y).map(|(t, y)| (y[0] - t.cos()).abs()).fold(0.0, f64::max);
441        assert!(worst < 1e-4 && sol.t.len() < 1000, "{worst} in {} steps", sol.t.len());
442    }
443
444    #[test]
445    fn higher_orders_need_fewer_steps_and_backward_integration_works() {
446        let f = |_: f64, y: &[f64]| vec![y[1], -y[0]];
447        let options = OdeOptions { relative_tolerance: 1e-9, absolute_tolerance: 1e-12, ..Default::default() };
448        let low = bdf(f, None::<NoJacobian>, 0.0, &[0.0, 1.0], 2.0, 1, options).unwrap();
449        let high = bdf(f, None::<NoJacobian>, 0.0, &[0.0, 1.0], 2.0, 5, options).unwrap();
450        assert!(high.t.len() * 10 < low.t.len(), "{} vs {}", high.t.len(), low.t.len());
451        assert!((high.last()[0] - 2f64.sin()).abs() < 1e-7);
452        // Backwards in time: y' = y from y(1) = e to t = 0.
453        let back = rosenbrock23(|_, y: &[f64]| vec![y[0]], None::<NoJacobian>, 1.0, &[std::f64::consts::E], 0.0, OdeOptions::default()).unwrap();
454        assert!((back.last()[0] - 1.0).abs() < 1e-4 && *back.t.last().unwrap() == 0.0);
455        assert!(bdf(f, None::<NoJacobian>, 0.0, &[0.0, 1.0], 1.0, 6, options).is_err());
456        assert!(rosenbrock23(f, None::<NoJacobian>, 0.0, &[], 1.0, options).is_err());
457    }
458}