~ruther/ctu-fee-eoa

ref: ef07dac05f823f189763ad0e33c1d64cb1a1ca49 ctu-fee-eoa/env/src/evolutionary_strategy.rs -rw-r--r-- 2.3 KiB
ef07dac0 — Rutherther feat: add evolutionary strategies to local search 2 months 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
use std::convert::Infallible;

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

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

pub trait EvolutionaryStrategy<TOut, TPerturbation: PerturbationOperator> {
    type Err;

    fn step(&mut self,
            perturbation: &mut TPerturbation,
            better: bool,
            stats: &Vec<LocalSearchCandidate<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);

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

pub struct OneToFiveStrategy;
impl<const LEN: usize, TOut> EvolutionaryStrategy<TOut, RandomDistributionPerturbation<LEN, Normal<f64>>> for OneToFiveStrategy {
    type Err = NormalError;

    fn step(&mut self,
            perturbation: &mut RandomDistributionPerturbation<LEN, Normal<f64>>,
            better: bool,
            _: &Vec<LocalSearchCandidate<SVector::<f64, LEN>, TOut>>
    ) -> Result<(), Self::Err> {
        normal_one_to_five(perturbation, better)
    }
}

impl<const LEN: usize, TOut> EvolutionaryStrategy<TOut, BoundedPerturbation<LEN, RandomDistributionPerturbation<LEN, Normal<f64>>>> for OneToFiveStrategy {
    type Err = NormalError;

    fn step(&mut self,
            perturbation: &mut BoundedPerturbation<LEN, RandomDistributionPerturbation<LEN, Normal<f64>>>,
            better: bool,
            _: &Vec<LocalSearchCandidate<<BoundedPerturbation<LEN, RandomDistributionPerturbation<LEN, Normal<f64>>> as PerturbationOperator>::Chromosome, TOut>>
    ) -> Result<(), Self::Err> {
        normal_one_to_five(perturbation.inner_mut(), better)
    }

}

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

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