crates/kleene-plan/tests/counted.rs
//! Counted relations: a count per row, multiplied by joins, summed by projection and
//! union, dropped by an ordinary rule, expanded only at the output; walk counts of bounded
//! length as plus-times steps. Each against a plain loop that enumerates the matches over
//! an edge list with parallel edges, a self loop and a two-cycle.
use std::collections::BTreeMap;
use kleene_plan::{Atom, Engine, Facts, Fold, Hops, Inputs, Plan, RelId, Term, Type, Var, Way};
use kleene_sparse::{CpuBackend, CpuDevice};
fn atom(rel: RelId, terms: &[Var]) -> Atom {
Atom {
rel,
terms: terms.iter().map(|&v| Term::Var(v)).collect(),
}
}
/// Edges with repeats (parallel edges): 0->1 twice, 1->2, 2->0, 2->3 three times, a self
/// loop 3->3, a two-cycle 4<->5, 5->5 twice.
const EDGES: [(u64, u64); 14] = [
(0, 1),
(0, 1),
(1, 2),
(2, 0),
(2, 3),
(2, 3),
(2, 3),
(3, 3),
(4, 5),
(5, 4),
(5, 5),
(5, 5),
(1, 4),
(3, 4),
];
/// (source, destination, number of parallel edges).
fn counted_edges() -> Facts {
let mut m: BTreeMap<(u64, u64), u64> = BTreeMap::new();
for &e in &EDGES {
*m.entry(e).or_default() += 1;
}
Facts::from_rows(3, m.into_iter().map(|((a, b), c)| [a, b, c])).unwrap()
}
/// Each edge pair once.
fn plain_edges() -> Facts {
let mut m: Vec<(u64, u64)> = EDGES.to_vec();
m.sort_unstable();
m.dedup();
Facts::from_rows(2, m.into_iter().map(|(a, b)| [a, b])).unwrap()
}
/// The walks of `len` edges from `s` over `edges` (each listed edge one walk step),
/// enumerated: (start, end) -> number of walks.
fn walks(
edges: &[(u64, u64)],
starts: &[u64],
lens: std::ops::RangeInclusive<u64>,
) -> BTreeMap<(u64, u64), u64> {
let mut out = BTreeMap::new();
fn go(
edges: &[(u64, u64)],
s: u64,
v: u64,
depth: u64,
lens: &std::ops::RangeInclusive<u64>,
out: &mut BTreeMap<(u64, u64), u64>,
) {
if lens.contains(&depth) {
*out.entry((s, v)).or_default() += 1;
}
if depth == *lens.end() {
return;
}
for &(a, b) in edges {
if a == v {
go(edges, s, b, depth + 1, lens, out);
}
}
}
for &s in starts {
go(edges, s, s, 0, &lens, &mut out);
}
out
}
fn counts(f: &Facts) -> BTreeMap<Vec<u64>, u64> {
f.rows()
.map(|r| {
let (k, c) = r.split_at(r.len() - 1);
(k.to_vec(), c[0])
})
.collect()
}
#[tokio::test]
async fn joins_multiply_projection_sums_union_adds() {
let engine: Engine<CpuBackend> = Engine::new(CpuDevice::new(3));
let mut p = Plan::new();
let e = p.input_counted("e", &[Type::U64, Type::U64]);
let plain = p.input("plain", 2);
// two(A, C, N): the walks A -> B -> C over the parallel edges, per pair of ends
let two = p.derived_counted("two", &[Type::U64, Type::U64]);
// ends(C, N): the same summed over A and B; and the one-edge walks added (a union)
let ends = p.derived_counted("ends", &[Type::U64]);
// distinct(A, C): two read without its count
let distinct = p.derived("distinct", 2);
// nodes(A, B, N): uncounted atoms: one per distinct binding (A, B, C)
let mids = p.derived_counted("mids", &[Type::U64, Type::U64]);
let [a, b, c, n, x, y] = ["A", "B", "C", "N", "X", "Y"].map(|v| p.var(v));
p.count_rule(
atom(two, &[a, c, n]),
[atom(e, &[a, b, x]), atom(e, &[b, c, y])],
)
.unwrap();
p.count_rule(atom(ends, &[c, n]), [atom(two, &[a, c, x])])
.unwrap();
p.count_rule(atom(ends, &[c, n]), [atom(e, &[a, c, x])])
.unwrap();
p.rule(atom(distinct, &[a, c]), [atom(two, &[a, c, x])])
.unwrap();
p.count_rule(
atom(mids, &[a, c, n]),
[atom(plain, &[a, b]), atom(plain, &[b, c])],
)
.unwrap();
let mut inp = Inputs::new();
inp.facts(e, counted_edges());
inp.facts(plain, plain_edges());
let o = engine.run(&p, &inp).await.unwrap();
let want2 = walks(&EDGES, &[0, 1, 2, 3, 4, 5], 2..=2);
let got2 = counts(o.get(two).unwrap());
let want2_rows: BTreeMap<Vec<u64>, u64> =
want2.iter().map(|(&(s, t), &k)| (vec![s, t], k)).collect();
assert_eq!(got2, want2_rows);
let mut want_ends: BTreeMap<Vec<u64>, u64> = BTreeMap::new();
for (&(_, t), &k) in want2
.iter()
.chain(walks(&EDGES, &[0, 1, 2, 3, 4, 5], 1..=1).iter())
{
*want_ends.entry(vec![t]).or_default() += k;
}
assert_eq!(counts(o.get(ends).unwrap()), want_ends);
let d: Vec<Vec<u64>> = o.get(distinct).unwrap().rows().collect();
assert_eq!(d, want2_rows.keys().cloned().collect::<Vec<_>>());
let mut edges: Vec<(u64, u64)> = EDGES.to_vec();
edges.sort_unstable();
edges.dedup();
let want_mids: BTreeMap<Vec<u64>, u64> = walks(&edges, &[0, 1, 2, 3, 4, 5], 2..=2)
.into_iter()
.map(|((s, t), k)| (vec![s, t], k))
.collect();
assert_eq!(counts(o.get(mids).unwrap()), want_mids);
// a sum and a mean weighed by the counts: of the end's id, per start
let mut q = Plan::new();
let e2 = q.input_counted("e", &[Type::U64, Type::U64]);
let sums = q.derived("sums", 2);
let means = q.derived_typed("means", &[Type::U64, Type::F64]);
let [a2, b2, x2, s2, m2] = ["A", "B", "X", "S", "M"].map(|v| q.var(v));
q.fold(
atom(sums, &[a2, s2]),
Fold::sum([a2], b2, s2).times([x2]),
[atom(e2, &[a2, b2, x2])],
)
.unwrap();
q.fold(
atom(means, &[a2, m2]),
Fold::avg([a2], b2, m2).times([x2]),
[atom(e2, &[a2, b2, x2])],
)
.unwrap();
let mut inp2 = Inputs::new();
inp2.facts(e2, counted_edges());
let o2 = engine.run(&q, &inp2).await.unwrap();
let mut want_sum: BTreeMap<u64, (u64, u64)> = BTreeMap::new();
for &(s, t) in &EDGES {
let x = want_sum.entry(s).or_default();
x.0 += t;
x.1 += 1;
}
let got_sum: BTreeMap<u64, (u64, u64)> = o2
.get(sums)
.unwrap()
.rows()
.map(|r| (r[0], (r[1], want_sum[&r[0]].1)))
.collect();
assert_eq!(got_sum, want_sum);
for r in o2.get(means).unwrap().rows() {
let (s, n) = want_sum[&r[0]];
assert_eq!(
Type::F64.decode(r[1], None),
kleene_plan::Datum::F64(s as f64 / n as f64)
);
}
// the bag, expanded at the output only
let bag = o.expand(&p, two, None).unwrap();
assert_eq!(bag.len() as u64, want2.values().sum::<u64>());
assert!(o.expand(&p, two, Some(3)).is_err());
assert!(o.expand(&p, distinct, None).is_err());
}
#[tokio::test]
async fn walk_counts_are_plus_times_steps() {
let engine: Engine<CpuBackend> = Engine::new(CpuDevice::new(3));
for (lo, hi) in [(0u64, 0u64), (1, 1), (3, 3), (6, 6), (1, 3), (2, 5)] {
for counted in [true, false] {
for way in [Way::Forward, Way::Backward] {
let mut p = Plan::new();
let from = p.input("from", 1);
let e = if counted {
p.input_counted("e", &[Type::U64, Type::U64])
} else {
p.input("e", 2)
};
let pairs = p.derived_counted("pairs", &[Type::U64, Type::U64]);
let ends = p.derived_counted("ends", &[Type::U64]);
let hops = Hops::new(lo, Some(hi));
p.walk_counted(pairs, from, e, way, hops).unwrap();
p.walk_counted(ends, from, e, way, hops).unwrap();
let mut inp = Inputs::new();
inp.facts(from, Facts::from_rows(1, [[0u64], [2], [5]]).unwrap());
inp.facts(
e,
if counted {
counted_edges()
} else {
plain_edges()
},
);
let o = engine.run(&p, &inp).await.unwrap();
let mut list: Vec<(u64, u64)> = EDGES.to_vec();
if !counted {
list.sort_unstable();
list.dedup();
}
if way == Way::Backward {
list = list.into_iter().map(|(a, b)| (b, a)).collect();
}
let want = walks(&list, &[0, 2, 5], lo..=hi);
let want_pairs: BTreeMap<Vec<u64>, u64> =
want.iter().map(|(&(s, t), &k)| (vec![s, t], k)).collect();
let tag = format!("{lo}..{hi} counted {counted} {way:?}");
assert_eq!(counts(o.get(pairs).unwrap()), want_pairs, "{tag}");
let mut want_ends: BTreeMap<Vec<u64>, u64> = BTreeMap::new();
for (&(_, t), &k) in &want {
*want_ends.entry(vec![t]).or_default() += k;
}
assert_eq!(counts(o.get(ends).unwrap()), want_ends, "{tag}");
}
}
}
}
#[test]
fn counted_relations_refuse_what_they_cannot_mean() {
let mut p = Plan::new();
let from = p.input("from", 1);
let e = p.input("e", 2);
let c = p.derived_counted("c", &[Type::U64]);
let d = p.derived("d", 1);
let [a, b, n] = ["A", "B", "N"].map(|v| p.var(v));
// unbounded walks have no finite count
assert!(
p.walk_counted(c, from, e, Way::Forward, Hops::new(1, None))
.is_err()
);
// a counted relation takes counting rules only, an uncounted one no counting rule
assert!(p.rule(atom(c, &[a, b]), [atom(e, &[a, b])]).is_err());
assert!(p.count_rule(atom(d, &[a]), [atom(e, &[a, b])]).is_err());
// the count is a fresh variable
assert!(p.count_rule(atom(c, &[a, b]), [atom(e, &[a, b])]).is_err());
assert!(p.count_rule(atom(c, &[a, n]), [atom(e, &[a, b])]).is_ok());
}