Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions .github/workflows/ci-cd.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
28 changes: 26 additions & 2 deletions genetic-rs/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -35,18 +35,42 @@ 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"
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"]
155 changes: 155 additions & 0 deletions genetic-rs/tests/knockout.rs
Original file line number Diff line number Diff line change
@@ -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<Ordering>` 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<usize>`: `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<Genome> = (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<Genome> = (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<Genome> = (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<Genome> = (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<Genome> = (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<Ordering>` 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);
}
156 changes: 156 additions & 0 deletions genetic-rs/tests/repopulator.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
//! 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::<f32>() * 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<Genome> = 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<Genome> = 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<Genome> = 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<Genome> = 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::<Genome>::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::<Genome>::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::<Genome>::from_parent(parent.clone(), 5, (), 0.0);
assert_eq!(
population[0], parent,
"the first element must be the original parent"
);
}
Loading