Your browser sucks, JavaScript disabled! Gunnar's console needs JavaScript and WebAssembly. Git over SSH on port 2222 does not.

nordisk/kleene

crates/kleene-plan/tests/graph_at.rs

//! `Source::GraphAt` and `Shifted`: a graph and an index over one vertex type's own rows,
//! read in a set's id space (rows from a base). Each answer against the same rule over the
//! pairs as ids in hand, and each procedure against the same graph from 0 with its vertices
//! shifted.

use std::collections::BTreeSet;
use std::sync::Arc;

use kleene_plan::{
    Atom, Engine, External, Facts, Hops, Inputs, Plan, Procedure, Shifted, Term, Value, Way,
};
use kleene_sparse::{BoolOrAnd, CpuBackend, CpuDevice, Csr};

/// A type's own rows 0..5: a cycle 0 -> 1 -> 2 -> 0, 2 -> 3, 4 alone.
const ROWS: [(u32, u32); 4] = [(0, 1), (1, 2), (2, 0), (2, 3)];
const N: usize = 5;
/// The type's id base in the set (another type's 7 ids before it).
const BASE: Value = 7;

fn at(rel: kleene_plan::RelId, vs: &[kleene_plan::Var]) -> Atom {
    Atom {
        rel,
        terms: vs.iter().map(|&v| Term::Var(v)).collect(),
    }
}

fn graph(n: usize, m: usize, pairs: &[(u32, u32)]) -> (Csr<u8>, Csr<u8>) {
    let (s, d): (Vec<u32>, Vec<u32>) = pairs.iter().copied().unzip();
    let out = Csr::from_edges(n, m, &s, &d, None, BoolOrAnd).unwrap();
    let inn = out.transpose();
    (out, inn)
}

fn engine() -> Engine<CpuBackend> {
    Engine::new(CpuDevice::new(2))
}

/// The closure, a walk of 2 edges from the seeds and the pairs listed, over `e` given by
/// `give`: (closure, walk ends, pairs).
async fn run(
    seeds: &[Value],
    give: impl FnOnce(&mut Inputs, kleene_plan::RelId),
) -> [BTreeSet<Vec<Value>>; 3] {
    let mut p = Plan::new();
    let e = p.input("e", 2);
    let seed = p.input("seed", 1);
    let t = p.derived("t", 2);
    let (x, y, z) = (p.var("X"), p.var("Y"), p.var("Z"));
    p.rule(at(t, &[x, y]), [at(e, &[x, y])]).unwrap();
    p.rule(at(t, &[x, z]), [at(t, &[x, y]), at(e, &[y, z])])
        .unwrap();
    let w = p.derived("w", 1);
    p.walk(w, seed, e, Way::Forward, Hops::new(2, Some(2)))
        .unwrap();
    let l = p.derived("l", 2);
    p.rule(at(l, &[x, y]), [at(e, &[x, y])]).unwrap();
    let mut inp = Inputs::new();
    inp.facts(
        seed,
        Facts::from_rows(1, seeds.iter().map(|&s| [s])).unwrap(),
    );
    give(&mut inp, e);
    let o = engine().run(&p, &inp).await.unwrap();
    [t, w, l].map(|r| o.get(r).unwrap().rows().collect())
}

#[tokio::test]
async fn a_graph_of_one_type_from_its_base_equals_its_pairs_as_ids() {
    let ids: Vec<[Value; 2]> = ROWS
        .iter()
        .map(|&(a, b)| [BASE + a as Value, BASE + b as Value])
        .collect();
    let seeds = [BASE, BASE + 2];
    let want = run(&seeds, |inp, e| {
        inp.facts(e, Facts::from_rows(2, ids.iter().copied()).unwrap());
    })
    .await;
    let (out, inn) = graph(N, N, &ROWS);
    let got = run(&seeds, |inp, e| {
        inp.graph_at(e, out, Some(inn), (BASE, BASE));
    })
    .await;
    assert_eq!(got, want);
    assert!(want[0].contains(&vec![BASE, BASE + 3]));
}

