scirs2-graph 0.4.1

Graph processing module for SciRS2 (scirs2-graph)
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
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
//! Graph generation algorithms
//!
//! This module provides functions for generating various types of graphs:
//! - Random graphs (Erdős–Rényi, Barabási–Albert, etc.)
//! - Regular graphs (complete, star, path, cycle)
//! - Lattice graphs
//! - Small-world networks

pub mod advanced;
pub mod random_graphs;
pub mod temporal;

pub use advanced::{forest_fire, lfr_benchmark, LfrParams};
pub use temporal::{temporal_barabasi_albert, temporal_random_walk, TemporalWalk};

pub use random_graphs::{
    barabasi_albert, chung_lu, erdos_renyi_g_nm, erdos_renyi_g_np, hyperbolic_random_graph,
    kronecker_graph, random_regular, watts_strogatz,
};

use scirs2_core::random::prelude::*;
use std::collections::HashSet;

use crate::base::{DiGraph, Graph};
use crate::error::{GraphError, Result};
use scirs2_core::random::seq::SliceRandom;

// Import IndexedRandom for .choose() on slices (rand 0.9+)
use scirs2_core::rand_prelude::IndexedRandom;

/// Create a new empty undirected graph
#[allow(dead_code)]
pub fn create_graph<N: crate::base::Node + std::fmt::Debug, E: crate::base::EdgeWeight>(
) -> Graph<N, E> {
    Graph::new()
}

/// Create a new empty directed graph
#[allow(dead_code)]
pub fn create_digraph<N: crate::base::Node + std::fmt::Debug, E: crate::base::EdgeWeight>(
) -> DiGraph<N, E> {
    DiGraph::new()
}

/// Generates an Erdős–Rényi random graph
///
/// # Arguments
/// * `n` - Number of nodes
/// * `p` - Probability of edge creation between any two nodes
/// * `rng` - Random number generator
///
/// # Returns
/// * `Result<Graph<usize, f64>>` - The generated graph with node IDs 0..n-1
#[allow(dead_code)]
pub fn erdos_renyi_graph<R: Rng>(n: usize, p: f64, rng: &mut R) -> Result<Graph<usize, f64>> {
    if !(0.0..=1.0).contains(&p) {
        return Err(GraphError::InvalidGraph(
            "Probability must be between 0 and 1".to_string(),
        ));
    }

    let mut graph = Graph::new();

    // Add all nodes
    for i in 0..n {
        graph.add_node(i);
    }

    // Add edges with probability p
    for i in 0..n {
        for j in i + 1..n {
            if rng.random::<f64>() < p {
                graph.add_edge(i, j, 1.0)?;
            }
        }
    }

    Ok(graph)
}

/// Generates a Barabási–Albert preferential attachment graph
///
/// # Arguments
/// * `n` - Total number of nodes
/// * `m` - Number of edges to attach from a new node to existing nodes
/// * `rng` - Random number generator
///
/// # Returns
/// * `Result<Graph<usize, f64>>` - The generated graph with node IDs 0..n-1
#[allow(dead_code)]
pub fn barabasi_albert_graph<R: Rng>(n: usize, m: usize, rng: &mut R) -> Result<Graph<usize, f64>> {
    if m >= n {
        return Err(GraphError::InvalidGraph(
            "m must be less than n".to_string(),
        ));
    }
    if m == 0 {
        return Err(GraphError::InvalidGraph("m must be positive".to_string()));
    }

    let mut graph = Graph::new();

    // Start with a complete graph of m+1 nodes
    for i in 0..=m {
        graph.add_node(i);
    }

    for i in 0..=m {
        for j in i + 1..=m {
            graph.add_edge(i, j, 1.0)?;
        }
    }

    // Keep track of node degrees for preferential attachment
    let mut degrees = vec![m; m + 1];
    let mut total_degree = m * (m + 1);

    // Add remaining nodes
    for new_node in (m + 1)..n {
        graph.add_node(new_node);

        let mut targets = HashSet::new();

        // Select m nodes to connect to based on preferential attachment
        while targets.len() < m {
            let mut cumulative_prob = 0.0;
            let random_value = rng.random::<f64>() * total_degree as f64;

            for (node_id, &degree) in degrees.iter().enumerate() {
                cumulative_prob += degree as f64;
                if random_value <= cumulative_prob && !targets.contains(&node_id) {
                    targets.insert(node_id);
                    break;
                }
            }
        }

        // Add edges to selected targets
        for &target in &targets {
            graph.add_edge(new_node, target, 1.0)?;
            degrees[target] += 1;
            total_degree += 2; // Each edge adds 2 to total degree
        }

        degrees.push(m); // New node has degree m
    }

    Ok(graph)
}

/// Generates a complete graph (clique)
///
/// # Arguments
/// * `n` - Number of nodes
///
/// # Returns
/// * `Result<Graph<usize, f64>>` - A complete graph with n nodes
#[allow(dead_code)]
pub fn complete_graph(n: usize) -> Result<Graph<usize, f64>> {
    let mut graph = Graph::new();

    // Add all nodes
    for i in 0..n {
        graph.add_node(i);
    }

    // Add all possible edges
    for i in 0..n {
        for j in i + 1..n {
            graph.add_edge(i, j, 1.0)?;
        }
    }

    Ok(graph)
}

/// Generates a star graph with one central node connected to all others
///
/// # Arguments
/// * `n` - Total number of nodes (must be >= 1)
///
/// # Returns
/// * `Result<Graph<usize, f64>>` - A star graph with node 0 as the center
#[allow(dead_code)]
pub fn star_graph(n: usize) -> Result<Graph<usize, f64>> {
    if n == 0 {
        return Err(GraphError::InvalidGraph(
            "Star graph must have at least 1 node".to_string(),
        ));
    }

    let mut graph = Graph::new();

    // Add all nodes
    for i in 0..n {
        graph.add_node(i);
    }

    // Connect center (node 0) to all other nodes
    for i in 1..n {
        graph.add_edge(0, i, 1.0)?;
    }

    Ok(graph)
}

/// Generates a path graph (nodes connected in a line)
///
/// # Arguments
/// * `n` - Number of nodes
///
/// # Returns
/// * `Result<Graph<usize, f64>>` - A path graph with nodes 0, 1, ..., n-1
#[allow(dead_code)]
pub fn path_graph(n: usize) -> Result<Graph<usize, f64>> {
    let mut graph = Graph::new();

    // Add all nodes
    for i in 0..n {
        graph.add_node(i);
    }

    // Connect consecutive nodes
    for i in 0..n.saturating_sub(1) {
        graph.add_edge(i, i + 1, 1.0)?;
    }

    Ok(graph)
}

