Skip to main content

evolutionary_planning/
de.rs

1//! Differential evolution (Storn and Price 1997) on real vectors, with Latin hypercube
2//! initialisation and a warm-start library (Yue et al. 2023), and RADES, the rank-based DE
3//! with a success archive (Parque 2024), in [`rades`].
4//!
5//! ```
6//! use evolutionary_planning::de::{Config, De};
7//! use evolutionary_planning::operators::real::Bounds;
8//! use evolutionary_planning::problems::single::rosenbrock;
9//! use evolutionary_planning::{Limits, SplitMix64};
10//!
11//! let mut de = De::new(Config::default(), Bounds::uniform(2, -2.0, 2.0));
12//! let mut objective = |x: &Vec<f64>| rosenbrock(x);
13//! let outcome = de.run(&mut objective, &mut Limits::evaluations(20_000), &mut (), &mut SplitMix64::new(1));
14//! assert!(outcome.best_cost() < 1e-8);
15//! ```
16
17pub mod rades;
18mod warm_start;
19
20use alloc::vec::Vec;
21
22use rand_core::Rng;
23pub use warm_start::WarmStartLibrary;
24
25use crate::evaluator::Evaluator;
26use crate::operators::Initializer;
27use crate::operators::real::{Bounds, latin_hypercube};
28use crate::rng::{below, distinct_indices, unit_f64};
29use crate::{Budget, Individual, Objective, Observer, Outcome, Stats, Stop};
30
31/// How the mutant vector is formed (the `x/y` of `DE/x/y/z`).
32#[derive(Debug, Clone, Copy, PartialEq, Eq)]
33pub enum Strategy {
34    /// `v = x_r1 + F (x_r2 - x_r3)`: the robust default.
35    Rand1,
36    /// `v = x_best + F (x_r1 - x_r2)`: faster, greedier.
37    Best1,
38    /// `v = x_i + F (x_best - x_i) + F (x_r1 - x_r2)`.
39    CurrentToBest1,
40    /// `v = x_r1 + F (x_r2 - x_r3) + F (x_r4 - x_r5)`: more exploratory.
41    Rand2,
42}
43
44/// How the trial vector takes coordinates from the mutant (the `z` of `DE/x/y/z`).
45#[derive(Debug, Clone, Copy, PartialEq, Eq)]
46pub enum CrossoverKind {
47    /// Each coordinate from the mutant with probability `CR`, one forced coordinate always.
48    Binomial,
49    /// A contiguous (cyclic) run of coordinates from the mutant, whose length is geometric
50    /// with continuation probability `CR`.
51    Exponential,
52}
53
54/// How the initial population is drawn.
55#[derive(Debug, Clone, Copy, PartialEq, Eq)]
56pub enum Initialization {
57    /// Independent uniform points in the bounds.
58    Uniform,
59    /// A Latin hypercube sample: one point per stratum and coordinate (Yue et al. 2023).
60    LatinHypercube,
61}
62
63/// Parameters of a [`De`] run.
64#[derive(Debug, Clone, Copy, PartialEq)]
65pub struct Config {
66    /// The population size `NP`, at least `6` (`Rand2` needs five distinct partners).
67    pub population_size: usize,
68    /// The differential weight `F`, typically in `(0, 1]`.
69    pub f: f64,
70    /// The crossover rate `CR` in `[0, 1]`.
71    pub cr: f64,
72    /// The mutation strategy.
73    pub strategy: Strategy,
74    /// Binomial or exponential crossover.
75    pub crossover: CrossoverKind,
76    /// Uniform or Latin hypercube initialisation.
77    pub initialization: Initialization,
78}
79
80impl Default for Config {
81    /// `DE/rand/1/bin` with `NP = 40`, `F = 0.5`, `CR = 0.9` and Latin hypercube
82    /// initialisation.
83    fn default() -> Self {
84        Self {
85            population_size: 40,
86            f: 0.5,
87            cr: 0.9,
88            strategy: Strategy::Rand1,
89            crossover: CrossoverKind::Binomial,
90            initialization: Initialization::LatinHypercube,
91        }
92    }
93}
94
95/// Differential evolution within box bounds. A trial coordinate that leaves the box is set
96/// halfway between the target's coordinate and the violated bound ("bounce back"), which
97/// keeps the population inside without piling it up on the boundary.
98#[derive(Debug, Clone, PartialEq)]
99pub struct De {
100    /// The run parameters.
101    pub config: Config,
102    /// The search box.
103    pub bounds: Bounds,
104}
105
106impl De {
107    /// Creates a DE run.
108    #[must_use]
109    pub fn new(config: Config, bounds: Bounds) -> Self {
110        Self { config, bounds }
111    }
112
113    /// Runs from a fresh initial population until the budget stops it.
114    ///
115    /// # Panics
116    ///
117    /// Panics if the population is smaller than `6`.
118    pub fn run<O, B, Obs, R>(
119        &mut self,
120        objective: &mut O,
121        budget: &mut B,
122        observer: &mut Obs,
123        rng: &mut R,
124    ) -> Outcome<Vec<f64>>
125    where
126        O: Objective<Vec<f64>> + ?Sized,
127        B: Budget<Stats> + ?Sized,
128        Obs: Observer + ?Sized,
129        R: Rng + ?Sized,
130    {
131        self.run_from(Vec::new(), objective, budget, observer, rng)
132    }
133
134    /// Runs with `seeds` (for example from a [`WarmStartLibrary`]) as the first members of
135    /// the initial population (truncated to the population size, clamped into the bounds);
136    /// the rest is drawn by [`Config::initialization`].
137    ///
138    /// # Panics
139    ///
140    /// Panics if the population is smaller than `6`.
141    pub fn run_from<O, B, Obs, R>(
142        &mut self,
143        seeds: Vec<Vec<f64>>,
144        objective: &mut O,
145        budget: &mut B,
146        observer: &mut Obs,
147        rng: &mut R,
148    ) -> Outcome<Vec<f64>>
149    where
150        O: Objective<Vec<f64>> + ?Sized,
151        B: Budget<Stats> + ?Sized,
152        Obs: Observer + ?Sized,
153        R: Rng + ?Sized,
154    {
155        assert!(
156            self.config.population_size >= 6,
157            "DE needs a population of at least six"
158        );
159
160        let mut evaluator = Evaluator::new(objective, budget, observer);
161        let genomes = self.initial_genomes(seeds, rng);
162        let Some(mut population) = evaluate_all(genomes, &mut evaluator) else {
163            return evaluator.outcome(Vec::new(), Stop::Budget);
164        };
165
166        evaluator.end_generation(crate::ga::population_best(&population));
167        loop {
168            let best = best_index(&population);
169            let mut next = population.clone();
170            for i in 0..population.len() {
171                let trial = self.trial(&population, i, best, rng);
172                let Some(cost) = evaluator.evaluate(&trial) else {
173                    return evaluator.outcome(population, Stop::Budget);
174                };
175
176                if cost <= population[i].cost {
177                    next[i] = Individual {
178                        genome: trial,
179                        cost,
180                    };
181                }
182            }
183
184            population = next;
185            evaluator.end_generation(crate::ga::population_best(&population));
186        }
187    }
188
189    /// Seeds followed by uniform or Latin hypercube points.
190    fn initial_genomes<R: Rng + ?Sized>(
191        &self,
192        mut seeds: Vec<Vec<f64>>,
193        rng: &mut R,
194    ) -> Vec<Vec<f64>> {
195        let size = self.config.population_size;
196        seeds.truncate(size);
197        for seed in &mut seeds {
198            self.bounds.clamp(seed);
199        }
200
201        let missing = size - seeds.len();
202        match self.config.initialization {
203            Initialization::Uniform => {
204                let mut bounds = self.bounds.clone();
205                seeds.extend((0..missing).map(|_| bounds.initialize(rng)));
206            }
207            Initialization::LatinHypercube => {
208                seeds.extend(latin_hypercube(&self.bounds, missing, rng));
209            }
210        }
211
212        seeds
213    }
214
215    /// The trial vector for target `i`: mutation, crossover, bounce-back.
216    fn trial<R: Rng + ?Sized>(
217        &self,
218        population: &[Individual<Vec<f64>>],
219        i: usize,
220        best: usize,
221        rng: &mut R,
222    ) -> Vec<f64> {
223        let mutant = self.mutant(population, i, best, rng);
224        let target = &population[i].genome;
225        let mut trial = cross(target, &mutant, self.config.cr, self.config.crossover, rng);
226        bounce_back(&mut trial, target, &self.bounds);
227
228        trial
229    }
230
231    /// The mutant vector of the configured strategy.
232    #[expect(
233        clippy::many_single_char_names,
234        reason = "the textbook names of the DE formulas"
235    )]
236    fn mutant<R: Rng + ?Sized>(
237        &self,
238        population: &[Individual<Vec<f64>>],
239        i: usize,
240        best: usize,
241        rng: &mut R,
242    ) -> Vec<f64> {
243        let x = |k: usize| &population[k].genome;
244        let f = self.config.f;
245        let n = self.bounds.dimension();
246        let r = distinct_indices(rng, population.len(), 5, Some(i));
247        (0..n)
248            .map(|d| match self.config.strategy {
249                Strategy::Rand1 => x(r[0])[d] + f * (x(r[1])[d] - x(r[2])[d]),
250                Strategy::Best1 => x(best)[d] + f * (x(r[0])[d] - x(r[1])[d]),
251                Strategy::CurrentToBest1 => {
252                    x(i)[d] + f * (x(best)[d] - x(i)[d]) + f * (x(r[0])[d] - x(r[1])[d])
253                }
254                Strategy::Rand2 => {
255                    x(r[0])[d] + f * (x(r[1])[d] - x(r[2])[d]) + f * (x(r[3])[d] - x(r[4])[d])
256                }
257            })
258            .collect()
259    }
260}
261
262/// Evaluates every genome; `None` if the budget ran out.
263fn evaluate_all<O, B, Obs>(
264    genomes: Vec<Vec<f64>>,
265    evaluator: &mut Evaluator<'_, Vec<f64>, O, B, Obs>,
266) -> Option<Vec<Individual<Vec<f64>>>>
267where
268    O: Objective<Vec<f64>> + ?Sized,
269    B: Budget<Stats> + ?Sized,
270    Obs: Observer + ?Sized,
271{
272    genomes
273        .into_iter()
274        .map(|g| evaluator.individual(g))
275        .collect()
276}
277
278/// The index of the cheapest individual (the first among equals).
279pub(crate) fn best_index<G>(population: &[Individual<G>]) -> usize {
280    let mut best = 0;
281    for (k, individual) in population.iter().enumerate() {
282        if individual.cost < population[best].cost {
283            best = k;
284        }
285    }
286
287    best
288}
289
290/// Binomial or exponential crossover of `target` with `mutant`.
291pub(crate) fn cross<R: Rng + ?Sized>(
292    target: &[f64],
293    mutant: &[f64],
294    cr: f64,
295    kind: CrossoverKind,
296    rng: &mut R,
297) -> Vec<f64> {
298    let n = target.len();
299    let mut trial = target.to_vec();
300    let forced = below(rng, n);
301    match kind {
302        CrossoverKind::Binomial => {
303            for d in 0..n {
304                if d == forced || unit_f64(rng) < cr {
305                    trial[d] = mutant[d];
306                }
307            }
308        }
309        CrossoverKind::Exponential => {
310            let mut d = forced;
311            for _ in 0..n {
312                trial[d] = mutant[d];
313                d = (d + 1) % n;
314                if unit_f64(rng) >= cr {
315                    break;
316                }
317            }
318        }
319    }
320
321    trial
322}
323
324/// Moves coordinates outside the box halfway between the target and the violated bound.
325pub(crate) fn bounce_back(trial: &mut [f64], target: &[f64], bounds: &Bounds) {
326    for (d, value) in trial.iter_mut().enumerate() {
327        let (low, high) = (bounds.lower()[d], bounds.upper()[d]);
328        if *value < low {
329            *value = f64::midpoint(low, target[d]);
330        } else if *value > high {
331            *value = f64::midpoint(high, target[d]);
332        }
333    }
334}
335
336#[cfg(test)]
337mod tests {
338    use super::*;
339    use crate::problems::single::{rastrigin, sphere};
340    use crate::{Limits, SplitMix64};
341
342    /// Every strategy and crossover solves the sphere.
343    #[test]
344    fn strategies_solve_sphere() {
345        for strategy in [
346            Strategy::Rand1,
347            Strategy::Best1,
348            Strategy::CurrentToBest1,
349            Strategy::Rand2,
350        ] {
351            for crossover in [CrossoverKind::Binomial, CrossoverKind::Exponential] {
352                let config = Config {
353                    strategy,
354                    crossover,
355                    cr: if crossover == CrossoverKind::Binomial {
356                        0.9
357                    } else {
358                        0.95
359                    },
360                    ..Config::default()
361                };
362                let mut de = De::new(config, Bounds::uniform(5, -5.0, 5.0));
363                let mut objective = |x: &Vec<f64>| sphere(x);
364                let outcome = de.run(
365                    &mut objective,
366                    &mut Limits::evaluations(40_000),
367                    &mut (),
368                    &mut SplitMix64::new(2),
369                );
370                assert!(
371                    outcome.best_cost() < 1e-6,
372                    "{config:?}: {}",
373                    outcome.best_cost()
374                );
375            }
376        }
377    }
378
379    /// DE with a low crossover rate solves separable Rastrigin.
380    #[test]
381    fn separable_rastrigin() {
382        let config = Config {
383            cr: 0.1,
384            ..Config::default()
385        };
386        let mut de = De::new(config, Bounds::uniform(5, -5.12, 5.12));
387        let mut objective = |x: &Vec<f64>| rastrigin(x);
388        let outcome = de.run(
389            &mut objective,
390            &mut Limits::evaluations(100_000),
391            &mut (),
392            &mut SplitMix64::new(4),
393        );
394
395        assert!(outcome.best_cost() < 1e-6, "{}", outcome.best_cost());
396    }
397
398    /// The population never leaves the bounds; same seed, same run; exact budget.
399    #[test]
400    fn bounded_and_deterministic() {
401        let bounds = Bounds::uniform(3, 0.0, 1.0);
402        let run = || {
403            let mut de = De::new(Config::default(), bounds.clone());
404            // The optimum is outside the box, so trials keep hitting the bound.
405            let mut objective = |x: &Vec<f64>| x.iter().map(|v| (v + 3.0) * (v + 3.0)).sum::<f64>();
406            de.run(
407                &mut objective,
408                &mut Limits::evaluations(2_001),
409                &mut (),
410                &mut SplitMix64::new(8),
411            )
412        };
413        let outcome = run();
414
415        assert_eq!(outcome, run());
416        assert_eq!(outcome.stats.evaluations, 2_001);
417        assert!(
418            outcome
419                .population
420                .iter()
421                .all(|i| bounds.contains(&i.genome))
422        );
423    }
424}