Skip to main content

lib_jsl_optimization/
nelder_mead_method.rs

1//! This file implements the Nelder-Mead method for optimization. 
2//! The Nelder-Mead method is a gradient-free optimization algorithm that is used to find the minimum of a function. 
3//! The algorithm works by maintaining a simplex of n+1 points in n-dimensional space, where each point represents a candidate solution to the optimization problem. 
4//! The algorithm iteratively updates the simplex by performing operations such as reflection, expansion, contraction, and shrinkage, based on the function values at the vertices of the simplex. 
5//! The algorithm continues until it reaches a point where the function values at the vertices of the simplex are sufficiently close to each other, indicating that it has found a local minimum. 
6//! The Nelder-Mead method can be effective for optimizing non-convex functions and functions with noisy gradients, but it can also be computationally expensive and may require careful tuning of the algorithm's parameters to achieve good performance.  
7//!
8//! See the book entry [Direct search](https://jwkunz.github.io/lib_jsl/book/optimization/direct-search.html#the-nelder-mead-simplex-method).
9
10use crate::optimization_traits::{GradientFreeMinimizationEngine, MinimizationControls, ObjectiveFunction, OptimizationResult};
11use lib_jsl_core::ErrorsJSL;
12
13pub struct NelderMeadMethod {
14    max_iterations: Option<usize>,
15    tolerance: Option<f64>,
16    bounds: Option<Vec<(f64, f64)>>,
17}
18
19impl NelderMeadMethod {
20    pub fn new() -> Self {
21        NelderMeadMethod {
22            max_iterations: None,
23            tolerance: None,
24            bounds: None,
25        }
26    }
27}
28
29impl Default for NelderMeadMethod {
30    fn default() -> Self {
31        Self::new()
32    }
33}
34
35impl MinimizationControls for NelderMeadMethod {
36    fn set_max_iterations(&mut self, max_iterations: Option<usize>) {
37        self.max_iterations = max_iterations;
38    }
39    fn get_max_iterations(&self) -> Option<usize> {
40        self.max_iterations
41    }
42    fn set_tolerance(&mut self, tolerance: Option<f64>) {
43        self.tolerance = tolerance;
44    }
45    fn get_tolerance(&self) -> Option<f64> {
46        self.tolerance
47    }
48    fn set_bounds(&mut self, bounds: Option<Vec<(f64, f64)>>) {
49        self.bounds = bounds;
50    }
51    fn get_bounds(&self) -> Option<Vec<(f64, f64)>> {
52        self.bounds.clone()
53    }
54}
55
56impl<T> GradientFreeMinimizationEngine<T> for NelderMeadMethod 
57where T: ObjectiveFunction {
58    fn gradient_free_minimize(
59        &self,
60        objective_function: &T,
61        initial_parameters: Vec<f64>,
62    ) -> Result<OptimizationResult, ErrorsJSL> {
63        if initial_parameters.is_empty() {
64            return Err(ErrorsJSL::Misconfiguration("Initial parameters must be a non-empty vector."));
65        }
66
67        let dimension = initial_parameters.len();
68        let max_iterations = self.get_max_iterations().unwrap_or(1000);
69        let tolerance = self.get_tolerance().unwrap_or(1e-8);
70        let bounds = self.get_bounds();
71
72        if let Some(ref b) = bounds {
73            if b.len() != dimension {
74                return Err(ErrorsJSL::Misconfiguration(
75                    "Bounds length must match the number of parameters.",
76                ));
77            }
78            for (lower, upper) in b.iter() {
79                if lower > upper {
80                    return Err(ErrorsJSL::Misconfiguration(
81                        "Each bound must satisfy lower <= upper.",
82                    ));
83                }
84            }
85        }
86
87        let alpha = 1.0;
88        let gamma = 2.0;
89        let rho = 0.5;
90        let sigma = 0.5;
91
92        let mut simplex: Vec<Vec<f64>> = Vec::with_capacity(dimension + 1);
93        let start = project_to_bounds(&initial_parameters, bounds.as_deref());
94        simplex.push(start.clone());
95        for i in 0..dimension {
96            // The initial simplex steps 5% of each coordinate (or 2.5e-4 from zero), as MATLAB's
97            // fminsearch does; at an upper bound it steps down instead, since a step projected
98            // back onto the bound would give a degenerate (flat) simplex.
99            let step = if start[i].abs() > 1e-12 { 0.05 * start[i].abs() } else { 2.5e-4 };
100            let mut vertex = start.clone();
101            vertex[i] += step;
102            let mut vertex = project_to_bounds(&vertex, bounds.as_deref());
103            if vertex[i] == start[i] {
104                vertex[i] -= step;
105                vertex = project_to_bounds(&vertex, bounds.as_deref());
106            }
107            simplex.push(vertex);
108        }
109
110        let mut values: Vec<f64> = simplex.iter().map(|x| objective_function.evaluate(x)).collect();
111
112        let mut result = OptimizationResult {
113            parameters: simplex[0].clone(),
114            objective_value: values[0],
115            iterations: 0,
116            converged: false,
117        };
118
119        for iteration in 0..max_iterations {
120            sort_simplex(&mut simplex, &mut values);
121
122            result.parameters = simplex[0].clone();
123            result.objective_value = values[0];
124            result.iterations = iteration + 1;
125
126            if function_value_stddev(&values) <= tolerance {
127                result.converged = true;
128                return Ok(result);
129            }
130
131            // ANCHOR: nelder_mead_step
132            let centroid = centroid_excluding_worst(&simplex);
133            let worst = &simplex[dimension];
134            let second_worst_value = values[dimension - 1];
135            let worst_value = values[dimension];
136
137            let reflected = combine(&centroid, worst, 1.0 + alpha, -alpha);
138            let reflected = project_to_bounds(&reflected, bounds.as_deref());
139            let reflected_value = objective_function.evaluate(&reflected);
140
141            if reflected_value < values[0] {
142                let expanded = combine(&centroid, &reflected, 1.0 - gamma, gamma);
143                let expanded = project_to_bounds(&expanded, bounds.as_deref());
144                let expanded_value = objective_function.evaluate(&expanded);
145                if expanded_value < reflected_value {
146                    simplex[dimension] = expanded;
147                    values[dimension] = expanded_value;
148                } else {
149                    simplex[dimension] = reflected;
150                    values[dimension] = reflected_value;
151                }
152                continue;
153            }
154
155            if reflected_value < second_worst_value {
156                simplex[dimension] = reflected;
157                values[dimension] = reflected_value;
158                continue;
159            }
160
161            if reflected_value < worst_value {
162                let outside_contracted = combine(&centroid, &reflected, 1.0 - rho, rho);
163                let outside_contracted = project_to_bounds(&outside_contracted, bounds.as_deref());
164                let outside_contracted_value = objective_function.evaluate(&outside_contracted);
165                if outside_contracted_value <= reflected_value {
166                    simplex[dimension] = outside_contracted;
167                    values[dimension] = outside_contracted_value;
168                    continue;
169                }
170            } else {
171                let inside_contracted = combine(&centroid, worst, 1.0 - rho, rho);
172                let inside_contracted = project_to_bounds(&inside_contracted, bounds.as_deref());
173                let inside_contracted_value = objective_function.evaluate(&inside_contracted);
174                if inside_contracted_value < worst_value {
175                    simplex[dimension] = inside_contracted;
176                    values[dimension] = inside_contracted_value;
177                    continue;
178                }
179            }
180
181            let best = simplex[0].clone();
182            for i in 1..=dimension {
183                simplex[i] = combine(&best, &simplex[i], 1.0 - sigma, sigma);
184                simplex[i] = project_to_bounds(&simplex[i], bounds.as_deref());
185                values[i] = objective_function.evaluate(&simplex[i]);
186            }
187            // ANCHOR_END: nelder_mead_step
188        }
189
190        sort_simplex(&mut simplex, &mut values);
191        result.parameters = simplex[0].clone();
192        result.objective_value = values[0];
193        result.converged = function_value_stddev(&values) <= tolerance;
194        Ok(result)
195    }
196}
197
198fn project_to_bounds(parameters: &[f64], bounds: Option<&[(f64, f64)]>) -> Vec<f64> {
199    if let Some(bounds) = bounds {
200        parameters
201            .iter()
202            .zip(bounds.iter())
203            .map(|(&value, &(lower, upper))| {
204                if value < lower {
205                    lower
206                } else if value > upper {
207                    upper
208                } else {
209                    value
210                }
211            })
212            .collect()
213    } else {
214        parameters.to_owned()
215    }
216}
217
218fn combine(a: &[f64], b: &[f64], wa: f64, wb: f64) -> Vec<f64> {
219    a.iter()
220        .zip(b.iter())
221        .map(|(&x, &y)| wa * x + wb * y)
222        .collect()
223}
224
225fn centroid_excluding_worst(simplex: &[Vec<f64>]) -> Vec<f64> {
226    let dimension = simplex[0].len();
227    let count = simplex.len() - 1;
228    let mut centroid = vec![0.0; dimension];
229    for point in simplex.iter().take(count) {
230        for i in 0..dimension {
231            centroid[i] += point[i];
232        }
233    }
234    for value in centroid.iter_mut() {
235        *value /= count as f64;
236    }
237    centroid
238}
239
240fn function_value_stddev(values: &[f64]) -> f64 {
241    let mean = values.iter().sum::<f64>() / values.len() as f64;
242    let variance = values
243        .iter()
244        .map(|v| {
245            let dv = *v - mean;
246            dv * dv
247        })
248        .sum::<f64>()
249        / values.len() as f64;
250    variance.sqrt()
251}
252
253fn sort_simplex(simplex: &mut Vec<Vec<f64>>, values: &mut Vec<f64>) {
254    let mut indexed: Vec<(Vec<f64>, f64)> = simplex.drain(..).zip(values.drain(..)).collect();
255    indexed.sort_by(|a, b| a.1.total_cmp(&b.1));
256    for (point, value) in indexed {
257        simplex.push(point);
258        values.push(value);
259    }
260}
261
262#[cfg(test)]
263mod tests {
264    use super::*;
265
266    struct TestObjectiveFunction;
267
268    impl ObjectiveFunction for TestObjectiveFunction {
269        fn evaluate(&self, parameters: &[f64]) -> f64 {
270            let x = parameters[0];
271            let y = parameters[1];
272            (x - 2.0).powi(2) + (y + 1.0).powi(2) + 3.0
273        }
274    }
275
276    #[test]
277    fn test_nelder_mead_method() {
278        let objective = TestObjectiveFunction;
279        let mut optimizer = NelderMeadMethod::new();
280        optimizer.set_max_iterations(Some(2000));
281        optimizer.set_tolerance(Some(1e-10));
282        optimizer.set_bounds(Some(vec![(-5.0, 5.0), (-5.0, 5.0)]));
283
284        let result = optimizer
285            .gradient_free_minimize(&objective, vec![0.0, 0.0])
286            .unwrap();
287
288        dbg!("Result: {:?}", &result);
289        assert!(result.converged);
290        assert!((result.parameters[0] - 2.0).abs() < 1e-3);
291        assert!((result.parameters[1] + 1.0).abs() < 1e-3);
292        assert!((result.objective_value - 3.0).abs() < 1e-6);
293    }
294
295    #[test]
296    fn a_start_on_the_upper_bound_does_not_flatten_the_simplex() {
297        // Minimum at (2, −1) inside the box; the start x = 3 is on the upper bound. The step to
298        // x = 3.15 was projected back to 3, so the simplex never left the line x = 3.
299        let mut nm = NelderMeadMethod::new();
300        nm.set_bounds(Some(vec![(0.0, 3.0), (-5.0, 5.0)]));
301        let r = nm.gradient_free_minimize(&TestObjectiveFunction, vec![3.0, 1.0]).unwrap();
302        assert!((r.parameters[0] - 2.0).abs() < 1e-3 && (r.parameters[1] + 1.0).abs() < 1e-3, "{r:?}");
303    }
304}