/// Generates a random tree with n nodes
///
/// Uses a random process to connect nodes while maintaining the tree property
/// (connected and acyclic). Each tree has exactly n-1 edges.
///
/// # Arguments
/// * `n` - Number of nodes
/// * `rng` - Random number generator
///
/// # Returns
/// * `Result<Graph<usize, f64>>` - A random tree with nodes 0, 1, ..., n-1
#[allow(dead_code)]
pub fn tree_graph<R: Rng>(n: usize, rng: &mut R) -> Result<Graph<usize, f64>> {
    if n == 0 {
        return Ok(Graph::new());
    }
    if n == 1 {
        let mut graph = Graph::new();
        graph.add_node(0);
        return Ok(graph);
    }

    let mut graph = Graph::new();

    // Add all nodes
    for i in 0..n {
        graph.add_node(i);
    }

    // Use Prim's algorithm variation to build a random tree
    let mut in_tree = vec![false; n];
    let mut tree_nodes = Vec::new();

    // Start with a random node
    let start = rng.random_range(0..n);
    in_tree[start] = true;
    tree_nodes.push(start);

    // Add n-1 edges to complete the tree
    for _ in 1..n {
        // Pick a random node already in the tree
        let tree_node = tree_nodes[rng.random_range(0..tree_nodes.len())];

        // Pick a random node not yet in the tree
        let candidates: Vec<usize> = (0..n).filter(|&i| !in_tree[i]).collect();
        if candidates.is_empty() {
            break;
        }

        let new_node = candidates[rng.random_range(0..candidates.len())];

        // Add edge and mark node as in tree
        graph.add_edge(tree_node, new_node, 1.0)?;
        in_tree[new_node] = true;
        tree_nodes.push(new_node);
    }

    Ok(graph)
}

/// Generates a random spanning tree from an existing graph
///
/// Uses Kruskal's algorithm with randomized edge selection to produce
/// a random spanning tree of the input graph.
///
/// # Arguments
/// * `graph` - The input graph to extract a spanning tree from
/// * `rng` - Random number generator
///
/// # Returns
/// * `Result<Graph<N, E>>` - A spanning tree of the input graph
#[allow(dead_code)]
pub fn random_spanning_tree<N, E, Ix, R>(
    graph: &Graph<N, E, Ix>,
    rng: &mut R,
) -> Result<Graph<N, E, Ix>>
where
    N: crate::base::Node + std::fmt::Debug,
    E: crate::base::EdgeWeight + Clone,
    Ix: petgraph::graph::IndexType,
    R: Rng,
{
    let nodes: Vec<N> = graph.nodes().into_iter().cloned().collect();
    if nodes.is_empty() {
        return Ok(Graph::new());
    }
    if nodes.len() == 1 {
        let mut tree = Graph::new();
        tree.add_node(nodes[0].clone());
        return Ok(tree);
    }

    // Get all edges and shuffle them randomly
    let mut edges: Vec<_> = graph.edges().into_iter().collect();
    edges.shuffle(rng);

    let mut tree = Graph::new();

    // Add all nodes to the tree
    for node in &nodes {
        tree.add_node(node.clone());
    }

    // Use Union-Find to track components
    let mut parent: std::collections::HashMap<N, N> =
        nodes.iter().map(|n| (n.clone(), n.clone())).collect();
    let mut rank: std::collections::HashMap<N, usize> =
        nodes.iter().map(|n| (n.clone(), 0)).collect();

    fn find<N: crate::base::Node>(parent: &mut std::collections::HashMap<N, N>, node: &N) -> N {
        if parent[node] != *node {
            let root = find(parent, &parent[node].clone());
            parent.insert(node.clone(), root.clone());
        }
        parent[node].clone()
    }

    fn union<N: crate::base::Node>(
        parent: &mut std::collections::HashMap<N, N>,
        rank: &mut std::collections::HashMap<N, usize>,
        x: &N,
        y: &N,
    ) -> bool {
        let root_x = find(parent, x);
        let root_y = find(parent, y);

        if root_x == root_y {
            return false; // Already in same component
        }

        // Union by rank
        match rank[&root_x].cmp(&rank[&root_y]) {
            std::cmp::Ordering::Less => {
                parent.insert(root_x, root_y);
            }
            std::cmp::Ordering::Greater => {
                parent.insert(root_y, root_x);
            }
            std::cmp::Ordering::Equal => {
                parent.insert(root_y, root_x.clone());
                *rank.get_mut(&root_x).expect("Operation failed") += 1;
            }
        }
        true
    }

    let mut edges_added = 0;

    // Add edges without creating cycles until we have n-1 edges
    for edge in edges {
        if union(&mut parent, &mut rank, &edge.source, &edge.target) {
            tree.add_edge(edge.source, edge.target, edge.weight)?;
            edges_added += 1;
            if edges_added == nodes.len() - 1 {
                break;
            }
        }
    }

    // Check if we have a spanning tree (connected graph)
    if edges_added != nodes.len() - 1 {
        return Err(GraphError::InvalidGraph(
            "Input graph is not connected - cannot create spanning tree".to_string(),
        ));
    }

    Ok(tree)
}

/// Generates a random forest (collection of trees)
///
/// Creates a forest by generating multiple random trees and combining them
/// into a single graph. The trees are disjoint (no edges between different trees).
///
/// # Arguments
/// * `tree_sizes` - Vector specifying the size of each tree in the forest
/// * `rng` - Random number generator
///
/// # Returns
/// * `Result<Graph<usize, f64>>` - A forest containing the specified trees
#[allow(dead_code)]
pub fn forest_graph<R: Rng>(
    _tree_sizes: &[usize],
    sizes: &[usize],
    rng: &mut R,
) -> Result<Graph<usize, f64>> {
    let mut forest = Graph::new();
    let mut node_offset = 0;

    for &tree_size in _tree_sizes {
        if tree_size == 0 {
            continue;
        }

        // Generate a tree with nodes starting from node_offset
        let tree = tree_graph(tree_size, rng)?;

        // Add nodes to forest with offset
        for i in 0..tree_size {
            forest.add_node(node_offset + i);
        }

        // Add edges with offset
        for edge in tree.edges() {
            forest.add_edge(
                node_offset + edge.source,
                node_offset + edge.target,
                edge.weight,
            )?;
        }

        node_offset += tree_size;
    }

    Ok(forest)
}

