kwik 1.19.2

A set of useful tools I use for my Ph.D. research.
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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
/*
 * 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.
 */

mod chromosome;
mod error;
mod fitness;
mod gene;
mod individual;
mod limit;
mod offspring;
mod solution;

use std::time::Instant;

use num_traits::AsPrimitive;
pub use rand::Rng;
use rand::{
	SeedableRng,
	distr::{Distribution, Uniform},
	rngs::SmallRng,
	seq::SliceRandom,
};
use rayon::prelude::*;

pub use crate::genetic::{
	chromosome::Chromosome,
	error::GeneticError,
	fitness::{Fitness, FitnessOrd},
	gene::Gene,
	individual::Individual,
	limit::GeneticLimit,
	offspring::Offspring,
	solution::GeneticSolution,
};

const DEFAULT_POPULATION_SIZE: usize = 100;
const DEFAULT_TOURNAMENT_SIZE: usize = 3;

/// Finds the optimal values for a set of inputs using a genetic algorithm.
///
/// # Examples
/// ```
/// use kwik::genetic::{
///     Genetic,
///     Gene,
///     Chromosome,
///     Fitness,
///     FitnessOrd,
///     Rng,
/// };
///
/// #[derive(Clone)]
/// struct MyData {
///     data: u32,
/// }
///
/// #[derive(Default, Clone)]
/// struct MyConfig {
///     config: Vec<MyData>,
/// }
///
/// let mut initial_chromosome = MyConfig::default();
///
/// initial_chromosome.push(MyData { data: 0 });
/// initial_chromosome.push(MyData { data: 0 });
/// initial_chromosome.push(MyData { data: 0 });
/// initial_chromosome.push(MyData { data: 0 });
/// initial_chromosome.push(MyData { data: 0 });
///
/// let mut genetic = Genetic::<MyConfig>::new(initial_chromosome).unwrap();
/// let result = genetic.run();
///
/// 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..50);
///     }
/// }
/// ```
pub struct Genetic<C>
where
	C: Chromosome + Send + Sync,
{
	initial_chromosome: C,
	population:         Vec<Individual<C>>,

	population_size:      usize,
	maybe_limit:          Option<GeneticLimit>,
	mutation_probability: f64,
	tournament_size:      usize,

	mating_dist: Uniform<usize>,
}

