Skip to main content

lib_jsl_root_finding/
newton_krylov.rs

1//! Jacobian-free Newton-Krylov for large nonlinear systems `F(x) = 0` (SciPy's
2//! `optimize.newton_krylov`): each Newton correction is found by a Krylov solver that needs only
3//! products of the Jacobian with vectors, which are approximated by one difference of `F` each.
4//!
5//! See the book entry [Nonlinear systems](https://jwkunz.github.io/lib_jsl/book/root_finding/nonlinear-systems.html#jacobian-free-newton-krylov).
6
7use lib_jsl_core::ErrorsJSL;
8use lib_jsl_linalg::sparse::{IterativeOptions, LgmresSolver, LinearOperator, bicgstab, gmres};
9use std::cell::{Cell, RefCell};
10
11/// The Krylov solver for the Newton corrections.
12#[derive(Clone, Copy, Debug, PartialEq, Eq)]
13#[non_exhaustive]
14pub enum InnerSolver {
15    /// GMRES, one cycle of `inner_maxiter` steps (SciPy's `method='gmres'`).
16    Gmres,
17    /// BiCGSTAB, at most `inner_maxiter` steps of two products each (`method='bicgstab'`).
18    Bicgstab,
19    /// LGMRES (SciPy's default inner solver): one cycle of 30 Krylov steps, augmented by up to 10
20    /// earlier Newton corrections, which are kept from one Newton iteration to the next and put
21    /// first in the subspace (SciPy's `outer_k=10`, `prepend_outer_v=True`,
22    /// `store_outer_Av=False`). `inner_maxiter` does not apply.
23    Lgmres,
24}
25
26/// Options for [`newton_krylov`] (SciPy's defaults). The iteration stops when
27/// `‖F‖∞ ≤ f_tol` and `‖F‖∞ ≤ f_rtol ‖F(x₀)‖∞`, and the last correction `dx` satisfies
28/// `‖dx‖∞ ≤ x_tol` and `‖dx‖∞ ≤ x_rtol ‖x‖∞`.
29#[derive(Clone, Copy, Debug)]
30pub struct NewtonKrylovOptions {
31    /// Default `ε^{1/3} ≈ 6 × 10⁻⁶`.
32    pub f_tol: f64,
33    pub f_rtol: f64,
34    pub x_tol: f64,
35    pub x_rtol: f64,
36    /// The most Newton iterations; default `100 (n + 1)`.
37    pub max_iter: Option<usize>,
38    /// Steps of the inner Krylov solver per Newton iteration.
39    pub inner_maxiter: usize,
40    /// The relative difference step; default `√ε`.
41    pub rdiff: Option<f64>,
42    /// Backtrack along the Newton direction to reduce `‖F‖²` (SciPy's Armijo search).
43    pub line_search: bool,
44    pub inner: InnerSolver,
45}
46
47impl Default for NewtonKrylovOptions {
48    fn default() -> Self {
49        NewtonKrylovOptions {
50            f_tol: f64::EPSILON.powf(1.0 / 3.0),
51            f_rtol: f64::INFINITY,
52            x_tol: f64::INFINITY,
53            x_rtol: f64::INFINITY,
54            max_iter: None,
55            inner_maxiter: 20,
56            rdiff: None,
57            line_search: true,
58            inner: InnerSolver::Gmres,
59        }
60    }
61}
62
63/// The result of [`newton_krylov`].
64#[derive(Clone, Debug)]
65#[non_exhaustive]
66pub struct NewtonKrylovResult {
67    pub x: Vec<f64>,
68    /// `F(x)`.
69    pub fun: Vec<f64>,
70    /// Newton iterations, counted as SciPy's `nit` (convergence tests made).
71    pub iterations: usize,
72    /// Evaluations of `F`, including those inside the Jacobian-vector products.
73    pub nfev: usize,
74    /// Products of the approximate Jacobian with a vector.
75    pub jacobian_products: usize,
76    pub converged: bool,
77}
78
79fn norm2(v: &[f64]) -> f64 {
80    v.iter().map(|x| x * x).sum::<f64>().sqrt()
81}
82
83fn max_norm(v: &[f64]) -> f64 {
84    v.iter().fold(0.0f64, |m, x| m.max(x.abs()))
85}
86
87/// A residual function `F: ℝⁿ → ℝⁿ`.
88type Residual<'a> = &'a mut dyn FnMut(&[f64]) -> Vec<f64>;
89
90/// `F` with an evaluation counter, shared by the Newton loop and the Jacobian operator.
91struct Counted<'a> {
92    f: RefCell<Residual<'a>>,
93    calls: Cell<usize>,
94}
95
96impl Counted<'_> {
97    fn eval(&self, x: &[f64]) -> Vec<f64> {
98        self.calls.set(self.calls.get() + 1);
99        (self.f.borrow_mut())(x)
100    }
101}
102
103// ANCHOR: jacobian
104/// The Jacobian at `x` seen only through products: `J v ≈ (F(x + h v/‖v‖) − F(x)) ‖v‖ / h`, with
105/// `h = rdiff · max(1, ‖x‖∞) / max(1, ‖F(x)‖∞)` (SciPy's `KrylovJacobian`).
106struct FiniteDifferenceJacobian<'a, 'b> {
107    f: &'b Counted<'a>,
108    x: Vec<f64>,
109    fx: Vec<f64>,
110    omega: f64,
111    products: Cell<usize>,
112}
113
114impl LinearOperator for FiniteDifferenceJacobian<'_, '_> {
115    fn shape(&self) -> (usize, usize) {
116        (self.x.len(), self.x.len())
117    }
118    fn matvec(&self, v: &[f64]) -> Vec<f64> {
119        let nv = norm2(v);
120        if nv == 0.0 {
121            return vec![0.0; v.len()];
122        }
123        self.products.set(self.products.get() + 1);
124        let sc = self.omega / nv;
125        let xs: Vec<f64> = self.x.iter().zip(v).map(|(x, vi)| x + sc * vi).collect();
126        self.f.eval(&xs).iter().zip(&self.fx).map(|(a, b)| (a - b) / sc).collect()
127    }
128    fn rmatvec(&self, _: &[f64]) -> Vec<f64> {
129        unimplemented!("the transposed Jacobian is not available without derivatives")
130    }
131}
132// ANCHOR_END: jacobian
133
134/// SciPy's `scalar_search_armijo`: the step `α` with `φ(α) ≤ φ(0) + c₁ α φ'(0)`, trying 1, then
135/// the minimiser of a quadratic, then of cubics, down to `α_min`.
136fn armijo(mut phi: impl FnMut(f64) -> f64, phi0: f64, derphi0: f64, amin: f64) -> Option<f64> {
137    let c1 = 1e-4;
138    let alpha0 = 1.0;
139    let mut phi_a0 = phi(alpha0);
140    if phi_a0 <= phi0 + c1 * alpha0 * derphi0 {
141        return Some(alpha0);
142    }
143    let mut alpha0 = alpha0;
144    let mut alpha1 = -derphi0 * alpha0 * alpha0 / 2.0 / (phi_a0 - phi0 - derphi0 * alpha0);
145    let mut phi_a1 = phi(alpha1);
146    if phi_a1 <= phi0 + c1 * alpha1 * derphi0 {
147        return Some(alpha1);
148    }
149    while alpha1 > amin {
150        let factor = alpha0 * alpha0 * alpha1 * alpha1 * (alpha1 - alpha0);
151        let a = (alpha0 * alpha0 * (phi_a1 - phi0 - derphi0 * alpha1) - alpha1 * alpha1 * (phi_a0 - phi0 - derphi0 * alpha0)) / factor;
152        let b = (-alpha0.powi(3) * (phi_a1 - phi0 - derphi0 * alpha1) + alpha1.powi(3) * (phi_a0 - phi0 - derphi0 * alpha0)) / factor;
153        let mut alpha2 = (-b + (b * b - 3.0 * a * derphi0).abs().sqrt()) / (3.0 * a);
154        let phi_a2 = phi(alpha2);
155        if phi_a2 <= phi0 + c1 * alpha2 * derphi0 {
156            return Some(alpha2);
157        }
158        if alpha1 - alpha2 > alpha1 / 2.0 || 1.0 - alpha2 / alpha1 < 0.96 {
159            alpha2 = alpha1 / 2.0;
160        }
161        alpha0 = alpha1;
162        alpha1 = alpha2;
163        phi_a0 = phi_a1;
164        phi_a1 = phi_a2;
165    }
166    None
167}
168
169// ANCHOR: newton_krylov
170/// Solves `F(x) = 0` for large `n` without forming the Jacobian (SciPy's `newton_krylov`). Each
171/// Newton iteration solves `J dx = −F(x)` inexactly with a Krylov method, to the relative
172/// accuracy `η` of the Eisenstat-Walker forcing sequence (choice 2, `γ = 0.9`), using finite-
173/// difference products `J v`; an Armijo line search on `‖F‖²` then sets the step. An optional
174/// preconditioner `M ≈ J⁻¹` (SciPy's `inner_M`) applies to the inner solves.
175pub fn newton_krylov<F>(mut f: F, x0: &[f64], preconditioner: Option<&dyn LinearOperator>, options: &NewtonKrylovOptions) -> Result<NewtonKrylovResult, ErrorsJSL>
176where
177    F: FnMut(&[f64]) -> Vec<f64>,
178{
179    let n = x0.len();
180    if n == 0 {
181        return Err(ErrorsJSL::InvalidInputRange("newton_krylov: the starting point must not be empty"));
182    }
183    let counted = Counted { f: RefCell::new(&mut f), calls: Cell::new(0) };
184    let mut x = x0.to_vec();
185    let mut fx = counted.eval(&x);
186    if fx.len() != n {
187        return Err(ErrorsJSL::InvalidInputRange("newton_krylov: F must map ℝⁿ to ℝⁿ"));
188    }
189    let max_iter = options.max_iter.unwrap_or(100 * (n + 1));
190    let rdiff = options.rdiff.unwrap_or(f64::EPSILON.sqrt());
191    let mut fx_norm = norm2(&fx);
192    let f0_norm = max_norm(&fx);
193    let mut dx = vec![f64::INFINITY; n];
194    let (gamma, eta_max, eta_threshold): (f64, f64, f64) = (0.9, 0.9999, 0.1);
195    let mut eta: f64 = 1e-3;
196    let mut augmented = LgmresSolver::new(30, 10);
197    augmented.store_outer_av = false;
198    augmented.prepend_outer_v = true;
199    let (mut checks, mut products, mut converged) = (0, 0, false);
200    for _ in 0..max_iter {
201        checks += 1;
202        let (f_inf, dx_inf) = (max_norm(&fx), max_norm(&dx));
203        if f_inf == 0.0 || (f_inf <= options.f_tol && f_inf / options.f_rtol <= f0_norm && dx_inf <= options.x_tol && dx_inf / options.x_rtol <= max_norm(&x)) {
204            converged = true;
205            break;
206        }
207        // Inexact Newton direction.
208        let omega = rdiff * max_norm(&x).max(1.0) / max_norm(&fx).max(1.0);
209        let jac = FiniteDifferenceJacobian { f: &counted, x: x.clone(), fx: fx.clone(), omega, products: Cell::new(0) };
210        let tol = eta.min(eta * fx_norm);
211        let inner = IterativeOptions { rtol: tol, atol: 0.0, max_iterations: Some(options.inner_maxiter) };
212        let sol = match options.inner {
213            InnerSolver::Gmres => gmres(&jac, &fx, None, preconditioner, options.inner_maxiter, inner)?,
214            InnerSolver::Bicgstab => bicgstab(&jac, &fx, None, preconditioner, inner)?,
215            InnerSolver::Lgmres => augmented.solve(&jac, &fx, None, preconditioner, IterativeOptions { max_iterations: Some(1), ..inner })?,
216        };
217        products += jac.products.get();
218        dx = sol.x.iter().map(|v| -v).collect();
219        if norm2(&dx) == 0.0 {
220            return Err(ErrorsJSL::Message("newton_krylov: the inner solve returned a zero step".into()));
221        }
222        // Line search on φ(s) = ‖F(x + s dx)‖².
223        let (s, x_new, f_new) = if options.line_search {
224            let mut last: Option<(f64, Vec<f64>)> = None;
225            let s = armijo(
226                |s| {
227                    let xt: Vec<f64> = x.iter().zip(&dx).map(|(a, d)| a + s * d).collect();
228                    let v = counted.eval(&xt);
229                    let p = if v.iter().all(|t| t.is_finite()) { norm2(&v).powi(2) } else { f64::INFINITY };
230                    last = Some((s, v));
231                    p
232                },
233                fx_norm * fx_norm,
234                -fx_norm * fx_norm,
235                1e-2,
236            )
237            .unwrap_or(1.0);
238            let x_new: Vec<f64> = x.iter().zip(&dx).map(|(a, d)| a + s * d).collect();
239            let f_new = match last {
240                Some((ls, v)) if ls == s => v,
241                _ => counted.eval(&x_new),
242            };
243            (s, x_new, f_new)
244        } else {
245            let x_new: Vec<f64> = x.iter().zip(&dx).map(|(a, d)| a + d).collect();
246            let f_new = counted.eval(&x_new);
247            (1.0, x_new, f_new)
248        };
249        let _ = s;
250        let fx_norm_new = norm2(&f_new);
251        x = x_new;
252        fx = f_new;
253        // Eisenstat-Walker forcing term.
254        let eta_a = gamma * fx_norm_new * fx_norm_new / (fx_norm * fx_norm);
255        eta = if gamma * eta * eta < eta_threshold { eta_max.min(eta_a) } else { eta_max.min(eta_a.max(gamma * eta * eta)) };
256        fx_norm = fx_norm_new;
257    }
258    let nfev = counted.calls.get();
259    Ok(NewtonKrylovResult { x, fun: fx, iterations: checks, nfev, jacobian_products: products, converged })
260}
261// ANCHOR_END: newton_krylov
262
263#[cfg(test)]
264mod tests {
265    use super::*;
266
267    /// The Bratu problem `Δu + λ eᵘ = 0` on the unit square with zero boundary values, by
268    /// 5-point differences on an `m × m` interior grid.
269    fn bratu(m: usize, lambda: f64) -> impl FnMut(&[f64]) -> Vec<f64> {
270        let h2 = 1.0 / ((m + 1) * (m + 1)) as f64;
271        move |u: &[f64]| {
272            let at = |i: isize, j: isize| if i < 0 || j < 0 || i >= m as isize || j >= m as isize { 0.0 } else { u[i as usize * m + j as usize] };
273            (0..m * m)
274                .map(|k| {
275                    let (i, j) = ((k / m) as isize, (k % m) as isize);
276                    (at(i - 1, j) + at(i + 1, j) + at(i, j - 1) + at(i, j + 1) - 4.0 * at(i, j)) / h2 + lambda * at(i, j).exp()
277                })
278                .collect()
279        }
280    }
281
282    #[test]
283    fn solves_the_bratu_problem() {
284        let m = 20;
285        for inner in [InnerSolver::Gmres, InnerSolver::Bicgstab, InnerSolver::Lgmres] {
286            let o = NewtonKrylovOptions { inner, inner_maxiter: 60, ..Default::default() };
287            let r = newton_krylov(bratu(m, 6.0), &vec![0.0; m * m], None, &o).unwrap();
288            assert!(r.converged, "{inner:?}: {} iterations", r.iterations);
289            assert!(max_norm(&r.fun) <= o.f_tol);
290            // The lower solution at λ = 6 peaks at 0.792975 on this grid (SciPy agrees).
291            let peak = r.x.iter().cloned().fold(0.0, f64::max);
292            assert!((peak - 0.792_974_648).abs() < 1e-6, "{peak}");
293        }
294    }
295
296    #[test]
297    fn small_system_and_errors() {
298        // x² + y² = 4, x y = 1.
299        let f = |v: &[f64]| vec![v[0] * v[0] + v[1] * v[1] - 4.0, v[0] * v[1] - 1.0];
300        let o = NewtonKrylovOptions { f_tol: 1e-12, ..Default::default() };
301        let r = newton_krylov(f, &[2.0, 0.5], None, &o).unwrap();
302        assert!(r.converged);
303        assert!((r.x[0] * r.x[0] + r.x[1] * r.x[1] - 4.0).abs() < 1e-11 && (r.x[0] * r.x[1] - 1.0).abs() < 1e-11);
304        assert!(newton_krylov(f, &[], None, &o).is_err());
305        assert!(newton_krylov(|v: &[f64]| vec![v[0]], &[1.0, 2.0], None, &o).is_err());
306    }
307}