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/src/harmonic.rs

//! Harmonic centrality, exact: for every vertex the sum of 1 / d over the vertices it
//! reaches, d the fewest edges from it (Marchiori and Latora's harmonic mean of distances,
//! Boldi and Vigna's "harmonic centrality" taken along out-edges; along in-edges it is
//! the same call with the matrix and its transpose swapped).
//!
//! One breadth-first search per vertex, 64 of them at once: a vertex's frontier and seen
//! sets are one word each, bit `k` for the batch's source `k`, so one walk over a row
//! serves all 64 searches. A level with few frontier edges is pushed (each frontier vertex
//! ORs its word into its out-neighbours' next words), a level whose frontier's out-edges
//! are a large part of the graph is pulled (every vertex not yet seen by all 64 sources ORs
//! its in-neighbours' frontier words). Each level counts, per source, the vertices first
//! reached there (a whole number, exact in any order), and each source's score adds
//! count / d level by level in rising d, so the answer is the one a plain search from every
//! vertex gives, bit for bit, at any number of workers.
//!
//! While every worker's three words a vertex fit in 1 GiB the batches run side by side,
//! each worker on its own words and no level waiting on another worker; above that one
//! batch runs at a time, each level split over the workers.
//!
//! The work is about `n / 64` searches over the graph, each a pass over the edges per
//! pulled level and over the frontier's edges per pushed one: exact is a matter of seconds
//! up to some 10^5 vertices and 10^6 edges and grows with the product of the two.

use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering::Relaxed};

use kleene_sparse::{CpuDevice, Csr};

use crate::GraphError;
use crate::centrality::{PIECE, each_of_level, each_piece, pieces_by_entries, square};

/// Sources a batch: a bit each of a word.
const LANES: usize = 64;

/// A level is pulled when its frontier's out-edges are more than one in this many of the
/// graph's edges.
const PULL_ABOVE: u64 = 16;

/// The state of one batch's searches.
struct Words {
    seen: Vec<AtomicU64>,
    front: Vec<AtomicU64>,
    next: Vec<AtomicU64>,
}

/// The batches run side by side, a worker's own words each, while every worker's words
/// take at most this many bytes together: no worker waits on another inside a search.
/// Larger graphs run one batch at a time with each level split over the workers.
const SIDE_BY_SIDE_BYTES: usize = 1 << 30;

/// Each bit of `bits` counted in `counts` at its place.
fn count_bits(mut bits: u64, counts: &mut [u64; LANES]) {
    while bits != 0 {
        counts[bits.trailing_zeros() as usize] += 1;
        bits &= bits - 1;
    }
}

/// The graph a search walks.
struct Graph<'a> {
    out: &'a Csr<u8>,
    inn: &'a Csr<u8>,
    oo: &'a [u64],
    m: u64,
    in_cuts: &'a [usize],
}

impl Words {
    fn new(n: usize) -> Self {
        let zero = || (0..n).map(|_| AtomicU64::new(0)).collect::<Vec<_>>();
        Words {
            seen: zero(),
            front: zero(),
            next: zero(),
        }
    }
}

/// The scores of the sources `first..first + lanes`, the batch's levels on `cpu`'s
/// workers. `st`'s words are all zero but for `seen`, which is reset here; they are left
/// so again.
fn batch(
    g: &Graph<'_>,
    st: &Words,
    active: &mut Vec<u32>,
    first: usize,
    lanes: usize,
    cpu: &CpuDevice,
) -> [f64; LANES] {
    let (out, inn, oo, m, in_cuts) = (g.out, g.inn, g.oo, g.m, g.in_cuts);
    let n = st.seen.len();
    let full = if lanes == LANES {
        u64::MAX
    } else {
        (1u64 << lanes) - 1
    };
    cpu.split(n, |r| {
        for v in r {
            st.seen[v].store(0, Relaxed);
        }
    });
    active.clear();
    for k in 0..lanes {
        let s = first + k;
        st.seen[s].store(1 << k, Relaxed);
        st.front[s].store(1 << k, Relaxed);
        active.push(s as u32);
    }
    let mut sums = [0f64; LANES];
    let mut d = 0u32;
    loop {
        d += 1;
        let front_edges: u64 = active
            .iter()
            .map(|&v| oo[v as usize + 1] - oo[v as usize])
            .sum();
        let found: Vec<Vec<u32>> = if front_edges * PULL_ABOVE > m {
            // Pull: every vertex not seen by all sources ORs its in-neighbours' fronts.
            each_piece(cpu, in_cuts.len() - 1, |p| {
                let mut mine = Vec::new();
                for w in in_cuts[p]..in_cuts[p + 1] {
                    let s = st.seen[w].load(Relaxed);
                    if s == full {
                        continue;
                    }
                    let mut acc = 0u64;
                    for &u in inn.row(w) {
                        acc |= st.front[u as usize].load(Relaxed);
                    }
                    let new = acc & !s;
                    if new != 0 {
                        st.next[w].store(new, Relaxed);
                        mine.push(w as u32);
                    }
                }
                mine
            })
        } else {
            // Push: each frontier vertex ORs its front into its out-neighbours' next
            // words; the first to give a vertex anything lists it.
            each_of_level(cpu, active, oo, |part| {
                let mut mine = Vec::new();
                for &u in part {
                    let f = st.front[u as usize].load(Relaxed);
                    for &w in out.row(u as usize) {
                        let bits = f & !st.seen[w as usize].load(Relaxed);
                        if bits != 0 && st.next[w as usize].fetch_or(bits, Relaxed) == 0 {
                            mine.push(w);
                        }
                    }
                }
                mine
            })
        };
        // this level's fronts are spent
        each_of_level(cpu, active, oo, |part| {
            for &u in part {
                st.front[u as usize].store(0, Relaxed);
            }
        });
        active.clear();
        for part in found {
            active.extend(part);
        }
        if active.is_empty() {
            break;
        }
        // The newly reached become the next front, and are counted per source.
        let counts = each_of_level(cpu, active, oo, |part| {
            let mut c = [0u64; LANES];
            for &w in part {
                let w = w as usize;
                let new = st.next[w].swap(0, Relaxed) & !st.seen[w].load(Relaxed);
                st.seen[w].fetch_or(new, Relaxed);
                st.front[w].store(new, Relaxed);
                count_bits(new, &mut c);
            }
            c
        });
        let mut c = [0u64; LANES];
        for part in counts {
            for (a, b) in c.iter_mut().zip(part) {
                *a += b;
            }
        }
        for k in 0..lanes {
            sums[k] += c[k] as f64 / f64::from(d);
        }
    }
    sums
}

