crates/kleene-graph/src/walks.rs
//! Walks of bounded length: the vertices (or the source, vertex pairs) joined by a walk
//! whose number of edges lies in a range.
use kleene_sparse::{BoolOrAnd, Csr, Mask, SparseBackend, Vector};
use crate::{BfsOptions, Graph, GraphBackend, GraphError, bfs};
/// How many edges a walk takes: from `min` to `max` (`None`: no bound), both included.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Hops {
/// The fewest edges.
pub min: u64,
/// The most edges; `None`: no bound.
pub max: Option<u64>,
}
impl Hops {
/// `min..=max` edges.
pub fn new(min: u64, max: Option<u64>) -> Self {
Hops { min, max }
}
/// Whether no length lies in the range.
pub fn is_empty(&self) -> bool {
self.max.is_some_and(|m| m < self.min)
}
}
/// The ends of walks and how the search went.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct WalkEnds {
/// The ends, rising.
pub vertices: Vec<u32>,
/// Frontier steps taken.
pub steps: u64,
}
/// The vertices at the end of a walk from one of `sources` along the edges of `g` whose
/// length lies in `hops` (GQL's WALK mode: vertices and edges may repeat, so a vertex is
/// an end of every length some walk to it has, not only of its distance).
///
/// Frontier steps on the graph core: `F(0)` = the sources, `F(i+1)` = every vertex an
/// edge leads to from `F(i)` (a push step with nothing closed: no visited set), the answer
/// the union of `F(min)` .. `F(max)`. The steps stop early when a frontier is empty, or
/// when, past `min`, a frontier adds nothing to the union: every later frontier is the
/// image of one already in it, so it adds nothing either. With no `max`, the walks of
/// `min` edges or more are a breadth-first search from `F(min)`.
pub fn walk_ends<B: GraphBackend>(
g: &Graph<B>,
sources: &[u32],
hops: Hops,
device: &B::Device,
) -> crate::Result<WalkEnds> {
let n = g.vertices();
if let Some(&s) = sources.iter().find(|&&s| s as usize >= n) {
return Err(GraphError::SourceOutOfRange {
source: s,
vertices: n,
});
}
if hops.is_empty() || sources.is_empty() {
return Ok(WalkEnds {
vertices: Vec::new(),
steps: 0,
});
}
let all = Mask::all(n);
let mut open = B::mask(all.clone(), device);
let mut ws = B::workspace(n, device);
let mut frontier = B::vector(Vector::from_indices(n, sources, 1u8)?, device);
let mut next = B::vector(Vector::<u8>::empty(n), device);
// The union so far.
let mut union = B::vector(Vector::<u8>::empty(n), device);
let mut in_union = 0usize;
let mut steps = 0u64;
let mut depth = 0u64;
loop {
if depth >= hops.min {
if hops.max.is_none() {
let r = bfs(g, &B::indices(&frontier), &BfsOptions::default(), device)?;
return Ok(WalkEnds {
vertices: r.vertices(),
steps: steps + r.steps.len() as u64,
});
}
B::assign_scalar(&mut union, &frontier, 1, 0);
let now = B::nvals(&union);
if depth > hops.min && now == in_union {
break;
}
in_union = now;
}
if hops.max.is_some_and(|m| depth >= m) || B::nvals(&frontier) == 0 {
break;
}
B::mask_assign(&mut open, &all, device);
B::step_push(&frontier, g.out(), &mut open, &mut next, &mut ws, device)?;
std::mem::swap(&mut frontier, &mut next);
steps += 1;
depth += 1;
}
Ok(WalkEnds {
vertices: B::indices(&union),
steps,
})
}
/// The (source, end) pairs of the walks from each of `sources` along `edges` (square)
/// whose length lies in `hops`, as a structural matrix (row: source): [`walk_ends`] for
/// every source at once, as boolean products. `R(0)` holds `(s, s)` for each source,
/// `R(i+1) = R(i) · edges` (no mask: walks, not shortest paths), the answer the union of
/// `R(min)` .. `R(max)`, with the same early stops; with no `max`, the closure of
/// `R(min)` along the edges ([`crate::closure`]). Returns the pairs and the products.
pub fn walk_pairs<B: SparseBackend>(
edges: &Csr<u8>,
sources: &[u32],
hops: Hops,
device: &B::Device,
) -> crate::Result<(Csr<u8>, u64)> {
let n = edges.nrows();
if edges.ncols() != n {
return Err(GraphError::NotSquare {
rows: n,
cols: edges.ncols(),
});
}
if let Some(&s) = sources.iter().find(|&&s| s as usize >= n) {
return Err(GraphError::SourceOutOfRange {
source: s,
vertices: n,
});
}
let empty = || Csr::<u8>::from_edges(n, n, &[], &[], None, BoolOrAnd);
if hops.is_empty() || sources.is_empty() {
return Ok((empty()?, 0));
}
let s = BoolOrAnd;
let host = crate::closure::strictly_rising(edges)?;
let e = B::matrix(host.clone().into_owned(), device);
let mut r = B::matrix(Csr::from_edges(n, n, sources, sources, None, s)?, device);
let mut union = B::matrix(empty()?, device);
let mut in_union = 0usize;
let mut steps = 0u64;
let mut depth = 0u64;
loop {
if depth >= hops.min {
if hops.max.is_none() {
let base = B::matrix_to_host(&r).pattern().to_structural();
let c = crate::closure::<B>(&base, &host, crate::Side::Right, device)?;
return Ok((c.pairs, steps + c.rounds as u64));
}
union = B::ewise_add_matrix(&union, &r, s, device)?;
let now = B::nnz(&union);
if depth > hops.min && now == in_union {
break;
}
in_union = now;
}
if hops.max.is_some_and(|m| depth >= m) || B::nnz(&r) == 0 {
break;
}
r = B::mxm(&r, &e, None, s, device)?;
steps += 1;
depth += 1;
}
Ok((B::matrix_to_host(&union).pattern().to_structural(), steps))
}
/// The number of walks from each of `sources` to each vertex along the edges of `edges`
/// (square) whose length lies in `hops` (`hops.max` must be given): rows (source, end,
/// count), by source then end, each pair with at least one walk once. An entry's value
/// is the number of edges it stands for (parallel edges; a structural matrix: one each).
///
/// The boolean walk of [`walk_pairs`] over plus-times: per source, `c(0)` is 1 at the
/// source, `c(i+1)[v]` = the sum over the edges `(u, v)` of `c(i)[u]` times the edge's
/// value (one sparse vector-matrix product a step), the answer the sum of `c(min)` ..
/// `c(max)`. Walks may repeat vertices and edges, so a cycle is walked round as often as
/// the length allows. A count past `u64` is an error, never wrapped.
pub fn walk_counts<T: kleene_sparse::Value + Into<u64>>(
edges: &Csr<T>,
sources: &[u32],
hops: Hops,
) -> crate::Result<Vec<(u32, u32, u64)>> {
let n = edges.nrows();
if edges.ncols() != n {
return Err(GraphError::NotSquare {
rows: n,
cols: edges.ncols(),
});
}
if let Some(&s) = sources.iter().find(|&&s| s as usize >= n) {
return Err(GraphError::SourceOutOfRange {
source: s,
vertices: n,
});
}
let Some(max) = hops.max else {
return Err(GraphError::Counts(
"walks of no bounded length are not counted (their number is not finite on a cycle)"
.into(),
));
};
let mut sorted = sources.to_vec();
sorted.sort_unstable();
sorted.dedup();
let over = || GraphError::Counts("a count past u64".into());
let weight = |k: usize| -> u64 { edges.values().map_or(1, |v| v[k].into()) };
let mut out: Vec<(u32, u32, u64)> = Vec::new();
// dense counts with the touched vertices listed, reset after each step
let mut cur = vec![0u64; n];
let mut next = vec![0u64; n];
let mut total = vec![0u64; n];
let (mut on, mut on_next, mut seen): (Vec<u32>, Vec<u32>, Vec<u32>) =
(Vec::new(), Vec::new(), Vec::new());
for &s in &sorted {
cur[s as usize] = 1;
on.push(s);
let mut depth = 0u64;
loop {
if depth >= hops.min {
for &v in &on {
let t = &mut total[v as usize];
if *t == 0 {
seen.push(v);
}
*t = t.checked_add(cur[v as usize]).ok_or_else(over)?;
}
}
if depth == max || on.is_empty() {
break;
}
for &u in &on {
let c = cur[u as usize];
let first = edges.pattern().range(u as usize).start;
for (j, &v) in edges.row(u as usize).iter().enumerate() {
let k = first + j;
let x = &mut next[v as usize];
if *x == 0 {
on_next.push(v);
}
let add = c.checked_mul(weight(k)).ok_or_else(over)?;
*x = x.checked_add(add).ok_or_else(over)?;
}
cur[u as usize] = 0;
}
on.clear();
std::mem::swap(&mut cur, &mut next);
std::mem::swap(&mut on, &mut on_next);
// an edge of value 0 leaves a 0 count listed: drop it
on.retain(|&v| cur[v as usize] != 0);
depth += 1;
}
for &v in &on {
cur[v as usize] = 0;
}
on.clear();
seen.sort_unstable();
for &v in &seen {
out.push((s, v, std::mem::take(&mut total[v as usize])));
}
seen.clear();
}
Ok(out)
}