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
157 changes: 157 additions & 0 deletions genetic-rs-common/src/builtin/eliminator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,16 @@ impl<G> FitnessObserver<G> for () {
fn observe(&mut self, _fitnesses: &[(G, f32)]) {}
}

impl<F, G> FitnessObserver<G> 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<G, A: FitnessObserver<G>, B: FitnessObserver<G>>(
Expand Down Expand Up @@ -523,3 +533,150 @@ mod knockout {

#[cfg(feature = "knockout")]
pub use knockout::*;

#[cfg(feature = "speciation")]
mod speciation {
use crate::{prelude::*, speciation::SpeciatedPopulation};

/// An eliminator that attempts to preserve new experimental structures by dividing a genome's
/// fitness by the number of genomes in its species.
pub struct SpeciatedFitnessEliminator<
F: FeatureBoundedFitnessFn<G>,
G: Speciated + FeatureBoundedGenome,
O: FeatureBoundedFitnessObserver<G> = (),
> {
/// The divergence threshold used to determine whether a genome belongs in a species.
/// See [`SpeciatedPopulation::threshold`] for more info.
pub speciation_threshold: f32,

/// The inner fitness eliminator used to hold settings and such.
pub inner: FitnessEliminator<F, G, O>,

/// 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: <G as Speciated>::Context,

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

impl<F, G, O> SpeciatedFitnessEliminator<F, G, O>
where
F: FeatureBoundedFitnessFn<G>,
G: Speciated + FeatureBoundedGenome,
O: FeatureBoundedFitnessObserver<G>,
{
/// Creates a new [`SpeciatedFitnessEliminator`] with a given fitness function and thresholds.
pub fn new(
fitness_fn: F,
speciation_threshold: f32,
keep_threshold: f32,
observer: O,
ctx: <G as Speciated>::Context,
) -> Self {
Self {
speciation_threshold,
inner: FitnessEliminator::new(fitness_fn, keep_threshold, observer),
ctx,
Comment thread
HyperCodec marked this conversation as resolved.
Resolved
_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<F, G, O>,
speciation_threshold: f32,
ctx: <G as Speciated>::Context,
) -> Self {
Self {
speciation_threshold,
inner: fitness_eliminator,
ctx,
_marker: std::marker::PhantomData,
}
}

/// Calculates the fitness of each genome, dividing by the number of genomes in its species, and sorts them by fitness.
/// Returns a vector of tuples containing the genome and its fitness score.
#[cfg(not(feature = "rayon"))]
pub fn calculate_and_sort(&self, genomes: Vec<G>) -> Vec<(G, f32)> {
let population =
SpeciatedPopulation::from_genomes(&genomes, self.speciation_threshold, &self.ctx);
let mut fitnesses = vec![0.0; genomes.len()];

for species in population.species {
let len = species.len() as f32;
debug_assert!(len != 0.0);
for index in species {
let genome = &genomes[index];
let fitness = self.inner.fitness_fn.fitness(genome);
if fitness < 0.0 {
fitnesses[index] = fitness * len;
} else {
fitnesses[index] = fitness / len;
}
}
}

let mut fitnesses: Vec<(G, f32)> = genomes.into_iter().zip(fitnesses).collect();
fitnesses.sort_by(|(_a, afit), (_b, bfit)| bfit.partial_cmp(afit).unwrap());
fitnesses
}

/// Calculates the fitness of each genome, dividing by the number of genomes in its species, and sorts them by fitness.
/// Returns a vector of tuples containing the genome and its fitness score.
#[cfg(feature = "rayon")]
pub fn calculate_and_sort(&self, genomes: Vec<G>) -> Vec<(G, f32)> {
let population =
SpeciatedPopulation::from_genomes(&genomes, self.speciation_threshold, &self.ctx);

let mut fitnesses = vec![0.0; genomes.len()];

for species in population.species {
let len = species.len() as f32;
debug_assert!(len != 0.0);
for index in species {
let genome = &genomes[index];
let fitness = self.inner.fitness_fn.fitness(genome);
if fitness < 0.0 {
fitnesses[index] = fitness * len;
} else {
fitnesses[index] = fitness / len;
}
}
}

let mut result: Vec<(G, f32)> = genomes.into_iter().zip(fitnesses).collect();
result.sort_by(|(_a, afit), (_b, bfit)| bfit.partial_cmp(afit).unwrap());
result
}
}

impl<F, G, O> Eliminator<G> for SpeciatedFitnessEliminator<F, G, O>
where
F: FeatureBoundedFitnessFn<G>,
G: Speciated + FeatureBoundedGenome,
O: FeatureBoundedFitnessObserver<G>,
{
#[cfg(not(feature = "rayon"))]
fn eliminate(&mut self, genomes: Vec<G>) -> Vec<G> {
let mut fitnesses = self.calculate_and_sort(genomes);
self.inner.observer.observe(&fitnesses);
let median_index = (fitnesses.len() as f32) * self.inner.threshold;
fitnesses.truncate(median_index as usize + 1);
fitnesses.into_iter().map(|(g, _)| g).collect()
}

#[cfg(feature = "rayon")]
fn eliminate(&mut self, genomes: Vec<G>) -> Vec<G> {
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()
Comment thread
HyperCodec marked this conversation as resolved.
Resolved
}
}
}

#[cfg(feature = "speciation")]
pub use speciation::*;
Loading