diff --git a/CHANGELOG.md b/CHANGELOG.md index b3ad6284a..c3985105c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,7 @@ - `SPAN` groups columns under a shared header cell (spanner). - `FORMAT` configures how a column's cells are displayed. - `FACET` sets row groups. + - `SUMMARISE` computes aggregates over rows. - `Writer::write_table` renders a resolved table, taking the new public `TableLayout` — the table's cells bundled with their column and row metadata. diff --git a/doc/_quarto.yml b/doc/_quarto.yml index a3296ce46..9066d88d3 100644 --- a/doc/_quarto.yml +++ b/doc/_quarto.yml @@ -64,6 +64,8 @@ website: href: syntax/clause/format.qmd - text: "`FACET`" href: syntax/clause/facet-tabulate.qmd + - text: "`SUMMARISE`" + href: syntax/clause/summarise.qmd - text: Gallery href: gallery/index.qmd - href: faq.qmd @@ -131,6 +133,8 @@ website: href: syntax/clause/format.qmd - text: "`FACET`" href: syntax/clause/facet-tabulate.qmd + - text: "`SUMMARISE`" + href: syntax/clause/summarise.qmd - section: Layers contents: - section: Types diff --git a/doc/ggsql.xml b/doc/ggsql.xml index 90de554f3..abc14b0a7 100644 --- a/doc/ggsql.xml +++ b/doc/ggsql.xml @@ -391,6 +391,8 @@ + + @@ -439,6 +441,8 @@ + + @@ -480,6 +484,8 @@ + + @@ -520,6 +526,8 @@ + + @@ -568,6 +576,8 @@ + + @@ -612,6 +622,8 @@ + + @@ -655,6 +667,8 @@ + + @@ -690,6 +704,8 @@ + + @@ -728,6 +744,8 @@ + + @@ -769,6 +787,8 @@ + + @@ -805,6 +825,47 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -821,6 +882,8 @@ + + diff --git a/doc/syntax/clause/summarise.qmd b/doc/syntax/clause/summarise.qmd new file mode 100644 index 000000000..d1172069a --- /dev/null +++ b/doc/syntax/clause/summarise.qmd @@ -0,0 +1,252 @@ +--- +title: "Summarise values into new rows" +--- + +Values can be summarised and displayed in dedicated rows. +This is helpful to display observations alongside statistics in the table. +`SUMMARISE` can be repeated to compute multiple summaries. + +## Clause syntax + +```ggsql +SUMMARISE [GROUP | GRAND] OF , ... + SETTING => , ... +``` + +Also accepts the spelling `SUMMARIZE`. + +## Scope + +```ggsql +[GROUP | GRAND] +``` + +The scope directly following the `SUMMARISE` clause determines which rows the operation aggregates over. +Setting the scope to `GROUP` will compute the summary for each group determined by `FACET` clauses separately. +The `GRAND` scope will compute the summary for all rows. +Without spelling out a scope, the default will be `GROUP`. +When no groups are declared by `FACET` and the scope is set to `GROUP`, all rows are treated as belonging to the same group. +The difference between a `FACET`-less `GROUP` scope and a `GRAND` scope is largely a difference in style and label spanning. +A query result with no rows cannot be summarised: `SUMMARISE` errors on an empty table. + +## Operation + +```ggsql + +``` + +This part of the clause can be an identifier or a string representing an expression. +The identifiers are the same ones used in stat [aggregation](draw.qmd#aggregate-functions) in plots. +When using an identifier, one of the following operations are available: + +| Name | Description | Numeric | Date(time) | Other | +|------|-------------|:-------:|:----------:|:-----:| +| `count` | Number of rows | ✓ | ✓ | ✓ | +| `n_distinct` | Number of distinct values | ✓ | ✓ | ✓ | +| `n_missing` | Number of nulls | ✓ | ✓ | ✓ | +| `sum` | Sum | ✓ | | | +| `prod` | Product | ✓ | | | +| `min` | Minimum | ✓ | ✓ | | +| `max` | Maximum | ✓ | ✓ | | +| `range` | max − min | ✓ | ✓ | | +| `mid` | (min + max) / 2 | ✓ | ✓ | | +| `mean` | Arithmetic mean | ✓ | ✓ | | +| `geomean` | Geometric mean | ✓ | | | +| `harmean` | Harmonic mean | ✓ | | | +| `rms` | Root-mean-square | ✓ | | | +| `median` | Median | ✓ | ✓ | | +| `sdev` | Standard deviation (population, ÷ n) | ✓ | ✓ | | +| `se` | Standard error (population, ÷ n) | ✓ | ✓ | | +| `var` | Variance (population, ÷ n) | ✓ | | | +| `iqr` | Interquartile range | ✓ | ✓ | | +| `p05` | 5th percentile | ✓ | ✓ | | +| `p10` | 10th percentile | ✓ | ✓ | | +| `p25` | 25th percentile | ✓ | ✓ | | +| `p50` | 50th percentile (median) | ✓ | ✓ | | +| `p75` | 75th percentile | ✓ | ✓ | | +| `p90` | 90th percentile | ✓ | ✓ | | +| `p95` | 95th percentile | ✓ | ✓ | | + +When using a string as an expression, you can use any of the identifiers in curly braces. +For example `'{mean}'` will display the mean via expression. +The expressions can be used to display multiple metrics in a single cell, e.g. `'{median} ({p25}, {p75})'` will display the median and interquartile range in one cell. +Inside the brackets, you can use limited arithmetic. +The operands include the operation identifiers listed above (like `mean`, `sdev`), numeric literals (`2`, `0.5`) and scientific notation (`1e6`). +The `+`, `-` unary operators and `+`, `-`, `*` and `/` binary operators and `(`/`)` parentheses for grouping. +For example you can use `'({mean - 1.96 * se}, {mean + 1.96 * se})'` to display a 95% confidence interval (assuming normal distribution) in parentheses separated by a comma. +If any placeholder in a string expression comes out `null` (see `missing` below), the whole cell comes out `null`. + +For the naked, non-string identifiers the formatting of the cell values is applied externally via `FORMAT` clauses. +The string expressions can be self-formatting via the same syntax as [scale breaks](scale.qmd#break-formatting). +A string-expression cell ignores a `FORMAT` wildcard label, but direct labels still apply — including `null => …` to replace a null result. +All summary metrics are assumed to be numeric. +As such, the `:num` formatter is implied and does not need to be written out in full. +The expression `'{mean:%.2f}'` will display the mean with two decimal points in printf-style. +Other formatters can be used, e.g. `{max:bytes}` to display base-1024 size. +When using arithmetic, the formatting is placed at the end and is applied to the result so that `'{mean + sdev:%.2f}'` rounds the expression to two decimals. + +Date and timestamp columns accept the order statistics (`min`, `max`, `mid`, `mean`, `median` and the percentiles), returning a date or timestamp, and `range`, `sdev`, `se` and `iqr`, returning a duration. +A date or timestamp renders as ISO text or via `:time` (`'{min:time %d %b %Y}'`); in arithmetic it becomes a plain number: days for dates, seconds for timestamps — so `'{max-min:duration d}'` renders a date range as a duration. +A date-valued `mean` or `mid` rounds to the nearest whole day. + +## Column selection + +```ggsql +OF , ... +``` + +The `SUMMARISE` clause requires a comma-separated list of columns to aggregate. +The columns must be part of the `TABULATE` selection. +The 'counting' operations listed above can be applied to columns of any type, the order and dispersion statistics also accept date and timestamp columns, and the remaining operations require numeric columns. + +## Settings + +```ggsql +SETTING => +``` + +The `SETTING` sub-clause is typical with key-value pairs. +It currently takes the following parameters: + +* `place`: the location of the summary rows relative to the body rows they summarise. +Can be `'top'` to place the summary rows at the top of each group or table, or `'bottom'` (default) to place the summary rows after the body rows. +* `rowlabel`: A string for the label of the summary row. The default `null` falls back to printing the operation, where string expression operations are displayed without formatting details. +* `missing`: A string option for how to treat `null` values in the table. +The default `'propagate'` will list any non-counting operation as `null`, while the tallies `count` and `n_missing` include null-rows — note that `n_distinct` is not a tally and comes out `null` when the column contains any. +Can be set to `'drop'` to explicitly ignore `null` values in aggregates and ignore these rows in counting operations. +* `blank`: A string displayed in cells of the summary row whose column are not summarised. +The default is an em dash (`'—'`); set it to `''` for empty cells. + +## Examples + +A summary without groups will summarise all rows. + +```{ggsql} +CREATE TEMP TABLE my_data AS +SELECT DISTINCT ON (species, island, sex) * FROM ggsql:penguins +WHERE bill_len IS NOT NULL AND sex IS NOT NULL + +TABULATE * FROM my_data +SUMMARISE mean OF bill_len, bill_dep +``` + +A grand summary will always summarise all rows, and is displayed with a stronger border. + +```{ggsql} +TABULATE * FROM my_data +SUMMARISE GRAND mean OF bill_len, bill_dep +``` + +Groups can be specified using `FACET`. + +```{ggsql} +TABULATE * FROM my_data +FACET island +SUMMARISE mean OF bill_len, bill_dep +``` + +The labels of summary rows compose with regular body row labels in the stub. + +```{ggsql} +TABULATE * FROM my_data +FACET island +FORMAT STUB species +SUMMARISE mean OF bill_len, bill_dep +``` + +The display of the label in the stub can be changed using the `rowlabel` setting. + +```{ggsql} +TABULATE * FROM my_data +FACET species +SUMMARISE mean OF bill_len, bill_dep + SETTING rowlabel => 'Average' +``` + +The display of non-summary cells can be changed using the `blank` setting. +Using an empty string (`''`) leaves these cells empty. + +```{ggsql} +TABULATE * FROM my_data +FACET species +SUMMARISE mean OF bill_len, bill_dep + SETTING blank => '' +``` + +The summary cells are subject to `FORMAT` when using plain identifiers, along with the body rows. + +```{ggsql} +TABULATE * FROM my_data +FACET species +FORMAT bill_len, bill_dep LABEL * => '{:num %.2f}' +SUMMARISE mean OF bill_len, bill_dep +``` + +To specifically format the summary values, you can use the expression string form. + +```{ggsql} +TABULATE * FROM my_data +FACET species +SUMMARISE '📏 {mean:%.2f}' OF bill_len, bill_dep +``` + +You can use repeated summaries. +The order in which the summaries are declared determine the order of the rows. + +```{ggsql} +TABULATE * FROM my_data +SUMMARISE p25 OF bill_len, bill_dep +SUMMARISE p50 OF bill_len, bill_dep +SUMMARISE p75 OF bill_len, bill_dep +``` + +Or display related summaries in a single cell. + +```{ggsql} +TABULATE * FROM my_data +SUMMARISE '{p50:%.2f} ({p25:%.2f}, {p75:%.2f})' OF bill_len, bill_dep +``` + +When data contains 'null' values, they propagate to aggregate metrics (but not necessarily count metrics). +Notice how the summary of `bill_len` comes out as 'null'. + +```{ggsql} +SELECT species, island, sex, + CASE WHEN island = 'Biscoe' THEN NULL ELSE bill_len END AS bill_len, + bill_dep, flipper_len, body_mass +FROM my_data + +TABULATE * +SUMMARISE '{mean:%.2f}' OF bill_len, bill_dep +``` + +You can ignore 'null' values by using the `missing => 'drop'` setting. + +```{ggsql} +SELECT species, island, sex, + CASE WHEN island = 'Biscoe' THEN NULL ELSE bill_len END AS bill_len, + bill_dep, flipper_len, body_mass +FROM my_data + +TABULATE * +SUMMARISE '{mean:%.2f}' OF bill_len, bill_dep + SETTING missing => 'drop' +``` + +Date and timestamp columns can be summarised with the order statistics, formatted with `:time`, and `range` gives their span as a duration. + +```{ggsql} +CREATE TEMP TABLE launches AS +SELECT * FROM (VALUES + ('Alpha', DATE '2024-01-15'), + ('Alpha', DATE '2024-02-10'), + ('Beta', DATE '2024-03-01'), + ('Beta', DATE '2024-03-20')) AS t(product, launched) + +TABULATE * FROM launches +FACET product +SUMMARISE '{min:time %d %b %Y} – {max}' OF launched + SETTING rowlabel => 'Dates' +SUMMARISE '{range:duration d}' OF launched + SETTING rowlabel => 'Duration' +``` \ No newline at end of file diff --git a/doc/syntax/index.qmd b/doc/syntax/index.qmd index 7f78d5c7a..31ea43d3e 100644 --- a/doc/syntax/index.qmd +++ b/doc/syntax/index.qmd @@ -20,6 +20,7 @@ ggsql augments the standard SQL syntax with a number of new clauses to describe - [`SPAN`](clause/span.qmd) can be used to group columns and display a label across them - [`FORMAT`](clause/format.qmd) declares formatting for columns - [`FACET`](clause/facet-tabulate.qmd) enables row-grouping operations on tables +- [`SUMMARISE`](clause/summarise.qmd) adds rows with summarised values to the table ## Layers There are many different layers to choose from when visualising your data. Some are straightforward translations of your data into visual marks such as a point layer, while others perform more or less complicated calculations like e.g. the histogram layer. A layer is selected by providing the layer name after the `DRAW` clause diff --git a/doc/vendor/SKILL.md b/doc/vendor/SKILL.md index c62e9fdc2..35ee3d04b 100644 --- a/doc/vendor/SKILL.md +++ b/doc/vendor/SKILL.md @@ -184,6 +184,7 @@ Configures cell display and column placement. - A SPAN id may stand in for its columns: `FORMAT Q1, price SETTING hjust => 'right'` - Settings: `hjust` (`'left'`/`'right'`/`'centre'`/`'center'` or 0–1; default right for numeric/stub, left otherwise), `width` (`'100px'` or `'20%'`) - `LABEL` works like SCALE's: direct replacement (`'adelie' => 'Pygoscelis adeliae'`), `null` on the right suppresses the cell, unquoted `null` on the left matches missing values, and `* => '...'` formats every value with a template (`{:lower}`, `{:num %.0f}`, etc.) +- Without a LABEL, float columns display at a shared per-column precision: the most decimals any value needs (each value the fewest that faithfully represents it), so whole values pad (`50.0` beside `39.1`) and SUMMARISE results round to the same precision. Integer columns display bare. ```ggsql SELECT * FROM ggsql:penguins LIMIT 5 @@ -194,6 +195,27 @@ TABULATE * FORMAT body_mass SETTING hjust => 'right' LABEL null => '-', * => '{:num %.0f}g' ``` +### SUMMARISE + +Adds summary rows computed over the table's rows: one per `FACET` group (`GROUP`, default) or a single row over all rows (`GRAND`, rendered with a stronger border; its label spans group stub columns). Repeatable — clause order is row order within a boundary. Also spelled `SUMMARIZE`. Columns must be part of the TABULATE selection. Errors on an empty query result. + +``` +SUMMARISE [GROUP | GRAND] OF , ... + SETTING => , ... +``` + +- **Operation** — an identifier: tallies `count n_distinct n_missing` (any column type); sums `sum prod`; extremes `min max range mid`; centrality `mean geomean harmean rms median`; dispersion `sdev se var iqr` (population statistics, ÷ n); percentiles `p05 p10 p25 p50 p75 p90 p95`. All but the tallies require numeric columns, except that date/timestamp columns also accept the order statistics (`min max mid mean median p*`, returning a date/timestamp) and `range sdev se iqr` (returning a duration). +- **Template** — or a string with `{expr}` placeholders interpolated into the cell: `'{median} ({p25}, {p75})'`. Expressions allow `+ - * /`, parentheses, unary `+`/`-`, numeric literals incl. scientific notation (`'{mean - 1.96 * se}'`). Per-placeholder formatting follows the placeholder after `:`; `num` is implied (`'{mean:%.2f}'` = `'{mean:num %.2f}'`; also `:bytes`, `:duration`, `:time`). A bare date/timestamp leaf renders ISO or via `:time` (`'{min:time %d %b %Y}'`); in arithmetic a date/timestamp operand becomes a plain number — days for dates, seconds for timestamps — so `'{max-min:duration d}'` renders a date range as a duration. A template self-formats: the column's `FORMAT` wildcard renaming does not apply, but direct renamings do (including `null => …` — a null placeholder nulls the whole cell); a bare operation takes the full renaming. +- **Settings** — `place` (`'bottom'` default / `'top'` — summary rows before or after the group/table body), `rowlabel` (stub label; default the operation, templates without their format specs), `missing` (`'propagate'` default — any null makes a non-tally summary null; `'drop'` — ignore nulls. `count` counts rows under propagate, non-null values under drop), `blank` (display text for cells in columns the clause does not summarise; default `'—'` — a summarised column that computes to null still reports `null`). + +```ggsql +TABULATE * FROM ggsql:penguins +FACET island +FORMAT STUB species +SUMMARISE mean OF bill_len, bill_dep +SUMMARISE GRAND '{mean:%.1f} ± {se:%.1f}' OF bill_len SETTING rowlabel => 'Mean ± SE' +``` + --- ## Layer types diff --git a/src/AGENTS.md b/src/AGENTS.md index 79ce15702..6b2072bb8 100644 --- a/src/AGENTS.md +++ b/src/AGENTS.md @@ -63,6 +63,18 @@ Grammar lives in [`/tree-sitter-ggsql/`](../tree-sitter-ggsql/) — when adding **Caching layer.** `CachingReader` (`cache.rs`) wraps a primary reader plus an in-memory `CacheBackend`, splitting work across two `Reader` surfaces. **`execute_sql` = source**: base reads of the user's data plus user setup/DML run on the primary (with result memoization), except `ggsql:` builtins, the `__ggsql_cache_meta__` table, and reads that reference a cache-resident internal table, which go to the cache. **`execute_sql_cached` = compute**: all dialect-generated/derived SQL (schema probes, stats, projection/map transforms, spatial setup, final layer queries — everything operating on `__ggsql_*` tables) runs on the cache; it defaults to `execute_sql` so a plain reader runs everything on one connection. Cache routing is by **exact-identifier membership** in the set of tables registered into the cache. Memoization keys on `hash(primary_uri + sql)` and is tracked in the `__ggsql_cache_meta__` table inside the cache backend. Each memoized read is bounded by a **TTL** (default 300s) and the whole memo by an **LRU byte budget** (default 512 MB); both are configurable via `CacheConfig` (env `GGSQL_CACHE_DISABLED`/`GGSQL_CACHE_TTL`/`GGSQL_CACHE_MAX_BYTES`, or per-connection URI query parameters `?cache_ttl=…&cache_max_bytes=…&cache_disabled=…`). The `__ggsql_cache_meta__` table is queryable for introspection (`SELECT * FROM __ggsql_cache_meta__`). Pure/non-visual SQL (CLI table fallback, Jupyter) goes through `execute_sql` so it reads the primary rather than the empty cache. `Reader::materialize_table` (default = `CREATE TEMP TABLE` on the reader, no Rust roundtrip) is overridden to read the body via the source surface and `register()` the result into the cache, so the primary is never written to; `Reader::caches_sources()` (default `false`, `true` for `CachingReader`) gates the executor's per-layer source staging: file sources are staged on the cache surface, while identifiers go through `materialize_table`, which routes the read to the cache (CTEs, builtins, cache-resident tables) or the primary as needed. `dialect()` returns the **cache** dialect, and every compute-surface failure is prefixed with the cache backend's scheme (``on the `duckdb` cache backend: …``) so a cache-dialect driver error is not mistaken for one from the user's own connection. Selected via the composite `+://` scheme (`reader_from_uri` / `split_cache_uri`) or the CLI `--cache` flag; off by default. The memo's bookkeeping — registering a table, its row in `__ggsql_cache_meta__`, LRU eviction under the byte budget — is `CacheTables`, which other callers use on a backend of their own (the Jupyter kernel's results API does, without wrapping the user's reader). An entry can be **pinned**, exempting it from eviction until unpinned (pins are kept in memory, not in the metadata table); `CachingReader` never pins, and the TTL and enabled checks stay in `CachingReader`. `CacheTables` takes a byte budget rather than a `CacheConfig`; `put` and `put_pinned` add entries, `contains` checks for one, and `evict_to`/`total_bytes`/`pinned_bytes` let a caller with a wider budget evict to that instead, `evict_to` returning the keys it evicted. Only an existing entry can be pinned. +### Validation vs execution + +`validate()` ([validate.rs](validate.rs)) runs every check possible with knowledge of the struct alone — no reader, no `DataFrame`, no `Labels`. Anything needing the query result's schema or sibling-clause context is execution's job, in `setup_*` functions under `execute/`. + +The shared machinery lives in `params.rs`: `validate_parameters` (check only; absence is always valid), `with_defaults` (fill defaults; assumes validated input), and `resolve_parameters` = the two composed. Each AST struct exposes what its consumers call: + +- `validate_settings()` — called from the struct's `validate()`, which `Table::validate()` aggregates with clause-index prefixes ("SPAN 1: …"). +- `resolve_settings()` — validate + fill in one step, for execute-side consumers that handle one clause at a time. +- `with_default_settings()` — fill only, for consumers that validate and fill at different moments (e.g. `setup_formats` validates per clause before merging, fills after). + +Don't add a `resolve_settings` that has no caller; don't give a `setup_*` function struct-local work that `validate()` could run. + ### `execute/` The pipeline that takes a parsed `Plot` (or `Table`) plus a `Reader` and produces a `ResolvedPlot` (or `ResolvedTable`) — typed data per layer, scales resolved, casts applied; for tables, cells laid out with spans, stub and formats. Submodules: diff --git a/src/execute/table/facet.rs b/src/execute/table/facet.rs index 90f55f5ec..0bb9c2791 100644 --- a/src/execute/table/facet.rs +++ b/src/execute/table/facet.rs @@ -9,7 +9,7 @@ use crate::array_util::value_to_string; use crate::dataframe::into_array_ref; use crate::plot::facet::{distinct_levels, level_keys, order_levels, Facet, FacetLayout, LevelKey}; use crate::plot::ParameterValue; -use crate::table::{TableColumn, TableRow}; +use crate::table::TableColumn; use crate::{ColumnSection, DataFrame}; /// Assign each `df` row its group key: one rank per facet variable (see @@ -56,36 +56,37 @@ fn facet_columns<'a>(facet: &Facet, df: &'a DataFrame) -> Result bool { + matches!( + facet.properties.get("separator"), + Some(ParameterValue::String(_)) + ) && facet.get_variables().len() > 1 +} + /// Collapse a separated facet into one variable: join the facet variables' /// (formatted) values per row into a column named for the first variable, -/// drop the originals, renumber the rows' group keys to single ids, and -/// reduce the facet to that variable. Group stub columns in `columns` are -/// replaced by one, keeping the first's label and properties. Passes -/// everything through unchanged when the facet sets no `separator` or has a -/// single variable. -/// The table pieces `collapse_group_columns` rewrites for a separated facet. -type Collapsed = (DataFrame, Vec, Vec, Option); - +/// drop the originals, and reduce the facet to that variable. Group stub +/// columns in `columns` are replaced by one, keeping the first's label and +/// properties. The rows' group keys are already single ids — `setup_rows` +/// renumbers them at birth. Passes everything through unchanged unless +/// [`collapses`] applies. pub(super) fn collapse_group_columns( df: DataFrame, mut columns: Vec, - mut rows: Vec, facet: Option<&Facet>, -) -> Result { - let Some(facet) = facet else { - return Ok((df, columns, rows, None)); +) -> Result<(DataFrame, Vec, Option), String> { + let Some(facet) = facet.filter(|f| collapses(f)) else { + return Ok((df, columns, facet.cloned())); }; let separator = match facet.properties.get("separator") { Some(ParameterValue::String(separator)) => separator.clone(), - _ => return Ok((df, columns, rows, Some(facet.clone()))), + _ => unreachable!("collapses gates on a separator"), }; - // One variable has nothing to join. - let variables = facet.get_variables(); - if variables.len() == 1 { - return Ok((df, columns, rows, Some(facet.clone()))); - } // The joined column takes the first variable's name. + let variables = facet.get_variables(); let name = variables[0].clone(); let arrays: Vec<&ArrayRef> = variables @@ -106,17 +107,6 @@ pub(super) fn collapse_group_columns( .and_then(|df| df.with_column(&name, into_array_ref(joined))) .map_err(|e| e.to_string())?; - // Single-id keys: rows are group-sorted, so the id is the chunk index. - let mut id = 0; - let mut previous: Option> = None; - for row in &mut rows { - if previous.as_ref().is_some_and(|key| *key != row.group) { - id += 1; - } - previous = Some(std::mem::take(&mut row.group)); - row.group = vec![id]; - } - // Replace the group stub columns with one, at the first's position. if let Some(position) = columns.iter().position(|c| c.is_group_stub()) { let mut joined_column = columns[position].clone(); @@ -135,7 +125,7 @@ pub(super) fn collapse_group_columns( resolved: facet.resolved, }; - Ok((df, columns, rows, Some(facet))) + Ok((df, columns, Some(facet))) } /// Rank one facet variable's rows: non-null levels in the scale-free facet diff --git a/src/execute/table/format.rs b/src/execute/table/format.rs index e112f95cb..a31670ec9 100644 --- a/src/execute/table/format.rs +++ b/src/execute/table/format.rs @@ -1,11 +1,13 @@ //! `TABULATE FORMAT` resolution: `setup_formats` validates `SETTING` //! parameters and reshapes the per-clause formats into one `Format` per -//! column, `apply_formats` replaces a column's values with their display -//! text (`LABEL`), and `resolve_column_properties` resolves a column's -//! `SETTING` display properties. +//! column, `apply_formatting` replaces a column's values with their display +//! text (`LABEL`, or the float display precision from `display_decimals`), +//! and `resolve_column_properties` resolves a column's `SETTING` display +//! properties. use std::collections::HashMap; +use arrow::array::Array; use arrow::datatypes::DataType; use crate::array_util::{new_str_array, value_to_string}; @@ -15,7 +17,7 @@ use crate::{ColumnSection, DataFrame, Format, GgsqlError, Result, Spanner}; /// Validate every FORMAT's `SETTING` parameters, then reshape `formats` /// into one `Format` per column it covers. `spans` must already be resolved -/// (`Table::resolve_spanners`) — a name matching a SPAN id expands to that +/// (`Table::setup_spanners`) — a name matching a SPAN id expands to that /// span's columns. pub(super) fn setup_formats( df: &DataFrame, @@ -24,7 +26,7 @@ pub(super) fn setup_formats( ) -> Result> { for (idx, format) in formats.iter().enumerate() { format - .resolve_settings() + .validate_settings() .map_err(|e| GgsqlError::ValidationError(format!("FORMAT {}: {}", idx + 1, e)))?; } @@ -47,12 +49,10 @@ pub(super) fn setup_formats( } // A column no clause claimed a section for resolves to the body. - // Settings were validated per clause above; resolving again post-merge - // only fills defaults. + // Settings were validated per clause above, so post-merge only fills + // defaults. for format in resolved.values_mut() { - format.settings = format - .resolve_settings() - .map_err(GgsqlError::ValidationError)?; + format.settings = format.with_default_settings(); format.target.get_or_insert(ColumnSection::Body); } Ok(resolved) @@ -89,38 +89,69 @@ fn expand_format_columns( Ok(columns) } -/// Replace every column in `df` named in `formats` with its resolved -/// display text. A column whose `Format` has no `LABEL` at all -/// (`label_spec` empty) is left untouched. -pub(super) fn apply_formats( +/// Replace display-affecting columns in `df` with their display text. A +/// column named in `formats` with a `LABEL` (mapping or template) gets +/// its resolved labels; a float column gets padded to its display decimals +/// (see `display_decimals`). Everything else is left untouched. +pub(super) fn apply_formatting( df: &DataFrame, formats: &HashMap, ) -> Result { let mut df = df.clone(); - for (name, format) in formats { - // Skip the per-row formatting pass for a column nobody asked to - // reformat — the common `FORMAT ... SETTING ...` case. - let has_labels = - !format.label_spec.rename_is_empty() || format.label_spec.template().is_some(); - if !has_labels { - continue; - } - + for name in df.get_column_names() { + let format = formats.get(&name); + // A column whose format carries no labels — the common + // `FORMAT ... SETTING ...` case — skips the labelling pass. + let has_labels = format + .is_some_and(|f| !f.label_spec.rename_is_empty() || f.label_spec.template().is_some()); let array = df - .column(name) - .expect("setup_formats already checked this column exists") + .column(&name) + .expect("the names come from this frame") .clone(); - let resolved = crate::format::resolve_column_values(&array, &format.label_spec) - .map_err(|e| GgsqlError::ValidationError(format!("FORMAT column '{name}': {e}")))?; - let display: Vec> = resolved - .into_iter() - .enumerate() - .map(|(row, value)| Some(value.unwrap_or_else(|| value_to_string(&array, row)))) + if has_labels { + let format = format.expect("has_labels implies a format"); + let resolved = crate::format::resolve_column_values(&array, &format.label_spec) + .map_err(|e| GgsqlError::ValidationError(format!("FORMAT column '{name}': {e}")))?; + + let display: Vec> = resolved + .into_iter() + .enumerate() + .map(|(row, value)| Some(value.unwrap_or_else(|| value_to_string(&array, row)))) + .collect(); + let display_refs: Vec> = display.iter().map(|s| s.as_deref()).collect(); + + df = df.with_column(&name, new_str_array(display_refs))?; + continue; + } + + // A labelled column's labels are its display, so only un-labelled + // columns reach the padding pass. Needing no decimals keeps the + // bare integer display. + let d = crate::format::display_decimals(&array); + if d == 0 { + continue; + } + let display: Vec> = (0..array.len()) + .map(|i| { + if array.is_null(i) { + None + } else { + Some(match array.data_type() { + DataType::Float64 => { + let v = crate::array_util::as_f64(&array).unwrap().value(i); + format!("{v:.d$}") + } + _ => { + let v = f64::from(crate::array_util::as_f32(&array).unwrap().value(i)); + format!("{v:.d$}") + } + }) + } + }) .collect(); let display_refs: Vec> = display.iter().map(|s| s.as_deref()).collect(); - - df = df.with_column(name, new_str_array(display_refs))?; + df = df.with_column(&name, new_str_array(display_refs))?; } Ok(df) @@ -313,7 +344,7 @@ mod tests { let frame = df! { "price" => vec![1.0f64, 2.0] }.unwrap(); let formats = HashMap::from([("price".to_string(), format_with("{}", None))]); - let result = apply_formats(&frame, &formats).unwrap(); + let result = apply_formatting(&frame, &formats).unwrap(); assert_eq!(column_content(&result, "price"), vec!["1", "2"]); } @@ -323,7 +354,7 @@ mod tests { let frame = df! { "price" => vec![1.0f64, 2.0] }.unwrap(); let formats = HashMap::from([("price".to_string(), format_with("${:num %.2f}", None))]); - let result = apply_formats(&frame, &formats).unwrap(); + let result = apply_formatting(&frame, &formats).unwrap(); assert_eq!(column_content(&result, "price"), vec!["$1.00", "$2.00"]); } @@ -334,7 +365,7 @@ mod tests { let mapping = Some(HashMap::from([("0".to_string(), Some("-".to_string()))])); let formats = HashMap::from([("price".to_string(), format_with("{:num %.2f}", mapping))]); - let result = apply_formats(&frame, &formats).unwrap(); + let result = apply_formatting(&frame, &formats).unwrap(); assert_eq!(column_content(&result, "price"), vec!["-", "5.00"]); } @@ -344,7 +375,7 @@ mod tests { let frame = df! { "price" => vec![Some(1.0f64), None] }.unwrap(); let formats = HashMap::from([("price".to_string(), format_with("{:num %.2f}", None))]); - let result = apply_formats(&frame, &formats).unwrap(); + let result = apply_formatting(&frame, &formats).unwrap(); assert_eq!(column_content(&result, "price"), vec!["1.00", "null"]); } diff --git a/src/execute/table/layout.rs b/src/execute/table/layout.rs index 9ae3e69bb..0a7661de7 100644 --- a/src/execute/table/layout.rs +++ b/src/execute/table/layout.rs @@ -7,7 +7,9 @@ use std::collections::HashMap; use super::format::resolve_column_properties; use super::stub::{create_row_labels, create_stubhead}; +use super::summary::{SummaryChunk, SummaryRow}; use crate::array_util::{column_to_strings, value_to_string}; +use crate::naming; use crate::plot::facet::Facet; use crate::plot::Titles; use crate::table::{ @@ -22,7 +24,7 @@ use crate::{ColumnSection, DataFrame, Format, GgsqlError, Result, Spanner}; /// any `gather`-ing spanner and then for stub columns. A `place => 'top'` /// facet consumes its columns as group labels; a `place => 'left'` facet /// keeps them as group stub columns. `spans` must already be resolved -/// (`Table::resolve_spanners`). +/// (`Table::setup_spanners`). pub(super) fn setup_columns( df: &DataFrame, spans: &[Spanner], @@ -60,6 +62,19 @@ pub(super) fn setup_rows( let df = super::facet::drop_null_rows(facet, &df).map_err(GgsqlError::ValidationError)?; let keys = super::facet::setup_groups(facet, &df).map_err(GgsqlError::ValidationError)?; let (df, keys) = super::facet::reorder_rows(&df, keys).map_err(GgsqlError::ValidationError)?; + // A separated facet collapses to a single grouping level: renumber the + // keys to single ids (rows are group-contiguous after the reorder, so + // the id is the chunk index) and nothing downstream sees the multi-rank + // keys the sort needed. + let keys = if super::facet::collapses(facet) { + let mut ids = Vec::with_capacity(keys.len()); + for (id, chunk) in keys.chunk_by(|a, b| a == b).enumerate() { + ids.extend(std::iter::repeat_n(vec![id], chunk.len())); + } + ids + } else { + keys + }; let mut rows = Vec::with_capacity(keys.len()); for key in keys { let first_in_group = rows.last().is_none_or(|row: &TableRow| row.group != key); @@ -76,8 +91,9 @@ pub(super) fn setup_rows( } /// Build the resolved `TableLayout` for a table from its already-resolved -/// `columns`, already-`FORMAT`-applied `df`, and `setup_rows` body rows — -/// spanner rows, column labels, and body, composed together and validated. +/// `columns`, already-`FORMAT`-applied `df`, `setup_rows` body rows and +/// computed `summaries` — spanner rows, column labels, and body, composed +/// together and validated. pub(super) fn build_cells( df: &DataFrame, columns: Vec, @@ -85,6 +101,7 @@ pub(super) fn build_cells( spans: &[Spanner], titles: &TableTitles, facet: Option<&Facet>, + summaries: &[SummaryChunk], ) -> Result { let spanners = create_spanners(&columns, spans); // Every label empty means `TITLE col => NULL` (or `=> ''`) on every @@ -113,6 +130,10 @@ pub(super) fn build_cells( let header = heading.rowbind(header); let mut body_cells = create_row_labels(df, &columns); body_cells.extend(create_body(df, &columns)); + // Group summaries weave in before the facet passes, so group-stub + // merging and group-heading offsets cover them for free; grand rows sit + // outside every group, so they weave in last. + let (rows, body_cells) = weave_group_summaries(rows, body_cells, &columns, summaries); let (body_rows, body_cells) = match facet { None => (rows, body_cells), Some(facet) => { @@ -124,6 +145,7 @@ pub(super) fn build_cells( } } }; + let (body_rows, body_cells) = weave_grand_summaries(body_rows, body_cells, &columns, summaries); let table_body = TableLayout::new(columns.clone(), body_rows, body_cells); let layout = header.rowbind(table_body); let caption_layout = create_caption(titles.caption.as_deref(), &columns); @@ -160,12 +182,17 @@ fn create_table_columns( .data_type(); let format = formats.get(&name); let properties = resolve_column_properties(dtype, format); - // Group stubs record nesting order - let target = group_stub_variables - .iter() - .position(|v| *v == name) - .map(ColumnSection::GroupStub) - .unwrap_or_else(|| format.and_then(|f| f.target).unwrap_or_default()); + // the synthetic summary-label column is always a stub. + let target = if name == naming::SUMMARY_LABEL_COLUMN { + ColumnSection::Stub + } else { + // Group stubs record nesting order + group_stub_variables + .iter() + .position(|v| *v == name) + .map(ColumnSection::GroupStub) + .unwrap_or_else(|| format.and_then(|f| f.target).unwrap_or_default()) + }; let label = match titles.titles.get(&name) { // A stub head is a row-label header, not a data column header — // default it blank rather than to the column's own name. @@ -214,11 +241,140 @@ fn create_body(df: &DataFrame, columns: &[TableColumn]) -> Vec { cells } +/// Interleave the `GROUP` chunks' rows into the body, in data space: each +/// chunk's `top` rows, then the chunk itself, then its bottom rows. +fn weave_group_summaries( + rows: Vec, + cells: Vec, + columns: &[TableColumn], + summaries: &[SummaryChunk], +) -> (Vec, Vec) { + let summaries: Vec<&SummaryChunk> = summaries.iter().filter(|(key, _)| key.is_some()).collect(); + if summaries.is_empty() { + return (rows, cells); + } + debug_assert_eq!( + rows.chunk_by(|a, b| a.group == b.group).count(), + summaries.len(), + "one summary chunk per group" + ); + + let inserted: usize = summaries.iter().map(|(_, rows)| rows.len()).sum(); + let mut new_rows = Vec::with_capacity(rows.len() + inserted); + let mut summary_cells = Vec::new(); + // row_map[old data-row index] = its grid row after the weave. + let mut row_map = vec![0usize; rows.len()]; + let mut old_index = 0usize; + for (chunk, (key, chunk_summaries)) in rows + .chunk_by(|a, b| a.group == b.group) + .zip(summaries.iter()) + { + let key = key.as_ref().expect("filtered to group chunks"); + debug_assert_eq!(chunk[0].group, *key, "summary chunks in group order"); + let tops: Vec<&SummaryRow> = chunk_summaries.iter().filter(|s| s.top).collect(); + weave_summary_block( + &mut new_rows, + &mut summary_cells, + &tops, + key.clone(), + columns, + true, + ); + for row in chunk.iter() { + row_map[old_index] = new_rows.len(); + new_rows.push(row.clone()); + old_index += 1; + } + let bottoms: Vec<&SummaryRow> = chunk_summaries.iter().filter(|s| !s.top).collect(); + weave_summary_block( + &mut new_rows, + &mut summary_cells, + &bottoms, + key.clone(), + columns, + false, + ); + } + + let mut cells = cells; + for cell in &mut cells { + cell.top = row_map[cell.top]; + cell.bottom = row_map[cell.bottom]; + } + summary_cells.extend(cells); + (new_rows, summary_cells) +} + +/// Place the `GRAND` chunk's rows: `top` rows above the whole body, bottom +/// rows below it. +fn weave_grand_summaries( + rows: Vec, + cells: Vec, + columns: &[TableColumn], + summaries: &[SummaryChunk], +) -> (Vec, Vec) { + let Some((_, grand)) = summaries.iter().find(|(key, _)| key.is_none()) else { + return (rows, cells); + }; + let tops: Vec<&SummaryRow> = grand.iter().filter(|s| s.top).collect(); + + let mut cells = cells; + for cell in &mut cells { + cell.offset_rows(tops.len()); + } + let mut new_rows = Vec::with_capacity(rows.len() + grand.len()); + let mut summary_cells = Vec::new(); + weave_summary_block( + &mut new_rows, + &mut summary_cells, + &tops, + Vec::new(), + columns, + true, + ); + new_rows.extend(rows); + let bottoms: Vec<&SummaryRow> = grand.iter().filter(|s| !s.top).collect(); + weave_summary_block( + &mut new_rows, + &mut summary_cells, + &bottoms, + Vec::new(), + columns, + false, + ); + summary_cells.extend(cells); + (new_rows, summary_cells) +} + +/// Emit one grid row per clause row in `block`, marking the block's first +/// and last rows (both, when the block is one row) for the positional +/// classes. `above` is whether the block sits above the rows it summarizes. +fn weave_summary_block( + new_rows: &mut Vec, + summary_cells: &mut Vec, + block: &[&SummaryRow], + key: Vec, + columns: &[TableColumn], + above: bool, +) { + for (index, summary) in block.iter().enumerate() { + summary_cells.extend(summary.cells( + new_rows.len(), + columns, + index == 0, + index == block.len() - 1, + above, + )); + new_rows.push(TableRow::summary(key.clone())); + } +} + /// Interleave group-label rows into the body. At each group boundary, emit /// one `GroupHeading` row per facet-variable level that changed, labels read -/// from the group's first row (so an unchanged outer variable isn't +/// from the group's first data row (so an unchanged outer variable isn't /// restated). Body cells keep their data-row numbering, shifted down by -/// the label rows before them. +/// the label rows before them. Summary rows interleave with the data rows +/// but have no row in `df`, so only data rows advance the label lookup. fn weave_group_labels( df: &DataFrame, columns: &[TableColumn], @@ -240,17 +396,18 @@ fn weave_group_labels( let mut out_rows = Vec::new(); let mut label_cells = Vec::new(); - // body_offset[data row] = how many label rows precede it in the grid. - let mut body_offset = vec![0usize; df.height()]; + // body_offset[body row] = how many label rows precede it in the grid. + let mut body_offset = vec![0usize; rows.len()]; // None until the first group's key is read: it emits every level. let mut previous_key: Option<&[usize]> = None; + let mut df_row = 0usize; let mut row = 0usize; for group_rows in rows.chunk_by(|a, b| a.group == b.group) { let key = group_rows[0].group.as_slice(); let labels: Vec = facet_arrays .iter() - .map(|array| value_to_string(array, row)) + .map(|array| value_to_string(array, df_row)) .collect(); // When multiple labels exist, we have a nesting pattern. // We don't need to repeat every level label at every group, @@ -275,6 +432,9 @@ fn weave_group_labels( for table_row in group_rows.iter() { body_offset[row] = out_rows.len() - row; + if !table_row.classes.contains(&TableClass::SummaryRow) { + df_row += 1; + } out_rows.push(table_row.clone()); row += 1; } @@ -289,10 +449,13 @@ fn weave_group_labels( Ok((out_rows, label_cells)) } -/// Merge each group stub column's row labels into rowspanned cells. A cell -/// at depth `d` spans rows while the `d + 1` outermost ranks of the rows' -/// group keys are equal, so a group never merges into a cell opened under -/// a different outer level even when its label repeats. +/// Merge each group-stub column's per-row labels into rowspanned cells. +/// Runs are read off `rows`, not cells: a cell at depth `d` spans rows while +/// the `d + 1` outermost ranks of the rows' group keys are equal, so a group +/// never merges into a cell opened under a different outer level even when +/// its label repeats. A summary row carries its chunk's key but has no stub +/// cell of its own, so it joins its group's run by construction; the run's +/// content comes from its first data row's cell. fn merge_group_stub_cells( cells: Vec, columns: &[TableColumn], @@ -302,34 +465,53 @@ fn merge_group_stub_cells( return cells; } - // Column index of a group stub column -> position of its open cell in - // `out`, for the column whose cells are currently being walked. - let mut open: HashMap = HashMap::new(); + // Each group-stub column's per-row cells, by row — replaced by merged + // cells below. + let mut stub_cells: HashMap<(usize, usize), TableCell> = HashMap::new(); let mut out: Vec = Vec::with_capacity(cells.len()); for cell in cells { - if let ColumnSection::GroupStub(depth) = columns[cell.left].target { - if let Some(&index) = open.get(&cell.left) { - let current_key = &rows[cell.top].group[..=depth]; - let previous_key = &rows[cell.top - 1].group[..=depth]; - if current_key == previous_key { - out[index].bottom = cell.bottom; - continue; - } + if columns[cell.left].is_group_stub() { + stub_cells.insert((cell.left, cell.top), cell); + } else { + out.push(cell); + } + } + + for (left, column) in columns.iter().enumerate() { + let ColumnSection::GroupStub(depth) = column.target else { + continue; + }; + let mut start = 0; + while start < rows.len() { + let mut end = start; + while end + 1 < rows.len() + && rows[end + 1].group[..=depth] == rows[start].group[..=depth] + { + end += 1; } - open.insert(cell.left, out.len()); + let source = (start..=end) + .find_map(|row| stub_cells.get(&(left, row))) + .expect("every group-stub run holds a data row"); + let mut merged = TableCell::new_stub_row_group(start, left, source.content.clone()); + merged.bottom = end; + merged.properties = source.properties.clone(); + out.push(merged); + start = end + 1; } - out.push(cell); } out } #[cfg(test)] mod tests { - use super::super::format::{apply_formats, setup_formats}; + use super::super::format::{apply_formatting, setup_formats}; + use super::super::summary::{compute_summaries, setup_summaries}; use super::*; use crate::df; use crate::plot::{ParameterValue, Parameters}; - use crate::table::{extract_table_titles, TableCellKind}; + use crate::table::{ + extract_table_titles, Summary, SummaryOperation, SummaryScope, TableCellKind, + }; use crate::{ColumnSection, GgsqlError, Spanner, Table}; /// Runs the same steps `resolve_table_with_reader` does, minus the @@ -340,13 +522,13 @@ mod tests { let titles = extract_table_titles(&mut titles_map); let column_names = df.get_column_names(); let spans = table - .resolve_spanners(&titles_map, Some(&column_names)) + .setup_spanners(&titles_map, &column_names) .map_err(GgsqlError::ValidationError)?; let formats = setup_formats(df, &table.formats, &spans)?; let columns = setup_columns(df, &spans, &titles_map, &formats, None); - let df = apply_formats(df, &formats)?; + let df = apply_formatting(df, &formats)?; let rows = vec![TableRow::body(); df.height()]; - build_cells(&df, columns, rows, &spans, &titles, None) + build_cells(&df, columns, rows, &spans, &titles, None, &[]) } /// `resolve_layout`, for the (common) tests that only care about cells. @@ -354,6 +536,329 @@ mod tests { resolve_layout(df, table).map(|layout| layout.cells) } + /// `resolve_layout`, plus the `SUMMARISE` steps and a facet. + fn resolve_layout_with_summaries( + df: &DataFrame, + table: &Table, + facet: Option<&Facet>, + ) -> Result { + let mut titles_map = table.titles.clone(); + let titles = extract_table_titles(&mut titles_map); + let (mut df, rows) = setup_rows(df.clone(), facet)?; + let column_names = df.get_column_names(); + let spans = table + .setup_spanners(&titles_map, &column_names) + .map_err(GgsqlError::ValidationError)?; + let formats = setup_formats(&df, &table.formats, &spans)?; + let summaries = setup_summaries(&mut df, &formats, &table.summaries)?; + let columns = setup_columns(&df, &spans, &titles_map, &formats, facet); + let computed = compute_summaries(&df, &rows, &summaries, &formats)?; + let df = apply_formatting(&df, &formats)?; + build_cells(&df, columns, rows, &spans, &titles, facet, &computed) + } + + fn summary_clause(operation: &str, scope: SummaryScope, columns: &[&str]) -> Summary { + Summary { + operation: SummaryOperation::Stat(operation.to_string()), + scope, + columns: columns.iter().map(|c| c.to_string()).collect(), + settings: Parameters::new(), + } + } + + fn top_facet(variables: &[&str]) -> Facet { + let mut facet = left_facet(variables); + facet.properties = crate::params! { "place" => "top" }; + facet + } + + /// Body rows (header excluded) whose classes contain `class`, as grid rows. + fn rows_with_class(layout: &TableLayout, class: TableClass) -> Vec { + layout + .rows + .iter() + .enumerate() + .filter(|(_, row)| !row.is_header && row.classes.contains(&class)) + .map(|(index, _)| index) + .collect() + } + + /// The cell at exactly `row` whose content is `content`. + fn find_cell<'a>(layout: &'a TableLayout, row: usize, content: &str) -> &'a TableCell { + layout + .cells + .iter() + .find(|cell| cell.top == row && cell.content == content) + .unwrap_or_else(|| panic!("no cell at row {row} with content {content:?}")) + } + + #[test] + fn group_summary_without_a_facet_weaves_below_the_single_group() { + let frame = df! { + "x" => vec![1.5, 3.5], + } + .unwrap(); + let mut table = Table::new(); + table.summaries = vec![summary_clause("mean", SummaryScope::Group, &["x"])]; + + let layout = resolve_layout_with_summaries(&frame, &table, None).unwrap(); + + // Column-label row, two data rows, then the summary row. + assert_eq!(layout.rows.len(), 4); + let summary_row = rows_with_class(&layout, TableClass::SummaryRow); + assert_eq!(summary_row, vec![3]); + assert_eq!( + find_cell(&layout, 3, "mean").kind, + TableCellKind::SummaryLabel + ); + assert_eq!( + find_cell(&layout, 3, "2.5").kind, + TableCellKind::SummaryValue + ); + } + + #[test] + fn grand_summaries_sit_outside_the_body() { + let frame = df! { + "x" => vec![1.5, 3.5], + } + .unwrap(); + let mut table = Table::new(); + let mut top = summary_clause("median", SummaryScope::Grand, &["x"]); + top.settings = crate::params! { "place" => "top" }; + // Written bottom-clause first: placement, not clause order, decides. + table.summaries = vec![summary_clause("mean", SummaryScope::Grand, &["x"]), top]; + + let layout = resolve_layout_with_summaries(&frame, &table, None).unwrap(); + + assert_eq!(layout.rows.len(), 5); + assert_eq!(rows_with_class(&layout, TableClass::SummaryRow), vec![1, 4]); + assert_eq!( + find_cell(&layout, 1, "median").kind, + TableCellKind::SummaryLabel + ); + assert_eq!( + find_cell(&layout, 4, "mean").kind, + TableCellKind::SummaryLabel + ); + } + + #[test] + fn summary_cells_carry_their_blocks_position_classes() { + let frame = df! { + "x" => vec![1.5, 3.5], + } + .unwrap(); + let mut table = Table::new(); + table.summaries = vec![ + summary_clause("mean", SummaryScope::Grand, &["x"]), + summary_clause("median", SummaryScope::Grand, &["x"]), + ]; + + let layout = resolve_layout_with_summaries(&frame, &table, None).unwrap(); + + // Header, two data rows, then the two-row grand block: the double + // border on the edge touching the body, the group's solid one on + // the far edge. + let has = |row: usize, class: TableClass| { + layout + .cells + .iter() + .filter(|cell| cell.top == row) + .all(|cell| cell.classes.contains(&class)) + }; + assert!(has(3, TableClass::GrandSummary)); + assert!(has(3, TableClass::GrandSummaryFirst)); + assert!(!has(3, TableClass::SummaryLast)); + assert!(has(4, TableClass::GrandSummary)); + assert!(!has(4, TableClass::GrandSummaryFirst)); + assert!(has(4, TableClass::SummaryLast)); + } + + #[test] + fn a_top_grand_block_puts_its_double_border_against_the_body() { + let frame = df! { + "x" => vec![1.5, 3.5], + } + .unwrap(); + let mut table = Table::new(); + let mut first = summary_clause("mean", SummaryScope::Grand, &["x"]); + first.settings = crate::params! { "place" => "top" }; + let mut second = summary_clause("median", SummaryScope::Grand, &["x"]); + second.settings = crate::params! { "place" => "top" }; + table.summaries = vec![first, second]; + + let layout = resolve_layout_with_summaries(&frame, &table, None).unwrap(); + + // Header, then the two-row grand block above the data rows: the far + // edge gets the group's solid border, the body edge the double one. + let has = |row: usize, class: TableClass| { + layout + .cells + .iter() + .filter(|cell| cell.top == row) + .all(|cell| cell.classes.contains(&class)) + }; + assert!(has(1, TableClass::SummaryFirst)); + assert!(!has(1, TableClass::GrandSummaryLast)); + assert!(!has(2, TableClass::SummaryFirst)); + assert!(has(2, TableClass::GrandSummaryLast)); + } + + #[test] + fn a_lone_summary_row_is_both_first_and_last() { + let frame = df! { + "x" => vec![1.5, 3.5], + } + .unwrap(); + let mut table = Table::new(); + table.summaries = vec![summary_clause("mean", SummaryScope::Grand, &["x"])]; + + let layout = resolve_layout_with_summaries(&frame, &table, None).unwrap(); + + let row = layout.rows.len() - 1; + assert!(layout + .cells + .iter() + .filter(|cell| cell.top == row) + .all(|cell| cell.classes.contains(&TableClass::GrandSummaryFirst) + && cell.classes.contains(&TableClass::SummaryLast))); + } + + #[test] + fn group_summary_weaves_after_its_groups_heading_rows() { + let frame = df! { + "region" => vec!["n".to_string(), "n".to_string(), "s".to_string()], + "x" => vec![1.5, 3.5, 10.5], + } + .unwrap(); + let mut table = Table::new(); + table.summaries = vec![summary_clause("mean", SummaryScope::Group, &["x"])]; + let facet = top_facet(&["region"]); + + let layout = resolve_layout_with_summaries(&frame, &table, Some(&facet)).unwrap(); + + // Col labels; heading n; 2 data; summary; heading s; data; summary. + let summary_rows = rows_with_class(&layout, TableClass::SummaryRow); + assert_eq!(summary_rows, vec![4, 7]); + assert_eq!(layout.rows[summary_rows[0]].group, vec![0]); + assert_eq!(layout.rows[summary_rows[1]].group, vec![1]); + assert_eq!( + find_cell(&layout, 4, "2.5").kind, + TableCellKind::SummaryValue + ); + assert_eq!( + find_cell(&layout, 7, "10.5").kind, + TableCellKind::SummaryValue + ); + } + + #[test] + fn group_stub_cells_grow_over_a_groups_summary_rows() { + let frame = df! { + "region" => vec!["n".to_string(), "n".to_string(), "s".to_string()], + "x" => vec![1.5, 3.5, 10.5], + } + .unwrap(); + let mut table = Table::new(); + table.summaries = vec![ + summary_clause("mean", SummaryScope::Group, &["x"]), + summary_clause("mean", SummaryScope::Grand, &["x"]), + ]; + let facet = left_facet(&["region"]); + + let layout = resolve_layout_with_summaries(&frame, &table, Some(&facet)).unwrap(); + + // Body: 2 data + summary (n), data + summary (s), grand summary. + let summary_rows = rows_with_class(&layout, TableClass::SummaryRow); + assert_eq!(summary_rows, vec![3, 5, 6]); + // The group stub cell for "n" spans its data rows and its summary. + let north = find_cell(&layout, 1, "n"); + assert_eq!(north.kind, TableCellKind::GroupHeading); + assert_eq!(north.bottom, 3); + // A group summary row emits no cell in the group stub column... + assert!(layout + .cells + .iter() + .all(|cell| cell.top != 3 || cell.left != north.left)); + // ...and the grand row's label spans the group stub column instead. + let grand_label = layout + .cells + .iter() + .find(|cell| cell.top == 6 && cell.left == north.left) + .expect("grand row's label spans the group stub column"); + assert_eq!(grand_label.kind, TableCellKind::SummaryLabel); + assert_eq!(grand_label.content, "mean"); + } + + #[test] + fn a_grand_summary_label_spans_the_group_stub_columns() { + let frame = df! { + "region" => vec!["n".to_string(), "s".to_string()], + "x" => vec![1.5, 10.5], + } + .unwrap(); + let mut table = Table::new(); + table.summaries = vec![summary_clause("mean", SummaryScope::Grand, &["x"])]; + let facet = left_facet(&["region"]); + + let layout = resolve_layout_with_summaries(&frame, &table, Some(&facet)).unwrap(); + + let grand_row = rows_with_class(&layout, TableClass::SummaryRow)[0]; + let label = find_cell(&layout, grand_row, "mean"); + assert_eq!(label.kind, TableCellKind::SummaryLabel); + assert_eq!(label.left, 0); + assert!( + label.right > label.left, + "the label colspans the group stub column" + ); + // No group-stub filler cell on the grand row, and no grid gaps. + assert!(layout + .cells + .iter() + .all(|cell| cell.top != grand_row || cell.kind != TableCellKind::GroupHeading)); + layout.slots_by_row(); + } + + #[test] + fn a_summary_label_spans_all_stub_columns() { + let frame = df! { + "a" => vec!["p".to_string(), "q".to_string()], + "b" => vec!["u".to_string(), "v".to_string()], + "x" => vec![1.5, 3.5], + } + .unwrap(); + let stub = |column: &str| crate::Format { + columns: vec![column.to_string()], + wildcard: false, + target: Some(ColumnSection::Stub), + settings: Parameters::new(), + label_spec: Default::default(), + }; + let mut table = Table::new(); + table.formats = vec![stub("a"), stub("b")]; + table.summaries = vec![summary_clause("mean", SummaryScope::Grand, &["x"])]; + + let layout = resolve_layout_with_summaries(&frame, &table, None).unwrap(); + + let summary_row = rows_with_class(&layout, TableClass::SummaryRow)[0]; + let label = find_cell(&layout, summary_row, "mean"); + assert_eq!(label.kind, TableCellKind::SummaryLabel); + assert_eq!(label.left, 0); + assert_eq!(label.right, 1); + // The second stub column emits no cell of its own on the summary row. + assert_eq!( + layout + .cells + .iter() + .filter(|cell| cell.top == summary_row && cell.kind == TableCellKind::SummaryLabel) + .count(), + 1 + ); + assert_eq!(find_cell(&layout, summary_row, "2.5").left, 2); + layout.slots_by_row(); + } + fn column(name: &str, label: &str) -> TableColumn { TableColumn { name: name.to_string(), @@ -446,16 +951,11 @@ mod tests { } fn left_facet(variables: &[&str]) -> Facet { - let mut properties = Parameters::new(); - properties.insert( - "place".to_string(), - ParameterValue::String("left".to_string()), - ); Facet { layout: crate::plot::facet::FacetLayout::Wrap { variables: variables.iter().map(|s| s.to_string()).collect(), }, - properties, + properties: crate::params! { "place" => "left" }, resolved: true, } } diff --git a/src/execute/table/mod.rs b/src/execute/table/mod.rs index 953dc887b..f79821550 100644 --- a/src/execute/table/mod.rs +++ b/src/execute/table/mod.rs @@ -11,10 +11,12 @@ mod facet; mod format; mod layout; mod stub; +mod summary; use facet::collapse_group_columns; -use format::{apply_formats, setup_formats}; +use format::{apply_formatting, setup_formats}; use layout::{build_cells, setup_columns, setup_rows}; +use summary::{compute_summaries, setup_summaries}; use crate::table::extract_table_titles; @@ -35,6 +37,9 @@ use crate::{DataFrame, GgsqlError, Result, SelectionItem, Spec}; /// UPDATE, DELETE) ahead of a TABULATE run here. pub fn resolve_table_with_reader(query: &str, reader: &dyn Reader) -> Result { let validated = validate(query)?; + if let Some(message) = validated.invalid_reason() { + return Err(GgsqlError::ValidationError(message)); + } let warnings: Vec = validated.warnings().to_vec(); let source_tree = SourceTree::new(query)?; @@ -45,7 +50,8 @@ pub fn resolve_table_with_reader(query: &str, reader: &dyn Reader) -> Result Result 'left'` facet keeps its columns as group stubs, so check // for body columns rather than emptiness. @@ -84,12 +91,22 @@ pub fn resolve_table_with_reader(query: &str, reader: &dyn Reader) -> Result panic!("expected a ValidationError, got {e:?}"), } } + + fn reader_with_region_sales() -> DuckDBReader { + let reader = DuckDBReader::from_connection_string("duckdb://memory").unwrap(); + reader + .execute_sql( + "CREATE TABLE t AS SELECT * FROM (VALUES \ + ('north', 'q1', 1), ('north', 'q2', 2), ('south', 'q1', 3)) \ + AS t(region, quarter, sales)", + ) + .unwrap(); + reader + } + + fn summary_row_indices(resolved: &ResolvedTable) -> Vec { + resolved + .rows() + .iter() + .enumerate() + .filter(|(_, row)| row.classes.contains(&TableClass::SummaryRow)) + .map(|(index, _)| index) + .collect() + } + + #[test] + fn test_tabulate_summarise_grand_without_facet_appends_one_row() { + let reader = reader_with_sales(); + let resolved = + resolve_table_with_reader("TABULATE * FROM sales SUMMARISE mean OF id", &reader) + .unwrap(); + + // Header row + 3 body rows + 1 summary row. + assert_eq!(resolved.rows().len(), 5); + // The summary row gets a synthetic stub column for its label. + assert_eq!( + resolved.columns()[0].name, + crate::naming::SUMMARY_LABEL_COLUMN + ); + assert_eq!(resolved.columns()[0].target, crate::ColumnSection::Stub); + + let label = resolved + .cells() + .iter() + .find(|c| c.kind == TableCellKind::SummaryLabel && c.top == 4) + .unwrap(); + assert_eq!(label.content, "mean"); + let value = resolved + .cells() + .iter() + .find(|c| c.kind == TableCellKind::SummaryValue && c.top == 4 && c.left == 1) + .unwrap(); + assert_eq!(value.content, "2"); + // The non-summarised column's cell shows the blank fill, an em dash + // by default. + let blank = resolved + .cells() + .iter() + .find(|c| c.kind == TableCellKind::SummaryValue && c.top == 4 && c.left == 2) + .unwrap(); + assert_eq!(blank.content, "—"); + } + + #[test] + fn test_tabulate_summarise_group_rows_follow_their_group() { + let reader = reader_with_region_sales(); + let resolved = resolve_table_with_reader( + "TABULATE * FROM t FACET region SETTING place => 'top' SUMMARISE mean OF sales", + &reader, + ) + .unwrap(); + + // Header; per group: heading, data rows, summary row. + assert_eq!(summary_row_indices(&resolved), [4, 7]); + + let last = resolved.columns().len() - 1; + let values: Vec<&str> = resolved + .cells() + .iter() + .filter(|c| { + c.kind == TableCellKind::SummaryValue && c.left == last && [4, 7].contains(&c.top) + }) + .map(|c| c.content.as_str()) + .collect(); + assert_eq!(values, ["1.5", "3"]); + } + + #[test] + fn test_tabulate_summarise_place_top_sits_before_the_group_rows() { + let reader = reader_with_region_sales(); + let resolved = resolve_table_with_reader( + "TABULATE * FROM t FACET region SETTING place => 'top' \ + SUMMARISE mean OF sales SETTING place => 'top'", + &reader, + ) + .unwrap(); + + // Header at 0, north's heading at 1, then north's summary row. + assert_eq!(summary_row_indices(&resolved), [2, 6]); + } + + #[test] + fn test_tabulate_summarise_grand_with_facet_uses_all_rows_and_rowlabel() { + let reader = reader_with_region_sales(); + let resolved = resolve_table_with_reader( + "TABULATE * FROM t FACET region SETTING place => 'top' \ + SUMMARISE GRAND mean OF sales SETTING rowlabel => 'Average'", + &reader, + ) + .unwrap(); + + let summary_row = summary_row_indices(&resolved); + // One grand row, after every body row. + assert_eq!(summary_row, [resolved.rows().len() - 1]); + + let label = resolved + .cells() + .iter() + .find(|c| c.kind == TableCellKind::SummaryLabel && c.top == summary_row[0]) + .unwrap(); + assert_eq!(label.content, "Average"); + let value = resolved + .cells() + .iter() + .find(|c| { + c.kind == TableCellKind::SummaryValue + && c.top == summary_row[0] + && resolved.columns()[c.left].name == "sales" + }) + .unwrap(); + assert_eq!(value.content, "2"); + } + + #[test] + fn test_tabulate_summarise_template_renders_stats_and_strips_the_default_label() { + let reader = reader_with_sales(); + let resolved = resolve_table_with_reader( + "TABULATE * FROM sales SUMMARISE '{mean} +/- {sdev:num %.2f}' OF id", + &reader, + ) + .unwrap(); + + let label = resolved + .cells() + .iter() + .find(|c| c.kind == TableCellKind::SummaryLabel) + .unwrap(); + assert_eq!(label.content, "mean +/- sdev"); + let value = resolved + .cells() + .iter() + .find(|c| c.kind == TableCellKind::SummaryValue && c.left == label.right + 1) + .unwrap(); + assert_eq!(value.content, "2 +/- 0.82"); + } + + #[test] + fn test_tabulate_summarise_template_evaluates_placeholder_arithmetic() { + let reader = reader_with_sales(); + let resolved = resolve_table_with_reader( + "TABULATE * FROM sales SUMMARISE '{mean-sdev:%.2f} - {mean+sdev:%.2f}' OF id", + &reader, + ) + .unwrap(); + + let label = resolved + .cells() + .iter() + .find(|c| c.kind == TableCellKind::SummaryLabel) + .unwrap(); + assert_eq!(label.content, "mean - sdev - mean + sdev"); + let value = resolved + .cells() + .iter() + .find(|c| c.kind == TableCellKind::SummaryValue && c.left == label.right + 1) + .unwrap(); + assert_eq!(value.content, "1.18 - 2.82"); + } + + #[test] + fn test_tabulate_summarise_template_expands_the_printf_sugar() { + let reader = reader_with_sales(); + let resolved = resolve_table_with_reader( + "TABULATE * FROM sales SUMMARISE '{sdev:%.2f}' OF id", + &reader, + ) + .unwrap(); + + let value = resolved + .cells() + .iter() + .find(|c| c.kind == TableCellKind::SummaryValue) + .unwrap(); + assert_eq!(value.content, "0.82"); + } + + #[test] + fn test_tabulate_summarise_template_ignores_the_column_format() { + let reader = reader_with_sales(); + let resolved = resolve_table_with_reader( + "TABULATE * FROM sales FORMAT id LABEL * => '[{}]' SUMMARISE '{mean}' OF id", + &reader, + ) + .unwrap(); + + // Templates self-format; a naked operation would take the label + // and render "[2]". + let value = resolved + .cells() + .iter() + .find(|c| c.kind == TableCellKind::SummaryValue) + .unwrap(); + assert_eq!(value.content, "2"); + } + + #[test] + fn test_tabulate_summarise_template_null_is_targetable_by_a_direct_label() { + let reader = DuckDBReader::from_connection_string("duckdb://memory").unwrap(); + reader + .execute_sql("CREATE TABLE t AS SELECT * FROM (VALUES (1.0), (NULL)) AS t(x)") + .unwrap(); + let resolved = resolve_table_with_reader( + "TABULATE * FROM t SUMMARISE '{mean} of {count}' OF x FORMAT x LABEL null => ''", + &reader, + ) + .unwrap(); + + let value = resolved + .cells() + .iter() + .find(|c| c.kind == TableCellKind::SummaryValue) + .unwrap(); + assert_eq!(value.content, ""); + } + + #[test] + fn test_tabulate_summarise_template_ignores_a_wildcard_label() { + let reader = DuckDBReader::from_connection_string("duckdb://memory").unwrap(); + reader + .execute_sql("CREATE TABLE t AS SELECT * FROM (VALUES (1.0), (2.0)) AS t(x)") + .unwrap(); + let resolved = resolve_table_with_reader( + "TABULATE * FROM t SUMMARISE '{mean} of {count}' OF x FORMAT x LABEL * => '{:num %.2f}'", + &reader, + ) + .unwrap(); + + let value = resolved + .cells() + .iter() + .find(|c| c.kind == TableCellKind::SummaryValue) + .unwrap(); + assert_eq!(value.content, "1.5 of 2"); + } + + #[test] + fn test_tabulate_summarise_template_nulls_the_whole_cell_on_a_null_stat() { + let reader = DuckDBReader::from_connection_string("duckdb://memory").unwrap(); + reader + .execute_sql("CREATE TABLE t AS SELECT * FROM (VALUES (1.0), (NULL)) AS t(x)") + .unwrap(); + let resolved = resolve_table_with_reader( + "TABULATE * FROM t SUMMARISE '{mean} of {count}' OF x", + &reader, + ) + .unwrap(); + + let value = resolved + .cells() + .iter() + .find(|c| c.kind == TableCellKind::SummaryValue) + .unwrap(); + assert_eq!(value.content, "null"); + } + + #[test] + fn test_tabulate_summarise_fills_unsummarised_cells_with_the_blank_default() { + let reader = DuckDBReader::from_connection_string("duckdb://memory").unwrap(); + reader + .execute_sql( + "CREATE TABLE t AS SELECT * FROM (VALUES (1.0, 'a'), (2.0, 'b')) AS t(x, y)", + ) + .unwrap(); + let resolved = + resolve_table_with_reader("TABULATE * FROM t SUMMARISE mean OF x", &reader).unwrap(); + + let contents: Vec<&str> = resolved + .cells() + .iter() + .filter(|c| c.kind == TableCellKind::SummaryValue) + .map(|c| c.content.as_str()) + .collect(); + assert_eq!(contents, ["1.5", "—"]); + } + + #[test] + fn test_tabulate_summarise_blank_setting_customises_the_fill() { + let reader = DuckDBReader::from_connection_string("duckdb://memory").unwrap(); + reader + .execute_sql( + "CREATE TABLE t AS SELECT * FROM (VALUES (1.0, 'a'), (2.0, 'b')) AS t(x, y)", + ) + .unwrap(); + let resolved = resolve_table_with_reader( + "TABULATE * FROM t SUMMARISE mean OF x SETTING blank => 'N/A'", + &reader, + ) + .unwrap(); + + let contents: Vec<&str> = resolved + .cells() + .iter() + .filter(|c| c.kind == TableCellKind::SummaryValue) + .map(|c| c.content.as_str()) + .collect(); + assert_eq!(contents, ["1.5", "N/A"]); + } + + #[test] + fn test_tabulate_summarise_null_value_reports_null_not_the_blank_fill() { + let reader = DuckDBReader::from_connection_string("duckdb://memory").unwrap(); + reader + .execute_sql("CREATE TABLE t AS SELECT * FROM (VALUES (1.0), (NULL)) AS t(x)") + .unwrap(); + let resolved = + resolve_table_with_reader("TABULATE * FROM t SUMMARISE mean OF x", &reader).unwrap(); + + let value = resolved + .cells() + .iter() + .find(|c| c.kind == TableCellKind::SummaryValue) + .unwrap(); + assert_eq!(value.content, "null"); + } + + #[test] + fn test_tabulate_summarise_errors_on_an_empty_table() { + let reader = DuckDBReader::from_connection_string("duckdb://memory").unwrap(); + reader + .execute_sql("CREATE TABLE t AS SELECT CAST(1 AS DOUBLE) AS x WHERE 1 = 0") + .unwrap(); + let result = + resolve_table_with_reader("TABULATE * FROM t SUMMARISE GRAND count OF x", &reader); + let Err(error) = result else { + panic!("SUMMARISE must error on an empty table"); + }; + assert!(error + .to_string() + .contains("cannot summarise an empty table")); + } + + fn body_contents(resolved: &ResolvedTable) -> Vec { + let mut contents: Vec = resolved + .cells() + .iter() + .filter(|c| c.kind == TableCellKind::Body) + .map(|c| c.content.clone()) + .collect(); + contents.sort(); + contents + } + + fn resolve_doubles(query: &str, values: &str) -> ResolvedTable { + let reader = DuckDBReader::from_connection_string("duckdb://memory").unwrap(); + reader + .execute_sql(&format!( + "CREATE TABLE t AS SELECT CAST(v AS DOUBLE) AS x FROM (VALUES {values}) AS t(v)" + )) + .unwrap(); + resolve_table_with_reader(query, &reader).unwrap() + } + + #[test] + fn test_tabulate_float_column_pads_to_a_shared_precision() { + let resolved = resolve_doubles("TABULATE * FROM t", "(39.1), (37.7), (50.0)"); + assert_eq!(body_contents(&resolved), ["37.7", "39.1", "50.0"]); + } + + #[test] + fn test_tabulate_float_precision_ignores_binary_noise() { + let resolved = resolve_doubles("TABULATE * FROM t", "(0.1 + 0.2), (1.5)"); + assert_eq!(body_contents(&resolved), ["0.3", "1.5"]); + } + + #[test] + fn test_tabulate_float_precision_keeps_real_decimals() { + let resolved = resolve_doubles("TABULATE * FROM t", "(1.25), (3.75)"); + assert_eq!(body_contents(&resolved), ["1.25", "3.75"]); + } + + #[test] + fn test_tabulate_format_label_overrides_inferred_precision() { + let resolved = resolve_doubles( + "TABULATE * FROM t FORMAT x LABEL * => '{:num %.3f}'", + "(1.5), (2.0)", + ); + assert_eq!(body_contents(&resolved), ["1.500", "2.000"]); + } + + #[test] + fn test_tabulate_summarise_matches_the_column_precision() { + let resolved = resolve_doubles( + "TABULATE * FROM t SUMMARISE mean OF x", + "(39.1), (37.7), (50.0)", + ); + let value = resolved + .cells() + .iter() + .find(|c| c.kind == TableCellKind::SummaryValue) + .unwrap(); + assert_eq!(value.content, "42.3"); + } + + #[test] + fn test_tabulate_summarise_pads_an_exactly_whole_mean() { + let resolved = resolve_doubles("TABULATE * FROM t SUMMARISE mean OF x", "(41.5), (42.5)"); + let value = resolved + .cells() + .iter() + .find(|c| c.kind == TableCellKind::SummaryValue) + .unwrap(); + assert_eq!(value.content, "42.0"); + } + + #[test] + fn test_tabulate_summarise_count_keeps_integer_display() { + let resolved = resolve_doubles( + "TABULATE * FROM t SUMMARISE count OF x", + "(39.1), (37.7), (50.0)", + ); + let value = resolved + .cells() + .iter() + .find(|c| c.kind == TableCellKind::SummaryValue) + .unwrap(); + assert_eq!(value.content, "3"); + } + + #[test] + fn test_tabulate_summarise_separated_facet_rekeys_the_summary_chunks() { + let reader = reader_with_region_sales(); + let resolved = resolve_table_with_reader( + "TABULATE * FROM t FACET region, quarter SETTING place => 'top', separator => ' - ' \ + SUMMARISE mean OF sales", + &reader, + ) + .unwrap(); + + // Header; per collapsed group (north-q1, north-q2, south-q1): + // heading, data row, summary row. + let summary_rows = summary_row_indices(&resolved); + assert_eq!(summary_rows, [3, 6, 9]); + + let last = resolved.columns().len() - 1; + let values: Vec<&str> = resolved + .cells() + .iter() + .filter(|c| { + c.kind == TableCellKind::SummaryValue + && c.left == last + && summary_rows.contains(&c.top) + }) + .map(|c| c.content.as_str()) + .collect(); + assert_eq!(values, ["1", "2", "3"]); + } + + #[test] + fn test_tabulate_summarise_rejects_a_non_numeric_column_for_numeric_ops() { + let reader = reader_with_sales(); + match resolve_table_with_reader("TABULATE * FROM sales SUMMARISE mean OF name", &reader) { + Ok(_) => panic!("expected mean OF a text column to error"), + Err(GgsqlError::ValidationError(msg)) => assert!(msg.contains("numeric")), + Err(e) => panic!("expected a ValidationError, got {e:?}"), + } + } + + #[test] + fn test_tabulate_summarise_rejects_a_column_outside_the_selection() { + let reader = reader_with_sales(); + match resolve_table_with_reader("TABULATE id FROM sales SUMMARISE mean OF name", &reader) { + Ok(_) => panic!("expected a non-selection column to error"), + Err(GgsqlError::ValidationError(msg)) => { + assert!(msg.contains("no column 'name'")) + } + Err(e) => panic!("expected a ValidationError, got {e:?}"), + } + } + + #[test] + fn test_tabulate_summarise_skips_the_null_group_under_missing_drop() { + let reader = DuckDBReader::from_connection_string("duckdb://memory").unwrap(); + reader + .execute_sql( + "CREATE TABLE t AS SELECT * FROM (VALUES ('a', 1), (NULL, 2), ('b', 3)) \ + AS t(name, sales)", + ) + .unwrap(); + + let resolved = resolve_table_with_reader( + "TABULATE * FROM t FACET name SETTING place => 'top', missing => 'drop' \ + SUMMARISE mean OF sales", + &reader, + ) + .unwrap(); + + // Header + per surviving group (heading, data row, summary row). + assert_eq!(resolved.rows().len(), 7); + assert_eq!(summary_row_indices(&resolved).len(), 2); + } + + #[test] + fn test_tabulate_summarise_clauses_stay_in_clause_order() { + let reader = reader_with_region_sales(); + let resolved = resolve_table_with_reader( + "TABULATE * FROM t SUMMARISE mean OF sales SUMMARISE median OF sales", + &reader, + ) + .unwrap(); + + let labels: Vec<(usize, &str)> = resolved + .cells() + .iter() + .filter(|c| c.kind == TableCellKind::SummaryLabel && !c.content.is_empty()) + .map(|c| (c.top, c.content.as_str())) + .collect(); + // Anti-alphabetical: clause order, not any other ordering, decides. + assert_eq!(labels, [(4, "mean"), (5, "median")]); + } } diff --git a/src/execute/table/summary.rs b/src/execute/table/summary.rs new file mode 100644 index 000000000..765a0eb94 --- /dev/null +++ b/src/execute/table/summary.rs @@ -0,0 +1,1457 @@ +//! `SUMMARISE` execution: `setup_summaries` validates the clauses against the +//! data, resolves their settings and prepares the frame for summary rows, +//! `compute_summaries` runs the aggregate operations on it. +//! +//! Most of `SUMMARY_OPERATIONS` are folds over a column's numeric values. +//! The tallies `count`, `n_distinct` and `n_missing` are type-free, and +//! date/timestamp columns accept the order statistics (returning a temporal +//! value) and the spread statistics (returning a duration). + +use std::collections::{HashMap, HashSet}; +use std::ops::Range; +use std::sync::Arc; + +use arrow::array::{ + Array, ArrayRef, Date32Array, Date64Array, Float64Array, StringArray, + TimestampMicrosecondArray, TimestampMillisecondArray, TimestampNanosecondArray, + TimestampSecondArray, +}; +use arrow::datatypes::{DataType, TimeUnit}; +use zygos::Value; + +use crate::array_util::{as_f64, cast_array, column_to_strings, value_to_string}; +use crate::naming; +use crate::params::ParameterValue; +use crate::table::{ + parse_template, BinOp, Format, StatExpr, Summary, SummaryOperation, SummaryScope, TableCell, + TableClass, TableColumn, TableRow, TemplateSegment, +}; +use crate::{ColumnSection, DataFrame, GgsqlError, Result}; + +/// Validate `summaries` against the data, resolve each clause's settings and +/// prepare the frame for summary rows; returns the resolved clauses. +/// Every summarised column must exist. Summary row labels need a stub +/// column to live in, so a table with summaries but no `STUB` column gets a +/// synthetic, empty one ([`naming::SUMMARY_LABEL_COLUMN`]). +pub(super) fn setup_summaries( + df: &mut DataFrame, + formats: &HashMap, + summaries: &[Summary], +) -> Result> { + if summaries.is_empty() { + return Ok(Vec::new()); + } + let mut resolved = Vec::with_capacity(summaries.len()); + let column_names = df.get_column_names(); + for summary in summaries { + summary + .validate_columns(&column_names) + .map_err(GgsqlError::ValidationError)?; + resolved.push(Summary { + settings: summary + .resolve_settings() + .map_err(GgsqlError::ValidationError)?, + ..summary.clone() + }); + } + if !formats + .values() + .any(|f| f.target == Some(ColumnSection::Stub)) + { + *df = df.with_column( + naming::SUMMARY_LABEL_COLUMN, + Arc::new(StringArray::from(vec![""; df.height()])), + )?; + } + Ok(resolved) +} + +/// One `SUMMARISE` row, ready for weaving into the table's grid: placement, +/// label and values all resolved. The weavers never see the `Summary` +/// clause itself. +#[derive(Debug)] +pub(super) struct SummaryRow { + /// Whether the row summarises its group (`GROUP`) or the whole table + /// (`GRAND`). + pub scope: SummaryScope, + /// Whether the row sits above (`true`) or below its group's rows. + pub top: bool, + /// The row's stub label: `rowlabel`, else the operation name. + pub label: String, + /// Display text for a body cell in a column the clause did not + /// summarise: the `blank` setting, em dash by default. + pub blank: String, + /// One-row frame of the computed values; its schema names the + /// summarised columns. Numeric for a bare operation — the column's + /// temporal type for a date-valued statistic on a date/timestamp + /// column — string for a template. A `FORMAT` `LABEL` may stringify + /// any of these. + pub frame: DataFrame, +} + +impl SummaryRow { + /// This row's cells at grid row `row`: the label spanning the stub + /// columns, then the computed values in their body columns. No cells in + /// group-stub columns: a `GROUP` row's are covered by the merged stub + /// cell; a `GRAND` row owns them by extending its label's colspan + /// leftward. `first`/`last` mark the row's position in its block (both + /// when the block is one row) and `above` whether the block sits above + /// the rows it summarizes; together they pick the positional style + /// classes. + pub(super) fn cells( + &self, + row: usize, + columns: &[TableColumn], + first: bool, + last: bool, + above: bool, + ) -> Vec { + // Every cell in the row carries the same classes: the scope's base + // class plus the block's positional markers. A group block gets the + // solid border on both outer edges; a grand block gets it on its + // far edge and the double border on the edge touching the body. + let (base, first_class, last_class) = match (self.scope, above) { + (SummaryScope::Group, _) => ( + TableClass::GroupSummary, + TableClass::SummaryFirst, + TableClass::SummaryLast, + ), + (SummaryScope::Grand, true) => ( + TableClass::GrandSummary, + TableClass::SummaryFirst, + TableClass::GrandSummaryLast, + ), + (SummaryScope::Grand, false) => ( + TableClass::GrandSummary, + TableClass::GrandSummaryFirst, + TableClass::SummaryLast, + ), + }; + let mut classes = vec![base]; + if first { + classes.push(first_class); + } + if last { + classes.push(last_class); + } + + let mut cells = vec![self.label_cell(row, columns, &classes)]; + cells.extend( + columns + .iter() + .enumerate() + .filter(|(_, column)| column.target == ColumnSection::Body) + .map(|(index, column)| { + let content = self + .frame + .column(&column.name) + .map(|array| column_to_strings(array).remove(0)) + .unwrap_or_else(|_| self.blank.clone()); + let mut cell = TableCell::new_summary_value(row, index, content) + .with_properties(column.properties.clone()); + cell.classes.extend_from_slice(&classes); + cell + }), + ); + cells + } + + /// The row's label cell, spanning every stub column — leftward over the + /// group-stub columns too for a `GRAND` row. + fn label_cell(&self, row: usize, columns: &[TableColumn], classes: &[TableClass]) -> TableCell { + let label_column = columns + .iter() + .position(|c| c.target == ColumnSection::Stub) + .expect("setup_summaries guarantees a stub column"); + let span_group_stubs = self.scope == SummaryScope::Grand; + let left = if span_group_stubs && columns.first().is_some_and(|c| c.is_group_stub()) { + 0 + } else { + label_column + }; + let right = columns + .iter() + .rposition(|c| c.target == ColumnSection::Stub) + .unwrap_or(label_column); + debug_assert!( + columns[left..=right].iter().all(|c| c.is_stub()), + "the label's colspan covers only stub columns" + ); + + let mut cell = TableCell::new_summary_label(row, label_column, self.label.clone()); + cell.left = left; + cell.right = right; + cell.classes.extend_from_slice(classes); + cell.with_properties(columns[label_column].properties.clone()) + } +} + +/// One chunk of summary rows: the chunk's group key (`None` for the `GRAND` +/// chunk) and the clause rows computed over it, in clause order. +pub(super) type SummaryChunk = (Option>, Vec); + +/// Compute every `SUMMARISE` clause against the (unformatted) data: one +/// chunk per group, in display order (`setup_rows` leaves rows +/// group-contiguous), then one `None`-keyed `GRAND` chunk over all rows. +/// The clauses arrive with settings resolved by [`setup_summaries`]. +/// An empty table errors: there is nothing to summarise. Chunks with no +/// matching clauses are omitted. Placement within a chunk is the weavers' +/// concern; they read each row's `top`. +/// +/// A bare operation's summary value takes its column's `FORMAT` `LABEL` +/// just like the body cells; a template self-formats via zygos, honouring +/// only direct labels from the column's `FORMAT`. +pub(super) fn compute_summaries( + df: &DataFrame, + rows: &[TableRow], + summaries: &[Summary], + formats: &HashMap, +) -> Result> { + if summaries.is_empty() { + return Ok(Vec::new()); + } + if rows.is_empty() { + return Err(GgsqlError::ValidationError( + "SUMMARISE: cannot summarise an empty table".to_string(), + )); + } + // Chunks the clauses emit into: one contiguous range per group, then one + // range over all rows for the GRAND clauses. Each accumulates its rows. + struct Chunk { + key: Option>, + range: Range, + rows: Vec, + } + let mut chunks: Vec = Vec::new(); + let mut start = 0; + for chunk in rows.chunk_by(|a, b| a.group == b.group) { + chunks.push(Chunk { + key: Some(chunk[0].group.clone()), + range: start..start + chunk.len(), + rows: Vec::new(), + }); + start += chunk.len(); + } + chunks.push(Chunk { + key: None, + range: 0..rows.len(), + rows: Vec::new(), + }); + + // Display decimals for every summarised column, computed once and + // shared by every clause and chunk. + let columns: HashSet<&str> = summaries + .iter() + .flat_map(|summary| summary.columns.iter().map(String::as_str)) + .collect(); + let decimals: HashMap<&str, usize> = columns + .into_iter() + .filter_map(|column| { + let d = crate::format::display_decimals(df.column(column).ok()?); + (d > 0).then_some((column, d)) + }) + .collect(); + + // Clause-outer: the label, placement and parsed template are clause-level + // facts, computed once and shared by every group's row. + for summary in summaries { + let template = match &summary.operation { + SummaryOperation::Template(template) => { + Some(parse_template(template).map_err(GgsqlError::ValidationError)?) + } + SummaryOperation::Stat(_) => None, + }; + let label = summary + .settings + .get("rowlabel") + .and_then(ParameterValue::as_str) + .map_or_else(|| summary.operation.as_label(), str::to_string); + let top = ParameterValue::is_str(summary.settings.get("place"), "top"); + let blank = summary + .settings + .get("blank") + .and_then(ParameterValue::as_str) + .expect("setup_summaries resolves every clause's settings"); + let targets = match summary.scope { + SummaryScope::Group => 0..chunks.len() - 1, + SummaryScope::Grand => chunks.len() - 1..chunks.len(), + }; + for index in targets { + let chunk = &mut chunks[index]; + let mut frame = summary_frame(df, summary, template.as_deref(), &chunk.range)?; + // The frame is made display-ready here (labels, display + // decimals); a template's cells take direct labels only. + format_summary_frame(&mut frame, summary, formats, &decimals)?; + chunk.rows.push(SummaryRow { + scope: summary.scope, + top, + label: label.clone(), + blank: blank.to_string(), + frame, + }); + } + } + Ok(chunks + .into_iter() + .filter_map(|chunk| (!chunk.rows.is_empty()).then_some((chunk.key, chunk.rows))) + .collect()) +} + +/// Compute one clause's frame over the rows in `range`: one row, one column +/// per summarised column. A bare operation yields a one-cell column of the +/// operation's value (see [`value_array`]); a template yields a string +/// column with the template rendered against the slice. +fn summary_frame( + df: &DataFrame, + summary: &Summary, + template: Option<&[TemplateSegment]>, + range: &Range, +) -> Result { + let drop_nulls = ParameterValue::is_str(summary.settings.get("missing"), "drop"); + + let columns = summary + .columns + .iter() + .map(|column| { + // setup_summaries' validate_columns guarantees presence; this + // guards direct callers. + let array = df.column(column).map_err(|_| { + GgsqlError::ValidationError(format!( + "SUMMARISE {}: no column '{column}' in the query result", + summary.operation + )) + })?; + let slice = array.slice(range.start, range.len()); + let cell: ArrayRef = match template { + Some(segments) => Arc::new(StringArray::from(vec![render_template( + segments, &slice, drop_nulls, + )?])), + None => { + let SummaryOperation::Stat(name) = &summary.operation else { + unreachable!("compute_summaries parses every template clause") + }; + value_array(&summary_stat(name, &slice, drop_nulls)?, slice.data_type()) + } + }; + Ok((column.clone(), cell)) + }) + .collect::>>()?; + DataFrame::new(columns) +} + +/// Render a template against one column's slice: literals verbatim, each +/// placeholder's expression evaluated over the slice and rendered through its +/// pre-compiled zygos template. A NULL placeholder makes the whole cell +/// NULL. Stats are memoized in `cache` across the template's placeholders, +/// so a repeated stat computes once per cell. +fn render_template( + segments: &[TemplateSegment], + slice: &ArrayRef, + drop_nulls: bool, +) -> Result> { + let mut cache = HashMap::new(); + let mut text = String::new(); + for segment in segments { + match segment { + TemplateSegment::Literal(literal) => text.push_str(literal), + TemplateSegment::Stat { expr, template } => { + let Some(value) = eval_stat_expr(expr, slice, drop_nulls, &mut cache)? else { + return Ok(None); + }; + // format() returns None only for Value::Null, excluded above + text.push_str(&template.format(&value, None).expect("value is non-null")) + } + } + } + Ok(Some(text)) +} + +/// Evaluate a template placeholder's expression over one column's slice: +/// stat leaves via `summary_stat` keep their type, so a date-valued leaf +/// renders through zygos's temporal formatting; any arithmetic projects the +/// operands to plain numbers via [`leaf_f64`]. A NULL leaf makes the whole +/// expression NULL. +fn eval_stat_expr( + expr: &StatExpr, + slice: &ArrayRef, + drop_nulls: bool, + cache: &mut HashMap>, +) -> Result> { + match expr { + StatExpr::Stat(name) => { + let key = name.to_ascii_lowercase(); + if let Some(value) = cache.get(&key) { + return Ok(value.clone()); + } + let value = summary_stat(name, slice, drop_nulls)?; + cache.insert(key, value.clone()); + Ok(value) + } + StatExpr::Number(n) => Ok(Some(Value::Number(*n))), + StatExpr::Neg(inner) => Ok(eval_stat_expr(inner, slice, drop_nulls, cache)? + .and_then(|v| leaf_f64(&v)) + .map(|v| Value::Number(-v))), + StatExpr::Binary(op, lhs, rhs) => { + let (Some(lhs), Some(rhs)) = ( + eval_stat_expr(lhs, slice, drop_nulls, cache)?, + eval_stat_expr(rhs, slice, drop_nulls, cache)?, + ) else { + return Ok(None); + }; + let (Some(lhs), Some(rhs)) = (leaf_f64(&lhs), leaf_f64(&rhs)) else { + return Ok(None); + }; + Ok(Some(Value::Number(match op { + BinOp::Add => lhs + rhs, + BinOp::Sub => lhs - rhs, + BinOp::Mul => lhs * rhs, + BinOp::Div => lhs / rhs, + }))) + } + } +} + +/// Project a stat leaf to a plain number for arithmetic: days for dates, +/// seconds for datetimes, itself for numbers. +fn leaf_f64(value: &Value) -> Option { + match value { + Value::Number(n) => Some(*n), + Value::Date(days) => Some(*days as f64), + Value::DateTime(us) => Some(*us as f64 / 1e6), + _ => None, + } +} + +/// Make a summary frame display-ready, per column: an explicit `FORMAT` +/// `LABEL` (mapping or template) becomes the display text; an un-labelled +/// float column pads to its body column's display decimals. A template's +/// cells are already-rendered strings, so they honour only direct labels +/// (including `null`), never the wildcard template, and never pad. +/// `decimals` covers every summarised column. +fn format_summary_frame( + frame: &mut DataFrame, + summary: &Summary, + formats: &HashMap, + decimals: &HashMap<&str, usize>, +) -> Result<()> { + let template = matches!(summary.operation, SummaryOperation::Template(_)); + // Tallies pad to no decimals: they are counts and keep their integer + // display. + let tally = match &summary.operation { + SummaryOperation::Stat(operation) => matches!( + operation.to_ascii_lowercase().as_str(), + "count" | "n_distinct" | "n_missing" + ), + SummaryOperation::Template(_) => false, + }; + for column in &summary.columns { + let label_spec = + formats + .get(column) + .map(|format| &format.label_spec) + .filter(|label_spec| { + !label_spec.rename_is_empty() || (!template && label_spec.template().is_some()) + }); + let array = frame.column(column)?.clone(); + let text = if let Some(label_spec) = label_spec { + let mut resolved = if template { + crate::format::resolve_column_values_direct(&array, label_spec) + } else { + crate::format::resolve_column_values(&array, label_spec) + } + .map_err(GgsqlError::ValidationError)?; + resolved + .remove(0) + .unwrap_or_else(|| value_to_string(&array, 0)) + } else { + if template || tally { + continue; + } + let Some(&d) = decimals.get(column.as_str()) else { + continue; + }; + let Ok(floats) = crate::array_util::as_f64(&array) else { + continue; + }; + if array.is_null(0) { + continue; + } + format!("{:.1$}", floats.value(0), d) + }; + *frame = frame.with_column(column, Arc::new(StringArray::from(vec![text])) as ArrayRef)?; + } + Ok(()) +} + +/// Compute one `SUMMARISE` operation over a column. With `drop_nulls`, nulls +/// are ignored; otherwise a single null makes the result `None` (NULL), as +/// does an empty input. Matching on `operation` is case-insensitive. +/// +/// Numeric columns yield [`Value::Number`]. Date/timestamp columns accept +/// the order statistics, which yield the column's own kind of temporal +/// value, and the spread statistics, which yield a duration as a number of +/// days (dates) or seconds (timestamps); the other folds reject them. +pub fn summary_stat(operation: &str, array: &ArrayRef, drop_nulls: bool) -> Result> { + // The type-free tallies bypass the numeric fold: `count` counts rows or + // non-null values, `n_missing` measures nulls so never goes NULL itself. + let op = operation.to_ascii_lowercase(); + match op.as_str() { + "count" => { + let count = if drop_nulls { + array.len() - array.logical_null_count() + } else { + array.len() + }; + return Ok(Some(Value::Number(count as f64))); + } + "n_missing" => return Ok(Some(Value::Number(array.logical_null_count() as f64))), + "n_distinct" => return Ok(n_distinct(array, drop_nulls)?.map(Value::Number)), + _ => {} + } + let Some(kind) = ValueKind::of(array.data_type()) else { + return Err(GgsqlError::ValidationError(format!( + "SUMMARISE {operation} requires a numeric, date or timestamp column, not {}", + array.data_type() + ))); + }; + kind.summary_stat(&op, array, drop_nulls) +} + +/// Fold one statistic over already-extracted values. +fn fold_stat(operation: &str, values: Vec) -> Result { + let v = &values; + let n = v.len() as f64; + let result = match operation { + "sum" => v.iter().sum(), + "prod" => v.iter().product(), + "min" => min(v), + "max" => max(v), + "range" => max(v) - min(v), + "mid" => (min(v) + max(v)) / 2.0, + "mean" => v.iter().sum::() / n, + "geomean" => (v.iter().map(|x| x.ln()).sum::() / n).exp(), + "harmean" => n / v.iter().map(|x| 1.0 / x).sum::(), + "rms" => (v.iter().map(|x| x * x).sum::() / n).sqrt(), + "sdev" => variance(v).sqrt(), + "se" => variance(v).sqrt() / n.sqrt(), + "var" => variance(v), + "iqr" => quantile(values.clone(), 0.75) - quantile(values.clone(), 0.25), + "median" | "p50" => quantile(values.clone(), 0.5), + "p05" => quantile(values.clone(), 0.05), + "p10" => quantile(values.clone(), 0.10), + "p25" => quantile(values.clone(), 0.25), + "p75" => quantile(values.clone(), 0.75), + "p90" => quantile(values.clone(), 0.90), + "p95" => quantile(values.clone(), 0.95), + _ => { + return Err(GgsqlError::InternalError(format!( + "SUMMARISE operation '{operation}' is not implemented" + ))) + } + }; + Ok(result) +} + +/// The flavour of column a fold operates on, fixing the unit its statistics +/// are computed in and how the result is wrapped. +enum ValueKind { + /// Any numeric type; statistics computed and reported as-is. + Numeric, + /// Date32/Date64; statistics computed and durations reported in days. + Date, + /// Any timestamp; statistics computed in µs, durations reported in + /// seconds. + DateTime, +} + +impl ValueKind { + fn of(dtype: &DataType) -> Option { + match dtype { + _ if dtype.is_numeric() => Some(Self::Numeric), + DataType::Date32 | DataType::Date64 => Some(Self::Date), + DataType::Timestamp(_, _) => Some(Self::DateTime), + _ => None, + } + } + + fn summary_stat( + &self, + operation: &str, + array: &ArrayRef, + drop_nulls: bool, + ) -> Result> { + // Temporal columns accept the order statistics, which return a + // value of the column's own kind, and the spread statistics, which + // return a duration. + let date_valued = matches!( + operation, + "min" + | "max" + | "mid" + | "mean" + | "median" + | "p05" + | "p10" + | "p25" + | "p50" + | "p75" + | "p90" + | "p95" + ); + let duration = matches!(operation, "range" | "sdev" | "se" | "iqr"); + if !matches!(self, Self::Numeric) && !date_valued && !duration { + return Err(GgsqlError::ValidationError(format!( + "SUMMARISE {operation} does not support {}", + array.data_type() + ))); + } + let Some(values) = self.values(array, drop_nulls)? else { + return Ok(None); + }; + let result = fold_stat(operation, values)?; + Ok(Some(match self { + Self::Numeric => Value::Number(result), + kind if date_valued => kind.typed(result), + kind => Value::Number(kind.duration(result)), + })) + } + + /// Extract the column's values in the kind's compute unit (unchanged + /// for numbers, days for dates, µs for timestamps). Returns `None` when + /// the result should be NULL: the input is empty, all-null, or holds + /// nulls without `drop_nulls`. + fn values(&self, array: &ArrayRef, drop_nulls: bool) -> Result>> { + let scale = match array.data_type() { + DataType::Date32 => 1.0, + DataType::Date64 => 1.0 / 86_400_000.0, + DataType::Timestamp(unit, _) => match unit { + TimeUnit::Second => 1e6, + TimeUnit::Millisecond => 1e3, + TimeUnit::Microsecond => 1.0, + TimeUnit::Nanosecond => 1e-3, + }, + _ => 1.0, + }; + // Timestamps don't cast to Float64 directly; going through Int64 + // first is lossless for every accepted dtype. + let f64s: ArrayRef = if array.data_type() == &DataType::Float64 { + array.clone() + } else if matches!(self, Self::Numeric) { + cast_array(array, &DataType::Float64)? + } else { + cast_array(&cast_array(array, &DataType::Int64)?, &DataType::Float64)? + }; + let array = as_f64(&f64s)?; + if array.is_empty() || (array.logical_null_count() > 0 && !drop_nulls) { + return Ok(None); + } + let values: Vec = array.iter().flatten().map(|v| v * scale).collect(); + Ok((!values.is_empty()).then_some(values)) + } + + /// Wrap a date-valued result in its temporal value, rounding to the + /// column's precision (whole days / whole µs). + fn typed(&self, value: f64) -> Value { + match self { + Self::Numeric => unreachable!("the numeric arm wraps directly"), + Self::Date => Value::Date(value.round() as i32), + Self::DateTime => Value::DateTime(value.round() as i64), + } + } + + /// Convert a duration from the compute unit to the reported unit (days + /// for dates, seconds for timestamps). + fn duration(&self, value: f64) -> f64 { + match self { + Self::Numeric => unreachable!("the numeric arm wraps directly"), + Self::Date => value, + Self::DateTime => value / 1e6, + } + } +} + +/// Build the one-cell array holding a bare operation's result. A date-valued +/// result keeps the summarised column's temporal type (and timezone) so it +/// displays and formats like a body cell; everything else is a Float64. +fn value_array(value: &Option, dtype: &DataType) -> ArrayRef { + let Some(value) = value else { + let dtype = match ValueKind::of(dtype) { + Some(ValueKind::Date | ValueKind::DateTime) => dtype.clone(), + _ => DataType::Float64, + }; + return arrow::array::new_null_array(&dtype, 1); + }; + match (value, dtype) { + (Value::Date(days), DataType::Date32) => Arc::new(Date32Array::from(vec![Some(*days)])), + (Value::Date(days), DataType::Date64) => { + Arc::new(Date64Array::from(vec![Some(*days as i64 * 86_400_000)])) + } + (Value::DateTime(us), DataType::Timestamp(unit, tz)) => { + let us = *us; + match unit { + TimeUnit::Second => Arc::new( + TimestampSecondArray::from(vec![Some(us / 1_000_000)]) + .with_timezone_opt(tz.clone()), + ), + TimeUnit::Millisecond => Arc::new( + TimestampMillisecondArray::from(vec![Some(us / 1_000)]) + .with_timezone_opt(tz.clone()), + ), + TimeUnit::Microsecond => Arc::new( + TimestampMicrosecondArray::from(vec![Some(us)]).with_timezone_opt(tz.clone()), + ), + TimeUnit::Nanosecond => Arc::new( + TimestampNanosecondArray::from(vec![Some(us * 1_000)]) + .with_timezone_opt(tz.clone()), + ), + } + } + _ => { + let Value::Number(n) = value else { + unreachable!("summary_stat yields Date/DateTime only on temporal columns") + }; + Arc::new(Float64Array::from(vec![Some(*n)])) + } + } +} + +/// Count a column's distinct non-null values: NULL when nulls propagate. +fn n_distinct(array: &ArrayRef, drop_nulls: bool) -> Result> { + if array.logical_null_count() > 0 && !drop_nulls { + return Ok(None); + } + let len = if array.data_type().is_numeric() { + // Bits, not display text: two values that round to the same display + // string still count as distinct + let f64s = cast_array(array, &DataType::Float64)?; + as_f64(&f64s)? + .iter() + .flatten() + .map(f64::to_bits) + .collect::>() + .len() + } else { + (0..array.len()) + .filter(|&idx| !array.is_null(idx)) + .map(|idx| value_to_string(array, idx)) + .collect::>() + .len() + }; + Ok(Some(len as f64)) +} + +/// Population variance, matching the plot stats' `VAR_POP`. +fn variance(values: &[f64]) -> f64 { + let mean = values.iter().sum::() / values.len() as f64; + values.iter().map(|x| (x - mean).powi(2)).sum::() / values.len() as f64 +} + +fn min(values: &[f64]) -> f64 { + values.iter().fold(f64::INFINITY, |a, &b| a.min(b)) +} + +fn max(values: &[f64]) -> f64 { + values.iter().fold(f64::NEG_INFINITY, |a, &b| a.max(b)) +} + +/// Linear-interpolated quantile. +/// Uses the `quantile_cont` convention, R's default `quantile(type = 7)`. +fn quantile(mut values: Vec, q: f64) -> f64 { + values.sort_by(f64::total_cmp); + let pos = q * (values.len() - 1) as f64; + let lower = values[pos.floor() as usize]; + let upper = values[pos.ceil() as usize]; + lower + (upper - lower) * pos.fract() +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::params::Parameters; + use arrow::array::{Float64Array, Int64Array, StringArray}; + use std::sync::Arc; + + /// Unwrap a `summary_stat` result to its plain number. + fn num(result: Result>) -> Option { + result.unwrap().and_then(|v| v.as_number()) + } + + #[test] + fn nulls_propagate_by_default() { + let array: ArrayRef = Arc::new(Float64Array::from(vec![Some(1.0), None, Some(3.0)])); + assert_eq!(num(summary_stat("mean", &array, false)), None); + assert_eq!(num(summary_stat("median", &array, false)), None); + } + + #[test] + fn drop_nulls_ignores_them() { + let array: ArrayRef = Arc::new(Float64Array::from(vec![Some(1.0), None, Some(3.0)])); + assert_eq!(num(summary_stat("mean", &array, true)), Some(2.0)); + assert_eq!(num(summary_stat("median", &array, true)), Some(2.0)); + } + + #[test] + fn mean_accepts_integer_columns() { + let array: ArrayRef = Arc::new(Int64Array::from(vec![1, 2, 3])); + assert_eq!(num(summary_stat("MEAN", &array, false)), Some(2.0)); + } + + #[test] + fn median_interpolates_even_counts() { + let odd: ArrayRef = Arc::new(Float64Array::from(vec![3.0, 1.0, 2.0])); + assert_eq!(num(summary_stat("median", &odd, false)), Some(2.0)); + + let even: ArrayRef = Arc::new(Float64Array::from(vec![1.0, 2.0, 3.0, 4.0])); + assert_eq!(num(summary_stat("median", &even, false)), Some(2.5)); + } + + #[test] + fn all_null_input_is_none() { + let array: ArrayRef = Arc::new(Float64Array::from(vec![None::, None])); + assert_eq!(num(summary_stat("mean", &array, true)), None); + } + + #[test] + fn non_numeric_column_is_rejected() { + let array: ArrayRef = Arc::new(StringArray::from(vec!["a", "b"])); + assert!(summary_stat("mean", &array, true).is_err()); + } + + #[test] + fn unknown_operation_is_rejected() { + let array: ArrayRef = Arc::new(Float64Array::from(vec![1.0])); + assert!(summary_stat("first", &array, false).is_err()); + } + + #[test] + fn count_is_type_free() { + let strings: ArrayRef = Arc::new(StringArray::from(vec![Some("a"), None, Some("b")])); + assert_eq!(num(summary_stat("count", &strings, false)), Some(3.0)); + assert_eq!(num(summary_stat("count", &strings, true)), Some(2.0)); + } + + #[test] + fn count_of_an_empty_slice_is_zero() { + let array: ArrayRef = Arc::new(Float64Array::from(Vec::::new())); + assert_eq!(num(summary_stat("count", &array, false)), Some(0.0)); + } + + #[test] + fn n_missing_counts_nulls() { + let array: ArrayRef = Arc::new(Float64Array::from(vec![Some(1.0), None, Some(3.0)])); + assert_eq!(num(summary_stat("n_missing", &array, false)), Some(1.0)); + assert_eq!(num(summary_stat("n_missing", &array, true)), Some(1.0)); + } + + #[test] + fn n_distinct_counts_distinct_values() { + let numeric: ArrayRef = Arc::new(Int64Array::from(vec![1, 2, 2, 3, 1])); + assert_eq!(num(summary_stat("n_distinct", &numeric, false)), Some(3.0)); + + let strings: ArrayRef = Arc::new(StringArray::from(vec!["a", "b", "a"])); + assert_eq!(num(summary_stat("n_distinct", &strings, false)), Some(2.0)); + } + + #[test] + fn n_distinct_propagates_nulls() { + let array: ArrayRef = Arc::new(Float64Array::from(vec![Some(1.0), None, Some(2.0)])); + assert_eq!(num(summary_stat("n_distinct", &array, false)), None); + assert_eq!(num(summary_stat("n_distinct", &array, true)), Some(2.0)); + } + + fn eval(template: &str, array: &ArrayRef, drop_nulls: bool) -> Option { + let segments = parse_template(template).unwrap(); + render_template(&segments, array, drop_nulls).unwrap() + } + + #[test] + fn template_arithmetic_combines_stats() { + let array: ArrayRef = Arc::new(Float64Array::from(vec![1.0, 2.0, 3.0])); + assert_eq!(eval("{mean+10}", &array, false).as_deref(), Some("12")); + assert_eq!(eval("{(3-mean)*2}", &array, false).as_deref(), Some("2")); + // A repeated stat computes once and combines cleanly. + assert_eq!(eval("{mean/mean}", &array, false).as_deref(), Some("1")); + assert_eq!(eval("{-mean}", &array, false).as_deref(), Some("−2")); + } + + #[test] + fn template_arithmetic_propagates_nulls() { + let array: ArrayRef = Arc::new(Float64Array::from(vec![Some(1.0), Some(2.0), None])); + assert_eq!(eval("{mean-sdev}", &array, false), None); + assert_eq!( + eval("{mean-sdev:%.1f}", &array, true).as_deref(), + Some("1.0") + ); + } + + #[test] + fn a_null_placeholder_nulls_the_whole_cell() { + let array: ArrayRef = Arc::new(Float64Array::from(vec![Some(1.0), Some(2.0), None])); + assert_eq!(eval("{mean} +/- {sdev}", &array, false), None); + assert_eq!( + eval("{mean} +/- {sdev}", &array, true).as_deref(), + Some("1.5 +/- 0.5") + ); + } + + fn stat(operation: &str, values: &[f64]) -> f64 { + let array: ArrayRef = Arc::new(Float64Array::from(values.to_vec())); + num(summary_stat(operation, &array, false)).unwrap() + } + + #[test] + fn numeric_operations() { + let v = &[1.0, 2.0, 3.0, 4.0]; + assert_eq!(stat("sum", v), 10.0); + assert_eq!(stat("prod", v), 24.0); + assert_eq!(stat("min", v), 1.0); + assert_eq!(stat("max", v), 4.0); + assert_eq!(stat("range", v), 3.0); + assert_eq!(stat("mid", v), 2.5); + assert_eq!(stat("mean", v), 2.5); + assert_eq!(stat("geomean", v), (24.0_f64).powf(0.25)); + assert_eq!(stat("harmean", v), 4.0 / (1.0 + 0.5 + 1.0 / 3.0 + 0.25)); + assert_eq!(stat("rms", v), ((1.0 + 4.0 + 9.0 + 16.0) / 4.0_f64).sqrt()); + assert_eq!(stat("sdev", v), 1.25_f64.sqrt()); + assert_eq!(stat("se", v), 1.25_f64.sqrt() / 2.0); + assert_eq!(stat("var", v), 1.25); + assert_eq!(stat("iqr", v), 1.5); + assert_eq!(stat("median", v), 2.5); + assert_eq!(stat("p50", v), 2.5); + assert!((stat("p05", v) - 1.15).abs() < 1e-12); + assert!((stat("p95", v) - 3.85).abs() < 1e-12); + } + + /// 2024-01-15, 2024-01-16, 2024-01-18 as days since the epoch. + fn dates() -> ArrayRef { + Arc::new(Date32Array::from(vec![19737, 19738, 19740])) + } + + #[test] + fn date_valued_ops_on_dates_return_dates() { + assert!(matches!( + summary_stat("min", &dates(), false).unwrap(), + Some(Value::Date(19737)) + )); + assert!(matches!( + summary_stat("max", &dates(), false).unwrap(), + Some(Value::Date(19740)) + )); + assert!(matches!( + summary_stat("median", &dates(), false).unwrap(), + Some(Value::Date(19738)) + )); + // (19737 + 19740) / 2 = 19738.5, rounding to 19739. + assert!(matches!( + summary_stat("mid", &dates(), false).unwrap(), + Some(Value::Date(19739)) + )); + } + + #[test] + fn a_mean_of_dates_rounds_to_a_whole_day() { + // Mean of 19737 and 19738 falls on 19737.5. + let array: ArrayRef = Arc::new(Date32Array::from(vec![19737, 19738])); + assert!(matches!( + summary_stat("mean", &array, false).unwrap(), + Some(Value::Date(19738)) + )); + } + + #[test] + fn spread_ops_on_dates_return_days() { + assert!(matches!( + summary_stat("range", &dates(), false).unwrap(), + Some(Value::Number(3.0)) + )); + assert!(matches!( + summary_stat("iqr", &dates(), false).unwrap(), + Some(Value::Number(1.5)) + )); + } + + #[test] + fn spread_ops_on_timestamps_return_seconds() { + let array: ArrayRef = Arc::new(TimestampSecondArray::from(vec![0, 10, 50])); + assert!(matches!( + summary_stat("range", &array, false).unwrap(), + Some(Value::Number(50.0)) + )); + // Population variance of 0, 10, 50 is 1400/3. + assert!(matches!( + summary_stat("sdev", &array, false).unwrap(), + Some(Value::Number(s)) if (s * s - 1400.0 / 3.0).abs() < 1e-9 + )); + } + + #[test] + fn date_valued_ops_on_timestamps_return_datetimes() { + let array: ArrayRef = Arc::new(TimestampMillisecondArray::from(vec![1_000, 3_000, 5_000])); + assert!(matches!( + summary_stat("min", &array, false).unwrap(), + Some(Value::DateTime(1_000_000)) + )); + assert!(matches!( + summary_stat("median", &array, false).unwrap(), + Some(Value::DateTime(3_000_000)) + )); + } + + #[test] + fn other_folds_reject_temporal_columns() { + for op in ["sum", "prod", "geomean", "harmean", "rms", "var"] { + assert!( + summary_stat(op, &dates(), false).is_err(), + "{op} should reject a date column" + ); + } + } + + #[test] + fn tallies_still_accept_temporal_columns() { + assert_eq!(num(summary_stat("count", &dates(), false)), Some(3.0)); + assert_eq!(num(summary_stat("n_distinct", &dates(), false)), Some(3.0)); + } + + #[test] + fn temporal_nulls_propagate_by_default() { + let array: ArrayRef = Arc::new(Date32Array::from(vec![Some(19737), None])); + assert!(summary_stat("min", &array, false).unwrap().is_none()); + assert!(matches!( + summary_stat("min", &array, true).unwrap(), + Some(Value::Date(19737)) + )); + } + + #[test] + fn templates_format_date_leaves_as_dates() { + assert_eq!( + eval("{min}", &dates(), false).as_deref(), + Some("2024-01-15") + ); + assert_eq!( + eval("{min:time %d %b %Y}", &dates(), false).as_deref(), + Some("15 Jan 2024") + ); + } + + #[test] + fn template_arithmetic_on_dates_is_a_number_of_days() { + assert_eq!(eval("{max-min}", &dates(), false).as_deref(), Some("3")); + assert_eq!( + eval("{max-min:duration d}", &dates(), false).as_deref(), + Some("3d") + ); + assert_eq!( + eval("{(max-min)/7:%.4f}", &dates(), false).as_deref(), + Some("0.4286") + ); + } + + #[test] + fn a_date_summary_frame_keeps_the_date_type() { + let df = DataFrame::new(vec![("d".to_string(), dates())]).unwrap(); + let rows = body_rows(&[&[], &[], &[]]); + + let computed = compute_summaries( + &df, + &rows, + &[summary("mean", SummaryScope::Grand, &["d"])], + &HashMap::new(), + ) + .unwrap(); + + let array = computed[0].1[0].frame.column("d").unwrap(); + assert_eq!(array.data_type(), &DataType::Date32); + // 19737.67 rounds to 19738: 2024-01-16. + assert_eq!(column_to_strings(array), vec!["2024-01-16"]); + } + + #[test] + fn a_timestamp_summary_frame_keeps_the_timestamp_type() { + let column: ArrayRef = Arc::new(TimestampSecondArray::from(vec![0, 3600, 7200])); + let df = DataFrame::new(vec![("t".to_string(), column)]).unwrap(); + let rows = body_rows(&[&[], &[], &[]]); + + let computed = compute_summaries( + &df, + &rows, + &[summary("max", SummaryScope::Grand, &["t"])], + &HashMap::new(), + ) + .unwrap(); + + let array = computed[0].1[0].frame.column("t").unwrap(); + assert_eq!( + array.data_type(), + &DataType::Timestamp(TimeUnit::Second, None) + ); + assert_eq!(column_to_strings(array), vec!["1970-01-01T02:00:00"]); + } + + fn summary(operation: &str, scope: SummaryScope, columns: &[&str]) -> Summary { + resolved(Summary { + operation: SummaryOperation::Stat(operation.to_string()), + scope, + columns: columns.iter().map(|c| c.to_string()).collect(), + settings: Parameters::new(), + }) + } + + /// `compute_summaries` expects clauses with resolved settings. + fn resolved(summary: Summary) -> Summary { + Summary { + settings: summary.resolve_settings().unwrap(), + ..summary + } + } + + fn body_rows(keys: &[&[usize]]) -> Vec { + keys.iter() + .map(|key| TableRow { + group: key.to_vec(), + ..TableRow::body() + }) + .collect() + } + + fn column_values(frame: &DataFrame, column: &str) -> Vec> { + as_f64(frame.column(column).unwrap()) + .unwrap() + .iter() + .collect() + } + + #[test] + fn grand_summary_is_a_single_ungrouped_row() { + let df = crate::df! { + "x" => vec![1.0, 2.0, 3.0], + } + .unwrap(); + let rows = body_rows(&[&[], &[], &[]]); + + let computed = compute_summaries( + &df, + &rows, + &[summary("mean", SummaryScope::Grand, &["x"])], + &HashMap::new(), + ) + .unwrap(); + + assert_eq!(computed.len(), 1); + let (key, rows) = &computed[0]; + assert_eq!(*key, None); + assert_eq!(rows.len(), 1); + assert!(!rows[0].top); + assert_eq!(rows[0].label, "mean"); + assert_eq!(column_values(&rows[0].frame, "x"), vec![Some(2.0)]); + } + + #[test] + fn group_summary_emits_one_row_per_group_in_display_order() { + let df = crate::df! { + "x" => vec![1.0, 3.0, 10.0, 20.0], + } + .unwrap(); + // Two nested-facet groups, contiguous after setup_rows' reorder. + let rows = body_rows(&[&[2, 0], &[2, 0], &[2, 1], &[2, 1]]); + + let computed = compute_summaries( + &df, + &rows, + &[summary("mean", SummaryScope::Group, &["x"])], + &HashMap::new(), + ) + .unwrap(); + + assert_eq!(computed.len(), 2); + assert_eq!(computed[0].0, Some(vec![2, 0])); + assert_eq!(computed[1].0, Some(vec![2, 1])); + assert_eq!(column_values(&computed[0].1[0].frame, "x"), vec![Some(2.0)]); + assert_eq!( + column_values(&computed[1].1[0].frame, "x"), + vec![Some(15.0)] + ); + } + + #[test] + fn rows_come_chunk_major_in_clause_order() { + let df = crate::df! { + "x" => vec![1.0, 10.0], + } + .unwrap(); + let rows = body_rows(&[&[0], &[1]]); + let above = resolved(Summary { + settings: crate::params! { "place" => "top" }, + ..summary("mean", SummaryScope::Group, &["x"]) + }); + let below = summary("median", SummaryScope::Group, &["x"]); + + let computed = compute_summaries(&df, &rows, &[below, above], &HashMap::new()).unwrap(); + + let order: Vec<(Vec, &str, bool)> = computed + .iter() + .flat_map(|(key, rows)| { + let key = key.clone().expect("GROUP chunks are keyed"); + rows.iter() + .map(move |row| (key.clone(), row.label.as_str(), row.top)) + }) + .collect(); + // Chunk-major, clause order within a chunk; placement is the + // weavers' concern. + assert_eq!( + order, + vec![ + (vec![0], "median", false), + (vec![0], "mean", true), + (vec![1], "median", false), + (vec![1], "mean", true), + ] + ); + } + + #[test] + fn rowlabel_overrides_the_operation_as_label() { + let df = crate::df! { + "x" => vec![1.0], + } + .unwrap(); + let rows = body_rows(&[&[]]); + let labelled = resolved(Summary { + settings: crate::params! { "rowlabel" => "Average" }, + ..summary("mean", SummaryScope::Grand, &["x"]) + }); + + let computed = compute_summaries(&df, &rows, &[labelled], &HashMap::new()).unwrap(); + + assert_eq!(computed[0].1[0].label, "Average"); + } + + #[test] + fn no_facet_means_one_group_with_an_empty_key() { + let df = crate::df! { + "x" => vec![2.0, 4.0], + } + .unwrap(); + let rows = body_rows(&[&[], &[]]); + + let computed = compute_summaries( + &df, + &rows, + &[summary("mean", SummaryScope::Group, &["x"])], + &HashMap::new(), + ) + .unwrap(); + + assert_eq!(computed.len(), 1); + assert_eq!(computed[0].0, Some(vec![])); + assert_eq!(column_values(&computed[0].1[0].frame, "x"), vec![Some(3.0)]); + } + + #[test] + fn the_missing_setting_drives_null_handling() { + let df = crate::df! { + "x" => vec![Some(1.0), None, Some(3.0)], + } + .unwrap(); + let rows = body_rows(&[&[], &[], &[]]); + + let drop = resolved(Summary { + settings: crate::params! { "missing" => "drop" }, + ..summary("mean", SummaryScope::Grand, &["x"]) + }); + + let computed = compute_summaries( + &df, + &rows, + &[summary("mean", SummaryScope::Grand, &["x"]), drop], + &HashMap::new(), + ) + .unwrap(); + + let (key, rows) = &computed[0]; + assert_eq!(*key, None); + assert_eq!(column_values(&rows[0].frame, "x"), vec![None]); + assert_eq!(column_values(&rows[1].frame, "x"), vec![Some(2.0)]); + } + + fn stub_format() -> Format { + Format { + columns: vec!["x".to_string()], + wildcard: false, + target: Some(ColumnSection::Stub), + settings: Parameters::new(), + label_spec: Default::default(), + } + } + + fn label_format(label_spec: zygos::LabelSpec) -> Format { + Format { + columns: Vec::new(), + wildcard: false, + target: None, + settings: Parameters::new(), + label_spec, + } + } + + #[test] + fn a_columns_format_formats_its_summary_value() { + let df = crate::df! { + "x" => vec![1.0, 2.0], + } + .unwrap(); + let rows = body_rows(&[&[], &[]]); + let mut label_spec = zygos::LabelSpec::new(); + label_spec.set_template("${:num %.2f}"); + let formats = HashMap::from([("x".to_string(), label_format(label_spec))]); + + let computed = compute_summaries( + &df, + &rows, + &[summary("mean", SummaryScope::Grand, &["x"])], + &formats, + ) + .unwrap(); + + assert_eq!( + column_to_strings(computed[0].1[0].frame.column("x").unwrap()), + vec!["$1.50"] + ); + } + + #[test] + fn a_label_applies_to_a_summary_value() { + let df = crate::df! { + "x" => vec![0.0, 0.0], + } + .unwrap(); + let rows = body_rows(&[&[], &[]]); + let mut label_spec = zygos::LabelSpec::new(); + label_spec.rename(zygos::Value::String("0".into()), "-"); + let formats = HashMap::from([("x".to_string(), label_format(label_spec))]); + + let computed = compute_summaries( + &df, + &rows, + &[summary("mean", SummaryScope::Grand, &["x"])], + &formats, + ) + .unwrap(); + + assert_eq!( + column_to_strings(computed[0].1[0].frame.column("x").unwrap()), + vec!["-"] + ); + } + + #[test] + fn a_label_formats_a_count_of_a_non_numeric_column() { + let df = crate::df! { + "text" => vec!["a", "b"], + } + .unwrap(); + let rows = body_rows(&[&[], &[]]); + let mut label_spec = zygos::LabelSpec::new(); + label_spec.set_template("[{}]"); + let formats = HashMap::from([("text".to_string(), label_format(label_spec))]); + + let computed = compute_summaries( + &df, + &rows, + &[summary("count", SummaryScope::Grand, &["text"])], + &formats, + ) + .unwrap(); + + assert_eq!( + column_to_strings(computed[0].1[0].frame.column("text").unwrap()), + vec!["[2]"] + ); + } + + #[test] + fn setup_adds_an_empty_label_column_when_no_stub_exists() { + let mut df = crate::df! { + "x" => vec![1.0, 2.0], + } + .unwrap(); + + setup_summaries( + &mut df, + &HashMap::new(), + &[summary("mean", SummaryScope::Group, &["x"])], + ) + .unwrap(); + + let labels = + crate::array_util::as_str(df.column(naming::SUMMARY_LABEL_COLUMN).unwrap()).unwrap(); + assert_eq!(labels.iter().collect::>(), vec![Some(""), Some("")]); + } + + #[test] + fn setup_leaves_the_frame_alone_when_a_stub_exists() { + let mut df = crate::df! { + "x" => vec![1.0, 2.0], + } + .unwrap(); + let formats = HashMap::from([("x".to_string(), stub_format())]); + + setup_summaries( + &mut df, + &formats, + &[summary("mean", SummaryScope::Group, &["x"])], + ) + .unwrap(); + + assert!(df.column(naming::SUMMARY_LABEL_COLUMN).is_err()); + } + + #[test] + fn setup_without_summaries_is_a_no_op() { + let mut df = crate::df! { + "x" => vec![1.0], + } + .unwrap(); + + setup_summaries(&mut df, &HashMap::new(), &[]).unwrap(); + + assert_eq!(df.width(), 1); + } + + #[test] + fn setup_rejects_a_summarised_column_the_data_lacks() { + let mut df = crate::df! { + "x" => vec![1.0], + } + .unwrap(); + + let result = setup_summaries( + &mut df, + &HashMap::new(), + &[summary("mean", SummaryScope::Group, &["y"])], + ); + + assert_eq!( + result.unwrap_err().to_string(), + "Validation error: SUMMARISE mean: no column 'y' in the query result" + ); + } + + #[test] + fn summarising_a_missing_column_errors() { + let df = crate::df! { + "x" => vec![1.0], + } + .unwrap(); + let rows = body_rows(&[&[]]); + + let result = compute_summaries( + &df, + &rows, + &[summary("mean", SummaryScope::Grand, &["y"])], + &HashMap::new(), + ); + assert!(result.is_err()); + } +} diff --git a/src/format.rs b/src/format.rs index eb7c18e64..3c19f9251 100644 --- a/src/format.rs +++ b/src/format.rs @@ -17,7 +17,7 @@ use arrow::array::{Array, ArrayRef, BooleanArray, Int64Array, UInt64Array}; use arrow::datatypes::DataType; use zygos::{LabelSpec, Value}; -use crate::array_util::{as_f64, as_str, cast_array, new_str_array}; +use crate::array_util::{as_f32, as_f64, as_str, cast_array, new_str_array}; use crate::plot::ArrayElement; /// Serde mirror for [`zygos::LabelSpec`], which is dependency-free and has no @@ -173,6 +173,24 @@ pub fn resolve_column_values( Ok(render_labels(spec, &values, false, Some(""), None)) } +/// Like [`resolve_column_values`], but consulting only the spec's direct +/// renames — the wildcard template is ignored. For already-rendered text +/// (a `SUMMARISE` template cell), where re-rendering a string through a +/// numeric template is meaningless. +pub fn resolve_column_values_direct( + column: &ArrayRef, + spec: &LabelSpec, +) -> Result>, String> { + let mut direct = LabelSpec::new(); + for (key, label) in spec.renames() { + match label { + Some(label) => direct.rename(key.clone(), label), + None => direct.suppress(key.clone()), + }; + } + resolve_column_values(column, &direct) +} + /// Shared label rendering behind [`label_elements`] and /// [`resolve_column_values`]. `share_precision` derives `{}` decimal /// precision across the un-renamed values (scale breaks) or renders each @@ -412,6 +430,54 @@ pub fn format_dataframe_column( .map_err(|e| format!("Failed to replace column: {}", e)) } +/// Decimal places to display a float column consistently: the most any +/// non-null value needs. Non-float columns need none. +pub fn display_decimals(column: &ArrayRef) -> usize { + let decimals: Box + '_> = match column.data_type() { + DataType::Float64 => Box::new( + as_f64(column) + .unwrap() + .iter() + .map(|v| v.unwrap_or(f64::NAN)), + ), + DataType::Float32 => Box::new( + as_f32(column) + .unwrap() + .iter() + .map(|v| f64::from(v.unwrap_or(f32::NAN))), + ), + _ => return 0, + }; + // Search each value only upward from the running maximum: a value + // fitting at fewer decimals cannot lower it, and a fit at `d` fits at + // every larger `d`, so nothing below the maximum needs checking. + let mut max = 0; + for v in decimals { + max = minimal_decimals(v, max); + if max == 15 { + break; + } + } + max +} + +/// Fewest decimal places that represent `v` within float noise: the +/// smallest `d >= from` whose rounded value is within a few ULP of `v`. +/// Caps at 15. Non-finite values contribute nothing. +fn minimal_decimals(v: f64, from: usize) -> usize { + if !v.is_finite() { + return from; + } + let tol = 4.0 * f64::EPSILON * v.abs(); + // Past 15 decimals an f64 carries no real information + (from..=15) + .find(|&d| { + let factor = 10f64.powi(d as i32); + ((v * factor).round() / factor - v).abs() <= tol + }) + .unwrap_or(15) +} + #[cfg(test)] mod tests { use super::*; @@ -426,6 +492,36 @@ mod tests { breaks.iter().map(|n| ArrayElement::Number(*n)).collect() } + fn floats(values: &[f64]) -> ArrayRef { + std::sync::Arc::new(arrow::array::Float64Array::from(values.to_vec())) + } + + #[test] + fn display_decimals_pads_to_the_widest_value() { + assert_eq!(display_decimals(&floats(&[39.1, 37.7, 50.0])), 1); + assert_eq!(display_decimals(&floats(&[1.25, 3.75])), 2); + } + + #[test] + fn display_decimals_trims_binary_float_noise() { + assert_eq!(display_decimals(&floats(&[0.1 + 0.2, 1.5])), 1); + // An irrational value rounds at no decimal count: full precision. + assert_eq!(display_decimals(&floats(&[std::f64::consts::PI])), 15); + } + + #[test] + fn display_decimals_keeps_real_low_order_digits() { + assert_eq!(display_decimals(&floats(&[1234567.01])), 2); + assert_eq!(display_decimals(&floats(&[1e-8])), 8); + } + + #[test] + fn display_decimals_is_zero_for_whole_and_non_float_columns() { + assert_eq!(display_decimals(&floats(&[50.0, 60.0])), 0); + let ints: ArrayRef = std::sync::Arc::new(arrow::array::Int64Array::from(vec![1, 2])); + assert_eq!(display_decimals(&ints), 0); + } + fn strings(breaks: &[&str]) -> Vec { breaks .iter() diff --git a/src/lib.rs b/src/lib.rs index 0301eae00..3bf1e4111 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -75,7 +75,7 @@ pub use plot::{ // Re-export the parse-time Plot/Table result and the Table stub pub use spec::Spec; -pub use table::{ColumnSection, Format, SelectionItem, Spanner, Table}; +pub use table::{ColumnSection, Format, SelectionItem, Spanner, Summary, Table}; // Re-export aesthetic classification utilities pub use plot::aesthetic::{ diff --git a/src/naming.rs b/src/naming.rs index 75f34fbc8..e1ede82d7 100644 --- a/src/naming.rs +++ b/src/naming.rs @@ -94,6 +94,10 @@ pub const SCHEMA_ALIAS: &str = concatcp!(GGSQL_SUFFIX, "schema", GGSQL_SUFFIX); /// Alias for the derived table a TABULATE selection wraps its source in pub const TABLE_ALIAS: &str = concatcp!(GGSQL_SUFFIX, "table", GGSQL_SUFFIX); +/// Synthetic stub column holding `SUMMARISE` row labels, inserted when a +/// table has summaries but no `STUB` column to put them in. Never names a +/// `DataFrame` column. +pub const SUMMARY_LABEL_COLUMN: &str = concatcp!(GGSQL_PREFIX, "summary_label", GGSQL_SUFFIX); /// Column holding each row's position in a query's output, in a result kept /// for the Jupyter kernel's results API. pub const RESULT_ROW_COLUMN: &str = concatcp!(GGSQL_PREFIX, "row", GGSQL_SUFFIX); diff --git a/src/params.rs b/src/params.rs index 010271a08..2bf93fbb3 100644 --- a/src/params.rs +++ b/src/params.rs @@ -1389,18 +1389,6 @@ impl ParamDefinition { } } - /// The effective value for this parameter: the user's value if present - /// (validated against the constraint), otherwise the default. - /// - /// Returns Ok(None) when the parameter is absent and the default is Null. - pub fn resolve( - &self, - value: Option<&ParameterValue>, - ) -> Result, String> { - self.validate(value)?; - Ok(value.cloned().or_else(|| self.to_parameter_value())) - } - /// Convert the default value to a ParameterValue, if not Null pub fn to_parameter_value(&self) -> Option { match &self.default { @@ -1444,22 +1432,44 @@ pub fn reject_unknown_parameters( )) } -/// Validate `properties` against `definitions` and resolve each parameter -/// to its effective value: the user's value if present, otherwise the -/// definition's default. Returns a new map with defaults filled. -pub fn resolve_parameters( +/// Validate `properties` against `definitions`: no unknown keys, and every +/// present value passes its definition's constraint. Absence is always +/// valid — defaults are [`resolve_parameters`]' business. +pub fn validate_parameters( properties: &Parameters, definitions: &[ParamDefinition], context: &str, -) -> Result { +) -> Result<(), String> { reject_unknown_parameters(properties, definitions, context)?; + for param in definitions { + param.validate(properties.get(param.name))?; + } + Ok(()) +} + +/// Each parameter's effective value: the user's value if present, +/// otherwise the definition's default. Assumes `properties` passes +/// [`validate_parameters`]. +pub fn with_defaults(properties: &Parameters, definitions: &[ParamDefinition]) -> Parameters { let mut resolved = properties.clone(); for param in definitions { - if let Some(value) = param.resolve(properties.get(param.name))? { + if let Some(value) = param.to_parameter_value() { resolved.entry(param.name.to_string()).or_insert(value); } } - Ok(resolved) + resolved +} + +/// Validate `properties` against `definitions` and resolve each parameter +/// to its effective value: the user's value if present, otherwise the +/// definition's default. Returns a new map with defaults filled. +pub fn resolve_parameters( + properties: &Parameters, + definitions: &[ParamDefinition], + context: &str, +) -> Result { + validate_parameters(properties, definitions, context)?; + Ok(with_defaults(properties, definitions)) } #[cfg(test)] @@ -1479,25 +1489,6 @@ mod tests { .validate(Some(value)) } - #[test] - fn param_definition_resolve_prefers_user_value_then_default() { - let def = ParamDefinition { - name: "bins", - default: DefaultParamValue::Number(30.0), - constraint: ParamConstraint::count(1.0), - }; - let present = Some(10.0.into()); - // User value wins over the default, absent falls back to the default, - // and a Null default means no value. - assert_eq!(def.resolve(present.as_ref()).unwrap(), Some(10.0.into())); - assert_eq!(def.resolve(None).unwrap(), Some(30.0.into())); - let no_default = ParamDefinition { - default: DefaultParamValue::Null, - ..def - }; - assert_eq!(no_default.resolve(None).unwrap(), None); - } - #[test] fn reject_unknown_parameters_lists_valid_names() { let defs = [ParamDefinition { diff --git a/src/parser/builder.rs b/src/parser/builder.rs index e0e5318e5..e048b71f1 100644 --- a/src/parser/builder.rs +++ b/src/parser/builder.rs @@ -8,7 +8,8 @@ use crate::plot::layer::geom::Geom; use crate::plot::projection::resolve_coord; use crate::plot::scale::{color_to_hex, is_color_aesthetic, is_user_facet_aesthetic, Transform}; use crate::plot::*; -use crate::{ColumnSection, Format, GgsqlError, Result, SelectionItem, Spanner, Spec, Table}; +use crate::table::*; +use crate::{GgsqlError, Result, Spec}; use std::collections::HashMap; use tree_sitter::Node; @@ -452,6 +453,11 @@ fn process_tab_clause(node: &Node, source: &SourceTree, table: &mut Table) -> Re "format_clause" => { table.formats.push(build_format_clause(&child, source)?); } + "summarise_clause" => { + table + .summaries + .push(build_summarise_clause(&child, source)?); + } "facet_clause" => { let facet = build_facet(&child, source)?; if facet.is_grid() { @@ -515,6 +521,65 @@ fn build_span_clause(node: &Node, source: &SourceTree, span_idx: usize) -> Resul }) } +/// Build a Summary from a summarise_clause node: +/// SUMMARISE [GROUP|GRAND] OF col, ... [SETTING ...] +fn build_summarise_clause(node: &Node, source: &SourceTree) -> Result { + let operation_node = node.child_by_field_name("operation").ok_or_else(|| { + GgsqlError::ParseError("Missing operation in SUMMARISE clause".to_string()) + })?; + let operation = match operation_node.kind() { + "string" => SummaryOperation::Template(parse_string_node(&operation_node, source)), + _ => SummaryOperation::Stat(naming::unquote_ident(&source.get_text(&operation_node))), + }; + + let scope = match node.child_by_field_name("scope") { + Some(scope_node) => match source.get_text(&scope_node).to_lowercase().as_str() { + "group" => SummaryScope::Group, + "grand" => SummaryScope::Grand, + text => { + return Err(GgsqlError::ParseError(format!( + "Unknown SUMMARISE scope: '{}'. Valid scopes: group, grand", + text + ))) + } + }, + None => SummaryScope::Group, + }; + + let columns_node = source + .find_node(node, "(column_list) @cols") + .ok_or_else(|| GgsqlError::ParseError("Missing columns in SUMMARISE clause".to_string()))?; + let columns = parse_column_list(&columns_node, source)?; + + // A repeated column would aggregate twice into the same cell — meaningless + // rather than redundant, so reject it. + let mut seen = std::collections::HashSet::new(); + let mut duplicates: Vec<&str> = Vec::new(); + for column in &columns { + if !seen.insert(column) && !duplicates.contains(&column.as_str()) { + duplicates.push(column); + } + } + if !duplicates.is_empty() { + return Err(GgsqlError::ParseError(format!( + "Duplicate columns in SUMMARISE clause: {}", + crate::and_list_quoted(&duplicates, '\'') + ))); + } + + let settings = match source.find_node(node, "(setting_clause) @s") { + Some(setting_node) => parse_setting_clause(&setting_node, source)?, + None => Parameters::new(), + }; + + Ok(Summary { + operation, + scope, + columns, + settings, + }) +} + /// Build a Format from a format_clause node: FORMAT [ANY|BODY|STUB] (*|col, ...) [SETTING ...] [LABEL ...] fn build_format_clause(node: &Node, source: &SourceTree) -> Result { let target = parse_format_target_identifier(node, source)?; @@ -1811,6 +1876,93 @@ mod tests { assert_eq!(table.formats[1].columns, vec!["bar"]); } + #[test] + fn test_tabulate_summarise_basic() { + let specs = parse_test_specs("TABULATE * FROM sales SUMMARISE mean OF foo, bar").unwrap(); + let table = specs[0].as_table().expect("expected a Table spec"); + + assert_eq!(table.summaries.len(), 1); + assert_eq!( + table.summaries[0].operation, + SummaryOperation::Stat("mean".to_string()) + ); + assert_eq!(table.summaries[0].scope, SummaryScope::Group); + assert_eq!(table.summaries[0].columns, vec!["foo", "bar"]); + assert!(table.summaries[0].settings.is_empty()); + } + + #[test] + fn test_tabulate_summarise_grand_scope_and_setting() { + let specs = parse_test_specs( + "TABULATE * FROM sales SUMMARISE GRAND sdev OF foo SETTING place => 'top'", + ) + .unwrap(); + let table = specs[0].as_table().expect("expected a Table spec"); + + assert_eq!(table.summaries[0].scope, SummaryScope::Grand); + assert_eq!( + table.summaries[0].settings.get("place"), + Some(&ParameterValue::String("top".to_string())) + ); + } + + #[test] + fn test_tabulate_summarise_operation_is_verbatim() { + let specs = parse_test_specs("TABULATE * FROM sales SUMMARIZE MEAN OF foo").unwrap(); + let table = specs[0].as_table().expect("expected a Table spec"); + + assert_eq!( + table.summaries[0].operation, + SummaryOperation::Stat("MEAN".to_string()) + ); + } + + #[test] + fn test_tabulate_summarise_template_operation() { + let specs = + parse_test_specs("TABULATE * FROM sales SUMMARISE '{mean} +/- {sdev}' OF foo").unwrap(); + let table = specs[0].as_table().expect("expected a Table spec"); + + assert_eq!( + table.summaries[0].operation, + SummaryOperation::Template("{mean} +/- {sdev}".to_string()) + ); + } + + #[test] + fn test_tabulate_repeated_summarise_clauses_produce_separate_summaries() { + let specs = parse_test_specs( + "TABULATE * FROM sales FACET region SUMMARISE mean OF foo SUMMARISE GRAND max OF foo, bar", + ) + .unwrap(); + let table = specs[0].as_table().expect("expected a Table spec"); + + assert_eq!(table.summaries.len(), 2); + assert_eq!( + table.summaries[0].operation, + SummaryOperation::Stat("mean".to_string()) + ); + assert_eq!(table.summaries[0].scope, SummaryScope::Group); + assert_eq!( + table.summaries[1].operation, + SummaryOperation::Stat("max".to_string()) + ); + assert_eq!(table.summaries[1].scope, SummaryScope::Grand); + assert_eq!(table.summaries[1].columns, vec!["foo", "bar"]); + } + + #[test] + fn test_tabulate_summarise_reports_all_duplicate_columns() { + let result = parse_test_specs("TABULATE * FROM sales SUMMARISE mean OF foo, bar, foo, bar"); + let error = result.unwrap_err().to_string(); + + assert!( + error.contains("Duplicate columns in SUMMARISE clause: 'foo' and 'bar'"), + "got: {}", + error + ); + } + // ======================================== // PROJECT Property Validation Tests // ======================================== diff --git a/src/reader/mod.rs b/src/reader/mod.rs index babd69830..e941eaa80 100644 --- a/src/reader/mod.rs +++ b/src/reader/mod.rs @@ -1862,6 +1862,9 @@ pub struct ColumnInfo { /// — see that function's doc comment for how the two relate. pub fn resolve_plot_with_reader(reader: &dyn Reader, query: &str) -> Result { let validated = validate(query)?; + // No early return on invalid here: plot validation runs before the + // execution-time transforms (e.g. the rule geom's setup_layer hook moving + // a SETTING intercept into mappings), so it has false positives. let warnings: Vec = validated.warnings().to_vec(); let prepared_data = prepare_data_with_reader(query, reader)?; diff --git a/src/table/facet.rs b/src/table/facet.rs index 015eff22e..4787013e9 100644 --- a/src/table/facet.rs +++ b/src/table/facet.rs @@ -32,9 +32,18 @@ const TABLE_FACET_PARAMS: &[ParamDefinition] = &[ }, ]; +/// Validate a table facet's settings: no unknown keys, every present value +/// within its constraint. Passes `None` straight through. +pub(crate) fn validate_settings(facet: &Option) -> Result<(), String> { + if let Some(facet) = facet { + crate::params::validate_parameters(&facet.properties, TABLE_FACET_PARAMS, "FACET setting")?; + } + Ok(()) +} + /// Validate a table facet's settings, apply defaults, and return the /// resolved facet. Passes `None` straight through. -pub(crate) fn setup_facet(facet: &Option) -> Result, String> { +pub(crate) fn resolve_settings(facet: &Option) -> Result, String> { let Some(facet) = facet else { return Ok(None); }; @@ -71,10 +80,10 @@ mod tests { } #[test] - fn setup_materializes_default_settings() { + fn resolve_settings_materializes_default_settings() { let facet = table_facet(Parameters::new()); - let resolved = setup_facet(&Some(facet)).unwrap().unwrap(); + let resolved = resolve_settings(&Some(facet)).unwrap().unwrap(); assert_eq!(resolved.properties.get("place"), Some(&"left".into())); assert_eq!(resolved.properties.get("missing"), Some(&"last".into())); @@ -82,23 +91,31 @@ mod tests { } #[test] - fn setup_passes_none_through() { - assert_eq!(setup_facet(&None).unwrap(), None); + fn resolve_settings_passes_none_through() { + assert_eq!(resolve_settings(&None).unwrap(), None); } #[test] - fn setup_rejects_an_invalid_place_value() { + fn validate_settings_rejects_an_invalid_place_value() { let settings = crate::params! { "place" => "bottom" }; - assert!(setup_facet(&Some(table_facet(settings))).is_err()); + assert!(validate_settings(&Some(table_facet(settings))).is_err()); + } + + #[test] + fn validate_settings_accepts_none_and_defaults() { + assert!(validate_settings(&None).is_ok()); + assert!(validate_settings(&Some(table_facet(Parameters::new()))).is_ok()); } #[test] fn groups_are_woven_only_when_place_is_top() { let settings = crate::params! { "place" => "top" }; - let woven = setup_facet(&Some(table_facet(settings))).unwrap().unwrap(); + let woven = resolve_settings(&Some(table_facet(settings))) + .unwrap() + .unwrap(); assert!(groups_are_woven(&woven)); - let left = setup_facet(&Some(table_facet(Parameters::new()))) + let left = resolve_settings(&Some(table_facet(Parameters::new()))) .unwrap() .unwrap(); assert!(!groups_are_woven(&left)); diff --git a/src/table/layout.rs b/src/table/layout.rs index 89230b3b3..98c9d72de 100644 --- a/src/table/layout.rs +++ b/src/table/layout.rs @@ -27,8 +27,13 @@ pub enum TableCellKind { StubHead, /// A data value (gt's `body`). Body, + /// A computed value in a `SUMMARISE` row. + SummaryValue, /// A row-label value in the stub (`TABULATE FORMAT STUB`, gt's `stub`). StubRowLabel, + /// A summary row's label cell in the stub (`SUMMARISE`'s `rowlabel` or + /// the operation name). + SummaryLabel, /// A spanner cell, grouping several columns under one label (`TABULATE /// SPAN`). Spanner, @@ -63,6 +68,7 @@ impl TableCellKind { | TableCellKind::Subtitle | TableCellKind::Filler // every current case is header-shaped | TableCellKind::StubRowLabel + | TableCellKind::SummaryLabel ) } } @@ -73,7 +79,9 @@ impl std::fmt::Display for TableCellKind { TableCellKind::ColumnLabel => "column label", TableCellKind::StubHead => "stub head", TableCellKind::Body => "body", + TableCellKind::SummaryValue => "summary value", TableCellKind::StubRowLabel => "stub row label", + TableCellKind::SummaryLabel => "summary label", TableCellKind::Spanner => "spanner", TableCellKind::Title => "title", TableCellKind::Subtitle => "subtitle", @@ -127,6 +135,8 @@ pub enum TableClass { /// The first body row of a facet group (gt's `gt_row_group_first`) — /// carries the thick border separating a group from what precedes it. RowGroupFirst, + /// A `SUMMARISE` row (gt's `gt_summary_row`). + SummaryRow, // -------------------------- Cell-scoped ------------------------- // Recorded on `TableCell::classes`, rendered on the ``/``. @@ -157,6 +167,25 @@ pub enum TableClass { /// A group-label cell (`TableCellKind::GroupHeading`, gt's /// `gt_group_heading`). GroupHeading, + /// A cell in a `SUMMARISE GROUP` row (gt's `gt_summary_row`). + GroupSummary, + /// A cell in the first row of a summary block — carries the border + /// separating the block from what precedes it (gt's + /// `gt_first_summary_row`). + SummaryFirst, + /// A cell in the last row of a summary block (gt's + /// `gt_last_summary_row`). + SummaryLast, + /// A cell in a `SUMMARISE GRAND` row (gt's `gt_grand_summary_row`). + GrandSummary, + /// A cell in the first row of a bottom-placed grand-summary block — + /// carries the double border separating the block from the body (gt's + /// `gt_first_grand_summary_row`). + GrandSummaryFirst, + /// A cell in the last row of a top-placed grand-summary block — carries + /// the double border separating the block from the body (gt's + /// `gt_last_grand_summary_row_top`). + GrandSummaryLast, /// Left/center/right-aligned cell content (gt's /// `gt_left`/`gt_center`/`gt_right`). AlignLeft, @@ -190,6 +219,13 @@ impl TableClass { TableClass::GroupHeading, TableClass::GroupHeadingRow, TableClass::RowGroupFirst, + TableClass::SummaryRow, + TableClass::GroupSummary, + TableClass::SummaryFirst, + TableClass::SummaryLast, + TableClass::GrandSummary, + TableClass::GrandSummaryFirst, + TableClass::GrandSummaryLast, TableClass::AlignLeft, TableClass::AlignCenter, TableClass::AlignRight, @@ -219,6 +255,13 @@ impl std::fmt::Display for TableClass { TableClass::Subtitle => "subtitle", TableClass::Caption => "caption", TableClass::Heading => "heading", + TableClass::SummaryRow => "summary_row", + TableClass::GroupSummary => "group_summary", + TableClass::SummaryFirst => "summary_first", + TableClass::SummaryLast => "summary_last", + TableClass::GrandSummary => "grand_summary", + TableClass::GrandSummaryFirst => "grand_summary_first", + TableClass::GrandSummaryLast => "grand_summary_last", TableClass::GroupHeading => "group_heading", TableClass::GroupHeadingRow => "group_heading_row", TableClass::RowGroupFirst => "row_group_first", @@ -305,6 +348,18 @@ impl TableCell { .with_classes(vec![TableClass::Row, TableClass::Stub]) } + /// A summary value cell (`TableClass::Row`). + pub(crate) fn new_summary_value(row: usize, col: usize, content: String) -> Self { + Self::new(TableCellKind::SummaryValue, row, row, col, col, content) + .with_classes(vec![TableClass::Row]) + } + + /// A summary row's stub label cell (`TableClass::Stub`). + pub(crate) fn new_summary_label(row: usize, index: usize, content: String) -> Self { + Self::new(TableCellKind::SummaryLabel, row, row, index, index, content) + .with_classes(vec![TableClass::Stub]) + } + /// A group-stub group-label cell (`TableClass::StubRowGroup`). pub(crate) fn new_stub_row_group(row: usize, index: usize, content: String) -> Self { Self::new(TableCellKind::GroupHeading, row, row, index, index, content) @@ -519,6 +574,18 @@ impl TableRow { ..Self::body() } } + + /// A summary row (`TableClass::SummaryRow`) keyed by its chunk's `group` + /// — empty for a `GRAND` row. The key marks the row as having no data + /// row behind it, so later passes (group-stub merge, group-label weave) + /// treat it accordingly. + pub fn summary(group: Vec) -> Self { + Self { + classes: vec![TableClass::SummaryRow], + group, + ..Self::body() + } + } } /// The row extent a set of cells implies — the highest `bottom` plus one, diff --git a/src/table/mod.rs b/src/table/mod.rs index c28d0935b..9cce6465d 100644 --- a/src/table/mod.rs +++ b/src/table/mod.rs @@ -4,14 +4,16 @@ //! statements, parallel to how `plot` defines `Plot` for `VISUALISE` //! statements: `source` (from `TABULATE FROM`), `selection` (from //! `TABULATE`'s own column list), `titles` (from `TABULATE TITLE`), `spans` -//! (from `TABULATE SPAN`), `formats` (from `TABULATE FORMAT`), and `facet` -//! (from `TABULATE FACET`) are populated so far. +//! (from `TABULATE SPAN`), `formats` (from `TABULATE FORMAT`), `facet` +//! (from `TABULATE FACET`), and `summaries` (from `TABULATE SUMMARISE`) are +//! populated so far. mod facet; mod layout; mod spanner; +mod summary; -pub(crate) use facet::{groups_are_woven, setup_facet}; +pub(crate) use facet::{groups_are_woven, resolve_settings as resolve_facet_settings}; pub(crate) use layout::{ compose_header, create_caption, create_column_labels, create_heading, extract_table_titles, move_stub_columns, standardise_hjust, Slot, TableTitles, @@ -19,6 +21,8 @@ pub(crate) use layout::{ pub use layout::{TableCell, TableCellKind, TableClass, TableColumn, TableLayout, TableRow}; pub use spanner::Spanner; pub(crate) use spanner::{create_spanners, reorder_table_columns}; +pub(crate) use summary::{parse_template, BinOp, StatExpr, TemplateSegment}; +pub use summary::{Summary, SummaryOperation, SummaryScope, SUMMARY_OPERATIONS}; use serde::{Deserialize, Serialize}; use std::collections::HashMap; @@ -59,6 +63,9 @@ pub struct Table { /// Row grouping (from `TABULATE FACET`). Only the wrap form is /// meaningful for tables; the builder rejects `BY`. pub facet: Option, + /// Row summaries (from `TABULATE SUMMARISE`), one per `SUMMARISE` clause + /// written — same one-clause-per-row model as `formats`. + pub summaries: Vec, } /// One item in a TABULATE column selection. @@ -96,6 +103,7 @@ impl Table { spans: Vec::new(), formats: Vec::new(), facet: None, + summaries: Vec::new(), } } } @@ -153,10 +161,13 @@ impl Table { } /// Reject columns claimed by two table features at once: a SPAN over a - /// STUB or FACET column, or a FORMAT STUB over a FACET column. Takes - /// already-`resolve_spanner_ids`-resolved spans, so every check compares - /// real column names, never a SPAN id. Needs no DataFrame, so this runs - /// from both `validate()` and real execution (`resolve_spanners`). + /// STUB or FACET column, a FORMAT STUB over a FACET column, or a + /// SUMMARISE of a STUB or FACET column. + /// + /// `resolved_spans` must come from `resolve_spanner_ids`, so every check + /// compares real column names, never a SPAN id. Needs no DataFrame, so + /// this runs from both `validate()` and real execution + /// (`setup_spanners`). pub fn validate_boundaries(&self, resolved_spans: &[Spanner]) -> Result<(), String> { let stub_columns: Vec = self .formats @@ -175,6 +186,11 @@ impl Table { span.validate_boundary(&stub_columns, "stub") .map_err(|e| format!("SPAN {}: {}", idx + 1, e))?; } + for (idx, summary) in self.summaries.iter().enumerate() { + summary + .validate_boundary(&stub_columns, "stub") + .map_err(|e| format!("SUMMARISE {}: {}", idx + 1, e))?; + } let Some(facet) = &self.facet else { return Ok(()); @@ -187,26 +203,63 @@ impl Table { if let Some(name) = facet_variables.iter().find(|v| stub_columns.contains(v)) { return Err(format!("FORMAT STUB cannot target FACET group '{name}'")); } + for (idx, summary) in self.summaries.iter().enumerate() { + summary + .validate_boundary(&facet_variables, "facet") + .map_err(|e| format!("SUMMARISE {}: {}", idx + 1, e))?; + } Ok(()) } + /// Validate everything checkable without the query result's schema: + /// each clause's settings, spanner ids, feature boundaries, and each + /// `SUMMARISE`'s operation. Column existence is execution's job. + /// Returns one message per problem found. + pub fn validate(&self) -> Vec { + let mut errors = Vec::new(); + for (idx, spanner) in self.spans.iter().enumerate() { + if let Err(e) = spanner.validate() { + errors.push(format!("SPAN {}: {}", idx + 1, e)); + } + } + match self.resolve_spanner_ids() { + Ok(resolved_spans) => { + if let Err(e) = self.validate_boundaries(&resolved_spans) { + errors.push(e); + } + } + Err(e) => errors.push(e), + } + for (idx, format) in self.formats.iter().enumerate() { + if let Err(e) = format.validate() { + errors.push(format!("FORMAT {}: {}", idx + 1, e)); + } + } + for (idx, summary) in self.summaries.iter().enumerate() { + if let Err(e) = summary.validate() { + errors.push(format!("SUMMARISE {}: {}", idx + 1, e)); + } + } + if let Err(e) = facet::validate_settings(&self.facet) { + errors.push(format!("FACET: {}", e)); + } + errors + } + /// Fully resolve this table's spanners for execution: settings /// validated and defaults filled, `OVER` ids folded, feature boundaries /// checked, columns checked against the real schema, and each `label` /// overlaid with any `TITLE => ...` entry. - pub fn resolve_spanners( + pub fn setup_spanners( &self, titles: &Titles, - column_names: Option<&[String]>, + column_names: &[String], ) -> Result, String> { let spans = self.resolve_spanner_ids()?; self.validate_boundaries(&spans)?; - // None (validate()'s case) skips this: no real schema to check. - if let Some(names) = column_names { - for span in &spans { - span.validate_columns(names)?; - } + for span in &spans { + span.validate_columns(column_names)?; } spans @@ -335,11 +388,22 @@ impl Format { } } - /// Validate `settings` against `FORMAT_PARAMS` and resolve each to its - /// effective value: the user's value if present, otherwise the - /// definition's default. - pub fn resolve_settings(&self) -> Result { - crate::params::resolve_parameters(&self.settings, FORMAT_PARAMS, "FORMAT setting") + /// Validate everything checkable without the query result's schema: + /// `settings` against `FORMAT_PARAMS`. + pub fn validate(&self) -> Result<(), String> { + self.validate_settings() + } + + /// Validate `settings` against `FORMAT_PARAMS`. + pub fn validate_settings(&self) -> Result<(), String> { + crate::params::validate_parameters(&self.settings, FORMAT_PARAMS, "FORMAT setting") + } + + /// Each setting's effective value: the user's value if present, + /// otherwise the `FORMAT_PARAMS` default. Assumes `settings` already + /// passes validation. + pub fn with_default_settings(&self) -> Parameters { + crate::params::with_defaults(&self.settings, FORMAT_PARAMS) } } @@ -417,30 +481,30 @@ mod tests { fn format_validate_settings_accepts_a_string_hjust() { let settings = crate::params! { "hjust" => "right" }; - assert!(format_with_settings(settings).resolve_settings().is_ok()); + assert!(format_with_settings(settings).validate_settings().is_ok()); } #[test] fn format_validate_settings_accepts_a_numeric_hjust() { let settings = crate::params! { "hjust" => 0.25 }; - assert!(format_with_settings(settings).resolve_settings().is_ok()); + assert!(format_with_settings(settings).validate_settings().is_ok()); } #[test] fn format_validate_settings_rejects_an_unrecognized_string() { let settings = crate::params! { "hjust" => "up" }; - assert!(format_with_settings(settings).resolve_settings().is_err()); + assert!(format_with_settings(settings).validate_settings().is_err()); } #[test] fn format_validate_settings_accepts_a_percent_or_pixel_width() { let settings = crate::params! { "width" => "20%" }; - assert!(format_with_settings(settings).resolve_settings().is_ok()); + assert!(format_with_settings(settings).validate_settings().is_ok()); let settings = crate::params! { "width" => "240px" }; - assert!(format_with_settings(settings).resolve_settings().is_ok()); + assert!(format_with_settings(settings).validate_settings().is_ok()); } #[test] @@ -492,6 +556,47 @@ mod tests { assert!(error.contains("cannot include stub column")); } + #[test] + fn validate_boundaries_rejects_a_summary_of_a_stub_column() { + let table = Table { + formats: vec![Format { + columns: vec!["a".to_string()], + wildcard: false, + target: Some(ColumnSection::Stub), + ..format_with_settings(Parameters::new()) + }], + summaries: vec![Summary { + operation: SummaryOperation::Stat("mean".to_string()), + columns: vec!["a".to_string()], + scope: SummaryScope::Grand, + settings: Parameters::new(), + }], + ..Table::new() + }; + + let resolved = table.resolve_spanner_ids().unwrap(); + let error = table.validate_boundaries(&resolved).unwrap_err(); + assert!(error.contains("SUMMARISE 1: cannot summarise stub column 'a'")); + } + + #[test] + fn validate_boundaries_rejects_a_summary_of_a_facet_column() { + let table = Table { + facet: Some(table_facet(&["a"])), + summaries: vec![Summary { + operation: SummaryOperation::Stat("mean".to_string()), + columns: vec!["a".to_string()], + scope: SummaryScope::Group, + settings: Parameters::new(), + }], + ..Table::new() + }; + + let resolved = table.resolve_spanner_ids().unwrap(); + let error = table.validate_boundaries(&resolved).unwrap_err(); + assert!(error.contains("SUMMARISE 1: cannot summarise facet column 'a'")); + } + fn table_facet(variables: &[&str]) -> crate::plot::facet::Facet { crate::plot::facet::Facet { layout: crate::plot::facet::FacetLayout::Wrap { diff --git a/src/table/spanner.rs b/src/table/spanner.rs index fd4f45ce4..d356f42e2 100644 --- a/src/table/spanner.rs +++ b/src/table/spanner.rs @@ -30,7 +30,8 @@ pub struct Spanner { /// `SETTING` parameters `SPAN` accepts — one static name/default/constraint /// list, mirroring how a `GeomTrait` declares `default_params()`, so -/// `Spanner::resolve_settings` doesn't hand-roll its own type checks per key. +/// `Spanner::validate_settings` doesn't hand-roll its own type checks per +/// key. const SPAN_PARAMS: &[ParamDefinition] = &[ ParamDefinition { name: "gather", @@ -47,6 +48,17 @@ const SPAN_PARAMS: &[ParamDefinition] = &[ ]; impl Spanner { + /// Validate everything checkable without the query result's schema: + /// `settings` against `SPAN_PARAMS`. + pub fn validate(&self) -> Result<(), String> { + self.validate_settings() + } + + /// Validate `settings` against `SPAN_PARAMS`. + pub fn validate_settings(&self) -> Result<(), String> { + crate::params::validate_parameters(&self.settings, SPAN_PARAMS, "SPAN setting") + } + /// Validate `settings` against `SPAN_PARAMS` and resolve each to its /// effective value: the user's value if present, otherwise the /// definition's default. @@ -127,7 +139,7 @@ fn gather_columns(columns: Vec, members: &[String]) -> Vec, members: &[String]) -> Vec, members: &[String]) -> Vec Vec { let mut levels: Vec = Vec::with_capacity(spans.len()); @@ -372,7 +384,7 @@ mod tests { } #[test] - #[should_panic(expected = "Table::resolve_spanners already validated")] + #[should_panic(expected = "Table::setup_spanners already validated")] fn gather_columns_panics_on_an_unvalidated_unknown_column() { let columns = vec![column("a", "a"), column("b", "b")]; @@ -673,10 +685,10 @@ mod tests { } #[test] - fn resolve_settings_accepts_valid_gather_and_level() { + fn validate_settings_accepts_valid_gather_and_level() { let settings = crate::params! { "gather" => false, "level" => 2.0 }; - assert!(spanner_with_settings(settings).resolve_settings().is_ok()); + assert!(spanner_with_settings(settings).validate_settings().is_ok()); } #[test] diff --git a/src/table/summary.rs b/src/table/summary.rs new file mode 100644 index 000000000..6523ea3ba --- /dev/null +++ b/src/table/summary.rs @@ -0,0 +1,734 @@ +//! Row summaries: the AST for `TABULATE SUMMARISE` clauses. + +use serde::{Deserialize, Serialize}; + +use crate::params::{DefaultParamValue, ParamConstraint, ParamDefinition, Parameters}; + +/// One `SUMMARISE` clause: an aggregate operation producing one summary row +/// per group — or a single row over all rows for `GRAND`. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct Summary { + /// The aggregate operation, verbatim as written. + pub operation: SummaryOperation, + /// Which rows the operation aggregates over. + pub scope: SummaryScope, + /// The columns to summarise, in the order written. + pub columns: Vec, + /// `SETTING` parameters for this SUMMARISE (e.g. `place => 'top'`, + /// `rowlabel => 'Average'`). + pub settings: Parameters, +} + +/// What a `SUMMARISE` clause computes per column: either one named stat, or +/// a template whose `{stat}` placeholders are each evaluated and interpolated +/// into the cell text. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum SummaryOperation { + /// A bare stat name (e.g. `mean`) — it doubles as the default row label. + /// Matching against the operation vocabulary is case-insensitive at + /// execution time. + Stat(String), + /// A template literal (e.g. `{mean} +/- {sdev}`), placeholders intact. + Template(String), +} + +impl std::fmt::Display for SummaryOperation { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + SummaryOperation::Stat(name) => write!(f, "{name}"), + SummaryOperation::Template(template) => write!(f, "'{template}'"), + } + } +} + +impl SummaryOperation { + /// The default row label: a `Stat`'s name; a `Template`'s literal text + /// with each placeholder reduced to its bare expression + /// (`{mean:num %.2f} +/- {sdev}` becomes `mean +/- sdev`). + pub(crate) fn as_label(&self) -> String { + match self { + SummaryOperation::Stat(name) => name.clone(), + // A template that reaches here unparseable keeps its raw text; + // execution parses (and errors) before building any label. + SummaryOperation::Template(template) => match parse_template(template) { + Ok(segments) => segments + .iter() + .map(|segment| match segment { + TemplateSegment::Literal(text) => text.clone(), + TemplateSegment::Stat { expr, .. } => expr.to_string(), + }) + .collect(), + Err(_) => template.clone(), + }, + } + } + + /// Validate against `SUMMARY_OPERATIONS`, case-insensitively: a `Stat` + /// directly, a `Template`'s placeholders one by one. + pub fn validate(&self) -> Result<(), String> { + let unknown = |name: &str| { + format!( + "Unknown operation '{}'. Valid operations: {}", + name, + crate::or_list_quoted(SUMMARY_OPERATIONS, '\'') + ) + }; + let known = |name: &str| { + SUMMARY_OPERATIONS + .iter() + .any(|op| name.eq_ignore_ascii_case(op)) + }; + match self { + SummaryOperation::Stat(name) if !known(name) => Err(unknown(name)), + SummaryOperation::Stat(_) => Ok(()), + SummaryOperation::Template(template) => { + for segment in parse_template(template)? { + if let TemplateSegment::Stat { expr, .. } = segment { + for name in expr.stat_names() { + if !known(name) { + return Err(unknown(name)); + } + } + } + } + Ok(()) + } + } + } +} + +/// One piece of a `SUMMARISE` template: literal text, or a `{expr:spec}` +/// placeholder whose expression is evaluated and interpolated. +#[derive(Debug, Clone)] +pub(crate) enum TemplateSegment { + /// Text copied to the cell verbatim. + Literal(String), + /// A `{expr}` or `{expr:spec}` placeholder, its zygos template + /// pre-compiled: `{:spec}`, or `{}` without a spec. The `%`-sugar is + /// already expanded (`{sd:%.1f}` compiles `{:num %.1f}`). + Stat { + expr: StatExpr, + template: zygos::Template, + }, +} + +/// An arithmetic expression over `SUMMARISE` operations, as written inside a +/// template placeholder: `mean`, `mean-sdev`, `(mean-sdev)*2`. +#[derive(Debug, Clone, PartialEq)] +pub(crate) enum StatExpr { + /// An operation name, resolved against the column at execution time. + Stat(String), + /// A numeric literal. + Number(f64), + /// `lhs op rhs`. + Binary(BinOp, Box, Box), + /// `-expr`. + Neg(Box), +} + +/// The arithmetic operators a [`StatExpr`] combines values with. +#[derive(Debug, Clone, Copy, PartialEq)] +pub(crate) enum BinOp { + Add, + Sub, + Mul, + Div, +} + +impl StatExpr { + /// Every operation name the expression references. + pub(crate) fn stat_names(&self) -> Vec<&str> { + fn collect<'a>(expr: &'a StatExpr, names: &mut Vec<&'a str>) { + match expr { + StatExpr::Stat(name) => names.push(name), + StatExpr::Number(_) => {} + StatExpr::Binary(_, lhs, rhs) => { + collect(lhs, names); + collect(rhs, names); + } + StatExpr::Neg(inner) => collect(inner, names), + } + } + let mut names = Vec::new(); + collect(self, &mut names); + names + } +} + +impl BinOp { + fn precedence(self) -> u8 { + match self { + BinOp::Add | BinOp::Sub => 0, + BinOp::Mul | BinOp::Div => 1, + } + } +} + +impl StatExpr { + /// Write the expression, parenthesizing a child binary only where its + /// grouping differs from what operator precedence would imply. + fn fmt_with( + &self, + f: &mut std::fmt::Formatter<'_>, + parent: Option<(BinOp, bool)>, + ) -> std::fmt::Result { + if let (Some((parent_op, is_rhs)), StatExpr::Binary(op, ..)) = (parent, self) { + let parenthesized = op.precedence() < parent_op.precedence() + || (is_rhs + && op.precedence() == parent_op.precedence() + && matches!(parent_op, BinOp::Sub | BinOp::Div)); + if parenthesized { + write!(f, "(")?; + } + self.fmt_with(f, None)?; + return if parenthesized { + write!(f, ")") + } else { + Ok(()) + }; + } + match self { + StatExpr::Stat(name) => write!(f, "{name}"), + StatExpr::Number(n) => write!(f, "{n}"), + StatExpr::Binary(op, lhs, rhs) => { + let symbol = match op { + BinOp::Add => "+", + BinOp::Sub => "-", + BinOp::Mul => "*", + BinOp::Div => "/", + }; + lhs.fmt_with(f, Some((*op, false)))?; + write!(f, " {symbol} ")?; + rhs.fmt_with(f, Some((*op, true))) + } + StatExpr::Neg(inner) => { + write!(f, "-")?; + match inner.as_ref() { + StatExpr::Binary(..) | StatExpr::Neg(_) => write!(f, "({inner})"), + _ => inner.fmt_with(f, None), + } + } + } + } +} + +impl std::fmt::Display for StatExpr { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + self.fmt_with(f, None) + } +} + +/// Parse a template placeholder's arithmetic expression: operation names and +/// numbers combined with `+ - * /`, parentheses and unary minus. +pub(crate) fn parse_stat_expr(source: &str) -> Result { + struct Parser<'a> { + source: &'a [u8], + pos: usize, + } + impl Parser<'_> { + fn peek(&self) -> Option { + self.source.get(self.pos).copied() + } + fn ws(&mut self) { + while matches!(self.peek(), Some(c) if c.is_ascii_whitespace()) { + self.pos += 1; + } + } + fn expr(&mut self) -> Result { + let mut lhs = self.term()?; + loop { + self.ws(); + let op = match self.peek() { + Some(b'+') => BinOp::Add, + Some(b'-') => BinOp::Sub, + _ => return Ok(lhs), + }; + self.pos += 1; + lhs = StatExpr::Binary(op, Box::new(lhs), Box::new(self.term()?)); + } + } + fn term(&mut self) -> Result { + let mut lhs = self.factor()?; + loop { + self.ws(); + let op = match self.peek() { + Some(b'*') => BinOp::Mul, + Some(b'/') => BinOp::Div, + _ => return Ok(lhs), + }; + self.pos += 1; + lhs = StatExpr::Binary(op, Box::new(lhs), Box::new(self.factor()?)); + } + } + fn factor(&mut self) -> Result { + self.ws(); + match self.peek() { + Some(b'-') => { + self.pos += 1; + Ok(StatExpr::Neg(Box::new(self.factor()?))) + } + Some(b'+') => { + self.pos += 1; + self.factor() + } + Some(b'(') => { + self.pos += 1; + let inner = self.expr()?; + self.ws(); + if self.peek() == Some(b')') { + self.pos += 1; + Ok(inner) + } else { + Err("Missing ')'".to_string()) + } + } + Some(c) if c.is_ascii_digit() || c == b'.' => self.number(), + Some(c) if c.is_ascii_alphabetic() || c == b'_' => Ok(self.ident()), + Some(c) => Err(format!("Unexpected '{}'", c as char)), + None => Err("Expected an operation name or number".to_string()), + } + } + fn number(&mut self) -> Result { + let start = self.pos; + while matches!(self.peek(), Some(c) if c.is_ascii_digit() || c == b'.') { + self.pos += 1; + } + // An exponent is taken only when it has at least one digit, so + // `1e` leaves the `e` to error as an unexpected character. + if matches!(self.peek(), Some(b'e' | b'E')) { + let mut pos = self.pos + 1; + if matches!(self.source.get(pos), Some(b'+' | b'-')) { + pos += 1; + } + if matches!(self.source.get(pos), Some(c) if c.is_ascii_digit()) { + self.pos = pos; + while matches!(self.peek(), Some(c) if c.is_ascii_digit()) { + self.pos += 1; + } + } + } + let text = std::str::from_utf8(&self.source[start..self.pos]).unwrap(); + text.parse::() + .map(StatExpr::Number) + .map_err(|_| format!("Invalid number '{text}'")) + } + fn ident(&mut self) -> StatExpr { + let start = self.pos; + while matches!(self.peek(), Some(c) if c.is_ascii_alphanumeric() || c == b'_') { + self.pos += 1; + } + let text = std::str::from_utf8(&self.source[start..self.pos]).unwrap(); + StatExpr::Stat(text.to_string()) + } + } + let mut parser = Parser { + source: source.as_bytes(), + pos: 0, + }; + let expr = parser.expr()?; + parser.ws(); + match parser.peek() { + Some(c) => Err(format!("Unexpected '{}'", c as char)), + None => Ok(expr), + } +} + +/// Split a template literal into text and placeholder segments. `{` opens a +/// placeholder and must be terminated and non-empty; `}` outside a +/// placeholder is literal text. +pub(crate) fn parse_template(template: &str) -> Result, String> { + let mut segments = Vec::new(); + let mut literal = String::new(); + let mut rest = template; + while let Some(open) = rest.find('{') { + literal.push_str(&rest[..open]); + rest = &rest[open + 1..]; + let Some(close) = rest.find('}') else { + return Err(format!("Missing '}}' in SUMMARISE template '{template}'")); + }; + let placeholder = rest[..close].trim(); + rest = &rest[close + 1..]; + if !literal.is_empty() { + segments.push(TemplateSegment::Literal(std::mem::take(&mut literal))); + } + if placeholder.is_empty() { + return Err(format!("Empty '{{}}' in SUMMARISE template '{template}'")); + } + let (name, spec) = match placeholder.split_once(':') { + Some((name, spec)) => (name.trim(), Some(spec.trim())), + None => (placeholder, None), + }; + if name.is_empty() { + return Err(format!( + "Missing operation name before ':' in SUMMARISE template '{template}'" + )); + } + // `{sd:%.1f}` is sugar for `{sd:num %.1f}`. + let source = match spec { + Some(spec) if spec.starts_with('%') => format!("{{:num {spec}}}"), + Some(spec) => format!("{{:{spec}}}"), + None => "{}".to_string(), + }; + segments.push(TemplateSegment::Stat { + expr: parse_stat_expr(name) + .map_err(|err| format!("{err} in SUMMARISE template '{{{placeholder}}}'"))?, + template: zygos::Template::parse(&source), + }); + } + literal.push_str(rest); + if !literal.is_empty() { + segments.push(TemplateSegment::Literal(literal)); + } + Ok(segments) +} + +/// Which rows a `SUMMARISE` clause aggregates over. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum SummaryScope { + /// One summary row per facet group. Without a `FACET`, all rows form a + /// single group. + #[default] + Group, + /// A single summary row over all rows. + Grand, +} + +/// Operations a `SUMMARISE` clause accepts: the plot aggregate vocabulary +/// (`AGG_NAMES`) minus the order-dependent positional ones (`first`, `last`, +/// `diff`), plus `se` and the type-free tallies `n_distinct` and `n_missing`. +pub const SUMMARY_OPERATIONS: &[&str] = &[ + "count", + "n_distinct", + "n_missing", + "sum", + "prod", + "min", + "max", + "range", + "mid", + "mean", + "geomean", + "harmean", + "rms", + "median", + "sdev", + "se", + "var", + "iqr", + "p05", + "p10", + "p25", + "p50", + "p75", + "p90", + "p95", +]; + +/// `SETTING` parameters `SUMMARISE` accepts. +const SUMMARY_PARAMS: &[ParamDefinition] = &[ + ParamDefinition { + name: "place", + default: DefaultParamValue::String("bottom"), + constraint: ParamConstraint::string_option(&["top", "bottom"]), + }, + ParamDefinition { + name: "rowlabel", + // No default: an unset rowlabel falls back to the operation verbatim. + default: DefaultParamValue::Null, + constraint: ParamConstraint::string(), + }, + ParamDefinition { + // Whether nulls make the summary null ('propagate') or are ignored + // ('drop'). + name: "missing", + default: DefaultParamValue::String("propagate"), + constraint: ParamConstraint::string_option(&["propagate", "drop"]), + }, + ParamDefinition { + // Display text for an empty cell in a summary row. + name: "blank", + default: DefaultParamValue::String("—"), + constraint: ParamConstraint::string(), + }, +]; + +impl Summary { + /// Validate everything checkable without the query result's schema: the + /// operation and `settings`. + pub fn validate(&self) -> Result<(), String> { + self.operation.validate()?; + self.validate_settings() + } + + /// Validate `settings` against `SUMMARY_PARAMS`. + pub fn validate_settings(&self) -> Result<(), String> { + crate::params::validate_parameters(&self.settings, SUMMARY_PARAMS, "SUMMARISE setting") + } + + /// Validate `settings` against `SUMMARY_PARAMS` and resolve each to its + /// effective value: the user's value if present, otherwise the + /// definition's default. + pub fn resolve_settings(&self) -> Result { + crate::params::resolve_parameters(&self.settings, SUMMARY_PARAMS, "SUMMARISE setting") + } + + /// Check this summary's columns against `off_limits`, columns claimed + /// by another feature — `context` names that feature in the error + /// (e.g. `"stub"`, `"facet"`). + pub fn validate_boundary(&self, off_limits: &[String], context: &str) -> Result<(), String> { + if let Some(name) = self.columns.iter().find(|name| off_limits.contains(name)) { + return Err(format!("cannot summarise {context} column '{name}'")); + } + + Ok(()) + } + + /// Check this clause's columns against the real query result's column + /// names. + pub fn validate_columns(&self, column_names: &[String]) -> Result<(), String> { + for column in &self.columns { + if !column_names.contains(column) { + return Err(format!( + "SUMMARISE {}: no column '{column}' in the query result", + self.operation + )); + } + } + + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn summary_with_settings(settings: Parameters) -> Summary { + Summary { + operation: SummaryOperation::Stat("mean".to_string()), + scope: SummaryScope::Group, + columns: vec!["a".to_string()], + settings, + } + } + + #[test] + fn summary_validate_settings_accepts_place_and_rowlabel() { + let settings = crate::params! { "place" => "top", "rowlabel" => "Average" }; + + assert!(summary_with_settings(settings).validate_settings().is_ok()); + } + + #[test] + fn summary_validate_settings_accepts_missing_options() { + for value in ["propagate", "drop"] { + let settings = crate::params! { "missing" => value }; + assert!(summary_with_settings(settings).validate_settings().is_ok()); + } + let settings = crate::params! { "missing" => "ignore" }; + assert!(summary_with_settings(settings).validate_settings().is_err()); + } + + #[test] + fn summary_validate_settings_rejects_a_non_string_rowlabel() { + let settings = crate::params! { "rowlabel" => 1.0 }; + + assert!(summary_with_settings(settings).validate_settings().is_err()); + } + + #[test] + fn summary_validate_settings_rejects_an_unknown_setting() { + let settings = crate::params! { "colour" => "red" }; + + assert!(summary_with_settings(settings).validate_settings().is_err()); + } + + #[test] + fn summary_operation_validate_accepts_case_insensitively() { + assert!(SummaryOperation::Stat("mean".to_string()) + .validate() + .is_ok()); + assert!(SummaryOperation::Stat("MEAN".to_string()) + .validate() + .is_ok()); + } + + #[test] + fn summary_operation_validate_rejects_unknown_and_positional() { + assert!(SummaryOperation::Stat("meen".to_string()) + .validate() + .is_err()); + assert!(SummaryOperation::Stat("first".to_string()) + .validate() + .is_err()); + } + + #[test] + fn summary_operation_validate_checks_a_templates_placeholders() { + assert!(SummaryOperation::Template("{mean} +/- {SDEV}".to_string()) + .validate() + .is_ok()); + assert!(SummaryOperation::Template("{mean} +/- {meen}".to_string()) + .validate() + .is_err()); + assert!(SummaryOperation::Template("{mean+1.96*se}".to_string()) + .validate() + .is_ok()); + assert!(SummaryOperation::Template("{mean+meen}".to_string()) + .validate() + .is_err()); + } + + #[test] + fn summary_operation_as_label_strips_a_templates_specs() { + assert_eq!( + SummaryOperation::Template("{mean:num %.2f} +/- {sdev}".to_string()).as_label(), + "mean +/- sdev" + ); + assert_eq!( + SummaryOperation::Stat("MEAN".to_string()).as_label(), + "MEAN" + ); + assert_eq!( + SummaryOperation::Template("{mean-sdev:%.1f}".to_string()).as_label(), + "mean - sdev" + ); + } + + #[test] + fn parse_template_splits_literals_and_stats() { + let segments = parse_template("{mean} +/- {sdev:num %.3f} (n={count})").unwrap(); + let stat = |index: usize| match &segments[index] { + TemplateSegment::Stat { expr, template } => (expr.to_string(), template.source()), + TemplateSegment::Literal(_) => panic!("segment {index} is a literal"), + }; + let literal = |index: usize| match &segments[index] { + TemplateSegment::Literal(text) => text.as_str(), + TemplateSegment::Stat { .. } => panic!("segment {index} is a stat"), + }; + + assert_eq!(segments.len(), 6); + assert_eq!(stat(0), ("mean".to_string(), "{}")); + assert_eq!(literal(1), " +/- "); + assert_eq!(stat(2), ("sdev".to_string(), "{:num %.3f}")); + assert_eq!(literal(3), " (n="); + assert_eq!(stat(4), ("count".to_string(), "{}")); + assert_eq!(literal(5), ")"); + } + + #[test] + fn parse_template_expands_the_printf_sugar() { + let segments = parse_template("{sd:%.1f}").unwrap(); + match &segments[0] { + TemplateSegment::Stat { expr, template } => { + assert_eq!(expr.to_string(), "sd"); + assert_eq!(template.source(), "{:num %.1f}"); + } + TemplateSegment::Literal(_) => panic!("expected a stat segment"), + } + } + + #[test] + fn parse_template_treats_a_stray_close_brace_as_literal() { + let segments = parse_template("a } b").unwrap(); + assert_eq!(segments.len(), 1); + match &segments[0] { + TemplateSegment::Literal(text) => assert_eq!(text, "a } b"), + TemplateSegment::Stat { .. } => panic!("expected a literal segment"), + } + } + + #[test] + fn parse_template_rejects_unterminated_and_empty_placeholders() { + assert!(parse_template("{mean").is_err()); + assert!(parse_template("{}").is_err()); + assert!(parse_template("{:num}").is_err()); + } + + #[test] + fn parse_stat_expr_applies_precedence_and_parentheses() { + // `*` binds tighter than `-`. + assert_eq!( + parse_stat_expr("mean-sdev*2").unwrap(), + StatExpr::Binary( + BinOp::Sub, + Box::new(StatExpr::Stat("mean".to_string())), + Box::new(StatExpr::Binary( + BinOp::Mul, + Box::new(StatExpr::Stat("sdev".to_string())), + Box::new(StatExpr::Number(2.0)), + )), + ) + ); + assert_eq!( + parse_stat_expr("(mean - sdev) * 2").unwrap(), + StatExpr::Binary( + BinOp::Mul, + Box::new(StatExpr::Binary( + BinOp::Sub, + Box::new(StatExpr::Stat("mean".to_string())), + Box::new(StatExpr::Stat("sdev".to_string())), + )), + Box::new(StatExpr::Number(2.0)), + ) + ); + } + + #[test] + fn parse_stat_expr_handles_unary_minus_and_decimals() { + assert_eq!( + parse_stat_expr("-mean").unwrap(), + StatExpr::Neg(Box::new(StatExpr::Stat("mean".to_string()))) + ); + assert_eq!( + parse_stat_expr("mean+.5").unwrap(), + StatExpr::Binary( + BinOp::Add, + Box::new(StatExpr::Stat("mean".to_string())), + Box::new(StatExpr::Number(0.5)), + ) + ); + } + + #[test] + fn parse_stat_expr_handles_unary_plus_and_scientific_notation() { + assert_eq!( + parse_stat_expr("+mean").unwrap(), + StatExpr::Stat("mean".to_string()) + ); + assert_eq!( + parse_stat_expr("mean*1.5e-2").unwrap(), + StatExpr::Binary( + BinOp::Mul, + Box::new(StatExpr::Stat("mean".to_string())), + Box::new(StatExpr::Number(0.015)), + ) + ); + assert_eq!(parse_stat_expr("2E3").unwrap(), StatExpr::Number(2000.0)); + // No digit after `e`: the `e` is not part of the number. + assert!(parse_stat_expr("1e").is_err()); + } + + #[test] + fn parse_stat_expr_rejects_malformed_input() { + assert!(parse_stat_expr("mean-").is_err()); + assert!(parse_stat_expr("(mean").is_err()); + assert!(parse_stat_expr("mean sdev").is_err()); + assert!(parse_stat_expr("mean % sdev").is_err()); + assert!(parse_stat_expr("1.2.3").is_err()); + } + + #[test] + fn stat_expr_display_keeps_grouping() { + assert_eq!( + parse_stat_expr("(mean - sdev) * 2").unwrap().to_string(), + "(mean - sdev) * 2" + ); + assert_eq!( + parse_stat_expr("mean-sdev*2").unwrap().to_string(), + "mean - sdev * 2" + ); + } +} diff --git a/src/validate.rs b/src/validate.rs index cdf4131a4..04c6562b8 100644 --- a/src/validate.rs +++ b/src/validate.rs @@ -56,6 +56,21 @@ impl Validated { pub fn warnings(&self) -> &[ValidationWarning] { &self.warnings } + + /// The validation errors joined into one message, when the query is invalid. + pub fn invalid_reason(&self) -> Option { + if self.valid { + None + } else { + Some( + self.errors + .iter() + .map(|e| e.message.as_str()) + .collect::>() + .join("\n"), + ) + } + } } /// A validation error (fatal). @@ -316,42 +331,14 @@ pub fn validate(query: &str) -> Result { }); } - // Validate each SPAN's SETTING parameters (unknown key, or wrong shape - // for a recognized one) — mirrors the per-layer settings validation - // above. + // Validate the table's clauses (settings, spanner ids, boundaries, + // operations) — mirrors the per-layer settings validation above. if let Some(table) = first_table { - for (idx, spanner) in table.spans.iter().enumerate() { - if let Err(e) = spanner.resolve_settings() { - errors.push(ValidationError { - message: format!("SPAN {}: {}", idx + 1, e), - location: None, - }); - } - } - - match table.resolve_spanner_ids() { - Ok(resolved_spans) => { - if let Err(e) = table.validate_boundaries(&resolved_spans) { - errors.push(ValidationError { - message: e, - location: None, - }); - } - } - Err(e) => errors.push(ValidationError { - message: e, + for message in table.validate() { + errors.push(ValidationError { + message, location: None, - }), - } - - // Validate each FORMAT's SETTING parameters the same way. - for (idx, format) in table.formats.iter().enumerate() { - if let Err(e) = format.resolve_settings() { - errors.push(ValidationError { - message: format!("FORMAT {}: {}", idx + 1, e), - location: None, - }); - } + }); } } @@ -429,6 +416,68 @@ mod tests { assert!(!validated.valid()); } + #[test] + fn test_validate_table_facet_rejects_an_unknown_setting() { + let validated = validate("TABULATE * FROM sales FACET region SETTING bogus => 1").unwrap(); + assert!(!validated.valid()); + assert!(validated.errors()[0].message.starts_with("FACET: ")); + } + + #[test] + fn test_validate_summarise_rejects_an_unknown_operation() { + let validated = validate("TABULATE * FROM sales SUMMARISE meen OF foo").unwrap(); + assert!(!validated.valid()); + assert!(validated.errors()[0] + .message + .contains("SUMMARISE 1: Unknown operation 'meen'")); + } + + #[test] + fn test_validate_summarise_accepts_operations_case_insensitively() { + let validated = validate("TABULATE * FROM sales SUMMARISE MEAN OF foo").unwrap(); + assert!(validated.valid()); + } + + #[test] + fn test_validate_summarise_rejects_positional_operations() { + let validated = validate("TABULATE * FROM sales SUMMARISE first OF foo").unwrap(); + assert!(!validated.valid()); + } + + #[test] + fn test_validate_summarise_accepts_a_template_with_known_stats() { + let validated = + validate("TABULATE * FROM sales SUMMARISE '{mean:num %.2f} +/- {SDEV}' OF foo") + .unwrap(); + assert!(validated.valid()); + } + + #[test] + fn test_validate_summarise_rejects_a_template_with_an_unknown_stat() { + let validated = + validate("TABULATE * FROM sales SUMMARISE '{mean} of {meen}' OF foo").unwrap(); + assert!(!validated.valid()); + assert!(validated.errors()[0] + .message + .contains("SUMMARISE 1: Unknown operation 'meen'")); + } + + #[test] + fn test_validate_summarise_rejects_a_malformed_template() { + let validated = validate("TABULATE * FROM sales SUMMARISE '{mean' OF foo").unwrap(); + assert!(!validated.valid()); + assert!(validated.errors()[0].message.contains("Missing '}'")); + } + + #[test] + fn test_validate_summarise_rejects_a_bad_setting() { + let validated = + validate("TABULATE * FROM sales SUMMARISE mean OF foo SETTING place => 'middle'") + .unwrap(); + assert!(!validated.valid()); + assert!(validated.errors()[0].message.contains("SUMMARISE 1:")); + } + #[test] fn test_validate_tabulate_from_is_valid() { // A TABULATE FROM has a data source (extract_sql injects diff --git a/src/writer/html.rs b/src/writer/html.rs index e83d05180..165ccd647 100644 --- a/src/writer/html.rs +++ b/src/writer/html.rs @@ -389,6 +389,53 @@ fn class_declarations(class: TableClass) -> &'static [(&'static str, &'static st ("border-top-width", "2px"), ("border-top-color", "#D3D3D3"), ], + TableClass::SummaryRow => &[], + TableClass::GroupSummary => &[ + ("color", "#333333"), + ("background-color", "#FFFFFF"), + ("text-transform", "inherit"), + ("padding-top", "8px"), + ("padding-bottom", "8px"), + ("padding-left", "5px"), + ("padding-right", "5px"), + ], + TableClass::SummaryFirst => &[ + ("border-top-style", "solid"), + ("border-top-width", "2px"), + ("border-top-color", "#D3D3D3"), + ], + TableClass::SummaryLast => &[ + ("padding-top", "8px"), + ("padding-bottom", "8px"), + ("padding-left", "5px"), + ("padding-right", "5px"), + ("border-bottom-style", "solid"), + ("border-bottom-width", "2px"), + ("border-bottom-color", "#D3D3D3"), + ], + TableClass::GrandSummary => &[ + ("color", "#333333"), + ("background-color", "#FFFFFF"), + ("text-transform", "inherit"), + ("padding-top", "8px"), + ("padding-bottom", "8px"), + ("padding-left", "5px"), + ("padding-right", "5px"), + ], + TableClass::GrandSummaryFirst => &[ + ("padding-top", "8px"), + ("padding-bottom", "8px"), + ("padding-left", "5px"), + ("padding-right", "5px"), + ("border-top-style", "double"), + ("border-top-width", "6px"), + ("border-top-color", "#D3D3D3"), + ], + TableClass::GrandSummaryLast => &[ + ("border-bottom-style", "double"), + ("border-bottom-width", "6px"), + ("border-bottom-color", "#D3D3D3"), + ], TableClass::AlignLeft => &[("text-align", "left")], TableClass::AlignCenter => &[("text-align", "center")], TableClass::AlignRight => &[ @@ -538,9 +585,10 @@ fn header_scope(kind: TableCellKind) -> Option<&'static str> { match kind { TableCellKind::ColumnLabel | TableCellKind::StubHead => Some("col"), TableCellKind::Spanner => Some("colgroup"), - TableCellKind::StubRowLabel => Some("row"), + TableCellKind::StubRowLabel | TableCellKind::SummaryLabel => Some("row"), TableCellKind::GroupHeading => Some("rowgroup"), TableCellKind::Body + | TableCellKind::SummaryValue | TableCellKind::Title | TableCellKind::Subtitle | TableCellKind::Caption diff --git a/tree-sitter-ggsql/grammar.js b/tree-sitter-ggsql/grammar.js index b6db1394a..3a59836ac 100644 --- a/tree-sitter-ggsql/grammar.js +++ b/tree-sitter-ggsql/grammar.js @@ -694,6 +694,7 @@ module.exports = grammar({ $.span_clause, $.format_clause, $.facet_clause, + $.summarise_clause, ), // FORMAT — configures cell formatting for a group of columns. Multiple @@ -718,6 +719,25 @@ module.exports = grammar({ caseInsensitive('STUB') // row-label column(s) ), + // SUMMARISE — adds aggregate rows to the table. One clause per operation; + // clauses repeat like FORMAT, each contributing its own summary row(s). + // GROUP (default) summarises within each facet group, GRAND over all rows. + // The operation is a plain identifier (a stat name) or a string template + // with {stat} placeholders; validity is checked downstream. + summarise_clause: $ => seq( + choice(caseInsensitive('SUMMARISE'), caseInsensitive('SUMMARIZE')), + optional(field('scope', $.summarise_scope)), + field('operation', choice($.identifier, $.string)), + caseInsensitive('OF'), + $.column_list, + optional($.setting_clause) + ), + + summarise_scope: $ => choice( + caseInsensitive('GROUP'), + caseInsensitive('GRAND') + ), + // SPAN — groups columns under one spanner cell. Multiple spanners repeat // the whole clause (SPAN ... SPAN ...), the same model DRAW/SCALE use for // more than one instance — not a comma list inside one SPAN. Two forms, diff --git a/tree-sitter-ggsql/queries/highlights.scm b/tree-sitter-ggsql/queries/highlights.scm index 845e5e01d..6945cfb20 100644 --- a/tree-sitter-ggsql/queries/highlights.scm +++ b/tree-sitter-ggsql/queries/highlights.scm @@ -109,6 +109,10 @@ (project_property_name) @property (title_type) @property +; SUMMARISE clause: operation name and GROUP/GRAND scope +(summarise_clause operation: (identifier) @function.builtin) +(summarise_scope) @keyword + ; Operators "=" @operator "!=" @operator diff --git a/tree-sitter-ggsql/test/corpus/basic.txt b/tree-sitter-ggsql/test/corpus/basic.txt index a0c4fd200..e0b038cc0 100644 --- a/tree-sitter-ggsql/test/corpus/basic.txt +++ b/tree-sitter-ggsql/test/corpus/basic.txt @@ -5094,3 +5094,120 @@ TABULATE * FROM sales FORMAT `body`, x (quoted_identifier)) (identifier (bare_identifier))))))) + +================================================================================ +TABULATE SUMMARISE clause +================================================================================ + +TABULATE * FROM sales SUMMARISE mean OF foo, bar + +-------------------------------------------------------------------------------- + +(query + (tabulate_statement + (tabulate_keyword) + (column_selection + (mapping_list + (mapping_element + (wildcard_mapping)))) + (single_source_from + source: (qualified_name + (identifier + (bare_identifier)))) + (tab_clause + (summarise_clause + operation: (identifier + (bare_identifier)) + (column_list + (identifier + (bare_identifier)) + (identifier + (bare_identifier))))))) + +================================================================================ +TABULATE SUMMARISE clause with GRAND scope and SETTING +================================================================================ + +TABULATE * FROM sales SUMMARISE GRAND sdev OF foo SETTING place => 'top' + +-------------------------------------------------------------------------------- + +(query + (tabulate_statement + (tabulate_keyword) + (column_selection + (mapping_list + (mapping_element + (wildcard_mapping)))) + (single_source_from + source: (qualified_name + (identifier + (bare_identifier)))) + (tab_clause + (summarise_clause + scope: (summarise_scope) + operation: (identifier + (bare_identifier)) + (column_list + (identifier + (bare_identifier))) + (setting_clause + (parameter_assignment + name: (parameter_name + (identifier + (bare_identifier))) + value: (parameter_value + (string)))))))) + +================================================================================ +TABULATE SUMMARISE template operation +================================================================================ + +TABULATE * FROM sales SUMMARISE '{mean} +/- {sdev}' OF foo + +-------------------------------------------------------------------------------- + +(query + (tabulate_statement + (tabulate_keyword) + (column_selection + (mapping_list + (mapping_element + (wildcard_mapping)))) + (single_source_from + source: (qualified_name + (identifier + (bare_identifier)))) + (tab_clause + (summarise_clause + operation: (string) + (column_list + (identifier + (bare_identifier))))))) + +================================================================================ +TABULATE SUMMARIZE spelling alias +================================================================================ + +TABULATE * FROM sales SUMMARIZE median OF foo + +-------------------------------------------------------------------------------- + +(query + (tabulate_statement + (tabulate_keyword) + (column_selection + (mapping_list + (mapping_element + (wildcard_mapping)))) + (single_source_from + source: (qualified_name + (identifier + (bare_identifier)))) + (tab_clause + (summarise_clause + operation: (identifier + (bare_identifier)) + (column_list + (identifier + (bare_identifier)))))))