Skip to main content

lib_jsl_optimization/
quasi_newton.rs

1//! Quasi-Newton minimizers: BFGS with a dense inverse-Hessian approximation and limited-memory
2//! L-BFGS. Both use a strong Wolfe line search, which keeps the curvature condition `yᵀs > 0`
3//! and hence the approximation positive definite.
4//!
5//! See the book entry [Newton and quasi-Newton methods](https://jwkunz.github.io/lib_jsl/book/optimization/newton-quasi-newton.html#bfgs).
6
7use crate::line_search::strong_wolfe;
8use crate::optimization_traits::{GradientBasedMinimizationEngine, GradientFunction, MinimizationControls, ObjectiveFunction, OptimizationResult};
9use lib_jsl_core::ErrorsJSL;
10use std::collections::VecDeque;
11
12fn dot(a: &[f64], b: &[f64]) -> f64 {
13    a.iter().zip(b).map(|(p, q)| p * q).sum()
14}
15
16fn inf_norm(a: &[f64]) -> f64 {
17    a.iter().fold(0.0, |m, v| m.max(v.abs()))
18}
19
20macro_rules! unbounded_controls {
21    ($t:ty) => {
22        impl MinimizationControls for $t {
23            fn set_max_iterations(&mut self, max_iterations: Option<usize>) {
24                self.max_iterations = max_iterations;
25            }
26            fn get_max_iterations(&self) -> Option<usize> {
27                self.max_iterations
28            }
29            fn set_tolerance(&mut self, tolerance: Option<f64>) {
30                self.tolerance = tolerance;
31            }
32            fn get_tolerance(&self) -> Option<f64> {
33                self.tolerance
34            }
35            /// Bounds are not supported; setting them makes minimization return an error.
36            fn set_bounds(&mut self, bounds: Option<Vec<(f64, f64)>>) {
37                self.bounds = bounds;
38            }
39            fn get_bounds(&self) -> Option<Vec<(f64, f64)>> {
40                self.bounds.clone()
41            }
42        }
43    };
44}
45pub(crate) use unbounded_controls;
46
47/// Checks the shared preconditions and returns the starting value and gradient.
48pub(crate) fn start<T: ObjectiveFunction, U: GradientFunction>(
49    bounds: &Option<Vec<(f64, f64)>>,
50    objective: &T,
51    gradient: &U,
52    x: &[f64],
53) -> Result<(f64, Vec<f64>), ErrorsJSL> {
54    if x.is_empty() {
55        return Err(ErrorsJSL::Misconfiguration("Initial parameters must be a non-empty vector."));
56    }
57    if bounds.is_some() {
58        return Err(ErrorsJSL::Misconfiguration("This method is unconstrained; bounds are not supported."));
59    }
60    let g = gradient.evaluate(x);
61    if g.len() != x.len() {
62        return Err(ErrorsJSL::Misconfiguration("Gradient length must match the number of parameters."));
63    }
64    Ok((objective.evaluate(x), g))
65}
66
67/// BFGS with a dense n × n inverse-Hessian approximation `H`, updated as
68/// `H ← (I − ρsyᵀ) H (I − ρysᵀ) + ρssᵀ`, `ρ = 1/(yᵀs)`, and initially scaled by `yᵀs / yᵀy` after
69/// the first step. Converges when `‖∇f‖∞` falls below the tolerance (default 1e-8).
70#[derive(Debug, Clone, Default)]
71pub struct Bfgs {
72    max_iterations: Option<usize>,
73    tolerance: Option<f64>,
74    bounds: Option<Vec<(f64, f64)>>,
75}
76
77impl Bfgs {
78    pub fn new() -> Self {
79        Self::default()
80    }
81}
82unbounded_controls!(Bfgs);
83
84impl<T: ObjectiveFunction, U: GradientFunction> GradientBasedMinimizationEngine<T, U> for Bfgs {
85    fn gradient_based_minimize(&self, objective: &T, gradient: &U, initial: Vec<f64>) -> Result<OptimizationResult, ErrorsJSL> {
86        let (mut f, mut g) = start(&self.bounds, objective, gradient, &initial)?;
87        let n = initial.len();
88        let tol = self.tolerance.unwrap_or(1e-8);
89        let max_iterations = self.max_iterations.unwrap_or(200 * n.max(5));
90        let mut x = initial;
91        let mut h = vec![vec![0.0; n]; n];
92        (0..n).for_each(|i| h[i][i] = 1.0);
93        let mut first = true;
94        let mut iterations = 0;
95        let mut converged = inf_norm(&g) <= tol;
96        while !converged && iterations < max_iterations {
97            iterations += 1;
98            let mut d: Vec<f64> = h.iter().map(|row| -dot(row, &g)).collect();
99            if dot(&d, &g) >= 0.0 {
100                // Lost positive definiteness to rounding: restart from steepest descent.
101                (0..n).for_each(|i| (0..n).for_each(|j| h[i][j] = if i == j { 1.0 } else { 0.0 }));
102                d = g.iter().map(|v| -v).collect();
103                first = true;
104            }
105            let step0 = if first { (1.0 / inf_norm(&g)).min(1.0) } else { 1.0 };
106            let Some(p) = strong_wolfe(objective, gradient, &x, f, &g, &d, step0, 1e-4, 0.9) else { break };
107            let s: Vec<f64> = p.x.iter().zip(&x).map(|(a, b)| a - b).collect();
108            let y: Vec<f64> = p.gradient.iter().zip(&g).map(|(a, b)| a - b).collect();
109            let sy = dot(&s, &y);
110            (x, f, g) = (p.x, p.value, p.gradient);
111            if sy > 1e-12 * dot(&s, &s).sqrt() * dot(&y, &y).sqrt() {
112                if first {
113                    let scale = sy / dot(&y, &y);
114                    h.iter_mut().flatten().for_each(|v| *v *= scale);
115                    first = false;
116                }
117                // ANCHOR: bfgs_update
118                let rho = 1.0 / sy;
119                let hy: Vec<f64> = h.iter().map(|row| dot(row, &y)).collect();
120                let yhy = dot(&y, &hy);
121                for i in 0..n {
122                    for j in 0..n {
123                        h[i][j] += -rho * (hy[i] * s[j] + s[i] * hy[j]) + (rho * rho * yhy + rho) * s[i] * s[j];
124                    }
125                }
126                // ANCHOR_END: bfgs_update
127            }
128            converged = inf_norm(&g) <= tol;
129        }
130        Ok(OptimizationResult { parameters: x, objective_value: f, iterations, converged })
131    }
132}
133
134/// Limited-memory BFGS: keeps the last `memory` correction pairs `(s, y)` and applies the inverse
135/// Hessian by the two-loop recursion in O(memory · n), so it scales to large problems.
136#[derive(Debug, Clone)]
137pub struct Lbfgs {
138    max_iterations: Option<usize>,
139    tolerance: Option<f64>,
140    bounds: Option<Vec<(f64, f64)>>,
141    pub memory: usize,
142}
143
144impl Default for Lbfgs {
145    fn default() -> Self {
146        Lbfgs { max_iterations: None, tolerance: None, bounds: None, memory: 10 }
147    }
148}
149
150impl Lbfgs {
151    pub fn new(memory: usize) -> Self {
152        Lbfgs { memory: memory.max(1), ..Self::default() }
153    }
154}
155unbounded_controls!(Lbfgs);
156
157impl<T: ObjectiveFunction, U: GradientFunction> GradientBasedMinimizationEngine<T, U> for Lbfgs {
158    fn gradient_based_minimize(&self, objective: &T, gradient: &U, initial: Vec<f64>) -> Result<OptimizationResult, ErrorsJSL> {
159        let (mut f, mut g) = start(&self.bounds, objective, gradient, &initial)?;
160        let n = initial.len();
161        let tol = self.tolerance.unwrap_or(1e-8);
162        let max_iterations = self.max_iterations.unwrap_or(200 * n.max(5));
163        let mut x = initial;
164        let mut pairs: VecDeque<(Vec<f64>, Vec<f64>, f64)> = VecDeque::with_capacity(self.memory);
165        let mut iterations = 0;
166        let mut converged = inf_norm(&g) <= tol;
167        while !converged && iterations < max_iterations {
168            iterations += 1;
169            // ANCHOR: two_loop
170            // Two-loop recursion: d = −H g.
171            let mut q = g.clone();
172            let mut alphas = Vec::with_capacity(pairs.len());
173            for (s, y, rho) in pairs.iter().rev() {
174                let a = rho * dot(s, &q);
175                q.iter_mut().zip(y).for_each(|(v, yi)| *v -= a * yi);
176                alphas.push(a);
177            }
178            let gamma = pairs.back().map_or(1.0, |(s, y, _)| dot(s, y) / dot(y, y));
179            q.iter_mut().for_each(|v| *v *= gamma);
180            for ((s, y, rho), a) in pairs.iter().zip(alphas.iter().rev()) {
181                let b = rho * dot(y, &q);
182                q.iter_mut().zip(s).for_each(|(v, si)| *v += (a - b) * si);
183            }
184            // ANCHOR_END: two_loop
185            let mut d: Vec<f64> = q.iter().map(|v| -v).collect();
186            if dot(&d, &g) >= 0.0 {
187                pairs.clear();
188                d = g.iter().map(|v| -v).collect();
189            }
190            let step0 = if pairs.is_empty() { (1.0 / inf_norm(&g)).min(1.0) } else { 1.0 };
191            let Some(p) = strong_wolfe(objective, gradient, &x, f, &g, &d, step0, 1e-4, 0.9) else { break };
192            let s: Vec<f64> = p.x.iter().zip(&x).map(|(a, b)| a - b).collect();
193            let y: Vec<f64> = p.gradient.iter().zip(&g).map(|(a, b)| a - b).collect();
194            let sy = dot(&s, &y);
195            (x, f, g) = (p.x, p.value, p.gradient);
196            if sy > 1e-12 * dot(&s, &s).sqrt() * dot(&y, &y).sqrt() {
197                if pairs.len() == self.memory {
198                    pairs.pop_front();
199                }
200                pairs.push_back((s, y, 1.0 / sy));
201            }
202            converged = inf_norm(&g) <= tol;
203        }
204        Ok(OptimizationResult { parameters: x, objective_value: f, iterations, converged })
205    }
206}
207
208#[cfg(test)]
209pub(crate) mod test_problems {
210    use super::*;
211
212    /// The n-dimensional Rosenbrock function, minimum 0 at (1, …, 1).
213    pub struct Rosenbrock;
214    impl ObjectiveFunction for Rosenbrock {
215        fn evaluate(&self, p: &[f64]) -> f64 {
216            p.windows(2).map(|w| 100.0 * (w[1] - w[0] * w[0]).powi(2) + (1.0 - w[0]).powi(2)).sum()
217        }
218    }
219    impl GradientFunction for Rosenbrock {
220        fn evaluate(&self, p: &[f64]) -> Vec<f64> {
221            let mut g = vec![0.0; p.len()];
222            for i in 0..p.len() - 1 {
223                let t = p[i + 1] - p[i] * p[i];
224                g[i] += -400.0 * p[i] * t - 2.0 * (1.0 - p[i]);
225                g[i + 1] += 200.0 * t;
226            }
227            g
228        }
229    }
230
231    /// An ill-conditioned quadratic `½ Σ c_i x_i²` with `c_i` from 1 to 1e4.
232    pub struct Quadratic;
233    impl ObjectiveFunction for Quadratic {
234        fn evaluate(&self, p: &[f64]) -> f64 {
235            let n = p.len() as f64;
236            p.iter().enumerate().map(|(i, v)| 0.5 * 1e4f64.powf(i as f64 / (n - 1.0)) * v * v).sum()
237        }
238    }
239    impl GradientFunction for Quadratic {
240        fn evaluate(&self, p: &[f64]) -> Vec<f64> {
241            let n = p.len() as f64;
242            p.iter().enumerate().map(|(i, v)| 1e4f64.powf(i as f64 / (n - 1.0)) * v).collect()
243        }
244    }
245}
246
247#[cfg(test)]
248mod tests {
249    use super::test_problems::*;
250    use super::*;
251
252    #[test]
253    fn bfgs_and_lbfgs_minimize_rosenbrock() {
254        for n in [2, 10] {
255            let x0: Vec<f64> = (0..n).map(|i| if i % 2 == 0 { -1.2 } else { 1.0 }).collect();
256            let b = Bfgs::new().gradient_based_minimize(&Rosenbrock, &Rosenbrock, x0.clone()).unwrap();
257            assert!(b.converged && b.parameters.iter().all(|v| (v - 1.0).abs() < 1e-6), "bfgs n={n}: {b:?}");
258            let l = Lbfgs::new(7).gradient_based_minimize(&Rosenbrock, &Rosenbrock, x0).unwrap();
259            assert!(l.converged && l.parameters.iter().all(|v| (v - 1.0).abs() < 1e-6), "lbfgs n={n}: {l:?}");
260            assert!(b.iterations < 200 && l.iterations < 300, "{} {}", b.iterations, l.iterations);
261        }
262    }
263
264    #[test]
265    fn bfgs_is_finite_on_quadratics_and_lbfgs_scales() {
266        // With exact line searches BFGS terminates in n steps on a quadratic; with inexact Wolfe
267        // steps and a condition number of 1e4 it still needs only a few dozen (gradient descent
268        // would need tens of thousands).
269        let b = Bfgs::new().gradient_based_minimize(&Quadratic, &Quadratic, vec![1.0; 8]).unwrap();
270        assert!(b.converged && b.iterations < 80, "{}", b.iterations);
271        let l = Lbfgs::default().gradient_based_minimize(&Quadratic, &Quadratic, vec![1.0; 1000]).unwrap();
272        assert!(l.converged && l.objective_value < 1e-12, "{l:?}");
273    }
274
275    #[test]
276    fn validation() {
277        let mut b = Bfgs::new();
278        assert!(b.gradient_based_minimize(&Quadratic, &Quadratic, vec![]).is_err());
279        b.set_bounds(Some(vec![(0.0, 1.0)]));
280        assert!(b.gradient_based_minimize(&Quadratic, &Quadratic, vec![1.0]).is_err());
281        // Starting at the optimum converges immediately.
282        let r = Lbfgs::default().gradient_based_minimize(&Rosenbrock, &Rosenbrock, vec![1.0, 1.0]).unwrap();
283        assert!(r.converged && r.iterations == 0);
284    }
285}