Skip to main content

lib_jsl_optimization/
line_search.rs

1//! Line searches for gradient-based minimizers.
2//!
3//! See the book entry [One-dimensional minimisation and line searches](https://jwkunz.github.io/lib_jsl/book/optimization/one-dimensional.html#line-searches-and-the-wolfe-conditions).
4
5use crate::optimization_traits::{GradientFunction, ObjectiveFunction};
6
7/// A point accepted by a line search: `x = x₀ + alpha·d`, with its value and gradient.
8#[derive(Debug, Clone)]
9pub struct LineSearchPoint {
10    pub alpha: f64,
11    pub x: Vec<f64>,
12    pub value: f64,
13    pub gradient: Vec<f64>,
14}
15
16fn dot(a: &[f64], b: &[f64]) -> f64 {
17    a.iter().zip(b).map(|(p, q)| p * q).sum()
18}
19
20/// Finds a step `alpha > 0` along the descent direction `d` from `x0` satisfying the strong Wolfe
21/// conditions
22///
23/// `f(x₀ + αd) ≤ f(x₀) + c₁ α ∇f(x₀)·d` and `|∇f(x₀ + αd)·d| ≤ c₂ |∇f(x₀)·d|`
24///
25/// (Nocedal and Wright, algorithms 3.5 and 3.6: bracketing by doubling, then zooming with
26/// safeguarded cubic interpolation). Use `c₂ ≈ 0.9` for quasi-Newton methods and `c₂ ≈ 0.1` for
27/// nonlinear conjugate gradients. Returns `None` if `d` is not a descent direction or no
28/// decreasing point is found; if the Wolfe conditions cannot be met to rounding precision, the
29/// best decreasing point found is returned.
30#[allow(clippy::too_many_arguments)]
31pub fn strong_wolfe<T, U>(
32    objective: &T,
33    gradient: &U,
34    x0: &[f64],
35    f0: f64,
36    g0: &[f64],
37    d: &[f64],
38    initial_step: f64,
39    c1: f64,
40    c2: f64,
41) -> Option<LineSearchPoint>
42where
43    T: ObjectiveFunction + ?Sized,
44    U: GradientFunction + ?Sized,
45{
46    let slope0 = dot(g0, d);
47    if slope0.is_nan() || slope0 >= 0.0 {
48        return None;
49    }
50    let eval = |alpha: f64| {
51        let x: Vec<f64> = x0.iter().zip(d).map(|(a, b)| a + alpha * b).collect();
52        let value = objective.evaluate(&x);
53        let g = gradient.evaluate(&x);
54        let slope = dot(&g, d);
55        (LineSearchPoint { alpha, x, value, gradient: g }, slope)
56    };
57    let sufficient = |p: &LineSearchPoint| p.value <= f0 + c1 * p.alpha * slope0;
58    let curvature = |slope: f64| slope.abs() <= -c2 * slope0;
59
60    let zoom = |mut lo: (LineSearchPoint, f64), mut hi: (LineSearchPoint, f64)| -> Option<LineSearchPoint> {
61        for _ in 0..60 {
62            let (a, b) = (lo.0.alpha, hi.0.alpha);
63            let width = (b - a).abs();
64            // Cubic interpolation of φ on [a, b] from values and slopes, safeguarded to the interior.
65            let d1 = lo.1 + hi.1 - 3.0 * (lo.0.value - hi.0.value) / (a - b);
66            let disc = d1 * d1 - lo.1 * hi.1;
67            let mut t = if disc >= 0.0 {
68                let d2 = (b - a).signum() * disc.sqrt();
69                b - (b - a) * (hi.1 + d2 - d1) / (hi.1 - lo.1 + 2.0 * d2)
70            } else {
71                f64::NAN
72            };
73            let (left, right) = (a.min(b), a.max(b));
74            if !t.is_finite() || t < left + 0.1 * width || t > right - 0.1 * width {
75                t = 0.5 * (a + b);
76            }
77            let (p, slope) = eval(t);
78            if !sufficient(&p) || p.value >= lo.0.value {
79                hi = (p, slope);
80            } else {
81                if curvature(slope) {
82                    return Some(p);
83                }
84                if slope * (hi.0.alpha - lo.0.alpha) >= 0.0 {
85                    hi = lo;
86                }
87                lo = (p, slope);
88            }
89            if width <= 1e-14 * right.max(1e-300) {
90                break;
91            }
92        }
93        (lo.0.value < f0).then_some(lo.0)
94    };
95
96    // ANCHOR: wolfe_bracket
97    let start = LineSearchPoint { alpha: 0.0, x: x0.to_vec(), value: f0, gradient: g0.to_vec() };
98    let mut prev = (start, slope0);
99    let mut alpha = initial_step;
100    for i in 0..60 {
101        let (p, slope) = eval(alpha);
102        if !p.value.is_finite() {
103            // Stepped outside the domain: shrink towards the last good point.
104            alpha = 0.5 * (prev.0.alpha + alpha);
105            continue;
106        }
107        if !sufficient(&p) || (i > 0 && p.value >= prev.0.value) {
108            return zoom(prev, (p, slope));
109        }
110        if curvature(slope) {
111            return Some(p);
112        }
113        if slope >= 0.0 {
114            return zoom((p, slope), prev);
115        }
116        alpha *= 2.0;
117        prev = (p, slope);
118    }
119    (prev.0.value < f0).then_some(prev.0)
120    // ANCHOR_END: wolfe_bracket
121}
122
123#[cfg(test)]
124mod tests {
125    use super::*;
126
127    struct Quartic;
128    impl ObjectiveFunction for Quartic {
129        fn evaluate(&self, p: &[f64]) -> f64 {
130            (p[0] - 3.0).powi(4) + p[1] * p[1]
131        }
132    }
133    impl GradientFunction for Quartic {
134        fn evaluate(&self, p: &[f64]) -> Vec<f64> {
135            vec![4.0 * (p[0] - 3.0).powi(3), 2.0 * p[1]]
136        }
137    }
138
139    #[test]
140    fn accepted_steps_satisfy_the_strong_wolfe_conditions() {
141        let x0 = [0.0, 1.0];
142        let f0 = ObjectiveFunction::evaluate(&Quartic, &x0);
143        let g0 = GradientFunction::evaluate(&Quartic, &x0);
144        let d: Vec<f64> = g0.iter().map(|v| -v).collect();
145        let slope0 = dot(&g0, &d);
146        for (step, c2) in [(1.0, 0.9), (1e-6, 0.9), (10.0, 0.1), (1e-3, 0.1)] {
147            let p = strong_wolfe(&Quartic, &Quartic, &x0, f0, &g0, &d, step, 1e-4, c2).unwrap();
148            assert!(p.value <= f0 + 1e-4 * p.alpha * slope0);
149            assert!(dot(&p.gradient, &d).abs() <= -c2 * slope0, "step {step} c2 {c2}");
150        }
151        // An ascent direction is rejected.
152        assert!(strong_wolfe(&Quartic, &Quartic, &x0, f0, &g0, &g0, 1.0, 1e-4, 0.9).is_none());
153    }
154}