crates/kleene-index/src/parents.rs
//! The why chain: from an entry, a parent per reached vertex on a shortest path (fewest
//! edges), so the chain entry -> X is read back in as many steps as it has edges.
use arrow_buffer::ScalarBuffer;
use kleene_graph::{SsspOptions, sssp_of};
use kleene_sparse::{CpuBackend, CpuDevice, Csr};
use crate::error::{Result, bad};
const NONE: u32 = u32::MAX;
/// A parent per vertex reached from one root (the root is its own parent; unreached
/// vertices have none).
#[derive(Clone, Debug)]
pub struct ParentTree {
root: u32,
parent: ScalarBuffer<u32>,
}
impl ParentTree {
/// The tree from `root` over the graph whose vertex `v` has the out-neighbours
/// `adj[off[v]..off[v + 1]]`: kleene-graph's shortest paths with every edge 1, so each
/// parent is one level nearer the root.
pub fn build(
off: ScalarBuffer<u64>,
adj: ScalarBuffer<u32>,
root: u32,
device: &CpuDevice,
) -> Result<Self> {
let n = off.len().checked_sub(1).ok_or_else(|| bad("no offsets"))?;
let ones = ScalarBuffer::from(vec![1u32; adj.len()]);
let w = Csr::new(n, n, off, adj, Some(ones))?;
let paths = sssp_of::<CpuBackend>(&w, None, root, &SsspOptions::default(), device)?;
let parent: Vec<u32> = (0..n as u32)
.map(|v| paths.parent(v).unwrap_or(NONE))
.collect();
Ok(ParentTree {
root,
parent: parent.into(),
})
}
/// A tree from its stored parents.
pub fn from_parts(root: u32, parent: ScalarBuffer<u32>) -> Result<Self> {
let n = parent.len();
if root as usize >= n
|| parent[root as usize] != root
|| parent.iter().any(|&p| p != NONE && p as usize >= n)
{
return Err(bad("stored parents do not make a tree from the root"));
}
Ok(ParentTree { root, parent })
}
/// The root.
pub fn root(&self) -> u32 {
self.root
}
/// The parent of every vertex (`u32::MAX`: not reached).
pub fn parents(&self) -> &ScalarBuffer<u32> {
&self.parent
}
/// Whether `v` is reached from the root.
#[inline]
pub fn reached(&self, v: u32) -> bool {
self.parent[v as usize] != NONE
}
/// The parent of `v` (the root's is the root).
#[inline]
pub fn parent(&self, v: u32) -> Option<u32> {
let p = self.parent[v as usize];
(p != NONE).then_some(p)
}
/// The chain from `v` back to the root, `v` first and the root last; empty when `v`
/// is not reached.
pub fn why(&self, v: u32) -> impl Iterator<Item = u32> + '_ {
let mut at = self.reached(v).then_some(v);
std::iter::from_fn(move || {
let v = at?;
at = (v != self.root).then(|| self.parent[v as usize]);
Some(v)
})
}
/// The chain root -> `v` into `out` (cleared first; reused storage); false when `v` is
/// not reached.
pub fn path_into(&self, v: u32, out: &mut Vec<u32>) -> bool {
out.clear();
out.extend(self.why(v));
out.reverse();
!out.is_empty()
}
}