radiate_core/genome/chromosomes/chromosome.rs
1use super::{Valid, gene::Gene};
2
3/// The [Chromosome] is part of the genetic makeup of an individual.
4/// It is a collection of [Gene] instances, it is essentially a
5/// light wrapper around a Vec of [Gene]s. The [Chromosome] struct, however, has some additional
6/// functionality and terminology that aligns with the biological concept of a chromosome
7///
8/// In traditional biological terms, a [Chromosome] is a long DNA molecule with part or all of the
9/// genetic material of an organism. The [Chromosome] is the 'genetic' part of the individual that is
10/// being evolved by the genetic algorithm.
11///
12/// We can think of a [Chromosome] as a Vec of structs which implement the [Gene] trait. For example,
13/// if we have a [Chromosome] with 3 [Gene]s, it is represented as follows:
14/// ```text
15/// Chromosome: [Gene, Gene, Gene]
16/// ```
17pub trait Chromosome: Valid {
18 type Gene: Gene;
19
20 fn as_slice(&self) -> &[Self::Gene];
21 fn as_mut_slice(&mut self) -> &mut [Self::Gene];
22
23 /// Retrieves the gene at the specified index.
24 ///
25 /// # Arguments
26 ///
27 /// * `index` - The position of the gene to retrieve.
28 ///
29 fn get(&self, index: usize) -> &Self::Gene {
30 &self.as_slice()[index]
31 }
32
33 fn get_mut(&mut self, index: usize) -> &mut Self::Gene {
34 &mut self.as_mut_slice()[index]
35 }
36
37 /// Sets the gene at the specified index.
38 ///
39 /// # Arguments
40 ///
41 /// * `index` - The position of the gene to set.
42 /// * [`Gene`] - The gene to replace at the specified index.
43 ///
44 fn set(&mut self, index: usize, gene: Self::Gene) {
45 self.as_mut_slice()[index] = gene;
46 }
47
48 fn len(&self) -> usize {
49 self.as_slice().len()
50 }
51
52 fn iter(&self) -> impl Iterator<Item = &Self::Gene> {
53 self.as_slice().iter()
54 }
55
56 fn iter_mut(&mut self) -> impl Iterator<Item = &mut Self::Gene> {
57 self.as_mut_slice().iter_mut()
58 }
59
60 fn zip_mut<'a>(
61 &'a mut self,
62 other: &'a mut Self,
63 ) -> impl Iterator<Item = (&'a mut Self::Gene, &'a mut Self::Gene)> {
64 self.iter_mut().zip(other.iter_mut())
65 }
66}