crates/kleene-graph/src/components.rs
use std::sync::atomic::Ordering::Relaxed;
use std::sync::atomic::{AtomicBool, AtomicU64};
use arrow_buffer::ScalarBuffer;
use kleene_sparse::{Bitset, CpuDevice, Csr, Mask, MinPlus, SparseBackend, Vector};
use crate::{GraphBackend, GraphError};
/// A component number per vertex: the lowest vertex number in its component.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Components {
/// The component of each vertex.
pub of: Vec<u32>,
/// Rounds (propagation rounds for weak components; colouring rounds for strong ones).
pub rounds: u32,
}
impl Components {
/// The number of components.
pub fn count(&self) -> usize {
self.of
.iter()
.enumerate()
.filter(|&(v, &c)| v as u32 == c)
.count()
}
/// [`Components::count`] on the device's threads.
pub fn count_on(&self, device: &CpuDevice) -> usize {
device
.split(self.of.len(), |r| {
let start = r.start;
self.of[r]
.iter()
.enumerate()
.filter(|&(i, &c)| (start + i) as u32 == c)
.count()
})
.into_iter()
.sum()
}
}
fn square(a: &Csr<u8>) -> crate::Result<usize> {
if a.nrows() != a.ncols() {
return Err(GraphError::NotSquare {
rows: a.nrows(),
cols: a.ncols(),
});
}
Ok(a.nrows())
}
/// Weakly connected components by FastSV (Zhang, Azad and Hu 2020) with sampling
/// (Sutton et al., Afforest; as in LAGraph):
///
/// 1. FastSV on a sample, the first [`SAMPLE`] out- and in-neighbours of every vertex:
/// each vertex holds a parent; each round the grandparents are pulled over the edges
/// (min-plus `mxv`, a row per vertex, in parallel), a vertex's parent is hooked onto the
/// least grandparent next to it, every vertex takes the least of that and its own
/// grandparent, and the parents are shortcut, until no grandparent changes.
/// 2. The most common root is taken for the giant component and made the least label.
/// 3. FastSV on all edges, but only the rows of vertices outside the giant are pulled (a
/// masked `mxv`): a giant vertex already holds the least label, and any other vertex
/// next to it pulls that label itself. On skewed graphs most edges are in the giant and
/// are never looked at.
///
/// Each vertex then holds the least vertex of its component.
pub fn components<B: GraphBackend>(a: &Csr<u8>, device: &B::Device) -> crate::Result<Components> {
components_of::<B>(a, &a.transpose(), device)
}
/// The neighbours per vertex and direction in the sampling phase of [`components`].
pub const SAMPLE: usize = 4;
/// The first `k` entries of every row, as a structural matrix.
fn first_of_rows(a: &Csr<u8>, k: usize) -> crate::Result<Csr<u64>> {
let n = a.nrows();
let mut offsets = Vec::with_capacity(n + 1);
let mut indices = Vec::with_capacity(n * k);
offsets.push(0u64);
for v in 0..n {
let row = a.row(v);
indices.extend_from_slice(&row[..row.len().min(k)]);
offsets.push(indices.len() as u64);
}
Ok(Csr::new(
n,
a.ncols(),
ScalarBuffer::from(offsets),
ScalarBuffer::from(indices),
None,
)?)
}
/// Run `f` on `0..n` cut into one piece per available core, in parallel.
fn par_ranges(n: usize, f: impl Fn(std::ops::Range<usize>) + Sync) {
let t = std::thread::available_parallelism()
.map_or(1, |x| x.get())
.min(n.div_ceil(1 << 14))
.max(1);
let size = n.div_ceil(t);
std::thread::scope(|sc| {
for k in 0..t {
let r = (k * size).min(n)..((k + 1) * size).min(n);
let f = &f;
sc.spawn(move || f(r));
}
});
}
const LOW: u64 = 0xFFFF_FFFF;
/// FastSV rounds over `o` and `i` (both directions), pulling only the rows `rows` allows.
/// `f` holds each vertex's parent as `(key << 32) | parent`, so the least word is the
/// least label; hooking is an atomic minimum, so the rounds' loops run on every core.
/// Returns the rounds.
fn fastsv<B: SparseBackend>(
o: &B::Matrix<u64>,
i: &B::Matrix<u64>,
rows: Option<&B::Mask>,
f: &[AtomicU64],
device: &B::Device,
) -> crate::Result<u32> {
let n = f.len();
let s = MinPlus::<u64>::new();
let at = |v: usize| f[v].load(Relaxed);
let mut gp: Vec<u64> = vec![0; n];
par_chunks(&mut gp, |base, part| {
for (k, g) in part.iter_mut().enumerate() {
*g = at((at(base + k) & LOW) as usize);
}
});
let mut rounds = 0u32;
loop {
rounds += 1;
let x = B::vector(Vector::dense(gp.clone(), Bitset::full(n))?, device);
for m in [
B::mxv(o, &x, rows, s, device)?,
B::mxv(i, &x, rows, s, device)?,
] {
let (idx, vals) = B::vector_to_host(&m).into_arrow();
let (idx, vals) = (idx.values(), &vals[..]);
// Hook v's parent, and v itself, onto the least grandparent next to v.
par_ranges(idx.len(), |r| {
for k in r {
let (v, least) = (idx[k] as usize, vals[k]);
let fv = at(v);
let p = (fv & LOW) as usize;
// Read before writing: most hooks change nothing, and a write to a
// shared root would bounce its cache line between every core.
if least < at(p) {
f[p].fetch_min(least, Relaxed);
}
if least < fv {
f[v].fetch_min(least, Relaxed);
}
}
});
}
let changed = AtomicBool::new(false);
let g = &gp;
par_ranges(n, |r| {
for v in r {
if g[v] < at(v) {
f[v].fetch_min(g[v], Relaxed);
}
}
});
par_chunks(&mut gp, |base, part| {
for (k, g) in part.iter_mut().enumerate() {
let new = at((at(base + k) & LOW) as usize);
if new != *g {
*g = new;
changed.store(true, Relaxed);
}
}
});
if !changed.into_inner() {
return Ok(rounds);
}
}
}
/// Run `f(start, piece)` on `v` cut into one piece per available core, in parallel.
fn par_chunks(v: &mut [u64], f: impl Fn(usize, &mut [u64]) + Sync) {
let n = v.len();
let t = std::thread::available_parallelism()
.map_or(1, |x| x.get())
.min(n.div_ceil(1 << 14))
.max(1);
let size = n.div_ceil(t).max(1);
std::thread::scope(|sc| {
for (k, part) in v.chunks_mut(size).enumerate() {
let f = &f;
sc.spawn(move || f(k * size, part));
}
});
}
/// [`components`] with the transpose in hand (a graph shared in both orders): no
/// symmetric matrix is built.
pub fn components_of<B: GraphBackend>(
out: &Csr<u8>,
inn: &Csr<u8>,
device: &B::Device,
) -> crate::Result<Components> {
B::components_of(out, inn, device)
}
/// [`components_of`] through the backend's operations (the default of
/// [`GraphBackend::components_of`]).
pub fn components_of_generic<B: SparseBackend>(
out: &Csr<u8>,
inn: &Csr<u8>,
device: &B::Device,
) -> crate::Result<Components> {
let n = square(out)?;
if inn.nrows() != n || inn.ncols() != n {
return Err(GraphError::NoTranspose);
}
// 1. The sample, labels keyed by themselves.
let f: Vec<AtomicU64> = (0..n as u64)
.map(|v| AtomicU64::new((v << 32) | v))
.collect();
let so = B::matrix(first_of_rows(out, SAMPLE)?, device);
let si = B::matrix(first_of_rows(inn, SAMPLE)?, device);
let mut rounds = fastsv::<B>(&so, &si, None, &f, device)?;
// 2. The giant: the most common root.
let parent = |v: usize| (f[v].load(Relaxed) & LOW) as u32;
let mut count = vec![0u32; n];
for v in 0..n {
count[parent(v) as usize] += 1;
}
let giant = (0..n).max_by_key(|&r| count[r]).unwrap_or(0) as u32;
drop(count);
// 3. All edges, rows outside the giant only; the giant's label sorts first.
let key = |x: u32| if x == giant { 0 } else { x as u64 + 1 };
for a in &f {
let p = (a.load(Relaxed) & LOW) as u32;
a.store((key(p) << 32) | p as u64, Relaxed);
}
let outside: Vec<u32> = (0..n as u32)
.filter(|&v| parent(v as usize) != giant)
.collect();
let rows = B::mask(Mask::from_indices(n, &outside), device);
let o = B::matrix(
Csr::<u64>::with_pattern(out.pattern().clone(), None)?,
device,
);
let i = B::matrix(
Csr::<u64>::with_pattern(inn.pattern().clone(), None)?,
device,
);
rounds += fastsv::<B>(&o, &i, Some(&rows), &f, device)?;
// Name each component by its least vertex.
let mut least = vec![u32::MAX; n];
for v in 0..n {
let r = parent(v) as usize;
least[r] = least[r].min(v as u32);
}
let of = (0..n).map(|v| least[parent(v) as usize]).collect();
Ok(Components { of, rounds })
}
/// Strip, again and again, every live vertex with no live in-edge or no live out-edge:
/// each is a strong component of its own.
fn trim(out: &Csr<u8>, inn: &Csr<u8>, alive: &mut [bool], of: &mut [u32]) {
let n = alive.len();
loop {
let mut removed = false;
for (m, t) in [(out, inn), (inn, out)] {
// Peel by `t`-degree (live predecessors when t = inn): a vertex with none goes,
// and its `m`-successors lose one.
let mut deg: Vec<u32> = (0..n)
.map(|v| {
if alive[v] {
t.row(v).iter().filter(|&&u| alive[u as usize]).count() as u32
} else {
0
}
})
.collect();
let mut stack: Vec<u32> = (0..n as u32)
.filter(|&v| alive[v as usize] && deg[v as usize] == 0)
.collect();
while let Some(v) = stack.pop() {
let vu = v as usize;
if !alive[vu] {
continue;
}
alive[vu] = false;
of[vu] = v;
removed = true;
for &w in m.row(vu) {
let wu = w as usize;
if alive[wu] {
deg[wu] -= 1;
if deg[wu] == 0 {
stack.push(w);
}
}
}
}
}
if !removed {
return;
}
}
}
/// Strongly connected components by trimming and colouring: strip vertices with no live
/// in- or out-edge (each is alone), then propagate the minimum vertex number forward over
/// the live edges (min-plus, masked to live vertices); a vertex that keeps its own number
/// is a root, and its component is what reaches it backwards through vertices of its
/// colour (one search from all roots at once, an arrival kept only where its colour
/// matches). Remove those, repeat.
pub fn scc<B: GraphBackend>(a: &Csr<u8>, device: &B::Device) -> crate::Result<Components> {
scc_of::<B>(a, &a.transpose(), device)
}
/// [`scc`] with the transpose in hand.
pub fn scc_of<B: GraphBackend>(
out: &Csr<u8>,
inn: &Csr<u8>,
device: &B::Device,
) -> crate::Result<Components> {
B::scc_of(out, inn, device)
}
/// [`scc_of`] through the backend's operations (the default of [`GraphBackend::scc_of`]).
pub fn scc_of_generic<B: SparseBackend>(
out: &Csr<u8>,
inn: &Csr<u8>,
device: &B::Device,
) -> crate::Result<Components> {
let n = square(out)?;
if inn.nrows() != n || inn.ncols() != n {
return Err(GraphError::NoTranspose);
}
let s = MinPlus::<u32>::new();
let o = B::matrix(
Csr::<u32>::with_pattern(out.pattern().clone(), None)?,
device,
);
let i = B::matrix(
Csr::<u32>::with_pattern(inn.pattern().clone(), None)?,
device,
);
let mut alive = vec![true; n];
let mut of = vec![u32::MAX; n];
let mut rounds = 0u32;
loop {
trim(out, inn, &mut alive, &mut of);
let ids: Vec<u32> = (0..n as u32).filter(|&v| alive[v as usize]).collect();
if ids.is_empty() {
break;
}
rounds += 1;
let live = B::mask(Mask::from_indices(n, &ids), device);
// Colour: the least live vertex that reaches each live vertex through live ones.
let mut colours = B::vector(Vector::sparse(n, ids.clone(), ids.clone())?, device);
let mut frontier = colours.clone();
while B::nvals(&frontier) > 0 {
let arrived = B::vxm(&frontier, &o, Some(&live), s, device)?;
frontier = B::accumulate(&mut colours, &arrived, s)?;
}
let host = B::vector_to_host(&colours);
let mut colour = vec![u32::MAX; n];
for (v, c) in host.iter() {
colour[v as usize] = c;
}
// Back from the roots, each search staying inside its colour.
let roots: Vec<u32> = ids
.iter()
.copied()
.filter(|&v| colour[v as usize] == v)
.collect();
for &r in &roots {
of[r as usize] = r;
alive[r as usize] = false;
}
// A vertex hears the colours of its successors in the frontier, none above its
// own: send them complemented so the minimum keeps the highest, its own if any.
let flipped: Vec<u32> = roots.iter().map(|&r| !r).collect();
let mut frontier = B::vector(Vector::sparse(n, roots, flipped)?, device);
while B::nvals(&frontier) > 0 {
let arrived = B::vxm(&frontier, &i, Some(&live), s, device)?;
let (c, a) = (&colour, &alive);
let kept = B::select_vector(&arrived, |v, x| a[v as usize] && c[v as usize] == !x);
for v in B::indices(&kept) {
of[v as usize] = colour[v as usize];
alive[v as usize] = false;
}
frontier = kept;
}
}
Ok(Components { of, rounds })
}