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
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
use nalgebra::DMatrix;
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
use uuid::Uuid;

/// Helper for serializing maps with consistent ordering.
fn sort_alphabetically<T: Serialize, S: serde::Serializer>(
    value: &T,
    serializer: S,
) -> Result<S::Ok, S::Error> {
    let value = serde_json::to_value(value).map_err(serde::ser::Error::custom)?;
    value.serialize(serializer)
}

/// Metadata struct that contains common metadata for any instance.
#[derive(Serialize, Deserialize, Debug)]
pub struct Meta {
    /// Unique instance ID.
    pub id: Uuid,
    /// Instance name.
    pub name: String,
    /// Main category of this instance.
    pub kind: String,
    /// Instance labels.
    pub labels: Vec<String>,
    /// Numeric instance weights.
    #[serde(serialize_with = "sort_alphabetically")]
    pub weights: HashMap<String, f64>,
    /// Miscellaneous data fields for this instance.
    #[serde(serialize_with = "sort_alphabetically")]
    pub annotations: HashMap<String, String>,
}

impl Meta {
    /// Create a new Meta struct with arguments.
    pub fn new(
        id: Option<Uuid>,
        name: Option<String>,
        kind: Option<String>,
        labels: Option<Vec<String>>,
        weights: Option<HashMap<String, f64>>,
        annotations: Option<HashMap<String, String>>,
    ) -> Self {
        let this_id: Uuid = match id {
            None => Uuid::new_v4(),
            Some(x) => x,
        };
        Meta {
            id: this_id,
            name: match name {
                None => this_id.to_string(),
                Some(x) => x,
            },
            kind: match kind {
                None => String::from("default"),
                Some(x) => x,
            },
            labels: match labels {
                None => vec![],
                Some(x) => x,
            },
            weights: match weights {
                None => HashMap::<String, f64>::new(),
                Some(x) => x,
            },
            annotations: match annotations {
                None => HashMap::<String, String>::new(),
                Some(x) => x,
            },
        }
    }

    /// Create a new Meta struct with default arguments.
    pub fn default() -> Self {
        Meta::new(None, None, None, None, None, None)
    }
}

#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct Node {
    /// Unique instance ID.
    pub id: Uuid,
    /// Instance name.
    pub name: String,
    /// Main category of this instance.
    pub kind: String,
    /// Instance labels.
    pub labels: Vec<String>,
    /// Numeric instance weights.
    #[serde(serialize_with = "sort_alphabetically")]
    pub weights: HashMap<String, f64>,
    /// Miscellaneous data fields for this instance.
    #[serde(serialize_with = "sort_alphabetically")]
    pub annotations: HashMap<String, String>,
    /// ID of the parent of this node, if any.
    pub parent: Option<Uuid>,
    /// IDs of this node's children,
    pub children: Vec<Uuid>,
    /// Whether this node is a bus node for its parent.
    pub is_bus: bool,
}

impl Node {
    /// Create a new node struct with arguments.
    pub fn new(
        id: Option<Uuid>,
        name: Option<String>,
        kind: Option<String>,
        labels: Option<Vec<String>>,
        weights: Option<HashMap<String, f64>>,
        annotations: Option<HashMap<String, String>>,
        parent: Option<Uuid>,
        children: Option<Vec<Uuid>>,
        is_bus: Option<bool>,
    ) -> Self {
        let Meta {
            id,
            name,
            kind,
            labels,
            weights,
            annotations,
        } = Meta::new(id, name, kind, labels, weights, annotations);

        Node {
            id,
            name,
            kind,
            labels,
            weights,
            annotations,
            parent,
            children: match children {
                None => vec![],
                Some(x) => x,
            },
            is_bus: match is_bus {
                None => false,
                Some(x) => x,
            },
        }
    }

    /// Create a new Node struct with default arguments.
    pub fn default() -> Self {
        Node::new(None, None, None, None, None, None, None, None, None)
    }
}

#[derive(Serialize, Deserialize, Debug)]
pub struct Edge {
    /// Unique instance ID.
    pub id: Uuid,
    /// Instance name.
    pub name: String,
    /// Main category of this instance.
    pub kind: String,
    /// Instance labels.
    pub labels: Vec<String>,
    /// Numeric instance weights.
    #[serde(serialize_with = "sort_alphabetically")]
    pub weights: HashMap<String, f64>,
    /// Miscellaneous data fields for this instance.
    #[serde(serialize_with = "sort_alphabetically")]
    pub annotations: HashMap<String, String>,
    /// Source node ID.
    pub source: Uuid,
    /// Target node ID.
    pub target: Uuid,
}

