Skip to main content

evolutionary_planning/
es.rs

1//! Evolution strategies on real vectors: the (μ/ρ,λ)- and (μ/ρ+λ)-ES with self-adaptive step
2//! sizes (Schwefel; Beyer and Schwefel 2002), and the (1+1)-ES with the 1/5th success rule
3//! (Rechenberg).
4//!
5//! ```
6//! use evolutionary_planning::es::{Config, Es};
7//! use evolutionary_planning::operators::real::Bounds;
8//! use evolutionary_planning::problems::single::sphere;
9//! use evolutionary_planning::{Limits, SplitMix64};
10//!
11//! let mut es = Es::new(Config::default(), Bounds::uniform(5, -3.0, 3.0));
12//! let mut objective = |x: &Vec<f64>| sphere(x);
13//! let outcome = es.run(&mut objective, &mut Limits::evaluations(20_000), &mut (), &mut SplitMix64::new(1));
14//! assert!(outcome.best_cost() < 1e-8);
15//! ```
16
17use alloc::vec::Vec;
18
19use rand_core::Rng;
20
21use crate::evaluator::Evaluator;
22use crate::operators::Initializer;
23use crate::rng::{below, distinct_indices, standard_normal};
24use crate::{Budget, Individual, Objective, Observer, Outcome, Stats, Stop};
25
26/// Which individuals compete for survival.
27#[derive(Debug, Clone, Copy, PartialEq, Eq)]
28pub enum Survival {
29    /// (μ,λ): the μ best of the λ offspring; parents die. Needs `λ >= μ`.
30    Comma,
31    /// (μ+λ): the μ best of parents and offspring together (elitist).
32    Plus,
33}
34
35/// How many step sizes each individual carries.
36#[derive(Debug, Clone, Copy, PartialEq, Eq)]
37pub enum StepSizes {
38    /// One σ, mutated with learning rate `τ = 1/sqrt(n)`.
39    Global,
40    /// One σ per coordinate, with `τ' = 1/sqrt(2n)` (global factor) and
41    /// `τ = 1/sqrt(2 sqrt(n))` (per coordinate).
42    PerCoordinate,
43}
44
45/// How the object variables of the ρ parents are combined.
46#[derive(Debug, Clone, Copy, PartialEq, Eq)]
47pub enum Recombination {
48    /// The centroid of the ρ parents (step sizes: arithmetic mean).
49    Intermediate,
50    /// Each coordinate (and its step size) from a uniformly chosen parent.
51    Discrete,
52}
53
54/// Parameters of an [`Es`] run.
55#[derive(Debug, Clone, Copy, PartialEq)]
56pub struct Config {
57    /// The number of parents μ, at least `1`.
58    pub mu: usize,
59    /// The number of parents recombined per offspring, `1..=mu`.
60    pub rho: usize,
61    /// The number of offspring λ per generation; at least μ for [`Survival::Comma`].
62    pub lambda: usize,
63    /// Comma or plus selection.
64    pub survival: Survival,
65    /// Global or per-coordinate step sizes.
66    pub step_sizes: StepSizes,
67    /// Intermediate or discrete recombination.
68    pub recombination: Recombination,
69    /// The initial step size, as a fraction of each coordinate's bound width.
70    pub initial_sigma: f64,
71    /// Step sizes never fall below this (absolute); prevents premature collapse to zero.
72    pub min_sigma: f64,
73}
74
75impl Default for Config {
76    /// A (15/2,100)-ES with per-coordinate step sizes, intermediate recombination, initial σ
77    /// a third of the bound width.
78    fn default() -> Self {
79        Self {
80            mu: 15,
81            rho: 2,
82            lambda: 100,
83            survival: Survival::Comma,
84            step_sizes: StepSizes::PerCoordinate,
85            recombination: Recombination::Intermediate,
86            initial_sigma: 0.3,
87            min_sigma: 1e-300,
88        }
89    }
90}
91
92/// One ES individual: object variables, step sizes and cost.
93#[derive(Debug, Clone, PartialEq)]
94struct Member {
95    /// The object variables.
96    x: Vec<f64>,
97    /// One step size (global) or one per coordinate.
98    sigma: Vec<f64>,
99    /// The cost of `x`.
100    cost: f64,
101}
102
103/// A self-adaptive evolution strategy over `Vec<f64>` within box bounds (offspring leaving
104/// the box are reflected back in).
105#[derive(Debug, Clone, PartialEq)]
106pub struct Es {
107    /// The run parameters.
108    pub config: Config,
109    /// The search box: initial parents are uniform in it, offspring are reflected into it.
110    pub bounds: crate::operators::real::Bounds,
111}
112
113impl Es {
114    /// Creates an ES.
115    #[must_use]
116    pub fn new(config: Config, bounds: crate::operators::real::Bounds) -> Self {
117        Self { config, bounds }
118    }
119
120    /// Runs until the budget stops it.
121    ///
122    /// # Panics
123    ///
124    /// Panics if `mu`, `rho` or `lambda` is `0`, `rho > mu`, or `lambda < mu` with comma
125    /// selection.
126    pub fn run<O, B, Obs, R>(
127        &mut self,
128        objective: &mut O,
129        budget: &mut B,
130        observer: &mut Obs,
131        rng: &mut R,
132    ) -> Outcome<Vec<f64>>
133    where
134        O: Objective<Vec<f64>> + ?Sized,
135        B: Budget<Stats> + ?Sized,
136        Obs: Observer + ?Sized,
137        R: Rng + ?Sized,
138    {
139        self.validate();
140        let mut evaluator = Evaluator::new(objective, budget, observer);
141        let Some(mut parents) = self.initial_parents(&mut evaluator, rng) else {
142            return evaluator.outcome(Vec::new(), Stop::Budget);
143        };
144
145        loop {
146            let mut offspring = Vec::with_capacity(self.config.lambda);
147            for _ in 0..self.config.lambda {
148                let child = self.offspring(&parents, rng);
149                let Some(cost) = evaluator.evaluate(&child.x) else {
150                    return evaluator.outcome(population(parents), Stop::Budget);
151                };
152                offspring.push(Member { cost, ..child });
153            }
154
155            if self.config.survival == Survival::Plus {
156                offspring.extend(parents);
157            }
158
159            offspring.sort_by(|a, b| a.cost.total_cmp(&b.cost));
160            offspring.truncate(self.config.mu);
161            parents = offspring;
162            evaluator.end_generation(parents[0].cost);
163        }
164    }
165
166    /// Checks the configuration.
167    fn validate(&self) {
168        let c = &self.config;
169        assert!(
170            c.mu > 0 && c.lambda > 0 && c.rho > 0,
171            "mu, rho and lambda must be positive"
172        );
173        assert!(c.rho <= c.mu, "rho must not exceed mu");
174        assert!(
175            c.survival == Survival::Plus || c.lambda >= c.mu,
176            "comma selection needs lambda >= mu"
177        );
178    }
179
180    /// μ uniform parents with the initial step sizes; `None` if the budget ran out.
181    fn initial_parents<O, B, Obs, R>(
182        &mut self,
183        evaluator: &mut Evaluator<'_, Vec<f64>, O, B, Obs>,
184        rng: &mut R,
185    ) -> Option<Vec<Member>>
186    where
187        O: Objective<Vec<f64>> + ?Sized,
188        B: Budget<Stats> + ?Sized,
189        Obs: Observer + ?Sized,
190        R: Rng + ?Sized,
191    {
192        let n = self.bounds.dimension();
193        let sigma: Vec<f64> = match self.config.step_sizes {
194            StepSizes::Global => {
195                let mean_width = (0..n).map(|i| self.bounds.width(i)).sum::<f64>() / dimension(n);
196                alloc::vec![self.config.initial_sigma * mean_width; 1]
197            }
198            StepSizes::PerCoordinate => (0..n)
199                .map(|i| self.config.initial_sigma * self.bounds.width(i))
200                .collect(),
201        };
202
203        let mut parents = Vec::with_capacity(self.config.mu);
204        for _ in 0..self.config.mu {
205            let x = self.bounds.initialize(rng);
206            let cost = evaluator.evaluate(&x)?;
207            parents.push(Member {
208                x,
209                sigma: sigma.clone(),
210                cost,
211            });
212        }
213
214        Some(parents)
215    }
216
217    /// Recombines ρ parents and mutates step sizes, then object variables.
218    fn offspring<R: Rng + ?Sized>(&self, parents: &[Member], rng: &mut R) -> Member {
219        let chosen = distinct_indices(rng, parents.len(), self.config.rho, None);
220        let mut child = self.recombine(parents, &chosen, rng);
221        self.mutate_sigma(&mut child.sigma, rng);
222        for (i, x) in child.x.iter_mut().enumerate() {
223            let sigma = if child.sigma.len() == 1 {
224                child.sigma[0]
225            } else {
226                child.sigma[i]
227            };
228            *x += sigma * standard_normal(rng);
229        }
230
231        let mut repair = crate::operators::real::Reflect(self.bounds.clone());
232        crate::operators::Repair::repair(&mut repair, &mut child.x, rng);
233        child
234    }
235
236    /// Recombines the parents at `chosen` into an unevaluated child.
237    fn recombine<R: Rng + ?Sized>(
238        &self,
239        parents: &[Member],
240        chosen: &[usize],
241        rng: &mut R,
242    ) -> Member {
243        let n = parents[0].x.len();
244        let k = parents[0].sigma.len();
245        let mut x = alloc::vec![0.0; n];
246        let mut sigma = alloc::vec![0.0; k];
247        match self.config.recombination {
248            Recombination::Intermediate => {
249                #[expect(clippy::cast_precision_loss, reason = "rho is tiny")]
250                let weight = 1.0 / chosen.len() as f64;
251                for &p in chosen {
252                    x.iter_mut()
253                        .zip(&parents[p].x)
254                        .for_each(|(a, b)| *a += weight * b);
255                    sigma
256                        .iter_mut()
257                        .zip(&parents[p].sigma)
258                        .for_each(|(a, b)| *a += weight * b);
259                }
260            }
261            Recombination::Discrete => {
262                for (i, xi) in x.iter_mut().enumerate() {
263                    *xi = parents[chosen[below(rng, chosen.len())]].x[i];
264                }
265                for (j, s) in sigma.iter_mut().enumerate() {
266                    *s = parents[chosen[below(rng, chosen.len())]].sigma[j];
267                }
268            }
269        }
270
271        Member {
272            x,
273            sigma,
274            cost: f64::INFINITY,
275        }
276    }
277
278    /// Log-normal self-adaptation of the step sizes.
279    fn mutate_sigma<R: Rng + ?Sized>(&self, sigma: &mut [f64], rng: &mut R) {
280        let n = dimension(self.bounds.dimension());
281        let floor = self.config.min_sigma;
282        if sigma.len() == 1 {
283            let tau = 1.0 / libm::sqrt(n);
284            sigma[0] = (sigma[0] * libm::exp(tau * standard_normal(rng))).max(floor);
285            return;
286        }
287
288        let tau_global = 1.0 / libm::sqrt(2.0 * n);
289        let tau_local = 1.0 / libm::sqrt(2.0 * libm::sqrt(n));
290        let global = tau_global * standard_normal(rng);
291        for s in sigma.iter_mut() {
292            *s = (*s * libm::exp(global + tau_local * standard_normal(rng))).max(floor);
293        }
294    }
295}
296
297/// The dimension as a float, at least `1`.
298fn dimension(n: usize) -> f64 {
299    #[expect(clippy::cast_precision_loss, reason = "dimensions are far below 2^52")]
300    let n = n.max(1) as f64;
301
302    n
303}
304
305/// Converts ES members into outcome individuals.
306fn population(members: Vec<Member>) -> Vec<Individual<Vec<f64>>> {
307    members
308        .into_iter()
309        .map(|m| Individual {
310            genome: m.x,
311            cost: m.cost,
312        })
313        .collect()
314}
315
316/// The (1+1)-ES with the 1/5th success rule: one parent, one Gaussian offspring per
317/// iteration, accepted if not worse; σ grows by `exp(1/3)` on success and shrinks by
318/// `exp(-1/12)` on failure, which keeps it stationary at a success rate of exactly 1/5.
319///
320/// ```
321/// use evolutionary_planning::es::OnePlusOne;
322/// use evolutionary_planning::problems::single::sphere;
323/// use evolutionary_planning::{Limits, SplitMix64};
324///
325/// let mut es = OnePlusOne { sigma: 1.0, min_sigma: 1e-300 };
326/// let mut objective = |x: &Vec<f64>| sphere(x);
327/// let outcome = es.run(vec![2.0; 5], &mut objective, &mut Limits::evaluations(3_000), &mut (), &mut SplitMix64::new(1));
328/// assert!(outcome.best_cost() < 1e-10);
329/// ```
330#[derive(Debug, Clone, Copy, PartialEq)]
331pub struct OnePlusOne {
332    /// The initial step size (absolute).
333    pub sigma: f64,
334    /// Step sizes never fall below this.
335    pub min_sigma: f64,
336}
337
338impl OnePlusOne {
339    /// Runs from `start` until the budget stops it; one iteration is one generation.
340    pub fn run<O, B, Obs, R>(
341        &mut self,
342        start: Vec<f64>,
343        objective: &mut O,
344        budget: &mut B,
345        observer: &mut Obs,
346        rng: &mut R,
347    ) -> Outcome<Vec<f64>>
348    where
349        O: Objective<Vec<f64>> + ?Sized,
350        B: Budget<Stats> + ?Sized,
351        Obs: Observer + ?Sized,
352        R: Rng + ?Sized,
353    {
354        let mut evaluator = Evaluator::new(objective, budget, observer);
355        let Some(mut current) = evaluator.individual(start) else {
356            return evaluator.outcome(Vec::new(), Stop::Budget);
357        };
358
359        let mut sigma = self.sigma;
360        loop {
361            let candidate: Vec<f64> = current
362                .genome
363                .iter()
364                .map(|x| x + sigma * standard_normal(rng))
365                .collect();
366            let Some(cost) = evaluator.evaluate(&candidate) else {
367                break;
368            };
369
370            if cost <= current.cost {
371                current = Individual {
372                    genome: candidate,
373                    cost,
374                };
375                sigma *= libm::exp(1.0 / 3.0);
376            } else {
377                sigma = (sigma * libm::exp(-1.0 / 12.0)).max(self.min_sigma);
378            }
379
380            evaluator.end_generation(current.cost);
381        }
382
383        evaluator.outcome(alloc::vec![current], Stop::Budget)
384    }
385}
386
387#[cfg(test)]
388mod tests {
389    use super::*;
390    use crate::operators::real::Bounds;
391    use crate::problems::single::{ellipsoid, rosenbrock, sphere};
392    use crate::{Limits, SplitMix64};
393
394    /// Every survival, step-size and recombination combination converges on the sphere.
395    #[test]
396    fn variants_converge_on_sphere() {
397        for survival in [Survival::Comma, Survival::Plus] {
398            for step_sizes in [StepSizes::Global, StepSizes::PerCoordinate] {
399                for recombination in [Recombination::Intermediate, Recombination::Discrete] {
400                    let config = Config {
401                        survival,
402                        step_sizes,
403                        recombination,
404                        ..Config::default()
405                    };
406                    let mut es = Es::new(config, Bounds::uniform(4, -5.0, 5.0));
407                    let mut objective = |x: &Vec<f64>| sphere(x);
408                    let outcome = es.run(
409                        &mut objective,
410                        &mut Limits::evaluations(30_000),
411                        &mut (),
412                        &mut SplitMix64::new(3),
413                    );
414                    assert!(
415                        outcome.best_cost() < 1e-6,
416                        "{config:?}: {}",
417                        outcome.best_cost()
418                    );
419                }
420            }
421        }
422    }
423
424    /// Per-coordinate step sizes cope with a badly scaled ellipsoid.
425    #[test]
426    fn per_coordinate_on_ellipsoid() {
427        let mut es = Es::new(Config::default(), Bounds::uniform(5, -3.0, 3.0));
428        let mut objective = |x: &Vec<f64>| ellipsoid(x);
429        let outcome = es.run(
430            &mut objective,
431            &mut Limits::evaluations(100_000),
432            &mut (),
433            &mut SplitMix64::new(1),
434        );
435
436        assert!(outcome.best_cost() < 1e-6, "{}", outcome.best_cost());
437    }
438
439    /// The (1+1)-ES converges linearly on the sphere and makes progress on Rosenbrock.
440    #[test]
441    fn one_plus_one() {
442        let mut es = OnePlusOne {
443            sigma: 1.0,
444            min_sigma: 1e-300,
445        };
446        let mut objective = |x: &Vec<f64>| sphere(x);
447        let outcome = es.run(
448            alloc::vec![3.0; 10],
449            &mut objective,
450            &mut Limits::evaluations(5_000),
451            &mut (),
452            &mut SplitMix64::new(2),
453        );
454        assert!(outcome.best_cost() < 1e-10, "{}", outcome.best_cost());
455
456        let mut objective = |x: &Vec<f64>| rosenbrock(x);
457        let outcome = es.run(
458            alloc::vec![0.0; 2],
459            &mut objective,
460            &mut Limits::evaluations(20_000),
461            &mut (),
462            &mut SplitMix64::new(2),
463        );
464        assert!(outcome.best_cost() < 1e-6, "{}", outcome.best_cost());
465    }
466
467    /// Same seed, same run; the budget is exact.
468    #[test]
469    fn deterministic() {
470        let run = || {
471            let mut es = Es::new(Config::default(), Bounds::uniform(3, -1.0, 1.0));
472            let mut objective = |x: &Vec<f64>| sphere(x);
473            es.run(
474                &mut objective,
475                &mut Limits::evaluations(777),
476                &mut (),
477                &mut SplitMix64::new(9),
478            )
479        };
480
481        assert_eq!(run(), run());
482        assert_eq!(run().stats.evaluations, 777);
483    }
484}