scirs2-graph 0.4.2

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
//! Streaming graph partitioning for large-scale graphs.
//!
//! When a graph is too large to fit in memory or arrives as a stream of
//! edges, streaming partitioners assign nodes to partitions in a single
//! pass. This module provides:
//!
//! - **LDG (Linear Deterministic Greedy)**: assigns each arriving vertex
//!   to the partition that maximizes the number of neighbors already present,
//!   penalized by partition size to maintain balance.
//! - **Hash partitioning**: simple baseline that assigns nodes by hash.

use scirs2_core::ndarray::Array2;

use crate::error::{GraphError, Result};

use super::types::{PartitionConfig, PartitionResult};

/// Linear Deterministic Greedy (LDG) streaming partitioner.
///
/// Processes nodes in order 0..n_nodes. For each node, it examines its
/// edges (among those already seen) and assigns the node to the partition
/// that maximizes:
///
///   score(p) = neighbors_in_p * (1 - |p| / capacity)
///
/// where capacity = ceil(n_nodes * (1 + balance_tolerance) / n_partitions).
///
/// # Arguments
/// * `edges` - Edge list as (src, dst) pairs. Both directions should be
///   included for undirected graphs.
/// * `n_nodes` - Total number of nodes (nodes are indexed 0..n_nodes).
/// * `config` - Partition configuration.
///
/// # Returns
/// A `PartitionResult` with partition assignments for all nodes.
///
/// # Errors
/// Returns `GraphError::InvalidParameter` if parameters are invalid.
pub fn streaming_partition(
    edges: &[(usize, usize)],
    n_nodes: usize,
    config: &PartitionConfig,
) -> Result<PartitionResult> {
    let k = config.n_partitions;

    if k < 2 {
        return Err(GraphError::InvalidParameter {
            param: "n_partitions".to_string(),
            value: format!("{}", k),
            expected: "at least 2".to_string(),
            context: "streaming_partition".to_string(),
        });
    }

    if n_nodes < 2 {
        return Err(GraphError::InvalidParameter {
            param: "n_nodes".to_string(),
            value: format!("{}", n_nodes),
            expected: "at least 2".to_string(),
            context: "streaming_partition".to_string(),
        });
    }

    if k > n_nodes {
        return Err(GraphError::InvalidParameter {
            param: "n_partitions".to_string(),
            value: format!("{}", k),
            expected: format!("at most {} (number of nodes)", n_nodes),
            context: "streaming_partition".to_string(),
        });
    }

    // Build adjacency list from edge list
    let mut adj_list: Vec<Vec<usize>> = vec![Vec::new(); n_nodes];
    for &(u, v) in edges {
        if u < n_nodes && v < n_nodes {
            adj_list[u].push(v);
        }
    }

    // Capacity per partition (with tolerance)
    let capacity =
        ((n_nodes as f64) * (1.0 + config.balance_tolerance) / (k as f64)).ceil() as usize;

    let mut assignments = vec![usize::MAX; n_nodes];
    let mut partition_sizes = vec![0usize; k];

    // Process nodes in order
    for node in 0..n_nodes {
        let mut best_partition = 0usize;
        let mut best_score = f64::NEG_INFINITY;

        for p in 0..k {
            if partition_sizes[p] >= capacity {
                continue;
            }

            // Count neighbors already in partition p
            let neighbors_in_p = adj_list[node]
                .iter()
                .filter(|&&nbr| nbr < node && assignments[nbr] == p)
                .count();

            // LDG scoring: neighbors * (1 - load_factor)
            let load_factor = partition_sizes[p] as f64 / capacity as f64;
            let score = (neighbors_in_p as f64) * (1.0 - load_factor);

            // Tie-breaking: prefer less-loaded partition
            if score > best_score
                || (score == best_score && partition_sizes[p] < partition_sizes[best_partition])
            {
                best_score = score;
                best_partition = p;
            }
        }

        assignments[node] = best_partition;
        partition_sizes[best_partition] += 1;
    }

    // Compute edge cut
    let mut edge_cut = 0usize;
    let mut seen_edges = std::collections::HashSet::new();
    for &(u, v) in edges {
        if u < n_nodes && v < n_nodes && u != v {
            let key = if u < v { (u, v) } else { (v, u) };
            if seen_edges.insert(key) && assignments[u] != assignments[v] {
                edge_cut += 1;
            }
        }
    }

    // Compute imbalance
    let ideal = n_nodes as f64 / k as f64;
    let imbalance = if ideal > 0.0 {
        partition_sizes
            .iter()
            .map(|&s| ((s as f64) - ideal).abs() / ideal)
            .fold(0.0f64, f64::max)
    } else {
        0.0
    };

    Ok(PartitionResult {
        assignments,
        edge_cut,
        partition_sizes,
        imbalance,
    })
}

