leiden-rs 0.8.1

High-performance Leiden community detection algorithm for graphs in Rust
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
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
//! Core Leiden algorithm implementation.

use std::borrow::Cow;

use rand::rngs::StdRng;
use rand::SeedableRng;
use rustc_hash::FxHashMap;

use crate::algorithm;
use crate::partition::Partition;
use crate::quality::{GraphData, Modularity, MoveComponents, QualityFunction};

#[cfg(feature = "rayon")]
use crate::parallel::{
    aggregate_edges_parallel, local_moving_parallel, AGG_PARALLEL_THRESHOLD,
};

#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

/// Default value for min_iterations serde deserialization.
#[cfg(feature = "serde")]
const fn default_min_iterations() -> usize {
    1
}

/// Quality function selection for the Leiden algorithm.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[non_exhaustive]
pub enum QualityType {
    /// Newman-Girvan modularity (default).
    #[default]
    Modularity,
    /// Constant Potts Model.
    CPM,
    /// Reichardt-Bornholdt with configuration model null.
    RBConfiguration,
    /// Reichardt-Bornholdt with Erdős-Rényi null model.
    RBER,
}

/// Configuration for the Leiden algorithm.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct LeidenConfig {
    /// Maximum number of Leiden iterations (local move → refine → aggregate).
    pub max_iterations: usize,
    /// Resolution parameter γ controlling community granularity.
    pub resolution: f64,
    /// Optional RNG seed for reproducible results.
    pub seed: Option<u64>,
    /// Quality function to optimize.
    pub quality: QualityType,
    /// Convergence threshold: stop when quality improvement is below this value.
    pub epsilon: f64,
    /// Maximum number of nodes per community (0 = unlimited).
    pub max_comm_size: usize,
    /// Minimum edge slots (CSR entries) for parallel local moving (default: 2000).
    /// Also requires at least 100 nodes. Only depends on graph structure for determinism.
    ///
    /// The parallel path uses graph coloring to partition nodes into independent
    /// sets. Nodes in the same color group are processed concurrently using a
    /// shared snapshot of community statistics. This "relaxed" consistency model
    /// may produce slightly different results compared to the sequential path, but
    /// typically converges to the same partition quality. The sequential path is
    /// always used as a final refinement pass after parallel processing.
    pub parallel_local_moving_threshold: Option<usize>,
    /// Minimum edge slots (CSR entries) for parallel aggregation (default: 10000).
    pub parallel_aggregation_threshold: Option<usize>,
    /// When true, skips the refinement phase (producing Louvain-like results).
    #[cfg_attr(feature = "serde", serde(default))]
    pub skip_refinement: bool,

    /// Minimum iterations before convergence check (default: 1).
    /// Prevents premature convergence by ensuring the algorithm runs
    /// for at least this many iterations before checking epsilon convergence.
    #[cfg_attr(feature = "serde", serde(default = "default_min_iterations"))]
    pub min_iterations: usize,

    /// When true, record per-iteration quality values in output (default: false).
    #[cfg_attr(feature = "serde", serde(default))]
    pub track_quality_history: bool,
}

impl Default for LeidenConfig {
    fn default() -> Self {
        Self {
            max_iterations: 100,
            resolution: 1.0,
            seed: None,
            quality: QualityType::default(),
            epsilon: 1e-10,
            max_comm_size: 0,
            parallel_local_moving_threshold: None,
            parallel_aggregation_threshold: None,
            skip_refinement: false,
            min_iterations: 1,
            track_quality_history: false,
        }
    }
}

impl LeidenConfig {
    /// Validate configuration parameters.
    ///
    /// Returns `Err(LeidenError)` if any parameter is invalid.
    pub fn validate(&self) -> crate::error::Result<()> {
        if self.max_iterations == 0 {
            return Err(crate::error::LeidenError::InvalidParameter {
                message: "max_iterations must be > 0".to_string(),
            });
        }
        if !self.resolution.is_finite() || self.resolution < 0.0 {
            return Err(crate::error::LeidenError::InvalidParameter {
                message: format!("resolution must be finite and non-negative, got {}", self.resolution),
            });
        }
        if !self.epsilon.is_finite() || self.epsilon <= 0.0 {
            return Err(crate::error::LeidenError::InvalidParameter {
                message: format!("epsilon must be finite and positive, got {}", self.epsilon),
            });
        }
        Ok(())
    }

    /// Create a builder for configuring the Leiden algorithm.
    #[must_use = "constructor returns a new instance"]
    pub fn builder() -> LeidenConfigBuilder {
        LeidenConfigBuilder::default()
    }
}

/// Builder for [`LeidenConfig`].
#[derive(Debug, Clone, Default)]
pub struct LeidenConfigBuilder {
    max_iterations: Option<usize>,
    resolution: Option<f64>,
    seed: Option<u64>,
    quality: Option<QualityType>,
    epsilon: Option<f64>,
    max_comm_size: Option<usize>,
    parallel_local_moving_threshold: Option<usize>,
    parallel_aggregation_threshold: Option<usize>,
    skip_refinement: Option<bool>,
    min_iterations: Option<usize>,
    track_quality_history: Option<bool>,
}

impl LeidenConfigBuilder {
    /// Set the maximum number of Leiden iterations.
    pub fn max_iterations(mut self, v: usize) -> Self {
        self.max_iterations = Some(v);
        self
    }

    /// Set the resolution parameter γ.
    pub fn resolution(mut self, v: f64) -> Self {
        self.resolution = Some(v);
        self
    }

    /// Set the RNG seed for reproducible results.
    pub fn seed(mut self, v: u64) -> Self {
        self.seed = Some(v);
        self
    }

    /// Set the RNG seed only if `v` is `Some`.
    pub fn maybe_seed(mut self, v: Option<u64>) -> Self {
        self.seed = v;
        self
    }

