Skip to main content

lib_jsl_optimization/
global.rs

1//! Global optimisation of functions with many local minima, following `scipy.optimize`: basin
2//! hopping (`basinhopping`), generalised simulated annealing with local search
3//! (`dual_annealing`), and the deterministic DIRECT algorithm (`direct`, the locally biased
4//! DIRECT-L variant that is SciPy's default).
5//!
6//! See the book entry [Assignment, trust regions and global optimisation](https://jwkunz.github.io/lib_jsl/book/optimization/assignment-trust-global.html#basin-hopping).
7
8use crate::bounded::{LbfgsbOptions, minimize_lbfgsb};
9use lib_jsl_core::ErrorsJSL;
10use lib_jsl_random::uniform_generator::{UniformGenerator, UniformRNG};
11use std::f64::consts::PI;
12
13/// The result of a global optimisation.
14#[derive(Clone, Debug)]
15#[non_exhaustive]
16pub struct GlobalResult {
17    pub x: Vec<f64>,
18    pub fun: f64,
19    /// Objective evaluations, including those for finite-difference gradients.
20    pub nfev: usize,
21    pub iterations: usize,
22}
23
24/// Counts evaluations and applies SciPy's two-point finite differences (`h = √ε max(1, |xᵢ|)`,
25/// stepping backwards at an upper bound).
26struct Counted<'a> {
27    f: &'a mut dyn FnMut(&[f64]) -> f64,
28    nfev: usize,
29}
30
31impl Counted<'_> {
32    fn eval(&mut self, x: &[f64]) -> f64 {
33        self.nfev += 1;
34        (self.f)(x)
35    }
36    fn value_and_gradient(&mut self, x: &[f64], ub: Option<&[f64]>) -> (f64, Vec<f64>) {
37        let fx = self.eval(x);
38        let mut g = vec![0.0; x.len()];
39        let mut xh = x.to_vec();
40        for i in 0..x.len() {
41            let mut h = f64::EPSILON.sqrt() * x[i].abs().max(1.0) * if x[i] < 0.0 { -1.0 } else { 1.0 };
42            if let Some(ub) = ub
43                && x[i] + h > ub[i]
44            {
45                h = -h.abs();
46            }
47            xh[i] = x[i] + h;
48            let dh = xh[i] - x[i];
49            g[i] = (self.eval(&xh) - fx) / dh;
50            xh[i] = x[i];
51        }
52        (fx, g)
53    }
54    /// L-BFGS-B from `x0` with finite-difference gradients.
55    fn local(&mut self, x0: &[f64], lb: &[f64], ub: &[f64], max_iterations: usize) -> (Vec<f64>, f64) {
56        let ub_owned = ub.to_vec();
57        let bounded = ub.iter().any(|v| v.is_finite());
58        let options = LbfgsbOptions { max_iterations, ..Default::default() };
59        match minimize_lbfgsb(|x| self.value_and_gradient(x, if bounded { Some(&ub_owned) } else { None }), x0, lb, ub, options) {
60            Ok(r) => (r.x, r.fun),
61            Err(_) => (x0.to_vec(), f64::INFINITY),
62        }
63    }
64}
65
66fn standard_normal(rng: &mut UniformRNG) -> f64 {
67    // Box-Muller.
68    let u1 = 1.0 - rng.next_f64();
69    let u2 = rng.next_f64();
70    (-2.0 * u1.ln()).sqrt() * (2.0 * PI * u2).cos()
71}
72
73// ------------------------------------------------------------------------------- basin hopping
74
75/// Options for [`basinhopping`] (SciPy's defaults).
76#[derive(Clone, Copy, Debug)]
77pub struct BasinhoppingOptions {
78    pub iterations: usize,
79    /// The Metropolis temperature `T`.
80    pub temperature: f64,
81    /// The initial maximum displacement of a random step.
82    pub stepsize: f64,
83    /// Adjust the step size every `interval` steps towards `target_accept_rate`.
84    pub interval: usize,
85    pub target_accept_rate: f64,
86    pub stepwise_factor: f64,
87    pub seed: u64,
88}
89
90impl Default for BasinhoppingOptions {
91    fn default() -> Self {
92        BasinhoppingOptions { iterations: 100, temperature: 1.0, stepsize: 0.5, interval: 50, target_accept_rate: 0.5, stepwise_factor: 0.9, seed: 0 }
93    }
94}
95
96// ANCHOR: basinhopping
97/// Basin hopping (Wales and Doye, 1997; SciPy's `basinhopping`): a random walk on the local
98/// minima. Each step displaces the current minimum uniformly by up to `stepsize` in every
99/// coordinate, minimises locally (L-BFGS-B with finite differences), and accepts the new minimum
100/// by the Metropolis rule `exp(−(f_new − f_old)/T) > u`. Every `interval` steps the step size is
101/// divided (or multiplied) by `stepwise_factor` if the acceptance rate is above (below) the
102/// target. Returns the lowest minimum seen.
103pub fn basinhopping(mut f: impl FnMut(&[f64]) -> f64, x0: &[f64], options: BasinhoppingOptions) -> GlobalResult {
104    let n = x0.len();
105    let (lb, ub) = (vec![f64::NEG_INFINITY; n], vec![f64::INFINITY; n]);
106    let mut c = Counted { f: &mut f, nfev: 0 };
107    let mut rng = UniformRNG::from_seed(options.seed);
108    let (mut x, mut fx) = c.local(x0, &lb, &ub, 15000);
109    let (mut best_x, mut best_f) = (x.clone(), fx);
110    let mut stepsize = options.stepsize;
111    let (mut nstep, mut naccept) = (0usize, 0usize);
112    for _ in 0..options.iterations {
113        let trial: Vec<f64> = x.iter().map(|v| v + stepsize * (2.0 * rng.next_f64() - 1.0)).collect();
114        let (xn, fn_) = c.local(&trial, &lb, &ub, 15000);
115        nstep += 1;
116        let accept = fn_ < fx || (-(fn_ - fx) / options.temperature).exp() > rng.next_f64();
117        if accept {
118            naccept += 1;
119            x = xn;
120            fx = fn_;
121            if fx < best_f {
122                best_f = fx;
123                best_x = x.clone();
124            }
125        }
126        if nstep % options.interval == 0 {
127            let rate = naccept as f64 / nstep as f64;
128            if rate > options.target_accept_rate {
129                stepsize /= options.stepwise_factor;
130            } else {
131                stepsize *= options.stepwise_factor;
132            }
133        }
134    }
135    GlobalResult { x: best_x, fun: best_f, nfev: c.nfev, iterations: options.iterations }
136}
137// ANCHOR_END: basinhopping
138
139// ------------------------------------------------------------------------------- dual annealing
140
141/// Options for [`dual_annealing`] (SciPy's defaults).
142#[derive(Clone, Copy, Debug)]
143pub struct DualAnnealingOptions {
144    pub max_iterations: usize,
145    pub initial_temp: f64,
146    pub restart_temp_ratio: f64,
147    /// The visiting distribution parameter `q_v ∈ (1, 3]`.
148    pub visit: f64,
149    /// The acceptance parameter `q_a < 1`.
150    pub accept: f64,
151    pub max_fun: usize,
152    pub no_local_search: bool,
153    pub seed: u64,
154}
155
156impl Default for DualAnnealingOptions {
157    fn default() -> Self {
158        DualAnnealingOptions { max_iterations: 1000, initial_temp: 5230.0, restart_temp_ratio: 2e-5, visit: 2.62, accept: -5.0, max_fun: 10_000_000, no_local_search: false, seed: 0 }
159    }
160}
161
162/// The Tsallis visiting distribution of generalised simulated annealing.
163struct Visiting {
164    q: f64,
165    lower: Vec<f64>,
166    range: Vec<f64>,
167    factor4_p: f64,
168    factor6: f64,
169}
170
171impl Visiting {
172    const TAIL_LIMIT: f64 = 1e8;
173    const MIN_VISIT_BOUND: f64 = 1e-10;
174
175    fn new(lower: &[f64], upper: &[f64], q: f64) -> Visiting {
176        let factor2 = ((4.0 - q) * (q - 1.0).ln()).exp();
177        let factor3 = ((2.0 - q) * 2f64.ln() / (q - 1.0)).exp();
178        let factor4_p = PI.sqrt() * factor2 / (factor3 * (3.0 - q));
179        let factor5 = 1.0 / (q - 1.0) - 0.5;
180        let d1 = 2.0 - factor5;
181        let factor6 = PI * (1.0 - factor5) / (PI * (1.0 - factor5)).sin() / lib_jsl_special_functions::ln_gamma(d1).exp();
182        Visiting { q, lower: lower.to_vec(), range: upper.iter().zip(lower).map(|(u, l)| u - l).collect(), factor4_p, factor6 }
183    }
184
185    /// One draw of the distortion: Mantegna's ratio of normals scaled by the temperature.
186    fn draw(&self, temperature: f64, rng: &mut UniformRNG) -> f64 {
187        let (x, y) = (standard_normal(rng), standard_normal(rng));
188        let factor1 = (temperature.ln() / (self.q - 1.0)).exp();
189        let factor4 = self.factor4_p * factor1;
190        let sigmax = (-(self.q - 1.0) * (self.factor6 / factor4).ln() / (3.0 - self.q)).exp();
191        let den = ((self.q - 1.0) * y.abs().ln() / (3.0 - self.q)).exp();
192        x * sigmax / den
193    }
194
195    fn wrap(&self, v: f64, i: usize) -> f64 {
196        let a = v - self.lower[i];
197        let b = a % self.range[i] + self.range[i];
198        let mut w = b % self.range[i] + self.lower[i];
199        if (w - self.lower[i]).abs() < Self::MIN_VISIT_BOUND {
200            w += Self::MIN_VISIT_BOUND;
201        }
202        w
203    }
204
205    /// A new point: every coordinate moved for the first `n` steps of a chain, one coordinate at
206    /// a time for the next `n`.
207    fn visit(&self, x: &[f64], step: usize, temperature: f64, rng: &mut UniformRNG) -> Vec<f64> {
208        let n = x.len();
209        let clip = |v: f64, rng: &mut UniformRNG| if v > Self::TAIL_LIMIT { Self::TAIL_LIMIT * rng.next_f64() } else if v < -Self::TAIL_LIMIT { -Self::TAIL_LIMIT * rng.next_f64() } else { v };
210        if step < n {
211            let visits: Vec<f64> = (0..n).map(|_| self.draw(temperature, rng)).collect();
212            visits.iter().enumerate().map(|(i, &v)| { let v = clip(v, rng); self.wrap(v + x[i], i) }).collect()
213        } else {
214            let mut out = x.to_vec();
215            let i = step - n;
216            let v = clip(self.draw(temperature, rng), rng);
217            out[i] = self.wrap(v + x[i], i);
218            out
219        }
220    }
221}
222
223// ANCHOR: dual_annealing
224/// Dual annealing (Xiang et al., 1997; SciPy's `dual_annealing`): generalised simulated
225/// annealing whose heavy-tailed Tsallis visiting distribution makes long jumps likely at high
226/// temperature, with the temperature falling as `T(t) = T₀ (2^{q_v−1} − 1)/((1 + t)^{q_v−1} − 1)`,
227/// acceptance of uphill moves with probability `[1 − (1 − q_a) ΔE/T]^{1/(1−q_a)}`, a local
228/// L-BFGS-B search whenever the best point improves (or nothing has improved for a long time), and
229/// re-annealing from a random point once the temperature falls below `restart_temp_ratio · T₀`.
230pub fn dual_annealing(mut f: impl FnMut(&[f64]) -> f64, lower: &[f64], upper: &[f64], options: DualAnnealingOptions) -> Result<GlobalResult, ErrorsJSL> {
231    let n = lower.len();
232    if upper.len() != n || lower.iter().zip(upper).any(|(l, u)| u <= l || u.is_nan() || !l.is_finite() || !u.is_finite()) {
233        return Err(ErrorsJSL::InvalidInputRange("need finite bounds with lower < upper"));
234    }
235    let o = options;
236    let mut c = Counted { f: &mut f, nfev: 0 };
237    let mut rng = UniformRNG::from_seed(o.seed);
238    let visiting = Visiting::new(lower, upper, o.visit);
239    let ls_max_iter = (n * 6).clamp(100, 1000);
240    let random_point = |rng: &mut UniformRNG| -> Vec<f64> { lower.iter().zip(upper).map(|(l, u)| l + (u - l) * rng.next_f64()).collect() };
241    // Energy state.
242    let mut current = random_point(&mut rng);
243    let mut e_current = c.eval(&current);
244    let mut reinit = 0;
245    while !e_current.is_finite() {
246        reinit += 1;
247        if reinit > 1000 {
248            return Err(ErrorsJSL::RuntimeError("could not find a finite starting value"));
249        }
250        current = random_point(&mut rng);
251        e_current = c.eval(&current);
252    }
253    let (mut xbest, mut ebest) = (current.clone(), e_current);
254    // Strategy chain state.
255    let (mut xmin, mut emin) = (current.clone(), e_current);
256    let mut not_improved = 0usize;
257    let mut not_improved_max = 1000usize;
258    let temperature_restart = o.initial_temp * o.restart_temp_ratio;
259    let t1 = ((o.visit - 1.0) * 2f64.ln()).exp() - 1.0;
260    let mut iteration = 0usize;
261    'outer: loop {
262        for i in 0..o.max_iterations {
263            let s = i as f64 + 2.0;
264            let t2 = ((o.visit - 1.0) * s.ln()).exp() - 1.0;
265            let temperature = o.initial_temp * t1 / t2;
266            if iteration >= o.max_iterations {
267                break 'outer;
268            }
269            if temperature < temperature_restart {
270                current = random_point(&mut rng);
271                e_current = c.eval(&current);
272                continue 'outer;
273            }
274            // One strategy chain.
275            let temperature_step = temperature / (i as f64 + 1.0);
276            not_improved += 1;
277            let mut improved = i == 0;
278            for j in 0..2 * n {
279                let x_visit = visiting.visit(&current, j, temperature, &mut rng);
280                let e = c.eval(&x_visit);
281                if e < e_current {
282                    current = x_visit;
283                    e_current = e;
284                    if e < ebest {
285                        ebest = e;
286                        xbest = current.clone();
287                        improved = true;
288                        not_improved = 0;
289                    }
290                } else {
291                    let r = rng.next_f64();
292                    let pqv_temp = 1.0 - (1.0 - o.accept) * (e - e_current) / temperature_step;
293                    let pqv = if pqv_temp <= 0.0 { 0.0 } else { (pqv_temp.ln() / (1.0 - o.accept)).exp() };
294                    if r <= pqv {
295                        current = x_visit;
296                        e_current = e;
297                        xmin = current.clone();
298                    }
299                    if not_improved >= not_improved_max && (j == 0 || e_current < emin) {
300                        emin = e_current;
301                        xmin = current.clone();
302                    }
303                }
304                if c.nfev >= o.max_fun {
305                    break 'outer;
306                }
307            }
308            if !o.no_local_search {
309                if improved {
310                    let (x, e) = c.local(&xbest, lower, upper, ls_max_iter);
311                    if e < ebest && x.iter().all(|v| v.is_finite()) {
312                        not_improved = 0;
313                        ebest = e;
314                        xbest = x.clone();
315                        current = x;
316                        e_current = e;
317                    }
318                    if c.nfev >= o.max_fun {
319                        break 'outer;
320                    }
321                }
322                if not_improved >= not_improved_max {
323                    let (x, e) = c.local(&xmin, lower, upper, ls_max_iter);
324                    let (x, e) = if e < emin { (x, e) } else { (xmin.clone(), emin) };
325                    xmin = x.clone();
326                    emin = e;
327                    not_improved = 0;
328                    not_improved_max = n;
329                    if e < ebest {
330                        ebest = e;
331                        xbest = x.clone();
332                        current = x;
333                        e_current = e;
334                    }
335                    if c.nfev >= o.max_fun {
336                        break 'outer;
337                    }
338                }
339            }
340            iteration += 1;
341        }
342    }
343    Ok(GlobalResult { x: xbest, fun: ebest, nfev: c.nfev, iterations: iteration })
344}
345// ANCHOR_END: dual_annealing
346
347// ------------------------------------------------------------------------------------- DIRECT
348
349/// Options for [`direct`] (SciPy's defaults; `max_fun` defaults to `1000 n`).
350#[derive(Clone, Copy, Debug)]
351pub struct DirectOptions {
352    /// The ε of the potential-optimality test.
353    pub eps: f64,
354    pub max_fun: Option<usize>,
355    pub max_iterations: usize,
356    /// Stop when the box holding the best point is smaller than this fraction of the domain.
357    pub vol_tol: f64,
358    /// Stop when half the longest side of that box (in the unit cube) is below this.
359    pub len_tol: f64,
360}
361
362impl Default for DirectOptions {
363    fn default() -> Self {
364        DirectOptions { eps: 1e-4, max_fun: None, max_iterations: 1000, vol_tol: 1e-16, len_tol: 1e-6 }
365    }
366}
367
368struct Box {
369    centre: Vec<f64>,
370    f: f64,
371    /// Side `k` has length `3^{−levels[k]}` in the unit cube.
372    levels: Vec<u32>,
373}
374
375impl Box {
376    fn size(&self) -> f64 {
377        3f64.powi(-(*self.levels.iter().min().expect("non-empty") as i32))
378    }
379}
380
381// ANCHOR: direct
382/// DIRECT, "DIviding RECTangles" (Jones, Perttunen and Stuckman, 1993), in Gablonsky and Kelley's
383/// locally biased form DIRECT-L. The domain is scaled to the unit cube and covered by boxes, each
384/// evaluated at its centre. Each iteration selects the *potentially optimal* boxes, those on the
385/// lower-right convex hull of (size, value), one per size, whose value could be the lowest for some
386/// Lipschitz constant `K` with a gain of at least `ε |f_min|`. Each selected box is trisected along
387/// its longest sides, the side whose new centres give the lowest value first. No gradients, no
388/// randomness: the search balances global exploration (large boxes) against local refinement.
389pub fn direct(mut f: impl FnMut(&[f64]) -> f64, lower: &[f64], upper: &[f64], options: DirectOptions) -> Result<GlobalResult, ErrorsJSL> {
390    let n = lower.len();
391    if upper.len() != n || n == 0 || lower.iter().zip(upper).any(|(l, u)| u <= l || u.is_nan() || l.is_nan()) {
392        return Err(ErrorsJSL::InvalidInputRange("need bounds with lower < upper"));
393    }
394    let o = options;
395    let max_fun = o.max_fun.unwrap_or(1000 * n);
396    let to_x = |c: &[f64]| -> Vec<f64> { c.iter().enumerate().map(|(i, v)| lower[i] + v * (upper[i] - lower[i])).collect() };
397    let nfev = std::cell::Cell::new(0usize);
398    let mut eval = |c: &[f64]| {
399        nfev.set(nfev.get() + 1);
400        f(&to_x(c))
401    };
402    let mut boxes = vec![Box { centre: vec![0.5; n], f: 0.0, levels: vec![0; n] }];
403    boxes[0].f = eval(&boxes[0].centre);
404    let mut best = 0usize;
405    let mut iterations = 0;
406    'outer: while iterations < o.max_iterations {
407        iterations += 1;
408        let fmin = boxes[best].f;
409        // One candidate per size: the lowest value (DIRECT-L).
410        let mut by_size: Vec<(f64, usize)> = Vec::new();
411        for (i, b) in boxes.iter().enumerate() {
412            let d = b.size();
413            match by_size.iter_mut().find(|(s, _)| (*s - d).abs() <= 1e-12 * d) {
414                Some(entry) => {
415                    if b.f < boxes[entry.1].f {
416                        entry.1 = i;
417                    }
418                }
419                None => by_size.push((d, i)),
420            }
421        }
422        by_size.sort_by(|a, b| a.0.total_cmp(&b.0));
423        // From the lowest value (the largest such box) to the largest box, the lower convex hull.
424        let start = (0..by_size.len()).min_by(|&a, &b| boxes[by_size[a].1].f.total_cmp(&boxes[by_size[b].1].f).then(by_size[b].0.total_cmp(&by_size[a].0))).expect("non-empty");
425        let mut hull: Vec<usize> = Vec::new();
426        for k in start..by_size.len() {
427            let p = (by_size[k].0, boxes[by_size[k].1].f);
428            while hull.len() >= 2 {
429                let a = (by_size[hull[hull.len() - 2]].0, boxes[by_size[hull[hull.len() - 2]].1].f);
430                let b = (by_size[hull[hull.len() - 1]].0, boxes[by_size[hull[hull.len() - 1]].1].f);
431                // Remove b if it lies on or above the segment a-p.
432                if (b.1 - a.1) * (p.0 - a.0) >= (p.1 - a.1) * (b.0 - a.0) {
433                    hull.pop();
434                } else {
435                    break;
436                }
437            }
438            if hull.len() == 1 && boxes[by_size[hull[0]].1].f <= p.1 && hull[0] != start {
439                hull.pop();
440            }
441            hull.push(k);
442        }
443        let mut selected = Vec::new();
444        for (h, &k) in hull.iter().enumerate() {
445            let (d, fj) = (by_size[k].0, boxes[by_size[k].1].f);
446            let ok = match hull.get(h + 1) {
447                Some(&next) => {
448                    let slope = (boxes[by_size[next].1].f - fj) / (by_size[next].0 - d);
449                    fj - slope * d <= fmin - o.eps * fmin.abs()
450                }
451                None => true,
452            };
453            if ok {
454                selected.push(by_size[k].1);
455            }
456        }
457        for idx in selected {
458            if nfev.get() >= max_fun {
459                break 'outer;
460            }
461            let lmin = *boxes[idx].levels.iter().min().expect("non-empty");
462            let dims: Vec<usize> = (0..n).filter(|&k| boxes[idx].levels[k] == lmin).collect();
463            let delta = 3f64.powi(-(lmin as i32 + 1));
464            // (best of the pair, dimension, centre +, value +, centre −, value −)
465            type Trial = (f64, usize, Vec<f64>, f64, Vec<f64>, f64);
466            let mut trials: Vec<Trial> = Vec::new();
467            for &k in &dims {
468                let mut cp = boxes[idx].centre.clone();
469                cp[k] += delta;
470                let fp = eval(&cp);
471                let mut cm = boxes[idx].centre.clone();
472                cm[k] -= delta;
473                let fm = eval(&cm);
474                trials.push((fp.min(fm), k, cp, fp, cm, fm));
475            }
476            trials.sort_by(|a, b| a.0.total_cmp(&b.0).then(a.1.cmp(&b.1)));
477            let mut levels = boxes[idx].levels.clone();
478            for (_, k, cp, fp, cm, fm) in trials {
479                levels[k] += 1;
480                boxes.push(Box { centre: cp, f: fp, levels: levels.clone() });
481                boxes.push(Box { centre: cm, f: fm, levels: levels.clone() });
482            }
483            boxes[idx].levels = levels;
484        }
485        best = (0..boxes.len()).min_by(|&a, &b| boxes[a].f.total_cmp(&boxes[b].f)).expect("non-empty");
486        let bb = &boxes[best];
487        let volume: f64 = bb.levels.iter().map(|&l| 3f64.powi(-(l as i32))).product();
488        if volume < o.vol_tol || 0.5 * bb.size() < o.len_tol || nfev.get() >= max_fun {
489            break;
490        }
491    }
492    let b = &boxes[best];
493    Ok(GlobalResult { x: to_x(&b.centre), fun: b.f, nfev: nfev.get(), iterations })
494}
495// ANCHOR_END: direct
496
497#[cfg(test)]
498mod tests {
499    use super::*;
500
501    fn rastrigin(x: &[f64]) -> f64 {
502        10.0 * x.len() as f64 + x.iter().map(|v| v * v - 10.0 * (2.0 * PI * v).cos()).sum::<f64>()
503    }
504    fn camel(x: &[f64]) -> f64 {
505        let (a, b) = (x[0], x[1]);
506        (4.0 - 2.1 * a * a + a.powi(4) / 3.0) * a * a + a * b + (-4.0 + 4.0 * b * b) * b * b
507    }
508
509    #[test]
510    fn dual_annealing_finds_the_rastrigin_minimum() {
511        let lb = vec![-5.12; 4];
512        let ub = vec![5.12; 4];
513        let r = dual_annealing(rastrigin, &lb, &ub, DualAnnealingOptions { seed: 3, ..Default::default() }).unwrap();
514        assert!(r.fun < 1e-8, "{r:?}");
515    }
516
517    #[test]
518    fn direct_and_basinhopping_find_the_six_hump_camel_minimum() {
519        let r = direct(camel, &[-3.0, -2.0], &[3.0, 2.0], DirectOptions::default()).unwrap();
520        assert!((r.fun + 1.031628453489877).abs() < 1e-4, "{r:?}");
521        let r = basinhopping(camel, &[2.0, 1.5], BasinhoppingOptions { seed: 1, iterations: 50, ..Default::default() });
522        assert!((r.fun + 1.031628453489877).abs() < 1e-8, "{r:?}");
523    }
524}