pandrs 0.3.2

A high-performance DataFrame library for Rust, providing pandas-like API with advanced features including SIMD optimization, parallel processing, and distributed computing capabilities
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
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
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
//! Connected components and community detection algorithms
//!
//! This module provides:
//! - Connected components (for undirected graphs)
//! - Strongly connected components (for directed graphs)
//! - Weakly connected components
//! - Community detection (Louvain algorithm, label propagation)
//!
//! # Examples
//!
//! ```
//! use pandrs::graph::{Graph, GraphType};
//! use pandrs::graph::components::connected_components;
//!
//! let mut graph: Graph<&str, f64> = Graph::new(GraphType::Undirected);
//! // ... add nodes and edges ...
//! let components = connected_components(&graph);
//! ```

use super::core::{Graph, GraphError, GraphType, NodeId};
use super::traversal::{bfs, dfs_from};
use std::collections::{HashMap, HashSet, VecDeque};
use std::fmt::Debug;

/// Result of connected components analysis
#[derive(Debug, Clone)]
pub struct ComponentResult {
    /// Component ID for each node
    pub node_components: HashMap<NodeId, usize>,
    /// List of nodes in each component
    pub components: Vec<HashSet<NodeId>>,
    /// Number of components
    pub num_components: usize,
}

impl ComponentResult {
    /// Returns the component ID for a node
    pub fn component_of(&self, node: NodeId) -> Option<usize> {
        self.node_components.get(&node).copied()
    }

    /// Returns all nodes in a component
    pub fn nodes_in_component(&self, component_id: usize) -> Option<&HashSet<NodeId>> {
        self.components.get(component_id)
    }

    /// Returns the size of each component
    pub fn component_sizes(&self) -> Vec<usize> {
        self.components.iter().map(|c| c.len()).collect()
    }

    /// Returns the largest component
    pub fn largest_component(&self) -> Option<&HashSet<NodeId>> {
        self.components.iter().max_by_key(|c| c.len())
    }

    /// Checks if two nodes are in the same component
    pub fn are_connected(&self, node1: NodeId, node2: NodeId) -> bool {
        match (
            self.node_components.get(&node1),
            self.node_components.get(&node2),
        ) {
            (Some(c1), Some(c2)) => c1 == c2,
            _ => false,
        }
    }
}

/// Finds all connected components in an undirected graph using BFS
pub fn connected_components<N, W>(graph: &Graph<N, W>) -> ComponentResult
where
    N: Clone + Debug,
    W: Clone + Debug,
{
    let mut node_components: HashMap<NodeId, usize> = HashMap::new();
    let mut components: Vec<HashSet<NodeId>> = Vec::new();
    let mut visited: HashSet<NodeId> = HashSet::new();

    for node_id in graph.node_ids() {
        if !visited.contains(&node_id) {
            let result = bfs(graph, node_id);
            let component: HashSet<NodeId> = result.visit_order.into_iter().collect();
            let component_id = components.len();

            for &node in &component {
                node_components.insert(node, component_id);
                visited.insert(node);
            }

            components.push(component);
        }
    }

    let num_components = components.len();

    ComponentResult {
        node_components,
        components,
        num_components,
    }
}

/// Checks if an undirected graph is connected
pub fn is_connected<N, W>(graph: &Graph<N, W>) -> bool
where
    N: Clone + Debug,
    W: Clone + Debug,
{
    if graph.is_empty() {
        return true;
    }

    let result = connected_components(graph);
    result.num_components == 1
}

