Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Radau, LSODA and event location

ProblemSolve accurately whether or not the problem is stiff, evaluate the solution anywhere (dense output), and find the times at which a function crosses zero (events)
Devised byRadau quadrature: Rodolphe Radau (1880); Radau IIA methods: Owe Axelsson (1969), John Butcher (1964); the implementation: Ernst Hairer and Gerhard Wanner (1991); Nordsieck form: Arnold Nordsieck (1962); ODEPACK: Alan Hindmarsh (1980–83); automatic stiffness switching: Linda Petzold (1983); RK45: John Dormand and Peter Prince (1980); DOP853: Ernst Hairer (1993)
AccuracyRadau IIA: order 5, L-stable, dense output of order 3. LSODA: Adams orders 1–12, BDF orders 1–5. Radau matches SciPy step for step; events to machine precision on the interpolant
CostRadau: per step, 1–7 Newton iterations of 3 function evaluations, with one real and one complex LU when the step changes. LSODA: 1–3 evaluations per step, plus an LU in BDF mode
Read firstRunge-Kutta methods, Stiff ODE solvers
APIsolve_ivp, IvpMethod, IvpOptions, Event, IvpSolution, DenseOutput, solve_ivp_explicit, ExplicitMethod, ExplicitOptions; solve_ivp_sparse, SparseJacobian

Overview

The previous entry solved stiff problems with Rosenbrock and BDF methods. This one adds the two stiff solvers of SciPy’s solve_ivp that the library lacked, and the two services that make a solver convenient:

  • Radau IIA of order 5 is an implicit Runge-Kutta method. It is L-stable, so the fastest decaying modes are damped completely, and it is accurate at tight tolerances. Each step costs more than a BDF step, but there are far fewer of them.
  • LSODA needs no decision about stiffness. It starts with Adams methods, which are cheap on non-stiff problems because they need no Jacobian. It switches to BDF when stability, not accuracy, limits the step, and switches back when the problem becomes non-stiff again.
  • Dense output: every step leaves behind a polynomial, so the solution can be evaluated at any time without restricting the steps.
  • Event location: the solver watches functions and reports the times at which they cross zero, such as a ball hitting the ground, and can stop the integration there.

Where it is used

Many systems have fast and slow parts, and solvers must cope without being told which is which.

  • Chemical kinetics and combustion. Reaction rates span many orders of magnitude, which makes the equations stiff.
  • Electrical circuits. Circuit simulators (SPICE) integrate stiff systems of differential-algebraic equations.
  • Event handling. Finding when a ball hits the ground, a valve opens or a satellite enters shadow is event location with dense output.
  • Automatic choice. LSODA switches between stiff and non-stiff methods as the solution changes.

History

Rodolphe Radau (1880) studied quadrature rules that use one end point of the interval; collocation at those points gives the Radau IIA Runge-Kutta methods, analysed by John Butcher (1964) and Owe Axelsson (1969). Ernst Hairer and Gerhard Wanner made the 3-stage method practical in their Fortran code RADAU5 (1991), solving its Newton systems as one real and one complex system, and SciPy’s Radau follows it. Arnold Nordsieck (1962) proposed storing a multistep method’s history as scaled derivatives, which makes changes of step size and order easy. Charles William Gear’s DIFSUB (1971) and Alan Hindmarsh’s LSODE (1980), part of ODEPACK, used this form for Adams and BDF methods of variable order. Linda Petzold (1983) added the switching between them that became LSODA, which SciPy, R’s deSolve and many other packages still call.

The idea

Radau IIA

An -stage implicit Runge-Kutta method finds stage values and sets . Radau IIA chooses the as the zeros of a Radau polynomial, , so that it is the collocation method whose cubic matches the differential equation at those three points. With the method is stiffly accurate, and therefore L-stable: its stability function vanishes at . It has order , and the collocation cubic is the dense output.

The stage equations are nonlinear equations. A simplified Newton iteration, with the Jacobian fixed for the step, would solve systems with the matrix . Hairer and Wanner’s trick diagonalises the matrix . It has one real eigenvalue and a complex pair , so in the transformed variables the system splits into

