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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
use super::genome::{genes::gene::Gene, genotype::Genotype};
use crate::engines::genome::chromosome::Chromosome;
use crate::engines::genome::genes::bit_gene::BitGene;
use crate::engines::genome::genes::char_gene::CharGene;
use crate::engines::genome::genes::float_gene::FloatGene;
use crate::engines::genome::genes::gene::BoundGene;
use crate::engines::genome::genes::int_gene::IntGene;
use crate::engines::genome::population::Population;
use crate::engines::genome::phenotype::Phenotype;

pub struct Codex<G, A, T>
where
    G: Gene<G, A> 
{
    pub encoder: Option<Box<dyn Fn() -> Genotype<G, A>>>,
    pub decoder: Option<fn(&Genotype<G, A>) -> T>,
}

impl<G: Gene<G, A>, A, T> Codex<G, A, T> {
    pub fn new() -> Self {
        Codex {
            encoder: None,
            decoder: None,
        }
    }

    pub fn encode(&self) -> Genotype<G, A> {
        match &self.encoder {
            Some(encoder) => encoder(),
            None => panic!("Encoder not set"),
        }
    }

    pub fn decode(&self, genotype: &Genotype<G, A>) -> T {
        match &self.decoder {
            Some(decoder) => decoder(genotype),
            None => panic!("Decoder not set"),
        }
    }

    pub fn encoder(mut self, encoder: impl Fn() -> Genotype<G, A> + 'static) -> Self {
        self.encoder = Some(Box::new(encoder));
        self
    }

    pub fn decoder(mut self, decoder: fn(&Genotype<G, A>) -> T) -> Self {
        self.decoder = Some(decoder);
        self
    }

    pub fn spawn(&self, num: i32) -> Vec<T> {
        (0..num)
            .into_iter()
            .map(|_| self.decode(&self.encode()))
            .collect::<Vec<T>>()
    }

    pub fn spawn_genotypes(&self, num: i32) -> Vec<Genotype<G, A>> {
        (0..num)
            .into_iter()
            .map(|_| self.encode())
            .collect::<Vec<Genotype<G, A>>>()
    }

    pub fn spawn_population(&self, num: i32) -> Population<G, A> {
        (0..num)
            .into_iter()
            .map(|_| Phenotype::from_genotype(self.encode(), 0))
            .collect::<Population<G, A>>()
    }
}


pub fn char(num_chromosomes: usize, num_genes: usize) -> Codex<CharGene, char, String> {
    Codex::new()
        .encoder(move || Genotype {
            chromosomes: (0..num_chromosomes)
                .into_iter()
                .map(|_| Chromosome::from_genes((0..num_genes)
                        .into_iter()
                        .map(|_| CharGene::new())
                        .collect::<Vec<CharGene>>()))
                .collect::<Vec<Chromosome<CharGene, char>>>(),
        })
        .decoder(|genotype| {
            genotype
                .iter()
                .map(|chromosome| {
                    chromosome
                        .iter()
                        .map(|gene| gene.allele())
                        .collect::<String>()
                })
                .collect::<String>()
        })
}

pub fn float(
    num_chromosomes: i32,
    num_genes: i32,
    min: f32,
    max: f32,
) -> Codex<FloatGene, f32, Vec<Vec<f32>>> {
    Codex::new()
        .encoder(move || Genotype {
            chromosomes: (0..num_chromosomes)
                .into_iter()
                .map(|_| Chromosome::from_genes((0..num_genes)
                        .into_iter()
                        .map(|_| FloatGene::new(min, max))
                        .collect::<Vec<FloatGene>>()))
                .collect::<Vec<Chromosome<FloatGene, f32>>>()
        })
        .decoder(|genotype| {
            genotype
                .iter()
                .map(|chromosome| {
                    chromosome
                        .iter()
                        .map(|gene| gene.allele())
                        .collect::<Vec<f32>>()
                })
                .collect::<Vec<Vec<f32>>>()
        })
}

pub fn bit(num_chromosomes: i32, num_genes: i32) -> Codex<BitGene, bool , Vec<Vec<bool>>> {
    Codex::new()
        .encoder(move || Genotype {
            chromosomes: (0..num_chromosomes)
                .into_iter()
                .map(|_| Chromosome::from_genes((0..num_genes)
                        .into_iter()
                        .map(|_| BitGene::new())
                        .collect::<Vec<BitGene>>()))
                .collect::<Vec<Chromosome<BitGene, bool>>>()
        })
        .decoder(|genotype| {
            genotype
                .iter()
                .map(|chromosome| {
                    chromosome
                        .iter()
                        .map(|gene| gene.allele())
                        .collect::<Vec<bool>>()
                })
                .collect::<Vec<Vec<bool>>>()
        })
}

pub fn int(
    num_chromosomes: i32,
    num_genes: i32,
    max: i32,
    min: i32,
) -> Codex<IntGene, i32, Vec<Vec<i32>>> {
    int_with_bounds(num_chromosomes, num_genes, max, min, i32::MAX, i32::MIN)
}

pub fn int_with_bounds(
    num_chromosomes: i32,
    num_genes: i32,
    max: i32,
    min: i32,
    upper_bound: i32,
    lower_bound: i32,
) -> Codex<IntGene, i32, Vec<Vec<i32>>> {
    Codex::new()
        .encoder(move || Genotype {
            chromosomes: (0..num_chromosomes)
                .into_iter()
                .map(|_| Chromosome::from_genes((0..num_genes)
                    .into_iter()
                    .map(|_| IntGene::new(min, max).with_bounds(upper_bound, lower_bound))
                    .collect::<Vec<IntGene>>()))
                .collect::<Vec<Chromosome<IntGene, i32>>>()
        })
        .decoder(|genotype| {
            genotype
                .iter()
                .map(|chromosome| {
                    chromosome
                        .iter()
                        .map(|gene| gene.allele())
                        .collect::<Vec<i32>>()
                })
                .collect::<Vec<Vec<i32>>>()
        })
}


#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_char() {
        let codex = char(1, 3);
        let genotype = codex.encode();
        let decoded = codex.decode(&genotype);
        assert_eq!(decoded.len(), 3);
    }

    #[test]
    fn test_float() {
        let codex = float(2, 3, 0.0, 1.0);
        let genotype = codex.encode();
        let decoded = codex.decode(&genotype);
        assert_eq!(decoded.len(), 2);
        assert_eq!(decoded[0].len(), 3);
    }

    #[test]
    fn test_bit() {
        let codex = bit(2, 3);
        let genotype = codex.encode();
        let decoded = codex.decode(&genotype);
        assert_eq!(decoded.len(), 2);
        assert_eq!(decoded[0].len(), 3);
    }

    #[test]
    fn test_int() {
        let codex = int(2, 3, 0, 1);
        let genotype = codex.encode();
        let decoded = codex.decode(&genotype);
        assert_eq!(decoded.len(), 2);
        assert_eq!(decoded[0].len(), 3);
    }
}