#[tokio::test]
async fn a_graph_between_two_types_equals_its_pairs_as_ids() {
    // Rows 0..3 of one type (from 0) to rows 0..2 of another (from 3): ids 0..3 and 3..5.
    let rows = [(0, 0), (1, 0), (2, 1)];
    let ids: Vec<[Value; 2]> = rows
        .iter()
        .map(|&(a, b)| [a as Value, 3 + b as Value])
        .collect();
    let want = run(&[0, 2], |inp, e| {
        inp.facts(e, Facts::from_rows(2, ids.iter().copied()).unwrap());
    })
    .await;
    let (out, inn) = graph(3, 2, &rows);
    let got = run(&[0, 2], |inp, e| {
        inp.graph_at(e, out, Some(inn), (0, 3));
    })
    .await;
    assert_eq!(got, want);
    assert_eq!(got[2], ids.iter().map(|r| r.to_vec()).collect());
}

#[tokio::test]
async fn a_procedure_on_a_graph_from_its_base_numbers_its_vertices_from_there() {
    for procedure in [
        Procedure::WeakComponents,
        Procedure::StrongComponents,
        Procedure::PageRank,
        Procedure::Sssp {
            source: 0,
            weights: None,
        },
        Procedure::Triangles,
    ] {
        let one = |shift: Value| {
            let mut p = Plan::new();
            let e = p.input("e", 2);
            let procedure = match procedure {
                Procedure::Sssp { weights, .. } => Procedure::Sssp {
                    source: shift,
                    weights,
                },
                x => x,
            };
            let r = p.derived("r", procedure.arity());
            p.procedure(r, e, procedure).unwrap();
            let (out, inn) = graph(N, N, &ROWS);
            let mut inp = Inputs::new();
            inp.graph_at(e, out, Some(inn), (shift, shift));
            (p, inp, r)
        };
        let (p0, i0, r0) = one(0);
        let (p1, i1, r1) = one(BASE);
        let from0 = engine()
            .run(&p0, &i0)
            .await
            .unwrap()
            .get(r0)
            .unwrap()
            .sorted_rows();
        let from_base = engine()
            .run(&p1, &i1)
            .await
            .unwrap()
            .get(r1)
            .unwrap()
            .sorted_rows();
        let nodes = procedure.vertex_columns();
        let want: Vec<Vec<Value>> = from0
            .iter()
            .map(|r| {
                let mut r = r.clone();
                for &c in nodes {
                    r[c] += BASE;
                }
                r
            })
            .collect();
        assert_eq!(from_base, want, "{procedure:?}");
        if !matches!(procedure, Procedure::Triangles) {
            // one row per vertex of the type, none for the ids before it
            assert!(from_base.iter().all(|r| r[0] >= BASE), "{procedure:?}");
        }
    }
}

/// `(row, row + 1)` for rows below 4, answered with either column bound or none.
#[derive(Debug)]
struct Next;

impl External for Next {
    fn arity(&self) -> usize {
        2
    }

    fn can(&self, _bound: u64) -> bool {
        true
    }

    fn lookup(
        &self,
        bound: u64,
        keys: &[&[Value]],
        n: usize,
        out: &mut dyn FnMut(usize, &[Value]),
    ) -> kleene_plan::Result<()> {
        let key = |i: usize, k: usize| keys[i].get(k).copied();
        for k in 0..n {
            for r in 0..4 {
                if (bound & 1 == 0 || key(0, k) == Some(r))
                    && (bound & 2 == 0 || key(1, k) == Some(r + 1))
                {
                    out(k, &[r, r + 1]);
                }
            }
        }
        Ok(())
    }
}

#[test]
fn a_shifted_external_hands_ids() {
    let s = Shifted::new(Arc::new(Next), vec![10, 20]).unwrap();
    let mut got = Vec::new();
    s.lookup(0, &[&[], &[]], 1, &mut |k, r| got.push((k, r.to_vec())))
        .unwrap();
    assert_eq!(
        got,
        (0..4)
            .map(|r| (0, vec![10 + r, 21 + r]))
            .collect::<Vec<_>>()
    );
    // A key below the base matches nothing; keys keep their places.
    let mut got = Vec::new();
    s.lookup(1, &[&[3, 12, 5, 13], &[]], 4, &mut |k, r| {
        got.push((k, r.to_vec()))
    })
    .unwrap();
    assert_eq!(got, vec![(1, vec![12, 23]), (3, vec![13, 24])]);
    let mut got = Vec::new();
    s.lookup(2, &[&[], &[21, 2]], 2, &mut |k, r| {
        got.push((k, r.to_vec()))
    })
    .unwrap();
    assert_eq!(got, vec![(0, vec![10, 21])]);
    assert!(Shifted::new(Arc::new(Next), vec![1]).is_err());
}