use alloc::vec::Vec;
use rand_core::Rng;
use super::{Crossover, Initializer, Mutation};
use crate::rng::{below, shuffle, two_sorted_indices};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RandomPermutation {
pub n: usize,
}
impl Initializer<Vec<usize>> for RandomPermutation {
fn initialize<R: Rng + ?Sized>(&mut self, rng: &mut R) -> Vec<usize> {
let mut p: Vec<usize> = (0..self.n).collect();
shuffle(rng, &mut p);
p
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Swap;
impl<T> Mutation<Vec<T>> for Swap {
fn mutate<R: Rng + ?Sized>(&mut self, genome: &mut Vec<T>, rng: &mut R) {
if genome.len() >= 2 {
let (i, j) = two_sorted_indices(rng, genome.len());
genome.swap(i, j);
}
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Insertion;
impl<T> Mutation<Vec<T>> for Insertion {
fn mutate<R: Rng + ?Sized>(&mut self, genome: &mut Vec<T>, rng: &mut R) {
if genome.len() >= 2 {
let from = below(rng, genome.len());
let item = genome.remove(from);
let to = below(rng, genome.len() + 1);
genome.insert(to, item);
}
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Inversion;
impl<T> Mutation<Vec<T>> for Inversion {
fn mutate<R: Rng + ?Sized>(&mut self, genome: &mut Vec<T>, rng: &mut R) {
if genome.len() >= 2 {
let (i, j) = two_sorted_indices(rng, genome.len());
genome[i..=j].reverse();
}
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Scramble;
impl<T> Mutation<Vec<T>> for Scramble {
fn mutate<R: Rng + ?Sized>(&mut self, genome: &mut Vec<T>, rng: &mut R) {
if genome.len() >= 2 {
let (i, j) = two_sorted_indices(rng, genome.len());
shuffle(rng, &mut genome[i..=j]);
}
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Pmx;
impl Crossover<Vec<usize>> for Pmx {
fn crossover<R: Rng + ?Sized>(
&mut self,
a: &Vec<usize>,
b: &Vec<usize>,
rng: &mut R,
) -> [Vec<usize>; 2] {
if a.len() < 2 {
return [a.clone(), b.clone()];
}
let (i, j) = two_sorted_indices(rng, a.len());
[pmx_child(a, b, i, j), pmx_child(b, a, i, j)]
}
}
fn pmx_child(donor: &[usize], filler: &[usize], i: usize, j: usize) -> Vec<usize> {
let n = donor.len();
let mut child = alloc::vec![usize::MAX; n];
let mut position_in_donor = alloc::vec![usize::MAX; n];
for (k, &v) in donor.iter().enumerate() {
position_in_donor[v] = k;
}
child[i..=j].copy_from_slice(&donor[i..=j]);
for k in (0..i).chain(j + 1..n) {
let mut value = filler[k];
while (i..=j).contains(&position_in_donor[value]) {
value = filler[position_in_donor[value]];
}
child[k] = value;
}
child
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Ox;
impl Crossover<Vec<usize>> for Ox {
fn crossover<R: Rng + ?Sized>(
&mut self,
a: &Vec<usize>,
b: &Vec<usize>,
rng: &mut R,
) -> [Vec<usize>; 2] {
if a.len() < 2 {
return [a.clone(), b.clone()];
}
let (i, j) = two_sorted_indices(rng, a.len());
[ox_child(a, b, i, j), ox_child(b, a, i, j)]
}
}
fn ox_child(donor: &[usize], filler: &[usize], i: usize, j: usize) -> Vec<usize> {
let n = donor.len();
let mut used = alloc::vec![false; n];
let mut child = alloc::vec![usize::MAX; n];
for k in i..=j {
child[k] = donor[k];
used[donor[k]] = true;
}
let mut write = (j + 1) % n;
for offset in 0..n {
let value = filler[(j + 1 + offset) % n];
if !used[value] {
child[write] = value;
used[value] = true;
write = (write + 1) % n;
}
}
child
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Cx;
impl Crossover<Vec<usize>> for Cx {
fn crossover<R: Rng + ?Sized>(
&mut self,
a: &Vec<usize>,
b: &Vec<usize>,
_rng: &mut R,
) -> [Vec<usize>; 2] {
let n = a.len();
let mut position_in_a = alloc::vec![0; n];
for (k, &v) in a.iter().enumerate() {
position_in_a[v] = k;
}
let mut c1 = b.clone();
let mut c2 = a.clone();
let mut visited = alloc::vec![false; n];
let mut take_from_a = true;
for start in 0..n {
if visited[start] {
continue;
}
let mut k = start;
while !visited[k] {
visited[k] = true;
if take_from_a {
c1[k] = a[k];
c2[k] = b[k];
}
k = position_in_a[b[k]];
}
take_from_a = !take_from_a;
}
[c1, c2]
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct EdgeRecombination;
impl Crossover<Vec<usize>> for EdgeRecombination {
fn crossover<R: Rng + ?Sized>(
&mut self,
a: &Vec<usize>,
b: &Vec<usize>,
rng: &mut R,
) -> [Vec<usize>; 2] {
[erx_child(a, b, rng), erx_child(b, a, rng)]
}
}
fn erx_child<R: Rng + ?Sized>(first: &[usize], second: &[usize], rng: &mut R) -> Vec<usize> {
let n = first.len();
if n < 2 {
return first.to_vec();
}
let mut edges: Vec<Vec<usize>> = alloc::vec![Vec::with_capacity(4); n];
for tour in [first, second] {
for k in 0..n {
let (v, next) = (tour[k], tour[(k + 1) % n]);
add_edge(&mut edges, v, next);
add_edge(&mut edges, next, v);
}
}
let mut used = alloc::vec![false; n];
let mut child = Vec::with_capacity(n);
let mut current = first[0];
loop {
child.push(current);
used[current] = true;
for list in &mut edges {
list.retain(|&v| v != current);
}
if child.len() == n {
return child;
}
current = next_erx_vertex(&edges, &used, current, rng);
}
}
fn add_edge(edges: &mut [Vec<usize>], v: usize, w: usize) {
if !edges[v].contains(&w) {
edges[v].push(w);
}
}
fn next_erx_vertex<R: Rng + ?Sized>(
edges: &[Vec<usize>],
used: &[bool],
current: usize,
rng: &mut R,
) -> usize {
let neighbours = &edges[current];
if neighbours.is_empty() {
let unused: Vec<usize> = (0..used.len()).filter(|&v| !used[v]).collect();
return unused[below(rng, unused.len())];
}
let fewest = neighbours
.iter()
.map(|&v| edges[v].len())
.min()
.unwrap_or(0);
let candidates: Vec<usize> = neighbours
.iter()
.copied()
.filter(|&v| edges[v].len() == fewest)
.collect();
candidates[below(rng, candidates.len())]
}
#[must_use]
pub fn is_permutation(p: &[usize]) -> bool {
let mut seen = alloc::vec![false; p.len()];
p.iter()
.all(|&v| v < seen.len() && !core::mem::replace(&mut seen[v], true))
}
#[cfg(test)]
mod tests {
use proptest::prelude::*;
use super::*;
use crate::SplitMix64;
proptest! {
#[test]
fn operators_keep_permutations(n in 1usize..30, seed in any::<u64>()) {
let mut rng = SplitMix64::new(seed);
let mut init = RandomPermutation { n };
let a = init.initialize(&mut rng);
let b = init.initialize(&mut rng);
for child in Pmx.crossover(&a, &b, &mut rng)
.into_iter()
.chain(Ox.crossover(&a, &b, &mut rng))
.chain(Cx.crossover(&a, &b, &mut rng))
.chain(EdgeRecombination.crossover(&a, &b, &mut rng))
{
prop_assert!(is_permutation(&child), "{:?}", child);
}
let mut m = a.clone();
Swap.mutate(&mut m, &mut rng);
Insertion.mutate(&mut m, &mut rng);
Inversion.mutate(&mut m, &mut rng);
Scramble.mutate(&mut m, &mut rng);
prop_assert!(is_permutation(&m));
}
}
#[test]
fn pmx_textbook_example() {
let a = [0, 1, 2, 3, 4, 5, 6, 7, 8];
let b = [8, 2, 6, 7, 1, 5, 4, 0, 3];
assert_eq!(pmx_child(&a, &b, 3, 6), [8, 2, 1, 3, 4, 5, 6, 0, 7]);
}
#[test]
fn cycle_crossover_keeps_positions() {
let a = alloc::vec![0, 1, 2, 3, 4, 5, 6, 7, 8];
let b = alloc::vec![8, 2, 5, 6, 3, 1, 7, 4, 0];
let [c1, c2] = Cx.crossover(&a, &b, &mut SplitMix64::new(0));
for k in 0..9 {
assert!(c1[k] == a[k] || c1[k] == b[k]);
assert!(c2[k] == a[k] || c2[k] == b[k]);
}
assert!(is_permutation(&c1) && is_permutation(&c2));
}
}