    /// Set the quality function to optimize.
    pub fn quality(mut self, v: QualityType) -> Self {
        self.quality = Some(v);
        self
    }

    /// Set the convergence threshold.
    pub fn epsilon(mut self, v: f64) -> Self {
        self.epsilon = Some(v);
        self
    }

    /// Set the maximum number of nodes per community (0 = unlimited).
    pub fn max_comm_size(mut self, v: usize) -> Self {
        self.max_comm_size = Some(v);
        self
    }

    /// Set the minimum edge slots for parallel local moving (default: 2000).
    /// Also requires at least 100 nodes. Only depends on graph structure for determinism.
    pub fn parallel_local_moving_threshold(mut self, v: usize) -> Self {
        self.parallel_local_moving_threshold = Some(v);
        self
    }

    /// Set the parallel local moving threshold only if `v` is `Some`.
    pub fn maybe_parallel_local_moving_threshold(mut self, v: Option<usize>) -> Self {
        self.parallel_local_moving_threshold = v;
        self
    }

    /// Set the minimum edge slots for parallel aggregation (default: 10000).
    pub fn parallel_aggregation_threshold(mut self, v: usize) -> Self {
        self.parallel_aggregation_threshold = Some(v);
        self
    }

    /// Set the parallel aggregation threshold only if `v` is `Some`.
    pub fn maybe_parallel_aggregation_threshold(mut self, v: Option<usize>) -> Self {
        self.parallel_aggregation_threshold = v;
        self
    }

    /// Skip the refinement phase, producing Louvain-like results.
    pub fn skip_refinement(mut self, v: bool) -> Self {
        self.skip_refinement = Some(v);
        self
    }

    /// Set the minimum number of iterations before convergence check.
    pub fn min_iterations(mut self, v: usize) -> Self {
        self.min_iterations = Some(v);
        self
    }

    /// When true, record per-iteration quality values in the output.
    pub fn track_quality_history(mut self, v: bool) -> Self {
        self.track_quality_history = Some(v);
        self
    }

    /// Build the configuration, applying defaults for unset fields.
    pub fn build(self) -> LeidenConfig {
        LeidenConfig {
            max_iterations: self.max_iterations.unwrap_or(100),
            resolution: self.resolution.unwrap_or(1.0),
            seed: self.seed,
            quality: self.quality.unwrap_or_default(),
            epsilon: self.epsilon.unwrap_or(1e-10),
            max_comm_size: self.max_comm_size.unwrap_or(0),
            parallel_local_moving_threshold: self.parallel_local_moving_threshold,
            parallel_aggregation_threshold: self.parallel_aggregation_threshold,
            skip_refinement: self.skip_refinement.unwrap_or(false),
            min_iterations: self.min_iterations.unwrap_or(1),
            track_quality_history: self.track_quality_history.unwrap_or(false),
        }
    }
}

/// Result of running the Leiden algorithm, containing the partition and its quality score.
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[non_exhaustive]
pub struct LeidenOutput {
    /// The detected community partition.
    pub partition: Partition,
    /// The quality score of the partition (higher is better).
    pub quality: f64,
    /// Per-iteration quality values (only populated if `track_quality_history` is enabled).
    pub quality_history: Vec<f64>,
}

impl LeidenOutput {
    /// Create a new Leiden output with the given partition and quality score.
    #[must_use = "constructor returns a new instance"]
    pub fn new(partition: Partition, quality: f64) -> Self {
        Self {
            partition,
            quality,
            quality_history: Vec::new(),
        }
    }
}

/// Owned quality function enum wrapping all supported quality functions.
///
/// Used internally to pass a quality function through the algorithm pipeline
/// without lifetime concerns. Implements [`QualityFunction`] by delegating
/// to the wrapped variant.
#[allow(clippy::upper_case_acronyms)]
enum QualityFn {
    Modularity(Modularity),
    CPM(crate::quality::CPM),
    RBConfiguration(crate::quality::RBConfiguration),
    RBER(crate::quality::RBER),
}

impl QualityFunction for QualityFn {
    #[inline]
    fn delta_move_from_components(&self, c: &MoveComponents) -> f64 {
        match self {
            Self::Modularity(q) => q.delta_move_from_components(c),
            Self::CPM(q) => q.delta_move_from_components(c),
            Self::RBConfiguration(q) => q.delta_move_from_components(c),
            Self::RBER(q) => q.delta_move_from_components(c),
        }
    }

    fn total_quality(&self, data: &GraphData, partition: &Partition) -> f64 {
        match self {
            Self::Modularity(q) => q.total_quality(data, partition),
            Self::CPM(q) => q.total_quality(data, partition),
            Self::RBConfiguration(q) => q.total_quality(data, partition),
            Self::RBER(q) => q.total_quality(data, partition),
        }
    }
}

/// The Leiden community detection algorithm.
#[derive(Debug, Clone)]
pub struct Leiden {
    config: LeidenConfig,
}

impl Leiden {
    /// Create a new Leiden instance with the given configuration.
    #[must_use = "constructor returns a new instance"]
    pub fn new(config: LeidenConfig) -> Self {
        Self { config }
    }

    fn create_quality(&self) -> QualityFn {
        match self.config.quality {
            QualityType::Modularity => {
                QualityFn::Modularity(Modularity::with_resolution(self.config.resolution))
            }
            QualityType::CPM => QualityFn::CPM(crate::quality::CPM::new(self.config.resolution)),
            QualityType::RBConfiguration => QualityFn::RBConfiguration(
                crate::quality::RBConfiguration::with_resolution(self.config.resolution),
            ),
            QualityType::RBER => QualityFn::RBER(crate::quality::RBER::new(self.config.resolution)),
        }
    }

