Skip to main content

lib_jsl_optimization/
least_squares.rs

1//! Nonlinear least squares by the Levenberg-Marquardt method, and curve fitting built on it.
2//!
3//! The problem is `min_p F(p) = ½ Σ r_i(p)²` for a residual vector `r: ℝⁿ → ℝᵐ` (`m ≥ n`). Each
4//! iteration solves the damped Gauss-Newton system `(JᵀJ + μ D) h = −Jᵀr`, where `D` is the
5//! diagonal of `JᵀJ` (Marquardt's scaling, which makes the method invariant to rescaling the
6//! parameters). The damping `μ` follows Nielsen's gain-ratio update: steps that achieve the
7//! predicted reduction shrink `μ` towards Gauss-Newton, failed steps grow it towards a short
8//! gradient-descent step.
9//!
10//! See the book entry [Nonlinear least squares and curve fitting](https://jwkunz.github.io/lib_jsl/book/optimization/least-squares.html).
11
12use crate::optimization_traits::MinimizationControls;
13use lib_jsl_core::ErrorsJSL;
14use ndarray::{Array1, Array2};
15use lib_jsl_linalg::{Inverse, Solve};
16
17/// The outcome of a least-squares solve.
18#[derive(Debug, Clone)]
19#[non_exhaustive]
20pub struct LeastSquaresResult {
21    pub parameters: Vec<f64>,
22    /// The residuals at the solution.
23    pub residuals: Vec<f64>,
24    /// `½ Σ r_i²` at the solution.
25    pub cost: f64,
26    /// The Jacobian `∂r_i/∂p_j` at the solution (row-major, m × n).
27    pub jacobian: Vec<Vec<f64>>,
28    pub iterations: usize,
29    pub converged: bool,
30}
31
32/// Levenberg-Marquardt solver. The tolerance (default 1e-10) applies to the gradient infinity
33/// norm (scaled by 1e-2), the relative step size and the relative cost reduction; bounds, when set, are enforced
34/// by projecting each trial point onto the box.
35#[derive(Debug, Clone)]
36pub struct LevenbergMarquardt {
37    max_iterations: Option<usize>,
38    tolerance: Option<f64>,
39    bounds: Option<Vec<(f64, f64)>>,
40    /// Initial damping relative to the largest diagonal entry of `JᵀJ`.
41    pub initial_damping: f64,
42    /// Relative step for forward-difference Jacobians.
43    pub difference_step: f64,
44}
45
46impl Default for LevenbergMarquardt {
47    fn default() -> Self {
48        LevenbergMarquardt { max_iterations: None, tolerance: None, bounds: None, initial_damping: 1e-3, difference_step: 1e-7 }
49    }
50}
51
52impl MinimizationControls for LevenbergMarquardt {
53    fn set_max_iterations(&mut self, max_iterations: Option<usize>) {
54        self.max_iterations = max_iterations;
55    }
56    fn get_max_iterations(&self) -> Option<usize> {
57        self.max_iterations
58    }
59    fn set_tolerance(&mut self, tolerance: Option<f64>) {
60        self.tolerance = tolerance;
61    }
62    fn get_tolerance(&self) -> Option<f64> {
63        self.tolerance
64    }
65    fn set_bounds(&mut self, bounds: Option<Vec<(f64, f64)>>) {
66        self.bounds = bounds;
67    }
68    fn get_bounds(&self) -> Option<Vec<(f64, f64)>> {
69        self.bounds.clone()
70    }
71}
72
73fn half_sum_squares(r: &[f64]) -> f64 {
74    0.5 * r.iter().map(|v| v * v).sum::<f64>()
75}
76
77impl LevenbergMarquardt {
78    pub fn new() -> Self {
79        Self::default()
80    }
81
82    fn project(&self, p: &mut [f64]) {
83        if let Some(b) = &self.bounds {
84            p.iter_mut().zip(b).for_each(|(v, (lo, hi))| *v = v.clamp(*lo, *hi));
85        }
86    }
87
88    /// Forward-difference Jacobian of `residuals` at `p` (with `r = residuals(p)` supplied).
89    pub fn numerical_jacobian<R>(&self, residuals: &R, p: &[f64], r: &[f64]) -> Vec<Vec<f64>>
90    where
91        R: Fn(&[f64]) -> Vec<f64>,
92    {
93        let mut jac = vec![vec![0.0; p.len()]; r.len()];
94        let mut q = p.to_vec();
95        for j in 0..p.len() {
96            let h = self.difference_step * p[j].abs().max(1.0);
97            q[j] = p[j] + h;
98            let rq = residuals(&q);
99            q[j] = p[j];
100            for i in 0..r.len() {
101                jac[i][j] = (rq[i] - r[i]) / h;
102            }
103        }
104        jac
105    }
106
107    /// Minimizes `½‖residuals(p)‖²` from `initial`, using the analytic `jacobian` when given and
108    /// forward differences otherwise.
109    pub fn solve<R, J>(&self, residuals: R, jacobian: Option<J>, initial: Vec<f64>) -> Result<LeastSquaresResult, ErrorsJSL>
110    where
111        R: Fn(&[f64]) -> Vec<f64>,
112        J: Fn(&[f64]) -> Vec<Vec<f64>>,
113    {
114        let n = initial.len();
115        if n == 0 {
116            return Err(ErrorsJSL::Misconfiguration("Initial parameters must be a non-empty vector."));
117        }
118        if let Some(b) = &self.bounds
119            && (b.len() != n || b.iter().any(|(lo, hi)| lo > hi))
120        {
121            return Err(ErrorsJSL::Misconfiguration("Bounds must match the parameters and satisfy lower <= upper."));
122        }
123        let tol = self.tolerance.unwrap_or(1e-10);
124        let max_iterations = self.max_iterations.unwrap_or(200 * (n + 1));
125        let jac_at = |p: &[f64], r: &[f64]| -> Result<Vec<Vec<f64>>, ErrorsJSL> {
126            let jac = match &jacobian {
127                Some(f) => f(p),
128                None => self.numerical_jacobian(&residuals, p, r),
129            };
130            if jac.len() != r.len() || jac.iter().any(|row| row.len() != n) {
131                return Err(ErrorsJSL::Misconfiguration("The Jacobian must be m × n."));
132            }
133            Ok(jac)
134        };
135        let normal_equations = |jac: &[Vec<f64>], r: &[f64]| {
136            let a = Array2::from_shape_fn((n, n), |(i, j)| jac.iter().map(|row| row[i] * row[j]).sum::<f64>());
137            let g = Array1::from_shape_fn(n, |i| jac.iter().zip(r).map(|(row, ri)| row[i] * ri).sum::<f64>());
138            (a, g)
139        };
140
141        let mut p = initial;
142        self.project(&mut p);
143        let mut r = residuals(&p);
144        if r.len() < n {
145            return Err(ErrorsJSL::Misconfiguration("There must be at least as many residuals as parameters."));
146        }
147        let mut cost = half_sum_squares(&r);
148        let mut jac = jac_at(&p, &r)?;
149        let (mut a, mut g) = normal_equations(&jac, &r);
150        let max_diag = (0..n).map(|i| a[[i, i]]).fold(0.0, f64::max);
151        let mut mu = self.initial_damping * max_diag.max(f64::MIN_POSITIVE);
152        let mut nu = 2.0;
153        let mut converged = false;
154        let mut iterations = 0;
155        while iterations < max_iterations {
156            if g.iter().fold(0.0f64, |m, v| m.max(v.abs())) <= 1e-2 * tol || cost == 0.0 {
157                converged = true;
158                break;
159            }
160            iterations += 1;
161            // ANCHOR: lm_step
162            let diag: Vec<f64> = (0..n).map(|i| a[[i, i]].max(1e-12 * max_diag.max(1.0))).collect();
163            let mut damped = a.clone();
164            (0..n).for_each(|i| damped[[i, i]] += mu * diag[i]);
165            let h = match damped.solve(&(-&g)) {
166                Ok(h) => h,
167                Err(_) => {
168                    mu *= nu;
169                    nu *= 2.0;
170                    continue;
171                }
172            };
173            let p_norm = p.iter().map(|v| v * v).sum::<f64>().sqrt();
174            if h.dot(&h).sqrt() <= tol * (p_norm + tol) {
175                converged = true;
176                break;
177            }
178            let mut trial: Vec<f64> = p.iter().zip(h.iter()).map(|(a, b)| a + b).collect();
179            self.project(&mut trial);
180            let step = Array1::from_shape_fn(n, |i| trial[i] - p[i]);
181            let r_trial = residuals(&trial);
182            let cost_trial = half_sum_squares(&r_trial);
183            // Predicted reduction of the linear model, ½ hᵀ(μ D h − g).
184            let predicted = 0.5 * (0..n).map(|i| step[i] * (mu * diag[i] * step[i] - g[i])).sum::<f64>();
185            let rho = if predicted > 0.0 { (cost - cost_trial) / predicted } else { -1.0 };
186            if rho > 0.0 && cost_trial.is_finite() {
187                let relative_drop = (cost - cost_trial) / cost.max(f64::MIN_POSITIVE);
188                p = trial;
189                r = r_trial;
190                cost = cost_trial;
191                jac = jac_at(&p, &r)?;
192                (a, g) = normal_equations(&jac, &r);
193                mu *= (1.0f64 / 3.0).max(1.0 - (2.0 * rho - 1.0).powi(3));
194            // ANCHOR_END: lm_step
195                nu = 2.0;
196                if relative_drop < tol {
197                    converged = true;
198                    break;
199                }
200            } else {
201                mu *= nu;
202                nu *= 2.0;
203                if !mu.is_finite() {
204                    break;
205                }
206            }
207        }
208        Ok(LeastSquaresResult { parameters: p, residuals: r, cost, jacobian: jac, iterations, converged })
209    }
210}
211
212/// The outcome of [`curve_fit`].
213#[derive(Debug, Clone)]
214#[non_exhaustive]
215pub struct CurveFitResult {
216    pub parameters: Vec<f64>,
217    /// Parameter covariance (n × n).
218    pub covariance: Vec<Vec<f64>>,
219    /// One-sigma parameter uncertainties, `√diag(covariance)`.
220    pub standard_errors: Vec<f64>,
221    /// `Σ ((y_i − f(x_i)) / σ_i)²`.
222    pub chi_squared: f64,
223    /// `chi_squared / (m − n)`.
224    pub reduced_chi_squared: f64,
225    pub iterations: usize,
226    pub converged: bool,
227}
228
229/// Fits `model(x, p)` to data `(x_i, y_i)` by weighted least squares with Levenberg-Marquardt.
230///
231/// With `sigma = Some(σ)` each residual is divided by its standard deviation and the covariance
232/// is `(JᵀJ)⁻¹` (absolute uncertainties). With `sigma = None` the residuals are unweighted and the
233/// covariance is scaled by the reduced chi-squared, which estimates the unknown noise level (as
234/// SciPy's `curve_fit` does by default).
235pub fn curve_fit<M>(
236    model: M,
237    x: &[f64],
238    y: &[f64],
239    sigma: Option<&[f64]>,
240    initial: Vec<f64>,
241    solver: &LevenbergMarquardt,
242) -> Result<CurveFitResult, ErrorsJSL>
243where
244    M: Fn(f64, &[f64]) -> f64,
245{
246    if x.len() != y.len() {
247        return Err(ErrorsJSL::IncompatibleArraySizes((x.len(), y.len())));
248    }
249    if let Some(s) = sigma
250        && (s.len() != y.len() || s.iter().any(|v| *v <= 0.0))
251    {
252        return Err(ErrorsJSL::Misconfiguration("sigma must match the data and be positive."));
253    }
254    let n = initial.len();
255    if x.len() <= n {
256        return Err(ErrorsJSL::Misconfiguration("There must be more data points than parameters."));
257    }
258    let weight = |i: usize| sigma.map_or(1.0, |s| 1.0 / s[i]);
259    let residuals = |p: &[f64]| (0..x.len()).map(|i| (y[i] - model(x[i], p)) * weight(i)).collect::<Vec<f64>>();
260    let fit = solver.solve(residuals, None::<fn(&[f64]) -> Vec<Vec<f64>>>, initial)?;
261    let jtj = Array2::from_shape_fn((n, n), |(i, j)| fit.jacobian.iter().map(|row| row[i] * row[j]).sum::<f64>());
262    let inv = jtj.inv().map_err(|_| ErrorsJSL::RuntimeError("The fit Jacobian is rank deficient; the covariance is undefined."))?;
263    let chi_squared = 2.0 * fit.cost;
264    let reduced_chi_squared = chi_squared / (x.len() - n) as f64;
265    let scale = if sigma.is_some() { 1.0 } else { reduced_chi_squared };
266    let covariance: Vec<Vec<f64>> = (0..n).map(|i| (0..n).map(|j| inv[[i, j]] * scale).collect()).collect();
267    let standard_errors = (0..n).map(|i| covariance[i][i].max(0.0).sqrt()).collect();
268    Ok(CurveFitResult {
269        parameters: fit.parameters,
270        covariance,
271        standard_errors,
272        chi_squared,
273        reduced_chi_squared,
274        iterations: fit.iterations,
275        converged: fit.converged,
276    })
277}
278
279#[cfg(test)]
280mod tests {
281    use super::*;
282
283    type NoJacobian = fn(&[f64]) -> Vec<Vec<f64>>;
284
285    #[test]
286    fn solves_the_rosenbrock_problem_with_and_without_an_analytic_jacobian() {
287        // Rosenbrock as least squares: r = (10(y − x²), 1 − x).
288        let r = |p: &[f64]| vec![10.0 * (p[1] - p[0] * p[0]), 1.0 - p[0]];
289        let j = |p: &[f64]| vec![vec![-20.0 * p[0], 10.0], vec![-1.0, 0.0]];
290        let lm = LevenbergMarquardt::new();
291        let analytic = lm.solve(r, Some(j), vec![-1.2, 1.0]).unwrap();
292        assert!(analytic.converged && (analytic.parameters[0] - 1.0).abs() < 1e-8 && (analytic.parameters[1] - 1.0).abs() < 1e-8);
293        let numeric = lm.solve(r, None::<NoJacobian>, vec![-1.2, 1.0]).unwrap();
294        assert!((numeric.parameters[0] - 1.0).abs() < 1e-6 && numeric.cost < 1e-14, "{numeric:?}");
295        assert!(analytic.iterations < 50);
296    }
297
298    #[test]
299    fn fits_an_exponential_decay_and_reports_consistent_uncertainties() {
300        // Deterministic pseudo-noise of known standard deviation 0.02.
301        let truth = [2.5, 1.3, 0.4];
302        let model = |t: f64, p: &[f64]| p[0] * (-p[1] * t).exp() + p[2];
303        let x: Vec<f64> = (0..60).map(|i| i as f64 * 0.1).collect();
304        let noise: Vec<f64> = (0..60).map(|i| 0.02 * 3f64.sqrt() * (2.0 * ((i * 37 + 11) % 61) as f64 / 60.0 - 1.0)).collect();
305        let y: Vec<f64> = x.iter().zip(&noise).map(|(&t, e)| model(t, &truth) + e).collect();
306        let fit = curve_fit(model, &x, &y, None, vec![1.0, 1.0, 0.0], &LevenbergMarquardt::new()).unwrap();
307        assert!(fit.converged);
308        for (k, t) in truth.iter().enumerate() {
309            assert!((fit.parameters[k] - t).abs() < 4.0 * fit.standard_errors[k], "param {k}: {fit:?}");
310            assert!(fit.standard_errors[k] > 0.0 && fit.standard_errors[k] < 0.05);
311        }
312        // Unweighted reduced chi-squared estimates the noise variance (≈ 0.02²).
313        assert!((fit.reduced_chi_squared.sqrt() - 0.02).abs() < 0.005);
314        // Supplying the true sigma gives a reduced chi-squared near one and similar errors.
315        let sigma = vec![0.02; 60];
316        let weighted = curve_fit(model, &x, &y, Some(&sigma), vec![1.0, 1.0, 0.0], &LevenbergMarquardt::new()).unwrap();
317        assert!((weighted.reduced_chi_squared - 1.0).abs() < 0.3);
318        assert!((weighted.parameters[1] - fit.parameters[1]).abs() < 1e-6);
319    }
320
321    #[test]
322    fn exact_linear_fit_bounds_and_validation() {
323        let x: Vec<f64> = (0..10).map(|i| i as f64).collect();
324        let y: Vec<f64> = x.iter().map(|t| 3.0 * t - 2.0).collect();
325        let fit = curve_fit(|t, p| p[0] * t + p[1], &x, &y, None, vec![0.0, 0.0], &LevenbergMarquardt::new()).unwrap();
326        assert!((fit.parameters[0] - 3.0).abs() < 1e-9 && (fit.parameters[1] + 2.0).abs() < 1e-9 && fit.chi_squared < 1e-16);
327        // A bound that excludes the unconstrained optimum is active at the solution.
328        let mut lm = LevenbergMarquardt::new();
329        lm.set_bounds(Some(vec![(0.0, 2.0), (-10.0, 10.0)]));
330        let r = |p: &[f64]| x.iter().zip(&y).map(|(t, v)| v - (p[0] * t + p[1])).collect::<Vec<_>>();
331        let bounded = lm.solve(r, None::<NoJacobian>, vec![1.0, 0.0]).unwrap();
332        assert!((bounded.parameters[0] - 2.0).abs() < 1e-12);
333        assert!(curve_fit(|t, p| p[0] * t, &x[..1], &y[..1], None, vec![1.0], &lm).is_err());
334        assert!(LevenbergMarquardt::new().solve(r, None::<NoJacobian>, vec![]).is_err());
335    }
336}