~ruther/ctu-fee-eoa

ref: aaf2bc68d200389de87196a9b98551f620a06648 ctu-fee-eoa/codes/eoa_lib/src/evolutionary_strategy.rs -rw-r--r-- 2.3 KiB
aaf2bc68 — Rutherther chore: part of 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
use std::{convert::Infallible, error::Error};

use nalgebra::SVector;
use rand_distr::{Normal, NormalError};

use crate::{local_search::LocalSearchStats, perturbation::{apply_to_perturbations, BoundedPerturbation, PerturbationOperator, RandomDistributionPerturbation}};

pub trait EvolutionaryStrategy<TOut, TPerturbation: PerturbationOperator> {
    type Err: Error + 'static;

    fn step(&mut self,
            perturbation: &mut TPerturbation,
            better: bool,
            stats: &LocalSearchStats<TPerturbation::Chromosome, TOut>
    ) -> Result<(), Self::Err>;
}

fn normal_one_to_five<const LEN: usize>(perturbation: &mut RandomDistributionPerturbation<LEN, Normal<f64>>, better: bool) -> Result<(), NormalError> {
    let exp: f64 = if better { 1.0 } else { 0.0 } - 0.2;
    let sigma = perturbation.std_dev();

    let new_sigma = sigma * exp.exp().powf(1.0 / LEN as f64);

    // Hopefully prevent cases when the sigma goes too low
    let new_sigma = if new_sigma < 0.000000001 {
        0.000000001
    } else {
        new_sigma
    };

    perturbation.set_std_dev(new_sigma)?;
    Ok(())
}

pub struct OneToFiveStrategy;
impl<const LEN: usize,
     TPerturbation: PerturbationOperator<Chromosome = SVector<f64, LEN>>,
     TOut> EvolutionaryStrategy<TOut, TPerturbation> for OneToFiveStrategy {
    type Err = NormalError;

    fn step(&mut self,
            perturbation: &mut TPerturbation,
            better: bool,
            _: &LocalSearchStats<SVector::<f64, LEN>, TOut>
    ) -> Result<(), Self::Err> {
        let mut found = false;
        let mut result = Ok(());
        apply_to_perturbations::<_, RandomDistributionPerturbation<LEN, Normal<f64>>>(
            perturbation,
            &mut |perturbation| {
                found = true;
                result = normal_one_to_five(perturbation, better);
            }
        );

        if !found {
            panic!("There is no random distribution perturbation!");
        }

        result
    }
}

pub struct IdentityStrategy;
impl<TOut, TPerturbation: PerturbationOperator> EvolutionaryStrategy<TOut, TPerturbation> for IdentityStrategy {
    type Err = Infallible;

    fn step(&mut self,
            _: &mut TPerturbation,
            _: bool,
            _: &LocalSearchStats<TPerturbation::Chromosome, TOut>
    ) -> Result<(), Self::Err> {
        Ok(())
    }
}