ecrs 0.1.0-beta.4

Evolutionary computation tools & algorithms
Documentation
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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
use std::{marker::PhantomData, ops::IndexMut};

use len_trait::Len;
use push_trait::{Nothing, Push};
use rand::{rngs::ThreadRng, Rng};

use crate::ga::individual::IndividualTrait;

/// # Mutation Operator
///
/// This trait defines common behaviour for mutation operators.
/// You can implement this trait to provide your custom crossover operator to the GA.
pub trait MutationOperator<IndividualT: IndividualTrait> {
    /// Mutates provided solution in place
    ///
    /// ## Arguments
    ///
    /// * `individual` - mutable reference to to-be-mutated individual
    /// * `mutation_rate` - probability of gene mutation
    fn apply(&mut self, individual: &mut IndividualT, mutation_rate: f64);
}

/// # Identity Mutation Operator
///
/// This struct implements [MutationOperator] trait and can be used with GA.
///
/// Identity does not perform any changes to the chromosome. Use this if you
/// do not want to mutate your solutions.
pub struct Identity;

impl Identity {
    /// Returns new [Identity] mutation operator
    pub fn new() -> Self {
        Identity {}
    }
}

impl<IndividualT: IndividualTrait> MutationOperator<IndividualT> for Identity {
    fn apply(&mut self, _individual: &mut IndividualT, _mutation_rate: f64) {}
}

/// ### Flilp bit mutation operator
///
/// This struct implements [MutationOperator] trait and can be used with GA
///
/// Genes are muatated by flipping the value - `1` becomes `0` and vice versa
pub struct FlipBit<R: Rng> {
    rng: R,
}

impl FlipBit<ThreadRng> {
    /// Returns new instance of [FlipBit] mutation operator with default RNG
    pub fn new() -> Self {
        Self::with_rng(rand::thread_rng())
    }
}

impl<R: Rng> FlipBit<R> {
    /// Returns new instance of [FlipBit] mutation operator with custom RNG
    pub fn with_rng(rng: R) -> Self {
        Self { rng }
    }
}

impl<IndividualT, R> MutationOperator<IndividualT> for FlipBit<R>
where
    IndividualT: IndividualTrait,
    IndividualT::ChromosomeT: IndexMut<usize, Output = bool> + Push<bool, PushedOut = Nothing>,
    R: Rng,
{
    /// Mutates provided solution in place
    ///
    /// Genes are muatated by flipping the value - `1` becomes `0` and vice versa
    ///
    /// ## Arguments
    ///
    /// * `individual` - mutable reference to to-be-mutated individual
    /// * `mutation_rate` - probability of gene mutation
    fn apply(&mut self, individual: &mut IndividualT, mutation_rate: f64) {
        let distribution = rand::distributions::Uniform::from(0.0..1.0);
        let chromosome_ref = individual.chromosome_mut();
        let chromosome_len = chromosome_ref.len();

        for i in 0..chromosome_len {
            if self.rng.sample(distribution) < mutation_rate {
                chromosome_ref[i] = !chromosome_ref[i];
            }
        }
    }
}

/// ### Interchange mustation operator
///
/// This struct implements [MutationOperator] trait and can be used with GA
///
/// If a gene is to be muatated, a new locus is randomly choosen and gene values are interchanged
pub struct Interchange<R: Rng> {
    rng: R,
}

impl Interchange<ThreadRng> {
    /// Returns new instance of [Interchange] mutation operator with default RNG
    pub fn new() -> Self {
        Self::with_rng(rand::thread_rng())
    }
}

impl<R: Rng> Interchange<R> {
    /// Returns new instance of [Interchange] mutation operator with custom RNG
    pub fn with_rng(rng: R) -> Self {
        Self { rng }
    }
}

