Skip to main content

lib_jsl_optimization/
golden_section_search.rs

1//! Golden section search for the minimum of a unimodal function of one variable.
2//!
3//! The search keeps an interval `[a, b]` known to contain the minimum and two interior points at
4//! the golden-ratio positions `b − (b − a)/φ` and `a + (b − a)/φ`. Comparing `f` at them discards
5//! one end; the surviving interior point is exactly where one of the next pair must be, so each
6//! iteration costs one new evaluation and shrinks the interval by `1/φ ≈ 0.618`. No derivatives
7//! are used. For a function that is not unimodal on `[a, b]` it finds a local minimum.
8//!
9//! See the book entry [One-dimensional minimisation and line searches](https://jwkunz.github.io/lib_jsl/book/optimization/one-dimensional.html#golden-section-search).
10use crate::optimization_traits::{
11    GradientFreeMinimizationEngine, MinimizationControls, ObjectiveFunction, OptimizationResult,
12};
13use lib_jsl_core::ErrorsJSL;
14
15/// Golden section search on the interval given by `bounds` (required, one pair). The initial
16/// parameters are ignored apart from their length, which must be 1. Stops when the interval is
17/// shorter than the tolerance (default 1e-5) or after `max_iterations` (default 1000) iterations,
18/// and returns the midpoint of the final interval; `iterations` counts evaluations of `f`.
19pub struct GoldenSectionSearch {
20    max_iterations: Option<usize>,
21    tolerance: Option<f64>,
22    bounds: Option<Vec<(f64, f64)>>,
23}
24
25impl GoldenSectionSearch {
26    pub fn new() -> Self {
27        GoldenSectionSearch {
28            max_iterations: None,
29            tolerance: None,
30            bounds: None,
31        }
32    }
33}
34
35impl Default for GoldenSectionSearch {
36    fn default() -> Self {
37        Self::new()
38    }
39}
40
41impl MinimizationControls for GoldenSectionSearch {
42    fn set_max_iterations(&mut self, max_iterations: Option<usize>) {
43        self.max_iterations = max_iterations;
44    }
45    fn get_max_iterations(&self) -> Option<usize> {
46        self.max_iterations
47    }
48    fn set_tolerance(&mut self, tolerance: Option<f64>) {
49        self.tolerance = tolerance;
50    }
51    fn get_tolerance(&self) -> Option<f64> {
52        self.tolerance
53    }
54    fn set_bounds(&mut self, bounds: Option<Vec<(f64, f64)>>) {
55        self.bounds = bounds;
56    }
57    fn get_bounds(&self) -> Option<Vec<(f64, f64)>> {
58        self.bounds.clone()
59    }
60}
61
62impl<T> GradientFreeMinimizationEngine<T> for GoldenSectionSearch 
63where T: ObjectiveFunction {
64    fn gradient_free_minimize(
65        &self,
66        objective_function: &T,
67        initial_parameters: Vec<f64>,
68    ) -> Result<OptimizationResult, ErrorsJSL> {
69        if initial_parameters.len() != 1 {
70            return Err(ErrorsJSL::Misconfiguration("Golden section search only supports one-dimensional optimization.  That is, the initial parameters must be a single value."));
71        }
72        let Some(bounds) = self.get_bounds() else {
73            return Err(ErrorsJSL::Misconfiguration("Golden section search needs bounds giving the interval to search."));
74        };
75        if bounds.len() != 1 {
76            return Err(ErrorsJSL::Misconfiguration("Bounds length must match the number of parameters."));
77        }
78        let (mut a, mut b) = bounds[0];
79        if a > b || !a.is_finite() || !b.is_finite() {
80            return Err(ErrorsJSL::Misconfiguration("The bounds must be finite, with lower ≤ upper."));
81        }
82        let tolerance = self.tolerance.unwrap_or(1e-5);
83        let max_iterations = self.max_iterations.unwrap_or(1000);
84        // ANCHOR: golden
85        let inv_phi = (5.0_f64.sqrt() - 1.0) / 2.0; // 1/φ ≈ 0.618
86        let mut c = b - inv_phi * (b - a);
87        let mut d = a + inv_phi * (b - a);
88        let (mut fc, mut fd) = (objective_function.evaluate(&[c]), objective_function.evaluate(&[d]));
89        let mut evaluations = 2;
90        while b - a > tolerance && evaluations < max_iterations {
91            if fc < fd {
92                // The minimum is in [a, d]; the old c becomes the new d.
93                (b, d, fd) = (d, c, fc);
94                c = b - inv_phi * (b - a);
95                fc = objective_function.evaluate(&[c]);
96            } else {
97                // The minimum is in [c, b]; the old d becomes the new c.
98                (a, c, fc) = (c, d, fd);
99                d = a + inv_phi * (b - a);
100                fd = objective_function.evaluate(&[d]);
101            }
102            evaluations += 1;
103        }
104        // ANCHOR_END: golden
105        let x = 0.5 * (a + b);
106        let result = OptimizationResult {
107            parameters: vec![x],
108            objective_value: objective_function.evaluate(&[x]),
109            iterations: evaluations,
110            converged: b - a <= tolerance,
111        };
112        Ok(result)
113    }
114
115
116}
117
118#[cfg(test)]
119mod test {
120    use super::*;
121    struct TestObjectiveFunction;
122    impl ObjectiveFunction for TestObjectiveFunction {
123        fn evaluate(&self, parameters: &[f64]) -> f64 {
124            let x = parameters[0];
125            // This is a simple quadratic function with a minimum at x = 2.0 and a minimum value of 1.0.  It is unimodal, so it is suitable for testing the golden section search algorithm.
126            (x - 2.0).powi(2) + 1.0
127        }
128    }
129    #[test]
130    fn test_golden_section_search() {
131        let objective_function = TestObjectiveFunction;
132        let mut optimizer = GoldenSectionSearch::new();
133        optimizer.set_tolerance(Some(1e-6));
134        optimizer.set_max_iterations(Some(1000));
135        optimizer.set_bounds(Some(vec![(0.0, 4.0)]));   
136        let result = optimizer.gradient_free_minimize(&objective_function, vec![0.0]).unwrap();
137        //dbg!("Result: {:?}", &result);
138        assert!((result.parameters[0] - 2.0).abs() < 1e-3);
139        assert!((result.objective_value - 1.0).abs() < 1e-3);
140        assert!(result.converged);
141    }
142
143    #[test]
144    fn one_evaluation_per_iteration_and_errors_without_bounds() {
145        use std::cell::Cell;
146        struct Counting(Cell<usize>);
147        impl ObjectiveFunction for Counting {
148            fn evaluate(&self, p: &[f64]) -> f64 {
149                self.0.set(self.0.get() + 1);
150                (p[0] - 0.3).abs()
151            }
152        }
153        let f = Counting(Cell::new(0));
154        let mut gs = GoldenSectionSearch::new();
155        gs.set_tolerance(Some(1e-8));
156        gs.set_bounds(Some(vec![(0.0, 1.0)]));
157        let r = gs.gradient_free_minimize(&f, vec![0.5]).unwrap();
158        // 0.618^k < 1e-8 needs k = 39 reductions: 2 + 38 evaluations, plus one at the answer.
159        // The old version evaluated both interior points every time.
160        assert!(r.converged && (r.parameters[0] - 0.3).abs() < 1e-8, "{r:?}");
161        assert!(f.0.get() <= 42, "{} evaluations", f.0.get());
162        // Missing bounds once panicked on an unwrap.
163        assert!(GoldenSectionSearch::new().gradient_free_minimize(&f, vec![0.5]).is_err());
164    }
165}