pub mod chain;
pub mod discrete;
pub mod permutation;
pub mod real;
pub mod selection;
pub mod sequence;
use alloc::vec::Vec;
use rand_core::Rng;
use crate::rng::{chance, unit_f64};
pub use selection::Selection;
pub trait Initializer<G> {
fn initialize<R: Rng + ?Sized>(&mut self, rng: &mut R) -> G;
}
pub trait Mutation<G: ?Sized> {
fn mutate<R: Rng + ?Sized>(&mut self, genome: &mut G, rng: &mut R);
}
pub trait Crossover<G> {
fn crossover<R: Rng + ?Sized>(&mut self, a: &G, b: &G, rng: &mut R) -> [G; 2];
}
pub trait Repair<G: ?Sized> {
fn repair<R: Rng + ?Sized>(&mut self, genome: &mut G, rng: &mut R);
}
impl<G: ?Sized, M: Mutation<G> + ?Sized> Mutation<G> for &mut M {
fn mutate<R: Rng + ?Sized>(&mut self, genome: &mut G, rng: &mut R) {
(**self).mutate(genome, rng);
}
}
impl<G, X: Crossover<G> + ?Sized> Crossover<G> for &mut X {
fn crossover<R: Rng + ?Sized>(&mut self, a: &G, b: &G, rng: &mut R) -> [G; 2] {
(**self).crossover(a, b, rng)
}
}
impl<G, I: Initializer<G> + ?Sized> Initializer<G> for &mut I {
fn initialize<R: Rng + ?Sized>(&mut self, rng: &mut R) -> G {
(**self).initialize(rng)
}
}
impl<G: ?Sized, P: Repair<G> + ?Sized> Repair<G> for &mut P {
fn repair<R: Rng + ?Sized>(&mut self, genome: &mut G, rng: &mut R) {
(**self).repair(genome, rng);
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Variation<I, X, M, P> {
pub init: I,
pub crossover: X,
pub mutation: M,
pub repair: P,
}
impl<I, X, M, P> Variation<I, X, M, P> {
pub fn breed<G, R>(
&mut self,
a: &G,
b: &G,
crossover_rate: f64,
mutation_rate: f64,
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, crossover_rate) {
self.crossover.crossover(a, b, rng)
} else {
[a.clone(), b.clone()]
};
for child in &mut children {
if chance(rng, mutation_rate) {
self.mutation.mutate(child, rng);
}
self.repair.repair(child, rng);
}
children
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct NoRepair;
impl<G: ?Sized> Repair<G> for NoRepair {
fn repair<R: Rng + ?Sized>(&mut self, _genome: &mut G, _rng: &mut R) {}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct NoMutation;
impl<G: ?Sized> Mutation<G> for NoMutation {
fn mutate<R: Rng + ?Sized>(&mut self, _genome: &mut G, _rng: &mut R) {}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct NoCrossover;
impl<G: Clone> Crossover<G> for NoCrossover {
fn crossover<R: Rng + ?Sized>(&mut self, a: &G, b: &G, _rng: &mut R) -> [G; 2] {
[a.clone(), b.clone()]
}
}
fn with_dyn<R: Rng + ?Sized, T>(rng: &mut R, f: impl FnOnce(&mut dyn Rng) -> T) -> T {
let mut rng = rng;
f(&mut rng)
}
pub fn initializer_fn<G, F: FnMut(&mut dyn Rng) -> G>(f: F) -> InitializerFn<F> {
InitializerFn(f)
}
#[derive(Debug, Clone, Copy)]
pub struct InitializerFn<F>(F);
impl<G, F: FnMut(&mut dyn Rng) -> G> Initializer<G> for InitializerFn<F> {
fn initialize<R: Rng + ?Sized>(&mut self, rng: &mut R) -> G {
with_dyn(rng, |rng| (self.0)(rng))
}
}
pub fn mutation_fn<G: ?Sized, F: FnMut(&mut G, &mut dyn Rng)>(f: F) -> MutationFn<F> {
MutationFn(f)
}
#[derive(Debug, Clone, Copy)]
pub struct MutationFn<F>(F);
impl<G: ?Sized, F: FnMut(&mut G, &mut dyn Rng)> Mutation<G> for MutationFn<F> {
fn mutate<R: Rng + ?Sized>(&mut self, genome: &mut G, rng: &mut R) {
with_dyn(rng, |rng| (self.0)(genome, rng));
}
}
pub fn crossover_fn<G, F: FnMut(&G, &G, &mut dyn Rng) -> [G; 2]>(f: F) -> CrossoverFn<F> {
CrossoverFn(f)
}
#[derive(Debug, Clone, Copy)]
pub struct CrossoverFn<F>(F);
impl<G, F: FnMut(&G, &G, &mut dyn Rng) -> [G; 2]> Crossover<G> for CrossoverFn<F> {
fn crossover<R: Rng + ?Sized>(&mut self, a: &G, b: &G, rng: &mut R) -> [G; 2] {
with_dyn(rng, |rng| (self.0)(a, b, rng))
}
}
pub fn repair_fn<G: ?Sized, F: FnMut(&mut G, &mut dyn Rng)>(f: F) -> RepairFn<F> {
RepairFn(f)
}
#[derive(Debug, Clone, Copy)]
pub struct RepairFn<F>(F);
impl<G: ?Sized, F: FnMut(&mut G, &mut dyn Rng)> Repair<G> for RepairFn<F> {
fn repair<R: Rng + ?Sized>(&mut self, genome: &mut G, rng: &mut R) {
with_dyn(rng, |rng| (self.0)(genome, rng));
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Mix<A, B> {
pub a: A,
pub b: B,
pub probability_a: f64,
}
#[must_use]
pub fn mix<A, B>(a: A, weight_a: f64, b: B, weight_b: f64) -> Mix<A, B> {
assert!(
weight_a >= 0.0 && weight_b >= 0.0 && weight_a + weight_b > 0.0,
"mix weights must be non-negative and not both zero"
);
Mix {
a,
b,
probability_a: weight_a / (weight_a + weight_b),
}
}
impl<G: ?Sized, A: Mutation<G>, B: Mutation<G>> Mutation<G> for Mix<A, B> {
fn mutate<R: Rng + ?Sized>(&mut self, genome: &mut G, rng: &mut R) {
if unit_f64(rng) < self.probability_a {
self.a.mutate(genome, rng);
} else {
self.b.mutate(genome, rng);
}
}
}
impl<G, A: Crossover<G>, B: Crossover<G>> Crossover<G> for Mix<A, B> {
fn crossover<R: Rng + ?Sized>(&mut self, a: &G, b: &G, rng: &mut R) -> [G; 2] {
if unit_f64(rng) < self.probability_a {
self.a.crossover(a, b, rng)
} else {
self.b.crossover(a, b, rng)
}
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Then<A, B> {
pub first: A,
pub second: B,
}
impl<G: ?Sized, A: Mutation<G>, B: Mutation<G>> Mutation<G> for Then<A, B> {
fn mutate<R: Rng + ?Sized>(&mut self, genome: &mut G, rng: &mut R) {
self.first.mutate(genome, rng);
self.second.mutate(genome, rng);
}
}
impl<G: ?Sized, A: Repair<G>, B: Repair<G>> Repair<G> for Then<A, B> {
fn repair<R: Rng + ?Sized>(&mut self, genome: &mut G, rng: &mut R) {
self.first.repair(genome, rng);
self.second.repair(genome, rng);
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Sometimes<M> {
pub inner: M,
pub probability: f64,
}
impl<G: ?Sized, M: Mutation<G>> Mutation<G> for Sometimes<M> {
fn mutate<R: Rng + ?Sized>(&mut self, genome: &mut G, rng: &mut R) {
if chance(rng, self.probability) {
self.inner.mutate(genome, rng);
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Seeded<G, I> {
seeds: Vec<G>,
inner: I,
}
impl<G, I> Seeded<G, I> {
#[must_use]
pub fn new(mut seeds: Vec<G>, inner: I, population_size: usize, max_fraction: f64) -> Self {
#[expect(
clippy::cast_possible_truncation,
clippy::cast_sign_loss,
clippy::cast_precision_loss,
reason = "a population fraction, clamped to [0, population_size]"
)]
let cap = ((max_fraction.clamp(0.0, 1.0) * population_size as f64) as usize).max(1);
seeds.truncate(cap);
seeds.reverse();
Self { seeds, inner }
}
}
impl<G, I: Initializer<G>> Initializer<G> for Seeded<G, I> {
fn initialize<R: Rng + ?Sized>(&mut self, rng: &mut R) -> G {
match self.seeds.pop() {
Some(seed) => seed,
None => self.inner.initialize(rng),
}
}
}
#[cfg(test)]
mod tests {
use alloc::vec;
use super::*;
use crate::SplitMix64;
#[test]
fn mix_respects_weights() {
let mut rng = SplitMix64::new(1);
let mut m = mix(
mutation_fn(|x: &mut u32, _| *x += 1),
1.0,
mutation_fn(|x: &mut u32, _| *x += 100),
0.0,
);
let mut value = 0;
for _ in 0..10 {
m.mutate(&mut value, &mut rng);
}
assert_eq!(value, 10);
}
#[test]
fn seeded_caps_and_orders() {
let mut rng = SplitMix64::new(1);
let mut init = Seeded::new(vec![1, 2, 3], initializer_fn(|_| 0), 10, 0.2);
let got: Vec<i32> = (0..4).map(|_| init.initialize(&mut rng)).collect();
assert_eq!(got, [1, 2, 0, 0]);
}
}