~ruther/ctu-fee-eoa

ref: dfddcfde9cade6fd94ace5bca2f846f48c230e3c ctu-fee-eoa/env/src/perturbation/mod.rs -rw-r--r-- 1.0 KiB
dfddcfde — Rutherther chore: split types and functions to separate module files a day ago
                                                                                
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
use rand::Rng;

use crate::binary_string::BinaryString;

pub trait PerturbationOperator {
    type Chromosome;

    fn perturb(self: &mut Self, chromosome: &Self::Chromosome) -> Self::Chromosome;
}

pub struct BinaryStringBitPerturbation<TRng: Rng> {
    rng: TRng,
    p: f64,
}

impl BinaryStringBitPerturbation<rand::rngs::ThreadRng> {
    pub fn new(p: f64) -> Self {
        Self {
            rng: rand::rng(),
            p
        }
    }
}

impl<TRng: Rng> PerturbationOperator for BinaryStringBitPerturbation<TRng> {
    type Chromosome = BinaryString;

    fn perturb(self: &mut Self, chromosome: &Self::Chromosome) -> Self::Chromosome {
        chromosome.perturb(&mut self.rng, self.p)
    }
}

#[test]
fn test_perturb() {
    let mut rng = rand::rng();

    assert_eq!(
        *BinaryString::new(vec![1, 1, 0, 0])
            .perturb(&mut rng, 1.0)
            .vec(),
        vec![0, 0, 1, 1]
    );

    assert_eq!(
        *BinaryString::new(vec![1, 1, 0, 0])
            .perturb(&mut rng, 0.0)
            .vec(),
        vec![1, 1, 0, 0]
    );
}