~ruther/ctu-fee-eoa

ref: f4e5737f84743bce957c891b4ea569cb4d067dab ctu-fee-eoa/codes/eoa_lib/src/perturbation/mod.rs -rw-r--r-- 13.1 KiB
f4e5737f — Rutherther chore: finalize report a month 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
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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
use std::{any::Any, borrow::{Borrow, BorrowMut}, marker::PhantomData};

use nalgebra::{allocator::Allocator, DefaultAllocator, Dim, SVector};
use rand::{distr::Distribution, Rng, RngCore, prelude::IteratorRandom};
use rand_distr::{uniform, Normal, NormalError, Uniform};

use crate::binary_string::BinaryString;

pub trait AnyPerturbationOperator: Any {
    fn as_any(&self) -> &dyn Any;
    fn as_any_mut(&mut self) -> &mut dyn Any;
}

pub enum Wrapped<'a, T> {
    Single,
    Wrapped(&'a dyn PerturbationOperator<Chromosome = T>),
    ListWrapped(Vec<&'a dyn PerturbationOperator<Chromosome = T>>),
}

pub enum WrappedMut<'a, T> {
    Single,
    Wrapped(&'a mut dyn PerturbationOperator<Chromosome = T>),
    ListWrapped(Vec<&'a mut dyn PerturbationOperator<Chromosome = T>>),
}

pub trait PerturbationOperator: AnyPerturbationOperator {
    type Chromosome;

    fn perturb(&self, chromosome: &mut Self::Chromosome, rng: &mut dyn RngCore);

    fn wrapped(&self) -> Wrapped<'_, Self::Chromosome> {
        Wrapped::Single
    }

    fn wrapped_mut(&mut self) -> WrappedMut<'_, Self::Chromosome> {
        WrappedMut::Single
    }
}

impl<T: PerturbationOperator> AnyPerturbationOperator for T
where
    T: Any + 'static
{
    fn as_any(&self) -> &dyn Any {
        self
    }
    fn as_any_mut(&mut self) -> &mut dyn Any {
        self
    }
}

pub struct IdentityPerturbation<TChromosome> {
    _phantom: PhantomData<TChromosome>
}

impl<TChromosome: 'static> PerturbationOperator for IdentityPerturbation<TChromosome> {
    type Chromosome = TChromosome;

    fn perturb(&self, _: &mut Self::Chromosome, _: &mut dyn RngCore) {
        // Do nothing.
    }
}

pub struct BinaryStringBitPerturbation<D> {
    pub p: f64,
    _phantom: PhantomData<D>
}

impl<D> BinaryStringBitPerturbation<D> {
    pub fn new(p: f64) -> Self {
        Self {
            p,
            _phantom: PhantomData
        }
    }
}

impl<D> PerturbationOperator for BinaryStringBitPerturbation<D>
where
    D: Dim,
    DefaultAllocator: Allocator<D>
{
    type Chromosome = BinaryString<D>;

    fn perturb(&self, chromosome: &mut Self::Chromosome, rng: &mut dyn RngCore) {
        chromosome.perturb(rng, self.p);
    }
}

pub struct BinaryStringSingleBitPerturbation<D> {
    _phantom: PhantomData<D>
}

impl<D> BinaryStringSingleBitPerturbation<D> {
    pub fn new() -> Self {
        Self {
            _phantom: PhantomData
        }
    }
}

impl<D> PerturbationOperator for BinaryStringSingleBitPerturbation<D>
where
    D: Dim,
    DefaultAllocator: Allocator<D>
{
    type Chromosome = BinaryString<D>;

    fn perturb(&self, chromosome: &mut Self::Chromosome, rng: &mut dyn RngCore) {
        let bit_range = 0..chromosome.vec.len();
        let flip_bit = rng.random_range(bit_range);

        chromosome.vec[flip_bit] = 1 - chromosome.vec[flip_bit];
    }
}

