1use 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
46pub trait QdProblem<G: ?Sized> {
51 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#[derive(Debug, Clone, PartialEq)]
64pub struct Grid {
65 lower: Vec<f64>,
67 upper: Vec<f64>,
69 bins: Vec<usize>,
71}
72
73impl Grid {
74 #[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 #[must_use]
104 pub fn dimension(&self) -> usize {
105 self.bins.len()
106 }
107
108 #[must_use]
110 pub fn cells(&self) -> usize {
111 self.bins.iter().product()
112 }
113
114 #[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#[derive(Debug, Clone, PartialEq)]
143pub struct Elite<G> {
144 pub genome: G,
146 pub cost: f64,
148 pub descriptor: Vec<f64>,
150}
151
152#[derive(Debug, Clone, Copy, PartialEq, Eq)]
154pub enum Insertion {
155 New,
157 Improved,
159 Rejected,
161}
162
163#[derive(Debug, Clone, PartialEq)]
165pub struct Archive<G> {
166 grid: Grid,
168 cells: Vec<Option<Elite<G>>>,
170 filled: Vec<usize>,
172}
173
174impl<G> Archive<G> {
175 #[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 #[must_use]
189 pub fn grid(&self) -> &Grid {
190 &self.grid
191 }
192
193 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 #[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 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 #[must_use]
229 pub fn len(&self) -> usize {
230 self.filled.len()
231 }
232
233 #[must_use]
235 pub fn is_empty(&self) -> bool {
236 self.filled.is_empty()
237 }
238
239 #[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 #[must_use]
251 pub fn qd_score(&self, offset: f64) -> f64 {
252 self.elites().map(|(_, e)| offset - e.cost).sum()
253 }
254
255 #[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 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#[derive(Debug, Clone, Copy, PartialEq)]
275pub struct Config {
276 pub initial: usize,
278 pub crossover_rate: f64,
280 pub mutation_rate: f64,
282 pub batch: usize,
284}
285
286impl Default for Config {
287 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#[derive(Debug, Clone, PartialEq)]
300pub struct QdOutcome<G> {
301 pub archive: Archive<G>,
303 pub stats: Stats,
305 pub stop: Stop,
307}
308
309#[derive(Debug, Clone, PartialEq)]
311pub struct MapElites<I, X, M, P> {
312 pub config: Config,
314 pub variation: Variation<I, X, M, P>,
316}
317
318impl<I, X, M, P> MapElites<I, X, M, P> {
319 #[must_use]
321 pub fn new(config: Config, variation: Variation<I, X, M, P>) -> Self {
322 Self { config, variation }
323 }
324
325 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 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 #[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 #[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 #[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}