diff --git a/src/components/replacement/common.rs b/src/components/replacement/common.rs index 136376c..6214c5f 100644 --- a/src/components/replacement/common.rs +++ b/src/components/replacement/common.rs @@ -118,9 +118,50 @@ impl Component

for MuPlusLambda { } } +/// Keeps the `max_population_size` fittest individuals from children. +#[derive(Clone, Serialize, Deserialize)] +pub struct MuCommaLambda { + /// Maximal allowed population size. + pub max_population_size: u32, +} + +impl MuCommaLambda { + pub fn from_params(max_population_size: u32) -> Self { + Self { + max_population_size, + } + } + + pub fn new(max_population_size: u32) -> Box> { + Box::new(Self::from_params(max_population_size)) + } +} + +impl Replacement

for MuCommaLambda { + fn replace( + &self, + _parents: Vec>, + offspring: Vec>, + _rng: &mut Random, + ) -> ExecResult>> { + let mut population = offspring.clone(); + population.sort_unstable_by_key(|i| *i.objective()); + population.truncate(self.max_population_size as usize); + Ok(population) + } +} + +impl Component

for MuCommaLambda { + fn execute(&self, problem: &P, state: &mut State

) -> ExecResult<()> { + replacement(self, problem, state) + } +} + /// Discards all individuals in the parent population, keeping the children unchanged. /// /// The opposite of this is [`DiscardOffspring`]. +/// +/// If 'max_population_size' is given, the new population is simply truncated. #[derive(Clone, Serialize, Deserialize)] pub struct Generational { /// Maximal allowed population size. @@ -146,7 +187,13 @@ impl Replacement

for Generational { offspring: Vec>, _rng: &mut Random, ) -> ExecResult>> { - Ok(offspring) + if offspring.len() > self.max_population_size as usize { + let mut population = offspring.clone(); + population.truncate(self.max_population_size as usize); + Ok(population) + } else { + Ok(offspring) + } } } diff --git a/src/components/replacement/mod.rs b/src/components/replacement/mod.rs index 8bea95c..5ff1f20 100644 --- a/src/components/replacement/mod.rs +++ b/src/components/replacement/mod.rs @@ -13,7 +13,8 @@ pub mod common; pub mod sa; pub use common::{ - DiscardOffspring, Generational, KeepBetterAtIndex, Merge, MuPlusLambda, RandomReplacement, + DiscardOffspring, Generational, KeepBetterAtIndex, Merge, MuCommaLambda, MuPlusLambda, + RandomReplacement, }; /// Trait for representing a component that replaces a parent population with its child population.