/// Harmonic centrality over `out` (its transpose `inn` gives the in-edges a pulled level
/// reads): for every vertex `v` the sum over the vertices `w != v` it reaches of
/// `1 / d(v, w)`, `d` the fewest edges from `v` to `w`. A vertex that reaches nothing
/// scores 0; self-loops and repeated edges change nothing.
pub fn harmonic(out: &Csr<u8>, inn: &Csr<u8>, cpu: &CpuDevice) -> crate::Result<Vec<f64>> {
    harmonic_within(out, inn, cpu, SIDE_BY_SIDE_BYTES)
}

/// [`harmonic`] with the batches side by side while the workers' words take at most
/// `side_by_side` bytes.
fn harmonic_within(
    out: &Csr<u8>,
    inn: &Csr<u8>,
    cpu: &CpuDevice,
    side_by_side: usize,
) -> crate::Result<Vec<f64>> {
    let n = square(out)?;
    if square(inn)? != n {
        return Err(GraphError::NotSquare {
            rows: inn.nrows(),
            cols: n,
        });
    }
    let mut scores = vec![0f64; n];
    if n == 0 {
        return Ok(scores);
    }
    let in_cuts = pieces_by_entries(inn.pattern().offsets(), PIECE);
    let g = Graph {
        out,
        inn,
        oo: out.pattern().offsets(),
        m: out.nnz() as u64,
        in_cuts: &in_cuts,
    };
    let batches = n.div_ceil(LANES);
    let workers = cpu.threads().min(batches);
    let lanes_of = |b: usize| LANES.min(n - b * LANES);
    if workers > 1 && workers * n * 3 * 8 <= side_by_side {
        // each worker its own words, the batches handed out from a shared counter
        let next = AtomicUsize::new(0);
        let alone = CpuDevice::new(1);
        let mut bufs: Vec<Vec<(usize, [f64; LANES])>> = vec![Vec::new(); workers];
        cpu.each_block(&mut bufs, |_, mine| {
            let st = Words::new(n);
            let mut active = Vec::new();
            loop {
                let b = next.fetch_add(1, Relaxed);
                if b >= batches {
                    break;
                }
                let sums = batch(&g, &st, &mut active, b * LANES, lanes_of(b), &alone);
                mine.push((b, sums));
            }
        });
        for (b, sums) in bufs.into_iter().flatten() {
            let first = b * LANES;
            let lanes = lanes_of(b);
            scores[first..first + lanes].copy_from_slice(&sums[..lanes]);
        }
    } else {
        let st = Words::new(n);
        let mut active: Vec<u32> = Vec::with_capacity(n);
        for b in 0..batches {
            let (first, lanes) = (b * LANES, lanes_of(b));
            let sums = batch(&g, &st, &mut active, first, lanes, cpu);
            scores[first..first + lanes].copy_from_slice(&sums[..lanes]);
        }
    }
    Ok(scores)
}

#[cfg(test)]
mod tests {
    use kleene_sparse::{BoolOrAnd, CpuDevice, Csr};

    /// Both ways of running the batches give the one-worker answer, bit for bit.
    #[test]
    fn side_by_side_and_split_levels_agree() {
        let mut x = 11u64;
        let mut next = || {
            x ^= x << 13;
            x ^= x >> 7;
            x ^= x << 17;
            x
        };
        let n = 700u32;
        let (mut s, mut d) = (Vec::new(), Vec::new());
        for _ in 0..6000 {
            let a = (next() % u64::from(n)) as u32;
            let b = (next() % u64::from(n)) as u32;
            s.push(if next() % 3 == 0 { a % 5 } else { a });
            d.push(b);
        }
        let a = Csr::from_edges(n as usize, n as usize, &s, &d, None, BoolOrAnd).unwrap();
        let at = a.transpose();
        let one = super::harmonic(&a, &at, &CpuDevice::new(1)).unwrap();
        for cpu in [
            CpuDevice::new(3).with_grain(1),
            CpuDevice::new(8).with_grain(16),
        ] {
            assert_eq!(
                super::harmonic_within(&a, &at, &cpu, usize::MAX).unwrap(),
                one
            );
            assert_eq!(super::harmonic_within(&a, &at, &cpu, 0).unwrap(), one);
        }
    }
}