rust-igraph 0.0.1-alpha.4

Pure-Rust, high-performance graph & network analysis library — 400+ algorithms, zero unsafe, igraph-compatible
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
//! ALGO-PR-027 / PR-027b — BFS-based k-hop neighbourhoods.
//!
//! - [`neighborhood_size`] / [`neighborhood_size_with_mode`] (PR-027):
//!   for every vertex `v` return *how many* vertices `w` satisfy
//!   `mindist <= dist(v, w) <= order`.
//! - [`neighborhood`] / [`neighborhood_with_mode`] (PR-027b): for every
//!   vertex `v` return *the list of* such vertices, in BFS visitation
//!   order (matching `igraph_neighborhood()` from
//!   `references/igraph/src/properties/neighborhood.c:208-303`).
//!
//! `dist` is unweighted graph distance; `order < 0` is treated as
//! infinity; `mode` is ignored on undirected graphs.

use std::collections::VecDeque;

use crate::core::{Graph, IgraphError, IgraphResult, VertexId};

/// Direction mode for `neighborhood_size_with_mode` on directed graphs.
/// Ignored on undirected graphs — every mode reduces to [`NeighborhoodMode::All`].
///
/// Counterpart of `igraph_neimode_t` (`include/igraph_constants.h`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NeighborhoodMode {
    /// Follow outgoing edges only (`IGRAPH_OUT`). For each source `v`,
    /// counts vertices reachable by following out-edges.
    Out,
    /// Follow incoming edges only (`IGRAPH_IN`). For each source `v`,
    /// counts vertices that can reach `v` by following out-edges (i.e.
    /// reachable from `v` along reversed edges).
    In,
    /// Ignore direction — treat every edge as bidirectional
    /// (`IGRAPH_ALL`).
    All,
}

/// k-hop neighbourhood size for every vertex (`mode = All`, `mindist = 0`).
///
/// For each vertex `v` returns the number of vertices within `order`
/// hops (inclusive), counting `v` itself. Negative `order` means
/// infinity (every reachable vertex is counted).
///
/// Counterpart of `igraph_neighborhood_size(graph, _, igraph_vss_all(),
/// order, IGRAPH_ALL, /*mindist=*/0)`.
///
/// # Errors
/// - [`IgraphError::InvalidArgument`] if `order >= 0` but `order` cannot
///   be represented as a non-negative integer (always satisfied for
///   `i32 >= 0`, so this can only fail via the with-mode variant when
///   `mindist > order`).
///
/// # Examples
/// ```
/// use rust_igraph::{Graph, neighborhood_size};
///
/// // Path P5: 0-1-2-3-4
/// let mut g = Graph::with_vertices(5);
/// for (u, v) in [(0, 1), (1, 2), (2, 3), (3, 4)] {
///     g.add_edge(u, v).unwrap();
/// }
/// // Order 1: self + immediate neighbours.
/// assert_eq!(neighborhood_size(&g, 1).unwrap(), vec![2, 3, 3, 3, 2]);
/// // Order 2: self + 2-hop ball.
/// assert_eq!(neighborhood_size(&g, 2).unwrap(), vec![3, 4, 5, 4, 3]);
/// ```
pub fn neighborhood_size(graph: &Graph, order: i32) -> IgraphResult<Vec<u32>> {
    neighborhood_size_with_mode(graph, order, NeighborhoodMode::All, 0)
}

/// Full mode-aware k-hop neighbourhood size with `mindist` filter.
///
/// For each source vertex `v` returns the number of vertices `w` such
/// that `mindist <= dist(v, w) <= order` (or `dist(v, w) >= mindist`
/// when `order < 0`, treating order as infinity). Direction follows
/// `mode` on directed graphs and is ignored on undirected graphs.
///
/// `mindist = 0` includes `v` itself; `mindist = 1` excludes `v` but
/// counts immediate neighbours; `mindist = k` excludes vertices reached
/// in fewer than `k` hops.
///
/// Counterpart of `igraph_neighborhood_size(graph, _, igraph_vss_all(),
/// order, mode, mindist)`.
///
/// # Errors
/// - [`IgraphError::InvalidArgument`] if `mindist < 0`.
/// - [`IgraphError::InvalidArgument`] if `order >= 0` and `mindist > order`.
///
/// # Examples
/// ```
/// use rust_igraph::{Graph, neighborhood_size_with_mode, NeighborhoodMode};
///
/// // Directed star: 0->1, 0->2, 0->3.
/// let mut g = Graph::new(4, true).unwrap();
/// for v in [1, 2, 3] { g.add_edge(0, v).unwrap(); }
///
/// // Out: 0 reaches all; leaves only see themselves.
/// assert_eq!(
///     neighborhood_size_with_mode(&g, -1, NeighborhoodMode::Out, 0).unwrap(),
///     vec![4, 1, 1, 1]
/// );
/// // In: leaves can reach 0 via reversed edges (in-mode walks against arc).
/// assert_eq!(
///     neighborhood_size_with_mode(&g, -1, NeighborhoodMode::In, 0).unwrap(),
///     vec![1, 2, 2, 2]
/// );
/// // mindist=1 excludes the vertex itself.
/// assert_eq!(
///     neighborhood_size_with_mode(&g, 1, NeighborhoodMode::All, 1).unwrap(),
///     vec![3, 1, 1, 1]
/// );
/// ```
pub fn neighborhood_size_with_mode(
    graph: &Graph,
    order: i32,
    mode: NeighborhoodMode,
    mindist: i32,
) -> IgraphResult<Vec<u32>> {
    if mindist < 0 {
        return Err(IgraphError::InvalidArgument(format!(
            "minimum distance must not be negative, got {mindist}"
        )));
    }
    if order >= 0 && mindist > order {
        return Err(IgraphError::InvalidArgument(format!(
            "minimum distance must not exceed neighbourhood order ({order}), got {mindist}"
        )));
    }

    let n = graph.vcount();
    if n == 0 {
        return Ok(Vec::new());
    }
    let n_us = n as usize;

    // C uses `order = no_of_nodes` when negative — effectively infinite
    // because BFS depth is bounded by n-1. We model the same way using
    // i64 to avoid sign-mixing on the comparisons inside the loop.
    let inf_order = order < 0;
    let effective_order: i64 = if inf_order {
        i64::from(n)
    } else {
        i64::from(order)
    };
    let mindist_i64 = i64::from(mindist);

    let directed = graph.is_directed();
    // `added[v] = src + 1` marks "v has been seen by source `src`",
    // matching the C reference (avoids per-source array allocation).
    let mut added: Vec<u32> = vec![0; n_us];
    let mut queue: VecDeque<(VertexId, i64)> = VecDeque::new();
    let mut result: Vec<u32> = vec![0; n_us];

    for src in 0..n {
        let marker = src + 1;
        added[src as usize] = marker;
        let mut size: u32 = u32::from(mindist_i64 == 0);
        queue.clear();
        if effective_order > 0 {
            queue.push_back((src, 0));
        }

        while let Some((actnode, actdist)) = queue.pop_front() {
            let neis = neighbours_for(graph, actnode, mode, directed)?;
            if actdist < effective_order - 1 {
                for nei in neis {
                    if added[nei as usize] != marker {
                        added[nei as usize] = marker;
                        queue.push_back((nei, actdist + 1));
                        if actdist + 1 >= mindist_i64 {
                            size = size
                                .checked_add(1)
                                .ok_or(IgraphError::Internal("neighborhood size overflowed u32"))?;
                        }
                    }
                }
            } else {
                // At the frontier: count but don't enqueue.
                for nei in neis {
                    if added[nei as usize] != marker {
                        added[nei as usize] = marker;
                        if actdist + 1 >= mindist_i64 {
                            size = size
                                .checked_add(1)
                                .ok_or(IgraphError::Internal("neighborhood size overflowed u32"))?;
                        }
                    }
                }
            }
        }

        result[src as usize] = size;
    }

    Ok(result)
}

