Skip to main content

lib_jsl_derivatives/
adaptive.rs

1//! Adaptive derivatives with error estimates by Richardson extrapolation (Ridders' method), the
2//! counterpart of `scipy.differentiate.derivative`, `jacobian` and `hessian`.
3//!
4//! Central differences with a decreasing sequence of steps `h, h/c, h/c², …` are combined in a
5//! Neville tableau that cancels the even powers of `h` in their truncation error. The entry whose
6//! change from its neighbours is smallest is returned, with that change as the error estimate,
7//! and the iteration stops when rounding error starts to dominate.
8//!
9//! See the book entry [Adaptive derivatives](https://jwkunz.github.io/lib_jsl/book/derivatives/adaptive.html).
10
11// Guards such as `!(x > 0.0)` are deliberate: unlike `x <= 0.0` they also reject NaN.
12#![allow(clippy::neg_cmp_op_on_partial_ord)]
13#![allow(clippy::needless_range_loop)]
14
15use lib_jsl_core::ErrorsJSL;
16
17/// Options for [`derivative`].
18#[derive(Clone, Copy, Debug)]
19pub struct DerivativeOptions {
20    /// The first (largest) step `h`, absolute.
21    pub initial_step: f64,
22    /// Each step is the previous divided by this factor (> 1).
23    pub step_factor: f64,
24    /// The largest number of steps (tableau rows).
25    pub max_iterations: usize,
26    /// Stop once the error estimate is below `atol + rtol |f'|`.
27    pub atol: f64,
28    pub rtol: f64,
29}
30
31impl Default for DerivativeOptions {
32    /// SciPy's defaults for the step: 0.5, reduced by factors of 2, at most 10 times.
33    fn default() -> Self {
34        DerivativeOptions { initial_step: 0.5, step_factor: 2.0, max_iterations: 10, atol: 0.0, rtol: f64::EPSILON.sqrt() * 1e-3 }
35    }
36}
37
38/// The result of [`derivative`].
39#[derive(Clone, Copy, Debug)]
40#[non_exhaustive]
41pub struct DerivativeResult {
42    pub df: f64,
43    /// The estimated absolute error.
44    pub error: f64,
45    /// Evaluations of the function.
46    pub nfev: usize,
47    /// `true` when the tolerance was met.
48    pub converged: bool,
49}
50
51// ANCHOR: ridders
52/// `f'(x)` with an error estimate, by Ridders' extrapolation of central differences.
53///
54/// Row `i` of the tableau starts from `D(hᵢ) = (f(x + hᵢ) − f(x − hᵢ)) / 2hᵢ` with `hᵢ = h/cⁱ`; each
55/// column `j` removes the next even power of `h`: `T(i, j) = (c^{2j} T(i, j−1) − T(i−1, j−1)) /
56/// (c^{2j} − 1)`. The best estimate is the entry whose difference from its two parents is
57/// smallest. Extrapolation stops when the diagonal grows by more than twice the best error, the
58/// sign that rounding error dominates.
59pub fn derivative(f: impl Fn(f64) -> f64, x: f64, options: DerivativeOptions) -> Result<DerivativeResult, ErrorsJSL> {
60    if !x.is_finite() || !(options.initial_step > 0.0) || !(options.step_factor > 1.0) || options.max_iterations == 0 {
61        return Err(ErrorsJSL::InvalidInputRange("need a finite point, a positive step and a step factor above 1"));
62    }
63    let c2 = options.step_factor * options.step_factor;
64    let mut h = options.initial_step;
65    let mut nfev = 0;
66    let mut central = |h: f64| {
67        nfev += 2;
68        (f(x + h) - f(x - h)) / (2.0 * h)
69    };
70    let mut prev_row = vec![central(h)];
71    let (mut best, mut err) = (prev_row[0], f64::INFINITY);
72    for iteration in 1..options.max_iterations {
73        h /= options.step_factor;
74        let mut row = vec![central(h)];
75        let mut fac = c2;
76        for j in 1..=prev_row.len() {
77            let t = (row[j - 1] * fac - prev_row[j - 1]) / (fac - 1.0);
78            fac *= c2;
79            let errt = (t - row[j - 1]).abs().max((t - prev_row[j - 1]).abs());
80            if errt <= err {
81                err = errt;
82                best = t;
83            }
84            row.push(t);
85        }
86        // The divergence test is meaningful only once the steps are small enough for the
87        // extrapolation to have converged at least roughly: after a few rows.
88        // Stop on divergence only once the estimate is already fairly accurate: early rows from a
89        // step that is too large for the function are inaccurate rather than noisy.
90        let diverging = iteration >= 3 && err <= f64::EPSILON.sqrt() * best.abs().max(1e-300) && (row[row.len() - 1] - prev_row[prev_row.len() - 1]).abs() >= 2.0 * err;
91        prev_row = row;
92        if err <= options.atol + options.rtol * best.abs() || diverging {
93            break;
94        }
95    }
96    Ok(DerivativeResult { df: best, error: err, nfev, converged: err <= options.atol + options.rtol * best.abs() || err.is_finite() && err <= 1e-8 * best.abs().max(1.0) })
97}
98// ANCHOR_END: ridders
99
100/// The Jacobian `Jᵢⱼ = ∂fᵢ/∂xⱼ` of `f: ℝⁿ → ℝᵐ`, each column by Ridders' method on the
101/// coordinate direction (as `scipy.differentiate.jacobian`), with the largest error estimate.
102pub fn jacobian(f: impl Fn(&[f64]) -> Vec<f64>, x: &[f64], options: DerivativeOptions) -> Result<(Vec<Vec<f64>>, f64), ErrorsJSL> {
103    let m = f(x).len();
104    let n = x.len();
105    let mut jac = vec![vec![0.0; n]; m];
106    let mut worst: f64 = 0.0;
107    for j in 0..n {
108        for (i, row) in jac.iter_mut().enumerate() {
109            let g = |t: f64| {
110                let mut z = x.to_vec();
111                z[j] = t;
112                f(&z)[i]
113            };
114            let r = derivative(g, x[j], options)?;
115            row[j] = r.df;
116            worst = worst.max(r.error);
117        }
118    }
119    Ok((jac, worst))
120}
121
122/// The Hessian `Hᵢⱼ = ∂²f/∂xᵢ∂xⱼ` of `f: ℝⁿ → ℝ`, as the Jacobian of the gradient, both by
123/// Ridders' method (as `scipy.differentiate.hessian`), symmetrised.
124pub fn hessian(f: impl Fn(&[f64]) -> f64, x: &[f64], options: DerivativeOptions) -> Result<Vec<Vec<f64>>, ErrorsJSL> {
125    let n = x.len();
126    let inner = DerivativeOptions { initial_step: options.initial_step / 4.0, ..options };
127    let grad = |z: &[f64]| -> Vec<f64> {
128        (0..n)
129            .map(|i| {
130                derivative(
131                    |t| {
132                        let mut w = z.to_vec();
133                        w[i] = t;
134                        f(&w)
135                    },
136                    z[i],
137                    inner,
138                )
139                .map(|r| r.df)
140                .unwrap_or(f64::NAN)
141            })
142            .collect()
143    };
144    let (mut h, _) = jacobian(grad, x, options)?;
145    for i in 0..n {
146        for j in 0..i {
147            let s = 0.5 * (h[i][j] + h[j][i]);
148            h[i][j] = s;
149            h[j][i] = s;
150        }
151    }
152    Ok(h)
153}
154
155#[cfg(test)]
156mod tests {
157    use super::*;
158
159    #[test]
160    fn derivatives_of_smooth_functions_are_near_machine_precision() {
161        for &x in &[0.3, 1.0, 2.7] {
162            let r = derivative(f64::exp, x, DerivativeOptions::default()).unwrap();
163            assert!((r.df - x.exp()).abs() < 1e-12 * x.exp(), "{x}: {:?}", r);
164            assert!(r.error < 1e-9 * x.exp());
165            let r = derivative(|t| (3.0 * t).sin(), x, DerivativeOptions::default()).unwrap();
166            assert!((r.df - 3.0 * (3.0 * x).cos()).abs() < 1e-11);
167        }
168    }
169
170    #[test]
171    fn jacobian_and_hessian_of_simple_maps() {
172        let f = |v: &[f64]| vec![v[0] * v[1], v[0].sin() + v[1] * v[1]];
173        let (j, _) = jacobian(f, &[0.5, 2.0], DerivativeOptions::default()).unwrap();
174        let want = [[2.0, 0.5], [0.5f64.cos(), 4.0]];
175        for i in 0..2 {
176            for k in 0..2 {
177                assert!((j[i][k] - want[i][k]).abs() < 1e-11);
178            }
179        }
180        let h = hessian(|v: &[f64]| v[0] * v[0] * v[1] + v[1].exp(), &[1.5, 0.5], DerivativeOptions::default()).unwrap();
181        let want = [[2.0 * 0.5, 2.0 * 1.5], [2.0 * 1.5, 0.5f64.exp()]];
182        for i in 0..2 {
183            for k in 0..2 {
184                assert!((h[i][k] - want[i][k]).abs() < 1e-8, "{h:?}");
185            }
186        }
187    }
188}