Skip to main content

evolutionary_planning/operators/
discrete.rs

1//! Operators for bit strings `Vec<bool>` and integer strings `Vec<u32>` with per-gene
2//! domains: random initialisation, bit flips, random reset and creep mutation. Crossovers
3//! for both live in [`sequence`](super::sequence).
4
5use alloc::vec::Vec;
6
7use rand_core::Rng;
8
9use super::{Initializer, Mutation, Repair};
10use crate::rng::{below, chance};
11
12/// Uniform random bit strings of a fixed length.
13#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14pub struct RandomBits {
15    /// The number of bits.
16    pub len: usize,
17}
18
19impl Initializer<Vec<bool>> for RandomBits {
20    fn initialize<R: Rng + ?Sized>(&mut self, rng: &mut R) -> Vec<bool> {
21        (0..self.len).map(|_| rng.next_u32() & 1 == 1).collect()
22    }
23}
24
25/// Flips each bit with probability `rate` (default `1/n`).
26///
27/// ```
28/// use evolutionary_planning::operators::{Mutation, discrete::BitFlip};
29/// use evolutionary_planning::SplitMix64;
30///
31/// let mut bits = vec![false; 8];
32/// BitFlip { rate: Some(1.0) }.mutate(&mut bits, &mut SplitMix64::new(1));
33/// assert!(bits.iter().all(|&b| b));
34/// ```
35#[derive(Debug, Clone, Copy, Default, PartialEq)]
36pub struct BitFlip {
37    /// The per-bit probability; `None` means `1/n`.
38    pub rate: Option<f64>,
39}
40
41impl Mutation<Vec<bool>> for BitFlip {
42    fn mutate<R: Rng + ?Sized>(&mut self, genome: &mut Vec<bool>, rng: &mut R) {
43        #[expect(clippy::cast_precision_loss, reason = "lengths are far below 2^52")]
44        let rate = self.rate.unwrap_or(1.0 / genome.len().max(1) as f64);
45        for bit in genome.iter_mut() {
46            if chance(rng, rate) {
47                *bit = !*bit;
48            }
49        }
50    }
51}
52
53/// Per-gene domains `0..size[i]` of an integer string.
54#[derive(Debug, Clone, PartialEq, Eq)]
55pub struct Domains(pub Vec<u32>);
56
57impl Domains {
58    /// The same domain `0..size` for `len` genes.
59    #[must_use]
60    pub fn uniform(len: usize, size: u32) -> Self {
61        Self(alloc::vec![size; len])
62    }
63}
64
65/// Uniform random integer strings.
66///
67/// # Panics
68///
69/// Panics on an empty domain (`size == 0`).
70impl Initializer<Vec<u32>> for Domains {
71    fn initialize<R: Rng + ?Sized>(&mut self, rng: &mut R) -> Vec<u32> {
72        self.0.iter().map(|&size| draw(rng, size)).collect()
73    }
74}
75
76/// Draws uniformly from `0..size`.
77fn draw<R: Rng + ?Sized>(rng: &mut R, size: u32) -> u32 {
78    u32::try_from(below(rng, size as usize)).expect("below(size) < size, a u32")
79}
80
81/// Replaces each gene with probability `rate` (default `1/n`) by a uniform value of its
82/// domain.
83#[derive(Debug, Clone, PartialEq)]
84pub struct RandomReset {
85    /// The per-gene domains.
86    pub domains: Domains,
87    /// The per-gene probability; `None` means `1/n`.
88    pub rate: Option<f64>,
89}
90
91impl Mutation<Vec<u32>> for RandomReset {
92    fn mutate<R: Rng + ?Sized>(&mut self, genome: &mut Vec<u32>, rng: &mut R) {
93        #[expect(clippy::cast_precision_loss, reason = "lengths are far below 2^52")]
94        let rate = self.rate.unwrap_or(1.0 / genome.len().max(1) as f64);
95        for (gene, &size) in genome.iter_mut().zip(&self.domains.0) {
96            if chance(rng, rate) {
97                *gene = draw(rng, size);
98            }
99        }
100    }
101}
102
103/// Creep mutation: adds a uniform step in `-max_step..=max_step` (non-zero) to each gene with
104/// probability `rate` (default `1/n`), clamped to the domain. Respects causality for ordinal
105/// integers, where random reset does not.
106#[derive(Debug, Clone, PartialEq)]
107pub struct Creep {
108    /// The per-gene domains.
109    pub domains: Domains,
110    /// The largest step, at least `1`.
111    pub max_step: u32,
112    /// The per-gene probability; `None` means `1/n`.
113    pub rate: Option<f64>,
114}
115
116impl Mutation<Vec<u32>> for Creep {
117    fn mutate<R: Rng + ?Sized>(&mut self, genome: &mut Vec<u32>, rng: &mut R) {
118        #[expect(clippy::cast_precision_loss, reason = "lengths are far below 2^52")]
119        let rate = self.rate.unwrap_or(1.0 / genome.len().max(1) as f64);
120        let max_step = self.max_step.max(1);
121        for (gene, &size) in genome.iter_mut().zip(&self.domains.0) {
122            if size <= 1 || !chance(rng, rate) {
123                continue;
124            }
125
126            let step = 1 + draw(rng, max_step);
127            *gene = if rng.next_u32() & 1 == 0 {
128                gene.saturating_sub(step)
129            } else {
130                gene.saturating_add(step).min(size - 1)
131            };
132        }
133    }
134}
135
136/// Clamps every gene into its domain.
137impl Repair<Vec<u32>> for Domains {
138    fn repair<R: Rng + ?Sized>(&mut self, genome: &mut Vec<u32>, _rng: &mut R) {
139        for (gene, &size) in genome.iter_mut().zip(&self.0) {
140            *gene = (*gene).min(size.saturating_sub(1));
141        }
142    }
143}
144
145#[cfg(test)]
146mod tests {
147    use super::*;
148    use crate::SplitMix64;
149
150    /// Integer operators stay within their domains.
151    #[test]
152    fn integer_operators_respect_domains() {
153        let mut domains = Domains(alloc::vec![1, 2, 5, 100]);
154        let mut rng = SplitMix64::new(3);
155        let mut reset = RandomReset {
156            domains: domains.clone(),
157            rate: Some(1.0),
158        };
159        let mut creep = Creep {
160            domains: domains.clone(),
161            max_step: 3,
162            rate: Some(1.0),
163        };
164        for _ in 0..200 {
165            let mut g = domains.initialize(&mut rng);
166            reset.mutate(&mut g, &mut rng);
167            creep.mutate(&mut g, &mut rng);
168            assert!(g.iter().zip(&domains.0).all(|(v, s)| v < s));
169        }
170    }
171}