pub struct GeneticSim<F, NG, G>{
pub genomes: Vec<G>,
/* private fields */
}
Expand description
The simulation controller.
use genetic_rs_common::prelude::*;
#[derive(Debug, Clone)]
struct MyGenome {
a: f32,
b: f32,
}
impl RandomlyMutable for MyGenome {
fn mutate(&mut self, rate: f32, rng: &mut impl rand::Rng) {
self.a += rng.gen::<f32>() * rate;
self.b += rng.gen::<f32>() * rate;
}
}
impl DivisionReproduction for MyGenome {
fn divide(&self, rng: &mut impl rand::Rng) -> Self {
let mut child = self.clone();
child.mutate(0.25, rng); // you'll generally want to use a constant mutation rate for mutating children.
child
}
}
impl Prunable for MyGenome {} // if we wanted to, we could implement the `despawn` function to run any cleanup code as needed. in this example, though, we do not need it.
impl GenerateRandom for MyGenome {
fn gen_random(rng: &mut impl rand::Rng) -> Self {
Self {
a: rng.gen(),
b: rng.gen(),
}
}
}
fn main() {
let my_fitness_fn = |e: &MyGenome| {
e.a * e.b // should result in genomes increasing their value
};
let mut rng = rand::thread_rng();
let mut sim = GeneticSim::new(
Vec::gen_random(&mut rng, 1000),
my_fitness_fn,
division_pruning_nextgen,
);
for _ in 0..100 {
// if this were a more complex simulation, you might test genomes in `sim.genomes` between `next_generation` calls to provide a more accurate reward.
sim.next_generation();
}
dbg!(sim.genomes);
}
Fields§
§genomes: Vec<G>
The current population of genomes
Implementations§
Source§impl<F, NG, G> GeneticSim<F, NG, G>
impl<F, NG, G> GeneticSim<F, NG, G>
Sourcepub fn new(
starting_genomes: Vec<G>,
fitness: F,
next_gen: NG,
) -> GeneticSim<F, NG, G>
pub fn new( starting_genomes: Vec<G>, fitness: F, next_gen: NG, ) -> GeneticSim<F, NG, G>
Creates a GeneticSim
with a given population of starting_genomes
(the size of which will be retained),
a given fitness function, and a given nextgen function.
Sourcepub fn next_generation(&mut self)
pub fn next_generation(&mut self)
Uses the next_gen
provided in GeneticSim::new
to create the next generation of genomes.
Auto Trait Implementations§
impl<F, NG, G> Freeze for GeneticSim<F, NG, G>
impl<F, NG, G> RefUnwindSafe for GeneticSim<F, NG, G>
impl<F, NG, G> Send for GeneticSim<F, NG, G>
impl<F, NG, G> Sync for GeneticSim<F, NG, G>
impl<F, NG, G> Unpin for GeneticSim<F, NG, G>
impl<F, NG, G> UnwindSafe for GeneticSim<F, NG, G>
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more