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

//! Several aggregates per rule head ([`Aggregate::many`]): count, sum, mean, least and
//! greatest of one group in one pass, against a plain loop over the distinct rows. Nulls
//! are skipped; a group with no value gets count 0 and null for the others (its `has` flag
//! 0); a count without a variable takes each row whole; `when` flags keep only their rows;
//! a counted body weighs each row by its count.

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

use arrow_array::{ArrayRef, Float64Array, Int64Array, UInt64Array};
use kleene_plan::{Aggregate, Atom, Datum, Engine, Inputs, NULL, Plan, Reduce, Term, Type, Value};
use kleene_sparse::{CpuBackend, CpuDevice};

/// Rows (shop, item, amount: i64 or null, price: f64 or null, flag: 0 or 1). Shop 3 has
/// amounts and prices only null.
/// (shop, item, amount, price, flag).
type Sale = (u64, u64, Option<i64>, Option<f64>, u64);

/// A sale and its weight.
type Weighed = (u64, u64, Option<i64>, Option<f64>, u64, u64);

fn sales() -> Vec<Sale> {
    let mut v = Vec::new();
    for i in 0..40u64 {
        let shop = i % 4;
        let amount = (shop != 3 && i % 5 != 2).then_some((i as i64 * 7) % 13 - 6);
        let price = (shop != 3 && i % 6 != 1).then_some(((i * 3) % 11) as f64 * 0.5);
        let row = (shop, i % 3, amount, price, (i % 7 != 3) as u64);
        // each row once (a relation is a set)
        if !v.iter().any(|r: &Sale| {
            (r.0, r.1, r.2, r.3.map(f64::to_bits), r.4)
                == (row.0, row.1, row.2, row.3.map(f64::to_bits), row.4)
        }) {
            v.push(row);
        }
    }
    v
}

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

/// One group's reductions by a plain loop: count(*), count(amount), count(distinct item),
/// sum(amount), avg(price), min(amount), max(price), sum(distinct amount), count of the
/// flagged rows; each row weighed by `w`.
#[derive(Debug, PartialEq)]
struct Want {
    all: u64,
    amounts: u64,
    items: u64,
    sum: Option<i64>,
    avg: Option<f64>,
    min: Option<i64>,
    max: Option<f64>,
    sum_distinct: Option<i64>,
    flagged: u64,
}

fn want(rows: &[Weighed]) -> BTreeMap<u64, Want> {
    let mut out = BTreeMap::new();
    let mut shops: Vec<u64> = rows.iter().map(|r| r.0).collect();
    shops.sort_unstable();
    shops.dedup();
    for s in shops {
        let g: Vec<_> = rows.iter().filter(|r| r.0 == s).collect();
        let amounts: Vec<(i64, u64)> = g.iter().filter_map(|r| r.2.map(|a| (a, r.5))).collect();
        let prices: Vec<(f64, u64)> = g.iter().filter_map(|r| r.3.map(|p| (p, r.5))).collect();
        let mut items: Vec<u64> = g.iter().map(|r| r.1).collect();
        items.sort_unstable();
        items.dedup();
        let mut distinct: Vec<i64> = amounts.iter().map(|x| x.0).collect();
        distinct.sort_unstable();
        distinct.dedup();
        let n: u64 = prices.iter().map(|x| x.1).sum();
        out.insert(
            s,
            Want {
                all: g.iter().map(|r| r.5).sum(),
                amounts: amounts.iter().map(|x| x.1).sum(),
                items: items.len() as u64,
                sum: (!amounts.is_empty()).then(|| amounts.iter().map(|x| x.0 * x.1 as i64).sum()),
                avg: (!prices.is_empty())
                    .then(|| prices.iter().map(|x| x.0 * x.1 as f64).sum::<f64>() / n as f64),
                min: amounts.iter().map(|x| x.0).min(),
                max: prices.iter().map(|x| x.0).reduce(f64::max),
                sum_distinct: (!distinct.is_empty()).then(|| distinct.iter().sum()),
                flagged: g.iter().filter(|r| r.4 == 1).map(|r| r.5).sum(),
            },
        );
    }
    out
}

