use rand::Rng;
use crate::gene::Gene;
use crate::genotype::Genotype;
use crate::operators::mutation::Mutation;
use crate::random::Random as RandomGene;
#[derive(Copy, Clone, Debug)]
#[allow(clippy::exhaustive_structs)]
pub struct Binomial {
pub chance: f64,
}
impl<G, const GENES: usize, RNG> Mutation<[G; GENES], RNG> for Binomial
where
G: Gene + RandomGene,
RNG: Rng,
{
fn mutate(&self, genotype: &mut [G; GENES], rng: &mut RNG) {
assert!(
self.chance >= 0.0_f64,
"chance of mutation has to be above or equal 0.0, but is {}",
self.chance
);
assert!(
self.chance <= 1.0_f64,
"chance of mutation has to be below or equal 1.0, but is {}",
self.chance
);
for gene in genotype {
if rng.gen_bool(self.chance) {
*gene = G::random(rng);
}
}
}
}
impl<G, RNG> Mutation<Vec<G>, RNG> for Binomial
where
G: Gene + RandomGene,
RNG: Rng,
{
fn mutate(&self, genotype: &mut Vec<G>, rng: &mut RNG) {
assert!(
self.chance >= 0.0_f64,
"chance of mutation has to be above or equal 0.0, but is {}",
self.chance
);
assert!(
self.chance <= 1.0_f64,
"chance of mutation has to be below or equal 1.0, but is {}",
self.chance
);
for gene in genotype {
if rng.gen_bool(self.chance) {
*gene = G::random(rng);
}
}
}
}
impl<RNG> Mutation<String, RNG> for Binomial
where
RNG: Rng,
{
fn mutate(&self, genotype: &mut String, rng: &mut RNG) {
assert!(
self.chance >= 0.0_f64,
"chance of mutation has to be above or equal 0.0, but is {}",
self.chance
);
assert!(
self.chance <= 1.0_f64,
"chance of mutation has to be below or equal 1.0, but is {}",
self.chance
);
let mut chars = genotype.chars().collect::<Vec<_>>();
for char in &mut chars {
if rng.gen_bool(self.chance) {
*char = <String as Genotype>::Gene::random(rng);
}
}
*genotype = chars.iter().collect::<String>();
}
}
#[cfg(test)]
mod tests {
use rand::rngs::SmallRng;
use rand::SeedableRng;
use super::{Binomial, Mutation};
#[test]
fn array() {
let mutation = Binomial { chance: 0.4 };
let mut rng = SmallRng::seed_from_u64(4);
let mut array = [0_u8, 1, 2, 3, 4];
mutation.mutate(&mut array, &mut rng);
assert_eq!(array, [0, 239, 2, 163, 4]);
}
#[test]
fn vector() {
let mutation = Binomial { chance: 0.4 };
let mut rng = SmallRng::seed_from_u64(4);
let mut array = vec![0_u8, 1, 2, 3, 4];
mutation.mutate(&mut array, &mut rng);
assert_eq!(array, [0, 239, 2, 163, 4]);
}
#[test]
fn string() {
let mutation = Binomial { chance: 0.25 };
let mut rng = SmallRng::seed_from_u64(1);
let mut string = String::from("test");
mutation.mutate(&mut string, &mut rng);
assert_eq!(string, "t\u{31df6}st");
}
}