one real and one complex system, about 5 times cheaper than the full one. The error estimate comes from an embedded formula of order 3, filtered through the real LU so that it stays small for stiff components. The library’s Radau follows SciPy’s code line by line, including its step-size controller, Newton stopping rule and Jacobian reuse, and with the same Jacobian it takes the same steps.

Nordsieck multistep methods

A multistep method of order keeps a polynomial that fits the recent solution. In Nordsieck form the polynomial is stored as scaled derivatives at the current time,

A step predicts by multiplying by the Pascal matrix (Taylor’s theorem for the polynomial), then corrects all components with one vector and one unknown, the correction :

The vector alone decides the method: Adams-Moulton or BDF, of order (Hindmarsh’s cfode computes them). Changing the step by a factor multiplies by . Changing the order adds or drops a component. The local error is a multiple of , and comparing the errors expected at orders , and chooses the order. For Adams methods the corrector is solved by functional iteration, which needs no Jacobian. For BDF, Newton’s method with is used.

Switching on stiffness

Adams methods have small stability regions: at order they are stable only while stays below a constant , from 0.5 at order 1 down to 0.025 at order 12. On a stiff problem this, not accuracy, limits the step. Every few steps LSODA compares two candidate steps:

  • the Adams step allowed by accuracy, cut to the stability bound . In Adams mode, is estimated from the contraction of the functional iteration, so no Jacobian is formed;
  • the BDF step that the same error would allow, from the ratio of the two methods’ error constants.

LSODA switches to BDF when the BDF step is at least 3 times larger (ODEPACK’s ratio is 5; the library’s smaller one is what makes it switch early on the reaction-diffusion chain below, as ODEPACK does, where a ratio of 5 left it with Adams for ten times as many steps), and back to Adams when Adams could take a step as large as BDF. On the Van der Pol oscillator with this happens in every cycle. The fast jumps are non-stiff and the slow stretches stiff:

Figure 2.23. Van der Pol solution.

Figure 2.24. Step sizes.

Over at , Radau takes 688 steps with 5664 function evaluations and 474 LU factorisations; LSODA takes 969 steps with 2056 evaluations, switching method 5 times. Radau takes fewer, longer steps, but each costs about 8 function evaluations against LSODA’s 2. Which is cheaper depends on the cost of against that of the linear algebra.

Dense output and events

Each accepted step defines a polynomial on its interval: Radau’s collocation cubic, or the Nordsieck polynomial with . Together they form a continuous solution of the method’s own order, which DenseOutput::evaluate returns at any time.

An event is a function . After each step it is evaluated at the new point. If its sign has changed (in the requested direction), the root of on the step’s polynomial is found by Brent’s method to machine precision. Events cost no extra steps and never force the step to land on them. A terminal event ends the integration at its root after a given number of occurrences.

Explicit methods: RK45 and DOP853

For problems that are not stiff, an explicit Runge-Kutta method is cheaper per step than either: no Jacobian and no linear algebra. solve_ivp_explicit provides SciPy’s two explicit methods, with the same dense output and events.

  • RK45 (Dormand and Prince, 1980) is SciPy’s default. It takes six stages per step, and the seventh, , is reused as the next step’s first (“first same as last”). The step is of order 5, with an embedded order-4 solution for the error estimate, and a quartic interpolant.
  • DOP853 (Hairer, 1993) has order 8, with twelve stages. Its error estimate blends an order-5 and an order-3 embedded solution, , which stays reliable when one of them is accidentally small. Three extra stages per step give an order-7 interpolant.

Both control the step as SciPy does. A step is accepted when the scaled error norm is below 1, and the step then grows by , but not at all after a rejection. Otherwise it shrinks by . The order is or 7 for the error estimators. A higher order pays off at tight tolerances. On an eccentric orbit, DOP853 needs about two-thirds of RK45’s evaluations for an error of , just over half for , and 40 % for (Figure 2.25).

The explicit solver also integrates backward (), and takes per-component absolute tolerances for states whose components have different scales. The tolerance vector is part of the new ExplicitOptions, so IvpOptions keeps its 2.0 form.

Algorithm