/// Hash-based streaming partition (baseline).
///
/// Assigns each node to partition `node % n_partitions`. This is the simplest
/// possible partitioner and serves as a baseline for comparison.
///
/// # Arguments
/// * `n_nodes` - Number of nodes (0-indexed).
/// * `n_partitions` - Number of partitions.
///
/// # Returns
/// A `PartitionResult` with uniform (or near-uniform) partition sizes.
pub fn hash_partition(n_nodes: usize, n_partitions: usize) -> PartitionResult {
    let mut assignments = vec![0usize; n_nodes];
    let mut partition_sizes = vec![0usize; n_partitions];

    for i in 0..n_nodes {
        let p = i % n_partitions;
        assignments[i] = p;
        partition_sizes[p] += 1;
    }

    let ideal = n_nodes as f64 / n_partitions as f64;
    let imbalance = if ideal > 0.0 {
        partition_sizes
            .iter()
            .map(|&s| ((s as f64) - ideal).abs() / ideal)
            .fold(0.0f64, f64::max)
    } else {
        0.0
    };

    PartitionResult {
        assignments,
        edge_cut: 0, // Not computed without adjacency info
        partition_sizes,
        imbalance,
    }
}

/// Evaluate a partition against an adjacency matrix.
///
/// Computes the edge cut (number of edges crossing partitions) and
/// the imbalance ratio.
///
/// # Arguments
/// * `adj` - Symmetric adjacency matrix (n x n).
/// * `assignments` - Partition assignment for each node.
/// * `n_partitions` - Number of partitions.
///
/// # Returns
/// A tuple `(edge_cut, imbalance)`.
pub fn evaluate_partition(
    adj: &Array2<f64>,
    assignments: &[usize],
    n_partitions: usize,
) -> (usize, f64) {
    let n = adj.nrows().min(assignments.len());

    let mut partition_sizes = vec![0usize; n_partitions];
    for &a in &assignments[..n] {
        if a < n_partitions {
            partition_sizes[a] += 1;
        }
    }

    let mut edge_cut = 0usize;
    for i in 0..n {
        for j in (i + 1)..n {
            if adj[[i, j]].abs() > 1e-15 && assignments[i] != assignments[j] {
                edge_cut += 1;
            }
        }
    }

    let ideal = n as f64 / n_partitions as f64;
    let imbalance = if ideal > 0.0 {
        partition_sizes
            .iter()
            .map(|&s| ((s as f64) - ideal).abs() / ideal)
            .fold(0.0f64, f64::max)
    } else {
        0.0
    };

    (edge_cut, imbalance)
}

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

    /// Build edge list for two cliques connected by a bridge.
    fn two_cliques_edges(n: usize) -> (Vec<(usize, usize)>, usize) {
        let size = 2 * n;
        let mut edges = Vec::new();
        // Clique 1
        for i in 0..n {
            for j in (i + 1)..n {
                edges.push((i, j));
                edges.push((j, i));
            }
        }
        // Clique 2
        for i in n..size {
            for j in (i + 1)..size {
                edges.push((i, j));
                edges.push((j, i));
            }
        }
        // Bridge
        edges.push((n - 1, n));
        edges.push((n, n - 1));
        (edges, size)
    }

    #[test]
    fn test_ldg_better_than_hash_on_structured() {
        let (edges, n_nodes) = two_cliques_edges(6);
        let config = PartitionConfig {
            n_partitions: 2,
            balance_tolerance: 0.1,
            ..PartitionConfig::default()
        };

        let ldg_result = streaming_partition(&edges, n_nodes, &config).expect("LDG should succeed");

        // Build adjacency matrix for evaluation
        let mut adj = Array2::<f64>::zeros((n_nodes, n_nodes));
        for &(u, v) in &edges {
            adj[[u, v]] = 1.0;
        }

        let hash_result = hash_partition(n_nodes, 2);
        let (hash_cut, _) = evaluate_partition(&adj, &hash_result.assignments, 2);

        // LDG should achieve a lower or equal edge cut on structured graphs
        assert!(
            ldg_result.edge_cut <= hash_cut + 2,
            "LDG edge cut ({}) should be competitive with hash ({})",
            ldg_result.edge_cut,
            hash_cut
        );
    }

    #[test]
    fn test_hash_uniform_sizes() {
        let n_nodes = 100;
        let k = 4;
        let result = hash_partition(n_nodes, k);
        assert_eq!(result.partition_sizes.len(), k);
        // Each partition should have 25 nodes
        for &s in &result.partition_sizes {
            assert_eq!(s, 25);
        }
        assert!(result.imbalance < 1e-10);
    }

    #[test]
    fn test_hash_near_uniform_sizes() {
        let n_nodes = 10;
        let k = 3;
        let result = hash_partition(n_nodes, k);
        assert_eq!(result.partition_sizes.len(), k);
        // Sizes should be 4, 3, 3 or similar
        let total: usize = result.partition_sizes.iter().sum();
        assert_eq!(total, n_nodes);
        for &s in &result.partition_sizes {
            assert!((3..=4).contains(&s));
        }
    }

    #[test]
    fn test_evaluate_partition() {
        let n = 4;
        let mut adj = Array2::<f64>::zeros((n, n));
        adj[[0, 1]] = 1.0;
        adj[[1, 0]] = 1.0;
        adj[[2, 3]] = 1.0;
        adj[[3, 2]] = 1.0;
        adj[[1, 2]] = 1.0;
        adj[[2, 1]] = 1.0;

        let assignments = vec![0, 0, 1, 1];
        let (cut, imbalance) = evaluate_partition(&adj, &assignments, 2);
        assert_eq!(cut, 1); // only edge 1-2 crosses
        assert!(imbalance < 1e-10);
    }

    #[test]
    fn test_single_node_trivial() {
        // Edge case: 2 nodes, 2 partitions
        let edges = vec![(0, 1), (1, 0)];
        let config = PartitionConfig {
            n_partitions: 2,
            balance_tolerance: 0.5,
            ..PartitionConfig::default()
        };
        let result = streaming_partition(&edges, 2, &config).expect("should succeed");
        assert_eq!(result.assignments.len(), 2);
        // Both nodes should be assigned (valid partition IDs)
        assert!(result.assignments[0] < 2);
        assert!(result.assignments[1] < 2);
        // Total nodes accounted for
        let total: usize = result.partition_sizes.iter().sum();
        assert_eq!(total, 2);
    }

    #[test]
    fn test_streaming_invalid_params() {
        let config = PartitionConfig {
            n_partitions: 1,
            ..PartitionConfig::default()
        };
        assert!(streaming_partition(&[], 10, &config).is_err());

        let config2 = PartitionConfig {
            n_partitions: 5,
            ..PartitionConfig::default()
        };
        assert!(streaming_partition(&[], 3, &config2).is_err());
    }

    #[test]
    fn test_edge_cut_computable() {
        let (edges, n_nodes) = two_cliques_edges(4);
        let mut adj = Array2::<f64>::zeros((n_nodes, n_nodes));
        for &(u, v) in &edges {
            adj[[u, v]] = 1.0;
        }

        let config = PartitionConfig {
            n_partitions: 2,
            balance_tolerance: 0.2,
            ..PartitionConfig::default()
        };
        let result = streaming_partition(&edges, n_nodes, &config).expect("should succeed");

        // Verify edge cut matches evaluate_partition
        let (eval_cut, _) = evaluate_partition(&adj, &result.assignments, 2);
        assert_eq!(result.edge_cut, eval_cut);
    }
}

