Skip to main content

lib_jsl_root_finding/
minpack.rs

1//! MINPACK's Levenberg-Marquardt method (`lmder` and `lmdif`, Moré 1978), as SciPy's
2//! `optimize.leastsq` and `optimize.root(method="lm")` call it: nonlinear least squares
3//! `min ‖F(x)‖²`, `F: ℝⁿ → ℝᵐ`, `m ≥ n`, and so also the roots of square systems.
4//!
5//! See the book entry [Levenberg-Marquardt for systems, mixed-integer programming and truncated Newton](https://jwkunz.github.io/lib_jsl/book/optimization/milp-tnc.html#minpacks-levenberg-marquardt).
6
7// MINPACK's loops over columns and rows read best as index loops.
8#![allow(clippy::needless_range_loop)]
9
10use crate::nonlinear_systems::SystemRootResult;
11use lib_jsl_core::ErrorsJSL;
12
13/// An analytic Jacobian for [`leastsq`] and [`root_lm`]: the `m × n` matrix `∂Fᵢ/∂xⱼ` by rows.
14pub type JacobianFn<'a> = &'a mut dyn FnMut(&[f64]) -> Vec<Vec<f64>>;
15
16/// Options for [`leastsq`] and [`root_lm`], with SciPy's `leastsq` defaults.
17#[derive(Clone, Copy, Debug)]
18pub struct LmOptions {
19    /// Stop when the relative reduction in the sum of squares is at most this (MINPACK info 1).
20    pub ftol: f64,
21    /// Stop when the relative change in `x` is at most this (info 2).
22    pub xtol: f64,
23    /// Stop when the cosine of the angle between `F` and any column of the Jacobian is at most
24    /// this (info 4).
25    pub gtol: f64,
26    /// The largest number of evaluations of `F`; `None` for SciPy's `100(n + 1)` with a
27    /// Jacobian and `200(n + 1)` without.
28    pub maxfev: Option<usize>,
29    /// The initial step bound is `factor ‖D x‖`.
30    pub factor: f64,
31    /// The relative step for forward-difference Jacobians, `√max(epsfcn, ε)`.
32    pub epsfcn: f64,
33}
34
35impl Default for LmOptions {
36    fn default() -> Self {
37        LmOptions { ftol: 1.49012e-8, xtol: 1.49012e-8, gtol: 0.0, maxfev: None, factor: 100.0, epsfcn: 0.0 }
38    }
39}
40
41/// The result of [`leastsq`].
42#[derive(Clone, Debug)]
43#[non_exhaustive]
44pub struct LmResult {
45    pub x: Vec<f64>,
46    /// `F(x)` at the solution.
47    pub fvec: Vec<f64>,
48    /// Evaluations of `F`, including those for finite-difference Jacobians.
49    pub nfev: usize,
50    /// Evaluations of the Jacobian (0 with finite differences).
51    pub njev: usize,
52    /// MINPACK's `info`: 1 ftol, 2 xtol, 3 both, 4 gtol, 5 the evaluation limit, 6–8 a tolerance
53    /// too small to improve on.
54    pub info: i32,
55}
56
57fn enorm(v: &[f64]) -> f64 {
58    // MINPACK guards against overflow; a scaled sum of squares does the same.
59    let s = v.iter().fold(0.0f64, |a, x| a.max(x.abs()));
60    if s == 0.0 || !s.is_finite() {
61        return s;
62    }
63    s * v.iter().map(|x| (x / s) * (x / s)).sum::<f64>().sqrt()
64}
65
66/// Householder QR with column pivoting (`qrfac`): `a` (m × n, rows) is overwritten by the
67/// Householder vectors below the diagonal and `R` above it; returns the permutation, `R`'s
68/// diagonal and the column norms of the original matrix.
69fn qrfac(a: &mut [Vec<f64>], m: usize, n: usize) -> (Vec<usize>, Vec<f64>, Vec<f64>) {
70    let eps = f64::EPSILON;
71    let col = |a: &[Vec<f64>], j: usize, from: usize| -> Vec<f64> { (from..m).map(|i| a[i][j]).collect() };
72    let acnorm: Vec<f64> = (0..n).map(|j| enorm(&col(a, j, 0))).collect();
73    let mut rdiag = acnorm.clone();
74    let mut wa = acnorm.clone();
75    let mut ipvt: Vec<usize> = (0..n).collect();
76    for j in 0..m.min(n) {
77        let kmax = (j..n).fold(j, |b, k| if rdiag[k] > rdiag[b] { k } else { b });
78        if kmax != j {
79            for row in a.iter_mut() {
80                row.swap(j, kmax);
81            }
82            rdiag[kmax] = rdiag[j];
83            wa[kmax] = wa[j];
84            ipvt.swap(j, kmax);
85        }
86        let mut ajnorm = enorm(&col(a, j, j));
87        if ajnorm != 0.0 {
88            if a[j][j] < 0.0 {
89                ajnorm = -ajnorm;
90            }
91            for i in j..m {
92                a[i][j] /= ajnorm;
93            }
94            a[j][j] += 1.0;
95            for k in j + 1..n {
96                let sum: f64 = (j..m).map(|i| a[i][j] * a[i][k]).sum();
97                let temp = sum / a[j][j];
98                for i in j..m {
99                    a[i][k] -= temp * a[i][j];
100                }
101                if rdiag[k] != 0.0 {
102                    let t = a[j][k] / rdiag[k];
103                    rdiag[k] *= (1.0 - t * t).max(0.0).sqrt();
104                    if 0.05 * (rdiag[k] / wa[k]).powi(2) <= eps {
105                        rdiag[k] = enorm(&col(a, k, j + 1));
106                        wa[k] = rdiag[k];
107                    }
108                }
109            }
110        }
111        rdiag[j] = -ajnorm;
112    }
113    (ipvt, rdiag, acnorm)
114}
115
116/// `qrsolv`: given `R` (upper triangle of `r`) from `A P = Q R`, solve
117/// `min ‖[A; D] x − [b; 0]‖` with `qtb = Qᵀb`; leaves `S` (with `PᵀAᵀAP + PᵀD²P = SᵀS`) in the
118/// strict lower triangle of `r` and its diagonal in `sdiag`.
119fn qrsolv(r: &mut [Vec<f64>], n: usize, ipvt: &[usize], diag: &[f64], qtb: &[f64], x: &mut [f64], sdiag: &mut [f64]) {
120    let mut wa = vec![0.0; n];
121    for j in 0..n {
122        for i in j..n {
123            r[i][j] = r[j][i];
124        }
125        x[j] = r[j][j];
126        wa[j] = qtb[j];
127    }
128    for j in 0..n {
129        let l = ipvt[j];
130        if diag[l] != 0.0 {
131            for v in sdiag.iter_mut().skip(j) {
132                *v = 0.0;
133            }
134            sdiag[j] = diag[l];
135            let mut qtbpj = 0.0;
136            for k in j..n {
137                if sdiag[k] == 0.0 {
138                    continue;
139                }
140                let (cos, sin) = if r[k][k].abs() < sdiag[k].abs() {
141                    let cotan = r[k][k] / sdiag[k];
142                    let sin = 0.5 / (0.25 + 0.25 * cotan * cotan).sqrt();
143                    (sin * cotan, sin)
144                } else {
145                    let tan = sdiag[k] / r[k][k];
146                    let cos = 0.5 / (0.25 + 0.25 * tan * tan).sqrt();
147                    (cos, cos * tan)
148                };
149                r[k][k] = cos * r[k][k] + sin * sdiag[k];
150                let temp = cos * wa[k] + sin * qtbpj;
151                qtbpj = -sin * wa[k] + cos * qtbpj;
152                wa[k] = temp;
153                for i in k + 1..n {
154                    let temp = cos * r[i][k] + sin * sdiag[i];
155                    sdiag[i] = -sin * r[i][k] + cos * sdiag[i];
156                    r[i][k] = temp;
157                }
158            }
159        }
160        sdiag[j] = r[j][j];
161        r[j][j] = x[j];
162    }
163    let mut nsing = n;
164    for j in 0..n {
165        if sdiag[j] == 0.0 && nsing == n {
166            nsing = j;
167        }
168        if nsing < n {
169            wa[j] = 0.0;
170        }
171    }
172    for j in (0..nsing).rev() {
173        let sum: f64 = (j + 1..nsing).map(|i| r[i][j] * wa[i]).sum();
174        wa[j] = (wa[j] - sum) / sdiag[j];
175    }
176    for j in 0..n {
177        x[ipvt[j]] = wa[j];
178    }
179}
180
181/// `lmpar`: the Levenberg-Marquardt parameter `λ` for which the step `x` solving
182/// `min ‖[J; √λ D] x − [−F; 0]‖` has `‖D x‖` within 10 % of `Δ` (or `λ = 0` if the Gauss-Newton
183/// step is shorter), by Moré's safeguarded Newton iteration on `‖D x(λ)‖ − Δ`.
184fn lmpar(r: &mut [Vec<f64>], n: usize, ipvt: &[usize], diag: &[f64], qtb: &[f64], delta: f64, par: f64) -> (f64, Vec<f64>) {
185    let dwarf = f64::MIN_POSITIVE;
186    let mut x = vec![0.0; n];
187    let mut sdiag = vec![0.0; n];
188    let mut wa1 = qtb.to_vec();
189    let mut nsing = n;
190    for j in 0..n {
191        if r[j][j] == 0.0 && nsing == n {
192            nsing = j;
193        }
194        if nsing < n {
195            wa1[j] = 0.0;
196        }
197    }
198    for j in (0..nsing).rev() {
199        wa1[j] /= r[j][j];
200        let temp = wa1[j];
201        for i in 0..j {
202            wa1[i] -= r[i][j] * temp;
203        }
204    }
205    for j in 0..n {
206        x[ipvt[j]] = wa1[j];
207    }
208    let mut wa2: Vec<f64> = (0..n).map(|j| diag[j] * x[j]).collect();
209    let mut dxnorm = enorm(&wa2);
210    let mut fp = dxnorm - delta;
211    if fp <= 0.1 * delta {
212        return (0.0, x);
213    }
214    let mut parl = 0.0;
215    if nsing >= n {
216        for j in 0..n {
217            let l = ipvt[j];
218            wa1[j] = diag[l] * (wa2[l] / dxnorm);
219        }
220        for j in 0..n {
221            let sum: f64 = (0..j).map(|i| r[i][j] * wa1[i]).sum();
222            wa1[j] = (wa1[j] - sum) / r[j][j];
223        }
224        let temp = enorm(&wa1);
225        parl = ((fp / delta) / temp) / temp;
226    }
227    for j in 0..n {
228        let sum: f64 = (0..=j).map(|i| r[i][j] * qtb[i]).sum();
229        wa1[j] = sum / diag[ipvt[j]];
230    }
231    let gnorm = enorm(&wa1);
232    let mut paru = gnorm / delta;
233    if paru == 0.0 {
234        paru = dwarf / delta.min(0.1);
235    }
236    let mut par = par.max(parl).min(paru);
237    if par == 0.0 {
238        par = gnorm / dxnorm;
239    }
240    let mut iter = 0;
241    loop {
242        iter += 1;
243        if par == 0.0 {
244            par = dwarf.max(0.001 * paru);
245        }
246        let sp = par.sqrt();
247        let d: Vec<f64> = diag.iter().map(|v| sp * v).collect();
248        qrsolv(r, n, ipvt, &d, qtb, &mut x, &mut sdiag);
249        wa2 = (0..n).map(|j| diag[j] * x[j]).collect();
250        dxnorm = enorm(&wa2);
251        let temp = fp;
252        fp = dxnorm - delta;
253        if fp.abs() <= 0.1 * delta || (parl == 0.0 && fp <= temp && temp < 0.0) || iter == 10 {
254            break;
255        }
256        for j in 0..n {
257            let l = ipvt[j];
258            wa1[j] = diag[l] * (wa2[l] / dxnorm);
259        }
260        for j in 0..n {
261            wa1[j] /= sdiag[j];
262            let temp = wa1[j];
263            for i in j + 1..n {
264                wa1[i] -= r[i][j] * temp;
265            }
266        }
267        let temp = enorm(&wa1);
268        let parc = ((fp / delta) / temp) / temp;
269        if fp > 0.0 {
270            parl = parl.max(par);
271        }
272        if fp < 0.0 {
273            paru = paru.min(par);
274        }
275        par = parl.max(par + parc);
276    }
277    (par, x)
278}
279
280// ANCHOR: leastsq
281/// Minimises `‖F(x)‖²` by MINPACK's Levenberg-Marquardt method (SciPy's `leastsq`; `lmder` with
282/// an analytic Jacobian, `lmdif` with forward differences). Each iteration factorises the
283/// Jacobian `J P = Q R` once, then finds by `lmpar` the damping `λ` whose step
284/// `min ‖J p + F‖² + λ‖D p‖²` fits the trust region `‖D p‖ ≤ Δ`, with `D` the running maximum of
285/// the column norms of `J` (MINPACK's `mode = 1`); `Δ` grows or shrinks with the ratio of actual
286/// to predicted reduction. `jac` returns the `m × n` Jacobian by rows.
287pub fn leastsq(
288    mut fun: impl FnMut(&[f64]) -> Vec<f64>,
289    mut jac: Option<JacobianFn<'_>>,
290    x0: &[f64],
291    options: LmOptions,
292) -> Result<LmResult, ErrorsJSL> {
293    let n = x0.len();
294    let eps = f64::EPSILON;
295    let mut x = x0.to_vec();
296    let mut fvec = fun(&x);
297    let m = fvec.len();
298    if n == 0 || m < n {
299        return Err(ErrorsJSL::InvalidInputRange("leastsq: need at least as many residuals as unknowns"));
300    }
301    let maxfev = options.maxfev.unwrap_or(if jac.is_some() { 100 * (n + 1) } else { 200 * (n + 1) });
302    let (mut nfev, mut njev) = (1usize, 0usize);
303    let mut fnorm = enorm(&fvec);
304    let mut par = 0.0;
305    let mut iter = 1;
306    let mut diag = vec![0.0; n];
307    let (mut delta, mut xnorm) = (0.0, 0.0);
308    let mut info = 0;
309    let fd_eps = options.epsfcn.max(eps).sqrt();
310    'outer: loop {
311        // The Jacobian, analytic or by forward differences (MINPACK's fdjac2).
312        let mut fjac: Vec<Vec<f64>> = match jac.as_mut() {
313            Some(j) => {
314                njev += 1;
315                j(&x)
316            }
317            None => {
318                let mut cols = vec![vec![0.0; n]; m];
319                for jj in 0..n {
320                    let temp = x[jj];
321                    let mut h = fd_eps * temp.abs();
322                    if h == 0.0 {
323                        h = fd_eps;
324                    }
325                    x[jj] = temp + h;
326                    let wa = fun(&x);
327                    x[jj] = temp;
328                    for i in 0..m {
329                        cols[i][jj] = (wa[i] - fvec[i]) / h;
330                    }
331                }
332                nfev += n;
333                cols
334            }
335        };
336        if fjac.len() != m || fjac.iter().any(|r| r.len() != n) {
337            return Err(ErrorsJSL::IncompatibleArraySizes((fjac.len(), m)));
338        }
339        let (ipvt, rdiag, acnorm) = qrfac(&mut fjac, m, n);
340        if iter == 1 {
341            for j in 0..n {
342                diag[j] = if acnorm[j] == 0.0 { 1.0 } else { acnorm[j] };
343            }
344            xnorm = enorm(&(0..n).map(|j| diag[j] * x[j]).collect::<Vec<_>>());
345            delta = options.factor * xnorm;
346            if delta == 0.0 {
347                delta = options.factor;
348            }
349        }
350        // Qᵀ F, keeping the first n components.
351        let mut wa4 = fvec.clone();
352        let mut qtf = vec![0.0; n];
353        for j in 0..n {
354            if fjac[j][j] != 0.0 {
355                let sum: f64 = (j..m).map(|i| fjac[i][j] * wa4[i]).sum();
356                let temp = -sum / fjac[j][j];
357                for i in j..m {
358                    wa4[i] += fjac[i][j] * temp;
359                }
360            }
361            fjac[j][j] = rdiag[j];
362            qtf[j] = wa4[j];
363        }
364        let mut gnorm = 0.0f64;
365        if fnorm != 0.0 {
366            for j in 0..n {
367                let l = ipvt[j];
368                if acnorm[l] != 0.0 {
369                    let sum: f64 = (0..=j).map(|i| fjac[i][j] * (qtf[i] / fnorm)).sum();
370                    gnorm = gnorm.max((sum / acnorm[l]).abs());
371                }
372            }
373        }
374        if gnorm <= options.gtol {
375            info = 4;
376            break;
377        }
378        for j in 0..n {
379            diag[j] = diag[j].max(acnorm[j]);
380        }
381        let mut r: Vec<Vec<f64>> = (0..n).map(|i| fjac[i][..n].to_vec()).collect();
382        loop {
383            let (p, step) = lmpar(&mut r, n, &ipvt, &diag, &qtf, delta, par);
384            par = p;
385            let wa1: Vec<f64> = step.iter().map(|v| -v).collect();
386            let wa2: Vec<f64> = (0..n).map(|j| x[j] + wa1[j]).collect();
387            let pnorm = enorm(&(0..n).map(|j| diag[j] * wa1[j]).collect::<Vec<_>>());
388            if iter == 1 {
389                delta = delta.min(pnorm);
390            }
391            let wa4 = fun(&wa2);
392            nfev += 1;
393            let fnorm1 = enorm(&wa4);
394            let actred = if 0.1 * fnorm1 < fnorm { 1.0 - (fnorm1 / fnorm).powi(2) } else { -1.0 };
395            let mut wa3 = vec![0.0; n];
396            for j in 0..n {
397                let temp = wa1[ipvt[j]];
398                for i in 0..=j {
399                    wa3[i] += r[i][j] * temp;
400                }
401            }
402            let temp1 = enorm(&wa3) / fnorm;
403            let temp2 = par.sqrt() * pnorm / fnorm;
404            let prered = temp1 * temp1 + temp2 * temp2 / 0.5;
405            let dirder = -(temp1 * temp1 + temp2 * temp2);
406            let ratio = if prered != 0.0 { actred / prered } else { 0.0 };
407            if ratio <= 0.25 {
408                let mut temp = if actred >= 0.0 { 0.5 } else { 0.5 * dirder / (dirder + 0.5 * actred) };
409                if 0.1 * fnorm1 >= fnorm || temp < 0.1 {
410                    temp = 0.1;
411                }
412                delta = temp * delta.min(pnorm / 0.1);
413                par /= temp;
414            } else if par == 0.0 || ratio >= 0.75 {
415                delta = pnorm / 0.5;
416                par *= 0.5;
417            }
418            if ratio >= 1e-4 {
419                x = wa2;
420                xnorm = enorm(&(0..n).map(|j| diag[j] * x[j]).collect::<Vec<_>>());
421                fvec = wa4;
422                fnorm = fnorm1;
423                iter += 1;
424            }
425            if actred.abs() <= options.ftol && prered <= options.ftol && 0.5 * ratio <= 1.0 {
426                info = 1;
427            }
428            if delta <= options.xtol * xnorm {
429                info = if info == 1 { 3 } else { 2 };
430            }
431            if info != 0 {
432                break 'outer;
433            }
434            if nfev >= maxfev {
435                info = 5;
436            }
437            if actred.abs() <= eps && prered <= eps && 0.5 * ratio <= 1.0 {
438                info = 6;
439            }
440            if delta <= eps * xnorm {
441                info = 7;
442            }
443            if gnorm <= eps {
444                info = 8;
445            }
446            if info != 0 {
447                break 'outer;
448            }
449            if ratio >= 1e-4 {
450                break;
451            }
452        }
453    }
454    Ok(LmResult { x, fvec, nfev, njev, info })
455}
456// ANCHOR_END: leastsq
457
458/// A root of the square system `F(x) = 0` by MINPACK's Levenberg-Marquardt method (SciPy's
459/// `root(method="lm")`): [`leastsq`] on `‖F‖²`. Converged when MINPACK stops on its ftol or xtol
460/// test (info 1–4) with `‖F‖∞` at most `1e-8`; a local minimum of `‖F‖` that is not a root is
461/// reported as not converged.
462pub fn root_lm(fun: impl FnMut(&[f64]) -> Vec<f64>, jac: Option<JacobianFn<'_>>, x0: &[f64], options: LmOptions) -> Result<SystemRootResult, ErrorsJSL> {
463    let r = leastsq(fun, jac, x0, options)?;
464    if r.fvec.len() != r.x.len() {
465        return Err(ErrorsJSL::IncompatibleArraySizes((r.fvec.len(), r.x.len())));
466    }
467    let residual = r.fvec.iter().fold(0.0f64, |a, v| a.max(v.abs()));
468    let converged = (1..=4).contains(&r.info) && residual <= 1e-8;
469    Ok(SystemRootResult::new(r.x, residual, r.nfev, r.nfev, converged))
470}
471
472#[cfg(test)]
473mod tests {
474    use super::*;
475
476    #[test]
477    fn rosenbrock_and_a_system() {
478        // Rosenbrock residuals: the minimum (1, 1) has zero residual.
479        let f = |x: &[f64]| vec![10.0 * (x[1] - x[0] * x[0]), 1.0 - x[0]];
480        let mut j = |x: &[f64]| vec![vec![-20.0 * x[0], 10.0], vec![-1.0, 0.0]];
481        let r = leastsq(f, Some(&mut j), &[-1.2, 1.0], LmOptions::default()).unwrap();
482        assert!((r.x[0] - 1.0).abs() < 1e-10 && (r.x[1] - 1.0).abs() < 1e-10, "{:?}", r.x);
483        let r2 = leastsq(f, None, &[-1.2, 1.0], LmOptions::default()).unwrap();
484        assert!((r2.x[0] - 1.0).abs() < 1e-8);
485        // x² + y² = 4, eˣ + y = 1.
486        let g = |x: &[f64]| vec![x[0] * x[0] + x[1] * x[1] - 4.0, x[0].exp() + x[1] - 1.0];
487        let s = root_lm(g, None, &[1.0, -1.0], LmOptions::default()).unwrap();
488        assert!(s.converged && s.residual < 1e-10, "{s:?}");
489    }
490}