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

//! Labelled set propagation: many sources at once, each edge passing only the sources its
//! label lets through (an entry set per edge).

use kleene_sparse::{BitsetUnion, Csr, SparseBackend, Vector};

use crate::paths::SourceSets;
use crate::propagate::propagate;
use crate::{GraphBackend, GraphError};

/// What each edge of a graph lets through, for [`label_reach`]: the edge at target slot
/// `j` (its place in the matrix's column indices) passes the sources in set
/// `slot_set[j]`, and set `s` is `set_words[s * words..(s + 1) * words]` (bit `k` of word
/// `b` is source `64 b + k`).
#[derive(Clone, Copy, Debug)]
pub struct EdgeSets<'a> {
    slot_set: &'a [u32],
    set_words: &'a [u64],
    words: usize,
}

impl<'a> EdgeSets<'a> {
    /// A set id per edge slot and `words` words per set, set after set. Refused: no
    /// words, words that are not whole sets, a slot naming a set that is not there.
    pub fn new(slot_set: &'a [u32], set_words: &'a [u64], words: usize) -> crate::Result<Self> {
        if words == 0 || !set_words.len().is_multiple_of(words) {
            return Err(GraphError::Labels(format!(
                "{} words are not whole sets of {words}",
                set_words.len()
            )));
        }
        let sets = set_words.len() / words;
        if let Some(&s) = slot_set.iter().find(|&&s| s as usize >= sets) {
            return Err(GraphError::Labels(format!(
                "an edge names set {s} of {sets}"
            )));
        }
        Ok(EdgeSets {
            slot_set,
            set_words,
            words,
        })
    }

    /// The set of each edge slot.
    pub fn slot_set(&self) -> &'a [u32] {
        self.slot_set
    }

    /// The sets' words, set after set.
    pub fn set_words(&self) -> &'a [u64] {
        self.set_words
    }

    /// Words per set.
    pub fn words(&self) -> usize {
        self.words
    }

    /// Word `b` of the set of edge slot `j`.
    #[inline]
    pub fn word(&self, j: usize, b: usize) -> u64 {
        self.set_words[self.slot_set[j] as usize * self.words + b]
    }
}

/// Labelled set propagation: for every vertex, which of the `sources` (numbered
/// `0..sources`) reach it along `a`'s rows when the edge at slot `j` passes only the
/// sources of its set. Source `k` starts at every vertex `v` of a seed `(v, k)` (a source
/// reaches the vertices it starts at). The answer does not depend on the backend or its
/// thread count.
pub fn label_reach<B: GraphBackend>(
    a: &Csr<u8>,
    sets: EdgeSets<'_>,
    seeds: &[(u32, u32)],
    sources: usize,
    device: &B::Device,
) -> crate::Result<SourceSets> {
    check(a, sets, seeds, sources)?;
    B::label_reach(a, sets, seeds, sources, device)
}

/// The checks every [`label_reach`] makes.
fn check(
    a: &Csr<u8>,
    sets: EdgeSets<'_>,
    seeds: &[(u32, u32)],
    sources: usize,
) -> crate::Result<()> {
    let n = a.nrows();
    if a.ncols() != n {
        return Err(GraphError::NotSquare {
            rows: n,
            cols: a.ncols(),
        });
    }
    if sets.slot_set.len() != a.nnz() {
        return Err(GraphError::Labels(format!(
            "{} edge sets for {} edges",
            sets.slot_set.len(),
            a.nnz()
        )));
    }
    if sources > sets.words * 64 {
        return Err(GraphError::Labels(format!(
            "{sources} sources in sets of {} words",
            sets.words
        )));
    }
    for &(v, k) in seeds {
        if v as usize >= n {
            return Err(GraphError::SourceOutOfRange {
                source: v,
                vertices: n,
            });
        }
        if k as usize >= sources {
            return Err(GraphError::Labels(format!(
                "a seed of source {k} of {sources}"
            )));
        }
    }
    Ok(())
}

/// [`label_reach`] through the backend's operations (the default of
/// [`GraphBackend::label_reach`]): per batch of 64 sources, the edges valued by their
/// set's word for the batch (edges that pass none dropped), then a bitset propagation
/// (union as add, intersection as multiply: an edge hands on the bits its set holds).
pub fn label_reach_generic<B: SparseBackend>(
    a: &Csr<u8>,
    sets: EdgeSets<'_>,
    seeds: &[(u32, u32)],
    sources: usize,
    device: &B::Device,
) -> crate::Result<SourceSets> {
    check(a, sets, seeds, sources)?;
    let n = a.nrows();
    let (off, adj) = (a.pattern().offsets(), a.pattern().indices());
    let mut batches = Vec::new();
    let mut rounds = Vec::new();
    let (mut src, mut dst, mut val) = (Vec::new(), Vec::new(), Vec::new());
    for b in 0..sources.div_ceil(64) {
        src.clear();
        dst.clear();
        val.clear();
        for v in 0..n {
            for j in off[v] as usize..off[v + 1] as usize {
                let w = sets.word(j, b);
                if w != 0 {
                    src.push(v as u32);
                    dst.push(adj[j]);
                    val.push(w);
                }
            }
        }
        let m = Csr::from_edges(n, n, &src, &dst, Some(&val), BitsetUnion)?;
        let pairs: Vec<(u32, u64)> = seeds
            .iter()
            .filter(|&&(_, k)| k as usize / 64 == b)
            .map(|&(v, k)| (v, 1u64 << (k % 64)))
            .collect();
        let init = Vector::from_pairs(n, pairs, BitsetUnion)?;
        let r = propagate::<B, _>(
            &B::matrix(m, device),
            B::vector(init, device),
            BitsetUnion,
            None,
            device,
        )?;
        batches.push(B::vector_to_host(&r.values));
        rounds.push(r.rounds);
    }
    Ok(SourceSets::from_batches(
        (0..sources as u32).collect(),
        batches,
        rounds,
    ))
}