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

//! Minimum spanning forest on the CPU device's workers, by Borůvka's rounds.
//!
//! Every edge counts both ways (the matrix's rows are its tails, but `u -> v` joins `u` and
//! `v` whichever way it points); self-loops are left out, and parallel edges (repeated
//! entries, or an edge stored both ways) are all candidates. Edges are ordered by weight
//! and, among equal weights, by their place among the matrix's entries: a strict order, so
//! the forest is the one minimum spanning forest of that order whatever the number of
//! workers (Kruskal's in the same order gives the same edges).
//!
//! A round, every pass split over the workers in pieces of about equal edges:
//!
//! 1. Each component's lightest edge leaving it: an atomic minimum of the edge's weight key
//!    at both ends' components, the key packed above the edge's place when it fits in 32
//!    bits (one minimum then names the edge); else, among the edges of the least key, a
//!    second atomic minimum of the edge's place.
//! 2. Each component with such an edge hooks onto the component at the other end. Two
//!    components that chose the same edge are a pair (the only cycle a strict order lets
//!    the choices make): the lower stays a root. Each hook adds its edge to the forest, so
//!    each chosen edge is added once.
//! 3. The hooks are followed to their roots (path halving, then a pass that writes only
//!    roots), and the edges left are renamed to the roots at their ends, those inside one
//!    component dropped. The edges are kept as (root, root, key) in one list whose order is
//!    the entries' order, so a pass reads it straight through and looks up no vertex.
//!
//! The rounds stop when no edge is left between two components; at most `log2(n)` rounds,
//! as each round at least halves the components that still have an edge out.

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

use kleene_sparse::{CpuDevice, Csr, Value};

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

/// A weight a spanning forest can be taken over: totally ordered through a key (`None`
/// for a value with no place in the order, a float's NaN), and summed into its total.
pub trait ForestWeight: Value + Copy {
    /// The total of a forest's weights (wide enough for any number of edges for integers).
    type Total: Copy + std::fmt::Debug + PartialEq + Default + Send + Sync;
    /// The weight of an edge of a matrix that stores no values.
    const ONE: Self;
    /// A key whose order is the weights' order; `None` refuses the weight.
    fn key(self) -> Option<u64>;
    /// `total + self`.
    fn add_to(self, total: Self::Total) -> Self::Total;
}

macro_rules! unsigned_weight {
    ($($t:ty),*) => {$(
        impl ForestWeight for $t {
            type Total = u128;
            const ONE: Self = 1;
            #[inline]
            fn key(self) -> Option<u64> {
                Some(self as u64)
            }
            #[inline]
            fn add_to(self, total: u128) -> u128 {
                total + self as u128
            }
        }
    )*};
}
unsigned_weight!(u8, u16, u32, u64);

macro_rules! signed_weight {
    ($($t:ty),*) => {$(
        impl ForestWeight for $t {
            type Total = i128;
            const ONE: Self = 1;
            #[inline]
            fn key(self) -> Option<u64> {
                Some((self as i64 as u64) ^ (1 << 63))
            }
            #[inline]
            fn add_to(self, total: i128) -> i128 {
                total + self as i128
            }
        }
    )*};
}
signed_weight!(i32, i64);

impl ForestWeight for f64 {
    type Total = f64;
    const ONE: Self = 1.0;
    #[inline]
    fn key(self) -> Option<u64> {
        if self.is_nan() {
            return None;
        }
        // -0.0 and 0.0 weigh the same
        let b = (self + 0.0).to_bits();
        Some(if b >> 63 == 1 { !b } else { b | (1 << 63) })
    }
    #[inline]
    fn add_to(self, total: f64) -> f64 {
        total + self
    }
}

impl ForestWeight for f32 {
    type Total = f64;
    const ONE: Self = 1.0;
    #[inline]
    fn key(self) -> Option<u64> {
        f64::from(self).key()
    }
    #[inline]
    fn add_to(self, total: f64) -> f64 {
        total + f64::from(self)
    }
}

/// A minimum spanning forest: its edges, their total weight, its trees and the rounds run.
#[derive(Clone, Debug, PartialEq)]
pub struct SpanningForest<W: ForestWeight> {
    /// The forest's edges as the matrix stores them, `(row, column, weight)`, in the order
    /// of the matrix's entries.
    pub edges: Vec<(u32, u32, W)>,
    /// The sum of their weights (summed in the edges' order).
    pub total: W::Total,
    /// The trees: the components of the graph, a vertex with no edge one of its own
    /// (vertices minus edges).
    pub trees: usize,
    /// Borůvka rounds run.
    pub rounds: u32,
}

/// No edge yet / not an edge.
const NONE: u32 = u32::MAX;

