crates/kleene-plan/tests/shortest.rs
//! `Plan::shortest`: shortest paths as (start, end, path, position, vertex) rows, planned
//! as their own stratum and equal to a plain search over every walk; along and against
//! the edges, the edges as facts or a graph, any one path or all.
use std::collections::BTreeMap;
use kleene_plan::{Engine, Facts, Hops, Inputs, Plan, Shortest, Stratum, Way, plan};
use kleene_sparse::{BoolOrAnd, CpuBackend, CpuDevice, Csr};
/// Two routes of length 2 from 0 to 3, a cycle 0 -> 1 -> 2 -> 0, a self-loop at 4.
const EDGES: [(u64, u64); 8] = [
(0, 1),
(1, 2),
(2, 0),
(0, 5),
(5, 3),
(1, 3),
(3, 4),
(4, 4),
];
/// Every shortest walk from `s` (length at least `min`, at most `max`), as vertex lists.
fn plain(edges: &[(u64, u64)], s: u64, min: u64, max: Option<u64>) -> BTreeMap<u64, Vec<Vec<u64>>> {
let mut best: BTreeMap<u64, Vec<Vec<u64>>> = BTreeMap::new();
let mut level = vec![vec![s]];
for depth in 0..=max.unwrap_or(12) {
if depth >= min {
for w in &level {
let t = *w.last().unwrap();
let e = best.entry(t).or_default();
if e.first().is_none_or(|x| x.len() == w.len()) {
e.push(w.clone());
}
}
}
level = level
.iter()
.flat_map(|w| {
let t = *w.last().unwrap();
edges.iter().filter(move |e| e.0 == t).map(move |e| {
let mut x = w.clone();
x.push(e.1);
x
})
})
.collect();
}
for v in best.values_mut() {
v.sort();
v.dedup();
}
best
}
#[tokio::test]
async fn shortest_paths_equal_a_plain_search() {
let engine: Engine<CpuBackend> = Engine::new(CpuDevice::new(2));
for graph in [false, true] {
for way in [Way::Forward, Way::Backward] {
for (min, max) in [(0, None), (1, None), (1, Some(2)), (0, Some(1))] {
for which in [Shortest::Any, Shortest::All] {
let mut p = Plan::new();
let seed = p.input("seed", 1);
let e = p.input("e", 2);
let sp = p.derived("sp", 5);
p.shortest(sp, seed, e, way, Hops::new(min, max), which)
.unwrap();
let strata = plan(&p).unwrap();
assert!(
matches!(strata[..], [Stratum::Walk { shortest: Some(w), .. }] if w == which),
"{strata:?}"
);
assert_eq!(
strata[0].kind(),
"shortest paths (kleene-graph BFS per start)"
);
let mut inp = Inputs::new();
inp.facts(seed, Facts::from_rows(1, [[0u64], [3]]).unwrap());
if graph {
let (s, d): (Vec<u32>, Vec<u32>) =
EDGES.iter().map(|&(a, b)| (a as u32, b as u32)).unzip();
let out = Csr::from_edges(6, 6, &s, &d, None, BoolOrAnd).unwrap();
inp.graph(e, out.clone(), Some(out.transpose()));
} else {
inp.facts(
e,
Facts::from_rows(2, EDGES.iter().map(|&(a, b)| [a, b])).unwrap(),
);
}
let o = engine.run(&p, &inp).await.unwrap();
let edges: Vec<(u64, u64)> = match way {
Way::Forward => EDGES.to_vec(),
Way::Backward => EDGES.iter().map(|&(a, b)| (b, a)).collect(),
};
let mut want: Vec<Vec<u64>> = Vec::new();
for s in [0, 3] {
for (t, paths) in plain(&edges, s, min, max) {
let keep: Vec<Vec<u64>> = match which {
Shortest::All => paths,
// The lowest vertex at each step back: the least reversed list.
Shortest::Any => {
let mut r: Vec<Vec<u64>> = paths
.iter()
.map(|p| p.iter().rev().copied().collect())
.collect();
r.sort();
vec![r[0].iter().rev().copied().collect()]
}
other => {
unreachable!("a mode the reference does not know: {other:?}")
}
};
for (k, path) in keep.iter().enumerate() {
for (i, &v) in path.iter().enumerate() {
want.push(vec![s, t, k as u64, i as u64, v]);
}
}
}
}
want.sort();
let what = format!("graph {graph} {way:?} {min}..{max:?} {which:?}");
assert_eq!(o.get(sp).unwrap().sorted_rows(), want, "{what}");
}
}
}
}
}
#[test]
fn shortest_refused() {
let mut p = Plan::new();
let seed = p.input("seed", 1);
let e = p.input("e", 2);
let four = p.derived("four", 4);
let sp = p.derived("sp", 5);
let hops = Hops::new(1, None);
assert!(
p.shortest(four, seed, e, Way::Forward, hops, Shortest::Any)
.is_err(),
"four columns"
);
assert!(
p.shortest(sp, seed, e, Way::Forward, Hops::new(2, None), Shortest::Any)
.is_err(),
"min 2"
);
assert!(
p.shortest(sp, e, e, Way::Forward, hops, Shortest::Any)
.is_err(),
"a start of two columns"
);
assert!(
p.shortest(seed, seed, e, Way::Forward, hops, Shortest::Any)
.is_err(),
"an input"
);
p.shortest(sp, seed, e, Way::Forward, hops, Shortest::All)
.unwrap();
assert!(
p.shortest(sp, seed, e, Way::Forward, hops, Shortest::Any)
.is_err(),
"given twice"
);
}