Radau step (from , , with step ):

  1. Predict the stage increments from the previous step’s collocation polynomial (zero at the first step).
  2. Newton iteration in the transformed variables, at most 6 iterations, stopping when the estimated remaining error falls below a tolerance, where is the observed contraction rate. If it diverges, re-evaluate the Jacobian once, then halve .
  3. Error estimate , in the RMS norm scaled by . If it exceeds 1, shrink with the predictive (Gustafsson) controller and retry.
  4. Accept; the next step is the controller’s choice, kept unchanged when the change would be less than 20% (so the LU can be reused). Re-evaluate the Jacobian if the Newton iteration was slow.

LSODA step (order , method Adams or BDF):

  1. Predict by the Pascal matrix.
  2. Correct: up to 3 functional (Adams) or Newton (BDF) iterations for . If they fail to converge, refresh the Jacobian (BDF) or cut by 4.
  3. Error test . On failure, choose the better of orders and , with at most a fifth of the step after two failures, and restart at order 1 after three.
  4. Accept: . Every steps, choose the order and step among , and , and test for a switch of method.

Implementation

    /// Simplified Newton iteration for the stage increments `Z` (SciPy's
    /// `solve_collocation_system`): in the eigenbasis `W = T⁻¹ Z` of the Radau matrix, the 3n × 3n
    /// system splits into one real and one complex n × n system.
    fn solve_collocation(&mut self, h: f64, z0: [Vec<f64>; 3], scale: &[f64]) -> Result<Collocation, ErrorsJSL> {
        let n = self.y.len();
        let (t, y) = (self.t, self.y.clone());
        let k = &self.k;
        let m_real = k.mu_real / h;
        let m_complex = k.mu_complex / h;
        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());
        let mut z = z0;
        let mut dw_norm_old: Option<f64> = None;
        let mut rate: Option<f64> = None;
        let mut converged = false;
        let mut iterations = 0;
        let lu_real = self.lu_real.as_ref().expect("factorised");
        let lu_complex = self.lu_complex.as_ref().expect("factorised");
        for it in 0..NEWTON_MAXITER {
            iterations = it + 1;
            let fs: Vec<Vec<f64>> = (0..3)
                .map(|s| {
                    let ys: Vec<f64> = y.iter().zip(&z[s]).map(|(a, b)| a + b).collect();
                    self.sys.f(t + h * k.c[s], &ys)
                })
                .collect();
            if fs.iter().flatten().any(|v| !v.is_finite()) {
                break;
            }
            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();
            let f_complex: Array1<C> = (0..n)
                .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]))
                .collect();
            let dw_real = lu_real.solve(&f_real).map_err(|_| ErrorsJSL::RuntimeError("Radau solve failed"))?;
            let dw_complex = lu_complex.solve(&f_complex).map_err(|_| ErrorsJSL::RuntimeError("Radau solve failed"))?;
            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()];
            let flat: Vec<f64> = dw.iter().flatten().copied().collect();
            let flat_scale: Vec<f64> = (0..3).flat_map(|_| scale.iter().copied()).collect();
            let dw_norm = rms(&flat, &flat_scale);
            if let Some(old) = dw_norm_old {
                rate = Some(dw_norm / old);
            }
            if let Some(r) = rate
                && (r >= 1.0 || r.powi((NEWTON_MAXITER - it) as i32) / (1.0 - r) * dw_norm > self.newton_tol)
            {
                break;
            }
            for r in 0..3 {
                for i in 0..n {
                    w[r][i] += dw[r][i];
                }
            }
            z = std::array::from_fn(|r| (0..n).map(|i| (0..3).map(|c| k.t[r][c] * w[c][i]).sum()).collect());
            if dw_norm == 0.0 || rate.is_some_and(|r| r / (1.0 - r) * dw_norm < self.newton_tol) {
                converged = true;
                break;
            }
            dw_norm_old = Some(dw_norm);
        }
        Ok((converged, iterations, z, rate))
    }
