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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
/// An enum for storing additional information for different types of genes
#[derive(Clone, Debug, PartialEq)]
pub enum GeneExtras {
    /// Input contains a current value
    Input(f64),
    /// Neuron contains a current value and an input count
    Neuron(f64, usize),
    Forward,
    Recurrent,
    Bias
}

#[derive(Clone, Debug, PartialEq)]
pub struct Gene {
    pub weight: f64,
    pub id: usize,
    pub variant: GeneExtras
}

impl Gene {
    pub fn forward(weight: f64, id: usize) -> Gene {
        Gene {
            weight: weight,
            id: id,
            variant: GeneExtras::Forward
        }
    }

    pub fn recurrent(weight: f64, id: usize) -> Gene {
        Gene {
            weight: weight,
            id: id,
            variant: GeneExtras::Recurrent
        }
    }

    pub fn input(weight: f64, id: usize) -> Gene {
        Gene {
            weight: weight,
            id: id,
            variant: GeneExtras::Input(0.0)
        }
    }

    pub fn bias(weight: f64) -> Gene {
        Gene {
            weight: weight,
            id: 0,
            variant: GeneExtras::Bias
        }
    }

    pub fn neuron(weight: f64, id: usize, inputs: usize) -> Gene {
        Gene {
            weight: weight,
            id: id,
            variant: GeneExtras::Neuron(0.0, inputs)
        }
    }

    #[doc(hidden)]
    pub fn ref_input(&self) -> Option<(f64, usize, f64)> {
        if let GeneExtras::Input(ref weight) = self.variant {
            Some((self.weight, self.id, *weight))
        } else {
            None
        }
    }

    #[doc(hidden)]
    pub fn ref_neuron(&self) -> Option<(f64, usize, f64, usize)> {
        if let GeneExtras::Neuron(ref value, ref inputs) = self.variant {
            Some((self.weight, self.id, *value, *inputs))
        } else {
            None
        }
    }

    #[doc(hidden)]
    pub fn ref_mut_neuron<'a>(&'a mut self) -> Option<(&'a mut f64, &'a mut usize, &'a mut f64, &'a mut usize)> {
        if let GeneExtras::Neuron(ref mut value, ref mut inputs) = self.variant {
            Some((&mut self.weight, &mut self.id, value, inputs))
        } else {
            None
        }
    }
}