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
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
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
//! Community detection with the Leiden algorithm, written once against [`GraphView`].
//!
//! Leiden improves on Louvain by guaranteeing that the communities it reports are
//! internally connected. The implementation works on contiguous indices `0..n`, so the
//! entry point below translates node IDs — which may be sparse after removals — into
//! positions on the way in and back again on the way out.

use crate::core::view::{GraphView, NodeId};
use rand::rngs::StdRng;
use rand::seq::SliceRandom;
use rand::{Rng, SeedableRng};
use std::collections::hash_map::DefaultHasher;
use std::collections::{HashMap, HashSet, VecDeque};
use std::hash::Hasher;

/// Error type for community detection failures.
#[derive(Debug, Clone, PartialEq, thiserror::Error)]
pub enum CommunityDetectionError {
    /// A node referenced during the computation does not exist.
    #[error("Invalid node reference: node ID {0} not found")]
    InvalidNode(NodeId),
    /// A floating-point result was NaN or infinite, which would corrupt the partition.
    #[error("Invalid floating-point result in community detection: {0}")]
    InvalidFloatResult(String),
    /// The algorithm's own bookkeeping became inconsistent.
    ///
    /// This reports a bug in the library rather than a problem with the input. The Leiden
    /// implementation works on positional indices of its own, distinct from the graph's
    /// node identifiers, and this is what a mismatch between them surfaces as.
    #[error("Internal inconsistency in community detection: {0}")]
    Internal(String),
}

/// Configuration for the Leiden community detection algorithm.
#[derive(Debug, Clone)]
pub struct CommunityConfig {
    /// Resolution parameter controlling community granularity: higher values yield more,
    /// smaller communities.
    pub gamma: f64,
    /// Scaling factor applied to modularity.
    pub resolution: f64,
    /// Maximum number of passes.
    pub iterations: usize,
    /// Whether to run reproducibly. With a `seed` this is redundant; without one it fixes
    /// the seed so that repeated runs agree.
    pub deterministic: bool,
    /// Seed for the random number generator.
    pub seed: Option<u64>,
    /// Communities smaller than this are merged into a neighbour where possible.
    pub min_community_size: usize,
}

impl Default for CommunityConfig {
    fn default() -> Self {
        Self {
            gamma: 1.0,
            resolution: 1.0,
            iterations: 10,
            deterministic: false,
            seed: None,
            min_community_size: 2,
        }
    }
}

/// Community detection available on every [`GraphView`] whose weights convert to `f64`.
pub trait CommunityDetection: GraphView {
    /// Detects communities with the given resolution and otherwise default settings.
    ///
    /// # Returns
    /// A map from community ID to the node IDs belonging to it.
    fn detect_communities(
        &self,
        gamma: f64,
    ) -> Result<HashMap<usize, Vec<NodeId>>, CommunityDetectionError>
    where
        Self::Weight: Into<f64>,
    {
        self.detect_communities_with_config(CommunityConfig {
            gamma,
            ..CommunityConfig::default()
        })
    }

    /// Detects communities with full control over the algorithm's settings.
    fn detect_communities_with_config(
        &self,
        config: CommunityConfig,
    ) -> Result<HashMap<usize, Vec<NodeId>>, CommunityDetectionError>
    where
        Self::Weight: Into<f64>,
    {
        // Node IDs may be sparse, so the algorithm runs over positions and the results are
        // translated back at the end.
        let index_to_id = self.node_id_vec();
        let id_to_index: HashMap<NodeId, usize> = index_to_id
            .iter()
            .enumerate()
            .map(|(index, &id)| (id, index))
            .collect();

        // Parallel edges between the same pair are summed into a single weighted
        // adjacency entry, which is what modularity treats them as anyway.
        let adjacency_list: Vec<Vec<(usize, f64)>> = index_to_id
            .iter()
            .map(|&id| {
                let mut totals: HashMap<usize, f64> = HashMap::new();
                for link in self.links(id) {
                    let Some(&index) = id_to_index.get(&link.target) else {
                        continue;
                    };
                    *totals.entry(index).or_insert(0.0) += link.weight.into();
                }
                totals.into_iter().collect()
            })
            .collect();

        let mut state = LeidenState::initialize(&adjacency_list, config)?;
        let mut previous = state.node_to_community.clone();

        for _ in 0..state.config.iterations {
            state.fast_louvain_move_nodes()?;
            state.refine_partition()?;
            state.enforce_gamma_properties()?;

            if state.node_to_community == previous {
                break;
            }
            previous = state.node_to_community.clone();

            if state.should_aggregate() {
                state.aggregate_graph()?;
            }
        }

        // Resolve first: merging undersized communities has to see original nodes and the
        // original adjacency, or it merges into communities it is not adjacent to.
        state.resolve_hierarchy()?;
        state.merge_small_communities(state.config.min_community_size)?;

        Ok(state
            .get_communities()
            .into_iter()
            .map(|(community, members)| {
                let members = members
                    .into_iter()
                    .filter_map(|index| index_to_id.get(index).copied())
                    .collect();
                (community, members)
            })
            .collect())
    }
}

