~ruther/ctu-fee-eoa

ref: ff86cab83b7a8afcf2cba73d12cb63b074544207 ctu-fee-eoa/codes/eoa_lib/src/replacement.rs -rw-r--r-- 4.5 KiB
ff86cab8 — Rutherther fix: problem g05 was missing sin calls 6 days 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
use rand::{seq::IteratorRandom, RngCore};
use std::fmt::Debug;

use crate::{comparison::BetterThanOperator, population::EvaluatedPopulation, selection::{Selection, TournamentSelection}};

fn extract_by_indices<T>(mut x: Vec<T>, mut idxs: Vec<usize>) -> Vec<T> {
    idxs.sort_unstable_by(|a, b| b.cmp(a));

    let mut result = Vec::with_capacity(idxs.len());
    for idx in idxs {
        if idx < x.len() {
            result.push(x.swap_remove(idx));
        }
    }

    result.reverse();
    result
}

pub trait Replacement<TChromosome, TResult> {
    fn replace(
        &self,
        parents_evaluations: EvaluatedPopulation<TChromosome, TResult>,
        offsprings_evaluations: EvaluatedPopulation<TChromosome, TResult>,
        better_than: &dyn BetterThanOperator<TResult>,
        rng: &mut dyn RngCore
    ) -> EvaluatedPopulation<TChromosome, TResult>;
}

pub struct BestReplacement;
impl BestReplacement {
    pub fn new() -> Self {
        Self
    }
}

impl<TChromosome, TResult: Debug> Replacement<TChromosome, TResult> for BestReplacement {
    fn replace(
        &self,
        parents_evaluations: EvaluatedPopulation<TChromosome, TResult>,
        offsprings_evaluations: EvaluatedPopulation<TChromosome, TResult>,
        better_than: &dyn BetterThanOperator<TResult>,
        _rng: &mut dyn RngCore
    ) -> EvaluatedPopulation<TChromosome, TResult> {
        let count = parents_evaluations.population.len();
        let mut population = parents_evaluations;
        population.join(offsprings_evaluations);

        let mut idxs = (0..population.population.len())
            .collect::<Vec<_>>();
        idxs.sort_unstable_by(|&i, &j| better_than.ordering(
            &population.population[i].evaluation,
            &population.population[j].evaluation)
        );

        idxs.truncate(count);

        EvaluatedPopulation::from_vec(
            extract_by_indices(population.deconstruct(), idxs)
        )
    }
}

pub struct GenerationalReplacement;
impl<TInput, TResult> Replacement<TInput, TResult> for GenerationalReplacement {
    fn replace(
        &self,
        parents: EvaluatedPopulation<TInput, TResult>,
        mut offsprings: EvaluatedPopulation<TInput, TResult>,
        _: &dyn BetterThanOperator<TResult>,
        _rng: &mut dyn RngCore
    ) -> EvaluatedPopulation<TInput, TResult> {
        let count = parents.population.len();
        if count == offsprings.population.len() {
            return offsprings;
        }

        offsprings.join(parents);
        offsprings.population.truncate(count);
        // let population = offsprings.deconstruct();
        // population.truncate(count);

        // EvaluatedPopulation::from_vec(population)

        offsprings
    }
}

pub struct RandomReplacement;

impl RandomReplacement {
    pub fn new() -> Self {
        Self
    }
}

impl<TInput, TResult> Replacement<TInput, TResult> for RandomReplacement {
    fn replace(
        &self,
        parents: EvaluatedPopulation<TInput, TResult>,
        offsprings: EvaluatedPopulation<TInput, TResult>,
        _: &dyn BetterThanOperator<TResult>,
        rng: &mut dyn RngCore
    ) -> EvaluatedPopulation<TInput, TResult> {
        let count = parents.population.len();

        EvaluatedPopulation::from_vec(
            parents.deconstruct()
                .into_iter()
                .chain(offsprings.deconstruct().into_iter())
                .choose_multiple(rng, count))
    }
}

pub struct TournamentReplacement {
    selection: TournamentSelection
}

impl TournamentReplacement {
    pub fn new(k: usize, p: f64) -> Self {
        TournamentReplacement {
            selection: TournamentSelection::new(
                k,
                p,
            )
        }
    }
}

impl<TInput, TResult: Debug> Replacement<TInput, TResult> for TournamentReplacement {
    fn replace(
        &self,
        parents: EvaluatedPopulation<TInput, TResult>,
        offsprings: EvaluatedPopulation<TInput, TResult>,
        better_than: &dyn BetterThanOperator<TResult>,
        rng: &mut dyn RngCore
    ) -> EvaluatedPopulation<TInput, TResult> {
        let count = parents.population.len();
        let mut population = parents;
        population.join(offsprings);

        // TODO: use a pool instead of allocating vector every run of this function
        let selected = self.selection.select(count, &population, better_than, rng)
            .collect::<Vec<_>>();

        let population = population.deconstruct();
        let population = extract_by_indices(population, selected);

        EvaluatedPopulation::from_vec(population)
    }
}