impl Edge {
    /// Create a new edge struct with arguments.
    pub fn new(
        id: Option<Uuid>,
        name: Option<String>,
        kind: Option<String>,
        labels: Option<Vec<String>>,
        weights: Option<HashMap<String, f64>>,
        annotations: Option<HashMap<String, String>>,
        source: Uuid,
        target: Uuid,
    ) -> Self {
        let Meta {
            id,
            name,
            kind,
            labels,
            weights,
            annotations,
        } = Meta::new(id, name, kind, labels, weights, annotations);
        Edge {
            id,
            name,
            kind,
            labels,
            weights,
            annotations,
            source,
            target,
        }
    }

    pub fn default() -> (Self, Node, Node) {
        let source = Node::default();
        let target = Node::default();
        (
            Edge::new(
                None,
                None,
                None,
                None,
                None,
                None,
                source.id.clone(),
                target.id.clone(),
            ),
            source,
            target,
        )
    }
}

#[derive(Serialize, Deserialize, Debug)]
pub struct Graph {
    /// Unique instance ID.
    pub id: Uuid,
    /// Instance name.
    pub name: String,
    /// Main category of this instance.
    pub kind: String,
    /// Instance labels.
    pub labels: Vec<String>,
    /// Numeric instance weights.
    #[serde(serialize_with = "sort_alphabetically")]
    pub weights: HashMap<String, f64>,
    /// Miscellaneous data fields for this instance.
    #[serde(serialize_with = "sort_alphabetically")]
    pub annotations: HashMap<String, String>,
    /// Nodes by their IDs.
    #[serde(serialize_with = "sort_alphabetically")]
    pub nodes: HashMap<Uuid, Node>,
    /// Edges by their IDs.
    #[serde(serialize_with = "sort_alphabetically")]
    pub edges: HashMap<Uuid, Edge>,
    /// Edges mapped from source ID, to target ID, to a Vec of edge IDs.
    #[serde(serialize_with = "sort_alphabetically")]
    _edges_forward: HashMap<Uuid, HashMap<Uuid, Vec<Uuid>>>,
    /// Edges mapped from target ID, to source ID, to a Vec of edge IDs.
    #[serde(serialize_with = "sort_alphabetically")]
    _edges_reverse: HashMap<Uuid, HashMap<Uuid, Vec<Uuid>>>,
}

impl Graph {
    /// Create a new graph instance with arguments.
    pub fn new(
        id: Option<Uuid>,
        name: Option<String>,
        kind: Option<String>,
        labels: Option<Vec<String>>,
        weights: Option<HashMap<String, f64>>,
        annotations: Option<HashMap<String, String>>,
        nodes: Option<Vec<Node>>,
        edges: Option<Vec<Edge>>,
    ) -> Self {
        let Meta {
            id,
            name,
            kind,
            labels,
            weights,
            annotations,
        } = Meta::new(id, name, kind, labels, weights, annotations);
        let mut graph = Graph {
            id,
            name,
            kind,
            labels,
            weights,
            annotations,
            nodes: HashMap::<Uuid, Node>::new(),
            edges: HashMap::<Uuid, Edge>::new(),
            _edges_forward: HashMap::<Uuid, HashMap<Uuid, Vec<Uuid>>>::new(),
            _edges_reverse: HashMap::<Uuid, HashMap<Uuid, Vec<Uuid>>>::new(),
        };
        if let Some(ns) = nodes {
            graph.add_nodes(ns, true)
        }
        if let Some(es) = edges {
            graph.add_edges(es, true);
        }
        graph
    }

    /// Create a new graph instance with default arguments.
    pub fn default() -> Self {
        Graph::new(None, None, None, None, None, None, None, None)
    }

    /// Update the forward edge map..
    pub fn update_edges_forward(&mut self) {
        self._edges_forward = {
            let mut map = HashMap::<Uuid, HashMap<Uuid, Vec<Uuid>>>::new();
            for edge in self.edges.values() {
                let id = edge.id.to_owned();
                let source = edge.source.to_owned();
                let target = edge.target.to_owned();
                map.entry(source.to_owned())
                    .or_insert(HashMap::<Uuid, Vec<Uuid>>::new())
                    .entry(target.to_owned())
                    .or_insert(vec![])
                    .push(id.to_owned());
            }
            map
        }
    }

