radiate_extensions/architects/
node_collection_builder.rs

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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
use std::collections::{BTreeMap, HashSet};

use crate::architects::node_collections::node::Node;
use crate::architects::node_collections::NodeCollection;
use crate::architects::node_collections::node_factory::NodeFactory;
use crate::architects::schema::node_types::NodeType;

use uuid::Uuid;

use super::NodeRepairs;

pub enum ConnectTypes {
    OneToOne,
    OneToMany,
    ManyToOne,
    AllToAll,
    AllToAllSelf,
    ParentToChild,
    Replace,
}

pub struct Relationship<'a> {
    pub source_id: &'a Uuid,
    pub target_id: &'a Uuid,
}

#[derive(Default)]
pub struct NodeCollectionBuilder<'a, C, T>
where
    C: NodeCollection<T> + NodeRepairs<T>,
    T: Clone + PartialEq + Default,
{
    pub factory: Option<&'a NodeFactory<T>>,
    pub nodes: BTreeMap<&'a Uuid, &'a Node<T>>,
    pub node_order: BTreeMap<usize, &'a Uuid>,
    pub relationships: Vec<Relationship<'a>>,
    pub removed: HashSet<&'a Uuid>,
    _phantom_c: std::marker::PhantomData<C>,
}

impl<'a, C, T> NodeCollectionBuilder<'a, C, T>
where
    C: NodeCollection<T> + NodeRepairs<T>,
    T: Clone + PartialEq + Default,
{
    pub fn new(factory: &'a NodeFactory<T>) -> Self {
        NodeCollectionBuilder {
            factory: Some(factory),
            nodes: BTreeMap::new(),
            node_order: BTreeMap::new(),
            relationships: Vec::new(),
            removed: HashSet::new(),
            _phantom_c: std::marker::PhantomData,
        }
    }

    pub fn one_to_one(mut self, one: &'a C, two: &'a C) -> Self {
        self.connect(ConnectTypes::OneToOne, one, two);
        self
    }

    pub fn one_to_many(mut self, one: &'a C, two: &'a C) -> Self {
        self.connect(ConnectTypes::OneToMany, one, two);
        self
    }

    pub fn many_to_one(mut self, one: &'a C, two: &'a C) -> Self {
        self.connect(ConnectTypes::ManyToOne, one, two);
        self
    }

    pub fn all_to_all(mut self, one: &'a C, two: &'a C) -> Self {
        self.connect(ConnectTypes::AllToAll, one, two);
        self
    }

    pub fn one_to_one_self(mut self, one: &'a C, two: &'a C) -> Self {
        self.connect(ConnectTypes::AllToAllSelf, one, two);
        self
    }

    pub fn parent_to_child(mut self, one: &'a C, two: &'a C) -> Self {
        self.connect(ConnectTypes::ParentToChild, one, two);
        self
    }

    pub fn replace(mut self, one: &'a C, two: &'a C) -> Self {
        self.connect(ConnectTypes::Replace, one, two);
        self
    }

    pub fn insert(mut self, collection: &'a C) -> Self {
        self.attach(collection.get_nodes());
        self
    }

    pub fn build(self) -> C {
        let mut index = 0;
        let mut new_nodes = Vec::new();
        let mut node_id_index_map = BTreeMap::new();

        for (_, node_id) in self.node_order.iter() {
            if self.removed.contains(node_id) {
                continue;
            }

            let node = self.nodes.get(node_id).unwrap();
            let new_node = Node::new(index, node.node_type, node.value.clone());

            new_nodes.push(new_node);
            node_id_index_map.insert(node_id, index);

            index += 1;
        }

        let mut new_collection = C::from_nodes(new_nodes);
        for rel in self.relationships {
            if self.removed.contains(rel.source_id) || self.removed.contains(rel.target_id) {
                continue;
            }

            let source_idx = node_id_index_map.get(&rel.source_id).unwrap();
            let target_idx = node_id_index_map.get(&rel.target_id).unwrap();

            new_collection.attach(*source_idx, *target_idx);
        }

        new_collection.repair(self.factory)
    }

    pub fn layer(&self, collections: Vec<&'a C>) -> Self {
        let mut conn = NodeCollectionBuilder::new(self.factory.unwrap());
        let mut previous = collections[0];

        for collection in collections.iter() {
            conn.attach((*collection).get_nodes());
        }

        for i in 1..collections.len() {
            conn = conn.one_to_one(previous, collections[i]);
            previous = collections[i];
        }

        conn
    }

    pub fn connect(&mut self, connection: ConnectTypes, one: &'a C, two: &'a C) {
        self.attach(one.get_nodes());
        self.attach(two.get_nodes());

        match connection {
            ConnectTypes::OneToOne => self.one_to_one_connect(one, two),
            ConnectTypes::OneToMany => self.one_to_many_connect(one, two),
            ConnectTypes::ManyToOne => self.many_to_one_connect(one, two),
            ConnectTypes::AllToAll => self.all_to_all_connect(one, two),
            ConnectTypes::AllToAllSelf => self.all_to_all_self_connect(one, two),
            ConnectTypes::ParentToChild => self.parent_to_child_connect(one, two),
            ConnectTypes::Replace => self.replace_connect(one, two),
        }
    }

    pub fn attach(&mut self, group: &'a [Node<T>]) {
        for node in group.iter() {
            if !self.nodes.contains_key(&node.id) {
                let node_id = &node.id;

                self.nodes.insert(node_id, node);
                self.node_order.insert(self.node_order.len(), node_id);

                for outgoing in group
                    .iter()
                    .filter(|item| node.outgoing().contains(&item.index))
                {
                    self.relationships.push(Relationship {
                        source_id: &node.id,
                        target_id: &outgoing.id,
                    });
                }
            }
        }
    }

    fn replace_connect(&mut self, one: &'a C, two: &'a C) {
        let two_inputs = self.get_inputs(two);
        let one_inputs = self.get_inputs(one);

        for node in one.iter() {
            self.removed.insert(&node.id);
        }

        let source_to_removed = self
            .relationships
            .iter()
            .filter(|rel| one_inputs.iter().any(|node| node.id == *rel.target_id))
            .map(|rel| (rel.source_id, rel.target_id))
            .collect::<Vec<(&Uuid, &Uuid)>>();

        if source_to_removed.len() != two_inputs.len() {
            panic!("Replace - OneGroup outputs must be the same length as TwoGroup inputs.");
        }

        for (source, target) in source_to_removed.into_iter().zip(two_inputs.into_iter()) {
            self.relationships.push(Relationship {
                source_id: source.0,
                target_id: &target.id,
            });
        }
    }

    fn one_to_one_connect(&mut self, one: &'a C, two: &'a C) {
        let one_outputs = self.get_outputs(one);
        let two_inputs = self.get_inputs(two);

        if one_outputs.len() != two_inputs.len() {
            panic!("OneToOne - oneGroup outputs must be the same length as twoGroup inputs.");
        }

        for (one, two) in one_outputs.into_iter().zip(two_inputs.into_iter()) {
            self.relationships.push(Relationship {
                source_id: &one.id,
                target_id: &two.id,
            });
        }
    }

    fn one_to_many_connect(&mut self, one: &'a C, two: &'a C) {
        let one_outputs = self.get_outputs(one);
        let two_inputs = self.get_inputs(two);

        if two_inputs.len() % one_outputs.len() != 0 {
            panic!("OneToMany - TwoGroup inputs must be a multiple of OneGroup outputs.");
        }

        for targets in two_inputs.chunks(one_outputs.len()) {
            for (source, target) in one_outputs.iter().zip(targets.iter()) {
                self.relationships.push(Relationship {
                    source_id: &source.id,
                    target_id: &target.id,
                });
            }
        }
    }

    fn many_to_one_connect(&mut self, one: &'a C, two: &'a C) {
        let one_outputs = self.get_outputs(one);
        let two_inputs = self.get_inputs(two);

        if one_outputs.len() % two_inputs.len() != 0 {
            panic!("ManyToOne - OneGroup outputs must be a multiple of TwoGroup inputs.");
        }

        for sources in one_outputs.chunks(two_inputs.len()) {
            for (source, target) in sources.iter().zip(two_inputs.iter()) {
                self.relationships.push(Relationship {
                    source_id: &source.id,
                    target_id: &target.id,
                });
            }
        }
    }

    fn all_to_all_connect(&mut self, one: &'a C, two: &'a C) {
        let one_outputs = self.get_outputs(one);
        let two_inputs = self.get_inputs(two);

        for source in one_outputs {
            for target in two_inputs.iter() {
                self.relationships.push(Relationship {
                    source_id: &source.id,
                    target_id: &target.id,
                });
            }
        }
    }

    fn all_to_all_self_connect(&mut self, one: &'a C, two: &'a C) {
        let one_outputs = self.get_outputs(one);
        let two_inputs = self.get_inputs(two);

        if one_outputs.len() != two_inputs.len() {
            panic!("Self - oneGroup outputs must be the same length as twoGroup inputs.");
        }

        for (one, two) in one_outputs.into_iter().zip(two_inputs.into_iter()) {
            self.relationships.push(Relationship {
                source_id: &one.id,
                target_id: &two.id,
            });
            self.relationships.push(Relationship {
                source_id: &two.id,
                target_id: &one.id,
            });
        }
    }

    fn parent_to_child_connect(&mut self, one: &'a C, two: &'a C) {
        let one_outputs = self.get_outputs(one);
        let two_inputs = self.get_inputs(two);

        if one_outputs.len() != 1 {
            panic!("ParentToChild - oneGroup outputs must be a single node.");
        }

        let parent_node = one_outputs[0];
        for child_node in two_inputs {
            self.relationships.push(Relationship {
                source_id: &parent_node.id,
                target_id: &child_node.id,
            });
        }
    }

    fn get_outputs(&self, collection: &'a C) -> Vec<&'a Node<T>> {
        let outputs = collection
            .iter()
            .enumerate()
            .skip_while(|(_, node)| !node.outgoing().is_empty())
            .map(|(idx, _)| collection.get(idx))
            .collect::<Vec<&Node<T>>>();

        if !outputs.is_empty() {
            return outputs;
        }

        let recurrent_outputs = collection
            .iter()
            .enumerate()
            .filter(|(_, node)| {
                node.outgoing().len() == 1
                    && node.is_recurrent()
                    && (node.node_type() == &NodeType::Gate
                        || node.node_type() == &NodeType::Aggregate)
            })
            .map(|(idx, _)| collection.get(idx))
            .collect::<Vec<&Node<T>>>();

        if !recurrent_outputs.is_empty() {
            return recurrent_outputs;
        }

        collection
            .iter()
            .enumerate()
            .filter(|(_, node)| node.incoming().is_empty())
            .map(|(idx, _)| collection.get(idx))
            .collect::<Vec<&Node<T>>>()
    }

    fn get_inputs(&self, collection: &'a C) -> Vec<&'a Node<T>> {
        let inputs = collection
            .iter()
            .enumerate()
            .take_while(|(_, node)| node.incoming().is_empty())
            .map(|(idx, _)| collection.get(idx))
            .collect::<Vec<&Node<T>>>();

        if !inputs.is_empty() {
            return inputs;
        }

        let recurrent_inputs = collection
            .iter()
            .enumerate()
            .filter(|(_, node)| {
                node.outgoing().len() == 1
                    && node.is_recurrent()
                    && node.node_type() == &NodeType::Gate
            })
            .map(|(idx, _)| collection.get(idx))
            .collect::<Vec<&Node<T>>>();

        if !recurrent_inputs.is_empty() {
            return recurrent_inputs;
        }

        collection
            .iter()
            .enumerate()
            .filter(|(_, node)| node.outgoing().is_empty())
            .map(|(idx, _)| collection.get(idx))
            .collect::<Vec<&Node<T>>>()
    }
}