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

//! The k-truss and the truss number of every edge, on the CPU device's workers.
//!
//! On the undirected graph without self-loops ([`crate::undirected`]): the k-truss is the
//! largest subgraph in which every edge sits in at least `k - 2` of the subgraph's
//! triangles (Cohen's definition, `LAGraph_KTruss`'s). An edge's support is the number of
//! triangles it sits in.
//!
//! - The supports are counted once, every triangle found at its highest vertex as
//!   [`crate::triangles`] finds it (each worker marks a vertex's lower neighbours in its
//!   own bit set), each adding one to its three edges.
//! - Then the edges below `k - 2` are peeled in rounds: each round's edges leave together,
//!   and every triangle they break takes one from each edge of it that stays. A triangle
//!   that loses two edges in the same round is counted down once, by the edge of the lower
//!   number; one that loses all three is not counted down. An edge whose support falls
//!   below `k - 2` is listed for the next round as it falls. A leaving edge finds its
//!   triangles by merging its ends' rows, or, when one row is much the longer, by looking
//!   the shorter row's vertices up in it.
//!
//! The rounds and the supports are fixed by the graph, so the answer does not depend on
//! the number of workers. [`truss_numbers`] goes on peeling with `k` one higher each time
//! the peeling stops, until no edge is left: an edge's truss number is the largest `k`
//! whose k-truss holds it (2 for an edge in no triangle).

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

use kleene_sparse::{CpuDevice, Csr};

use crate::centrality::square;

/// The k-truss.
#[derive(Clone, Debug)]
pub struct KTruss {
    /// The edges kept, both ways (rows sorted), each valued by its support: the triangles
    /// of the k-truss it sits in.
    pub edges: Csr<u32>,
    /// Peeling rounds run (rounds that removed edges, plus the last that found none).
    pub rounds: u32,
}

/// Still in the graph.
const ALIVE: u32 = u32::MAX;

/// Vertices a worker takes from the shared counter at a time when counting supports.
const CHUNK: usize = 64;

/// A row this many times longer than the other is searched, not merged.
const SEARCH_RATIO: usize = 16;

/// `f(x)` for every `x` in both sorted lists.
fn common(a: &[u32], b: &[u32], mut f: impl FnMut(u32)) {
    let (short, long) = if a.len() <= b.len() { (a, b) } else { (b, a) };
    if short.len() * SEARCH_RATIO < long.len() {
        let mut from = 0;
        for &x in short {
            from += long[from..].partition_point(|&y| y < x);
            if long.get(from) == Some(&x) {
                f(x);
            }
        }
        return;
    }
    let (mut i, mut j) = (0, 0);
    while i < a.len() && j < b.len() {
        let (x, y) = (a[i], b[j]);
        if x < y {
            i += 1;
        } else if y < x {
            j += 1;
        } else {
            f(x);
            i += 1;
            j += 1;
        }
    }
}

/// The edges of an undirected graph by number (an edge's number: the place in `und` of
/// its entry in its higher vertex's row), their supports and the round each left in.
struct Peel<'a> {
    und: &'a Csr<u8>,
    support: Vec<AtomicU32>,
    /// The round each edge left in ([`ALIVE`]: still in).
    gone: Vec<AtomicU32>,
    /// The threshold each edge left at, when kept ([`truss_numbers`]).
    left: Option<Vec<AtomicU32>>,
    /// The edges (higher, lower) of the round to run.
    front: Vec<(u32, u32)>,
    round: u32,
    /// Edges still in.
    alive: usize,
}

