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

use std::collections::BTreeMap;

use arrow_buffer::ScalarBuffer;
use kleene_sparse::{BitsetUnion, Csr, Mask, MinPlus, SparseBackend, Vector};

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

const LOW: u64 = 0xFFFF_FFFF;

/// Shortest paths from one source: a distance and a parent per reached vertex.
#[derive(Clone, Debug)]
pub struct Paths {
    source: u32,
    /// `(distance << 32) | parent` per reached vertex.
    packed: Vector<u64>,
    /// Relaxation steps.
    pub rounds: u32,
    /// Steps that pulled (the rest pushed).
    pub pulls: u32,
}

impl Paths {
    /// Paths from `source` given as `(distance << 32) | parent` per reached vertex (the
    /// source holds `source`): how a backend with its own search hands its answer back.
    pub fn from_packed(source: u32, packed: Vector<u64>, rounds: u32, pulls: u32) -> Self {
        Paths {
            source,
            packed,
            rounds,
            pulls,
        }
    }

    /// The source.
    pub fn source(&self) -> u32 {
        self.source
    }

    /// The distance to `v`, if reached.
    pub fn distance(&self, v: u32) -> Option<u64> {
        self.packed.get(v as usize).map(|x| x >> 32)
    }

    /// The vertex before `v` on a shortest path (the source is its own parent).
    pub fn parent(&self, v: u32) -> Option<u32> {
        self.packed.get(v as usize).map(|x| (x & LOW) as u32)
    }

    /// A shortest path from the source to `v`, both ends included (among equal paths the
    /// one through the lowest-numbered parents).
    pub fn path(&self, v: u32) -> Option<Vec<u32>> {
        let mut out = vec![v];
        let mut at = v;
        while at != self.source {
            at = self.parent(at)?;
            out.push(at);
            if out.len() > self.packed.len() + 1 {
                return None;
            }
        }
        out.reverse();
        Some(out)
    }

    /// The reached vertices, rising.
    pub fn reached(&self) -> Vec<u32> {
        self.packed.indices()
    }
}

/// How [`sssp_of`] steps.
#[derive(Clone, Debug)]
pub struct SsspOptions {
    /// Bucket width of delta-stepping (`None`: the mean edge weight, 1 when structural).
    pub delta: Option<u64>,
    /// Pull (when the transpose is given) once the frontier's out-edges times this exceed
    /// the edges into unsettled vertices.
    pub alpha: u64,
}

impl Default for SsspOptions {
    fn default() -> Self {
        SsspOptions {
            delta: None,
            alpha: 14,
        }
    }
}

/// `weights` with each value moved to the high word (`1 << 32` per edge when structural).
fn shifted(weights: &Csr<u32>) -> crate::Result<Csr<u64>> {
    let v: Vec<u64> = match weights.values() {
        Some(w) => w.iter().map(|&x| (x as u64) << 32).collect(),
        None => vec![1u64 << 32; weights.nnz()],
    };
    Ok(Csr::with_pattern(
        weights.pattern().clone(),
        Some(ScalarBuffer::from(v)),
    )?)
}

/// Shortest paths from `source` along the weighted edges of `weights` (row `u` holds the
/// targets of `u` with each edge's weight; a structural matrix weighs every edge 1).
pub fn sssp<B: GraphBackend>(
    weights: &Csr<u32>,
    source: u32,
    device: &B::Device,
) -> crate::Result<Paths> {
    sssp_of::<B>(weights, None, source, &SsspOptions::default(), device)
}

/// Shortest paths by delta-stepping over `(distance << 32) | vertex` words under min-plus:
/// the minimum keeps the shortest distance and, among equal ones, the lowest parent, so the
/// path is kept with no second pass.
///
/// Vertices are taken in buckets of width `delta` by distance. A bucket is relaxed until
/// nothing in it changes; then its vertices are settled (no path can still shorten them)
/// and masked out of every later step, so no edge into a settled vertex is looked at again.
/// A step pushes the frontier along its out-edges (`vxm`), or, with `transposed` (the same
/// edges by target) given and a large frontier, lets every unsettled vertex pull from its
/// in-edges (`mxv`). Distances must stay below 2^32 (a longer one reads as no path).
pub fn sssp_of<B: GraphBackend>(
    weights: &Csr<u32>,
    transposed: Option<&Csr<u32>>,
    source: u32,
    opts: &SsspOptions,
    device: &B::Device,
) -> crate::Result<Paths> {
    check_sssp(weights, transposed, source)?;
    B::sssp_of(weights, transposed, source, opts, device)
}

