xgraph 3.0.0

Graph algorithms for Rust: shortest paths, centrality, connectivity, spanning trees and community detection, over directed, undirected and heterogeneous multigraphs
Documentation
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
//! Graph search algorithms and operations for heterogeneous multigraphs.
//!
//! This module provides a suite of graph traversal and analysis algorithms tailored for
//! heterogeneous multigraphs, supporting both directed and undirected graphs with multiple
//! edge types between nodes. Key functionalities include:
//! - Path existence checking using Depth-First Search (DFS).
//! - Shortest path finding using Breadth-First Search (BFS).
//! - Cycle detection for directed and undirected graphs.
//! - Node existence verification.
//!
//! All methods support filtering by edge types, enabling analysis of subgraphs defined by
//! specific edge categories. The module is available only when the `hgraph` feature is enabled
//! in your `Cargo.toml`:
//! ```toml
//! [dependencies.xgraph]
//! version = "x.y.z"
//! features = ["hgraph"]
//! ```

#[cfg(feature = "hgraph")]
use crate::core::view::NodeId;
#[cfg(feature = "hgraph")]
use crate::hgraph::h_graph::HeterogeneousGraph;
#[cfg(feature = "hgraph")]
use std::collections::HashSet;
#[cfg(feature = "hgraph")]
use std::fmt::Debug;
#[cfg(feature = "hgraph")]
use std::hash::Hash;

// Error handling additions

/// Error type for graph search operation failures.
///
/// Represents errors that may occur during graph traversal or analysis, such as referencing
/// invalid nodes.
#[cfg(feature = "hgraph")]
#[derive(Debug, thiserror::Error)]
pub enum SearchError {
    /// Indicates a node referenced in the graph does not exist.
    #[error("Invalid node reference: node ID {0} not found")]
    InvalidNodeReference(NodeId),
}

#[cfg(feature = "hgraph")]
impl From<crate::core::TraversalError> for SearchError {
    fn from(error: crate::core::TraversalError) -> Self {
        match error {
            crate::core::TraversalError::InvalidNode(id) => SearchError::InvalidNodeReference(id),
        }
    }
}

/// Result type alias for search operations.
///
/// Wraps the result of search methods, enabling error handling without panicking.
#[cfg(feature = "hgraph")]
pub type Result<T> = std::result::Result<T, SearchError>;