/// Solves `y' = f(t, y)`, `y(t0) = y0` on `[t0, t1]` (`t1 > t0`) with the given method (SciPy's
/// `solve_ivp`), returning every accepted step, the dense output, and the occurrences of each
/// event. `jac`, if given, returns `∂f/∂y` as rows; otherwise forward differences are used.
///
/// After each step, every event function is evaluated at the new point; where its sign changes
/// in the requested direction, the zero is found by Brent's method on the step's interpolant.
/// A terminal event that reaches its count ends the integration there.
pub 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>
where
    F: Fn(f64, &[f64]) -> Vec<f64>,
    J: Fn(f64, &[f64]) -> Vec<Vec<f64>>,
{
    let (t0, t1) = t_span;
    if y0.is_empty() || !(t1 > t0) || !t0.is_finite() || !t1.is_finite() {
        return Err(ErrorsJSL::InvalidInputRange("need a non-empty state and finite t0 < t1"));
    }
    if !(options.rtol > 0.0) || !(options.atol > 0.0) {
        return Err(ErrorsJSL::InvalidInputRange("tolerances must be positive"));
    }
    let sys = Counter { f: &f, jac: jac.as_ref(), sparse: None, nfev: 0, njev: 0, nlu: 0 };
    let mut stepper: Box<dyn Stepper + '_> = match method {
        IvpMethod::Radau => Box::new(Radau::new(sys, t0, y0, t1, options)),
        IvpMethod::Lsoda => Box::new(Lsoda::new(sys, t0, y0, t1, options)),
    };
    let (ts, ys, status, t_events, y_events, dense) = drive(stepper.as_mut(), t0, t1, y0, events, options.max_steps)?;
    let (nfev, njev, nlu, rejected_steps) = stepper.counts();
    let switches = stepper.switches();
    Ok(IvpSolution { t: ts, y: ys, status, t_events, y_events, dense, nfev, njev, nlu, rejected_steps, switches })
}
    /// SciPy's `RungeKutta._step_impl`: try `h`, accept if the error norm is below 1 and grow the
    /// step by `min(10, 0.9 err^{−1/(q+1)})` (not above 1 after a rejection), otherwise shrink it by
    /// `max(0.2, 0.9 err^{−1/(q+1)})` and retry; the last step is cut to end exactly at `t_bound`.
    fn step(&mut self) -> Result<Segment, ErrorsJSL> {
        let t = self.t;
        let min_step = 10.0 * ((t + self.direction * t.abs().max(f64::MIN_POSITIVE) * f64::EPSILON) - t).abs().max(f64::MIN_POSITIVE);
        let mut h_abs = self.h_abs.min(self.max_step).max(min_step);
        let mut rejected = false;
        loop {
            if h_abs < min_step {
                return Err(ErrorsJSL::RuntimeError("solve_ivp_explicit: the step size became too small"));
            }
            let mut t_new = t + self.direction * h_abs;
            if self.direction * (t_new - self.t_bound) > 0.0 {
                t_new = self.t_bound;
            }
            let h = t_new - t;
            h_abs = h.abs();
            let (y_new, k) = self.rk_step(h);
            let scale: Vec<f64> = (0..y_new.len()).map(|i| self.atol[i] + self.y[i].abs().max(y_new[i].abs()) * self.rtol).collect();
            let err = self.error_norm(&k, h, &scale);
            if err < 1.0 {
                let mut factor = if err == 0.0 { MAX_FACTOR } else { MAX_FACTOR.min(SAFETY * err.powf(self.error_exponent())) };
                if rejected {
                    factor = factor.min(1.0);
                }
                let y_old = std::mem::replace(&mut self.y, y_new);
                let f_new = k[k.len() - 1].clone();
                let f_old = std::mem::replace(&mut self.fy, f_new.clone());
                self.t = t_new;
                self.h_abs = h_abs * factor;
                let coeffs = self.dense(t, &y_old, (&f_old, &f_new), k, h);
                return Ok(Segment { t_start: t.min(t_new), t_end: t.max(t_new), t_ref: t, h, y_ref: y_old, coeffs });
            }
            h_abs *= MIN_FACTOR.max(SAFETY * err.powf(self.error_exponent()));
            self.rejected += 1;
            rejected = true;
        }
    }
  • Radau is a direct port of SciPy’s Radau. Without an analytic Jacobian it uses forward differences instead of SciPy’s adaptive num_jac, so the step sequences then differ slightly.
  • LSODA here is the library’s own implementation of Petzold’s scheme, with ODEPACK’s coefficients and step and order rules. It is not a port of the Fortran code, whose many heuristics SciPy calls directly, so its steps differ from SciPy’s.
  • solve_ivp (Radau, LSODA) integrates forward in time only, with scalar tolerances. solve_ivp_explicit (RK45, DOP853) integrates in either direction, with per-component absolute tolerances.
  • RK45 and DOP853 are step-for-step ports of SciPy’s classes, with coefficient tables generated from SciPy’s own. DOP853 always computes its three interpolation stages. SciPy computes them only when dense output is requested or an event changes sign in the step, so its evaluation counts are lower without dense output.

