radiate-core 1.2.22

Core traits and interfaces for the Radiate genetic algorithm library.
Documentation
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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
use super::phenotype::Phenotype;
use crate::objectives::Scored;
use crate::sync::MutCell;
use crate::{Chromosome, Score};
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
use std::fmt::Debug;
use std::ops::{Index, IndexMut, Range};

/// A [Population] is a collection of [Phenotype] instances.
///
/// This struct is the core collection of individuals
/// being evolved by the `GeneticEngine`. It can be thought of as a Vec of `Phenotype`s and
/// is essentially a light wrapper around such a Vec. The [Population] struct, however, has some
/// additional functionality that allows for sorting and iteration over the individuals in the population.
///
/// Note: Although the [Population] offers mut methods to mut the individuals in the population, the [Population]
/// itself offers no way to increase or decrease the number of individuals in the population. As such, the [Population]
/// should be thought of as an 'immutable' data structure. If you need to add or remove individuals from the population,
/// you should create a new [Population] instance with the new individuals. To further facilitate this way of
/// thinking, the [Population] struct and everything it contains implements the `Clone` trait.
///
/// # Type Parameters
/// - `C`: The type of chromosome used in the genotype, which must implement the `Chromosome` trait.
#[derive(Default, PartialEq)]
pub struct Population<C: Chromosome> {
    individuals: Vec<Member<C>>,
}

impl<C: Chromosome> Population<C> {
    pub fn new(individuals: Vec<Phenotype<C>>) -> Self {
        Population {
            individuals: individuals.into_iter().map(Member::from).collect(),
        }
    }

    pub fn empty() -> Self {
        Population {
            individuals: Vec::new(),
        }
    }

    pub fn with_capacity(capacity: usize) -> Self {
        Population {
            individuals: Vec::with_capacity(capacity),
        }
    }

    pub fn get(&self, index: usize) -> Option<&Phenotype<C>> {
        self.individuals.get(index).map(|cell| cell.borrow())
    }

    pub fn get_mut(&mut self, index: usize) -> Option<&mut Phenotype<C>> {
        self.individuals
            .get_mut(index)
            .map(|cell| cell.borrow_mut())
    }

    pub fn ref_clone_member(&self, index: usize) -> Option<Member<C>>
    where
        C: Clone,
    {
        self.individuals.get(index).map(|cell| cell.clone())
    }

    pub fn push(&mut self, individual: impl Into<Member<C>>) {
        self.individuals.push(individual.into());
    }

    pub fn iter(&self) -> impl Iterator<Item = &Phenotype<C>> {
        self.individuals.iter().map(Member::borrow)
    }

    pub fn iter_mut(&mut self) -> impl Iterator<Item = &mut Phenotype<C>> {
        self.individuals.iter_mut().map(Member::borrow_mut)
    }

    pub fn len(&self) -> usize {
        self.individuals.len()
    }

    pub fn clear(&mut self) {
        self.individuals.clear();
    }

    pub fn is_empty(&self) -> bool {
        self.individuals.is_empty()
    }

    pub fn get_scores(&self) -> impl Iterator<Item = &Score> {
        self.individuals
            .iter()
            .filter_map(|individual| individual.borrow().score())
    }

    pub fn extend(&mut self, other: Self) {
        self.individuals.extend(other.individuals);
    }

    pub fn shared_count(&self) -> usize {
        self.individuals
            .iter()
            .filter(|individual| !individual.is_unique())
            .count()
    }

    pub fn get_pair_mut(
        &mut self,
        first: usize,
        second: usize,
    ) -> Option<(&mut Phenotype<C>, &mut Phenotype<C>)> {
        if first == second {
            None
        } else if first < second {
            let (left, right) = self.individuals.split_at_mut(second);
            Some((left[first].borrow_mut(), right[0].borrow_mut()))
        } else {
            let (left, right) = self.individuals.split_at_mut(first);
            Some((right[0].borrow_mut(), left[second].borrow_mut()))
        }
    }
}

impl<C: Chromosome + Clone> From<&Population<C>> for Population<C> {
    fn from(population: &Population<C>) -> Self {
        population.clone()
    }
}

impl<C: Chromosome> From<Vec<Phenotype<C>>> for Population<C> {
    fn from(individuals: Vec<Phenotype<C>>) -> Self {
        Population {
            individuals: individuals.into_iter().map(Member::from).collect(),
        }
    }
}