#[cfg(feature = "hgraph")]
/// Trait for graph search operations in heterogeneous multigraphs.
///
/// Defines methods for path finding, cycle detection, and node existence checks, with support
/// for edge type filtering. All methods that may fail due to invalid input return a `Result`
/// to handle errors gracefully.
#[deprecated(
    since = "3.0.0",
    note = "superseded by `xgraph::core::Traversal`; the `*_by_types` variants become \
            `graph.of_edge_kinds(&[..])` followed by the ordinary method"
)]
pub trait HeteroSearch<W, N, E>
where
    W: Copy + Default + PartialEq + Debug,
    N: Clone + Eq + Hash + Debug + crate::hgraph::h_node::NodeType,
    E: Clone + Default + Debug + crate::hgraph::h_edge::EdgeType,
{
    /// Checks if a path exists between two nodes using DFS.
    ///
    /// # Arguments
    /// * `start` - The starting node ID.
    /// * `target` - The target node ID.
    ///
    /// # Returns
    /// `true` if a path exists from `start` to `target`, `false` otherwise.
    fn has_path(&self, start: NodeId, target: NodeId) -> bool;

    /// Checks if a path exists between two nodes using DFS, considering only specific edge types.
    ///
    /// # Arguments
    /// * `start` - The starting node ID.
    /// * `target` - The target node ID.
    /// * `edge_types` - A slice of edge type strings to filter the search.
    ///
    /// # Returns
    /// `true` if a path exists from `start` to `target` using only the specified edge types,
    /// `false` otherwise.
    fn has_path_by_types(&self, start: NodeId, target: NodeId, edge_types: &[&str]) -> bool;

    /// Finds the shortest path between nodes using BFS.
    ///
    /// Returns the path as a vector of node IDs from `start` to `target`, or an error if either
    /// node does not exist.
    ///
    /// # Arguments
    /// * `start` - The starting node ID.
    /// * `target` - The target node ID.
    ///
    /// # Returns
    /// A `Result` containing `Some(Vec<NodeId>)` with the path if found, `None` if no path exists,
    /// or an error if nodes are invalid.
    fn bfs_path(&self, start: NodeId, target: NodeId) -> Result<Option<Vec<NodeId>>>;

    /// Finds the shortest path between nodes using BFS, considering only specific edge types.
    ///
    /// Returns the path as a vector of node IDs from `start` to `target`, or an error if either
    /// node does not exist.
    ///
    /// # Arguments
    /// * `start` - The starting node ID.
    /// * `target` - The target node ID.
    /// * `edge_types` - A slice of edge type strings to filter the search.
    ///
    /// # Returns
    /// A `Result` containing `Some(Vec<NodeId>)` with the path if found, `None` if no path exists,
    /// or an error if nodes are invalid.
    fn bfs_path_by_types(
        &self,
        start: NodeId,
        target: NodeId,
        edge_types: &[&str],
    ) -> Result<Option<Vec<NodeId>>>;

    /// Recursive DFS implementation for path checking.
    ///
    /// Internal helper method for `has_path`.
    ///
    /// # Arguments
    /// * `current` - The current node ID being explored.
    /// * `target` - The target node ID.
    /// * `visited` - A set of already visited node IDs.
    ///
    /// # Returns
    /// `true` if a path to `target` is found, `false` otherwise.
    fn dfs(&self, current: NodeId, target: NodeId, visited: &mut HashSet<NodeId>) -> bool;

    /// Recursive DFS implementation for path checking with edge type filtering.
    ///
    /// Internal helper method for `has_path_by_types`.
    ///
    /// # Arguments
    /// * `current` - The current node ID being explored.
    /// * `target` - The target node ID.
    /// * `visited` - A set of already visited node IDs.
    /// * `edge_types` - A slice of edge type strings to filter the search.
    ///
    /// # Returns
    /// `true` if a path to `target` is found using specified edge types, `false` otherwise.
    fn dfs_by_types(
        &self,
        current: NodeId,
        target: NodeId,
        visited: &mut HashSet<NodeId>,
        edge_types: &[&str],
    ) -> bool;

    /// Checks if a node exists in the graph.
    ///
    /// # Arguments
    /// * `node` - The node ID to check.
    ///
    /// # Returns
    /// `true` if the node exists, `false` otherwise.
    fn has_node(&self, node: NodeId) -> bool;

    /// Detects cycles in the graph.
    ///
    /// Uses DFS-based cycle detection, differing in approach based on whether the graph is
    /// directed or undirected.
    ///
    /// # Returns
    /// `true` if the graph contains at least one cycle, `false` otherwise.
    fn has_cycle(&self) -> bool;

    /// Detects cycles in the graph, considering only specific edge types.
    ///
    /// Uses DFS-based cycle detection with edge type filtering.
    ///
    /// # Arguments
    /// * `edge_types` - A slice of edge type strings to filter the search.
    ///
    /// # Returns
    /// `true` if a cycle exists using only the specified edge types, `false` otherwise.
    fn has_cycle_by_types(&self, edge_types: &[&str]) -> bool;

    /// Helper for directed cycle detection.
    ///
    /// Internal method using DFS with a recursion stack to detect cycles in directed graphs.
    ///
    /// # Arguments
    /// * `node` - The current node ID being explored.
    /// * `visited` - A set of already visited node IDs.
    /// * `recursion_stack` - A set tracking nodes in the current recursion path.
    ///
    /// # Returns
    /// `true` if a cycle is detected, `false` otherwise.
    fn has_cycle_directed(
        &self,
        node: NodeId,
        visited: &mut HashSet<NodeId>,
        recursion_stack: &mut HashSet<NodeId>,
    ) -> bool;

    /// Helper for directed cycle detection with edge type filtering.
    ///
    /// Internal method using DFS with a recursion stack and edge type filtering.
    ///
    /// # Arguments
    /// * `node` - The current node ID being explored.
    /// * `visited` - A set of already visited node IDs.
    /// * `recursion_stack` - A set tracking nodes in the current recursion path.
    /// * `edge_types` - A slice of edge type strings to filter the search.
    ///
    /// # Returns
    /// `true` if a cycle is detected using specified edge types, `false` otherwise.
    fn has_cycle_directed_by_types(
        &self,
        node: NodeId,
        visited: &mut HashSet<NodeId>,
        recursion_stack: &mut HashSet<NodeId>,
        edge_types: &[&str],
    ) -> bool;

    /// Helper for undirected cycle detection.
    ///
    /// Internal method using DFS with parent tracking to detect cycles in undirected graphs.
    ///
    /// # Arguments
    /// * `node` - The current node ID being explored.
    /// * `parent` - The parent node ID in the DFS tree, if any.
    /// * `visited` - A set of already visited node IDs.
    ///
    /// # Returns
    /// `true` if a cycle is detected, `false` otherwise.
    fn has_cycle_undirected(
        &self,
        node: NodeId,
        parent: Option<NodeId>,
        visited: &mut HashSet<NodeId>,
    ) -> bool;

    /// Helper for undirected cycle detection with edge type filtering.
    ///
    /// Internal method using DFS with parent tracking and edge type filtering.
    ///
    /// # Arguments
    /// * `node` - The current node ID being explored.
    /// * `parent` - The parent node ID in the DFS tree, if any.
    /// * `visited` - A set of already visited node IDs.
    /// * `edge_types` - A slice of edge type strings to filter the search.
    ///
    /// # Returns
    /// `true` if a cycle is detected using specified edge types, `false` otherwise.
    fn has_cycle_undirected_by_types(
        &self,
        node: NodeId,
        parent: Option<NodeId>,
        visited: &mut HashSet<NodeId>,
        edge_types: &[&str],
    ) -> bool;
}