    /// Update the reverse edge map..
    pub fn update_edges_reverse(&mut self) {
        self._edges_reverse = {
            let mut map = HashMap::<Uuid, HashMap<Uuid, Vec<Uuid>>>::new();
            for edge in self.edges.values() {
                let id = edge.id.to_owned();
                let source = edge.source.to_owned();
                let target = edge.target.to_owned();
                map.entry(target.to_owned())
                    .or_insert(HashMap::<Uuid, Vec<Uuid>>::new())
                    .entry(source.to_owned())
                    .or_insert(vec![])
                    .push(id.to_owned());
            }
            map
        }
    }

    /// Update edge maps.
    pub fn update_edge_maps(&mut self) {
        self.update_edges_forward();
        self.update_edges_reverse();
    }

    /// Whether a node ID exists in the graph.
    pub fn has_node(&self, id: &Uuid) -> bool {
        self.nodes.contains_key(&id)
    }

    /// Whether an edge ID exists in the graph.
    pub fn has_edge(&self, id: &Uuid) -> bool {
        self.edges.contains_key(&id)
    }

    /// Add a single node.
    pub fn add_node(&mut self, node: Node, safe: bool) {
        let id = node.id.to_owned();
        self.nodes.insert(id.to_owned(), node);
        if safe {
            self.check_node(&id);
        }
    }

    /// Add multiple nodes.
    pub fn add_nodes(&mut self, nodes: Vec<Node>, safe: bool) {
        let mut ids = vec![];
        for n in nodes {
            ids.push(n.id.to_owned());
            self.add_node(n, false);
        }
        if safe {
            for id in ids {
                self.check_node(&id);
            }
        }
    }

    /// Check whether a node's references exist.
    pub fn check_node(&self, id: &Uuid) {
        if let Some(node) = self.nodes.get(&id) {
            if let Some(parent_id) = node.parent {
                if !self.has_node(&parent_id) {
                    panic!("Parent node doesn't exist in this graph.");
                }
            }
            for child_id in node.children.iter() {
                if !self.has_node(&child_id) {
                    panic!("Child node doesn't exist in this graph.");
                }
            }
            if node.is_bus {
                match node.parent {
                    None => panic!("Node is a bus without a parent."),
                    Some(_) => (),
                };
            }
        } else {
            panic!("Node should exist!");
        }
    }

    /// Set parent value for a node.
    pub fn set_parent(&mut self, child_id: &Uuid, parent_id: Option<&Uuid>) {
        if !self.has_node(&child_id) {
            return;
        }
        // Remove child from current parent
        if let Some(child) = self.nodes.get(child_id) {
            if let Some(current_parent_id) = child.parent {
                if let Some(current_parent) = self.nodes.get_mut(&current_parent_id) {
                    current_parent.children.retain(|x| x != child_id);
                }
            }
        }

        // Unset current parent.
        if let Some(child) = self.nodes.get_mut(child_id) {
            child.parent = None;
        }

        // Set new parent.
        if let Some(p_id) = parent_id {
            if self.has_node(p_id) {
                if let Some(child) = self.nodes.get_mut(child_id) {
                    child.parent = Some(p_id.to_owned());
                }
                if let Some(parent) = self.nodes.get_mut(p_id) {
                    parent.children.push(child_id.to_owned());
                }
            } else {
                if let Some(child) = self.nodes.get_mut(child_id) {
                    child.is_bus = false;
                }
            }
        }
    }

    /**
    Set the is_bus value of a node. Will only ever be set to `true` is it has a parent
    node to be a bus for.
    */
    pub fn set_bus(&mut self, child_id: &Uuid, is_bus: bool) {
        if let Some(child) = self.nodes.get_mut(child_id) {
            match child.parent {
                None => child.is_bus = false,
                Some(_) => child.is_bus = is_bus,
            };
        }
    }

    /// Add a single edge.
    pub fn add_edge(&mut self, edge: Edge, safe: bool) {
        let id = edge.id.to_owned();
        let source = edge.source.to_owned();
        let target = edge.target.to_owned();
        self._edges_forward
            .entry(source.to_owned())
            .or_insert(HashMap::<Uuid, Vec<Uuid>>::new())
            .entry(target.to_owned())
            .or_insert(vec![])
            .push(id.to_owned());
        self._edges_reverse
            .entry(source)
            .or_insert(HashMap::<Uuid, Vec<Uuid>>::new())
            .entry(target)
            .or_insert(vec![])
            .push(id.to_owned());
        self.edges.insert(id.to_owned(), edge);
        if safe {
            self.check_edge(&id);
        }
    }

