Skip to main content

lib_jsl_integration/
dormand_prince.rs

1//! Adaptive Dormand-Prince 5(4) integration of ordinary differential equations.
2//!
3//! See the book entry [Runge-Kutta methods](https://jwkunz.github.io/lib_jsl/book/integration/runge-kutta.html).
4
5use crate::stiff_ode::{OdeOptions, OdeSolution, starting_step, validate, weighted_max};
6use lib_jsl_core::ErrorsJSL;
7
8// ANCHOR: tableau
9/// The nodes `c`, coefficients `a` and fifth-order weights (last row of `a`) of the
10/// Dormand-Prince 5(4) pair. The seventh stage is evaluated at the new solution, so it is the
11/// first stage of the next step ("first same as last").
12const C: [f64; 7] = [0.0, 0.2, 0.3, 0.8, 8.0 / 9.0, 1.0, 1.0];
13const A: [[f64; 6]; 7] = [
14    [0.0; 6],
15    [0.2, 0.0, 0.0, 0.0, 0.0, 0.0],
16    [3.0 / 40.0, 9.0 / 40.0, 0.0, 0.0, 0.0, 0.0],
17    [44.0 / 45.0, -56.0 / 15.0, 32.0 / 9.0, 0.0, 0.0, 0.0],
18    [19372.0 / 6561.0, -25360.0 / 2187.0, 64448.0 / 6561.0, -212.0 / 729.0, 0.0, 0.0],
19    [9017.0 / 3168.0, -355.0 / 33.0, 46732.0 / 5247.0, 49.0 / 176.0, -5103.0 / 18656.0, 0.0],
20    [35.0 / 384.0, 0.0, 500.0 / 1113.0, 125.0 / 192.0, -2187.0 / 6784.0, 11.0 / 84.0],
21];
22/// Fifth-order weights minus the embedded fourth-order weights: `h Σ eⱼ kⱼ` estimates the
23/// local error.
24const E: [f64; 7] = [
25    35.0 / 384.0 - 5179.0 / 57600.0,
26    0.0,
27    500.0 / 1113.0 - 7571.0 / 16695.0,
28    125.0 / 192.0 - 393.0 / 640.0,
29    -2187.0 / 6784.0 + 92097.0 / 339200.0,
30    11.0 / 84.0 - 187.0 / 2100.0,
31    -1.0 / 40.0,
32];
33// ANCHOR_END: tableau
34
35/// Solves `y' = f(t, y)` from `(t0, y0)` to `t1` (which may be less than `t0`) with the
36/// adaptive Dormand-Prince 5(4) method, the method of MATLAB's `ode45` and SciPy's `RK45`.
37///
38/// Each step costs six new evaluations of `f` (the seventh is reused by the next step). The
39/// embedded fourth-order solution estimates the local error, and steps are accepted when every
40/// component's error is below `absolute_tolerance + relative_tolerance · |yᵢ|`; the step size
41/// then grows or shrinks by `0.9 · error^(−1/5)`, between a fifth and five times. Returns every
42/// accepted step. For stiff problems, where this method is forced into tiny steps, use
43/// [`rosenbrock23`](crate::stiff_ode::rosenbrock23) or [`bdf`](crate::stiff_ode::bdf).
44pub fn dormand_prince_solve<F>(f: F, t0: f64, y0: &[f64], t1: f64, options: OdeOptions) -> Result<OdeSolution, ErrorsJSL>
45where
46    F: Fn(f64, &[f64]) -> Vec<f64>,
47{
48    validate(y0, t0, t1, &options)?;
49    let n = y0.len();
50    let eval = |t: f64, y: &[f64]| -> Result<Vec<f64>, ErrorsJSL> {
51        let v = f(t, y);
52        if v.len() != n {
53            return Err(ErrorsJSL::IncompatibleArraySizes((v.len(), n)));
54        }
55        Ok(v)
56    };
57    let span = t1 - t0;
58    let direction = span.signum();
59    let (mut t, mut y) = (t0, y0.to_vec());
60    let mut solution = OdeSolution { t: vec![t], y: vec![y.clone()], rejected_steps: 0, nfev: 1, jacobian_evaluations: 0 };
61    let mut k = vec![eval(t, &y)?];
62    let mut h = starting_step(&y, &k[0], span, &options);
63    for _ in 0..options.max_steps {
64        if span == 0.0 || (t1 - t) * direction <= 0.0 {
65            return Ok(solution);
66        }
67        // ANCHOR: dopri_step
68        h = h.min((t1 - t).abs());
69        let hs = h * direction;
70        k.truncate(1);
71        for s in 1..7 {
72            let stage: Vec<f64> = (0..n).map(|i| y[i] + hs * (0..s).map(|j| A[s][j] * k[j][i]).sum::<f64>()).collect();
73            let t_stage = t + C[s] * hs;
74            k.push(eval(t_stage, &stage)?);
75        }
76        solution.nfev += 6;
77        // Stage 7 was evaluated at the fifth-order solution itself.
78        let y_new: Vec<f64> = (0..n).map(|i| y[i] + hs * (0..6).map(|j| A[6][j] * k[j][i]).sum::<f64>()).collect();
79        let local: Vec<f64> = (0..n).map(|i| hs * (0..7).map(|j| E[j] * k[j][i]).sum::<f64>()).collect();
80        let error = weighted_max(&local, &y, &y_new, &options);
81        if error <= 1.0 && y_new.iter().all(|v| v.is_finite()) {
82            t = if (t1 - t).abs() <= h { t1 } else { t + hs };
83            y = y_new;
84            let last = k.pop().expect("seven stages");
85            k = vec![last];
86            solution.t.push(t);
87            solution.y.push(y.clone());
88        } else {
89            solution.rejected_steps += 1;
90        }
91        let factor = if error.is_finite() { 0.9 * error.max(1e-10).powf(-0.2) } else { 0.1 };
92        h *= factor.clamp(0.2, 5.0);
93        // ANCHOR_END: dopri_step
94        if h < 1e-14 * span.abs().max(t.abs()) {
95            return Err(ErrorsJSL::RuntimeError("Dormand-Prince: the step size underflowed (the problem may be stiff or singular)."));
96        }
97    }
98    Err(ErrorsJSL::RuntimeError("Dormand-Prince: too many steps (the problem may be stiff)."))
99}
100
101#[cfg(test)]
102mod test {
103    use super::*;
104    use std::f64::consts::PI;
105
106
107    #[test]
108    fn solves_systems_to_the_requested_accuracy() {
109        // The harmonic oscillator over five periods.
110        let oscillator = |_t: f64, y: &[f64]| vec![y[1], -y[0]];
111        for tol in [1e-6, 1e-9, 1e-12] {
112            let options = OdeOptions { relative_tolerance: tol, absolute_tolerance: tol, ..Default::default() };
113            let s = dormand_prince_solve(oscillator, 0.0, &[1.0, 0.0], 10.0 * PI, options).unwrap();
114            let y = s.y.last().unwrap();
115            let error = ((y[0] - 1.0).powi(2) + y[1].powi(2)).sqrt();
116            assert!(error < 1000.0 * tol, "tol {tol}: error {error}");
117            assert_eq!(*s.t.last().unwrap(), 10.0 * PI);
118        }
119        // Backwards in time, and y' = y: e^{-1} at t = −1.
120        let s = dormand_prince_solve(|_, y| vec![y[0]], 0.0, &[1.0], -1.0, OdeOptions { relative_tolerance: 1e-10, absolute_tolerance: 1e-12, ..Default::default() }).unwrap();
121        assert!((s.y.last().unwrap()[0] - (-1f64).exp()).abs() < 1e-9);
122        // First same as last: six evaluations per attempted step, plus the first.
123        assert_eq!(s.nfev, 1 + 6 * (s.t.len() - 1 + s.rejected_steps));
124    }
125
126    #[test]
127    fn reports_failures() {
128        assert!(dormand_prince_solve(|_, y| vec![y[0]], 0.0, &[], 1.0, OdeOptions::default()).is_err());
129        // y' = y² from y(0) = 1 blows up at t = 1.
130        assert!(dormand_prince_solve(|_, y| vec![y[0] * y[0]], 0.0, &[1.0], 2.0, OdeOptions::default()).is_err());
131    }
132}