Your browser sucks, JavaScript disabled! Gunnar's console needs JavaScript and WebAssembly. Git over SSH on port 2222 does not.

nordisk/kleene

crates/kleene-graph/tests/harmonic.rs

//! Harmonic centrality: equal, bit for bit, to a plain one-thread breadth-first search
//! from every vertex, whatever the number of workers, on hand-made and generated graphs and
//! the edge cases (no vertices, isolated vertices, self-loops, both ways of an edge,
//! repeated edges, more than one batch of 64 sources, deep graphs).

use std::collections::VecDeque;

use kleene_graph::harmonic;
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
}

/// One search from every vertex on one thread; each score adds the vertices first reached
/// at a level over the level, level by level.
fn plain(a: &Csr<u8>) -> Vec<f64> {
    let n = a.nrows();
    let mut dist = vec![u32::MAX; n];
    let mut q = VecDeque::new();
    (0..n)
        .map(|s| {
            dist.fill(u32::MAX);
            dist[s] = 0;
            q.clear();
            q.push_back(s);
            let mut at = Vec::new();
            while let Some(v) = q.pop_front() {
                for &w in a.row(v) {
                    let w = w as usize;
                    if dist[w] == u32::MAX {
                        dist[w] = dist[v] + 1;
                        let d = dist[w] as usize;
                        if at.len() < d {
                            at.resize(d, 0u64);
                        }
                        at[d - 1] += 1;
                        q.push_back(w);
                    }
                }
            }
            at.iter()
                .enumerate()
                .fold(0f64, |sum, (i, &c)| sum + c as f64 / (i + 1) as f64)
        })
        .collect()
}

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),
    ]
}

fn fixtures() -> Vec<(&'static str, Csr<u8>)> {
    let side = 20u32;
    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.push((v, v + side));
            }
        }
    }
    let path: Vec<(u32, u32)> = (0..299u32).map(|v| (v, v + 1)).collect();
    let star: Vec<(u32, u32)> = (1..700u32).flat_map(|v| [(0, v), (v, 0)]).collect();
    vec![
        ("skewed", graph(1500, &skewed(1500, 9000, 7))),
        ("sparse", graph(1000, &skewed(1000, 700, 3))),
        ("grid", graph((side * side) as usize, &grid)),
        ("path", graph(300, &path)),
        ("star", graph(700, &star)),
        // 63, 64 and 65 vertices: one batch short, full, and one over
        (
            "ring63",
            graph(
                63,
                &(0..63u32).map(|v| (v, (v + 1) % 63)).collect::<Vec<_>>(),
            ),
        ),
        (
            "ring64",
            graph(
                64,
                &(0..64u32).map(|v| (v, (v + 1) % 64)).collect::<Vec<_>>(),
            ),
        ),
        (
            "ring65",
            graph(
                65,
                &(0..65u32).map(|v| (v, (v + 1) % 65)).collect::<Vec<_>>(),
            ),
        ),
    ]
}

#[test]
fn harmonic_equals_a_search_from_every_vertex_at_any_worker_count() {
    for (name, a) in fixtures() {
        let want = plain(&a);
        assert!(want.iter().any(|&x| x > 0.0), "{name}");
        let at = a.transpose();
        for cpu in devices() {
            let got = harmonic(&a, &at, &cpu).unwrap();
            assert_eq!(got, want, "{name} on {} threads", cpu.threads());
        }
    }
}

#[test]
fn harmonic_by_hand_and_edge_cases() {
    let cpu = CpuDevice::new(3).with_grain(1);
    let run = |a: &Csr<u8>| harmonic(a, &a.transpose(), &cpu).unwrap();
    // No vertices.
    assert!(run(&graph(0, &[])).is_empty());
    // 0 -> 1 -> 2, 0 -> 2 (2 at distance 1, not 2), a self-loop at 2, both ways 3 <-> 4,
    // the edge 0 -> 1 twice, vertex 5 alone.
    let a = graph(6, &[(0, 1), (1, 2), (0, 2), (2, 2), (3, 4), (4, 3), (0, 1)]);
    assert_eq!(run(&a), vec![2.0, 1.0, 0.0, 1.0, 1.0, 0.0]);
    // A path 0 -> 1 -> 2 -> 3: 1 + 1/2 + 1/3 from 0.
    let p = graph(4, &[(0, 1), (1, 2), (2, 3)]);
    assert_eq!(run(&p), vec![1.0 + 0.5 + 1.0 / 3.0, 1.5, 1.0, 0.0]);
    // Along in-edges: the same call with the matrix and its transpose swapped.
    let pt = p.transpose();
    assert_eq!(
        harmonic(&pt, &p, &cpu).unwrap(),
        vec![0.0, 1.0, 1.5, 1.0 + 0.5 + 1.0 / 3.0]
    );
    // Only isolated vertices, and a lone self-loop.
    assert_eq!(run(&graph(70, &[(5, 5)])), vec![0.0; 70]);
    // Not square, or a transpose of another size.
    let r = Csr::from_edges(2, 3, &[0], &[2], None, BoolOrAnd).unwrap();
    assert!(harmonic(&r, &r.transpose(), &cpu).is_err());
    assert!(harmonic(&p, &graph(5, &[]), &cpu).is_err());
}