use alloc::vec::Vec;
use rand_core::Rng;
use crate::operators::{Crossover, Initializer, Mutation, Repair, Variation};
use crate::rng::{below, chance};
use crate::{Budget, Event, Observer, Stats, Stop, sanitize};
pub trait QdProblem<G: ?Sized> {
fn evaluate(&mut self, genome: &G, descriptor: &mut [f64]) -> f64;
}
impl<G: ?Sized, F: FnMut(&G, &mut [f64]) -> f64> QdProblem<G> for F {
fn evaluate(&mut self, genome: &G, descriptor: &mut [f64]) -> f64 {
self(genome, descriptor)
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Grid {
lower: Vec<f64>,
upper: Vec<f64>,
bins: Vec<usize>,
}
impl Grid {
#[must_use]
pub fn new(lower: Vec<f64>, upper: Vec<f64>, bins: Vec<usize>) -> Self {
assert!(
lower.len() == upper.len() && lower.len() == bins.len(),
"grid dimensions differ"
);
for ((lo, hi), b) in lower.iter().zip(&upper).zip(&bins) {
assert!(
*b > 0 && lo.is_finite() && hi.is_finite() && lo < hi,
"invalid grid dimension"
);
}
assert!(
bins.iter()
.try_fold(1usize, |acc, &b| acc.checked_mul(b))
.is_some(),
"too many cells"
);
Self { lower, upper, bins }
}
#[must_use]
pub fn dimension(&self) -> usize {
self.bins.len()
}
#[must_use]
pub fn cells(&self) -> usize {
self.bins.iter().product()
}
#[must_use]
pub fn cell(&self, descriptor: &[f64]) -> usize {
let mut index = 0;
for (i, &value) in descriptor.iter().enumerate().take(self.dimension()) {
#[expect(clippy::cast_precision_loss, reason = "bin counts are far below 2^52")]
let bins = self.bins[i] as f64;
let t = ((value - self.lower[i]) / (self.upper[i] - self.lower[i]) * bins)
.clamp(0.0, bins - 1.0);
#[expect(
clippy::cast_possible_truncation,
clippy::cast_sign_loss,
reason = "clamped to 0..bins"
)]
let bin = if t.is_nan() {
0
} else {
libm::floor(t) as usize
};
index = index * self.bins[i] + bin;
}
index
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Elite<G> {
pub genome: G,
pub cost: f64,
pub descriptor: Vec<f64>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Insertion {
New,
Improved,
Rejected,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Archive<G> {
grid: Grid,
cells: Vec<Option<Elite<G>>>,
filled: Vec<usize>,
}
impl<G> Archive<G> {
#[must_use]
pub fn new(grid: Grid) -> Self {
let cells = (0..grid.cells()).map(|_| None).collect();
Self {
grid,
cells,
filled: Vec::new(),
}
}
#[must_use]
pub fn grid(&self) -> &Grid {
&self.grid
}
pub fn insert(&mut self, genome: G, cost: f64, descriptor: Vec<f64>) -> Insertion {
let cost = sanitize(cost);
let index = self.grid.cell(&descriptor);
let outcome = match &self.cells[index] {
None => {
self.filled.push(index);
Insertion::New
}
Some(elite) if cost < elite.cost => Insertion::Improved,
Some(_) => return Insertion::Rejected,
};
self.cells[index] = Some(Elite {
genome,
cost,
descriptor,
});
outcome
}
#[must_use]
pub fn get(&self, index: usize) -> Option<&Elite<G>> {
self.cells.get(index).and_then(Option::as_ref)
}
pub fn elites(&self) -> impl Iterator<Item = (usize, &Elite<G>)> + '_ {
self.filled
.iter()
.filter_map(|&i| self.cells[i].as_ref().map(|e| (i, e)))
}
#[must_use]
pub fn len(&self) -> usize {
self.filled.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.filled.is_empty()
}
#[must_use]
pub fn coverage(&self) -> f64 {
#[expect(clippy::cast_precision_loss, reason = "cell counts are far below 2^52")]
let fraction = self.filled.len() as f64 / self.cells.len() as f64;
fraction
}
#[must_use]
pub fn qd_score(&self, offset: f64) -> f64 {
self.elites().map(|(_, e)| offset - e.cost).sum()
}
#[must_use]
pub fn best(&self) -> Option<&Elite<G>> {
self.elites()
.map(|(_, e)| e)
.min_by(|a, b| a.cost.total_cmp(&b.cost))
}
fn random<R: Rng + ?Sized>(&self, rng: &mut R) -> Option<&Elite<G>> {
if self.filled.is_empty() {
return None;
}
self.cells[self.filled[below(rng, self.filled.len())]].as_ref()
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Config {
pub initial: usize,
pub crossover_rate: f64,
pub mutation_rate: f64,
pub batch: usize,
}
impl Default for Config {
fn default() -> Self {
Self {
initial: 100,
crossover_rate: 0.0,
mutation_rate: 1.0,
batch: 100,
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct QdOutcome<G> {
pub archive: Archive<G>,
pub stats: Stats,
pub stop: Stop,
}
#[derive(Debug, Clone, PartialEq)]
pub struct MapElites<I, X, M, P> {
pub config: Config,
pub variation: Variation<I, X, M, P>,
}
impl<I, X, M, P> MapElites<I, X, M, P> {
#[must_use]
pub fn new(config: Config, variation: Variation<I, X, M, P>) -> Self {
Self { config, variation }
}
pub fn run<G, Q, B, Obs, R>(
&mut self,
problem: &mut Q,
grid: Grid,
budget: &mut B,
observer: &mut Obs,
rng: &mut R,
) -> QdOutcome<G>
where
G: Clone,
I: Initializer<G>,
X: Crossover<G>,
M: Mutation<G>,
P: Repair<G>,
Q: QdProblem<G> + ?Sized,
B: Budget<Stats> + ?Sized,
Obs: Observer + ?Sized,
R: Rng + ?Sized,
{
let dimension = grid.dimension();
let mut archive = Archive::new(grid);
let mut stats = Stats::default();
let mut offspring = 0;
while !budget.exhausted(&stats) {
let genome =
if stats.evaluations < self.config.initial.max(1) as u64 || archive.is_empty() {
self.variation.init.initialize(rng)
} else {
self.offspring(&archive, rng)
};
let mut descriptor = alloc::vec![0.0; dimension];
let cost = sanitize(problem.evaluate(&genome, &mut descriptor));
stats.evaluations += 1;
if archive.insert(genome, cost, descriptor) != Insertion::Rejected
&& cost < stats.best_cost
{
stats.best_cost = cost;
if Obs::ENABLED {
observer.observe(Event::Improved {
evaluations: stats.evaluations,
cost,
});
}
}
offspring += 1;
if offspring == self.config.batch.max(1) {
offspring = 0;
stats.generations += 1;
if Obs::ENABLED {
observer.observe(Event::Generation {
stats,
population_best: stats.best_cost,
});
}
}
}
QdOutcome {
archive,
stats,
stop: Stop::Budget,
}
}
fn offspring<G, R>(&mut self, archive: &Archive<G>, rng: &mut R) -> G
where
G: Clone,
X: Crossover<G>,
M: Mutation<G>,
P: Repair<G>,
R: Rng + ?Sized,
{
let first = archive
.random(rng)
.map(|e| e.genome.clone())
.expect("the archive is not empty");
let mut child = if chance(rng, self.config.crossover_rate) {
let second = archive
.random(rng)
.map(|e| e.genome.clone())
.expect("the archive is not empty");
let [child, _] = self.variation.crossover.crossover(&first, &second, rng);
child
} else {
first
};
if chance(rng, self.config.mutation_rate) {
self.variation.mutation.mutate(&mut child, rng);
}
self.variation.repair.repair(&mut child, rng);
child
}
}
#[cfg(test)]
mod tests {
use alloc::collections::BTreeMap;
use super::*;
use crate::operators::real::{Bounds, Clamp, Gaussian, IsoLineDd};
use crate::{Limits, SplitMix64};
#[test]
fn archive_invariants() {
let grid = Grid::new(
alloc::vec![-1.0, -1.0],
alloc::vec![1.0, 1.0],
alloc::vec![8, 6],
);
let reference = grid.clone();
let mut cheapest: BTreeMap<usize, f64> = BTreeMap::new();
let mut problem = |x: &Vec<f64>, d: &mut [f64]| {
d[0] = x[0];
d[1] = x[1] * x[2];
let cost = (x[0] - 0.3) * (x[0] - 0.3) + x[2] * x[2];
let entry = cheapest.entry(reference.cell(d)).or_insert(f64::INFINITY);
*entry = entry.min(cost);
cost
};
let bounds = Bounds::uniform(3, -1.0, 1.0);
let mut qd = MapElites::new(
Config {
crossover_rate: 0.5,
..Config::default()
},
Variation {
init: bounds.clone(),
crossover: IsoLineDd {
sigma_iso: 0.05,
sigma_line: 0.2,
},
mutation: Gaussian {
sigma: 0.05,
rate: None,
},
repair: Clamp(bounds),
},
);
let outcome = qd.run(
&mut problem,
grid,
&mut Limits::evaluations(4_000),
&mut (),
&mut SplitMix64::new(4),
);
let archive = &outcome.archive;
assert_eq!(archive.len(), cheapest.len());
for (index, elite) in archive.elites() {
assert_eq!(archive.grid().cell(&elite.descriptor), index);
assert_eq!(elite.cost, cheapest[&index]);
}
assert_eq!(outcome.stats.evaluations, 4_000);
}
#[test]
fn insertion_rules() {
let mut archive = Archive::new(Grid::new(
alloc::vec![0.0],
alloc::vec![1.0],
alloc::vec![2],
));
assert_eq!(archive.insert("a", 3.0, alloc::vec![0.2]), Insertion::New);
let score = archive.qd_score(10.0);
assert_eq!(
archive.insert("b", 3.0, alloc::vec![0.3]),
Insertion::Rejected
);
assert_eq!(
archive.insert("c", 1.0, alloc::vec![0.4]),
Insertion::Improved
);
assert!(archive.qd_score(10.0) > score);
assert_eq!(archive.insert("d", 5.0, alloc::vec![7.0]), Insertion::New);
assert_eq!(archive.coverage(), 1.0);
assert_eq!(archive.best().map(|e| e.genome), Some("c"));
}
#[test]
fn grid_clamps() {
let grid = Grid::new(
alloc::vec![0.0, 0.0],
alloc::vec![1.0, 1.0],
alloc::vec![4, 3],
);
assert_eq!(grid.cell(&[-5.0, 5.0]), 2);
assert_eq!(grid.cell(&[0.99, 0.99]), 11);
assert_eq!(grid.cell(&[f64::NAN, 0.5]), 1);
}
}