Your browser sucks, JavaScript disabled! Gunnar's console needs JavaScript and WebAssembly. Git over SSH on port 2222 does not.

nordisk/kleene

crates/kleene-index/src/reach.rs

//! Reachability: "can A reach B" from the strong-component condensation and 2-hop labels,
//! and "who reaches X" as one bitset per target set.
//!
//! The labels are pruned landmark labels on the condensation (a DAG): components are taken
//! in order of (in-degree + 1) * (out-degree + 1), highest first, and each one's rank is
//! written into the in-label of every component it reaches and the out-label of every one
//! reaching it, unless the labels so far already answer that pair. Then A reaches B
//! exactly when A and B share a component, or the out-label of A's component and the
//! in-label of B's share a rank: a merge of two short sorted lists.

use arrow_buffer::ScalarBuffer;
use gatling::gatling_mask_walk::{Condensed, Csr as GCsr};

use crate::error::{Result, bad};

const NONE: u32 = u32::MAX;

/// Strong components (gatling's `Condensed`: Tarjan's, without recursion), numbered so
/// that an edge between two components goes from a higher number to a lower one.
fn strong_components(off: &[u64], adj: &[u32]) -> (Vec<u32>, u32) {
    let c = Condensed::new(GCsr::new(off, adj));
    let comp = (0..(off.len() - 1) as u32)
        .map(|v| c.component(v))
        .collect();
    (comp, c.components() as u32)
}

/// A CSR over `n` rows from (row, column) pairs, columns rising and unique per row.
fn csr(n: usize, mut pairs: Vec<(u32, u32)>) -> (Vec<u64>, Vec<u32>) {
    pairs.sort_unstable();
    pairs.dedup();
    let mut off = vec![0u64; n + 1];
    for &(r, _) in &pairs {
        off[r as usize + 1] += 1;
    }
    for i in 0..n {
        off[i + 1] += off[i];
    }
    (off, pairs.into_iter().map(|(_, c)| c).collect())
}

fn share(a: &[u32], b: &[u32]) -> bool {
    let (mut i, mut j) = (0, 0);
    while i < a.len() && j < b.len() {
        match a[i].cmp(&b[j]) {
            std::cmp::Ordering::Less => i += 1,
            std::cmp::Ordering::Greater => j += 1,
            std::cmp::Ordering::Equal => return true,
        }
    }
    false
}

/// "Can A reach B" for every pair of vertices, in a few compares (see the module doc).
#[derive(Clone, Debug)]
pub struct Reach {
    comp: ScalarBuffer<u32>,
    out_off: ScalarBuffer<u64>,
    out_lab: ScalarBuffer<u32>,
    in_off: ScalarBuffer<u64>,
    in_lab: ScalarBuffer<u32>,
}