/// k-hop neighbourhood vertex list for every vertex (`mode = All`, `mindist = 0`).
///
/// For each vertex `v` returns the list of vertices `w` within `order`
/// hops (inclusive), in BFS visitation order with `v` first. Negative
/// `order` means infinity.
///
/// Counterpart of `igraph_neighborhood(graph, _, igraph_vss_all(),
/// order, IGRAPH_ALL, /*mindist=*/0)`.
///
/// # Errors
/// Same as [`neighborhood_with_mode`].
///
/// # Examples
/// ```
/// use rust_igraph::{Graph, neighborhood};
///
/// // Path P5: 0-1-2-3-4
/// let mut g = Graph::with_vertices(5);
/// for (u, v) in [(0, 1), (1, 2), (2, 3), (3, 4)] {
///     g.add_edge(u, v).unwrap();
/// }
/// // Order 1: each vertex's 1-hop ball.
/// let n1 = neighborhood(&g, 1).unwrap();
/// assert_eq!(n1[0], vec![0, 1]);
/// assert_eq!(n1[2], vec![2, 1, 3]);
/// ```
pub fn neighborhood(graph: &Graph, order: i32) -> IgraphResult<Vec<Vec<u32>>> {
    neighborhood_with_mode(graph, order, NeighborhoodMode::All, 0)
}

/// Full mode-aware k-hop neighbourhood vertex list with `mindist` filter.
///
/// For each source vertex `v` returns the list of vertices `w` such that
/// `mindist <= dist(v, w) <= order` (or `dist(v, w) >= mindist` when
/// `order < 0`). The list is in BFS visitation order; when `mindist = 0`
/// the source is the first element.
///
/// Direction follows `mode` on directed graphs; on undirected graphs
/// every mode reduces to [`NeighborhoodMode::All`].
///
/// Counterpart of `igraph_neighborhood(graph, _, igraph_vss_all(),
/// order, mode, mindist)`.
///
/// # Errors
/// - [`IgraphError::InvalidArgument`] if `mindist < 0`.
/// - [`IgraphError::InvalidArgument`] if `order >= 0` and `mindist > order`.
///
/// # Examples
/// ```
/// use rust_igraph::{Graph, neighborhood_with_mode, NeighborhoodMode};
///
/// // Directed star: 0->1, 0->2, 0->3.
/// let mut g = Graph::new(4, true).unwrap();
/// for v in [1, 2, 3] { g.add_edge(0, v).unwrap(); }
///
/// // Out from 0: hub reaches all (BFS order: self, then 1, 2, 3).
/// let nbh = neighborhood_with_mode(&g, -1, NeighborhoodMode::Out, 0).unwrap();
/// assert_eq!(nbh[0], vec![0, 1, 2, 3]);
/// // Leaves stay alone.
/// assert_eq!(nbh[1], vec![1]);
///
/// // mindist=1 strips the source.
/// let nbh1 = neighborhood_with_mode(&g, 1, NeighborhoodMode::All, 1).unwrap();
/// assert_eq!(nbh1[0].len(), 3);  // 1, 2, 3 (some order)
/// assert!(!nbh1[0].contains(&0));
/// ```
pub fn neighborhood_with_mode(
    graph: &Graph,
    order: i32,
    mode: NeighborhoodMode,
    mindist: i32,
) -> IgraphResult<Vec<Vec<u32>>> {
    if mindist < 0 {
        return Err(IgraphError::InvalidArgument(format!(
            "minimum distance must not be negative, got {mindist}"
        )));
    }
    if order >= 0 && mindist > order {
        return Err(IgraphError::InvalidArgument(format!(
            "minimum distance must not exceed neighbourhood order ({order}), got {mindist}"
        )));
    }

    let n = graph.vcount();
    if n == 0 {
        return Ok(Vec::new());
    }
    let n_us = n as usize;

    let inf_order = order < 0;
    let effective_order: i64 = if inf_order {
        i64::from(n)
    } else {
        i64::from(order)
    };
    let mindist_i64 = i64::from(mindist);

    let directed = graph.is_directed();
    let mut added: Vec<u32> = vec![0; n_us];
    let mut queue: VecDeque<(VertexId, i64)> = VecDeque::new();
    let mut result: Vec<Vec<u32>> = Vec::with_capacity(n_us);

    for src in 0..n {
        let marker = src + 1;
        added[src as usize] = marker;
        let mut tmp: Vec<u32> = Vec::new();
        if mindist_i64 == 0 {
            tmp.push(src);
        }
        queue.clear();
        if effective_order > 0 {
            queue.push_back((src, 0));
        }

        while let Some((actnode, actdist)) = queue.pop_front() {
            let neis = neighbours_for(graph, actnode, mode, directed)?;
            if actdist < effective_order - 1 {
                for nei in neis {
                    if added[nei as usize] != marker {
                        added[nei as usize] = marker;
                        queue.push_back((nei, actdist + 1));
                        if actdist + 1 >= mindist_i64 {
                            tmp.push(nei);
                        }
                    }
                }
            } else {
                for nei in neis {
                    if added[nei as usize] != marker {
                        added[nei as usize] = marker;
                        if actdist + 1 >= mindist_i64 {
                            tmp.push(nei);
                        }
                    }
                }
            }
        }

        result.push(tmp);
    }

    Ok(result)
}

