From a7b8d8f55ea27b784e8764a6ffcd1b63912e0cb9 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Tue, 10 Mar 2026 12:04:35 +0000 Subject: [PATCH 1/4] Initial plan From 15a3dd06ba3e79a66ee17d45ab881f6d4b56271c Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Tue, 10 Mar 2026 12:11:56 +0000 Subject: [PATCH 2/4] Add examples to CI workflow and register missing example metadata in Cargo.toml Co-authored-by: HyperCodec <72839119+HyperCodec@users.noreply.github.com> --- .github/workflows/ci-cd.yml | 18 ++++++++++++++++++ genetic-rs/Cargo.toml | 12 ++++++++++-- 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ci-cd.yml b/.github/workflows/ci-cd.yml index c999d27..43c103f 100644 --- a/.github/workflows/ci-cd.yml +++ b/.github/workflows/ci-cd.yml @@ -24,6 +24,24 @@ jobs: - name: Run Clippy run: cargo clippy --all-features -- -D warnings + examples: + runs-on: ubuntu-latest + name: Run Examples + permissions: + contents: read + steps: + - uses: actions/checkout@v4 + - name: Run readme_ex example + run: cargo run --example readme_ex --features builtin,genrand + - name: Run crossover example + run: cargo run --example crossover --features crossover,genrand + - name: Run knockout example + run: cargo run --example knockout --features knockout,crossover,genrand + - name: Run derive example + run: cargo run --example derive --features derive + - name: Run speciation example + run: cargo run --example speciation --features speciation,genrand + fmt: runs-on: ubuntu-latest name: Formatting Checks diff --git a/genetic-rs/Cargo.toml b/genetic-rs/Cargo.toml index 25d76c3..e9114f0 100644 --- a/genetic-rs/Cargo.toml +++ b/genetic-rs/Cargo.toml @@ -35,13 +35,21 @@ unexpected_cfgs = { level = "allow", check-cfg = ["cfg(publish)", "cfg(docsrs)"] [dev-dependencies] rand = "0.10.0" +[[example]] +name = "readme_ex" +required-features = ["builtin", "genrand"] + [[example]] name = "crossover" -required-features = ["crossover"] +required-features = ["crossover", "genrand"] + +[[example]] +name = "knockout" +required-features = ["knockout", "crossover", "genrand"] [[example]] name = "speciation" -required-features = ["speciation"] +required-features = ["speciation", "genrand"] [[example]] name = "derive" From 2641263c9129fb6378106efc3a08c1c65cc53d4e Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Tue, 10 Mar 2026 12:29:29 +0000 Subject: [PATCH 3/4] Add comprehensive integration test suite covering all major invariants Co-authored-by: HyperCodec <72839119+HyperCodec@users.noreply.github.com> --- genetic-rs/Cargo.toml | 16 ++ genetic-rs/tests/knockout.rs | 155 +++++++++++++++++ genetic-rs/tests/repopulator.rs | 154 +++++++++++++++++ genetic-rs/tests/simulation.rs | 226 ++++++++++++++++++++++++ genetic-rs/tests/speciation.rs | 295 ++++++++++++++++++++++++++++++++ 5 files changed, 846 insertions(+) create mode 100644 genetic-rs/tests/knockout.rs create mode 100644 genetic-rs/tests/repopulator.rs create mode 100644 genetic-rs/tests/simulation.rs create mode 100644 genetic-rs/tests/speciation.rs diff --git a/genetic-rs/Cargo.toml b/genetic-rs/Cargo.toml index e9114f0..58d03c7 100644 --- a/genetic-rs/Cargo.toml +++ b/genetic-rs/Cargo.toml @@ -55,6 +55,22 @@ required-features = ["speciation", "genrand"] name = "derive" required-features = ["derive"] +[[test]] +name = "simulation" +required-features = ["builtin", "genrand"] + +[[test]] +name = "knockout" +required-features = ["knockout", "genrand"] + +[[test]] +name = "repopulator" +required-features = ["crossover", "genrand"] + +[[test]] +name = "speciation" +required-features = ["speciation", "genrand"] + [[test]] name = "derive_macros" required-features = ["derive", "genrand", "crossover"] diff --git a/genetic-rs/tests/knockout.rs b/genetic-rs/tests/knockout.rs new file mode 100644 index 0000000..db950ef --- /dev/null +++ b/genetic-rs/tests/knockout.rs @@ -0,0 +1,155 @@ +//! Integration tests for [`KnockoutEliminator`], [`KnockoutWinner`], and +//! related types. + +use std::cmp::Ordering; + +use genetic_rs::prelude::*; + +// ───────────────────────────────────────────────────────────────────────────── +// Shared test genome +// ───────────────────────────────────────────────────────────────────────────── + +#[derive(Clone, Debug)] +struct Genome(f32); + +impl GenerateRandom for Genome { + fn gen_random(rng: &mut impl rand::Rng) -> Self { + Self(rng.random()) + } +} + +/// Knockout function that keeps the genome with the smaller value. +/// `a.total_cmp(&b)` returns `Less` when a < b, mapping to `KnockoutWinner::First` (a survives). +fn smaller_wins(a: &Genome, b: &Genome) -> KnockoutWinner { + a.0.total_cmp(&b.0).into() +} + +// ───────────────────────────────────────────────────────────────────────────── +// KnockoutWinner helpers +// ───────────────────────────────────────────────────────────────────────────── + +/// `!First == Second` and `!Second == First`. +#[test] +fn knockout_winner_not_impl() { + assert_eq!(!KnockoutWinner::First, KnockoutWinner::Second); + assert_eq!(!KnockoutWinner::Second, KnockoutWinner::First); +} + +/// `From` must map correctly. +#[test] +fn knockout_winner_from_ordering() { + assert_eq!(KnockoutWinner::from(Ordering::Less), KnockoutWinner::First); + assert_eq!(KnockoutWinner::from(Ordering::Equal), KnockoutWinner::First); + assert_eq!( + KnockoutWinner::from(Ordering::Greater), + KnockoutWinner::Second + ); +} + +/// `Into`: `First` → 0, `Second` → 1. +#[test] +fn knockout_winner_into_usize() { + assert_eq!(usize::from(KnockoutWinner::First), 0usize); + assert_eq!(usize::from(KnockoutWinner::Second), 1usize); +} + +// ───────────────────────────────────────────────────────────────────────────── +// KnockoutEliminator output-size invariants +// ───────────────────────────────────────────────────────────────────────────── + +/// With an even-sized population the output must be exactly half. +#[test] +fn knockout_output_half_size_even_input() { + let genomes: Vec = (0..10).map(|i| Genome(i as f32)).collect(); + let mut elim = KnockoutEliminator::new(smaller_wins, ActionIfOdd::Panic); + let survivors = elim.eliminate(genomes); + assert_eq!(survivors.len(), 5); +} + +/// `ActionIfOdd::KeepSingle` with 11 genomes: 1 bypasses contest + 5 winners = 6. +#[test] +fn knockout_action_if_odd_keep_single() { + let genomes: Vec = (0..11).map(|i| Genome(i as f32)).collect(); + let mut elim = KnockoutEliminator::new(smaller_wins, ActionIfOdd::KeepSingle); + let survivors = elim.eliminate(genomes); + assert_eq!(survivors.len(), 6); +} + +/// `ActionIfOdd::DeleteSingle` with 11 genomes: 1 is discarded + 5 winners = 5. +#[test] +fn knockout_action_if_odd_delete_single() { + let genomes: Vec = (0..11).map(|i| Genome(i as f32)).collect(); + let mut elim = KnockoutEliminator::new(smaller_wins, ActionIfOdd::DeleteSingle); + let survivors = elim.eliminate(genomes); + assert_eq!(survivors.len(), 5); +} + +/// `ActionIfOdd::Panic` must panic when given an odd number of genomes. +#[test] +#[should_panic] +fn knockout_action_if_odd_panic_panics() { + let genomes: Vec = (0..11).map(|i| Genome(i as f32)).collect(); + let mut elim = KnockoutEliminator::new(smaller_wins, ActionIfOdd::Panic); + let _ = elim.eliminate(genomes); +} + +/// With a population of 1, [`KnockoutEliminator`] must return it unchanged. +#[test] +fn knockout_single_genome_returns_unchanged() { + let genomes = vec![Genome(42.0)]; + let mut elim = KnockoutEliminator::new(smaller_wins, ActionIfOdd::Panic); + let survivors = elim.eliminate(genomes); + assert_eq!(survivors.len(), 1); + assert!((survivors[0].0 - 42.0).abs() < 1e-6); +} + +// ───────────────────────────────────────────────────────────────────────────── +// KnockoutEliminator correctness +// ───────────────────────────────────────────────────────────────────────────── + +/// In each pair `(a, b)` the correct genome must survive based on the knockout fn. +/// +/// With genomes [0, 1, 2, …, 9] and `smaller_wins`: +/// - Pairs: (0,1), (2,3), (4,5), (6,7), (8,9) +/// - `a < b` → `Less` → `First` → a survives → even-indexed values survive. +#[test] +fn knockout_correct_genome_survives() { + let genomes: Vec = (0..10).map(|i| Genome(i as f32)).collect(); + let mut elim = KnockoutEliminator::new(smaller_wins, ActionIfOdd::Panic); + let survivors = elim.eliminate(genomes); + + for g in &survivors { + assert!( + (g.0 as i32) % 2 == 0, + "expected even (smaller) value to survive each pair, got {}", + g.0 + ); + } +} + +// ───────────────────────────────────────────────────────────────────────────── +// FitnessKnockoutFn +// ───────────────────────────────────────────────────────────────────────────── + +/// [`FitnessKnockoutFn`] must delegate to the inner fitness function and +/// produce a consistent result based on the `afit.total_cmp(&bfit)` comparison. +/// +/// The `From` mapping is: +/// - `Less` → `First` (a survives — a had lower fitness) +/// - `Greater` → `Second` (b survives — b had lower fitness) +/// +/// This tests the actual implementation behaviour rather than any particular +/// notion of "higher fitness wins"; it guards against regressions in the +/// delegation and ordering logic. +#[test] +fn fitness_knockout_fn_delegates_to_fitness_fn() { + let ko_fn = FitnessKnockoutFn::new(|g: &Genome| g.0); + let a = Genome(1.0); + let b = Genome(9.0); + + // 1.0.total_cmp(&9.0) = Less → First (a survives) + assert_eq!(ko_fn.knockout(&a, &b), KnockoutWinner::First); + + // 9.0.total_cmp(&1.0) = Greater → Second (b survives) + assert_eq!(ko_fn.knockout(&b, &a), KnockoutWinner::Second); +} diff --git a/genetic-rs/tests/repopulator.rs b/genetic-rs/tests/repopulator.rs new file mode 100644 index 0000000..5ac2462 --- /dev/null +++ b/genetic-rs/tests/repopulator.rs @@ -0,0 +1,154 @@ +//! Integration tests for [`MitosisRepopulator`], [`CrossoverRepopulator`], +//! and the [`FromParent`] helper. + +use genetic_rs::prelude::*; + +// ───────────────────────────────────────────────────────────────────────────── +// Shared test genome +// ───────────────────────────────────────────────────────────────────────────── + +#[derive(Clone, Debug, PartialEq)] +struct Genome(f32); + +impl GenerateRandom for Genome { + fn gen_random(rng: &mut impl rand::Rng) -> Self { + Self(rng.random()) + } +} + +impl RandomlyMutable for Genome { + type Context = (); + + fn mutate(&mut self, _: &(), rate: f32, rng: &mut impl rand::Rng) { + self.0 += rng.random::() * rate; + } +} + +impl Mitosis for Genome { + type Context = (); + + fn divide(&self, ctx: &(), rate: f32, rng: &mut impl rand::Rng) -> Self { + let mut child = self.clone(); + child.mutate(ctx, rate, rng); + child + } +} + +/// Deterministic crossover: the child is exactly the average of its parents. +/// A zero mutation rate means no random component is added. +impl Crossover for Genome { + type Context = (); + + fn crossover(&self, other: &Self, _: &(), _rate: f32, _rng: &mut impl rand::Rng) -> Self { + Self((self.0 + other.0) / 2.0) + } +} + +fn fitness(g: &Genome) -> f32 { + g.0 +} + +// ───────────────────────────────────────────────────────────────────────────── +// MitosisRepopulator +// ───────────────────────────────────────────────────────────────────────────── + +/// The repopulator must grow the population back to the target size. +#[test] +fn mitosis_repopulator_fills_to_target() { + let mut rng = rand::rng(); + let mut genomes: Vec = Vec::gen_random(&mut rng, 5); + MitosisRepopulator::new(0.1, ()).repopulate(&mut genomes, 20); + assert_eq!(genomes.len(), 20); +} + +/// If the population is already at the target, it must not grow further. +#[test] +fn mitosis_repopulator_no_op_when_at_target() { + let mut rng = rand::rng(); + let mut genomes: Vec = Vec::gen_random(&mut rng, 10); + MitosisRepopulator::new(0.1, ()).repopulate(&mut genomes, 10); + assert_eq!(genomes.len(), 10); +} + +/// At mutation rate 0.0 each child must be an exact clone of its parent. +#[test] +fn mitosis_zero_mutation_rate_produces_clone() { + let parent = Genome(42.0); + let mut rng = rand::rng(); + let child = parent.divide(&(), 0.0, &mut rng); + assert_eq!(child, parent, "child at rate 0.0 must be identical to parent"); +} + +// ───────────────────────────────────────────────────────────────────────────── +// CrossoverRepopulator +// ───────────────────────────────────────────────────────────────────────────── + +/// The crossover repopulator must grow the population back to the target size. +#[test] +fn crossover_repopulator_fills_to_target() { + let mut rng = rand::rng(); + let mut genomes: Vec = Vec::gen_random(&mut rng, 5); + CrossoverRepopulator::new(0.1, ()).repopulate(&mut genomes, 20); + assert_eq!(genomes.len(), 20); +} + +/// If the population is already at the target, it must not grow further. +#[test] +fn crossover_repopulator_no_op_when_at_target() { + let mut rng = rand::rng(); + let mut genomes: Vec = Vec::gen_random(&mut rng, 10); + CrossoverRepopulator::new(0.1, ()).repopulate(&mut genomes, 10); + assert_eq!(genomes.len(), 10); +} + +/// Crossover child must equal the average of its parents when mutation rate is 0. +#[test] +fn crossover_child_is_average_of_parents() { + let p1 = Genome(2.0); + let p2 = Genome(4.0); + let mut rng = rand::rng(); + let child = p1.crossover(&p2, &(), 0.0, &mut rng); + assert!( + (child.0 - 3.0).abs() < 1e-6, + "expected child value 3.0, got {}", + child.0 + ); +} + +/// Population size stays constant when `GeneticSim` uses crossover over many generations. +#[test] +fn population_size_constant_with_crossover_sim() { + let mut rng = rand::rng(); + let initial_size = 30; + let mut sim = GeneticSim::new( + Vec::::gen_random(&mut rng, initial_size), + FitnessEliminator::new_without_observer(fitness), + CrossoverRepopulator::new(0.05, ()), + ); + sim.perform_generations(50); + assert_eq!(sim.genomes.len(), initial_size); +} + +// ───────────────────────────────────────────────────────────────────────────── +// FromParent +// ───────────────────────────────────────────────────────────────────────────── + +/// [`Vec::from_parent`] must produce exactly the requested number of genomes. +#[test] +fn from_parent_creates_correct_count() { + let parent = Genome(1.0); + let population = Vec::::from_parent(parent, 15, (), 0.0); + assert_eq!(population.len(), 15); +} + +/// The original parent must be the first element of the returned population. +#[test] +fn from_parent_includes_original_parent() { + let parent = Genome(7.0); + let population = Vec::::from_parent(parent.clone(), 5, (), 0.0); + assert_eq!( + population[0], + parent, + "the first element must be the original parent" + ); +} diff --git a/genetic-rs/tests/simulation.rs b/genetic-rs/tests/simulation.rs new file mode 100644 index 0000000..01c4005 --- /dev/null +++ b/genetic-rs/tests/simulation.rs @@ -0,0 +1,226 @@ +//! Integration tests for [`GeneticSim`] core invariants, [`FitnessEliminator`] behaviour, +//! and helper types such as [`FitnessObserver`]. + +use genetic_rs::prelude::*; + +// ───────────────────────────────────────────────────────────────────────────── +// Shared test genome +// ───────────────────────────────────────────────────────────────────────────── + +/// A simple genome whose fitness is just its value. +#[derive(Clone, Debug)] +struct Genome(f32); + +impl GenerateRandom for Genome { + fn gen_random(rng: &mut impl rand::Rng) -> Self { + Self(rng.random()) + } +} + +impl RandomlyMutable for Genome { + type Context = (); + + fn mutate(&mut self, _: &(), rate: f32, rng: &mut impl rand::Rng) { + self.0 += rng.random::() * rate; + } +} + +impl Mitosis for Genome { + type Context = (); + + fn divide(&self, ctx: &(), rate: f32, rng: &mut impl rand::Rng) -> Self { + let mut child = self.clone(); + child.mutate(ctx, rate, rng); + child + } +} + +fn fitness(g: &Genome) -> f32 { + g.0 +} + +// ───────────────────────────────────────────────────────────────────────────── +// GeneticSim population-size invariants +// ───────────────────────────────────────────────────────────────────────────── + +/// The population size must be identical before and after a single generation. +#[test] +fn population_size_preserved_after_next_generation() { + let mut rng = rand::rng(); + let initial_size = 20; + let mut sim = GeneticSim::new( + Vec::::gen_random(&mut rng, initial_size), + FitnessEliminator::new_without_observer(fitness), + MitosisRepopulator::new(0.1, ()), + ); + sim.next_generation(); + assert_eq!(sim.genomes.len(), initial_size); +} + +/// The population size must remain constant over many generations. +#[test] +fn population_size_preserved_over_many_generations() { + let mut rng = rand::rng(); + let initial_size = 50; + let mut sim = GeneticSim::new( + Vec::::gen_random(&mut rng, initial_size), + FitnessEliminator::new_without_observer(fitness), + MitosisRepopulator::new(0.1, ()), + ); + sim.perform_generations(100); + assert_eq!(sim.genomes.len(), initial_size); +} + +// ───────────────────────────────────────────────────────────────────────────── +// GenerateRandom / GenerateRandomCollection +// ───────────────────────────────────────────────────────────────────────────── + +/// [`Vec::gen_random`] must produce exactly the requested number of genomes. +#[test] +fn gen_random_collection_produces_correct_size() { + let mut rng = rand::rng(); + for size in [1usize, 10, 100] { + let population: Vec = Vec::gen_random(&mut rng, size); + assert_eq!( + population.len(), + size, + "expected {size} genomes, got {}", + population.len() + ); + } +} + +// ───────────────────────────────────────────────────────────────────────────── +// FitnessEliminator elimination behaviour +// ───────────────────────────────────────────────────────────────────────────── + +/// With the default threshold (0.5) and 10 genomes, exactly 6 must survive and +/// all survivors must be in the top half by fitness. +#[test] +fn fitness_eliminator_keeps_top_by_fitness() { + // Genomes with distinct, known fitness values 0.0 … 9.0. + let genomes: Vec = (0..10).map(|i| Genome(i as f32)).collect(); + let mut eliminator = FitnessEliminator::new_without_observer(fitness); + let survivors = eliminator.eliminate(genomes); + + // threshold=0.5, n=10 → floor(10*0.5) + 1 = 6 survivors. + assert_eq!(survivors.len(), 6, "expected 6 survivors with default threshold"); + + // Every survivor must be in the top half (fitness ≥ 4.0). + for g in &survivors { + assert!( + g.0 >= 4.0, + "genome with fitness {} survived but is below the top-half threshold", + g.0, + ); + } +} + +/// The genome with the highest fitness must always survive elimination. +#[test] +fn fitness_eliminator_highest_fitness_always_survives() { + let genomes: Vec = (0..20).map(|i| Genome(i as f32)).collect(); + let mut eliminator = FitnessEliminator::new_without_observer(fitness); + let survivors = eliminator.eliminate(genomes); + assert!( + survivors.iter().any(|g| g.0 == 19.0), + "the highest-fitness genome (19.0) must always survive" + ); +} + +/// The genome with the lowest fitness must always be eliminated. +#[test] +fn fitness_eliminator_lowest_fitness_never_survives() { + let genomes: Vec = (0..20).map(|i| Genome(i as f32)).collect(); + let mut eliminator = FitnessEliminator::new_without_observer(fitness); + let survivors = eliminator.eliminate(genomes); + assert!( + !survivors.iter().any(|g| g.0 == 0.0), + "the lowest-fitness genome (0.0) must always be eliminated" + ); +} + +/// [`FitnessEliminator::calculate_and_sort`] must return genomes sorted in +/// descending order of fitness. +#[test] +fn fitness_eliminator_sorts_descending() { + let genomes = vec![Genome(3.0), Genome(1.0), Genome(4.0), Genome(2.0)]; + let eliminator = FitnessEliminator::new_without_observer(fitness); + let sorted = eliminator.calculate_and_sort(genomes); + + for window in sorted.windows(2) { + assert!( + window[0].1 >= window[1].1, + "fitness values are not in descending order: {} before {}", + window[0].1, + window[1].1, + ); + } +} + +/// A custom threshold controls the exact fraction of the population kept. +#[test] +fn fitness_eliminator_custom_threshold() { + // 10 genomes, threshold=0.3 → floor(10*0.3) + 1 = 4 survivors. + let genomes: Vec = (0..10).map(|i| Genome(i as f32)).collect(); + let mut eliminator = FitnessEliminator::new(fitness, 0.3, ()); + let survivors = eliminator.eliminate(genomes); + assert_eq!(survivors.len(), 4, "expected 4 survivors with threshold=0.3"); +} + +/// [`FitnessEliminator::new`] must panic when the threshold is outside [0, 1]. +#[test] +#[should_panic] +fn fitness_eliminator_invalid_threshold_panics() { + FitnessEliminator::new(fitness, 1.5_f32, ()); +} + +// ───────────────────────────────────────────────────────────────────────────── +// FitnessEliminator builder +// ───────────────────────────────────────────────────────────────────────────── + +/// The builder pattern must produce an eliminator with the specified settings. +#[test] +fn fitness_eliminator_builder() { + let mut rng = rand::rng(); + let mut eliminator: FitnessEliminator<_, Genome, ()> = FitnessEliminator::builder() + .fitness_fn(fitness) + .threshold(0.4) + .build(); + + let genomes: Vec = Vec::gen_random(&mut rng, 10); + let _ = eliminator.eliminate(genomes); + assert!((eliminator.threshold - 0.4).abs() < 1e-6); +} + +// ───────────────────────────────────────────────────────────────────────────── +// FitnessObserver +// ───────────────────────────────────────────────────────────────────────────── + +/// A counting observer used below. +struct Counter(usize); + +impl FitnessObserver for Counter { + fn observe(&mut self, _: &[(Genome, f32)]) { + self.0 += 1; + } +} + +/// The observer must be called exactly once per generation. +#[test] +fn observer_called_once_per_generation() { + let mut rng = rand::rng(); + let eliminator = FitnessEliminator::new(fitness, 0.5, Counter(0)); + let mut sim = GeneticSim::new( + Vec::::gen_random(&mut rng, 10), + eliminator, + MitosisRepopulator::new(0.0, ()), + ); + + sim.perform_generations(7); + assert_eq!( + sim.eliminator.observer.0, + 7, + "observer must be called once per generation" + ); +} diff --git a/genetic-rs/tests/speciation.rs b/genetic-rs/tests/speciation.rs new file mode 100644 index 0000000..db28e1a --- /dev/null +++ b/genetic-rs/tests/speciation.rs @@ -0,0 +1,295 @@ +//! Integration tests for [`SpeciatedPopulation`], [`SpeciatedFitnessEliminator`], +//! and [`SpeciatedCrossoverRepopulator`]. + +use genetic_rs::prelude::*; +use genetic_rs::speciation::SpeciatedPopulation; + +// ───────────────────────────────────────────────────────────────────────────── +// Shared test genome +// ───────────────────────────────────────────────────────────────────────────── + +/// A genome whose species membership is fully determined by its integer `class`. +/// Two genomes with the same class have divergence 0.0; different classes give 1.0. +#[derive(Clone, Debug, PartialEq)] +struct Genome { + class: i32, + val: f32, +} + +impl Speciated for Genome { + type Context = (); + + fn divergence(&self, other: &Self, _: &()) -> f32 { + if self.class == other.class { + 0.0 + } else { + 1.0 + } + } +} + +impl GenerateRandom for Genome { + fn gen_random(rng: &mut impl rand::Rng) -> Self { + Self { + class: rng.random_range(0..3), + val: rng.random(), + } + } +} + +impl RandomlyMutable for Genome { + type Context = (); + + fn mutate(&mut self, _: &(), rate: f32, rng: &mut impl rand::Rng) { + self.val += rng.random::() * rate; + } +} + +impl Crossover for Genome { + type Context = (); + + fn crossover(&self, other: &Self, _: &(), _rate: f32, _rng: &mut impl rand::Rng) -> Self { + Self { + class: self.class, + val: (self.val + other.val) / 2.0, + } + } +} + +fn fitness(g: &Genome) -> f32 { + g.val +} + +// ───────────────────────────────────────────────────────────────────────────── +// SpeciatedPopulation — species grouping +// ───────────────────────────────────────────────────────────────────────────── + +/// All identical genomes must end up in a single species. +#[test] +fn identical_genomes_in_same_species() { + let genomes: Vec = (0..5) + .map(|_| Genome { + class: 0, + val: 0.0, + }) + .collect(); + let pop = SpeciatedPopulation::from_genomes(&genomes, 0.5, &()); + assert_eq!(pop.species.len(), 1, "expected a single species"); + assert_eq!( + pop.species[0].len(), + 5, + "all genomes must belong to the single species" + ); +} + +/// Genomes of four distinct classes must form four separate species. +#[test] +fn different_class_genomes_in_different_species() { + let genomes: Vec = (0..4) + .map(|i| Genome { + class: i, + val: 0.0, + }) + .collect(); + let pop = SpeciatedPopulation::from_genomes(&genomes, 0.5, &()); + assert_eq!(pop.species.len(), 4); +} + +/// With a threshold > 1.0 (larger than the max divergence) all genomes, +/// regardless of class, must end up in the same species. +#[test] +fn high_threshold_groups_all_genomes() { + let genomes: Vec = (0..6) + .map(|i| Genome { + class: i % 3, + val: 0.0, + }) + .collect(); + // Divergence is at most 1.0; with threshold 1.5 everything is "close enough". + let pop = SpeciatedPopulation::from_genomes(&genomes, 1.5, &()); + assert_eq!(pop.species.len(), 1, "all genomes must be in one species"); +} + +/// Every genome index must appear in exactly one species. +#[test] +fn every_genome_index_appears_exactly_once() { + let n = 9usize; + let genomes: Vec = (0..n) + .map(|i| Genome { + class: (i % 3) as i32, + val: i as f32, + }) + .collect(); + let pop = SpeciatedPopulation::from_genomes(&genomes, 0.5, &()); + + let mut seen = vec![false; n]; + for species in &pop.species { + for &idx in species { + assert!(!seen[idx], "genome index {idx} appears in more than one species"); + seen[idx] = true; + } + } + assert!( + seen.iter().all(|&v| v), + "not every genome index appeared in a species" + ); +} + +// ───────────────────────────────────────────────────────────────────────────── +// SpeciatedPopulation — insert_genome +// ───────────────────────────────────────────────────────────────────────────── + +/// Inserting a genome from a new class must create a new species. +#[test] +fn insert_genome_creates_new_species_for_novel_genome() { + let genomes = vec![ + Genome { + class: 0, + val: 0.0, + }, + Genome { + class: 1, + val: 0.0, + }, // divergence 1.0 > threshold 0.5 → new species + ]; + let mut pop = SpeciatedPopulation { + species: vec![vec![0]], + threshold: 0.5, + }; + let created_new = pop.insert_genome(1, &genomes, &()); + assert!(created_new, "expected a new species to be created"); + assert_eq!(pop.species.len(), 2); +} + +/// Inserting a genome from an existing class must join that species. +#[test] +fn insert_genome_joins_existing_species_for_similar_genome() { + let genomes = vec![ + Genome { + class: 0, + val: 0.0, + }, + Genome { + class: 0, + val: 1.0, + }, // divergence 0.0 < threshold 0.5 → joins species + ]; + let mut pop = SpeciatedPopulation { + species: vec![vec![0]], + threshold: 0.5, + }; + let created_new = pop.insert_genome(1, &genomes, &()); + assert!(!created_new, "must not create a new species for a similar genome"); + assert_eq!(pop.species.len(), 1); + assert_eq!(pop.species[0].len(), 2); +} + +// ───────────────────────────────────────────────────────────────────────────── +// SpeciatedPopulation — round-robin iterator +// ───────────────────────────────────────────────────────────────────────────── + +/// The round-robin iterator must visit every genome index within one full cycle. +/// With equal-sized species the cycle length equals the total number of genomes. +#[test] +fn round_robin_covers_all_genomes() { + // 3 classes × 2 genomes each = 6 genomes, 3 species of equal size. + let genomes: Vec = (0..6) + .map(|i| Genome { + class: (i % 3) as i32, + val: i as f32, + }) + .collect(); + let pop = SpeciatedPopulation::from_genomes(&genomes, 0.5, &()); + + let mut seen = vec![false; 6]; + for idx in pop.round_robin().take(6) { + seen[idx] = true; + } + assert!( + seen.iter().all(|&v| v), + "round_robin must cover all genome indices in one cycle" + ); +} + +/// The enumerate variant must yield matching (species_index, genome_index) pairs. +#[test] +fn round_robin_enumerate_species_index_is_valid() { + let genomes: Vec = (0..6) + .map(|i| Genome { + class: (i % 3) as i32, + val: i as f32, + }) + .collect(); + let pop = SpeciatedPopulation::from_genomes(&genomes, 0.5, &()); + + for (species_i, genome_i) in pop.round_robin_enumerate().take(12) { + assert!( + pop.species[species_i].contains(&genome_i), + "genome index {genome_i} is not in species {species_i}" + ); + } +} + +// ───────────────────────────────────────────────────────────────────────────── +// SpeciatedFitnessEliminator — fitness scaling and population-size invariants +// ───────────────────────────────────────────────────────────────────────────── + +/// The population size must remain constant when using [`SpeciatedFitnessEliminator`] +/// together with [`SpeciatedCrossoverRepopulator`]. +#[test] +fn speciated_sim_population_size_preserved() { + let mut rng = rand::rng(); + let initial_size = 30; + + let eliminator = SpeciatedFitnessEliminator::new(fitness, 0.5, 0.5, (), ()); + let repopulator = SpeciatedCrossoverRepopulator::new( + 0.1, + 0.5, + ActionIfIsolated::CrossoverSimilarSpecies, + (), + (), + ); + + let mut sim = GeneticSim::new( + Vec::::gen_random(&mut rng, initial_size), + eliminator, + repopulator, + ); + sim.perform_generations(20); + assert_eq!(sim.genomes.len(), initial_size); +} + +/// Speciation must give fitness bonuses to rare/isolated genomes: +/// an isolated genome with *lower* raw fitness can out-compete a large species +/// with higher raw fitness because the large species has its fitness divided by +/// its size. +/// +/// Setup: +/// - 4 genomes of class 0 with val = 1.0 → adjusted fitness = 1.0 / 4 = 0.25 +/// - 1 genome of class 1 with val = 0.5 → adjusted fitness = 0.5 / 1 = 0.5 +/// +/// With threshold = 0.5 and 5 genomes, 3 survive. +/// Sorted adjusted fitness: [0.5, 0.25, 0.25, 0.25, 0.25] +/// → the class-1 genome (raw 0.5) must survive despite the lower raw fitness. +#[test] +fn speciation_protects_rare_species() { + let mut class0_genomes: Vec = (0..4) + .map(|_| Genome { + class: 0, + val: 1.0, + }) + .collect(); + let rare = Genome { + class: 1, + val: 0.5, + }; + class0_genomes.push(rare.clone()); + + let mut eliminator = SpeciatedFitnessEliminator::new(fitness, 0.5, 0.5, (), ()); + let survivors = eliminator.eliminate(class0_genomes); + + assert!( + survivors.iter().any(|g| g == &rare), + "the rare species genome must survive despite lower raw fitness" + ); +} From 4af20c58f1e8a43f7b01b8a60b7929f51cc7f875 Mon Sep 17 00:00:00 2001 From: Tristan Murphy <72839119+HyperCodec@users.noreply.github.com> Date: Tue, 10 Mar 2026 12:30:58 +0000 Subject: [PATCH 4/4] cargo fmt --- genetic-rs/tests/repopulator.rs | 8 +++-- genetic-rs/tests/simulation.rs | 15 ++++++--- genetic-rs/tests/speciation.rs | 56 ++++++++++----------------------- 3 files changed, 32 insertions(+), 47 deletions(-) diff --git a/genetic-rs/tests/repopulator.rs b/genetic-rs/tests/repopulator.rs index 5ac2462..27235fd 100644 --- a/genetic-rs/tests/repopulator.rs +++ b/genetic-rs/tests/repopulator.rs @@ -76,7 +76,10 @@ fn mitosis_zero_mutation_rate_produces_clone() { let parent = Genome(42.0); let mut rng = rand::rng(); let child = parent.divide(&(), 0.0, &mut rng); - assert_eq!(child, parent, "child at rate 0.0 must be identical to parent"); + assert_eq!( + child, parent, + "child at rate 0.0 must be identical to parent" + ); } // ───────────────────────────────────────────────────────────────────────────── @@ -147,8 +150,7 @@ fn from_parent_includes_original_parent() { let parent = Genome(7.0); let population = Vec::::from_parent(parent.clone(), 5, (), 0.0); assert_eq!( - population[0], - parent, + population[0], parent, "the first element must be the original parent" ); } diff --git a/genetic-rs/tests/simulation.rs b/genetic-rs/tests/simulation.rs index 01c4005..12ed2c6 100644 --- a/genetic-rs/tests/simulation.rs +++ b/genetic-rs/tests/simulation.rs @@ -104,7 +104,11 @@ fn fitness_eliminator_keeps_top_by_fitness() { let survivors = eliminator.eliminate(genomes); // threshold=0.5, n=10 → floor(10*0.5) + 1 = 6 survivors. - assert_eq!(survivors.len(), 6, "expected 6 survivors with default threshold"); + assert_eq!( + survivors.len(), + 6, + "expected 6 survivors with default threshold" + ); // Every survivor must be in the top half (fitness ≥ 4.0). for g in &survivors { @@ -165,7 +169,11 @@ fn fitness_eliminator_custom_threshold() { let genomes: Vec = (0..10).map(|i| Genome(i as f32)).collect(); let mut eliminator = FitnessEliminator::new(fitness, 0.3, ()); let survivors = eliminator.eliminate(genomes); - assert_eq!(survivors.len(), 4, "expected 4 survivors with threshold=0.3"); + assert_eq!( + survivors.len(), + 4, + "expected 4 survivors with threshold=0.3" + ); } /// [`FitnessEliminator::new`] must panic when the threshold is outside [0, 1]. @@ -219,8 +227,7 @@ fn observer_called_once_per_generation() { sim.perform_generations(7); assert_eq!( - sim.eliminator.observer.0, - 7, + sim.eliminator.observer.0, 7, "observer must be called once per generation" ); } diff --git a/genetic-rs/tests/speciation.rs b/genetic-rs/tests/speciation.rs index db28e1a..448ccf4 100644 --- a/genetic-rs/tests/speciation.rs +++ b/genetic-rs/tests/speciation.rs @@ -67,12 +67,7 @@ fn fitness(g: &Genome) -> f32 { /// All identical genomes must end up in a single species. #[test] fn identical_genomes_in_same_species() { - let genomes: Vec = (0..5) - .map(|_| Genome { - class: 0, - val: 0.0, - }) - .collect(); + let genomes: Vec = (0..5).map(|_| Genome { class: 0, val: 0.0 }).collect(); let pop = SpeciatedPopulation::from_genomes(&genomes, 0.5, &()); assert_eq!(pop.species.len(), 1, "expected a single species"); assert_eq!( @@ -85,12 +80,7 @@ fn identical_genomes_in_same_species() { /// Genomes of four distinct classes must form four separate species. #[test] fn different_class_genomes_in_different_species() { - let genomes: Vec = (0..4) - .map(|i| Genome { - class: i, - val: 0.0, - }) - .collect(); + let genomes: Vec = (0..4).map(|i| Genome { class: i, val: 0.0 }).collect(); let pop = SpeciatedPopulation::from_genomes(&genomes, 0.5, &()); assert_eq!(pop.species.len(), 4); } @@ -125,7 +115,10 @@ fn every_genome_index_appears_exactly_once() { let mut seen = vec![false; n]; for species in &pop.species { for &idx in species { - assert!(!seen[idx], "genome index {idx} appears in more than one species"); + assert!( + !seen[idx], + "genome index {idx} appears in more than one species" + ); seen[idx] = true; } } @@ -143,14 +136,8 @@ fn every_genome_index_appears_exactly_once() { #[test] fn insert_genome_creates_new_species_for_novel_genome() { let genomes = vec![ - Genome { - class: 0, - val: 0.0, - }, - Genome { - class: 1, - val: 0.0, - }, // divergence 1.0 > threshold 0.5 → new species + Genome { class: 0, val: 0.0 }, + Genome { class: 1, val: 0.0 }, // divergence 1.0 > threshold 0.5 → new species ]; let mut pop = SpeciatedPopulation { species: vec![vec![0]], @@ -165,21 +152,18 @@ fn insert_genome_creates_new_species_for_novel_genome() { #[test] fn insert_genome_joins_existing_species_for_similar_genome() { let genomes = vec![ - Genome { - class: 0, - val: 0.0, - }, - Genome { - class: 0, - val: 1.0, - }, // divergence 0.0 < threshold 0.5 → joins species + Genome { class: 0, val: 0.0 }, + Genome { class: 0, val: 1.0 }, // divergence 0.0 < threshold 0.5 → joins species ]; let mut pop = SpeciatedPopulation { species: vec![vec![0]], threshold: 0.5, }; let created_new = pop.insert_genome(1, &genomes, &()); - assert!(!created_new, "must not create a new species for a similar genome"); + assert!( + !created_new, + "must not create a new species for a similar genome" + ); assert_eq!(pop.species.len(), 1); assert_eq!(pop.species[0].len(), 2); } @@ -273,16 +257,8 @@ fn speciated_sim_population_size_preserved() { /// → the class-1 genome (raw 0.5) must survive despite the lower raw fitness. #[test] fn speciation_protects_rare_species() { - let mut class0_genomes: Vec = (0..4) - .map(|_| Genome { - class: 0, - val: 1.0, - }) - .collect(); - let rare = Genome { - class: 1, - val: 0.5, - }; + let mut class0_genomes: Vec = (0..4).map(|_| Genome { class: 0, val: 1.0 }).collect(); + let rare = Genome { class: 1, val: 0.5 }; class0_genomes.push(rare.clone()); let mut eliminator = SpeciatedFitnessEliminator::new(fitness, 0.5, 0.5, (), ());