diff --git a/genetic-rs-common/src/builtin/eliminator.rs b/genetic-rs-common/src/builtin/eliminator.rs index b220913..d9c4e08 100644 --- a/genetic-rs-common/src/builtin/eliminator.rs +++ b/genetic-rs-common/src/builtin/eliminator.rs @@ -52,6 +52,16 @@ impl FitnessObserver for () { fn observe(&mut self, _fitnesses: &[(G, f32)]) {} } +impl FitnessObserver for F +where + F: Fn(&[(G, f32)]), + G: FeatureBoundedGenome, +{ + fn observe(&mut self, fitnesses: &[(G, f32)]) { + (self)(fitnesses); + } +} + /// An observer that calls two observers in sequence. /// Created by [`FitnessObserver::layer`]. pub struct LayeredObserver, B: FitnessObserver>( @@ -523,3 +533,150 @@ mod knockout { #[cfg(feature = "knockout")] pub use knockout::*; + +#[cfg(feature = "speciation")] +mod speciation { + use crate::{prelude::*, speciation::SpeciatedPopulation}; + + /// An eliminator that attempts to preserve new experimental structures by dividing a genome's + /// fitness by the number of genomes in its species. + pub struct SpeciatedFitnessEliminator< + F: FeatureBoundedFitnessFn, + G: Speciated + FeatureBoundedGenome, + O: FeatureBoundedFitnessObserver = (), + > { + /// The divergence threshold used to determine whether a genome belongs in a species. + /// See [`SpeciatedPopulation::threshold`] for more info. + pub speciation_threshold: f32, + + /// The inner fitness eliminator used to hold settings and such. + pub inner: FitnessEliminator, + + /// The context used to determine species membership. + /// This is necessary since the eliminator needs to calculate species membership to divide fitness by species size, and some genome types may require context to calculate divergence. + pub ctx: ::Context, + + _marker: std::marker::PhantomData, + } + + impl SpeciatedFitnessEliminator + where + F: FeatureBoundedFitnessFn, + G: Speciated + FeatureBoundedGenome, + O: FeatureBoundedFitnessObserver, + { + /// Creates a new [`SpeciatedFitnessEliminator`] with a given fitness function and thresholds. + pub fn new( + fitness_fn: F, + speciation_threshold: f32, + keep_threshold: f32, + observer: O, + ctx: ::Context, + ) -> Self { + Self { + speciation_threshold, + inner: FitnessEliminator::new(fitness_fn, keep_threshold, observer), + ctx, + _marker: std::marker::PhantomData, + } + } + + /// Creates a new [`SpeciatedFitnessEliminator`] from a regular [`FitnessEliminator`] and a speciation threshold. + /// Useful since you can use the builder for [`FitnessEliminator`] to construct the fitness function and observer, then convert it into a [`SpeciatedFitnessEliminator`] with this method. + pub fn from_fitness_eliminator( + fitness_eliminator: FitnessEliminator, + speciation_threshold: f32, + ctx: ::Context, + ) -> Self { + Self { + speciation_threshold, + inner: fitness_eliminator, + ctx, + _marker: std::marker::PhantomData, + } + } + + /// Calculates the fitness of each genome, dividing by the number of genomes in its species, and sorts them by fitness. + /// Returns a vector of tuples containing the genome and its fitness score. + #[cfg(not(feature = "rayon"))] + pub fn calculate_and_sort(&self, genomes: Vec) -> Vec<(G, f32)> { + let population = + SpeciatedPopulation::from_genomes(&genomes, self.speciation_threshold, &self.ctx); + let mut fitnesses = vec![0.0; genomes.len()]; + + for species in population.species { + let len = species.len() as f32; + debug_assert!(len != 0.0); + for index in species { + let genome = &genomes[index]; + let fitness = self.inner.fitness_fn.fitness(genome); + if fitness < 0.0 { + fitnesses[index] = fitness * len; + } else { + fitnesses[index] = fitness / len; + } + } + } + + let mut fitnesses: Vec<(G, f32)> = genomes.into_iter().zip(fitnesses).collect(); + fitnesses.sort_by(|(_a, afit), (_b, bfit)| bfit.partial_cmp(afit).unwrap()); + fitnesses + } + + /// Calculates the fitness of each genome, dividing by the number of genomes in its species, and sorts them by fitness. + /// Returns a vector of tuples containing the genome and its fitness score. + #[cfg(feature = "rayon")] + pub fn calculate_and_sort(&self, genomes: Vec) -> Vec<(G, f32)> { + let population = + SpeciatedPopulation::from_genomes(&genomes, self.speciation_threshold, &self.ctx); + + let mut fitnesses = vec![0.0; genomes.len()]; + + for species in population.species { + let len = species.len() as f32; + debug_assert!(len != 0.0); + for index in species { + let genome = &genomes[index]; + let fitness = self.inner.fitness_fn.fitness(genome); + if fitness < 0.0 { + fitnesses[index] = fitness * len; + } else { + fitnesses[index] = fitness / len; + } + } + } + + let mut result: Vec<(G, f32)> = genomes.into_iter().zip(fitnesses).collect(); + result.sort_by(|(_a, afit), (_b, bfit)| bfit.partial_cmp(afit).unwrap()); + result + } + } + + impl Eliminator for SpeciatedFitnessEliminator + where + F: FeatureBoundedFitnessFn, + G: Speciated + FeatureBoundedGenome, + O: FeatureBoundedFitnessObserver, + { + #[cfg(not(feature = "rayon"))] + fn eliminate(&mut self, genomes: Vec) -> Vec { + let mut fitnesses = self.calculate_and_sort(genomes); + self.inner.observer.observe(&fitnesses); + let median_index = (fitnesses.len() as f32) * self.inner.threshold; + fitnesses.truncate(median_index as usize + 1); + fitnesses.into_iter().map(|(g, _)| g).collect() + } + + #[cfg(feature = "rayon")] + fn eliminate(&mut self, genomes: Vec) -> Vec { + let mut fitnesses = self.calculate_and_sort(genomes); + self.inner.observer.observe(&fitnesses); + let median_index = (fitnesses.len() as f32) * self.inner.threshold; + fitnesses.truncate(median_index as usize + 1); + fitnesses.into_par_iter().map(|(g, _)| g).collect() + } + } +} + +#[cfg(feature = "speciation")] +pub use speciation::*; diff --git a/genetic-rs-common/src/builtin/repopulator.rs b/genetic-rs-common/src/builtin/repopulator.rs index 5f13994..52f9e81 100644 --- a/genetic-rs-common/src/builtin/repopulator.rs +++ b/genetic-rs-common/src/builtin/repopulator.rs @@ -150,6 +150,16 @@ mod crossover { } } } + + impl Default for CrossoverRepopulator + where + G: Crossover, + G::Context: Default, + { + fn default() -> Self { + Self::new(0.05, G::Context::default()) + } + } } #[cfg(feature = "crossover")] @@ -157,43 +167,82 @@ pub use crossover::*; #[cfg(feature = "speciation")] mod speciation { - use std::collections::HashMap; - use rand::RngExt; - use super::*; + use crate::speciation::{Speciated, SpeciatedPopulation}; - /// Used in speciated crossover nextgens. Allows for genomes to avoid crossover with ones that are too different. - pub trait Speciated { - /// The type used to distinguish - /// one genome's species from another. - type Species: Eq + std::hash::Hash; // I really don't like that we need `Eq` when `PartialEq` better fits the definiton. + use super::*; - /// Get/calculate this genome's species. - fn species(&self) -> Self::Species; + /// The action to take when a genome is found to be in a species by itself. + /// This can be used to prevent species from going extinct due to bad luck in crossover. + pub enum ActionIfIsolated { + /// Do nothing, allowing the species to go extinct if the genome is not fit enough. + /// If all species happen to be isolated (no species has >= 2 members), the + /// repopulator automatically falls back to [`CrossoverRepopulator`] to avoid + /// an infinite loop. + DoNothing, + + /// Perform crossover between the genome and itself to create a new member of the species. + /// This can help prevent species from going extinct, but can also lead to less diversity in the population. + CrossoverSelf, + + /// Perform crossover between the genome and a random member of the most similar species to create a new member of the species. + /// This can help prevent species from going extinct while maintaining more diversity than self-crossover, but can also lead to more computational overhead. + CrossoverSimilarSpecies, + + /// Perform crossover between the genome and a random member of the entire population, ignoring species boundaries, to create a new member of the species. + /// This can help prevent species from going extinct, but can also contribute to more broken or dysfunctional species. + CrossoverRandom, } /// Repopulator that uses crossover reproduction to create new genomes, but only between genomes of the same species. pub struct SpeciatedCrossoverRepopulator { - /// The inner crossover repopulator. This holds the settings for crossover operations, - /// but may also be called if [`allow_emergency_repr`][Self::allow_emergency_repr] is `true`. - pub crossover: CrossoverRepopulator, + /// The inner crossover repopulator. This holds the settings for crossover operations. + pub inner: CrossoverRepopulator, - /// Whether to allow genomes to reproduce across species boundaries - /// (effectively vanilla crossover) - /// in emergency situations where no genomes have compatible partners. - /// If disabled, the simulation will panic in such a situation. - pub allow_emergency_repr: bool, + /// The threshold used to determine if a genome belongs in a species. + /// See [`SpeciatedPopulation::threshold`] for more info. + pub speciation_threshold: f32, + + /// The action to take when a genome is found to be in a species by itself. + pub action_if_isolated: ActionIfIsolated, + + /// Additional context for speciation. + pub ctx: ::Context, _marker: std::marker::PhantomData, } impl SpeciatedCrossoverRepopulator { /// Creates a new [`SpeciatedCrossoverRepopulator`]. - pub fn new(mutation_rate: f32, allow_emergency_repr: bool, ctx: G::Context) -> Self { + pub fn new( + mutation_rate: f32, + threshold: f32, + action_if_isolated: ActionIfIsolated, + crossover_ctx: ::Context, + spec_ctx: ::Context, + ) -> Self { Self { - crossover: CrossoverRepopulator::new(mutation_rate, ctx), - allow_emergency_repr, + inner: CrossoverRepopulator::new(mutation_rate, crossover_ctx), + ctx: spec_ctx, + speciation_threshold: threshold, + action_if_isolated, + _marker: std::marker::PhantomData, + } + } + + /// Creates a new [`SpeciatedCrossoverRepopulator`] from an existing [`CrossoverRepopulator`], using the same mutation settings. + pub fn from_crossover( + inner: CrossoverRepopulator, + threshold: f32, + action_if_isolated: ActionIfIsolated, + ctx: ::Context, + ) -> Self { + Self { + inner, + ctx, + speciation_threshold: threshold, + action_if_isolated, _marker: std::marker::PhantomData, } } @@ -203,60 +252,122 @@ mod speciation { where G: Crossover + Speciated, { - // i'm still not really satisfied with this implementation, - // but it's better than the old one. fn repopulate(&mut self, genomes: &mut Vec, target_size: usize) { let initial_size = genomes.len(); - let mut rng = rand::rng(); - let mut species: HashMap<::Species, Vec<&G>> = HashMap::new(); - - for genome in genomes.iter() { - let spec = genome.species(); - species.entry(spec).or_insert_with(Vec::new).push(genome); + if initial_size >= target_size { + return; } - let mut species_iter = species.values(); - let to_create = target_size - initial_size; - let mut new_genomes = Vec::with_capacity(to_create); - - while new_genomes.len() < to_create { - if let Some(spec) = species_iter.next() { - if spec.len() < 2 { - continue; - } + let mut rng = rand::rng(); + let population = + SpeciatedPopulation::from_genomes(genomes, self.speciation_threshold, &self.ctx); + + // if all species are isolated, we fall back to the inner crossover repopulator to avoid an infinite loop. + if matches!(self.action_if_isolated, ActionIfIsolated::DoNothing) + && !population.species.iter().any(|s| s.len() >= 2) + { + self.inner.repopulate(genomes, target_size); + return; + } - for (i, &parent1) in spec.iter().enumerate() { - let mut j = rng.random_range(1..spec.len()); - if j == i { - j = 0; + let amount_to_make = target_size - initial_size; + let mut species_cycle = population.round_robin_enumerate(); + + let mut i = 0; + while i < amount_to_make { + let (species_i, genome_i) = species_cycle.next().unwrap(); + let species = &population.species[species_i]; + let parent1 = &genomes[genome_i]; + if species.len() < 2 { + match self.action_if_isolated { + ActionIfIsolated::DoNothing => continue, + ActionIfIsolated::CrossoverSelf => { + let child = parent1.crossover( + parent1, + &self.inner.ctx, + self.inner.mutation_rate, + &mut rng, + ); + genomes.push(child); + i += 1; + continue; } - let parent2 = spec[j]; - - new_genomes.push(parent1.crossover( - parent2, - &self.crossover.ctx, - self.crossover.mutation_rate, - &mut rng, - )); - } - } else { - // reached the end, reset the iterator - - if new_genomes.is_empty() { - // no genomes have compatible partners - if self.allow_emergency_repr { - self.crossover.repopulate(genomes, target_size); - return; - } else { - panic!("no genomes with common species"); + ActionIfIsolated::CrossoverSimilarSpecies => { + let mut best_species_i = 0; + let mut best_divergence = f32::MAX; + for (j, species) in population.species.iter().enumerate() { + if j == species_i || species.is_empty() { + continue; + } + let representative = &genomes[species[0]]; + let divergence = parent1.divergence(representative, &self.ctx); + if divergence < best_divergence { + best_divergence = divergence; + best_species_i = j; + } + } + + let best_species = &population.species[best_species_i]; + let j = rng.random_range(0..best_species.len()); + let parent2 = &genomes[best_species[j]]; + let child = parent1.crossover( + parent2, + &self.inner.ctx, + self.inner.mutation_rate, + &mut rng, + ); + genomes.push(child); + i += 1; + continue; + } + ActionIfIsolated::CrossoverRandom => { + let mut j = rng.random_range(1..initial_size); + if j == genome_i { + j = 0; + } + + let parent2 = &genomes[j]; + let child = parent1.crossover( + parent2, + &self.inner.ctx, + self.inner.mutation_rate, + &mut rng, + ); + genomes.push(child); + i += 1; + continue; } } + } - species_iter = species.values(); + let mut j = rng.random_range(1..species.len()); + if genome_i == species[j] { + j = 0; } + let parent2 = &genomes[species[j]]; + + let child = + parent1.crossover(parent2, &self.inner.ctx, self.inner.mutation_rate, &mut rng); + genomes.push(child); + + i += 1; } + } + } - genomes.extend(new_genomes); + impl Default for SpeciatedCrossoverRepopulator + where + G: Crossover + Speciated, + ::Context: Default, + ::Context: Default, + { + fn default() -> Self { + Self::from_crossover( + CrossoverRepopulator::default(), + 0.1, + ActionIfIsolated::CrossoverSimilarSpecies, + ::Context::default(), + ) } } } diff --git a/genetic-rs-common/src/lib.rs b/genetic-rs-common/src/lib.rs index 05b0f2c..f77903d 100644 --- a/genetic-rs-common/src/lib.rs +++ b/genetic-rs-common/src/lib.rs @@ -8,6 +8,10 @@ #[cfg(feature = "builtin")] pub mod builtin; +/// Common speciation code used for speciated eliminators and repopulators. +#[cfg(feature = "speciation")] +pub mod speciation; + /// Used to quickly import everything this crate has to offer. /// Simply add `use genetic_rs::prelude::*` to begin using this crate. pub mod prelude; diff --git a/genetic-rs-common/src/prelude.rs b/genetic-rs-common/src/prelude.rs index bd3c19f..ade6ac9 100644 --- a/genetic-rs-common/src/prelude.rs +++ b/genetic-rs-common/src/prelude.rs @@ -5,4 +5,7 @@ pub use crate::*; #[cfg(feature = "builtin")] pub use crate::builtin::{eliminator::*, repopulator::*}; +#[cfg(feature = "speciation")] +pub use crate::speciation::Speciated; + pub use rand::prelude::*; diff --git a/genetic-rs-common/src/speciation.rs b/genetic-rs-common/src/speciation.rs new file mode 100644 index 0000000..6dd8fcb --- /dev/null +++ b/genetic-rs-common/src/speciation.rs @@ -0,0 +1,129 @@ +/// Trait that allows a genome to be separated into species. +pub trait Speciated { + /// The context type for speciation. This can be used to provide additional information + /// that may be needed to calculate the divergence between two genomes. + type Context; + + /// How structurally different this genome is to another genome. The higher the value, the more different they are. + /// When implementing this, you should consider only the major structural differences that could + /// take several generations to evolve an optimal solution. Do not consider minor differences that + /// are easily evolved in a single generation, such as a single weight change. + /// By common convention, this is typically a value between 0 and 1. + /// Additionally, it should also be symmetric, meaning that the divergence between genome A and genome B should be + /// the same as the divergence between genome B and genome A. + /// This value is used to separate genomes into a species. + fn divergence(&self, other: &Self, ctx: &Self::Context) -> f32; +} + +/// A population of genomes that have been separated into species. +pub struct SpeciatedPopulation { + /// The species in this population. Each species is a vector of indices into the original genome vector. + /// The first genome in a species is its representation (i.e. the one that gets compared to other genomes to determine + /// if they belong in the species) + pub species: Vec>, + + /// The threshold used to determine if a genome belongs in a species. If the divergence between a genome and the representative genome + /// of a species is less than this threshold, then the genome belongs in that species. + pub threshold: f32, +} + +impl SpeciatedPopulation { + /// Inserts a genome into the speciated population. + /// Returns whether a new species was created by this insertion. + pub fn insert_genome( + &mut self, + index: usize, + genomes: &[G], + ctx: &G::Context, + ) -> bool { + if let Some(species) = self.get_species_mut(index, genomes, ctx) { + species.push(index); + return false; + } + self.species.push(vec![index]); + true + } + + /// Creates a new speciated population from a population of genomes. + /// Note that this can be O(n^2) worst case, but is typically much faster in practice, + /// especially if the genome structure doesn't mutate often. + pub fn from_genomes(population: &[G], threshold: f32, ctx: &G::Context) -> Self { + let mut speciated_population = SpeciatedPopulation { + species: Vec::new(), + threshold, + }; + for index in 0..population.len() { + speciated_population.insert_genome(index, population, ctx); + } + speciated_population + } + + /// Gets the species that a genome belongs to, if any. + pub fn get_species( + &self, + index: usize, + genomes: &[G], + ctx: &G::Context, + ) -> Option<&Vec> { + let genome = &genomes[index]; + self.species + .iter() + .find(|species| genome.divergence(&genomes[species[0]], ctx) < self.threshold) + } + + /// Get a mutable reference to the species that a genome belongs to, if any. + pub fn get_species_mut( + &mut self, + index: usize, + genomes: &[G], + ctx: &G::Context, + ) -> Option<&mut Vec> { + let genome = &genomes[index]; + self.species + .iter_mut() + .find(|species| genome.divergence(&genomes[species[0]], ctx) < self.threshold) + } + + /// Round robin cyclic iterator over the genomes in this population. + /// Note that the index value is the index in the original genome vector, not the index in the species vector. + pub fn round_robin(&self) -> impl Iterator + '_ { + let species = &self.species; + let mut idx_in_species = vec![0; self.species.len()]; + let mut species_i = 0usize; + + std::iter::from_fn(move || { + if species.is_empty() { + return None; + } + + let cur_species = &species[species_i]; + let genome_index = cur_species[idx_in_species[species_i]]; + idx_in_species[species_i] = (idx_in_species[species_i] + 1) % cur_species.len(); + species_i = (species_i + 1) % species.len(); + Some(genome_index) + }) + } + + /// Round robin, but also returns the species index along with the genome index. + /// Note that the genome index value is the index in the original genome vector, not the index in the species vector. + /// However, the species index represents the index in [`Self::species`]. + /// Format is (species_index, genome_index). + pub fn round_robin_enumerate(&self) -> impl Iterator + '_ { + let species = &self.species; + let mut idx_in_species = vec![0; self.species.len()]; + let mut species_i = 0usize; + + std::iter::from_fn(move || { + if species.is_empty() { + return None; + } + + let cur_species = &species[species_i]; + let cur_species_i = species_i; + let genome_index = cur_species[idx_in_species[species_i]]; + idx_in_species[species_i] = (idx_in_species[species_i] + 1) % cur_species.len(); + species_i = (species_i + 1) % species.len(); + Some((cur_species_i, genome_index)) + }) + } +} diff --git a/genetic-rs/examples/speciation.rs b/genetic-rs/examples/speciation.rs index 662ee45..a9f3635 100644 --- a/genetic-rs/examples/speciation.rs +++ b/genetic-rs/examples/speciation.rs @@ -1,26 +1,56 @@ use genetic_rs::prelude::*; +/// Max value of divergence() that will count two genomes as the same species. +const SPECIATION_THRESHOLD: f32 = 0.1; + #[derive(Clone, PartialEq, Debug)] struct MyGenome { - val1: f32, - val2: f32, + vals: Vec, +} + +impl GenerateRandom for MyGenome { + fn gen_random(rng: &mut impl rand::Rng) -> Self { + Self { + vals: (0..10).map(|_| rng.random_range(-1.0..1.0)).collect(), + } + } } impl RandomlyMutable for MyGenome { type Context = (); - fn mutate(&mut self, _: &(), rate: f32, rng: &mut impl Rng) { - self.val1 += rng.random_range(-1.0..1.0) * rate; - self.val2 += rng.random_range(-1.0..1.0) * rate; + fn mutate(&mut self, _ctx: &Self::Context, rate: f32, rng: &mut impl rand::Rng) { + // internal mutation + for val in &mut self.vals { + if rng.random_bool(rate as f64) { + *val += rng.random_range(-0.1..0.1); + } + } + + // structural mutations + if rng.random_bool(rate as f64) { + // add a new random gene + self.vals.push(rng.random_range(-1.0..1.0)); + } + if self.vals.len() > 1 && rng.random_bool(rate as f64) { + // remove a random gene + let index = rng.random_range(0..self.vals.len()); + self.vals.remove(index); + } } } impl Mitosis for MyGenome { type Context = (); - fn divide(&self, _: &(), rate: f32, rng: &mut impl Rng) -> Self { + fn divide( + &self, + ctx: &::Context, + rate: f32, + rng: &mut impl rand::Rng, + ) -> Self { let mut child = self.clone(); - child.mutate(&(), rate, rng); + child.mutate(ctx, rate, rng); child } } @@ -28,52 +58,96 @@ impl Mitosis for MyGenome { impl Crossover for MyGenome { type Context = (); - fn crossover(&self, other: &Self, _: &(), rate: f32, rng: &mut impl Rng) -> Self { - let mut child = Self { - val1: (self.val1 + other.val1) / 2., - val2: (self.val2 + other.val2) / 2., - }; - child.mutate(&(), rate, rng); + fn crossover( + &self, + other: &Self, + ctx: &Self::Context, + rate: f32, + rng: &mut impl rand::Rng, + ) -> Self { + // even though they ideally shouldn't crossover if they aren't the same length + // because of speciation, we can still allow it in emergency scenarios to prevent extinction + // and encourage more diversity, at the cost of more broken or dysfunctional species + let mut child; + let smaller; + if self.vals.len() < other.vals.len() { + child = other.clone(); + smaller = self; + } else { + child = self.clone(); + smaller = other; + } + + for i in 0..smaller.vals.len() { + if rng.random_bool(0.5) { + child.vals[i] = smaller.vals[i]; + } + } + + child.mutate(ctx, rate, rng); + child } } -#[derive(PartialEq, Eq, Hash)] -struct MySpecies(u32); - impl Speciated for MyGenome { - type Species = MySpecies; + type Context = (); - fn species(&self) -> Self::Species { - MySpecies((self.val1 + self.val2).round() as u32) + fn divergence(&self, other: &Self, _ctx: &Self::Context) -> f32 { + // distance in lengths divided by the larger length + let larger = self.vals.len().max(other.vals.len()); + // can't be 0 because of how we set up mutate() + assert!(larger != 0); + let length_diff = (self.vals.len() as isize - other.vals.len() as isize).abs() as f32; + length_diff / larger as f32 } } -impl GenerateRandom for MyGenome { - fn gen_random(rng: &mut impl Rng) -> Self { - Self { - val1: rng.random_range(-1.0..1.0), - val2: rng.random_range(-1.0..1.0), - } - } +fn fitness(genome: &MyGenome) -> f32 { + // the fitness function is just the sum of the genes, which encourages longer genomes. + // however, since the structure mutation can add negative values initially, speciation + // will help protect those genomes until they can mutate the internal state into positive values. + genome.vals.iter().sum() } -fn fitness(g: &MyGenome) -> f32 { - // train to make val1 and val2 as different as possible - (g.val1 - g.val2).abs() +fn print_fitnesses(fitnesses: &[(MyGenome, f32)]) { + // note that with SpeciatedFitnessEliminator, + // these values are divided by the number of genomes in the species if positive, + // multiplied if negative. + let hi = fitnesses[0].1; + let med = fitnesses[fitnesses.len() / 2].1; + let lo = fitnesses[fitnesses.len() - 1].1; + + println!("hi: {hi} med: {med} lo: {lo}"); } fn main() { let mut rng = rand::rng(); + let fitness_eliminator = FitnessEliminator::builder() + .fitness_fn(fitness) + .observer(print_fitnesses) + .build_or_panic(); + + let crossover_rep = CrossoverRepopulator::default(); + let mut sim = GeneticSim::new( Vec::gen_random(&mut rng, 100), - FitnessEliminator::new_without_observer(fitness), - // 25% mutation rate, allow cross-species reproduction in emergency scenarios - SpeciatedCrossoverRepopulator::new(0.25, true, ()), + SpeciatedFitnessEliminator::from_fitness_eliminator( + fitness_eliminator, + SPECIATION_THRESHOLD, + (), + ), + SpeciatedCrossoverRepopulator::from_crossover( + crossover_rep, + SPECIATION_THRESHOLD, + ActionIfIsolated::CrossoverSimilarSpecies, + (), + ), ); sim.perform_generations(100); - dbg!(sim.genomes); + // rerunning multiple times should show a lot of diversity in genome length + dbg!(&sim.genomes[0]); }