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

nordisk/kleene

crates/kleene-datalog/tests/count_i64.rs

//! A count into a head column declared i64: the count reads back as the plain count, from
//! a counting aggregate ([`Aggregate::count`]) and from the counts of several reductions
//! ([`Aggregate::many`]: [`Reduce::count`], a count of values, a count of distinct values),
//! the same as into a u64 column.

use std::collections::{BTreeMap, BTreeSet};

use kleene_datalog::{Aggregate, Datum, Engine, Facts, Inputs, Output, Program, Reduce, Rel, Type};
use kleene_sparse::{CpuBackend, CpuDevice};

/// (group, value): group g holds values 0..g + 1, some twice.
fn rows() -> Vec<[u64; 2]> {
    let mut v = Vec::new();
    for g in 0..6u64 {
        for x in 0..=g {
            v.push([g, x]);
            v.push([g, x % 2]);
        }
    }
    v
}

/// The plain count per group: its distinct values (a relation is a set of rows).
fn want() -> BTreeMap<u64, i64> {
    let mut by: BTreeMap<u64, BTreeSet<u64>> = BTreeMap::new();
    for [a, b] in rows() {
        by.entry(a).or_default().insert(b);
    }
    by.into_iter().map(|(g, s)| (g, s.len() as i64)).collect()
}

/// `e(G, X)` over [`rows`], and a program that adds its rules over `e`.
async fn run(rules: impl FnOnce(&mut Program, &Rel<2>)) -> (Program, Output) {
    let mut p = Program::new();
    let e = p.input_typed("e", [Type::U64, Type::U64]);
    rules(&mut p, &e);
    let mut inputs = Inputs::new();
    inputs
        .facts(&e, Facts::from_rows(2, rows().iter()).unwrap())
        .unwrap();
    let out = Engine::<CpuBackend>::new(CpuDevice::new(2))
        .run(&p, &inputs)
        .await
        .unwrap();
    (p, out)
}

fn group(d: &Datum) -> u64 {
    match *d {
        Datum::U64(g) => g,
        ref other => panic!("{other:?}"),
    }
}

#[tokio::test]
async fn a_count_into_an_i64_column_is_the_plain_count() {
    let mut rels = None;
    let (p, out) = run(|p, e| {
        let fan = p.derived_typed("fan", [Type::U64, Type::I64]);
        let fan_u = p.derived_typed("fan_u", [Type::U64, Type::U64]);
        let [g, x, n] = ["G", "X", "N"].map(|v| p.var(v));
        p.aggregate(
            fan.at([g, n]),
            Aggregate::count([g], [x], n),
            [e.at([g, x])],
        )
        .unwrap();
        p.aggregate(
            fan_u.at([g, n]),
            Aggregate::count([g], [x], n),
            [e.at([g, x])],
        )
        .unwrap();
        rels = Some((fan, fan_u));
    })
    .await;
    let (fan, fan_u) = rels.unwrap();
    let want = want();
    let got = out.datums(&p, &fan).unwrap();
    assert_eq!(got.len(), want.len());
    for [g, n] in &got {
        let g = group(g);
        assert_eq!(*n, Datum::I64(want[&g]), "group {g}");
    }
    for [g, n] in &out.datums(&p, &fan_u).unwrap() {
        let g = group(g);
        assert_eq!(*n, Datum::U64(want[&g] as u64), "group {g}");
    }
}

#[tokio::test]
async fn the_counts_of_several_reductions_into_i64_columns_are_the_plain_counts() {
    let mut rel = None;
    let (p, out) = run(|p, e| {
        let stats = p.derived_typed("stats", [Type::U64, Type::I64, Type::I64, Type::I64]);
        let [g, x, all, of, d] = ["G", "X", "All", "Of", "D"].map(|v| p.var(v));
        p.aggregate(
            stats.at([g, all, of, d]),
            Aggregate::many(
                [g],
                [
                    Reduce::count(all),
                    Reduce::count_of([x], of),
                    Reduce::count_of([x], d).distinct(),
                ],
            ),
            [e.at([g, x])],
        )
        .unwrap();
        rel = Some(stats);
    })
    .await;
    let want = want();
    let got = out.datums(&p, &rel.unwrap()).unwrap();
    assert_eq!(got.len(), want.len());
    for [g, a, o, d] in got {
        let g = group(&g);
        let n = Datum::I64(want[&g]);
        assert_eq!([a, o, d], [n.clone(), n.clone(), n], "group {g}");
    }
}