use alloc::vec::Vec;
use rand_core::Rng;
use crate::evaluator::Evaluator;
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 Scheme {
Generational,
SteadyState {
only_if_better: bool,
},
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Config {
pub population_size: usize,
pub elitism: usize,
pub crossover_rate: f64,
pub mutation_rate: f64,
pub scheme: Scheme,
}
impl Default for Config {
fn default() -> Self {
Self {
population_size: 100,
elitism: 1,
crossover_rate: 0.9,
mutation_rate: 1.0,
scheme: Scheme::Generational,
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Operators<I, S, X, M, P> {
pub init: I,
pub selection: S,
pub crossover: X,
pub mutation: M,
pub repair: P,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Ga<I, S, X, M, P> {
pub config: Config,
pub operators: Operators<I, S, X, M, P>,
}
pub(crate) trait Refine<G> {
fn refine<O, B, Obs, R>(
&mut self,
child: Individual<G>,
evaluator: &mut Evaluator<'_, G, O, B, Obs>,
rng: &mut R,
) -> Individual<G>
where
G: Clone,
O: Objective<G> + ?Sized,
B: Budget<Stats> + ?Sized,
Obs: Observer + ?Sized,
R: Rng + ?Sized;
}
pub(crate) struct NoRefine;
impl<G> Refine<G> for NoRefine {
fn refine<O, B, Obs, R>(
&mut self,
child: Individual<G>,
_evaluator: &mut Evaluator<'_, G, O, B, Obs>,
_rng: &mut R,
) -> Individual<G>
where
G: Clone,
O: Objective<G> + ?Sized,
B: Budget<Stats> + ?Sized,
Obs: Observer + ?Sized,
R: Rng + ?Sized,
{
child
}
}
impl<I, S, X, M, P> Ga<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,
{
self.run_from(Vec::new(), objective, budget, observer, rng)
}
pub fn run_from<G, O, B, Obs, R>(
&mut self,
seeds: Vec<G>,
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(seeds, &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(Vec::new(), &mut evaluator, memetic, rng)
}
pub(crate) fn evolve<G, O, B, Obs, F, R>(
&mut self,
seeds: Vec<G>,
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,
{
assert!(
self.config.population_size >= 2,
"a GA needs at least two individuals"
);
let Some(mut population) = self.initial_population(seeds, evaluator, refine, rng) else {
return finish(evaluator, Vec::new());
};
evaluator.end_generation(population_best(&population));
match self.config.scheme {
Scheme::Generational => self.generational(&mut population, evaluator, refine, rng),
Scheme::SteadyState { only_if_better } => {
self.steady_state(&mut population, only_if_better, evaluator, refine, rng);
}
}
finish(evaluator, population)
}
fn initial_population<G, O, B, Obs, F, R>(
&mut self,
seeds: Vec<G>,
evaluator: &mut Evaluator<'_, G, O, B, Obs>,
refine: &mut F,
rng: &mut R,
) -> Option<Vec<Individual<G>>>
where
G: Clone,
I: Initializer<G>,
O: Objective<G> + ?Sized,
B: Budget<Stats> + ?Sized,
Obs: Observer + ?Sized,
F: Refine<G>,
R: Rng + ?Sized,
{
let size = self.config.population_size;
let mut genomes = seeds;
genomes.truncate(size);
while genomes.len() < size {
genomes.push(self.operators.init.initialize(rng));
}
let mut population = Vec::with_capacity(size);
for genome in genomes {
let individual = evaluator.individual(genome)?;
population.push(refine.refine(individual, evaluator, rng));
}
Some(population)
}
fn generational<G, O, B, Obs, F, R>(
&mut self,
population: &mut Vec<Individual<G>>,
evaluator: &mut Evaluator<'_, G, O, B, Obs>,
refine: &mut F,
rng: &mut R,
) 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 size = self.config.population_size;
let mut parents = Vec::with_capacity(2);
loop {
crate::cost::sort_population(population);
let costs: Vec<f64> = population.iter().map(|i| i.cost).collect();
let mut next: Vec<Individual<G>> =
population[..self.config.elitism.min(size - 1)].to_vec();
while next.len() < size {
parents.clear();
self.operators
.selection
.select(&costs, 2, rng, &mut parents);
for child in self.breed(
&population[parents[0]].genome,
&population[parents[1]].genome,
rng,
) {
if next.len() == size {
break;
}
let Some(individual) = evaluator.individual(child) else {
return;
};
next.push(refine.refine(individual, evaluator, rng));
}
}
*population = next;
evaluator.end_generation(population_best(population));
}
}
fn steady_state<G, O, B, Obs, F, R>(
&mut self,
population: &mut [Individual<G>],
only_if_better: bool,
evaluator: &mut Evaluator<'_, G, O, B, Obs>,
refine: &mut F,
rng: &mut R,
) 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 mut parents = Vec::with_capacity(2);
let mut offspring_in_generation = 0;
loop {
let costs: Vec<f64> = population.iter().map(|i| i.cost).collect();
parents.clear();
self.operators
.selection
.select(&costs, 2, rng, &mut parents);
let children = self.breed(
&population[parents[0]].genome,
&population[parents[1]].genome,
rng,
);
for child in children {
let Some(individual) = evaluator.individual(child) else {
return;
};
let individual = refine.refine(individual, evaluator, rng);
replace_worst(population, individual, only_if_better);
offspring_in_generation += 1;
if offspring_in_generation == population.len() {
offspring_in_generation = 0;
evaluator.end_generation(population_best(population));
}
}
}
}
fn breed<G, R>(&mut self, a: &G, b: &G, rng: &mut R) -> [G; 2]
where
G: Clone,
X: Crossover<G>,
M: Mutation<G>,
P: Repair<G>,
R: Rng + ?Sized,
{
let mut children = if chance(rng, self.config.crossover_rate) {
self.operators.crossover.crossover(a, b, rng)
} else {
[a.clone(), b.clone()]
};
for child in &mut children {
if chance(rng, self.config.mutation_rate) {
self.operators.mutation.mutate(child, rng);
}
self.operators.repair.repair(child, rng);
}
children
}
}
fn replace_worst<G>(
population: &mut [Individual<G>],
newcomer: Individual<G>,
only_if_better: bool,
) {
let worst = population
.iter()
.enumerate()
.max_by(|a, b| a.1.cost.total_cmp(&b.1.cost).then(a.0.cmp(&b.0)))
.map_or(0, |(index, _)| index);
if !only_if_better || newcomer.cost < population[worst].cost {
population[worst] = newcomer;
}
}
pub(crate) fn population_best<G>(population: &[Individual<G>]) -> f64 {
population
.iter()
.map(|i| i.cost)
.fold(f64::INFINITY, f64::min)
}
fn finish<G: Clone, O, B, Obs>(
evaluator: &mut Evaluator<'_, G, O, B, Obs>,
population: Vec<Individual<G>>,
) -> Outcome<G>
where
O: Objective<G> + ?Sized,
B: Budget<Stats> + ?Sized,
Obs: Observer + ?Sized,
{
evaluator.outcome(population, Stop::Budget)
}
#[cfg(test)]
mod tests;