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/hyperball.rs

//! Harmonic centrality, estimated: HyperBall (Boldi and Vigna, "In-Core Computation of
//! Geometric Centralities with HyperBall", 2013), for graphs where a search from every
//! vertex is too much.
//!
//! Every vertex keeps a HyperLogLog counter of the ball of vertices it reaches in at most
//! `t` edges: at `t = 0` the vertex alone, and each round its counter takes the
//! register-wise maximum of its own and its out-neighbours' counters of the round before
//! (the ball of radius `t` is the vertex and its out-neighbours' balls of radius `t - 1`).
//! The estimate of the ball's size grows by about the number of vertices first reached at
//! distance `t`, and each vertex's score adds that growth over `t`. The rounds stop when no
//! counter changes; a vertex whose counter and out-neighbours' counters did not change in a
//! round is not looked at again until one does.
//!
//! The vertices are hashed from a fixed seed, every counter is fixed by the graph and the
//! seed, and every score adds its terms in round order, so the answer is the same at any
//! number of workers. With `2^b` registers a counter's size has a relative standard error of
//! about `1.04 / sqrt(2^b)`; the scores, sums of differences of those sizes, are tested
//! against [`crate::harmonic`] (see [`HyperBallOptions`]). The memory is two counters a
//! vertex, `2^b` bytes each, plus three numbers.

use std::sync::Mutex;
use std::sync::atomic::{AtomicBool, Ordering::Relaxed};

use kleene_sparse::{CpuDevice, Csr};

use crate::GraphError;
use crate::centrality::{each_piece, square};

/// HyperBall's settings.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct HyperBallOptions {
    /// `b`: each counter has `2^b` registers (4 to 16). The default 7 (128 registers, 256
    /// bytes a vertex) gives a counter a relative standard error of about 9 %, and the
    /// scores a mean relative error of about 4 % on the tested graphs.
    pub log2_registers: u8,
    /// The seed of the vertices' hashes.
    pub seed: u64,
    /// The most rounds (distances); the default has no limit.
    pub max_rounds: u32,
}

impl Default for HyperBallOptions {
    fn default() -> Self {
        HyperBallOptions {
            log2_registers: 7,
            seed: 0x5EED_4B41_1B00_0001,
            max_rounds: u32::MAX,
        }
    }
}

/// HyperBall's answer.
#[derive(Clone, Debug, PartialEq)]
pub struct HarmonicEstimate {
    /// The estimated score of each vertex.
    pub scores: Vec<f64>,
    /// Rounds run (the last changed no counter, unless the limit stopped them).
    pub rounds: u32,
}

/// Vertices a piece of the counters holds.
const PIECE_VERTICES: usize = 1 << 12;

fn splitmix(x: u64) -> u64 {
    let mut z = x.wrapping_add(0x9E37_79B9_7F4A_7C15);
    z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
    z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
    z ^ (z >> 31)
}

/// The HyperLogLog estimate of a counter's registers.
fn estimate(regs: &[u8]) -> f64 {
    let m = regs.len() as f64;
    let alpha = match regs.len() {
        16 => 0.673,
        32 => 0.697,
        64 => 0.709,
        _ => 0.7213 / (1.0 + 1.079 / m),
    };
    let mut sum = 0f64;
    let mut zeros = 0usize;
    for &r in regs {
        sum += f64::from_bits((1023u64.saturating_sub(u64::from(r))) << 52);
        zeros += usize::from(r == 0);
    }
    let e = alpha * m * m / sum;
    if e <= 2.5 * m && zeros > 0 {
        // small range: linear counting
        m * (m / zeros as f64).ln()
    } else {
        e
    }
}

/// One side of the counters: each piece's registers and which vertices' counters changed
/// in the round that made them.
struct Side {
    regs: Vec<u8>,
    changed: Vec<bool>,
}

/// Each piece's running estimates and scores.
struct Acc {
    est: Vec<f64>,
    score: Vec<f64>,
}