impl<G: GraphView + ?Sized> CommunityDetection for G {}

/// Internal state for the Leiden clustering algorithm.
///
/// Manages graph structure, community assignments, and weights during clustering.
///
/// # Fields
/// - `adjacency_list`: Graph representation as adjacency list
/// - `node_to_community`: Current community assignments
/// - `community_weights`: Total edge weights per community
/// - `total_weight`: Sum of all edge weights
/// - `hierarchy`: Tracks community assignments across levels
/// - `original_size`: Original number of nodes
/// - `config`: Algorithm configuration
/// - `rng`: Random number generator
struct LeidenState {
    adjacency_list: Vec<Vec<(usize, f64)>>,
    /// The adjacency as first supplied, in original node indices.
    ///
    /// `adjacency_list` is replaced by the aggregated graph as the algorithm coarsens the
    /// partition, so anything that has to reason about original nodes — merging undersized
    /// communities, in particular — needs this to stay correct.
    original_adjacency: Vec<Vec<(usize, f64)>>,
    node_to_community: HashMap<usize, usize>,
    community_weights: HashMap<usize, f64>,
    total_weight: f64,
    /// One entry per aggregation step, mapping an index of the level below to the index of
    /// the coarser node that absorbed it.
    ///
    /// Composing them carries an original node down to its index in the current graph;
    /// `node_to_community` then gives the community it currently belongs to. Keeping the
    /// two separate is what stops the index spaces from being mixed.
    hierarchy: Vec<HashMap<usize, usize>>,
    original_size: usize,
    config: CommunityConfig,
    rng: StdRng,
}

#[allow(dead_code)]
impl LeidenState {
    fn initialize(
        adjacency_list: &[Vec<(usize, f64)>],
        config: CommunityConfig,
    ) -> Result<Self, CommunityDetectionError> {
        let mut node_to_community = HashMap::new();
        let mut community_weights = HashMap::new();
        let mut total_weight = 0.0;

        for (node, neighbors) in adjacency_list.iter().enumerate() {
            node_to_community.insert(node, node);
            let weight = neighbors.iter().map(|(_, w)| w).sum::<f64>();
            community_weights.insert(node, weight);
            total_weight += weight;
        }

        let rng = if config.deterministic {
            StdRng::seed_from_u64(config.seed.unwrap_or(42))
        } else {
            StdRng::seed_from_u64(config.seed.unwrap_or_else(rand::random))
        };

        Ok(Self {
            adjacency_list: adjacency_list.to_vec(),
            original_adjacency: adjacency_list.to_vec(),
            node_to_community,
            community_weights,
            total_weight,
            hierarchy: Vec::new(),
            original_size: adjacency_list.len(),
            config,
            rng,
        })
    }

