From bf112e460b58d10eb95a55292d67080dbeecd0bf Mon Sep 17 00:00:00 2001 From: Tristan Murphy <72839119+HyperCodec@users.noreply.github.com> Date: Mon, 9 Mar 2026 13:04:07 +0000 Subject: [PATCH 01/17] implement SpeiatedFitnessEliminator --- genetic-rs-common/src/builtin/eliminator.rs | 134 ++++++++++++++++++++ genetic-rs-common/src/lib.rs | 4 + genetic-rs-common/src/prelude.rs | 3 + genetic-rs-common/src/speciation.rs | 73 +++++++++++ 4 files changed, 214 insertions(+) create mode 100644 genetic-rs-common/src/speciation.rs diff --git a/genetic-rs-common/src/builtin/eliminator.rs b/genetic-rs-common/src/builtin/eliminator.rs index b220913..833aeff 100644 --- a/genetic-rs-common/src/builtin/eliminator.rs +++ b/genetic-rs-common/src/builtin/eliminator.rs @@ -523,3 +523,137 @@ 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, 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 fitness function used to evaluate genomes. + pub fitness_fn: F, + + /// The percentage of genomes to keep. Must be between 0.0 and 1.0. + pub keep_threshold: f32, + + /// The fitness observer used to observe fitness scores. + pub observer: Option, + + _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. + /// Panics if the thresholds are not between 0.0 and 1.0. + pub fn new(fitness_fn: F, speciation_threshold: f32, keep_threshold: f32, observer: Option) -> Self { + if !(0.0..=1.0).contains(&speciation_threshold) { + panic!("Speciation threshold must be between 0.0 and 1.0"); + } + if !(0.0..=1.0).contains(&keep_threshold) { + panic!("Keep threshold must be between 0.0 and 1.0"); + } + Self { + fitness_fn, + speciation_threshold, + keep_threshold, + observer, + _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) -> Self { + Self::new(fitness_eliminator.fitness_fn, speciation_threshold, fitness_eliminator.threshold, Some(fitness_eliminator.observer)) + } + + /// 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); + let mut fitnesses = vec![0.0; genomes.len()]; + + for species in population.species { + let len = species.len() as f32; + for index in species { + let genome = &genomes[index]; + let fitness = self.fitness_fn.fitness(genome) / len; + fitnesses[index] = fitness; + } + } + + let mut fitnesses: Vec<(G, f32)> = genomes.into_iter().zip(fitnesses.into_iter()).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); + + // Create fitnesses array with default values + let mut fitnesses = vec![0.0; genomes.len()]; + + // Process species sequentially, but within each species compute fitnesses in parallel + for species in population.species { + let len = species.len() as f32; + let updates: Vec<(usize, f32)> = species + .par_iter() + .map(|&index| { + let genome = &genomes[index]; + let fitness = self.fitness_fn.fitness(genome) / len; + (index, fitness) + }) + .collect(); + + for (index, fitness) in updates { + fitnesses[index] = fitness; + } + } + + // Pair genomes with fitnesses and sort + let mut result: Vec<(G, f32)> = genomes.into_iter().zip(fitnesses.into_iter()).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); + let median_index = (fitnesses.len() as f32) * self.keep_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); + let median_index = (fitnesses.len() as f32) * self.keep_threshold; + fitnesses.truncate(median_index as usize + 1); + fitnesses.into_par_iter().map(|(g, _)| g).collect() + } + } +} + +#[cfg(feature = "speciation")] +pub use speciation::*; \ No newline at end of file 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..474f5bc --- /dev/null +++ b/genetic-rs-common/src/speciation.rs @@ -0,0 +1,73 @@ +/// Trait that allows a genome to be separated into species. +pub trait Speciated { + /// 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) -> 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]) -> bool { + if let Some(species) = self.get_species_mut(index, genomes) { + 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) -> Self { + let mut speciated_population = SpeciatedPopulation { + species: Vec::new(), + threshold, + }; + for index in 0..population.len() { + speciated_population.insert_genome(index, population); + } + speciated_population + } + + /// Gets the species that a genome belongs to, if any. + pub fn get_species(&self, index: usize, genomes: &[G]) -> Option<&Vec> { + let genome = &genomes[index]; + for species in &self.species { + if genome.divergence(&genomes[species[0]]) < self.threshold { + return Some(species); + } + } + None + } + + /// 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]) -> Option<&mut Vec> { + let genome = &genomes[index]; + for species in &mut self.species { + if genome.divergence(&genomes[species[0]]) < self.threshold { + return Some(species); + } + } + None + } +} \ No newline at end of file From b33448ed23ae84e63c382653cfb87961b477399f Mon Sep 17 00:00:00 2001 From: Tristan Murphy <72839119+HyperCodec@users.noreply.github.com> Date: Mon, 9 Mar 2026 13:04:15 +0000 Subject: [PATCH 02/17] cargo fmt --- genetic-rs-common/src/builtin/eliminator.rs | 45 +++++++++++++++------ genetic-rs-common/src/speciation.rs | 8 +++- 2 files changed, 38 insertions(+), 15 deletions(-) diff --git a/genetic-rs-common/src/builtin/eliminator.rs b/genetic-rs-common/src/builtin/eliminator.rs index 833aeff..3722a9d 100644 --- a/genetic-rs-common/src/builtin/eliminator.rs +++ b/genetic-rs-common/src/builtin/eliminator.rs @@ -527,10 +527,14 @@ 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, G: Speciated + FeatureBoundedGenome, O: FeatureBoundedFitnessObserver = ()> { + 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, @@ -540,7 +544,7 @@ mod speciation { /// The percentage of genomes to keep. Must be between 0.0 and 1.0. pub keep_threshold: f32, - + /// The fitness observer used to observe fitness scores. pub observer: Option, @@ -555,7 +559,12 @@ mod speciation { { /// Creates a new [`SpeciatedFitnessEliminator`] with a given fitness function and thresholds. /// Panics if the thresholds are not between 0.0 and 1.0. - pub fn new(fitness_fn: F, speciation_threshold: f32, keep_threshold: f32, observer: Option) -> Self { + pub fn new( + fitness_fn: F, + speciation_threshold: f32, + keep_threshold: f32, + observer: Option, + ) -> Self { if !(0.0..=1.0).contains(&speciation_threshold) { panic!("Speciation threshold must be between 0.0 and 1.0"); } @@ -573,8 +582,16 @@ mod speciation { /// 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) -> Self { - Self::new(fitness_eliminator.fitness_fn, speciation_threshold, fitness_eliminator.threshold, Some(fitness_eliminator.observer)) + pub fn from_fitness_eliminator( + fitness_eliminator: FitnessEliminator, + speciation_threshold: f32, + ) -> Self { + Self::new( + fitness_eliminator.fitness_fn, + speciation_threshold, + fitness_eliminator.threshold, + Some(fitness_eliminator.observer), + ) } /// Calculates the fitness of each genome, dividing by the number of genomes in its species, and sorts them by fitness. @@ -593,7 +610,8 @@ mod speciation { } } - let mut fitnesses: Vec<(G, f32)> = genomes.into_iter().zip(fitnesses.into_iter()).collect(); + let mut fitnesses: Vec<(G, f32)> = + genomes.into_iter().zip(fitnesses.into_iter()).collect(); fitnesses.sort_by(|(_a, afit), (_b, bfit)| bfit.partial_cmp(afit).unwrap()); fitnesses } @@ -603,10 +621,10 @@ mod speciation { #[cfg(feature = "rayon")] pub fn calculate_and_sort(&self, genomes: Vec) -> Vec<(G, f32)> { let population = SpeciatedPopulation::from_genomes(&genomes, self.speciation_threshold); - + // Create fitnesses array with default values let mut fitnesses = vec![0.0; genomes.len()]; - + // Process species sequentially, but within each species compute fitnesses in parallel for species in population.species { let len = species.len() as f32; @@ -618,14 +636,15 @@ mod speciation { (index, fitness) }) .collect(); - + for (index, fitness) in updates { fitnesses[index] = fitness; } } - + // Pair genomes with fitnesses and sort - let mut result: Vec<(G, f32)> = genomes.into_iter().zip(fitnesses.into_iter()).collect(); + let mut result: Vec<(G, f32)> = + genomes.into_iter().zip(fitnesses.into_iter()).collect(); result.sort_by(|(_a, afit), (_b, bfit)| bfit.partial_cmp(afit).unwrap()); result } @@ -656,4 +675,4 @@ mod speciation { } #[cfg(feature = "speciation")] -pub use speciation::*; \ No newline at end of file +pub use speciation::*; diff --git a/genetic-rs-common/src/speciation.rs b/genetic-rs-common/src/speciation.rs index 474f5bc..24729a8 100644 --- a/genetic-rs-common/src/speciation.rs +++ b/genetic-rs-common/src/speciation.rs @@ -61,7 +61,11 @@ impl SpeciatedPopulation { } /// 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]) -> Option<&mut Vec> { + pub fn get_species_mut( + &mut self, + index: usize, + genomes: &[G], + ) -> Option<&mut Vec> { let genome = &genomes[index]; for species in &mut self.species { if genome.divergence(&genomes[species[0]]) < self.threshold { @@ -70,4 +74,4 @@ impl SpeciatedPopulation { } None } -} \ No newline at end of file +} From 1233e02097b2e098201230a7bc8316ba423c1d34 Mon Sep 17 00:00:00 2001 From: Tristan Murphy <72839119+HyperCodec@users.noreply.github.com> Date: Mon, 9 Mar 2026 17:11:20 +0000 Subject: [PATCH 03/17] create new speciatedcrossoverrepopulator --- genetic-rs-common/src/builtin/eliminator.rs | 52 +++----- genetic-rs-common/src/builtin/repopulator.rs | 130 +++++++++---------- genetic-rs-common/src/speciation.rs | 70 ++++++++-- 3 files changed, 146 insertions(+), 106 deletions(-) diff --git a/genetic-rs-common/src/builtin/eliminator.rs b/genetic-rs-common/src/builtin/eliminator.rs index 3722a9d..d0945d6 100644 --- a/genetic-rs-common/src/builtin/eliminator.rs +++ b/genetic-rs-common/src/builtin/eliminator.rs @@ -539,14 +539,12 @@ mod speciation { /// See [`SpeciatedPopulation::threshold`] for more info. pub speciation_threshold: f32, - /// The fitness function used to evaluate genomes. - pub fitness_fn: F, - - /// The percentage of genomes to keep. Must be between 0.0 and 1.0. - pub keep_threshold: f32, + /// The inner fitness eliminator used to hold settings and such. + pub inner: FitnessEliminator, - /// The fitness observer used to observe fitness scores. - pub observer: Option, + /// 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, } @@ -563,19 +561,13 @@ mod speciation { fitness_fn: F, speciation_threshold: f32, keep_threshold: f32, - observer: Option, + observer: O, + ctx: ::Context, ) -> Self { - if !(0.0..=1.0).contains(&speciation_threshold) { - panic!("Speciation threshold must be between 0.0 and 1.0"); - } - if !(0.0..=1.0).contains(&keep_threshold) { - panic!("Keep threshold must be between 0.0 and 1.0"); - } Self { - fitness_fn, speciation_threshold, - keep_threshold, - observer, + inner: FitnessEliminator::new(fitness_fn, keep_threshold, observer), + ctx, _marker: std::marker::PhantomData, } } @@ -585,27 +577,28 @@ mod speciation { pub fn from_fitness_eliminator( fitness_eliminator: FitnessEliminator, speciation_threshold: f32, + ctx: ::Context, ) -> Self { - Self::new( - fitness_eliminator.fitness_fn, + Self { speciation_threshold, - fitness_eliminator.threshold, - Some(fitness_eliminator.observer), - ) + 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); + 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; for index in species { let genome = &genomes[index]; - let fitness = self.fitness_fn.fitness(genome) / len; + let fitness = self.inner.fitness_fn.fitness(genome) / len; fitnesses[index] = fitness; } } @@ -620,19 +613,17 @@ mod speciation { /// 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); + let population = SpeciatedPopulation::from_genomes(&genomes, self.speciation_threshold, &self.ctx); - // Create fitnesses array with default values let mut fitnesses = vec![0.0; genomes.len()]; - // Process species sequentially, but within each species compute fitnesses in parallel for species in population.species { let len = species.len() as f32; let updates: Vec<(usize, f32)> = species .par_iter() .map(|&index| { let genome = &genomes[index]; - let fitness = self.fitness_fn.fitness(genome) / len; + let fitness = self.inner.fitness_fn.fitness(genome) / len; (index, fitness) }) .collect(); @@ -642,7 +633,6 @@ mod speciation { } } - // Pair genomes with fitnesses and sort let mut result: Vec<(G, f32)> = genomes.into_iter().zip(fitnesses.into_iter()).collect(); result.sort_by(|(_a, afit), (_b, bfit)| bfit.partial_cmp(afit).unwrap()); @@ -659,7 +649,7 @@ mod speciation { #[cfg(not(feature = "rayon"))] fn eliminate(&mut self, genomes: Vec) -> Vec { let mut fitnesses = self.calculate_and_sort(genomes); - let median_index = (fitnesses.len() as f32) * self.keep_threshold; + let median_index = (fitnesses.len() as f32) * self.inner.threshold; fitnesses.truncate(median_index as usize + 1); fitnesses.into_iter().map(|(g, _)| g).collect() } @@ -667,7 +657,7 @@ mod speciation { #[cfg(feature = "rayon")] fn eliminate(&mut self, genomes: Vec) -> Vec { let mut fitnesses = self.calculate_and_sort(genomes); - let median_index = (fitnesses.len() as f32) * self.keep_threshold; + 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() } diff --git a/genetic-rs-common/src/builtin/repopulator.rs b/genetic-rs-common/src/builtin/repopulator.rs index 5f13994..25a0f30 100644 --- a/genetic-rs-common/src/builtin/repopulator.rs +++ b/genetic-rs-common/src/builtin/repopulator.rs @@ -157,43 +157,59 @@ pub use crossover::*; #[cfg(feature = "speciation")] mod speciation { - use std::collections::HashMap; - use rand::RngExt; + use crate::speciation::{Speciated, SpeciatedPopulation}; + use super::*; - /// 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. + /// 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. + DoNothing, - /// Get/calculate this genome's species. - fn species(&self) -> Self::Species; + /// Perform crossover between the genome and itself to create a new member of the species. This can help prevent extinction while still introducing some variation, but may be more computationally expensive than cloning. + SelfCrossover, } /// 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, + + /// The threshold used to determine if a genome belongs in a species. + /// See [`SpeciatedPopulation::threshold`] for more info. + pub speciation_threshold: f32, - /// 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 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 { + 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_repopulator(inner: CrossoverRepopulator, threshold: f32, action_if_isolated: ActionIfIsolated, ctx: ::Context) -> Self { Self { - crossover: CrossoverRepopulator::new(mutation_rate, ctx), - allow_emergency_repr, + inner, + ctx, + speciation_threshold: threshold, + action_if_isolated, _marker: std::marker::PhantomData, } } @@ -203,60 +219,42 @@ 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); - } - - 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; - } - - for (i, &parent1) in spec.iter().enumerate() { - let mut j = rng.random_range(1..spec.len()); - if j == i { - j = 0; - } - 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"); + let population = SpeciatedPopulation::from_genomes(&genomes, self.speciation_threshold, &self.ctx); + + 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::SelfCrossover => { + let child = parent1.crossover(parent1, &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]]; - genomes.extend(new_genomes); + let child = parent1.crossover(parent2, &self.inner.ctx, self.inner.mutation_rate, &mut rng); + genomes.push(child); + + i += 1; + } } } } diff --git a/genetic-rs-common/src/speciation.rs b/genetic-rs-common/src/speciation.rs index 24729a8..2945c03 100644 --- a/genetic-rs-common/src/speciation.rs +++ b/genetic-rs-common/src/speciation.rs @@ -1,5 +1,9 @@ /// 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 @@ -8,7 +12,7 @@ pub trait Speciated { /// 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) -> f32; + fn divergence(&self, other: &Self, ctx: &Self::Context) -> f32; } /// A population of genomes that have been separated into species. @@ -26,8 +30,8 @@ pub struct SpeciatedPopulation { 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]) -> bool { - if let Some(species) = self.get_species_mut(index, genomes) { + 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; } @@ -38,22 +42,22 @@ impl SpeciatedPopulation { /// 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) -> Self { + 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); + 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]) -> Option<&Vec> { + pub fn get_species(&self, index: usize, genomes: &[G], ctx: &G::Context) -> Option<&Vec> { let genome = &genomes[index]; for species in &self.species { - if genome.divergence(&genomes[species[0]]) < self.threshold { + if genome.divergence(&genomes[species[0]], ctx) < self.threshold { return Some(species); } } @@ -65,13 +69,61 @@ impl SpeciatedPopulation { &mut self, index: usize, genomes: &[G], + ctx: &G::Context, ) -> Option<&mut Vec> { let genome = &genomes[index]; for species in &mut self.species { - if genome.divergence(&genomes[species[0]]) < self.threshold { + if genome.divergence(&genomes[species[0]], ctx) < self.threshold { return Some(species); } } None } -} + + /// 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] += 1; + if idx_in_species[species_i] >= cur_species.len() { + idx_in_species[species_i] = 0; + 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`]. + 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 genome_index = cur_species[idx_in_species[species_i]]; + idx_in_species[species_i] += 1; + if idx_in_species[species_i] >= cur_species.len() { + idx_in_species[species_i] = 0; + species_i = (species_i + 1) % species.len(); + } + Some((species_i, genome_index)) + }) + } +} \ No newline at end of file From a32cd23b1ac71c93e4eaf4fa5c40dd265bf2170e Mon Sep 17 00:00:00 2001 From: Tristan Murphy <72839119+HyperCodec@users.noreply.github.com> Date: Mon, 9 Mar 2026 17:16:48 +0000 Subject: [PATCH 04/17] doc changes --- genetic-rs-common/src/builtin/repopulator.rs | 5 ++++- genetic-rs-common/src/speciation.rs | 1 + 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/genetic-rs-common/src/builtin/repopulator.rs b/genetic-rs-common/src/builtin/repopulator.rs index 25a0f30..b31c970 100644 --- a/genetic-rs-common/src/builtin/repopulator.rs +++ b/genetic-rs-common/src/builtin/repopulator.rs @@ -167,9 +167,12 @@ mod speciation { /// 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. + /// Note that if all species have only one member (not likely, but possible), + /// this can result in the repopulator hanging. DoNothing, - /// Perform crossover between the genome and itself to create a new member of the species. This can help prevent extinction while still introducing some variation, but may be more computationally expensive than cloning. + /// 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. SelfCrossover, } diff --git a/genetic-rs-common/src/speciation.rs b/genetic-rs-common/src/speciation.rs index 2945c03..443f10a 100644 --- a/genetic-rs-common/src/speciation.rs +++ b/genetic-rs-common/src/speciation.rs @@ -106,6 +106,7 @@ impl SpeciatedPopulation { /// 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()]; From c6876aeed2c732a9149abc3df90d128bbdef5dda Mon Sep 17 00:00:00 2001 From: Tristan Murphy <72839119+HyperCodec@users.noreply.github.com> Date: Mon, 9 Mar 2026 18:23:20 +0000 Subject: [PATCH 05/17] write speciation example --- genetic-rs-common/src/builtin/eliminator.rs | 21 +++- genetic-rs-common/src/builtin/repopulator.rs | 70 ++++++++++- genetic-rs/examples/speciation.rs | 120 ++++++++++++++----- 3 files changed, 173 insertions(+), 38 deletions(-) diff --git a/genetic-rs-common/src/builtin/eliminator.rs b/genetic-rs-common/src/builtin/eliminator.rs index d0945d6..0a5ad02 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>( @@ -596,10 +606,15 @@ mod speciation { 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) / len; - fitnesses[index] = fitness; + let fitness = self.inner.fitness_fn.fitness(genome); + if fitness < 0.0 { + fitnesses[index] = fitness * len; + } else { + fitnesses[index] = fitness / len; + } } } @@ -649,6 +664,7 @@ mod speciation { #[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() @@ -657,6 +673,7 @@ mod speciation { #[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() diff --git a/genetic-rs-common/src/builtin/repopulator.rs b/genetic-rs-common/src/builtin/repopulator.rs index b31c970..30902b0 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")] @@ -173,7 +183,15 @@ mod speciation { /// 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. - SelfCrossover, + 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. @@ -207,7 +225,7 @@ mod speciation { } /// Creates a new [`SpeciatedCrossoverRepopulator`] from an existing [`CrossoverRepopulator`], using the same mutation settings. - pub fn from_crossover_repopulator(inner: CrossoverRepopulator, threshold: f32, action_if_isolated: ActionIfIsolated, ctx: ::Context) -> Self { + pub fn from_crossover(inner: CrossoverRepopulator, threshold: f32, action_if_isolated: ActionIfIsolated, ctx: ::Context) -> Self { Self { inner, ctx, @@ -238,11 +256,46 @@ mod speciation { if species.len() < 2 { match self.action_if_isolated { ActionIfIsolated::DoNothing => continue, - ActionIfIsolated::SelfCrossover => { + ActionIfIsolated::CrossoverSelf => { let child = parent1.crossover(parent1, &self.inner.ctx, self.inner.mutation_rate, &mut rng); genomes.push(child); i += 1; continue; + }, + 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..genomes.len()); + 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; } } } @@ -260,6 +313,17 @@ mod speciation { } } } + + 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()) + } + } } #[cfg(feature = "speciation")] diff --git a/genetic-rs/examples/speciation.rs b/genetic-rs/examples/speciation.rs index 662ee45..43c2f78 100644 --- a/genetic-rs/examples/speciation.rs +++ b/genetic-rs/examples/speciation.rs @@ -1,26 +1,52 @@ 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 +54,80 @@ 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. + 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]); } From f1a0fe7bca69036d9fe2ef5804a18d3dbec5a550 Mon Sep 17 00:00:00 2001 From: Tristan Murphy <72839119+HyperCodec@users.noreply.github.com> Date: Mon, 9 Mar 2026 18:23:32 +0000 Subject: [PATCH 06/17] cargo fmt --- genetic-rs-common/src/builtin/eliminator.rs | 6 ++- genetic-rs-common/src/builtin/repopulator.rs | 55 ++++++++++++++++---- genetic-rs-common/src/speciation.rs | 20 +++++-- genetic-rs/examples/speciation.rs | 31 ++++++++--- 4 files changed, 88 insertions(+), 24 deletions(-) diff --git a/genetic-rs-common/src/builtin/eliminator.rs b/genetic-rs-common/src/builtin/eliminator.rs index 0a5ad02..7ba8c1f 100644 --- a/genetic-rs-common/src/builtin/eliminator.rs +++ b/genetic-rs-common/src/builtin/eliminator.rs @@ -601,7 +601,8 @@ mod speciation { /// 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 population = + SpeciatedPopulation::from_genomes(&genomes, self.speciation_threshold, &self.ctx); let mut fitnesses = vec![0.0; genomes.len()]; for species in population.species { @@ -628,7 +629,8 @@ mod speciation { /// 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 population = + SpeciatedPopulation::from_genomes(&genomes, self.speciation_threshold, &self.ctx); let mut fitnesses = vec![0.0; genomes.len()]; diff --git a/genetic-rs-common/src/builtin/repopulator.rs b/genetic-rs-common/src/builtin/repopulator.rs index 30902b0..dcb8c93 100644 --- a/genetic-rs-common/src/builtin/repopulator.rs +++ b/genetic-rs-common/src/builtin/repopulator.rs @@ -214,7 +214,13 @@ mod speciation { impl SpeciatedCrossoverRepopulator { /// Creates a new [`SpeciatedCrossoverRepopulator`]. - pub fn new(mutation_rate: f32, threshold: f32, action_if_isolated: ActionIfIsolated, crossover_ctx: ::Context, spec_ctx: ::Context) -> Self { + pub fn new( + mutation_rate: f32, + threshold: f32, + action_if_isolated: ActionIfIsolated, + crossover_ctx: ::Context, + spec_ctx: ::Context, + ) -> Self { Self { inner: CrossoverRepopulator::new(mutation_rate, crossover_ctx), ctx: spec_ctx, @@ -225,7 +231,12 @@ mod speciation { } /// 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 { + pub fn from_crossover( + inner: CrossoverRepopulator, + threshold: f32, + action_if_isolated: ActionIfIsolated, + ctx: ::Context, + ) -> Self { Self { inner, ctx, @@ -243,11 +254,12 @@ mod speciation { fn repopulate(&mut self, genomes: &mut Vec, target_size: usize) { let initial_size = genomes.len(); let mut rng = rand::rng(); - let population = SpeciatedPopulation::from_genomes(&genomes, self.speciation_threshold, &self.ctx); + let population = + SpeciatedPopulation::from_genomes(&genomes, self.speciation_threshold, &self.ctx); 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(); @@ -257,11 +269,16 @@ mod speciation { match self.action_if_isolated { ActionIfIsolated::DoNothing => continue, ActionIfIsolated::CrossoverSelf => { - let child = parent1.crossover(parent1, &self.inner.ctx, self.inner.mutation_rate, &mut rng); + let child = parent1.crossover( + parent1, + &self.inner.ctx, + self.inner.mutation_rate, + &mut rng, + ); genomes.push(child); i += 1; continue; - }, + } ActionIfIsolated::CrossoverSimilarSpecies => { let mut best_species_i = 0; let mut best_divergence = f32::MAX; @@ -280,11 +297,16 @@ mod speciation { 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); + 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..genomes.len()); if j == genome_i { @@ -292,7 +314,12 @@ mod speciation { } let parent2 = &genomes[j]; - let child = parent1.crossover(parent2, &self.inner.ctx, self.inner.mutation_rate, &mut rng); + let child = parent1.crossover( + parent2, + &self.inner.ctx, + self.inner.mutation_rate, + &mut rng, + ); genomes.push(child); i += 1; continue; @@ -306,7 +333,8 @@ mod speciation { } let parent2 = &genomes[species[j]]; - let child = parent1.crossover(parent2, &self.inner.ctx, self.inner.mutation_rate, &mut rng); + let child = + parent1.crossover(parent2, &self.inner.ctx, self.inner.mutation_rate, &mut rng); genomes.push(child); i += 1; @@ -321,7 +349,12 @@ mod speciation { ::Context: Default, { fn default() -> Self { - Self::from_crossover(CrossoverRepopulator::default(), 0.1, ActionIfIsolated::CrossoverSimilarSpecies, ::Context::default()) + Self::from_crossover( + CrossoverRepopulator::default(), + 0.1, + ActionIfIsolated::CrossoverSimilarSpecies, + ::Context::default(), + ) } } } diff --git a/genetic-rs-common/src/speciation.rs b/genetic-rs-common/src/speciation.rs index 443f10a..cb68592 100644 --- a/genetic-rs-common/src/speciation.rs +++ b/genetic-rs-common/src/speciation.rs @@ -30,7 +30,12 @@ pub struct SpeciatedPopulation { 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 { + 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; @@ -54,7 +59,12 @@ impl SpeciatedPopulation { } /// Gets the species that a genome belongs to, if any. - pub fn get_species(&self, index: usize, genomes: &[G], ctx: &G::Context) -> Option<&Vec> { + pub fn get_species( + &self, + index: usize, + genomes: &[G], + ctx: &G::Context, + ) -> Option<&Vec> { let genome = &genomes[index]; for species in &self.species { if genome.divergence(&genomes[species[0]], ctx) < self.threshold { @@ -86,7 +96,7 @@ impl SpeciatedPopulation { 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; @@ -111,7 +121,7 @@ impl SpeciatedPopulation { 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; @@ -127,4 +137,4 @@ impl SpeciatedPopulation { Some((species_i, genome_index)) }) } -} \ No newline at end of file +} diff --git a/genetic-rs/examples/speciation.rs b/genetic-rs/examples/speciation.rs index 43c2f78..a31811f 100644 --- a/genetic-rs/examples/speciation.rs +++ b/genetic-rs/examples/speciation.rs @@ -43,8 +43,12 @@ impl RandomlyMutable for MyGenome { impl Mitosis for MyGenome { type Context = (); - fn divide(&self, ctx: &::Context, rate: f32, rng: &mut impl rand::Rng) - -> Self { + fn divide( + &self, + ctx: &::Context, + rate: f32, + rng: &mut impl rand::Rng, + ) -> Self { let mut child = self.clone(); child.mutate(ctx, rate, rng); child @@ -54,7 +58,13 @@ impl Mitosis for MyGenome { impl Crossover for MyGenome { type Context = (); - fn crossover(&self, other: &Self, ctx: &Self::Context, rate: f32, rng: &mut impl rand::Rng) -> Self { + 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 @@ -105,7 +115,7 @@ fn print_fitnesses(fitnesses: &[(MyGenome, f32)]) { // these values are divided by the number of genomes in the species. let hi = fitnesses[0].1; let med = fitnesses[fitnesses.len() / 2].1; - let lo = fitnesses[fitnesses.len()-1].1; + let lo = fitnesses[fitnesses.len() - 1].1; println!("hi: {hi} med: {med} lo: {lo}"); } @@ -122,8 +132,17 @@ fn main() { let mut sim = GeneticSim::new( Vec::gen_random(&mut rng, 100), - SpeciatedFitnessEliminator::from_fitness_eliminator(fitness_eliminator, SPECIATION_THRESHOLD, ()), - SpeciatedCrossoverRepopulator::from_crossover(crossover_rep, SPECIATION_THRESHOLD, ActionIfIsolated::CrossoverSimilarSpecies, ()) + SpeciatedFitnessEliminator::from_fitness_eliminator( + fitness_eliminator, + SPECIATION_THRESHOLD, + (), + ), + SpeciatedCrossoverRepopulator::from_crossover( + crossover_rep, + SPECIATION_THRESHOLD, + ActionIfIsolated::CrossoverSimilarSpecies, + (), + ), ); sim.perform_generations(100); From b3b504f3199141985ce278971ab7d24115adc866 Mon Sep 17 00:00:00 2001 From: Tristan Murphy <72839119+HyperCodec@users.noreply.github.com> Date: Mon, 9 Mar 2026 18:26:36 +0000 Subject: [PATCH 07/17] fix clippy warnigns --- genetic-rs-common/src/builtin/eliminator.rs | 4 ++-- genetic-rs-common/src/builtin/repopulator.rs | 2 +- genetic-rs-common/src/speciation.rs | 14 ++------------ 3 files changed, 5 insertions(+), 15 deletions(-) diff --git a/genetic-rs-common/src/builtin/eliminator.rs b/genetic-rs-common/src/builtin/eliminator.rs index 7ba8c1f..4e707c7 100644 --- a/genetic-rs-common/src/builtin/eliminator.rs +++ b/genetic-rs-common/src/builtin/eliminator.rs @@ -538,7 +538,7 @@ pub use knockout::*; mod speciation { use crate::{prelude::*, speciation::SpeciatedPopulation}; - //// An eliminator that attempts to preserve new experimental structures by dividing a genome's + /// 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, @@ -620,7 +620,7 @@ mod speciation { } let mut fitnesses: Vec<(G, f32)> = - genomes.into_iter().zip(fitnesses.into_iter()).collect(); + genomes.into_iter().zip(fitnesses).collect(); fitnesses.sort_by(|(_a, afit), (_b, bfit)| bfit.partial_cmp(afit).unwrap()); fitnesses } diff --git a/genetic-rs-common/src/builtin/repopulator.rs b/genetic-rs-common/src/builtin/repopulator.rs index dcb8c93..5c2a9ce 100644 --- a/genetic-rs-common/src/builtin/repopulator.rs +++ b/genetic-rs-common/src/builtin/repopulator.rs @@ -255,7 +255,7 @@ mod speciation { let initial_size = genomes.len(); let mut rng = rand::rng(); let population = - SpeciatedPopulation::from_genomes(&genomes, self.speciation_threshold, &self.ctx); + SpeciatedPopulation::from_genomes(genomes, self.speciation_threshold, &self.ctx); let amount_to_make = target_size - initial_size; let mut species_cycle = population.round_robin_enumerate(); diff --git a/genetic-rs-common/src/speciation.rs b/genetic-rs-common/src/speciation.rs index cb68592..95ae24d 100644 --- a/genetic-rs-common/src/speciation.rs +++ b/genetic-rs-common/src/speciation.rs @@ -66,12 +66,7 @@ impl SpeciatedPopulation { ctx: &G::Context, ) -> Option<&Vec> { let genome = &genomes[index]; - for species in &self.species { - if genome.divergence(&genomes[species[0]], ctx) < self.threshold { - return Some(species); - } - } - None + 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. @@ -82,12 +77,7 @@ impl SpeciatedPopulation { ctx: &G::Context, ) -> Option<&mut Vec> { let genome = &genomes[index]; - for species in &mut self.species { - if genome.divergence(&genomes[species[0]], ctx) < self.threshold { - return Some(species); - } - } - None + self.species.iter_mut().find(|species| genome.divergence(&genomes[species[0]], ctx) < self.threshold) } /// Round robin cyclic iterator over the genomes in this population. From b610ff582d2ec89576ab45e5e7c60865f7399358 Mon Sep 17 00:00:00 2001 From: Tristan Murphy <72839119+HyperCodec@users.noreply.github.com> Date: Mon, 9 Mar 2026 18:29:28 +0000 Subject: [PATCH 08/17] fix rayon feature compile error --- genetic-rs-common/src/builtin/eliminator.rs | 22 ++++++++++----------- 1 file changed, 10 insertions(+), 12 deletions(-) diff --git a/genetic-rs-common/src/builtin/eliminator.rs b/genetic-rs-common/src/builtin/eliminator.rs index 4e707c7..52e3b9a 100644 --- a/genetic-rs-common/src/builtin/eliminator.rs +++ b/genetic-rs-common/src/builtin/eliminator.rs @@ -636,22 +636,20 @@ mod speciation { for species in population.species { let len = species.len() as f32; - let updates: Vec<(usize, f32)> = species - .par_iter() - .map(|&index| { - let genome = &genomes[index]; - let fitness = self.inner.fitness_fn.fitness(genome) / len; - (index, fitness) - }) - .collect(); - - for (index, fitness) in updates { - fitnesses[index] = fitness; + 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.into_iter()).collect(); + genomes.into_iter().zip(fitnesses).collect(); result.sort_by(|(_a, afit), (_b, bfit)| bfit.partial_cmp(afit).unwrap()); result } From 64c53141dc52bd05e0a347bc2c1938d04bc7860b Mon Sep 17 00:00:00 2001 From: Tristan Murphy <72839119+HyperCodec@users.noreply.github.com> Date: Mon, 9 Mar 2026 18:30:06 +0000 Subject: [PATCH 09/17] cargo fmt --- genetic-rs-common/src/builtin/eliminator.rs | 6 ++---- genetic-rs-common/src/speciation.rs | 8 ++++++-- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/genetic-rs-common/src/builtin/eliminator.rs b/genetic-rs-common/src/builtin/eliminator.rs index 52e3b9a..1b0626f 100644 --- a/genetic-rs-common/src/builtin/eliminator.rs +++ b/genetic-rs-common/src/builtin/eliminator.rs @@ -619,8 +619,7 @@ mod speciation { } } - let mut fitnesses: Vec<(G, f32)> = - genomes.into_iter().zip(fitnesses).collect(); + 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 } @@ -648,8 +647,7 @@ mod speciation { } } - let mut result: Vec<(G, f32)> = - genomes.into_iter().zip(fitnesses).collect(); + 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 } diff --git a/genetic-rs-common/src/speciation.rs b/genetic-rs-common/src/speciation.rs index 95ae24d..963b2a9 100644 --- a/genetic-rs-common/src/speciation.rs +++ b/genetic-rs-common/src/speciation.rs @@ -66,7 +66,9 @@ impl SpeciatedPopulation { ctx: &G::Context, ) -> Option<&Vec> { let genome = &genomes[index]; - self.species.iter().find(|species| genome.divergence(&genomes[species[0]], ctx) < self.threshold) + 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. @@ -77,7 +79,9 @@ impl SpeciatedPopulation { ctx: &G::Context, ) -> Option<&mut Vec> { let genome = &genomes[index]; - self.species.iter_mut().find(|species| genome.divergence(&genomes[species[0]], ctx) < self.threshold) + self.species + .iter_mut() + .find(|species| genome.divergence(&genomes[species[0]], ctx) < self.threshold) } /// Round robin cyclic iterator over the genomes in this population. From e135cf1ec1da8e05556cfe06ba59411bd34de3d1 Mon Sep 17 00:00:00 2001 From: Tristan Murphy <72839119+HyperCodec@users.noreply.github.com> Date: Tue, 10 Mar 2026 11:27:08 +0000 Subject: [PATCH 10/17] implement comment fix --- genetic-rs/examples/speciation.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/genetic-rs/examples/speciation.rs b/genetic-rs/examples/speciation.rs index a31811f..a9f3635 100644 --- a/genetic-rs/examples/speciation.rs +++ b/genetic-rs/examples/speciation.rs @@ -112,7 +112,8 @@ fn fitness(genome: &MyGenome) -> f32 { fn print_fitnesses(fitnesses: &[(MyGenome, f32)]) { // note that with SpeciatedFitnessEliminator, - // these values are divided by the number of genomes in the species. + // 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; From 424c477813cf1a32f0e6a15645dc5301b0944ee6 Mon Sep 17 00:00:00 2001 From: Tristan Murphy <72839119+HyperCodec@users.noreply.github.com> Date: Tue, 10 Mar 2026 11:28:54 +0000 Subject: [PATCH 11/17] fix potential edge case + shitty doc comment (AI tab complete fucked me over) --- genetic-rs-common/src/builtin/eliminator.rs | 1 - genetic-rs-common/src/builtin/repopulator.rs | 4 ++++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/genetic-rs-common/src/builtin/eliminator.rs b/genetic-rs-common/src/builtin/eliminator.rs index 1b0626f..d9c4e08 100644 --- a/genetic-rs-common/src/builtin/eliminator.rs +++ b/genetic-rs-common/src/builtin/eliminator.rs @@ -566,7 +566,6 @@ mod speciation { O: FeatureBoundedFitnessObserver, { /// Creates a new [`SpeciatedFitnessEliminator`] with a given fitness function and thresholds. - /// Panics if the thresholds are not between 0.0 and 1.0. pub fn new( fitness_fn: F, speciation_threshold: f32, diff --git a/genetic-rs-common/src/builtin/repopulator.rs b/genetic-rs-common/src/builtin/repopulator.rs index 5c2a9ce..99a46ca 100644 --- a/genetic-rs-common/src/builtin/repopulator.rs +++ b/genetic-rs-common/src/builtin/repopulator.rs @@ -253,6 +253,10 @@ mod speciation { { fn repopulate(&mut self, genomes: &mut Vec, target_size: usize) { let initial_size = genomes.len(); + if initial_size >= target_size { + return; + } + let mut rng = rand::rng(); let population = SpeciatedPopulation::from_genomes(genomes, self.speciation_threshold, &self.ctx); From eb97a1602b275c4b8e6dfa76bbde40ea8aadee9c Mon Sep 17 00:00:00 2001 From: Tristan Murphy <72839119+HyperCodec@users.noreply.github.com> Date: Tue, 10 Mar 2026 11:31:26 +0000 Subject: [PATCH 12/17] fix found robin iterator --- genetic-rs-common/src/speciation.rs | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/genetic-rs-common/src/speciation.rs b/genetic-rs-common/src/speciation.rs index 963b2a9..8a630ec 100644 --- a/genetic-rs-common/src/speciation.rs +++ b/genetic-rs-common/src/speciation.rs @@ -98,11 +98,8 @@ impl SpeciatedPopulation { let cur_species = &species[species_i]; let genome_index = cur_species[idx_in_species[species_i]]; - idx_in_species[species_i] += 1; - if idx_in_species[species_i] >= cur_species.len() { - idx_in_species[species_i] = 0; - species_i = (species_i + 1) % species.len(); - } + idx_in_species[species_i] = (idx_in_species[species_i] + 1) % cur_species.len(); + species_i = (species_i + 1) % species.len(); Some(genome_index) }) } From f6ae0f3195f8792d54280d4de159cbbd0f174502 Mon Sep 17 00:00:00 2001 From: Tristan Murphy <72839119+HyperCodec@users.noreply.github.com> Date: Tue, 10 Mar 2026 11:32:44 +0000 Subject: [PATCH 13/17] fix enumerated round robin --- genetic-rs-common/src/speciation.rs | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/genetic-rs-common/src/speciation.rs b/genetic-rs-common/src/speciation.rs index 8a630ec..6dd8fcb 100644 --- a/genetic-rs-common/src/speciation.rs +++ b/genetic-rs-common/src/speciation.rs @@ -119,13 +119,11 @@ impl SpeciatedPopulation { } 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] += 1; - if idx_in_species[species_i] >= cur_species.len() { - idx_in_species[species_i] = 0; - species_i = (species_i + 1) % species.len(); - } - Some((species_i, genome_index)) + 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)) }) } } From 362de191b447cffb4117c97385f903ef3b50b20f Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Tue, 10 Mar 2026 11:41:59 +0000 Subject: [PATCH 14/17] Initial plan From 853ab6cbc1c6761c277a5072793bb411756c8de0 Mon Sep 17 00:00:00 2001 From: Tristan Murphy <72839119+HyperCodec@users.noreply.github.com> Date: Tue, 10 Mar 2026 11:42:36 +0000 Subject: [PATCH 15/17] fix CrossoverRandom affecting new genomes --- genetic-rs-common/src/builtin/repopulator.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/genetic-rs-common/src/builtin/repopulator.rs b/genetic-rs-common/src/builtin/repopulator.rs index 99a46ca..afe580c 100644 --- a/genetic-rs-common/src/builtin/repopulator.rs +++ b/genetic-rs-common/src/builtin/repopulator.rs @@ -312,7 +312,7 @@ mod speciation { continue; } ActionIfIsolated::CrossoverRandom => { - let mut j = rng.random_range(1..genomes.len()); + let mut j = rng.random_range(1..initial_size); if j == genome_i { j = 0; } From 820b77f181b5c14e49f473de37598642c9f927c9 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Tue, 10 Mar 2026 11:44:39 +0000 Subject: [PATCH 16/17] Fix ActionIfIsolated::DoNothing hang when all species are isolated Co-authored-by: HyperCodec <72839119+HyperCodec@users.noreply.github.com> --- genetic-rs-common/src/builtin/repopulator.rs | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/genetic-rs-common/src/builtin/repopulator.rs b/genetic-rs-common/src/builtin/repopulator.rs index 99a46ca..3fad2a8 100644 --- a/genetic-rs-common/src/builtin/repopulator.rs +++ b/genetic-rs-common/src/builtin/repopulator.rs @@ -177,8 +177,9 @@ mod speciation { /// 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. - /// Note that if all species have only one member (not likely, but possible), - /// this can result in the repopulator hanging. + /// 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. @@ -261,6 +262,17 @@ mod speciation { let population = SpeciatedPopulation::from_genomes(genomes, self.speciation_threshold, &self.ctx); + // When DoNothing is selected, the loop skips isolated species without + // making progress. If *all* species are isolated there are no eligible + // pairs and the loop would never terminate. Fall back to the inner + // repopulator in that case. + if matches!(self.action_if_isolated, ActionIfIsolated::DoNothing) + && !population.species.iter().any(|s| s.len() >= 2) + { + self.inner.repopulate(genomes, target_size); + return; + } + let amount_to_make = target_size - initial_size; let mut species_cycle = population.round_robin_enumerate(); From 12340c1dffe24a71cdf9d815f84eebb76cb64c60 Mon Sep 17 00:00:00 2001 From: Tristan Murphy <72839119+HyperCodec@users.noreply.github.com> Date: Tue, 10 Mar 2026 11:52:16 +0000 Subject: [PATCH 17/17] fix doc comment --- genetic-rs-common/src/builtin/repopulator.rs | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/genetic-rs-common/src/builtin/repopulator.rs b/genetic-rs-common/src/builtin/repopulator.rs index 3fad2a8..624719c 100644 --- a/genetic-rs-common/src/builtin/repopulator.rs +++ b/genetic-rs-common/src/builtin/repopulator.rs @@ -177,7 +177,7 @@ mod speciation { /// 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 + /// 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, @@ -262,10 +262,7 @@ mod speciation { let population = SpeciatedPopulation::from_genomes(genomes, self.speciation_threshold, &self.ctx); - // When DoNothing is selected, the loop skips isolated species without - // making progress. If *all* species are isolated there are no eligible - // pairs and the loop would never terminate. Fall back to the inner - // repopulator in that case. + // 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) {