/// Generates a cycle graph (circular arrangement of nodes)
///
/// # Arguments
/// * `n` - Number of nodes (must be >= 3 for a meaningful cycle)
///
/// # Returns
/// * `Result<Graph<usize, f64>>` - A cycle graph with nodes 0, 1, ..., n-1
#[allow(dead_code)]
pub fn cycle_graph(n: usize) -> Result<Graph<usize, f64>> {
    if n < 3 {
        return Err(GraphError::InvalidGraph(
            "Cycle graph must have at least 3 nodes".to_string(),
        ));
    }

    let mut graph = Graph::new();

    // Add all nodes
    for i in 0..n {
        graph.add_node(i);
    }

    // Connect consecutive nodes
    for i in 0..n {
        graph.add_edge(i, (i + 1) % n, 1.0)?;
    }

    Ok(graph)
}

/// Generates a 2D grid/lattice graph
///
/// # Arguments
/// * `rows` - Number of rows
/// * `cols` - Number of columns
///
/// # Returns
/// * `Result<Graph<usize, f64>>` - A grid graph where node ID = row * cols + col
#[allow(dead_code)]
pub fn grid_2d_graph(rows: usize, cols: usize) -> Result<Graph<usize, f64>> {
    if rows == 0 || cols == 0 {
        return Err(GraphError::InvalidGraph(
            "Grid dimensions must be positive".to_string(),
        ));
    }

    let mut graph = Graph::new();

    // Add all nodes
    for i in 0..(rows * cols) {
        graph.add_node(i);
    }

    // Add edges to adjacent nodes (4-connectivity)
    for row in 0..rows {
        for col in 0..cols {
            let node_id = row * cols + col;

            // Connect to right neighbor
            if col + 1 < cols {
                let right_neighbor = row * cols + (col + 1);
                graph.add_edge(node_id, right_neighbor, 1.0)?;
            }

            // Connect to bottom neighbor
            if row + 1 < rows {
                let bottom_neighbor = (row + 1) * cols + col;
                graph.add_edge(node_id, bottom_neighbor, 1.0)?;
            }
        }
    }

    Ok(graph)
}

/// Generates a 3D grid/lattice graph
///
/// # Arguments
/// * `x_dim` - Size in x dimension
/// * `y_dim` - Size in y dimension  
/// * `z_dim` - Size in z dimension
///
/// # Returns
/// * `Result<Graph<usize, f64>>` - A 3D grid graph where node ID = z*x_dim*y_dim + y*x_dim + x
#[allow(dead_code)]
pub fn grid_3d_graph(x_dim: usize, y_dim: usize, z_dim: usize) -> Result<Graph<usize, f64>> {
    if x_dim == 0 || y_dim == 0 || z_dim == 0 {
        return Err(GraphError::InvalidGraph(
            "Grid dimensions must be positive".to_string(),
        ));
    }

    let mut graph = Graph::new();

    // Add all nodes
    for i in 0..(x_dim * y_dim * z_dim) {
        graph.add_node(i);
    }

    // Connect neighbors in 3D grid
    for z in 0..z_dim {
        for y in 0..y_dim {
            for x in 0..x_dim {
                let node_id = z * x_dim * y_dim + y * x_dim + x;

                // Connect to right neighbor
                if x + 1 < x_dim {
                    let right_neighbor = z * x_dim * y_dim + y * x_dim + (x + 1);
                    graph.add_edge(node_id, right_neighbor, 1.0)?;
                }

                // Connect to front neighbor
                if y + 1 < y_dim {
                    let front_neighbor = z * x_dim * y_dim + (y + 1) * x_dim + x;
                    graph.add_edge(node_id, front_neighbor, 1.0)?;
                }

                // Connect to top neighbor
                if z + 1 < z_dim {
                    let top_neighbor = (z + 1) * x_dim * y_dim + y * x_dim + x;
                    graph.add_edge(node_id, top_neighbor, 1.0)?;
                }
            }
        }
    }

    Ok(graph)
}

/// Generates a triangular lattice graph
///
/// # Arguments
/// * `rows` - Number of rows
/// * `cols` - Number of columns
///
/// # Returns
/// * `Result<Graph<usize, f64>>` - A triangular lattice where each node has up to 6 neighbors
#[allow(dead_code)]
pub fn triangular_lattice_graph(rows: usize, cols: usize) -> Result<Graph<usize, f64>> {
    if rows == 0 || cols == 0 {
        return Err(GraphError::InvalidGraph(
            "Lattice dimensions must be positive".to_string(),
        ));
    }

    let mut graph = Graph::new();

    // Add all nodes
    for i in 0..(rows * cols) {
        graph.add_node(i);
    }

    for row in 0..rows {
        for col in 0..cols {
            let node_id = row * cols + col;

            // Standard grid connections (4-connected)
            // Right neighbor
            if col + 1 < cols {
                let right_neighbor = row * cols + (col + 1);
                graph.add_edge(node_id, right_neighbor, 1.0)?;
            }

            // Bottom neighbor
            if row + 1 < rows {
                let bottom_neighbor = (row + 1) * cols + col;
                graph.add_edge(node_id, bottom_neighbor, 1.0)?;
            }

            // Diagonal connections for triangular lattice
            // Bottom-right diagonal
            if row + 1 < rows && col + 1 < cols {
                let diag_neighbor = (row + 1) * cols + (col + 1);
                graph.add_edge(node_id, diag_neighbor, 1.0)?;
            }

            // Bottom-left diagonal (for even rows)
            if row + 1 < rows && col > 0 && row % 2 == 0 {
                let diag_neighbor = (row + 1) * cols + (col - 1);
                graph.add_edge(node_id, diag_neighbor, 1.0)?;
            }
        }
    }

    Ok(graph)
}

/// Generates a hexagonal lattice graph (honeycomb structure)
///
/// # Arguments
/// * `rows` - Number of rows
/// * `cols` - Number of columns
///
/// # Returns
/// * `Result<Graph<usize, f64>>` - A hexagonal lattice where each node has exactly 3 neighbors
#[allow(dead_code)]
pub fn hexagonal_lattice_graph(rows: usize, cols: usize) -> Result<Graph<usize, f64>> {
    if rows == 0 || cols == 0 {
        return Err(GraphError::InvalidGraph(
            "Lattice dimensions must be positive".to_string(),
        ));
    }

    let mut graph = Graph::new();

    // Add all nodes
    for i in 0..(rows * cols) {
        graph.add_node(i);
    }

    for row in 0..rows {
        for col in 0..cols {
            let node_id = row * cols + col;

            // Hexagonal lattice connections (3 neighbors per node in honeycomb pattern)
            // This creates a simplified hexagonal structure

            // Right neighbor (horizontal)
            if col + 1 < cols {
                let right_neighbor = row * cols + (col + 1);
                graph.add_edge(node_id, right_neighbor, 1.0)?;
            }

            // Connect in honeycomb pattern
            if row % 2 == 0 {
                // Even _rows: connect down-left and down-right
                if row + 1 < rows {
                    if col > 0 {
                        let down_left = (row + 1) * cols + (col - 1);
                        graph.add_edge(node_id, down_left, 1.0)?;
                    }
                    if col < cols {
                        let down_right = (row + 1) * cols + col;
                        graph.add_edge(node_id, down_right, 1.0)?;
                    }
                }
            } else {
                // Odd _rows: connect down-left and down-right with offset
                if row + 1 < rows {
                    let down_left = (row + 1) * cols + col;
                    graph.add_edge(node_id, down_left, 1.0)?;

                    if col + 1 < cols {
                        let down_right = (row + 1) * cols + (col + 1);
                        graph.add_edge(node_id, down_right, 1.0)?;
                    }
                }
            }
        }
    }

    Ok(graph)
}