#[cfg(feature = "hgraph")]
#[cfg(feature = "hgraph")]
#[allow(deprecated)]
impl<W, N, E> HeteroSearch<W, N, E> for HeterogeneousGraph<W, N, E>
where
    W: Copy + Default + PartialEq + Debug,
    N: Clone + Eq + Hash + Debug + crate::hgraph::h_node::NodeType,
    E: Clone + Default + Debug + crate::hgraph::h_edge::EdgeType,
{
    fn has_path(&self, start: NodeId, target: NodeId) -> bool {
        crate::core::Traversal::has_path(self, start, target).unwrap_or(false)
    }

    fn has_path_by_types(&self, start: NodeId, target: NodeId, edge_types: &[&str]) -> bool {
        crate::core::Traversal::has_path(&self.of_edge_kinds(edge_types), start, target)
            .unwrap_or(false)
    }

    fn bfs_path(&self, start: NodeId, target: NodeId) -> Result<Option<Vec<NodeId>>> {
        crate::core::Traversal::bfs_path(self, start, target).map_err(SearchError::from)
    }

    fn bfs_path_by_types(
        &self,
        start: NodeId,
        target: NodeId,
        edge_types: &[&str],
    ) -> Result<Option<Vec<NodeId>>> {
        crate::core::Traversal::bfs_path(&self.of_edge_kinds(edge_types), start, target)
            .map_err(SearchError::from)
    }

    fn dfs(&self, current: NodeId, target: NodeId, visited: &mut HashSet<NodeId>) -> bool {
        crate::core::Traversal::explore_into(self, current, Some(target), visited).unwrap_or(false)
    }

    fn dfs_by_types(
        &self,
        current: NodeId,
        target: NodeId,
        visited: &mut HashSet<NodeId>,
        edge_types: &[&str],
    ) -> bool {
        crate::core::Traversal::explore_into(
            &self.of_edge_kinds(edge_types),
            current,
            Some(target),
            visited,
        )
        .unwrap_or(false)
    }

    fn has_node(&self, node: NodeId) -> bool {
        crate::core::GraphView::contains_node(self, node)
    }

    fn has_cycle(&self) -> bool {
        crate::core::Traversal::has_cycle(self).unwrap_or(false)
    }

    fn has_cycle_by_types(&self, edge_types: &[&str]) -> bool {
        crate::core::Traversal::has_cycle(&self.of_edge_kinds(edge_types)).unwrap_or(false)
    }

    fn has_cycle_directed(
        &self,
        node: NodeId,
        visited: &mut HashSet<NodeId>,
        _recursion_stack: &mut HashSet<NodeId>,
    ) -> bool {
        crate::core::Traversal::has_cycle_from(self, node, visited).unwrap_or(false)
    }

    fn has_cycle_directed_by_types(
        &self,
        node: NodeId,
        visited: &mut HashSet<NodeId>,
        _recursion_stack: &mut HashSet<NodeId>,
        edge_types: &[&str],
    ) -> bool {
        crate::core::Traversal::has_cycle_from(&self.of_edge_kinds(edge_types), node, visited)
            .unwrap_or(false)
    }

    fn has_cycle_undirected(
        &self,
        node: NodeId,
        _parent: Option<NodeId>,
        visited: &mut HashSet<NodeId>,
    ) -> bool {
        crate::core::Traversal::has_cycle_from(self, node, visited).unwrap_or(false)
    }

    fn has_cycle_undirected_by_types(
        &self,
        node: NodeId,
        _parent: Option<NodeId>,
        visited: &mut HashSet<NodeId>,
        edge_types: &[&str],
    ) -> bool {
        crate::core::Traversal::has_cycle_from(&self.of_edge_kinds(edge_types), node, visited)
            .unwrap_or(false)
    }
}