    /// Add multiple edges.
    pub fn add_edges(&mut self, edges: Vec<Edge>, safe: bool) {
        for e in edges {
            self.add_edge(e, safe);
        }
    }

    /// Check whether an edge's references exist.
    pub fn check_edge(&self, id: &Uuid) {
        if let Some(edge) = self.edges.get(id) {
            if !self.has_node(&edge.source) {
                panic!("Source node should exist in the graph.");
            }
            if !self.has_node(&edge.target) {
                panic!("Target node should exist in the graph.");
            }
        } else {
            panic!("Edge should exist!");
        }
    }

    /// Get the adjacency matrix for this graph.
    pub fn get_adjacency_matrix(
        &self,
        sources: Option<Vec<Uuid>>,
        targets: Option<Vec<Uuid>>,
        aggregator: &Aggregator,
        fields: Option<&HashSet<String>>,
    ) -> DMatrix<f64> {
        let _sources: Vec<Uuid> = match sources {
            None => {
                let mut vec: Vec<Uuid> = self.nodes.keys().map(|x| x.to_owned()).collect();
                vec.sort();
                vec
            }
            Some(srcs) => srcs,
        };
        let _targets = match targets {
            None => _sources.clone(),
            Some(tgts) => tgts,
        };

        let mut adj = DMatrix::<f64>::zeros(_sources.len(), _targets.len());

        for (col, source) in _sources.iter().enumerate() {
            if !self._edges_forward.contains_key(source) {
                continue;
            }
            let tgt_map = self._edges_forward.get(source).unwrap();
            for (row, target) in _targets.iter().enumerate() {
                if !tgt_map.contains_key(target) {
                    continue;
                }
                let edges: Vec<&Edge> = tgt_map
                    .get(target)
                    .unwrap()
                    .iter()
                    .map(|x| self.edges.get(x).unwrap())
                    .collect();
                adj[(row, col)] = get_aggregate(&edges, &aggregator, &fields);
            }
        }

        adj
    }
}

pub enum Aggregator {
    Kinds,
    Labels,
    Weights,
    Annotations,
}

pub trait Metadata {
    fn get_meta(&self) -> Meta;
}

impl Metadata for Meta {
    fn get_meta(&self) -> Meta {
        Meta {
            id: self.id.to_owned(),
            name: self.name.clone(),
            kind: self.kind.clone(),
            labels: self.labels.clone(),
            weights: self.weights.clone(),
            annotations: self.annotations.clone(),
        }
    }
}

impl Metadata for Node {
    fn get_meta(&self) -> Meta {
        Meta {
            id: self.id.to_owned(),
            name: self.name.clone(),
            kind: self.kind.clone(),
            labels: self.labels.clone(),
            weights: self.weights.clone(),
            annotations: self.annotations.clone(),
        }
    }
}
impl Metadata for Edge {
    fn get_meta(&self) -> Meta {
        Meta {
            id: self.id.to_owned(),
            name: self.name.clone(),
            kind: self.kind.clone(),
            labels: self.labels.clone(),
            weights: self.weights.clone(),
            annotations: self.annotations.clone(),
        }
    }
}

impl Metadata for Graph {
    fn get_meta(&self) -> Meta {
        Meta {
            id: self.id.to_owned(),
            name: self.name.clone(),
            kind: self.kind.clone(),
            labels: self.labels.clone(),
            weights: self.weights.clone(),
            annotations: self.annotations.clone(),
        }
    }
}

pub fn get_aggregate(
    objects: &Vec<&impl Metadata>,
    aggregator: &Aggregator,
    fields: &Option<&HashSet<String>>,
) -> f64 {
    get_aggregates(objects, aggregator, fields).values().sum()
}