/// Generates a Watts-Strogatz small-world graph
///
/// # Arguments
/// * `n` - Number of nodes
/// * `k` - Each node is connected to k nearest neighbors in ring topology (must be even)
/// * `p` - Probability of rewiring each edge
/// * `rng` - Random number generator
///
/// # Returns
/// * `Result<Graph<usize, f64>>` - A small-world graph
#[allow(dead_code)]
pub fn watts_strogatz_graph<R: Rng>(
    n: usize,
    k: usize,
    p: f64,
    rng: &mut R,
) -> Result<Graph<usize, f64>> {
    if k >= n || !k.is_multiple_of(2) {
        return Err(GraphError::InvalidGraph(
            "k must be even and less than n".to_string(),
        ));
    }
    if !(0.0..=1.0).contains(&p) {
        return Err(GraphError::InvalidGraph(
            "Probability must be between 0 and 1".to_string(),
        ));
    }

    let mut graph = Graph::new();

    // Add all nodes
    for i in 0..n {
        graph.add_node(i);
    }

    // Create regular ring lattice
    for i in 0..n {
        for j in 1..=(k / 2) {
            let neighbor = (i + j) % n;
            graph.add_edge(i, neighbor, 1.0)?;
        }
    }

    // Rewire edges with probability p
    let edges_to_process: Vec<_> = graph.edges().into_iter().collect();

    for edge in edges_to_process {
        if rng.random::<f64>() < p {
            // Remove the original edge (we'll recreate the graph to do this)
            let mut new_graph = Graph::new();

            // Add all nodes
            for i in 0..n {
                new_graph.add_node(i);
            }

            // Add all edges except the one we're rewiring
            for existing_edge in graph.edges() {
                if (existing_edge.source != edge.source || existing_edge.target != edge.target)
                    && (existing_edge.source != edge.target || existing_edge.target != edge.source)
                {
                    new_graph.add_edge(
                        existing_edge.source,
                        existing_edge.target,
                        existing_edge.weight,
                    )?;
                }
            }

            // Add rewired edge to a random node
            let mut new_target = rng.random_range(0..n);
            while new_target == edge.source || new_graph.has_node(&new_target) {
                new_target = rng.random_range(0..n);
            }

            new_graph.add_edge(edge.source, new_target, 1.0)?;
            graph = new_graph;
        }
    }

    Ok(graph)
}

/// Generates a graph using the Stochastic Block Model (SBM)
///
/// The SBM generates a graph where nodes are divided into communities (blocks)
/// and edge probabilities depend on which communities the nodes belong to.
///
/// # Arguments
/// * `block_sizes` - Vector specifying the size of each block/community
/// * `block_matrix` - Probability matrix where entry (i,j) is the probability
///   of an edge between nodes in block i and block j
/// * `rng` - Random number generator
///
/// # Returns
/// * `Result<Graph<usize, f64>>` - The generated graph with node IDs 0..n-1
///   where nodes 0..block_sizes\[0\]-1 are in block 0, etc.
#[allow(dead_code)]
pub fn stochastic_block_model<R: Rng>(
    block_sizes: &[usize],
    block_matrix: &[Vec<f64>],
    rng: &mut R,
) -> Result<Graph<usize, f64>> {
    if block_sizes.is_empty() {
        return Err(GraphError::InvalidGraph(
            "At least one block must be specified".to_string(),
        ));
    }

    if block_matrix.len() != block_sizes.len() {
        return Err(GraphError::InvalidGraph(
            "Block _matrix dimensions must match number of blocks".to_string(),
        ));
    }

    for row in block_matrix {
        if row.len() != block_sizes.len() {
            return Err(GraphError::InvalidGraph(
                "Block _matrix must be square".to_string(),
            ));
        }
        for &prob in row {
            if !(0.0..=1.0).contains(&prob) {
                return Err(GraphError::InvalidGraph(
                    "All probabilities must be between 0 and 1".to_string(),
                ));
            }
        }
    }

    let total_nodes: usize = block_sizes.iter().sum();
    let mut graph = Graph::new();

    // Add all nodes
    for i in 0..total_nodes {
        graph.add_node(i);
    }

    // Create mapping from node to block
    let mut node_to_block = vec![0; total_nodes];
    let mut current_node = 0;
    for (block_id, &block_size) in block_sizes.iter().enumerate() {
        for _ in 0..block_size {
            node_to_block[current_node] = block_id;
            current_node += 1;
        }
    }

    // Generate edges based on block probabilities
    for i in 0..total_nodes {
        for j in (i + 1)..total_nodes {
            let block_i = node_to_block[i];
            let block_j = node_to_block[j];
            let prob = block_matrix[block_i][block_j];

            if rng.random::<f64>() < prob {
                graph.add_edge(i, j, 1.0)?;
            }
        }
    }

    Ok(graph)
}

/// Generates a simple stochastic block model with two communities
///
/// This is a convenience function for creating a two-community SBM with
/// high intra-community probability and low inter-community probability.
///
/// # Arguments
/// * `n1` - Size of first community
/// * `n2` - Size of second community
/// * `p_in` - Probability of edges within communities
/// * `p_out` - Probability of edges between communities
/// * `rng` - Random number generator
///
/// # Returns
/// * `Result<Graph<usize, f64>>` - The generated graph
#[allow(dead_code)]
pub fn two_community_sbm<R: Rng>(
    n1: usize,
    n2: usize,
    p_in: f64,
    p_out: f64,
    rng: &mut R,
) -> Result<Graph<usize, f64>> {
    let block_sizes = vec![n1, n2];
    let block_matrix = vec![vec![p_in, p_out], vec![p_out, p_in]];

    stochastic_block_model(&block_sizes, &block_matrix, rng)
}