/// A minimum spanning forest of the graph `weights` (each entry an edge between its row and
/// its column, taken both ways; a matrix with no values weighs every edge
/// [`ForestWeight::ONE`]) by Borůvka's rounds on the device's workers (see the module).
/// Refused: a matrix that is not square, a weight with no key (NaN), `u32::MAX` entries or
/// more.
pub fn spanning_forest<W: ForestWeight>(
    weights: &Csr<W>,
    cpu: &CpuDevice,
) -> crate::Result<SpanningForest<W>> {
    let n = weights.nrows();
    if weights.ncols() != n {
        return Err(GraphError::NotSquare {
            rows: n,
            cols: weights.ncols(),
        });
    }
    let m = weights.nnz();
    if m >= NONE as usize {
        return Err(GraphError::Weights(format!(
            "{m} edges, more than the {} a spanning forest takes",
            NONE - 1
        )));
    }
    let (off, idx) = (weights.pattern().offsets(), weights.pattern().indices());
    let vals = weights.values();
    let weight = |e: usize| vals.map_or(W::ONE, |v| v[e]);
    let cuts = pieces_by_entries(off, PIECE);
    // the edges that are not self-loops, each (end, end, weight key) and its entry, in
    // one segment of the lists per piece of rows (the segment of entries those rows hold),
    // its live edges at the front; segments are compacted in place, so a place in the
    // lists (its order the entries' order) stays the edge's for every round
    let segs = cuts.len() - 1;
    let start: Vec<usize> = cuts.iter().map(|&r| off[r] as usize).collect();
    let mut live: Vec<Live> = vec![[0u64; 2]; m];
    let mut ent = vec![0u32; m];
    let filled: Vec<(usize, Option<usize>)> = {
        let slots = segments(&mut live, &mut ent, &start);
        each_piece(cpu, segs, |p| {
            let mut g = slots[p].lock().unwrap_or_else(|e| e.into_inner());
            let (l, en) = &mut *g;
            let (mut k, mut bad) = (0usize, None);
            for u in cuts[p]..cuts[p + 1] {
                for e in off[u] as usize..off[u + 1] as usize {
                    let v = idx[e];
                    if v as usize == u {
                        continue;
                    }
                    match weight(e).key() {
                        Some(key) => {
                            l[k] = edge(u as u32, v, key);
                            en[k] = e as u32;
                            k += 1;
                        }
                        None => {
                            bad.get_or_insert(e);
                        }
                    }
                }
            }
            (k, bad)
        })
    };
    if let Some(e) = filled.iter().find_map(|f| f.1) {
        return Err(GraphError::Weights(format!(
            "the weight of entry {e} ({:?}) has no place in the order",
            weight(e)
        )));
    }
    let mut len: Vec<usize> = filled.iter().map(|f| f.0).collect();
    let live_at = |len: &[usize], p: usize| start[p]..start[p] + len[p];
    // keys below 2^32 are packed above the edge's place in the live list (whose order is
    // the entries' order: compaction keeps it), so one minimum names the edge
    let packed = each_piece(cpu, segs, |p| {
        live[live_at(&len, p)].iter().all(|l| l[1] >> 32 == 0)
    })
    .into_iter()
    .all(|x| x);
    let parent: Vec<AtomicU32> = (0..n as u32).map(AtomicU32::new).collect();
    let best_key: Vec<AtomicU64> = (0..n).map(|_| AtomicU64::new(u64::MAX)).collect();
    let best_pos: Vec<AtomicU32> = if packed {
        Vec::new()
    } else {
        (0..n).map(|_| AtomicU32::new(NONE)).collect()
    };
    // the place in the live list of the edge component `c` chose
    let best_of = |c: u32| {
        if packed {
            let k = best_key[c as usize].load(Relaxed);
            if k == u64::MAX { NONE } else { k as u32 }
        } else {
            best_pos[c as usize].load(Relaxed)
        }
    };
    let min_at = |slot: &AtomicU64, k: u64| {
        if k < slot.load(Relaxed) {
            slot.fetch_min(k, Relaxed);
        }
    };
    // the components that may still have an edge out
    let mut roots: Vec<u32> = (0..n as u32).collect();
    // the forest's entries, a bit each
    let picked: Vec<AtomicU64> = (0..m.div_ceil(64)).map(|_| AtomicU64::new(0)).collect();
    let mut rounds = 0u32;
    const ROOTS: usize = 1 << 14;
    while len.iter().any(|&k| k > 0) {
        rounds += 1;
        let edge_pieces = segs;
        let span = |p: usize| live_at(&len, p);
        // 1. each end's lightest edge: the packed key, or the key then the place
        each_piece(cpu, edge_pieces, |p| {
            for i in span(p) {
                let [ab, key] = live[i];
                let k = if packed { (key << 32) | i as u64 } else { key };
                min_at(&best_key[(ab >> 32) as usize], k);
                min_at(&best_key[ab as u32 as usize], k);
            }
        });
        if !packed {
            each_piece(cpu, edge_pieces, |p| {
                for i in span(p) {
                    let [ab, key] = live[i];
                    for c in [(ab >> 32) as u32, ab as u32] {
                        if best_key[c as usize].load(Relaxed) == key {
                            let slot = &best_pos[c as usize];
                            if (i as u32) < slot.load(Relaxed) {
                                slot.fetch_min(i as u32, Relaxed);
                            }
                        }
                    }
                }
            });
        }
        // 2. hooks: each root onto the other end of its edge, the lower of a pair stays
        let root_pieces = roots.len().div_ceil(ROOTS);
        let rpiece = |p: usize| &roots[p * ROOTS..((p + 1) * ROOTS).min(roots.len())];
        each_piece(cpu, root_pieces, |p| {
            for &c in rpiece(p) {
                let i = best_of(c);
                if i == NONE {
                    continue;
                }
                let ab = live[i as usize][0];
                let (a, b) = ((ab >> 32) as u32, ab as u32);
                let o = if a == c { b } else { a };
                if best_of(o) == i && c < o {
                    continue;
                }
                parent[c as usize].store(o, Relaxed);
                let e = ent[i as usize] as usize;
                picked[e / 64].fetch_or(1 << (e % 64), Relaxed);
            }
        });
        // 3. the hooks shortened by path halving, then every hooked root pointed at its
        // root (once the halving is over only roots are written, so a racing write cannot
        // undo one), the choices cleared, the roots that stay kept
        each_piece(cpu, root_pieces, |p| {
            for &c in rpiece(p) {
                let mut x = c;
                loop {
                    let px = parent[x as usize].load(Relaxed);
                    let gx = parent[px as usize].load(Relaxed);
                    if px == gx {
                        break;
                    }
                    parent[x as usize].store(gx, Relaxed);
                    x = gx;
                }
            }
        });
        let kept: Vec<Vec<u32>> = each_piece(cpu, root_pieces, |p| {
            let mut mine = Vec::new();
            for &c in rpiece(p) {
                let mut r = c;
                loop {
                    let pr = parent[r as usize].load(Relaxed);
                    if pr == r {
                        break;
                    }
                    r = pr;
                }
                parent[c as usize].store(r, Relaxed);
            }
            for &c in rpiece(p) {
                let had = best_of(c) != NONE;
                best_key[c as usize].store(u64::MAX, Relaxed);
                if !packed {
                    best_pos[c as usize].store(NONE, Relaxed);
                }
                if had && parent[c as usize].load(Relaxed) == c {
                    mine.push(c);
                }
            }
            mine
        });
        roots = kept.concat();
        // the edges between two components left, their ends renamed to the new roots,
        // each segment compacted in place
        let slots = segments(&mut live, &mut ent, &start);
        let left: Vec<usize> = each_piece(cpu, segs, |p| {
            let mut g = slots[p].lock().unwrap_or_else(|e| e.into_inner());
            let (l, en) = &mut *g;
            let mut k = 0;
            for i in 0..len[p] {
                let [ab, key] = l[i];
                let a = parent[(ab >> 32) as usize].load(Relaxed);
                let b = parent[ab as u32 as usize].load(Relaxed);
                if a != b {
                    l[k] = edge(a, b, key);
                    en[k] = en[i];
                    k += 1;
                }
            }
            k
        });
        drop(slots);
        len = left;
    }
    // the forest in the entries' order, each piece of rows on a worker
    let parts: Vec<Vec<(u32, u32, W)>> = each_piece(cpu, segs, |p| {
        let mut mine = Vec::new();
        for u in cuts[p]..cuts[p + 1] {
            for e in off[u] as usize..off[u + 1] as usize {
                if picked[e / 64].load(Relaxed) >> (e % 64) & 1 == 1 {
                    mine.push((u as u32, idx[e], weight(e)));
                }
            }
        }
        mine
    });
    let edges = parts.concat();
    let total = edges
        .iter()
        .fold(W::Total::default(), |t, &(_, _, w)| w.add_to(t));
    Ok(SpanningForest {
        trees: n - edges.len(),
        edges,
        total,
        rounds,
    })
}

/// The segments of `live` and `ent` that begin at `start` (the last value the end), each
/// behind a lock for the one worker that takes it.
#[allow(clippy::type_complexity)]
fn segments<'a>(
    mut live: &'a mut [Live],
    mut ent: &'a mut [u32],
    start: &[usize],
) -> Vec<Mutex<(&'a mut [Live], &'a mut [u32])>> {
    let mut out = Vec::with_capacity(start.len().saturating_sub(1));
    for w in start.windows(2) {
        let (l, rest) = live.split_at_mut(w[1] - w[0]);
        let (e, erest) = ent.split_at_mut(w[1] - w[0]);
        out.push(Mutex::new((l, e)));
        live = rest;
        ent = erest;
    }
    out
}

/// An edge between two components: their roots in one word (`a << 32 | b`), its weight
/// key in the other.
type Live = [u64; 2];

fn edge(a: u32, b: u32, key: u64) -> Live {
    [(u64::from(a) << 32) | u64::from(b), key]
}