    fn fast_louvain_move_nodes(&mut self) -> Result<(), CommunityDetectionError> {
        let mut nodes: Vec<usize> = (0..self.adjacency_list.len()).collect();
        if self.config.deterministic {
            nodes.sort_unstable();
        } else {
            nodes.shuffle(&mut self.rng);
        }

        let mut queue: VecDeque<usize> = nodes.into_iter().collect();
        let mut processed = HashSet::new();

        while let Some(node) = queue.pop_front() {
            if processed.contains(&node) {
                continue;
            }
            processed.insert(node);

            let current_comm = *self.node_to_community.get(&node).ok_or_else(|| {
                CommunityDetectionError::Internal(format!("index {} has no community", node))
            })?;
            let mut eligible_communities = self.find_eligible_communities(node, current_comm);
            if self.config.deterministic {
                eligible_communities.sort_unstable();
            }

            let mut best_comm = current_comm;
            let mut best_delta = f64::MIN;

            for comm in &eligible_communities {
                let delta = self.calculate_move_delta(node, *comm)?;
                if delta > best_delta {
                    best_delta = delta;
                    best_comm = *comm;
                }
            }

            if best_delta > 0.0 && best_comm != current_comm {
                self.move_node(node, best_comm)?;

                let mut neighbors: Vec<usize> = self.adjacency_list[node]
                    .iter()
                    .map(|&(n, _)| n)
                    .filter(|n| !processed.contains(n))
                    .collect();
                if self.config.deterministic {
                    neighbors.sort_unstable();
                }
                for neighbor in neighbors {
                    queue.push_back(neighbor);
                }
            }

            if queue.len() > self.original_size * 2 {
                break;
            }
        }
        Ok(())
    }

    fn generate_order_key(&mut self, node: usize) -> u64 {
        let mut hasher = DefaultHasher::new();
        hasher.write_u64(self.rng.random::<u64>());
        hasher.write_usize(node);
        hasher.finish()
    }

    fn refine_partition(&mut self) -> Result<(), CommunityDetectionError> {
        let mut singleton_partition = self.create_singleton_partition();

        let mut communities: Vec<usize> = self
            .node_to_community
            .values()
            .copied()
            .collect::<HashSet<_>>()
            .into_iter()
            .collect();
        if self.config.deterministic {
            communities.sort_unstable();
        }

        for comm in communities {
            self.refine_community_subset(comm, &mut singleton_partition)?;
        }

        self.node_to_community = singleton_partition;
        self.hierarchy.push(self.node_to_community.clone());
        Ok(())
    }

    /// Collapses the level hierarchy into one final assignment of original nodes to
    /// communities, and returns the state to original-node indices.
    ///
    /// Everything that runs after this point — merging undersized communities, reading the
    /// result — then speaks a single index space. Mixing the aggregated indices with the
    /// original ones is what used to let an undersized community merge into a community it
    /// shares no edge with, producing a disconnected community on a graph whose components
    /// are disjoint.
    fn resolve_hierarchy(&mut self) -> Result<(), CommunityDetectionError> {
        let final_communities: HashMap<usize, usize> = (0..self.original_size)
            .map(|node| (node, self.community_of_original(node)))
            .collect();

        self.node_to_community = final_communities;
        self.adjacency_list = self.original_adjacency.clone();
        self.hierarchy.clear();
        self.recompute_community_weights();
        Ok(())
    }

    /// Recomputes each community's total incident weight from the current adjacency.
    fn recompute_community_weights(&mut self) {
        let mut weights: HashMap<usize, f64> = HashMap::new();
        let mut total = 0.0;

        for (node, neighbors) in self.adjacency_list.iter().enumerate() {
            let weight: f64 = neighbors.iter().map(|(_, w)| w).sum();
            // `move_node` reads a node's own weight under its node key and the community
            // totals under community keys, so both are recorded.
            weights.insert(node, weight);
            total += weight;
        }
        for (&node, &community) in &self.node_to_community {
            if node == community {
                continue;
            }
            let node_weight = self
                .adjacency_list
                .get(node)
                .map(|neighbors| neighbors.iter().map(|(_, w)| w).sum::<f64>())
                .unwrap_or(0.0);
            *weights.entry(community).or_insert(0.0) += node_weight;
        }

        self.community_weights = weights;
        self.total_weight = total;
    }

    fn should_aggregate(&self) -> bool {
        let current_modularity = self.calculate_modularity().unwrap_or(0.0);
        let communities = self.get_communities();
        communities.values().any(|nodes| nodes.len() > 1) && current_modularity > 0.0
    }