impl Reach {
    /// Labels for the graph whose vertex `v` has the out-neighbours
    /// `adj[off[v]..off[v + 1]]`.
    pub fn build(off: &[u64], adj: &[u32]) -> Result<Self> {
        check_csr(off, adj)?;
        let n = off.len() - 1;
        let (comp, comps) = strong_components(off, adj);
        let c = comps as usize;
        let mut pairs = Vec::new();
        for v in 0..n {
            for &w in &adj[off[v] as usize..off[v + 1] as usize] {
                let (a, b) = (comp[v], comp[w as usize]);
                if a != b {
                    pairs.push((a, b));
                }
            }
        }
        let rev: Vec<(u32, u32)> = pairs.iter().map(|&(a, b)| (b, a)).collect();
        let (doff, dadj) = csr(c, pairs);
        let (roff, radj) = csr(c, rev);
        let deg = |o: &[u64], x: usize| o[x + 1] - o[x];
        let mut order: Vec<u32> = (0..comps).collect();
        order.sort_by_key(|&x| {
            let x = x as usize;
            (
                std::cmp::Reverse((deg(&doff, x) + 1) * (deg(&roff, x) + 1)),
                x,
            )
        });
        let mut lin: Vec<Vec<u32>> = vec![Vec::new(); c];
        let mut lout: Vec<Vec<u32>> = vec![Vec::new(); c];
        let mut seen = vec![NONE; c];
        let mut queue: Vec<u32> = Vec::new();
        for (rank, &v) in order.iter().enumerate() {
            let (rank, v) = (rank as u32, v as usize);
            // forward: v reaches u
            queue.clear();
            queue.push(v as u32);
            seen[v] = 2 * rank;
            let mut head = 0;
            while head < queue.len() {
                let u = queue[head] as usize;
                head += 1;
                if share(&lout[v], &lin[u]) {
                    continue;
                }
                lin[u].push(rank);
                for &w in &dadj[doff[u] as usize..doff[u + 1] as usize] {
                    if seen[w as usize] != 2 * rank {
                        seen[w as usize] = 2 * rank;
                        queue.push(w);
                    }
                }
            }
            // backward: u reaches v (v itself is always labelled)
            queue.clear();
            queue.push(v as u32);
            seen[v] = 2 * rank + 1;
            let mut head = 0;
            while head < queue.len() {
                let u = queue[head] as usize;
                head += 1;
                if u != v && share(&lout[u], &lin[v]) {
                    continue;
                }
                lout[u].push(rank);
                for &w in &radj[roff[u] as usize..roff[u + 1] as usize] {
                    if seen[w as usize] != 2 * rank + 1 {
                        seen[w as usize] = 2 * rank + 1;
                        queue.push(w);
                    }
                }
            }
        }
        let flat = |l: Vec<Vec<u32>>| {
            let mut off = Vec::with_capacity(l.len() + 1);
            off.push(0u64);
            let mut all = Vec::new();
            for x in l {
                all.extend_from_slice(&x);
                off.push(all.len() as u64);
            }
            (ScalarBuffer::from(off), ScalarBuffer::from(all))
        };
        let (out_off, out_lab) = flat(lout);
        let (in_off, in_lab) = flat(lin);
        Ok(Reach {
            comp: comp.into(),
            out_off,
            out_lab,
            in_off,
            in_lab,
        })
    }

    /// Labels from their stored parts (as [`Reach::parts`] gave them).
    pub fn from_parts(
        parts: [ScalarBuffer<u64>; 2],
        labels: [ScalarBuffer<u32>; 3],
    ) -> Result<Self> {
        let [out_off, in_off] = parts;
        let [comp, out_lab, in_lab] = labels;
        let c = out_off
            .len()
            .checked_sub(1)
            .ok_or_else(|| bad("no label offsets"))?;
        let fits = |off: &ScalarBuffer<u64>, lab: &ScalarBuffer<u32>| {
            off.len() == c + 1
                && off.windows(2).all(|w| w[0] <= w[1])
                && off.last() == Some(&(lab.len() as u64))
                && lab.iter().all(|&r| (r as usize) < c)
        };
        if !fits(&out_off, &out_lab)
            || !fits(&in_off, &in_lab)
            || comp.iter().any(|&x| x as usize >= c)
        {
            return Err(bad("stored reach labels do not fit together"));
        }
        Ok(Reach {
            comp,
            out_off,
            out_lab,
            in_off,
            in_lab,
        })
    }

    /// `[out_off, in_off]` and `[comp, out_labels, in_labels]`.
    pub fn parts(&self) -> ([&ScalarBuffer<u64>; 2], [&ScalarBuffer<u32>; 3]) {
        (
            [&self.out_off, &self.in_off],
            [&self.comp, &self.out_lab, &self.in_lab],
        )
    }

    /// The number of vertices.
    pub fn vertices(&self) -> usize {
        self.comp.len()
    }

    /// The number of strong components.
    pub fn components(&self) -> usize {
        self.out_off.len() - 1
    }

    /// The strong component of `v` (an edge between components goes from a higher number
    /// to a lower one).
    pub fn component(&self, v: u32) -> u32 {
        self.comp[v as usize]
    }

    /// Label entries in all (in and out).
    pub fn label_entries(&self) -> usize {
        self.out_lab.len() + self.in_lab.len()
    }

    /// Whether a path leads from `a` to `b` (every vertex reaches itself).
    #[inline]
    pub fn reaches(&self, a: u32, b: u32) -> bool {
        let (ca, cb) = (
            self.comp[a as usize] as usize,
            self.comp[b as usize] as usize,
        );
        if ca == cb {
            return true;
        }
        if ca < cb {
            return false;
        }
        let out = &self.out_lab[self.out_off[ca] as usize..self.out_off[ca + 1] as usize];
        let inn = &self.in_lab[self.in_off[cb] as usize..self.in_off[cb + 1] as usize];
        share(out, inn)
    }
}