pub fn get_aggregates(
    objects: &Vec<&impl Metadata>,
    aggregator: &Aggregator,
    fields: &Option<&HashSet<String>>,
) -> HashMap<String, f64> {
    let mut map = HashMap::<String, f64>::new();

    match aggregator {
        Aggregator::Kinds => {
            for obj in objects.iter() {
                let meta = obj.get_meta();
                if let Some(fs) = fields {
                    if !fs.contains(&meta.kind) {
                        continue;
                    }
                }
                *map.entry(meta.kind.clone()).or_insert(0.0) += 1.0;
            }
        }
        Aggregator::Labels => {
            for obj in objects.iter() {
                let meta = obj.get_meta();
                if let Some(fs) = fields {
                    for label in meta.labels.iter() {
                        if !fs.contains(label) {
                            continue;
                        }
                        *map.entry(label.clone()).or_insert(0.0) += 1.0;
                    }
                } else {
                    for label in meta.labels.iter() {
                        *map.entry(label.clone()).or_insert(0.0) += 1.0;
                    }
                }
            }
        }
        Aggregator::Annotations => {
            for obj in objects.iter() {
                let meta = obj.get_meta();
                if let Some(fs) = fields {
                    for key in meta.annotations.keys() {
                        if !fs.contains(key) {
                            continue;
                        }
                        *map.entry(key.clone()).or_insert(0.0) += 1.0;
                    }
                } else {
                    for key in meta.annotations.keys() {
                        *map.entry(key.clone()).or_insert(0.0) += 1.0;
                    }
                }
            }
        }
        Aggregator::Weights => {
            for obj in objects.iter() {
                let meta = obj.get_meta();
                if let Some(fs) = fields {
                    for (key, value) in meta.weights.iter() {
                        if !fs.contains(key) {
                            continue;
                        }
                        *map.entry(key.clone()).or_insert(0.0) += value;
                    }
                } else {
                    for (key, value) in meta.weights.iter() {
                        *map.entry(key.clone()).or_insert(0.0) += value;
                    }
                }
            }
        }
    };

    map
}

#[cfg(test)]
mod tests {
    use super::*;
    use pretty_assertions::assert_eq;
    use serde_json::to_string;
    use uuid::uuid;
    #[test]
    fn test_meta() {
        let name = String::from("Hello meta");
        let id = Uuid::new_v4();
        let kind = String::from("default");
        let labels = vec![String::from("default")];
        let weights = HashMap::<String, f64>::new();
        let annotations = HashMap::<String, String>::new();
        let m1 = Meta {
            id,
            name,
            kind,
            labels,
            weights,
            annotations,
        };
        let m2 = Meta::new(
            Some(m1.id.to_owned()),
            Some(m1.name.to_owned()),
            Some(m1.kind.to_owned()),
            Some(m1.labels.to_owned()),
            None,
            None,
        );
        let s1 = to_string(&m1).unwrap();
        let s2 = to_string(&m2).unwrap();
        assert_eq!(s1, s2);
    }

    #[test]
    fn test_node() {
        let mut node = Node::default();
        node.id = uuid!("00000000-0000-0000-0000-000000000000");
        node.name = "test".to_string();
        let ser = to_string(&node).unwrap();
        assert_eq!(
            ser,
            r#"{"id":"00000000-0000-0000-0000-000000000000","name":"test","kind":"default","labels":[],"weights":{},"annotations":{},"parent":null,"children":[],"isBus":false}"#
        );
    }

    #[test]
    fn test_edge() {
        let (mut edge, _, _) = Edge::default();
        edge.id = uuid!("00000000-0000-0000-0000-000000000000");
        edge.source = uuid!("00000000-0000-0000-0000-000000000001");
        edge.target = uuid!("00000000-0000-0000-0000-000000000002");
        edge.name = "test".to_string();
        let ser = to_string(&edge).unwrap();
        assert_eq!(
            ser,
            r#"{"id":"00000000-0000-0000-0000-000000000000","name":"test","kind":"default","labels":[],"weights":{},"annotations":{},"source":"00000000-0000-0000-0000-000000000001","target":"00000000-0000-0000-0000-000000000002"}"#
        );
    }