    pub fn get_communities(&self) -> HashMap<usize, Vec<usize>> {
        let mut final_mapping: HashMap<usize, Vec<usize>> = HashMap::new();
        for node in 0..self.original_size {
            final_mapping
                .entry(self.community_of_original(node))
                .or_default()
                .push(node);
        }
        for nodes in final_mapping.values_mut() {
            nodes.sort_unstable();
        }
        final_mapping
    }

    /// Follows an original node down through every aggregation step and reports the
    /// community it currently sits in.
    fn community_of_original(&self, node: usize) -> usize {
        let mut current = node;
        for level in &self.hierarchy {
            current = level.get(&current).copied().unwrap_or(current);
        }
        self.node_to_community
            .get(&current)
            .copied()
            .unwrap_or(current)
    }

    fn find_eligible_communities(&self, node: usize, original_comm: usize) -> Vec<usize> {
        let mut comms: Vec<usize> = self.adjacency_list[node]
            .iter()
            .map(|(n, _)| self.node_to_community.get(n).copied().unwrap_or(*n))
            .filter(|&comm| comm != original_comm)
            .collect();
        comms.sort_unstable();
        comms.dedup();
        comms
    }

    fn calculate_move_delta(
        &self,
        node: usize,
        new_community: usize,
    ) -> Result<f64, CommunityDetectionError> {
        let old_community = self.node_to_community.get(&node).copied().unwrap_or(node);
        if old_community == new_community {
            return Ok(0.0);
        }

        let k_i = self.community_weights.get(&node).copied().unwrap_or(0.0);
        let sum_tot_new = self
            .community_weights
            .get(&new_community)
            .copied()
            .unwrap_or(0.0);
        let sum_tot_old = self
            .community_weights
            .get(&old_community)
            .copied()
            .unwrap_or(0.0);
        let m = self.total_weight.max(f64::EPSILON);

        let sum_in_new: f64 = self.adjacency_list[node]
            .iter()
            .filter(|(n, _)| self.node_to_community.get(n).copied().unwrap_or(*n) == new_community)
            .map(|(_, w)| w)
            .sum();
        let sum_in_old: f64 = self.adjacency_list[node]
            .iter()
            .filter(|(n, _)| self.node_to_community.get(n).copied().unwrap_or(*n) == old_community)
            .map(|(_, w)| w)
            .sum();

        let delta_new = sum_in_new - self.config.resolution * (sum_tot_new + k_i) * k_i / (2.0 * m);
        let delta_old = sum_in_old - self.config.resolution * (sum_tot_old) * k_i / (2.0 * m);

        let result = delta_new - delta_old;
        if result.is_nan() || result.is_infinite() {
            return Err(CommunityDetectionError::InvalidFloatResult(format!(
                "Delta calculation resulted in {} for node {}",
                if result.is_nan() { "NaN" } else { "infinity" },
                node
            )));
        }
        Ok(result)
    }

    fn move_node(
        &mut self,
        node: usize,
        new_community: usize,
    ) -> Result<(), CommunityDetectionError> {
        let old_community = self.node_to_community.get(&node).copied().unwrap_or(node);
        let node_weight = self.community_weights.get(&node).copied().unwrap_or(0.0);

        let old_weight = self
            .community_weights
            .get_mut(&old_community)
            .ok_or_else(|| {
                CommunityDetectionError::Internal(format!(
                    "community {} has no recorded weight",
                    old_community
                ))
            })?;
        *old_weight -= node_weight;
        *self.community_weights.entry(new_community).or_insert(0.0) += node_weight;

        self.node_to_community.insert(node, new_community);
        Ok(())
    }

    fn create_singleton_partition(&self) -> HashMap<usize, usize> {
        (0..self.adjacency_list.len()).map(|n| (n, n)).collect()
    }