/// The rule over `sale` (or the counted `sale` with each row's weight), its rows read back.
async fn run(weighed: bool) -> (BTreeMap<u64, Want>, Vec<(u64, u64, u64)>, String) {
    let rows = sales();
    let weight = |i: usize| if weighed { (i % 3) as u64 + 1 } else { 1 };
    let mut p = Plan::new();
    let types = [Type::U64, Type::U64, Type::I64, Type::F64, Type::U64];
    let sale = if weighed {
        p.input_counted("sale", &types)
    } else {
        p.input_typed("sale", &types)
    };
    let outs = [
        Type::U64,
        Type::U64,
        Type::U64,
        Type::U64,
        Type::I64,
        Type::F64,
        Type::I64,
        Type::F64,
        Type::I64,
        Type::U64,
        Type::U64,
        Type::U64,
    ];
    let shops = p.derived_typed("shops", &outs);
    let [s, i, a, pr, f, w] = ["S", "I", "A", "P", "F", "W"].map(|x| p.var(x));
    let [
        all,
        cnt,
        items,
        sum,
        avg,
        min,
        max,
        sumd,
        flagged,
        has_sum,
        has_max,
    ] = [
        "All", "Cnt", "Items", "Sum", "Avg", "Min", "Max", "SumD", "Flagged", "HasSum", "HasMax",
    ]
    .map(|x| p.var(x));
    let agg = Aggregate::many(
        [s],
        [
            Reduce::count(all),
            Reduce::count_of([a], cnt),
            Reduce::count_of([i], items).distinct(),
            Reduce::sum(a, sum).has(has_sum),
            Reduce::avg(pr, avg),
            Reduce::min(a, min),
            Reduce::max(pr, max).has(has_max),
            Reduce::sum(a, sumd).distinct(),
            Reduce::count(flagged).when([f]),
        ],
    );
    let (agg, body) = if weighed {
        (agg.times([w]), atom(sale, &[s, i, a, pr, f, w]))
    } else {
        (agg, atom(sale, &[s, i, a, pr, f]))
    };
    let r = p
        .aggregate(
            atom(
                shops,
                &[
                    s, all, cnt, items, sum, avg, min, max, sumd, flagged, has_sum, has_max,
                ],
            ),
            agg,
            [body],
        )
        .unwrap();
    let shown = p.show_rule(r);
    let u = |v: Vec<u64>| -> ArrayRef { Arc::new(UInt64Array::from(v)) };
    let mut cols: Vec<ArrayRef> = vec![
        u(rows.iter().map(|r| r.0).collect()),
        u(rows.iter().map(|r| r.1).collect()),
        Arc::new(Int64Array::from(
            rows.iter().map(|r| r.2).collect::<Vec<_>>(),
        )),
        Arc::new(Float64Array::from(
            rows.iter().map(|r| r.3).collect::<Vec<_>>(),
        )),
        u(rows.iter().map(|r| r.4).collect()),
    ];
    if weighed {
        cols.push(u((0..rows.len()).map(weight).collect()));
    }
    let mut inputs = Inputs::new();
    inputs.columns(sale, cols);
    let out = Engine::<CpuBackend>::new(CpuDevice::new(3))
        .run(&p, &inputs)
        .await
        .unwrap();
    let ty = |c: usize, v: Value| outs[c].decode(v, None);
    let int = |d: Datum| match d {
        Datum::I64(x) => Some(x),
        Datum::Null => None,
        d => panic!("{d:?}"),
    };
    let float = |d: Datum| match d {
        Datum::F64(x) => Some(x),
        Datum::Null => None,
        d => panic!("{d:?}"),
    };
    let mut got = BTreeMap::new();
    let mut flags = Vec::new();
    for r in out.get(shops).unwrap().rows() {
        got.insert(
            r[0],
            Want {
                all: r[1],
                amounts: r[2],
                items: r[3],
                sum: int(ty(4, r[4])),
                avg: float(ty(5, r[5])),
                min: int(ty(6, r[6])),
                max: float(ty(7, r[7])),
                sum_distinct: int(ty(8, r[8])),
                flagged: r[9],
            },
        );
        flags.push((r[0], r[10], r[11]));
    }
    let plain: Vec<_> = rows
        .iter()
        .enumerate()
        .map(|(k, r)| (r.0, r.1, r.2, r.3, r.4, weight(k)))
        .collect();
    assert_eq!(got, want(&plain));
    (got, flags, shown)
}

#[tokio::test]
async fn several_aggregates_of_a_group_in_one_pass() {
    let (got, flags, shown) = run(false).await;
    // shop 3: no amount and no price: counts 0, the rest null, the has flags 0
    let none = &got[&3];
    assert_eq!(
        (none.amounts, none.sum, none.avg, none.min, none.max),
        (0, None, None, None, None)
    );
    assert_eq!(flags, vec![(0, 1, 1), (1, 1, 1), (2, 1, 1), (3, 0, 0)]);
    assert!(shown.contains("Sum = sum (A) has HasSum"), "{shown}");
    assert!(shown.contains("Flagged = count () when F"), "{shown}");
    assert_eq!(NULL, u64::MAX);
}

#[tokio::test]
async fn a_counted_body_weighs_each_row_by_its_count() {
    let (got, _, shown) = run(true).await;
    let (plain, _, _) = run(false).await;
    assert!(got[&0].all > plain[&0].all, "the rows weighed");
    assert!(shown.contains("times W"), "{shown}");
}

#[test]
fn reductions_that_do_not_fit_are_refused() {
    let mut p = Plan::new();
    let e = p.input_typed("e", &[Type::U64, Type::Str]);
    let h = p.derived_typed("h", &[Type::U64, Type::U64]);
    let [x, y, n] = ["X", "Y", "N"].map(|v| p.var(v));
    // a sum of strings
    let err = p
        .aggregate(
            atom(h, &[x, n]),
            Aggregate::many([x], [Reduce::sum(y, n)]),
            [atom(e, &[x, y])],
        )
        .unwrap_err();
    assert!(err.to_string().contains("str"), "{err}");
    // the result bound by the body
    let err = p
        .aggregate(
            atom(h, &[x, y]),
            Aggregate::many([x], [Reduce::count(y)]),
            [atom(e, &[x, y])],
        )
        .unwrap_err();
    assert!(err.to_string().contains("bound by a body atom"), "{err}");
    // no reduction
    let err = p
        .aggregate(
            atom(h, &[x, x]),
            Aggregate::many([x], []),
            [atom(e, &[x, y])],
        )
        .unwrap_err();
    assert!(err.to_string().contains("no reduction"), "{err}");
}