pub struct BinaryStringFlipPerturbation<D> {
    _phantom: PhantomData<D>
}

impl<D> BinaryStringFlipPerturbation<D> {
    pub fn new() -> Self {
        Self {
            _phantom: PhantomData
        }
    }
}

impl<D> PerturbationOperator for BinaryStringFlipPerturbation<D>
where
    D: Dim,
    DefaultAllocator: Allocator<D>
{
    type Chromosome = BinaryString<D>;

    fn perturb(&self, chromosome: &mut Self::Chromosome, _: &mut dyn RngCore) {
        chromosome.vec
            .apply(|c| *c = 1 - *c);
    }
}

pub struct BinaryStringFlipNPerturbation<D> {
    n: usize,
    _phantom: PhantomData<D>,
}

impl<D> BinaryStringFlipNPerturbation<D> {
    pub fn new(n: usize) -> Self {
        Self {
            n,
            _phantom: PhantomData
        }
    }
}

impl<D> PerturbationOperator for BinaryStringFlipNPerturbation<D>
where
    D: Dim,
    DefaultAllocator: Allocator<D>
{
    type Chromosome = BinaryString<D>;

    fn perturb(&self, chromosome: &mut Self::Chromosome, rng: &mut dyn RngCore) {
        let index = rng.random_range(0..chromosome.vec.len());

        for i in index..(index + self.n).min(chromosome.vec.len()) {
            chromosome.vec[i] = 1 - chromosome.vec[i];
        }
    }
}

pub struct RandomDistributionPerturbation<const LEN: usize, TDistribution: Distribution<f64>> {
    distribution: TDistribution,
    parameter: f64
}

impl<const LEN: usize> RandomDistributionPerturbation<LEN, Normal<f64>> {
    pub fn normal(std_dev: f64) -> Result<Self, NormalError> {
        Ok(Self {
            distribution: Normal::new(0.0, std_dev)?,
            parameter: std_dev
        })
    }

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

    pub fn set_std_dev(&mut self, std_dev: f64) -> Result<f64, NormalError> {
        self.parameter = std_dev;
        self.distribution = Normal::new(0.0, std_dev)?;
        Ok(std_dev)
    }
}

impl<const LEN: usize> RandomDistributionPerturbation<LEN, Uniform<f64>> {
    pub fn uniform(range: f64) -> Result<Self, uniform::Error> {
        Ok(Self {
            distribution: Uniform::new(-range/2.0, range/2.0)?,
            parameter: range,
        })
    }

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

    pub fn set_range(&mut self, range: f64) -> Result<f64, uniform::Error> {
        self.parameter = range;
        self.distribution = Uniform::new(-range/2.0, range/2.0)?;
        Ok(range)
    }
}

impl<TDistribution: Distribution<f64> + 'static, const LEN: usize> PerturbationOperator for RandomDistributionPerturbation<LEN, TDistribution> {
    type Chromosome = SVector<f64, LEN>;

    fn perturb(&self, chromosome: &mut Self::Chromosome, rng: &mut dyn RngCore) {
        *chromosome += Self::Chromosome::zeros().map(|_| self.distribution.sample(rng));
    }
}

pub struct PatternPerturbation<const LEN: usize> {
    d: f64
}

impl<const LEN: usize> PatternPerturbation<LEN> {
    pub fn new(d: f64) -> Self {
        Self {
            d
        }
    }
}

impl<const LEN: usize> PerturbationOperator for PatternPerturbation<LEN> {
    type Chromosome = SVector::<f64, LEN>;

    fn perturb(&self, chromosome: &mut Self::Chromosome, rng: &mut dyn RngCore) {
        // 1. Choose dimension
        let idx = rng.random_range(0..LEN);
        // 2. Direction
        let d = if rng.random_bool(0.5) {
            self.d
        } else {
            -self.d
        };

        // Apply
        chromosome[idx] += d;
    }
}