    /// Collapses each community of the current graph into a single node.
    ///
    /// Everything here is expressed in the *current* index space. Building the coarser
    /// graph from original node indices instead — which is what this used to do from the
    /// second aggregation onwards — reads the wrong rows of the adjacency list and silently
    /// drops the rest, which is how communities spanning disconnected components appeared.
    fn aggregate_graph(&mut self) -> Result<(), CommunityDetectionError> {
        let size = self.adjacency_list.len();

        // Community labels are numbered in ascending order, so the coarser graph does not
        // depend on hash iteration order.
        let mut labels: Vec<usize> = (0..size)
            .map(|node| self.node_to_community.get(&node).copied().unwrap_or(node))
            .collect::<HashSet<_>>()
            .into_iter()
            .collect();
        labels.sort_unstable();
        let coarse_of_label: HashMap<usize, usize> = labels
            .iter()
            .enumerate()
            .map(|(coarse, &label)| (label, coarse))
            .collect();

        let level: HashMap<usize, usize> = (0..size)
            .map(|node| {
                let label = self.node_to_community.get(&node).copied().unwrap_or(node);
                (node, coarse_of_label[&label])
            })
            .collect();

        let mut aggregated: Vec<HashMap<usize, f64>> = vec![HashMap::new(); labels.len()];
        for node in 0..size {
            let from = level[&node];
            for (neighbor, weight) in &self.adjacency_list[node] {
                if let Some(&to) = level.get(neighbor) {
                    *aggregated[from].entry(to).or_insert(0.0) += weight;
                }
            }
        }

        self.adjacency_list = aggregated
            .into_iter()
            .map(|edges| edges.into_iter().collect())
            .collect();
        // Every coarse node starts in a community of its own again.
        self.node_to_community = (0..labels.len()).map(|node| (node, node)).collect();
        self.hierarchy.push(level);
        self.community_weights = self.calculate_new_community_weights()?;
        self.total_weight = self.community_weights.values().sum();
        Ok(())
    }

    fn calculate_new_community_weights(
        &self,
    ) -> Result<HashMap<usize, f64>, CommunityDetectionError> {
        Ok(self
            .adjacency_list
            .iter()
            .enumerate()
            .map(|(node, edges)| (node, edges.iter().map(|(_, w)| w).sum()))
            .collect())
    }

    fn calculate_modularity(&self) -> Result<f64, CommunityDetectionError> {
        let mut modularity = 0.0;
        let m = self.total_weight.max(f64::EPSILON);

        for (node, &community) in &self.node_to_community {
            let node_weight = self.community_weights.get(node).copied().unwrap_or(0.0);
            if *node < self.adjacency_list.len() {
                for (neighbor, weight) in &self.adjacency_list[*node] {
                    if community == *self.node_to_community.get(neighbor).unwrap() {
                        let neighbor_weight =
                            self.community_weights.get(neighbor).copied().unwrap_or(0.0);
                        let term = *weight
                            - self.config.resolution
                                * self.config.gamma
                                * (node_weight * neighbor_weight)
                                / (2.0 * m);
                        if term.is_nan() || term.is_infinite() {
                            return Err(CommunityDetectionError::InvalidFloatResult(format!(
                                "Modularity term resulted in {} for node {}",
                                if term.is_nan() { "NaN" } else { "infinity" },
                                node
                            )));
                        }
                        modularity += term;
                    }
                }
            }
        }
        let result = modularity / (2.0 * m);
        if result.is_nan() || result.is_infinite() {
            return Err(CommunityDetectionError::InvalidFloatResult(format!(
                "Modularity resulted in {}",
                if result.is_nan() { "NaN" } else { "infinity" }
            )));
        }
        Ok(result)
    }

    fn get_nodes_in_community(&self, comm: usize) -> Vec<usize> {
        let mut nodes: Vec<usize> = self
            .node_to_community
            .iter()
            .filter(|(_, &c)| c == comm)
            .map(|(&n, _)| n)
            .collect();
        if self.config.deterministic {
            nodes.sort_unstable();
        }
        nodes
    }

    fn enforce_gamma_properties(&mut self) -> Result<(), CommunityDetectionError> {
        let mut communities: Vec<usize> = self
            .node_to_community
            .values()
            .copied()
            .collect::<HashSet<_>>()
            .into_iter()
            .collect();
        if self.config.deterministic {
            communities.sort_unstable();
        }

        for comm in communities {
            if !self.is_community_connected(comm) {
                self.split_disconnected_community(comm)?;
            }
        }
        Ok(())
    }

