Skip to content

Calculated measures

A calculated measure is derived after aggregation — a formula over the values a group already rolled up (margin = (revenue - cost) / revenue), not a fresh aggregation of the source rows. That distinction matters: revenue and cost are summed per group by the engine, then the ratio is computed on those subtotals — never a mean-of-means. The engine does the math; the frontend does zero.

from dash import Dash
from dash_tensor_grid import TensorGrid, build_grid
payload = build_grid(sales, {
"rows": ["region"],
"measures": {"revenue": "sum", "cost": "sum"}, # true aggregations
"calculated": {"margin": "(revenue - cost) / revenue"}, # post-aggregation
"formats": {"revenue": "currency:USD", "cost": "currency:USD", "margin": "percentage:1"},
"grand_total": True,
})
app = Dash(__name__)
app.layout = TensorGrid(
id="grid",
row_data=payload["row_data"],
column_defs=payload["column_defs"],
)
  • Calculated vs. aggregation. A measures entry aggregates raw rows (sum, mean, …); a calculated entry runs a formula over the already-aggregated measures of each group. Keep ratios, margins, and weighted averages in calculated — summing a ratio column would be wrong.
  • The formula reads sibling measures by name (revenue, cost), plus context values like _total_ and _parent_ where available. Full operator / function reference: formula DSL.
  • Same string, everywhere. The expression parses identically in the Polars engine (Dash) and the parity-verified @tensorgrid/core port (adapters), so a calculated measure renders the same value in every framework.
  • In Dash you can also tag the form explicitly — {"dsl": "..."} (safe), {"sql": "..."} (a true aggregation), or {"python": "pkg:fn"} (runs code, needs allow_code=True). See the config schema.
  • Just rolling numbers up? Use a plain aggregation instead.