Skip to main content

evolutionary_planning/
cmaes.rs

1//! CMA-ES, the covariance matrix adaptation evolution strategy, exactly as in Hansen's
2//! tutorial (arXiv:1604.00772): Figure 6 with the default parameters of Table 1, including
3//! the negative ("active") recombination weights, `h_σ` and `δ(h_σ)`, the rescaling (46) of
4//! negatively weighted steps, the lazy eigendecomposition of Appendix B.2 (each one
5//! warm-started from the previous eigenbasis) and the termination criteria of Appendix B.3. IPOP restarts (Auger and Hansen 2005) with growing
6//! population size are in [`Ipop`].
7//!
8//! ```mermaid
9//! graph LR
10//!     ask["ask: z ~ N(0, I), y = B D z, x = m + σ y"] --> eval[evaluate and rank]
11//!     eval --> mean["m += c_m σ ⟨y⟩_w"]
12//!     mean --> psigma["p_σ, σ (43, 44)"]
13//!     psigma --> pc["h_σ, p_c (45)"]
14//!     pc --> cov["C (46, 47)"]
15//!     cov --> eigen["every k generations: C = B D² Bᵀ"]
16//!     eigen --> stop{B.3 criteria}
17//!     stop -->|continue| ask
18//! ```
19//!
20//! Two interfaces: ask-and-tell ([`CmaEs::ask`], [`CmaEs::tell`]) for callers that evaluate
21//! a batch themselves (for example in parallel), and [`CmaEs::minimize`] with a budget.
22//!
23//! ```
24//! use evolutionary_planning::cmaes::{CmaEs, Config};
25//! use evolutionary_planning::problems::single::rosenbrock;
26//! use evolutionary_planning::{Limits, SplitMix64};
27//!
28//! let mut cma = CmaEs::new(vec![0.0; 4], 0.5, Config::default());
29//! let mut objective = |x: &Vec<f64>| rosenbrock(x);
30//! let outcome = cma.minimize(&mut objective, &mut Limits::evaluations(20_000).with_target(1e-10), &mut (), &mut SplitMix64::new(1));
31//! assert!(outcome.best_cost() <= 1e-10);
32//! ```
33
34mod eigen;
35mod params;
36mod termination;
37
38use alloc::vec::Vec;
39
40use rand_core::Rng;
41
42pub use params::Parameters;
43use termination::History;
44pub use termination::Termination;
45
46use crate::evaluator::Evaluator;
47use crate::operators::real::Bounds;
48use crate::rng::{standard_normal, uniform};
49use crate::{
50    Budget, Event, Individual, Objective, Observer, Outcome, Stats, Stop, ranking, sanitize,
51};
52
53/// Evaluated candidates of one generation (repaired points with their objective values).
54type Population = Vec<Individual<Vec<f64>>>;
55
56/// User-settable options of a [`CmaEs`] run; everything else follows Table 1.
57#[derive(Debug, Clone, PartialEq)]
58pub struct Config {
59    /// The population size λ; `None` means the default `4 + ⌊3 ln n⌋`. Increasing it improves
60    /// global search at the price of speed; decreasing it is not recommended.
61    pub lambda: Option<usize>,
62    /// TolFun: stop when recent best costs and the current generation's costs lie within this
63    /// range. Default `1e-12`.
64    pub tol_fun: f64,
65    /// TolX: stop when all standard deviations and `σ p_c` fall below this. `None` means
66    /// `1e-12` times the initial σ.
67    pub tol_x: Option<f64>,
68    /// TolXUp: stop when `σ max(diag D)` grew by more than this factor. Default `1e4`.
69    pub tol_x_up: f64,
70    /// ConditionCov: stop when the condition number of C exceeds this. Default `1e14`.
71    pub max_condition: f64,
72    /// Box bounds, handled by the penalisation (63) of Appendix B.5 in
73    /// [`CmaEs::minimize`]: the objective is evaluated at the closest point in the box, and
74    /// `penalty · ‖x - x_repaired‖²` is added for ranking only. `None` is unbounded.
75    pub bounds: Option<Bounds>,
76    /// The penalty factor α of (63); choose it so that penalty and cost differences have a
77    /// similar magnitude. Default `1`.
78    pub penalty: f64,
79}
80
81impl Default for Config {
82    fn default() -> Self {
83        Self {
84            lambda: None,
85            tol_fun: 1e-12,
86            tol_x: None,
87            tol_x_up: 1e4,
88            max_condition: 1e14,
89            bounds: None,
90            penalty: 1.0,
91        }
92    }
93}
94
95/// The state of one CMA-ES run.
96#[derive(Debug, Clone, PartialEq)]
97pub struct CmaEs {
98    /// The options.
99    config: Config,
100    /// The strategy parameters of Table 1.
101    params: Parameters,
102    /// The distribution mean `m`.
103    mean: Vec<f64>,
104    /// The step size `σ`.
105    sigma: f64,
106    /// The covariance matrix `C`, row-major `n × n`, symmetric.
107    covariance: Vec<f64>,
108    /// The eigenvectors of `C` as columns of a row-major matrix `B`, from the last
109    /// decomposition.
110    basis: Vec<f64>,
111    /// The square roots of the eigenvalues of `C`, the diagonal of `D`.
112    scales: Vec<f64>,
113    /// The evolution path of the step size, `p_σ`.
114    path_sigma: Vec<f64>,
115    /// The evolution path of the rank-one update, `p_c`.
116    path_c: Vec<f64>,
117    /// Completed generations `g`.
118    generation: u64,
119    /// The generation of the last eigendecomposition.
120    decomposed_at: u64,
121    /// `σ_0 · max(diag D_0)`, the reference of TolXUp.
122    initial_scale: f64,
123    /// The TolX threshold.
124    tol_x: f64,
125    /// Whether the last decomposition found a non-positive eigenvalue.
126    degenerate: bool,
127    /// The standard normal samples `z_k` of the current generation.
128    z: Vec<Vec<f64>>,
129    /// The steps `y_k = B D z_k` of the current generation.
130    y: Vec<Vec<f64>>,
131    /// The candidates `x_k = m + σ y_k` of the current generation.
132    x: Vec<Vec<f64>>,
133    /// Whether `ask` was called since the last `tell`.
134    asked: bool,
135    /// Cost history for the termination criteria.
136    history: History,
137}
138
139impl CmaEs {
140    /// Starts a run at `mean` with step size `sigma` and `C = I`.
141    ///
142    /// The tutorial advises that the optimum should lie within `mean ± 3σ`; for a search
143    /// interval `[a, b]` per coordinate, a uniform mean and `σ = 0.3 (b - a)` work well.
144    ///
145    /// # Panics
146    ///
147    /// Panics if `mean` is empty, `sigma` is not positive and finite, or the configured λ is
148    /// below 2.
149    #[must_use]
150    pub fn new(mean: Vec<f64>, sigma: f64, config: Config) -> Self {
151        let n = mean.len();
152
153        Self::with_covariance(mean, sigma, eigen::identity(n), config)
154    }
155
156    /// Starts a run with a given covariance matrix (row-major `n × n`, symmetric positive
157    /// definite), for example to warm-start from a previous run's [`CmaEs::covariance`] or
158    /// to encode different search ranges per coordinate (`c_ii = Δs_i²`).
159    ///
160    /// # Panics
161    ///
162    /// Panics as [`CmaEs::new`], or if `covariance` has the wrong size.
163    #[must_use]
164    pub fn with_covariance(
165        mean: Vec<f64>,
166        sigma: f64,
167        covariance: Vec<f64>,
168        config: Config,
169    ) -> Self {
170        let n = mean.len();
171        assert!(n > 0, "CMA-ES needs at least one dimension");
172        assert!(
173            sigma > 0.0 && sigma.is_finite(),
174            "the step size must be positive and finite"
175        );
176        assert_eq!(covariance.len(), n * n, "the covariance must be n × n");
177
178        let lambda = config
179            .lambda
180            .unwrap_or_else(|| Parameters::default_lambda(n));
181        let params = Parameters::new(n, lambda);
182        let tol_x = config.tol_x.unwrap_or(1e-12 * sigma);
183        let mut cma = Self {
184            config,
185            params,
186            mean,
187            sigma,
188            covariance,
189            basis: Vec::new(),
190            scales: Vec::new(),
191            path_sigma: alloc::vec![0.0; n],
192            path_c: alloc::vec![0.0; n],
193            generation: 0,
194            decomposed_at: 0,
195            initial_scale: 0.0,
196            tol_x,
197            degenerate: false,
198            z: Vec::new(),
199            y: Vec::new(),
200            x: Vec::new(),
201            asked: false,
202            history: History::default(),
203        };
204        cma.decompose();
205        cma.initial_scale = cma.sigma * cma.max_scale();
206
207        cma
208    }
209
210    /// The strategy parameters in use.
211    #[must_use]
212    pub fn parameters(&self) -> &Parameters {
213        &self.params
214    }
215
216    /// The distribution mean `m`, the current estimate of the optimum.
217    #[must_use]
218    pub fn mean(&self) -> &[f64] {
219        &self.mean
220    }
221
222    /// The step size `σ`.
223    #[must_use]
224    pub fn sigma(&self) -> f64 {
225        self.sigma
226    }
227
228    /// The covariance matrix `C`, row-major `n × n`.
229    #[must_use]
230    pub fn covariance(&self) -> &[f64] {
231        &self.covariance
232    }
233
234    /// Completed generations.
235    #[must_use]
236    pub fn generation(&self) -> u64 {
237        self.generation
238    }
239
240    /// The condition number of `C` from the last decomposition, `+∞` if degenerate.
241    #[must_use]
242    pub fn condition(&self) -> f64 {
243        if self.degenerate {
244            return f64::INFINITY;
245        }
246
247        let max = self.max_scale();
248        let min = self.scales.iter().copied().fold(f64::INFINITY, f64::min);
249
250        (max / min) * (max / min)
251    }
252
253    /// Moves the mean, keeping σ, C and the evolution paths: a warm start for a shifted
254    /// problem, such as the next control period of a receding-horizon planner.
255    ///
256    /// # Panics
257    ///
258    /// Panics if `mean` has the wrong dimension.
259    pub fn set_mean(&mut self, mean: Vec<f64>) {
260        assert_eq!(
261            mean.len(),
262            self.mean.len(),
263            "the mean must keep its dimension"
264        );
265        self.mean = mean;
266        self.asked = false;
267    }
268
269    /// Samples the λ candidates of the next generation, (38)–(40).
270    pub fn ask<R: Rng + ?Sized>(&mut self, rng: &mut R) -> &[Vec<f64>] {
271        let n = self.params.n;
272        let lambda = self.params.lambda;
273        self.z.resize_with(lambda, || alloc::vec![0.0; n]);
274        self.y.resize_with(lambda, || alloc::vec![0.0; n]);
275        self.x.resize_with(lambda, || alloc::vec![0.0; n]);
276        for k in 0..lambda {
277            for zi in &mut self.z[k] {
278                *zi = standard_normal(rng);
279            }
280
281            for i in 0..n {
282                let mut yi = 0.0;
283                for j in 0..n {
284                    yi += self.basis[i * n + j] * self.scales[j] * self.z[k][j];
285                }
286                self.y[k][i] = yi;
287                self.x[k][i] = self.mean[i] + self.sigma * yi;
288            }
289        }
290
291        self.asked = true;
292        &self.x
293    }
294
295    /// Updates the distribution from the costs of the last [`CmaEs::ask`]ed candidates, in
296    /// the same order, (41)–(47); returns the termination criterion that fired, if any.
297    ///
298    /// NaN costs count as `+∞`.
299    ///
300    /// # Panics
301    ///
302    /// Panics if `ask` was not called since the last `tell`, or `costs.len() != λ`.
303    pub fn tell(&mut self, costs: &[f64]) -> Option<Termination> {
304        assert!(self.asked, "tell without ask");
305        assert_eq!(costs.len(), self.params.lambda, "one cost per candidate");
306        self.asked = false;
307
308        let costs: Vec<f64> = costs.iter().map(|&c| sanitize(c)).collect();
309        let order = ranking(&costs);
310        self.update(&order);
311        self.generation += 1;
312        if self.generation - self.decomposed_at >= self.params.eigen_interval() {
313            self.decompose();
314        }
315
316        let sorted: Vec<f64> = order.iter().map(|&k| costs[k]).collect();
317        self.history.push(&sorted);
318
319        self.termination(&sorted)
320    }
321
322    /// The distribution update (41)–(47) for the ranking `order` of the current candidates.
323    fn update(&mut self, order: &[usize]) {
324        let p = &self.params;
325        let n = p.n;
326        let mut y_w = alloc::vec![0.0; n];
327        let mut z_w = alloc::vec![0.0; n];
328        for (i, &k) in order.iter().take(p.mu).enumerate() {
329            for j in 0..n {
330                y_w[j] += p.weights[i] * self.y[k][j];
331                z_w[j] += p.weights[i] * self.z[k][j];
332            }
333        }
334
335        for j in 0..n {
336            self.mean[j] += p.c_m * self.sigma * y_w[j];
337        }
338
339        let norm_ps = self.update_path_sigma(&z_w);
340        let h_sigma = self.h_sigma(norm_ps);
341        let p = &self.params;
342        let factor = h_sigma * libm::sqrt(p.c_c * (2.0 - p.c_c) * p.mu_eff);
343        for j in 0..n {
344            self.path_c[j] = (1.0 - p.c_c) * self.path_c[j] + factor * y_w[j];
345        }
346
347        self.update_covariance(order, h_sigma);
348        let p = &self.params;
349        self.sigma *= libm::exp(p.c_sigma / p.d_sigma * (norm_ps / p.chi_n - 1.0));
350    }
351
352    /// The step-size path update (43), with `C^{-1/2} ⟨y⟩_w = B ⟨z⟩_w`; returns `‖p_σ‖`.
353    fn update_path_sigma(&mut self, z_w: &[f64]) -> f64 {
354        let p = &self.params;
355        let n = p.n;
356        let factor = libm::sqrt(p.c_sigma * (2.0 - p.c_sigma) * p.mu_eff);
357        let mut norm = 0.0;
358        for i in 0..n {
359            let bz: f64 = (0..n).map(|j| self.basis[i * n + j] * z_w[j]).sum();
360            self.path_sigma[i] = (1.0 - p.c_sigma) * self.path_sigma[i] + factor * bz;
361            norm += self.path_sigma[i] * self.path_sigma[i];
362        }
363
364        libm::sqrt(norm)
365    }
366
367    /// The Heaviside function `h_σ`, using the generation number `g + 1` of this update: the
368    /// correction `sqrt(1 - (1 - c_σ)^(2 (g + 1)))` equals Appendix C's
369    /// `sqrt(1 - (1 - cs)^(2 counteval / lambda))`, as `counteval = λ (g + 1)` there.
370    fn h_sigma(&self, norm_ps: f64) -> f64 {
371        let p = &self.params;
372        #[expect(
373            clippy::cast_precision_loss,
374            reason = "generation counts are far below 2^52"
375        )]
376        let g1 = (self.generation + 1) as f64;
377        let correction = libm::sqrt(1.0 - libm::pow(1.0 - p.c_sigma, 2.0 * g1));
378        #[expect(clippy::cast_precision_loss, reason = "dimensions are far below 2^52")]
379        let threshold = (1.4 + 2.0 / (p.n as f64 + 1.0)) * p.chi_n;
380
381        if norm_ps / correction < threshold {
382            1.0
383        } else {
384            0.0
385        }
386    }
387
388    /// The covariance update (46)–(47).
389    fn update_covariance(&mut self, order: &[usize], h_sigma: f64) {
390        let p = &self.params;
391        let n = p.n;
392        #[expect(clippy::cast_precision_loss, reason = "dimensions are far below 2^52")]
393        let nf = n as f64;
394        let delta = (1.0 - h_sigma) * p.c_c * (2.0 - p.c_c);
395        let decay = 1.0 + p.c_1 * delta - p.c_1 - p.c_mu * p.weight_sum();
396        let rank_weights: Vec<f64> = order
397            .iter()
398            .enumerate()
399            .map(|(i, &k)| {
400                let w = p.weights[i];
401                if w >= 0.0 {
402                    w
403                } else {
404                    // ‖C^{-1/2} y‖² = ‖B z‖² = ‖z‖², since B is orthonormal.
405                    let z2: f64 = self.z[k].iter().map(|v| v * v).sum();
406                    w * nf / z2
407                }
408            })
409            .collect();
410
411        for i in 0..n {
412            for j in i..n {
413                let mut rank_mu = 0.0;
414                for (rank, &k) in order.iter().enumerate() {
415                    rank_mu += rank_weights[rank] * self.y[k][i] * self.y[k][j];
416                }
417
418                let value = decay * self.covariance[i * n + j]
419                    + p.c_1 * self.path_c[i] * self.path_c[j]
420                    + p.c_mu * rank_mu;
421                self.covariance[i * n + j] = value;
422                self.covariance[j * n + i] = value;
423            }
424        }
425    }
426
427    /// Recomputes `B` and `D` from `C`.
428    fn decompose(&mut self) {
429        let n = self.params.n;
430        let eigen = if self.basis.len() == n * n {
431            eigen::decompose_in_basis(&self.covariance, n, &self.basis)
432        } else {
433            eigen::decompose(&self.covariance, n)
434        };
435        self.degenerate = eigen.values.iter().any(|&v| !(v > 0.0 && v.is_finite()));
436        self.scales = eigen
437            .values
438            .iter()
439            .map(|&v| libm::sqrt(v.max(f64::MIN_POSITIVE)))
440            .collect();
441        self.basis = eigen.vectors;
442        self.decomposed_at = self.generation;
443    }
444
445    /// The largest diagonal element of `D`.
446    fn max_scale(&self) -> f64 {
447        self.scales.iter().copied().fold(0.0, f64::max)
448    }
449
450    /// Checks the criteria of Appendix B.3 in the tutorial's order.
451    fn termination(&self, sorted_costs: &[f64]) -> Option<Termination> {
452        let n = self.params.n;
453        let window = self.fun_window();
454        let checks = [
455            (Termination::NoEffectAxis, self.no_effect_axis()),
456            (Termination::NoEffectCoord, self.no_effect_coord()),
457            (
458                Termination::ConditionCov,
459                self.condition() > self.config.max_condition,
460            ),
461            (
462                Termination::EqualFunValues,
463                self.history.recent_best_range(window) == Some(0.0),
464            ),
465            (
466                Termination::Stagnation,
467                self.history.stagnated(120 + window - 10, self.generation),
468            ),
469            (
470                Termination::TolXUp,
471                self.sigma * self.max_scale() > self.config.tol_x_up * self.initial_scale,
472            ),
473            (Termination::TolFun, self.tol_fun(sorted_costs, window)),
474            (Termination::TolX, self.tol_x_reached(n)),
475        ];
476
477        checks
478            .into_iter()
479            .find_map(|(criterion, fired)| fired.then_some(criterion))
480    }
481
482    /// The window `10 + ⌈30 n / λ⌉` of EqualFunValues and TolFun.
483    fn fun_window(&self) -> usize {
484        10 + (30 * self.params.n).div_ceil(self.params.lambda)
485    }
486
487    /// NoEffectAxis: `m == m + 0.1 σ d_i b_i` for `i = g mod n`.
488    #[expect(
489        clippy::float_cmp,
490        reason = "the criterion is exact floating-point equality"
491    )]
492    fn no_effect_axis(&self) -> bool {
493        let n = self.params.n;
494        #[expect(
495            clippy::cast_possible_truncation,
496            reason = "the remainder is below n, a usize"
497        )]
498        let axis = (self.generation % n as u64) as usize;
499        let step = 0.1 * self.sigma * self.scales[axis];
500
501        (0..n).all(|k| self.mean[k] + step * self.basis[k * n + axis] == self.mean[k])
502    }
503
504    /// NoEffectCoord: `m_i == m_i + 0.2 σ sqrt(c_ii)` for some `i`.
505    #[expect(
506        clippy::float_cmp,
507        reason = "the criterion is exact floating-point equality"
508    )]
509    fn no_effect_coord(&self) -> bool {
510        let n = self.params.n;
511
512        (0..n).any(|i| {
513            let step = 0.2 * self.sigma * libm::sqrt(self.covariance[i * n + i]);
514            self.mean[i] + step == self.mean[i]
515        })
516    }
517
518    /// TolFun: recent best costs and the current costs all within `tol_fun`.
519    fn tol_fun(&self, sorted_costs: &[f64], window: usize) -> bool {
520        let Some((low, high)) = self.history.recent_best_bounds(window) else {
521            return false;
522        };
523
524        let low = low.min(sorted_costs[0]);
525        let high = high.max(sorted_costs[sorted_costs.len() - 1]);
526
527        high - low < self.config.tol_fun
528    }
529
530    /// TolX: every `σ sqrt(c_ii)` and every `|σ p_c,i|` below the threshold.
531    fn tol_x_reached(&self, n: usize) -> bool {
532        (0..n).all(|i| {
533            self.sigma * libm::sqrt(self.covariance[i * n + i]) < self.tol_x
534                && (self.sigma * self.path_c[i]).abs() < self.tol_x
535        })
536    }
537
538    /// Minimises `objective` until the budget or a termination criterion stops the run.
539    ///
540    /// A generation interrupted by the budget is not told; every evaluated candidate still
541    /// counts for [`Outcome::best`]. The population of the outcome is the last complete
542    /// generation (repaired points with their objective values).
543    pub fn minimize<O, B, Obs, R>(
544        &mut self,
545        objective: &mut O,
546        budget: &mut B,
547        observer: &mut Obs,
548        rng: &mut R,
549    ) -> Outcome<Vec<f64>>
550    where
551        O: Objective<Vec<f64>> + ?Sized,
552        B: Budget<Stats> + ?Sized,
553        Obs: Observer + ?Sized,
554        R: Rng + ?Sized,
555    {
556        let mut evaluator = Evaluator::new(objective, budget, observer);
557        let (stop, population) = self.run(&mut evaluator, rng);
558
559        evaluator.outcome(population, stop)
560    }
561
562    /// The generation loop behind [`CmaEs::minimize`] and [`Ipop`].
563    fn run<O, B, Obs, R>(
564        &mut self,
565        evaluator: &mut Evaluator<'_, Vec<f64>, O, B, Obs>,
566        rng: &mut R,
567    ) -> (Stop, Population)
568    where
569        O: Objective<Vec<f64>> + ?Sized,
570        B: Budget<Stats> + ?Sized,
571        Obs: Observer + ?Sized,
572        R: Rng + ?Sized,
573    {
574        let mut last = Vec::new();
575        loop {
576            let Some((ranks, population)) = self.evaluate_generation(evaluator, rng) else {
577                return (Stop::Budget, last);
578            };
579
580            let termination = self.tell(&ranks);
581            evaluator.end_generation(crate::ga::population_best(&population));
582            last = population;
583            if let Some(criterion) = termination {
584                return (Stop::CmaEs(criterion), last);
585            }
586        }
587    }
588
589    /// Asks for and evaluates one generation: returns the ranking costs (with the bound
590    /// penalty) and the evaluated repaired points, or `None` if the budget ran out.
591    fn evaluate_generation<O, B, Obs, R>(
592        &mut self,
593        evaluator: &mut Evaluator<'_, Vec<f64>, O, B, Obs>,
594        rng: &mut R,
595    ) -> Option<(Vec<f64>, Population)>
596    where
597        O: Objective<Vec<f64>> + ?Sized,
598        B: Budget<Stats> + ?Sized,
599        Obs: Observer + ?Sized,
600        R: Rng + ?Sized,
601    {
602        let candidates = self.ask(rng).to_vec();
603        let mut ranks = Vec::with_capacity(candidates.len());
604        let mut population = Vec::with_capacity(candidates.len());
605        for x in candidates {
606            let (repaired, penalty) = match &self.config.bounds {
607                Some(bounds) => {
608                    let mut repaired = x.clone();
609                    bounds.clamp(&mut repaired);
610                    let distance: f64 = x
611                        .iter()
612                        .zip(&repaired)
613                        .map(|(a, b)| (a - b) * (a - b))
614                        .sum();
615                    (repaired, self.config.penalty * distance)
616                }
617                None => (x, 0.0),
618            };
619
620            let cost = evaluator.evaluate(&repaired)?;
621            ranks.push(cost + penalty);
622            population.push(Individual {
623                genome: repaired,
624                cost,
625            });
626        }
627
628        Some((ranks, population))
629    }
630}
631
632/// IPOP-CMA-ES (Auger and Hansen 2005): independent restarts with the population size
633/// multiplied by `factor` each time, from a uniform mean in `bounds` with `σ = sigma_fraction
634/// · (b - a)` (mean width), until the budget is exhausted or `max_restarts` is reached.
635///
636/// ```
637/// use evolutionary_planning::cmaes::{Config, Ipop};
638/// use evolutionary_planning::operators::real::Bounds;
639/// use evolutionary_planning::problems::single::rastrigin;
640/// use evolutionary_planning::{Limits, SplitMix64};
641///
642/// let mut ipop = Ipop::new(Config::default(), Bounds::uniform(3, -5.0, 5.0));
643/// let mut objective = |x: &Vec<f64>| rastrigin(x);
644/// let outcome = ipop.run(&mut objective, &mut Limits::evaluations(100_000).with_target(1e-8), &mut (), &mut SplitMix64::new(3));
645/// assert!(outcome.best_cost() <= 1e-8);
646/// ```
647#[derive(Debug, Clone, PartialEq)]
648pub struct Ipop {
649    /// The options of every restart; its `lambda` is the first population size.
650    pub config: Config,
651    /// The box the initial means are drawn from.
652    pub bounds: Bounds,
653    /// The initial σ as a fraction of the mean bound width. Default `0.3`.
654    pub sigma_fraction: f64,
655    /// The population growth per restart. Default `2`.
656    pub factor: f64,
657    /// The largest number of restarts after the first run. Default `9`.
658    pub max_restarts: u64,
659}
660
661impl Ipop {
662    /// IPOP with the defaults: `σ = 0.3 (b - a)`, doubling λ, at most nine restarts.
663    #[must_use]
664    pub fn new(config: Config, bounds: Bounds) -> Self {
665        Self {
666            config,
667            bounds,
668            sigma_fraction: 0.3,
669            factor: 2.0,
670            max_restarts: 9,
671        }
672    }
673
674    /// Runs restarts until the budget stops them or `max_restarts` restarts have terminated.
675    ///
676    /// # Panics
677    ///
678    /// Panics if the bounds have dimension `0` or zero width.
679    pub fn run<O, B, Obs, R>(
680        &mut self,
681        objective: &mut O,
682        budget: &mut B,
683        observer: &mut Obs,
684        rng: &mut R,
685    ) -> Outcome<Vec<f64>>
686    where
687        O: Objective<Vec<f64>> + ?Sized,
688        B: Budget<Stats> + ?Sized,
689        Obs: Observer + ?Sized,
690        R: Rng + ?Sized,
691    {
692        let n = self.bounds.dimension();
693        #[expect(clippy::cast_precision_loss, reason = "dimensions are far below 2^52")]
694        let width = (0..n).map(|i| self.bounds.width(i)).sum::<f64>() / n as f64;
695        let sigma = self.sigma_fraction * width;
696        let mut lambda = self
697            .config
698            .lambda
699            .unwrap_or_else(|| Parameters::default_lambda(n));
700        let mut evaluator = Evaluator::new(objective, budget, observer);
701        let mut restart = 0;
702        loop {
703            let mean = (0..n)
704                .map(|i| uniform(rng, self.bounds.lower()[i], self.bounds.upper()[i]))
705                .collect();
706            let config = Config {
707                lambda: Some(lambda),
708                ..self.config.clone()
709            };
710            let mut cma = CmaEs::new(mean, sigma, config);
711            let (stop, population) = cma.run(&mut evaluator, rng);
712            if stop == Stop::Budget || restart >= self.max_restarts {
713                return evaluator.outcome(population, stop);
714            }
715
716            restart += 1;
717            #[expect(
718                clippy::cast_possible_truncation,
719                clippy::cast_sign_loss,
720                clippy::cast_precision_loss,
721                reason = "population sizes are small positive integers"
722            )]
723            {
724                lambda = libm::round(lambda as f64 * self.factor) as usize;
725            }
726            evaluator.emit(Event::Restart {
727                restart,
728                population: lambda,
729            });
730        }
731    }
732}
733
734#[cfg(test)]
735mod tests;