    fn is_community_connected(&self, community: usize) -> bool {
        let nodes = self.get_nodes_in_community(community);
        if nodes.len() <= 1 {
            return true;
        }

        let mut visited = HashSet::new();
        let mut stack = vec![nodes[0]];

        while let Some(node) = stack.pop() {
            if visited.insert(node) && node < self.adjacency_list.len() {
                for (neighbor, _) in &self.adjacency_list[node] {
                    if nodes.contains(neighbor) && !visited.contains(neighbor) {
                        stack.push(*neighbor);
                    }
                }
            }
        }

        visited.len() == nodes.len()
    }

    fn split_disconnected_community(
        &mut self,
        community: usize,
    ) -> Result<(), CommunityDetectionError> {
        let nodes = self.get_nodes_in_community(community);
        if nodes.is_empty() {
            return Ok(());
        }

        let components = self.find_connected_components(&nodes);
        for (i, component) in components.iter().enumerate() {
            let new_comm = if i == 0 {
                community
            } else {
                self.adjacency_list.len() + i
            };
            for &node in component {
                self.move_node(node, new_comm)?;
            }
        }
        Ok(())
    }

    fn find_connected_components(&self, nodes: &[usize]) -> Vec<Vec<usize>> {
        let node_set: HashSet<_> = nodes.iter().copied().collect();
        let mut visited = HashSet::new();
        let mut components = Vec::new();

        for &node in nodes {
            if !visited.contains(&node) {
                let mut component = Vec::new();
                let mut stack = vec![node];

                while let Some(current) = stack.pop() {
                    if visited.insert(current) && current < self.adjacency_list.len() {
                        component.push(current);
                        for (neighbor, _) in &self.adjacency_list[current] {
                            if node_set.contains(neighbor) && !visited.contains(neighbor) {
                                stack.push(*neighbor);
                            }
                        }
                    }
                }
                if self.config.deterministic {
                    component.sort_unstable();
                }
                components.push(component);
            }
        }
        components
    }

    fn merge_small_communities(&mut self, min_size: usize) -> Result<(), CommunityDetectionError> {
        let communities = self.get_communities();
        let mut to_merge: Vec<usize> = communities
            .iter()
            .filter(|(_, nodes)| nodes.len() < min_size)
            .map(|(comm, _)| *comm)
            .collect();
        if self.config.deterministic {
            to_merge.sort_unstable();
        }

        for comm in to_merge {
            let mut best_target = comm;
            let mut max_connections = 0.0;

            for node in &communities[&comm] {
                if *node < self.adjacency_list.len() {
                    for (neighbor, weight) in &self.adjacency_list[*node] {
                        let target = self
                            .node_to_community
                            .get(neighbor)
                            .copied()
                            .unwrap_or(*neighbor);
                        if target != comm
                            && communities.get(&target).map_or(0, |v| v.len()) >= min_size
                        {
                            let count = *weight;
                            if count > max_connections {
                                max_connections = count;
                                best_target = target;
                            }
                        }
                    }
                }
            }

            if best_target != comm {
                for node in &communities[&comm] {
                    self.move_node(*node, best_target)?;
                }
            }
        }
        Ok(())
    }