In practice

Both methods are compared with scipy.integrate.solve_ivp (SciPy 1.17.1; references from book/generator/data/make_ivp_refs.py) on two stiff problems and a non-stiff one. The errors are relative to a reference solution at , and :

Table 2.20. Radau and LSODA against SciPy.

problemmethodrtolsteps (library / SciPy)f evaluations (library / SciPy)final error (library / SciPy)method switches
Van der Pol, μ = 100 (stiff)Radau1e-4236 / 2362152 / 21521e-6 / 1e-6
Van der Pol, μ = 100 (stiff)Radau1e-71202 / 12029586 / 95861e-10 / 1e-10
Van der Pol, μ = 100 (stiff)LSODA1e-4512 / 5191179 / 10356e-4 / 4e-45
Van der Pol, μ = 100 (stiff)LSODA1e-71085 / 12212282 / 21457e-7 / 6e-75
Robertson kinetics (stiff)Radau1e-462 / 62535 / 5353e-8 / 3e-8
Robertson kinetics (stiff)Radau1e-7304 / 3042319 / 23196e-11 / 6e-11
Robertson kinetics (stiff)LSODA1e-4192 / 182352 / 2446e-6 / 5e-61
Robertson kinetics (stiff)LSODA1e-7438 / 602869 / 9242e-8 / 3e-91
Arenstorf orbit (non-stiff)Radau1e-4181 / 1811565 / 14619e-3 / 9e-3
Arenstorf orbit (non-stiff)Radau1e-7995 / 9958186 / 81582e-6 / 2e-6
Arenstorf orbit (non-stiff)LSODA1e-4270 / 403547 / 7531e0 / 9e-12
Arenstorf orbit (non-stiff)LSODA1e-7604 / 7591185 / 16334e-3 / 3e-50

With analytic Jacobians, Radau takes exactly SciPy’s steps and reaches the same errors. LSODA’s costs are within a factor of two of ODEPACK’s, sometimes lower. Its errors are similar on Van der Pol, but several times larger on Robertson’s problem and more than a hundred times larger on the Arenstorf orbit at . That orbit amplifies any local error by orders of magnitude along the trajectory. Neither LSODA handles Arenstorf at . The orbit needs a tight tolerance or a high-order explicit method.

Table 2.21. Event location against reference event times.

eventmethodevents foundlargest time error (library)largest time error (SciPy)
Arenstorf orbit: every crossing of y = 0 (6 in the reference)Radau6 (SciPy 6)1e-71e-7
Arenstorf orbit: every crossing of y = 0 (6 in the reference)LSODA7 (SciPy 7)2e-48e-6
Van der Pol: first time x falls through −1.5 (terminal)Radau13e-93e-9
Van der Pol: first time x falls through −1.5 (terminal)LSODA14e-54e-5

Events are located on the interpolant to machine precision, so their errors are the solution’s errors. Radau’s and SciPy’s Radau agree to all digits. The LSODA runs both find a spurious seventh crossing, because the orbit has drifted by the end.

The explicit methods were run on Van der Pol with μ = 2, the Lorenz system, a Kepler orbit and Van der Pol integrated backwards, at three tolerances, against SciPy with dense output:

Table 2.22. RK45 and DOP853 against SciPy.