/// Generates a planted partition model (special case of SBM)
///
/// In this model, there are k communities of equal size, with high
/// intra-community probability and low inter-community probability.
///
/// # Arguments
/// * `n` - Total number of nodes (must be divisible by k)
/// * `k` - Number of communities
/// * `p_in` - Probability of edges within communities
/// * `p_out` - Probability of edges between communities
/// * `rng` - Random number generator
///
/// # Returns
/// * `Result<Graph<usize, f64>>` - The generated graph
#[allow(dead_code)]
pub fn planted_partition_model<R: Rng>(
    n: usize,
    k: usize,
    p_in: f64,
    p_out: f64,
    rng: &mut R,
) -> Result<Graph<usize, f64>> {
    if !n.is_multiple_of(k) {
        return Err(GraphError::InvalidGraph(
            "Number of nodes must be divisible by number of communities".to_string(),
        ));
    }

    let community_size = n / k;
    let block_sizes = vec![community_size; k];

    // Create block matrix
    let mut block_matrix = vec![vec![p_out; k]; k];
    for (i, row) in block_matrix.iter_mut().enumerate().take(k) {
        row[i] = p_in;
    }

    stochastic_block_model(&block_sizes, &block_matrix, rng)
}

/// Generates a random graph using the Configuration Model
///
/// The Configuration Model generates a random graph where each node has a specified degree.
/// The degree sequence is the sequence of degrees for all nodes. The algorithm creates
/// "stubs" (half-edges) for each node according to its degree, then randomly connects
/// the stubs to form edges.
///
/// # Arguments
/// * `degree_sequence` - Vector specifying the degree of each node
/// * `rng` - Random number generator
///
/// # Returns
/// * `Result<Graph<usize, f64>>` - The generated graph with node IDs 0..n-1
///
/// # Notes
/// * The sum of all degrees must be even (since each edge contributes 2 to the total degree)
/// * Self-loops and multiple edges between the same pair of nodes are possible
/// * If you want a simple graph (no self-loops or multiple edges), you may need to
///   regenerate or post-process the result
#[allow(dead_code)]
pub fn configuration_model<R: Rng>(
    degree_sequence: &[usize],
    rng: &mut R,
) -> Result<Graph<usize, f64>> {
    if degree_sequence.is_empty() {
        return Ok(Graph::new());
    }

    // Check that sum of degrees is even
    let total_degree: usize = degree_sequence.iter().sum();
    if !total_degree.is_multiple_of(2) {
        return Err(GraphError::InvalidGraph(
            "Sum of degrees must be even".to_string(),
        ));
    }

    let n = degree_sequence.len();
    let mut graph = Graph::new();

    // Add all nodes
    for i in 0..n {
        graph.add_node(i);
    }

    // Create stubs (half-edges) for each node
    let mut stubs = Vec::new();
    for (node_id, &degree) in degree_sequence.iter().enumerate() {
        for _ in 0..degree {
            stubs.push(node_id);
        }
    }

    // Randomly connect stubs to form edges
    while stubs.len() >= 2 {
        // Pick two random stubs
        let idx1 = rng.random_range(0..stubs.len());
        let stub1 = stubs.remove(idx1);

        let idx2 = rng.random_range(0..stubs.len());
        let stub2 = stubs.remove(idx2);

        // Connect the nodes (allow self-loops and multiple edges)
        graph.add_edge(stub1, stub2, 1.0)?;
    }

    Ok(graph)
}

/// Generates a simple random graph using the Configuration Model
///
/// This variant attempts to generate a simple graph (no self-loops or multiple edges)
/// by rejecting problematic edge attempts. If too many rejections occur, it returns
/// an error indicating that the degree sequence may not be realizable as a simple graph.
///
/// # Arguments
/// * `degree_sequence` - Vector specifying the degree of each node
/// * `rng` - Random number generator
/// * `max_attempts` - Maximum number of attempts before giving up
///
/// # Returns
/// * `Result<Graph<usize, f64>>` - The generated simple graph
#[allow(dead_code)]
pub fn simple_configuration_model<R: Rng>(
    degree_sequence: &[usize],
    rng: &mut R,
    max_attempts: usize,
) -> Result<Graph<usize, f64>> {
    if degree_sequence.is_empty() {
        return Ok(Graph::new());
    }

    // Check that sum of degrees is even
    let total_degree: usize = degree_sequence.iter().sum();
    if !total_degree.is_multiple_of(2) {
        return Err(GraphError::InvalidGraph(
            "Sum of degrees must be even".to_string(),
        ));
    }

    let n = degree_sequence.len();

    // Check for degree _sequence constraints for simple graphs
    for &degree in degree_sequence {
        if degree >= n {
            return Err(GraphError::InvalidGraph(
                "Node degree cannot exceed n-1 in a simple graph".to_string(),
            ));
        }
    }

    let mut _attempts = 0;

    while _attempts < max_attempts {
        let mut graph = Graph::new();

        // Add all nodes
        for i in 0..n {
            graph.add_node(i);
        }

        // Create stubs (half-edges) for each node
        let mut stubs = Vec::new();
        for (node_id, &degree) in degree_sequence.iter().enumerate() {
            for _ in 0..degree {
                stubs.push(node_id);
            }
        }

        let mut success = true;

        // Randomly connect stubs to form edges
        while stubs.len() >= 2 && success {
            // Pick two random stubs
            let idx1 = rng.random_range(0..stubs.len());
            let stub1 = stubs[idx1];

            let idx2 = rng.random_range(0..stubs.len());
            let stub2 = stubs[idx2];

            // Check for self-loop or existing edge
            if stub1 == stub2 || graph.has_edge(&stub1, &stub2) {
                // Try a few more times before giving up on this attempt
                let mut retries = 0;
                let mut found_valid = false;

                while retries < 50 && !found_valid {
                    let new_idx2 = rng.random_range(0..stubs.len());
                    let new_stub2 = stubs[new_idx2];

                    if stub1 != new_stub2 && !graph.has_edge(&stub1, &new_stub2) {
                        // Remove stubs and add edge
                        // Remove the larger index first to avoid index shifting issues
                        if idx1 > new_idx2 {
                            stubs.remove(idx1);
                            stubs.remove(new_idx2);
                        } else {
                            stubs.remove(new_idx2);
                            stubs.remove(idx1);
                        }
                        graph.add_edge(stub1, new_stub2, 1.0)?;
                        found_valid = true;
                    }
                    retries += 1;
                }

                if !found_valid {
                    success = false;
                }
            } else {
                // Remove stubs and add edge
                // Remove the larger index first to avoid index shifting issues
                if idx1 > idx2 {
                    stubs.remove(idx1);
                    stubs.remove(idx2);
                } else {
                    stubs.remove(idx2);
                    stubs.remove(idx1);
                }
                graph.add_edge(stub1, stub2, 1.0)?;
            }
        }

        if success && stubs.is_empty() {
            return Ok(graph);
        }

        _attempts += 1;
    }

    Err(GraphError::InvalidGraph(
        "Could not generate simple graph with given degree _sequence after maximum _attempts"
            .to_string(),
    ))
}

