Skip to main content

evolutionary_planning/operators/
sequence.rs

1//! Positional crossovers for any `Vec<T>`: one-point, two-point and uniform. They also accept
2//! parents of different lengths: cut points lie within the shorter parent and tails are
3//! exchanged whole, so lengths are swapped, never invented.
4
5use alloc::vec::Vec;
6
7use rand_core::Rng;
8
9use super::Crossover;
10use crate::rng::{below, two_sorted_indices, unit_f64};
11
12/// One-point crossover: cut both parents at the same position `c ∈ 1..min_len` and exchange
13/// the tails.
14///
15/// ```
16/// use evolutionary_planning::operators::{Crossover, sequence::OnePoint};
17/// use evolutionary_planning::SplitMix64;
18///
19/// let [c1, c2] = OnePoint.crossover(&vec![0; 4], &vec![1; 4], &mut SplitMix64::new(1));
20/// assert_eq!(c1.len() + c2.len(), 8);
21/// ```
22#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
23pub struct OnePoint;
24
25impl<T: Clone> Crossover<Vec<T>> for OnePoint {
26    fn crossover<R: Rng + ?Sized>(&mut self, a: &Vec<T>, b: &Vec<T>, rng: &mut R) -> [Vec<T>; 2] {
27        let shorter = a.len().min(b.len());
28        if shorter < 2 {
29            return [a.clone(), b.clone()];
30        }
31
32        let cut = 1 + below(rng, shorter - 1);
33
34        [splice(a, b, cut, cut), splice(b, a, cut, cut)]
35    }
36}
37
38/// Returns `head[..head_cut]` followed by `tail[tail_cut..]`.
39pub(crate) fn splice<T: Clone>(head: &[T], tail: &[T], head_cut: usize, tail_cut: usize) -> Vec<T> {
40    let mut child = Vec::with_capacity(head_cut + tail.len() - tail_cut);
41    child.extend_from_slice(&head[..head_cut]);
42    child.extend_from_slice(&tail[tail_cut..]);
43
44    child
45}
46
47/// Two-point crossover: exchange the segment between two cut points within the shorter
48/// parent.
49#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
50pub struct TwoPoint;
51
52impl<T: Clone> Crossover<Vec<T>> for TwoPoint {
53    fn crossover<R: Rng + ?Sized>(&mut self, a: &Vec<T>, b: &Vec<T>, rng: &mut R) -> [Vec<T>; 2] {
54        let shorter = a.len().min(b.len());
55        if shorter < 2 {
56            return [a.clone(), b.clone()];
57        }
58
59        let (i, j) = two_sorted_indices(rng, shorter + 1);
60        let mut c1 = a.clone();
61        let mut c2 = b.clone();
62        c1[i..j].clone_from_slice(&b[i..j]);
63        c2[i..j].clone_from_slice(&a[i..j]);
64
65        [c1, c2]
66    }
67}
68
69/// Uniform crossover: exchange each position of the common prefix with probability `swap`.
70#[derive(Debug, Clone, Copy, PartialEq)]
71pub struct UniformCrossover {
72    /// The per-position exchange probability; `0.5` is customary.
73    pub swap: f64,
74}
75
76impl Default for UniformCrossover {
77    fn default() -> Self {
78        Self { swap: 0.5 }
79    }
80}
81
82impl<T: Clone> Crossover<Vec<T>> for UniformCrossover {
83    fn crossover<R: Rng + ?Sized>(&mut self, a: &Vec<T>, b: &Vec<T>, rng: &mut R) -> [Vec<T>; 2] {
84        let mut c1 = a.clone();
85        let mut c2 = b.clone();
86        for k in 0..a.len().min(b.len()) {
87            if unit_f64(rng) < self.swap {
88                c1[k] = b[k].clone();
89                c2[k] = a[k].clone();
90            }
91        }
92
93        [c1, c2]
94    }
95}
96
97#[cfg(test)]
98mod tests {
99    use alloc::vec;
100
101    use super::*;
102    use crate::SplitMix64;
103
104    /// Positional crossovers keep the per-position multiset of the parents.
105    #[test]
106    fn crossovers_exchange_positions() {
107        let a = vec![0u8; 10];
108        let b = vec![1u8; 10];
109        let mut rng = SplitMix64::new(5);
110        for _ in 0..50 {
111            for [c1, c2] in [
112                OnePoint.crossover(&a, &b, &mut rng),
113                TwoPoint.crossover(&a, &b, &mut rng),
114                UniformCrossover::default().crossover(&a, &b, &mut rng),
115            ] {
116                for k in 0..10 {
117                    assert_eq!(c1[k] + c2[k], 1);
118                }
119            }
120        }
121    }
122
123    /// One-point crossover of unequal parents swaps tails.
124    #[test]
125    fn one_point_unequal_lengths() {
126        let [c1, c2] = OnePoint.crossover(&vec![0; 3], &vec![1; 7], &mut SplitMix64::new(2));
127
128        assert_eq!(c1.len() + c2.len(), 10);
129        assert!(c1.len() == 7 && c2.len() == 3);
130    }
131}