Expand description
§Chromosome
Utilities for genetic algorithms
§Example
use core::{
iter::Sum,
ops::{Mul, Sub},
};
use chromosome::Fitness;
use chromosome::{Chromosome, DefaultSimulator, FitnessSelector, Simulator};
use rand_pcg::Pcg64;
use rand_seeder::Seeder;
struct DiophantusEquation<'a, 'b, T> {
coefficients: &'a Vec<T>,
result: &'b T,
}
impl<'a, 'b, T> DiophantusEquation<'a, 'b, T> {
fn new(coefficients: &'a Vec<T>, result: &'b T) -> Self {
DiophantusEquation {
coefficients: coefficients,
result: result,
}
}
}
impl<'a, 'b, T: Mul<Output = T> + Sum + Sub<Output = T> + Into<f64> + Clone> Fitness
for DiophantusEquation<'a, 'b, T>
{
type Value = T;
fn fitness(self: &Self, chromosome: &Chromosome<T>) -> T {
(0..usize::min(self.coefficients.len(), chromosome.genes.len()))
.map(|i| self.coefficients[i].clone() * chromosome.genes[i].clone())
.sum::<T>()
- self.result.clone()
}
fn is_ideal_fitness(&self, fitness: Self::Value) -> bool {
fitness.into() == 0_f64
}
}
#[test]
fn diophantus_equation() {
let mut rng: Pcg64 = Seeder::from([23, 87, 85]).into_rng();
let coefs = vec![2_i32, 23, 54, 1];
let equation = DiophantusEquation::new(&coefs, &2);
let sim_result = DefaultSimulator::new(vec![1; 4], 0.09, 10000).simulate(
vec![
Chromosome::new_random(equation.coefficients.len(), 0_i32..10, &mut rng),
Chromosome::new_random(equation.coefficients.len(), 0_i32..10, &mut rng),
],
FitnessSelector::from(equation),
&mut rng,
);
assert!(sim_result.is_some())
}
Structs§
- Chromosome
- Chromosome contains genes and provide genetic operations on them
- Default
Simulator - DefaultSimulator make default simulation
- Fitness
Selector - FitnessSelector selects chromosomes by fitness values
- Simulation
Iter - SimulationIter provides Simulating genetics by iterating. each
next()
call produces next generation..collect()
gives all generations up to finalideal
one
Traits§
- Fitness
- Fitness trait provides interface for finging fitness value for chromosome
- Selector
- Genetic selector
- Simulator
- Simulator makes blocking simulation of genetics returns Chromosome if simulation successful and solution found and None if no solution
- Superposition