Skip to main content

outram_foam_basic_lib/ode/
mod.rs

1// SPDX-License-Identifier: GPL-3.0-only
2// Copyright (C) 2026 OUTRAM PARK contributors
3// Derived from OpenFOAM (www.openfoam.com)
4// Copyright (C) 2004-2023 OpenFOAM Foundation
5// Copyright (C) 2016-2023 OpenCFD Ltd.
6//
7// This file is part of OUTRAM PARK.
8//
9// OUTRAM PARK is free software: you can redistribute it and/or modify it
10// under the terms of the GNU General Public License as published by the
11// Free Software Foundation, either version 3 of the License, or (at your
12// option) any later version.
13//
14// OUTRAM PARK is distributed in the hope that it will be useful, but
15// WITHOUT ANY WARRANTY; without even the implied warranty of
16// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17// General Public License for more details.
18//
19// You should have received a copy of the GNU General Public License along
20// with OUTRAM PARK.  If not, see <https://www.gnu.org/licenses/>.
21
22//! Ordinary differential equation solvers for systems `dy/dx = f(x, y)`.
23//!
24//! Ports the OpenFOAM `ODE` layer: user systems implement the [`OdeSystem`](crate::ode::OdeSystem)
25//! trait, and one of the concrete steppers integrates them with adaptive step
26//! control — [`Euler`](crate::ode::euler::Euler) (explicit 1st order),
27//! [`Rkf45`](crate::ode::rkf45::Rkf45) (explicit Runge-Kutta-Fehlberg 4(5)), and
28//! [`Rosenbrock23`](crate::ode::rosenbrock23::Rosenbrock23) (semi-implicit, for stiff systems,
29//! requiring a Jacobian). The independent variable `x`, state `y`, and step
30//! size are bare `f64` in the caller's own units; tolerances are set through
31//! [`OdeSolverConfig`](crate::ode::OdeSolverConfig).
32//!
33//! # Storing an integrator: [`OdeIntegrator`](crate::ode::integrator::OdeIntegrator)
34//!
35//! The three steppers above take the system by reference on every call, which
36//! is awkward for any caller that wants to *keep* "the integrator for this
37//! material point" as a struct field — storing a borrow would force a lifetime
38//! parameter, which the workspace design rules forbid.
39//!
40//! [`integrator`](crate::ode::integrator) solves that with two enums that own
41//! what they integrate: [`OdeSolver`](crate::ode::integrator::OdeSolver) selects
42//! the stepper, and
43//! [`OdeIntegrator`](crate::ode::integrator::OdeIntegrator) selects how the
44//! system is supplied —
45//! [`OdeIntegrator::TypedState`](crate::ode::integrator::OdeIntegrator::TypedState)
46//! (a concrete system owned
47//! by value, statically dispatched, **preferred**) or
48//! [`OdeIntegrator::DynSystem`](crate::ode::integrator::OdeIntegrator::DynSystem)
49//! (an `Arc<dyn OdeSystem + Send + Sync>`, kept by
50//! maintainer decision for flexibility). Neither borrows, so neither needs a
51//! lifetime.
52
53pub mod euler;
54pub mod integrator;
55pub mod parallel;
56pub mod rkf45;
57pub mod rosenbrock23;
58
59pub use euler::Euler;
60pub use integrator::{
61    DynSystemIntegrator, NoTypedSystem, OdeIntegrator, OdeSolver, SharedOdeSystem,
62    TypedStateIntegrator,
63};
64pub use parallel::{
65    adaptive_quadrature_batch, ensemble_backend_for, integrate_ensemble, integrate_ensemble_mixed,
66    quadrature_backend_for, quadrature_batch, AdaptiveSettings, GaussOrder, OdeEnsemble,
67    OdeEnsembleFailure, OdeLane, OdeLaneSolution, OdeLaneStatus, QuadratureBatch,
68    QuadratureBatchFailure, QuadratureInterval, QuadratureRule, QuadratureSolution,
69    QuadratureStatus,
70};
71pub use rkf45::Rkf45;
72pub use rosenbrock23::Rosenbrock23;
73
74use crate::matrix::SquareMatrix;
75
76// ── ODE system trait ─────────────────────────────────────────────────────────
77
78/// Abstract ODE system `dy/dx = f(x, y)`. Maps to `Foam::ODESystem`.
79pub trait OdeSystem {
80    /// Number of coupled equations (the length of the state vector `y`).
81    fn n_eqns(&self) -> usize;
82
83    /// Fill `dydx` with the derivatives at `(x, y)`.
84    fn derivatives(&self, x: f64, y: &[f64], dydx: &mut Vec<f64>);
85
86    /// Fill `dfdx` and `dfdy` with the Jacobian at `(x, y)`.
87    ///
88    /// Required only by stiff solvers (Rosenbrock23). The default panics.
89    fn jacobian(&self, _x: f64, _y: &[f64], _dfdx: &mut Vec<f64>, _dfdy: &mut SquareMatrix) {
90        unimplemented!("jacobian not implemented for this ODE system");
91    }
92}
93
94// ── Solver configuration ─────────────────────────────────────────────────────
95
96/// Common parameters for the adaptive step-size controller.
97/// Defaults match `Foam::adaptiveSolver` and `Foam::ODESolver`.
98#[derive(Debug, Clone)]
99pub struct OdeSolverConfig {
100    /// Absolute per-equation tolerance.
101    pub abs_tol: f64,
102    /// Relative per-equation tolerance.
103    pub rel_tol: f64,
104    /// Safety factor on the step-size scaling (0 < safeScale < 1).
105    pub safe_scale: f64,
106    /// Exponent for step *increase*.
107    pub alpha_inc: f64,
108    /// Exponent for step *decrease*.
109    pub alpha_dec: f64,
110    /// Minimum scale factor applied per step.
111    pub min_scale: f64,
112    /// Maximum scale factor applied per step.
113    pub max_scale: f64,
114    /// Maximum sub-steps for one `integrate()` call.
115    pub max_steps: usize,
116}
117
118impl Default for OdeSolverConfig {
119    fn default() -> Self {
120        Self {
121            abs_tol: 1e-6,
122            rel_tol: 1e-4,
123            safe_scale: 0.9,
124            alpha_inc: 0.2,
125            alpha_dec: 0.25,
126            min_scale: 0.2,
127            max_scale: 10.0,
128            max_steps: 10_000,
129        }
130    }
131}
132
133// ── Error type ───────────────────────────────────────────────────────────────
134
135/// Failure modes of an adaptive integration.
136#[derive(Debug, Clone, PartialEq)]
137pub enum OdeError {
138    /// The step size shrank below machine epsilon while trying to meet the
139    /// error tolerance — the system is too stiff for the chosen solver, or the
140    /// tolerances are unattainable.
141    StepSizeUnderflow,
142    /// The interval could not be spanned within `max_steps` sub-steps; carries
143    /// the number of steps taken.
144    MaxStepsExceeded(usize),
145    /// The system produced a non-finite (NaN or infinite) error estimate, so
146    /// the state cannot be trusted and integration stopped.
147    ///
148    /// The usual cause is `derivatives` or `jacobian` returning a non-finite
149    /// value — for example a numerically-differenced Jacobian
150    /// ([`crate::math::differentiate::NumericalJacobian`]) that could not form
151    /// a column, or an evaluation that left the model's valid range.
152    ///
153    /// # Why this variant exists
154    ///
155    /// Before bead `op-ad6h` this case did not error at all: it returned
156    /// `Ok(())` with a NaN state, because the per-equation error fold used
157    /// `f64::max`, which discards NaN. A wrong answer reported as success is
158    /// the worst failure mode available to a solver, so it is now a distinct
159    /// error rather than being folded into
160    /// [`StepSizeUnderflow`](Self::StepSizeUnderflow), which would have named
161    /// the wrong cause.
162    NonFiniteState,
163}
164
165impl std::fmt::Display for OdeError {
166    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
167        match self {
168            Self::StepSizeUnderflow => write!(f, "ODE step size underflow"),
169            Self::MaxStepsExceeded(n) => write!(f, "ODE exceeded {n} steps"),
170            Self::NonFiniteState => write!(
171                f,
172                "ODE produced a non-finite error estimate (NaN or infinite state)"
173            ),
174        }
175    }
176}
177
178impl std::error::Error for OdeError {}
179
180// ── Shared utilities ─────────────────────────────────────────────────────────
181
182/// Normalised scalar error — max over all equations.
183/// Maps to `Foam::ODESolver::normalizeError`.
184pub(crate) fn normalize_error(
185    y0: &[f64],
186    y: &[f64],
187    err: &[f64],
188    abs_tol: f64,
189    rel_tol: f64,
190) -> f64 {
191    err.iter()
192        .zip(y0)
193        .zip(y)
194        .map(|((e, &a), &b)| {
195            let tol = abs_tol + rel_tol * a.abs().max(b.abs());
196            e.abs() / tol
197        })
198        // NB: `fold(0.0, f64::max)` here was a silent-wrong-answer bug
199        // (bead `op-ad6h`). Rust's `f64::max` follows IEEE-754 `maxNum` and
200        // DISCARDS a NaN operand, so `f64::max(0.0, NaN) == 0.0`: a NaN error
201        // read as *zero* error, the step was accepted as perfectly converged,
202        // and `integrate` returned `Ok(())` with a NaN state. Returning NaN
203        // instead would not fix it either, because the caller's accept test is
204        // `err <= 1.0` and every comparison against NaN is false — the step
205        // would be rejected, but `dx` would then shrink to underflow with no
206        // indication of why.
207        //
208        // So a non-finite error is reported as `INFINITY`, which is both true
209        // ("this step is unboundedly bad") and actionable: the caller rejects
210        // it and, per the check in `adaptive_step`, returns
211        // `OdeError::NonFiniteState` rather than a misleading
212        // `StepSizeUnderflow`.
213        .fold(0.0_f64, |acc, e| {
214            if e.is_nan() || acc.is_nan() {
215                f64::INFINITY
216            } else {
217                acc.max(e)
218            }
219        })
220}
221
222/// Adaptive step-size loop shared by all explicit solvers.
223///
224/// Calls `inner_step(x0, y0, dydx0, dx, y_out) -> err`, retrying with a
225/// smaller `dx` whenever `err > 1`. Updates `x`, `y`, and `dx_try`.
226/// Matches `Foam::adaptiveSolver::solve`.
227pub(crate) fn adaptive_step<Sys: OdeSystem + ?Sized>(
228    cfg: &OdeSolverConfig,
229    mut inner_step: impl FnMut(f64, &[f64], &[f64], f64, &mut Vec<f64>) -> f64,
230    ode: &Sys,
231    x: &mut f64,
232    y: &mut Vec<f64>,
233    dydx0: &mut Vec<f64>,
234    y_temp: &mut Vec<f64>,
235    dx_try: &mut f64,
236) -> Result<(), OdeError> {
237    let mut dx = *dx_try;
238    ode.derivatives(*x, y, dydx0);
239
240    let err = loop {
241        let err = inner_step(*x, y, dydx0, dx, y_temp);
242        // A non-finite error means the system produced NaN or an infinite
243        // value; shrinking `dx` cannot recover from that, so fail immediately
244        // and name the real cause instead of grinding down to a misleading
245        // `StepSizeUnderflow`. See `OdeError::NonFiniteState` and bead
246        // `op-ad6h`.
247        if !err.is_finite() {
248            return Err(OdeError::NonFiniteState);
249        }
250        if err <= 1.0 {
251            break err;
252        }
253        let scale = (cfg.safe_scale * err.powf(-cfg.alpha_dec)).max(cfg.min_scale);
254        dx *= scale;
255        if dx.abs() < f64::EPSILON {
256            return Err(OdeError::StepSizeUnderflow);
257        }
258    };
259
260    *x += dx;
261    std::mem::swap(y, y_temp);
262
263    let threshold = (cfg.max_scale / cfg.safe_scale).powf(-1.0 / cfg.alpha_inc);
264    *dx_try = if err > threshold {
265        let scale = (cfg.safe_scale * err.powf(-cfg.alpha_inc)).clamp(cfg.min_scale, cfg.max_scale);
266        dx * scale
267    } else {
268        dx * cfg.safe_scale * cfg.max_scale
269    };
270
271    Ok(())
272}
273
274/// Integrate from `x_start` to `x_end` using repeated adaptive steps.
275pub(crate) fn integrate_interval(
276    cfg: &OdeSolverConfig,
277    step_fn: &mut dyn FnMut(&mut f64, &mut Vec<f64>, &mut f64) -> Result<(), OdeError>,
278    x_start: f64,
279    x_end: f64,
280    y: &mut Vec<f64>,
281    dx_est: &mut f64,
282) -> Result<(), OdeError> {
283    let mut x = x_start;
284    let mut dx = *dx_est;
285    let mut n_steps = 0usize;
286
287    while x < x_end {
288        let dx_try = (x + dx).min(x_end) - x;
289        let mut dx_limited = dx_try;
290        step_fn(&mut x, y, &mut dx_limited)?;
291        dx = dx_limited;
292        n_steps += 1;
293        if n_steps > cfg.max_steps {
294            return Err(OdeError::MaxStepsExceeded(n_steps));
295        }
296    }
297
298    *dx_est = dx;
299    Ok(())
300}