radiate_engines/builder/
selectors.rs

1use crate::GeneticEngineBuilder;
2use radiate_core::{Chromosome, Select};
3use std::sync::Arc;
4
5#[derive(Clone)]
6pub struct SelectionParams<C: Chromosome> {
7    pub offspring_fraction: f32,
8    pub survivor_selector: Arc<dyn Select<C>>,
9    pub offspring_selector: Arc<dyn Select<C>>,
10}
11
12impl<C, T> GeneticEngineBuilder<C, T>
13where
14    C: Chromosome + PartialEq + Clone,
15    T: Clone + Send,
16{
17    /// Set the fraction of the population that will be replaced by offspring each generation.
18    /// Default is 0.8. This is a value from 0...=1 that represents the fraction of
19    /// population that will be replaced by offspring each generation. The remainder will 'survive' to the next generation.
20    pub fn offspring_fraction(mut self, offspring_fraction: f32) -> Self {
21        self.add_error_if(
22            || !(0.0..=1.0).contains(&offspring_fraction),
23            "offspring_fraction must be between 0.0 and 1.0",
24        );
25
26        self.params.selection_params.offspring_fraction = offspring_fraction;
27        self
28    }
29
30    pub fn boxed_survivor_selector(mut self, selector: Box<dyn Select<C>>) -> Self {
31        self.params.selection_params.survivor_selector = selector.into();
32        self
33    }
34
35    pub fn boxed_offspring_selector(mut self, selector: Box<dyn Select<C>>) -> Self {
36        self.params.selection_params.offspring_selector = selector.into();
37        self
38    }
39
40    /// Set the survivor selector of the genetic engine. This is the selector that will
41    /// be used to select the survivors of the population. Default is `TournamentSelector`
42    /// with a group size of 3.
43    pub fn survivor_selector<S: Select<C> + 'static>(mut self, selector: S) -> Self {
44        self.params.selection_params.survivor_selector = Arc::new(selector);
45        self
46    }
47
48    /// Set the offspring selector of the genetic engine. This is the selector that will
49    /// be used to select the offspring of the population. Default is `RouletteSelector`.
50    pub fn offspring_selector<S: Select<C> + 'static>(mut self, selector: S) -> Self {
51        self.params.selection_params.offspring_selector = Arc::new(selector);
52        self
53    }
54}