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/many.rs

//! Several aggregates per rule head from the Datalog side: one rule gives each group's
//! count, sum, mean, least and greatest value ([`Aggregate::many`] through
//! [`Program::aggregate`]), nulls skipped, as a plain loop gives.

use std::collections::BTreeMap;
use std::sync::Arc;

use arrow_array::{ArrayRef, Int64Array, StringArray};
use kleene_datalog::{Aggregate, Datum, Engine, Inputs, Program, Reduce, Type};
use kleene_sparse::{CpuBackend, CpuDevice};

#[tokio::test]
async fn count_sum_avg_min_max_of_a_group_in_one_rule() {
    let who = ["ann", "bo", "ann", "cy", "bo", "ann", "cy", "di"];
    let amount = [
        Some(5),
        Some(-2),
        None,
        Some(9),
        Some(4),
        Some(1),
        None,
        None,
    ];
    let mut p = Program::new();
    let sale = p.input_typed("sale", [Type::Str, Type::I64]);
    let stats = p.derived_typed(
        "stats",
        [
            Type::Str,
            Type::U64,
            Type::I64,
            Type::F64,
            Type::I64,
            Type::I64,
        ],
    );
    let [w, a, n, s, m, lo, hi] = ["W", "A", "N", "S", "M", "Lo", "Hi"].map(|x| p.var(x));
    // stats(W, N, S, M, Lo, Hi) :- N = count (A), S = sum (A), M = avg (A), Lo = min (A),
    //     Hi = max (A) by (W): sale(W, A).
    p.aggregate(
        stats.at([w, n, s, m, lo, hi]),
        Aggregate::many(
            [w],
            [
                Reduce::count_of([a], n),
                Reduce::sum(a, s),
                Reduce::avg(a, m),
                Reduce::min(a, lo),
                Reduce::max(a, hi),
            ],
        ),
        [sale.at([w, a])],
    )
    .unwrap();
    let mut inputs = Inputs::new();
    let ws: ArrayRef = Arc::new(StringArray::from(who.to_vec()));
    let am: ArrayRef = Arc::new(Int64Array::from(amount.to_vec()));
    inputs.columns(&sale, [ws, am]);
    let out = Engine::<CpuBackend>::new(CpuDevice::new(2))
        .run(&p, &inputs)
        .await
        .unwrap();
    let got: BTreeMap<String, Vec<Datum>> = out
        .datums(&p, &stats)
        .unwrap()
        .into_iter()
        .map(|r| {
            let mut r = r.to_vec();
            let Datum::Str(k) = r.remove(0) else {
                panic!("a name")
            };
            (k, r)
        })
        .collect();
    let mut want: BTreeMap<String, Vec<Datum>> = BTreeMap::new();
    for &name in &who {
        let vals: Vec<i64> = who
            .iter()
            .zip(&amount)
            .filter(|(w, a)| **w == name && a.is_some())
            .map(|(_, a)| a.unwrap())
            .collect();
        let or_null = |x: Option<i64>| x.map_or(Datum::Null, Datum::I64);
        want.insert(
            name.into(),
            vec![
                Datum::U64(vals.len() as u64),
                or_null((!vals.is_empty()).then(|| vals.iter().sum())),
                if vals.is_empty() {
                    Datum::Null
                } else {
                    Datum::F64(vals.iter().sum::<i64>() as f64 / vals.len() as f64)
                },
                or_null(vals.iter().copied().min()),
                or_null(vals.iter().copied().max()),
            ],
        );
    }
    assert_eq!(got, want);
    // di has no amount: count 0, the rest null
    assert_eq!(
        got["di"],
        vec![
            Datum::U64(0),
            Datum::Null,
            Datum::Null,
            Datum::Null,
            Datum::Null
        ]
    );
}