crates/kleene-graph/tests/hyperball.rs
//! HyperBall's harmonic centrality against the exact kernel ([`harmonic`]) on graphs where
//! exact is practical: with `2^b` registers the mean relative error over the vertices that
//! reach any is at most two standard errors of a counter, `2 * 1.04 / sqrt(2^b)`, and so is
//! the error of the scores' total, for b 6, 7 (the default), 8 and 10 and two seeds; the
//! same answer at any worker count; the edge cases.
use kleene_graph::{HyperBallOptions, harmonic, harmonic_estimate};
use kleene_sparse::{BoolOrAnd, CpuDevice, Csr};
fn graph(n: usize, edges: &[(u32, u32)]) -> Csr<u8> {
let (s, d): (Vec<u32>, Vec<u32>) = edges.iter().copied().unzip();
Csr::from_edges(n, n, &s, &d, None, BoolOrAnd).unwrap()
}
fn skewed(n: u32, m: usize, seed: u64) -> Vec<(u32, u32)> {
let mut x = seed;
let mut next = || {
x ^= x << 13;
x ^= x >> 7;
x ^= x << 17;
x
};
let mut e = Vec::with_capacity(m + m / 8);
for _ in 0..m {
let a = (next() % u64::from(n)) as u32;
let b = (next() % u64::from(n)) as u32;
let (a, b) = if next() % 4 == 0 { (a % 8, b) } else { (a, b) };
e.push((a, b));
if next() % 8 == 0 {
e.push((b, a));
}
}
e
}
fn fixtures() -> Vec<(&'static str, Csr<u8>)> {
let side = 30u32;
let mut grid = Vec::new();
for r in 0..side {
for c in 0..side {
let v = r * side + c;
if c + 1 < side {
grid.extend([(v, v + 1), (v + 1, v)]);
}
if r + 1 < side {
grid.extend([(v, v + side), (v + side, v)]);
}
}
}
let path: Vec<(u32, u32)> = (0..499u32).map(|v| (v, v + 1)).collect();
vec![
("skewed", graph(2000, &skewed(2000, 15000, 7))),
("sparse", graph(2000, &skewed(2000, 2500, 3))),
("grid", graph((side * side) as usize, &grid)),
("path", graph(500, &path)),
]
}
/// The mean relative error over the vertices with an exact score above 0, and the
/// relative error of the total.
fn errors(exact: &[f64], est: &[f64]) -> (f64, f64) {
let errs: Vec<f64> = exact
.iter()
.zip(est)
.filter(|x| *x.0 > 0.0)
.map(|(x, y)| (y - x).abs() / x)
.collect();
let (t, te): (f64, f64) = (exact.iter().sum(), est.iter().sum());
(
errs.iter().sum::<f64>() / errs.len() as f64,
(te - t).abs() / t,
)
}
#[test]
fn hyperball_is_within_two_standard_errors_of_exact() {
let cpu = CpuDevice::new(8);
for (name, a) in fixtures() {
let exact = harmonic(&a, &a.transpose(), &cpu).unwrap();
for b in [6u8, 7, 8, 10] {
let bound = 2.0 * 1.04 / f64::from(1u32 << b).sqrt();
for seed in [1u64, 2] {
let o = HyperBallOptions {
log2_registers: b,
seed,
..Default::default()
};
let e = harmonic_estimate(&a, &o, &cpu).unwrap();
let (mean, total) = errors(&exact, &e.scores);
assert!(
mean <= bound && total <= bound,
"{name} b {b} seed {seed}: mean {mean:.4} total {total:.4} bound {bound:.4}"
);
assert!(e.scores.iter().all(|&x| x >= 0.0 && x.is_finite()));
}
}
}
}
#[test]
fn hyperball_gives_the_same_answer_at_any_worker_count() {
for (name, a) in fixtures() {
let o = HyperBallOptions::default();
let one = harmonic_estimate(&a, &o, &CpuDevice::new(1)).unwrap();
for cpu in [
CpuDevice::new(2).with_grain(1),
CpuDevice::new(5).with_grain(16),
CpuDevice::new(12).with_grain(64),
] {
assert_eq!(harmonic_estimate(&a, &o, &cpu).unwrap(), one, "{name}");
}
}
}
#[test]
fn hyperball_edge_cases() {
let cpu = CpuDevice::new(3).with_grain(1);
let o = HyperBallOptions::default();
// No vertices: no scores, no rounds.
let e = harmonic_estimate(&graph(0, &[]), &o, &cpu).unwrap();
assert!(e.scores.is_empty());
assert_eq!(e.rounds, 0);
// Isolated vertices and self-loops reach nothing: 0, after one round that changes
// nothing.
let e = harmonic_estimate(&graph(50, &[(3, 3), (7, 7)]), &o, &cpu).unwrap();
assert_eq!(e.scores, vec![0.0; 50]);
assert_eq!(e.rounds, 1);
// A pair both ways and an edge twice: each about 1.
let e = harmonic_estimate(&graph(3, &[(0, 1), (1, 0), (0, 1)]), &o, &cpu).unwrap();
assert!((e.scores[0] - 1.0).abs() < 0.05 && (e.scores[1] - 1.0).abs() < 0.05);
assert_eq!(e.scores[2], 0.0);
// The round limit stops it: one round counts the out-neighbours only.
let star: Vec<(u32, u32)> = (1..300u32).flat_map(|v| [(0, v), (v, 299 + v)]).collect();
let a = graph(599, &star);
let one = harmonic_estimate(&a, &HyperBallOptions { max_rounds: 1, ..o }, &cpu).unwrap();
assert_eq!(one.rounds, 1);
assert!(
(one.scores[0] - 299.0).abs() < 299.0 * 0.2,
"{}",
one.scores[0]
);
let all = harmonic_estimate(&a, &o, &cpu).unwrap();
// and two rounds the vertices two edges away too: about 299 / 2 more
assert!(all.scores[0] > one.scores[0] + 100.0, "{}", all.scores[0]);
// Registers outside 2^4..2^16, or a matrix not square: refused.
for b in [3u8, 17] {
let bad = HyperBallOptions {
log2_registers: b,
..o
};
assert!(harmonic_estimate(&a, &bad, &cpu).is_err());
}
let r = Csr::from_edges(2, 3, &[0], &[2], None, BoolOrAnd).unwrap();
assert!(harmonic_estimate(&r, &o, &cpu).is_err());
}