/// The checks every [`sssp_of`] makes, whichever backend runs it.
fn check_sssp(weights: &Csr<u32>, transposed: Option<&Csr<u32>>, source: u32) -> crate::Result<()> {
    let n = weights.nrows();
    if weights.ncols() != n {
        return Err(GraphError::NotSquare {
            rows: n,
            cols: weights.ncols(),
        });
    }
    if source as usize >= n {
        return Err(GraphError::SourceOutOfRange {
            source,
            vertices: n,
        });
    }
    if let Some(t) = transposed
        && (t.nrows() != n || t.ncols() != n || t.nnz() != weights.nnz())
    {
        return Err(GraphError::NoTranspose);
    }
    Ok(())
}

/// The bucket width [`sssp_of`] uses: `opts.delta`, or the mean weight (1 when structural).
pub fn sssp_delta(weights: &Csr<u32>, opts: &SsspOptions) -> u64 {
    opts.delta
        .unwrap_or_else(|| match weights.values() {
            Some(w) if !w.is_empty() => w.iter().map(|&x| x as u64).sum::<u64>() / w.len() as u64,
            _ => 1,
        })
        .max(1)
}

/// [`sssp_of`] through the backend's operations (the default of [`GraphBackend::sssp_of`]).
pub fn sssp_of_generic<B: SparseBackend>(
    weights: &Csr<u32>,
    transposed: Option<&Csr<u32>>,
    source: u32,
    opts: &SsspOptions,
    device: &B::Device,
) -> crate::Result<Paths> {
    check_sssp(weights, transposed, source)?;
    let n = weights.nrows();
    let delta = sssp_delta(weights, opts);
    let s = MinPlus::<u64>::new();
    let w = B::matrix(shifted(weights)?, device);
    let wt = transposed
        .map(|t| shifted(t).map(|m| B::matrix(m, device)))
        .transpose()?;
    let edges = weights.nnz() as u64;
    let mut dist = vec![u64::MAX; n];
    dist[source as usize] = source as u64;
    let mut unsettled = Mask::all(n);
    let mut left = n as u64;
    let mut buckets: BTreeMap<u64, Vec<u32>> = BTreeMap::from([(0, vec![source])]);
    let (mut rounds, mut pulls) = (0u32, 0u32);
    let bucket_of = |x: u64| (x >> 32) / delta;
    while let Some((b, mut frontier)) = buckets.pop_first() {
        frontier.retain(|&v| unsettled.allows(v as usize) && bucket_of(dist[v as usize]) == b);
        frontier.sort_unstable();
        frontier.dedup();
        let mut settle: Vec<u32> = Vec::new();
        while !frontier.is_empty() {
            rounds += 1;
            let vals: Vec<u64> = frontier
                .iter()
                .map(|&v| (dist[v as usize] & !LOW) | v as u64)
                .collect();
            let fv = B::vector(Vector::sparse(n, frontier.clone(), vals)?, device);
            let mask = B::mask(unsettled.clone(), device);
            let out_edges: u64 = frontier
                .iter()
                .map(|&v| weights.row(v as usize).len() as u64)
                .sum();
            let arrived = match &wt {
                Some(t) if out_edges * opts.alpha > edges * left / n.max(1) as u64 => {
                    pulls += 1;
                    B::mxv(t, &fv, Some(&mask), s, device)?
                }
                _ => B::vxm(&fv, &w, Some(&mask), s, device)?,
            };
            settle.extend_from_slice(&frontier);
            let mut next = Vec::new();
            for (v, x) in B::vector_to_host(&arrived).iter() {
                let vu = v as usize;
                if x < dist[vu] {
                    dist[vu] = x;
                    let bv = bucket_of(x);
                    if bv <= b {
                        next.push(v);
                    } else {
                        buckets.entry(bv).or_default().push(v);
                    }
                }
            }
            next.sort_unstable();
            next.dedup();
            frontier = next;
        }
        // `unsettled` starts as every place (a complemented mask): `close` settles a
        // vertex in either form, once, however often it was in the bucket's frontiers.
        for v in settle {
            if unsettled.close(v as usize) {
                left -= 1;
            }
        }
    }
    let (idx, val): (Vec<u32>, Vec<u64>) = dist
        .iter()
        .enumerate()
        .filter(|&(_, &d)| d != u64::MAX)
        .map(|(v, &d)| (v as u32, d))
        .unzip();
    Ok(Paths {
        source,
        packed: Vector::sparse(n, idx, val)?,
        rounds,
        pulls,
    })
}