/// Per-vertex induced subgraphs of k-hop neighbourhoods (`mode = All`, `mindist = 0`).
///
/// For each vertex `v`, computes its `order`-hop neighbourhood (the set
/// of vertices within distance `order` of `v`, including `v` itself) and
/// returns the induced subgraph on that vertex set. The result is a
/// `Vec<Graph>` of length `graph.vcount()`.
///
/// Counterpart of `igraph_neighborhood_graphs(graph, _, igraph_vss_all(),
/// order, IGRAPH_ALL, /*mindist=*/0)`.
///
/// # Errors
/// - [`IgraphError::InvalidArgument`] if `order >= 0` and internal
///   constraints are violated (same as [`neighborhood_with_mode`]).
///
/// # Examples
/// ```
/// use rust_igraph::{Graph, neighborhood_graphs};
///
/// // Path graph: 0 - 1 - 2 - 3
/// let mut g = Graph::with_vertices(4);
/// g.add_edge(0, 1).unwrap();
/// g.add_edge(1, 2).unwrap();
/// g.add_edge(2, 3).unwrap();
///
/// let gs = neighborhood_graphs(&g, 1).unwrap();
/// assert_eq!(gs.len(), 4);
/// // Vertex 0's 1-hop neighborhood: {0, 1}, induced subgraph has 1 edge
/// assert_eq!(gs[0].vcount(), 2);
/// assert_eq!(gs[0].ecount(), 1);
/// // Vertex 1's 1-hop neighborhood: {0, 1, 2}, induced subgraph has 2 edges
/// assert_eq!(gs[1].vcount(), 3);
/// assert_eq!(gs[1].ecount(), 2);
/// ```
pub fn neighborhood_graphs(graph: &Graph, order: i32) -> IgraphResult<Vec<Graph>> {
    neighborhood_graphs_with_mode(graph, order, NeighborhoodMode::All, 0)
}

/// Per-vertex induced subgraphs of k-hop neighbourhoods with full mode control.
///
/// Generalises [`neighborhood_graphs`] with direction `mode` and
/// `mindist` filter (minimum distance to include a vertex in the
/// neighbourhood).
///
/// For each source `v`, collects the set of vertices `w` with
/// `mindist <= dist(v, w) <= order`, then builds the induced subgraph
/// on that set. Negative `order` means infinity.
///
/// Counterpart of `igraph_neighborhood_graphs(graph, _, igraph_vss_all(),
/// order, mode, mindist)`.
///
/// # Errors
/// - [`IgraphError::InvalidArgument`] if `mindist < 0`.
/// - [`IgraphError::InvalidArgument`] if `order >= 0` and `mindist > order`.
///
/// # Examples
/// ```
/// use rust_igraph::{Graph, neighborhood_graphs_with_mode, NeighborhoodMode};
///
/// // Directed star: 0->1, 0->2, 0->3
/// let mut g = Graph::new(4, true).unwrap();
/// for v in [1, 2, 3] { g.add_edge(0, v).unwrap(); }
///
/// let gs = neighborhood_graphs_with_mode(&g, 1, NeighborhoodMode::Out, 0).unwrap();
/// // Vertex 0's out-1-hop: {0, 1, 2, 3}, induced subgraph has 3 edges
/// assert_eq!(gs[0].vcount(), 4);
/// assert_eq!(gs[0].ecount(), 3);
/// // Vertex 1's out-1-hop: {1} only (no outgoing edges)
/// assert_eq!(gs[1].vcount(), 1);
/// assert_eq!(gs[1].ecount(), 0);
/// ```
pub fn neighborhood_graphs_with_mode(
    graph: &Graph,
    order: i32,
    mode: NeighborhoodMode,
    mindist: i32,
) -> IgraphResult<Vec<Graph>> {
    use crate::algorithms::operators::induced_subgraph::induced_subgraph;

    let neighborhoods = neighborhood_with_mode(graph, order, mode, mindist)?;
    let n = graph.vcount();
    let mut result: Vec<Graph> = Vec::with_capacity(n as usize);

    for vids in &neighborhoods {
        if vids.len() == n as usize {
            result.push(graph.clone());
        } else {
            let sub = induced_subgraph(graph, vids)?;
            result.push(sub.graph);
        }
    }

    Ok(result)
}

