Initial commit.

This commit is contained in:
2017-12-19 09:45:31 +01:00
commit be38bf5bd7
5 changed files with 298 additions and 0 deletions

130
src/lib.rs Normal file
View File

@@ -0,0 +1,130 @@
extern crate rayon;
use rayon::prelude::*;
pub trait Individual: Send {
type Fitness: Send + Ord;
fn fitness(&self) -> Self::Fitness;
fn mate(&self, other: &Self) -> Self;
fn mutate(&mut self);
}
pub trait Select<T>: Send
where
T: Individual
{
fn select(&self, population: Vec<Wrapper<T>>) -> Vec<Wrapper<T>>;
}
pub struct MaximizeSelector {
count: usize,
}
impl MaximizeSelector {
pub fn new(count: usize) -> Self {
MaximizeSelector {
count: count,
}
}
}
impl<T> Select<T> for MaximizeSelector
where
T: Individual
{
fn select(&self, mut population: Vec<Wrapper<T>>) -> Vec<Wrapper<T>> {
population.par_sort_unstable_by(|a, b| b.fitness.cmp(&a.fitness));
population.into_iter().take(self.count).collect()
}
}
pub struct MinimizeSelector {
count: usize,
}
impl MinimizeSelector {
pub fn new(count: usize) -> Self {
MinimizeSelector {
count: count,
}
}
}
impl<T> Select<T> for MinimizeSelector
where
T: Individual
{
fn select(&self, mut population: Vec<Wrapper<T>>) -> Vec<Wrapper<T>> {
population.par_sort_unstable_by(|a, b| a.fitness.cmp(&b.fitness));
population.into_iter().take(self.count).collect()
}
}
#[derive(Clone)]
pub struct Wrapper<T>
where
T: Individual,
{
pub individual: T,
pub fitness: Option<T::Fitness>,
}
pub struct Simulation<T>
where
T: Individual,
{
pub population: Vec<Wrapper<T>>,
}
impl<T> Simulation<T>
where
T: Individual,
{
pub fn with_population(initial: Vec<T>) -> Self {
let mut population = Vec::with_capacity(initial.len() * 2);
initial
.into_par_iter()
.map(|individual| Wrapper {
individual: individual,
fitness: None,
})
.collect_into(&mut population);
Simulation {
population: population,
}
}
pub fn calculate(&mut self) {
self.population.par_iter_mut()
.filter(|wrapper| wrapper.fitness.is_none())
.for_each(|wrapper| wrapper.fitness = Some(wrapper.individual.fitness()));
self.population.par_sort_unstable_by(|a, b| b.fitness.cmp(&a.fitness));
}
pub fn evolve<F>(&mut self, func: F)
where
F: Fn(&[Wrapper<T>], &mut Vec<Wrapper<T>>)
{
let mut population = Vec::with_capacity(self.population.len());
func(&self.population, &mut population);
self.population = population;
self.calculate();
}
}