impl<IndividualT, G, R> MutationOperator<IndividualT> for Interchange<R>
where
    G: Copy,
    IndividualT: IndividualTrait,
    IndividualT::ChromosomeT: IndexMut<usize, Output = G> + Push<G, PushedOut = Nothing>,
    R: Rng,
{
    /// Mutates provided solution in place
    ///
    /// If a gene is to be muatated, a new locus is randomly choosen and gene values are interchanged
    ///
    /// ## Arguments
    ///
    /// * `individual` - mutable reference to to-be-mutated individual
    /// * `mutation_rate` - probability of gene mutation
    fn apply(&mut self, individual: &mut IndividualT, mutation_rate: f64) {
        let chromosome_ref = individual.chromosome_mut();
        let chromosome_len = chromosome_ref.len();

        let dist = rand::distributions::Uniform::from(0.0..1.0);
        let index_dist = rand::distributions::Uniform::from(0..chromosome_len);

        for i in 0..chromosome_len {
            if self.rng.sample(dist) < mutation_rate {
                let rand_index = rand::thread_rng().sample(index_dist);
                let gene = chromosome_ref[rand_index];
                chromosome_ref[rand_index] = chromosome_ref[i];
                chromosome_ref[i] = gene;
            }
        }
    }
}

/// ### Reversing mutation operator
///
/// This struct implements [MutationOperator] trait and can be used with GA
///
/// Random locus is selected and genes next to the selection position are reversed
pub struct Reversing<R: Rng = ThreadRng> {
    rng: R,
}

impl Reversing<ThreadRng> {
    /// Returns new instance of [Reversing] mutation operator with default RNG
    pub fn new() -> Self {
        Self::with_rng(rand::thread_rng())
    }
}

impl<R: Rng> Reversing<R> {
    /// Returns new instance of [Reversing] mutation operator with custom RNG
    pub fn with_rng(rng: R) -> Self {
        Self { rng }
    }
}

impl<IndividualT, GeneT, R> MutationOperator<IndividualT> for Reversing<R>
where
    GeneT: Copy,
    IndividualT: IndividualTrait,
    IndividualT::ChromosomeT: IndexMut<usize, Output = GeneT> + Push<GeneT, PushedOut = Nothing>,
    R: Rng,
{
    /// Mutates provided solution in place
    ///
    /// Random locus is selected and genes next to the selection position are reversed
    ///
    /// ## Arguments
    ///
    /// * `individual` - mutable reference to to-be-mutated individual
    /// * `mutation_rate` - probability of gene mutation
    fn apply(&mut self, individual: &mut IndividualT, mutation_rate: f64) {
        let dist = rand::distributions::Uniform::from(0.0..1.0);
        let chromosome_ref = individual.chromosome_mut();
        let chromosome_len = chromosome_ref.len();

        for i in 1..chromosome_len {
            if self.rng.sample(dist) < mutation_rate {
                let gene = chromosome_ref[i];
                chromosome_ref[i] = chromosome_ref[i - 1];
                chromosome_ref[i - 1] = gene;
            }
        }
    }
}

/// ### [Inversion] mutation operator
///
/// This struct implements [MutationOperator] trait and can be used with GA
///
/// Two random locations are chosen marking out a segment of chromosome.
/// Genes from this segment are then rotated around the segment's middle point.
pub struct Inversion<R: Rng, GeneT: Copy> {
    rng: R,
    _marker: PhantomData<GeneT>,
}

impl<GeneT: Copy> Inversion<ThreadRng, GeneT> {
    /// Returns new instance of [Inversion] mutation operator with default RNG
    pub fn new() -> Self {
        Self::with_rng(rand::thread_rng())
    }
}

impl<R: Rng, GeneT: Copy> Inversion<R, GeneT> {
    /// Returns new instance of [Inversion] mutation operator with custom RNG
    pub fn with_rng(rng: R) -> Self {
        Self {
            rng,
            _marker: PhantomData,
        }
    }
}