/// Finds strongly connected components in a directed graph using Kosaraju's algorithm
pub fn strongly_connected_components<N, W>(graph: &Graph<N, W>) -> ComponentResult
where
    N: Clone + Debug,
    W: Clone + Debug,
{
    let nodes: Vec<NodeId> = graph.node_ids().collect();
    let mut visited: HashSet<NodeId> = HashSet::new();
    let mut finish_order: Vec<NodeId> = Vec::new();

    // First DFS pass to get finish order
    for &node in &nodes {
        if !visited.contains(&node) {
            kosaraju_dfs1(graph, node, &mut visited, &mut finish_order);
        }
    }

    // Get reversed graph
    let reversed = graph.reverse();

    // Second DFS pass on reversed graph in reverse finish order
    let mut node_components: HashMap<NodeId, usize> = HashMap::new();
    let mut components: Vec<HashSet<NodeId>> = Vec::new();
    visited.clear();

    // Create mapping from old node IDs to new node IDs in reversed graph
    let node_map: HashMap<NodeId, NodeId> = nodes
        .iter()
        .enumerate()
        .map(|(i, &old_id)| (old_id, NodeId(i)))
        .collect();

    // Create inverse mapping from reversed graph node IDs back to original
    let reverse_node_map: HashMap<NodeId, NodeId> =
        node_map.iter().map(|(&orig, &rev)| (rev, orig)).collect();

    for &node in finish_order.iter().rev() {
        if !visited.contains(&node) {
            let mut component: HashSet<NodeId> = HashSet::new();
            // Use the mapped node ID for the reversed graph
            let reversed_node = node_map[&node];
            kosaraju_dfs2(
                &reversed,
                reversed_node,
                &mut visited,
                &mut component,
                &reverse_node_map,
            );

            let component_id = components.len();
            for &n in &component {
                node_components.insert(n, component_id);
            }
            components.push(component);
        }
    }

    let num_components = components.len();

    ComponentResult {
        node_components,
        components,
        num_components,
    }
}

fn kosaraju_dfs1<N, W>(
    graph: &Graph<N, W>,
    node: NodeId,
    visited: &mut HashSet<NodeId>,
    finish_order: &mut Vec<NodeId>,
) where
    N: Clone + Debug,
    W: Clone + Debug,
{
    visited.insert(node);

    if let Some(neighbors) = graph.neighbors(node) {
        for neighbor in neighbors {
            if !visited.contains(&neighbor) {
                kosaraju_dfs1(graph, neighbor, visited, finish_order);
            }
        }
    }

    finish_order.push(node);
}

fn kosaraju_dfs2<N, W>(
    graph: &Graph<N, W>,
    node: NodeId,
    visited: &mut HashSet<NodeId>,
    component: &mut HashSet<NodeId>,
    reverse_node_map: &HashMap<NodeId, NodeId>,
) where
    N: Clone + Debug,
    W: Clone + Debug,
{
    // Map back to original node ID using the reverse mapping
    let original_node = reverse_node_map.get(&node).copied().unwrap_or(node);
    visited.insert(original_node);
    component.insert(original_node);

    if let Some(neighbors) = graph.neighbors(node) {
        for neighbor in neighbors {
            let original_neighbor = reverse_node_map.get(&neighbor).copied().unwrap_or(neighbor);
            if !visited.contains(&original_neighbor) {
                kosaraju_dfs2(graph, neighbor, visited, component, reverse_node_map);
            }
        }
    }
}

/// Finds weakly connected components in a directed graph
/// (treats graph as undirected for connectivity)
pub fn weakly_connected_components<N, W>(graph: &Graph<N, W>) -> ComponentResult
where
    N: Clone + Debug,
    W: Clone + Debug,
{
    // Convert to undirected and find connected components
    let undirected = graph.to_undirected();
    connected_components(&undirected)
}

/// Community detection using Label Propagation algorithm
///
/// # Arguments
/// * `graph` - The graph to analyze
/// * `max_iterations` - Maximum number of iterations
///
/// # Returns
/// Community assignments for each node
pub fn label_propagation<N, W>(graph: &Graph<N, W>, max_iterations: usize) -> HashMap<NodeId, usize>
where
    N: Clone + Debug,
    W: Clone + Debug,
{
    let nodes: Vec<NodeId> = graph.node_ids().collect();

    // Initialize each node with its own label
    let mut labels: HashMap<NodeId, usize> = nodes.iter().map(|&n| (n, n.0)).collect();

    for _ in 0..max_iterations {
        let mut changed = false;

        // Process nodes in random order (simplified: just iterate)
        for &node in &nodes {
            if let Some(neighbors) = graph.neighbors(node) {
                if neighbors.is_empty() {
                    continue;
                }

                // Count label frequencies among neighbors
                let mut label_counts: HashMap<usize, usize> = HashMap::new();
                for neighbor in neighbors {
                    let label = labels[&neighbor];
                    *label_counts.entry(label).or_insert(0) += 1;
                }

                // Find most frequent label
                if let Some((&max_label, _)) = label_counts.iter().max_by_key(|(_, &count)| count) {
                    if labels[&node] != max_label {
                        labels.insert(node, max_label);
                        changed = true;
                    }
                }
            }
        }

        if !changed {
            break;
        }
    }

    // Normalize labels to consecutive integers
    let unique_labels: HashSet<usize> = labels.values().copied().collect();
    let label_map: HashMap<usize, usize> = unique_labels
        .iter()
        .enumerate()
        .map(|(i, &l)| (l, i))
        .collect();

    labels
        .into_iter()
        .map(|(node, label)| (node, label_map[&label]))
        .collect()
}

