use alloc::vec::Vec;
use rand_core::Rng;
use crate::evaluator::Evaluator;
use crate::ga::{NoRefine, Operators, Refine, population_best};
use crate::operators::{Crossover, Initializer, Mutation, Repair, Selection};
use crate::rng::chance;
use crate::{Budget, Individual, Objective, Observer, Outcome, Stats, Stop};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Acceptance {
Always,
LocalLeast,
BetterParent,
LocalElitist,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Config {
pub population_size: usize,
pub deme_size: usize,
pub offspring: usize,
pub crossover_rate: f64,
pub acceptance: Acceptance,
pub max_without_improvement: Option<u64>,
pub max_without_acceptance: Option<u64>,
}
impl Default for Config {
fn default() -> Self {
Self {
population_size: 60,
deme_size: 9,
offspring: 2,
crossover_rate: 0.6,
acceptance: Acceptance::LocalElitist,
max_without_improvement: None,
max_without_acceptance: None,
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Diffusion<I, S, X, M, P> {
pub config: Config,
pub operators: Operators<I, S, X, M, P>,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
struct Progress {
improved: bool,
accepted: bool,
}
impl<I, S, X, M, P> Diffusion<I, S, X, M, P> {
#[must_use]
pub fn new(config: Config, operators: Operators<I, S, X, M, P>) -> Self {
Self { config, operators }
}
pub fn run<G, O, B, Obs, R>(
&mut self,
objective: &mut O,
budget: &mut B,
observer: &mut Obs,
rng: &mut R,
) -> Outcome<G>
where
G: Clone,
I: Initializer<G>,
S: Selection,
X: Crossover<G>,
M: Mutation<G>,
P: Repair<G>,
O: Objective<G> + ?Sized,
B: Budget<Stats> + ?Sized,
Obs: Observer + ?Sized,
R: Rng + ?Sized,
{
let mut evaluator = Evaluator::new(objective, budget, observer);
self.evolve(&mut evaluator, &mut NoRefine, rng)
}
pub fn run_memetic<G, L, O, B, Obs, R>(
&mut self,
memetic: &mut crate::memetic::Memetic<L>,
objective: &mut O,
budget: &mut B,
observer: &mut Obs,
rng: &mut R,
) -> Outcome<G>
where
G: Clone,
I: Initializer<G>,
S: Selection,
X: Crossover<G>,
M: Mutation<G>,
P: Repair<G>,
L: crate::memetic::LocalSearch<G>,
O: Objective<G> + ?Sized,
B: Budget<Stats> + ?Sized,
Obs: Observer + ?Sized,
R: Rng + ?Sized,
{
let mut evaluator = Evaluator::new(objective, budget, observer);
self.evolve(&mut evaluator, memetic, rng)
}
fn evolve<G, O, B, Obs, F, R>(
&mut self,
evaluator: &mut Evaluator<'_, G, O, B, Obs>,
refine: &mut F,
rng: &mut R,
) -> Outcome<G>
where
G: Clone,
I: Initializer<G>,
S: Selection,
X: Crossover<G>,
M: Mutation<G>,
P: Repair<G>,
O: Objective<G> + ?Sized,
B: Budget<Stats> + ?Sized,
Obs: Observer + ?Sized,
F: Refine<G>,
R: Rng + ?Sized,
{
let radius = self.config.deme_size.max(3) / 2;
assert!(
self.config.population_size >= 2 * (2 * radius + 1),
"the ring must hold at least two demes"
);
let mut population = Vec::with_capacity(self.config.population_size);
for _ in 0..self.config.population_size {
let Some(member) = evaluator.individual(self.operators.init.initialize(rng)) else {
return evaluator.outcome(population, Stop::Budget);
};
population.push(member);
}
evaluator.end_generation(population_best(&population));
let (mut without_improvement, mut without_acceptance) = (0, 0);
loop {
let Some(progress) = self.generation(&mut population, radius, evaluator, refine, rng)
else {
return evaluator.outcome(population, Stop::Budget);
};
evaluator.end_generation(population_best(&population));
without_improvement = if progress.improved {
0
} else {
without_improvement + 1
};
without_acceptance = if progress.accepted {
0
} else {
without_acceptance + 1
};
let stagnated = self
.config
.max_without_improvement
.is_some_and(|m| without_improvement >= m)
|| self
.config
.max_without_acceptance
.is_some_and(|m| without_acceptance >= m);
if stagnated {
return evaluator.outcome(population, Stop::Stagnation);
}
}
}
fn generation<G, O, B, Obs, F, R>(
&mut self,
population: &mut [Individual<G>],
radius: usize,
evaluator: &mut Evaluator<'_, G, O, B, Obs>,
refine: &mut F,
rng: &mut R,
) -> Option<Progress>
where
G: Clone,
S: Selection,
X: Crossover<G>,
M: Mutation<G>,
P: Repair<G>,
O: Objective<G> + ?Sized,
B: Budget<Stats> + ?Sized,
Obs: Observer + ?Sized,
F: Refine<G>,
R: Rng + ?Sized,
{
let n = population.len();
let mut progress = Progress::default();
let mut picked = Vec::with_capacity(1);
for centre in 0..n {
let neighbours: Vec<usize> = (1..=radius)
.flat_map(|d| [(centre + n - d) % n, (centre + d) % n])
.collect();
let costs: Vec<f64> = neighbours.iter().map(|&k| population[k].cost).collect();
picked.clear();
self.operators.selection.select(&costs, 1, rng, &mut picked);
let partner = neighbours[picked[0]];
let child = self.best_offspring(
&population[centre].genome,
&population[partner].genome,
evaluator,
rng,
)?;
let child = refine.refine(child, evaluator, rng);
let deme_worst = costs
.iter()
.copied()
.fold(population[centre].cost, f64::max);
let deme_best = costs
.iter()
.copied()
.fold(population[centre].cost, f64::min);
if self.accepts(&child, &population[centre], deme_worst, deme_best) {
progress.accepted = true;
progress.improved |= child.cost < deme_best;
population[centre] = child;
}
}
Some(progress)
}
fn best_offspring<G, O, B, Obs, R>(
&mut self,
own: &G,
partner: &G,
evaluator: &mut Evaluator<'_, G, O, B, Obs>,
rng: &mut R,
) -> Option<Individual<G>>
where
G: Clone,
X: Crossover<G>,
M: Mutation<G>,
P: Repair<G>,
O: Objective<G> + ?Sized,
B: Budget<Stats> + ?Sized,
Obs: Observer + ?Sized,
R: Rng + ?Sized,
{
let mut best: Option<Individual<G>> = None;
let mut produced = 0;
while produced < self.config.offspring.max(1) {
let children = if chance(rng, self.config.crossover_rate) {
self.operators.crossover.crossover(own, partner, rng)
} else {
[own.clone(), own.clone()]
};
for mut child in children {
if produced == self.config.offspring.max(1) {
break;
}
self.operators.mutation.mutate(&mut child, rng);
self.operators.repair.repair(&mut child, rng);
let individual = evaluator.individual(child)?;
produced += 1;
if best.as_ref().is_none_or(|b| individual.cost < b.cost) {
best = Some(individual);
}
}
}
best
}
fn accepts<G>(
&self,
child: &Individual<G>,
parent: &Individual<G>,
deme_worst: f64,
deme_best: f64,
) -> bool {
match self.config.acceptance {
Acceptance::Always => true,
Acceptance::LocalLeast => child.cost < deme_worst,
Acceptance::BetterParent => child.cost < parent.cost,
Acceptance::LocalElitist => {
let parent_is_best = parent.cost <= deme_best;
child.cost < deme_worst && (!parent_is_best || child.cost < parent.cost)
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::memetic::{Memetic, Rosenbrock};
use crate::operators::NoRepair;
use crate::operators::real::{Bounds, Polynomial, Sbx};
use crate::operators::selection::LinearRanking;
use crate::problems::single::{rastrigin, rosenbrock};
use crate::{Limits, SplitMix64};
fn real(
acceptance: Acceptance,
bounds: &Bounds,
) -> Diffusion<Bounds, LinearRanking, Sbx, Polynomial, NoRepair> {
Diffusion::new(
Config {
acceptance,
..Config::default()
},
Operators {
init: bounds.clone(),
selection: LinearRanking::default(),
crossover: Sbx {
bounds: bounds.clone(),
eta: 15.0,
},
mutation: Polynomial {
bounds: bounds.clone(),
eta: 20.0,
rate: None,
},
repair: NoRepair,
},
)
}
#[test]
fn acceptance_rules() {
let bounds = Bounds::uniform(4, -5.12, 5.12);
for acceptance in [
Acceptance::Always,
Acceptance::LocalLeast,
Acceptance::BetterParent,
Acceptance::LocalElitist,
] {
let mut objective = |x: &Vec<f64>| rastrigin(x);
let outcome = real(acceptance, &bounds).run(
&mut objective,
&mut Limits::evaluations(40_000),
&mut (),
&mut SplitMix64::new(2),
);
assert!(
outcome.best_cost() < 3.0,
"{acceptance:?}: {}",
outcome.best_cost()
);
if matches!(
acceptance,
Acceptance::BetterParent | Acceptance::LocalElitist
) {
assert_eq!(
outcome.population[0].cost,
outcome.best_cost(),
"{acceptance:?}"
);
}
}
}
#[test]
fn stagnation_stops() {
let bounds = Bounds::uniform(2, -1.0, 1.0);
let mut diffusion = real(Acceptance::BetterParent, &bounds);
diffusion.config.max_without_acceptance = Some(5);
let mut flat = |_: &Vec<f64>| 1.0;
let outcome = diffusion.run(
&mut flat,
&mut Limits::evaluations(1_000_000),
&mut (),
&mut SplitMix64::new(1),
);
assert_eq!(outcome.stop, Stop::Stagnation);
assert!(outcome.stats.evaluations < 1_000);
}
#[test]
fn hygleam_solves_rosenbrock() {
let bounds = Bounds::uniform(5, -2.0, 2.0);
let mut diffusion = real(Acceptance::LocalElitist, &bounds);
diffusion.config.population_size = 20;
diffusion.config.deme_size = 5;
let mut memetic = Memetic::adaptive(Rosenbrock::default());
let mut objective = |x: &Vec<f64>| rosenbrock(x);
let outcome = diffusion.run_memetic(
&mut memetic,
&mut objective,
&mut Limits::evaluations(40_000),
&mut (),
&mut SplitMix64::new(3),
);
assert!(outcome.best_cost() < 1e-6, "{}", outcome.best_cost());
}
}