crates/kleene-graph/tests/spanning.rs
//! Minimum spanning forest: Borůvka's rounds on the workers against Kruskal's on one thread,
//! on hand-made graphs, generated ones and the edge cases. In Kruskal's order (weight, then
//! entry place) the forest must be the same edges; with ties broken the other way it must
//! have the same total.
use arrow_buffer::ScalarBuffer;
use kleene_graph::{ForestWeight, GraphError, spanning_forest};
use kleene_sparse::{CpuDevice, Csr, Value};
fn devices() -> [CpuDevice; 3] {
[
CpuDevice::new(1),
CpuDevice::new(4).with_grain(8),
CpuDevice::new(7),
]
}
/// A matrix of the edges as given, in rows by their tail and in the given order within a
/// row (repeats kept: parallel edges).
fn raw<W: Value + Copy>(n: usize, edges: &[(u32, u32, W)]) -> Csr<W> {
let mut rows: Vec<Vec<(u32, W)>> = vec![Vec::new(); n];
for &(u, v, w) in edges {
rows[u as usize].push((v, w));
}
let mut off = vec![0u64];
let (mut idx, mut val) = (Vec::new(), Vec::new());
for r in rows {
for (v, w) in r {
idx.push(v);
val.push(w);
}
off.push(idx.len() as u64);
}
Csr::new(
n,
n,
ScalarBuffer::from(off),
ScalarBuffer::from(idx),
Some(ScalarBuffer::from(val)),
)
.unwrap()
}
fn find(p: &mut [usize], mut x: usize) -> usize {
while p[x] != x {
p[x] = p[p[x]];
x = p[x];
}
x
}
/// Kruskal on one thread: entries sorted by weight key, ties by place (rising, or falling
/// with `reverse_ties`); a forest of entry places, sorted.
fn kruskal<W: ForestWeight>(a: &Csr<W>, reverse_ties: bool) -> (Vec<usize>, W::Total) {
let n = a.nrows();
let off = a.pattern().offsets();
let idx = a.pattern().indices();
let w = |e: usize| a.values().map_or(W::ONE, |v| v[e]);
let mut es: Vec<(u64, i64, usize, usize, usize)> = Vec::new();
for u in 0..n {
for e in off[u] as usize..off[u + 1] as usize {
let tie = if reverse_ties { -(e as i64) } else { e as i64 };
es.push((w(e).key().unwrap(), tie, e, u, idx[e] as usize));
}
}
es.sort();
let mut p: Vec<usize> = (0..n).collect();
let mut out = Vec::new();
for (_, _, e, u, v) in es {
let (a, b) = (find(&mut p, u), find(&mut p, v));
if a != b {
p[a] = b;
out.push(e);
}
}
out.sort_unstable();
let total = out.iter().fold(W::Total::default(), |t, &e| w(e).add_to(t));
(out, total)
}
fn components<W: Value>(a: &Csr<W>) -> usize {
let n = a.nrows();
let mut p: Vec<usize> = (0..n).collect();
for u in 0..n {
for &v in a.row(u) {
let (x, y) = (find(&mut p, u), find(&mut p, v as usize));
p[x] = y;
}
}
(0..n).filter(|&v| find(&mut p, v) == v).count()
}
/// The forest's edges as entry places (each edge of the answer found among the entries
/// with its ends and weight, the places used once each).
fn places<W: ForestWeight>(a: &Csr<W>, edges: &[(u32, u32, W)]) -> Vec<usize> {
let off = a.pattern().offsets();
let idx = a.pattern().indices();
let mut used = vec![false; a.nnz()];
let mut out = Vec::new();
for &(u, v, w) in edges {
let e = (off[u as usize] as usize..off[u as usize + 1] as usize)
.find(|&e| !used[e] && idx[e] == v && a.values().map_or(W::ONE, |x| x[e]) == w)
.expect("an edge of the forest is an entry");
used[e] = true;
out.push(e);
}
out.sort_unstable();
out
}
fn check<W: ForestWeight>(name: &str, a: &Csr<W>) {
let (want, total) = kruskal(a, false);
let (_, other) = kruskal(a, true);
assert_eq!(total, other, "{name}: both tie orders weigh the same");
let trees = components(a);
for cpu in devices() {
let f = spanning_forest(a, &cpu).unwrap();
assert_eq!(
places(a, &f.edges),
want,
"{name} on {} threads",
cpu.threads()
);
assert_eq!(f.total, total, "{name}");
assert_eq!(f.trees, trees, "{name}");
assert_eq!(f.trees + f.edges.len(), a.nrows(), "{name}");
}
}
/// Edges from a fixed seed with weights in `0..range` (small ranges: many ties).
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;
// a few hubs: skewed degrees
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_forests() {
// a square with a diagonal, a triangle apart, an isolated vertex, a self-loop
let g = raw(
9u32 as usize,
&[
(0, 1, 4u64),
(1, 2, 1),
(2, 3, 3),
(3, 0, 2),
(0, 2, 5),
(4, 5, 7),
(5, 6, 7),
(6, 4, 7),
(7, 7, 0),
],
);
let f = spanning_forest(&g, &CpuDevice::new(2)).unwrap();
assert_eq!(
f.edges,
vec![(1, 2, 1), (2, 3, 3), (3, 0, 2), (4, 5, 7), (5, 6, 7)]
);
assert_eq!(f.total, 20);
assert_eq!(f.trees, 4, "square, triangle, 7 and 8");
check("hand", &g);
}
#[test]
fn parallel_edges_and_both_ways() {
// 0-1 three times (the lightest in the middle), 1-2 stored both ways with other weights
let g = raw(
3,
&[
(0, 1, 9u32),
(0, 1, 2),
(0, 1, 5),
(1, 2, 8),
(2, 1, 3),
(1, 0, 1),
],
);
let f = spanning_forest(&g, &CpuDevice::new(3)).unwrap();
assert_eq!(f.edges, vec![(1, 0, 1), (2, 1, 3)]);
assert_eq!(f.total, 4);
check("parallel", &g);
}
#[test]
fn ties_weigh_the_same() {
// every weight equal: any spanning tree, total n - 1
let mut e = Vec::new();
for u in 0..40u32 {
for v in 0..40u32 {
if (u * 7 + v * 3) % 5 == 0 && u != v {
e.push((u, v, 6u64));
}
}
}
let g = raw(40, &e);
check("all ties", &g);
let f = spanning_forest(&g, &CpuDevice::new(4)).unwrap();
assert_eq!(f.total, 6 * (40 - f.trees as u128));
for range in [1, 2, 3, 16] {
check(
&format!("range {range}"),
&raw(500, &generated(500, 3000, range, 11 + range)),
);
}
}
#[test]
fn generated_graphs() {
for (n, m, seed) in [
(1000u32, 2500usize, 1u64),
(5000, 40000, 2),
(60000, 300000, 3),
] {
let e = generated(n, m, 1 << 20, seed);
check(&format!("n {n} m {m}"), &raw(n as usize, &e));
}
// a long path in a random order: many rounds of few hooks
let mut path: Vec<(u32, u32, u64)> = (0..20000u32)
.map(|v| (v, v + 1, u64::from((v * 7919) % 1000)))
.collect();
path.reverse();
check("path", &raw(20001, &path));
}
#[test]
fn signed_and_float_weights() {
let e = generated(3000, 20000, 1000, 9);
let signed: Vec<(u32, u32, i64)> = e.iter().map(|&(a, b, w)| (a, b, w as i64 - 500)).collect();
check("signed", &raw(3000, &signed));
let float: Vec<(u32, u32, f64)> = e
.iter()
.map(|&(a, b, w)| (a, b, (w as f64 - 300.0) / 7.0))
.collect();
let g = raw(3000, &float);
let (want, _) = kruskal(&g, false);
for cpu in devices() {
let f = spanning_forest(&g, &cpu).unwrap();
assert_eq!(places(&g, &f.edges), want);
let sum: f64 = f.edges.iter().map(|e| e.2).sum();
assert_eq!(f.total, sum);
}
let f32s: Vec<(u32, u32, f32)> = e.iter().map(|&(a, b, w)| (a, b, w as f32)).collect();
check("f32", &raw(3000, &f32s));
// NaN has no place in the order
let nan = raw(3, &[(0, 1, 1.0f64), (1, 2, f64::NAN)]);
assert!(matches!(
spanning_forest(&nan, &CpuDevice::new(2)),
Err(GraphError::Weights(_))
));
}
#[test]
fn structural_weighs_one() {
let (s, d): (Vec<u32>, Vec<u32>) = [(0u32, 1u32), (1, 2), (2, 0), (3, 4)].into_iter().unzip();
let g = Csr::<u8>::from_edges(6, 6, &s, &d, None, kleene_sparse::BoolOrAnd).unwrap();
let f = spanning_forest(&g, &CpuDevice::new(2)).unwrap();
assert_eq!(f.edges.len(), 3);
assert_eq!(f.total, 3);
assert_eq!(f.trees, 3);
}
#[test]
fn edge_cases() {
let cpu = CpuDevice::new(4);
let empty = raw::<u64>(0, &[]);
let f = spanning_forest(&empty, &cpu).unwrap();
assert_eq!((f.edges.len(), f.total, f.trees, f.rounds), (0, 0, 0, 0));
let one = raw::<u64>(1, &[]);
assert_eq!(spanning_forest(&one, &cpu).unwrap().trees, 1);
let looped = raw(1, &[(0, 0, 3u64)]);
let f = spanning_forest(&looped, &cpu).unwrap();
assert_eq!((f.edges.len(), f.trees), (0, 1));
let none = raw::<u64>(50, &[]);
assert_eq!(spanning_forest(&none, &cpu).unwrap().trees, 50);
let zero = raw(3, &[(0, 1, 0u64), (1, 2, 0)]);
let f = spanning_forest(&zero, &cpu).unwrap();
assert_eq!((f.edges.len(), f.total), (2, 0));
let wide = Csr::<u64>::new(
2,
3,
ScalarBuffer::from(vec![0u64, 0, 0]),
ScalarBuffer::from(Vec::<u32>::new()),
None,
)
.unwrap();
assert!(matches!(
spanning_forest(&wide, &cpu),
Err(GraphError::NotSquare { .. })
));
// the largest weights still order and sum
let big = raw(
3,
&[(0, 1, u64::MAX), (1, 2, u64::MAX), (0, 2, u64::MAX - 1)],
);
let f = spanning_forest(&big, &cpu).unwrap();
assert_eq!(f.total, u128::from(u64::MAX) * 2 - 1);
}