crates/kleene-graph/src/bfs.rs
use kleene_sparse::{CpuBackend, Mask, SparseBackend, Vector};
use crate::backend::GraphBackend;
use crate::graph::{Graph, GraphError};
/// How a search steps.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Direction {
/// Push while the frontier is small, pull when its edges outweigh the unvisited ones
/// (Beamer's rule), back to push when a pull costs more edges than a push would (push
/// only when the graph has no transpose).
#[default]
Auto,
/// Push every step: the frontier sends along its out-edges.
Push,
/// Pull every step: each unvisited vertex looks for a frontier vertex among its
/// in-edges.
Pull,
}
/// Options of a search.
#[derive(Clone, Debug)]
pub struct BfsOptions {
/// How to step.
pub direction: Direction,
/// The vertices the search may enter (sources are visited whatever it says).
pub allowed: Option<Mask>,
/// Stop after this many levels.
pub max_depth: Option<u32>,
/// Switch from push to pull when the frontier's edges exceed the unexplored edges
/// divided by this (Beamer's alpha).
pub alpha: u64,
/// Switch from pull back to push when the frontier holds fewer than the vertices
/// divided by this (Beamer's beta), or when a push would look at fewer edges than the
/// last pull did.
pub beta: u64,
}
impl Default for BfsOptions {
fn default() -> Self {
BfsOptions {
direction: Direction::Auto,
allowed: None,
max_depth: None,
alpha: 14,
beta: 24,
}
}
}
/// One level of a search.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Step {
/// The level the step reached.
pub depth: u32,
/// Push or pull.
pub direction: Direction,
/// Vertices on the frontier before the step.
pub frontier: usize,
/// Vertices the step reached.
pub reached: usize,
/// Edges the step looked at (a pull stops at the first frontier vertex it finds).
pub examined: u64,
}
/// The result of a search.
#[derive(Clone, Debug)]
pub struct Bfs<B: SparseBackend> {
/// The level of each reached vertex (0 for the sources); no entry for a vertex not
/// reached.
pub levels: B::Vector<u32>,
/// The number of vertices reached (sources included).
pub reached: usize,
/// The deepest level reached.
pub depth: u32,
/// The steps, in order.
pub steps: Vec<Step>,
}
impl<B: SparseBackend> Bfs<B> {
/// The reached vertices, rising.
pub fn vertices(&self) -> Vec<u32> {
B::indices(&self.levels)
}
/// The levels on the host.
pub fn levels_on_host(&self) -> Vector<u32> {
B::vector_to_host(&self.levels)
}
}
/// The buffers of a search, kept between searches over graphs of one vertex count: the
/// frontiers, the visited mask, the levels, the step log and the backend's workspace. A
/// search run on kept state allocates nothing once the buffers have grown.
#[derive(Debug)]
pub struct BfsState<B: SparseBackend> {
n: usize,
frontier: B::Vector<u8>,
next: B::Vector<u8>,
pub(crate) levels: B::Vector<u32>,
open: B::Mask,
start: Mask,
ws: B::Workspace,
pub(crate) steps: Vec<Step>,
/// The CPU search's own buffers ([`crate::beamer_bfs`]; empty on other backends).
pub(crate) cpu: crate::beamer::Scratch,
}
impl<B: SparseBackend> BfsState<B> {
/// State for searches over `n` vertices.
pub fn new(n: usize, device: &B::Device) -> Self {
BfsState {
n,
frontier: B::vector(Vector::empty(n), device),
next: B::vector(Vector::empty(n), device),
levels: B::vector(Vector::empty(n), device),
open: B::mask(Mask::all(n), device),
start: Mask::all(n),
ws: B::workspace(n, device),
steps: Vec::with_capacity(64),
cpu: crate::beamer::Scratch::default(),
}
}
/// The level of each vertex the last search reached.
pub fn levels(&self) -> &B::Vector<u32> {
&self.levels
}
/// The steps of the last search, in order.
pub fn steps(&self) -> &[Step] {
&self.steps
}
}
/// What a search on kept state found (its levels and steps stay in the state).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct BfsSummary {
/// The number of vertices reached (sources included).
pub reached: usize,
/// The deepest level reached.
pub depth: u32,
}
/// Where the next level of a search runs: [`GraphBackend::bfs_place`]'s answer.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Place {
/// On the graph's own backend.
#[default]
Here,
/// On the host, on the CPU backend ([`GraphBackend::host_pattern`],
/// [`GraphBackend::host_device`]).
Host,
}
/// What a search knows before a level, for [`GraphBackend::bfs_place`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct LevelInfo {
/// Levels done so far.
pub depth: u32,
/// The graph's vertices.
pub vertices: usize,
/// The graph's edges.
pub edges: u64,
/// Vertices on the frontier, when the search read them for this level.
pub frontier: Option<usize>,
/// The frontier's out-edges, when Beamer's rule summed them for this level.
pub frontier_edges: Option<u64>,
/// Vertices reached so far (sources included).
pub reached: u64,
/// Whether the levels run on the host now.
pub on_host: bool,
}
/// Breadth-first search from `sources` (repeats are kept once).
pub fn bfs<B: GraphBackend>(
g: &Graph<B>,
sources: &[u32],
opts: &BfsOptions,
device: &B::Device,
) -> crate::Result<Bfs<B>> {
let mut st = BfsState::new(g.vertices(), device);
let sum = bfs_with(g, sources, opts, device, &mut st)?;
Ok(Bfs {
levels: st.levels,
reached: sum.reached,
depth: sum.depth,
steps: st.steps,
})
}
/// Breadth-first search from `sources` on kept state: [`bfs`] with every buffer reused.
/// The backend's [`GraphBackend::bfs_of`] runs it (on the CPU, direction-optimizing search
/// on the device's threads, [`crate::beamer_bfs`]).
pub fn bfs_with<B: GraphBackend>(
g: &Graph<B>,
sources: &[u32],
opts: &BfsOptions,
device: &B::Device,
st: &mut BfsState<B>,
) -> crate::Result<BfsSummary> {
check(g, sources, opts)?;
if st.n != g.vertices() {
*st = BfsState::new(g.vertices(), device);
}
B::bfs_of(g, sources, opts, device, st)
}
/// Check a search's input against its graph.
pub(crate) fn check<B: SparseBackend>(
g: &Graph<B>,
sources: &[u32],
opts: &BfsOptions,
) -> crate::Result<()> {
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 opts.direction == Direction::Pull && g.inn().is_none() {
return Err(GraphError::NoTranspose);
}
match &opts.allowed {
Some(m) if m.len() != n => Err(GraphError::MaskLength {
mask: m.len(),
vertices: n,
}),
_ => Ok(()),
}
}
/// [`bfs_with`] by the backend's push and pull steps, levels switched by Beamer's rule:
/// what [`GraphBackend::bfs_of`] runs unless a backend has a search of its own. Before each
/// level the backend's [`GraphBackend::bfs_place`] may move the search to the host (the
/// frontier, the open places and the levels, once) and back; the steps are the same.
pub fn bfs_with_generic<B: GraphBackend>(
g: &Graph<B>,
sources: &[u32],
opts: &BfsOptions,
device: &B::Device,
st: &mut BfsState<B>,
) -> crate::Result<BfsSummary> {
bfs_with_placed(g, sources, opts, device, st, &mut |info| {
B::bfs_place(info, device)
})
}
/// [`bfs_with_generic`] asking `place` (in place of the backend's
/// [`GraphBackend::bfs_place`]) where each level runs; a backend without a host side
/// ([`GraphBackend::host_pattern`]) runs every level here.
pub fn bfs_with_placed<B: GraphBackend>(
g: &Graph<B>,
sources: &[u32],
opts: &BfsOptions,
device: &B::Device,
st: &mut BfsState<B>,
place: &mut dyn FnMut(&LevelInfo) -> Place,
) -> crate::Result<BfsSummary> {
check(g, sources, opts)?;
let n = g.vertices();
if st.n != n {
*st = BfsState::new(n, device);
}
// Places a step may reach: neither visited nor outside the vertex mask. Each step
// closes what it reaches, in place, and reuses `next`: nothing is allocated per level.
// kept as the places left closed (a complemented mask), so that adding the sources
// below closes them whichever way round the options gave the mask
match &opts.allowed {
Some(m) if m.is_complement() => st.start.assign(m),
Some(m) => {
let mut closed = m.bits().clone();
closed.invert();
st.start = Mask::new(closed).complement();
}
None => st.start.assign_all(),
}
B::mask_assign(&mut st.open, &st.start, device);
B::load_indices(&mut st.frontier, sources, 1, device)?;
B::clear_vector(&mut st.levels, device);
B::assign_scalar(&mut st.levels, &st.frontier, 0, 0);
B::mask_add_vector(&mut st.open, &st.frontier);
st.steps.clear();
let BfsState {
frontier,
next,
levels,
open,
ws,
steps,
..
} = st;
let mut walk = Walk {
reached: B::nvals(frontier),
depth: 0,
explored: 0,
pulling: false,
last_pull: 0,
edges: g.edges() as u64,
vertices: n,
};
let host = match (B::host_pattern(g.out()), B::host_device(device)) {
(Some(out), Some(dev)) => match g.inn() {
None => Some((out, None, dev)),
Some(inn) => B::host_pattern(inn).map(|inn| (out, Some(inn), dev)),
},
_ => None,
};
let mut swaps = 0u32;
loop {
let bufs = Bufs::<B> {
frontier: &mut *frontier,
next: &mut *next,
levels: &mut *levels,
open: &mut *open,
ws: &mut *ws,
};
let here = &mut |info: &LevelInfo| host.is_none() || place(info) == Place::Here;
let (ended, s) = levels_on::<B>(
g.out(),
g.inn(),
opts,
device,
bufs,
steps,
&mut walk,
false,
here,
)?;
swaps += s;
let Some((out_h, inn_h, dev_h)) = host.filter(|_| !ended) else {
break;
};
// the next levels on the host: the state moves there once
let mut hf = B::vector_to_host(frontier);
let mut hn = Vector::empty(n);
let mut hl = B::vector_to_host(levels);
let mut ho = B::mask_to_host(open);
let mut hws = <CpuBackend as SparseBackend>::workspace(n, dev_h);
let bufs = Bufs::<CpuBackend> {
frontier: &mut hf,
next: &mut hn,
levels: &mut hl,
open: &mut ho,
ws: &mut hws,
};
let on_host = &mut |info: &LevelInfo| place(info) == Place::Host;
let (ended, _) = levels_on::<CpuBackend>(
out_h, inn_h, opts, dev_h, bufs, steps, &mut walk, true, on_host,
)?;
*levels = B::vector(hl, device);
if ended {
break;
}
*frontier = B::vector(hf, device);
*open = B::mask(ho, device);
}
// Each vector keeps its role, so the next search meets the sizes it grew to.
if swaps % 2 == 1 {
std::mem::swap(frontier, next);
}
Ok(BfsSummary {
reached: walk.reached,
depth: walk.depth,
})
}
/// What a search carries from level to level (and across a move to the host and back).
struct Walk {
reached: usize,
depth: u32,
explored: u64,
pulling: bool,
last_pull: u64,
edges: u64,
vertices: usize,
}
/// A search's buffers on one backend.
struct Bufs<'a, C: SparseBackend> {
frontier: &'a mut C::Vector<u8>,
next: &'a mut C::Vector<u8>,
levels: &'a mut C::Vector<u32>,
open: &'a mut C::Mask,
ws: &'a mut C::Workspace,
}
/// Levels on backend `C` while `stay` says so: whether the search ended, and how often
/// the frontier and next vectors swapped.
#[allow(clippy::too_many_arguments)]
fn levels_on<C: SparseBackend>(
out: &C::Matrix<u8>,
inn: Option<&C::Matrix<u8>>,
opts: &BfsOptions,
device: &C::Device,
bufs: Bufs<'_, C>,
steps: &mut Vec<Step>,
w: &mut Walk,
on_host: bool,
stay: &mut dyn FnMut(&LevelInfo) -> bool,
) -> crate::Result<(bool, u32)> {
let Bufs {
frontier,
next,
levels,
open,
ws,
} = bufs;
let n = w.vertices;
let mut swaps = 0u32;
while C::nvals(frontier) > 0 {
if opts.max_depth.is_some_and(|d| w.depth >= d) {
break;
}
let nf = C::nvals(frontier);
// The frontier's edges steer only the automatic choice.
let auto = opts.direction == Direction::Auto && inn.is_some();
let mf = if auto {
C::row_lengths_at(out, frontier)
} else {
0
};
let info = LevelInfo {
depth: w.depth,
vertices: n,
edges: w.edges,
frontier: Some(nf),
frontier_edges: auto.then_some(mf),
reached: w.reached as u64,
on_host,
};
if !stay(&info) {
return Ok((false, swaps));
}
w.pulling = match (opts.direction, inn) {
(Direction::Push, _) | (Direction::Auto, None) => false,
(Direction::Pull, _) => true,
(Direction::Auto, Some(_)) => {
if w.pulling {
// Keep pulling while the frontier is large and a push would look at
// more edges than the last pull did.
(nf as u64) * opts.beta >= n as u64 && mf >= w.last_pull
} else {
// Beamer's rule, and (once a pull has been measured) only when a push
// would look at more edges than that pull did.
mf * opts.alpha > w.edges.saturating_sub(w.explored)
&& (w.last_pull == 0 || mf > w.last_pull)
}
}
};
w.explored += mf;
let examined = if w.pulling {
let inn = inn.ok_or(GraphError::NoTranspose)?;
let ex = C::step_pull(frontier, inn, open, next, ws, device)?;
w.last_pull = ex;
ex
} else {
C::step_push(frontier, out, open, next, ws, device)?
};
let got = C::nvals(next);
w.depth += 1;
steps.push(Step {
depth: w.depth,
direction: if w.pulling {
Direction::Pull
} else {
Direction::Push
},
frontier: nf,
reached: got,
examined,
});
if got == 0 {
w.depth -= 1;
break;
}
C::assign_scalar(levels, next, w.depth, 0);
w.reached += got;
std::mem::swap(frontier, next);
swaps += 1;
}
Ok((true, swaps))
}