Skip to main content

evolutionary_planning/de/
rades.rs

1//! RADES, rank-based differential evolution with a successful archive (Parque 2024,
2//! equations (5)–(11)).
3//!
4//! Each target `i` keeps a stagnation counter `q_i`. While `q_i ≤ Q` the search exploits the
5//! population: the reference vector is `x_i` and the mutant is
6//! `x_best + F (x_r1 - x_r2)`. Once the target has failed more than `Q` times in a row it
7//! explores from the archive of successful trials: reference `A_i`, mutant
8//! `A_best + F (A_r1 - A_r2)`. The indices `r1`, `r2` are rank-biased by (9),
9//! `r = ⌊|P| / (2β - 1) · (β - sqrt(β² - 4 (β - 1) u))⌋` into the cost-sorted population or
10//! archive; `r2` is redrawn while it equals `r1` (the paper does not say, and an equal pair
11//! gives a zero difference vector). The trial is `u = x^r + b ∘ (v - x^r)` with a binomial mask `b` (10)–(11), and it
12//! replaces the target if strictly better (5); successful trials enter the archive, which is
13//! capped at `|P|` by deleting a uniformly random member (the paper leaves the choice open).
14//!
15//! ```
16//! use evolutionary_planning::de::rades::{Config, Rades};
17//! use evolutionary_planning::operators::real::Bounds;
18//! use evolutionary_planning::problems::single::sphere;
19//! use evolutionary_planning::{Limits, SplitMix64};
20//!
21//! let mut rades = Rades::new(Config::default(), Bounds::uniform(4, -5.0, 5.0));
22//! let mut objective = |x: &Vec<f64>| sphere(x);
23//! let outcome = rades.run(&mut objective, &mut Limits::evaluations(20_000), &mut (), &mut SplitMix64::new(2));
24//! assert!(outcome.best_cost() < 1e-6);
25//! ```
26
27use alloc::vec::Vec;
28
29use rand_core::Rng;
30
31use super::{CrossoverKind, best_index, bounce_back, cross};
32use crate::evaluator::Evaluator;
33use crate::operators::Initializer;
34use crate::operators::real::Bounds;
35use crate::rng::{below, unit_f64};
36use crate::{Budget, Individual, Objective, Observer, Outcome, Stats, Stop, ranking};
37
38/// Parameters of a [`Rades`] run; the defaults are the paper's.
39#[derive(Debug, Clone, Copy, PartialEq)]
40pub struct Config {
41    /// The population size `NP`, at least `3`. Paper: `10`.
42    pub population_size: usize,
43    /// The scaling factor `F`. Paper: `0.7`.
44    pub f: f64,
45    /// The crossover probability `CR`. Paper: `0.5`.
46    pub cr: f64,
47    /// The stagnation threshold `Q`. Paper: `128`.
48    pub stagnation: u64,
49    /// The rank bias `β > 1` of (9); larger values bias less. Paper: `2`.
50    pub beta: f64,
51}
52
53impl Default for Config {
54    fn default() -> Self {
55        Self {
56            population_size: 10,
57            f: 0.7,
58            cr: 0.5,
59            stagnation: 128,
60            beta: 2.0,
61        }
62    }
63}
64
65/// The RADES optimiser over a box.
66#[derive(Debug, Clone, PartialEq)]
67pub struct Rades {
68    /// The run parameters.
69    pub config: Config,
70    /// The search box; trials are bounced back into it as in [`De`](super::De).
71    pub bounds: Bounds,
72}
73
74/// The evolving state of one run.
75struct State {
76    /// The population `P`.
77    population: Vec<Individual<Vec<f64>>>,
78    /// The archive `A` of successful trials, at most `|P|` long.
79    archive: Vec<Individual<Vec<f64>>>,
80    /// The stagnation counters `q_i`.
81    stale: Vec<u64>,
82}
83
84impl Rades {
85    /// Creates a RADES run.
86    #[must_use]
87    pub fn new(config: Config, bounds: Bounds) -> Self {
88        Self { config, bounds }
89    }
90
91    /// Runs until the budget stops it.
92    ///
93    /// # Panics
94    ///
95    /// Panics if the population is smaller than `3` or `β <= 1`.
96    pub fn run<O, B, Obs, R>(
97        &mut self,
98        objective: &mut O,
99        budget: &mut B,
100        observer: &mut Obs,
101        rng: &mut R,
102    ) -> Outcome<Vec<f64>>
103    where
104        O: Objective<Vec<f64>> + ?Sized,
105        B: Budget<Stats> + ?Sized,
106        Obs: Observer + ?Sized,
107        R: Rng + ?Sized,
108    {
109        assert!(
110            self.config.population_size >= 3,
111            "RADES needs a population of at least three"
112        );
113        assert!(self.config.beta > 1.0, "the rank bias must exceed one");
114
115        let mut evaluator = Evaluator::new(objective, budget, observer);
116        let mut state = State {
117            population: Vec::with_capacity(self.config.population_size),
118            archive: Vec::new(),
119            stale: alloc::vec![0; self.config.population_size],
120        };
121        for _ in 0..self.config.population_size {
122            let Some(individual) = evaluator.individual(self.bounds.clone().initialize(rng)) else {
123                return evaluator.outcome(state.population, Stop::Budget);
124            };
125            state.population.push(individual);
126        }
127
128        // The paper initialises the archive from the population.
129        state.archive.clone_from(&state.population);
130        loop {
131            if !self.generation(&mut state, &mut evaluator, rng) {
132                return evaluator.outcome(state.population, Stop::Budget);
133            }
134
135            evaluator.end_generation(crate::ga::population_best(&state.population));
136        }
137    }
138
139    /// One pass over all targets; `false` if the budget ran out.
140    fn generation<O, B, Obs, R>(
141        &self,
142        state: &mut State,
143        evaluator: &mut Evaluator<'_, Vec<f64>, O, B, Obs>,
144        rng: &mut R,
145    ) -> bool
146    where
147        O: Objective<Vec<f64>> + ?Sized,
148        B: Budget<Stats> + ?Sized,
149        Obs: Observer + ?Sized,
150        R: Rng + ?Sized,
151    {
152        let population_order = ranking(&costs(&state.population));
153        let archive_order = ranking(&costs(&state.archive));
154        let best = best_index(&state.population);
155        let archive_best = archive_order.first().copied();
156        for i in 0..state.population.len() {
157            let explore = state.stale[i] > self.config.stagnation && archive_best.is_some();
158            let trial = if explore {
159                let archive_i = &state.archive[i % state.archive.len()].genome;
160                self.trial(
161                    archive_i,
162                    &state.archive,
163                    &archive_order,
164                    archive_best.unwrap_or(0),
165                    rng,
166                )
167            } else {
168                let x_i = state.population[i].genome.clone();
169                self.trial(&x_i, &state.population, &population_order, best, rng)
170            };
171
172            let Some(cost) = evaluator.evaluate(&trial) else {
173                return false;
174            };
175
176            if cost < state.population[i].cost {
177                let individual = Individual {
178                    genome: trial,
179                    cost,
180                };
181                state.population[i] = individual.clone();
182                Self::archive(state, individual, rng);
183                state.stale[i] = 0;
184            } else {
185                state.stale[i] += 1;
186            }
187        }
188
189        true
190    }
191
192    /// Builds the trial from reference `reference` and the rank-biased mutant over `source`.
193    fn trial<R: Rng + ?Sized>(
194        &self,
195        reference: &[f64],
196        source: &[Individual<Vec<f64>>],
197        order: &[usize],
198        best: usize,
199        rng: &mut R,
200    ) -> Vec<f64> {
201        let r1 = order[self.biased_rank(source.len(), rng)];
202        let mut r2 = order[self.biased_rank(source.len(), rng)];
203        // Equal indices give a zero difference vector; redraw (a bounded number of times).
204        for _ in 0..16 {
205            if r2 != r1 || source.len() < 2 {
206                break;
207            }
208            r2 = order[self.biased_rank(source.len(), rng)];
209        }
210        let x = |k: usize| &source[k].genome;
211        let mutant: Vec<f64> = (0..reference.len())
212            .map(|d| x(best)[d] + self.config.f * (x(r1)[d] - x(r2)[d]))
213            .collect();
214        let mut trial = cross(
215            reference,
216            &mutant,
217            self.config.cr,
218            CrossoverKind::Binomial,
219            rng,
220        );
221        bounce_back(&mut trial, reference, &self.bounds);
222
223        trial
224    }
225
226    /// The rank-biased index (9) into a sorted list of `size` members.
227    fn biased_rank<R: Rng + ?Sized>(&self, size: usize, rng: &mut R) -> usize {
228        let beta = self.config.beta;
229        let u = unit_f64(rng);
230        #[expect(
231            clippy::cast_precision_loss,
232            reason = "population sizes are far below 2^52"
233        )]
234        let scale = size as f64 / (2.0 * beta - 1.0);
235        let value = scale * (beta - libm::sqrt(beta * beta - 4.0 * (beta - 1.0) * u));
236
237        #[expect(
238            clippy::cast_possible_truncation,
239            clippy::cast_sign_loss,
240            reason = "a non-negative rank below size"
241        )]
242        let rank = libm::floor(value) as usize;
243
244        rank.min(size - 1)
245    }
246
247    /// Adds a successful trial to the archive, deleting a random member beyond `|P|`.
248    fn archive<R: Rng + ?Sized>(state: &mut State, individual: Individual<Vec<f64>>, rng: &mut R) {
249        state.archive.push(individual);
250        if state.archive.len() > state.population.len() {
251            let victim = below(rng, state.archive.len());
252            state.archive.swap_remove(victim);
253        }
254    }
255}
256
257/// The costs of a population.
258fn costs(population: &[Individual<Vec<f64>>]) -> Vec<f64> {
259    population.iter().map(|i| i.cost).collect()
260}
261
262#[cfg(test)]
263mod tests {
264    use super::*;
265    use crate::problems::single::{rastrigin, rosenbrock};
266    use crate::{Limits, SplitMix64};
267
268    /// The rank bias stays in range and favours good ranks.
269    #[test]
270    fn biased_ranks() {
271        let rades = Rades::new(Config::default(), Bounds::uniform(1, 0.0, 1.0));
272        let mut rng = SplitMix64::new(1);
273        let mut counts = [0usize; 10];
274        for _ in 0..10_000 {
275            counts[rades.biased_rank(10, &mut rng)] += 1;
276        }
277
278        assert!(counts[0] > counts[5]);
279        assert_eq!(counts.iter().sum::<usize>(), 10_000);
280    }
281
282    /// RADES gets close to the Rosenbrock optimum and into the deep basins of Rastrigin. It
283    /// is a greedy, best-based scheme tuned for small budgets (the paper uses 300
284    /// evaluations), so it converges slowly in the curved valley and is not guaranteed to
285    /// find Rastrigin's global optimum.
286    #[test]
287    fn optimises_standard_functions() {
288        let mut rades = Rades::new(
289            Config {
290                population_size: 20,
291                ..Config::default()
292            },
293            Bounds::uniform(2, -2.0, 2.0),
294        );
295        let mut objective = |x: &Vec<f64>| rosenbrock(x);
296        let outcome = rades.run(
297            &mut objective,
298            &mut Limits::evaluations(20_000),
299            &mut (),
300            &mut SplitMix64::new(3),
301        );
302        assert!(outcome.best_cost() < 1e-2, "{}", outcome.best_cost());
303
304        let mut rades = Rades::new(
305            Config {
306                population_size: 20,
307                ..Config::default()
308            },
309            Bounds::uniform(3, -5.12, 5.12),
310        );
311        let mut objective = |x: &Vec<f64>| rastrigin(x);
312        let outcome = rades.run(
313            &mut objective,
314            &mut Limits::evaluations(60_000),
315            &mut (),
316            &mut SplitMix64::new(3),
317        );
318        assert!(outcome.best_cost() < 4.0, "{}", outcome.best_cost());
319    }
320
321    /// Same seed, same run; exact budget.
322    #[test]
323    fn deterministic() {
324        let run = || {
325            let mut rades = Rades::new(Config::default(), Bounds::uniform(3, -1.0, 1.0));
326            let mut objective = |x: &Vec<f64>| x.iter().sum::<f64>();
327            rades.run(
328                &mut objective,
329                &mut Limits::evaluations(1_000),
330                &mut (),
331                &mut SplitMix64::new(5),
332            )
333        };
334
335        assert_eq!(run(), run());
336        assert_eq!(run().stats.evaluations, 1_000);
337    }
338}