    fn refine_community_subset(
        &mut self,
        comm: usize,
        partition: &mut HashMap<usize, usize>,
    ) -> Result<(), CommunityDetectionError> {
        let mut nodes: Vec<usize> = self
            .node_to_community
            .iter()
            .filter(|(_, &c)| c == comm)
            .map(|(&n, _)| n)
            .collect();

        let max_passes = 10;
        let mut changed;

        for _ in 0..max_passes {
            changed = false;

            if self.config.deterministic {
                nodes.sort_unstable();
            } else {
                nodes.shuffle(&mut self.rng);
            }

            for &node in &nodes {
                if node >= self.adjacency_list.len() {
                    continue;
                }

                let current_comm = partition.get(&node).copied().unwrap_or(node);
                let mut best_comm = current_comm;
                let mut best_delta = f64::MIN;

                let k_i = self.community_weights.get(&node).copied().unwrap_or(0.0);
                let m = self.total_weight.max(f64::EPSILON);

                let mut neighbor_comms: Vec<usize> = self.adjacency_list[node]
                    .iter()
                    .map(|(n, _)| self.node_to_community.get(n).copied().unwrap_or(*n))
                    .collect::<HashSet<_>>()
                    .into_iter()
                    .collect();
                if self.config.deterministic {
                    neighbor_comms.sort_unstable();
                }

                for &neighbor_comm in &neighbor_comms {
                    if neighbor_comm != current_comm {
                        let sum_tot_new = self
                            .community_weights
                            .get(&neighbor_comm)
                            .copied()
                            .unwrap_or(0.0);
                        let sum_tot_old = self
                            .community_weights
                            .get(&current_comm)
                            .copied()
                            .unwrap_or(0.0);
                        let sum_in_new: f64 = self.adjacency_list[node]
                            .iter()
                            .filter(|(n, _)| {
                                self.node_to_community.get(n).copied().unwrap_or(*n)
                                    == neighbor_comm
                            })
                            .map(|(_, w)| w)
                            .sum();
                        let sum_in_old: f64 = self.adjacency_list[node]
                            .iter()
                            .filter(|(n, _)| {
                                self.node_to_community.get(n).copied().unwrap_or(*n) == current_comm
                            })
                            .map(|(_, w)| w)
                            .sum();

                        let delta_new = sum_in_new
                            - self.config.resolution * (sum_tot_new + k_i) * k_i / (2.0 * m);
                        let delta_old =
                            sum_in_old - self.config.resolution * sum_tot_old * k_i / (2.0 * m);
                        let delta = delta_new - delta_old;

                        if delta.is_nan() || delta.is_infinite() {
                            return Err(CommunityDetectionError::InvalidFloatResult(format!(
                                "Delta resulted in {} for node {}",
                                if delta.is_nan() { "NaN" } else { "infinity" },
                                node
                            )));
                        }

                        if delta > best_delta {
                            best_delta = delta;
                            best_comm = neighbor_comm;
                        }
                    }
                }

                if self.config.deterministic {
                    if best_delta > 0.0 && best_comm != current_comm {
                        partition.insert(node, best_comm);
                        changed = true;
                    }
                } else if best_delta > 0.0
                    && self.rng.random::<f64>() < best_delta.exp() / (1.0 + best_delta.exp())
                {
                    partition.insert(node, best_comm);
                    changed = true;
                }
            }

            if !changed {
                break;
            }
        }
        Ok(())
    }

    fn calculate_community_connections(
        node: usize,
        comm: usize,
        adjacency_list: &[Vec<(usize, f64)>],
        node_to_community: &HashMap<usize, usize>,
    ) -> f64 {
        if node >= adjacency_list.len() {
            return 0.0;
        }
        adjacency_list[node]
            .iter()
            .filter(|(n, _)| node_to_community.get(n).copied().unwrap_or(*n) == comm)
            .map(|(_, w)| w)
            .sum()
    }
}

#[cfg(test)]
#[cfg(feature = "graph")]
mod tests {
    use super::*;
    use crate::core::EdgeFiltered;
    use crate::graph::Graph;

    /// Two triangles joined by a single edge — the textbook two-community graph.
    fn barbell() -> (Graph<f64, usize, ()>, Vec<NodeId>) {
        let mut graph = Graph::<f64, usize, ()>::new(false);
        let nodes: Vec<_> = (0..6).map(|i| graph.add_node(i)).collect();
        for triangle in [[0, 1, 2], [3, 4, 5]] {
            for pair in [(0, 1), (1, 2), (0, 2)] {
                graph
                    .add_edge(nodes[triangle[pair.0]], nodes[triangle[pair.1]], 1.0, ())
                    .unwrap();
            }
        }
        graph.add_edge(nodes[2], nodes[3], 1.0, ()).unwrap();
        (graph, nodes)
    }

    #[test]
    fn test_every_node_is_placed_exactly_once() {
        let (graph, nodes) = barbell();
        let communities = graph.detect_communities(1.0).unwrap();

        let mut placed: Vec<NodeId> = communities.values().flatten().copied().collect();
        placed.sort_unstable();
        assert_eq!(placed, nodes);
    }