impl<C: Chromosome> AsMut<[Member<C>]> for Population<C> {
    fn as_mut(&mut self) -> &mut [Member<C>] {
        self.individuals.as_mut()
    }
}

impl<C: Chromosome> Index<Range<usize>> for Population<C> {
    type Output = [Member<C>];
    fn index(&self, index: Range<usize>) -> &Self::Output {
        &self.individuals[index]
    }
}

impl<C: Chromosome> Index<usize> for Population<C> {
    type Output = Phenotype<C>;

    fn index(&self, index: usize) -> &Self::Output {
        &self.individuals[index].borrow()
    }
}

impl<C: Chromosome> IndexMut<usize> for Population<C> {
    fn index_mut(&mut self, index: usize) -> &mut Self::Output {
        self.individuals[index].borrow_mut()
    }
}

impl<C: Chromosome + Clone> IntoIterator for Population<C> {
    type Item = Phenotype<C>;
    type IntoIter = std::vec::IntoIter<Phenotype<C>>;

    fn into_iter(self) -> Self::IntoIter {
        self.individuals
            .into_iter()
            .map(|cell| cell.into_inner())
            .collect::<Vec<_>>()
            .into_iter()
    }
}

impl<C: Chromosome> FromIterator<Phenotype<C>> for Population<C> {
    fn from_iter<I: IntoIterator<Item = Phenotype<C>>>(iter: I) -> Self {
        Population {
            individuals: iter.into_iter().map(Member::from).collect(),
        }
    }
}

impl<C: Chromosome> FromIterator<Member<C>> for Population<C> {
    fn from_iter<I: IntoIterator<Item = Member<C>>>(iter: I) -> Self {
        let individuals = iter.into_iter().collect::<Vec<Member<C>>>();
        Population { individuals }
    }
}

/// Create a new instance of the Population from the given size and closure.
/// This will iterate the given closure `size` times and collect
/// the results into a Vec of new individuals.
impl<C: Chromosome, F> From<(usize, F)> for Population<C>
where
    F: Fn() -> Phenotype<C>,
{
    fn from((size, f): (usize, F)) -> Self {
        let mut individuals = Vec::with_capacity(size);
        for _ in 0..size {
            individuals.push(f());
        }

        Population {
            individuals: individuals.into_iter().map(Member::from).collect(),
        }
    }
}

impl<C: Chromosome + Clone> Clone for Population<C> {
    fn clone(&self) -> Self {
        self.individuals
            .iter()
            .map(|individual| individual.borrow().clone())
            .collect::<Population<C>>()
    }
}

impl<C: Chromosome + Debug> Debug for Population<C> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Population [\n")?;
        for individual in &self.individuals {
            write!(f, "{:?},\n ", individual.borrow())?;
        }
        write!(f, "]")
    }
}

#[cfg(feature = "serde")]
impl<C: Chromosome + Serialize> Serialize for Population<C> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        let phenotypes: Vec<&Phenotype<C>> = self.individuals.iter().map(Member::borrow).collect();
        phenotypes.serialize(serializer)
    }
}

#[cfg(feature = "serde")]
impl<'de, C: Chromosome + Deserialize<'de>> Deserialize<'de> for Population<C> {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let phenotypes = Vec::<Phenotype<C>>::deserialize(deserializer)?;

        Ok(Population {
            individuals: phenotypes.into_iter().map(Member::from).collect(),
        })
    }
}

#[derive(Clone, PartialEq)]
pub struct Member<C: Chromosome> {
    cell: MutCell<Phenotype<C>>,
}

impl<C: Chromosome> Member<C> {
    pub fn borrow(&self) -> &Phenotype<C> {
        self.cell.borrow()
    }

    pub fn borrow_mut(&mut self) -> &mut Phenotype<C> {
        self.cell.borrow_mut()
    }

    pub fn into_inner(self) -> Phenotype<C>
    where
        C: Clone,
    {
        self.cell.into_inner()
    }

    pub fn is_unique(&self) -> bool {
        self.cell.is_unique()
    }

    pub fn ref_count(&self) -> usize {
        self.cell.strong_count()
    }
}

impl<C: Chromosome + Debug> Debug for Member<C> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{:?}", self.borrow())
    }
}

