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
1 change: 1 addition & 0 deletions .github/workflows/ci-cd.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ on:
push:
branches: [main]
pull_request:
workflow_dispatch:

jobs:
test:
Expand Down
7 changes: 0 additions & 7 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,4 @@ authors = ["HyperCodec"]
homepage = "https://github.com/hypercodec/genetic-rs"
repository = "https://github.com/hypercodec/genetic-rs"
license = "MIT"
edition = "2021"
edition = "2021"
9 changes: 4 additions & 5 deletions genetic-rs-common/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,10 @@ categories = ["algorithms", "science", "simulation"]

[features]
default = ["builtin", "genrand", "crossover"]
builtin = []
builtin = ["dep:rand"]
crossover = ["builtin"]
speciation = ["crossover"]
genrand = []
genrand = ["dep:rand"]
rayon = ["dep:rayon"]
tracing = ["dep:tracing"]

Expand All @@ -27,7 +27,6 @@ features = ["crossover", "speciation"]
rustdoc-args = ["--cfg", "docsrs"]

[dependencies]
replace_with = "0.1.7"
rand = "0.9.0"
rand = { version = "0.9.0", optional = true }
rayon = { version = "1.10.0", optional = true }
tracing = { version = "0.1.41", optional = true }
tracing = { version = "0.1.41", optional = true }
108 changes: 108 additions & 0 deletions genetic-rs-common/src/builtin/eliminator.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
use crate::Eliminator;

#[cfg(feature = "rayon")]
use rayon::prelude::*;

/// A trait for fitness functions. This allows for more flexibility in defining fitness functions.
/// Any `Fn(&G) -> f32` can be used as a fitness function.
pub trait FitnessFn<G> {
/// Evaluates a genome's fitness
fn fitness(&self, genome: &G) -> f32;
}

impl<G, F> FitnessFn<G> for F
where
F: Fn(&G) -> f32,
{
fn fitness(&self, genome: &G) -> f32 {
(self)(genome)
}
}

/// A fitness-based eliminator that eliminates genomes based on their fitness scores.
pub struct FitnessEliminator<F: FitnessFn<G>, G: Sized + Send> {
/// 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 threshold: f32,

_marker: std::marker::PhantomData<G>,
}

// TODO only require `Send` and `Sync` for `F` when `rayon` is enabled`
impl<F, G> FitnessEliminator<F, G>
where
F: FitnessFn<G> + Send + Sync,
G: Sized + Send + Sync,
{
/// Creates a new [`FitnessEliminator`] with a given fitness function and threshold.
/// Panics if the threshold is not between 0.0 and 1.0.
pub fn new(fitness_fn: F, threshold: f32) -> Self {
if !(0.0..=1.0).contains(&threshold) {
panic!("Threshold must be between 0.0 and 1.0");
}
Self {
fitness_fn,
threshold,
_marker: std::marker::PhantomData,
}
}

/// Creates a new [`FitnessEliminator`] with a default threshold of 0.5 (all genomes below median fitness are eliminated).
pub fn new_with_default(fitness_fn: F) -> Self {
Self::new(fitness_fn, 0.5)
}

/// Calculates the fitness of each genome 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<G>) -> Vec<(G, f32)> {
let mut fitnesses: Vec<(G, f32)> = genomes
.into_iter()
.map(|g| {
let fit = self.fitness_fn.fitness(&g);
(g, fit)
})
.collect();
fitnesses.sort_by(|(_a, afit), (_b, bfit)| bfit.partial_cmp(afit).unwrap());
fitnesses
}

/// Calculates the fitness of each genome 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<G>) -> Vec<(G, f32)> {
let mut fitnesses: Vec<(G, f32)> = genomes
.into_par_iter()
.map(|g| {
let fit = self.fitness_fn.fitness(&g);
(g, fit)
})
.collect();
fitnesses.sort_by(|(_a, afit), (_b, bfit)| bfit.partial_cmp(afit).unwrap());
fitnesses
}
}

impl<F, G> Eliminator<G> for FitnessEliminator<F, G>
where
F: FitnessFn<G> + Send + Sync,
G: Sized + Send + Sync,
{
#[cfg(not(feature = "rayon"))]
fn eliminate(&self, genomes: Vec<G>) -> Vec<G> {
let mut fitnesses = self.calculate_and_sort(genomes);
let median_index = (fitnesses.len() as f32) * self.threshold;
fitnesses.truncate(median_index as usize + 1);
fitnesses.into_iter().map(|(g, _)| g).collect()
}

#[cfg(feature = "rayon")]
fn eliminate(&self, genomes: Vec<G>) -> Vec<G> {
let mut fitnesses = self.calculate_and_sort(genomes);
let median_index = (fitnesses.len() as f32) * self.threshold;
fitnesses.truncate(median_index as usize + 1);
fitnesses.into_par_iter().map(|(g, _)| g).collect()
}
}
5 changes: 5 additions & 0 deletions genetic-rs-common/src/builtin/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
/// Contains types implementing [`Eliminator`]
pub mod eliminator;

/// Contains types implementing [`Repopulator`]
pub mod repopulator;
Loading