diff --git a/README.md b/README.md index a0e3b1b8..b4f28ebd 100644 --- a/README.md +++ b/README.md @@ -449,6 +449,14 @@ The file can be found [under configs directory](./configs/datagen/hydra_columns. **`--flat`**: flatten record such that output data of multiple experiments is flatten into one json file. +**`--group-columns`** (Hydra rows only): which label columns the subpopulation is taken over, as comma-separated indices into the columns before the value column, e.g. `1` or `0,1`; default `0`. +Any non-empty subset works, since the grid stores every subset of a record's labels; it picks the one the `hydra-*` row (`lib` and `polars`) asks and scores. +With `--metrics accuracy`, the record also summarises each scored group's error in the row's own metric (relative error; mean rank error for `hydra-kll`): `err_mean`, `err_p50`, `err_p90`, `err_max`, `groups_scored`, plus `schema_width` (`d`), `records` (`N`) and `fanned_mass` (`N·(2^d − 1)`). + +**`--per-group-out PATH`** (Hydra rows only): write those per-group errors as a CSV, `group_key,n_q,error`, one row per group (`n_q` is its record count, `group_key` its tagged labels such as `label0:a;label1:x`, with `\`, `:` and `;` in a label escaped by `\`). +Every group is listed, so the `n_q` sum to the stream's records; a group that cannot be scored (its true statistic is zero, e.g. zero entropy) has an empty `error` and is left out of the `err_*` summary. +It takes exactly one accuracy measurement (query or merge). + #### General Explanation Most of the input and output is shared between this hydra example and the previous hll example. diff --git a/aqpbm-cli/src/cli.rs b/aqpbm-cli/src/cli.rs index bd14e42a..65e02ee4 100644 --- a/aqpbm-cli/src/cli.rs +++ b/aqpbm-cli/src/cli.rs @@ -234,10 +234,29 @@ pub struct SketchbenchArgs { /// merge exactly, so a gap is a defect; for KLL it is the result. #[arg(long, default_value_t = 2, help_heading = "Measurement content")] pub merge_shards: usize, + /// Which label columns the `hydra-*` rows group by, comma-separated + /// indices into the columns before the value column: any non-empty subset + /// (`0`, `1`, `0,1`). The grid stores every subset, so this picks the one + /// asked and scored. Every other target ignores it. + #[arg( + long, + value_delimiter = ',', + default_value = "0", + help_heading = "Measurement content" + )] + pub group_columns: Vec, /// Path to append JSONL records to. `-` or omitted sends them to stdout. #[arg(long, help_heading = "Output")] pub report: Option, + /// Write a `hydra-*` row's per-group errors to this CSV, one row per group: + /// `group_key,n_q,error` (`n_q` is the group's record count, `error` the + /// row's own metric, empty for a group that cannot be scored, such as one + /// with zero entropy). The `n_q` sum to the stream's records; the record's + /// `err_*` fields summarise the scored rows. Takes exactly one accuracy + /// measurement: query or merge. + #[arg(long, help_heading = "Output")] + pub per_group_out: Option, /// Write one line for the whole invocation instead of one per measurement, /// folding its records into a single flattened row: one slot per operation, /// one field per metric. One record per measurement is the default; this is the diff --git a/aqpbm-cli/src/main.rs b/aqpbm-cli/src/main.rs index 8334d4dd..44edd0f9 100644 --- a/aqpbm-cli/src/main.rs +++ b/aqpbm-cli/src/main.rs @@ -350,6 +350,21 @@ fn run_sketchbench(args: SketchbenchArgs) -> Result<()> { None => ParamSet::empty(&variant), }; + let mut group_columns = args.group_columns.clone(); + group_columns.sort_unstable(); + group_columns.dedup(); + if args.per_group_out.is_some() { + if !variant.starts_with("hydra-") { + bail!("--per-group-out: only the hydra-* rows score groups, and {variant} is not one"); + } + match want.iter().filter(|(_, m)| *m == Metric::Accuracy).count() { + 0 => bail!("--per-group-out writes an accuracy measurement, and none was asked for"), + 1 => {} + _ => bail!( + "--per-group-out writes one accuracy measurement; ask for query or merge, not both" + ), + } + } let req = Requirement { variant: variant.clone(), library: library.clone(), @@ -357,6 +372,8 @@ fn run_sketchbench(args: SketchbenchArgs) -> Result<()> { width, workers: args.workers.max(1), merge_shards: args.merge_shards, + group_columns, + per_group_out: args.per_group_out.as_ref().map(std::path::PathBuf::from), comparator: args.comparator.clone(), runs: args.runs, warmup_runs: args.warmup_runs, diff --git a/aqpbm-cli/src/rows/hydra_univmon.rs b/aqpbm-cli/src/rows/hydra_univmon.rs index eca3acd0..34320aa9 100644 --- a/aqpbm-cli/src/rows/hydra_univmon.rs +++ b/aqpbm-cli/src/rows/hydra_univmon.rs @@ -77,7 +77,7 @@ pub(crate) fn row_hydra_univmon_l1_norm_lib( table, want, SubpopL1NormGT { - group_columns: vec![SCORED_LABEL_COLUMN], + group_columns: group_columns(req, description)?, value_column: value_column(description), }, hus::insert_hydra_univmon::<$t>, @@ -114,7 +114,7 @@ pub(crate) fn row_hydra_univmon_l1_norm_polars( table, want, SubpopL1NormGT { - group_columns: vec![SCORED_LABEL_COLUMN], + group_columns: group_columns(req, description)?, value_column: value_column(description), }, hup::insert_polars_subpop_l1_norm::<$t>, @@ -147,7 +147,7 @@ pub(crate) fn row_hydra_univmon_l2_norm_lib( table, want, SubpopL2NormGT { - group_columns: vec![SCORED_LABEL_COLUMN], + group_columns: group_columns(req, description)?, value_column: value_column(description), }, hus::insert_hydra_univmon::<$t>, @@ -184,7 +184,7 @@ pub(crate) fn row_hydra_univmon_l2_norm_polars( table, want, SubpopL2NormGT { - group_columns: vec![SCORED_LABEL_COLUMN], + group_columns: group_columns(req, description)?, value_column: value_column(description), }, hup::insert_polars_subpop_l2_norm::<$t>, @@ -217,7 +217,7 @@ pub(crate) fn row_hydra_univmon_entropy_lib( table, want, SubpopEntropyGT { - group_columns: vec![SCORED_LABEL_COLUMN], + group_columns: group_columns(req, description)?, value_column: value_column(description), }, hus::insert_hydra_univmon::<$t>, @@ -254,7 +254,7 @@ pub(crate) fn row_hydra_univmon_entropy_polars( table, want, SubpopEntropyGT { - group_columns: vec![SCORED_LABEL_COLUMN], + group_columns: group_columns(req, description)?, value_column: value_column(description), }, hup::insert_polars_subpop_entropy::<$t>, diff --git a/aqpbm-cli/src/rows/mod.rs b/aqpbm-cli/src/rows/mod.rs index e1f1c59c..66524a42 100644 --- a/aqpbm-cli/src/rows/mod.rs +++ b/aqpbm-cli/src/rows/mod.rs @@ -23,12 +23,12 @@ use aqpbm_core::accuracy::keyed::{ }; use aqpbm_core::accuracy::quantile::{RankErrorGT, RelativeValueErrorGT}; use aqpbm_core::accuracy::subpopulation::{ - SubpopCardinalityGT, SubpopEntropyGT, SubpopFrequencyGT, SubpopL1NormGT, SubpopL2NormGT, - SubpopRankErrorGT, + GroupKey, SubpopCardinalityGT, SubpopEntropyGT, SubpopFrequencyGT, SubpopL1NormGT, + SubpopL2NormGT, SubpopRankErrorGT, }; use aqpbm_core::accuracy::topk::TopkGT; use aqpbm_core::accuracy::Score; -use aqpbm_core::accuracy::{questions, CountedValue, GroundTruth}; +use aqpbm_core::accuracy::{questions, CountedValue, GroundTruth, PerGroup}; use aqpbm_core::error::RunError; use aqpbm_core::measure::{ record_calls, runs_for, Measurement, Pass as CorePass, Report, RunOutcome, MIN_MERGE_SHARDS, @@ -37,9 +37,6 @@ use aqpbm_core::metrics::{Metric, Operation}; use aqpbm_core::{ColumnItem, GeneratedTable, TableDescription}; use sketch_bench::wrappers::frequency_value::FrequencyValue; -/// The label column every subpopulation comparator scores over. -const SCORED_LABEL_COLUMN: usize = 0; - const KEYED_KEY_COLUMN: usize = 0; fn value_column(description: &TableDescription) -> usize { diff --git a/aqpbm-cli/src/rows/statistic.rs b/aqpbm-cli/src/rows/statistic.rs index 3e6c0678..7724a139 100644 --- a/aqpbm-cli/src/rows/statistic.rs +++ b/aqpbm-cli/src/rows/statistic.rs @@ -109,6 +109,28 @@ pub(super) fn topk_row( ) } +/// The label columns a grouped row asks and scores: `--group-columns`, which +/// must name at least one column, and only columns before the value column, +/// since those are the grid's key columns. +pub(super) fn group_columns( + req: &Requirement, + description: &TableDescription, +) -> Result, RunError> { + let labels = value_column(description); + if req.group_columns.is_empty() { + return Err(RunError::Sketch( + "--group-columns names no column; a group is taken over at least one".into(), + )); + } + if let Some(&column) = req.group_columns.iter().find(|&&c| c >= labels) { + return Err(RunError::Sketch(format!( + "--group-columns {column}: the label columns are 0..{labels}, the ones \ + before the value column" + ))); + } + Ok(req.group_columns.clone()) +} + /// A row answering **subpopulation frequency**: how often a value occurs inside /// a group. #[allow(clippy::too_many_arguments, clippy::type_complexity)] @@ -119,8 +141,8 @@ pub(super) fn subpop_frequency_row( want: &[(Operation, Metric)], insert: InsertBody<(String, V)>, insert_step: InsertStepBody<(String, V)>, - query: QueryBody<(String, V), (Vec, V), f64>, - merge: Option, V), f64>>, + query: QueryBody<(String, V), (GroupKey, V), f64>, + merge: Option>, prepare: Option>, ) -> Result { scored_row( @@ -128,7 +150,10 @@ pub(super) fn subpop_frequency_row( description, table, want, - SubpopFrequencyGT::::over_columns(vec![SCORED_LABEL_COLUMN], value_column(description)), + SubpopFrequencyGT::::over_columns( + group_columns(req, description)?, + value_column(description), + ), peel_labeled::, insert, insert_step, @@ -148,8 +173,8 @@ pub(super) fn subpop_cardinality_row( want: &[(Operation, Metric)], insert: InsertBody<(String, V)>, insert_step: InsertStepBody<(String, V)>, - query: QueryBody<(String, V), Vec, f64>, - merge: Option, f64>>, + query: QueryBody<(String, V), GroupKey, f64>, + merge: Option>, prepare: Option>, ) -> Result { scored_row( @@ -158,7 +183,7 @@ pub(super) fn subpop_cardinality_row( table, want, SubpopCardinalityGT { - group_columns: vec![SCORED_LABEL_COLUMN], + group_columns: group_columns(req, description)?, value_column: value_column(description), }, peel_labeled::, @@ -181,12 +206,12 @@ pub(super) fn subpop_vector_row( ground_truth: G, insert: InsertBody<(String, V)>, insert_step: InsertStepBody<(String, V)>, - query: QueryBody<(String, V), Vec, f64>, - merge: Option, f64>>, + query: QueryBody<(String, V), GroupKey, f64>, + merge: Option>, prepare: Option>, ) -> Result where - G: GroundTruth, Answer = f64> + 'static, + G: GroundTruth + 'static, G::Truth: 'static, { scored_row( @@ -212,8 +237,8 @@ pub(super) fn subpop_quantile_row( want: &[(Operation, Metric)], insert: InsertBody<(String, V)>, insert_step: InsertStepBody<(String, V)>, - query: QueryBody<(String, V), (Vec, f64), f64>, - merge: Option, f64), f64>>, + query: QueryBody<(String, V), (GroupKey, f64), f64>, + merge: Option>, prepare: Option>, ) -> Result { scored_row( @@ -222,7 +247,7 @@ pub(super) fn subpop_quantile_row( table, want, SubpopRankErrorGT { - group_columns: vec![SCORED_LABEL_COLUMN], + group_columns: group_columns(req, description)?, value_column: value_column(description), }, peel_labeled::, @@ -348,7 +373,11 @@ where G::Probe: 'static, G::Answer: 'static, { - let (probes, score) = questions(ground_truth, &table)?; + let (probes, score, per_group) = questions(ground_truth, &table)?; + let score = match &req.per_group_out { + Some(path) => per_group_written(score, per_group, path)?, + None => score, + }; let items = materialise(description, table)?; let mut bodies = Vec::with_capacity(want.len()); for &(operation, metric) in want { @@ -399,6 +428,37 @@ where Ok(bodies) } +/// The scorer, also writing every group to `path` as `group_key,n_q,error` +/// whenever it scores; `error` is empty for a group that cannot be scored. Every pass answers the same, so +/// each rewrites the same rows. The file is created here, so a path that +/// cannot be written fails before anything is measured. +fn per_group_written( + score: Score, + per_group: PerGroup, + path: &std::path::Path, +) -> Result, RunError> { + let fail = + |e: std::io::Error| RunError::Sketch(format!("--per-group-out {}: {e}", path.display())); + std::fs::File::create(path).map_err(fail)?; + let path = path.to_path_buf(); + Ok(Rc::new(move |answers: &[A]| { + let mut csv = String::from("group_key,n_q,error\n"); + for g in per_group(answers) { + // A label may hold a comma or a quote; CSV quotes the field then. + let key = if g.group.contains([',', '"', '\n']) { + format!("\"{}\"", g.group.replace('"', "\"\"")) + } else { + g.group + }; + let error = g.error.map_or(String::new(), |e| e.to_string()); + csv.push_str(&format!("{key},{},{error}\n", g.n_q)); + } + std::fs::write(&path, csv) + .unwrap_or_else(|e| panic!("--per-group-out {}: {e}", path.display())); + score(answers) + })) +} + /// A row that answers **nothing**: measured but not scored. The parallel-insert /// rows, whose worker sketches are dropped rather than asked, and whose ingest /// is one call over the whole stream rather than a loop over it. diff --git a/aqpbm-cli/tests/hydra_grouping.rs b/aqpbm-cli/tests/hydra_grouping.rs new file mode 100644 index 00000000..281ccec5 --- /dev/null +++ b/aqpbm-cli/tests/hydra_grouping.rs @@ -0,0 +1,163 @@ +//! `--group-columns`: a Hydra row asks and scores the label subset it names, +//! any non-empty one, not only column 0. On a grid large enough that no two of +//! the few subkeys share a column in most rows, the sketch answers each group +//! as the exact baseline does, so a group asked at the wrong columns shows up +//! as error. + +use std::process::Command; + +/// Two overlapping label columns (both render ranks over one alphabet, so +/// `b` is a value of each) over few values, and a value column at `dtype`. +fn spec(dtype: &str) -> std::path::PathBuf { + let path = std::env::temp_dir().join(format!( + "hydra_grouping_{}_{dtype}.yaml", + std::process::id() + )); + let yaml = format!( + "column_num: 3 +column_label: [key1, key2, value] +row_num: 5000 +column_spec: + - data_type: string + distribution: {{kind: uniform, lower_bound: 0.0, upper_bound: 4.0, seed: 1}} + - data_type: string + distribution: {{kind: zipf, skewness: 1.1, population_size: 3, seed: 2}} + - data_type: {dtype} + distribution: {{kind: zipf, skewness: 1.2, population_size: 40, seed: 3}} +" + ); + std::fs::write(&path, yaml).expect("the temp dir is writable"); + path +} + +/// The query accuracy record of one run, plus the per-group CSV it wrote. +fn scored( + variant: &str, + library: &str, + config: &str, + dtype: &str, + group_columns: &str, +) -> (serde_json::Value, String) { + let spec = spec(dtype); + let csv = spec.with_extension(format!("{variant}.{library}.{group_columns}.csv")); + let out = Command::new(env!("CARGO_BIN_EXE_approxbench")) + .args(["sketchbench", "--variant", variant, "--library", library]) + .args(["--config", config, "--dtype", dtype]) + .args(["--spec", spec.to_str().expect("utf-8 path")]) + .args(["--group-columns", group_columns]) + .args(["--per-group-out", csv.to_str().expect("utf-8 path")]) + .args(["--operations", "query", "--metrics", "accuracy"]) + .args(["--runs", "1", "--warmup-runs", "0"]) + .env("BENCH_WARMUP_SECS", "0") + .output() + .expect("approxbench runs"); + assert!( + out.status.success(), + "{}", + String::from_utf8_lossy(&out.stderr) + ); + let stdout = String::from_utf8(out.stdout).expect("utf-8"); + let record: serde_json::Value = + serde_json::from_str(stdout.lines().last().expect("one record")).expect("JSON"); + let csv = std::fs::read_to_string(&csv).expect("--per-group-out was written"); + (record["bench"]["accuracy"].clone(), csv) +} + +/// Every Hydra family, lib at a grid far larger than its 19 subkeys and the +/// polars baseline, grouped by column 1 alone and by both columns: both score +/// (about) zero, and the per-group file has one row per group, keyed by the +/// columns asked. +#[test] +fn any_label_subset_is_asked_where_it_was_inserted() { + let rows = [ + ("hydra-cms", "rows=3 cols=1024 cell_rows=3 cell_cols=256", "i64"), + ("hydra-cs", "rows=3 cols=1024 cell_rows=3 cell_cols=256", "i64"), + ("hydra-hll", "rows=3 cols=1024", "i64"), + ("hydra-kll", "rows=3 cols=1024 cell_k=4096", "f64"), + ( + "hydra-univmon-l1-norm", + "rows=3 cols=1024 cell_heap_size=64 cell_sketch_row=3 cell_sketch_col=256 cell_layer_size=4", + "i64", + ), + ]; + for (variant, config, dtype) in rows { + for group_columns in ["1", "0,1"] { + for (library, tolerance) in [("polars", 0.0), ("lib", 0.01)] { + let (acc, csv) = scored(variant, library, config, dtype, group_columns); + let at = format!("{variant}/{library} --group-columns {group_columns}: {acc}"); + assert!(acc["err_max"].as_f64().expect(&at) <= tolerance, "{at}"); + assert_eq!(acc["schema_width"], 2.0, "{at}"); + assert_eq!(acc["records"], 5000.0, "{at}"); + assert_eq!(acc["fanned_mass"], 15000.0, "{at}"); + + let mut lines = csv.lines(); + assert_eq!(lines.next(), Some("group_key,n_q,error"), "{at}"); + let rows: Vec<&str> = lines.collect(); + let scored = rows.iter().filter(|r| !r.ends_with(',')).count(); + assert_eq!(scored as f64, acc["groups_scored"].as_f64().expect(&at)); + let n_q: u64 = rows + .iter() + .map(|r| r.split(',').nth(1).and_then(|n| n.parse::().ok())) + .map(|n| n.expect("n_q is a count")) + .sum(); + assert_eq!(n_q, 5000, "every record is in exactly one group: {at}"); + let key = rows[0].split(',').next().expect("a key"); + match group_columns { + "1" => assert!(key.starts_with("label1:") && !key.contains(';'), "{key}"), + _ => assert!( + key.starts_with("label0:") && key.contains(";label1:"), + "{key}" + ), + } + } + } + } +} + +/// A grouping column has to be a label column: the value column is not a key +/// of the grid. +#[test] +fn a_group_column_past_the_labels_is_refused() { + let spec = spec("i64"); + let out = Command::new(env!("CARGO_BIN_EXE_approxbench")) + .args(["sketchbench", "--variant", "hydra-cms", "--library", "lib"]) + .args([ + "--spec", + spec.to_str().expect("utf-8 path"), + "--dtype", + "i64", + ]) + .args(["--group-columns", "2"]) + .args(["--operations", "query", "--metrics", "accuracy"]) + .args(["--runs", "1", "--warmup-runs", "0"]) + .output() + .expect("approxbench runs"); + assert!(!out.status.success()); + let err = String::from_utf8_lossy(&out.stderr); + assert!(err.contains("--group-columns 2"), "{err}"); +} + +/// `--per-group-out` writes an accuracy measurement, so a run that asks for +/// none is refused rather than leaving an empty file. +#[test] +fn per_group_out_without_accuracy_is_refused() { + let spec = spec("i64"); + let csv = spec.with_extension("no-accuracy.csv"); + let out = Command::new(env!("CARGO_BIN_EXE_approxbench")) + .args(["sketchbench", "--variant", "hydra-cms", "--library", "lib"]) + .args([ + "--spec", + spec.to_str().expect("utf-8 path"), + "--dtype", + "i64", + ]) + .args(["--per-group-out", csv.to_str().expect("utf-8 path")]) + .args(["--operations", "query", "--metrics", "throughput"]) + .args(["--runs", "1", "--warmup-runs", "0"]) + .output() + .expect("approxbench runs"); + assert!(!out.status.success()); + let err = String::from_utf8_lossy(&out.stderr); + assert!(err.contains("none was asked for"), "{err}"); + assert!(!csv.exists(), "no file is left behind"); +} diff --git a/aqpbm-core/src/accuracy/mod.rs b/aqpbm-core/src/accuracy/mod.rs index 1310d39d..1ae393ed 100644 --- a/aqpbm-core/src/accuracy/mod.rs +++ b/aqpbm-core/src/accuracy/mod.rs @@ -102,6 +102,29 @@ pub trait GroundTruth { probes: &[Self::Probe], answers: &[Self::Answer], ) -> BTreeMap; + + /// ④ Every group with its error, for a comparator whose population is + /// subpopulations; empty for every other. [`score`](Self::score) summarises + /// the scored rows, and `--per-group-out` writes them all. + fn per_group( + &self, + _truth: &Self::Truth, + _probes: &[Self::Probe], + _answers: &[Self::Answer], + ) -> Vec { + Vec::new() + } +} + +/// One subpopulation: its key, how many records it carried (`n_q`), and its +/// error in the comparator's own metric, lower is better. `None` when the group +/// cannot be scored (its true statistic is zero, so it has no relative error); +/// it is still listed, so the groups' `n_q` sum to the stream's records. +#[derive(Clone, Debug, PartialEq)] +pub struct GroupError { + pub group: String, + pub n_q: u64, + pub error: Option, } /// How a row's answers turn into the named error metrics: the scorer @@ -109,14 +132,18 @@ pub trait GroundTruth { /// comparator type. pub type Score = Rc BTreeMap>; +/// The same answers, read back group by group: [`GroundTruth::per_group`]. +pub type PerGroup = Rc Vec>; + /// Draw the questions: the exact answer over the generated table, the probes -/// off it, and a scorer holding both. Run once per row, outside every clock, -/// so no comparator type reaches a measurement. +/// off it, and a scorer holding both (and the per-group reader beside it). Run +/// once per row, outside every clock, so no comparator type reaches a +/// measurement. #[allow(clippy::type_complexity)] pub fn questions( gt: G, table: &GeneratedTable, -) -> Result<(Rc>, Score), RunError> +) -> Result<(Rc>, Score, PerGroup), RunError> where G: GroundTruth + 'static, G::Truth: 'static, @@ -133,7 +160,11 @@ where let (gt, truth, probes) = (gt.clone(), truth.clone(), probes.clone()); Rc::new(move |answers: &[G::Answer]| gt.score(&truth, &probes, answers)) }; - Ok((probes, score)) + let per_group: PerGroup = { + let (gt, truth, probes) = (gt.clone(), truth.clone(), probes.clone()); + Rc::new(move |answers: &[G::Answer]| gt.per_group(&truth, &probes, answers)) + }; + Ok((probes, score, per_group)) } pub(crate) fn scalar_error(truth: f64, answers: &[f64]) -> BTreeMap { diff --git a/aqpbm-core/src/accuracy/subpopulation/cardinality.rs b/aqpbm-core/src/accuracy/subpopulation/cardinality.rs index 69e990b5..3cf99df0 100644 --- a/aqpbm-core/src/accuracy/subpopulation/cardinality.rs +++ b/aqpbm-core/src/accuracy/subpopulation/cardinality.rs @@ -7,8 +7,8 @@ use std::hash::Hash; use aqpbm_datagen::{ColumnData, DataGenError, GeneratedTable}; -use super::{group_labels, owned, Group}; -use crate::accuracy::{curve, GroundTruth}; +use super::{group_errors, group_labels, owned, write_groups, GroupKey}; +use crate::accuracy::{curve, GroundTruth, GroupError}; /// Ground truth for a grouped cardinality sketch: how many distinct values one /// subpopulation held. The population is the **subpopulation**, one entry per @@ -19,75 +19,91 @@ pub struct SubpopCardinalityGT { pub value_column: usize, } -/// Exact distinct-value counts per group, plus the ranking and the unfiltered -/// population. +/// Exact distinct-value counts per group, plus the ranking, the unfiltered +/// population, each group's record count and the stream's shape. pub struct SubpopCardTruth { - exact: HashMap, - ranked: Vec, - all: Vec, + exact: HashMap, + ranked: Vec, + all: Vec, + sizes: HashMap, + records: u64, + schema_width: usize, } /// One pass over the rows at whatever type the value column holds: a row /// contributes its value to exactly one group, and the group's truth is the -/// size of that set. +/// size of that set; the second number is how many records it carried. fn distinct_per_group( labels: &[&str], - width: usize, + columns: &[usize], values: &[V], -) -> HashMap { - let mut per_group: HashMap, HashSet<&V>> = HashMap::new(); - for (group, value) in labels.chunks(width).zip(values) { +) -> HashMap { + let mut per_group: HashMap, (HashSet<&V>, u64)> = HashMap::new(); + for (group, value) in labels.chunks(columns.len()).zip(values) { match per_group.get_mut(group) { - Some(seen) => { + Some((seen, records)) => { seen.insert(value); + *records += 1; } None => { - per_group.insert(group.to_vec(), HashSet::from([value])); + per_group.insert(group.to_vec(), (HashSet::from([value]), 1)); } } } per_group .into_iter() - .map(|(group, seen)| (owned(&group), seen.len() as u64)) + .map(|(group, (seen, records))| (owned(&group, columns), (seen.len() as u64, records))) .collect() } impl GroundTruth for SubpopCardinalityGT { type Truth = SubpopCardTruth; - type Probe = Group; + type Probe = GroupKey; type Answer = f64; fn truth(&self, table: &GeneratedTable) -> Result { let labels = group_labels(table, &self.group_columns)?; - let width = self.group_columns.len(); - let exact = match table.column(self.value_column)? { - ColumnData::Int64(v) => distinct_per_group(&labels, width, v), - ColumnData::Unsigned64(v) => distinct_per_group(&labels, width, v), - ColumnData::String(v) => distinct_per_group(&labels, width, v), + let columns = &self.group_columns; + let counted = match table.column(self.value_column)? { + ColumnData::Int64(v) => distinct_per_group(&labels, columns, v), + ColumnData::Unsigned64(v) => distinct_per_group(&labels, columns, v), + ColumnData::String(v) => distinct_per_group(&labels, columns, v), ColumnData::Float64(v) => { let bits: Vec = v.iter().map(|x| x.to_bits()).collect(); - distinct_per_group(&labels, width, &bits) + distinct_per_group(&labels, columns, &bits) } }; + let exact: HashMap = + counted.iter().map(|(g, (d, _))| (g.clone(), *d)).collect(); + let sizes = counted.into_iter().map(|(g, (_, n))| (g, n)).collect(); - let mut by_count: Vec<(Group, u64)> = exact.iter().map(|(g, c)| (g.clone(), *c)).collect(); + let mut by_count: Vec<(GroupKey, u64)> = + exact.iter().map(|(g, c)| (g.clone(), *c)).collect(); by_count.sort_unstable_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0))); let all = curve::shuffled(&by_count); let ranked = by_count.into_iter().map(|(g, _)| g).collect(); - Ok(SubpopCardTruth { exact, ranked, all }) + Ok(SubpopCardTruth { + exact, + ranked, + all, + sizes, + records: table.row_num, + schema_width: self.value_column, + }) } - fn probes(&self, truth: &SubpopCardTruth) -> Vec { + fn probes(&self, truth: &SubpopCardTruth) -> Vec { curve::union_of(&truth.all, &truth.ranked, Clone::clone) } fn score( &self, truth: &SubpopCardTruth, - probes: &[Group], + probes: &[GroupKey], answers: &[f64], ) -> BTreeMap { - let est: HashMap<&Group, f64> = probes.iter().zip(answers).map(|(p, a)| (p, *a)).collect(); + let est: HashMap<&GroupKey, f64> = + probes.iter().zip(answers).map(|(p, a)| (p, *a)).collect(); let mut metrics: BTreeMap = BTreeMap::new(); curve::error_curve( &truth.ranked, @@ -102,8 +118,27 @@ impl GroundTruth for SubpopCardinalityGT { ); metrics.insert("subpopulations".into(), truth.exact.len() as f64); metrics.insert("group_columns".into(), self.group_columns.len() as f64); + let groups = self.per_group(truth, probes, answers); + write_groups(&groups, truth.records, truth.schema_width, &mut metrics); metrics } + + /// Relative error per group, as `are_all` averages it; a group with no + /// distinct value is listed unscored. + fn per_group( + &self, + truth: &SubpopCardTruth, + probes: &[GroupKey], + answers: &[f64], + ) -> Vec { + let est: HashMap<&GroupKey, f64> = + probes.iter().zip(answers).map(|(p, a)| (p, *a)).collect(); + group_errors(truth.exact.iter().map(|(g, &d)| { + let err = + (d > 0).then(|| (est.get(g).copied().unwrap_or(0.0) - d as f64).abs() / d as f64); + (g.clone(), truth.sizes[g], err) + })) + } } #[cfg(test)] @@ -120,7 +155,7 @@ mod tests { let truth = gt .truth(&records()) .expect("the table has the named columns"); - assert_eq!(truth.exact[&vec!["a".to_string()]], 2); - assert_eq!(truth.exact[&vec!["b".to_string()]], 1); + assert_eq!(truth.exact[&vec![Some("a".to_string())]], 2); + assert_eq!(truth.exact[&vec![Some("b".to_string())]], 1); } } diff --git a/aqpbm-core/src/accuracy/subpopulation/entropy.rs b/aqpbm-core/src/accuracy/subpopulation/entropy.rs index b768a08d..4d2bdbb3 100644 --- a/aqpbm-core/src/accuracy/subpopulation/entropy.rs +++ b/aqpbm-core/src/accuracy/subpopulation/entropy.rs @@ -2,9 +2,11 @@ use std::collections::BTreeMap; use aqpbm_datagen::{DataGenError, GeneratedTable}; -use super::frequency_vector::{probes_over, score_over, truth_over, SubpopVectorTruth}; -use super::Group; -use crate::accuracy::GroundTruth; +use super::frequency_vector::{ + per_group_over, probes_over, score_over, truth_over, SubpopVectorTruth, +}; +use super::GroupKey; +use crate::accuracy::{GroundTruth, GroupError}; pub struct SubpopEntropyGT { /// Which label columns the subpopulation is taken over. @@ -29,25 +31,34 @@ pub fn entropy(counts: &[u64]) -> f64 { impl GroundTruth for SubpopEntropyGT { type Truth = SubpopVectorTruth; - type Probe = Group; + type Probe = GroupKey; type Answer = f64; fn truth(&self, table: &GeneratedTable) -> Result { truth_over(table, &self.group_columns, self.value_column, entropy) } - fn probes(&self, truth: &SubpopVectorTruth) -> Vec { + fn probes(&self, truth: &SubpopVectorTruth) -> Vec { probes_over(truth) } fn score( &self, truth: &SubpopVectorTruth, - probes: &[Group], + probes: &[GroupKey], answers: &[f64], ) -> BTreeMap { score_over(truth, probes, answers, self.group_columns.len()) } + + fn per_group( + &self, + truth: &SubpopVectorTruth, + probes: &[GroupKey], + answers: &[f64], + ) -> Vec { + per_group_over(truth, probes, answers) + } } #[cfg(test)] @@ -67,9 +78,9 @@ mod tests { let truth = over(vec![0]) .truth(&records()) .expect("the table has the named columns"); - assert_eq!(truth.exact[&vec!["b".to_string()]], 0.0); + assert_eq!(truth.exact[&vec![Some("b".to_string())]], 0.0); let expected = -(2.0 / 3.0 * (2.0f64 / 3.0).log2() + 1.0 / 3.0 * (1.0f64 / 3.0).log2()); - assert!((truth.exact[&vec!["a".to_string()]] - expected).abs() < 1e-12); + assert!((truth.exact[&vec![Some("a".to_string())]] - expected).abs() < 1e-12); } #[test] @@ -91,6 +102,34 @@ mod tests { assert_eq!(cmp["aae_all"], 0.0); } + /// Over both columns only (a, x) holds two values; the other groups have + /// zero entropy and no relative error, but are still listed, so `n_q` + /// sums to the stream's 6 records. + #[test] + fn a_zero_entropy_group_is_listed_unscored() { + let gt = over(vec![0, 1]); + let truth = gt + .truth(&records()) + .expect("the table has the named columns"); + let probes = gt.probes(&truth); + let rows: Vec<(String, u64, Option)> = gt + .per_group(&truth, &probes, &vec![0.0; probes.len()]) + .into_iter() + .map(|g| (g.group, g.n_q, g.error)) + .collect(); + assert_eq!( + rows, + vec![ + ("label0:a;label1:x".to_string(), 2, Some(1.0)), + ("label0:b;label1:y".to_string(), 2, None), + ("label0:a;label1:y".to_string(), 1, None), + ("label0:b;label1:x".to_string(), 1, None), + ] + ); + let cmp = null_over(>, &records()); + assert_eq!(cmp["groups_scored"], 1.0); + } + #[test] fn a_different_grouping_is_a_different_population() { let cmp = null_over(&over(vec![0, 1]), &records()); diff --git a/aqpbm-core/src/accuracy/subpopulation/frequency.rs b/aqpbm-core/src/accuracy/subpopulation/frequency.rs index 381cacd2..588a286f 100644 --- a/aqpbm-core/src/accuracy/subpopulation/frequency.rs +++ b/aqpbm-core/src/accuracy/subpopulation/frequency.rs @@ -6,8 +6,8 @@ use std::marker::PhantomData; use aqpbm_datagen::{DataGenError, GeneratedTable}; -use super::{group_labels, owned, Group}; -use crate::accuracy::{curve, CountedValue, GroundTruth}; +use super::{group_errors, group_labels, owned, write_groups, GroupKey}; +use crate::accuracy::{curve, CountedValue, GroundTruth, GroupError}; pub struct SubpopFrequencyGT { /// Which label columns the subpopulation is taken over. A grouped sketch @@ -28,19 +28,23 @@ impl SubpopFrequencyGT { } } -/// The exact per-(group, value) counts, the ranking, and the unfiltered -/// population. Owned: the truth outlives the borrow of the table. +/// The exact per-(group, value) counts, the ranking, the unfiltered +/// population, each group's record count and the stream's shape. Owned: the +/// truth outlives the borrow of the table. pub struct SubpopFreqTruth { - exact: HashMap<(Group, V::CountKey), u64>, - ranked: Vec<(Group, V)>, - all: Vec<(Group, V)>, + exact: HashMap<(GroupKey, V::CountKey), u64>, + ranked: Vec<(GroupKey, V)>, + all: Vec<(GroupKey, V)>, subpopulations: usize, + sizes: HashMap, + records: u64, + schema_width: usize, } type CountedByGroup<'a, V> = HashMap, HashMap<::CountKey, (u64, V)>>; -fn counted_key(pair: &(Group, V)) -> (Group, V::CountKey) { +fn counted_key(pair: &(GroupKey, V)) -> (GroupKey, V::CountKey) { (pair.0.clone(), pair.1.count_key()) } @@ -49,7 +53,7 @@ where V: CountedValue, { type Truth = SubpopFreqTruth; - type Probe = (Group, V); + type Probe = (GroupKey, V); type Answer = f64; fn truth(&self, table: &GeneratedTable) -> Result, DataGenError> { @@ -76,10 +80,12 @@ where } } let subpopulations = counted.len(); - let mut exact: HashMap<(Group, V::CountKey), u64> = HashMap::new(); - let mut by_count: Vec<((Group, V), u64)> = Vec::new(); + let mut exact: HashMap<(GroupKey, V::CountKey), u64> = HashMap::new(); + let mut by_count: Vec<((GroupKey, V), u64)> = Vec::new(); + let mut sizes: HashMap = HashMap::with_capacity(subpopulations); for (group, seen) in counted { - let group = owned(&group); + let group = owned(&group, &self.group_columns); + sizes.insert(group.clone(), seen.values().map(|(count, _)| count).sum()); for (key, (count, value)) in seen { exact.insert((group.clone(), key), count); by_count.push(((group.clone(), value), count)); @@ -99,20 +105,23 @@ where ranked, all, subpopulations, + sizes, + records: table.row_num, + schema_width: self.value_column, }) } - fn probes(&self, truth: &SubpopFreqTruth) -> Vec<(Group, V)> { + fn probes(&self, truth: &SubpopFreqTruth) -> Vec<(GroupKey, V)> { curve::union_of(&truth.all, &truth.ranked, counted_key) } fn score( &self, truth: &SubpopFreqTruth, - probes: &[(Group, V)], + probes: &[(GroupKey, V)], answers: &[f64], ) -> BTreeMap { - let est: HashMap<(Group, V::CountKey), f64> = probes + let est: HashMap<(GroupKey, V::CountKey), f64> = probes .iter() .zip(answers) .map(|(p, a)| (counted_key(p), *a)) @@ -136,8 +145,37 @@ where // be read. metrics.insert("subpopulations".into(), truth.subpopulations as f64); metrics.insert("group_columns".into(), self.group_columns.len() as f64); + let groups = self.per_group(truth, probes, answers); + write_groups(&groups, truth.records, truth.schema_width, &mut metrics); metrics } + + /// A group's error is the relative error of its (group, value) pairs, + /// averaged over the group's pairs as `are_all` averages over every pair. + fn per_group( + &self, + truth: &SubpopFreqTruth, + probes: &[(GroupKey, V)], + answers: &[f64], + ) -> Vec { + let est: HashMap<(GroupKey, V::CountKey), f64> = probes + .iter() + .zip(answers) + .map(|(p, a)| (counted_key(p), *a)) + .collect(); + let mut per_group: HashMap<&GroupKey, (f64, usize)> = HashMap::new(); + for (key, &count) in &truth.exact { + let err = (est.get(key).copied().unwrap_or(0.0) - count as f64).abs() / count as f64; + let held = per_group.entry(&key.0).or_insert((0.0, 0)); + held.0 += err; + held.1 += 1; + } + group_errors( + per_group + .into_iter() + .map(|(g, (sum, pairs))| (g.clone(), truth.sizes[g], Some(sum / pairs as f64))), + ) + } } #[cfg(test)] @@ -151,31 +189,17 @@ mod tests { /// and this double answers 0 whatever it was fed, so nothing needs to go /// into it. struct NullSubpop; - impl NullSubpop { - fn estimate_subpop_frequency(&self, _: &[&str], _: &i64) -> f64 { - 0.0 - } - } - fn query_null(s: &mut NullSubpop, p: &(Group, i64)) -> f64 { - s.estimate_subpop_frequency(&labels(&p.0), &p.1) - } - - fn labels(group: &Group) -> Vec<&str> { - group.iter().map(String::as_str).collect() + fn query_null(_: &mut NullSubpop, _: &(GroupKey, i64)) -> f64 { + 0.0 } /// The estimator that is exactly right, built from the same rows the /// comparator reads. Pins that the comparator's own truth is self-consistent. struct ExactSubpop { - counts: HashMap<(Group, i64), u64>, - } - impl ExactSubpop { - fn estimate_subpop_frequency(&self, group: &[&str], value: &i64) -> f64 { - *self.counts.get(&(owned(group), *value)).unwrap_or(&0) as f64 - } + counts: HashMap<(GroupKey, i64), u64>, } - fn query_exact(s: &mut ExactSubpop, p: &(Group, i64)) -> f64 { - s.estimate_subpop_frequency(&labels(&p.0), &p.1) + fn query_exact(s: &mut ExactSubpop, p: &(GroupKey, i64)) -> f64 { + *s.counts.get(p).unwrap_or(&0) as f64 } fn over(group_columns: Vec) -> SubpopFrequencyGT { @@ -258,6 +282,27 @@ mod tests { assert_eq!(cmp["group_columns"], 2.0); } + /// A group's error averages its own pairs: `a` holds (a,10) twice and + /// (a,20) once, so overcounting (a,10) by one misses that pair by 0.5 and + /// group `a` by 0.25, while `b` is exact. Over groups the mean is 0.125, + /// not `are_all`'s 0.5 / 3 over pairs. + #[test] + fn a_group_error_is_the_mean_over_its_pairs() { + let table = records(); + let gt = over(vec![0]); + let truth = gt.truth(&table).expect("the table has the named columns"); + let mut counts = truth.exact.clone(); + *counts + .get_mut(&(vec![Some("a".to_string())], 10)) + .expect("(a, 10) occurs") += 1; + let cmp = + crate::accuracy::score_with(>, &query_exact, &mut ExactSubpop { counts }, &table); + assert_eq!(cmp["err_mean"], 0.125); + assert_eq!(cmp["err_max"], 0.25); + assert_eq!(cmp["groups_scored"], 2.0); + assert!((cmp["are_all"] - 0.5 / 3.0).abs() < 1e-12); + } + #[test] fn a_grouping_column_that_is_not_text_is_refused() { let Err(err) = over(vec![2]).truth(&records()) else { diff --git a/aqpbm-core/src/accuracy/subpopulation/frequency_vector.rs b/aqpbm-core/src/accuracy/subpopulation/frequency_vector.rs index 76f8b287..08421ec4 100644 --- a/aqpbm-core/src/accuracy/subpopulation/frequency_vector.rs +++ b/aqpbm-core/src/accuracy/subpopulation/frequency_vector.rs @@ -4,22 +4,25 @@ use std::hash::Hash; use aqpbm_datagen::{ColumnData, DataGenError, GeneratedTable}; -use super::{group_labels, owned, Group}; -use crate::accuracy::curve; +use super::{group_errors, group_labels, owned, write_groups, GroupKey}; +use crate::accuracy::{curve, GroupError}; pub struct SubpopVectorTruth { - pub(super) exact: HashMap, - ranked: Vec, - all: Vec, + pub(super) exact: HashMap, + ranked: Vec, + all: Vec, + sizes: HashMap, + records: u64, + schema_width: usize, } fn histogram_per_group( labels: &[&str], - width: usize, + columns: &[usize], values: &[V], -) -> HashMap> { +) -> HashMap> { let mut per_group: HashMap, HashMap<&V, u64>> = HashMap::new(); - for (group, value) in labels.chunks(width).zip(values) { + for (group, value) in labels.chunks(columns.len()).zip(values) { match per_group.get_mut(group) { Some(seen) => *seen.entry(value).or_insert(0) += 1, None => { @@ -29,7 +32,7 @@ fn histogram_per_group( } per_group .into_iter() - .map(|(group, seen)| (owned(&group), seen.into_values().collect())) + .map(|(group, seen)| (owned(&group, columns), seen.into_values().collect())) .collect() } @@ -37,16 +40,16 @@ pub(super) fn counts_per_group( table: &GeneratedTable, group_columns: &[usize], value_column: usize, -) -> Result>, DataGenError> { +) -> Result>, DataGenError> { let labels = group_labels(table, group_columns)?; - let width = group_columns.len(); + let columns = group_columns; Ok(match table.column(value_column)? { - ColumnData::Int64(v) => histogram_per_group(&labels, width, v), - ColumnData::Unsigned64(v) => histogram_per_group(&labels, width, v), - ColumnData::String(v) => histogram_per_group(&labels, width, v), + ColumnData::Int64(v) => histogram_per_group(&labels, columns, v), + ColumnData::Unsigned64(v) => histogram_per_group(&labels, columns, v), + ColumnData::String(v) => histogram_per_group(&labels, columns, v), ColumnData::Float64(v) => { let bits: Vec = v.iter().map(|x| x.to_bits()).collect(); - histogram_per_group(&labels, width, &bits) + histogram_per_group(&labels, columns, &bits) } }) } @@ -58,14 +61,15 @@ pub(super) fn truth_over( fold: impl Fn(&[u64]) -> f64, ) -> Result { let counts = counts_per_group(table, group_columns, value_column)?; - let exact: HashMap = counts + let exact: HashMap = counts .iter() .map(|(group, counts)| (group.clone(), fold(counts))) .collect(); - let mut by_statistic: Vec<(Group, f64)> = exact.iter().map(|(g, v)| (g.clone(), *v)).collect(); + let mut by_statistic: Vec<(GroupKey, f64)> = + exact.iter().map(|(g, v)| (g.clone(), *v)).collect(); by_statistic.sort_unstable_by(|a, b| b.1.total_cmp(&a.1).then_with(|| a.0.cmp(&b.0))); - let sized: Vec<(Group, u64)> = by_statistic + let sized: Vec<(GroupKey, u64)> = by_statistic .iter() .map(|(g, _)| { let size = counts.get(g).map(|c| c.iter().sum()).unwrap_or(0); @@ -73,21 +77,29 @@ pub(super) fn truth_over( }) .collect(); let all = curve::shuffled(&sized); + let sizes = sized.into_iter().collect(); let ranked = by_statistic.into_iter().map(|(g, _)| g).collect(); - Ok(SubpopVectorTruth { exact, ranked, all }) + Ok(SubpopVectorTruth { + exact, + ranked, + all, + sizes, + records: table.row_num, + schema_width: value_column, + }) } -pub(super) fn probes_over(truth: &SubpopVectorTruth) -> Vec { +pub(super) fn probes_over(truth: &SubpopVectorTruth) -> Vec { curve::union_of(&truth.all, &truth.ranked, Clone::clone) } pub(super) fn score_over( truth: &SubpopVectorTruth, - probes: &[Group], + probes: &[GroupKey], answers: &[f64], group_columns: usize, ) -> BTreeMap { - let est: HashMap<&Group, f64> = probes.iter().zip(answers).map(|(p, a)| (p, *a)).collect(); + let est: HashMap<&GroupKey, f64> = probes.iter().zip(answers).map(|(p, a)| (p, *a)).collect(); let mut metrics: BTreeMap = BTreeMap::new(); curve::error_curve( &truth.ranked, @@ -102,16 +114,33 @@ pub(super) fn score_over( ); metrics.insert("subpopulations".into(), truth.exact.len() as f64); metrics.insert("group_columns".into(), group_columns as f64); + let groups = per_group_over(truth, probes, answers); + write_groups(&groups, truth.records, truth.schema_width, &mut metrics); metrics } +/// Relative error per group, as `are_all` averages it: a group whose true +/// statistic is zero (entropy over one value) has no relative error, so it is +/// listed unscored. +pub(super) fn per_group_over( + truth: &SubpopVectorTruth, + probes: &[GroupKey], + answers: &[f64], +) -> Vec { + let est: HashMap<&GroupKey, f64> = probes.iter().zip(answers).map(|(p, a)| (p, *a)).collect(); + group_errors(truth.exact.iter().map(|(g, &v)| { + let err = (v > 0.0).then(|| (est.get(g).copied().unwrap_or(0.0) - v).abs() / v); + (g.clone(), truth.sizes[g], err) + })) +} + #[cfg(test)] mod tests { use super::*; use crate::accuracy::subpopulation::records; - fn group(label: &str) -> Group { - vec![label.to_string()] + fn group(label: &str) -> GroupKey { + vec![Some(label.to_string())] } #[test] diff --git a/aqpbm-core/src/accuracy/subpopulation/l1_norm.rs b/aqpbm-core/src/accuracy/subpopulation/l1_norm.rs index 9a9710ca..c32f9f5f 100644 --- a/aqpbm-core/src/accuracy/subpopulation/l1_norm.rs +++ b/aqpbm-core/src/accuracy/subpopulation/l1_norm.rs @@ -2,9 +2,11 @@ use std::collections::BTreeMap; use aqpbm_datagen::{DataGenError, GeneratedTable}; -use super::frequency_vector::{probes_over, score_over, truth_over, SubpopVectorTruth}; -use super::Group; -use crate::accuracy::GroundTruth; +use super::frequency_vector::{ + per_group_over, probes_over, score_over, truth_over, SubpopVectorTruth, +}; +use super::GroupKey; +use crate::accuracy::{GroundTruth, GroupError}; pub struct SubpopL1NormGT { /// Which label columns the subpopulation is taken over. @@ -18,25 +20,34 @@ pub fn l1_norm(counts: &[u64]) -> f64 { impl GroundTruth for SubpopL1NormGT { type Truth = SubpopVectorTruth; - type Probe = Group; + type Probe = GroupKey; type Answer = f64; fn truth(&self, table: &GeneratedTable) -> Result { truth_over(table, &self.group_columns, self.value_column, l1_norm) } - fn probes(&self, truth: &SubpopVectorTruth) -> Vec { + fn probes(&self, truth: &SubpopVectorTruth) -> Vec { probes_over(truth) } fn score( &self, truth: &SubpopVectorTruth, - probes: &[Group], + probes: &[GroupKey], answers: &[f64], ) -> BTreeMap { score_over(truth, probes, answers, self.group_columns.len()) } + + fn per_group( + &self, + truth: &SubpopVectorTruth, + probes: &[GroupKey], + answers: &[f64], + ) -> Vec { + per_group_over(truth, probes, answers) + } } #[cfg(test)] @@ -56,8 +67,8 @@ mod tests { let truth = over(vec![0]) .truth(&records()) .expect("the table has the named columns"); - assert_eq!(truth.exact[&vec!["a".to_string()]], 3.0); - assert_eq!(truth.exact[&vec!["b".to_string()]], 3.0); + assert_eq!(truth.exact[&vec![Some("a".to_string())]], 3.0); + assert_eq!(truth.exact[&vec![Some("b".to_string())]], 3.0); } #[test] @@ -74,6 +85,65 @@ mod tests { assert_eq!(cmp["aae_all"], 0.0); } + /// The per-group summary on a fixed case. Over both columns the groups + /// carry 2, 1, 1 and 2 records; answering 2, 2, 1.5 and 3 misses them by + /// 0, 1, 0.5 and 0.5 relatively, so sorted `[0, 0.5, 0.5, 1]`: mean 0.5, + /// p50 (index round(1.5) = 2) 0.5, p90 (index round(2.7) = 3) 1, max 1. + #[test] + fn per_group_errors_are_summarised_over_groups() { + let gt = over(vec![0, 1]); + let table = records(); + let key = |a: &str, b: &str| vec![Some(a.to_string()), Some(b.to_string())]; + let mut answers = std::collections::HashMap::from([ + (key("a", "x"), 2.0), + (key("a", "y"), 2.0), + (key("b", "x"), 1.5), + (key("b", "y"), 3.0), + ]); + let ask = |held: &mut std::collections::HashMap, p: &GroupKey| held[p]; + let cmp = crate::accuracy::score_with(>, &ask, &mut answers, &table); + assert_eq!(cmp["err_mean"], 0.5); + assert_eq!(cmp["err_p50"], 0.5); + assert_eq!(cmp["err_p90"], 1.0); + assert_eq!(cmp["err_max"], 1.0); + assert_eq!(cmp["groups_scored"], 4.0); + assert_eq!(cmp["schema_width"], 2.0); + assert_eq!(cmp["records"], 6.0); + assert_eq!(cmp["fanned_mass"], 18.0); + + let truth = gt.truth(&table).expect("the table has the named columns"); + let probes = gt.probes(&truth); + let asked: Vec = probes.iter().map(|p| answers[p]).collect(); + let rows: Vec<(String, u64, Option)> = gt + .per_group(&truth, &probes, &asked) + .into_iter() + .map(|g| (g.group, g.n_q, g.error)) + .collect(); + assert_eq!( + rows, + vec![ + ("label0:a;label1:x".to_string(), 2, Some(0.0)), + ("label0:b;label1:y".to_string(), 2, Some(0.5)), + ("label0:a;label1:y".to_string(), 1, Some(1.0)), + ("label0:b;label1:x".to_string(), 1, Some(0.5)), + ] + ); + } + + /// Column 1 alone is asked with column 0 left open, and named by column 1. + #[test] + fn a_group_on_a_later_column_leaves_the_earlier_ones_open() { + let gt = over(vec![1]); + let truth = gt + .truth(&records()) + .expect("the table has the named columns"); + assert_eq!(truth.exact[&vec![None, Some("x".to_string())]], 3.0); + let probes = gt.probes(&truth); + let groups = gt.per_group(&truth, &probes, &vec![0.0; probes.len()]); + let keys: Vec<&str> = groups.iter().map(|g| g.group.as_str()).collect(); + assert_eq!(keys, ["label1:x", "label1:y"]); + } + #[test] fn a_different_grouping_is_a_different_population() { let cmp = null_over(&over(vec![0, 1]), &records()); diff --git a/aqpbm-core/src/accuracy/subpopulation/l2_norm.rs b/aqpbm-core/src/accuracy/subpopulation/l2_norm.rs index a2069e22..267da2da 100644 --- a/aqpbm-core/src/accuracy/subpopulation/l2_norm.rs +++ b/aqpbm-core/src/accuracy/subpopulation/l2_norm.rs @@ -2,9 +2,11 @@ use std::collections::BTreeMap; use aqpbm_datagen::{DataGenError, GeneratedTable}; -use super::frequency_vector::{probes_over, score_over, truth_over, SubpopVectorTruth}; -use super::Group; -use crate::accuracy::GroundTruth; +use super::frequency_vector::{ + per_group_over, probes_over, score_over, truth_over, SubpopVectorTruth, +}; +use super::GroupKey; +use crate::accuracy::{GroundTruth, GroupError}; pub struct SubpopL2NormGT { /// Which label columns the subpopulation is taken over. @@ -22,25 +24,34 @@ pub fn l2_norm(counts: &[u64]) -> f64 { impl GroundTruth for SubpopL2NormGT { type Truth = SubpopVectorTruth; - type Probe = Group; + type Probe = GroupKey; type Answer = f64; fn truth(&self, table: &GeneratedTable) -> Result { truth_over(table, &self.group_columns, self.value_column, l2_norm) } - fn probes(&self, truth: &SubpopVectorTruth) -> Vec { + fn probes(&self, truth: &SubpopVectorTruth) -> Vec { probes_over(truth) } fn score( &self, truth: &SubpopVectorTruth, - probes: &[Group], + probes: &[GroupKey], answers: &[f64], ) -> BTreeMap { score_over(truth, probes, answers, self.group_columns.len()) } + + fn per_group( + &self, + truth: &SubpopVectorTruth, + probes: &[GroupKey], + answers: &[f64], + ) -> Vec { + per_group_over(truth, probes, answers) + } } #[cfg(test)] @@ -60,8 +71,8 @@ mod tests { let truth = over(vec![0]) .truth(&records()) .expect("the table has the named columns"); - assert!((truth.exact[&vec!["a".to_string()]] - 5.0f64.sqrt()).abs() < 1e-12); - assert_eq!(truth.exact[&vec!["b".to_string()]], 3.0); + assert!((truth.exact[&vec![Some("a".to_string())]] - 5.0f64.sqrt()).abs() < 1e-12); + assert_eq!(truth.exact[&vec![Some("b".to_string())]], 3.0); } #[test] diff --git a/aqpbm-core/src/accuracy/subpopulation/mod.rs b/aqpbm-core/src/accuracy/subpopulation/mod.rs index 76d7f1ad..0f92c223 100644 --- a/aqpbm-core/src/accuracy/subpopulation/mod.rs +++ b/aqpbm-core/src/accuracy/subpopulation/mod.rs @@ -17,10 +17,21 @@ pub use l1_norm::{l1_norm, SubpopL1NormGT}; pub use l2_norm::{l2_norm, SubpopL2NormGT}; pub use rank_error::{SubpopRankErrorGT, SubpopRankTruth}; +use std::collections::BTreeMap; + use aqpbm_datagen::{ColumnItem, DataGenError, GeneratedTable}; +use crate::accuracy::curve::percentile; +use crate::accuracy::GroupError; + pub type Group = Vec; +/// A subpopulation as a grid is asked for it: one slot per label column up to +/// the last one grouped on, `Some` at the grouped columns and `None` at the +/// rest. Grouping on column 1 alone asks `[None, Some(v)]`, which a wrapper +/// can tell apart from grouping on column 0. +pub type GroupKey = Vec>; + pub(crate) fn group_labels<'a>( table: &'a GeneratedTable, columns: &[usize], @@ -45,8 +56,79 @@ pub(crate) fn group_labels<'a>( Ok(flat) } -fn owned(group: &[&str]) -> Group { - group.iter().map(|label| (*label).to_string()).collect() +/// `group` holds one label per entry of `columns`, in that order. +fn owned(group: &[&str], columns: &[usize]) -> GroupKey { + let mut key = vec![None; columns.iter().max().map_or(0, |last| last + 1)]; + for (label, &column) in group.iter().zip(columns) { + key[column] = Some((*label).to_string()); + } + key +} + +/// How a group is named in `--per-group-out`: each grouped column's value +/// tagged with its column, as the grid's subkeys are (`label1:x`), with `\`, +/// `:` and `;` escaped. The same encoding as sketch-bench's +/// `polars_shared::subset_key`, which this crate cannot depend on. +fn rendered(key: &GroupKey) -> String { + let mut out = String::new(); + for (j, label) in key.iter().enumerate() { + let Some(label) = label else { continue }; + if !out.is_empty() { + out.push(';'); + } + out.push_str(&format!("label{j}:")); + for ch in label.chars() { + if matches!(ch, '\\' | ':' | ';') { + out.push('\\'); + } + out.push(ch); + } + } + out +} + +/// One [`GroupError`] per group, heaviest first (ties on the key), so the +/// per-group file reads the same across runs. +fn group_errors(errors: impl Iterator)>) -> Vec { + let mut out: Vec = errors + .map(|(key, n_q, error)| GroupError { + group: rendered(&key), + n_q, + error, + }) + .collect(); + out.sort_by(|a, b| b.n_q.cmp(&a.n_q).then_with(|| a.group.cmp(&b.group))); + out +} + +/// The per-group summary every grouped comparator reports, in its own metric: +/// `err_mean` / `err_p50` / `err_p90` / `err_max` over the scored groups (none +/// written when no group was scored), `groups_scored`, and the stream's shape +/// against which a group's error is read: `schema_width` (`d`, the label +/// columns before the value), `records` (`N`) and `fanned_mass` +/// (`N·(2^d − 1)`, every subset a record is inserted into). +fn write_groups( + groups: &[GroupError], + records: u64, + schema_width: usize, + metrics: &mut BTreeMap, +) { + let mut errs: Vec = groups.iter().filter_map(|g| g.error).collect(); + errs.sort_by(f64::total_cmp); + if let Some(&max) = errs.last() { + metrics.insert( + "err_mean".into(), + errs.iter().sum::() / errs.len() as f64, + ); + metrics.insert("err_p50".into(), percentile(&errs, 0.5)); + metrics.insert("err_p90".into(), percentile(&errs, 0.9)); + metrics.insert("err_max".into(), max); + } + metrics.insert("groups_scored".into(), errs.len() as f64); + metrics.insert("schema_width".into(), schema_width as f64); + metrics.insert("records".into(), records as f64); + let subsets = 2f64.powi(schema_width as i32) - 1.0; + metrics.insert("fanned_mass".into(), records as f64 * subsets); } /// key1 ∈ {a, b}, key2 ∈ {x, y}; the value column is what gets counted. @@ -76,15 +158,15 @@ fn records() -> GeneratedTable { #[cfg(test)] fn null_over(gt: &G, table: &GeneratedTable) -> std::collections::BTreeMap where - G: crate::accuracy::GroundTruth, + G: crate::accuracy::GroundTruth, { - crate::accuracy::score_with(gt, &|_: &mut (), _: &Group| 0.0, &mut (), table) + crate::accuracy::score_with(gt, &|_: &mut (), _: &GroupKey| 0.0, &mut (), table) } #[cfg(test)] fn exact_over(gt: &G, table: &GeneratedTable) -> std::collections::BTreeMap where - G: crate::accuracy::GroundTruth, + G: crate::accuracy::GroundTruth, { let mut exact = gt .truth(table) @@ -92,10 +174,23 @@ where .exact; crate::accuracy::score_with( gt, - &|held: &mut std::collections::HashMap, p: &Group| { + &|held: &mut std::collections::HashMap, p: &GroupKey| { held.get(p).copied().unwrap_or(0.0) }, &mut exact, table, ) } + +#[cfg(test)] +mod tests { + use super::*; + + /// A label holding the separators is escaped as the grid's subkeys are, + /// so it cannot be read as two columns. + #[test] + fn rendered_keys_escape_the_separators() { + let key = vec![None, Some(r"x:y;z\".to_string()), Some(String::new())]; + assert_eq!(rendered(&key), r"label1:x\:y\;z\\;label2:"); + } +} diff --git a/aqpbm-core/src/accuracy/subpopulation/rank_error.rs b/aqpbm-core/src/accuracy/subpopulation/rank_error.rs index 5364184c..01ec1259 100644 --- a/aqpbm-core/src/accuracy/subpopulation/rank_error.rs +++ b/aqpbm-core/src/accuracy/subpopulation/rank_error.rs @@ -5,9 +5,9 @@ use std::collections::HashMap; use aqpbm_datagen::{DataGenError, GeneratedTable}; -use super::{group_labels, owned, Group}; +use super::{group_errors, group_labels, owned, write_groups, GroupKey}; use crate::accuracy::quantile::rank_err; -use crate::accuracy::{curve, f64_values, GroundTruth}; +use crate::accuracy::{curve, f64_values, GroundTruth, GroupError}; /// Number of quantiles probed per group — the same grid the ungrouped /// comparator uses, named once in [`super::quantile`]. @@ -24,17 +24,18 @@ pub struct SubpopRankErrorGT { /// The ordered statistic inside each group, plus the groups worth probing. pub struct SubpopRankTruth { - per_group: HashMap>, + per_group: HashMap>, /// Every group, shuffled: probe order must not hand the baseline the /// locality the encounter order would. - probed: Vec, + probed: Vec, items: usize, + schema_width: usize, } impl GroundTruth for SubpopRankErrorGT { type Truth = SubpopRankTruth; /// One (group, fraction) question. - type Probe = (Group, f64); + type Probe = (GroupKey, f64); type Answer = f64; fn truth(&self, table: &GeneratedTable) -> Result { @@ -53,13 +54,13 @@ impl GroundTruth for SubpopRankErrorGT { } } } - let mut per_group: HashMap> = HashMap::with_capacity(borrowed.len()); + let mut per_group: HashMap> = HashMap::with_capacity(borrowed.len()); for (group, mut held) in borrowed { held.sort_by(f64::total_cmp); - per_group.insert(owned(&group), held); + per_group.insert(owned(&group, &self.group_columns), held); } - let mut by_size: Vec<(Group, u64)> = per_group + let mut by_size: Vec<(GroupKey, u64)> = per_group .iter() .map(|(g, v)| (g.clone(), v.len() as u64)) .collect(); @@ -69,10 +70,11 @@ impl GroundTruth for SubpopRankErrorGT { per_group, probed, items: table.row_num as usize, + schema_width: self.value_column, }) } - fn probes(&self, truth: &SubpopRankTruth) -> Vec<(Group, f64)> { + fn probes(&self, truth: &SubpopRankTruth) -> Vec<(GroupKey, f64)> { let mut out = Vec::with_capacity(truth.probed.len() * GROUP_GRID_POINTS); for group in &truth.probed { match truth.per_group.get(group) { @@ -89,41 +91,16 @@ impl GroundTruth for SubpopRankErrorGT { fn score( &self, truth: &SubpopRankTruth, - probes: &[(Group, f64)], + probes: &[(GroupKey, f64)], answers: &[f64], ) -> BTreeMap { - let mut sum_mean = 0.0f64; - let mut max_err = 0.0f64; - let mut scored_groups = 0usize; - - // The probe set is one contiguous grid per group, in order. - for (chunk_p, chunk_a) in probes - .chunks(GROUP_GRID_POINTS) - .zip(answers.chunks(GROUP_GRID_POINTS)) - { - let Some((group, _)) = chunk_p.first() else { - continue; - }; - let Some(sorted) = truth.per_group.get(group) else { - continue; - }; - let mut group_sum = 0.0f64; - for ((_, q), est) in chunk_p.iter().zip(chunk_a) { - let err = rank_err(sorted, *est, *q); - group_sum += err; - if err > max_err { - max_err = err; - } - } - sum_mean += group_sum / GROUP_GRID_POINTS as f64; - scored_groups += 1; - } - + let (groups, max_err) = rank_errors(truth, probes, answers); + let scored_groups = groups.len(); let mut metrics: BTreeMap = BTreeMap::new(); metrics.insert( "mean_rank_err".into(), if scored_groups > 0 { - sum_mean / scored_groups as f64 + groups.iter().filter_map(|g| g.error).sum::() / scored_groups as f64 } else { 0.0 }, @@ -134,8 +111,63 @@ impl GroundTruth for SubpopRankErrorGT { metrics.insert("probes".into(), scored_groups as f64); metrics.insert("subpopulations".into(), truth.per_group.len() as f64); metrics.insert("group_columns".into(), self.group_columns.len() as f64); + write_groups( + &groups, + truth.items as u64, + truth.schema_width, + &mut metrics, + ); metrics } + + /// A group's error is its mean rank error over the grid, the number + /// `mean_rank_err` averages over groups. + fn per_group( + &self, + truth: &SubpopRankTruth, + probes: &[(GroupKey, f64)], + answers: &[f64], + ) -> Vec { + rank_errors(truth, probes, answers).0 + } +} + +/// Each group's mean rank error over its grid, plus the largest rank error any +/// single probe saw. +fn rank_errors( + truth: &SubpopRankTruth, + probes: &[(GroupKey, f64)], + answers: &[f64], +) -> (Vec, f64) { + let mut max_err = 0.0f64; + let mut groups = Vec::new(); + + // The probe set is one contiguous grid per group, in order. + for (chunk_p, chunk_a) in probes + .chunks(GROUP_GRID_POINTS) + .zip(answers.chunks(GROUP_GRID_POINTS)) + { + let Some((group, _)) = chunk_p.first() else { + continue; + }; + let Some(sorted) = truth.per_group.get(group) else { + continue; + }; + let mut group_sum = 0.0f64; + for ((_, q), est) in chunk_p.iter().zip(chunk_a) { + let err = rank_err(sorted, *est, *q); + group_sum += err; + if err > max_err { + max_err = err; + } + } + groups.push(( + group.clone(), + sorted.len() as u64, + Some(group_sum / GROUP_GRID_POINTS as f64), + )); + } + (group_errors(groups.into_iter()), max_err) } #[cfg(test)] @@ -154,11 +186,11 @@ mod tests { .expect("the table has the named columns"); assert_eq!(truth.items, 6); assert_eq!( - truth.per_group[&vec!["a".to_string()]], + truth.per_group[&vec![Some("a".to_string())]], vec![10.0, 10.0, 20.0] ); assert_eq!( - truth.per_group[&vec!["b".to_string()]], + truth.per_group[&vec![Some("b".to_string())]], vec![30.0, 30.0, 30.0] ); } diff --git a/configs/datagen/hydra_columns.yaml b/configs/datagen/hydra_columns.yaml index 50cb4b5c..88b098f0 100644 --- a/configs/datagen/hydra_columns.yaml +++ b/configs/datagen/hydra_columns.yaml @@ -40,7 +40,8 @@ column_label: [key1, key2, value] row_num: 200000 column_spec: - # key1: the column the comparator groups by. + # key1: the column the comparator groups by unless `--group-columns` names + # another subset (`1`, `0,1`). - data_type: string distribution: kind: uniform diff --git a/configs/datagen/hydra_columns_f64.yaml b/configs/datagen/hydra_columns_f64.yaml index ac22d2a6..15b54921 100644 --- a/configs/datagen/hydra_columns_f64.yaml +++ b/configs/datagen/hydra_columns_f64.yaml @@ -21,7 +21,8 @@ column_label: [key1, key2, value] row_num: 200000 column_spec: - # key1: the column the comparator groups by. + # key1: the column the comparator groups by unless `--group-columns` names + # another subset (`1`, `0,1`). - data_type: string distribution: kind: uniform diff --git a/configs/datagen/hydra_columns_string.yaml b/configs/datagen/hydra_columns_string.yaml index 9997da4c..132e5c2c 100644 --- a/configs/datagen/hydra_columns_string.yaml +++ b/configs/datagen/hydra_columns_string.yaml @@ -23,7 +23,8 @@ column_label: [key1, key2, value] row_num: 200000 column_spec: - # key1: the column the comparator groups by. + # key1: the column the comparator groups by unless `--group-columns` names + # another subset (`1`, `0,1`). - data_type: string distribution: kind: uniform diff --git a/configs/datagen/hydra_columns_u64.yaml b/configs/datagen/hydra_columns_u64.yaml index 11a04211..8e6b57d8 100644 --- a/configs/datagen/hydra_columns_u64.yaml +++ b/configs/datagen/hydra_columns_u64.yaml @@ -21,7 +21,8 @@ column_label: [key1, key2, value] row_num: 200000 column_spec: - # key1: the column the comparator groups by. + # key1: the column the comparator groups by unless `--group-columns` names + # another subset (`1`, `0,1`). - data_type: string distribution: kind: uniform diff --git a/configs/datagen/hydra_kll_disjoint_labels.yaml b/configs/datagen/hydra_kll_disjoint_labels.yaml index cff3f56d..b98a7559 100644 --- a/configs/datagen/hydra_kll_disjoint_labels.yaml +++ b/configs/datagen/hydra_kll_disjoint_labels.yaml @@ -10,7 +10,8 @@ column_label: [key1, key2, value] row_num: 200000 column_spec: - # key1: the column the comparator groups by. + # key1: the column the comparator groups by unless `--group-columns` names + # another subset (`1`, `0,1`). - data_type: string distribution: kind: uniform diff --git a/configs/datagen/hydra_univmon_columns.yaml b/configs/datagen/hydra_univmon_columns.yaml index ee4d1356..adad591e 100644 --- a/configs/datagen/hydra_univmon_columns.yaml +++ b/configs/datagen/hydra_univmon_columns.yaml @@ -25,7 +25,8 @@ column_label: [key1, key2, value] row_num: 20000 column_spec: - # key1: the column the comparator groups by. + # key1: the column the comparator groups by unless `--group-columns` names + # another subset (`1`, `0,1`). - data_type: string distribution: kind: uniform diff --git a/sketch-bench/src/request.rs b/sketch-bench/src/request.rs index 1a13d182..421990a7 100644 --- a/sketch-bench/src/request.rs +++ b/sketch-bench/src/request.rs @@ -118,6 +118,10 @@ pub struct Requirement { pub workers: usize, /// How many shards a merge measurement folds pub merge_shards: usize, + /// The label columns a grouped (`hydra-*`) row asks and scores, ascending + pub group_columns: Vec, + /// Where a grouped row writes each scored group's error, if anywhere + pub per_group_out: Option, /// A named comparator, or `None` for the row's default. pub comparator: Option, /// Measured runs, and the warm-ups run and discarded before them diff --git a/sketch-bench/src/wrappers/hydra_cms/mod.rs b/sketch-bench/src/wrappers/hydra_cms/mod.rs index 6a01f62c..a3eac34b 100644 --- a/sketch-bench/src/wrappers/hydra_cms/mod.rs +++ b/sketch-bench/src/wrappers/hydra_cms/mod.rs @@ -60,11 +60,14 @@ mod tests { fed(&mut h, &r); } // (a, 10) occurs twice, under two different second labels. - assert_eq!(h.estimate_subpop_frequency(&["a"], &10i64), 2.0); - assert_eq!(h.estimate_subpop_frequency(&["a"], &20i64), 1.0); - assert_eq!(h.estimate_subpop_frequency(&["b"], &30i64), 1.0); + assert_eq!(h.estimate_subpop_frequency(&[Some("a")], &10i64), 2.0); + assert_eq!(h.estimate_subpop_frequency(&[Some("a")], &20i64), 1.0); + assert_eq!(h.estimate_subpop_frequency(&[Some("b")], &30i64), 1.0); // The full key is its own subpopulation and is stored too. - assert_eq!(h.estimate_subpop_frequency(&["a", "x"], &10i64), 1.0); + assert_eq!( + h.estimate_subpop_frequency(&[Some("a"), Some("x")], &10i64), + 1.0 + ); } /// A group that never occurred must estimate zero. This is the failure mode @@ -74,7 +77,7 @@ mod tests { fn an_absent_group_estimates_zero() { let mut h = built(); fed(&mut h, &record("a;x", 10)); - assert_eq!(h.estimate_subpop_frequency(&["zzz"], &10i64), 0.0); + assert_eq!(h.estimate_subpop_frequency(&[Some("zzz")], &10i64), 0.0); } /// Count-Min is linear and the grid is cell-wise, so folding two shards is @@ -91,7 +94,7 @@ mod tests { left.inner .merge(&right.inner) .expect("both operands built from one ParamSet, so shapes match"); - assert_eq!(left.estimate_subpop_frequency(&["a"], &10i64), 7.0); + assert_eq!(left.estimate_subpop_frequency(&[Some("a")], &10i64), 7.0); } /// The grid's key columns are fixed at construction: a record of another @@ -126,8 +129,8 @@ mod tests { fn an_empty_label_keeps_its_column() { let mut h = built(); fed(&mut h, &record(";x", 10)); - assert_eq!(h.estimate_subpop_frequency(&[""], &10i64), 1.0); - assert_eq!(h.estimate_subpop_frequency(&["x"], &10i64), 0.0); + assert_eq!(h.estimate_subpop_frequency(&[Some("")], &10i64), 1.0); + assert_eq!(h.estimate_subpop_frequency(&[Some("x")], &10i64), 0.0); } #[test] diff --git a/sketch-bench/src/wrappers/hydra_cms/polars.rs b/sketch-bench/src/wrappers/hydra_cms/polars.rs index 6bcacd40..706143dc 100644 --- a/sketch-bench/src/wrappers/hydra_cms/polars.rs +++ b/sketch-bench/src/wrappers/hydra_cms/polars.rs @@ -33,7 +33,7 @@ pub fn build_polars_subpop_frequency_cms( } impl PolarsSubpopFrequencyCms { - pub fn estimate_subpop_frequency(&self, labels: &[&str], value: &T) -> f64 { + pub fn estimate_subpop_frequency(&self, labels: &[Option<&str>], value: &T) -> f64 { self.0.query(labels, value) } } @@ -92,7 +92,7 @@ pub fn insert_step_polars_subpop_frequency_cms( pub fn query_polars_subpop_frequency_cms( params: &ParamSet, items: Rc>, - probes: Rc, T)>>, + probes: Rc>, T)>>, passes: usize, ) -> Result>, BuildError> { let mut out = Vec::with_capacity(passes); diff --git a/sketch-bench/src/wrappers/hydra_cms/sketchlib.rs b/sketch-bench/src/wrappers/hydra_cms/sketchlib.rs index dc3a629d..243ed3e4 100644 --- a/sketch-bench/src/wrappers/hydra_cms/sketchlib.rs +++ b/sketch-bench/src/wrappers/hydra_cms/sketchlib.rs @@ -39,7 +39,11 @@ pub fn build_hydra_cms(config: &ParamSet, label_columns: usize) -> Result(&self, labels: &[&str], value: &V) -> f64 { + pub fn estimate_subpop_frequency( + &self, + labels: &[Option<&str>], + value: &V, + ) -> f64 { query( &self.inner, labels, @@ -106,7 +110,7 @@ pub fn insert_step_hydra_cms( pub fn query_hydra_cms( params: &ParamSet, items: Rc>, - probes: Rc, V)>>, + probes: Rc>, V)>>, passes: usize, ) -> Result>, BuildError> { merge_query_hydra_cms(params, items, probes, 1, passes) @@ -117,7 +121,7 @@ pub fn query_hydra_cms( pub fn merge_query_hydra_cms( params: &ParamSet, items: Rc>, - probes: Rc, V)>>, + probes: Rc>, V)>>, shards: usize, passes: usize, ) -> Result>, BuildError> { diff --git a/sketch-bench/src/wrappers/hydra_cs/mod.rs b/sketch-bench/src/wrappers/hydra_cs/mod.rs index 6d49033b..270e903b 100644 --- a/sketch-bench/src/wrappers/hydra_cs/mod.rs +++ b/sketch-bench/src/wrappers/hydra_cs/mod.rs @@ -60,11 +60,14 @@ mod tests { fed(&mut h, &r); } // (a, 10) occurs twice, under two different second labels. - assert_eq!(h.estimate_subpop_frequency(&["a"], &10i64), 2.0); - assert_eq!(h.estimate_subpop_frequency(&["a"], &20i64), 1.0); - assert_eq!(h.estimate_subpop_frequency(&["b"], &30i64), 1.0); + assert_eq!(h.estimate_subpop_frequency(&[Some("a")], &10i64), 2.0); + assert_eq!(h.estimate_subpop_frequency(&[Some("a")], &20i64), 1.0); + assert_eq!(h.estimate_subpop_frequency(&[Some("b")], &30i64), 1.0); // The full key is its own subpopulation and is stored too. - assert_eq!(h.estimate_subpop_frequency(&["a", "x"], &10i64), 1.0); + assert_eq!( + h.estimate_subpop_frequency(&[Some("a"), Some("x")], &10i64), + 1.0 + ); } /// A group that never occurred must estimate zero. This is the failure mode @@ -74,7 +77,7 @@ mod tests { fn an_absent_group_estimates_zero() { let mut h = built(); fed(&mut h, &record("a;x", 10)); - assert_eq!(h.estimate_subpop_frequency(&["zzz"], &10i64), 0.0); + assert_eq!(h.estimate_subpop_frequency(&[Some("zzz")], &10i64), 0.0); } /// Count Sketch is linear and the grid is cell-wise, so folding two shards is @@ -91,7 +94,7 @@ mod tests { left.inner .merge(&right.inner) .expect("both operands built from one ParamSet, so shapes match"); - assert_eq!(left.estimate_subpop_frequency(&["a"], &10i64), 7.0); + assert_eq!(left.estimate_subpop_frequency(&[Some("a")], &10i64), 7.0); } #[test] diff --git a/sketch-bench/src/wrappers/hydra_cs/polars.rs b/sketch-bench/src/wrappers/hydra_cs/polars.rs index 73e0ad8b..adab3d57 100644 --- a/sketch-bench/src/wrappers/hydra_cs/polars.rs +++ b/sketch-bench/src/wrappers/hydra_cs/polars.rs @@ -33,7 +33,7 @@ pub fn build_polars_subpop_frequency_cs( } impl PolarsSubpopFrequencyCs { - pub fn estimate_subpop_frequency(&self, labels: &[&str], value: &T) -> f64 { + pub fn estimate_subpop_frequency(&self, labels: &[Option<&str>], value: &T) -> f64 { self.0.query(labels, value) } } @@ -91,7 +91,7 @@ pub fn insert_step_polars_subpop_frequency_cs( pub fn query_polars_subpop_frequency_cs( params: &ParamSet, items: Rc>, - probes: Rc, T)>>, + probes: Rc>, T)>>, passes: usize, ) -> Result>, BuildError> { let mut out = Vec::with_capacity(passes); diff --git a/sketch-bench/src/wrappers/hydra_cs/sketchlib.rs b/sketch-bench/src/wrappers/hydra_cs/sketchlib.rs index 554a3808..9c326e78 100644 --- a/sketch-bench/src/wrappers/hydra_cs/sketchlib.rs +++ b/sketch-bench/src/wrappers/hydra_cs/sketchlib.rs @@ -39,7 +39,11 @@ pub fn build_hydra_cs(config: &ParamSet, label_columns: usize) -> Result(&self, labels: &[&str], value: &V) -> f64 { + pub fn estimate_subpop_frequency( + &self, + labels: &[Option<&str>], + value: &V, + ) -> f64 { query( &self.inner, labels, @@ -106,7 +110,7 @@ pub fn insert_step_hydra_cs( pub fn query_hydra_cs( params: &ParamSet, items: Rc>, - probes: Rc, V)>>, + probes: Rc>, V)>>, passes: usize, ) -> Result>, BuildError> { merge_query_hydra_cs(params, items, probes, 1, passes) @@ -117,7 +121,7 @@ pub fn query_hydra_cs( pub fn merge_query_hydra_cs( params: &ParamSet, items: Rc>, - probes: Rc, V)>>, + probes: Rc>, V)>>, shards: usize, passes: usize, ) -> Result>, BuildError> { diff --git a/sketch-bench/src/wrappers/hydra_hll/mod.rs b/sketch-bench/src/wrappers/hydra_hll/mod.rs index 52ef926f..29efabf5 100644 --- a/sketch-bench/src/wrappers/hydra_hll/mod.rs +++ b/sketch-bench/src/wrappers/hydra_hll/mod.rs @@ -58,7 +58,7 @@ mod tests { } fed_hll(&mut h, &record("a;y", 20)); // Two distinct values under label `a`, seen four times. - let est = h.estimate_subpop_cardinality(&["a"]); + let est = h.estimate_subpop_cardinality(&[Some("a")]); assert!( (est - 2.0).abs() < 0.5, "two distinct values under `a`, estimated {est}" @@ -69,7 +69,7 @@ mod tests { fn hll_absent_group_estimates_zero() { let mut h = built_hll(); fed_hll(&mut h, &record("a;x", 10)); - assert_eq!(h.estimate_subpop_cardinality(&["zzz"]), 0.0); + assert_eq!(h.estimate_subpop_cardinality(&[Some("zzz")]), 0.0); } /// A HyperLogLog is register-wise mergeable, so two shards fold without @@ -84,7 +84,7 @@ mod tests { left.inner .merge(&right.inner) .expect("both operands built from one ParamSet, so shapes match"); - let est = left.estimate_subpop_cardinality(&["a"]); + let est = left.estimate_subpop_cardinality(&[Some("a")]); assert!( (est - 3.0).abs() < 0.5, "three distinct values across both shards, estimated {est}" diff --git a/sketch-bench/src/wrappers/hydra_hll/polars.rs b/sketch-bench/src/wrappers/hydra_hll/polars.rs index 272b99c1..822445b0 100644 --- a/sketch-bench/src/wrappers/hydra_hll/polars.rs +++ b/sketch-bench/src/wrappers/hydra_hll/polars.rs @@ -34,7 +34,7 @@ pub fn build_polars_subpop_cardinality( } impl PolarsSubpopCardinality { - pub fn estimate_subpop_cardinality(&self, labels: &[&str]) -> f64 { + pub fn estimate_subpop_cardinality(&self, labels: &[Option<&str>]) -> f64 { self.0.query(labels) } } @@ -92,7 +92,7 @@ pub fn insert_step_polars_subpop_cardinality( pub fn query_polars_subpop_cardinality( params: &ParamSet, items: Rc>, - probes: Rc>>, + probes: Rc>>>, passes: usize, ) -> Result>, BuildError> { let mut out = Vec::with_capacity(passes); diff --git a/sketch-bench/src/wrappers/hydra_hll/sketchlib.rs b/sketch-bench/src/wrappers/hydra_hll/sketchlib.rs index fc4815c4..bbd303a6 100644 --- a/sketch-bench/src/wrappers/hydra_hll/sketchlib.rs +++ b/sketch-bench/src/wrappers/hydra_hll/sketchlib.rs @@ -35,7 +35,7 @@ pub fn build_hydra_hll(config: &ParamSet, label_columns: usize) -> Result f64 { + pub fn estimate_subpop_cardinality(&self, labels: &[Option<&str>]) -> f64 { query(&self.inner, labels, &HydraQuery::Cardinality, "hydra-hll") } } @@ -96,7 +96,7 @@ pub fn insert_step_hydra_hll( pub fn query_hydra_hll( params: &ParamSet, items: Rc>, - probes: Rc>>, + probes: Rc>>>, passes: usize, ) -> Result>, BuildError> { merge_query_hydra_hll(params, items, probes, 1, passes) @@ -107,7 +107,7 @@ pub fn query_hydra_hll( pub fn merge_query_hydra_hll( params: &ParamSet, items: Rc>, - probes: Rc>>, + probes: Rc>>>, shards: usize, passes: usize, ) -> Result>, BuildError> { diff --git a/sketch-bench/src/wrappers/hydra_kll/mod.rs b/sketch-bench/src/wrappers/hydra_kll/mod.rs index e6758577..de6f74f6 100644 --- a/sketch-bench/src/wrappers/hydra_kll/mod.rs +++ b/sketch-bench/src/wrappers/hydra_kll/mod.rs @@ -64,7 +64,7 @@ mod tests { for _ in 0..500 { fed_kll(&mut h, &frecord("b;x", 10_000.0)); } - let median = h.estimate_subpop_quantile(&["a"], 0.5); + let median = h.estimate_subpop_quantile(&[Some("a")], 0.5); assert!( (1.0..=101.0).contains(&median), "group `a` spans 1..=101, median estimated {median}" @@ -80,8 +80,8 @@ mod tests { for v in 1..=101 { fed_kll(&mut h, &frecord("a;x", v as f64)); } - assert_eq!(h.estimate_subpop_quantile(&["a"], 0.0), 1.0); - assert_eq!(h.estimate_subpop_quantile(&["a"], 1.0), 101.0); + assert_eq!(h.estimate_subpop_quantile(&[Some("a")], 0.0), 1.0); + assert_eq!(h.estimate_subpop_quantile(&[Some("a")], 1.0), 101.0); } /// The library allocates a cell's retained slots once, so the footprint is diff --git a/sketch-bench/src/wrappers/hydra_kll/polars.rs b/sketch-bench/src/wrappers/hydra_kll/polars.rs index 44ecb2f4..11a6a268 100644 --- a/sketch-bench/src/wrappers/hydra_kll/polars.rs +++ b/sketch-bench/src/wrappers/hydra_kll/polars.rs @@ -46,8 +46,8 @@ impl PolarsSubpopQuantile { /// `floor(phi * n)`, clamped to the last index. That is the index whose /// rank interval contains `phi * n`, which is what the rank-error /// comparator scores against, so an exact answer scores zero. - pub fn estimate_subpop_quantile(&self, labels: &[&str], phi: f64) -> f64 { - let Some(values) = self.sorted.get(&prefix_key(labels)) else { + pub fn estimate_subpop_quantile(&self, labels: &[Option<&str>], phi: f64) -> f64 { + let Some(values) = self.sorted.get(&group_key(labels)) else { return f64::NAN; }; if values.is_empty() { @@ -157,7 +157,7 @@ pub fn insert_step_polars_subpop_quantile( params: &ParamSet, items: Rc>, - probes: Rc, f64)>>, + probes: Rc>, f64)>>, passes: usize, ) -> Result>, BuildError> { let mut out = Vec::with_capacity(passes); diff --git a/sketch-bench/src/wrappers/hydra_kll/sketchlib.rs b/sketch-bench/src/wrappers/hydra_kll/sketchlib.rs index 672de091..7f0ea176 100644 --- a/sketch-bench/src/wrappers/hydra_kll/sketchlib.rs +++ b/sketch-bench/src/wrappers/hydra_kll/sketchlib.rs @@ -46,7 +46,7 @@ impl HydraKll { /// at a rank, which is what rank error is defined over. The `Cdf` variant /// answers the inverse question. #[inline] - pub fn estimate_subpop_quantile(&self, labels: &[&str], phi: f64) -> f64 { + pub fn estimate_subpop_quantile(&self, labels: &[Option<&str>], phi: f64) -> f64 { query(&self.inner, labels, &HydraQuery::Quantile(phi), "hydra-kll") } } @@ -112,7 +112,7 @@ pub fn insert_step_hydra_kll( pub fn query_hydra_kll( params: &ParamSet, items: Rc>, - probes: Rc, f64)>>, + probes: Rc>, f64)>>, passes: usize, ) -> Result>, BuildError> { merge_query_hydra_kll(params, items, probes, 1, passes) @@ -123,7 +123,7 @@ pub fn query_hydra_kll( pub fn merge_query_hydra_kll( params: &ParamSet, items: Rc>, - probes: Rc, f64)>>, + probes: Rc>, f64)>>, shards: usize, passes: usize, ) -> Result>, BuildError> { diff --git a/sketch-bench/src/wrappers/hydra_shared.rs b/sketch-bench/src/wrappers/hydra_shared.rs index 0521e338..1af9d7ef 100644 --- a/sketch-bench/src/wrappers/hydra_shared.rs +++ b/sketch-bench/src/wrappers/hydra_shared.rs @@ -6,8 +6,8 @@ use crate::wrappers::BuildError; use asap_sketchlib::input::{HydraCounter, HydraQuery}; use asap_sketchlib::{DataInput, Hydra}; -pub(crate) fn labels(group: &[String]) -> Vec<&str> { - group.iter().map(String::as_str).collect() +pub(crate) fn labels(group: &[Option]) -> Vec> { + group.iter().map(Option::as_deref).collect() } /// The label columns of a `;`-joined record stream, which every record must @@ -54,10 +54,11 @@ pub(crate) fn update(h: &mut Hydra, key: &str, value: &DataInput, variant: &str) } } -/// Asks `query` of the subpopulation `group` constrains: its values are the -/// leading key columns' (the scored subpopulations group by column 0), the -/// rest unconstrained. A probe wider than the grid is refused. -pub(crate) fn query(h: &Hydra, group: &[&str], query: &HydraQuery, variant: &str) -> f64 { +/// Asks `query` of the subpopulation `group` constrains: a value at each +/// grouped column, `None` (unconstrained) at the rest and past its end, so any +/// non-empty subset of the key columns can be asked. A probe wider than the +/// grid is refused. +pub(crate) fn query(h: &Hydra, group: &[Option<&str>], query: &HydraQuery, variant: &str) -> f64 { let width = h.schema().len(); if group.len() > width { panic!( @@ -65,7 +66,9 @@ pub(crate) fn query(h: &Hydra, group: &[&str], query: &HydraQuery, variant: &str group.len() ); } - let key: Vec> = (0..width).map(|i| group.get(i).copied()).collect(); + let key: Vec> = (0..width) + .map(|i| group.get(i).copied().flatten()) + .collect(); h.query_key(&key, query) .unwrap_or_else(|e| panic!("{variant}: probe {group:?}: {e}")) } diff --git a/sketch-bench/src/wrappers/hydra_univmon/mod.rs b/sketch-bench/src/wrappers/hydra_univmon/mod.rs index 181375ee..ab6073c8 100644 --- a/sketch-bench/src/wrappers/hydra_univmon/mod.rs +++ b/sketch-bench/src/wrappers/hydra_univmon/mod.rs @@ -59,7 +59,7 @@ mod tests { fed(&mut h, &record("a;x", 10)); } fed(&mut h, &record("a;y", 20)); - let est = h.estimate_subpop_l1_norm(&["a"]); + let est = h.estimate_subpop_l1_norm(&[Some("a")]); assert!( (est - 4.0).abs() < 0.5, "four records under `a`, estimated {est}" @@ -73,7 +73,7 @@ mod tests { fed(&mut h, &record("a;x", 10)); } fed(&mut h, &record("a;y", 20)); - let est = h.estimate_subpop_cardinality(&["a"]); + let est = h.estimate_subpop_cardinality(&[Some("a")]); assert!( (est - 2.0).abs() < 0.5, "two distinct values under `a`, estimated {est}" @@ -86,7 +86,7 @@ mod tests { for _ in 0..8 { fed(&mut h, &record("a;x", 10)); } - let est = h.estimate_subpop_entropy(&["a"]); + let est = h.estimate_subpop_entropy(&[Some("a")]); assert!( est.abs() < 0.1, "one value, so no uncertainty, estimated {est}" @@ -99,8 +99,8 @@ mod tests { for _ in 0..4 { fed(&mut h, &record("a;x", 10)); } - let l1 = h.estimate_subpop_l1_norm(&["a"]); - let l2 = h.estimate_subpop_l2_norm(&["a"]); + let l1 = h.estimate_subpop_l1_norm(&[Some("a")]); + let l2 = h.estimate_subpop_l2_norm(&[Some("a")]); assert!((l1 - l2).abs() < 0.5, "l1 {l1}, l2 {l2}"); } @@ -116,7 +116,7 @@ mod tests { left.inner .merge(&right.inner) .expect("both operands built from one ParamSet, so shapes match"); - let est = left.estimate_subpop_l1_norm(&["a"]); + let est = left.estimate_subpop_l1_norm(&[Some("a")]); assert!( (est - 7.0).abs() < 0.5, "seven records in all, estimated {est}" @@ -174,14 +174,17 @@ mod baseline_tests { type Asked = fn( &ParamSet, Rc>, - Rc>>, + Rc>>>, usize, ) -> Result>, crate::wrappers::BuildError>; fn answers_for(query: Asked) -> Vec { let params = ParamSet::of(&HydraUnivmonParams::canonical()); - let probes = Rc::new(vec![vec!["a".to_string()], vec!["b".to_string()]]); + let probes = Rc::new(vec![ + vec![Some("a".to_string())], + vec![Some("b".to_string())], + ]); let mut passes = query(¶ms, stream(), probes, 1).expect("baseline builds"); let pass = passes.pop().expect("one pass"); pass().0 diff --git a/sketch-bench/src/wrappers/hydra_univmon/polars.rs b/sketch-bench/src/wrappers/hydra_univmon/polars.rs index eb71f9f1..0e9dd152 100644 --- a/sketch-bench/src/wrappers/hydra_univmon/polars.rs +++ b/sketch-bench/src/wrappers/hydra_univmon/polars.rs @@ -39,7 +39,7 @@ impl Default for PolarsSubpopCardinalityUnivmon { } impl PolarsSubpopCardinalityUnivmon { - pub fn estimate_subpop_cardinality(&self, labels: &[&str]) -> f64 { + pub fn estimate_subpop_cardinality(&self, labels: &[Option<&str>]) -> f64 { self.0.query(labels) } } @@ -59,7 +59,7 @@ fn build_polars_subpop_vector( } impl PolarsSubpopUnivmon { - pub fn estimate_subpop_statistic(&self, labels: &[&str]) -> f64 { + pub fn estimate_subpop_statistic(&self, labels: &[Option<&str>]) -> f64 { self.0.query(labels) } } @@ -116,7 +116,7 @@ pub fn insert_step_polars_subpop_cardinality_univmon( pub fn query_polars_subpop_cardinality_univmon( params: &ParamSet, items: Rc>, - probes: Rc>>, + probes: Rc>>>, passes: usize, ) -> Result>, BuildError> { let mut out = Vec::with_capacity(passes); @@ -209,7 +209,7 @@ fn insert_step_polars_subpop_vector( fn query_polars_subpop_vector( params: &ParamSet, items: Rc>, - probes: Rc>>, + probes: Rc>>>, passes: usize, fold: fn(&[u64]) -> f64, ) -> Result>, BuildError> { @@ -274,7 +274,7 @@ pub fn insert_step_polars_subpop_l1_norm( pub fn query_polars_subpop_l1_norm( params: &ParamSet, items: Rc>, - probes: Rc>>, + probes: Rc>>>, passes: usize, ) -> Result>, BuildError> { query_polars_subpop_vector(params, items, probes, passes, l1_norm) @@ -307,7 +307,7 @@ pub fn insert_step_polars_subpop_l2_norm( pub fn query_polars_subpop_l2_norm( params: &ParamSet, items: Rc>, - probes: Rc>>, + probes: Rc>>>, passes: usize, ) -> Result>, BuildError> { query_polars_subpop_vector(params, items, probes, passes, l2_norm) @@ -340,7 +340,7 @@ pub fn insert_step_polars_subpop_entropy( pub fn query_polars_subpop_entropy( params: &ParamSet, items: Rc>, - probes: Rc>>, + probes: Rc>>>, passes: usize, ) -> Result>, BuildError> { query_polars_subpop_vector(params, items, probes, passes, entropy) diff --git a/sketch-bench/src/wrappers/hydra_univmon/sketchlib.rs b/sketch-bench/src/wrappers/hydra_univmon/sketchlib.rs index 11c689fa..e7465088 100644 --- a/sketch-bench/src/wrappers/hydra_univmon/sketchlib.rs +++ b/sketch-bench/src/wrappers/hydra_univmon/sketchlib.rs @@ -49,7 +49,7 @@ pub fn build_hydra_univmon( impl HydraUnivmon { #[inline] - pub fn estimate_subpop_cardinality(&self, labels: &[&str]) -> f64 { + pub fn estimate_subpop_cardinality(&self, labels: &[Option<&str>]) -> f64 { query( &self.inner, labels, @@ -59,17 +59,17 @@ impl HydraUnivmon { } #[inline] - pub fn estimate_subpop_l1_norm(&self, labels: &[&str]) -> f64 { + pub fn estimate_subpop_l1_norm(&self, labels: &[Option<&str>]) -> f64 { query(&self.inner, labels, &HydraQuery::L1Norm, "hydra-univmon") } #[inline] - pub fn estimate_subpop_l2_norm(&self, labels: &[&str]) -> f64 { + pub fn estimate_subpop_l2_norm(&self, labels: &[Option<&str>]) -> f64 { query(&self.inner, labels, &HydraQuery::L2Norm, "hydra-univmon") } #[inline] - pub fn estimate_subpop_entropy(&self, labels: &[&str]) -> f64 { + pub fn estimate_subpop_entropy(&self, labels: &[Option<&str>]) -> f64 { query(&self.inner, labels, &HydraQuery::Entropy, "hydra-univmon") } } @@ -131,10 +131,10 @@ pub fn insert_step_hydra_univmon( fn asked_hydra_univmon( params: &ParamSet, items: Rc>, - probes: Rc>>, + probes: Rc>>>, shards: usize, passes: usize, - estimate: fn(&HydraUnivmon, &[&str]) -> f64, + estimate: fn(&HydraUnivmon, &[Option<&str>]) -> f64, ) -> Result>, BuildError> { let mut out = Vec::with_capacity(passes); for _ in 0..passes { @@ -162,7 +162,7 @@ fn asked_hydra_univmon( pub fn query_hydra_univmon_cardinality( params: &ParamSet, items: Rc>, - probes: Rc>>, + probes: Rc>>>, passes: usize, ) -> Result>, BuildError> { asked_hydra_univmon( @@ -180,7 +180,7 @@ pub fn query_hydra_univmon_cardinality( pub fn merge_query_hydra_univmon_cardinality( params: &ParamSet, items: Rc>, - probes: Rc>>, + probes: Rc>>>, shards: usize, passes: usize, ) -> Result>, BuildError> { @@ -197,7 +197,7 @@ pub fn merge_query_hydra_univmon_cardinality( pub fn query_hydra_univmon_l1_norm( params: &ParamSet, items: Rc>, - probes: Rc>>, + probes: Rc>>>, passes: usize, ) -> Result>, BuildError> { asked_hydra_univmon( @@ -215,7 +215,7 @@ pub fn query_hydra_univmon_l1_norm( pub fn merge_query_hydra_univmon_l1_norm( params: &ParamSet, items: Rc>, - probes: Rc>>, + probes: Rc>>>, shards: usize, passes: usize, ) -> Result>, BuildError> { @@ -232,7 +232,7 @@ pub fn merge_query_hydra_univmon_l1_norm( pub fn query_hydra_univmon_l2_norm( params: &ParamSet, items: Rc>, - probes: Rc>>, + probes: Rc>>>, passes: usize, ) -> Result>, BuildError> { asked_hydra_univmon( @@ -250,7 +250,7 @@ pub fn query_hydra_univmon_l2_norm( pub fn merge_query_hydra_univmon_l2_norm( params: &ParamSet, items: Rc>, - probes: Rc>>, + probes: Rc>>>, shards: usize, passes: usize, ) -> Result>, BuildError> { @@ -267,7 +267,7 @@ pub fn merge_query_hydra_univmon_l2_norm( pub fn query_hydra_univmon_entropy( params: &ParamSet, items: Rc>, - probes: Rc>>, + probes: Rc>>>, passes: usize, ) -> Result>, BuildError> { asked_hydra_univmon( @@ -285,7 +285,7 @@ pub fn query_hydra_univmon_entropy( pub fn merge_query_hydra_univmon_entropy( params: &ParamSet, items: Rc>, - probes: Rc>>, + probes: Rc>>>, shards: usize, passes: usize, ) -> Result>, BuildError> { diff --git a/sketch-bench/src/wrappers/polars_shared.rs b/sketch-bench/src/wrappers/polars_shared.rs index d049a1b9..7e9e3c52 100644 --- a/sketch-bench/src/wrappers/polars_shared.rs +++ b/sketch-bench/src/wrappers/polars_shared.rs @@ -287,9 +287,17 @@ pub fn subset_key(parts: &[&str], mask: usize) -> String { out } -/// The key a probe of the leading label columns `labels` reads. -pub fn prefix_key(labels: &[&str]) -> String { - subset_key(labels, (1 << labels.len()) - 1) +/// The key a probe reads: `labels` holds a value at each grouped column and +/// `None` at the rest, so any subset of the columns is a group, not only a +/// prefix of them. +pub fn group_key(labels: &[Option<&str>]) -> String { + let parts: Vec<&str> = labels.iter().map(|l| l.unwrap_or("")).collect(); + let mask = labels + .iter() + .enumerate() + .filter(|(_, l)| l.is_some()) + .fold(0, |mask, (j, _)| mask | (1 << j)); + subset_key(&parts, mask) } /// Expand one record into `(subset_key, value)` rows, one per non-empty subset @@ -360,9 +368,9 @@ impl PolarsSubpopFrequencyCore { } } - pub fn query(&self, labels: &[&str], value: &T) -> f64 { + pub fn query(&self, labels: &[Option<&str>], value: &T) -> f64 { self.counts - .get(&(prefix_key(labels), value.count_key())) + .get(&(group_key(labels), value.count_key())) .copied() .unwrap_or(0) as f64 } @@ -426,8 +434,8 @@ impl PolarsSubpopCardinalityCore { } } - pub fn query(&self, labels: &[&str]) -> f64 { - self.distinct.get(&prefix_key(labels)).copied().unwrap_or(0) as f64 + pub fn query(&self, labels: &[Option<&str>]) -> f64 { + self.distinct.get(&group_key(labels)).copied().unwrap_or(0) as f64 } pub fn memory_bytes(&self) -> usize { @@ -495,8 +503,8 @@ impl PolarsSubpopVectorCore { .collect(); } - pub fn query(&self, labels: &[&str]) -> f64 { - self.exact.get(&prefix_key(labels)).copied().unwrap_or(0.0) + pub fn query(&self, labels: &[Option<&str>]) -> f64 { + self.exact.get(&group_key(labels)).copied().unwrap_or(0.0) } pub fn memory_bytes(&self) -> usize { @@ -542,7 +550,8 @@ mod tests { fn subset_keys_tag_each_value_with_its_column() { assert_eq!(subset_key(&["a", "b", "c"], 0b101), "label0:a;label2:c"); assert_eq!(subset_key(&["x:y;z", ""], 0b11), r"label0:x\:y\;z;label1:"); - assert_eq!(prefix_key(&["a", "b"]), "label0:a;label1:b"); + assert_eq!(group_key(&[Some("a"), Some("b")]), "label0:a;label1:b"); + assert_eq!(group_key(&[None, Some("b")]), "label1:b"); } /// #74: the column-0 group `a` holds 2 records (`a;a`, `a;b`). The old @@ -553,8 +562,11 @@ mod tests { core.update(&("a;a".to_string(), 7)); core.update(&("a;b".to_string(), 7)); core.finalize(); - assert_eq!(core.query(&["a"], &7), 2.0); - assert_eq!(core.query(&["a", "a"], &7), 1.0); - assert_eq!(core.query(&["b"], &7), 0.0); + assert_eq!(core.query(&[Some("a")], &7), 2.0); + assert_eq!(core.query(&[Some("a"), Some("a")], &7), 1.0); + assert_eq!(core.query(&[Some("b")], &7), 0.0); + // Column 1 alone: `a` once, `b` once, with column 0 unconstrained. + assert_eq!(core.query(&[None, Some("a")], &7), 1.0); + assert_eq!(core.query(&[None, Some("b")], &7), 1.0); } }