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
use crate::FitnessEvaluator;
/// Parameters of a simulation.
pub struct Parameters<T: FitnessEvaluator> {
/// Size of the population for every generation. (default = 100)
///
/// Increasing this value might improve results (because of a larger gene pool), but will
/// *drastically* increase time to convergence.
pub population_size: usize,
/// The length of the genetic code for all cells (default = 10)
///
/// This value will most likely need to be changed in accordance with the problem you're trying to solve.
pub genetic_code_length: usize,
pub keep_threshold: f64,
pub mutation_chance_percent: f64,
/// How many generations between result samples (default = 1000)
///
/// Since observing results are expensive (a result contains a _copy_ of the genetic code of the current best cell),
/// this parameter allows fine-grained control on exactly when
/// progress is observed. Lower values will decrease performance but increase observability, and vice-versa.
pub emit_result_every: usize,
/// The fitness evaluator to use for this simulation.
pub fitness_evaluator: T,
}
impl<T> Parameters<T>
where
T: FitnessEvaluator,
{
pub fn new(evaluator: T) -> Parameters<T> {
Parameters {
population_size: 100,
genetic_code_length: 10,
keep_threshold: 0.5,
mutation_chance_percent: 0.01,
emit_result_every: 1000,
fitness_evaluator: evaluator,
}
}
pub fn with_population_size(mut self, population_size: usize) -> Self {
self.population_size = population_size;
self
}
pub fn with_genetic_code_length(mut self, length: usize) -> Self {
self.genetic_code_length = length;
self
}
pub fn with_keep_threshold(mut self, threshold: f64) -> Self {
self.keep_threshold = threshold;
self
}
pub fn with_mutation_chance_percent(mut self, mutation_chance: f64) -> Self {
self.mutation_chance_percent = mutation_chance;
self
}
}
#[cfg(test)]
mod tests {
use super::{FitnessEvaluator, Parameters};
struct MockEvaluator;
impl FitnessEvaluator for MockEvaluator {
fn evaluate(&self, _code: &Vec<u8>) -> f64 {
0.0
}
}
#[test]
fn parameters_init() {
let params = Parameters::new(MockEvaluator {});
assert_eq!(params.genetic_code_length, 10);
assert_eq!(params.population_size, 100);
assert_eq!(params.keep_threshold, 0.5);
assert_eq!(params.mutation_chance_percent, 0.01);
assert_eq!(params.emit_result_every, 1000);
}
}