/// Direction-aware neighbour list. Undirected graphs use
/// `Graph::neighbors` regardless of `mode` (matches C semantics).
fn neighbours_for(
    graph: &Graph,
    v: VertexId,
    mode: NeighborhoodMode,
    directed: bool,
) -> IgraphResult<Vec<VertexId>> {
    if !directed {
        return graph.neighbors(v);
    }
    match mode {
        NeighborhoodMode::Out => graph.out_neighbors_vec(v),
        NeighborhoodMode::In => graph.in_neighbors_vec(v),
        NeighborhoodMode::All => {
            let mut out = graph.out_neighbors_vec(v)?;
            out.extend(graph.in_neighbors_vec(v)?);
            Ok(out)
        }
    }
}

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

    // ---- C reference fixture: directed n=6 with loops and multi-edges ----
    // Built from references/igraph/tests/unit/igraph_neighborhood_size.c
    // edges: 0->1, 0->2, 1->1 (self-loop), 1->3, 2->0, 2->3, 3->4, 3->4
    fn c_ref_graph() -> Graph {
        let mut g = Graph::new(6, true).unwrap();
        for (u, v) in [
            (0, 1),
            (0, 2),
            (1, 1),
            (1, 3),
            (2, 0),
            (2, 3),
            (3, 4),
            (3, 4),
        ] {
            g.add_edge(u, v).unwrap();
        }
        g
    }

    #[test]
    fn empty_graph_returns_empty_vector() {
        let g = Graph::with_vertices(0);
        assert!(neighborhood_size(&g, 1).unwrap().is_empty());
    }

    #[test]
    fn singleton_order_0_is_one() {
        let g = Graph::with_vertices(1);
        assert_eq!(neighborhood_size(&g, 0).unwrap(), vec![1]);
        assert_eq!(neighborhood_size(&g, 5).unwrap(), vec![1]);
    }

    #[test]
    fn no_edges_only_self_at_any_order() {
        let g = Graph::with_vertices(4);
        assert_eq!(neighborhood_size(&g, 0).unwrap(), vec![1, 1, 1, 1]);
        assert_eq!(neighborhood_size(&g, 5).unwrap(), vec![1, 1, 1, 1]);
    }

    #[test]
    fn ring_p5_matches_python_reference_order_1() {
        // python-igraph testStructural: Ring(10, circular=False) order=1
        // → [2,3,3,3,3,3,3,3,3,2]. Smaller P5 equivalent: [2,3,3,3,2].
        let mut g = Graph::with_vertices(5);
        for (u, v) in [(0, 1), (1, 2), (2, 3), (3, 4)] {
            g.add_edge(u, v).unwrap();
        }
        assert_eq!(neighborhood_size(&g, 1).unwrap(), vec![2, 3, 3, 3, 2]);
    }

    #[test]
    fn ring_p10_matches_python_order_1() {
        let mut g = Graph::with_vertices(10);
        for i in 0..9 {
            g.add_edge(i, i + 1).unwrap();
        }
        assert_eq!(
            neighborhood_size(&g, 1).unwrap(),
            vec![2, 3, 3, 3, 3, 3, 3, 3, 3, 2]
        );
    }

    #[test]
    fn ring_p10_matches_python_order_3() {
        let mut g = Graph::with_vertices(10);
        for i in 0..9 {
            g.add_edge(i, i + 1).unwrap();
        }
        assert_eq!(
            neighborhood_size(&g, 3).unwrap(),
            vec![4, 5, 6, 7, 7, 7, 7, 6, 5, 4]
        );
    }

    #[test]
    fn ring_p10_order_3_mindist_2_matches_python() {
        let mut g = Graph::with_vertices(10);
        for i in 0..9 {
            g.add_edge(i, i + 1).unwrap();
        }
        assert_eq!(
            neighborhood_size_with_mode(&g, 3, NeighborhoodMode::All, 2).unwrap(),
            vec![2, 2, 3, 4, 4, 4, 4, 3, 2, 2]
        );
    }

    #[test]
    fn c_ref_order_0_is_self_only() {
        let g = c_ref_graph();
        // C .out: ( 1 1 1 1 1 1 )
        assert_eq!(neighborhood_size(&g, 0).unwrap(), vec![1, 1, 1, 1, 1, 1]);
    }

    #[test]
    fn c_ref_order_1_all_mode() {
        let g = c_ref_graph();
        // C .out: ( 3 3 3 4 2 1 )
        assert_eq!(neighborhood_size(&g, 1).unwrap(), vec![3, 3, 3, 4, 2, 1]);
    }

    #[test]
    fn c_ref_order_1_in_mode() {
        let g = c_ref_graph();
        // C .out: ( 2 2 2 3 2 1 )
        assert_eq!(
            neighborhood_size_with_mode(&g, 1, NeighborhoodMode::In, 0).unwrap(),
            vec![2, 2, 2, 3, 2, 1]
        );
    }

    #[test]
    fn c_ref_order_10_all_mode_saturates() {
        let g = c_ref_graph();
        // C .out: ( 5 5 5 5 5 1 ) — vertex 5 is isolated.
        assert_eq!(neighborhood_size(&g, 10).unwrap(), vec![5, 5, 5, 5, 5, 1]);
    }

    #[test]
    fn c_ref_order_2_mindist_2_out_mode() {
        let g = c_ref_graph();
        // C .out: ( 1 1 2 0 0 0 )
        assert_eq!(
            neighborhood_size_with_mode(&g, 2, NeighborhoodMode::Out, 2).unwrap(),
            vec![1, 1, 2, 0, 0, 0]
        );
    }

    #[test]
    fn c_ref_order_4_mindist_4_all_mode_all_zero() {
        let g = c_ref_graph();
        // Diameter is 3, so mindist=4 yields all zeros.
        assert_eq!(
            neighborhood_size_with_mode(&g, 4, NeighborhoodMode::All, 4).unwrap(),
            vec![0, 0, 0, 0, 0, 0]
        );
    }

    #[test]
    fn c_ref_infinite_order_out_mode() {
        let g = c_ref_graph();
        // C .out: ( 5 3 5 2 1 1 )
        assert_eq!(
            neighborhood_size_with_mode(&g, -1, NeighborhoodMode::Out, 0).unwrap(),
            vec![5, 3, 5, 2, 1, 1]
        );
    }

    #[test]
    fn c_ref_infinite_order_mindist_2_out_mode() {
        let g = c_ref_graph();
        // C .out: ( 2 1 2 0 0 0 )
        assert_eq!(
            neighborhood_size_with_mode(&g, -1, NeighborhoodMode::Out, 2).unwrap(),
            vec![2, 1, 2, 0, 0, 0]
        );
    }

    #[test]
    fn c_ref_infinite_order_mindist_2_in_mode() {
        let g = c_ref_graph();
        // C .out: ( 0 1 0 1 3 0 )
        assert_eq!(
            neighborhood_size_with_mode(&g, -1, NeighborhoodMode::In, 2).unwrap(),
            vec![0, 1, 0, 1, 3, 0]
        );
    }

    #[test]
    fn negative_mindist_errors() {
        let g = Graph::with_vertices(3);
        match neighborhood_size_with_mode(&g, 2, NeighborhoodMode::All, -1) {
            Err(IgraphError::InvalidArgument(msg)) => assert!(msg.contains("negative")),
            other => panic!("expected InvalidArgument for negative mindist, got {other:?}"),
        }
    }

    #[test]
    fn mindist_exceeding_finite_order_errors() {
        let g = Graph::with_vertices(3);
        match neighborhood_size_with_mode(&g, 2, NeighborhoodMode::All, 3) {
            Err(IgraphError::InvalidArgument(msg)) => assert!(msg.contains("exceed")),
            other => panic!("expected InvalidArgument for mindist > order, got {other:?}"),
        }
    }

    #[test]
    fn infinite_order_allows_any_mindist() {
        // mindist > vcount is fine when order is infinite.
        let mut g = Graph::with_vertices(3);
        g.add_edge(0, 1).unwrap();
        g.add_edge(1, 2).unwrap();
        // mindist=10: nobody is at distance >= 10 → all zeros.
        assert_eq!(
            neighborhood_size_with_mode(&g, -1, NeighborhoodMode::All, 10).unwrap(),
            vec![0, 0, 0]
        );
    }

    #[test]
    fn k4_complete_undirected_order_1() {
        let mut g = Graph::with_vertices(4);
        for u in 0..4 {
            for v in (u + 1)..4 {
                g.add_edge(u, v).unwrap();
            }
        }
        // Every vertex sees self + 3 neighbours.
        assert_eq!(neighborhood_size(&g, 1).unwrap(), vec![4, 4, 4, 4]);
    }

    #[test]
    fn directed_star_out_in_modes() {
        // 0 -> 1, 0 -> 2, 0 -> 3
        let mut g = Graph::new(4, true).unwrap();
        for v in [1, 2, 3] {
            g.add_edge(0, v).unwrap();
        }
        // Out: hub reaches all, leaves stay alone.
        assert_eq!(
            neighborhood_size_with_mode(&g, -1, NeighborhoodMode::Out, 0).unwrap(),
            vec![4, 1, 1, 1]
        );
        // In: leaves reach hub by reversed walk.
        assert_eq!(
            neighborhood_size_with_mode(&g, -1, NeighborhoodMode::In, 0).unwrap(),
            vec![1, 2, 2, 2]
        );
        // All: everything connected.
        assert_eq!(
            neighborhood_size_with_mode(&g, -1, NeighborhoodMode::All, 0).unwrap(),
            vec![4, 4, 4, 4]
        );
    }

    #[test]
    fn self_loop_does_not_inflate_count() {
        let mut g = Graph::with_vertices(3);
        g.add_edge(0, 0).unwrap();
        g.add_edge(0, 1).unwrap();
        g.add_edge(1, 2).unwrap();
        // Self-loop on 0: order 1 still {0, 1} → size 2.
        assert_eq!(neighborhood_size(&g, 1).unwrap(), vec![2, 3, 2]);
    }

    #[test]
    fn multi_edge_does_not_double_count() {
        let mut g = Graph::with_vertices(3);
        g.add_edge(0, 1).unwrap();
        g.add_edge(0, 1).unwrap();
        g.add_edge(1, 2).unwrap();
        assert_eq!(neighborhood_size(&g, 1).unwrap(), vec![2, 3, 2]);
    }

    #[test]
    fn mindist_equals_order_counts_frontier_only() {
        // P5: 0-1-2-3-4. order=2, mindist=2 → only vertices at distance 2.
        let mut g = Graph::with_vertices(5);
        for (u, v) in [(0, 1), (1, 2), (2, 3), (3, 4)] {
            g.add_edge(u, v).unwrap();
        }
        // d=2 ball for each vertex: 0→{2}, 1→{3}, 2→{0,4}, 3→{1}, 4→{2}.
        assert_eq!(
            neighborhood_size_with_mode(&g, 2, NeighborhoodMode::All, 2).unwrap(),
            vec![1, 1, 2, 1, 1]
        );
    }

    // ---- neighborhood (vertex lists) tests ----
    //
    // BFS visitation order depends on adjacency-list iteration, so it
    // differs subtly between Rust / C / Python. The semantically
    // meaningful claim is set equality, so all neighborhood tests sort
    // both sides before comparing.

    fn sorted(mut v: Vec<u32>) -> Vec<u32> {
        v.sort_unstable();
        v
    }

    fn sorted_all(nbh: Vec<Vec<u32>>) -> Vec<Vec<u32>> {
        nbh.into_iter().map(sorted).collect()
    }

    #[test]
    fn neighborhood_empty_graph_returns_empty() {
        let g = Graph::with_vertices(0);
        assert!(neighborhood(&g, 1).unwrap().is_empty());
    }

    #[test]
    fn neighborhood_singleton_order_0_is_self_only() {
        let g = Graph::with_vertices(1);
        assert_eq!(neighborhood(&g, 0).unwrap(), vec![vec![0]]);
        assert_eq!(neighborhood(&g, 5).unwrap(), vec![vec![0]]);
    }

    #[test]
    fn neighborhood_no_edges_returns_singletons() {
        let g = Graph::with_vertices(3);
        let n0 = neighborhood(&g, 0).unwrap();
        assert_eq!(n0, vec![vec![0], vec![1], vec![2]]);
        let n5 = neighborhood(&g, 5).unwrap();
        assert_eq!(n5, vec![vec![0], vec![1], vec![2]]);
    }

    #[test]
    fn neighborhood_p5_order_1_set_eq() {
        // P5: 0-1-2-3-4
        let mut g = Graph::with_vertices(5);
        for (u, v) in [(0, 1), (1, 2), (2, 3), (3, 4)] {
            g.add_edge(u, v).unwrap();
        }
        let got = sorted_all(neighborhood(&g, 1).unwrap());
        let exp: Vec<Vec<u32>> = vec![
            vec![0, 1],
            vec![0, 1, 2],
            vec![1, 2, 3],
            vec![2, 3, 4],
            vec![3, 4],
        ];
        assert_eq!(got, exp);
    }

    #[test]
    fn neighborhood_p5_order_2_set_eq() {
        let mut g = Graph::with_vertices(5);
        for (u, v) in [(0, 1), (1, 2), (2, 3), (3, 4)] {
            g.add_edge(u, v).unwrap();
        }
        let got = sorted_all(neighborhood(&g, 2).unwrap());
        let exp: Vec<Vec<u32>> = vec![
            vec![0, 1, 2],
            vec![0, 1, 2, 3],
            vec![0, 1, 2, 3, 4],
            vec![1, 2, 3, 4],
            vec![2, 3, 4],
        ];
        assert_eq!(got, exp);
    }

    #[test]
    fn neighborhood_c_ref_order_0_is_self_only() {
        // C .out: 0:(0) 1:(1) 2:(2) 3:(3) 4:(4) 5:(5)
        let g = c_ref_graph();
        let got = neighborhood(&g, 0).unwrap();
        let exp: Vec<Vec<u32>> = (0..6).map(|i| vec![i]).collect();
        assert_eq!(got, exp);
    }

    #[test]
    fn neighborhood_c_ref_order_1_all_set_eq() {
        // C .out: 0:(0 1 2) 1:(1 0 3) 2:(2 0 3) 3:(3 1 2 4) 4:(4 3) 5:(5)
        let g = c_ref_graph();
        let got = sorted_all(neighborhood(&g, 1).unwrap());
        let exp: Vec<Vec<u32>> = vec![
            vec![0, 1, 2],
            vec![0, 1, 3],
            vec![0, 2, 3],
            vec![1, 2, 3, 4],
            vec![3, 4],
            vec![5],
        ];
        assert_eq!(got, exp);
    }

    #[test]
    fn neighborhood_c_ref_order_1_in_set_eq() {
        // C .out: 0:(0 2) 1:(1 0) 2:(2 0) 3:(3 1 2) 4:(4 3) 5:(5)
        let g = c_ref_graph();
        let got = sorted_all(neighborhood_with_mode(&g, 1, NeighborhoodMode::In, 0).unwrap());
        let exp: Vec<Vec<u32>> = vec![
            vec![0, 2],
            vec![0, 1],
            vec![0, 2],
            vec![1, 2, 3],
            vec![3, 4],
            vec![5],
        ];
        assert_eq!(got, exp);
    }

    #[test]
    fn neighborhood_c_ref_order_10_all_saturates_set_eq() {
        // C .out: 0:(0 1 2 3 4) 1:(0 1 2 3 4) 2:(0 1 2 3 4) 3:(0 1 2 3 4)
        //         4:(0 1 2 3 4) 5:(5)
        let g = c_ref_graph();
        let got = sorted_all(neighborhood(&g, 10).unwrap());
        let big: Vec<u32> = (0..5).collect();
        let exp: Vec<Vec<u32>> = vec![
            big.clone(),
            big.clone(),
            big.clone(),
            big.clone(),
            big,
            vec![5],
        ];
        assert_eq!(got, exp);
    }

    #[test]
    fn neighborhood_c_ref_order_2_mindist_2_out_set_eq() {
        // C .out: 0:(3) 1:(4) 2:(1 4) 3:() 4:() 5:()
        let g = c_ref_graph();
        let got = sorted_all(neighborhood_with_mode(&g, 2, NeighborhoodMode::Out, 2).unwrap());
        let exp: Vec<Vec<u32>> = vec![vec![3], vec![4], vec![1, 4], vec![], vec![], vec![]];
        assert_eq!(got, exp);
    }

    #[test]
    fn neighborhood_c_ref_order_4_mindist_4_all_empty() {
        // Diameter < 4 ⇒ all empty.
        let g = c_ref_graph();
        let got = neighborhood_with_mode(&g, 4, NeighborhoodMode::All, 4).unwrap();
        let exp: Vec<Vec<u32>> = vec![vec![]; 6];
        assert_eq!(got, exp);
    }

    #[test]
    fn neighborhood_c_ref_infinite_order_out_set_eq() {
        // C .out: 0:(0 1 2 3 4) 1:(1 3 4) 2:(0 1 2 3 4) 3:(3 4) 4:(4) 5:(5)
        let g = c_ref_graph();
        let got = sorted_all(neighborhood_with_mode(&g, -1, NeighborhoodMode::Out, 0).unwrap());
        let exp: Vec<Vec<u32>> = vec![
            vec![0, 1, 2, 3, 4],
            vec![1, 3, 4],
            vec![0, 1, 2, 3, 4],
            vec![3, 4],
            vec![4],
            vec![5],
        ];
        assert_eq!(got, exp);
    }

    #[test]
    fn neighborhood_c_ref_infinite_mindist_2_out_set_eq() {
        // C .out: 0:(3 4) 1:(4) 2:(1 4) 3:() 4:() 5:()
        let g = c_ref_graph();
        let got = sorted_all(neighborhood_with_mode(&g, -1, NeighborhoodMode::Out, 2).unwrap());
        let exp: Vec<Vec<u32>> = vec![vec![3, 4], vec![4], vec![1, 4], vec![], vec![], vec![]];
        assert_eq!(got, exp);
    }

    #[test]
    fn neighborhood_c_ref_infinite_mindist_2_in_set_eq() {
        // C .out: 0:() 1:(2) 2:() 3:(0) 4:(0 1 2) 5:()
        let g = c_ref_graph();
        let got = sorted_all(neighborhood_with_mode(&g, -1, NeighborhoodMode::In, 2).unwrap());
        let exp: Vec<Vec<u32>> = vec![vec![], vec![2], vec![], vec![0], vec![0, 1, 2], vec![]];
        assert_eq!(got, exp);
    }

    #[test]
    fn neighborhood_negative_mindist_errors() {
        let g = Graph::with_vertices(3);
        match neighborhood_with_mode(&g, 2, NeighborhoodMode::All, -1) {
            Err(IgraphError::InvalidArgument(msg)) => assert!(msg.contains("negative")),
            other => panic!("expected InvalidArgument for negative mindist, got {other:?}"),
        }
    }

    #[test]
    fn neighborhood_mindist_exceeds_order_errors() {
        let g = Graph::with_vertices(3);
        match neighborhood_with_mode(&g, 2, NeighborhoodMode::All, 3) {
            Err(IgraphError::InvalidArgument(msg)) => assert!(msg.contains("exceed")),
            other => panic!("expected InvalidArgument, got {other:?}"),
        }
    }

    #[test]
    fn neighborhood_lengths_match_neighborhood_size() {
        // PR-027b list lengths should equal PR-027 sizes for any
        // (order, mode, mindist) triple — the two are tightly coupled.
        let g = c_ref_graph();
        for order in [0_i32, 1, 2, 3, 10, -1] {
            for &mode in &[
                NeighborhoodMode::Out,
                NeighborhoodMode::In,
                NeighborhoodMode::All,
            ] {
                for mindist in [0_i32, 1, 2] {
                    if order >= 0 && mindist > order {
                        continue;
                    }
                    let sizes = neighborhood_size_with_mode(&g, order, mode, mindist).unwrap();
                    let lists = neighborhood_with_mode(&g, order, mode, mindist).unwrap();
                    let list_lens: Vec<u32> = lists
                        .iter()
                        .map(|v| u32::try_from(v.len()).unwrap())
                        .collect();
                    assert_eq!(
                        sizes, list_lens,
                        "size/list-len mismatch at order={order} mode={mode:?} mindist={mindist}",
                    );
                }
            }
        }
    }

    #[test]
    fn neighborhood_self_loop_not_double_visited() {
        let mut g = Graph::with_vertices(3);
        g.add_edge(0, 0).unwrap();
        g.add_edge(0, 1).unwrap();
        g.add_edge(1, 2).unwrap();
        let got = sorted_all(neighborhood(&g, 1).unwrap());
        assert_eq!(got, vec![vec![0, 1], vec![0, 1, 2], vec![1, 2]]);
    }

    #[test]
    fn neighborhood_multi_edge_not_double_visited() {
        let mut g = Graph::with_vertices(3);
        g.add_edge(0, 1).unwrap();
        g.add_edge(0, 1).unwrap();
        g.add_edge(1, 2).unwrap();
        let got = sorted_all(neighborhood(&g, 1).unwrap());
        assert_eq!(got, vec![vec![0, 1], vec![0, 1, 2], vec![1, 2]]);
    }

    #[test]
    fn neighborhood_mindist_1_excludes_self() {
        // P5 order 1 mindist 1 → only neighbours, not self.
        let mut g = Graph::with_vertices(5);
        for (u, v) in [(0, 1), (1, 2), (2, 3), (3, 4)] {
            g.add_edge(u, v).unwrap();
        }
        let got = sorted_all(neighborhood_with_mode(&g, 1, NeighborhoodMode::All, 1).unwrap());
        assert_eq!(
            got,
            vec![vec![1], vec![0, 2], vec![1, 3], vec![2, 4], vec![3]]
        );
        for list in &got {
            for (i, neighbors) in got.iter().enumerate() {
                let i_u32 = u32::try_from(i).unwrap();
                if std::ptr::eq(list, neighbors) {
                    assert!(!list.contains(&i_u32), "mindist=1 should exclude self");
                }
            }
        }
    }

    // ---- neighborhood_graphs tests ----

    #[test]
    fn neighborhood_graphs_empty_graph() {
        let g = Graph::with_vertices(0);
        let gs = neighborhood_graphs(&g, 1).unwrap();
        assert!(gs.is_empty());
    }

    #[test]
    fn neighborhood_graphs_isolated_vertices() {
        let g = Graph::with_vertices(3);
        let gs = neighborhood_graphs(&g, 1).unwrap();
        assert_eq!(gs.len(), 3);
        for sub in &gs {
            assert_eq!(sub.vcount(), 1);
            assert_eq!(sub.ecount(), 0);
        }
    }

    #[test]
    fn neighborhood_graphs_path_order_1() {
        // Path: 0-1-2-3
        let mut g = Graph::with_vertices(4);
        g.add_edge(0, 1).unwrap();
        g.add_edge(1, 2).unwrap();
        g.add_edge(2, 3).unwrap();

        let gs = neighborhood_graphs(&g, 1).unwrap();
        assert_eq!(gs.len(), 4);
        // v=0: {0,1} → 1 edge
        assert_eq!(gs[0].vcount(), 2);
        assert_eq!(gs[0].ecount(), 1);
        // v=1: {0,1,2} → 2 edges (0-1, 1-2)
        assert_eq!(gs[1].vcount(), 3);
        assert_eq!(gs[1].ecount(), 2);
        // v=2: {1,2,3} → 2 edges
        assert_eq!(gs[2].vcount(), 3);
        assert_eq!(gs[2].ecount(), 2);
        // v=3: {2,3} → 1 edge
        assert_eq!(gs[3].vcount(), 2);
        assert_eq!(gs[3].ecount(), 1);
    }

    #[test]
    fn neighborhood_graphs_order_0_is_singletons() {
        let mut g = Graph::with_vertices(3);
        g.add_edge(0, 1).unwrap();
        g.add_edge(1, 2).unwrap();

        let gs = neighborhood_graphs(&g, 0).unwrap();
        assert_eq!(gs.len(), 3);
        for sub in &gs {
            assert_eq!(sub.vcount(), 1);
            assert_eq!(sub.ecount(), 0);
        }
    }

    #[test]
    fn neighborhood_graphs_complete_graph_order_1() {
        // K4: all vertices within 1 hop of each other
        let mut g = Graph::with_vertices(4);
        g.add_edge(0, 1).unwrap();
        g.add_edge(0, 2).unwrap();
        g.add_edge(0, 3).unwrap();
        g.add_edge(1, 2).unwrap();
        g.add_edge(1, 3).unwrap();
        g.add_edge(2, 3).unwrap();

        let gs = neighborhood_graphs(&g, 1).unwrap();
        assert_eq!(gs.len(), 4);
        for sub in &gs {
            // Every vertex's 1-hop neighbourhood is the whole graph
            assert_eq!(sub.vcount(), 4);
            assert_eq!(sub.ecount(), 6);
        }
    }

    #[test]
    fn neighborhood_graphs_directed_out_mode() {
        // Star: 0->1, 0->2, 0->3
        let mut g = Graph::new(4, true).unwrap();
        g.add_edge(0, 1).unwrap();
        g.add_edge(0, 2).unwrap();
        g.add_edge(0, 3).unwrap();

        let gs = neighborhood_graphs_with_mode(&g, 1, NeighborhoodMode::Out, 0).unwrap();
        assert_eq!(gs.len(), 4);
        // v=0 out-1-hop: {0,1,2,3}, induced subgraph has all 3 edges
        assert_eq!(gs[0].vcount(), 4);
        assert_eq!(gs[0].ecount(), 3);
        // v=1 out-1-hop: {1} only
        assert_eq!(gs[1].vcount(), 1);
        assert_eq!(gs[1].ecount(), 0);
    }

    #[test]
    fn neighborhood_graphs_directed_in_mode() {
        // Star: 0->1, 0->2, 0->3
        let mut g = Graph::new(4, true).unwrap();
        g.add_edge(0, 1).unwrap();
        g.add_edge(0, 2).unwrap();
        g.add_edge(0, 3).unwrap();

        let gs = neighborhood_graphs_with_mode(&g, 1, NeighborhoodMode::In, 0).unwrap();
        // v=0 in-1-hop: {0} only (no in-edges)
        assert_eq!(gs[0].vcount(), 1);
        assert_eq!(gs[0].ecount(), 0);
        // v=1 in-1-hop: {0,1} (0->1 edge exists)
        assert_eq!(gs[1].vcount(), 2);
        assert_eq!(gs[1].ecount(), 1);
    }

    #[test]
    fn neighborhood_graphs_mindist_excludes_close_vertices() {
        // Path: 0-1-2-3
        let mut g = Graph::with_vertices(4);
        g.add_edge(0, 1).unwrap();
        g.add_edge(1, 2).unwrap();
        g.add_edge(2, 3).unwrap();

        // mindist=1, order=2: exclude self, include dist 1 and 2
        let gs = neighborhood_graphs_with_mode(&g, 2, NeighborhoodMode::All, 1).unwrap();
        // v=0: mindist=1, order=2 → {1, 2}; induced subgraph has edge 1-2
        assert_eq!(gs[0].vcount(), 2);
        assert_eq!(gs[0].ecount(), 1);
        // v=1: mindist=1, order=2 → {0, 2, 3}; edges: 2-3 (0-1 and 1-2 don't survive without 1)
        // Wait — vertex 1 is excluded (mindist=1), so {0, 2, 3}
        // Edges between {0,2,3}: only 2-3
        assert_eq!(gs[1].vcount(), 3);
        assert_eq!(gs[1].ecount(), 1);
    }

    #[test]
    fn neighborhood_graphs_infinite_order_returns_full_component() {
        // Two components: {0,1,2}, {3,4}
        let mut g = Graph::with_vertices(5);
        g.add_edge(0, 1).unwrap();
        g.add_edge(1, 2).unwrap();
        g.add_edge(3, 4).unwrap();

        let gs = neighborhood_graphs(&g, -1).unwrap();
        // v=0: reachable {0,1,2}, 2 edges
        assert_eq!(gs[0].vcount(), 3);
        assert_eq!(gs[0].ecount(), 2);
        // v=3: reachable {3,4}, 1 edge
        assert_eq!(gs[3].vcount(), 2);
        assert_eq!(gs[3].ecount(), 1);
    }

    #[test]
    fn neighborhood_graphs_preserves_directedness() {
        let mut g = Graph::new(3, true).unwrap();
        g.add_edge(0, 1).unwrap();
        g.add_edge(1, 2).unwrap();

        let gs = neighborhood_graphs_with_mode(&g, 1, NeighborhoodMode::All, 0).unwrap();
        for sub in &gs {
            assert!(sub.is_directed());
        }
    }
}