radiate_rust/engines/codexes/
float_codex.rs1use crate::engines::genome::chromosome::Chromosome;
2use crate::engines::genome::genes::float_gene::FloatGene;
3use crate::engines::genome::genes::gene::{BoundGene, Gene};
4use crate::engines::genome::genotype::Genotype;
5
6use super::Codex;
7
8pub struct FloatCodex {
9 pub num_chromosomes: usize,
10 pub num_genes: usize,
11 pub min: f32,
12 pub max: f32,
13 pub lower_bound: f32,
14 pub upper_bound: f32,
15}
16
17impl FloatCodex {
18 pub fn new(num_chromosomes: usize, num_genes: usize, min: f32, max: f32) -> Self {
19 FloatCodex {
20 num_chromosomes,
21 num_genes,
22 min,
23 max,
24 lower_bound: f32::MIN,
25 upper_bound: f32::MAX,
26 }
27 }
28
29 pub fn with_bounds(mut self, lower_bound: f32, upper_bound: f32) -> Self {
30 self.lower_bound = lower_bound;
31 self.upper_bound = upper_bound;
32 self
33 }
34
35 pub fn scalar(min: f32, max: f32) -> Self {
36 FloatCodex::new(1, 1, min, max)
37 }
38}
39
40impl Codex<FloatGene, f32, Vec<Vec<f32>>> for FloatCodex {
41 fn encode(&self) -> Genotype<FloatGene, f32> {
42 Genotype {
43 chromosomes: (0..self.num_chromosomes)
44 .into_iter()
45 .map(|_| Chromosome::from_genes((0..self.num_genes)
46 .into_iter()
47 .map(|_| FloatGene::new(self.min, self.max).with_bounds(self.lower_bound, self.upper_bound))
48 .collect::<Vec<FloatGene>>()))
49 .collect::<Vec<Chromosome<FloatGene, f32>>>(),
50 }
51 }
52
53 fn decode(&self, genotype: &Genotype<FloatGene, f32>) -> Vec<Vec<f32>> {
54 genotype
55 .iter()
56 .map(|chromosome| {
57 chromosome
58 .iter()
59 .map(|gene| *gene.allele())
60 .collect::<Vec<f32>>()
61 })
62 .collect::<Vec<Vec<f32>>>()
63 }
64}