Skip to main content

lib_jsl_optimization/
brute.rs

1//! Brute-force minimisation over a grid (SciPy's `optimize.brute`).
2//!
3//! See the book entry [Brute force, isotonic regression and gradient checks](https://jwkunz.github.io/lib_jsl/book/optimization/brute-isotonic.html).
4
5use crate::nelder_mead_method::NelderMeadMethod;
6use crate::optimization_traits::{GradientFreeMinimizationEngine, MinimizationControls, ObjectiveFunction};
7use lib_jsl_core::ErrorsJSL;
8
9/// The result of [`brute`].
10#[derive(Clone, Debug)]
11#[non_exhaustive]
12pub struct BruteResult {
13    /// The minimiser: the best grid point, or the polished point when a finish was asked for.
14    pub x: Vec<f64>,
15    /// The objective at `x`.
16    pub fun: f64,
17    /// The grid's coordinates along each axis.
18    pub grid: Vec<Vec<f64>>,
19    /// The objective at every grid point, the last axis varying fastest.
20    pub values: Vec<f64>,
21}
22
23struct Wrapped<'a>(&'a dyn Fn(&[f64]) -> f64);
24
25impl ObjectiveFunction for Wrapped<'_> {
26    fn evaluate(&self, parameters: &[f64]) -> f64 {
27        (self.0)(parameters)
28    }
29}
30
31// ANCHOR: brute
32/// Minimises `f` by evaluating it at every point of the grid with `ns` equally spaced points
33/// from `lo` to `hi` (both included) on each axis (SciPy's `brute` with `(lo, hi)` ranges and
34/// `Ns = ns`, SciPy's default 20). With `finish`, the best grid point is polished by Nelder-Mead,
35/// as SciPy's default `finish = fmin`, and kept only if the polished point is better.
36pub fn brute(f: impl Fn(&[f64]) -> f64, ranges: &[(f64, f64)], ns: usize, finish: bool) -> Result<BruteResult, ErrorsJSL> {
37    if ranges.is_empty() || ns < 2 || ranges.iter().any(|(a, b)| !a.is_finite() || !b.is_finite()) {
38        return Err(ErrorsJSL::InvalidInputRange("brute: need at least one finite range and two points per axis"));
39    }
40    let d = ranges.len();
41    let total = ns.checked_pow(d as u32).filter(|&t| t <= 100_000_000).ok_or(ErrorsJSL::InvalidInputRange("brute: grid too large"))?;
42    let grid: Vec<Vec<f64>> = ranges.iter().map(|&(a, b)| (0..ns).map(|i| if i + 1 == ns { b } else { a + (b - a) * i as f64 / (ns - 1) as f64 }).collect()).collect();
43    let mut values = Vec::with_capacity(total);
44    let mut point = vec![0.0; d];
45    let (mut best, mut best_x) = (f64::INFINITY, vec![f64::NAN; d]);
46    for flat in 0..total {
47        let mut r = flat;
48        for k in (0..d).rev() {
49            point[k] = grid[k][r % ns];
50            r /= ns;
51        }
52        let v = f(&point);
53        // The first of equal minima, as NumPy's argmin.
54        if v < best || best_x[0].is_nan() {
55            best = v;
56            best_x.clone_from(&point);
57        }
58        values.push(v);
59    }
60    if finish {
61        let mut nm = NelderMeadMethod::new();
62        nm.set_tolerance(Some(1e-14));
63        nm.set_max_iterations(Some(5000));
64        if let Ok(r) = nm.gradient_free_minimize(&Wrapped(&f), best_x.clone())
65            && r.objective_value < best
66        {
67            best = r.objective_value;
68            best_x = r.parameters;
69        }
70    }
71    Ok(BruteResult { x: best_x, fun: best, grid, values })
72}
73// ANCHOR_END: brute
74
75#[cfg(test)]
76mod tests {
77    use super::*;
78
79    #[test]
80    fn grid_then_polish() {
81        // A shifted quadratic whose minimum (0.31, −0.77) is off the grid.
82        let f = |x: &[f64]| (x[0] - 0.31).powi(2) + 2.0 * (x[1] + 0.77).powi(2);
83        let r = brute(f, &[(-1.0, 1.0), (-1.0, 1.0)], 21, false).unwrap();
84        assert_eq!(r.values.len(), 441);
85        assert!((r.x[0] - 0.3).abs() < 1e-15 && (r.x[1] + 0.8).abs() < 1e-15);
86        let r = brute(f, &[(-1.0, 1.0), (-1.0, 1.0)], 21, true).unwrap();
87        assert!((r.x[0] - 0.31).abs() < 1e-6 && (r.x[1] + 0.77).abs() < 1e-6, "{:?}", r.x);
88    }
89}