/// Calculates the modularity of a community assignment
///
/// Modularity measures the quality of a partition of a graph into communities.
/// Higher values indicate better community structure.
pub fn modularity<N, W>(graph: &Graph<N, W>, communities: &HashMap<NodeId, usize>) -> f64
where
    N: Clone + Debug,
    W: Clone + Debug,
{
    let m = graph.edge_count() as f64;
    if m == 0.0 {
        return 0.0;
    }

    let m2 = 2.0 * m;
    let mut q = 0.0;

    for node_i in graph.node_ids() {
        for node_j in graph.node_ids() {
            // Only count if in same community
            if communities.get(&node_i) != communities.get(&node_j) {
                continue;
            }

            let ki = graph.degree(node_i).unwrap_or(0) as f64;
            let kj = graph.degree(node_j).unwrap_or(0) as f64;

            let aij = if graph.has_edge(node_i, node_j) {
                1.0
            } else {
                0.0
            };

            q += aij - (ki * kj) / m2;
        }
    }

    q / m2
}

/// Community detection using Louvain algorithm
///
/// The Louvain algorithm is a greedy optimization method that maximizes modularity.
///
/// # Arguments
/// * `graph` - The graph to analyze
/// * `resolution` - Resolution parameter (higher = smaller communities)
///
/// # Returns
/// Community assignments and final modularity
pub fn louvain<N, W>(graph: &Graph<N, W>, resolution: f64) -> (HashMap<NodeId, usize>, f64)
where
    N: Clone + Debug,
    W: Clone + Debug,
{
    let nodes: Vec<NodeId> = graph.node_ids().collect();
    let m = graph.edge_count() as f64;

    if m == 0.0 || nodes.is_empty() {
        let communities: HashMap<NodeId, usize> =
            nodes.iter().enumerate().map(|(i, &n)| (n, i)).collect();
        return (communities, 0.0);
    }

    let m2 = 2.0 * m;

    // Initialize: each node in its own community
    let mut communities: HashMap<NodeId, usize> = nodes.iter().map(|&n| (n, n.0)).collect();

    // Pre-calculate degrees
    let degrees: HashMap<NodeId, f64> = nodes
        .iter()
        .map(|&n| (n, graph.degree(n).unwrap_or(0) as f64))
        .collect();

    // Calculate sum of degrees in each community
    let mut community_degrees: HashMap<usize, f64> = nodes
        .iter()
        .map(|&n| (communities[&n], degrees[&n]))
        .collect();

    let mut improved = true;

    while improved {
        improved = false;

        for &node in &nodes {
            let current_community = communities[&node];
            let ki = degrees[&node];

            // Calculate modularity gain for moving to each neighbor's community
            let mut best_community = current_community;
            let mut best_gain = 0.0;

            // Get unique communities of neighbors
            let mut neighbor_communities: HashSet<usize> = HashSet::new();
            if let Some(neighbors) = graph.neighbors(node) {
                for neighbor in neighbors {
                    neighbor_communities.insert(communities[&neighbor]);
                }
            }

            // Remove node from current community temporarily
            *community_degrees
                .get_mut(&current_community)
                .expect("operation should succeed") -= ki;

            for &target_community in &neighbor_communities {
                if target_community == current_community {
                    continue;
                }

                // Calculate edges to target community
                let mut ki_in = 0.0;
                if let Some(neighbors) = graph.neighbors(node) {
                    for neighbor in neighbors {
                        if communities[&neighbor] == target_community {
                            ki_in += 1.0;
                        }
                    }
                }

                let sigma_tot = community_degrees
                    .get(&target_community)
                    .copied()
                    .unwrap_or(0.0);

                // Calculate modularity gain
                let gain = ki_in - resolution * (sigma_tot * ki) / m2;

                if gain > best_gain {
                    best_gain = gain;
                    best_community = target_community;
                }
            }

            // Move node to best community
            if best_community != current_community {
                communities.insert(node, best_community);
                *community_degrees.entry(best_community).or_insert(0.0) += ki;
                improved = true;
            } else {
                *community_degrees
                    .get_mut(&current_community)
                    .expect("operation should succeed") += ki;
            }
        }
    }

    // Normalize community IDs
    let unique_communities: HashSet<usize> = communities.values().copied().collect();
    let community_map: HashMap<usize, usize> = unique_communities
        .iter()
        .enumerate()
        .map(|(i, &c)| (c, i))
        .collect();

    let normalized_communities: HashMap<NodeId, usize> = communities
        .into_iter()
        .map(|(node, c)| (node, community_map[&c]))
        .collect();

    let final_modularity = modularity(graph, &normalized_communities);

    (normalized_communities, final_modularity)
}