    /// Core Leiden iteration loop.
    ///
    /// Runs the three-phase cycle (local moving → refinement → aggregation)
    /// and calls `on_iteration` after each successful local-moving phase,
    /// allowing the caller to collect per-level information without
    /// duplicating the algorithm logic.
    ///
    /// The `on_iteration` closure receives `(data, partition, q_after,
    /// flat_mapping, original_n)`. For `run()` an empty closure is passed
    /// and the compiler eliminates it entirely via monomorphization.
    fn run_core<'a, F>(
        &self,
        input_data: &'a GraphData,
        quality: &QualityFn,
        initial_partition: Option<Partition>,
        on_iteration: &mut F,
    ) -> crate::error::Result<(Partition, f64, Vec<f64>)>
    where
        F: FnMut(&GraphData, &Partition, f64, &[usize], usize),
    {
        self.config.validate()?;

        let original_n = input_data.node_count();
        let mut data: Cow<'a, GraphData> = Cow::Borrowed(input_data);
        let mut partition = initial_partition.unwrap_or_else(|| Partition::new(data.node_count()));
        partition.renumber();
        let mut flat_mapping: Vec<usize> = (0..data.node_count()).collect();
        let mut quality_history: Vec<f64> = Vec::new();

        let mut rng = match self.config.seed {
            Some(seed) => StdRng::seed_from_u64(seed),
            None => StdRng::from_rng(&mut rand::rng()),
        };

        let mut local_moving_buffers =
            algorithm::LocalMovingBuffers::new(data.node_count(), 1);
        let mut refinement_buffers =
            algorithm::RefinementBuffers::new(data.node_count(), 1);

        for iteration in 0..self.config.max_iterations {
            let q_before = quality.total_quality(&data, &partition);
            let changed = local_moving_dispatch(
                std::slice::from_ref(&*data),
                &mut partition,
                quality,
                &mut rng,
                &algorithm::MovingConfig {
                    max_comm_size: self.config.max_comm_size,
                    epsilon: self.config.epsilon,
                },
                &self.config,
                &mut local_moving_buffers,
            );
            if !changed {
                break;
            }
            partition.renumber();

            let q_after = quality.total_quality(&data, &partition);

            on_iteration(&data, &partition, q_after, &flat_mapping, original_n);

            // Track per-iteration quality if enabled
            if self.config.track_quality_history {
                quality_history.push(q_after);
            }

            // Only check epsilon convergence after min_iterations
            if iteration >= self.config.min_iterations
                && (q_after - q_before).abs() < self.config.epsilon
            {
                break;
            }

            let refined = if !self.config.skip_refinement {
                refinement(&data, &partition, quality, &mut rng, self.config.epsilon, &mut refinement_buffers)
            } else {
                // In Louvain mode, use the unrefined partition directly
                partition.clone()
            };

            let (agg_data, orig_to_agg, agg_initial_partition) =
                aggregate(&data, &refined, &partition, &self.config)?;

            for orig_node in 0..original_n {
                flat_mapping[orig_node] = orig_to_agg[flat_mapping[orig_node]];
            }

            data = Cow::Owned(agg_data);
            partition = agg_initial_partition;

            if data.node_count() <= 1 {
                break;
            }
        }

        // Resolve aggregate nodes back to original node IDs.
        let mut result = Partition::from_membership(vec![0; original_n]);
        for (orig_node, &agg_node) in flat_mapping.iter().enumerate() {
            let comm = partition.community_of(agg_node);
            result.move_node(orig_node, comm);
        }
        result.renumber();
        // Compute quality on the original input graph, not the aggregated graph
        let q = quality.total_quality(input_data, &result);
        Ok((result, q, quality_history))
    }

    /// Run the Leiden algorithm on the given graph.
    ///
    /// Returns a [`LeidenOutput`] containing the community partition and its quality score.
    #[must_use = "algorithm result should be used"]
    pub fn run(&self, data: &GraphData) -> crate::error::Result<LeidenOutput> {
        if data.node_count() == 0 {
            return Ok(LeidenOutput {
                partition: Partition::new(0),
                quality: 0.0,
                quality_history: Vec::new(),
            });
        }

        let quality = self.create_quality();
        let (partition, q, quality_history) =
            self.run_core(data, &quality, None, &mut |_, _, _, _, _| {})?;
        Ok(LeidenOutput {
            partition,
            quality: q,
            quality_history,
        })
    }

    /// Run the Leiden algorithm with an initial partition (warm-start).
    ///
    /// Instead of starting from a singleton partition (each node in its own community),
    /// this method uses the provided partition as the starting point. Useful for:
    /// - Resuming optimization from a previous run
    /// - Incremental refinement after minor graph changes
    /// - Seeding with an external community detection result
    #[must_use = "algorithm result should be used"]
    pub fn run_with_initial_partition(
        &self,
        data: &GraphData,
        mut initial_partition: Partition,
    ) -> crate::error::Result<LeidenOutput> {
        if data.node_count() == 0 {
            return Ok(LeidenOutput {
                partition: Partition::new(0),
                quality: 0.0,
                quality_history: Vec::new(),
            });
        }
        if initial_partition.len() != data.node_count() {
            return Err(crate::error::LeidenError::InvalidPartition {
                message: format!(
                    "partition size {} does not match graph node count {}",
                    initial_partition.len(),
                    data.node_count()
                ),
            });
        }
        // Renumber first so num_communities reflects the actual max community ID.
        initial_partition.renumber();
        if initial_partition.num_communities() > data.node_count() {
            return Err(crate::error::LeidenError::InvalidPartition {
                message: format!(
                    "partition has {} communities but graph only has {} nodes",
                    initial_partition.num_communities(),
                    data.node_count()
                ),
            });
        }

        let quality = self.create_quality();
        let (partition, q, quality_history) = self.run_core(
            data,
            &quality,
            Some(initial_partition),
            &mut |_, _, _, _, _| {},
        )?;
        Ok(LeidenOutput {
            partition,
            quality: q,
            quality_history,
        })
    }

    /// Run the Leiden algorithm and capture intermediate community structure
    /// at each aggregation level.
    ///
    /// Returns a [`HierarchicalOutput`](crate::hierarchy::HierarchicalOutput)
    /// containing the final partition, quality, and per-level membership vectors.
    #[must_use = "algorithm result should be used"]
    pub fn run_hierarchical(
        &self,
        data: &GraphData,
    ) -> crate::error::Result<crate::hierarchy::HierarchicalOutput> {
        use crate::hierarchy::{HierarchicalOutput, HierarchyLevel};

        if data.node_count() == 0 {
            return Ok(HierarchicalOutput {
                levels: vec![HierarchyLevel {
                    node_count: 0,
                    num_communities: 0,
                    quality: 0.0,
                    membership: vec![],
                }],
                partition: Partition::new(0),
                quality: 0.0,
            });
        }

        let quality = self.create_quality();
        let mut levels: Vec<HierarchyLevel> = Vec::new();
        let (partition, q, _quality_history) = self.run_core(
            data,
            &quality,
            None,
            &mut |data, part, q_after, flat_mapping, original_n| {
                let membership = resolve_to_original_nodes(flat_mapping, part, original_n);
                levels.push(HierarchyLevel {
                    node_count: data.node_count(),
                    num_communities: part.num_communities(),
                    quality: q_after,
                    membership,
                });
            },
        )?;

        Ok(HierarchicalOutput {
            levels,
            partition,
            quality: q,
        })
    }
}

