crates/kleene-graph/src/shortest.rs
//! Shortest paths as vertex lists: per source, one shortest path to each vertex it
//! reaches (ANY SHORTEST), or every shortest path (ALL SHORTEST), read back from the
//! levels of a breadth-first search.
use kleene_sparse::Csr;
use crate::{BfsOptions, BfsState, Graph, GraphBackend, GraphError, Hops, bfs_with};
/// Which shortest paths to keep for each (source, end) pair.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Shortest {
/// One: through the lowest-numbered vertex at each step back from the end.
Any,
/// Every one.
All,
}
/// Shortest paths and how the search went.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ShortestPaths {
/// Each path's vertices from its source to its end, sorted by source, end, then the
/// vertices.
pub paths: Vec<Vec<u32>>,
/// Breadth-first steps taken over all sources.
pub steps: u64,
}
/// The shortest paths along `g` from each of `sources` to every vertex they reach with a
/// number of edges in `hops`. `out` is `g`'s adjacency on the host (it is read to find,
/// per vertex, the vertices one level before it).
///
/// `hops.min` is 0 or 1: with 0 the source is an end at length 0; with 1 every path takes
/// an edge first, so the source is an end only through a cycle (its shortest cycle). One
/// breadth-first search per source on the graph core (from the source, or with `min` 1
/// from its successors, one level deeper) gives each vertex its distance; a vertex's
/// parents are the vertices at the distance before with an edge to it. Any: the path back
/// through the lowest parent at each step; All: every path back. Refused: `hops.min` over
/// 1, a source out of range, and (All) more than `limit` paths.
pub fn shortest_paths<B: GraphBackend>(
g: &Graph<B>,
out: &Csr<u8>,
sources: &[u32],
hops: Hops,
which: Shortest,
limit: usize,
device: &B::Device,
) -> crate::Result<ShortestPaths> {
let n = g.vertices();
if out.nrows() != n || out.ncols() != n {
return Err(GraphError::NotSquare {
rows: out.nrows(),
cols: out.ncols(),
});
}
if let Some(&s) = sources.iter().find(|&&s| s as usize >= n) {
return Err(GraphError::SourceOutOfRange {
source: s,
vertices: n,
});
}
if hops.min > 1 {
return Err(GraphError::Paths(format!(
"shortest paths of {} edges or more: a shortest path takes at least 0 or 1",
hops.min
)));
}
let mut sources = sources.to_vec();
sources.sort_unstable();
sources.dedup();
let mut paths: Vec<Vec<u32>> = Vec::new();
let mut steps = 0u64;
if hops.is_empty() {
return Ok(ShortestPaths { paths, steps });
}
let mut st = BfsState::<B>::new(n, device);
// Distances of the vertices reached from the current source (u32::MAX: not reached).
let mut dist = vec![u32::MAX; n];
let mut parents: Vec<Vec<u32>> = vec![Vec::new(); n];
for &s in &sources {
let (starts, shift) = if hops.min == 0 {
(vec![s], 0u32)
} else {
let mut next = out.row(s as usize).to_vec();
next.dedup();
(next, 1)
};
let max_depth = match hops.max {
Some(m) if m < shift as u64 => continue,
Some(m) => Some(u32::try_from(m - shift as u64).unwrap_or(u32::MAX)),
None => None,
};
if starts.is_empty() {
continue;
}
let opts = BfsOptions {
max_depth,
..BfsOptions::default()
};
bfs_with(g, &starts, &opts, device, &mut st)?;
steps += st.steps().len() as u64;
let levels = B::vector_to_host(st.levels());
let reached: Vec<(u32, u32)> = levels.iter().map(|(v, l)| (v, l + shift)).collect();
for &(v, d) in &reached {
dist[v as usize] = d;
}
// Parents, rising: the start for the first level, else a vertex one level before.
for &(u, du) in &reached {
for &v in out.row(u as usize) {
let dv = dist[v as usize];
if dv != u32::MAX && dv == du + 1 && !(shift == 1 && dv == 1) {
parents[v as usize].push(u);
}
}
}
let mut ends: Vec<(u32, u32)> = reached.clone();
ends.sort_unstable();
for &(t, d) in &ends {
pair_paths(s, t, d, shift, &parents, which, limit, &mut paths)?;
}
for &(v, _) in &reached {
dist[v as usize] = u32::MAX;
parents[v as usize].clear();
}
}
Ok(ShortestPaths { paths, steps })
}
/// The shortest paths from `s` to `t` (at distance `d`), pushed onto `paths` sorted by
/// their vertices.
#[allow(clippy::too_many_arguments)]
fn pair_paths(
s: u32,
t: u32,
d: u32,
shift: u32,
parents: &[Vec<u32>],
which: Shortest,
limit: usize,
paths: &mut Vec<Vec<u32>>,
) -> crate::Result<()> {
// The parents of `v` at distance `dv`: the source for the first level when the search
// started from its successors.
let up = |v: u32, dv: u32| -> &[u32] {
if shift == 1 && dv == 1 {
std::slice::from_ref(&s)
} else {
&parents[v as usize]
}
};
if d == 0 {
paths.push(vec![s]);
return Ok(());
}
match which {
Shortest::Any => {
let mut back = vec![t];
let mut at = (t, d);
while at.1 > 0 {
let p = *up(at.0, at.1)
.iter()
.min()
.expect("a reached vertex has a parent");
back.push(p);
at = (p, at.1 - 1);
}
back.reverse();
paths.push(back);
}
Shortest::All => {
let start = paths.len();
// Depth first back from the end: the stack holds (vertex, distance, next parent).
let mut stack: Vec<(u32, u32, usize)> = vec![(t, d, 0)];
while let Some(&mut (v, dv, ref mut i)) = stack.last_mut() {
if dv == 0 {
let mut p: Vec<u32> = stack.iter().rev().map(|x| x.0).collect();
p.shrink_to_fit();
paths.push(p);
if paths.len() > limit {
return Err(GraphError::Paths(format!(
"more than {limit} shortest paths"
)));
}
stack.pop();
continue;
}
let ps = up(v, dv);
if *i == ps.len() {
stack.pop();
continue;
}
let p = ps[*i];
*i += 1;
stack.push((p, dv - 1, 0));
}
paths[start..].sort_unstable();
}
}
Ok(())
}