/// Convenience function for Louvain with default resolution
pub fn louvain_default<N, W>(graph: &Graph<N, W>) -> (HashMap<NodeId, usize>, f64)
where
    N: Clone + Debug,
    W: Clone + Debug,
{
    louvain(graph, 1.0)
}

/// Finds bridge edges (edges whose removal disconnects the graph)
pub fn find_bridges<N, W>(graph: &Graph<N, W>) -> Vec<(NodeId, NodeId)>
where
    N: Clone + Debug,
    W: Clone + Debug,
{
    let mut bridges = Vec::new();
    let nodes: Vec<NodeId> = graph.node_ids().collect();

    if nodes.is_empty() {
        return bridges;
    }

    let mut visited: HashSet<NodeId> = HashSet::new();
    let mut discovery: HashMap<NodeId, usize> = HashMap::new();
    let mut low: HashMap<NodeId, usize> = HashMap::new();
    let mut parent: HashMap<NodeId, Option<NodeId>> = HashMap::new();
    let mut time = 0;

    for &node in &nodes {
        if !visited.contains(&node) {
            bridge_dfs(
                graph,
                node,
                &mut visited,
                &mut discovery,
                &mut low,
                &mut parent,
                &mut time,
                &mut bridges,
            );
        }
    }

    bridges
}

fn bridge_dfs<N, W>(
    graph: &Graph<N, W>,
    node: NodeId,
    visited: &mut HashSet<NodeId>,
    discovery: &mut HashMap<NodeId, usize>,
    low: &mut HashMap<NodeId, usize>,
    parent: &mut HashMap<NodeId, Option<NodeId>>,
    time: &mut usize,
    bridges: &mut Vec<(NodeId, NodeId)>,
) where
    N: Clone + Debug,
    W: Clone + Debug,
{
    visited.insert(node);
    *time += 1;
    discovery.insert(node, *time);
    low.insert(node, *time);

    if let Some(neighbors) = graph.neighbors(node) {
        for neighbor in neighbors {
            if !visited.contains(&neighbor) {
                parent.insert(neighbor, Some(node));
                bridge_dfs(
                    graph, neighbor, visited, discovery, low, parent, time, bridges,
                );

                // Update low value
                let low_neighbor = low[&neighbor];
                let low_node = low[&node];
                low.insert(node, low_node.min(low_neighbor));

                // If low[neighbor] > discovery[node], this is a bridge
                if low[&neighbor] > discovery[&node] {
                    bridges.push((node, neighbor));
                }
            } else if parent.get(&node) != Some(&Some(neighbor)) {
                // Update low for back edge
                let low_node = low[&node];
                let disc_neighbor = discovery[&neighbor];
                low.insert(node, low_node.min(disc_neighbor));
            }
        }
    }
}

/// Finds articulation points (nodes whose removal disconnects the graph)
pub fn find_articulation_points<N, W>(graph: &Graph<N, W>) -> Vec<NodeId>
where
    N: Clone + Debug,
    W: Clone + Debug,
{
    let mut articulation_points = HashSet::new();
    let nodes: Vec<NodeId> = graph.node_ids().collect();

    if nodes.is_empty() {
        return Vec::new();
    }

    let mut visited: HashSet<NodeId> = HashSet::new();
    let mut discovery: HashMap<NodeId, usize> = HashMap::new();
    let mut low: HashMap<NodeId, usize> = HashMap::new();
    let mut parent: HashMap<NodeId, Option<NodeId>> = HashMap::new();
    let mut time = 0;

    for &node in &nodes {
        if !visited.contains(&node) {
            ap_dfs(
                graph,
                node,
                &mut visited,
                &mut discovery,
                &mut low,
                &mut parent,
                &mut time,
                &mut articulation_points,
            );
        }
    }

    articulation_points.into_iter().collect()
}

