1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
use rand::prelude::IteratorRandom;

use crate::{
    genes::{Activation, Node},
    genome::Genome,
    rng::GenomeRng,
};

use super::Mutations;

impl Mutations {
    /// This mutation changes the activation function of one random hidden node to any other choosen from `activation_pool`.
    /// If the pool is empty (the current activation function is excluded) nothing is changed.
    pub fn change_activation(
        activation_pool: &[Activation],
        genome: &mut Genome,
        rng: &mut GenomeRng,
    ) {
        if let Some(node) = genome.hidden.random(rng) {
            let updated = Node::new(
                node.id,
                activation_pool
                    .iter()
                    .filter(|&&activation| activation != node.activation)
                    .choose(rng)
                    .cloned()
                    .unwrap_or(node.activation),
            );

            genome.hidden.replace(updated);
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::GenomeContext;

    #[test]
    fn change_activation() {
        let mut gc = GenomeContext::default();

        let mut genome = gc.initialized_genome();

        genome.add_node_with_context(&mut gc);

        let old_activation = genome.hidden.iter().next().unwrap().activation;

        genome.change_activation_with_context(&mut gc);

        assert_ne!(
            genome.hidden.iter().next().unwrap().activation,
            old_activation
        );
    }
}