Skip to main content

lib_jsl_optimization/
powells_method.rs

1//! Powell's method: derivative-free minimisation by successive line searches along a set of
2//! conjugate directions.
3//!
4//! Starting from the coordinate axes, each iteration minimises the objective along every direction
5//! in turn, then tries the direction of the overall move. When that direction is a productive
6//! replacement it takes the place of the direction that contributed the largest decrease, so after
7//! `n` iterations the set is (for a quadratic) mutually conjugate and the minimum is reached
8//! exactly. The line searches use bracketing followed by Brent's parabolic/golden-section method.
9//!
10//! Bounds, if set, are enforced by clamping every trial point into the box, so the returned
11//! solution always lies inside it.
12//!
13//! See the book entry [Direct search](https://jwkunz.github.io/lib_jsl/book/optimization/direct-search.html#powells-method).
14
15use crate::optimization_traits::{GradientFreeMinimizationEngine, MinimizationControls, ObjectiveFunction, OptimizationResult};
16use lib_jsl_core::ErrorsJSL;
17
18#[derive(Debug, Clone, Default)]
19pub struct PowellsMethod {
20    max_iterations: Option<usize>,
21    tolerance: Option<f64>,
22    bounds: Option<Vec<(f64, f64)>>,
23}
24
25impl PowellsMethod {
26    pub fn new() -> Self {
27        Self::default()
28    }
29}
30
31impl MinimizationControls for PowellsMethod {
32    fn set_max_iterations(&mut self, max_iterations: Option<usize>) {
33        self.max_iterations = max_iterations;
34    }
35    fn get_max_iterations(&self) -> Option<usize> {
36        self.max_iterations
37    }
38    fn set_tolerance(&mut self, tolerance: Option<f64>) {
39        self.tolerance = tolerance;
40    }
41    fn get_tolerance(&self) -> Option<f64> {
42        self.tolerance
43    }
44    fn set_bounds(&mut self, bounds: Option<Vec<(f64, f64)>>) {
45        self.bounds = bounds;
46    }
47    fn get_bounds(&self) -> Option<Vec<(f64, f64)>> {
48        self.bounds.clone()
49    }
50}
51
52fn clamp_into(point: &mut [f64], bounds: &Option<Vec<(f64, f64)>>) {
53    if let Some(b) = bounds {
54        for (x, &(lo, hi)) in point.iter_mut().zip(b) {
55            *x = x.clamp(lo, hi);
56        }
57    }
58}
59
60/// Minimises `g(t)` along a line: brackets a minimum from `t = 0` and refines it with Brent's
61/// method. Returns `(t, g(t))`.
62fn line_search(g: &mut impl FnMut(f64) -> f64, tol: f64) -> (f64, f64) {
63    const GOLD: f64 = 1.618_033_988_749_895;
64    let (mut a, mut b) = (0.0, 1.0);
65    let (mut fa, mut fb) = (g(a), g(b));
66    if fb > fa {
67        // Downhill is the other way (or the step overshot): swap so b is the lower point.
68        std::mem::swap(&mut a, &mut b);
69        std::mem::swap(&mut fa, &mut fb);
70    }
71    // Now f(b) <= f(a). Expand away from a until the function rises.
72    let mut c = b + GOLD * (b - a);
73    let mut fc = g(c);
74    let mut guard = 0;
75    while fc < fb && guard < 60 {
76        let next = c + GOLD * (c - b);
77        (a, b, c) = (b, c, next);
78        (fa, fb, fc) = (fb, fc, g(c));
79        guard += 1;
80    }
81    let _ = fa;
82    // Brent on [min(a,c), max(a,c)] with b inside.
83    let (mut lo, mut hi) = (a.min(c), a.max(c));
84    let (mut x, mut w, mut v) = (b, b, b);
85    let (mut fx, mut fw, mut fv) = (fb, fb, fb);
86    let (mut d, mut e): (f64, f64) = (0.0, 0.0);
87    for _ in 0..100 {
88        let xm = 0.5 * (lo + hi);
89        let tol1 = tol * x.abs() + 1e-12;
90        let tol2 = 2.0 * tol1;
91        if (x - xm).abs() <= tol2 - 0.5 * (hi - lo) {
92            break;
93        }
94        let mut golden = true;
95        if e.abs() > tol1 {
96            let r = (x - w) * (fx - fv);
97            let mut q = (x - v) * (fx - fw);
98            let mut p = (x - v) * q - (x - w) * r;
99            q = 2.0 * (q - r);
100            if q > 0.0 {
101                p = -p;
102            }
103            q = q.abs();
104            if p.abs() < (0.5 * q * e).abs() && p > q * (lo - x) && p < q * (hi - x) {
105                e = d;
106                d = p / q;
107                let u = x + d;
108                if u - lo < tol2 || hi - u < tol2 {
109                    d = tol1.copysign(xm - x);
110                }
111                golden = false;
112            }
113        }
114        if golden {
115            e = if x >= xm { lo - x } else { hi - x };
116            d = 0.381_966_011_250_105_1 * e;
117        }
118        let u = if d.abs() >= tol1 { x + d } else { x + tol1.copysign(d) };
119        let fu = g(u);
120        if fu <= fx {
121            if u >= x { lo = x } else { hi = x }
122            (v, w, x) = (w, x, u);
123            (fv, fw, fx) = (fw, fx, fu);
124        } else {
125            if u < x { lo = u } else { hi = u }
126            if fu <= fw || w == x {
127                (v, w) = (w, u);
128                (fv, fw) = (fw, fu);
129            } else if fu <= fv || v == x || v == w {
130                v = u;
131                fv = fu;
132            }
133        }
134    }
135    (x, fx)
136}
137
138impl<T> GradientFreeMinimizationEngine<T> for PowellsMethod
139where
140    T: ObjectiveFunction,
141{
142    fn gradient_free_minimize(&self, objective_function: &T, initial_parameters: Vec<f64>) -> Result<OptimizationResult, ErrorsJSL> {
143        let n = initial_parameters.len();
144        if n == 0 {
145            return Err(ErrorsJSL::Misconfiguration("Initial parameters must be a non-empty vector."));
146        }
147        let bounds = self.get_bounds();
148        if let Some(b) = &bounds {
149            if b.len() != n {
150                return Err(ErrorsJSL::Misconfiguration("Bounds length must match the number of parameters."));
151            }
152            if b.iter().any(|&(lo, hi)| lo > hi) {
153                return Err(ErrorsJSL::Misconfiguration("Each bound must satisfy lower <= upper."));
154            }
155        }
156        let max_iterations = self.get_max_iterations().unwrap_or(1000);
157        let tol = self.get_tolerance().unwrap_or(1e-8);
158
159        let mut p = initial_parameters;
160        clamp_into(&mut p, &bounds);
161        let mut fp = objective_function.evaluate(&p);
162        if !fp.is_finite() {
163            return Err(ErrorsJSL::Misconfiguration("Objective is not finite at the initial point."));
164        }
165        let mut dirs: Vec<Vec<f64>> = (0..n).map(|i| (0..n).map(|j| f64::from(i == j)).collect()).collect();
166        let mut iterations = 0;
167        let mut converged = false;
168
169        // Minimise along `dir` starting at `from`; returns the new point and value.
170        let minimise_along = |from: &[f64], dir: &[f64]| -> (Vec<f64>, f64) {
171            let trial = |t: f64| -> Vec<f64> {
172                let mut x: Vec<f64> = from.iter().zip(dir).map(|(&a, &d)| a + t * d).collect();
173                clamp_into(&mut x, &bounds);
174                x
175            };
176            let mut g = |t: f64| objective_function.evaluate(&trial(t));
177            let (t, ft) = line_search(&mut g, 1e-3_f64.min(tol.sqrt()).max(1e-10));
178            (trial(t), ft)
179        };
180
181        while iterations < max_iterations {
182            iterations += 1;
183            // ANCHOR: powell_iteration
184            let (p0, f0) = (p.clone(), fp);
185            let (mut biggest, mut biggest_i) = (0.0, 0);
186            for (i, dir) in dirs.iter().enumerate() {
187                let before = fp;
188                let (x, fx) = minimise_along(&p, dir);
189                if fx < fp {
190                    (p, fp) = (x, fx);
191                }
192                if before - fp > biggest {
193                    biggest = before - fp;
194                    biggest_i = i;
195                }
196            }
197            if 2.0 * (f0 - fp) <= tol * (f0.abs() + fp.abs()) + 1e-300 {
198                converged = true;
199                break;
200            }
201            // Extrapolated point and the net displacement direction.
202            let net: Vec<f64> = p.iter().zip(&p0).map(|(a, b)| a - b).collect();
203            let mut extrapolated: Vec<f64> = p.iter().zip(&net).map(|(a, d)| a + d).collect();
204            clamp_into(&mut extrapolated, &bounds);
205            let fe = objective_function.evaluate(&extrapolated);
206            if fe < f0 {
207                let t = 2.0 * (f0 - 2.0 * fp + fe) * (f0 - fp - biggest).powi(2) - biggest * (f0 - fe).powi(2);
208                if t < 0.0 && net.iter().any(|&d| d != 0.0) {
209                    let (x, fx) = minimise_along(&p, &net);
210                    if fx < fp {
211                        (p, fp) = (x, fx);
212                    }
213                    let last = dirs.len() - 1;
214                    dirs.swap(biggest_i, last);
215                    dirs[last] = net;
216                }
217            }
218            // ANCHOR_END: powell_iteration
219        }
220        Ok(OptimizationResult { parameters: p, objective_value: fp, iterations, converged })
221    }
222}
223
224#[cfg(test)]
225mod tests {
226    use super::*;
227
228    struct Fn1<F: Fn(&[f64]) -> f64>(F);
229    impl<F: Fn(&[f64]) -> f64> ObjectiveFunction for Fn1<F> {
230        fn evaluate(&self, p: &[f64]) -> f64 {
231            (self.0)(p)
232        }
233    }
234
235    #[test]
236    fn quadratic_with_correlated_variables() {
237        // A positive-definite skewed bowl: minimum at (1, -2, 3) with coupled coordinates.
238        let f = Fn1(|p: &[f64]| {
239            let (x, y, z) = (p[0] - 1.0, p[1] + 2.0, p[2] - 3.0);
240            x * x + 10.0 * y * y + 5.0 * z * z + 4.0 * x * y + 3.0 * y * z + 7.0
241        });
242        let r = PowellsMethod::new().gradient_free_minimize(&f, vec![-4.0, 5.0, 0.0]).unwrap();
243        assert!(r.converged);
244        for (got, want) in r.parameters.iter().zip([1.0, -2.0, 3.0]) {
245            assert!((got - want).abs() < 1e-4, "{:?}", r.parameters);
246        }
247        assert!((r.objective_value - 7.0).abs() < 1e-8);
248    }
249
250    #[test]
251    fn rosenbrock_valley() {
252        let f = Fn1(|p: &[f64]| (1.0 - p[0]).powi(2) + 100.0 * (p[1] - p[0] * p[0]).powi(2));
253        let mut opt = PowellsMethod::new();
254        opt.set_tolerance(Some(1e-12));
255        let r = opt.gradient_free_minimize(&f, vec![-1.2, 1.0]).unwrap();
256        assert!((r.parameters[0] - 1.0).abs() < 1e-4 && (r.parameters[1] - 1.0).abs() < 1e-4, "{:?}", r.parameters);
257    }
258
259    #[test]
260    fn bounds_keep_the_solution_inside_the_box() {
261        let f = Fn1(|p: &[f64]| (p[0] - 3.0).powi(2) + (p[1] - 3.0).powi(2));
262        let mut opt = PowellsMethod::new();
263        opt.set_bounds(Some(vec![(-1.0, 2.0), (-1.0, 1.0)]));
264        let r = opt.gradient_free_minimize(&f, vec![0.0, 0.0]).unwrap();
265        assert!((r.parameters[0] - 2.0).abs() < 1e-6 && (r.parameters[1] - 1.0).abs() < 1e-6, "{:?}", r.parameters);
266    }
267
268    #[test]
269    fn one_dimension_and_errors() {
270        let f = Fn1(|p: &[f64]| (p[0] - 0.5).powi(4) + 1.0);
271        let r = PowellsMethod::new().gradient_free_minimize(&f, vec![10.0]).unwrap();
272        assert!((r.parameters[0] - 0.5).abs() < 1e-2);
273        assert!(PowellsMethod::new().gradient_free_minimize(&f, vec![]).is_err());
274        let mut bad = PowellsMethod::new();
275        bad.set_bounds(Some(vec![(1.0, 0.0)]));
276        assert!(bad.gradient_free_minimize(&f, vec![0.5]).is_err());
277        bad.set_bounds(Some(vec![(0.0, 1.0), (0.0, 1.0)]));
278        assert!(bad.gradient_free_minimize(&f, vec![0.5]).is_err());
279        let nan = Fn1(|_: &[f64]| f64::NAN);
280        assert!(PowellsMethod::new().gradient_free_minimize(&nan, vec![0.0]).is_err());
281    }
282}