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
// [[file:../spdkit.note::*imports][imports:1]]
use std::iter::FromIterator;

use crate::common::*;
use crate::encoding::*;
use crate::fitness::*;
use crate::gears::*;
use crate::individual::*;
use crate::operators::*;
use crate::population::*;
use crate::random::*;
use crate::termination::*;
// imports:1 ends here

// [[file:../spdkit.note::109fedb5][109fedb5]]
use std::marker::PhantomData;

pub trait Evolve<G, F, C>
where
    G: Genome,
    F: EvaluateFitness<G>,
    C: EvaluateObjectiveValue<G>,
{
    // Define how to evolve to next generation.
    fn next_generation(
        &mut self,
        cur_population: &Population<G>,
        valuer: &mut Valuer<G, F, C>,
    ) -> Population<G>;
}
// 109fedb5 ends here

// [[file:../spdkit.note::*core][core:1]]
pub struct EvolutionAlgorithm<G, B, S>
where
    G: Genome,
    B: Breed<G>,
    S: Survive<G>,
{
    breeder: B,
    survivor: S,
    _g: PhantomData<G>,
}

impl<G, B, S> EvolutionAlgorithm<G, B, S>
where
    G: Genome,
    B: Breed<G>,
    S: Survive<G>,
{
    pub fn new(breeder: B, survivor: S) -> Self {
        Self {
            breeder,
            survivor,
            _g: PhantomData,
        }
    }
}

impl<G, C, B, S, F> Evolve<G, F, C> for EvolutionAlgorithm<G, B, S>
where
    G: Genome,
    C: EvaluateObjectiveValue<G>,
    B: Breed<G>,
    S: Survive<G>,
    F: EvaluateFitness<G>,
{
    fn next_generation(
        &mut self,
        cur_population: &Population<G>,
        valuer: &mut Valuer<G, F, C>,
    ) -> Population<G> {
        let mut rng = get_rng!();
        evolve_one_step(
            cur_population,
            &mut self.breeder,
            &mut self.survivor,
            valuer,
            &mut *rng,
        )
    }
}

fn evolve_one_step<G, C, B, S, F, R>(
    cur_population: &Population<G>,
    breeder: &mut B,
    survivor: &mut S,
    valuer: &mut Valuer<G, F, C>,
    rng: &mut R,
) -> Population<G>
where
    G: Genome,
    C: EvaluateObjectiveValue<G>,
    B: Breed<G>,
    S: Survive<G>,
    F: EvaluateFitness<G>,
    R: Rng + Sized,
{
    // 1. create new individuals from parent population.
    // 1.1 breed new genomes
    let new_genomes = breeder.breed(cur_population.size_limit(), cur_population, rng);
    // 1.2 create new individuals from genomes.
    let mut new_indvs = valuer.create_individuals(new_genomes);
    println!("bred {} new individuals", new_indvs.len());

    // 2. create new population by supplanting bad performing individuals
    // 2.1 combine all available individuals into one.
    let old_indvs = cur_population.individuals();
    new_indvs.extend_from_slice(old_indvs);

    // 2.2 create a new population from combined new individuals
    let nlimit = cur_population.size_limit();
    let tmp_population = valuer.build_population(new_indvs).with_size_limit(nlimit);
    let m = tmp_population.size();

    // 2.3 remove low quality individuals
    let survived_indvs = survivor.survive(tmp_population, rng);
    let n = m - survived_indvs.len();
    println!("removed {} bad individuals.", n);
    let mut new_population = valuer
        .build_population(survived_indvs)
        .with_size_limit(nlimit);

    new_population.to_owned()
}
// core:1 ends here

// [[file:../spdkit.note::*pub][pub:1]]
/// Evolution engine.
pub struct Engine<G, E, F, C>
where
    G: Genome,
    E: Evolve<G, F, C>,
    F: EvaluateFitness<G>,
    C: EvaluateObjectiveValue<G>,
{
    nlast: usize,

    algo: Option<E>,
    valuer: Option<Valuer<G, F, C>>,
    population: Option<Population<G>>,
}