impl<C> Genetic<C>
where
	C: Chromosome + Send + Sync,
{
	/// Creates an instance of the genetic runner using the supplied
	/// chromosome as the initial value.
	pub fn new(initial_chromosome: C) -> Result<Self, GeneticError> {
		if initial_chromosome.is_empty() {
			return Err(GeneticError::EmptyInitialChromosome);
		}

		if !initial_chromosome.is_valid() {
			return Err(GeneticError::InvalidInitialChromosome);
		}

		let mutation_probability = 1.0 / initial_chromosome.len() as f64;

		let genetic = Genetic {
			initial_chromosome,
			population: vec![],

			population_size: DEFAULT_POPULATION_SIZE,
			maybe_limit: None,
			mutation_probability,
			tournament_size: DEFAULT_TOURNAMENT_SIZE,

			mating_dist: init_mating_dist(DEFAULT_POPULATION_SIZE)?,
		};

		Ok(genetic)
	}

	/// Sets the population size and fills the population with individuals.
	///
	/// # Errors
	///
	/// This function returns an error if the population size is zero.
	#[inline]
	pub fn set_population_size(
		&mut self,
		population_size: impl AsPrimitive<usize>,
	) -> Result<(), GeneticError> {
		let population_size = population_size.as_();

		if population_size == 0 {
			return Err(GeneticError::InvalidPopulationSize);
		}

		self.population_size = population_size;
		self.mating_dist = init_mating_dist(population_size)?;

		Ok(())
	}

	/// Sets the population size and fills the population with individuals.
	///
	/// # Errors
	///
	/// This function returns an error if the population size is zero.
	#[inline]
	pub fn with_population_size(
		mut self,
		population_size: impl AsPrimitive<usize>,
	) -> Result<Self, GeneticError> {
		self.set_population_size(population_size)?;
		Ok(self)
	}

	/// Sets the genetic limit.
	#[inline]
	pub fn set_limit(&mut self, limit: GeneticLimit) {
		self.maybe_limit = Some(limit);
	}

	/// Sets the genetic limit.
	#[inline]
	#[must_use]
	pub fn with_limit(mut self, limit: GeneticLimit) -> Self {
		self.set_limit(limit);
		self
	}

	/// Sets the mutation probability.
	#[inline]
	pub fn set_mutation_probability(&mut self, mutation_probability: impl AsPrimitive<f64>) {
		self.mutation_probability = mutation_probability.as_();
	}

	/// Sets the mutation probability.
	#[inline]
	#[must_use]
	pub fn with_mutation_probability(
		mut self,
		mutation_probability: impl AsPrimitive<f64>,
	) -> Self {
		self.set_mutation_probability(mutation_probability);
		self
	}

	/// Sets the tournament size.
	#[inline]
	pub fn set_tournament_size(&mut self, tournament_size: impl AsPrimitive<usize>) {
		self.tournament_size = tournament_size.as_();
	}

	/// Sets the tournament size.
	#[inline]
	#[must_use]
	pub fn with_tournament_size(mut self, tournament_size: impl AsPrimitive<usize>) -> Self {
		self.set_tournament_size(tournament_size);
		self
	}

	/// Runs the genetic algorithm until either the most fit individual has a
	/// fitness of 0 or the population has converged and is no longer changing.
	pub fn run(&mut self) -> Result<GeneticSolution<C>, GeneticError> {
		init_population(
			&mut self.population,
			self.population_size,
			&self.initial_chromosome,
			self.maybe_limit.as_ref(),
		)?;

		let time = Instant::now();

		let mut total_mutations = self.iterate()?;

		let mut generation_count: u64 = 1;
		let mut convergence_count: u64 = 0;
		let mut last_fittest = self.population[0].clone();

		while !last_fittest.is_optimal() {
			if let Some(limit) = &self.maybe_limit {
				match limit {
					GeneticLimit::Runtime(max_runtime) if time.elapsed().ge(max_runtime) => {
						break;
					},

					GeneticLimit::Generations(max_generations)
						if generation_count >= *max_generations =>
					{
						break;
					},

					GeneticLimit::Convergence(max_convergence)
						if convergence_count >= *max_convergence =>
					{
						break;
					},

					_ => {},
				}
			}

			total_mutations += self.iterate()?;

			let fittest = &self.population[0];

			if fittest.eq(&last_fittest) {
				convergence_count += 1;
			} else {
				last_fittest = fittest.clone();
				convergence_count = 0;
			}

			generation_count += 1;
		}

		let solution = GeneticSolution::new(
			self.population[0].chromosome().clone(),
			generation_count,
			total_mutations,
			time.elapsed(),
		);

		Ok(solution)
	}

	/// Performs one iteration of the genetic algorithm, creating a new
	/// generation and overwriting the current population. Returns the total
	/// number of mutations that occurred during the creation of the new
	/// generation.
	fn iterate(&mut self) -> Result<u64, GeneticError> {
		let population_size = self.population.len();

		let maybe_max_runtime = self
			.maybe_limit
			.as_ref()
			.and_then(|limit| match limit {
				GeneticLimit::Runtime(max_runtime) => Some(max_runtime),
				_ => None,
			});

		let new_offpring = (0..population_size)
			.into_par_iter()
			.map(|_| {
				let mut rng = SmallRng::from_rng(&mut rand::rng());
				let (parent1, parent2) = self.gen_mating_pair(&mut rng);

				parent1.mate(
					&mut rng,
					parent2,
					self.mutation_probability,
					maybe_max_runtime,
				)
			})
			.collect::<Result<Vec<Offspring<C>>, GeneticError>>()?;

		let mut new_generation = Vec::<Individual<C>>::new();
		let mut total_mutations = 0u64;

		for offspring in new_offpring {
			total_mutations += offspring.mutations();
			new_generation.push(offspring.into_individual());
		}

		new_generation.sort_unstable();
		self.population = new_generation;

		Ok(total_mutations)
	}

	/// Selects two individuals to mate
	fn gen_mating_pair(&self, rng: &mut impl Rng) -> (&Individual<C>, &Individual<C>) {
		let index1 = self.gen_tournament_parent(rng);
		let mut index2 = self.gen_tournament_parent(rng);

		while index1 == index2 {
			index2 = self.gen_tournament_parent(rng);
		}

		(&self.population[index1], &self.population[index2])
	}

	fn gen_tournament_parent(&self, rng: &mut impl Rng) -> usize {
		self.mating_dist
			.sample_iter(rng)
			.take(self.tournament_size)
			.min()
			.unwrap_or(0)
	}
}

