radiate_core/codecs/
permutation.rs1use crate::{
2 Codec, Gene, Genotype, PermutationChromosome, PermutationGene,
3 chromosomes::ContiguousChromosome, random_provider,
4};
5use std::sync::Arc;
6
7#[derive(Clone)]
8pub struct PermutationCodec<A: PartialEq + Clone> {
9 alleles: Arc<[A]>,
10}
11
12impl<A: PartialEq + Clone> PermutationCodec<A> {
13 pub fn new(alleles: Vec<A>) -> Self {
14 PermutationCodec {
15 alleles: alleles.into_boxed_slice().into(),
16 }
17 }
18}
19
20impl<A: PartialEq + Clone> Codec<PermutationChromosome<A>, Vec<A>> for PermutationCodec<A> {
21 fn encode(&self) -> Genotype<PermutationChromosome<A>> {
22 Genotype::from(PermutationChromosome::new(
23 random_provider::shuffled_indices(0..self.alleles.len())
24 .iter()
25 .map(|i| PermutationGene::new(*i, Arc::clone(&self.alleles)))
26 .collect(),
27 Arc::clone(&self.alleles),
28 ))
29 }
30
31 fn decode(&self, genotype: &Genotype<PermutationChromosome<A>>) -> Vec<A> {
32 genotype
33 .iter()
34 .flat_map(|chromosome| {
35 chromosome
36 .as_slice()
37 .iter()
38 .map(|gene| gene.allele().clone())
39 })
40 .collect()
41 }
42}
43
44impl<A: PartialEq + Clone> Codec<PermutationChromosome<A>, Vec<Vec<A>>>
45 for Vec<PermutationChromosome<A>>
46{
47 fn encode(&self) -> Genotype<PermutationChromosome<A>> {
48 Genotype::from(
49 self.iter()
50 .map(|chromosome| {
51 PermutationChromosome::new(
52 chromosome
53 .as_slice()
54 .iter()
55 .map(|gene| gene.new_instance())
56 .collect(),
57 Arc::clone(chromosome.alleles()),
58 )
59 })
60 .collect::<Vec<PermutationChromosome<A>>>(),
61 )
62 }
63
64 fn decode(&self, genotype: &Genotype<PermutationChromosome<A>>) -> Vec<Vec<A>> {
65 genotype
66 .iter()
67 .map(|chromosome| {
68 chromosome
69 .as_slice()
70 .iter()
71 .map(|gene| gene.allele().clone())
72 .collect::<Vec<A>>()
73 })
74 .collect::<Vec<Vec<A>>>()
75 }
76}
77
78impl<A: PartialEq + Clone> Codec<PermutationChromosome<A>, Vec<A>> for PermutationChromosome<A> {
79 fn encode(&self) -> Genotype<PermutationChromosome<A>> {
80 Genotype::from(PermutationChromosome::new(
81 self.as_slice()
82 .iter()
83 .map(|gene| gene.new_instance())
84 .collect(),
85 Arc::clone(self.alleles()),
86 ))
87 }
88
89 fn decode(&self, genotype: &Genotype<PermutationChromosome<A>>) -> Vec<A> {
90 genotype
91 .iter()
92 .flat_map(|chromosome| {
93 chromosome
94 .as_slice()
95 .iter()
96 .map(|gene| gene.allele().clone())
97 })
98 .collect()
99 }
100}