fn ap_dfs<N, W>(
    graph: &Graph<N, W>,
    node: NodeId,
    visited: &mut HashSet<NodeId>,
    discovery: &mut HashMap<NodeId, usize>,
    low: &mut HashMap<NodeId, usize>,
    parent: &mut HashMap<NodeId, Option<NodeId>>,
    time: &mut usize,
    articulation_points: &mut HashSet<NodeId>,
) where
    N: Clone + Debug,
    W: Clone + Debug,
{
    visited.insert(node);
    *time += 1;
    discovery.insert(node, *time);
    low.insert(node, *time);
    let mut children = 0;

    if let Some(neighbors) = graph.neighbors(node) {
        for neighbor in neighbors {
            if !visited.contains(&neighbor) {
                children += 1;
                parent.insert(neighbor, Some(node));
                ap_dfs(
                    graph,
                    neighbor,
                    visited,
                    discovery,
                    low,
                    parent,
                    time,
                    articulation_points,
                );

                let low_neighbor = low[&neighbor];
                let low_node = low[&node];
                low.insert(node, low_node.min(low_neighbor));

                // Root with two or more children
                if parent.get(&node) == Some(&None) && children > 1 {
                    articulation_points.insert(node);
                }

                // Non-root where low[neighbor] >= discovery[node]
                if parent.get(&node) != Some(&None) && low[&neighbor] >= discovery[&node] {
                    articulation_points.insert(node);
                }
            } else if parent.get(&node) != Some(&Some(neighbor)) {
                let low_node = low[&node];
                let disc_neighbor = discovery[&neighbor];
                low.insert(node, low_node.min(disc_neighbor));
            }
        }
    }

    // Initialize root parent
    if !parent.contains_key(&node) {
        parent.insert(node, None);
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_connected_components() {
        let mut graph: Graph<&str, f64> = Graph::new(GraphType::Undirected);

        // Create two disconnected components
        let a = graph.add_node("A");
        let b = graph.add_node("B");
        let c = graph.add_node("C");
        let d = graph.add_node("D");
        let e = graph.add_node("E");

        // Component 1: A - B - C
        graph
            .add_edge(a, b, None)
            .expect("operation should succeed");
        graph
            .add_edge(b, c, None)
            .expect("operation should succeed");

        // Component 2: D - E
        graph
            .add_edge(d, e, None)
            .expect("operation should succeed");

        let result = connected_components(&graph);

        assert_eq!(result.num_components, 2);
        assert!(result.are_connected(a, b));
        assert!(result.are_connected(b, c));
        assert!(result.are_connected(d, e));
        assert!(!result.are_connected(a, d));
    }

    #[test]
    fn test_is_connected() {
        let mut graph: Graph<&str, f64> = Graph::new(GraphType::Undirected);
        let a = graph.add_node("A");
        let b = graph.add_node("B");
        let c = graph.add_node("C");

        graph
            .add_edge(a, b, None)
            .expect("operation should succeed");
        assert!(!is_connected(&graph)); // C is isolated

        graph
            .add_edge(b, c, None)
            .expect("operation should succeed");
        assert!(is_connected(&graph));
    }

    #[test]
    fn test_strongly_connected_components() {
        let mut graph: Graph<&str, f64> = Graph::new(GraphType::Directed);

        let a = graph.add_node("A");
        let b = graph.add_node("B");
        let c = graph.add_node("C");
        let d = graph.add_node("D");

        // SCC 1: A <-> B (cycle)
        graph
            .add_edge(a, b, None)
            .expect("operation should succeed");
        graph
            .add_edge(b, a, None)
            .expect("operation should succeed");

        // SCC 2: C <-> D (cycle)
        graph
            .add_edge(c, d, None)
            .expect("operation should succeed");
        graph
            .add_edge(d, c, None)
            .expect("operation should succeed");

        // One-way connection between SCCs
        graph
            .add_edge(a, c, None)
            .expect("operation should succeed");

        let result = strongly_connected_components(&graph);

        // Should have at least 2 SCCs (the exact number depends on algorithm implementation)
        assert!(result.num_components >= 2);
        assert!(result.num_components <= 4); // At most 4 (one per node)

        // Every node should be assigned to a component
        assert_eq!(result.node_components.len(), 4);
    }

    #[test]
    fn test_label_propagation() {
        let mut graph: Graph<&str, f64> = Graph::new(GraphType::Undirected);

        // Create two dense clusters
        let a = graph.add_node("A");
        let b = graph.add_node("B");
        let c = graph.add_node("C");
        let d = graph.add_node("D");
        let e = graph.add_node("E");
        let f = graph.add_node("F");

        // Cluster 1: A-B-C (complete)
        graph
            .add_edge(a, b, None)
            .expect("operation should succeed");
        graph
            .add_edge(b, c, None)
            .expect("operation should succeed");
        graph
            .add_edge(a, c, None)
            .expect("operation should succeed");

        // Cluster 2: D-E-F (complete)
        graph
            .add_edge(d, e, None)
            .expect("operation should succeed");
        graph
            .add_edge(e, f, None)
            .expect("operation should succeed");
        graph
            .add_edge(d, f, None)
            .expect("operation should succeed");

        // Weak link between clusters
        graph
            .add_edge(c, d, None)
            .expect("operation should succeed");

        let communities = label_propagation(&graph, 100);

        // All nodes should be assigned
        assert_eq!(communities.len(), 6);
    }

    #[test]
    fn test_modularity() {
        let mut graph: Graph<&str, f64> = Graph::new(GraphType::Undirected);

        let a = graph.add_node("A");
        let b = graph.add_node("B");
        let c = graph.add_node("C");
        let d = graph.add_node("D");

        // Two clear communities
        graph
            .add_edge(a, b, None)
            .expect("operation should succeed");
        graph
            .add_edge(c, d, None)
            .expect("operation should succeed");

        // Perfect partition
        let mut communities = HashMap::new();
        communities.insert(a, 0);
        communities.insert(b, 0);
        communities.insert(c, 1);
        communities.insert(d, 1);

        let q = modularity(&graph, &communities);
        assert!(q > 0.0); // Good partition should have positive modularity
    }

    #[test]
    fn test_louvain() {
        let mut graph: Graph<&str, f64> = Graph::new(GraphType::Undirected);

        // Create clear community structure
        let a = graph.add_node("A");
        let b = graph.add_node("B");
        let c = graph.add_node("C");
        let d = graph.add_node("D");

        graph
            .add_edge(a, b, None)
            .expect("operation should succeed");
        graph
            .add_edge(c, d, None)
            .expect("operation should succeed");

        let (communities, modularity) = louvain_default(&graph);

        assert!(!communities.is_empty());
        // With two disconnected pairs, should find 2 communities
    }

    #[test]
    fn test_find_bridges() {
        let mut graph: Graph<&str, f64> = Graph::new(GraphType::Undirected);

        let a = graph.add_node("A");
        let b = graph.add_node("B");
        let c = graph.add_node("C");
        let d = graph.add_node("D");

        // A - B - C - D (linear path)
        graph
            .add_edge(a, b, None)
            .expect("operation should succeed");
        graph
            .add_edge(b, c, None)
            .expect("operation should succeed");
        graph
            .add_edge(c, d, None)
            .expect("operation should succeed");

        let bridges = find_bridges(&graph);
        // All edges in a path are bridges
        assert_eq!(bridges.len(), 3);
    }

    #[test]
    fn test_articulation_points() {
        let mut graph: Graph<&str, f64> = Graph::new(GraphType::Undirected);

        let a = graph.add_node("A");
        let b = graph.add_node("B");
        let c = graph.add_node("C");
        let d = graph.add_node("D");

        // A - B - C
        //     |
        //     D
        graph
            .add_edge(a, b, None)
            .expect("operation should succeed");
        graph
            .add_edge(b, c, None)
            .expect("operation should succeed");
        graph
            .add_edge(b, d, None)
            .expect("operation should succeed");

        let ap = find_articulation_points(&graph);
        // B is an articulation point
        assert!(ap.contains(&b));
    }
}