    #[test]
    fn test_graph() {
        let mut graph = Graph::default();
        graph.id = uuid!("00000000-0000-0000-0000-000000000000");
        graph.name = "test".to_string();
        let ser = to_string(&graph).unwrap();
        assert_eq!(
            ser,
            r#"{"id":"00000000-0000-0000-0000-000000000000","name":"test","kind":"default","labels":[],"weights":{},"annotations":{},"nodes":{},"edges":{},"_edges_forward":{},"_edges_reverse":{}}"#
        );
        let source = Node {
            id: uuid!("a0000000-0000-0000-0000-000000000001"),
            name: "source".to_string(),
            ..Node::default()
        };
        let target = Node {
            id: uuid!("a0000000-0000-0000-0000-000000000002"),
            name: "target".to_string(),
            ..Node::default()
        };
        let edge1 = Edge {
            source: source.id.to_owned(),
            target: target.id.to_owned(),
            id: uuid!("e0000000-0000-0000-0000-000000000001"),
            name: "edge1".to_string(),
            weights: HashMap::from([
                ("adjacency".to_string(), 1.0),
                ("energy".to_string(), 0.5),
                ("spatial".to_string(), 0.5),
            ]),
            ..Edge::default().0
        };
        let edge2 = Edge {
            source: target.id.to_owned(),
            target: source.id.to_owned(),
            id: uuid!("e0000000-0000-0000-0000-000000000002"),
            name: "edge2".to_string(),
            kind: "reverse".to_string(),
            weights: HashMap::from([
                ("adjacency".to_string(), 2.0),
                ("energy".to_string(), 1.5),
                ("spatial".to_string(), 0.5),
            ]),
            ..Edge::default().0
        };
        let edge3 = Edge {
            source: source.id.to_owned(),
            target: target.id.to_owned(),
            id: uuid!("e0000000-0000-0000-0000-000000000003"),
            name: "edge3".to_string(),
            weights: HashMap::from([
                ("adjacency".to_string(), 3.0),
                ("energy".to_string(), 2.0),
                ("spatial".to_string(), 1.0),
            ]),
            ..Edge::default().0
        };
        graph.add_nodes(vec![source, target], true);
        graph.add_edges(vec![edge1, edge2, edge3], true);
        assert_eq!(
            to_string(&graph).unwrap(),
            r#"{"id":"00000000-0000-0000-0000-000000000000","name":"test","kind":"default","labels":[],"weights":{},"annotations":{},"nodes":{"a0000000-0000-0000-0000-000000000001":{"annotations":{},"children":[],"id":"a0000000-0000-0000-0000-000000000001","isBus":false,"kind":"default","labels":[],"name":"source","parent":null,"weights":{}},"a0000000-0000-0000-0000-000000000002":{"annotations":{},"children":[],"id":"a0000000-0000-0000-0000-000000000002","isBus":false,"kind":"default","labels":[],"name":"target","parent":null,"weights":{}}},"edges":{"e0000000-0000-0000-0000-000000000001":{"annotations":{},"id":"e0000000-0000-0000-0000-000000000001","kind":"default","labels":[],"name":"edge1","source":"a0000000-0000-0000-0000-000000000001","target":"a0000000-0000-0000-0000-000000000002","weights":{"adjacency":1.0,"energy":0.5,"spatial":0.5}},"e0000000-0000-0000-0000-000000000002":{"annotations":{},"id":"e0000000-0000-0000-0000-000000000002","kind":"reverse","labels":[],"name":"edge2","source":"a0000000-0000-0000-0000-000000000002","target":"a0000000-0000-0000-0000-000000000001","weights":{"adjacency":2.0,"energy":1.5,"spatial":0.5}},"e0000000-0000-0000-0000-000000000003":{"annotations":{},"id":"e0000000-0000-0000-0000-000000000003","kind":"default","labels":[],"name":"edge3","source":"a0000000-0000-0000-0000-000000000001","target":"a0000000-0000-0000-0000-000000000002","weights":{"adjacency":3.0,"energy":2.0,"spatial":1.0}}},"_edges_forward":{"a0000000-0000-0000-0000-000000000001":{"a0000000-0000-0000-0000-000000000002":["e0000000-0000-0000-0000-000000000001","e0000000-0000-0000-0000-000000000003"]},"a0000000-0000-0000-0000-000000000002":{"a0000000-0000-0000-0000-000000000001":["e0000000-0000-0000-0000-000000000002"]}},"_edges_reverse":{"a0000000-0000-0000-0000-000000000001":{"a0000000-0000-0000-0000-000000000002":["e0000000-0000-0000-0000-000000000001","e0000000-0000-0000-0000-000000000003"]},"a0000000-0000-0000-0000-000000000002":{"a0000000-0000-0000-0000-000000000001":["e0000000-0000-0000-0000-000000000002"]}}}"#
        );

        let mat = graph.get_adjacency_matrix(None, None, &Aggregator::Weights, None);
        assert_eq!(
            mat,
            DMatrix::<f64>::from_vec(2, 2, vec![0.0, 8.0, 4.0, 0.0])
        );
        let mat2 = graph.get_adjacency_matrix(
            None,
            None,
            &Aggregator::Weights,
            Some(&HashSet::from(["spatial".to_string()])),
        );
        assert_eq!(
            mat2,
            DMatrix::<f64>::from_vec(2, 2, vec![0.0, 1.5, 0.5, 0.0])
        );
    }
}