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
/*
* Copyright (c) Kia Shakiba
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use crateFitnessOrd;
pub use crateGene;
/// This defines a chromosome (i.e., a set of genes). With this,
/// genes can be added and retrieved. The overall fitness of the
/// chromosome can also be computed.
///
/// # Examples
/// ```
/// use kwik::genetic::{
/// Gene,
/// Chromosome,
/// Fitness,
/// FitnessOrd,
/// Rng,
/// };
///
/// #[derive(Clone)]
/// struct MyData {
/// data: u32,
/// }
///
/// #[derive(Clone)]
/// struct MyConfig {
/// config: Vec<MyData>,
/// }
///
/// impl Chromosome for MyConfig {
/// type Gene = MyData;
///
/// fn base(&self) -> Self {
/// MyConfig {
/// config: Vec::new(),
/// }
/// }
///
/// fn is_empty(&self) -> bool {
/// self.config.is_empty()
/// }
///
/// fn len(&self) -> usize {
/// self.config.len()
/// }
///
/// fn push(&mut self, data: MyData) {
/// self.config.push(data);
/// }
///
/// fn get(&self, index: usize) -> &MyData {
/// &self.config[index]
/// }
///
/// fn clear(&mut self) {
/// self.config.clear();
/// }
///
/// fn is_valid(&self) -> bool {
/// true
/// }
///
/// fn is_optimal(&self) -> bool {
/// self.sum() == 100
/// }
/// }
///
/// impl MyConfig {
/// fn sum(&self) -> u32 {
/// self.config
/// .iter()
/// .map(|item| item.data)
/// .sum::<u32>()
/// }
/// }
///
/// impl FitnessOrd for MyConfig {
/// fn fitness_cmp(&self, other: &Self) -> Fitness {
/// let self_diff = (100 - self.sum() as i32).abs();
/// let other_diff = (100 - other.sum() as i32).abs();
///
/// if self_diff < other_diff {
/// return Fitness::Stronger;
/// }
///
/// if self_diff > other_diff {
/// return Fitness::Weaker;
/// }
///
/// Fitness::Equal
/// }
/// }
///
/// impl Gene for MyData {
/// fn mutate(&mut self, rng: &mut impl Rng, _genes: &[Option<Self>]) {
/// self.data = rng.gen_range(0..10);
/// }
/// }
/// ```