fn resolve_to_original_nodes(
    flat_mapping: &[usize],
    partition: &Partition,
    original_n: usize,
) -> Vec<usize> {
    let mut result = vec![0; original_n];
    for orig_node in 0..original_n {
        let agg_node = flat_mapping[orig_node];
        result[orig_node] = partition.community_of(agg_node);
    }
    result
}

fn local_moving_dispatch(
    data: &[GraphData],
    partition: &mut Partition,
    quality: &(dyn QualityFunction + Sync),
    rng: &mut StdRng,
    cfg: &algorithm::MovingConfig,
    _config: &LeidenConfig,
    buffers: &mut algorithm::LocalMovingBuffers,
) -> bool {
    #[cfg(feature = "rayon")]
    {
        if should_use_parallel(&data[0], _config) {
            let (parallel_changed, converged_naturally) =
                local_moving_parallel(&data[0], partition, quality, rng, cfg.max_comm_size, cfg.epsilon);
            if converged_naturally {
                return parallel_changed;
            }
            let sequential_changed = algorithm::local_moving_generic(
                data,
                &[1.0],
                partition,
                quality,
                rng,
                cfg,
                buffers,
            );
            return parallel_changed || sequential_changed;
        }
    }
    algorithm::local_moving_generic(
        data,
        &[1.0],
        partition,
        quality,
        rng,
        cfg,
        buffers,
    )
}

/// Decide whether to use parallel local moving based on graph structure.
/// MUST only depend on graph properties, NOT on runtime state (threads, load),
/// to ensure deterministic behavior (same graph → same code path → same result).
#[cfg(feature = "rayon")]
#[inline]
fn should_use_parallel(data: &GraphData, config: &LeidenConfig) -> bool {
    let n = data.node_count();
    // Use edge slot count (total CSR entries) as the work estimate.
    // 2000 edge slots ≈ ~500 nodes × avg_degree 4, or ~200 nodes × avg_degree 10
    let edge_slots = data.out_offsets[n];
    let threshold = config.parallel_local_moving_threshold.unwrap_or(2000);
    edge_slots >= threshold && n >= 100
}

fn refinement(
    data: &GraphData,
    partition: &Partition,
    quality: &(dyn QualityFunction + Sync),
    rng: &mut StdRng,
    epsilon: f64,
    buffers: &mut algorithm::RefinementBuffers,
) -> Partition {
    if data.total_weight() <= 0.0 {
        return Partition::new(data.node_count());
    }
    let layers = std::slice::from_ref(data);
    algorithm::refinement_generic(
        data.node_count(),
        1, // single layer
        partition,
        rng,
        buffers,
        |community, nodes, buf| {
            algorithm::refine_community_generic(
                layers,
                &[1.0],
                partition,
                quality,
                &algorithm::CommunitySubset { community, nodes },
                &algorithm::MovingConfig {
                    max_comm_size: 0,
                    epsilon,
                },
                buf,
            )
        },
    )
}

fn aggregate_edges_sequential(
    data: &GraphData,
    orig_to_agg: &[usize],
    directed: bool,
) -> FxHashMap<(usize, usize), f64> {
    let n = data.node_count();
    let mut agg_edges: FxHashMap<(usize, usize), f64> = FxHashMap::default();
    for u in 0..n {
        algorithm::aggregate_node_edges_into(data, u, orig_to_agg, directed, &mut agg_edges);
    }
    agg_edges
}