#[cfg(test)]
#[cfg(feature = "hgraph")]
#[allow(deprecated)]
mod tests {
    use super::*;
    use crate::core::view::NodeId;
    use crate::hgraph::h_edge::EdgeType;
    use crate::hgraph::h_node::NodeType;

    #[derive(Clone, Eq, PartialEq, Hash, Debug)]
    struct TestNode(String);
    impl NodeType for TestNode {
        fn as_string(&self) -> String {
            self.0.clone()
        }
    }

    #[derive(Clone, Debug, Default)]
    struct TestEdge(String);
    impl EdgeType for TestEdge {
        fn as_string(&self) -> String {
            self.0.clone()
        }
    }

    #[test]
    fn test_has_path() {
        let mut graph = HeterogeneousGraph::<f64, TestNode, TestEdge>::new(false);
        let n0 = graph.add_node(TestNode("A".to_string()));
        let n1 = graph.add_node(TestNode("B".to_string()));
        graph
            .add_edge(n0, n1, 1.0, TestEdge("road".to_string()))
            .unwrap();

        assert!(graph.has_path(n0, n1));
        assert!(graph.has_path(n1, n0));
    }

    #[test]
    fn test_has_path_by_types() {
        let mut graph = HeterogeneousGraph::<f64, TestNode, TestEdge>::new(false);
        let n0 = graph.add_node(TestNode("A".to_string()));
        let n1 = graph.add_node(TestNode("B".to_string()));
        let n2 = graph.add_node(TestNode("C".to_string()));
        graph
            .add_edge(n0, n1, 1.0, TestEdge("road".to_string()))
            .unwrap();
        graph
            .add_edge(n1, n2, 1.0, TestEdge("bridge".to_string()))
            .unwrap();

        assert!(graph.has_path_by_types(n0, n1, &["road"]));
        assert!(!graph.has_path_by_types(n0, n2, &["road"]));
        assert!(graph.has_path_by_types(n0, n2, &["road", "bridge"]));
    }

    #[test]
    fn test_bfs_path() {
        let mut graph = HeterogeneousGraph::<f64, TestNode, TestEdge>::new(true);
        let n0 = graph.add_node(TestNode("A".to_string()));
        let n1 = graph.add_node(TestNode("B".to_string()));
        let n2 = graph.add_node(TestNode("C".to_string()));
        graph
            .add_edge(n0, n1, 1.0, TestEdge("road".to_string()))
            .unwrap();
        graph
            .add_edge(n1, n2, 1.0, TestEdge("bridge".to_string()))
            .unwrap();

        assert_eq!(graph.bfs_path(n0, n2).unwrap(), Some(vec![n0, n1, n2]));
    }

    #[test]
    fn test_bfs_path_by_types() {
        let mut graph = HeterogeneousGraph::<f64, TestNode, TestEdge>::new(true);
        let n0 = graph.add_node(TestNode("A".to_string()));
        let n1 = graph.add_node(TestNode("B".to_string()));
        let n2 = graph.add_node(TestNode("C".to_string()));
        graph
            .add_edge(n0, n1, 1.0, TestEdge("road".to_string()))
            .unwrap();
        graph
            .add_edge(n1, n2, 1.0, TestEdge("bridge".to_string()))
            .unwrap();

        assert_eq!(
            graph.bfs_path_by_types(n0, n1, &["road"]).unwrap(),
            Some(vec![n0, n1])
        );
        assert_eq!(graph.bfs_path_by_types(n0, n2, &["road"]).unwrap(), None);
        assert_eq!(
            graph
                .bfs_path_by_types(n0, n2, &["road", "bridge"])
                .unwrap(),
            Some(vec![n0, n1, n2])
        );
    }

