crates/kleene-datalog/tests/procedure_far_ids.rs
//! A graph procedure from the Datalog side over ids far apart (addresses of a binary): weak
//! components and PageRank by [`Program::procedure`], answered in those ids, and a rule
//! reading the components; against the same program over dense ids, mapped.
use std::collections::BTreeSet;
use kleene_datalog::{Engine, Facts, Inputs, Procedure, Program};
use kleene_sparse::{CpuBackend, CpuDevice};
const CALLS: [(u64, u64); 6] = [(0, 1), (1, 2), (2, 0), (3, 4), (4, 5), (6, 6)];
fn addr(v: u64) -> u64 {
0x7f00_0000_0000 + v * 0x1_0000_0040
}
async fn run(id: fn(u64) -> u64) -> (Vec<Vec<u64>>, Vec<Vec<u64>>, BTreeSet<Vec<u64>>) {
let mut p = Program::new();
let calls = p.input::<2>("calls");
let part = p.derived::<2>("part");
let rank = p.derived::<2>("rank");
p.procedure(&part, &calls, Procedure::WeakComponents)
.unwrap();
p.procedure(&rank, &calls, Procedure::PageRank).unwrap();
// together(F, G) :- part(F, C), part(G, C), F < G.
let together = p.derived::<2>("together");
let (f, g, c) = (p.var("F"), p.var("G"), p.var("C"));
p.rule(
together.at([f, g]),
[
part.at([f, c]).into(),
part.at([g, c]).into(),
kleene_datalog::lt(f, g),
],
)
.unwrap();
let mut inputs = Inputs::new();
inputs
.facts(
&calls,
Facts::from_rows(2, CALLS.iter().map(|&(a, b)| [id(a), id(b)])).unwrap(),
)
.unwrap();
let out = Engine::<CpuBackend>::new(CpuDevice::new(2))
.run(&p, &inputs)
.await
.unwrap();
let rows = |r: &kleene_datalog::Rel<2>| -> Vec<Vec<u64>> { out.get(r).unwrap().sorted_rows() };
(
rows(&part),
rows(&rank),
out.get(&together).unwrap().rows().collect(),
)
}
#[tokio::test]
async fn components_and_ranks_in_the_callers_ids() {
let (part, rank, together) = run(|v| v).await;
let (part_far, rank_far, together_far) = run(addr).await;
let both = |r: &Vec<Vec<u64>>| -> Vec<Vec<u64>> {
r.iter().map(|x| vec![addr(x[0]), addr(x[1])]).collect()
};
assert_eq!(part_far, both(&part));
let first =
|r: &Vec<Vec<u64>>| -> Vec<Vec<u64>> { r.iter().map(|x| vec![addr(x[0]), x[1]]).collect() };
assert_eq!(rank_far, first(&rank));
let mapped: BTreeSet<Vec<u64>> = together
.iter()
.map(|x| vec![addr(x[0]), addr(x[1])])
.collect();
assert_eq!(together_far, mapped);
assert_eq!(together.len(), 3 + 3);
}