From 600d9ae9104b7ad3ce1c9abcdc089418720a09db Mon Sep 17 00:00:00 2001 From: Rutherther Date: Mon, 27 Oct 2025 11:36:22 +0100 Subject: [PATCH] feat: add mutation and combined perturbations --- codes/eoa_lib/src/perturbation/mod.rs | 54 +++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) diff --git a/codes/eoa_lib/src/perturbation/mod.rs b/codes/eoa_lib/src/perturbation/mod.rs index a066faa3b91fee767513bc88f2fbcf0907309f2c..9af7eaa46141fb36c835625b9493772c454d6432 100644 --- a/codes/eoa_lib/src/perturbation/mod.rs +++ b/codes/eoa_lib/src/perturbation/mod.rs @@ -210,6 +210,60 @@ where } } +/// Perform given perturbation only with given probability +pub struct MutationPerturbation { + perturbation: Box>, + rng: Box, + probability: f64 +} + +impl MutationPerturbation { + pub fn new(perturbation: Box>, probability: f64) -> Self { + Self { + perturbation, + rng: Box::new(rand::rng()), + probability + } + } +} + +impl PerturbationOperator for MutationPerturbation { + type Chromosome = T; + + fn perturb(self: &mut Self, chromosome: &Self::Chromosome) -> Self::Chromosome { + if self.rng.random_bool(self.probability) { + self.perturbation.perturb(chromosome) + } else { + chromosome.clone() + } + } +} + +pub struct CombinedPerturbation { + perturbations: Vec>>, +} + +impl CombinedPerturbation { + pub fn new(perturbations: Vec>>) -> Self { + Self { + perturbations, + } + } +} + +impl PerturbationOperator for CombinedPerturbation { + type Chromosome = T; + + fn perturb(self: &mut Self, chromosome: &Self::Chromosome) -> Self::Chromosome { + let mut current_chromosome = chromosome.clone(); + for perturbation in self.perturbations.iter_mut() { + current_chromosome = perturbation.perturb(¤t_chromosome); + } + + current_chromosome + } +} + #[cfg(test)] pub mod tests { use crate::binary_string::BinaryString;