// ============================================================================
// Stateful streaming partitioner with FENNEL / Hashing / LDG backends
// ============================================================================

/// Algorithm variant for the stateful streaming partitioner.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum StreamingPartitionAlgorithm {
    /// FENNEL: minimize edge cut + imbalance penalty, vertex streaming.
    /// Score for partition p: `|N(v) ∩ Vp| - γ · |Vp|^α`.
    Fennel,
    /// Consistent hashing baseline: `v % k`.
    Hashing,
    /// Linear Deterministic Greedy: `|N(v) ∩ Vp| · (1 - |Vp| / cap)`.
    LinearDeterministic,
}

/// Configuration for the stateful streaming partitioner.
#[derive(Debug, Clone)]
pub struct StreamingPartitionConfig {
    /// Number of target partitions. Must be >= 2.
    pub n_parts: usize,
    /// Algorithm variant. Default: `Fennel`.
    pub algorithm: StreamingPartitionAlgorithm,
    /// Balance penalty weight γ for FENNEL. Default 1.5.
    pub gamma: f64,
    /// FENNEL exponent α (default 1.5, higher = stronger balance enforcement).
    /// Set to 0.0 to auto-compute from graph density.
    pub alpha: f64,
}

impl Default for StreamingPartitionConfig {
    fn default() -> Self {
        Self {
            n_parts: 2,
            algorithm: StreamingPartitionAlgorithm::Fennel,
            gamma: 1.5,
            alpha: 1.5,
        }
    }
}