/// For every vertex, which of the sources reach it.
#[derive(Clone, Debug)]
pub struct SourceSets {
    sources: Vec<u32>,
    /// One word per vertex per batch of 64 sources: bit `k` of batch `b` is source
    /// `64 b + k`.
    batches: Vec<Vector<u64>>,
    /// Rounds of each batch.
    pub rounds: Vec<u32>,
}

impl SourceSets {
    /// Sets given as one word per vertex per batch of 64 sources (bit `k` of batch `b` is
    /// source `64 b + k`), with the rounds of each batch.
    pub fn from_batches(sources: Vec<u32>, batches: Vec<Vector<u64>>, rounds: Vec<u32>) -> Self {
        SourceSets {
            sources,
            batches,
            rounds,
        }
    }

    /// The sources, in the order given.
    pub fn sources(&self) -> &[u32] {
        &self.sources
    }

    /// One word per vertex per batch of 64 sources: bit `k` of batch `b`'s word at `v` is
    /// set when source `64 b + k` reaches `v`.
    pub fn batches(&self) -> &[Vector<u64>] {
        &self.batches
    }

    /// The sources that reach `v` (a source reaches itself), in the order given.
    pub fn sources_of(&self, v: u32) -> Vec<u32> {
        let mut out = Vec::new();
        for (b, batch) in self.batches.iter().enumerate() {
            let mut w = batch.get(v as usize).unwrap_or(0);
            while w != 0 {
                let k = w.trailing_zeros() as usize;
                w &= w - 1;
                out.push(self.sources[b * 64 + k]);
            }
        }
        out
    }

    /// The vertices some source reaches, rising.
    pub fn reached(&self) -> Vec<u32> {
        let mut all: Vec<u32> = self.batches.iter().flat_map(|b| b.indices()).collect();
        all.sort_unstable();
        all.dedup();
        all
    }
}

/// Set propagation: for every vertex the set of `sources` that reach it along `a`'s rows,
/// 64 sources per word, one bitset-union propagation per batch of 64.
pub fn reach_sets<B: GraphBackend>(
    a: &Csr<u8>,
    sources: &[u32],
    device: &B::Device,
) -> crate::Result<SourceSets> {
    check_sets(a, sources)?;
    B::reach_sets(a, sources, device)
}

/// The checks every [`reach_sets`] makes, whichever backend runs it.
fn check_sets(a: &Csr<u8>, sources: &[u32]) -> crate::Result<()> {
    let n = a.nrows();
    if a.ncols() != n {
        return Err(GraphError::NotSquare {
            rows: n,
            cols: a.ncols(),
        });
    }
    if let Some(&s) = sources.iter().find(|&&s| s as usize >= n) {
        return Err(GraphError::SourceOutOfRange {
            source: s,
            vertices: n,
        });
    }
    Ok(())
}

/// [`reach_sets`] through the backend's operations (the default of
/// [`GraphBackend::reach_sets`]).
pub fn reach_sets_generic<B: SparseBackend>(
    a: &Csr<u8>,
    sources: &[u32],
    device: &B::Device,
) -> crate::Result<SourceSets> {
    check_sets(a, sources)?;
    let n = a.nrows();
    let m = B::matrix(a.pattern().to_structural::<u64>(), device);
    let mut batches = Vec::new();
    let mut rounds = Vec::new();
    for chunk in sources.chunks(64) {
        let pairs: Vec<(u32, u64)> = chunk
            .iter()
            .enumerate()
            .map(|(k, &s)| (s, 1u64 << k))
            .collect();
        let init = Vector::from_pairs(n, pairs, BitsetUnion)?;
        let r = propagate::<B, _>(&m, B::vector(init, device), BitsetUnion, None, device)?;
        batches.push(B::vector_to_host(&r.values));
        rounds.push(r.rounds);
    }
    Ok(SourceSets {
        sources: sources.to_vec(),
        batches,
        rounds,
    })
}