impl<G, E, F, C> Engine<G, E, F, C>
where
    G: Genome,
    E: Evolve<G, F, C>,
    F: EvaluateFitness<G>,
    C: EvaluateObjectiveValue<G>,
{
    pub fn create() -> Self {
        Self {
            nlast: 30,

            algo: None,
            valuer: None,
            population: None,
        }
    }

    /// Set core algorithm for evolution
    pub fn algorithm(mut self, algo: E) -> Self {
        self.algo = Some(algo);
        self
    }

    /// The last n generations for termination criterion.
    pub fn termination_nlast(mut self, n: usize) -> Self {
        self.set_termination_nlast(n);
        self
    }

    /// The last n generations for termination criterion.
    pub fn set_termination_nlast(&mut self, n: usize) {
        assert!(n > 1, "invalid nlast value");
        self.nlast = n;
    }

    /// Set Valuer for evolution.
    pub fn valuer(mut self, valuer: Valuer<G, F, C>) -> Self {
        self.valuer = Some(valuer);
        self
    }

    /// Evolves one step forward from seeds.
    ///
    /// # Parameters
    ///
    /// * seeds: genomes as initial seeds for evolution. The length of seeds
    /// will be set as the internal population size limit.
    ///
    /// # Returns
    ///
    /// * return an iterator over `Generation`.
    ///
    pub fn evolve<'a>(
        &'a mut self,
        seeds: &[G],
    ) -> impl Iterator<Item = Result<Generation<G>>> + 'a {
        let mut termination = RunningMean::new(self.nlast);
        let mut valuer = self.valuer.take().expect("no valuer");
        let mut algo = self.algo.take().expect("no algo");

        // create individuals, build population.
        let indvs = valuer.create_individuals(seeds.to_vec());
        let nlimit = seeds.len();
        let mut population = valuer.build_population(indvs).with_size_limit(nlimit);

        // enter main loop
        let mut ig = 0;
        std::iter::from_fn(move || {
            if ig == 0 {
                println!("initial population:");
                for m in population.members() {
                    // println!("{}", m);
                }
            } else {
                let new_population = algo.next_generation(&population, &mut valuer);

                population = new_population;
            }

            let g = Generation {
                index: ig,
                population: population.clone(),
            };
            ig += 1;

            // avoid infinite loop using a reliable termination criterion.
            if termination.meets(&g) {
                error!("Terminated for stagnation!");
                error!(
                    "Simulation has evolved for {} generations without changes.",
                    self.nlast
                );

                None
            } else {
                Some(Ok(g))
            }
        })
    }
}
// pub:1 ends here

// [[file:../spdkit.note::*test][test:1]]
#[cfg(test)]
mod test {
    use super::*;
    use crate::common::*;
    use crate::fitness;
    use crate::gears::*;
    use crate::operators::selection::RouletteWheelSelection;
    use crate::operators::variation::OnePointCrossOver;

    #[test]
    fn test_engine() -> Result<()> {
        // create a valuer gear
        let valuer = Valuer::new()
            .with_fitness(fitness::Maximize)
            .with_creator(OneMax);

        // create a survivor gear
        let survivor = Survivor::default();

        // create a breeder gear
        let breeder = crate::gears::GeneticBreeder::new()
            .with_crossover(OnePointCrossOver)
            .with_selector(RouletteWheelSelection::new(2));

        // setup the algorithm
        let algo = EvolutionAlgorithm::new(breeder, survivor);

        let seeds = build_initial_genomes(10);
        for g in Engine::create()
            .valuer(valuer)
            .algorithm(algo)
            .evolve(&seeds)
            .take(10)
        {
            let generation = g?;
            generation.summary();
        }

        Ok(())
    }

    // test only
    fn build_initial_genomes(n: usize) -> Vec<Binary> {
        // generate `n` binary genomes in size of 10.
        (0..n).map(|_| random_binary(11)).collect()
    }

    fn random_binary(length: usize) -> Binary {
        let mut rng = get_rng!();
        let list: Vec<_> = (0..length).map(|_| rng.gen()).collect();
        Binary::new(list)
    }
}
// test:1 ends here