Skip to main content

lib_jsl_optimization/
conjugate_gradient.rs

1//! Nonlinear conjugate gradient minimization.
2//!
3//! See the book entry [Gradient descent and nonlinear conjugate gradients](https://jwkunz.github.io/lib_jsl/book/optimization/gradient-methods.html#nonlinear-conjugate-gradients).
4
5use crate::line_search::strong_wolfe;
6use crate::optimization_traits::{GradientBasedMinimizationEngine, GradientFunction, MinimizationControls, ObjectiveFunction, OptimizationResult};
7use crate::quasi_newton::{start, unbounded_controls};
8use lib_jsl_core::ErrorsJSL;
9
10fn dot(a: &[f64], b: &[f64]) -> f64 {
11    a.iter().zip(b).map(|(p, q)| p * q).sum()
12}
13
14/// The formula for `β` in the direction update `d ← −g + β d`.
15#[derive(Clone, Copy, Debug, PartialEq, Eq)]
16pub enum ConjugateGradientBeta {
17    /// `β = ‖g₊‖² / ‖g‖²`.
18    FletcherReeves,
19    /// `β = max(0, g₊ᵀ(g₊ − g) / ‖g‖²)`, PR+ (restarts automatically on lost conjugacy).
20    PolakRibierePlus,
21    /// `β = g₊ᵀy / dᵀy` with `y = g₊ − g`.
22    HestenesStiefel,
23    /// `β = ‖g₊‖² / dᵀy`.
24    DaiYuan,
25}
26
27/// Nonlinear conjugate gradients: O(n) memory, a strong Wolfe line search with `c₂ = 0.1`, the
28/// initial step of each line search scaled from the previous one (Nocedal and Wright eq. 3.60),
29/// and a restart to steepest descent every `n` iterations or whenever the direction is not a
30/// descent direction. Converges when `‖∇f‖∞` falls below the tolerance (default 1e-8). On a
31/// strictly convex quadratic with exact line searches every variant reduces to linear CG.
32#[derive(Debug, Clone)]
33pub struct NonlinearConjugateGradient {
34    max_iterations: Option<usize>,
35    tolerance: Option<f64>,
36    bounds: Option<Vec<(f64, f64)>>,
37    pub beta: ConjugateGradientBeta,
38}
39
40impl NonlinearConjugateGradient {
41    pub fn new(beta: ConjugateGradientBeta) -> Self {
42        NonlinearConjugateGradient { max_iterations: None, tolerance: None, bounds: None, beta }
43    }
44}
45
46impl Default for NonlinearConjugateGradient {
47    fn default() -> Self {
48        Self::new(ConjugateGradientBeta::PolakRibierePlus)
49    }
50}
51unbounded_controls!(NonlinearConjugateGradient);
52
53impl<T: ObjectiveFunction, U: GradientFunction> GradientBasedMinimizationEngine<T, U> for NonlinearConjugateGradient {
54    fn gradient_based_minimize(&self, objective: &T, gradient: &U, initial: Vec<f64>) -> Result<OptimizationResult, ErrorsJSL> {
55        let (mut f, mut g) = start(&self.bounds, objective, gradient, &initial)?;
56        let n = initial.len();
57        let tol = self.tolerance.unwrap_or(1e-8);
58        let max_iterations = self.max_iterations.unwrap_or(1000 * n.max(5));
59        let inf_norm = |v: &[f64]| v.iter().fold(0.0f64, |m, a| m.max(a.abs()));
60        let mut x = initial;
61        let mut d: Vec<f64> = g.iter().map(|v| -v).collect();
62        let mut step = (1.0 / inf_norm(&g).max(f64::MIN_POSITIVE)).min(1.0);
63        let mut previous_slope = dot(&g, &d);
64        let mut since_restart = 0;
65        let mut iterations = 0;
66        let mut converged = inf_norm(&g) <= tol;
67        while !converged && iterations < max_iterations {
68            iterations += 1;
69            let slope = dot(&g, &d);
70            if slope >= 0.0 {
71                d = g.iter().map(|v| -v).collect();
72                since_restart = 0;
73                continue;
74            }
75            let step0 = if iterations == 1 { step } else { (step * previous_slope / slope).clamp(1e-10, 1e10) };
76            let Some(p) = strong_wolfe(objective, gradient, &x, f, &g, &d, step0, 1e-4, 0.1) else {
77                if since_restart == 0 {
78                    break;
79                }
80                d = g.iter().map(|v| -v).collect();
81                since_restart = 0;
82                continue;
83            };
84            step = p.alpha;
85            previous_slope = slope;
86            let y: Vec<f64> = p.gradient.iter().zip(&g).map(|(a, b)| a - b).collect();
87            let gg = dot(&g, &g);
88            let new_gg = dot(&p.gradient, &p.gradient);
89            let dy = dot(&d, &y);
90            // ANCHOR: cg_direction
91            let beta = match self.beta {
92                ConjugateGradientBeta::FletcherReeves => new_gg / gg,
93                ConjugateGradientBeta::PolakRibierePlus => (dot(&p.gradient, &y) / gg).max(0.0),
94                ConjugateGradientBeta::HestenesStiefel => dot(&p.gradient, &y) / dy,
95                ConjugateGradientBeta::DaiYuan => new_gg / dy,
96            };
97            (x, f, g) = (p.x, p.value, p.gradient);
98            since_restart += 1;
99            let beta = if since_restart >= n || !beta.is_finite() {
100                since_restart = 0;
101                0.0
102            } else {
103                beta
104            };
105            d.iter_mut().zip(&g).for_each(|(di, gi)| *di = -gi + beta * *di);
106            // ANCHOR_END: cg_direction
107            converged = inf_norm(&g) <= tol;
108        }
109        Ok(OptimizationResult { parameters: x, objective_value: f, iterations, converged })
110    }
111}
112
113#[cfg(test)]
114mod tests {
115    use super::*;
116    use crate::quasi_newton::test_problems::{Quadratic, Rosenbrock};
117    use ConjugateGradientBeta::*;
118
119    #[test]
120    fn every_beta_formula_minimizes_rosenbrock() {
121        for beta in [FletcherReeves, PolakRibierePlus, HestenesStiefel, DaiYuan] {
122            let cg = NonlinearConjugateGradient::new(beta);
123            for n in [2, 6] {
124                let x0: Vec<f64> = (0..n).map(|i| if i % 2 == 0 { -1.2 } else { 1.0 }).collect();
125                let r = cg.gradient_based_minimize(&Rosenbrock, &Rosenbrock, x0).unwrap();
126                assert!(r.converged && r.parameters.iter().all(|v| (v - 1.0).abs() < 1e-6), "{beta:?} n={n}: {r:?}");
127            }
128        }
129    }
130
131    #[test]
132    fn handles_large_ill_conditioned_quadratics_and_validates() {
133        let r = NonlinearConjugateGradient::default().gradient_based_minimize(&Quadratic, &Quadratic, vec![1.0; 500]).unwrap();
134        assert!(r.converged && r.objective_value < 1e-12, "{r:?}");
135        let mut cg = NonlinearConjugateGradient::default();
136        assert!(cg.gradient_based_minimize(&Quadratic, &Quadratic, vec![]).is_err());
137        cg.set_bounds(Some(vec![(0.0, 1.0)]));
138        assert!(cg.gradient_based_minimize(&Quadratic, &Quadratic, vec![1.0]).is_err());
139    }
140}