    #[test]
    fn test_dfs() {
        let mut graph = HeterogeneousGraph::<f64, TestNode, TestEdge>::new(false);
        let n0 = graph.add_node(TestNode("A".to_string()));
        let n1 = graph.add_node(TestNode("B".to_string()));
        let n2 = graph.add_node(TestNode("C".to_string()));
        graph
            .add_edge(n0, n1, 1.0, TestEdge("road".to_string()))
            .unwrap();
        graph
            .add_edge(n1, n2, 1.0, TestEdge("bridge".to_string()))
            .unwrap();

        let mut visited = HashSet::new();
        assert!(graph.dfs(n0, n2, &mut visited));
    }

    #[test]
    fn test_invalid_nodes() {
        let graph = HeterogeneousGraph::<f64, TestNode, TestEdge>::new(false);
        assert!(!graph.has_node(NodeId::from_index(0)));
        assert!(!graph.has_path(NodeId::from_index(0), NodeId::from_index(1)));
        assert!(!graph.has_path_by_types(NodeId::from_index(0), NodeId::from_index(1), &["road"]));
        assert!(matches!(
            graph.bfs_path(NodeId::from_index(0), NodeId::from_index(1)),
            Err(SearchError::InvalidNodeReference(_))
        ));
        assert!(matches!(
            graph.bfs_path_by_types(NodeId::from_index(0), NodeId::from_index(1), &["road"]),
            Err(SearchError::InvalidNodeReference(_))
        ));
    }

    #[test]
    fn test_cycle_detection_directed() {
        let mut graph = HeterogeneousGraph::<f64, TestNode, TestEdge>::new(true);
        let n0 = graph.add_node(TestNode("A".to_string()));
        let n1 = graph.add_node(TestNode("B".to_string()));
        let n2 = graph.add_node(TestNode("C".to_string()));

        graph
            .add_edge(n0, n1, 1.0, TestEdge("road".to_string()))
            .unwrap();
        graph
            .add_edge(n1, n2, 1.0, TestEdge("bridge".to_string()))
            .unwrap();
        graph
            .add_edge(n2, n0, 1.0, TestEdge("path".to_string()))
            .unwrap();

        assert!(graph.has_cycle());
    }

    #[test]
    fn test_cycle_detection_directed_by_types() {
        let mut graph = HeterogeneousGraph::<f64, TestNode, TestEdge>::new(true);
        let n0 = graph.add_node(TestNode("A".to_string()));
        let n1 = graph.add_node(TestNode("B".to_string()));
        let n2 = graph.add_node(TestNode("C".to_string()));

        graph
            .add_edge(n0, n1, 1.0, TestEdge("road".to_string()))
            .unwrap();
        graph
            .add_edge(n1, n2, 1.0, TestEdge("bridge".to_string()))
            .unwrap();
        graph
            .add_edge(n2, n0, 1.0, TestEdge("path".to_string()))
            .unwrap();

        assert!(graph.has_cycle_by_types(&["road", "bridge", "path"]));
        assert!(!graph.has_cycle_by_types(&["road", "bridge"]));
    }

    #[test]
    fn test_cycle_detection_undirected() {
        let mut graph = HeterogeneousGraph::<f64, TestNode, TestEdge>::new(false);
        let n0 = graph.add_node(TestNode("A".to_string()));
        let n1 = graph.add_node(TestNode("B".to_string()));
        let n2 = graph.add_node(TestNode("C".to_string()));

        graph
            .add_edge(n0, n1, 1.0, TestEdge("road".to_string()))
            .unwrap();
        graph
            .add_edge(n1, n2, 1.0, TestEdge("bridge".to_string()))
            .unwrap();
        graph
            .add_edge(n2, n0, 1.0, TestEdge("path".to_string()))
            .unwrap();

        assert!(graph.has_cycle());
    }