/// Generates a random geometric graph
///
/// In a random geometric graph, `n` points are placed uniformly at random
/// in the unit square [0,1)^2. An edge is created between two nodes whenever
/// their Euclidean distance is at most `radius`.
///
/// # Arguments
/// * `n` - Number of nodes
/// * `radius` - Connection radius (typical range: 0.05 to 0.5)
/// * `rng` - Random number generator
///
/// # Returns
/// * `Result<Graph<usize, f64>>` - The generated graph where edge weights
///   are the Euclidean distances between connected nodes
///
/// # Applications
/// Models wireless sensor networks, ad-hoc networks, and spatial networks
/// where connectivity depends on physical proximity.
#[allow(dead_code)]
pub fn random_geometric_graph<R: Rng>(
    n: usize,
    radius: f64,
    rng: &mut R,
) -> Result<Graph<usize, f64>> {
    if radius < 0.0 {
        return Err(GraphError::InvalidGraph(
            "Radius must be non-negative".to_string(),
        ));
    }

    let mut graph = Graph::new();

    // Add all nodes
    for i in 0..n {
        graph.add_node(i);
    }

    if n == 0 {
        return Ok(graph);
    }

    // Generate random positions in [0,1)^2
    let positions: Vec<(f64, f64)> = (0..n)
        .map(|_| (rng.random::<f64>(), rng.random::<f64>()))
        .collect();

    let radius_sq = radius * radius;

    // Connect nodes within the radius
    for i in 0..n {
        for j in (i + 1)..n {
            let dx = positions[i].0 - positions[j].0;
            let dy = positions[i].1 - positions[j].1;
            let dist_sq = dx * dx + dy * dy;

            if dist_sq <= radius_sq {
                let dist = dist_sq.sqrt();
                graph.add_edge(i, j, dist)?;
            }
        }
    }

    Ok(graph)
}

/// Generates a power-law cluster graph (Holme & Kim model)
///
/// This is a variant of the Barabasi-Albert model that adds a triad formation
/// step to increase clustering. After each preferential attachment step, with
/// probability `p_triangle`, a triangle is formed by connecting the new node
/// to a neighbor of the just-connected node.
///
/// # Arguments
/// * `n` - Total number of nodes (must be > m)
/// * `m` - Number of edges to add per new node
/// * `p_triangle` - Probability of triad formation step (0 = pure BA, 1 = max clustering)
/// * `rng` - Random number generator
///
/// # Returns
/// * `Result<Graph<usize, f64>>` - The generated graph
///
/// # Reference
/// Holme & Kim, "Growing scale-free networks with tunable clustering",
/// Physical Review E, 2002.
///
/// # Properties
/// - Scale-free degree distribution (power law)
/// - Tunable clustering coefficient via `p_triangle`
/// - When `p_triangle = 0`, equivalent to Barabasi-Albert model
#[allow(dead_code)]
pub fn power_law_cluster_graph<R: Rng>(
    n: usize,
    m: usize,
    p_triangle: f64,
    rng: &mut R,
) -> Result<Graph<usize, f64>> {
    if m == 0 {
        return Err(GraphError::InvalidGraph("m must be positive".to_string()));
    }
    if m >= n {
        return Err(GraphError::InvalidGraph(
            "m must be less than n".to_string(),
        ));
    }
    if !(0.0..=1.0).contains(&p_triangle) {
        return Err(GraphError::InvalidGraph(
            "p_triangle must be between 0 and 1".to_string(),
        ));
    }

    let mut graph = Graph::new();

    // Start with a complete graph of m+1 nodes
    for i in 0..=m {
        graph.add_node(i);
    }
    for i in 0..=m {
        for j in (i + 1)..=m {
            graph.add_edge(i, j, 1.0)?;
        }
    }

    // Track degrees for preferential attachment
    let mut degrees = vec![m; m + 1];
    let mut total_degree = m * (m + 1);

    // Add remaining nodes one at a time
    for new_node in (m + 1)..n {
        graph.add_node(new_node);

        let mut targets_added: HashSet<usize> = HashSet::new();
        let mut edges_to_add = m;

        // First edge: always preferential attachment
        if edges_to_add > 0 {
            let target = select_preferential_attachment(
                &degrees,
                total_degree,
                &targets_added,
                new_node,
                rng,
            );
            if let Some(t) = target {
                graph.add_edge(new_node, t, 1.0)?;
                targets_added.insert(t);
                degrees[t] += 1;
                total_degree += 2;
                edges_to_add -= 1;
            }
        }

        // Remaining edges: either triad formation or preferential attachment
        while edges_to_add > 0 {
            if rng.random::<f64>() < p_triangle && !targets_added.is_empty() {
                // Triad formation: pick a random target already connected,
                // then connect to one of its neighbors
                let last_target = *targets_added.iter().last().unwrap_or(&0);
                let neighbors_of_target = graph.neighbors(&last_target).unwrap_or_default();

                // Find a neighbor that is not already targeted or the new node
                let candidates: Vec<usize> = neighbors_of_target
                    .into_iter()
                    .filter(|nb| *nb != new_node && !targets_added.contains(nb))
                    .collect();

                if let Some(&chosen) = candidates.choose(rng) {
                    graph.add_edge(new_node, chosen, 1.0)?;
                    targets_added.insert(chosen);
                    degrees[chosen] += 1;
                    total_degree += 2;
                    edges_to_add -= 1;
                    continue;
                }
                // Fall through to preferential attachment if no valid neighbor found
            }

            // Preferential attachment
            let target = select_preferential_attachment(
                &degrees,
                total_degree,
                &targets_added,
                new_node,
                rng,
            );
            if let Some(t) = target {
                graph.add_edge(new_node, t, 1.0)?;
                targets_added.insert(t);
                degrees[t] += 1;
                total_degree += 2;
                edges_to_add -= 1;
            } else {
                // Cannot find more targets; bail to avoid infinite loop
                break;
            }
        }

        degrees.push(targets_added.len());
    }

    Ok(graph)
}

