1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
//! The `order` module provides `operator::MutationOp`s for permutation encoded
//! `genetic::Genotype`s.

use crate::{
    operator::{GeneticOperator, MutationOp},
    random::{random_cut_points, Rng},
};
use std::fmt::Debug;

#[allow(missing_copy_implementations)]
#[derive(Clone, Debug, PartialEq)]
pub struct InsertOrderMutator {
    mutation_rate: f64,
}

impl InsertOrderMutator {
    pub fn new(mutation_rate: f64) -> Self {
        InsertOrderMutator { mutation_rate }
    }

    pub fn mutation_rate(&self) -> f64 {
        self.mutation_rate
    }

    pub fn set_mutation_rate(&mut self, value: f64) {
        self.mutation_rate = value;
    }
}

impl GeneticOperator for InsertOrderMutator {
    fn name() -> String {
        "Order-Insert-Mutation".to_string()
    }
}

impl<V> MutationOp<Vec<V>> for InsertOrderMutator
where
    V: Clone + Debug + PartialEq + Send + Sync,
{
    fn mutate<R>(&self, genome: Vec<V>, rng: &mut R) -> Vec<V>
    where
        R: Rng + Sized,
    {
        let genome_length = genome.len();
        let num_mutations =
            ((genome_length as f64 * self.mutation_rate) + rng.gen::<f64>()).floor() as usize;
        let mut mutated = genome;
        for _ in 0..num_mutations {
            let (locus1, locus2) = random_cut_points(rng, genome_length);
            let value2 = mutated.remove(locus2);
            mutated.insert(locus1 + 1, value2);
        }
        mutated
    }
}

#[allow(missing_copy_implementations)]
#[derive(Clone, Debug, PartialEq)]
pub struct SwapOrderMutator {
    mutation_rate: f64,
}

impl SwapOrderMutator {
    pub fn new(mutation_rate: f64) -> Self {
        SwapOrderMutator { mutation_rate }
    }

    pub fn mutation_rate(&self) -> f64 {
        self.mutation_rate
    }

    pub fn set_mutation_rate(&mut self, value: f64) {
        self.mutation_rate = value;
    }
}

impl GeneticOperator for SwapOrderMutator {
    fn name() -> String {
        "Order-Swap-Mutation".to_string()
    }
}

impl<V> MutationOp<Vec<V>> for SwapOrderMutator
where
    V: Clone + Debug + PartialEq + Send + Sync,
{
    fn mutate<R>(&self, genome: Vec<V>, rng: &mut R) -> Vec<V>
    where
        R: Rng + Sized,
    {
        let genome_length = genome.len();
        let num_mutations =
            ((genome_length as f64 * self.mutation_rate) + rng.gen::<f64>()).floor() as usize;
        let mut mutated = genome;
        for _ in 0..num_mutations {
            let (locus1, locus2) = random_cut_points(rng, genome_length);
            mutated.swap(locus1, locus2);
        }
        mutated
    }
}