fn aggregate(
    data: &GraphData,
    refined_partition: &Partition,
    coarse_partition: &Partition,
    _config: &LeidenConfig,
) -> crate::error::Result<(GraphData, Vec<usize>, Partition)> {
    let n = data.node_count();
    let (orig_to_agg, agg_n) = algorithm::build_orig_to_agg_mapping(n, refined_partition);

    let directed = data.is_directed();
    let agg_edges_map: FxHashMap<(usize, usize), f64> = {
        #[cfg(feature = "rayon")]
        {
            let edge_slots = data.out_offsets[n];
            let threshold = _config.parallel_aggregation_threshold.unwrap_or(AGG_PARALLEL_THRESHOLD);
            if edge_slots >= threshold {
                aggregate_edges_parallel(data, &orig_to_agg, directed)
            } else {
                aggregate_edges_sequential(data, &orig_to_agg, directed)
            }
        }
        #[cfg(not(feature = "rayon"))]
        {
            aggregate_edges_sequential(data, &orig_to_agg, directed)
        }
    };

    algorithm::build_aggregated_graph(
        orig_to_agg,
        agg_n,
        directed,
        agg_edges_map,
        coarse_partition,
        |orig| data.node_weight(orig),
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::graph::{GraphData, GraphDataBuilder};
    use rand::prelude::IndexedRandom;

    fn make_two_cliques() -> GraphData {
        let mut b = GraphDataBuilder::new(10);
        for i in 0..5 {
            for j in (i + 1)..5 {
                b.add_edge(i, j, 1.0).unwrap();
            }
        }
        for i in 5..10 {
            for j in (i + 1)..10 {
                b.add_edge(i, j, 1.0).unwrap();
            }
        }
        b.add_edge(0, 5, 1.0).unwrap();
        b.build().unwrap()
    }

    #[test]
    fn test_two_cliques() {
        let graph = make_two_cliques();
        let leiden = Leiden::new(LeidenConfig::default());
        let partition = leiden.run(&graph).unwrap().partition;

        assert_eq!(partition.num_communities(), 2);

        let comm0 = partition.community_of(0);
        for i in 1..5 {
            assert_eq!(partition.community_of(i), comm0, "node {i}");
        }
        let comm5 = partition.community_of(5);
        for i in 6..10 {
            assert_eq!(partition.community_of(i), comm5, "node {i}");
        }
        assert_ne!(comm0, comm5);
    }

    #[test]
    fn test_single_node() {
        let data = GraphDataBuilder::new(1).build().unwrap();

        let leiden = Leiden::new(LeidenConfig::default());
        let partition = leiden.run(&data).unwrap().partition;
        assert_eq!(partition.num_communities(), 1);
    }

    #[test]
    fn test_ring_of_cliques() {
        let mut b = GraphDataBuilder::new(12);

        for i in 0..4 {
            for j in (i + 1)..4 {
                b.add_edge(i, j, 1.0).unwrap();
            }
        }
        for i in 4..8 {
            for j in (i + 1)..8 {
                b.add_edge(i, j, 1.0).unwrap();
            }
        }
        for i in 8..12 {
            for j in (i + 1)..12 {
                b.add_edge(i, j, 1.0).unwrap();
            }
        }
        b.add_edge(0, 4, 0.1).unwrap();
        b.add_edge(4, 8, 0.1).unwrap();
        b.add_edge(8, 0, 0.1).unwrap();

        let data = b.build().unwrap();
        let leiden = Leiden::new(LeidenConfig::default());
        let partition = leiden.run(&data).unwrap().partition;

        assert_eq!(partition.num_communities(), 3);
    }

    #[test]
    fn test_empty_graph() {
        let data = GraphDataBuilder::new(0).build().unwrap();
        let leiden = Leiden::new(LeidenConfig::default());
        let partition = leiden.run(&data).unwrap().partition;
        assert_eq!(partition.num_communities(), 0);
    }

    #[test]
    fn test_disconnected_graph() {
        let mut b = GraphDataBuilder::new(6);

        for i in 0..3 {
            for j in (i + 1)..3 {
                b.add_edge(i, j, 1.0).unwrap();
            }
        }
        for i in 3..6 {
            for j in (i + 1)..6 {
                b.add_edge(i, j, 1.0).unwrap();
            }
        }

        let data = b.build().unwrap();
        let leiden = Leiden::new(LeidenConfig::default());
        let partition = leiden.run(&data).unwrap().partition;

        assert_eq!(partition.num_communities(), 2);

        let comm0 = partition.community_of(0);
        assert_eq!(partition.community_of(1), comm0);
        assert_eq!(partition.community_of(2), comm0);

        let comm3 = partition.community_of(3);
        assert_eq!(partition.community_of(4), comm3);
        assert_eq!(partition.community_of(5), comm3);

        assert_ne!(comm0, comm3);
    }

    #[test]
    fn test_single_edge() {
        let mut b = GraphDataBuilder::new(2);
        b.add_edge(0, 1, 1.0).unwrap();
        let data = b.build().unwrap();

        let leiden = Leiden::new(LeidenConfig::default());
        let partition = leiden.run(&data).unwrap().partition;

        assert_eq!(partition.num_communities(), 1);
        assert_eq!(partition.community_of(0), partition.community_of(1));
    }

    #[test]
    fn test_weighted_graph() {
        let mut b = GraphDataBuilder::new(6);

        for i in 0..3 {
            for j in (i + 1)..3 {
                b.add_edge(i, j, 5.0).unwrap();
            }
        }
        for i in 3..6 {
            for j in (i + 1)..6 {
                b.add_edge(i, j, 5.0).unwrap();
            }
        }
        b.add_edge(0, 3, 0.1).unwrap();

        let data = b.build().unwrap();
        let leiden = Leiden::new(LeidenConfig::default());
        let partition = leiden.run(&data).unwrap().partition;

        assert_eq!(partition.num_communities(), 2);

        let comm0 = partition.community_of(0);
        for i in 1..3 {
            assert_eq!(partition.community_of(i), comm0, "node {i}");
        }
        let comm3 = partition.community_of(3);
        for i in 4..6 {
            assert_eq!(partition.community_of(i), comm3, "node {i}");
        }
        assert_ne!(comm0, comm3);
    }

    #[test]
    fn test_large_random_graph_determinism() {
        let mut rng = StdRng::seed_from_u64(12345);

        let mut builder = GraphDataBuilder::new(100);

        let clusters: Vec<Vec<usize>> = (0..4).map(|c| (c * 25..(c + 1) * 25).collect()).collect();

        for cluster in &clusters {
            for &node in cluster {
                let others: Vec<usize> = cluster.iter().filter(|&&x| x != node).copied().collect();
                let count = std::cmp::min(5, others.len());
                let chosen: Vec<usize> = others.choose_multiple(&mut rng, count).copied().collect();
                for &neighbor in &chosen {
                    if neighbor > node {
                        builder.add_edge(node, neighbor, 1.0).unwrap();
                    }
                }
            }
        }

        for i in 0..4 {
            for j in (i + 1)..4 {
                let mut pairs: Vec<(usize, usize)> = Vec::new();
                for &a in &clusters[i] {
                    for &bb in &clusters[j] {
                        pairs.push((a, bb));
                    }
                }
                let count = std::cmp::min(3, pairs.len());
                for &(a, b) in pairs.choose_multiple(&mut rng, count) {
                    builder.add_edge(a, b, 0.1).unwrap();
                }
            }
        }

        let data = builder.build().unwrap();

        let leiden = Leiden::new(LeidenConfig {
            seed: Some(42),
            ..Default::default()
        });
        let partition1 = leiden.run(&data).unwrap().partition;

        let leiden2 = Leiden::new(LeidenConfig {
            seed: Some(42),
            ..Default::default()
        });
        let partition2 = leiden2.run(&data).unwrap().partition;

        assert_eq!(
            partition1.as_slice(),
            partition2.as_slice(),
            "same seed should produce identical partitions"
        );
        assert!(
            partition1.num_communities() >= 2,
            "expected at least 2 communities, got {}",
            partition1.num_communities()
        );
    }

    #[test]
    fn test_star_graph() {
        let mut b = GraphDataBuilder::new(11);
        for i in 1..11 {
            b.add_edge(0, i, 1.0).unwrap();
        }
        let data = b.build().unwrap();

        let leiden = Leiden::new(LeidenConfig::default());
        let partition = leiden.run(&data).unwrap().partition;

        assert!(partition.num_communities() >= 1);
    }

    #[test]
    fn test_isolated_nodes_with_edges() {
        let mut b = GraphDataBuilder::new(9);
        for i in 0..4 {
            for j in (i + 1)..4 {
                b.add_edge(i, j, 1.0).unwrap();
            }
        }
        for i in 4..8 {
            for j in (i + 1)..8 {
                b.add_edge(i, j, 1.0).unwrap();
            }
        }
        let data = b.build().unwrap();

        let leiden = Leiden::new(LeidenConfig::default());
        let partition = leiden.run(&data).unwrap().partition;

        assert_eq!(partition.num_communities(), 3);

        let comm0 = partition.community_of(0);
        for i in 1..4 {
            assert_eq!(partition.community_of(i), comm0, "node {i}");
        }
        let comm4 = partition.community_of(4);
        for i in 5..8 {
            assert_eq!(partition.community_of(i), comm4, "node {i}");
        }
        let comm8 = partition.community_of(8);
        assert_ne!(comm8, comm0);
        assert_ne!(comm8, comm4);
    }

    #[test]
    fn test_seed_determinism_different_seeds() {
        let graph = make_two_cliques();

        let config1 = LeidenConfig {
            seed: Some(1),
            ..Default::default()
        };
        let leiden1 = Leiden::new(config1);
        let partition1 = leiden1.run(&graph).unwrap().partition;

        let config2 = LeidenConfig {
            seed: Some(2),
            ..Default::default()
        };
        let leiden2 = Leiden::new(config2);
        let partition2 = leiden2.run(&graph).unwrap().partition;

        assert_eq!(partition1.num_communities(), 2);
        assert_eq!(partition2.num_communities(), 2);
    }

    #[test]
    fn test_self_loop() {
        let mut b = GraphDataBuilder::new(4);
        b.add_edge(0, 1, 1.0).unwrap();
        b.add_edge(2, 3, 1.0).unwrap();
        b.add_edge(0, 0, 2.0).unwrap();
        let data = b.build().unwrap();

        let leiden = Leiden::new(LeidenConfig::default());
        let partition = leiden.run(&data).unwrap().partition;

        assert_eq!(partition.num_communities(), 2);
        assert_eq!(partition.community_of(0), partition.community_of(1));
        assert_eq!(partition.community_of(2), partition.community_of(3));
        assert_ne!(partition.community_of(0), partition.community_of(2));
    }

    #[test]
    fn test_hierarchical_matches_run() {
        let graph = make_two_cliques();
        let leiden = Leiden::new(LeidenConfig {
            seed: Some(42),
            ..Default::default()
        });
        let normal = leiden.run(&graph).unwrap();
        let hierarchical = leiden.run_hierarchical(&graph).unwrap();

        assert_eq!(
            normal.partition.as_slice(),
            hierarchical.partition.as_slice()
        );
        assert!((normal.quality - hierarchical.quality).abs() < 1e-10);
        assert!(!hierarchical.levels.is_empty());
    }

    #[test]
    fn test_hierarchical_levels_decrease_nodes() {
        let graph = make_two_cliques();
        let leiden = Leiden::new(LeidenConfig {
            seed: Some(42),
            ..Default::default()
        });
        let h = leiden.run_hierarchical(&graph).unwrap();

        for window in h.levels.windows(2) {
            assert!(window[1].node_count <= window[0].node_count);
        }

        if !h.levels.is_empty() {
            let last_level = &h.levels[h.levels.len() - 1];
            for node in 0..graph.node_count() {
                assert_eq!(last_level.membership[node], h.partition.community_of(node));
            }
        }
    }

    #[test]
    fn test_hierarchical_community_of_at_level() {
        let graph = make_two_cliques();
        let leiden = Leiden::new(LeidenConfig {
            seed: Some(42),
            ..Default::default()
        });
        let h = leiden.run_hierarchical(&graph).unwrap();

        if h.levels.len() >= 2 {
            assert!(h.levels[0].num_communities >= h.partition.num_communities());
        }
    }

    #[test]
    fn test_parallel_matches_sequential() {
        let graph = make_two_cliques();
        let leiden = Leiden::new(LeidenConfig {
            seed: Some(42),
            ..Default::default()
        });
        let result_normal = leiden.run(&graph).unwrap();
        assert!(result_normal.partition.num_communities() >= 1);
    }

    // LeidenConfig::validate() error path tests
    #[test]
    fn test_validate_rejects_zero_iterations() {
        let config = LeidenConfig {
            max_iterations: 0,
            ..Default::default()
        };
        let err = config.validate().unwrap_err();
        assert!(matches!(err, crate::error::LeidenError::InvalidParameter { .. }));
    }

    #[test]
    fn test_validate_rejects_negative_resolution() {
        let config = LeidenConfig {
            resolution: -1.0,
            ..Default::default()
        };
        let err = config.validate().unwrap_err();
        assert!(matches!(err, crate::error::LeidenError::InvalidParameter { .. }));
    }

    #[test]
    fn test_validate_rejects_nan_resolution() {
        let config = LeidenConfig {
            resolution: f64::NAN,
            ..Default::default()
        };
        let err = config.validate().unwrap_err();
        assert!(matches!(err, crate::error::LeidenError::InvalidParameter { .. }));
    }

    #[test]
    fn test_validate_rejects_infinite_resolution() {
        let config = LeidenConfig {
            resolution: f64::INFINITY,
            ..Default::default()
        };
        let err = config.validate().unwrap_err();
        assert!(matches!(err, crate::error::LeidenError::InvalidParameter { .. }));
    }

    #[test]
    fn test_validate_rejects_zero_epsilon() {
        let config = LeidenConfig {
            epsilon: 0.0,
            ..Default::default()
        };
        let err = config.validate().unwrap_err();
        assert!(matches!(err, crate::error::LeidenError::InvalidParameter { .. }));
    }

    #[test]
    fn test_validate_rejects_negative_epsilon() {
        let config = LeidenConfig {
            epsilon: -1e-10,
            ..Default::default()
        };
        let err = config.validate().unwrap_err();
        assert!(matches!(err, crate::error::LeidenError::InvalidParameter { .. }));
    }

    #[test]
    fn test_validate_rejects_nan_epsilon() {
        let config = LeidenConfig {
            epsilon: f64::NAN,
            ..Default::default()
        };
        let err = config.validate().unwrap_err();
        assert!(matches!(err, crate::error::LeidenError::InvalidParameter { .. }));
    }

    #[test]
    fn test_validate_rejects_infinite_epsilon() {
        let config = LeidenConfig {
            epsilon: f64::INFINITY,
            ..Default::default()
        };
        let err = config.validate().unwrap_err();
        assert!(matches!(err, crate::error::LeidenError::InvalidParameter { .. }));
    }

    #[test]
    fn test_validate_accepts_defaults() {
        assert!(LeidenConfig::default().validate().is_ok());
    }

    #[test]
    fn test_validate_accepts_zero_resolution() {
        let config = LeidenConfig {
            resolution: 0.0,
            ..Default::default()
        };
        assert!(config.validate().is_ok());
    }

    // ── Louvain mode (skip_refinement) tests ──────────────────────────────

    #[test]
    fn test_louvain_mode_produces_valid_partition() {
        let graph = make_two_cliques();
        let config = LeidenConfig {
            skip_refinement: true,
            seed: Some(42),
            ..Default::default()
        };
        let result = Leiden::new(config).run(&graph).unwrap();
        assert_eq!(result.partition.num_communities(), 2);

        let comm0 = result.partition.community_of(0);
        for i in 1..5 {
            assert_eq!(result.partition.community_of(i), comm0, "node {i}");
        }
        let comm5 = result.partition.community_of(5);
        for i in 6..10 {
            assert_eq!(result.partition.community_of(i), comm5, "node {i}");
        }
        assert_ne!(comm0, comm5);
    }

    #[test]
    fn test_louvain_quality_le_than_leiden() {
        let graph = make_two_cliques();

        let leiden = Leiden::new(LeidenConfig {
            seed: Some(42),
            skip_refinement: false,
            ..Default::default()
        });
        let leiden_result = leiden.run(&graph).unwrap();

        let louvain = Leiden::new(LeidenConfig {
            seed: Some(42),
            skip_refinement: true,
            ..Default::default()
        });
        let louvain_result = louvain.run(&graph).unwrap();

        // Refinement phase should produce quality >= unrefined (Louvain)
        assert!(
            louvain_result.quality <= leiden_result.quality + 1e-12,
            "Louvain quality {:.10} should be <= Leiden quality {:.10}",
            louvain_result.quality,
            leiden_result.quality
        );
        // Validate both produce valid partitions
        assert!(leiden_result.partition.num_communities() >= 1);
        assert!(louvain_result.partition.num_communities() >= 1);
    }

    #[test]
    fn test_louvain_quality_le_than_leiden_with_cpm() {
        let mut b = GraphDataBuilder::new(12);
        for i in 0..4 {
            for j in (i + 1)..4 {
                b.add_edge(i, j, 1.0).unwrap();
            }
        }
        for i in 4..8 {
            for j in (i + 1)..8 {
                b.add_edge(i, j, 1.0).unwrap();
            }
        }
        for i in 8..12 {
            for j in (i + 1)..12 {
                b.add_edge(i, j, 1.0).unwrap();
            }
        }
        b.add_edge(0, 4, 0.1).unwrap();
        b.add_edge(4, 8, 0.1).unwrap();
        b.add_edge(8, 0, 0.1).unwrap();
        let graph = b.build().unwrap();

        let leiden = Leiden::new(LeidenConfig {
            seed: Some(42),
            quality: QualityType::CPM,
            resolution: 0.5,
            skip_refinement: false,
            ..Default::default()
        });
        let leiden_result = leiden.run(&graph).unwrap();

        let louvain = Leiden::new(LeidenConfig {
            seed: Some(42),
            quality: QualityType::CPM,
            resolution: 0.5,
            skip_refinement: true,
            ..Default::default()
        });
        let louvain_result = louvain.run(&graph).unwrap();

        assert!(
            louvain_result.quality <= leiden_result.quality + 1e-12,
            "Louvain quality {:.10} should be <= Leiden quality {:.10} with CPM",
            louvain_result.quality,
            leiden_result.quality
        );
        assert!(leiden_result.partition.num_communities() >= 1);
        assert!(louvain_result.partition.num_communities() >= 1);
    }

    #[test]
    fn test_louvain_builder_method() {
        let config = LeidenConfig::builder()
            .skip_refinement(true)
            .seed(42)
            .build();
        assert!(config.skip_refinement);

        let default_config = LeidenConfig::builder().build();
        assert!(!default_config.skip_refinement);
    }

    #[test]
    fn test_default_skip_refinement_false() {
        let config = LeidenConfig::default();
        assert!(!config.skip_refinement, "default should be false (Leiden mode)");

        let explicit = LeidenConfig {
            skip_refinement: false,
            ..Default::default()
        };
        let graph = make_two_cliques();
        let default_result = Leiden::new(config).run(&graph).unwrap();
        let explicit_result = Leiden::new(explicit).run(&graph).unwrap();

        assert_eq!(
            default_result.partition.as_slice(),
            explicit_result.partition.as_slice(),
            "default and explicit skip_refinement=false should match"
        );
        assert!((default_result.quality - explicit_result.quality).abs() < 1e-10);
    }

    // ── Convergence control tests ─────────────────────────────────

    #[test]
    fn test_min_iterations_does_not_break_convergence() {
        // min_iterations guards only the epsilon convergence check,
        // not the !changed (no nodes moved) check. Verify the algorithm
        // still converges correctly with high min_iterations.
        let graph = make_two_cliques();

        for &min_iter in &[1, 5, 10, 50] {
            let config = LeidenConfig {
                min_iterations: min_iter,
                seed: Some(42),
                ..Default::default()
            };
            let result = Leiden::new(config).run(&graph).unwrap();
            assert_eq!(
                result.partition.num_communities(),
                2,
                "min_iterations={min_iter} should not break convergence"
            );
        }
    }

    #[test]
    fn test_min_iterations_with_quality_tracking() {
        // Verify that min_iterations and quality_history work together
        let graph = make_two_cliques();
        let config = LeidenConfig {
            min_iterations: 5,
            track_quality_history: true,
            seed: Some(42),
            ..Default::default()
        };
        let result = Leiden::new(config).run(&graph).unwrap();

        // Correct partition
        assert_eq!(result.partition.num_communities(), 2);
        // quality_history captures iterations where nodes moved
        assert!(
            !result.quality_history.is_empty(),
            "quality_history should have entries"
        );
        // Same partition as default config (deterministic)
        let default_result = Leiden::new(LeidenConfig {
            seed: Some(42),
            ..Default::default()
        })
        .run(&graph)
        .unwrap();
        assert_eq!(result.partition.as_slice(), default_result.partition.as_slice());
    }

    #[test]
    fn test_min_iterations_one_converges_normally() {
        let graph = make_two_cliques();
        let config = LeidenConfig {
            min_iterations: 1,
            track_quality_history: true,
            seed: Some(42),
            ..Default::default()
        };
        let result = Leiden::new(config).run(&graph).unwrap();
        // Should converge to 2 communities (same as default)
        assert_eq!(result.partition.num_communities(), 2);
        assert!(!result.quality_history.is_empty());
    }

    #[test]
    fn test_quality_history_tracked_when_enabled() {
        let graph = make_two_cliques();
        let config = LeidenConfig {
            track_quality_history: true,
            seed: Some(42),
            ..Default::default()
        };
        let result = Leiden::new(config).run(&graph).unwrap();
        assert!(
            !result.quality_history.is_empty(),
            "quality_history should be non-empty when enabled"
        );
    }

    #[test]
    fn test_quality_history_empty_by_default() {
        let graph = make_two_cliques();
        let result = Leiden::new(LeidenConfig::default()).run(&graph).unwrap();
        assert!(
            result.quality_history.is_empty(),
            "quality_history should be empty by default"
        );
    }

    #[test]
    fn test_quality_history_monotonic() {
        let graph = make_two_cliques();
        let config = LeidenConfig {
            track_quality_history: true,
            seed: Some(42),
            ..Default::default()
        };
        let result = Leiden::new(config).run(&graph).unwrap();
        for window in result.quality_history.windows(2) {
            assert!(
                window[1] >= window[0] - 1e-10,
                "quality decreased: {:.15} -> {:.15}",
                window[0],
                window[1]
            );
        }
    }

    #[test]
    fn test_builder_min_iterations() {
        let config = LeidenConfig::builder().min_iterations(10).build();
        assert_eq!(config.min_iterations, 10);

        let default_config = LeidenConfig::builder().build();
        assert_eq!(default_config.min_iterations, 1);
    }

    #[test]
    fn test_builder_track_quality_history() {
        let config = LeidenConfig::builder().track_quality_history(true).build();
        assert!(config.track_quality_history);

        let default_config = LeidenConfig::builder().build();
        assert!(!default_config.track_quality_history);
    }
}