/// Helper: select a node via preferential attachment (probability proportional to degree)
fn select_preferential_attachment<R: Rng>(
    degrees: &[usize],
    total_degree: usize,
    excluded: &HashSet<usize>,
    new_node: usize,
    rng: &mut R,
) -> Option<usize> {
    if total_degree == 0 {
        return None;
    }

    // Try up to 100 times to find a non-excluded target
    for _ in 0..100 {
        let mut cumulative = 0.0;
        let random_value = rng.random::<f64>() * total_degree as f64;

        for (node_id, &degree) in degrees.iter().enumerate() {
            if node_id == new_node {
                continue;
            }
            cumulative += degree as f64;
            if random_value <= cumulative && !excluded.contains(&node_id) {
                return Some(node_id);
            }
        }
    }
    None
}

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

    #[test]
    fn test_erdos_renyi_graph() {
        let mut rng = StdRng::seed_from_u64(42);
        let graph = erdos_renyi_graph(10, 0.3, &mut rng).expect("Operation failed");

        assert_eq!(graph.node_count(), 10);
        // With p=0.3 and 45 possible edges, we expect around 13-14 edges
        // but this is random, so we just check it's reasonable
        assert!(graph.edge_count() <= 45);
    }

    #[test]
    fn test_complete_graph() {
        let graph = complete_graph(5).expect("Operation failed");

        assert_eq!(graph.node_count(), 5);
        assert_eq!(graph.edge_count(), 10); // n*(n-1)/2 = 5*4/2 = 10
    }

    #[test]
    fn test_star_graph() {
        let graph = star_graph(6).expect("Operation failed");

        assert_eq!(graph.node_count(), 6);
        assert_eq!(graph.edge_count(), 5); // n-1 edges
    }

    #[test]
    fn test_path_graph() {
        let graph = path_graph(5).expect("Operation failed");

        assert_eq!(graph.node_count(), 5);
        assert_eq!(graph.edge_count(), 4); // n-1 edges
    }

    #[test]
    fn test_cycle_graph() {
        let graph = cycle_graph(5).expect("Operation failed");

        assert_eq!(graph.node_count(), 5);
        assert_eq!(graph.edge_count(), 5); // n edges

        // Test error case
        assert!(cycle_graph(2).is_err());
    }

    #[test]
    fn test_grid_2d_graph() {
        let graph = grid_2d_graph(3, 4).expect("Operation failed");

        assert_eq!(graph.node_count(), 12); // 3*4 = 12 nodes
        assert_eq!(graph.edge_count(), 17); // (3-1)*4 + 3*(4-1) = 8 + 9 = 17 edges
    }

    #[test]
    fn test_grid_3d_graph() {
        let graph = grid_3d_graph(2, 2, 2).expect("Operation failed");

        assert_eq!(graph.node_count(), 8); // 2*2*2 = 8 nodes
                                           // Each internal node connects to 3 neighbors in 3D grid
                                           // Expected edges: 3 faces × 2 edges per face + 3 additional connections = 12 edges
        assert_eq!(graph.edge_count(), 12);
    }

    #[test]
    fn test_triangular_lattice_graph() {
        let graph = triangular_lattice_graph(3, 3).expect("Operation failed");

        assert_eq!(graph.node_count(), 9); // 3*3 = 9 nodes
                                           // Triangular lattice has more edges than regular grid due to diagonal connections
        assert!(graph.edge_count() > 12); // More than standard 2D grid edges
    }

    #[test]
    fn test_hexagonal_lattice_graph() {
        let graph = hexagonal_lattice_graph(3, 3).expect("Operation failed");

        assert_eq!(graph.node_count(), 9); // 3*3 = 9 nodes
                                           // Hexagonal lattice should have fewer edges than triangular due to honeycomb structure
        assert!(graph.edge_count() >= 6);
    }

    #[test]
    fn test_barabasi_albert_graph() {
        let mut rng = StdRng::seed_from_u64(42);
        let graph = barabasi_albert_graph(10, 2, &mut rng).expect("Operation failed");

        assert_eq!(graph.node_count(), 10);
        // Should have 3 + 2*7 = 17 edges (3 initial edges + 2 for each of the 7 new nodes)
        assert_eq!(graph.edge_count(), 17);
    }

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

        // Two blocks of size 3 and 4
        let block_sizes = vec![3, 4];
        // High intra-block probability, low inter-block probability
        let block_matrix = vec![vec![0.8, 0.1], vec![0.1, 0.8]];

        let graph = stochastic_block_model(&block_sizes, &block_matrix, &mut rng)
            .expect("Operation failed");

        assert_eq!(graph.node_count(), 7); // 3 + 4 = 7 nodes

        // Check that all nodes are present
        for i in 0..7 {
            assert!(graph.has_node(&i));
        }
    }

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

        let graph = two_community_sbm(5, 5, 0.8, 0.1, &mut rng).expect("Operation failed");

        assert_eq!(graph.node_count(), 10);

        // Should have some edges within communities and fewer between
        // This is probabilistic so we can't test exact numbers
        assert!(graph.edge_count() > 0);
    }

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

        let graph = planted_partition_model(12, 3, 0.7, 0.1, &mut rng).expect("Operation failed");

        assert_eq!(graph.node_count(), 12); // 12 nodes total

        // 3 communities of size 4 each
        // Should have some edges
        assert!(graph.edge_count() > 0);
    }

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

        // Empty blocks
        assert!(stochastic_block_model(&[], &[], &mut rng).is_err());

        // Mismatched dimensions
        let block_sizes = vec![3, 4];
        let wrong_matrix = vec![vec![0.5]];
        assert!(stochastic_block_model(&block_sizes, &wrong_matrix, &mut rng).is_err());

        // Invalid probabilities
        let bad_matrix = vec![vec![1.5, 0.5], vec![0.5, 0.5]];
        assert!(stochastic_block_model(&block_sizes, &bad_matrix, &mut rng).is_err());

        // Non-divisible nodes for planted partition
        assert!(planted_partition_model(10, 3, 0.5, 0.1, &mut rng).is_err());
    }

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

        // Test valid degree sequence (even sum)
        let degree_sequence = vec![2, 2, 2, 2]; // Sum = 8 (even)
        let graph = configuration_model(&degree_sequence, &mut rng).expect("Operation failed");

        assert_eq!(graph.node_count(), 4);
        // Should have 4 edges (sum of degrees / 2)
        assert_eq!(graph.edge_count(), 4);

        // Check that each node has the correct degree
        for (i, &expected_degree) in degree_sequence.iter().enumerate() {
            let actual_degree = graph.degree(&i);
            assert_eq!(actual_degree, expected_degree);
        }
    }

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

        // Test odd degree sum (should fail)
        let odd_degree_sequence = vec![1, 2, 2]; // Sum = 5 (odd)
        assert!(configuration_model(&odd_degree_sequence, &mut rng).is_err());

        // Test empty sequence
        let empty_sequence = vec![];
        let graph = configuration_model(&empty_sequence, &mut rng).expect("Operation failed");
        assert_eq!(graph.node_count(), 0);
    }

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

        // Test valid degree sequence for simple graph
        let degree_sequence = vec![2, 2, 2, 2]; // Sum = 8 (even)
        let graph =
            simple_configuration_model(&degree_sequence, &mut rng, 100).expect("Operation failed");

        assert_eq!(graph.node_count(), 4);
        assert_eq!(graph.edge_count(), 4);

        // Check that graph is simple (no self-loops)
        for i in 0..4 {
            assert!(!graph.has_edge(&i, &i), "Graph should not have self-loops");
        }

        // Check degrees
        for (i, &expected_degree) in degree_sequence.iter().enumerate() {
            let actual_degree = graph.degree(&i);
            assert_eq!(actual_degree, expected_degree);
        }
    }

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

        // Test degree too large for simple graph
        let invalid_degree_sequence = vec![4, 2, 2, 2]; // Node 0 has degree 4, but n=4, so max degree is 3
        assert!(simple_configuration_model(&invalid_degree_sequence, &mut rng, 10).is_err());

        // Test odd degree sum
        let odd_degree_sequence = vec![1, 2, 2]; // Sum = 5 (odd)
        assert!(simple_configuration_model(&odd_degree_sequence, &mut rng, 10).is_err());
    }

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

        // Test empty tree
        let empty_tree = tree_graph(0, &mut rng).expect("Operation failed");
        assert_eq!(empty_tree.node_count(), 0);
        assert_eq!(empty_tree.edge_count(), 0);

        // Test single node tree
        let single_tree = tree_graph(1, &mut rng).expect("Operation failed");
        assert_eq!(single_tree.node_count(), 1);
        assert_eq!(single_tree.edge_count(), 0);

        // Test tree with multiple nodes
        let tree = tree_graph(5, &mut rng).expect("Operation failed");
        assert_eq!(tree.node_count(), 5);
        assert_eq!(tree.edge_count(), 4); // n-1 edges for a tree

        // Verify all nodes are present
        for i in 0..5 {
            assert!(tree.has_node(&i));
        }
    }

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

        // Create a complete graph
        let complete = complete_graph(4).expect("Operation failed");

        // Generate spanning tree
        let spanning_tree = random_spanning_tree(&complete, &mut rng).expect("Operation failed");

        assert_eq!(spanning_tree.node_count(), 4);
        assert_eq!(spanning_tree.edge_count(), 3); // n-1 edges for spanning tree

        // Verify all nodes are present
        for i in 0..4 {
            assert!(spanning_tree.has_node(&i));
        }
    }

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

        // Create forest with trees of sizes [3, 2, 4]
        let tree_sizes = vec![3, 2, 4];
        let forest = forest_graph(&tree_sizes, &tree_sizes, &mut rng).expect("Operation failed");

        assert_eq!(forest.node_count(), 9); // 3 + 2 + 4 = 9 nodes
        assert_eq!(forest.edge_count(), 6); // (3-1) + (2-1) + (4-1) = 6 edges

        // Verify all nodes are present
        for i in 0..9 {
            assert!(forest.has_node(&i));
        }

        // Test empty forest
        let empty_forest = forest_graph(&[], &[], &mut rng).expect("Operation failed");
        assert_eq!(empty_forest.node_count(), 0);
        assert_eq!(empty_forest.edge_count(), 0);

        // Test forest with empty trees
        let forest_with_zeros =
            forest_graph(&[0, 3, 0, 2], &[0, 3, 0, 2], &mut rng).expect("Operation failed");
        assert_eq!(forest_with_zeros.node_count(), 5); // 3 + 2 = 5 nodes
        assert_eq!(forest_with_zeros.edge_count(), 3); // (3-1) + (2-1) = 3 edges
    }

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

        let graph = random_geometric_graph(20, 0.4, &mut rng).expect("Operation failed");
        assert_eq!(graph.node_count(), 20);
        // With radius=0.4, we should have some edges but not all
        assert!(graph.edge_count() > 0);
        assert!(graph.edge_count() < 20 * 19 / 2);

        // Edge weights should be distances (positive)
        for edge in graph.edges() {
            assert!(edge.weight > 0.0);
            assert!(edge.weight <= 0.4 + 1e-10); // within radius
        }
    }

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

        // With large radius, should be almost complete
        let graph = random_geometric_graph(5, 2.0, &mut rng).expect("Operation failed");
        assert_eq!(graph.node_count(), 5);
        // max distance in unit square is sqrt(2) < 2.0, so all pairs connected
        assert_eq!(graph.edge_count(), 10); // C(5,2) = 10
    }

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

        let graph = random_geometric_graph(10, 0.0, &mut rng).expect("Operation failed");
        assert_eq!(graph.node_count(), 10);
        assert_eq!(graph.edge_count(), 0); // no edges with zero radius
    }

    #[test]
    fn test_random_geometric_graph_errors() {
        let mut rng = StdRng::seed_from_u64(42);
        assert!(random_geometric_graph(10, -0.1, &mut rng).is_err());
    }

    #[test]
    fn test_random_geometric_graph_empty() {
        let mut rng = StdRng::seed_from_u64(42);
        let graph = random_geometric_graph(0, 0.5, &mut rng).expect("Operation failed");
        assert_eq!(graph.node_count(), 0);
        assert_eq!(graph.edge_count(), 0);
    }

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

        let graph = power_law_cluster_graph(20, 2, 0.5, &mut rng).expect("Operation failed");
        assert_eq!(graph.node_count(), 20);
        // Should have at least the initial complete graph edges + m edges per node
        assert!(graph.edge_count() > 0);
    }

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

        // p_triangle = 0 is equivalent to BA model
        let graph = power_law_cluster_graph(15, 2, 0.0, &mut rng).expect("Operation failed");
        assert_eq!(graph.node_count(), 15);
        assert!(graph.edge_count() > 0);
    }

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

        // p_triangle = 1 maximizes clustering
        let graph = power_law_cluster_graph(15, 2, 1.0, &mut rng).expect("Operation failed");
        assert_eq!(graph.node_count(), 15);
        assert!(graph.edge_count() > 0);
    }

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

        // m = 0
        assert!(power_law_cluster_graph(10, 0, 0.5, &mut rng).is_err());
        // m >= n
        assert!(power_law_cluster_graph(5, 5, 0.5, &mut rng).is_err());
        // invalid p_triangle
        assert!(power_law_cluster_graph(10, 2, 1.5, &mut rng).is_err());
        assert!(power_law_cluster_graph(10, 2, -0.1, &mut rng).is_err());
    }
}