method and tolerance (atol = rtol/1000)steps, 4 problems (library / SciPy)function evaluationsproblems with identical steps and evaluationsfinal state (relative)dense output (relative)
RK45, rtol = 10⁻³169 / 1691256 / 12564 of 41e-91e-11
RK45, rtol = 10⁻⁶559 / 5593956 / 39564 of 42e-121e-13
RK45, rtol = 10⁻¹⁰3382 / 338220828 / 208284 of 42e-137e-14
DOP853, rtol = 10⁻³114 / 1142066 / 20664 of 42e-92e-9
DOP853, rtol = 10⁻⁶212 / 2123872 / 38724 of 42e-121e-11
DOP853, rtol = 10⁻¹⁰598 / 59710490 / 104513 of 41e-102e-10

In 23 of the 24 runs the step sequences are identical to SciPy’s. In the 24th, DOP853 at , rounding differences tip one step decision the other way, after which the runs drift apart by the tolerance. Events and per-component tolerances:

Table 2.23. Events and per-component tolerances with the explicit methods.

casefunction evaluations (library / SciPy)difference (relative)
DOP853, a falling body with quadratic drag: the landing time (terminal event)425 / 3651e-13
RK45, Van der Pol with atol = (10⁻⁹, 10⁻³): the final state1286 / 12861e-15

The landing time agrees to . The library’s count is higher because it builds DOP853’s interpolant on every step (see Implementation).

Figure 2.25. Work and precision on a Kepler orbit with eccentricity 0.6, over one period, for tolerances from 10⁻³ to 10⁻¹². SciPy's results (markers) fall on the library's (lines). For more than about 300 evaluations, DOP853 is 20 to 200 times more accurate than RK45 at the same cost.

Sparse Jacobians

Large stiff systems, such as discretised partial differential equations, have sparse Jacobians. solve_ivp_sparse takes either a function returning as a sparse matrix, or only its sparsity pattern (SciPy’s jac_sparsity).

  • Finite differences from a pattern. Columns are grouped so that no two columns in a group share a row (Curtis, Powell and Reid, 1974). One evaluation of then differences every column of a group, so a tridiagonal Jacobian costs three evaluations instead of .
  • Sparse factorisations. The Newton matrices are factorised by the library’s sparse LU with a minimum-degree ordering. Radau’s complex matrix becomes the real matrix , which is just as sparse.
/// [`solve_ivp`] for large stiff systems with sparse Jacobians (SciPy's `solve_ivp` with a sparse
/// `jac` or with `jac_sparsity`). The Newton matrices of Radau (`μ/h · I − J`, real and complex)
/// and of LSODA's BDF corrector (`I − h l₀ J`) are factorised by the sparse LU
/// ([`SparseLu`], minimum-degree ordering); Radau's complex system is solved in its real form
/// of twice the size. With [`SparseJacobian::Pattern`], the Jacobian is estimated by grouped
/// forward differences: columns sharing no row are perturbed together (Curtis, Powell and Reid),
/// so a banded `n × n` Jacobian costs a few evaluations of `f` instead of `n`.
pub fn solve_ivp_sparse<F>(f: F, jac: SparseJacobian, t_span: (f64, f64), y0: &[f64], method: IvpMethod, options: IvpOptions, events: &[Event]) -> Result<IvpSolution, ErrorsJSL>
where
    F: Fn(f64, &[f64]) -> Vec<f64>,
{
    let (t0, t1) = t_span;
    if y0.is_empty() || !(t1 > t0) || !t0.is_finite() || !t1.is_finite() {
        return Err(ErrorsJSL::InvalidInputRange("need a non-empty state and finite t0 < t1"));
    }
    if !(options.rtol > 0.0) || !(options.atol > 0.0) {
        return Err(ErrorsJSL::InvalidInputRange("tolerances must be positive"));
    }
    if let SparseJacobian::Pattern(p) = &jac
        && (p.nrows != y0.len() || p.ncols != y0.len())
    {
        return Err(ErrorsJSL::IncompatibleArraySizes((p.nrows, y0.len())));
    }
    let sys: Counter<'_, F, DenseJacFn> = Counter { f: &f, jac: None, sparse: Some(&jac), nfev: 0, njev: 0, nlu: 0 };
    let mut stepper: Box<dyn Stepper + '_> = match method {
        IvpMethod::Radau => Box::new(Radau::new(sys, t0, y0, t1, options)),
        IvpMethod::Lsoda => Box::new(Lsoda::new(sys, t0, y0, t1, options)),
    };
    let (ts, ys, status, t_events, y_events, dense) = drive(stepper.as_mut(), t0, t1, y0, events, options.max_steps)?;
    let (nfev, njev, nlu, rejected_steps) = stepper.counts();
    let switches = stepper.switches();
    Ok(IvpSolution { t: ts, y: ys, status, t_events, y_events, dense, nfev, njev, nlu, rejected_steps, switches })
}