/// A stateful online streaming partitioner.
///
/// Nodes arrive one at a time (with their adjacency list as observed so far).
/// Each call to [`assign_vertex`](StreamingPartitioner::assign_vertex) makes an
/// irrevocable assignment based on already-assigned neighbors.
///
/// # Example
///
/// ```rust,no_run
/// use scirs2_graph::partitioning::{StreamingPartitioner, StreamingPartitionConfig, StreamingPartitionAlgorithm};
///
/// let config = StreamingPartitionConfig { n_parts: 3, ..Default::default() };
/// let mut sp = StreamingPartitioner::new(10, config);
/// // Assign node 0 with no neighbors yet
/// let part = sp.assign_vertex(0, &[]);
/// assert!(part < 3);
/// ```
pub struct StreamingPartitioner {
    config: StreamingPartitionConfig,
    /// Partition assignment for each node; `None` means not yet assigned.
    partition: Vec<Option<usize>>,
    /// Number of nodes in each partition.
    part_sizes: Vec<usize>,
    /// Total nodes processed so far.
    n_assigned: usize,
}

impl StreamingPartitioner {
    /// Create a new streaming partitioner for `n_nodes` nodes.
    pub fn new(n_nodes: usize, config: StreamingPartitionConfig) -> Self {
        let k = config.n_parts;
        Self {
            config,
            partition: vec![None; n_nodes],
            part_sizes: vec![0usize; k],
            n_assigned: 0,
        }
    }

    /// Assign vertex `v` to a partition given its (already-known) neighbors.
    ///
    /// Only neighbors whose partition is already determined influence the score.
    /// Returns the assigned partition ID.
    pub fn assign_vertex(&mut self, v: usize, neighbors: &[(usize, f64)]) -> usize {
        if v >= self.partition.len() {
            // Grow if needed
            self.partition.resize(v + 1, None);
        }

        // If already assigned, return current assignment
        if let Some(p) = self.partition[v] {
            return p;
        }

        let k = self.config.n_parts;
        let n_total = self.partition.len().max(1);
        // Capacity with 5% slack
        let cap = ((n_total as f64 * 1.05) / k as f64).ceil() as usize;

        let best_p = match self.config.algorithm {
            StreamingPartitionAlgorithm::Hashing => v % k,
            StreamingPartitionAlgorithm::LinearDeterministic => {
                let mut best = 0usize;
                let mut best_score = f64::NEG_INFINITY;
                for p in 0..k {
                    if self.part_sizes[p] >= cap {
                        continue;
                    }
                    let nbrs_in_p: f64 = neighbors
                        .iter()
                        .filter(|&&(nb, _)| {
                            nb < self.partition.len() && self.partition[nb] == Some(p)
                        })
                        .map(|&(_, w)| w)
                        .sum();
                    let load = self.part_sizes[p] as f64 / cap as f64;
                    let score = nbrs_in_p * (1.0 - load);
                    if score > best_score
                        || (score == best_score && self.part_sizes[p] < self.part_sizes[best])
                    {
                        best_score = score;
                        best = p;
                    }
                }
                best
            }
            StreamingPartitionAlgorithm::Fennel => {
                // FENNEL score: |N(v) ∩ Vp| - γ · |Vp|^α
                let gamma = self.config.gamma;
                let alpha = if self.config.alpha <= 0.0 {
                    // Auto: sqrt(k) / n gives good defaults
                    (k as f64).sqrt() / (n_total as f64).max(1.0)
                } else {
                    self.config.alpha
                };

                let mut best = 0usize;
                let mut best_score = f64::NEG_INFINITY;
                for p in 0..k {
                    if self.part_sizes[p] >= cap {
                        continue;
                    }
                    let nbrs_in_p: f64 = neighbors
                        .iter()
                        .filter(|&&(nb, _)| {
                            nb < self.partition.len() && self.partition[nb] == Some(p)
                        })
                        .map(|&(_, w)| w)
                        .sum();
                    let penalty = gamma * (self.part_sizes[p] as f64).powf(alpha);
                    let score = nbrs_in_p - penalty;
                    if score > best_score
                        || (score == best_score && self.part_sizes[p] < self.part_sizes[best])
                    {
                        best_score = score;
                        best = p;
                    }
                }
                best
            }
        };

        self.partition[v] = Some(best_p);
        self.part_sizes[best_p] += 1;
        self.n_assigned += 1;
        best_p
    }

