1pub mod chain;
18pub mod discrete;
19pub mod permutation;
20pub mod real;
21pub mod selection;
22pub mod sequence;
23
24use alloc::vec::Vec;
25
26use rand_core::Rng;
27
28use crate::rng::{chance, unit_f64};
29
30pub use selection::Selection;
31
32pub trait Initializer<G> {
34 fn initialize<R: Rng + ?Sized>(&mut self, rng: &mut R) -> G;
36}
37
38pub trait Mutation<G: ?Sized> {
40 fn mutate<R: Rng + ?Sized>(&mut self, genome: &mut G, rng: &mut R);
42}
43
44pub trait Crossover<G> {
46 fn crossover<R: Rng + ?Sized>(&mut self, a: &G, b: &G, rng: &mut R) -> [G; 2];
48}
49
50pub trait Repair<G: ?Sized> {
54 fn repair<R: Rng + ?Sized>(&mut self, genome: &mut G, rng: &mut R);
56}
57
58impl<G: ?Sized, M: Mutation<G> + ?Sized> Mutation<G> for &mut M {
59 fn mutate<R: Rng + ?Sized>(&mut self, genome: &mut G, rng: &mut R) {
60 (**self).mutate(genome, rng);
61 }
62}
63
64impl<G, X: Crossover<G> + ?Sized> Crossover<G> for &mut X {
65 fn crossover<R: Rng + ?Sized>(&mut self, a: &G, b: &G, rng: &mut R) -> [G; 2] {
66 (**self).crossover(a, b, rng)
67 }
68}
69
70impl<G, I: Initializer<G> + ?Sized> Initializer<G> for &mut I {
71 fn initialize<R: Rng + ?Sized>(&mut self, rng: &mut R) -> G {
72 (**self).initialize(rng)
73 }
74}
75
76impl<G: ?Sized, P: Repair<G> + ?Sized> Repair<G> for &mut P {
77 fn repair<R: Rng + ?Sized>(&mut self, genome: &mut G, rng: &mut R) {
78 (**self).repair(genome, rng);
79 }
80}
81
82#[derive(Debug, Clone, PartialEq)]
85pub struct Variation<I, X, M, P> {
86 pub init: I,
88 pub crossover: X,
90 pub mutation: M,
92 pub repair: P,
94}
95
96impl<I, X, M, P> Variation<I, X, M, P> {
97 pub fn breed<G, R>(
100 &mut self,
101 a: &G,
102 b: &G,
103 crossover_rate: f64,
104 mutation_rate: f64,
105 rng: &mut R,
106 ) -> [G; 2]
107 where
108 G: Clone,
109 X: Crossover<G>,
110 M: Mutation<G>,
111 P: Repair<G>,
112 R: Rng + ?Sized,
113 {
114 let mut children = if chance(rng, crossover_rate) {
115 self.crossover.crossover(a, b, rng)
116 } else {
117 [a.clone(), b.clone()]
118 };
119
120 for child in &mut children {
121 if chance(rng, mutation_rate) {
122 self.mutation.mutate(child, rng);
123 }
124
125 self.repair.repair(child, rng);
126 }
127
128 children
129 }
130}
131
132#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
134pub struct NoRepair;
135
136impl<G: ?Sized> Repair<G> for NoRepair {
137 fn repair<R: Rng + ?Sized>(&mut self, _genome: &mut G, _rng: &mut R) {}
138}
139
140#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
142pub struct NoMutation;
143
144impl<G: ?Sized> Mutation<G> for NoMutation {
145 fn mutate<R: Rng + ?Sized>(&mut self, _genome: &mut G, _rng: &mut R) {}
146}
147
148#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
150pub struct NoCrossover;
151
152impl<G: Clone> Crossover<G> for NoCrossover {
153 fn crossover<R: Rng + ?Sized>(&mut self, a: &G, b: &G, _rng: &mut R) -> [G; 2] {
154 [a.clone(), b.clone()]
155 }
156}
157
158fn with_dyn<R: Rng + ?Sized, T>(rng: &mut R, f: impl FnOnce(&mut dyn Rng) -> T) -> T {
160 let mut rng = rng;
161
162 f(&mut rng)
163}
164
165pub fn initializer_fn<G, F: FnMut(&mut dyn Rng) -> G>(f: F) -> InitializerFn<F> {
175 InitializerFn(f)
176}
177
178#[derive(Debug, Clone, Copy)]
180pub struct InitializerFn<F>(F);
181
182impl<G, F: FnMut(&mut dyn Rng) -> G> Initializer<G> for InitializerFn<F> {
183 fn initialize<R: Rng + ?Sized>(&mut self, rng: &mut R) -> G {
184 with_dyn(rng, |rng| (self.0)(rng))
185 }
186}
187
188pub fn mutation_fn<G: ?Sized, F: FnMut(&mut G, &mut dyn Rng)>(f: F) -> MutationFn<F> {
190 MutationFn(f)
191}
192
193#[derive(Debug, Clone, Copy)]
195pub struct MutationFn<F>(F);
196
197impl<G: ?Sized, F: FnMut(&mut G, &mut dyn Rng)> Mutation<G> for MutationFn<F> {
198 fn mutate<R: Rng + ?Sized>(&mut self, genome: &mut G, rng: &mut R) {
199 with_dyn(rng, |rng| (self.0)(genome, rng));
200 }
201}
202
203pub fn crossover_fn<G, F: FnMut(&G, &G, &mut dyn Rng) -> [G; 2]>(f: F) -> CrossoverFn<F> {
205 CrossoverFn(f)
206}
207
208#[derive(Debug, Clone, Copy)]
210pub struct CrossoverFn<F>(F);
211
212impl<G, F: FnMut(&G, &G, &mut dyn Rng) -> [G; 2]> Crossover<G> for CrossoverFn<F> {
213 fn crossover<R: Rng + ?Sized>(&mut self, a: &G, b: &G, rng: &mut R) -> [G; 2] {
214 with_dyn(rng, |rng| (self.0)(a, b, rng))
215 }
216}
217
218pub fn repair_fn<G: ?Sized, F: FnMut(&mut G, &mut dyn Rng)>(f: F) -> RepairFn<F> {
220 RepairFn(f)
221}
222
223#[derive(Debug, Clone, Copy)]
225pub struct RepairFn<F>(F);
226
227impl<G: ?Sized, F: FnMut(&mut G, &mut dyn Rng)> Repair<G> for RepairFn<F> {
228 fn repair<R: Rng + ?Sized>(&mut self, genome: &mut G, rng: &mut R) {
229 with_dyn(rng, |rng| (self.0)(genome, rng));
230 }
231}
232
233#[derive(Debug, Clone, Copy, PartialEq)]
244pub struct Mix<A, B> {
245 pub a: A,
247 pub b: B,
249 pub probability_a: f64,
251}
252
253#[must_use]
259pub fn mix<A, B>(a: A, weight_a: f64, b: B, weight_b: f64) -> Mix<A, B> {
260 assert!(
261 weight_a >= 0.0 && weight_b >= 0.0 && weight_a + weight_b > 0.0,
262 "mix weights must be non-negative and not both zero"
263 );
264
265 Mix {
266 a,
267 b,
268 probability_a: weight_a / (weight_a + weight_b),
269 }
270}
271
272impl<G: ?Sized, A: Mutation<G>, B: Mutation<G>> Mutation<G> for Mix<A, B> {
273 fn mutate<R: Rng + ?Sized>(&mut self, genome: &mut G, rng: &mut R) {
274 if unit_f64(rng) < self.probability_a {
275 self.a.mutate(genome, rng);
276 } else {
277 self.b.mutate(genome, rng);
278 }
279 }
280}
281
282impl<G, A: Crossover<G>, B: Crossover<G>> Crossover<G> for Mix<A, B> {
283 fn crossover<R: Rng + ?Sized>(&mut self, a: &G, b: &G, rng: &mut R) -> [G; 2] {
284 if unit_f64(rng) < self.probability_a {
285 self.a.crossover(a, b, rng)
286 } else {
287 self.b.crossover(a, b, rng)
288 }
289 }
290}
291
292#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
294pub struct Then<A, B> {
295 pub first: A,
297 pub second: B,
299}
300
301impl<G: ?Sized, A: Mutation<G>, B: Mutation<G>> Mutation<G> for Then<A, B> {
302 fn mutate<R: Rng + ?Sized>(&mut self, genome: &mut G, rng: &mut R) {
303 self.first.mutate(genome, rng);
304 self.second.mutate(genome, rng);
305 }
306}
307
308impl<G: ?Sized, A: Repair<G>, B: Repair<G>> Repair<G> for Then<A, B> {
309 fn repair<R: Rng + ?Sized>(&mut self, genome: &mut G, rng: &mut R) {
310 self.first.repair(genome, rng);
311 self.second.repair(genome, rng);
312 }
313}
314
315#[derive(Debug, Clone, Copy, PartialEq)]
317pub struct Sometimes<M> {
318 pub inner: M,
320 pub probability: f64,
322}
323
324impl<G: ?Sized, M: Mutation<G>> Mutation<G> for Sometimes<M> {
325 fn mutate<R: Rng + ?Sized>(&mut self, genome: &mut G, rng: &mut R) {
326 if chance(rng, self.probability) {
327 self.inner.mutate(genome, rng);
328 }
329 }
330}
331
332#[derive(Debug, Clone, PartialEq)]
339pub struct Seeded<G, I> {
340 seeds: Vec<G>,
342 inner: I,
344}
345
346impl<G, I> Seeded<G, I> {
347 #[must_use]
350 pub fn new(mut seeds: Vec<G>, inner: I, population_size: usize, max_fraction: f64) -> Self {
351 #[expect(
352 clippy::cast_possible_truncation,
353 clippy::cast_sign_loss,
354 clippy::cast_precision_loss,
355 reason = "a population fraction, clamped to [0, population_size]"
356 )]
357 let cap = ((max_fraction.clamp(0.0, 1.0) * population_size as f64) as usize).max(1);
358 seeds.truncate(cap);
359 seeds.reverse();
360
361 Self { seeds, inner }
362 }
363}
364
365impl<G, I: Initializer<G>> Initializer<G> for Seeded<G, I> {
366 fn initialize<R: Rng + ?Sized>(&mut self, rng: &mut R) -> G {
367 match self.seeds.pop() {
368 Some(seed) => seed,
369 None => self.inner.initialize(rng),
370 }
371 }
372}
373
374#[cfg(test)]
375mod tests {
376 use alloc::vec;
377
378 use super::*;
379 use crate::SplitMix64;
380
381 #[test]
383 fn mix_respects_weights() {
384 let mut rng = SplitMix64::new(1);
385 let mut m = mix(
386 mutation_fn(|x: &mut u32, _| *x += 1),
387 1.0,
388 mutation_fn(|x: &mut u32, _| *x += 100),
389 0.0,
390 );
391 let mut value = 0;
392 for _ in 0..10 {
393 m.mutate(&mut value, &mut rng);
394 }
395
396 assert_eq!(value, 10);
397 }
398
399 #[test]
401 fn seeded_caps_and_orders() {
402 let mut rng = SplitMix64::new(1);
403 let mut init = Seeded::new(vec![1, 2, 3], initializer_fn(|_| 0), 10, 0.2);
404 let got: Vec<i32> = (0..4).map(|_| init.initialize(&mut rng)).collect();
405
406 assert_eq!(got, [1, 2, 0, 0]);
407 }
408}