Table 2.24. A stiff reaction-diffusion chain with 200 unknowns and a tridiagonal Jacobian, against SciPy.

Stiff reaction-diffusion chainFinal state vs SciPy (relative)Library steps / Jacobians / LUsSciPy steps / Jacobians / LUsLibrary f evaluations, sparse vs dense
Radau, n = 2002e-1635 / 3 / 1435 / 3 / 14265 vs 856 dense
LSODA, n = 2009e-978 / 3 / 978 / 6 / 6152 vs 743 dense
  • Radau repeats SciPy’s run exactly: the same steps, Jacobians and factorisations, with the final state to rounding. The grouped differences cut the evaluations of from 856 to 265. SciPy does not count its finite-difference evaluations in nfev, so its count is not shown.
  • LSODA: SciPy’s ignores jac_sparsity. Both take 78 steps, switching to BDF after about 20 of them; the library forms 3 Jacobians against SciPy’s 6 and its final state agrees with SciPy’s to (both are accurate to the tolerance , so this measures their different rounding and step histories, not an error).

Strengths

  • Radau: L-stable, order 5, efficient at tight tolerances on stiff problems and on problems with eigenvalues near the imaginary axis.
  • LSODA: no need to classify the problem, and cheap per step. Non-stiff stretches run without forming any Jacobian.
  • Dense output and events with every method, at no extra cost in steps.

Weaknesses

  • Radau’s step costs grow quickly with when the Jacobian is dense (two LUs per step change, one of them complex); for sparse systems use solve_ivp_sparse.
  • The library’s LSODA is not ODEPACK. On some problems its step and order heuristics are less economical or less accurate.
  • Backward integration and vector tolerances only with the explicit methods; no mass matrices.

Exercises

  1. Show that the stability function of Radau IIA tends to zero as , using (stiff accuracy).
  2. Derive the Nordsieck vector for the trapezoidal rule (Adams-Moulton of order 2) and check .
  3. Show that rescaling the Nordsieck array by represents the same polynomial with step .
  4. Estimate when the Van der Pol oscillator is stiff from the eigenvalues of its Jacobian on the slow branch, and compare with the switching times in the figure.
  5. A ball bounces with a coefficient of restitution of 0.8. Use a terminal event to stop at each impact, restart with the reflected velocity multiplied by 0.8, and check that the times between impacts shrink by the factor 0.8.
Hints and answers
  1. The stability function is . For a stiffly accurate method, is the last row of , so , which tends to .
  2. With , , , the trapezoidal rule with the quadratic predictor gives , , and the second derivative changes by , so .
  3. with and is unchanged.
  4. On the slow branch , the Jacobian has an eigenvalue near , which is large for . Adams at order then needs , a few hundredths, while accuracy alone would allow steps of order 1.
  5. Each flight lasts with , so the flight times form a geometric series with ratio 0.8.

Further reading

  • E. Hairer and G. Wanner, Solving Ordinary Differential Equations II: Stiff and Differential-Algebraic Problems, 2nd ed., Springer, 1996.
  • A. C. Hindmarsh, “ODEPACK, a systematized collection of ODE solvers”, in Scientific Computing, North-Holland, 1983, 55–64.
  • L. R. Petzold, “Automatic selection of methods for solving stiff and nonstiff systems of ordinary differential equations”, SIAM Journal on Scientific and Statistical Computing 4 (1983) 136–148.
  • L. F. Shampine and M. W. Reichelt, “The MATLAB ODE suite”, SIAM Journal on Scientific Computing 18 (1997) 1–22.
  • E. Hairer, S. P. Nørsett and G. Wanner, Solving Ordinary Differential Equations I: Nonstiff Problems, 2nd ed., Springer, 1993, section II.6 (dense output).