    /// Return the current partition assignments (`None` = not yet assigned).
    pub fn current_partition(&self) -> &[Option<usize>] {
        &self.partition
    }

    /// Estimate the edge cut from the current partition state.
    ///
    /// Only counts edges where both endpoints are assigned and in different parts.
    /// Counts each undirected edge once.
    pub fn edge_cut_estimate(&self, adj: &[Vec<(usize, f64)>]) -> usize {
        let mut cut = 0usize;
        for (i, nbrs) in adj.iter().enumerate() {
            let pi = match self.partition.get(i).copied().flatten() {
                Some(p) => p,
                None => continue,
            };
            for &(j, _) in nbrs {
                if j <= i {
                    continue; // count each edge once
                }
                let pj = match self.partition.get(j).copied().flatten() {
                    Some(p) => p,
                    None => continue,
                };
                if pi != pj {
                    cut += 1;
                }
            }
        }
        cut
    }
}

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

    fn build_path_adj(n: usize) -> Vec<Vec<(usize, f64)>> {
        let mut adj = vec![vec![]; n];
        for i in 0..(n - 1) {
            adj[i].push((i + 1, 1.0));
            adj[i + 1].push((i, 1.0));
        }
        adj
    }

    #[test]
    fn test_streaming_fennel_assignment() {
        let n = 20;
        let adj = build_path_adj(n);
        let config = StreamingPartitionConfig {
            n_parts: 4,
            algorithm: StreamingPartitionAlgorithm::Fennel,
            ..StreamingPartitionConfig::default()
        };
        let mut sp = StreamingPartitioner::new(n, config);

        for i in 0..n {
            let nbrs: Vec<(usize, f64)> = adj[i].clone();
            let p = sp.assign_vertex(i, &nbrs);
            assert!(p < 4, "part {} out of range", p);
        }

        // All nodes assigned
        for opt in sp.current_partition() {
            assert!(opt.is_some(), "node should be assigned");
        }
    }

    #[test]
    fn test_streaming_hashing_uniform() {
        let n = 100;
        let config = StreamingPartitionConfig {
            n_parts: 4,
            algorithm: StreamingPartitionAlgorithm::Hashing,
            ..StreamingPartitionConfig::default()
        };
        let mut sp = StreamingPartitioner::new(n, config);
        for i in 0..n {
            sp.assign_vertex(i, &[]);
        }
        // Each part should have exactly 25 nodes
        for &s in &sp.part_sizes {
            assert_eq!(s, 25, "hash partition should be uniform");
        }
    }

    #[test]
    fn test_streaming_ldg_assigns_all() {
        let n = 30;
        let adj = build_path_adj(n);
        let config = StreamingPartitionConfig {
            n_parts: 3,
            algorithm: StreamingPartitionAlgorithm::LinearDeterministic,
            ..StreamingPartitionConfig::default()
        };
        let mut sp = StreamingPartitioner::new(n, config);
        for i in 0..n {
            let nbrs = adj[i].clone();
            let p = sp.assign_vertex(i, &nbrs);
            assert!(p < 3);
        }
        let total: usize = sp.part_sizes.iter().sum();
        assert_eq!(total, n);
    }

    #[test]
    fn test_streaming_edge_cut_estimate() {
        let n = 10;
        let adj = build_path_adj(n);
        let config = StreamingPartitionConfig {
            n_parts: 2,
            algorithm: StreamingPartitionAlgorithm::Fennel,
            ..StreamingPartitionConfig::default()
        };
        let mut sp = StreamingPartitioner::new(n, config);
        for i in 0..n {
            let nbrs = adj[i].clone();
            sp.assign_vertex(i, &nbrs);
        }
        let cut = sp.edge_cut_estimate(&adj);
        // For a path of 10 split into 2, cut should be small (1-3 edges)
        assert!(cut <= n, "edge cut {} should be <= n={}", cut, n);
    }
}