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
#![warn(missing_docs)]
#![warn(missing_doc_code_examples)]
use rand::Rng;
use rand::seq::SliceRandom;
pub mod functions;
pub struct Settings {
pub population_size: u32,
pub number_of_generations: u32,
pub crossover_probability: f64,
pub mutation_probability: f64,
pub verbose: bool,
pub elitism: bool,
pub elitism_fraction: f64,
pub maximize_fitness: bool,
pub number_of_dimensions: u32,
pub upper_bound: Vec<f64>,
pub lower_bound: Vec<f64>,
pub fitness_function: Box<dyn FnMut(Vec<f64>) -> f64>,
}
impl Default for Settings {
fn default() -> Self {
Self {
fitness_function: Box::new(crate::functions::summation),
population_size: 100,
number_of_generations: 100,
crossover_probability: 0.8,
mutation_probability: 0.1,
verbose: true,
elitism: true,
elitism_fraction: 0.2,
maximize_fitness: true,
number_of_dimensions: 2,
upper_bound: vec![ 1.0, 1.0],
lower_bound: vec![-1.0, -1.0],
}
}
}
impl Settings {
pub fn set_fitness_function<F: 'static + FnMut(Vec<f64>) -> f64>(&mut self, f: F) {
self.fitness_function = Box::new(f);
}
}
pub struct Optimizer {
settings: Settings,
current_population: Population,
new_population: Population,
best_fitness: f64,
best_representation: Vec<f64>
}
impl Optimizer {
pub fn new(mut settings: Settings) -> Self {
Self {
current_population: Population::new(&mut settings),
new_population: Population::empty(),
settings: settings,
best_fitness: -f64::INFINITY,
best_representation: vec![]
}
}
pub fn solve(&mut self) {
for _ in 0..self.settings.number_of_generations {
self.iterate();
}
}
pub fn report(&self) {
println!("{}", self.best_fitness);
}
fn check_bounds(&self, x: Individual) -> bool {
let mut state = true;
for i in 0..self.settings.number_of_dimensions as usize{
if x.representation[i] < self.settings.lower_bound[i] ||
x.representation[i] > self.settings.upper_bound[i] {
state = false;
}
}
state
}
fn iterate(&mut self) {
self.implement_elitism();
self.implement_crossover();
self.implement_mutation();
self.fill_population();
self.current_population = self.new_population.copy();
if self.current_population.get_best() > self.best_fitness {
self.best_fitness = self.current_population.get_best();
}
self.current_population.sort();
self.new_population = Population::empty();
self.report();
}
fn implement_elitism(&mut self) {
if self.settings.elitism {
let number_of_elites: f64 = self.settings.elitism_fraction * self.settings.population_size as f64;
for i in (self.settings.population_size as usize - number_of_elites as usize)..self.settings.population_size as usize{
self.new_population.individuals.push(self.current_population.individuals[i].clone())
}
}
}
fn implement_crossover(&mut self) {
let number_of_crosses: f64 = self.settings.crossover_probability * self.settings.population_size as f64;
for i in (self.settings.population_size as usize - number_of_crosses as usize)..self.settings.population_size as usize{
let thingone = self.current_population.get_random();
let thingtwo = self.current_population.get_random();
self.new_population.individuals.push(thingone.cross(thingtwo))
}
}
fn implement_mutation(&mut self) {
for i in 0..self.settings.population_size as usize {
let mut rng = rand::thread_rng();
if rng.gen::<f64>() < self.settings.mutation_probability {
self.new_population.individuals.push(self.current_population.individuals[i].mutate())
}
}
}
fn fill_population(&mut self) {
while self.new_population.individuals.len() < self.settings.population_size as usize {
self.new_population.individuals.push(Individual::new(&mut self.settings));
}
}
}
struct Population {
individuals: Vec<Individual>,
}
impl Population {
fn new(mut settings: &mut Settings) -> Self {
let mut pop = vec![];
for _ in 0..settings.population_size {
pop.push(Individual::new(&mut settings))
}
Self {
individuals: pop,
}
}
fn empty() -> Self {
Self {
individuals: vec![],
}
}
fn copy(&self) -> Self {
let mut pop = Population::empty();
for indi in &self.individuals {
pop.individuals.push((*indi).clone());
}
pop
}
fn get_best(&self) -> f64 {
let mut best_fitness = -f64::INFINITY;
for i in 0..(*self).individuals.len() {
if self.individuals[i].fitness > best_fitness {
best_fitness = self.individuals[i].fitness;
}
}
best_fitness
}
fn get_mean(&self) {
}
fn get_std(&self) {
}
fn get_random(&mut self) -> Individual {
let option = self.individuals.choose_mut(&mut rand::thread_rng());
match option {
Some(x) => (*x).clone(),
None => self.individuals[self.individuals.len()-1].clone()
}
}
fn sort(&mut self) {
self.individuals.sort_unstable_by(|x, y| x.fitness.partial_cmp(&y.fitness).unwrap());
}
}
#[cfg(test)]
mod population_tests {
use super::*;
#[test]
fn basic_inst() {
let x = Population::new(&mut Settings::default());
}
#[test]
fn empty_inst() {
let x = Population::empty();
}
#[test]
fn sort_check() {
let mut x = Population::new(&mut Settings::default());
x.sort();
}
#[test]
fn stat_check() {
let x = Population::new(&mut Settings::default());
x.get_best();
x.get_mean();
x.get_std();
}
}
pub struct Individual {
representation: Vec<f64>,
fitness: f64,
}
impl Individual {
fn new(sets: &mut crate::Settings) -> Self {
let mut rng = rand::thread_rng();
let mut v: Vec<f64> = vec![];
for i in 0..sets.number_of_dimensions as usize {
v.push(rng.gen_range(sets.lower_bound[i], sets.upper_bound[i]));
}
Self {
representation: v.clone(),
fitness: (sets.fitness_function)(v.clone())
}
}
fn clone(&self) -> Self {
Self {
representation: self.representation.clone(),
fitness: self.fitness,
}
}
fn mutate(&self) -> Self {
self.clone()
}
fn cross(&self, other_individual: Self) -> Self {
let mut v = vec![];
let mut rng = rand::thread_rng();
for i in 0..self.representation.len() {
if rng.gen::<f64>() < 0.5 {
v.push(self.representation[i])
} else {
v.push(other_individual.representation[i])
}
}
Self {
representation: v,
fitness: 0.0
}
}
}
#[cfg(test)]
mod individual_tests {
use super::*;
#[test]
fn basic_inst() {
let x = Individual {
representation: vec![0.0, 0.0],
fitness: 0.0
};
}
#[test]
fn settings_inst() {
let x = Individual::new(&mut crate::Settings::default());
}
#[test]
fn clone_check() {
let x = Individual::new(&mut crate::Settings::default());
let y = x.clone();
}
#[test]
fn mutate_check() {
let x = Individual::new(&mut crate::Settings::default());
let y = x.mutate();
}
}