Skip to main content

lib_jsl_integration/
ivp.rs

1//! Initial value problems `y' = f(t, y)` with dense output and event location, following
2//! `scipy.integrate.solve_ivp`:
3//!
4//! * [`IvpMethod::Radau`]: the implicit Runge-Kutta method Radau IIA of order 5 (Hairer and
5//!   Wanner), L-stable, with a cubic collocation polynomial as dense output. A step-for-step port
6//!   of SciPy's `Radau`.
7//! * [`IvpMethod::Lsoda`]: variable-order, variable-step multistep methods in Nordsieck form that
8//!   switch automatically between Adams-Moulton (orders 1 to 12, functional iteration) for
9//!   non-stiff stretches and BDF (orders 1 to 5, Newton iteration) for stiff ones, after Petzold's
10//!   LSODA. The method coefficients are those of Hindmarsh's ODEPACK.
11//!
12//! Every accepted step contributes a polynomial piece to a [`DenseOutput`], so the solution can be
13//! evaluated anywhere, and [`Event`] functions `g(t, y)` are located to machine precision on it by
14//! Brent's method.
15//!
16//! See the book entry [Radau, LSODA and event location](https://jwkunz.github.io/lib_jsl/book/integration/radau-lsoda.html).
17
18// Guards such as `!(x > 0.0)` are deliberate: unlike `x <= 0.0` they also reject NaN.
19#![allow(clippy::neg_cmp_op_on_partial_ord)]
20// The coefficient recurrences read most clearly with explicit indices.
21#![allow(clippy::needless_range_loop)]
22
23use lib_jsl_core::ErrorsJSL;
24use lib_jsl_linalg::Factorize;
25use lib_jsl_linalg::LuFactorization;
26use lib_jsl_linalg::sparse::{CooMatrix, CsrMatrix, SparseLu, minimum_degree};
27use ndarray::{Array1, Array2};
28use num_complex::Complex;
29
30type C = Complex<f64>;
31
32/// The method of [`solve_ivp`].
33#[derive(Clone, Copy, Debug, PartialEq, Eq)]
34pub enum IvpMethod {
35    /// Radau IIA, order 5 (SciPy's `Radau`).
36    Radau,
37    /// Adams/BDF with automatic stiffness switching (as SciPy's `LSODA`).
38    Lsoda,
39}
40
41/// Tolerances and limits for [`solve_ivp`]. Each step keeps the local error of every component
42/// below `atol + rtol · |yᵢ|`, measured in the root-mean-square norm as in SciPy.
43#[derive(Clone, Copy, Debug)]
44pub struct IvpOptions {
45    pub rtol: f64,
46    pub atol: f64,
47    /// The first step; chosen automatically when `None`.
48    pub first_step: Option<f64>,
49    /// The largest step.
50    pub max_step: f64,
51    /// The largest number of step attempts.
52    pub max_steps: usize,
53}
54
55impl Default for IvpOptions {
56    /// SciPy's defaults: `rtol = 1e-3`, `atol = 1e-6`.
57    fn default() -> Self {
58        IvpOptions { rtol: 1e-3, atol: 1e-6, first_step: None, max_step: f64::INFINITY, max_steps: 1_000_000 }
59    }
60}
61
62/// The boxed function of an [`Event`].
63pub type EventFunction<'a> = Box<dyn Fn(f64, &[f64]) -> f64 + 'a>;
64
65/// An event function `g(t, y)` whose zeros are located during the integration.
66pub struct Event<'a> {
67    pub function: EventFunction<'a>,
68    /// `+1`: only zeros where `g` increases; `-1`: only where it decreases; `0`: both.
69    pub direction: f64,
70    /// Stop the integration after this many occurrences (SciPy's `terminal`); `None` never stops.
71    pub terminal: Option<usize>,
72}
73
74impl<'a> Event<'a> {
75    /// A non-terminal event in either direction.
76    pub fn new(function: impl Fn(f64, &[f64]) -> f64 + 'a) -> Self {
77        Event { function: Box::new(function), direction: 0.0, terminal: None }
78    }
79}
80
81/// One polynomial piece of the dense output: `y(t) = y_ref + Σₖ cₖ sᵏ⁺¹` with
82/// `s = (t − t_ref) / h`, valid on `[t_start, t_end]`.
83#[derive(Clone, Debug)]
84pub struct Segment {
85    pub t_start: f64,
86    pub t_end: f64,
87    t_ref: f64,
88    h: f64,
89    y_ref: Vec<f64>,
90    coeffs: Vec<Vec<f64>>,
91}
92
93impl Segment {
94    /// The interpolant at `t` (extrapolated outside the segment).
95    pub fn evaluate(&self, t: f64) -> Vec<f64> {
96        let s = (t - self.t_ref) / self.h;
97        let mut y = self.y_ref.clone();
98        let mut p = 1.0;
99        for c in &self.coeffs {
100            p *= s;
101            for (yi, ci) in y.iter_mut().zip(c) {
102                *yi += ci * p;
103            }
104        }
105        y
106    }
107}
108
109/// The continuous solution: one polynomial piece per accepted step.
110#[derive(Clone, Debug, Default)]
111pub struct DenseOutput {
112    pub segments: Vec<Segment>,
113}
114
115impl DenseOutput {
116    /// The solution at `t`, from the piece that contains it (the first or last piece outside the
117    /// integration interval).
118    pub fn evaluate(&self, t: f64) -> Vec<f64> {
119        let i = self.segments.partition_point(|s| s.t_end < t).min(self.segments.len().saturating_sub(1));
120        self.segments[i].evaluate(t)
121    }
122}
123
124/// Why the integration stopped.
125#[derive(Clone, Copy, Debug, PartialEq, Eq)]
126pub enum IvpStatus {
127    /// The end of the interval was reached.
128    Finished,
129    /// A terminal event occurred.
130    TerminatedByEvent,
131}
132
133/// The result of [`solve_ivp`].
134#[derive(Clone, Debug)]
135pub struct IvpSolution {
136    /// The times of the accepted steps (and of a terminal event).
137    pub t: Vec<f64>,
138    pub y: Vec<Vec<f64>>,
139    pub status: IvpStatus,
140    /// For each event function, the times at which it occurred and the states there.
141    pub t_events: Vec<Vec<f64>>,
142    pub y_events: Vec<Vec<Vec<f64>>>,
143    pub dense: DenseOutput,
144    pub nfev: usize,
145    pub njev: usize,
146    pub nlu: usize,
147    pub rejected_steps: usize,
148    /// For LSODA, the times at which the method switched and whether it switched to BDF (`true`)
149    /// or back to Adams (`false`).
150    pub switches: Vec<(f64, bool)>,
151}
152
153/// The RMS norm of `v / scale` (SciPy's `norm`).
154fn rms(v: &[f64], scale: &[f64]) -> f64 {
155    (v.iter().zip(scale).map(|(a, s)| (a / s) * (a / s)).sum::<f64>() / v.len() as f64).sqrt()
156}
157
158/// Counts evaluations of `f` and its Jacobian.
159/// A boxed function returning a sparse Jacobian.
160pub type SparseJacobianFn<'a> = Box<dyn Fn(f64, &[f64]) -> CsrMatrix + 'a>;
161
162/// A dense Jacobian function (the unused type of [`solve_ivp_sparse`]'s dense slot).
163type DenseJacFn = fn(f64, &[f64]) -> Vec<Vec<f64>>;
164
165/// A sparse Jacobian for [`solve_ivp_sparse`]: a function returning `∂f/∂y` as a sparse
166/// matrix, or the sparsity pattern of `∂f/∂y` for grouped finite differences (SciPy's
167/// `jac_sparsity`).
168pub enum SparseJacobian<'a> {
169    Analytic(SparseJacobianFn<'a>),
170    /// The pattern: the stored entries mark where `∂fᵢ/∂yⱼ` may be non-zero (values ignored).
171    Pattern(CsrMatrix),
172}
173
174/// A Jacobian, dense rows or sparse.
175enum JacMatrix {
176    Dense(Vec<Vec<f64>>),
177    Sparse(CsrMatrix),
178}
179
180enum RealLu {
181    Dense(LuFactorization<f64>),
182    Sparse(SparseLu),
183}
184
185impl RealLu {
186    fn solve(&self, b: &Array1<f64>) -> Result<Array1<f64>, ErrorsJSL> {
187        match self {
188            RealLu::Dense(lu) => lu.solve(b).map_err(|_| ErrorsJSL::RuntimeError("linear solve failed")),
189            RealLu::Sparse(lu) => lu.solve(b.as_slice().expect("contiguous")).map(Array1::from).map_err(|_| ErrorsJSL::RuntimeError("linear solve failed")),
190        }
191    }
192}
193
194/// A complex system `(α + iβ) I − J`; sparse ones are solved as the real system
195/// `[[αI − J, −βI], [βI, αI − J]]` of twice the size.
196enum ComplexLu {
197    Dense(LuFactorization<C>),
198    Sparse(SparseLu),
199}
200
201impl ComplexLu {
202    fn solve(&self, b: &Array1<C>) -> Result<Array1<C>, ErrorsJSL> {
203        match self {
204            ComplexLu::Dense(lu) => lu.solve(b).map_err(|_| ErrorsJSL::RuntimeError("linear solve failed")),
205            ComplexLu::Sparse(lu) => {
206                let n = b.len();
207                let rhs: Vec<f64> = b.iter().map(|z| z.re).chain(b.iter().map(|z| z.im)).collect();
208                let x = lu.solve(&rhs).map_err(|_| ErrorsJSL::RuntimeError("linear solve failed"))?;
209                Ok((0..n).map(|i| C::new(x[i], x[n + i])).collect())
210            }
211        }
212    }
213}
214
215/// Minimum-degree orders by pattern: the key is (order, nonzeros, hash of the pattern).
216type OrderCache = std::cell::RefCell<std::collections::HashMap<(usize, usize, u64), std::rc::Rc<Vec<usize>>>>;
217
218thread_local! {
219    /// Minimum-degree orders by sparsity pattern: the symbolic part of the sparse LU, which the
220    /// Newton matrices of one solve share (their pattern is the Jacobian's plus the diagonal).
221    static ORDERS: OrderCache = std::cell::RefCell::new(std::collections::HashMap::new());
222}
223
224type FactorCache = std::cell::RefCell<std::collections::HashMap<(usize, usize, u64), SparseLu>>;
225
226thread_local! {
227    /// The latest sparse LU factors by sparsity pattern, for refactoring with new values.
228    static FACTORS: FactorCache = std::cell::RefCell::new(std::collections::HashMap::new());
229}
230
231fn pattern_key(m: &CsrMatrix) -> (usize, usize, u64) {
232    use std::hash::{Hash, Hasher};
233    let mut h = std::collections::hash_map::DefaultHasher::new();
234    m.indptr.hash(&mut h);
235    m.indices.hash(&mut h);
236    (m.nrows, m.indices.len(), h.finish())
237}
238
239/// The sparse LU of a Newton matrix: numerical refactoring (the pivot sequence and the structure
240/// of the factors kept) when an earlier matrix of the same pattern was factored and its pivots
241/// still suit, and a full factorisation otherwise.
242fn sparse_factor(m: &CsrMatrix) -> Result<SparseLu, lib_jsl_linalg::LinalgError> {
243    let key = pattern_key(m);
244    let reused = FACTORS.with(|c| c.borrow().get(&key).and_then(|base| base.refactor(m).ok()));
245    let lu = match reused {
246        Some(lu) => lu,
247        None => SparseLu::factor_with_order(m, &cached_order(m))?,
248    };
249    FACTORS.with(|c| {
250        let mut c = c.borrow_mut();
251        if c.len() >= 16 {
252            c.clear();
253        }
254        c.insert(key, lu.clone());
255    });
256    Ok(lu)
257}
258
259/// The minimum-degree column order of `m`, computed once per sparsity pattern.
260fn cached_order(m: &CsrMatrix) -> std::rc::Rc<Vec<usize>> {
261    use std::hash::{Hash, Hasher};
262    let mut h = std::collections::hash_map::DefaultHasher::new();
263    m.indptr.hash(&mut h);
264    m.indices.hash(&mut h);
265    let key = (m.nrows, m.indices.len(), h.finish());
266    ORDERS.with(|c| {
267        let mut c = c.borrow_mut();
268        if let Some(q) = c.get(&key) {
269            return q.clone();
270        }
271        if c.len() >= 16 {
272            c.clear();
273        }
274        let q = std::rc::Rc::new(minimum_degree(m));
275        c.insert(key, q.clone());
276        q
277    })
278}
279
280impl JacMatrix {
281    /// The LU factors of `a I − s J`.
282    fn factor_real(&self, a: f64, s: f64) -> Result<RealLu, ErrorsJSL> {
283        let fail = |_| ErrorsJSL::RuntimeError("singular Newton matrix");
284        match self {
285            JacMatrix::Dense(j) => {
286                let n = j.len();
287                let m = Array2::from_shape_fn((n, n), |(r, c)| if r == c { a } else { 0.0 } - s * j[r][c]);
288                m.factorize().map(RealLu::Dense).map_err(fail)
289            }
290            JacMatrix::Sparse(j) => {
291                let n = j.nrows;
292                let mut coo = CooMatrix::new(n, n);
293                for r in 0..n {
294                    coo.push(r, r, a);
295                    for p in j.indptr[r]..j.indptr[r + 1] {
296                        coo.push(r, j.indices[p], -s * j.data[p]);
297                    }
298                }
299                let m = coo.to_csr().map_err(fail)?;
300                sparse_factor(&m).map(RealLu::Sparse).map_err(fail)
301            }
302        }
303    }
304
305    /// The LU factors of `a I − J` for complex `a`.
306    fn factor_complex(&self, a: C) -> Result<ComplexLu, ErrorsJSL> {
307        let fail = |_| ErrorsJSL::RuntimeError("singular Newton matrix");
308        match self {
309            JacMatrix::Dense(j) => {
310                let n = j.len();
311                let m = Array2::from_shape_fn((n, n), |(r, c)| if r == c { a } else { C::new(0.0, 0.0) } - j[r][c]);
312                m.factorize().map(ComplexLu::Dense).map_err(fail)
313            }
314            JacMatrix::Sparse(j) => {
315                let n = j.nrows;
316                let mut coo = CooMatrix::new(2 * n, 2 * n);
317                for r in 0..n {
318                    coo.push(r, r, a.re);
319                    coo.push(n + r, n + r, a.re);
320                    coo.push(r, n + r, -a.im);
321                    coo.push(n + r, r, a.im);
322                    for p in j.indptr[r]..j.indptr[r + 1] {
323                        coo.push(r, j.indices[p], -j.data[p]);
324                        coo.push(n + r, n + j.indices[p], -j.data[p]);
325                    }
326                }
327                let m = coo.to_csr().map_err(fail)?;
328                sparse_factor(&m).map(ComplexLu::Sparse).map_err(fail)
329            }
330        }
331    }
332
333    /// `maxᵢ Σⱼ |Jᵢⱼ| wⱼ / wᵢ`.
334    fn weighted_norm(&self, w: &[f64]) -> f64 {
335        match self {
336            JacMatrix::Dense(j) => j.iter().enumerate().map(|(i, row)| row.iter().zip(w).map(|(a, e)| a.abs() * e).sum::<f64>() / w[i]).fold(0.0, f64::max),
337            JacMatrix::Sparse(j) => (0..j.nrows).map(|i| (j.indptr[i]..j.indptr[i + 1]).map(|p| j.data[p].abs() * w[j.indices[p]]).sum::<f64>() / w[i]).fold(0.0, f64::max),
338        }
339    }
340}
341
342/// Groups of columns with no row in common (greedy, as Curtis, Powell and Reid), so that one
343/// evaluation of `f` gives a finite difference for every column of a group.
344fn column_groups(pattern: &CsrMatrix) -> Vec<Vec<usize>> {
345    let n = pattern.ncols;
346    let mut rows_of: Vec<Vec<usize>> = vec![Vec::new(); n];
347    for r in 0..pattern.nrows {
348        for p in pattern.indptr[r]..pattern.indptr[r + 1] {
349            rows_of[pattern.indices[p]].push(r);
350        }
351    }
352    let mut groups: Vec<(Vec<usize>, Vec<bool>)> = Vec::new();
353    for c in 0..n {
354        match groups.iter_mut().find(|(_, used)| rows_of[c].iter().all(|&r| !used[r])) {
355            Some((g, used)) => {
356                g.push(c);
357                rows_of[c].iter().for_each(|&r| used[r] = true);
358            }
359            None => {
360                let mut used = vec![false; pattern.nrows];
361                rows_of[c].iter().for_each(|&r| used[r] = true);
362                groups.push((vec![c], used));
363            }
364        }
365    }
366    groups.into_iter().map(|(g, _)| g).collect()
367}
368
369struct Counter<'a, F, J> {
370    f: &'a F,
371    jac: Option<&'a J>,
372    sparse: Option<&'a SparseJacobian<'a>>,
373    nfev: usize,
374    njev: usize,
375    nlu: usize,
376}
377
378impl<F, J> Counter<'_, F, J>
379where
380    F: Fn(f64, &[f64]) -> Vec<f64>,
381    J: Fn(f64, &[f64]) -> Vec<Vec<f64>>,
382{
383    fn f(&mut self, t: f64, y: &[f64]) -> Vec<f64> {
384        self.nfev += 1;
385        (self.f)(t, y)
386    }
387
388    /// The Jacobian, analytic or by forward differences.
389    fn jacobian(&mut self, t: f64, y: &[f64], fy: &[f64]) -> JacMatrix {
390        self.njev += 1;
391        match self.sparse {
392            Some(SparseJacobian::Analytic(j)) => return JacMatrix::Sparse(j(t, y)),
393            Some(SparseJacobian::Pattern(pattern)) => {
394                let mut data = vec![0.0; pattern.data.len()];
395                let mut z = y.to_vec();
396                for group in column_groups(pattern) {
397                    let hs: Vec<f64> = group.iter().map(|&c| f64::EPSILON.sqrt() * y[c].abs().max(1e-5)).collect();
398                    for (&c, h) in group.iter().zip(&hs) {
399                        z[c] = y[c] + h;
400                    }
401                    let fz = self.f(t, &z);
402                    let mut h_of = vec![0.0; y.len()];
403                    for (&c, h) in group.iter().zip(&hs) {
404                        z[c] = y[c];
405                        h_of[c] = *h;
406                    }
407                    for r in 0..pattern.nrows {
408                        for p in pattern.indptr[r]..pattern.indptr[r + 1] {
409                            let c = pattern.indices[p];
410                            if h_of[c] != 0.0 {
411                                data[p] = (fz[r] - fy[r]) / h_of[c];
412                            }
413                        }
414                    }
415                }
416                return JacMatrix::Sparse(CsrMatrix { nrows: pattern.nrows, ncols: pattern.ncols, indptr: pattern.indptr.clone(), indices: pattern.indices.clone(), data });
417            }
418            None => {}
419        }
420        if let Some(j) = self.jac {
421            return JacMatrix::Dense(j(t, y));
422        }
423        let n = y.len();
424        let mut jac = vec![vec![0.0; n]; n];
425        let mut z = y.to_vec();
426        for k in 0..n {
427            let h = f64::EPSILON.sqrt() * y[k].abs().max(1e-5);
428            z[k] = y[k] + h;
429            let fz = self.f(t, &z);
430            z[k] = y[k];
431            for i in 0..n {
432                jac[i][k] = (fz[i] - fy[i]) / h;
433            }
434        }
435        JacMatrix::Dense(jac)
436    }
437}
438
439/// SciPy's `select_initial_step` for a method of the given order.
440#[allow(clippy::too_many_arguments)]
441fn select_initial_step<F, J>(sys: &mut Counter<F, J>, t0: f64, y0: &[f64], f0: &[f64], span: f64, max_step: f64, order: f64, o: &IvpOptions) -> f64
442where
443    F: Fn(f64, &[f64]) -> Vec<f64>,
444    J: Fn(f64, &[f64]) -> Vec<Vec<f64>>,
445{
446    let scale: Vec<f64> = y0.iter().map(|v| o.atol + v.abs() * o.rtol).collect();
447    let d0 = rms(y0, &scale);
448    let d1 = rms(f0, &scale);
449    let h0 = if d0 < 1e-5 || d1 < 1e-5 { 1e-6 } else { 0.01 * d0 / d1 };
450    let h0 = h0.min(span);
451    let y1: Vec<f64> = y0.iter().zip(f0).map(|(y, f)| y + h0 * f).collect();
452    let f1 = sys.f(t0 + h0, &y1);
453    let diff: Vec<f64> = f1.iter().zip(f0).map(|(a, b)| a - b).collect();
454    let d2 = rms(&diff, &scale) / h0;
455    let h1 = if d1 <= 1e-15 && d2 <= 1e-15 { (h0 * 1e-3).max(1e-6) } else { (0.01 / d1.max(d2)).powf(1.0 / (order + 1.0)) };
456    (100.0 * h0).min(h1).min(span).min(max_step)
457}
458
459/// Brent's method on `[a, b]` with SciPy's `brentq` tolerances `xtol = rtol = 4ε`.
460fn brentq(f: impl Fn(f64) -> f64, a: f64, b: f64) -> f64 {
461    let (xtol, rtol) = (4.0 * f64::EPSILON, 4.0 * f64::EPSILON);
462    let (mut xpre, mut xcur) = (a, b);
463    let (mut xblk, mut fblk, mut spre, mut scur) = (0.0, 0.0, 0.0, 0.0);
464    let mut fpre = f(xpre);
465    let mut fcur = f(xcur);
466    if fpre == 0.0 {
467        return xpre;
468    }
469    if fcur == 0.0 {
470        return xcur;
471    }
472    for _ in 0..100 {
473        if fpre != 0.0 && fcur != 0.0 && (fpre < 0.0) != (fcur < 0.0) {
474            xblk = xpre;
475            fblk = fpre;
476            spre = xcur - xpre;
477            scur = spre;
478        }
479        if fblk.abs() < fcur.abs() {
480            xpre = xcur;
481            xcur = xblk;
482            xblk = xpre;
483            fpre = fcur;
484            fcur = fblk;
485            fblk = fpre;
486        }
487        let delta = (xtol + rtol * xcur.abs()) / 2.0;
488        let sbis = (xblk - xcur) / 2.0;
489        if fcur == 0.0 || sbis.abs() < delta {
490            return xcur;
491        }
492        if spre.abs() > delta && fcur.abs() < fpre.abs() {
493            let stry = if xpre == xblk {
494                -fcur * (xcur - xpre) / (fcur - fpre)
495            } else {
496                let dpre = (fpre - fcur) / (xpre - xcur);
497                let dblk = (fblk - fcur) / (xblk - xcur);
498                -fcur * (fblk * dblk - fpre * dpre) / (dblk * dpre * (fblk - fpre))
499            };
500            if 2.0 * stry.abs() < spre.abs().min(3.0 * sbis.abs() - delta) {
501                spre = scur;
502                scur = stry;
503            } else {
504                spre = sbis;
505                scur = sbis;
506            }
507        } else {
508            spre = sbis;
509            scur = sbis;
510        }
511        xpre = xcur;
512        fpre = fcur;
513        xcur += if scur.abs() > delta { scur } else if sbis > 0.0 { delta } else { -delta };
514        fcur = f(xcur);
515    }
516    xcur
517}
518
519/// A method that advances one accepted step at a time.
520trait Stepper {
521    fn t(&self) -> f64;
522    fn y(&self) -> &[f64];
523    /// Takes one accepted step and returns its dense-output piece.
524    fn step(&mut self) -> Result<Segment, ErrorsJSL>;
525    fn counts(&self) -> (usize, usize, usize, usize);
526    fn switches(&self) -> Vec<(f64, bool)> {
527        Vec::new()
528    }
529}
530
531// ------------------------------------------------------------------------------------- Radau
532
533const NEWTON_MAXITER: usize = 6;
534
535/// The result of the collocation solve: converged, iterations, stage increments, rate.
536type Collocation = (bool, usize, [Vec<f64>; 3], Option<f64>);
537
538struct RadauConstants {
539    c: [f64; 3],
540    e: [f64; 3],
541    mu_real: f64,
542    mu_complex: C,
543    t: [[f64; 3]; 3],
544    ti: [[f64; 3]; 3],
545    p: [[f64; 3]; 3],
546}
547
548// The digits are SciPy's, kept so that the two implementations take the same steps.
549#[allow(clippy::excessive_precision)]
550fn radau_constants() -> RadauConstants {
551    let s6 = 6f64.sqrt();
552    RadauConstants {
553        c: [(4.0 - s6) / 10.0, (4.0 + s6) / 10.0, 1.0],
554        e: [(-13.0 - 7.0 * s6) / 3.0, (-13.0 + 7.0 * s6) / 3.0, -1.0 / 3.0],
555        mu_real: 3.0 + 3f64.powf(2.0 / 3.0) - 3f64.powf(1.0 / 3.0),
556        mu_complex: C::new(3.0 + 0.5 * (3f64.powf(1.0 / 3.0) - 3f64.powf(2.0 / 3.0)), -0.5 * (3f64.powf(5.0 / 6.0) + 3f64.powf(7.0 / 6.0))),
557        t: [
558            [0.09443876248897524, -0.14125529502095421, 0.03002919410514742],
559            [0.25021312296533332, 0.20412935229379994, -0.38294211275726192],
560            [1.0, 1.0, 0.0],
561        ],
562        ti: [
563            [4.17871859155190428, 0.32768282076106237, 0.52337644549944951],
564            [-4.17871859155190428, -0.32768282076106237, 0.47662355450055044],
565            [0.50287263494578682, -2.57192694985560522, 0.59603920482822492],
566        ],
567        p: [
568            [13.0 / 3.0 + 7.0 * s6 / 3.0, -23.0 / 3.0 - 22.0 * s6 / 3.0, 10.0 / 3.0 + 5.0 * s6],
569            [13.0 / 3.0 - 7.0 * s6 / 3.0, -23.0 / 3.0 + 22.0 * s6 / 3.0, 10.0 / 3.0 - 5.0 * s6],
570            [1.0 / 3.0, -8.0 / 3.0, 10.0 / 3.0],
571        ],
572    }
573}
574
575struct Radau<'a, F, J> {
576    sys: Counter<'a, F, J>,
577    k: RadauConstants,
578    o: IvpOptions,
579    t: f64,
580    t_bound: f64,
581    y: Vec<f64>,
582    f: Vec<f64>,
583    h_abs: f64,
584    h_abs_old: Option<f64>,
585    error_norm_old: Option<f64>,
586    jac: JacMatrix,
587    lu_real: Option<RealLu>,
588    lu_complex: Option<ComplexLu>,
589    current_jac: bool,
590    sol: Option<Segment>,
591    newton_tol: f64,
592    rejected: usize,
593}
594
595fn predict_factor(h_abs: f64, h_abs_old: Option<f64>, error_norm: f64, error_norm_old: Option<f64>) -> f64 {
596    let multiplier = match (h_abs_old, error_norm_old) {
597        (Some(ho), Some(eo)) if error_norm != 0.0 => h_abs / ho * (eo / error_norm).powf(0.25),
598        _ => 1.0,
599    };
600    multiplier.min(1.0) * error_norm.powf(-0.25)
601}
602
603impl<'a, F, J> Radau<'a, F, J>
604where
605    F: Fn(f64, &[f64]) -> Vec<f64>,
606    J: Fn(f64, &[f64]) -> Vec<Vec<f64>>,
607{
608    fn new(mut sys: Counter<'a, F, J>, t0: f64, y0: &[f64], t_bound: f64, o: IvpOptions) -> Self {
609        let f = sys.f(t0, y0);
610        let h_abs = match o.first_step {
611            Some(h) => h,
612            None => select_initial_step(&mut sys, t0, y0, &f, t_bound - t0, o.max_step, 3.0, &o),
613        };
614        let jac = sys.jacobian(t0, y0, &f);
615        let newton_tol = (10.0 * f64::EPSILON / o.rtol).max(0.03f64.min(o.rtol.sqrt()));
616        Radau {
617            sys,
618            k: radau_constants(),
619            o,
620            t: t0,
621            t_bound,
622            y: y0.to_vec(),
623            f,
624            h_abs,
625            h_abs_old: None,
626            error_norm_old: None,
627            jac,
628            lu_real: None,
629            lu_complex: None,
630            current_jac: true,
631            sol: None,
632            newton_tol,
633            rejected: 0,
634        }
635    }
636
637    fn factor_real(&mut self, h: f64) -> Result<RealLu, ErrorsJSL> {
638        self.sys.nlu += 1;
639        self.jac.factor_real(self.k.mu_real / h, 1.0)
640    }
641
642    fn factor_complex(&mut self, h: f64) -> Result<ComplexLu, ErrorsJSL> {
643        self.sys.nlu += 1;
644        self.jac.factor_complex(self.k.mu_complex / h)
645    }
646
647    // ANCHOR: collocation
648    /// Simplified Newton iteration for the stage increments `Z` (SciPy's
649    /// `solve_collocation_system`): in the eigenbasis `W = T⁻¹ Z` of the Radau matrix, the 3n × 3n
650    /// system splits into one real and one complex n × n system.
651    fn solve_collocation(&mut self, h: f64, z0: [Vec<f64>; 3], scale: &[f64]) -> Result<Collocation, ErrorsJSL> {
652        let n = self.y.len();
653        let (t, y) = (self.t, self.y.clone());
654        let k = &self.k;
655        let m_real = k.mu_real / h;
656        let m_complex = k.mu_complex / h;
657        let mut w: [Vec<f64>; 3] = std::array::from_fn(|r| (0..n).map(|i| (0..3).map(|c| k.ti[r][c] * z0[c][i]).sum()).collect());
658        let mut z = z0;
659        let mut dw_norm_old: Option<f64> = None;
660        let mut rate: Option<f64> = None;
661        let mut converged = false;
662        let mut iterations = 0;
663        let lu_real = self.lu_real.as_ref().expect("factorised");
664        let lu_complex = self.lu_complex.as_ref().expect("factorised");
665        for it in 0..NEWTON_MAXITER {
666            iterations = it + 1;
667            let fs: Vec<Vec<f64>> = (0..3)
668                .map(|s| {
669                    let ys: Vec<f64> = y.iter().zip(&z[s]).map(|(a, b)| a + b).collect();
670                    self.sys.f(t + h * k.c[s], &ys)
671                })
672                .collect();
673            if fs.iter().flatten().any(|v| !v.is_finite()) {
674                break;
675            }
676            let f_real: Array1<f64> = (0..n).map(|i| (0..3).map(|s| fs[s][i] * k.ti[0][s]).sum::<f64>() - m_real * w[0][i]).collect();
677            let f_complex: Array1<C> = (0..n)
678                .map(|i| (0..3).map(|s| fs[s][i] * C::new(k.ti[1][s], k.ti[2][s])).sum::<C>() - m_complex * C::new(w[1][i], w[2][i]))
679                .collect();
680            let dw_real = lu_real.solve(&f_real).map_err(|_| ErrorsJSL::RuntimeError("Radau solve failed"))?;
681            let dw_complex = lu_complex.solve(&f_complex).map_err(|_| ErrorsJSL::RuntimeError("Radau solve failed"))?;
682            let dw: [Vec<f64>; 3] = [dw_real.to_vec(), dw_complex.iter().map(|z| z.re).collect(), dw_complex.iter().map(|z| z.im).collect()];
683            let flat: Vec<f64> = dw.iter().flatten().copied().collect();
684            let flat_scale: Vec<f64> = (0..3).flat_map(|_| scale.iter().copied()).collect();
685            let dw_norm = rms(&flat, &flat_scale);
686            if let Some(old) = dw_norm_old {
687                rate = Some(dw_norm / old);
688            }
689            if let Some(r) = rate
690                && (r >= 1.0 || r.powi((NEWTON_MAXITER - it) as i32) / (1.0 - r) * dw_norm > self.newton_tol)
691            {
692                break;
693            }
694            for r in 0..3 {
695                for i in 0..n {
696                    w[r][i] += dw[r][i];
697                }
698            }
699            z = std::array::from_fn(|r| (0..n).map(|i| (0..3).map(|c| k.t[r][c] * w[c][i]).sum()).collect());
700            if dw_norm == 0.0 || rate.is_some_and(|r| r / (1.0 - r) * dw_norm < self.newton_tol) {
701                converged = true;
702                break;
703            }
704            dw_norm_old = Some(dw_norm);
705        }
706        Ok((converged, iterations, z, rate))
707    }
708    // ANCHOR_END: collocation
709}
710
711impl<F, J> Stepper for Radau<'_, F, J>
712where
713    F: Fn(f64, &[f64]) -> Vec<f64>,
714    J: Fn(f64, &[f64]) -> Vec<Vec<f64>>,
715{
716    fn t(&self) -> f64 {
717        self.t
718    }
719    fn y(&self) -> &[f64] {
720        &self.y
721    }
722    fn counts(&self) -> (usize, usize, usize, usize) {
723        (self.sys.nfev, self.sys.njev, self.sys.nlu, self.rejected)
724    }
725
726    fn step(&mut self) -> Result<Segment, ErrorsJSL> {
727        let (t, y) = (self.t, self.y.clone());
728        let n = y.len();
729        let min_step = 10.0 * (t.next_up() - t).abs();
730        let (mut h_abs, h_abs_old, error_norm_old) = if self.h_abs > self.o.max_step {
731            (self.o.max_step, None, None)
732        } else if self.h_abs < min_step {
733            (min_step, None, None)
734        } else {
735            (self.h_abs, self.h_abs_old, self.error_norm_old)
736        };
737        let mut rejected = false;
738        let (h, t_new, z, error_norm, n_iter, rate);
739        loop {
740            if h_abs < min_step {
741                return Err(ErrorsJSL::RuntimeError("Radau: the required step size is less than the spacing between numbers"));
742            }
743            let mut t_try = t + h_abs;
744            if t_try > self.t_bound {
745                t_try = self.t_bound;
746            }
747            let h_try = t_try - t;
748            h_abs = h_try.abs();
749            let z0: [Vec<f64>; 3] = match &self.sol {
750                None => std::array::from_fn(|_| vec![0.0; n]),
751                Some(s) => std::array::from_fn(|i| s.evaluate(t + h_try * self.k.c[i]).iter().zip(&y).map(|(a, b)| a - b).collect()),
752            };
753            let scale: Vec<f64> = y.iter().map(|v| self.o.atol + v.abs() * self.o.rtol).collect();
754            let mut result;
755            loop {
756                if self.lu_real.is_none() || self.lu_complex.is_none() {
757                    self.lu_real = Some(self.factor_real(h_try)?);
758                    self.lu_complex = Some(self.factor_complex(h_try)?);
759                }
760                result = self.solve_collocation(h_try, z0.clone(), &scale)?;
761                if !result.0 {
762                    if self.current_jac {
763                        break;
764                    }
765                    self.jac = self.sys.jacobian(t, &y, &self.f.clone());
766                    self.current_jac = true;
767                    self.lu_real = None;
768                    self.lu_complex = None;
769                    continue;
770                }
771                break;
772            }
773            let (converged, it, zz, rt) = result;
774            if !converged {
775                h_abs *= 0.5;
776                self.lu_real = None;
777                self.lu_complex = None;
778                continue;
779            }
780            let y_new: Vec<f64> = y.iter().zip(&zz[2]).map(|(a, b)| a + b).collect();
781            let ze: Vec<f64> = (0..n).map(|i| (0..3).map(|s| zz[s][i] * self.k.e[s]).sum::<f64>() / h_try).collect();
782            let lu = self.lu_real.as_ref().expect("factorised");
783            let rhs: Array1<f64> = (0..n).map(|i| self.f[i] + ze[i]).collect();
784            let mut err = lu.solve(&rhs).map_err(|_| ErrorsJSL::RuntimeError("Radau solve failed"))?.to_vec();
785            let scale: Vec<f64> = y.iter().zip(&y_new).map(|(a, b)| self.o.atol + a.abs().max(b.abs()) * self.o.rtol).collect();
786            let mut en = rms(&err, &scale);
787            let safety = 0.9 * (2 * NEWTON_MAXITER + 1) as f64 / (2 * NEWTON_MAXITER + it) as f64;
788            if rejected && en > 1.0 {
789                let ye: Vec<f64> = y.iter().zip(&err).map(|(a, b)| a + b).collect();
790                let fe = self.sys.f(t, &ye);
791                let rhs: Array1<f64> = (0..n).map(|i| fe[i] + ze[i]).collect();
792                err = self.lu_real.as_ref().expect("factorised").solve(&rhs).map_err(|_| ErrorsJSL::RuntimeError("Radau solve failed"))?.to_vec();
793                en = rms(&err, &scale);
794            }
795            if en > 1.0 {
796                let factor = predict_factor(h_abs, h_abs_old, en, error_norm_old);
797                h_abs *= (safety * factor).max(0.2);
798                self.lu_real = None;
799                self.lu_complex = None;
800                rejected = true;
801                self.rejected += 1;
802                continue;
803            }
804            h = h_try;
805            t_new = t_try;
806            z = zz;
807            error_norm = en;
808            n_iter = it;
809            rate = rt;
810            let recompute_jac = n_iter > 2 && rate.is_some_and(|r| r > 1e-3);
811            let mut factor = predict_factor(h_abs, h_abs_old, error_norm, error_norm_old);
812            factor = (safety * factor).min(10.0);
813            if !recompute_jac && factor < 1.2 {
814                factor = 1.0;
815            } else {
816                self.lu_real = None;
817                self.lu_complex = None;
818            }
819            let y_new_v = y_new;
820            let f_new = self.sys.f(t_new, &y_new_v);
821            if recompute_jac {
822                self.jac = self.sys.jacobian(t_new, &y_new_v, &f_new);
823                self.current_jac = true;
824            } else {
825                self.current_jac = false;
826            }
827            self.h_abs_old = Some(self.h_abs);
828            self.error_norm_old = Some(error_norm);
829            self.h_abs = h_abs * factor;
830            self.t = t_new;
831            self.y = y_new_v;
832            self.f = f_new;
833            break;
834        }
835        // Dense output: y(t_old + x h) = y_old + Q (x, x², x³), Q = Zᵀ P.
836        let coeffs: Vec<Vec<f64>> = (0..3).map(|kk| (0..n).map(|i| (0..3).map(|s| z[s][i] * self.k.p[s][kk]).sum()).collect()).collect();
837        let seg = Segment { t_start: t, t_end: t_new, t_ref: t, h, y_ref: y, coeffs };
838        self.sol = Some(seg.clone());
839        Ok(seg)
840    }
841}
842
843// ------------------------------------------------------------------------------------- LSODA
844
845/// The ODEPACK coefficients (`cfode`): for each order `q`, the corrector vector `l` (length
846/// `q + 1`) and the test constants `(tesco₁, tesco₂, tesco₃)` for orders `q − 1`, `q`, `q + 1`.
847struct Coefficients {
848    el: Vec<Vec<f64>>,
849    tesco: Vec<[f64; 3]>,
850}
851
852// ANCHOR: cfode
853fn cfode(adams: bool) -> Coefficients {
854    let max_order = if adams { 12 } else { 5 };
855    let mut el = vec![Vec::new(); max_order + 1];
856    let mut tesco = vec![[0.0; 3]; max_order + 2];
857    if adams {
858        el[1] = vec![1.0, 1.0];
859        tesco[1] = [0.0, 2.0, 0.0];
860        tesco[2][0] = 1.0;
861        let mut pc = [0.0; 13];
862        pc[0] = 1.0;
863        let mut rqfac = 1.0;
864        for nq in 2..=12usize {
865            // p(x) = (x + 1)(x + 2)…(x + nq − 1), its integral over [−1, 0] and that of x p(x).
866            let rq1fac = rqfac;
867            rqfac /= nq as f64;
868            let fnqm1 = (nq - 1) as f64;
869            pc[nq - 1] = 0.0;
870            for i in (1..nq).rev() {
871                pc[i] = pc[i - 1] + fnqm1 * pc[i];
872            }
873            pc[0] *= fnqm1;
874            let (mut pint, mut xpin, mut tsign) = (pc[0], pc[0] / 2.0, 1.0);
875            for i in 1..nq {
876                tsign = -tsign;
877                pint += tsign * pc[i] / (i + 1) as f64;
878                xpin += tsign * pc[i] / (i + 2) as f64;
879            }
880            let mut e = vec![0.0; nq + 1];
881            e[0] = pint * rq1fac;
882            e[1] = 1.0;
883            for i in 1..nq {
884                e[i + 1] = rq1fac * pc[i] / (i + 1) as f64;
885            }
886            el[nq] = e;
887            let agamq = rqfac * xpin;
888            let ragq = 1.0 / agamq;
889            tesco[nq][1] = ragq;
890            if nq < 12 {
891                tesco[nq + 1][0] = ragq * rqfac / (nq + 1) as f64;
892            }
893            tesco[nq - 1][2] = ragq;
894        }
895    } else {
896        let mut pc = [0.0; 7];
897        pc[0] = 1.0;
898        let mut rq1fac = 1.0;
899        for nq in 1..=5usize {
900            // p(x) = x (x + 1)…(x + nq − 1).
901            let fnq = nq as f64;
902            pc[nq] = 0.0;
903            for i in (1..=nq).rev() {
904                pc[i] = pc[i - 1] + fnq * pc[i];
905            }
906            pc[0] *= fnq;
907            let mut e: Vec<f64> = (0..=nq).map(|i| pc[i] / pc[1]).collect();
908            e[1] = 1.0;
909            tesco[nq] = [rq1fac, (nq + 1) as f64 / e[0], (nq + 2) as f64 / e[0]];
910            el[nq] = e;
911            rq1fac /= fnq;
912        }
913    }
914    Coefficients { el, tesco }
915}
916// ANCHOR_END: cfode
917
918/// LSODA switches from Adams to BDF when the BDF step that the error estimate allows is at least
919/// this many times the Adams step that stability allows (ODEPACK's value is 5; the cost of a BDF
920/// step is below five Adams steps when the Jacobian is sparse or small, and 3 gave SciPy's step
921/// count on the stiff test chain).
922const STIFF_RATIO: f64 = 3.0;
923
924/// Stability limits `h ‖J‖` of the Adams methods of orders 1 to 12 (LSODA's `sm1`).
925const SM1: [f64; 13] = [0.0, 0.5, 0.575, 0.55, 0.45, 0.35, 0.25, 0.2, 0.15, 0.1, 0.075, 0.05, 0.025];
926
927struct Lsoda<'a, F, J> {
928    sys: Counter<'a, F, J>,
929    o: IvpOptions,
930    adams: Coefficients,
931    bdf: Coefficients,
932    stiff: bool,
933    t: f64,
934    t_bound: f64,
935    /// Nordsieck array: z[j] = hʲ y⁽ʲ⁾ / j!.
936    z: Vec<Vec<f64>>,
937    q: usize,
938    h: f64,
939    /// Steps until the next order/step-size decision.
940    countdown: usize,
941    acor_saved: Option<Vec<f64>>,
942    jac: Option<JacMatrix>,
943    jac_age: usize,
944    lu: Option<(RealLu, f64)>,
945    lipschitz: f64,
946    steps: usize,
947    last_switch: usize,
948    switches: Vec<(f64, bool)>,
949    rejected: usize,
950    y_now: Vec<f64>,
951}
952
953impl<'a, F, J> Lsoda<'a, F, J>
954where
955    F: Fn(f64, &[f64]) -> Vec<f64>,
956    J: Fn(f64, &[f64]) -> Vec<Vec<f64>>,
957{
958    fn new(mut sys: Counter<'a, F, J>, t0: f64, y0: &[f64], t_bound: f64, o: IvpOptions) -> Self {
959        let f0 = sys.f(t0, y0);
960        let h = match o.first_step {
961            Some(h) => h,
962            None => select_initial_step(&mut sys, t0, y0, &f0, t_bound - t0, o.max_step, 1.0, &o),
963        };
964        let z = vec![y0.to_vec(), f0.iter().map(|v| v * h).collect()];
965        Lsoda {
966            sys,
967            o,
968            adams: cfode(true),
969            bdf: cfode(false),
970            stiff: false,
971            t: t0,
972            t_bound,
973            z,
974            q: 1,
975            h,
976            countdown: 2,
977            acor_saved: None,
978            jac: None,
979            jac_age: 0,
980            lu: None,
981            lipschitz: 0.0,
982            steps: 0,
983            last_switch: 0,
984            switches: Vec::new(),
985            rejected: 0,
986            y_now: y0.to_vec(),
987        }
988    }
989
990    fn coefficients(&self) -> &Coefficients {
991        if self.stiff { &self.bdf } else { &self.adams }
992    }
993
994    fn max_order(&self) -> usize {
995        if self.stiff { 5 } else { 12 }
996    }
997
998    fn rescale(&mut self, r: f64) {
999        let mut p = 1.0;
1000        for zj in self.z.iter_mut().skip(1) {
1001            p *= r;
1002            zj.iter_mut().for_each(|v| *v *= p);
1003        }
1004        self.h *= r;
1005    }
1006
1007    /// Multiplies the Nordsieck array by the Pascal matrix: the predictor at `t + h`.
1008    fn predict(z: &mut [Vec<f64>]) {
1009        let q = z.len() - 1;
1010        for k in 0..q {
1011            for j in (k + 1..=q).rev() {
1012                let (lo, hi) = z.split_at_mut(j);
1013                for (a, b) in lo[j - 1].iter_mut().zip(&hi[0]) {
1014                    *a += b;
1015                }
1016            }
1017        }
1018    }
1019
1020    /// The weighted norm used by ODEPACK: RMS of `v / ewt`, `ewt = rtol |y| + atol`.
1021    fn norm(&self, v: &[f64]) -> f64 {
1022        let ewt: Vec<f64> = self.z[0].iter().map(|y| self.o.rtol * y.abs() + self.o.atol).collect();
1023        rms(v, &ewt)
1024    }
1025
1026    /// The weighted row norm of the Jacobian, LSODA's estimate of ‖J‖ in stiff mode.
1027    fn jacobian_norm(&self, jac: &JacMatrix) -> f64 {
1028        let ewt: Vec<f64> = self.z[0].iter().map(|y| self.o.rtol * y.abs() + self.o.atol).collect();
1029        jac.weighted_norm(&ewt)
1030    }
1031}
1032
1033impl<F, J> Stepper for Lsoda<'_, F, J>
1034where
1035    F: Fn(f64, &[f64]) -> Vec<f64>,
1036    J: Fn(f64, &[f64]) -> Vec<Vec<f64>>,
1037{
1038    fn t(&self) -> f64 {
1039        self.t
1040    }
1041    fn y(&self) -> &[f64] {
1042        &self.y_now
1043    }
1044    fn counts(&self) -> (usize, usize, usize, usize) {
1045        (self.sys.nfev, self.sys.njev, self.sys.nlu, self.rejected)
1046    }
1047    fn switches(&self) -> Vec<(f64, bool)> {
1048        self.switches.clone()
1049    }
1050
1051    // ANCHOR: lsoda_step
1052    fn step(&mut self) -> Result<Segment, ErrorsJSL> {
1053        let n = self.z[0].len();
1054        let mut failures = 0;
1055        loop {
1056            if self.h > self.o.max_step {
1057                self.rescale(self.o.max_step / self.h);
1058            }
1059            if self.t + self.h > self.t_bound {
1060                self.rescale((self.t_bound - self.t) / self.h);
1061            }
1062            if self.h < 10.0 * (self.t.next_up() - self.t) {
1063                return Err(ErrorsJSL::RuntimeError("LSODA: the step size underflowed"));
1064            }
1065            let t_new = if self.t + self.h >= self.t_bound * (1.0 - 1e-15) && self.t_bound - self.t <= self.h * (1.0 + 1e-12) { self.t_bound } else { self.t + self.h };
1066            let q = self.q;
1067            let (el, tesco) = {
1068                let c = self.coefficients();
1069                (c.el[q].clone(), c.tesco[q])
1070            };
1071            let mut zp = self.z.clone();
1072            Self::predict(&mut zp);
1073            // Corrector: acor solves acor = h f(z₀ + l₀ acor) − z₁, by functional iteration
1074            // (Adams) or by Newton's method with P = I − h l₀ J (BDF).
1075            if self.stiff {
1076                let need_jac = self.jac.is_none() || self.jac_age >= 20;
1077                if need_jac {
1078                    let f0 = self.sys.f(t_new, &zp[0]);
1079                    let jac = self.sys.jacobian(t_new, &zp[0], &f0);
1080                    self.lipschitz = self.jacobian_norm(&jac);
1081                    self.jac = Some(jac);
1082                    self.jac_age = 0;
1083                    self.lu = None;
1084                }
1085                let hl0 = self.h * el[0];
1086                if self.lu.as_ref().is_none_or(|(_, v)| (hl0 / v - 1.0).abs() > 0.3) {
1087                    let jac = self.jac.as_ref().expect("evaluated");
1088                    self.sys.nlu += 1;
1089                    let lu = jac.factor_real(1.0, hl0).map_err(|_| ErrorsJSL::RuntimeError("LSODA: singular iteration matrix"))?;
1090                    self.lu = Some((lu, hl0));
1091                }
1092            }
1093            let mut acor = vec![0.0; n];
1094            let mut y = zp[0].clone();
1095            let (mut crate_, mut delp) = (0.7f64, 0.0f64);
1096            let conit = 0.5 / (q + 2) as f64;
1097            let mut converged = false;
1098            let (mut prev_y, mut prev_f): (Option<Vec<f64>>, Option<Vec<f64>>) = (None, None);
1099            let mut lipschitz_step = 0.0f64;
1100            for m in 0..3 {
1101                let fy = self.sys.f(t_new, &y);
1102                if fy.iter().any(|v| !v.is_finite()) {
1103                    break;
1104                }
1105                let del;
1106                if self.stiff {
1107                    // If the LU was formed for a different h l₀, correct the Newton step by the ratio.
1108                    let (lu, hl0_lu) = self.lu.as_ref().expect("factorised");
1109                    let r: Array1<f64> = (0..n).map(|i| self.h * fy[i] - zp[1][i] - acor[i]).collect();
1110                    let mut x = lu.solve(&r).map_err(|_| ErrorsJSL::RuntimeError("LSODA: solve failed"))?.to_vec();
1111                    let ratio = 2.0 / (1.0 + self.h * el[0] / hl0_lu);
1112                    if (ratio - 1.0).abs() > 1e-12 {
1113                        x.iter_mut().for_each(|v| *v *= ratio);
1114                    }
1115                    del = self.norm(&x);
1116                    for i in 0..n {
1117                        acor[i] += x[i];
1118                    }
1119                } else {
1120                    let r: Vec<f64> = (0..n).map(|i| self.h * fy[i] - zp[1][i]).collect();
1121                    let d: Vec<f64> = r.iter().zip(&acor).map(|(a, b)| a - b).collect();
1122                    del = self.norm(&d);
1123                    acor = r;
1124                    if let (Some(py), Some(pf)) = (&prev_y, &prev_f) {
1125                        let dy: Vec<f64> = y.iter().zip(py).map(|(a, b)| a - b).collect();
1126                        let df: Vec<f64> = fy.iter().zip(pf).map(|(a, b)| a - b).collect();
1127                        let ny = self.norm(&dy);
1128                        if ny > 0.0 {
1129                            lipschitz_step = lipschitz_step.max(self.norm(&df) / ny);
1130                        }
1131                    }
1132                    prev_y = Some(y.clone());
1133                    prev_f = Some(fy.clone());
1134                }
1135                y = (0..n).map(|i| zp[0][i] + el[0] * acor[i]).collect();
1136                if m > 0 {
1137                    crate_ = (0.2 * crate_).max(del / delp);
1138                }
1139                let dcon = del * (1.5 * crate_).min(1.0) / (tesco[1] * conit);
1140                if dcon <= 1.0 {
1141                    converged = true;
1142                    break;
1143                }
1144                if m >= 1 && del > 2.0 * delp {
1145                    break;
1146                }
1147                delp = del;
1148            }
1149            if !self.stiff && lipschitz_step > 0.0 {
1150                self.lipschitz = lipschitz_step;
1151            }
1152            if !converged {
1153                failures += 1;
1154                if self.stiff && self.jac_age > 0 {
1155                    self.jac = None;
1156                    continue;
1157                }
1158                self.rejected += 1;
1159                if failures > 10 {
1160                    return Err(ErrorsJSL::RuntimeError("LSODA: repeated corrector failures"));
1161                }
1162                self.rescale(0.25);
1163                continue;
1164            }
1165            // Local error test.
1166            let dsm = self.norm(&acor) / tesco[1];
1167            if dsm > 1.0 {
1168                failures += 1;
1169                self.rejected += 1;
1170                if failures >= 3 {
1171                    // Restart at order one from the current state.
1172                    let f0 = self.sys.f(self.t, &self.z[0]);
1173                    self.z.truncate(2);
1174                    self.q = 1;
1175                    self.h *= 0.1;
1176                    self.z[1] = f0.iter().map(|v| v * self.h).collect();
1177                    self.countdown = 2;
1178                    self.acor_saved = None;
1179                    continue;
1180                }
1181                // As ODEPACK: the larger of the steps allowed at this order and one lower; after a
1182                // second failure, at most a fifth of the step.
1183                let rhsm = 1.0 / (1.2 * dsm.powf(1.0 / (q + 1) as f64) + 1.2e-6);
1184                let rhdn = if q > 1 { 1.0 / (1.3 * (self.norm(&self.z[q]) / tesco[0]).powf(1.0 / q as f64) + 1.3e-6) } else { 0.0 };
1185                let mut rh = rhsm;
1186                if rhdn > rhsm {
1187                    rh = rhdn;
1188                    self.z.truncate(q);
1189                    self.q = q - 1;
1190                }
1191                if failures >= 2 {
1192                    rh = rh.min(0.2);
1193                }
1194                self.rescale(rh.clamp(0.1, 0.9));
1195                self.countdown = self.q + 1;
1196                self.acor_saved = None;
1197                continue;
1198            }
1199            // Accept: z ← z_pred + l acor.
1200            for j in 0..=q {
1201                for i in 0..n {
1202                    zp[j][i] += el[j] * acor[i];
1203                }
1204            }
1205            self.z = zp;
1206            self.t = t_new;
1207            self.y_now = self.z[0].clone();
1208            self.steps += 1;
1209            if self.stiff {
1210                self.jac_age += 1;
1211            }
1212            let seg = Segment { t_start: t_new - self.h, t_end: t_new, t_ref: t_new, h: self.h, y_ref: self.z[0].clone(), coeffs: self.z[1..].to_vec() };
1213            // Order and step size, every q + 1 steps (ODEPACK's `ialth`).
1214            self.countdown = self.countdown.saturating_sub(1);
1215            if self.countdown == 1 && q < self.max_order() {
1216                self.acor_saved = Some(acor.clone());
1217            }
1218            if self.countdown == 0 {
1219                let rhsm = 1.0 / (1.2 * dsm.powf(1.0 / (q + 1) as f64) + 1.2e-6);
1220                let rhdn = if q > 1 { 1.0 / (1.3 * (self.norm(&self.z[q]) / tesco[0]).powf(1.0 / q as f64) + 1.3e-6) } else { 0.0 };
1221                let rhup = match (&self.acor_saved, q < self.max_order()) {
1222                    (Some(prev), true) => {
1223                        let d: Vec<f64> = acor.iter().zip(prev).map(|(a, b)| a - b).collect();
1224                        1.0 / (1.4 * (self.norm(&d) / tesco[2]).powf(1.0 / (q + 2) as f64) + 1.4e-6)
1225                    }
1226                    _ => 0.0,
1227                };
1228                let (mut rh, mut new_q) = (rhsm, q);
1229                if rhup > rh {
1230                    rh = rhup;
1231                    new_q = q + 1;
1232                }
1233                if rhdn > rh {
1234                    rh = rhdn;
1235                    new_q = q - 1;
1236                }
1237                // Stiffness detection (Petzold): compare the step each method could take, with
1238                // the Adams step also limited by its stability region, h ‖J‖ ≤ sm1(q).
1239                if self.steps >= self.last_switch + 20 && self.lipschitz > 0.0 {
1240                    let cm = |c: &Coefficients, k: usize| c.tesco[k][1] * c.el[k][k];
1241                    if !self.stiff {
1242                        let rh1 = rh.min(SM1[new_q] / (self.h * self.lipschitz));
1243                        let q2 = q.min(5);
1244                        let dm2 = dsm * (cm(&self.adams, q) / cm(&self.bdf, q2));
1245                        let rh2 = 1.0 / (1.2 * dm2.powf(1.0 / (q2 + 1) as f64) + 1.2e-6);
1246                        if rh2 >= STIFF_RATIO * rh1 {
1247                            self.stiff = true;
1248                            self.switches.push((self.t, true));
1249                            self.last_switch = self.steps;
1250                            self.jac = None;
1251                            self.lu = None;
1252                            self.z.truncate(q2 + 1);
1253                            self.q = q2;
1254                            self.countdown = q2 + 1;
1255                            self.acor_saved = None;
1256                            self.rescale(rh2.min(10.0));
1257                            return Ok(seg);
1258                        }
1259                    } else {
1260                        let dm1 = dsm * (cm(&self.bdf, q) / cm(&self.adams, q));
1261                        let rh1 = (1.0 / (1.2 * dm1.powf(1.0 / (q + 1) as f64) + 1.2e-6)).min(SM1[q] / (self.h * self.lipschitz));
1262                        if rh1 >= rh {
1263                            self.stiff = false;
1264                            self.switches.push((self.t, false));
1265                            self.last_switch = self.steps;
1266                            self.lu = None;
1267                            self.countdown = q + 1;
1268                            self.acor_saved = None;
1269                            self.rescale(rh1.min(10.0));
1270                            return Ok(seg);
1271                        }
1272                    }
1273                }
1274                let rh = rh.min(10.0);
1275                if rh >= 1.1 {
1276                    if new_q > q {
1277                        let extra: Vec<f64> = acor.iter().map(|a| a * el[q] / (q + 1) as f64).collect();
1278                        self.z.push(extra);
1279                    } else if new_q < q {
1280                        self.z.truncate(new_q + 1);
1281                    }
1282                    self.q = new_q;
1283                    self.rescale(rh);
1284                } else if new_q < q && rhdn >= rhsm {
1285                    self.z.truncate(new_q + 1);
1286                    self.q = new_q;
1287                }
1288                self.countdown = self.q + 1;
1289                self.acor_saved = None;
1290            }
1291            return Ok(seg);
1292        }
1293    }
1294    // ANCHOR_END: lsoda_step
1295}
1296
1297mod explicit;
1298pub use explicit::{ExplicitMethod, ExplicitOptions, solve_ivp_explicit};
1299
1300// ------------------------------------------------------------------------------------- driver
1301
1302/// The parts of an [`IvpSolution`] that the driver produces.
1303type Driven = (Vec<f64>, Vec<Vec<f64>>, IvpStatus, Vec<Vec<f64>>, Vec<Vec<Vec<f64>>>, DenseOutput);
1304
1305/// Advances `stepper` from `t0` to `t1` (in either direction), locating events on each step's
1306/// interpolant and collecting the dense output (in increasing time).
1307fn drive(stepper: &mut dyn Stepper, t0: f64, t1: f64, y0: &[f64], events: &[Event], max_steps: usize) -> Result<Driven, ErrorsJSL> {
1308    let mut ts = vec![t0];
1309    let mut ys = vec![y0.to_vec()];
1310    let mut t_events = vec![Vec::new(); events.len()];
1311    let mut y_events = vec![Vec::new(); events.len()];
1312    let mut counts = vec![0usize; events.len()];
1313    let mut g: Vec<f64> = events.iter().map(|e| (e.function)(t0, y0)).collect();
1314    let mut dense = DenseOutput::default();
1315    let mut status = IvpStatus::Finished;
1316    let mut attempts = 0;
1317    let direction = if t1 >= t0 { 1.0 } else { -1.0 };
1318    while direction * (t1 - stepper.t()) > 0.0 {
1319        attempts += 1;
1320        if attempts > max_steps {
1321            return Err(ErrorsJSL::RuntimeError("solve_ivp: too many steps"));
1322        }
1323        let t_old = stepper.t();
1324        let seg = stepper.step()?;
1325        let (t_new, y_new) = (stepper.t(), stepper.y().to_vec());
1326        let g_new: Vec<f64> = events.iter().map(|e| (e.function)(t_new, &y_new)).collect();
1327        // Events active in this step, with their roots, in time order.
1328        let mut active: Vec<(f64, usize)> = Vec::new();
1329        for (i, e) in events.iter().enumerate() {
1330            // Crossing directions refer to increasing time, as in SciPy.
1331            let (before, after) = if direction > 0.0 { (g[i], g_new[i]) } else { (g_new[i], g[i]) };
1332            let up = before <= 0.0 && after >= 0.0;
1333            let down = before >= 0.0 && after <= 0.0;
1334            if (up && e.direction > 0.0) || (down && e.direction < 0.0) || ((up || down) && e.direction == 0.0) {
1335                let root = brentq(|t| (e.function)(t, &seg.evaluate(t)), t_old, t_new);
1336                active.push((root, i));
1337            }
1338        }
1339        active.sort_by(|a, b| (direction * a.0).total_cmp(&(direction * b.0)));
1340        let mut stop_at = None;
1341        for &(root, i) in &active {
1342            t_events[i].push(root);
1343            y_events[i].push(seg.evaluate(root));
1344            counts[i] += 1;
1345            if events[i].terminal.is_some_and(|k| counts[i] >= k) {
1346                stop_at = Some(root);
1347                break;
1348            }
1349        }
1350        g = g_new;
1351        dense.segments.push(seg.clone());
1352        if let Some(root) = stop_at {
1353            ts.push(root);
1354            ys.push(seg.evaluate(root));
1355            if let Some(last) = dense.segments.last_mut() {
1356                if direction > 0.0 { last.t_end = root } else { last.t_start = root }
1357            }
1358            status = IvpStatus::TerminatedByEvent;
1359            break;
1360        }
1361        ts.push(t_new);
1362        ys.push(y_new);
1363    }
1364    if direction < 0.0 {
1365        dense.segments.reverse();
1366    }
1367    Ok((ts, ys, status, t_events, y_events, dense))
1368}
1369
1370// ANCHOR: solve_ivp
1371/// Solves `y' = f(t, y)`, `y(t0) = y0` on `[t0, t1]` (`t1 > t0`) with the given method (SciPy's
1372/// `solve_ivp`), returning every accepted step, the dense output, and the occurrences of each
1373/// event. `jac`, if given, returns `∂f/∂y` as rows; otherwise forward differences are used.
1374///
1375/// After each step, every event function is evaluated at the new point; where its sign changes
1376/// in the requested direction, the zero is found by Brent's method on the step's interpolant.
1377/// A terminal event that reaches its count ends the integration there.
1378pub fn solve_ivp<F, J>(f: F, jac: Option<J>, t_span: (f64, f64), y0: &[f64], method: IvpMethod, options: IvpOptions, events: &[Event]) -> Result<IvpSolution, ErrorsJSL>
1379where
1380    F: Fn(f64, &[f64]) -> Vec<f64>,
1381    J: Fn(f64, &[f64]) -> Vec<Vec<f64>>,
1382{
1383    let (t0, t1) = t_span;
1384    if y0.is_empty() || !(t1 > t0) || !t0.is_finite() || !t1.is_finite() {
1385        return Err(ErrorsJSL::InvalidInputRange("need a non-empty state and finite t0 < t1"));
1386    }
1387    if !(options.rtol > 0.0) || !(options.atol > 0.0) {
1388        return Err(ErrorsJSL::InvalidInputRange("tolerances must be positive"));
1389    }
1390    let sys = Counter { f: &f, jac: jac.as_ref(), sparse: None, nfev: 0, njev: 0, nlu: 0 };
1391    let mut stepper: Box<dyn Stepper + '_> = match method {
1392        IvpMethod::Radau => Box::new(Radau::new(sys, t0, y0, t1, options)),
1393        IvpMethod::Lsoda => Box::new(Lsoda::new(sys, t0, y0, t1, options)),
1394    };
1395    let (ts, ys, status, t_events, y_events, dense) = drive(stepper.as_mut(), t0, t1, y0, events, options.max_steps)?;
1396    let (nfev, njev, nlu, rejected_steps) = stepper.counts();
1397    let switches = stepper.switches();
1398    Ok(IvpSolution { t: ts, y: ys, status, t_events, y_events, dense, nfev, njev, nlu, rejected_steps, switches })
1399}
1400// ANCHOR_END: solve_ivp
1401
1402// ANCHOR: solve_ivp_sparse
1403/// [`solve_ivp`] for large stiff systems with sparse Jacobians (SciPy's `solve_ivp` with a sparse
1404/// `jac` or with `jac_sparsity`). The Newton matrices of Radau (`μ/h · I − J`, real and complex)
1405/// and of LSODA's BDF corrector (`I − h l₀ J`) are factorised by the sparse LU
1406/// ([`SparseLu`], minimum-degree ordering); Radau's complex system is solved in its real form
1407/// of twice the size. With [`SparseJacobian::Pattern`], the Jacobian is estimated by grouped
1408/// forward differences: columns sharing no row are perturbed together (Curtis, Powell and Reid),
1409/// so a banded `n × n` Jacobian costs a few evaluations of `f` instead of `n`.
1410pub fn solve_ivp_sparse<F>(f: F, jac: SparseJacobian, t_span: (f64, f64), y0: &[f64], method: IvpMethod, options: IvpOptions, events: &[Event]) -> Result<IvpSolution, ErrorsJSL>
1411where
1412    F: Fn(f64, &[f64]) -> Vec<f64>,
1413{
1414    let (t0, t1) = t_span;
1415    if y0.is_empty() || !(t1 > t0) || !t0.is_finite() || !t1.is_finite() {
1416        return Err(ErrorsJSL::InvalidInputRange("need a non-empty state and finite t0 < t1"));
1417    }
1418    if !(options.rtol > 0.0) || !(options.atol > 0.0) {
1419        return Err(ErrorsJSL::InvalidInputRange("tolerances must be positive"));
1420    }
1421    if let SparseJacobian::Pattern(p) = &jac
1422        && (p.nrows != y0.len() || p.ncols != y0.len())
1423    {
1424        return Err(ErrorsJSL::IncompatibleArraySizes((p.nrows, y0.len())));
1425    }
1426    let sys: Counter<'_, F, DenseJacFn> = Counter { f: &f, jac: None, sparse: Some(&jac), nfev: 0, njev: 0, nlu: 0 };
1427    let mut stepper: Box<dyn Stepper + '_> = match method {
1428        IvpMethod::Radau => Box::new(Radau::new(sys, t0, y0, t1, options)),
1429        IvpMethod::Lsoda => Box::new(Lsoda::new(sys, t0, y0, t1, options)),
1430    };
1431    let (ts, ys, status, t_events, y_events, dense) = drive(stepper.as_mut(), t0, t1, y0, events, options.max_steps)?;
1432    let (nfev, njev, nlu, rejected_steps) = stepper.counts();
1433    let switches = stepper.switches();
1434    Ok(IvpSolution { t: ts, y: ys, status, t_events, y_events, dense, nfev, njev, nlu, rejected_steps, switches })
1435}
1436// ANCHOR_END: solve_ivp_sparse
1437
1438#[cfg(test)]
1439mod tests {
1440    use super::*;
1441
1442    type Jac = fn(f64, &[f64]) -> Vec<Vec<f64>>;
1443
1444    #[test]
1445    fn sparse_jacobians_match_the_dense_solver() {
1446        // A stiff reaction-diffusion chain: y_i' = D (y_{i−1} − 2 y_i + y_{i+1}) − y_i³.
1447        let n = 40;
1448        let d = 400.0;
1449        let f = move |_t: f64, y: &[f64]| (0..n).map(|i| d * ((if i > 0 { y[i - 1] } else { 0.0 }) - 2.0 * y[i] + (if i + 1 < n { y[i + 1] } else { 0.0 })) - y[i].powi(3)).collect::<Vec<_>>();
1450        let y0: Vec<f64> = (0..n).map(|i| (std::f64::consts::PI * (i + 1) as f64 / (n + 1) as f64).sin()).collect();
1451        let mut coo = CooMatrix::new(n, n);
1452        for i in 0..n {
1453            for j in i.saturating_sub(1)..(i + 2).min(n) {
1454                coo.push(i, j, 1.0);
1455            }
1456        }
1457        let pattern = coo.to_csr().unwrap();
1458        let o = IvpOptions { rtol: 1e-8, atol: 1e-10, ..Default::default() };
1459        for method in [IvpMethod::Radau, IvpMethod::Lsoda] {
1460            let dense = solve_ivp(f, None::<Jac>, (0.0, 0.5), &y0, method, o, &[]).unwrap();
1461            let sp = solve_ivp_sparse(f, SparseJacobian::Pattern(pattern.clone()), (0.0, 0.5), &y0, method, o, &[]).unwrap();
1462            let (a, b) = (dense.y.last().unwrap(), sp.y.last().unwrap());
1463            assert!(a.iter().zip(b).all(|(p, q)| (p - q).abs() < 1e-9), "{method:?}");
1464            // Three groups of columns instead of n (LSODA may not need a Jacobian at all).
1465            assert!(sp.nfev < dense.nfev || (method == IvpMethod::Lsoda && sp.nfev == dense.nfev && sp.njev == 0), "{method:?} {} {}", sp.nfev, dense.nfev);
1466            let analytic = SparseJacobian::Analytic(Box::new(move |_t: f64, y: &[f64]| {
1467                let mut c = CooMatrix::new(n, n);
1468                for i in 0..n {
1469                    c.push(i, i, -2.0 * d - 3.0 * y[i] * y[i]);
1470                    if i > 0 {
1471                        c.push(i, i - 1, d);
1472                    }
1473                    if i + 1 < n {
1474                        c.push(i, i + 1, d);
1475                    }
1476                }
1477                c.to_csr().unwrap()
1478            }));
1479            let an = solve_ivp_sparse(f, analytic, (0.0, 0.5), &y0, method, o, &[]).unwrap();
1480            assert!(an.y.last().unwrap().iter().zip(a).all(|(p, q)| (p - q).abs() < 1e-8), "{method:?}");
1481        }
1482    }
1483
1484    #[test]
1485    fn cfode_matches_the_known_coefficients() {
1486        let bdf = cfode(false);
1487        // BDF2: l = (2/3, 1, 1/3).
1488        assert!((bdf.el[2][0] - 2.0 / 3.0).abs() < 1e-15 && (bdf.el[2][2] - 1.0 / 3.0).abs() < 1e-15);
1489        let adams = cfode(true);
1490        // Adams-Moulton order 2 (trapezoid): l = (1/2, 1, 1/2).
1491        assert!((adams.el[2][0] - 0.5).abs() < 1e-15 && (adams.el[2][2] - 0.5).abs() < 1e-15);
1492    }
1493
1494    #[test]
1495    fn exponential_decay_with_both_methods() {
1496        for method in [IvpMethod::Radau, IvpMethod::Lsoda] {
1497            let o = IvpOptions { rtol: 1e-8, atol: 1e-10, ..Default::default() };
1498            let sol = solve_ivp(|_, y: &[f64]| vec![-y[0], -2.0 * y[1]], None::<Jac>, (0.0, 5.0), &[1.0, 1.0], method, o, &[]).unwrap();
1499            let y = sol.y.last().unwrap();
1500            assert!((y[0] - (-5f64).exp()).abs() < 1e-7, "{method:?} {y:?}");
1501            assert!((sol.dense.evaluate(2.3)[0] - (-2.3f64).exp()).abs() < 1e-6, "{method:?} dense");
1502        }
1503    }
1504
1505    #[test]
1506    fn a_terminal_event_stops_at_the_ground() {
1507        // A ball thrown up at 10 m/s from 0 m under gravity: it lands at t = 20/9.81.
1508        let ground = Event { function: Box::new(|_, y: &[f64]| y[0]), direction: -1.0, terminal: Some(1) };
1509        for method in [IvpMethod::Radau, IvpMethod::Lsoda] {
1510            let sol = solve_ivp(|_, y: &[f64]| vec![y[1], -9.81], None::<Jac>, (0.0, 10.0), &[0.0, 10.0], method, IvpOptions::default(), std::slice::from_ref(&ground)).unwrap();
1511            assert_eq!(sol.status, IvpStatus::TerminatedByEvent);
1512            let t = *sol.t.last().unwrap();
1513            // Radau is exact for this quadratic; LSODA starts at order one, accurate to the tolerance.
1514            assert!((t - 20.0 / 9.81).abs() < 1e-6, "{method:?} {t}");
1515        }
1516    }
1517
1518    #[test]
1519    fn lsoda_switches_to_bdf_on_a_stiff_problem() {
1520        // Robertson's chemical kinetics.
1521        let f = |_: f64, y: &[f64]| vec![-0.04 * y[0] + 1e4 * y[1] * y[2], 0.04 * y[0] - 1e4 * y[1] * y[2] - 3e7 * y[1] * y[1], 3e7 * y[1] * y[1]];
1522        let o = IvpOptions { rtol: 1e-6, atol: 1e-10, ..Default::default() };
1523        let sol = solve_ivp(f, None::<Jac>, (0.0, 1e3), &[1.0, 0.0, 0.0], IvpMethod::Lsoda, o, &[]).unwrap();
1524        assert!(sol.switches.iter().any(|s| s.1), "no switch to BDF");
1525        let y = sol.y.last().unwrap();
1526        assert!((y.iter().sum::<f64>() - 1.0).abs() < 1e-6);
1527        assert!(sol.t.len() < 2000, "{} steps", sol.t.len());
1528    }
1529}