lib_jsl_optimization/
golden_section_search.rs1use crate::optimization_traits::{
11 GradientFreeMinimizationEngine, MinimizationControls, ObjectiveFunction, OptimizationResult,
12};
13use lib_jsl_core::ErrorsJSL;
14
15pub 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 let inv_phi = (5.0_f64.sqrt() - 1.0) / 2.0; 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 (b, d, fd) = (d, c, fc);
94 c = b - inv_phi * (b - a);
95 fc = objective_function.evaluate(&[c]);
96 } else {
97 (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 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 (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 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 assert!(r.converged && (r.parameters[0] - 0.3).abs() < 1e-8, "{r:?}");
161 assert!(f.0.get() <= 42, "{} evaluations", f.0.get());
162 assert!(GoldenSectionSearch::new().gradient_free_minimize(&f, vec![0.5]).is_err());
164 }
165}