~ruther/ctu-fee-eoa

ref: 372dc756e002ef91480f4455c046b8d8da30458d ctu-fee-eoa/codes/eoa_lib/src/replacement.rs -rw-r--r-- 7.9 KiB
372dc756 — Rutherther tests: adjust evolution one_max algorithm to always find optimum 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
use rand::{seq::IteratorRandom, RngCore};
use std::fmt::Debug;

use crate::{comparison::BetterThanOperator, fitness::FitnessFunction, 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
}

#[derive(Clone, Debug)]
pub struct Population<TChromosome> {
    population: Vec<TChromosome>
}

#[derive(Clone, Debug)]
pub struct EvaluatedChromosome<TChromosome, TResult> {
    pub chromosome: TChromosome,
    pub evaluation: TResult,
}

#[derive(Clone, Debug)]
pub struct EvaluatedPopulation<TChromosome, TResult> {
    pub population: Vec<EvaluatedChromosome<TChromosome, TResult>>
}

impl<TChromosome> Population<TChromosome> {
    pub fn from_vec(vec: Vec<TChromosome>) -> Self {
        Self {
            population: vec
        }
    }

    pub fn from_iterator(iter: impl Iterator<Item = TChromosome>) -> Self {
        Self::from_vec(iter.collect())
    }

    pub fn evaluate<T: FitnessFunction<In = TChromosome>>(self, func: &T) -> Result<EvaluatedPopulation<TChromosome, T::Out>, T::Err> {
        EvaluatedPopulation::evaluate(
            self.population,
            func
        )
    }

    pub fn iter(&mut self) -> impl Iterator<Item = &TChromosome> {
        self.population.iter()
    }

    pub fn iter_mut(&mut self) -> impl Iterator<Item = &mut TChromosome> {
        self.population.iter_mut()
    }
}

impl<TInput, TResult> EvaluatedChromosome<TInput, TResult> {
    pub fn deconstruct(self) -> (TInput, TResult) {
        (self.chromosome, self.evaluation)
    }
}

impl<TChromosome, TResult> EvaluatedPopulation<TChromosome, TResult> {
    pub fn new() -> Self {
        Self {
            population: vec![]
        }
    }

    pub fn evaluate<T: FitnessFunction<In = TChromosome, Out = TResult>>(chromosomes: Vec<TChromosome>, func: &T) -> Result<Self, T::Err> {
        Ok(EvaluatedPopulation::from_vec(
            chromosomes.into_iter()
                .map(|chromosome|
                     Ok(EvaluatedChromosome {
                         evaluation: func.fit(&chromosome)?,
                         chromosome
                     }))
                .collect::<Result<_, _>>()?))
    }

    pub fn from_vec(vec: Vec<EvaluatedChromosome<TChromosome, TResult>>) -> Self {
        Self {
            population: vec
        }
    }

    pub fn best_candidate(&self, better_than: &impl BetterThanOperator<TResult>) -> &EvaluatedChromosome<TChromosome, TResult> {
        let mut best_so_far = &self.population[0];
        for individual in self.population.iter().skip(1) {
            if better_than.better_than(&individual.evaluation, &best_so_far.evaluation) {
                best_so_far = individual;
            }
        }

        best_so_far
    }

    pub fn add(&mut self, c: EvaluatedChromosome<TChromosome, TResult>) {
        self.population.push(c)
    }

    pub fn deconstruct(self) -> Vec<EvaluatedChromosome<TChromosome, TResult>> {
        self.population
    }

    fn join(&mut self, mut offsprings: EvaluatedPopulation<TChromosome, TResult>) {
        self.population.append(&mut offsprings.population);
    }

    pub fn iter(&mut self) -> impl Iterator<Item = &EvaluatedChromosome<TChromosome, TResult>> {
        self.population.iter()
    }

    pub fn iter_mut(&mut self) -> impl Iterator<Item = &mut EvaluatedChromosome<TChromosome, TResult>> {
        self.population.iter_mut()
    }

}

impl<TChromosome, TResult: Copy> EvaluatedPopulation<TChromosome, TResult> {
    pub fn evaluations_vec(&self) -> Vec<TResult> {
        self.population
            .iter()
            .map(|individual| individual.evaluation)
            .collect()
    }
}

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: Copy + 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,
    evaluation_pool: Vec<f64>
}

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

impl<TInput, TResult: Copy + 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)
    }
}