fn init_population<C>(
	population: &mut Vec<Individual<C>>,
	population_size: usize,
	initial_chromosome: &C,
	maybe_limit: Option<&GeneticLimit>,
) -> Result<(), GeneticError>
where
	C: Chromosome + Send + Sync,
{
	population.clear();
	population.push(initial_chromosome.clone().into());

	let mutated_population = (0..(population_size - 1))
		.into_par_iter()
		.map(|_| {
			let chromosome = init_mutated_chromosome(initial_chromosome, maybe_limit)?;

			Ok(chromosome.into())
		})
		.collect::<Result<Vec<Individual<C>>, GeneticError>>()?;

	population.extend(mutated_population);

	Ok(())
}

fn init_mutated_chromosome<C>(
	chromosome: &C,
	maybe_limit: Option<&GeneticLimit>,
) -> Result<C, GeneticError>
where
	C: Chromosome,
{
	let time = Instant::now();

	let mut rng = SmallRng::from_rng(&mut rand::rng());
	let mut mutated_genes = vec![None; chromosome.len()];

	loop {
		let mut gene_indexes = (0..chromosome.len()).collect::<Vec<_>>();
		gene_indexes.shuffle(&mut rng);

		for index in gene_indexes {
			let mut gene = chromosome.get(index).clone();

			gene.mutate(&mut rng, &mutated_genes);
			mutated_genes[index] = Some(gene);
		}

		let mut mutated_chromosome = chromosome.base();

		for gene in mutated_genes.iter_mut() {
			let gene = gene.take().ok_or(GeneticError::Internal)?;

			mutated_chromosome.push(gene);
		}

		if mutated_chromosome.len() != chromosome.len() {
			return Err(GeneticError::Internal);
		}

		if mutated_chromosome.is_valid() {
			return Ok(mutated_chromosome);
		}

		mutated_genes.clear();
		mutated_genes.resize(chromosome.len(), None);

		if let Some(GeneticLimit::Runtime(max_runtime)) = maybe_limit
			&& time.elapsed().ge(max_runtime)
		{
			return Err(GeneticError::InitialPopulationTimeout);
		}
	}
}

fn init_mating_dist(population_size: usize) -> Result<Uniform<usize>, GeneticError> {
	Uniform::try_from(0..population_size).map_err(|_| GeneticError::Internal)
}

#[cfg(test)]
mod tests {
	use crate::genetic::{Chromosome, Fitness, FitnessOrd, Gene, Genetic, Rng};

	#[derive(Clone)]
	struct TestData {
		data: u32,
	}

	#[derive(Default, Clone)]
	struct TestConfig {
		config: Vec<TestData>,
	}

	impl Chromosome for TestConfig {
		type Gene = TestData;

		fn base(&self) -> Self {
			TestConfig {
				config: Vec::new()
			}
		}

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

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

		fn push(&mut self, data: TestData) {
			self.config.push(data);
		}

		fn get(&self, index: usize) -> &TestData {
			&self.config[index]
		}

		fn clear(&mut self) {
			self.config.clear()
		}

		fn is_optimal(&self) -> bool {
			let sum = self
				.config
				.iter()
				.map(|item| item.data)
				.sum::<u32>();

			sum == 100
		}
	}

	impl TestConfig {
		fn sum(&self) -> u32 {
			self.config
				.iter()
				.map(|item| item.data)
				.sum::<u32>()
		}
	}

	impl FitnessOrd for TestConfig {
		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 TestData {
		fn mutate(&mut self, rng: &mut impl Rng, _genes: &[Option<Self>]) {
			self.data = rng.random_range(0..50);
		}
	}

	#[test]
	fn it_optimizes() {
		let mut initial_chromosome = TestConfig::default();

		initial_chromosome.push(TestData {
			data: 0
		});
		initial_chromosome.push(TestData {
			data: 0
		});
		initial_chromosome.push(TestData {
			data: 0
		});
		initial_chromosome.push(TestData {
			data: 0
		});
		initial_chromosome.push(TestData {
			data: 0
		});

		let mut genetic = Genetic::<TestConfig>::new(initial_chromosome).unwrap();

		let result = genetic.run().unwrap();

		assert_ne!(result.generations(), 0);
		assert_ne!(result.mutations(), 0);
		assert_eq!(result.chromosome().sum(), 100);
	}
}