impl<IndividualT: IndividualTrait, GeneT: Copy, R: Rng> MutationOperator<IndividualT> for Inversion<R, GeneT>
where
    IndividualT::ChromosomeT: Len + AsMut<[GeneT]>,
{
    /// Mutates provided solution in place
    ///
    /// Two random locations are chosen marking out a segment of chromosome.
    /// Genes from this segment are then rotated around the segment's middle point.
    ///
    /// ## Arguments
    ///
    /// * `individual` - mutable reference to to-be-mutated individual
    /// * `mutation_rate` - probability of gene mutation
    fn apply(&mut self, individual: &mut IndividualT, mutation_rate: f64) {
        let _marker: PhantomData<GeneT> = PhantomData;

        let r: f64 = self.rng.gen();

        if r > mutation_rate {
            return;
        }

        let chromosome_len = individual.chromosome().len();
        let mut from: usize = self.rng.gen_range(0..chromosome_len);
        let mut to: usize = self.rng.gen_range(from..chromosome_len);

        while from < to {
            individual.chromosome_mut().as_mut().swap(from, to);
            from += 1;
            to -= 1;
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::ga::{individual::IndividualTrait, Individual};
    use itertools::Itertools;
    use rand::{distributions::Uniform, Rng};

    use super::{FlipBit, Identity, Interchange, MutationOperator, Reversing};

    #[test]
    fn identity_does_not_change_chromosome() {
        let chromosome = rand::thread_rng()
            .sample_iter(Uniform::from(-1.0..1.0))
            .take(30)
            .collect_vec();

        let mut individual = Individual {
            chromosome: chromosome.clone(),
            fitness: f64::default(),
        };

        let mut identity_mutation = Identity;

        identity_mutation.apply(&mut individual, 1.);

        assert_eq!(chromosome, individual.chromosome);
    }

    #[test]
    fn flipbit_negates_chromosome() {
        let chromosome = rand::thread_rng()
            .sample_iter(Uniform::from(-1.0..1.0))
            .take(30)
            .map(|val| val > 0.)
            .collect_vec();

        let chromosome_clone = chromosome.clone();

        let mut individual = Individual {
            chromosome,
            fitness: f64::default(),
        };

        let mut operator = FlipBit::new();

        operator.apply(&mut individual, 1.);

        for (actual, expected) in std::iter::zip(chromosome_clone, individual.chromosome()) {
            assert_eq!(actual, !*expected);
        }
    }

    #[test]
    fn flipbit_does_not_mutate_rate_0() {
        let chromosome = rand::thread_rng()
            .sample_iter(Uniform::from(-1.0..1.0))
            .take(30)
            .map(|val| val > 0.)
            .collect_vec();

        let chromosome_clone = chromosome.clone();

        let mut individual = Individual {
            chromosome,
            fitness: f64::default(),
        };

        let mut operator = FlipBit::new();

        operator.apply(&mut individual, 0.);

        for (actual, expected) in std::iter::zip(chromosome_clone, individual.chromosome()) {
            assert_eq!(actual, *expected);
        }
    }

    #[test]
    fn interchange_introduces_changes() {
        let chromosome = rand::thread_rng()
            .sample_iter(Uniform::from(-1.0..1.0))
            .take(300)
            .map(|val| val > 0.)
            .collect_vec();

        let chromosome_clone = chromosome.clone();

        let mut individual = Individual {
            chromosome,
            fitness: f64::default(),
        };

        let mut operator = Interchange::new();

        operator.apply(&mut individual, 1.);
        let changes = std::iter::zip(chromosome_clone, individual.chromosome())
            .filter(|p| p.0 != *p.1)
            .count();
        assert!(changes > 0);
    }

    #[test]
    fn interchange_does_not_mutate_rate_0() {
        let chromosome = rand::thread_rng()
            .sample_iter(Uniform::from(-1.0..1.0))
            .take(30)
            .map(|val| val > 0.)
            .collect_vec();

        let chromosome_clone = chromosome.clone();

        let mut individual = Individual {
            chromosome,
            fitness: f64::default(),
        };

        let mut operator = Interchange::new();

        operator.apply(&mut individual, 0.);

        for (actual, expected) in std::iter::zip(chromosome_clone, individual.chromosome()) {
            assert_eq!(actual, *expected);
        }
    }

    #[test]
    fn reversing_bubbles_first_gene_when_rate_1() {
        let chromosome = rand::thread_rng()
            .sample_iter(Uniform::from(-1.0..1.0))
            .take(40)
            .collect_vec();

        let mut individual = Individual {
            chromosome,
            fitness: f64::default(),
        };

        let first_gene_value = individual.chromosome()[0];

        let mut operator = Reversing::new();

        operator.apply(&mut individual, 1.0);

        assert_eq!(
            first_gene_value,
            individual.chromosome()[individual.chromosome().len() - 1]
        );
    }
}