Skip to main content

lib_jsl_optimization/
shgo.rs

1//! Simplicial homology global optimisation (Endres, Sandrock and Focke, 2018; SciPy's `shgo`
2//! with `sampling_method='simplicial'` (the default) or `'sobol'`).
3//!
4//! See the book entry [Global and combinatorial optimisation](https://jwkunz.github.io/lib_jsl/book/optimization/shgo-qap.html).
5
6use crate::constrained::{ConstrainedOptions, ConstrainedProblem};
7use crate::slsqp::{SlsqpOptions, slsqp};
8use lib_jsl_core::ErrorsJSL;
9use lib_jsl_geometry::algorithms::hull_nd::DelaunayNd;
10use lib_jsl_random::quasi_random::SobolSequence;
11
12/// How [`shgo`] samples the box.
13#[derive(Clone, Copy, Debug, PartialEq, Eq)]
14#[non_exhaustive]
15pub enum ShgoSampling {
16    /// SciPy's default: the `2^d` corners and the centre of the box, triangulated, and refined at each further
17    /// iteration by adding the midpoints of all edges. Practical up to about six variables.
18    Simplicial,
19    /// The first `n · iters` points of the (unscrambled) Sobol sequence, triangulated once.
20    Sobol,
21}
22
23/// Options for [`shgo`], with SciPy's defaults (simplicial sampling, one iteration).
24#[derive(Clone, Copy, Debug)]
25#[non_exhaustive]
26pub struct ShgoOptions {
27    pub sampling: ShgoSampling,
28    /// Sampling points per iteration (Sobol sampling only).
29    pub n: usize,
30    /// Iterations: with simplicial sampling each refines the complex; with Sobol sampling each adds `n`
31    /// points of the sequence.
32    pub iters: usize,
33    /// Tolerances of the local SLSQP solves (`tolerance` is SLSQP's `ftol`).
34    pub local: ConstrainedOptions,
35}
36
37impl Default for ShgoOptions {
38    fn default() -> Self {
39        ShgoOptions { sampling: ShgoSampling::Simplicial, n: 100, iters: 1, local: ConstrainedOptions { tolerance: 1e-10, max_iterations: 200 } }
40    }
41}
42
43impl ShgoOptions {
44    /// Sobol sampling with `n` points per iteration.
45    pub fn with_samples(n: usize, iters: usize) -> Self {
46        ShgoOptions { sampling: ShgoSampling::Sobol, n, iters, ..Default::default() }
47    }
48
49    /// Simplicial sampling with `iters` refinements.
50    pub fn simplicial(iters: usize) -> Self {
51        ShgoOptions { iters, ..Default::default() }
52    }
53}
54
55/// The result of [`shgo`].
56#[derive(Clone, Debug)]
57#[non_exhaustive]
58pub struct ShgoResult {
59    /// The global minimiser found and its value.
60    pub x: Vec<f64>,
61    pub fun: f64,
62    /// All distinct local minima found, sorted by value (SciPy's `xl`, `funl`).
63    pub xl: Vec<Vec<f64>>,
64    pub funl: Vec<f64>,
65    /// Sampling evaluations, local solves, and the sampled points that were minimisers.
66    pub nfev: usize,
67    pub nlfev: usize,
68    pub minimizers: Vec<Vec<f64>>,
69}
70
71/// Fills `nbrs` with the edges of the Delaunay triangulation of `pts` (in one dimension, of adjacent points).
72fn fill_neighbours(nbrs: &mut [Vec<usize>], pts: &[Vec<f64>]) -> Result<(), ErrorsJSL> {
73    if pts[0].len() == 1 {
74        let mut order: Vec<usize> = (0..pts.len()).collect();
75        order.sort_by(|&a, &b| pts[a][0].total_cmp(&pts[b][0]));
76        for w in order.windows(2) {
77            nbrs[w[0]].push(w[1]);
78            nbrs[w[1]].push(w[0]);
79        }
80    } else {
81        let tri = DelaunayNd::new(pts)?;
82        for s in &tri.simplices {
83            for &a in s {
84                for &b in s {
85                    if a != b && !nbrs[a].contains(&b) {
86                        nbrs[a].push(b);
87                    }
88                }
89            }
90        }
91    }
92    Ok(())
93}
94
95// ANCHOR: shgo
96/// Finds the global minimum of `problem` in the box `[lower, upper]` (with its inequality and
97/// equality constraints) by simplicial homology global optimisation.
98///
99/// The box is sampled either by a simplicial complex (the corners and centre of the box, refined `iters − 1`
100/// times by the midpoints of all edges; vertices violating an inequality get the value +∞) or by the first
101/// `n · iters` points of the (unscrambled) Sobol sequence (infeasible ones dropped); the vertices are
102/// Delaunay-triangulated. A
103/// sample whose value is lower than at all its neighbours in the triangulation is a
104/// *minimiser*: it approximates a local minimum, and the number of them estimates the number of
105/// basins (the rank of the complex's homology, in the language of the paper). A local SLSQP solve
106/// is started from each minimiser in order of value, and the distinct results are returned with
107/// the best of them.
108pub fn shgo<P: ConstrainedProblem>(problem: &P, lower: &[f64], upper: &[f64], options: ShgoOptions) -> Result<ShgoResult, ErrorsJSL> {
109    let d = lower.len();
110    if d == 0 || upper.len() != d || lower.iter().zip(upper).any(|(l, u)| l.is_nan() || u.is_nan() || l >= u) {
111        return Err(ErrorsJSL::InvalidInputRange("need finite bounds with lower < upper"));
112    }
113    let feasible = |x: &[f64]| !problem.inequalities(x).iter().any(|g| *g > 0.0);
114    let mut pts: Vec<Vec<f64>> = Vec::new();
115    let mut vals: Vec<f64> = Vec::new();
116    let mut nfev = 0;
117    let mut nbrs: Vec<Vec<usize>>;
118    match options.sampling {
119        ShgoSampling::Sobol => {
120            let mut sobol = SobolSequence::new(d)?;
121            let total = options.n * options.iters.max(1);
122            for _ in 0..total {
123                let u = sobol.next_point();
124                let x: Vec<f64> = u.iter().zip(lower.iter().zip(upper)).map(|(t, (l, h))| l + t * (h - l)).collect();
125                if !feasible(&x) {
126                    continue;
127                }
128                nfev += 1;
129                vals.push(problem.objective(&x));
130                pts.push(x);
131            }
132            if pts.len() < d + 2 {
133                return Err(ErrorsJSL::InvalidInputRange("too few feasible sampling points; increase n"));
134            }
135            nbrs = vec![Vec::new(); pts.len()];
136            fill_neighbours(&mut nbrs, &pts)?;
137        }
138        ShgoSampling::Simplicial => {
139            if d > 8 {
140                return Err(ErrorsJSL::InvalidInputRange("simplicial sampling is limited to 8 variables; use Sobol sampling"));
141            }
142            // The corners and the centre; infeasible vertices stay in the complex (with value +∞) so that
143            // the triangulation covers the whole box, and are never minimisers.
144            let mut all: Vec<Vec<f64>> = (0..1usize << d).map(|c| (0..d).map(|k| if c >> k & 1 == 1 { upper[k] } else { lower[k] }).collect()).collect();
145            all.push(lower.iter().zip(upper).map(|(l, h)| 0.5 * (l + h)).collect());
146            let scale = lower.iter().zip(upper).map(|(l, h)| h - l).fold(0.0f64, f64::max);
147            let mut done = 0;
148            let mut level = 1;
149            loop {
150                vals.extend((done..all.len()).map(|i| {
151                    if feasible(&all[i]) {
152                        nfev += 1;
153                        problem.objective(&all[i])
154                    } else {
155                        f64::INFINITY
156                    }
157                }));
158                done = all.len();
159                nbrs = vec![Vec::new(); all.len()];
160                fill_neighbours(&mut nbrs, &all)?;
161                if level >= options.iters.max(1) {
162                    break;
163                }
164                level += 1;
165                // Refinement: the midpoint of every edge.
166                let mut added: Vec<Vec<f64>> = Vec::new();
167                for i in 0..all.len() {
168                    for &j in nbrs[i].iter().filter(|&&j| j > i) {
169                        let m: Vec<f64> = all[i].iter().zip(&all[j]).map(|(a, b)| 0.5 * (a + b)).collect();
170                        if !all.iter().chain(&added).any(|q| q.iter().zip(&m).all(|(a, b)| (a - b).abs() <= 1e-9 * scale)) {
171                            added.push(m);
172                        }
173                    }
174                }
175                if added.is_empty() {
176                    break;
177                }
178                all.extend(added);
179            }
180            let finite: Vec<usize> = (0..all.len()).filter(|&i| vals[i].is_finite()).collect();
181            if finite.is_empty() {
182                return Err(ErrorsJSL::InvalidInputRange("no feasible vertex in the box"));
183            }
184            pts = all;
185        }
186    }
187    let mut minimizers: Vec<usize> = (0..pts.len()).filter(|&i| vals[i].is_finite() && !nbrs[i].is_empty() && nbrs[i].iter().all(|&j| vals[i] < vals[j])).collect();
188    minimizers.sort_by(|&a, &b| vals[a].total_cmp(&vals[b]));
189    let local = SlsqpOptions::new(options.local.tolerance, options.local.max_iterations);
190    let mut xl: Vec<Vec<f64>> = Vec::new();
191    let mut funl: Vec<f64> = Vec::new();
192    let mut nlfev = 0;
193    for &m in &minimizers {
194        nlfev += 1;
195        let r = slsqp(problem, pts[m].clone(), Some(lower), Some(upper), local)?;
196        if r.maxcv > 1e-6 || !r.fun.is_finite() {
197            continue;
198        }
199        let scale = lower.iter().zip(upper).map(|(l, h)| h - l).fold(0.0f64, f64::max);
200        let dup = xl.iter().any(|x| x.iter().zip(&r.x).map(|(a, b)| (a - b).abs()).fold(0.0f64, f64::max) <= 1e-6 * scale);
201        if !dup {
202            xl.push(r.x);
203            funl.push(r.fun);
204        }
205    }
206    let mut order: Vec<usize> = (0..xl.len()).collect();
207    // Minima that tie to 1e-8 keep the order in which their minimisers were found (as SciPy's list does), so that
208    // the "best" of equal minima does not depend on rounding noise.
209    order.sort_by(|&a, &b| (funl[a] * 1e8).round().total_cmp(&(funl[b] * 1e8).round()));
210    let xl: Vec<Vec<f64>> = order.iter().map(|&i| xl[i].clone()).collect();
211    let funl: Vec<f64> = order.iter().map(|&i| funl[i]).collect();
212    let (x, fun) = match xl.first() {
213        Some(x) => (x.clone(), funl[0]),
214        None => {
215            let b = (0..pts.len()).filter(|&i| vals[i].is_finite()).min_by(|&a, &b| vals[a].total_cmp(&vals[b])).unwrap();
216            (pts[b].clone(), vals[b])
217        }
218    };
219    Ok(ShgoResult { x, fun, xl, funl, nfev, nlfev, minimizers: minimizers.iter().map(|&m| pts[m].clone()).collect() })
220}
221// ANCHOR_END: shgo
222
223#[cfg(test)]
224mod tests {
225    use super::*;
226
227    struct Himmelblau;
228    impl ConstrainedProblem for Himmelblau {
229        fn objective(&self, x: &[f64]) -> f64 {
230            (x[0] * x[0] + x[1] - 11.0).powi(2) + (x[0] + x[1] * x[1] - 7.0).powi(2)
231        }
232    }
233
234    #[test]
235    fn finds_all_four_minima_of_himmelblau() {
236        let r = shgo(&Himmelblau, &[-5.0, -5.0], &[5.0, 5.0], ShgoOptions::with_samples(128, 1)).unwrap();
237        assert!(r.fun.abs() < 1e-10, "{}", r.fun);
238        // All four global minima, each with f = 0.
239        let four = r.funl.iter().filter(|f| f.abs() < 1e-8).count();
240        assert_eq!(four, 4, "{:?} {:?}", r.xl, r.funl);
241    }
242
243    #[test]
244    fn simplicial_sampling_refines_towards_the_four_minima() {
245        let one = shgo(&Himmelblau, &[-5.0, -5.0], &[5.0, 5.0], ShgoOptions::simplicial(1)).unwrap();
246        // The first complex (corners and centre: 5 points) resolves no more than one basin.
247        assert_eq!(one.nfev, 5);
248        assert!(!one.xl.is_empty() && one.xl.len() <= 1);
249        let r = shgo(&Himmelblau, &[-5.0, -5.0], &[5.0, 5.0], ShgoOptions::simplicial(4)).unwrap();
250        assert!(r.fun.abs() < 1e-10);
251        let more = shgo(&Himmelblau, &[-5.0, -5.0], &[5.0, 5.0], ShgoOptions::simplicial(4)).unwrap();
252        let four = more.funl.iter().filter(|f| f.abs() < 1e-8).count();
253        assert_eq!(four, 4, "{:?}", more.xl);
254        // With a constraint that removes two basins.
255        struct Half;
256        impl ConstrainedProblem for Half {
257            fn objective(&self, x: &[f64]) -> f64 {
258                Himmelblau.objective(x)
259            }
260            fn inequalities(&self, x: &[f64]) -> Vec<f64> {
261                vec![-x[0]]
262            }
263        }
264        let r = shgo(&Half, &[-5.0, -5.0], &[5.0, 5.0], ShgoOptions::simplicial(4)).unwrap();
265        assert!(r.xl.iter().all(|x| x[0] >= -1e-6) && r.xl.len() >= 2, "{:?}", r.xl);
266    }
267}