impl<C: Chromosome + PartialEq> PartialOrd for Member<C> {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        self.borrow().partial_cmp(other.borrow())
    }
}

impl<C: Chromosome> From<Phenotype<C>> for Member<C> {
    fn from(p: Phenotype<C>) -> Self {
        Member {
            cell: MutCell::from(p),
        }
    }
}

impl<C: Chromosome> Scored for Member<C> {
    fn score(&self) -> Option<&Score> {
        self.borrow().score()
    }
}

unsafe impl<C: Chromosome> Send for Member<C> {}
unsafe impl<C: Chromosome> Sync for Member<C> {}

#[cfg(test)]
mod test {
    use super::*;
    use crate::{CharChromosome, FloatChromosome, Score, objectives::Optimize};

    #[test]
    fn test_new() {
        let population = Population::<CharChromosome>::default();
        assert_eq!(population.len(), 0);
    }

    #[test]
    fn test_from_vec() {
        let individuals = vec![
            Phenotype::from((vec![CharChromosome::from("hello")], 0)),
            Phenotype::from((vec![CharChromosome::from("world")], 0)),
        ];

        let population = Population::new(individuals.clone());
        assert_eq!(population.len(), individuals.len());
    }

    #[test]
    fn test_from_fn() {
        let population = Population::from((10, || {
            Phenotype::from((vec![CharChromosome::from("hello")], 0))
        }));

        assert_eq!(population.len(), 10);

        for individual in population.iter() {
            assert_eq!(individual.genotype().len(), 1);
            assert_eq!(individual.genotype().iter().next().unwrap().len(), 5);
        }
    }

    #[test]
    fn test_is_empty() {
        let population = Population::<CharChromosome>::default();
        assert!(population.is_empty());
    }

    #[test]
    fn test_sort_by() {
        let mut population = Population::from((10, || {
            Phenotype::from((vec![FloatChromosome::from((10, -10.0..10.0))], 0))
        }));

        for i in 0..population.len() {
            population[i].set_score(Some(Score::from(i)));
        }

        // deep clone population
        let mut minimize_population = population.clone();
        let mut maximize_population = population.clone();

        Optimize::Minimize.sort(&mut minimize_population);
        Optimize::Maximize.sort(&mut maximize_population);

        for i in 0..population.len() {
            assert_eq!(minimize_population[i].score().unwrap().as_usize(), i);
            assert_eq!(
                maximize_population[i].score().unwrap().as_usize(),
                population.len() - i - 1
            );
        }
    }

    #[test]
    fn test_population_get() {
        let population = Population::new(vec![
            Phenotype::from((vec![CharChromosome::from("hello")], 0)),
            Phenotype::from((vec![CharChromosome::from("world")], 0)),
        ]);

        assert_eq!(population.get(0).unwrap().genotype().len(), 1);
        assert_eq!(population.get(1).unwrap().genotype().len(), 1);
        assert_eq!(population.get(0).unwrap().genotype()[0].len(), 5);
        assert_eq!(population.get(1).unwrap().genotype()[0].len(), 5);
    }

    #[test]
    fn test_population_get_mut() {
        let mut population = Population::new(vec![
            Phenotype::from((vec![CharChromosome::from("hello")], 0)),
            Phenotype::from((vec![CharChromosome::from("world")], 0)),
        ]);

        if let Some(individual) = population.get_mut(0) {
            individual.set_score(Some(Score::from(1.0)));
        }

        if let Some(individual) = population.get_mut(1) {
            individual.set_score(Some(Score::from(2.0)));
        }

        assert_eq!(population.get(0).unwrap().score().unwrap().as_f32(), 1.0);
        assert_eq!(population.get(1).unwrap().score().unwrap().as_f32(), 2.0);
    }

    #[test]
    #[cfg(feature = "serde")]
    fn test_population_can_serialize() {
        let individuals = vec![
            Phenotype::from((vec![CharChromosome::from("hello")], 0)),
            Phenotype::from((vec![CharChromosome::from("world")], 0)),
        ];
        let population = Population::new(individuals.clone());

        let serialized =
            serde_json::to_string(&population).expect("Failed to serialize Population");
        let deserialized: Population<CharChromosome> =
            serde_json::from_str(&serialized).expect("Failed to deserialize Population");

        assert_eq!(population, deserialized);
    }
}