Skip to main content

evolutionary_planning/
map_elites.rs

1//! MAP-Elites (Mouret and Clune 2015): quality diversity over a grid of behaviour
2//! descriptors. The archive keeps, for every cell of the descriptor grid, the cheapest genome
3//! whose behaviour falls into it, so a run returns a map of diverse, locally optimal
4//! solutions (for example plans that differ in length and risk) instead of one optimum.
5//!
6//! ```mermaid
7//! graph LR
8//!     init[random genomes] --> insert[insert into grid]
9//!     insert --> pick[pick a random elite, maybe a second]
10//!     pick --> vary[crossover, mutation, repair]
11//!     vary --> eval[cost and descriptor]
12//!     eval --> insert
13//! ```
14//!
15//! ```
16//! use evolutionary_planning::map_elites::{Config, Grid, MapElites};
17//! use evolutionary_planning::operators::real::{Bounds, Gaussian};
18//! use evolutionary_planning::operators::{NoCrossover, Variation, real::Clamp};
19//! use evolutionary_planning::{Limits, SplitMix64};
20//!
21//! let bounds = Bounds::uniform(3, -1.0, 1.0);
22//! let mut qd = MapElites::new(Config::default(), Variation {
23//!     init: bounds.clone(),
24//!     crossover: NoCrossover,
25//!     mutation: Gaussian { sigma: 0.1, rate: Some(1.0) },
26//!     repair: Clamp(bounds),
27//! });
28//! // Behaviour: the first two coordinates; cost: the square of the third.
29//! let mut problem = |x: &Vec<f64>, descriptor: &mut [f64]| {
30//!     descriptor.copy_from_slice(&x[..2]);
31//!     x[2] * x[2]
32//! };
33//! let grid = Grid::new(vec![-1.0, -1.0], vec![1.0, 1.0], vec![10, 10]);
34//! let outcome = qd.run(&mut problem, grid, &mut Limits::evaluations(5_000), &mut (), &mut SplitMix64::new(1));
35//! assert!(outcome.archive.coverage() > 0.95);
36//! ```
37
38use alloc::vec::Vec;
39
40use rand_core::Rng;
41
42use crate::operators::{Crossover, Initializer, Mutation, Repair, Variation};
43use crate::rng::{below, chance};
44use crate::{Budget, Event, Observer, Stats, Stop, sanitize};
45
46/// A problem for quality diversity: a cost to minimise and a behaviour descriptor.
47///
48/// Implemented for every `FnMut(&G, &mut [f64]) -> f64` that writes the descriptor and
49/// returns the cost.
50pub trait QdProblem<G: ?Sized> {
51    /// Writes the descriptor of `genome` into `descriptor` (of the grid's dimension) and
52    /// returns its cost (NaN counts as `+∞`).
53    fn evaluate(&mut self, genome: &G, descriptor: &mut [f64]) -> f64;
54}
55
56impl<G: ?Sized, F: FnMut(&G, &mut [f64]) -> f64> QdProblem<G> for F {
57    fn evaluate(&mut self, genome: &G, descriptor: &mut [f64]) -> f64 {
58        self(genome, descriptor)
59    }
60}
61
62/// A regular grid over a box of descriptor space.
63#[derive(Debug, Clone, PartialEq)]
64pub struct Grid {
65    /// The lower corner, one value per descriptor dimension.
66    lower: Vec<f64>,
67    /// The upper corner; `upper[i] > lower[i]`.
68    upper: Vec<f64>,
69    /// The number of cells per dimension, each at least `1`.
70    bins: Vec<usize>,
71}
72
73impl Grid {
74    /// A grid with `bins[i]` equal cells per dimension between `lower` and `upper`.
75    ///
76    /// # Panics
77    ///
78    /// Panics if the lengths differ, a dimension has zero bins or an empty or non-finite
79    /// range, or the cell count overflows.
80    #[must_use]
81    pub fn new(lower: Vec<f64>, upper: Vec<f64>, bins: Vec<usize>) -> Self {
82        assert!(
83            lower.len() == upper.len() && lower.len() == bins.len(),
84            "grid dimensions differ"
85        );
86        for ((lo, hi), b) in lower.iter().zip(&upper).zip(&bins) {
87            assert!(
88                *b > 0 && lo.is_finite() && hi.is_finite() && lo < hi,
89                "invalid grid dimension"
90            );
91        }
92        assert!(
93            bins.iter()
94                .try_fold(1usize, |acc, &b| acc.checked_mul(b))
95                .is_some(),
96            "too many cells"
97        );
98
99        Self { lower, upper, bins }
100    }
101
102    /// The descriptor dimension.
103    #[must_use]
104    pub fn dimension(&self) -> usize {
105        self.bins.len()
106    }
107
108    /// The total number of cells.
109    #[must_use]
110    pub fn cells(&self) -> usize {
111        self.bins.iter().product()
112    }
113
114    /// The flat (row-major) index of the cell containing `descriptor`; values outside the box
115    /// fall into the edge cells, NaN into the first.
116    #[must_use]
117    pub fn cell(&self, descriptor: &[f64]) -> usize {
118        let mut index = 0;
119        for (i, &value) in descriptor.iter().enumerate().take(self.dimension()) {
120            #[expect(clippy::cast_precision_loss, reason = "bin counts are far below 2^52")]
121            let bins = self.bins[i] as f64;
122            let t = ((value - self.lower[i]) / (self.upper[i] - self.lower[i]) * bins)
123                .clamp(0.0, bins - 1.0);
124            #[expect(
125                clippy::cast_possible_truncation,
126                clippy::cast_sign_loss,
127                reason = "clamped to 0..bins"
128            )]
129            let bin = if t.is_nan() {
130                0
131            } else {
132                libm::floor(t) as usize
133            };
134            index = index * self.bins[i] + bin;
135        }
136
137        index
138    }
139}
140
141/// One stored elite.
142#[derive(Debug, Clone, PartialEq)]
143pub struct Elite<G> {
144    /// The genome.
145    pub genome: G,
146    /// Its cost; the smallest of every genome offered for this cell.
147    pub cost: f64,
148    /// Its behaviour descriptor, inside this cell.
149    pub descriptor: Vec<f64>,
150}
151
152/// What happened to a genome offered to the [`Archive`].
153#[derive(Debug, Clone, Copy, PartialEq, Eq)]
154pub enum Insertion {
155    /// It filled an empty cell.
156    New,
157    /// It replaced a costlier elite.
158    Improved,
159    /// Its cell holds an elite at least as cheap.
160    Rejected,
161}
162
163/// The MAP-Elites archive: one elite per grid cell.
164#[derive(Debug, Clone, PartialEq)]
165pub struct Archive<G> {
166    /// The grid.
167    grid: Grid,
168    /// The elite of each cell, by flat index.
169    cells: Vec<Option<Elite<G>>>,
170    /// The flat indices of the filled cells, in the order they were first filled.
171    filled: Vec<usize>,
172}
173
174impl<G> Archive<G> {
175    /// An empty archive over `grid`.
176    #[must_use]
177    pub fn new(grid: Grid) -> Self {
178        let cells = (0..grid.cells()).map(|_| None).collect();
179
180        Self {
181            grid,
182            cells,
183            filled: Vec::new(),
184        }
185    }
186
187    /// The grid.
188    #[must_use]
189    pub fn grid(&self) -> &Grid {
190        &self.grid
191    }
192
193    /// Offers a genome; it enters if its cell is empty or holds a strictly costlier elite.
194    pub fn insert(&mut self, genome: G, cost: f64, descriptor: Vec<f64>) -> Insertion {
195        let cost = sanitize(cost);
196        let index = self.grid.cell(&descriptor);
197        let outcome = match &self.cells[index] {
198            None => {
199                self.filled.push(index);
200                Insertion::New
201            }
202            Some(elite) if cost < elite.cost => Insertion::Improved,
203            Some(_) => return Insertion::Rejected,
204        };
205
206        self.cells[index] = Some(Elite {
207            genome,
208            cost,
209            descriptor,
210        });
211        outcome
212    }
213
214    /// The elite of cell `index`, if any.
215    #[must_use]
216    pub fn get(&self, index: usize) -> Option<&Elite<G>> {
217        self.cells.get(index).and_then(Option::as_ref)
218    }
219
220    /// The filled cells and their elites, in the order the cells were first filled.
221    pub fn elites(&self) -> impl Iterator<Item = (usize, &Elite<G>)> + '_ {
222        self.filled
223            .iter()
224            .filter_map(|&i| self.cells[i].as_ref().map(|e| (i, e)))
225    }
226
227    /// The number of filled cells.
228    #[must_use]
229    pub fn len(&self) -> usize {
230        self.filled.len()
231    }
232
233    /// Whether no cell is filled.
234    #[must_use]
235    pub fn is_empty(&self) -> bool {
236        self.filled.is_empty()
237    }
238
239    /// The fraction of filled cells.
240    #[must_use]
241    pub fn coverage(&self) -> f64 {
242        #[expect(clippy::cast_precision_loss, reason = "cell counts are far below 2^52")]
243        let fraction = self.filled.len() as f64 / self.cells.len() as f64;
244
245        fraction
246    }
247
248    /// The QD-score `Σ (offset - cost)` over all elites; with `offset` at least the worst
249    /// possible cost it only grows during a run.
250    #[must_use]
251    pub fn qd_score(&self, offset: f64) -> f64 {
252        self.elites().map(|(_, e)| offset - e.cost).sum()
253    }
254
255    /// The cheapest elite.
256    #[must_use]
257    pub fn best(&self) -> Option<&Elite<G>> {
258        self.elites()
259            .map(|(_, e)| e)
260            .min_by(|a, b| a.cost.total_cmp(&b.cost))
261    }
262
263    /// A uniformly random elite; `None` if empty.
264    fn random<R: Rng + ?Sized>(&self, rng: &mut R) -> Option<&Elite<G>> {
265        if self.filled.is_empty() {
266            return None;
267        }
268
269        self.cells[self.filled[below(rng, self.filled.len())]].as_ref()
270    }
271}
272
273/// Parameters of a [`MapElites`] run.
274#[derive(Debug, Clone, Copy, PartialEq)]
275pub struct Config {
276    /// The number of random genomes evaluated before variation starts, at least `1`.
277    pub initial: usize,
278    /// The probability that an offspring comes from crossover of two random elites.
279    pub crossover_rate: f64,
280    /// The probability that an offspring is mutated.
281    pub mutation_rate: f64,
282    /// Offspring per reported generation (only affects [`Stats::generations`] and events).
283    pub batch: usize,
284}
285
286impl Default for Config {
287    /// 100 random genomes, mutation only, batches of 100.
288    fn default() -> Self {
289        Self {
290            initial: 100,
291            crossover_rate: 0.0,
292            mutation_rate: 1.0,
293            batch: 100,
294        }
295    }
296}
297
298/// The result of a MAP-Elites run.
299#[derive(Debug, Clone, PartialEq)]
300pub struct QdOutcome<G> {
301    /// The final archive.
302    pub archive: Archive<G>,
303    /// The counters; [`Stats::best_cost`] is the cheapest elite's cost.
304    pub stats: Stats,
305    /// Why the run ended.
306    pub stop: Stop,
307}
308
309/// MAP-Elites over any genome.
310#[derive(Debug, Clone, PartialEq)]
311pub struct MapElites<I, X, M, P> {
312    /// The run parameters.
313    pub config: Config,
314    /// The variation operators.
315    pub variation: Variation<I, X, M, P>,
316}
317
318impl<I, X, M, P> MapElites<I, X, M, P> {
319    /// Creates a MAP-Elites run.
320    #[must_use]
321    pub fn new(config: Config, variation: Variation<I, X, M, P>) -> Self {
322        Self { config, variation }
323    }
324
325    /// Fills an archive over `grid` until the budget stops the run.
326    pub fn run<G, Q, B, Obs, R>(
327        &mut self,
328        problem: &mut Q,
329        grid: Grid,
330        budget: &mut B,
331        observer: &mut Obs,
332        rng: &mut R,
333    ) -> QdOutcome<G>
334    where
335        G: Clone,
336        I: Initializer<G>,
337        X: Crossover<G>,
338        M: Mutation<G>,
339        P: Repair<G>,
340        Q: QdProblem<G> + ?Sized,
341        B: Budget<Stats> + ?Sized,
342        Obs: Observer + ?Sized,
343        R: Rng + ?Sized,
344    {
345        let dimension = grid.dimension();
346        let mut archive = Archive::new(grid);
347        let mut stats = Stats::default();
348        let mut offspring = 0;
349        while !budget.exhausted(&stats) {
350            let genome =
351                if stats.evaluations < self.config.initial.max(1) as u64 || archive.is_empty() {
352                    self.variation.init.initialize(rng)
353                } else {
354                    self.offspring(&archive, rng)
355                };
356
357            let mut descriptor = alloc::vec![0.0; dimension];
358            let cost = sanitize(problem.evaluate(&genome, &mut descriptor));
359            stats.evaluations += 1;
360            if archive.insert(genome, cost, descriptor) != Insertion::Rejected
361                && cost < stats.best_cost
362            {
363                stats.best_cost = cost;
364                if Obs::ENABLED {
365                    observer.observe(Event::Improved {
366                        evaluations: stats.evaluations,
367                        cost,
368                    });
369                }
370            }
371
372            offspring += 1;
373            if offspring == self.config.batch.max(1) {
374                offspring = 0;
375                stats.generations += 1;
376                if Obs::ENABLED {
377                    observer.observe(Event::Generation {
378                        stats,
379                        population_best: stats.best_cost,
380                    });
381                }
382            }
383        }
384
385        QdOutcome {
386            archive,
387            stats,
388            stop: Stop::Budget,
389        }
390    }
391
392    /// Breeds one offspring from random elites.
393    fn offspring<G, R>(&mut self, archive: &Archive<G>, rng: &mut R) -> G
394    where
395        G: Clone,
396        X: Crossover<G>,
397        M: Mutation<G>,
398        P: Repair<G>,
399        R: Rng + ?Sized,
400    {
401        let first = archive
402            .random(rng)
403            .map(|e| e.genome.clone())
404            .expect("the archive is not empty");
405        let mut child = if chance(rng, self.config.crossover_rate) {
406            let second = archive
407                .random(rng)
408                .map(|e| e.genome.clone())
409                .expect("the archive is not empty");
410            let [child, _] = self.variation.crossover.crossover(&first, &second, rng);
411            child
412        } else {
413            first
414        };
415
416        if chance(rng, self.config.mutation_rate) {
417            self.variation.mutation.mutate(&mut child, rng);
418        }
419
420        self.variation.repair.repair(&mut child, rng);
421        child
422    }
423}
424
425#[cfg(test)]
426mod tests {
427    use alloc::collections::BTreeMap;
428
429    use super::*;
430    use crate::operators::real::{Bounds, Clamp, Gaussian, IsoLineDd};
431    use crate::{Limits, SplitMix64};
432
433    /// Archive invariants after a run: every elite lies in its own cell, it is the cheapest of
434    /// all genomes ever offered for that cell, and coverage and QD-score only grow.
435    #[test]
436    fn archive_invariants() {
437        let grid = Grid::new(
438            alloc::vec![-1.0, -1.0],
439            alloc::vec![1.0, 1.0],
440            alloc::vec![8, 6],
441        );
442        let reference = grid.clone();
443        let mut cheapest: BTreeMap<usize, f64> = BTreeMap::new();
444        let mut problem = |x: &Vec<f64>, d: &mut [f64]| {
445            d[0] = x[0];
446            d[1] = x[1] * x[2];
447            let cost = (x[0] - 0.3) * (x[0] - 0.3) + x[2] * x[2];
448            let entry = cheapest.entry(reference.cell(d)).or_insert(f64::INFINITY);
449            *entry = entry.min(cost);
450            cost
451        };
452        let bounds = Bounds::uniform(3, -1.0, 1.0);
453        let mut qd = MapElites::new(
454            Config {
455                crossover_rate: 0.5,
456                ..Config::default()
457            },
458            Variation {
459                init: bounds.clone(),
460                crossover: IsoLineDd {
461                    sigma_iso: 0.05,
462                    sigma_line: 0.2,
463                },
464                mutation: Gaussian {
465                    sigma: 0.05,
466                    rate: None,
467                },
468                repair: Clamp(bounds),
469            },
470        );
471        let outcome = qd.run(
472            &mut problem,
473            grid,
474            &mut Limits::evaluations(4_000),
475            &mut (),
476            &mut SplitMix64::new(4),
477        );
478        let archive = &outcome.archive;
479
480        assert_eq!(archive.len(), cheapest.len());
481        for (index, elite) in archive.elites() {
482            assert_eq!(archive.grid().cell(&elite.descriptor), index);
483            assert_eq!(elite.cost, cheapest[&index]);
484        }
485        assert_eq!(outcome.stats.evaluations, 4_000);
486    }
487
488    /// Insertion outcomes and the monotone QD-score.
489    #[test]
490    fn insertion_rules() {
491        let mut archive = Archive::new(Grid::new(
492            alloc::vec![0.0],
493            alloc::vec![1.0],
494            alloc::vec![2],
495        ));
496        assert_eq!(archive.insert("a", 3.0, alloc::vec![0.2]), Insertion::New);
497        let score = archive.qd_score(10.0);
498        assert_eq!(
499            archive.insert("b", 3.0, alloc::vec![0.3]),
500            Insertion::Rejected
501        );
502        assert_eq!(
503            archive.insert("c", 1.0, alloc::vec![0.4]),
504            Insertion::Improved
505        );
506        assert!(archive.qd_score(10.0) > score);
507        assert_eq!(archive.insert("d", 5.0, alloc::vec![7.0]), Insertion::New);
508        assert_eq!(archive.coverage(), 1.0);
509        assert_eq!(archive.best().map(|e| e.genome), Some("c"));
510    }
511
512    /// Out-of-range and NaN descriptors fall into edge cells.
513    #[test]
514    fn grid_clamps() {
515        let grid = Grid::new(
516            alloc::vec![0.0, 0.0],
517            alloc::vec![1.0, 1.0],
518            alloc::vec![4, 3],
519        );
520
521        assert_eq!(grid.cell(&[-5.0, 5.0]), 2);
522        assert_eq!(grid.cell(&[0.99, 0.99]), 11);
523        assert_eq!(grid.cell(&[f64::NAN, 0.5]), 1);
524    }
525}