pub enum BoundedPerturbationStrategy {
    /// Trims the value to get a value within bounds
    Trim,
    /// Retries calling the underlying perturbation until
    /// value within bounds is returned. If argument is given,
    /// this is the maximum number of retries to do and then
    /// fall back to trimming. Zero means retry indefinitely.
    Retry(usize)
}

pub struct BoundedPerturbation<const LEN: usize, T: PerturbationOperator<Chromosome = SVector<f64, LEN>>> {
    min_max: SVector<(f64, f64), LEN>,
    strategy: BoundedPerturbationStrategy,
    perturbation: T,
}

impl<const LEN: usize, T: PerturbationOperator<Chromosome = SVector<f64, LEN>>> BoundedPerturbation<LEN, T> {
    pub fn new(
        perturbation: T,
        min: SVector<f64, LEN>,
        max: SVector<f64, LEN>,
        strategy: BoundedPerturbationStrategy
    ) -> Self {
        let min_max = min.zip_map(&max, |min, max| (min, max));
        Self {
            min_max,
            strategy,
            perturbation
        }
    }

    fn within_bounds(&self, chromosome: &SVector<f64, LEN>) -> bool {
        chromosome.iter()
            .zip(self.min_max.iter())
            .all(|(&c, &(min, max))| c <= max && c >= min)
    }

    fn bound(&self, mut chromosome: SVector<f64, LEN>) -> SVector<f64, LEN> {
        chromosome
            .zip_apply(&self.min_max, |c, (min, max)| *c = c.clamp(min, max));

        chromosome
    }

    fn retry_perturb(&self, chromosome: &mut SVector<f64, LEN>, retries: Option<usize>, rng: &mut dyn RngCore) {
        let mut perturbed = chromosome.clone();
        self.perturbation.perturb(&mut perturbed, rng);

        if self.within_bounds(&perturbed) {
            *chromosome = perturbed;
            return;
        }

        match retries {
            Some(0) | None => *chromosome = self.bound(perturbed),
            Some(retries) => {
                *chromosome = perturbed;
                self.retry_perturb(chromosome, Some(retries - 1), rng);
            }
        }
    }
}

impl<const LEN: usize, T> PerturbationOperator for BoundedPerturbation<LEN, T>
where
    T: PerturbationOperator<Chromosome = SVector<f64, LEN>>
{
    type Chromosome = SVector<f64, LEN>;

    fn perturb(&self, chromosome: &mut Self::Chromosome, rng: &mut dyn RngCore) {
        match self.strategy {
            BoundedPerturbationStrategy::Trim => self.retry_perturb(chromosome, None, rng),
            BoundedPerturbationStrategy::Retry(retries) => self.retry_perturb(chromosome, Some(retries), rng)
        }
    }

    fn wrapped(&self) -> Wrapped<'_, Self::Chromosome> {
        Wrapped::Wrapped(&self.perturbation)
    }

    fn wrapped_mut(&mut self) -> WrappedMut<'_, Self::Chromosome> {
        WrappedMut::Wrapped(&mut self.perturbation)
    }
}

/// Perform given perturbation only with given probability
pub struct MutationPerturbation<T> {
    perturbation: Box<dyn PerturbationOperator<Chromosome = T>>,
    pub probability: f64
}

impl<T: 'static> MutationPerturbation<T> {
    pub fn new(perturbation: Box<dyn PerturbationOperator<Chromosome = T>>, probability: f64) -> Self {
        Self {
            perturbation,
            probability
        }
    }

    pub fn apply_to_mutations(
        base_perturbation: &mut dyn PerturbationOperator<Chromosome = T>,
        apply: &mut dyn FnMut(&mut MutationPerturbation<T>)
    ) {
        apply_to_perturbations(base_perturbation, apply);
    }
}

