mod elitism;
pub use self::elitism::Elitism;
mod greedy;
pub use self::greedy::Greedy;
mod rosomaxa;
pub use self::rosomaxa::Rosomaxa;
pub use self::rosomaxa::RosomaxaConfig;
use crate::construction::heuristics::InsertionContext;
use crate::models::Problem;
use crate::solver::Statistics;
use crate::utils::{compare_floats, Environment};
use std::cmp::Ordering;
use std::fmt::Display;
use std::sync::Arc;
pub type Individual = InsertionContext;
#[derive(Debug, PartialEq, Eq, Hash)]
pub enum SelectionPhase {
Initial,
Exploration,
Exploitation,
}
pub trait Population: Display {
fn add_all(&mut self, individuals: Vec<Individual>) -> bool;
fn add(&mut self, individual: Individual) -> bool;
fn on_generation(&mut self, statistics: &Statistics);
fn cmp(&self, a: &Individual, b: &Individual) -> Ordering;
fn select<'a>(&'a self) -> Box<dyn Iterator<Item = &Individual> + 'a>;
fn ranked<'a>(&'a self) -> Box<dyn Iterator<Item = (&Individual, usize)> + 'a>;
fn size(&self) -> usize;
fn selection_phase(&self) -> SelectionPhase;
}
fn is_same_fitness(a: &Individual, b: &Individual) -> bool {
let fitness_a = a.get_fitness_values();
let fitness_b = b.get_fitness_values();
fitness_a.zip(fitness_b).all(|(a, b)| compare_floats(a, b) == Ordering::Equal)
}
pub fn get_default_selection_size(environment: &Environment) -> usize {
environment.parallelism.available_cpus().min(8)
}
pub fn get_default_population(
problem: Arc<Problem>,
environment: Arc<Environment>,
) -> Box<dyn Population + Send + Sync> {
let selection_size = get_default_selection_size(environment.as_ref());
if selection_size == 1 {
Box::new(Greedy::new(problem, 1, None))
} else {
let config = RosomaxaConfig::new_with_defaults(selection_size);
let population =
Rosomaxa::new(problem, environment, config).expect("cannot create rosomaxa with default configuration");
Box::new(population)
}
}
pub fn create_elitism_population(
problem: Arc<Problem>,
environment: Arc<Environment>,
) -> Box<dyn Population + Sync + Send> {
let selection_size = get_default_selection_size(environment.as_ref());
Box::new(Elitism::new(problem, environment.random.clone(), 4, selection_size))
}