/// Harmonic centrality over `out`, estimated by HyperBall: for every vertex `v` about the
/// sum over the vertices `w != v` it reaches of `1 / d(v, w)` ([`crate::harmonic`]'s
/// score). Self-loops and repeated edges change nothing.
pub fn harmonic_estimate(
    out: &Csr<u8>,
    opts: &HyperBallOptions,
    cpu: &CpuDevice,
) -> crate::Result<HarmonicEstimate> {
    let n = square(out)?;
    let b = opts.log2_registers;
    if !(4..=16).contains(&b) {
        return Err(GraphError::Paths(format!(
            "HyperBall takes 2^4 to 2^16 registers a counter, not 2^{b}"
        )));
    }
    let m = 1usize << b;
    let pieces = n.div_ceil(PIECE_VERTICES);
    let range = |p: usize| p * PIECE_VERTICES..((p + 1) * PIECE_VERTICES).min(n);
    // the ball of radius 0: the vertex alone
    let first: Vec<Side> = each_piece(cpu, pieces, |p| {
        let r = range(p);
        let mut regs = vec![0u8; r.len() * m];
        for (i, v) in r.clone().enumerate() {
            let h = splitmix(opts.seed ^ splitmix(v as u64));
            let j = (h & (m as u64 - 1)) as usize;
            let rank = ((h >> b).trailing_zeros() + 1).min(64 - u32::from(b) + 1) as u8;
            regs[i * m + j] = rank;
        }
        Side {
            regs,
            changed: vec![true; r.len()],
        }
    });
    let acc: Vec<Mutex<Acc>> = each_piece(cpu, pieces, |p| {
        let r = range(p);
        let one = estimate(&first[p].regs[..m.min(first[p].regs.len())]);
        Mutex::new(Acc {
            est: vec![one; r.len()],
            score: vec![0f64; r.len()],
        })
    });
    let mut cur = first;
    let mut spare: Vec<Mutex<Side>> = (0..pieces)
        .map(|p| {
            let len = range(p).len();
            Mutex::new(Side {
                regs: vec![0u8; len * m],
                changed: vec![false; len],
            })
        })
        .collect();
    let mut rounds = 0u32;
    while rounds < opts.max_rounds && n > 0 {
        rounds += 1;
        let t = f64::from(rounds);
        let any = AtomicBool::new(false);
        let now = &cur;
        let counter = |v: usize| {
            let (p, i) = (v / PIECE_VERTICES, v % PIECE_VERTICES);
            &now[p].regs[i * m..(i + 1) * m]
        };
        let changed = |v: usize| now[v / PIECE_VERTICES].changed[v % PIECE_VERTICES];
        each_piece(cpu, pieces, |p| {
            let mut next = spare[p].lock().unwrap_or_else(|e| e.into_inner());
            let mut a = acc[p].lock().unwrap_or_else(|e| e.into_inner());
            let Side {
                regs,
                changed: moved,
            } = &mut *next;
            let mut piece_moved = false;
            for (i, v) in range(p).enumerate() {
                let own = counter(v);
                let mine = &mut regs[i * m..(i + 1) * m];
                mine.copy_from_slice(own);
                let row = out.row(v);
                if !row.iter().any(|&w| changed(w as usize)) {
                    moved[i] = false;
                    continue;
                }
                for &w in row {
                    let w = w as usize;
                    if w != v && changed(w) {
                        for (x, &y) in mine.iter_mut().zip(counter(w)) {
                            *x = (*x).max(y);
                        }
                    }
                }
                moved[i] = mine != own;
                if moved[i] {
                    piece_moved = true;
                    let e = estimate(mine);
                    a.score[i] += (e - a.est[i]).max(0.0) / t;
                    a.est[i] = e;
                }
            }
            if piece_moved {
                any.store(true, Relaxed);
            }
        });
        let made: Vec<Side> = spare
            .into_iter()
            .map(|s| s.into_inner().unwrap_or_else(|e| e.into_inner()))
            .collect();
        spare = std::mem::replace(&mut cur, made)
            .into_iter()
            .map(Mutex::new)
            .collect();
        if !any.load(Relaxed) {
            break;
        }
    }
    let mut scores = Vec::with_capacity(n);
    for a in acc {
        scores.extend(a.into_inner().unwrap_or_else(|e| e.into_inner()).score);
    }
    Ok(HarmonicEstimate { scores, rounds })
}