    #[test]
    fn test_cycle_detection_undirected_by_types() {
        let mut graph = HeterogeneousGraph::<f64, TestNode, TestEdge>::new(false);
        let n0 = graph.add_node(TestNode("A".to_string()));
        let n1 = graph.add_node(TestNode("B".to_string()));
        let n2 = graph.add_node(TestNode("C".to_string()));

        graph
            .add_edge(n0, n1, 1.0, TestEdge("road".to_string()))
            .unwrap();
        graph
            .add_edge(n1, n2, 1.0, TestEdge("bridge".to_string()))
            .unwrap();
        graph
            .add_edge(n2, n0, 1.0, TestEdge("path".to_string()))
            .unwrap();

        assert!(graph.has_cycle_by_types(&["road", "bridge", "path"]));
        assert!(!graph.has_cycle_by_types(&["road", "bridge"]));
    }

    #[test]
    fn test_no_cycle_directed() {
        let mut graph = HeterogeneousGraph::<f64, TestNode, TestEdge>::new(true);
        let n0 = graph.add_node(TestNode("A".to_string()));
        let n1 = graph.add_node(TestNode("B".to_string()));
        let n2 = graph.add_node(TestNode("C".to_string()));

        graph
            .add_edge(n0, n1, 1.0, TestEdge("road".to_string()))
            .unwrap();
        graph
            .add_edge(n1, n2, 1.0, TestEdge("bridge".to_string()))
            .unwrap();

        assert!(!graph.has_cycle());
    }

    #[test]
    fn test_no_cycle_directed_by_types() {
        let mut graph = HeterogeneousGraph::<f64, TestNode, TestEdge>::new(true);
        let n0 = graph.add_node(TestNode("A".to_string()));
        let n1 = graph.add_node(TestNode("B".to_string()));
        let n2 = graph.add_node(TestNode("C".to_string()));

        graph
            .add_edge(n0, n1, 1.0, TestEdge("road".to_string()))
            .unwrap();
        graph
            .add_edge(n1, n2, 1.0, TestEdge("bridge".to_string()))
            .unwrap();

        assert!(!graph.has_cycle_by_types(&["road", "bridge"]));
    }

    #[test]
    fn test_no_cycle_undirected() {
        let mut graph = HeterogeneousGraph::<f64, TestNode, TestEdge>::new(false);
        let n0 = graph.add_node(TestNode("A".to_string()));
        let n1 = graph.add_node(TestNode("B".to_string()));
        let n2 = graph.add_node(TestNode("C".to_string()));

        graph
            .add_edge(n0, n1, 1.0, TestEdge("road".to_string()))
            .unwrap();
        graph
            .add_edge(n1, n2, 1.0, TestEdge("bridge".to_string()))
            .unwrap();

        assert!(!graph.has_cycle());
    }

    #[test]
    fn test_no_cycle_undirected_by_types() {
        let mut graph = HeterogeneousGraph::<f64, TestNode, TestEdge>::new(false);
        let n0 = graph.add_node(TestNode("A".to_string()));
        let n1 = graph.add_node(TestNode("B".to_string()));
        let n2 = graph.add_node(TestNode("C".to_string()));

        graph
            .add_edge(n0, n1, 1.0, TestEdge("road".to_string()))
            .unwrap();
        graph
            .add_edge(n1, n2, 1.0, TestEdge("bridge".to_string()))
            .unwrap();

        assert!(!graph.has_cycle_by_types(&["road", "bridge"]));
    }

    #[test]
    fn test_multiple_edges() {
        let mut graph = HeterogeneousGraph::<f64, TestNode, TestEdge>::new(true);
        let n0 = graph.add_node(TestNode("A".to_string()));
        let n1 = graph.add_node(TestNode("B".to_string()));

        graph
            .add_edge(n0, n1, 1.0, TestEdge("road".to_string()))
            .unwrap();
        graph
            .add_edge(n0, n1, 2.0, TestEdge("path".to_string()))
            .unwrap();

        assert!(graph.has_path(n0, n1));
        assert!(graph.has_path_by_types(n0, n1, &["road"]));
        assert_eq!(graph.bfs_path(n0, n1).unwrap(), Some(vec![n0, n1]));
        assert_eq!(
            graph.bfs_path_by_types(n0, n1, &["path"]).unwrap(),
            Some(vec![n0, n1])
        );
        assert!(!graph.has_cycle());
        assert!(!graph.has_cycle_by_types(&["road", "path"]));
    }
}