crates/kleene-graph/tests/bfs.rs
//! BFS on the CPU backend against a plain queue walk, in every direction.
use std::collections::VecDeque;
use kleene_graph::{BfsOptions, Direction, Graph, GraphError, bfs};
use kleene_sparse::{BoolOrAnd, CpuBackend, CpuDevice, Csr, Mask};
type B = CpuBackend;
fn csr(n: usize, edges: &[(u32, u32)]) -> Csr<u8> {
let (src, dst): (Vec<u32>, Vec<u32>) = edges.iter().copied().unzip();
Csr::from_edges(n, n, &src, &dst, None, BoolOrAnd).unwrap()
}
/// Levels by a queue walk (u32::MAX for not reached).
fn walk(n: usize, edges: &[(u32, u32)], sources: &[u32], allowed: Option<&Mask>) -> Vec<u32> {
let mut adj = vec![Vec::new(); n];
for &(a, b) in edges {
adj[a as usize].push(b);
}
let mut level = vec![u32::MAX; n];
let mut q = VecDeque::new();
for &s in sources {
if level[s as usize] == u32::MAX {
level[s as usize] = 0;
q.push_back(s);
}
}
while let Some(v) = q.pop_front() {
for &w in &adj[v as usize] {
let ok = allowed.is_none_or(|m| m.allows(w as usize));
if ok && level[w as usize] == u32::MAX {
level[w as usize] = level[v as usize] + 1;
q.push_back(w);
}
}
}
level
}
fn levels_of(r: &kleene_graph::Bfs<B>, n: usize) -> Vec<u32> {
let mut out = vec![u32::MAX; n];
for (i, l) in r.levels_on_host().iter() {
out[i as usize] = l;
}
out
}
/// A pseudo-random graph with a few hubs (a fixed stream: the same every run).
fn random_graph(n: usize, m: usize, seed: u64) -> Vec<(u32, u32)> {
let mut x = seed;
let mut step = || {
x = x
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
(x >> 33) as u32
};
(0..m)
.map(|k| {
let a = if k % 7 == 0 {
step() % 8
} else {
step() % n as u32
};
(a, step() % n as u32)
})
.collect()
}
#[test]
fn a_chain_with_a_branch_gets_its_levels() {
let edges = [(0, 1), (1, 2), (1, 3), (3, 4), (5, 0)];
let d = CpuDevice::new(1);
let g = Graph::<B>::new(csr(6, &edges), &d).unwrap();
let r = bfs(&g, &[0], &BfsOptions::default(), &d).unwrap();
assert_eq!(r.vertices(), vec![0, 1, 2, 3, 4]);
assert_eq!(r.reached, 5);
assert_eq!(r.depth, 3);
assert_eq!(levels_of(&r, 6), walk(6, &edges, &[0], None));
}
#[test]
fn push_pull_and_auto_agree_with_the_walk_on_random_graphs() {
for (seed, threads) in [(1u64, 1usize), (2, 4), (3, 4)] {
let n = 3000;
let edges = random_graph(n, 9000, seed);
let d = CpuDevice::new(threads).with_grain(64);
let g = Graph::<B>::new(csr(n, &edges), &d).unwrap();
let want = walk(n, &edges, &[0, 17], None);
for direction in [Direction::Push, Direction::Pull, Direction::Auto] {
let opts = BfsOptions {
direction,
..BfsOptions::default()
};
let r = bfs(&g, &[0, 17, 0], &opts, &d).unwrap();
assert_eq!(levels_of(&r, n), want, "{direction:?} seed {seed}");
assert_eq!(r.reached, want.iter().filter(|&&l| l != u32::MAX).count());
}
}
}
#[test]
fn auto_switches_to_pull_on_a_hub_and_back() {
// 0 -> every vertex 1..n, each of those -> n+1 tail chain of 3.
let n = 2000;
let mut edges: Vec<(u32, u32)> = (1..n as u32).map(|v| (0, v)).collect();
edges.extend((1..n as u32).map(|v| (v, n as u32)));
edges.extend([(n as u32, n as u32 + 1), (n as u32 + 1, n as u32 + 2)]);
let total = n + 3;
let d = CpuDevice::new(2);
let g = Graph::<B>::new(csr(total, &edges), &d).unwrap();
let r = bfs(&g, &[0], &BfsOptions::default(), &d).unwrap();
let dirs: Vec<Direction> = r.steps.iter().map(|s| s.direction).collect();
assert!(dirs.contains(&Direction::Pull), "{dirs:?}");
assert_eq!(*dirs.last().unwrap(), Direction::Push, "{dirs:?}");
assert_eq!(levels_of(&r, total), walk(total, &edges, &[0], None));
}
#[test]
fn a_vertex_mask_keeps_the_search_out() {
let edges = [(0, 1), (1, 2), (0, 3), (3, 2), (2, 4)];
let d = CpuDevice::new(1);
let g = Graph::<B>::new(csr(5, &edges), &d).unwrap();
let allowed = Mask::from_indices(5, &[1]).complement();
for direction in [Direction::Push, Direction::Pull] {
let opts = BfsOptions {
direction,
allowed: Some(allowed.clone()),
..BfsOptions::default()
};
let r = bfs(&g, &[0], &opts, &d).unwrap();
assert_eq!(levels_of(&r, 5), walk(5, &edges, &[0], Some(&allowed)));
assert_eq!(r.vertices(), vec![0, 2, 3, 4]);
}
}
#[test]
fn max_depth_stops_early() {
let edges = [(0, 1), (1, 2), (2, 3)];
let d = CpuDevice::new(1);
let g = Graph::<B>::push_only(csr(4, &edges), &d).unwrap();
let opts = BfsOptions {
max_depth: Some(2),
..BfsOptions::default()
};
let r = bfs(&g, &[0], &opts, &d).unwrap();
assert_eq!(r.vertices(), vec![0, 1, 2]);
assert_eq!(r.depth, 2);
}
#[test]
fn a_stored_transpose_is_used_as_given() {
let edges = [(0, 1), (1, 2)];
let d = CpuDevice::new(1);
let out = csr(3, &edges);
let inn = out.transpose();
let g = Graph::<B>::with_transpose(out, inn, &d).unwrap();
let opts = BfsOptions {
direction: Direction::Pull,
..BfsOptions::default()
};
assert_eq!(bfs(&g, &[0], &opts, &d).unwrap().vertices(), vec![0, 1, 2]);
}
#[test]
fn bad_input_is_refused() {
let d = CpuDevice::new(1);
let g = Graph::<B>::push_only(csr(3, &[(0, 1)]), &d).unwrap();
let pull = BfsOptions {
direction: Direction::Pull,
..BfsOptions::default()
};
assert_eq!(
bfs(&g, &[0], &pull, &d).unwrap_err(),
GraphError::NoTranspose
);
assert!(matches!(
bfs(&g, &[3], &BfsOptions::default(), &d),
Err(GraphError::SourceOutOfRange { source: 3, .. })
));
let short = BfsOptions {
allowed: Some(Mask::all(2)),
..BfsOptions::default()
};
assert!(matches!(
bfs(&g, &[0], &short, &d),
Err(GraphError::MaskLength { .. })
));
let rect = Csr::<u8>::from_edges(2, 3, &[0], &[2], None, BoolOrAnd).unwrap();
assert!(matches!(
Graph::<B>::new(rect, &d),
Err(GraphError::NotSquare { .. })
));
}