pub fn apply_to_perturbations<T: 'static, U: PerturbationOperator<Chromosome = T>>(
    base_perturbation: &mut dyn PerturbationOperator<Chromosome = T>,
    apply: &mut dyn FnMut(&mut U)
) {
    if let Some(mutation) = base_perturbation.as_any_mut().downcast_mut::<U>() {
        apply(mutation);
    }

    match base_perturbation.wrapped_mut() {
        WrappedMut::Single => (),
        WrappedMut::Wrapped(wrapped) => {
            apply_to_perturbations(wrapped, apply);
        },
        WrappedMut::ListWrapped(wrapped) => {
            for wrapped in wrapped {
                apply_to_perturbations(wrapped, apply);
            }
        }
    };
}

impl<T: 'static> PerturbationOperator for MutationPerturbation<T> {
    type Chromosome = T;

    fn perturb(&self, chromosome: &mut Self::Chromosome, rng: &mut dyn RngCore) {
        if rng.random_bool(self.probability) {
            self.perturbation.perturb(chromosome, rng);
        }
    }

    fn wrapped(&self) -> Wrapped<'_, Self::Chromosome> {
        Wrapped::Wrapped(self.perturbation.as_ref())
    }

    fn wrapped_mut(&mut self) -> WrappedMut<'_, Self::Chromosome> {
        WrappedMut::Wrapped(self.perturbation.as_mut())
    }
}

pub struct CombinedPerturbation<T> {
    perturbations: Vec<Box<dyn PerturbationOperator<Chromosome = T>>>,
}

impl<T> CombinedPerturbation<T> {
    pub fn new(perturbations: Vec<Box<dyn PerturbationOperator<Chromosome = T>>>) -> Self {
        Self {
            perturbations,
        }
    }
}

impl<T: 'static> PerturbationOperator for CombinedPerturbation<T> {
    type Chromosome = T;

    fn perturb(&self, chromosome: &mut Self::Chromosome, rng: &mut dyn RngCore) {
        for perturbation in self.perturbations.iter() {
            perturbation.perturb(chromosome, rng);
        }
    }

    fn wrapped(&self) -> Wrapped<'_, Self::Chromosome> {
        Wrapped::ListWrapped(
            self.perturbations
                .iter()
                .map(|p| p.as_ref()).collect())
    }

    fn wrapped_mut(&mut self) -> WrappedMut<'_, Self::Chromosome> {
        WrappedMut::ListWrapped(
            self.perturbations
                .iter_mut()
                .map(|p| p.as_mut()).collect())
    }
}

pub struct OneOfPerturbation<T> {
    perturbations: Vec<Box<dyn PerturbationOperator<Chromosome = T>>>
}

impl<T> OneOfPerturbation<T> {
    pub fn new(perturbations: Vec<Box<dyn PerturbationOperator<Chromosome = T>>>) -> Self {
        Self {
            perturbations
        }
    }
}

impl<T: 'static> PerturbationOperator for OneOfPerturbation<T> {
    type Chromosome = T;

    fn perturb(&self, chromosome: &mut Self::Chromosome, rng: &mut dyn RngCore) {
        let chosen = (0..self.perturbations.len()).choose(rng);
        if let Some(chosen) = chosen {
            self.perturbations[chosen].perturb(chromosome, rng);
        }
    }
}

#[cfg(test)]
pub mod tests {
    use crate::binary_string::BinaryString;

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

        let mut binary_string1 = BinaryString::new_dyn(vec![1, 1, 0, 0]);
        binary_string1.perturb(&mut rng, 1.0);
        assert_eq!(
            *binary_string1
                .vec()
                .iter()
                .map(|&x| x)
                .collect::<Vec<_>>(),
            vec![0, 0, 1, 1]
        );

        let mut binary_string2 = BinaryString::new_dyn(vec![1, 1, 0, 0]);
        binary_string2.perturb(&mut rng, 0.0);
        assert_eq!(
            *binary_string2
                .vec()
                .iter()
                .map(|&x| x)
                .collect::<Vec<_>>(),
            vec![1, 1, 0, 0]
        );
    }
}