fn check_csr(off: &[u64], adj: &[u32]) -> Result<()> {
    let n = off.len().checked_sub(1).ok_or_else(|| bad("no offsets"))?;
    if u32::try_from(n).is_err() {
        return Err(bad("more than 2^32 vertices"));
    }
    if off[0] != 0
        || off.windows(2).any(|w| w[0] > w[1])
        || off[n] != adj.len() as u64
        || adj.iter().any(|&w| w as usize >= n)
    {
        return Err(bad("offsets and neighbours do not make a square graph"));
    }
    Ok(())
}

/// For each target set, the bitset of the vertices that reach it (a target reaches its own
/// set).
#[derive(Clone, Debug)]
pub struct ReverseReach {
    vertices: usize,
    words: usize,
    bits: ScalarBuffer<u64>,
}

impl ReverseReach {
    /// One backward search per set over the graph given by its by-destination offsets and
    /// neighbours (`in_adj[in_off[v]..in_off[v + 1]]` are the sources of edges into `v`).
    /// The sets are searched in parallel on gatling.
    pub fn build(in_off: &[u64], in_adj: &[u32], sets: &[Vec<u32>]) -> Result<Self> {
        check_csr(in_off, in_adj)?;
        let n = in_off.len() - 1;
        if sets.iter().flatten().any(|&t| t as usize >= n) {
            return Err(bad("a target is not a vertex"));
        }
        let words = n.div_ceil(64);
        let workers = gatling::gatling_forkjoin::default_workers();
        let one = |s: usize| -> Vec<u64> {
            let mut bits = vec![0u64; words];
            let mut queue: Vec<u32> = Vec::new();
            for &t in &sets[s] {
                let t = t as usize;
                if bits[t / 64] & (1 << (t % 64)) == 0 {
                    bits[t / 64] |= 1 << (t % 64);
                    queue.push(t as u32);
                }
            }
            let mut head = 0;
            while head < queue.len() {
                let u = queue[head] as usize;
                head += 1;
                for &w in &in_adj[in_off[u] as usize..in_off[u + 1] as usize] {
                    let w = w as usize;
                    if bits[w / 64] & (1 << (w % 64)) == 0 {
                        bits[w / 64] |= 1 << (w % 64);
                        queue.push(w as u32);
                    }
                }
            }
            bits
        };
        let per = gatling::gatling_forkjoin::gatling_for_each(sets.len(), workers, one);
        let bits: Vec<u64> = per.into_iter().flatten().collect();
        Ok(ReverseReach {
            vertices: n,
            words,
            bits: bits.into(),
        })
    }

    /// Bitsets from their stored words (`sets * ceil(vertices / 64)` of them).
    pub fn from_parts(vertices: usize, bits: ScalarBuffer<u64>) -> Result<Self> {
        let words = vertices.div_ceil(64);
        if words == 0 && !bits.is_empty() || words > 0 && !bits.len().is_multiple_of(words) {
            return Err(bad("stored reach bitsets do not fit the vertex count"));
        }
        Ok(ReverseReach {
            vertices,
            words,
            bits,
        })
    }

    /// The words of every set's bitset, set after set.
    pub fn words(&self) -> &ScalarBuffer<u64> {
        &self.bits
    }

    /// The number of vertices.
    pub fn vertices(&self) -> usize {
        self.vertices
    }

    /// The number of target sets.
    pub fn sets(&self) -> usize {
        self.bits.len().checked_div(self.words).unwrap_or(0)
    }

    fn set(&self, s: usize) -> &[u64] {
        &self.bits[s * self.words..(s + 1) * self.words]
    }

    /// Whether `v` reaches target set `s`.
    #[inline]
    pub fn reaches(&self, v: u32, s: usize) -> bool {
        let v = v as usize;
        self.set(s)[v / 64] & (1 << (v % 64)) != 0
    }

    /// How many vertices reach set `s`.
    pub fn count(&self, s: usize) -> usize {
        kleene_sparse::Simd::detect().popcount(self.set(s))
    }

    /// The vertices that reach set `s`, rising.
    pub fn who(&self, s: usize) -> impl Iterator<Item = u32> + '_ {
        self.set(s).iter().enumerate().flat_map(|(i, &w)| {
            let mut w = w;
            std::iter::from_fn(move || {
                (w != 0).then(|| {
                    let b = w.trailing_zeros();
                    w &= w - 1;
                    (i * 64) as u32 + b
                })
            })
        })
    }
}