crates/kleene-graph/tests/graphalytics.rs
//! Community detection by label propagation and the local clustering coefficient (LDBC
//! Graphalytics' CDLP and LCC): each equal to a plain single-threaded reference written
//! here from the specification, whatever the number of workers.
use std::collections::{BTreeMap, BTreeSet};
use kleene_graph::{cdlp, lcc};
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()
}
/// Skewed edges from a fixed seed: a quarter from the eight lowest numbers (hubs), some
/// both ways, self-loops and repeats in.
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 && (r + 2 * c) % 4 != 0 {
grid.extend([(v, v + side), (v + side, v)]);
}
// a one-way diagonal now and then: triangles with a single edge
if r + 1 < side && c + 1 < side && (r * c) % 3 == 0 {
grid.push((v, v + side + 1));
}
}
}
let path: Vec<(u32, u32)> = (0..99u32).map(|v| (v, v + 1)).collect();
// every vertex to four hubs and to one other: degrees skewed enough to be renumbered
let hubs: Vec<(u32, u32)> = (4..2000u32)
.flat_map(|v| [(v, 0), (v, 1), (v, 2), (v, 3), (v, (v * 7 + 3) % 2000)])
.collect();
vec![
("skewed", graph(3000, &skewed(3000, 30000, 5))),
("grid", graph((side * side) as usize, &grid)),
("path", graph(100, &path)),
// two triangles sharing an edge (one way and both ways), a 4-clique, a self-loop,
// an isolated vertex and a pair
(
"small",
graph(
12,
&[
(0, 1),
(1, 2),
(2, 0),
(2, 1),
(1, 3),
(3, 2),
(4, 5),
(4, 6),
(4, 7),
(5, 6),
(5, 7),
(6, 7),
(7, 4),
(8, 8),
(10, 11),
],
),
),
("hubs", graph(2000, &hubs)),
]
}
fn devices() -> Vec<CpuDevice> {
vec![
CpuDevice::new(1),
CpuDevice::new(2).with_grain(1),
CpuDevice::new(5).with_grain(16),
CpuDevice::new(12).with_grain(64),
]
}
/// Graphalytics' CDLP on one thread: every round each vertex takes the smallest of the most
/// frequent labels of its in- and out-neighbours (a neighbour both ways counts twice, a
/// self-loop not at all, no neighbours: its own label), all from the last round's labels;
/// stop after `max_rounds` or when a round changes nothing. The labels and the rounds.
fn plain_cdlp(out: &Csr<u8>, max_rounds: u32) -> (Vec<u32>, u32) {
let n = out.nrows();
let inn = out.transpose();
let mut labels: Vec<u32> = (0..n as u32).collect();
let mut rounds = 0;
while rounds < max_rounds {
let mut next = labels.clone();
for (v, x) in next.iter_mut().enumerate() {
let mut count: BTreeMap<u32, usize> = BTreeMap::new();
for &u in out.row(v).iter().chain(inn.row(v)) {
if u as usize != v {
*count.entry(labels[u as usize]).or_default() += 1;
}
}
if let Some(&most) = count.values().max() {
*x = *count.iter().find(|(_, c)| **c == most).unwrap().0;
}
}
rounds += 1;
let same = next == labels;
labels = next;
if same {
break;
}
}
(labels, rounds)
}
/// Graphalytics' LCC on one thread, by its definition: the neighbours of `v` are the
/// vertices with an edge to or from it, `v` left out; the edges between two of them (each
/// direction its own edge) over `d (d - 1)`, 0 below two neighbours.
fn plain_lcc(out: &Csr<u8>) -> Vec<f64> {
let n = out.nrows();
let inn = out.transpose();
(0..n)
.map(|v| {
let nb: BTreeSet<u32> = out
.row(v)
.iter()
.chain(inn.row(v))
.copied()
.filter(|&u| u as usize != v)
.collect();
let d = nb.len() as f64;
if nb.len() < 2 {
return 0.0;
}
let mut t = 0u64;
for &a in &nb {
for &b in out.row(a as usize) {
if b != a && nb.contains(&b) {
t += 1;
}
}
}
t as f64 / (d * (d - 1.0))
})
.collect()
}
#[test]
fn cdlp_equals_the_specifications_rounds_at_any_worker_count() {
for (name, out) in fixtures() {
let inn = out.transpose();
for max_rounds in [0, 1, 3, 100] {
let (want, rounds) = plain_cdlp(&out, max_rounds);
for cpu in devices() {
let got = cdlp(&out, &inn, max_rounds, &cpu).unwrap();
assert_eq!(
got.rounds,
rounds,
"{name}, {max_rounds} rounds, on {}",
cpu.threads()
);
assert_eq!(
got.labels,
want,
"{name}, {max_rounds} rounds, on {}",
cpu.threads()
);
}
}
}
}
#[test]
fn cdlp_by_hand_on_a_small_graph() {
let (_, small) = fixtures().remove(3);
let got = cdlp(&small, &small.transpose(), 100, &CpuDevice::new(2)).unwrap();
// a self-loop alone and an isolated vertex keep their labels
assert_eq!(got.labels[8], 8);
assert_eq!(got.labels[9], 9);
// the first round: 0 sees 1 (out) and 2 (in) once each, a tie: the smaller, 1
let one = cdlp(&small, &small.transpose(), 1, &CpuDevice::new(1)).unwrap();
assert_eq!(one.labels[0], 1);
// 1 sees 2 and 3 (out), 0 and 2 (in): 2 twice
assert_eq!(one.labels[1], 2);
assert_eq!(one.labels[10], 11);
assert_eq!(one.labels[11], 10);
assert_eq!(one.rounds, 1);
}
#[test]
fn lcc_equals_the_specification_at_any_worker_count() {
for (name, out) in fixtures() {
let inn = out.transpose();
let want = plain_lcc(&out);
for cpu in devices() {
let got = lcc(&out, &inn, &cpu).unwrap();
assert_eq!(got, want, "{name} on {}", cpu.threads());
}
}
}
#[test]
fn lcc_by_hand_on_a_small_graph() {
let (_, small) = fixtures().remove(3);
let got = lcc(&small, &small.transpose(), &CpuDevice::new(3)).unwrap();
// 0: neighbours 1, 2; between them 1->2 and 2->1: 2 / (2 * 1)
assert_eq!(got[0], 1.0);
// 1: neighbours 0, 2, 3; between them 2->0 and 3->2: 2 / (3 * 2)
assert_eq!(got[1], 2.0 / 6.0);
// the 4-clique with one edge back: 4 has 5, 6, 7 with 5->6, 5->7, 6->7: 3 / 6
assert_eq!(got[4], 0.5);
// 7: 4, 5, 6 with 4->5, 4->6, 5->6: 3 / 6
assert_eq!(got[7], 0.5);
for v in [8, 9, 10, 11] {
assert_eq!(got[v], 0.0, "vertex {v}");
}
}