Skip to main content

evolutionary_planning/
diffusion.rs

1//! GLEAM's diffusion model (Jakob 2021, section 7): a structured population on a ring, where
2//! every individual mates only within its deme of neighbours, so good genes spread slowly,
3//! niches form and premature convergence is counteracted.
4//!
5//! ```mermaid
6//! graph LR
7//!     pick[next individual on the ring] --> partner[partner from its deme, linear ranking]
8//!     partner --> breed[offspring: crossover, mutation, repair]
9//!     breed --> best[best offspring, optional local search]
10//!     best --> accept{acceptance rule}
11//!     accept -->|accepted| replace[replace the individual]
12//!     accept -->|rejected| pick
13//!     replace --> pick
14//! ```
15//!
16//! A generation visits every individual once, in ring order, updating in place. Two
17//! stagnation counters serve as the termination criteria Jakob recommends: generations in
18//! which no deme's best improved, and generations without any accepted offspring.
19//!
20//! ```
21//! use evolutionary_planning::diffusion::{Config, Diffusion};
22//! use evolutionary_planning::ga::Operators;
23//! use evolutionary_planning::operators::{NoRepair, discrete::{BitFlip, RandomBits}, sequence::UniformCrossover};
24//! use evolutionary_planning::operators::selection::LinearRanking;
25//! use evolutionary_planning::problems::single::one_max;
26//! use evolutionary_planning::{Limits, SplitMix64};
27//!
28//! let mut diffusion = Diffusion::new(Config::default(), Operators {
29//!     init: RandomBits { len: 30 },
30//!     selection: LinearRanking::default(),
31//!     crossover: UniformCrossover::default(),
32//!     mutation: BitFlip::default(),
33//!     repair: NoRepair,
34//! });
35//! let mut objective = |b: &Vec<bool>| one_max(b);
36//! let outcome = diffusion.run(&mut objective, &mut Limits::evaluations(20_000).with_target(0.0), &mut (), &mut SplitMix64::new(1));
37//! assert_eq!(outcome.best_cost(), 0.0);
38//! ```
39
40use alloc::vec::Vec;
41
42use rand_core::Rng;
43
44use crate::evaluator::Evaluator;
45use crate::ga::{NoRefine, Operators, Refine, population_best};
46use crate::operators::{Crossover, Initializer, Mutation, Repair, Selection};
47use crate::rng::chance;
48use crate::{Budget, Individual, Objective, Observer, Outcome, Stats, Stop};
49
50/// When the best offspring of a mating replaces the individual at the deme's centre.
51#[derive(Debug, Clone, Copy, PartialEq, Eq)]
52pub enum Acceptance {
53    /// Always.
54    Always,
55    /// If it is better than the worst individual of the deme ("local least").
56    LocalLeast,
57    /// If it is better than the individual it replaces.
58    BetterParent,
59    /// If it is better than the deme's worst, and, when the individual is the deme's best,
60    /// also better than it ("local elitist"); the default.
61    LocalElitist,
62}
63
64/// Parameters of a [`Diffusion`] run.
65#[derive(Debug, Clone, Copy, PartialEq)]
66pub struct Config {
67    /// The number of individuals on the ring, at least twice the deme size.
68    pub population_size: usize,
69    /// The deme size (the individual and its neighbours), odd, at least `3`; Jakob reports
70    /// 7 to 11 as typical. An even value is rounded up.
71    pub deme_size: usize,
72    /// Offspring produced per mating; the best one competes for acceptance.
73    pub offspring: usize,
74    /// The probability that a mating uses crossover (otherwise the offspring are mutants of
75    /// the individual).
76    pub crossover_rate: f64,
77    /// The acceptance rule.
78    pub acceptance: Acceptance,
79    /// Stop after this many consecutive generations in which no deme's best improved.
80    pub max_without_improvement: Option<u64>,
81    /// Stop after this many consecutive generations without an accepted offspring.
82    pub max_without_acceptance: Option<u64>,
83}
84
85impl Default for Config {
86    /// 60 individuals, demes of 9, two offspring per mating, crossover rate 0.6, local
87    /// elitist acceptance, no stagnation limits.
88    fn default() -> Self {
89        Self {
90            population_size: 60,
91            deme_size: 9,
92            offspring: 2,
93            crossover_rate: 0.6,
94            acceptance: Acceptance::LocalElitist,
95            max_without_improvement: None,
96            max_without_acceptance: None,
97        }
98    }
99}
100
101/// The diffusion-model GA; the [`Operators::selection`] picks the partner within the deme
102/// (linear ranking is GLEAM's choice).
103#[derive(Debug, Clone, PartialEq)]
104pub struct Diffusion<I, S, X, M, P> {
105    /// The run parameters.
106    pub config: Config,
107    /// The breeding operators.
108    pub operators: Operators<I, S, X, M, P>,
109}
110
111/// What one generation changed.
112#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
113struct Progress {
114    /// Some accepted offspring beat its deme's best.
115    improved: bool,
116    /// Some offspring was accepted.
117    accepted: bool,
118}
119
120impl<I, S, X, M, P> Diffusion<I, S, X, M, P> {
121    /// Creates a diffusion-model run.
122    #[must_use]
123    pub fn new(config: Config, operators: Operators<I, S, X, M, P>) -> Self {
124        Self { config, operators }
125    }
126
127    /// Runs until the budget or a stagnation limit stops it.
128    ///
129    /// # Panics
130    ///
131    /// Panics if the population is smaller than twice the deme size.
132    pub fn run<G, O, B, Obs, R>(
133        &mut self,
134        objective: &mut O,
135        budget: &mut B,
136        observer: &mut Obs,
137        rng: &mut R,
138    ) -> Outcome<G>
139    where
140        G: Clone,
141        I: Initializer<G>,
142        S: Selection,
143        X: Crossover<G>,
144        M: Mutation<G>,
145        P: Repair<G>,
146        O: Objective<G> + ?Sized,
147        B: Budget<Stats> + ?Sized,
148        Obs: Observer + ?Sized,
149        R: Rng + ?Sized,
150    {
151        let mut evaluator = Evaluator::new(objective, budget, observer);
152
153        self.evolve(&mut evaluator, &mut NoRefine, rng)
154    }
155
156    /// Runs HyGLEAM: the diffusion model with `memetic` local search on the best offspring of
157    /// every mating.
158    ///
159    /// # Panics
160    ///
161    /// Panics if the population is smaller than twice the deme size.
162    pub fn run_memetic<G, L, O, B, Obs, R>(
163        &mut self,
164        memetic: &mut crate::memetic::Memetic<L>,
165        objective: &mut O,
166        budget: &mut B,
167        observer: &mut Obs,
168        rng: &mut R,
169    ) -> Outcome<G>
170    where
171        G: Clone,
172        I: Initializer<G>,
173        S: Selection,
174        X: Crossover<G>,
175        M: Mutation<G>,
176        P: Repair<G>,
177        L: crate::memetic::LocalSearch<G>,
178        O: Objective<G> + ?Sized,
179        B: Budget<Stats> + ?Sized,
180        Obs: Observer + ?Sized,
181        R: Rng + ?Sized,
182    {
183        let mut evaluator = Evaluator::new(objective, budget, observer);
184
185        self.evolve(&mut evaluator, memetic, rng)
186    }
187
188    /// The generation loop with its stagnation counters.
189    fn evolve<G, O, B, Obs, F, R>(
190        &mut self,
191        evaluator: &mut Evaluator<'_, G, O, B, Obs>,
192        refine: &mut F,
193        rng: &mut R,
194    ) -> Outcome<G>
195    where
196        G: Clone,
197        I: Initializer<G>,
198        S: Selection,
199        X: Crossover<G>,
200        M: Mutation<G>,
201        P: Repair<G>,
202        O: Objective<G> + ?Sized,
203        B: Budget<Stats> + ?Sized,
204        Obs: Observer + ?Sized,
205        F: Refine<G>,
206        R: Rng + ?Sized,
207    {
208        let radius = self.config.deme_size.max(3) / 2;
209        assert!(
210            self.config.population_size >= 2 * (2 * radius + 1),
211            "the ring must hold at least two demes"
212        );
213
214        let mut population = Vec::with_capacity(self.config.population_size);
215        for _ in 0..self.config.population_size {
216            let Some(member) = evaluator.individual(self.operators.init.initialize(rng)) else {
217                return evaluator.outcome(population, Stop::Budget);
218            };
219            population.push(member);
220        }
221
222        evaluator.end_generation(population_best(&population));
223        let (mut without_improvement, mut without_acceptance) = (0, 0);
224        loop {
225            let Some(progress) = self.generation(&mut population, radius, evaluator, refine, rng)
226            else {
227                return evaluator.outcome(population, Stop::Budget);
228            };
229
230            evaluator.end_generation(population_best(&population));
231            without_improvement = if progress.improved {
232                0
233            } else {
234                without_improvement + 1
235            };
236            without_acceptance = if progress.accepted {
237                0
238            } else {
239                without_acceptance + 1
240            };
241            let stagnated = self
242                .config
243                .max_without_improvement
244                .is_some_and(|m| without_improvement >= m)
245                || self
246                    .config
247                    .max_without_acceptance
248                    .is_some_and(|m| without_acceptance >= m);
249            if stagnated {
250                return evaluator.outcome(population, Stop::Stagnation);
251            }
252        }
253    }
254
255    /// One pass over the ring; `None` if the budget ran out.
256    fn generation<G, O, B, Obs, F, R>(
257        &mut self,
258        population: &mut [Individual<G>],
259        radius: usize,
260        evaluator: &mut Evaluator<'_, G, O, B, Obs>,
261        refine: &mut F,
262        rng: &mut R,
263    ) -> Option<Progress>
264    where
265        G: Clone,
266        S: Selection,
267        X: Crossover<G>,
268        M: Mutation<G>,
269        P: Repair<G>,
270        O: Objective<G> + ?Sized,
271        B: Budget<Stats> + ?Sized,
272        Obs: Observer + ?Sized,
273        F: Refine<G>,
274        R: Rng + ?Sized,
275    {
276        let n = population.len();
277        let mut progress = Progress::default();
278        let mut picked = Vec::with_capacity(1);
279        for centre in 0..n {
280            let neighbours: Vec<usize> = (1..=radius)
281                .flat_map(|d| [(centre + n - d) % n, (centre + d) % n])
282                .collect();
283            let costs: Vec<f64> = neighbours.iter().map(|&k| population[k].cost).collect();
284            picked.clear();
285            self.operators.selection.select(&costs, 1, rng, &mut picked);
286            let partner = neighbours[picked[0]];
287            let child = self.best_offspring(
288                &population[centre].genome,
289                &population[partner].genome,
290                evaluator,
291                rng,
292            )?;
293            let child = refine.refine(child, evaluator, rng);
294            let deme_worst = costs
295                .iter()
296                .copied()
297                .fold(population[centre].cost, f64::max);
298            let deme_best = costs
299                .iter()
300                .copied()
301                .fold(population[centre].cost, f64::min);
302            if self.accepts(&child, &population[centre], deme_worst, deme_best) {
303                progress.accepted = true;
304                progress.improved |= child.cost < deme_best;
305                population[centre] = child;
306            }
307        }
308
309        Some(progress)
310    }
311
312    /// Breeds `offspring` children of the individual and its partner and returns the best.
313    fn best_offspring<G, O, B, Obs, R>(
314        &mut self,
315        own: &G,
316        partner: &G,
317        evaluator: &mut Evaluator<'_, G, O, B, Obs>,
318        rng: &mut R,
319    ) -> Option<Individual<G>>
320    where
321        G: Clone,
322        X: Crossover<G>,
323        M: Mutation<G>,
324        P: Repair<G>,
325        O: Objective<G> + ?Sized,
326        B: Budget<Stats> + ?Sized,
327        Obs: Observer + ?Sized,
328        R: Rng + ?Sized,
329    {
330        let mut best: Option<Individual<G>> = None;
331        let mut produced = 0;
332        while produced < self.config.offspring.max(1) {
333            let children = if chance(rng, self.config.crossover_rate) {
334                self.operators.crossover.crossover(own, partner, rng)
335            } else {
336                [own.clone(), own.clone()]
337            };
338
339            for mut child in children {
340                if produced == self.config.offspring.max(1) {
341                    break;
342                }
343
344                self.operators.mutation.mutate(&mut child, rng);
345                self.operators.repair.repair(&mut child, rng);
346                let individual = evaluator.individual(child)?;
347                produced += 1;
348                if best.as_ref().is_none_or(|b| individual.cost < b.cost) {
349                    best = Some(individual);
350                }
351            }
352        }
353
354        best
355    }
356
357    /// The acceptance rule.
358    fn accepts<G>(
359        &self,
360        child: &Individual<G>,
361        parent: &Individual<G>,
362        deme_worst: f64,
363        deme_best: f64,
364    ) -> bool {
365        match self.config.acceptance {
366            Acceptance::Always => true,
367            Acceptance::LocalLeast => child.cost < deme_worst,
368            Acceptance::BetterParent => child.cost < parent.cost,
369            Acceptance::LocalElitist => {
370                let parent_is_best = parent.cost <= deme_best;
371                child.cost < deme_worst && (!parent_is_best || child.cost < parent.cost)
372            }
373        }
374    }
375}
376
377#[cfg(test)]
378mod tests {
379    use super::*;
380    use crate::memetic::{Memetic, Rosenbrock};
381    use crate::operators::NoRepair;
382    use crate::operators::real::{Bounds, Polynomial, Sbx};
383    use crate::operators::selection::LinearRanking;
384    use crate::problems::single::{rastrigin, rosenbrock};
385    use crate::{Limits, SplitMix64};
386
387    /// A real-coded diffusion model.
388    fn real(
389        acceptance: Acceptance,
390        bounds: &Bounds,
391    ) -> Diffusion<Bounds, LinearRanking, Sbx, Polynomial, NoRepair> {
392        Diffusion::new(
393            Config {
394                acceptance,
395                ..Config::default()
396            },
397            Operators {
398                init: bounds.clone(),
399                selection: LinearRanking::default(),
400                crossover: Sbx {
401                    bounds: bounds.clone(),
402                    eta: 15.0,
403                },
404                mutation: Polynomial {
405                    bounds: bounds.clone(),
406                    eta: 20.0,
407                    rate: None,
408                },
409                repair: NoRepair,
410            },
411        )
412    }
413
414    /// Every acceptance rule makes progress on Rastrigin; the elitist ones (better parent,
415    /// local elitist) never lose the best individual.
416    #[test]
417    fn acceptance_rules() {
418        let bounds = Bounds::uniform(4, -5.12, 5.12);
419        for acceptance in [
420            Acceptance::Always,
421            Acceptance::LocalLeast,
422            Acceptance::BetterParent,
423            Acceptance::LocalElitist,
424        ] {
425            let mut objective = |x: &Vec<f64>| rastrigin(x);
426            let outcome = real(acceptance, &bounds).run(
427                &mut objective,
428                &mut Limits::evaluations(40_000),
429                &mut (),
430                &mut SplitMix64::new(2),
431            );
432            assert!(
433                outcome.best_cost() < 3.0,
434                "{acceptance:?}: {}",
435                outcome.best_cost()
436            );
437            if matches!(
438                acceptance,
439                Acceptance::BetterParent | Acceptance::LocalElitist
440            ) {
441                assert_eq!(
442                    outcome.population[0].cost,
443                    outcome.best_cost(),
444                    "{acceptance:?}"
445                );
446            }
447        }
448    }
449
450    /// The stagnation criteria end a converged run before the budget.
451    #[test]
452    fn stagnation_stops() {
453        let bounds = Bounds::uniform(2, -1.0, 1.0);
454        let mut diffusion = real(Acceptance::BetterParent, &bounds);
455        diffusion.config.max_without_acceptance = Some(5);
456        let mut flat = |_: &Vec<f64>| 1.0;
457        let outcome = diffusion.run(
458            &mut flat,
459            &mut Limits::evaluations(1_000_000),
460            &mut (),
461            &mut SplitMix64::new(1),
462        );
463
464        assert_eq!(outcome.stop, Stop::Stagnation);
465        assert!(outcome.stats.evaluations < 1_000);
466    }
467
468    /// HyGLEAM (diffusion model plus adaptive Rosenbrock search) solves Rosenbrock in 5D.
469    #[test]
470    fn hygleam_solves_rosenbrock() {
471        let bounds = Bounds::uniform(5, -2.0, 2.0);
472        let mut diffusion = real(Acceptance::LocalElitist, &bounds);
473        diffusion.config.population_size = 20;
474        diffusion.config.deme_size = 5;
475        let mut memetic = Memetic::adaptive(Rosenbrock::default());
476        let mut objective = |x: &Vec<f64>| rosenbrock(x);
477        let outcome = diffusion.run_memetic(
478            &mut memetic,
479            &mut objective,
480            &mut Limits::evaluations(40_000),
481            &mut (),
482            &mut SplitMix64::new(3),
483        );
484
485        assert!(outcome.best_cost() < 1e-6, "{}", outcome.best_cost());
486    }
487}