    #[test]
    fn test_a_seed_makes_the_partition_reproducible() {
        let (graph, _) = barbell();
        let config = CommunityConfig {
            gamma: 1.0,
            seed: Some(42),
            deterministic: true,
            ..CommunityConfig::default()
        };

        let first = graph
            .detect_communities_with_config(config.clone())
            .unwrap();
        for _ in 0..3 {
            assert_eq!(
                graph
                    .detect_communities_with_config(config.clone())
                    .unwrap(),
                first
            );
        }
    }

    #[test]
    fn test_modularity_stays_within_its_bounds() {
        let (graph, _) = barbell();
        let adjacency: Vec<Vec<(usize, f64)>> = graph
            .node_id_vec()
            .into_iter()
            .map(|node| {
                graph
                    .links(node)
                    // The Leiden state works on positions of its own, not node identifiers.
                    .map(|link| (link.target.index(), link.weight))
                    .collect()
            })
            .collect();

        let state = LeidenState::initialize(&adjacency, CommunityConfig::default()).unwrap();
        let modularity = state.calculate_modularity().unwrap();
        assert!((-1.0..=1.0).contains(&modularity));
    }

    #[test]
    fn test_communities_survive_sparse_ids() {
        let mut graph = Graph::<f64, usize, ()>::new(false);
        let a = graph.add_node(0);
        let gap = graph.add_node(1);
        let b = graph.add_node(2);
        let c = graph.add_node(3);
        graph.remove_node(gap).unwrap();
        graph.add_edge(a, b, 1.0, ()).unwrap();
        graph.add_edge(b, c, 1.0, ()).unwrap();

        let communities = graph.detect_communities(1.0).unwrap();
        let mut placed: Vec<NodeId> = communities.values().flatten().copied().collect();
        placed.sort_unstable();
        assert_eq!(placed, vec![a, b, c]);
    }

    #[test]
    fn test_detection_over_a_filtered_view() {
        let (graph, nodes) = barbell();
        // Drop the single edge joining the two triangles and they cannot be one community.
        let bridge = graph.edges_between(nodes[2], nodes[3])[0];
        let split = EdgeFiltered::new(&graph, move |edge| edge != bridge);

        let left: HashSet<NodeId> = nodes[0..3].iter().copied().collect();
        // Swept over seeds: no seed may put nodes from both components in one community,
        // since Leiden's defining guarantee is that the communities it reports are connected.
        for seed in (0..2000).map(|i| i * 7919 + 13) {
            let communities = split
                .detect_communities_with_config(CommunityConfig {
                    seed: Some(seed),
                    deterministic: true,
                    ..CommunityConfig::default()
                })
                .unwrap();
            for members in communities.values() {
                let members: HashSet<NodeId> = members.iter().copied().collect();
                assert!(
                    members.is_subset(&left) || members.is_disjoint(&left),
                    "seed {} produced a community spanning both components: {:?}",
                    seed,
                    members
                );
            }
        }
    }

    /// Leiden's defining guarantee is that the communities it reports are internally
    /// connected. Nothing had been enforcing it across aggregation levels: from the second
    /// aggregation onwards the coarser graph was built by indexing the *current* adjacency
    /// list with *original* node indices, so roughly a third of unseeded runs on this graph
    /// put nodes from two disconnected components into one community.
    #[test]
    fn test_communities_are_never_disconnected() {
        let (graph, nodes) = barbell();
        let bridge = graph.edges_between(nodes[2], nodes[3])[0];
        let split = EdgeFiltered::new(&graph, move |edge| edge != bridge);
        let left: HashSet<NodeId> = nodes[0..3].iter().copied().collect();

        // Unseeded, because the partition depends on hash iteration order as well as on
        // the RNG: fixing only the seed would not have exercised the failure.
        for run in 0..200 {
            let communities = split.detect_communities(1.0).unwrap();
            for members in communities.values() {
                let members: HashSet<NodeId> = members.iter().copied().collect();
                assert!(
                    members.is_subset(&left) || members.is_disjoint(&left),
                    "run {} produced a community spanning both components: {:?}",
                    run,
                    members
                );
            }
        }
    }
}