use rand::Rng;
use serde::{Deserialize, Serialize};
use crate::{genes::Activation, genome::Genome};
pub use self::error::MutationError;
pub type MutationResult = Result<(), MutationError>;
mod add_connection;
mod add_node;
mod add_recurrent_connection;
mod change_activation;
mod change_weights;
mod duplicate_node;
mod error;
mod remove_connection;
mod remove_node;
mod remove_recurrent_connection;
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(tag = "type")]
#[serde(rename_all = "snake_case")]
pub enum Mutations {
ChangeWeights {
chance: f64,
percent_perturbed: f64,
standard_deviation: f64,
},
ChangeActivation {
chance: f64,
activation_pool: Vec<Activation>,
},
AddNode {
chance: f64,
activation_pool: Vec<Activation>,
},
AddConnection { chance: f64 },
AddRecurrentConnection { chance: f64 },
RemoveNode { chance: f64 },
RemoveConnection { chance: f64 },
RemoveRecurrentConnection { chance: f64 },
DuplicateNode { chance: f64 },
}
impl Mutations {
pub fn mutate(&self, genome: &mut Genome, rng: &mut impl Rng) -> MutationResult {
match self {
&Mutations::ChangeWeights {
chance,
percent_perturbed,
standard_deviation,
} => {
if rng.gen::<f64>() < chance {
Self::change_weights(percent_perturbed, standard_deviation, genome, rng);
}
}
Mutations::AddNode {
chance,
activation_pool,
} => {
if rng.gen::<f64>() < *chance {
Self::add_node(activation_pool, genome, rng)
}
}
&Mutations::AddConnection { chance } => {
if rng.gen::<f64>() < chance {
return Self::add_connection(genome, rng);
}
}
&Mutations::AddRecurrentConnection { chance } => {
if rng.gen::<f64>() < chance {
return Self::add_recurrent_connection(genome, rng);
}
}
Mutations::ChangeActivation {
chance,
activation_pool,
} => {
if rng.gen::<f64>() < *chance {
Self::change_activation(activation_pool, genome, rng)
}
}
&Mutations::RemoveNode { chance } => {
if rng.gen::<f64>() < chance {
return Self::remove_node(genome, rng);
}
}
&Mutations::RemoveConnection { chance } => {
if rng.gen::<f64>() < chance {
return Self::remove_connection(genome, rng);
}
}
&Mutations::RemoveRecurrentConnection { chance } => {
if rng.gen::<f64>() < chance {
return Self::remove_recurrent_connection(genome, rng);
}
}
&Mutations::DuplicateNode { chance } => {
if rng.gen::<f64>() < chance {
return Self::duplicate_node(genome, rng);
}
}
}
Ok(())
}
}