crates/kleene-graph/tests/flow.rs
//! Maximum flow: push-relabel rounds on the workers (Dinic's phases to finish) against
//! Edmonds-Karp on one thread, on hand-made graphs, generated ones and the edge cases. Each answer is also
//! checked as a flow (within the capacities, conserved at every vertex but the ends) whose
//! value is the capacity of the cut it names (so it is maximum).
use std::collections::VecDeque;
use arrow_buffer::ScalarBuffer;
use kleene_graph::{GraphError, MaxFlow, MaxFlowF64, max_flow, max_flow_f64};
use kleene_sparse::{CpuDevice, Csr};
fn devices() -> [CpuDevice; 3] {
[
CpuDevice::new(1),
CpuDevice::new(4).with_grain(8),
CpuDevice::new(7),
]
}
/// A matrix of the arcs as given, rows by tail, the given order within a row (repeats
/// kept: parallel arcs).
fn raw(n: usize, arcs: &[(u32, u32, u64)]) -> Csr<u64> {
let mut rows: Vec<Vec<(u32, u64)>> = vec![Vec::new(); n];
for &(u, v, c) in arcs {
rows[u as usize].push((v, c));
}
let mut off = vec![0u64];
let (mut idx, mut val) = (Vec::new(), Vec::new());
for r in rows {
for (v, c) in r {
idx.push(v);
val.push(c);
}
off.push(idx.len() as u64);
}
Csr::new(
n,
n,
ScalarBuffer::from(off),
ScalarBuffer::from(idx),
Some(ScalarBuffer::from(val)),
)
.unwrap()
}
/// Edmonds-Karp on a dense residual matrix (parallel arcs summed): the flow value.
fn edmonds_karp(a: &Csr<u64>, s: usize, t: usize) -> u128 {
let n = a.nrows();
let mut r = vec![vec![0u128; n]; n];
let off = a.pattern().offsets();
let idx = a.pattern().indices();
for u in 0..n {
for e in off[u] as usize..off[u + 1] as usize {
let v = idx[e] as usize;
if v != u {
r[u][v] += u128::from(a.values().map_or(1, |x| x[e]));
}
}
}
let mut value = 0;
loop {
let mut prev = vec![usize::MAX; n];
prev[s] = s;
let mut q = VecDeque::from([s]);
while let Some(u) = q.pop_front() {
for v in 0..n {
if prev[v] == usize::MAX && r[u][v] > 0 {
prev[v] = u;
q.push_back(v);
}
}
}
if prev[t] == usize::MAX {
return value;
}
let mut push = u128::MAX;
let mut v = t;
while v != s {
push = push.min(r[prev[v]][v]);
v = prev[v];
}
let mut v = t;
while v != s {
r[prev[v]][v] -= push;
r[v][prev[v]] += push;
v = prev[v];
}
value += push;
}
}
/// The answer is a flow of its value, and the cut it names has that capacity.
fn certify(name: &str, a: &Csr<u64>, s: u32, t: u32, f: &MaxFlow) {
let n = a.nrows();
let off = a.pattern().offsets();
let idx = a.pattern().indices();
let cap = |e: usize| a.values().map_or(1, |x| x[e]);
assert_eq!(f.flow.len(), a.nnz(), "{name}");
assert_eq!(f.source_side.len(), n, "{name}");
let mut net = vec![0i128; n];
let mut cut = 0u128;
for u in 0..n {
for e in off[u] as usize..off[u + 1] as usize {
let v = idx[e] as usize;
assert!(f.flow[e] <= cap(e), "{name}: entry {e} over its capacity");
if v == u {
assert_eq!(f.flow[e], 0, "{name}: a self-loop carries nothing");
continue;
}
net[u] -= i128::from(f.flow[e]);
net[v] += i128::from(f.flow[e]);
match (f.source_side[u], f.source_side[v]) {
(true, false) => {
assert_eq!(f.flow[e], cap(e), "{name}: a cut arc is full");
cut += u128::from(cap(e));
}
(false, true) => assert_eq!(f.flow[e], 0, "{name}: a cut arc back is empty"),
_ => {}
}
}
}
for (v, &x) in net.iter().enumerate() {
if v as u32 != s && v as u32 != t {
assert_eq!(x, 0, "{name}: conserved at {v}");
}
}
assert_eq!(
net[t as usize], f.value as i128,
"{name}: the value reaches the target"
);
assert!(
f.source_side[s as usize] && !f.source_side[t as usize],
"{name}"
);
assert_eq!(cut, f.value, "{name}: the cut's capacity is the value");
}
fn check(name: &str, a: &Csr<u64>, s: u32, t: u32) -> u128 {
let want = if a.nrows() <= 800 {
Some(edmonds_karp(a, s as usize, t as usize))
} else {
None
};
let mut first: Option<MaxFlow> = None;
for cpu in devices() {
let f = max_flow(a, s, t, &cpu).unwrap();
if let Some(w) = want {
assert_eq!(f.value, w, "{name} {s}->{t} on {} threads", cpu.threads());
}
certify(name, a, s, t, &f);
// push-relabel ran: a round at least when anything flows, Dinic only to finish
if f.value > 0 {
assert!(
f.rounds > 0,
"{name}: push-relabel rounds on {} threads",
cpu.threads()
);
}
// the value is the same whatever the workers (the flow on each arc may differ)
if let Some(g) = &first {
assert_eq!(
f.value,
g.value,
"{name}: the same on {} threads",
cpu.threads()
);
assert_eq!(
f.source_side,
g.source_side,
"{name}: the cut on {} threads",
cpu.threads()
);
}
first = Some(f);
}
first.unwrap().value
}
/// Arcs from a fixed seed, capacities in `0..range` (some zero), hubs for skewed degrees.
fn generated(n: u32, m: usize, range: u64, seed: u64) -> Vec<(u32, u32, u64)> {
let mut x = seed;
let mut next = move || {
x ^= x << 13;
x ^= x >> 7;
x ^= x << 17;
x
};
(0..m)
.map(|_| {
let a = (next() % u64::from(n)) as u32;
let b = if next() % 4 == 0 {
(next() % 8) as u32
} else {
(next() % u64::from(n)) as u32
};
(a, b, next() % range)
})
.collect()
}
#[test]
fn hand_made_flows() {
// the textbook network (CLRS 26.1): 23 from 0 to 5
let g = raw(
6,
&[
(0, 1, 16),
(0, 2, 13),
(1, 3, 12),
(2, 1, 4),
(2, 4, 14),
(3, 2, 9),
(3, 5, 20),
(4, 3, 7),
(4, 5, 4),
],
);
assert_eq!(check("clrs", &g, 0, 5), 23);
let f = max_flow(&g, 0, 5, &CpuDevice::new(2)).unwrap();
assert_eq!(
f.source_side,
vec![true, true, true, false, true, false],
"the cut {{0, 1, 2, 4}}: 12 + 7 + 4"
);
// backwards it is another problem
check("clrs back", &g, 5, 0);
// a path that needs an arc undone: 0->1->2->3 first, then 0->2, 1->3
let g = raw(4, &[(0, 1, 1), (1, 2, 1), (2, 3, 1), (0, 2, 1), (1, 3, 1)]);
assert_eq!(check("undo", &g, 0, 3), 2);
}
#[test]
fn parallel_arcs_zero_capacities_and_loops() {
// three arcs 0->1 (one of 0), a self-loop, 1->2 twice, an arc back 2->0
let g = raw(
3,
&[
(0, 1, 4),
(0, 1, 0),
(0, 1, 3),
(0, 0, 9),
(1, 2, 2),
(1, 2, 6),
(2, 0, 5),
],
);
assert_eq!(check("parallel", &g, 0, 2), 7);
let f = max_flow(&g, 0, 2, &CpuDevice::new(3)).unwrap();
assert_eq!(f.flow[1], 0, "the zero arc");
assert_eq!(f.flow[3], 0, "the self-loop");
assert_eq!(f.flow[0] + f.flow[2], 7);
// every capacity zero: nothing flows, only the source on its side
let z = raw(3, &[(0, 1, 0), (1, 2, 0)]);
let f = max_flow(&z, 0, 2, &CpuDevice::new(2)).unwrap();
assert_eq!(f.value, 0);
assert_eq!(f.source_side, vec![true, false, false]);
assert_eq!(f.phases, 0);
}
#[test]
fn no_path_from_source_to_target() {
// 0 -> 1 -> 2, 3 apart; and 2 -> 0 only one way
let g = raw(4, &[(0, 1, 5), (1, 2, 5), (3, 3, 1)]);
assert_eq!(check("apart", &g, 0, 3), 0);
assert_eq!(check("against the arcs", &g, 2, 0), 0);
let f = max_flow(&g, 0, 3, &CpuDevice::new(2)).unwrap();
assert_eq!(f.source_side, vec![true, true, true, false]);
}
#[test]
fn generated_networks() {
for (n, m, range, seed) in [
(60u32, 400usize, 10u64, 1u64),
(300, 3000, 100, 2),
(700, 6000, 1000, 3),
(500, 2500, 2, 4),
] {
let g = raw(n as usize, &generated(n, m, range, seed));
for (s, t) in [(0, n - 1), (1, 2), (n / 2, 0), (5, 3)] {
check(&format!("n {n} m {m} range {range}"), &g, s, t);
}
}
// large: certified only (frontiers past one piece, many phases)
let g = raw(60000, &generated(60000, 400000, 50, 7));
let v = check("large", &g, 0, 59999);
assert!(v > 0);
// a long grid: deep level searches
let side = 120u32;
let mut arcs = Vec::new();
for r in 0..side {
for c in 0..side {
let v = r * side + c;
if c + 1 < side {
arcs.push((v, v + 1, u64::from((v * 7) % 9 + 1)));
arcs.push((v + 1, v, u64::from((v * 5) % 4)));
}
if r + 1 < side {
arcs.push((v, v + side, u64::from((v * 3) % 7 + 1)));
}
}
}
check(
"grid",
&raw((side * side) as usize, &arcs),
0,
side * side - 1,
);
}
#[test]
fn structural_and_narrow_capacities() {
// no values: each arc 1, so the flow counts arc-disjoint paths
let (s, d): (Vec<u32>, Vec<u32>) =
[(0u32, 1u32), (0, 2), (0, 3), (1, 4), (2, 4), (3, 1), (2, 3)]
.into_iter()
.unzip();
let g = Csr::<u8>::from_edges(5, 5, &s, &d, None, kleene_sparse::BoolOrAnd).unwrap();
assert_eq!(max_flow(&g, 0, 4, &CpuDevice::new(2)).unwrap().value, 2);
let w: Vec<u32> = vec![3, 1, 4, 1, 5, 9, 2];
let g = Csr::<u32>::from_edges(
5,
5,
&s,
&d,
Some(&w),
kleene_sparse::PlusTimes::<u32>::new(),
)
.unwrap();
// 0->1->4 (1), 0->2->4 (1); 0->3->1 adds nothing past 1->4
assert_eq!(max_flow(&g, 0, 4, &CpuDevice::new(2)).unwrap().value, 2);
// capacities near u64::MAX: the value is wider than one
let big = raw(
3,
&[
(0, 1, u64::MAX),
(0, 1, u64::MAX),
(1, 2, u64::MAX),
(1, 2, u64::MAX),
],
);
assert_eq!(
max_flow(&big, 0, 2, &CpuDevice::new(2)).unwrap().value,
2 * u128::from(u64::MAX)
);
}
#[test]
fn edge_cases_refused() {
let cpu = CpuDevice::new(2);
let g = raw(3, &[(0, 1, 1)]);
assert!(matches!(max_flow(&g, 1, 1, &cpu), Err(GraphError::Flow(_))));
assert!(matches!(
max_flow(&g, 0, 3, &cpu),
Err(GraphError::SourceOutOfRange { .. })
));
let empty = raw(0, &[]);
assert!(matches!(
max_flow(&empty, 0, 1, &cpu),
Err(GraphError::SourceOutOfRange { .. })
));
let one = raw(1, &[(0, 0, 3)]);
assert!(matches!(
max_flow(&one, 0, 0, &cpu),
Err(GraphError::Flow(_))
));
let wide = Csr::<u64>::new(
2,
3,
ScalarBuffer::from(vec![0u64, 0, 0]),
ScalarBuffer::from(Vec::<u32>::new()),
None,
)
.unwrap();
assert!(matches!(
max_flow(&wide, 0, 1, &cpu),
Err(GraphError::NotSquare { .. })
));
}
/// The matrix of `a` with each capacity `c` as the float `c / 2` (halves add exactly).
fn halves(a: &Csr<u64>) -> Csr<f64> {
let vals: Vec<f64> = a
.values()
.unwrap()
.iter()
.map(|&c| c as f64 / 2.0)
.collect();
Csr::new(
a.nrows(),
a.ncols(),
ScalarBuffer::from(a.pattern().offsets().to_vec()),
ScalarBuffer::from(a.pattern().indices().to_vec()),
Some(ScalarBuffer::from(vals)),
)
.unwrap()
}
/// A float answer is a flow of its value within `tol`, and its cut has that capacity.
fn certify_f64(name: &str, a: &Csr<f64>, s: u32, t: u32, f: &MaxFlowF64, tol: f64) {
let n = a.nrows();
let (off, idx, cap) = (
a.pattern().offsets(),
a.pattern().indices(),
a.values().unwrap(),
);
assert_eq!(f.flow.len(), a.nnz(), "{name}");
let mut net = vec![0f64; n];
let mut cut = 0f64;
for u in 0..n {
for e in off[u] as usize..off[u + 1] as usize {
let v = idx[e] as usize;
assert!(
f.flow[e] >= 0.0 && f.flow[e] <= cap[e] + tol,
"{name}: entry {e}"
);
if v == u {
assert_eq!(f.flow[e], 0.0, "{name}: a self-loop carries nothing");
continue;
}
net[u] -= f.flow[e];
net[v] += f.flow[e];
match (f.source_side[u], f.source_side[v]) {
(true, false) => {
assert!(
(f.flow[e] - cap[e]).abs() <= tol,
"{name}: a cut arc is full"
);
cut += cap[e];
}
(false, true) => assert!(f.flow[e] <= tol, "{name}: a cut arc back is empty"),
_ => {}
}
}
}
for (v, &x) in net.iter().enumerate() {
if v as u32 != s && v as u32 != t {
assert!(x.abs() <= tol * n as f64, "{name}: conserved at {v} ({x})");
}
}
assert!(
(net[t as usize] - f.value).abs() <= tol * n as f64,
"{name}: the value"
);
assert!(
(cut - f.value).abs() <= tol * n as f64,
"{name}: the cut's capacity"
);
}
#[test]
fn float_capacities() {
// halves of whole capacities: the float flow is half the whole one, exactly
for (n, m, range, seed) in [
(60u32, 400usize, 10u64, 1u64),
(300, 3000, 100, 2),
(700, 6000, 1000, 3),
] {
let g = raw(n as usize, &generated(n, m, range, seed));
let h = halves(&g);
for (s, t) in [(0, n - 1), (1, 2), (n / 2, 0)] {
let want = edmonds_karp(&g, s as usize, t as usize) as f64 / 2.0;
let mut first: Option<MaxFlowF64> = None;
for cpu in devices() {
let f = max_flow_f64(&h, s, t, &cpu).unwrap();
assert_eq!(f.value, want, "n {n} {s}->{t} on {} threads", cpu.threads());
certify_f64(&format!("n {n}"), &h, s, t, &f, 1e-9);
if f.value > 0.0 {
assert!(f.rounds > 0, "push-relabel rounds");
}
if let Some(g) = &first {
assert_eq!(
f.source_side,
g.source_side,
"the cut on {} threads",
cpu.threads()
);
}
first = Some(f);
}
}
}
// thirds: not exact in binary, within the tolerance of the sums
let g = raw(300, &generated(300, 3000, 100, 5));
let thirds: Vec<f64> = g
.values()
.unwrap()
.iter()
.map(|&c| c as f64 / 3.0)
.collect();
let h = Csr::new(
300,
300,
ScalarBuffer::from(g.pattern().offsets().to_vec()),
ScalarBuffer::from(g.pattern().indices().to_vec()),
Some(ScalarBuffer::from(thirds)),
)
.unwrap();
let want = edmonds_karp(&g, 0, 299) as f64 / 3.0;
let f = max_flow_f64(&h, 0, 299, &CpuDevice::new(4)).unwrap();
assert!(
(f.value - want).abs() <= 1e-9 * want.max(1.0),
"{} for {want}",
f.value
);
certify_f64("thirds", &h, 0, 299, &f, 1e-9);
// refused: a negative, infinite or NaN capacity; the source as the target
for bad in [-1.0, f64::INFINITY, f64::NAN] {
let a = Csr::new(
2,
2,
ScalarBuffer::from(vec![0u64, 1, 1]),
ScalarBuffer::from(vec![1u32]),
Some(ScalarBuffer::from(vec![bad])),
)
.unwrap();
assert!(
matches!(
max_flow_f64(&a, 0, 1, &CpuDevice::new(2)),
Err(GraphError::Flow(_))
),
"{bad}"
);
}
assert!(max_flow_f64(&h, 3, 3, &CpuDevice::new(2)).is_err());
// zero and below-tolerance capacities carry nothing; a self-loop nothing
let a = Csr::new(
3,
3,
ScalarBuffer::from(vec![0u64, 3, 4, 4]),
ScalarBuffer::from(vec![0u32, 1, 1, 2]),
Some(ScalarBuffer::from(vec![5.0, 0.0, 2.5, 1.25])),
)
.unwrap();
let f = max_flow_f64(&a, 0, 2, &CpuDevice::new(2)).unwrap();
assert_eq!(f.value, 1.25);
assert_eq!(f.flow, vec![0.0, 0.0, 1.25, 1.25]);
}