impl<'a> Peel<'a> {
    /// Every edge's support, by every triangle once at its highest vertex.
    fn new(und: &'a Csr<u8>, keep_left: bool, cpu: &CpuDevice) -> Self {
        let n = und.nrows();
        let off = und.pattern().offsets();
        let support: Vec<AtomicU32> = (0..und.nnz()).map(|_| AtomicU32::new(0)).collect();
        let gone: Vec<AtomicU32> = (0..und.nnz()).map(|_| AtomicU32::new(ALIVE)).collect();
        let lower = |u: usize| {
            let row = und.row(u);
            &row[..row.partition_point(|&w| (w as usize) < u)]
        };
        let words = n.div_ceil(64);
        let next = AtomicUsize::new(0);
        let mut bufs: Vec<Vec<u64>> = (0..cpu.threads()).map(|_| Vec::new()).collect();
        cpu.each_block(&mut bufs, |_, marks| {
            loop {
                let c = next.fetch_add(CHUNK, Relaxed);
                if c >= n {
                    break;
                }
                for u in c..(c + CHUNK).min(n) {
                    let lu = lower(u);
                    if lu.len() < 2 {
                        continue;
                    }
                    if marks.is_empty() {
                        // made by the worker that uses it
                        marks.resize(words, 0);
                    }
                    for &w in lu {
                        marks[w as usize >> 6] |= 1 << (w & 63);
                    }
                    let first = lu[0];
                    for (i, &v) in lu.iter().enumerate().skip(1) {
                        let lv = lower(v as usize);
                        let from = lv.partition_point(|&w| w < first);
                        let mut here = 0u32;
                        for (j, &w) in lv.iter().enumerate().skip(from) {
                            if (marks[w as usize >> 6] >> (w & 63)) & 1 == 0 {
                                continue;
                            }
                            // the triangle u > v > w
                            here += 1;
                            support[off[v as usize] as usize + j].fetch_add(1, Relaxed);
                            let at = lu.partition_point(|&x| x < w);
                            support[off[u] as usize + at].fetch_add(1, Relaxed);
                        }
                        if here > 0 {
                            support[off[u] as usize + i].fetch_add(here, Relaxed);
                        }
                    }
                    for &w in lu {
                        marks[w as usize >> 6] = 0;
                    }
                }
            }
        });
        Peel {
            und,
            support,
            gone,
            left: keep_left.then(|| (0..und.nnz()).map(|_| AtomicU32::new(0)).collect()),
            front: Vec::new(),
            round: 0,
            alive: und.nnz() / 2,
        }
    }

    /// The number of the edge `a`-`b` (present in the graph).
    fn id(&self, a: u32, b: u32) -> usize {
        let (hi, lo) = if a > b { (a, b) } else { (b, a) };
        let row = self.und.row(hi as usize);
        self.und.pattern().offsets()[hi as usize] as usize + row.partition_point(|&x| x < lo)
    }

    /// List every edge still in with a support below `t` for the next round.
    fn scan(&mut self, t: u32, cpu: &CpuDevice) {
        let (und, round) = (self.und, self.round);
        let (support, gone, left) = (&self.support, &self.gone, &self.left);
        let off = und.pattern().offsets();
        let parts = cpu.split(und.nrows(), |r| {
            let mut mine = Vec::new();
            for u in r {
                let row = und.row(u);
                let lower = &row[..row.partition_point(|&w| (w as usize) < u)];
                for (i, &w) in lower.iter().enumerate() {
                    let e = off[u] as usize + i;
                    if gone[e].load(Relaxed) == ALIVE && support[e].load(Relaxed) < t {
                        gone[e].store(round, Relaxed);
                        if let Some(left) = left {
                            left[e].store(t, Relaxed);
                        }
                        mine.push((u as u32, w));
                    }
                }
            }
            mine
        });
        self.front.clear();
        for p in parts {
            self.front.extend(p);
        }
    }

    /// Peel rounds at threshold `t` until one removes nothing (the first front listed by
    /// [`Peel::scan`]); the rounds run.
    fn peel(&mut self, t: u32, cpu: &CpuDevice) -> u32 {
        let mut rounds = 0;
        loop {
            rounds += 1;
            if self.front.is_empty() {
                return rounds;
            }
            self.alive -= self.front.len();
            let r = self.round;
            let this = &*self;
            let found = cpu.split(this.front.len(), |range| {
                let mut mine = Vec::new();
                for &(u, v) in &this.front[range] {
                    let e = this.id(u, v);
                    common(this.und.row(u as usize), this.und.row(v as usize), |x| {
                        let (e1, e2) = (this.id(u, x), this.id(v, x));
                        let (g1, g2) = (this.gone[e1].load(Relaxed), this.gone[e2].load(Relaxed));
                        // left in an earlier round: the triangle is already gone
                        if g1 < r || g2 < r {
                            return;
                        }
                        // in for this round (listed for a later one counts as in)
                        let (in1, in2) = (g1 > r, g2 > r);
                        let mut down = |id: usize, a: u32, b: u32| {
                            if this.support[id].fetch_sub(1, Relaxed) == t
                                && this.gone[id]
                                    .compare_exchange(ALIVE, r + 1, Relaxed, Relaxed)
                                    .is_ok()
                            {
                                if let Some(left) = &this.left {
                                    left[id].store(t, Relaxed);
                                }
                                mine.push((a.max(b), a.min(b)));
                            }
                        };
                        match (in1, in2) {
                            (true, true) => {
                                down(e1, u, x);
                                down(e2, v, x);
                            }
                            (true, false) if e < e2 => down(e1, u, x),
                            (false, true) if e < e1 => down(e2, v, x),
                            _ => {}
                        }
                    });
                }
                mine
            });
            self.front.clear();
            for p in found {
                self.front.extend(p);
            }
            self.round += 1;
        }
    }

