radiate_gp/collections/graphs/
codex.rs

1use super::{Graph, GraphChromosome, GraphNode};
2use crate::{Factory, NodeStore};
3use radiate::{Chromosome, Codex, Genotype};
4
5pub struct GraphCodex<T> {
6    store: NodeStore<T>,
7    template: GraphChromosome<T>,
8}
9
10impl<T> GraphCodex<T> {
11    pub fn directed(input_size: usize, output_size: usize, store: impl Into<NodeStore<T>>) -> Self
12    where
13        T: Clone + Default,
14    {
15        let new_store = store.into();
16
17        GraphCodex {
18            store: new_store.clone(),
19            template: Graph::directed(input_size, output_size, &new_store)
20                .into_iter()
21                .collect(),
22        }
23    }
24
25    pub fn recurrent(input_size: usize, output_size: usize, store: impl Into<NodeStore<T>>) -> Self
26    where
27        T: Clone + Default,
28    {
29        let new_store = store.into();
30
31        GraphCodex {
32            store: new_store.clone(),
33            template: Graph::recurrent(input_size, output_size, &new_store)
34                .into_iter()
35                .collect(),
36        }
37    }
38}
39
40impl<T> Codex<GraphChromosome<T>, Graph<T>> for GraphCodex<T>
41where
42    T: Clone + PartialEq + Default,
43{
44    fn encode(&self) -> Genotype<GraphChromosome<T>> {
45        let chromosome = self.template.new_instance(Some(self.store.clone()));
46        return Genotype::new(vec![chromosome]);
47    }
48
49    fn decode(&self, genotype: &Genotype<GraphChromosome<T>>) -> Graph<T> {
50        Graph::new(
51            genotype
52                .iter()
53                .next()
54                .unwrap()
55                .iter()
56                .cloned()
57                .collect::<Vec<GraphNode<T>>>(),
58        )
59    }
60}