    /// The graph's entries both ways valued by `value(edge)`, only the edges `keep`s.
    fn matrix(
        &self,
        cpu: &CpuDevice,
        keep: impl Fn(usize) -> bool + Sync,
        value: impl Fn(usize) -> u32 + Sync,
    ) -> crate::Result<Csr<u32>> {
        let und = self.und;
        let n = und.nrows();
        let rows: Vec<(Vec<u32>, Vec<u32>, Vec<u64>)> = cpu.split(n, |r| {
            let (mut adj, mut val, mut lens) = (Vec::new(), Vec::new(), Vec::new());
            for v in r {
                let before = adj.len();
                for &w in und.row(v) {
                    let e = self.id(v as u32, w);
                    if keep(e) {
                        adj.push(w);
                        val.push(value(e));
                    }
                }
                lens.push((adj.len() - before) as u64);
            }
            (adj, val, lens)
        });
        let mut off = Vec::with_capacity(n + 1);
        off.push(0u64);
        let total = rows.iter().map(|r| r.0.len()).sum();
        let (mut adj, mut val) = (Vec::with_capacity(total), Vec::with_capacity(total));
        let mut end = 0u64;
        for (a, v, lens) in rows {
            adj.extend(a);
            val.extend(v);
            for l in lens {
                end += l;
                off.push(end);
            }
        }
        Ok(Csr::new(
            n,
            n,
            arrow_buffer::ScalarBuffer::from(off),
            arrow_buffer::ScalarBuffer::from(adj),
            Some(arrow_buffer::ScalarBuffer::from(val)),
        )?)
    }
}

/// The k-truss of the undirected graph `und` (rows sorted, each edge both ways, no
/// self-loops: [`crate::undirected`]): the largest subgraph in which every edge sits in at
/// least `k - 2` of its triangles, each edge valued by its support there. For `k <= 2`
/// every edge is kept.
pub fn ktruss(und: &Csr<u8>, k: u32, cpu: &CpuDevice) -> crate::Result<KTruss> {
    square(und)?;
    let mut p = Peel::new(und, false, cpu);
    let t = k.saturating_sub(2);
    p.scan(t, cpu);
    let rounds = p.peel(t, cpu);
    let edges = p.matrix(
        cpu,
        |e| p.gone[e].load(Relaxed) == ALIVE,
        |e| p.support[e].load(Relaxed),
    )?;
    Ok(KTruss { edges, rounds })
}

/// The truss number of every edge of the undirected graph `und` (as for [`ktruss`]): the
/// largest `k` whose k-truss holds it, 2 for an edge in no triangle. Every entry of `und`
/// valued, both ways.
pub fn truss_numbers(und: &Csr<u8>, cpu: &CpuDevice) -> crate::Result<Csr<u32>> {
    square(und)?;
    let mut p = Peel::new(und, true, cpu);
    // peel at threshold t = k - 2 for k = 3, 4, ... until no edge is left
    let mut t = 1u32;
    while p.alive > 0 {
        p.scan(t, cpu);
        p.peel(t, cpu);
        t += 1;
    }
    let left = p.left.as_ref().expect("kept for truss numbers");
    // an edge leaving at threshold t (k = t + 2) is in the (t + 1)-truss
    p.matrix(cpu, |_| true, |e| left[e].load(Relaxed) + 1)
}