Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

improvement: experimental backend aggregations in table charts (#5704)

Shahmir Varqha7eaa8928f31c
diff --git a/frontend/src/components/app-config/user-config-form.tsx b/frontend/src/components/app-config/user-config-form.tsx
index ce6457cf6e..8715db8a75 100644
--- a/frontend/src/components/app-config/user-config-form.tsx
+++ b/frontend/src/components/app-config/user-config-form.tsx
@@ -1645,6 +1645,7 @@ export const UserConfigForm: React.FC = () => {
/>
</FormControl>
</FormItem>
+
<FormDescription>
Enable experimental real-time collaboration. This change
requires a page refresh to take effect.
@@ -1669,6 +1670,10 @@ export const UserConfigForm: React.FC = () => {
/>
</FormControl>
</FormItem>
+ <IsOverridden
+ userConfig={config}
+ name="experimental.performant_table_charts"
+ />
<FormDescription>
Enable experimental table charts which are computed on the
backend.
diff --git a/frontend/src/components/data-table/__tests__/__snapshots__/chart-spec-model.test.ts.snap b/frontend/src/components/data-table/__tests__/__snapshots__/chart-spec-model.test.ts.snap
index b526d96379..e77110bc3c 100644
--- a/frontend/src/components/data-table/__tests__/__snapshots__/chart-spec-model.test.ts.snap
+++ b/frontend/src/components/data-table/__tests__/__snapshots__/chart-spec-model.test.ts.snap
@@ -135,6 +135,7 @@ exports[`ColumnChartSpecModel > should expect bin values to be used for number a
},
},
"data": {
+ "name": "bin_values",
"values": [
{
"bin_end": 10,
@@ -148,7 +149,7 @@ exports[`ColumnChartSpecModel > should expect bin values to be used for number a
},
],
},
- "height": 100,
+ "height": 30,
"layer": [
{
"encoding": {
@@ -188,6 +189,7 @@ exports[`ColumnChartSpecModel > should expect bin values to be used for number a
{
"name": "hover",
"select": {
+ "clear": "mouseout",
"on": "mouseover",
"type": "point",
},
@@ -248,6 +250,462 @@ exports[`ColumnChartSpecModel > should expect bin values to be used for number a
],
},
],
+ "width": 70,
+}
+`;
+
+exports[`ColumnChartSpecModel > should handle boolean stats when feat flag is true 1`] = `
+{
+ "background": "transparent",
+ "config": {
+ "axis": {
+ "domain": false,
+ },
+ "view": {
+ "stroke": "transparent",
+ },
+ },
+ "data": {
+ "name": "boolean_values",
+ "values": [
+ {
+ "count": 5,
+ "value": "true",
+ },
+ {
+ "count": 5,
+ "value": "false",
+ },
+ {
+ "count": 10,
+ "value": "null",
+ },
+ ],
+ },
+ "encoding": {
+ "color": {
+ "field": "value",
+ "legend": null,
+ "scale": {
+ "domain": [
+ "true",
+ "false",
+ "null",
+ ],
+ "range": [
+ "#027864",
+ "#027864",
+ "#cc4e00",
+ ],
+ },
+ "type": "nominal",
+ },
+ "tooltip": [
+ {
+ "field": "value",
+ "title": "boolean",
+ "type": "nominal",
+ },
+ {
+ "field": "count_with_percent",
+ "title": "Count",
+ "type": "nominal",
+ },
+ ],
+ "x": {
+ "axis": null,
+ "field": "count",
+ "scale": {
+ "type": "linear",
+ },
+ "type": "quantitative",
+ },
+ "y": {
+ "axis": {
+ "labelColor": "#8b8d98",
+ "labelExpr": "datum.label === 'true' || datum.label === 'True' ? 'True' : datum.label === 'false' || datum.label === 'False' ? 'False' : 'Null'",
+ "tickWidth": 0,
+ "title": null,
+ },
+ "field": "value",
+ "scale": {
+ "paddingInner": 1,
+ },
+ "sort": [
+ "true",
+ "false",
+ "null",
+ ],
+ "type": "nominal",
+ },
+ },
+ "height": 100,
+ "layer": [
+ {
+ "mark": {
+ "color": "#027864",
+ "height": 11,
+ "type": "bar",
+ },
+ },
+ {
+ "encoding": {
+ "text": {
+ "field": "count",
+ "format": ",d",
+ "type": "quantitative",
+ },
+ },
+ "mark": {
+ "align": "left",
+ "baseline": "middle",
+ "color": "#8b8d98",
+ "dx": 3,
+ "type": "text",
+ },
+ },
+ ],
+ "mark": {
+ "color": "#027864",
+ "type": "bar",
+ },
+ "transform": [
+ {
+ "as": "count_with_percent",
+ "calculate": "format(datum.count, ',d') + ' (' + format(datum.count / 20 * 100, '.1f') + '%)'",
+ },
+ ],
+}
+`;
+
+exports[`ColumnChartSpecModel > should handle datetime bin values when feat flag is true 1`] = `
+{
+ "background": "transparent",
+ "config": {
+ "axis": {
+ "domain": false,
+ },
+ "concat": {
+ "spacing": 0,
+ },
+ "view": {
+ "stroke": "transparent",
+ },
+ },
+ "data": {
+ "name": "bin_values",
+ "values": [
+ {
+ "bin_end": "2023-01-02",
+ "bin_start": "2023-01-01",
+ "count": 10,
+ },
+ {
+ "bin_end": "2023-01-03",
+ "bin_start": "2023-01-02",
+ "count": 20,
+ },
+ {
+ "bin_end": null,
+ "bin_start": null,
+ "count": 10,
+ },
+ ],
+ },
+ "hconcat": [
+ {
+ "height": 30,
+ "layer": [
+ {
+ "encoding": {
+ "x": {
+ "axis": null,
+ "field": "bin_start",
+ "type": "nominal",
+ },
+ "y": {
+ "axis": null,
+ "field": "count",
+ "type": "quantitative",
+ },
+ },
+ "mark": {
+ "color": "#cc4e00",
+ "type": "bar",
+ },
+ },
+ {
+ "encoding": {
+ "tooltip": [
+ {
+ "field": "count",
+ "format": ",d",
+ "title": "nulls",
+ "type": "quantitative",
+ },
+ ],
+ "x": {
+ "axis": null,
+ "field": "bin_start",
+ "type": "nominal",
+ },
+ "y": {
+ "aggregate": "max",
+ "axis": null,
+ "type": "quantitative",
+ },
+ },
+ "mark": {
+ "opacity": 0,
+ "type": "bar",
+ },
+ },
+ ],
+ "transform": [
+ {
+ "filter": "datum['bin_start'] === null && datum['bin_end'] === null",
+ },
+ ],
+ "width": 5,
+ },
+ {
+ "height": 30,
+ "layer": [
+ {
+ "encoding": {
+ "strokeWidth": {
+ "condition": {
+ "empty": false,
+ "param": "hover",
+ "value": 0.5,
+ },
+ "value": 0,
+ },
+ "x": {
+ "axis": null,
+ "bin": {
+ "binned": true,
+ "step": 2,
+ },
+ "field": "bin_start",
+ "type": "temporal",
+ },
+ "x2": {
+ "axis": null,
+ "field": "bin_end",
+ "type": "temporal",
+ },
+ "y": {
+ "axis": null,
+ "field": "count",
+ "type": "quantitative",
+ },
+ },
+ "mark": {
+ "color": "#027864",
+ "stroke": "#027864",
+ "strokeWidth": 0,
+ "type": "bar",
+ },
+ "params": [
+ {
+ "name": "hover",
+ "select": {
+ "clear": "mouseout",
+ "on": "mouseover",
+ "type": "point",
+ },
+ },
+ ],
+ },
+ {
+ "encoding": {
+ "tooltip": [
+ {
+ "field": "bin_start",
+ "timeUnit": "yearmonthdate",
+ "title": "datetime (start)",
+ "type": "temporal",
+ },
+ {
+ "field": "bin_end",
+ "timeUnit": "yearmonthdate",
+ "title": "datetime (end)",
+ "type": "temporal",
+ },
+ {
+ "field": "count",
+ "format": ",d",
+ "title": "Count",
+ "type": "quantitative",
+ },
+ ],
+ "x": {
+ "axis": null,
+ "bin": {
+ "binned": true,
+ "step": 2,
+ },
+ "field": "bin_start",
+ "type": "temporal",
+ },
+ "x2": {
+ "axis": null,
+ "bin": {
+ "binned": true,
+ "step": 2,
+ },
+ "field": "bin_end",
+ "type": "temporal",
+ },
+ "y": {
+ "aggregate": "max",
+ "axis": null,
+ "type": "quantitative",
+ },
+ },
+ "mark": {
+ "opacity": 0,
+ "type": "bar",
+ },
+ },
+ ],
+ "width": 70,
+ },
+ ],
+ "height": 100,
+ "resolve": {
+ "scale": {
+ "y": "shared",
+ },
+ },
+}
+`;
+
+exports[`ColumnChartSpecModel > should handle string value counts when feat flag is true 1`] = `
+{
+ "background": "transparent",
+ "config": {
+ "axis": {
+ "domain": false,
+ },
+ "view": {
+ "stroke": "transparent",
+ },
+ },
+ "data": {
+ "name": "value_counts",
+ "values": [
+ {
+ "count": 10,
+ "proportion": 0.25,
+ "value": "A",
+ "xEnd": 10,
+ "xMid": 5,
+ "xStart": 0,
+ },
+ {
+ "count": 30,
+ "proportion": 0.75,
+ "value": "B",
+ "xEnd": 40,
+ "xMid": 25,
+ "xStart": 10,
+ },
+ ],
+ },
+ "height": 100,
+ "layer": [
+ {
+ "encoding": {
+ "color": {
+ "condition": [
+ {
+ "param": "hover_bar",
+ "value": "#027864",
+ },
+ {
+ "test": "datum.value == "None" || datum.value == "null"",
+ "value": "#cc4e00",
+ },
+ ],
+ "legend": null,
+ "value": "#4cbba5",
+ },
+ "tooltip": [
+ {
+ "field": "value",
+ "title": "string",
+ "type": "nominal",
+ },
+ {
+ "field": "count_with_percent",
+ "title": "Count",
+ "type": "nominal",
+ },
+ ],
+ "x": {
+ "axis": null,
+ "field": "xStart",
+ "type": "quantitative",
+ },
+ "x2": {
+ "field": "xEnd",
+ "type": "quantitative",
+ },
+ },
+ "mark": {
+ "type": "bar",
+ },
+ "params": [
+ {
+ "name": "hover_bar",
+ "select": {
+ "clear": "mouseout",
+ "on": "mouseover",
+ "type": "point",
+ },
+ },
+ ],
+ "transform": [
+ {
+ "as": "count_with_percent",
+ "calculate": "format(datum.count, ',d') + ' (' + format(datum.count / 40 * 100, '.1f') + '%)'",
+ },
+ ],
+ },
+ {
+ "encoding": {
+ "text": {
+ "field": "clipped_text",
+ },
+ "x": {
+ "axis": null,
+ "field": "xMid",
+ "type": "quantitative",
+ },
+ },
+ "mark": {
+ "clip": true,
+ "color": "white",
+ "ellipsis": " ",
+ "fontSize": 8.5,
+ "type": "text",
+ },
+ "transform": [
+ {
+ "as": "clipped_text",
+ "calculate": "datum.proportion > 0.5 ? slice(datum.value, 0, 8) : datum.proportion > 0.2 ? slice(datum.value, 0, 3) : datum.proportion > 0.1 ? slice(datum.value, 0, 1) : ''",
+ },
+ ],
+ },
+ ],
+ "transform": [
+ {
+ "as": "percent",
+ "calculate": "datum.count / 40",
+ },
+ ],
}
`;
diff --git a/frontend/src/components/data-table/__tests__/chart-spec-model.test.ts b/frontend/src/components/data-table/__tests__/chart-spec-model.test.ts
index be8fa25470..695f24f8e3 100644
--- a/frontend/src/components/data-table/__tests__/chart-spec-model.test.ts
+++ b/frontend/src/components/data-table/__tests__/chart-spec-model.test.ts
@@ -1,11 +1,12 @@
/* Copyright 2024 Marimo. All rights reserved. */
import { describe, expect, it, vi } from "vitest";
-import { ColumnChartSpecModel } from "../chart-spec-model";
+import { ColumnChartSpecModel } from "../column-summary/chart-spec-model";
import type {
BinValues,
ColumnHeaderStats,
ColumnName,
FieldTypes,
+ ValueCounts,
} from "../types";
// Mock the runtime config
@@ -26,13 +27,15 @@ describe("ColumnChartSpecModel", () => {
integer: "integer",
boolean: "boolean",
string: "string",
+ datetime: "datetime",
};
- const mockStats: Record<ColumnName, ColumnHeaderStats> = {
+ const mockStats: Record<ColumnName, Partial<ColumnHeaderStats>> = {
date: { min: "2023-01-01", max: "2023-12-31" },
number: { min: 0, max: 100 },
integer: { min: 1, max: 10 },
- boolean: { true: 5, false: 5 },
+ boolean: { true: 5, false: 5, nulls: 10 },
string: { unique: 20 },
+ datetime: { nulls: 10 },
};
const mockBinValues: Record<ColumnName, BinValues> = {
number: [
@@ -43,6 +46,16 @@ describe("ColumnChartSpecModel", () => {
{ bin_start: 0, bin_end: 10, count: 10 },
{ bin_start: 10, bin_end: 20, count: 20 },
],
+ datetime: [
+ { bin_start: "2023-01-01", bin_end: "2023-01-02", count: 10 },
+ { bin_start: "2023-01-02", bin_end: "2023-01-03", count: 20 },
+ ],
+ };
+ const mockValueCounts: Record<ColumnName, ValueCounts> = {
+ string: [
+ { value: "A", count: 10 },
+ { value: "B", count: 30 },
+ ],
};
it("should create an instance", () => {
@@ -51,6 +64,7 @@ describe("ColumnChartSpecModel", () => {
mockFieldTypes,
mockStats,
mockBinValues,
+ mockValueCounts,
{ includeCharts: true },
);
expect(model).toBeInstanceOf(ColumnChartSpecModel);
@@ -67,6 +81,7 @@ describe("ColumnChartSpecModel", () => {
mockFieldTypes,
mockStats,
mockBinValues,
+ mockValueCounts,
{ includeCharts: true },
);
const dateSummary = model.getHeaderSummary("date");
@@ -81,6 +96,7 @@ describe("ColumnChartSpecModel", () => {
mockFieldTypes,
mockStats,
mockBinValues,
+ mockValueCounts,
{ includeCharts: false },
);
const numberSummary = model.getHeaderSummary("number");
@@ -95,6 +111,7 @@ describe("ColumnChartSpecModel", () => {
mockFieldTypes,
mockStats,
mockBinValues,
+ mockValueCounts,
{ includeCharts: true },
);
const stringSummary = model.getHeaderSummary("string");
@@ -105,7 +122,7 @@ describe("ColumnChartSpecModel", () => {
const specialFieldTypes: FieldTypes = {
"column.with[special:chars]": "time",
};
- const specialStats: Record<ColumnName, ColumnHeaderStats> = {
+ const specialStats: Record<ColumnName, Partial<ColumnHeaderStats>> = {
"column.with[special:chars]": { min: "2023-01-01", max: "2023-12-31" },
};
const model = new ColumnChartSpecModel(
@@ -113,6 +130,7 @@ describe("ColumnChartSpecModel", () => {
specialFieldTypes,
specialStats,
mockBinValues,
+ mockValueCounts,
{ includeCharts: true },
);
const summary = model.getHeaderSummary("column.with[special:chars]");
@@ -129,6 +147,7 @@ describe("ColumnChartSpecModel", () => {
mockFieldTypes,
mockStats,
mockBinValues,
+ mockValueCounts,
{ includeCharts: true, usePreComputedValues: true },
);
const summary = model.getHeaderSummary("number");
@@ -151,6 +170,97 @@ describe("ColumnChartSpecModel", () => {
expect(summary2.spec?.data?.values).toEqual(mockBinValues.integer);
});
+ it("should handle datetime bin values when feat flag is true", () => {
+ const model = new ColumnChartSpecModel(
+ mockData,
+ mockFieldTypes,
+ mockStats,
+ mockBinValues,
+ mockValueCounts,
+ { includeCharts: true, usePreComputedValues: true },
+ );
+
+ const summary = model.getHeaderSummary("datetime");
+ expect(summary.spec).toBeDefined();
+ // @ts-expect-error data.values should be available
+ expect(summary.spec?.data?.values).toEqual(mockBinValues.datetime);
+
+ // Expect hconcat since there are nulls
+ // @ts-expect-error hconcat should be available
+ expect(summary.spec?.hconcat).toBeDefined();
+ expect(summary.spec).toMatchSnapshot();
+
+ // Test again without the nulls
+ const mockStats2 = {
+ ...mockStats,
+ datetime: { min: "2023-01-01", max: "2023-12-31" },
+ };
+ const model2 = new ColumnChartSpecModel(
+ mockData,
+ mockFieldTypes,
+ mockStats2,
+ mockBinValues,
+ mockValueCounts,
+ { includeCharts: true, usePreComputedValues: true },
+ );
+ const summary2 = model2.getHeaderSummary("datetime");
+ expect(summary2.spec).toBeDefined();
+
+ // No hconcat since there are no nulls
+ // @ts-expect-error hconcat should be available
+ expect(summary2.spec?.hconcat).toBeUndefined();
+ });
+
+ it("should handle boolean stats when feat flag is true", () => {
+ const model = new ColumnChartSpecModel(
+ mockData,
+ mockFieldTypes,
+ mockStats,
+ mockBinValues,
+ mockValueCounts,
+ { includeCharts: true, usePreComputedValues: true },
+ );
+ const summary = model.getHeaderSummary("boolean");
+ expect(summary.spec).toBeDefined();
+ // @ts-expect-error data.values should be available
+ expect(summary.spec?.data?.values).toEqual([
+ { value: "true", count: 5 },
+ { value: "false", count: 5 },
+ { value: "null", count: 10 },
+ ]);
+
+ // Snapshot
+ expect(summary.spec).toMatchSnapshot();
+ });
+
+ it("should handle string value counts when feat flag is true", () => {
+ const model = new ColumnChartSpecModel(
+ mockData,
+ mockFieldTypes,
+ mockStats,
+ mockBinValues,
+ mockValueCounts,
+ { includeCharts: true, usePreComputedValues: true },
+ );
+ const summary = model.getHeaderSummary("string");
+ expect(summary.spec).toBeDefined();
+ // @ts-expect-error data.values should be available
+ expect(summary.spec?.data?.values).toEqual([
+ { value: "A", count: 10, xStart: 0, xEnd: 10, xMid: 5, proportion: 0.25 },
+ {
+ value: "B",
+ count: 30,
+ xStart: 10,
+ xEnd: 40,
+ xMid: 25,
+ proportion: 0.75,
+ },
+ ]);
+
+ // Snapshot
+ expect(summary.spec).toMatchSnapshot();
+ });
+
describe("snapshot", () => {
const fieldTypes: FieldTypes = {
...mockFieldTypes,
@@ -163,6 +273,7 @@ describe("ColumnChartSpecModel", () => {
fieldTypes,
mockStats,
mockBinValues,
+ mockValueCounts,
{ includeCharts: true },
);
expect(model.getHeaderSummary("date").spec).toMatchSnapshot();
@@ -174,6 +285,7 @@ describe("ColumnChartSpecModel", () => {
fieldTypes,
mockStats,
mockBinValues,
+ mockValueCounts,
{ includeCharts: true },
);
expect(model.getHeaderSummary("a").spec).toMatchSnapshot();
@@ -185,6 +297,7 @@ describe("ColumnChartSpecModel", () => {
fieldTypes,
mockStats,
mockBinValues,
+ mockValueCounts,
{ includeCharts: true },
);
expect(model.getHeaderSummary("a").spec).toMatchSnapshot();
@@ -196,6 +309,7 @@ describe("ColumnChartSpecModel", () => {
fieldTypes,
mockStats,
mockBinValues,
+ mockValueCounts,
{ includeCharts: true },
);
expect(model.getHeaderSummary("a").spec).toMatchSnapshot();
@@ -209,6 +323,7 @@ describe("ColumnChartSpecModel", () => {
mockFieldTypes,
mockStats,
mockBinValues,
+ mockValueCounts,
{ includeCharts: true },
);
@@ -224,6 +339,7 @@ describe("ColumnChartSpecModel", () => {
mockFieldTypes,
mockStats,
mockBinValues,
+ mockValueCounts,
{ includeCharts: true },
);
@@ -239,6 +355,7 @@ describe("ColumnChartSpecModel", () => {
mockFieldTypes,
mockStats,
mockBinValues,
+ mockValueCounts,
{ includeCharts: true },
);
@@ -255,6 +372,7 @@ describe("ColumnChartSpecModel", () => {
mockFieldTypes,
mockStats,
mockBinValues,
+ mockValueCounts,
{ includeCharts: true },
);
@@ -272,6 +390,7 @@ describe("ColumnChartSpecModel", () => {
mockFieldTypes,
mockStats,
mockBinValues,
+ mockValueCounts,
{ includeCharts: true },
);
@@ -289,6 +408,7 @@ describe("ColumnChartSpecModel", () => {
mockFieldTypes,
mockStats,
mockBinValues,
+ mockValueCounts,
{ includeCharts: true },
);
const spec = model.getHeaderSummary("date").spec;
@@ -308,6 +428,7 @@ describe("ColumnChartSpecModel", () => {
mockFieldTypes,
mockStats,
mockBinValues,
+ mockValueCounts,
{ includeCharts: true },
);
diff --git a/frontend/src/components/data-table/chart-spec-model.tsx b/frontend/src/components/data-table/chart-spec-model.tsx
deleted file mode 100644
index 4808ee3a79..0000000000
--- a/frontend/src/components/data-table/chart-spec-model.tsx
+++ /dev/null
@@ -1,521 +0,0 @@
-/* Copyright 2024 Marimo. All rights reserved. */
-
-import { mint, orange, slate } from "@radix-ui/colors";
-import type { TopLevelSpec } from "vega-lite";
-// @ts-expect-error vega-typings does not include formats
-import { formats } from "vega-loader";
-import { asRemoteURL } from "@/core/runtime/config";
-import type { TopLevelFacetedUnitSpec } from "@/plugins/impl/data-explorer/queries/types";
-import { arrow } from "@/plugins/impl/vega/formats";
-import { parseCsvData } from "@/plugins/impl/vega/loader";
-import { logNever } from "@/utils/assertNever";
-import {
- byteStringToBinary,
- extractBase64FromDataURL,
- isDataURLString,
- typedAtob,
-} from "@/utils/json/base64";
-import type {
- BinValues,
- ColumnHeaderStats,
- ColumnName,
- FieldTypes,
-} from "./types";
-
-// We rely on vega's built-in binning to determine bar widths.
-const MAX_BAR_HEIGHT = 20; // px
-
-// Arrow formats have a magic number at the beginning of the file.
-const ARROW_MAGIC_NUMBER = "ARROW1";
-
-// register arrow reader under type 'arrow'
-formats("arrow", arrow);
-
-export class ColumnChartSpecModel<T> {
- private columnStats = new Map<ColumnName, ColumnHeaderStats>();
- private columnBinValues = new Map<ColumnName, BinValues>();
-
- public static readonly EMPTY = new ColumnChartSpecModel(
- [],
- {},
- {},
- {},
- {
- includeCharts: false,
- usePreComputedValues: false,
- },
- );
-
- private dataSpec: TopLevelSpec["data"];
- private sourceName: "data_0" | "source_0";
-
- constructor(
- private readonly data: T[] | string,
- private readonly fieldTypes: FieldTypes,
- readonly stats: Record<ColumnName, ColumnHeaderStats>,
- readonly binValues: Record<ColumnName, BinValues>,
- private readonly opts: {
- includeCharts: boolean;
- usePreComputedValues?: boolean;
- },
- ) {
- // Data may come in from a few different sources:
- // - A URL
- // - A CSV data URI (e.g. "data:text/csv;base64,...")
- // - A CSV string (e.g. "a,b,c\n1,2,3\n4,5,6")
- // - An array of objects
- // For each case, we need to set up the data spec and source name appropriately.
- // If its a file, the source name will be "source_0", otherwise it will be "data_0".
- // We have a few snapshot tests to ensure that the spec is correct for each case.
- if (typeof this.data === "string") {
- if (this.data.startsWith("./@file") || this.data.startsWith("/@file")) {
- this.dataSpec = { url: asRemoteURL(this.data).href };
- this.sourceName = "source_0";
- } else if (isDataURLString(this.data)) {
- this.sourceName = "data_0";
- const base64 = extractBase64FromDataURL(this.data);
- const decoded = typedAtob(base64);
-
- if (decoded.startsWith(ARROW_MAGIC_NUMBER)) {
- this.dataSpec = {
- values: byteStringToBinary(decoded),
- // @ts-expect-error vega-typings does not include arrow format
- format: { type: "arrow" },
- };
- } else {
- // Assume it's a CSV string
- this.parseCsv(decoded);
- }
- } else {
- // Assume it's a CSV string
- this.parseCsv(this.data);
- this.sourceName = "data_0";
- }
- } else {
- this.dataSpec = { values: this.data };
- this.sourceName = "source_0";
- }
-
- this.columnBinValues = new Map(Object.entries(binValues));
- this.columnStats = new Map(Object.entries(stats));
- }
-
- public getColumnStats(column: string) {
- return this.columnStats.get(column);
- }
-
- public getHeaderSummary(column: string) {
- return {
- stats: this.columnStats.get(column),
- type: this.fieldTypes[column],
- spec: this.opts.includeCharts ? this.getVegaSpec(column) : undefined,
- };
- }
-
- private parseCsv(data: string) {
- this.dataSpec = {
- values: parseCsvData(data) as T[],
- };
- }
-
- private getVegaSpec(column: string): TopLevelFacetedUnitSpec | null {
- if (!this.data) {
- return null;
- }
-
- const usePreComputedValues = this.opts.usePreComputedValues;
- const binValues = this.columnBinValues.get(column);
- const hasBinValues = binValues && binValues.length > 0;
-
- const base: TopLevelFacetedUnitSpec = {
- data:
- hasBinValues && usePreComputedValues
- ? { values: binValues }
- : (this.dataSpec as TopLevelFacetedUnitSpec["data"]),
- background: "transparent",
- config: {
- view: {
- stroke: "transparent",
- },
- axis: {
- domain: false,
- },
- },
- height: 100,
- } as TopLevelFacetedUnitSpec;
- const type = this.fieldTypes[column];
-
- // https://github.com/vega/altair/blob/32990a597af7c09586904f40b3f5e6787f752fa5/doc/user_guide/encodings/index.rst#escaping-special-characters-in-column-names
- // escape periods in column names
- column = column.replaceAll(".", "\\.");
- // escape brackets in column names
- column = column.replaceAll("[", "\\[").replaceAll("]", "\\]");
- // escape colons in column names
- column = column.replaceAll(":", "\\:");
-
- const scale = this.getScale();
-
- switch (type) {
- case "date":
- case "datetime":
- case "time": {
- const format =
- type === "date"
- ? "%Y-%m-%d"
- : type === "time"
- ? "%H:%M:%S"
- : "%Y-%m-%dT%H:%M:%S";
-
- return {
- ...base,
- // Two layers: one with the visible bars, and one with invisible bars
- // that provide a larger tooltip area.
- // @ts-expect-error 'layer' property not in TopLevelFacetedUnitSpec
- layer: [
- {
- mark: {
- type: "bar",
- color: mint.mint11,
- },
- encoding: {
- x: {
- field: column,
- type: "temporal",
- axis: null,
- bin: true,
- scale: scale,
- },
- y: { aggregate: "count", type: "quantitative", axis: null },
- // Color nulls
- color: {
- condition: {
- test: `datum["bin_maxbins_10_${column}_range"] === "null"`,
- value: orange.orange11,
- },
- value: mint.mint11,
- },
- },
- },
-
- // 0 opacity full-height bars with tooltips, since it is too hard to trigger
- // the tooltip for very small bars.
- {
- mark: {
- type: "bar",
- opacity: 0,
- },
- encoding: {
- x: {
- field: column,
- type: "temporal",
- axis: null,
- bin: true,
- scale: scale,
- },
- y: { aggregate: "max", type: "quantitative", axis: null },
- tooltip: [
- {
- // Can also use column, but this is more explicit
- field: `bin_maxbins_10_${column}`,
- type: "temporal",
- format: format,
- bin: { binned: true },
- title: `${column} (start)`,
- },
- {
- field: `bin_maxbins_10_${column}_end`,
- type: "temporal",
- format: format,
- bin: { binned: true },
- title: `${column} (end)`,
- },
- {
- aggregate: "count",
- type: "quantitative",
- title: "Count",
- format: ",d",
- },
- ],
- // Color nulls
- color: {
- condition: {
- test: `datum["bin_maxbins_10_${column}_range"] === "null"`,
- value: orange.orange11,
- },
- value: mint.mint11,
- },
- },
- },
- ],
- };
- }
- case "integer":
- case "number": {
- // Create a histogram spec that properly handles null values
- const format = type === "integer" ? ",d" : ".2f";
-
- if (!usePreComputedValues || !hasBinValues) {
- return getLegacyNumericSpec(column, format, base);
- }
-
- const stats = this.columnStats.get(column);
-
- return {
- ...base, // Assuming base contains shared configurations
- // Two layers: one with the visible bars, and one with invisible bars
- // that provide a larger tooltip area.
- // @ts-expect-error 'layer' property not in TopLevelFacetedUnitSpec
- layer: [
- {
- mark: {
- type: "bar",
- color: mint.mint11,
- stroke: mint.mint11,
- strokeWidth: 0,
- },
- params: [
- {
- name: "hover",
- select: {
- type: "point",
- on: "mouseover",
- },
- },
- ],
- encoding: {
- x: {
- field: "bin_start",
- type: "quantitative",
- bin: { binned: true, step: 2 },
- },
- x2: {
- field: "bin_end",
- axis: null,
- },
- y: {
- field: "count",
- type: "quantitative",
- axis: null,
- },
- strokeWidth: {
- condition: {
- param: "hover",
- empty: false,
- value: 0.5,
- },
- value: 0,
- },
- },
- },
-
- // Tooltip layer
- {
- mark: {
- type: "bar",
- opacity: 0,
- },
- encoding: {
- x: {
- field: "bin_start",
- type: "quantitative",
- bin: { binned: true, step: 2 },
- axis: {
- title: null,
- labelFontSize: 8.5,
- labelOpacity: 0.5,
- labelExpr:
- "(datum.value >= 10000 || datum.value <= -10000) ? format(datum.value, '.2e') : format(datum.value, '.2~f')",
- // TODO: Tick count provides a better UI, but it did not work
- values: [
- stats?.min,
- stats?.p25,
- stats?.median,
- stats?.p75,
- stats?.p95,
- stats?.max,
- ].filter((value): value is number => value !== undefined),
- },
- },
- x2: {
- field: "bin_end",
- },
- y: {
- aggregate: "max",
- type: "quantitative",
- axis: null,
- },
- tooltip: [
- {
- field: "bin_range",
- type: "nominal",
- title: column,
- },
- {
- field: "count",
- type: "quantitative",
- title: "Count",
- format: ",d",
- },
- ],
- },
- transform: [
- {
- calculate: `format(datum.bin_start, '${format}') + ' - ' + format(datum.bin_end, '${format}')`,
- as: "bin_range",
- },
- ],
- },
- ],
- };
- }
- case "boolean":
- return {
- ...base,
- mark: { type: "bar", color: mint.mint11 },
- encoding: {
- y: {
- field: column,
- type: "nominal",
- axis: {
- labelExpr:
- "datum.label === 'true' || datum.label === 'True' ? 'True' : 'False'",
- tickWidth: 0,
- title: null,
- labelColor: slate.slate9,
- },
- },
- x: {
- aggregate: "count",
- type: "quantitative",
- axis: null,
- scale: { type: "linear" },
- },
- tooltip: [
- { field: column, type: "nominal", title: "Value" },
- {
- aggregate: "count",
- type: "quantitative",
- title: "Count",
- format: ",d",
- },
- ],
- },
- layer: [
- {
- mark: {
- type: "bar",
- color: mint.mint11,
- height: MAX_BAR_HEIGHT,
- },
- },
- {
- mark: {
- type: "text",
- align: "left",
- baseline: "middle",
- dx: 3,
- color: slate.slate9,
- },
- encoding: {
- text: {
- aggregate: "count",
- type: "quantitative",
- },
- },
- },
- ],
- } as TopLevelFacetedUnitSpec; // "layer" not in TopLevelFacetedUnitSpec
- case "unknown":
- case "string":
- return null;
- default:
- logNever(type);
- return null;
- }
- }
-
- private getScale() {
- return {
- align: 0,
- paddingInner: 0,
- paddingOuter: {
- expr: `length(data('${this.sourceName}')) == 2 ? 1 : length(data('${this.sourceName}')) == 3 ? 0.5 : length(data('${this.sourceName}')) == 4 ? 0 : 0`,
- },
- };
- }
-}
-
-function getLegacyNumericSpec(
- column: string,
- format: string,
- base: TopLevelFacetedUnitSpec,
-): TopLevelFacetedUnitSpec {
- return {
- ...base, // Assuming base contains shared configurations
- // Two layers: one with the visible bars, and one with invisible bars
- // that provide a larger tooltip area.
- // @ts-expect-error 'layer' property not in TopLevelFacetedUnitSpec
- layer: [
- {
- mark: {
- type: "bar",
- color: mint.mint11,
- },
- encoding: {
- x: {
- field: column,
- type: "quantitative",
- bin: true,
- },
- y: {
- aggregate: "count",
- type: "quantitative",
- axis: null,
- },
- },
- },
-
- // Tooltip layer
- {
- mark: {
- type: "bar",
- opacity: 0,
- },
- encoding: {
- x: {
- field: column,
- type: "quantitative",
- bin: true,
- axis: {
- title: null,
- labelFontSize: 8.5,
- labelOpacity: 0.5,
- labelExpr:
- "(datum.value >= 10000 || datum.value <= -10000) ? format(datum.value, '.2e') : format(datum.value, '.2~f')",
- },
- },
- y: {
- aggregate: "max",
- type: "quantitative",
- axis: null,
- },
- tooltip: [
- {
- field: column,
- type: "quantitative",
- bin: true,
- title: column,
- format: format,
- },
- {
- aggregate: "count",
- type: "quantitative",
- title: "Count",
- format: ",d",
- },
- ],
- },
- },
- ],
- };
-}
diff --git a/frontend/src/components/charts/chart-skeleton.tsx b/frontend/src/components/data-table/column-summary/chart-skeleton.tsx
similarity index 100%
rename from frontend/src/components/charts/chart-skeleton.tsx
rename to frontend/src/components/data-table/column-summary/chart-skeleton.tsx
diff --git a/frontend/src/components/data-table/column-summary/chart-spec-model.tsx b/frontend/src/components/data-table/column-summary/chart-spec-model.tsx
new file mode 100644
index 0000000000..52504e49d7
--- /dev/null
+++ b/frontend/src/components/data-table/column-summary/chart-spec-model.tsx
@@ -0,0 +1,914 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+
+import { mint, orange, slate } from "@radix-ui/colors";
+import type { TopLevelSpec } from "vega-lite";
+import type { StringFieldDef } from "vega-lite/build/src/channeldef";
+// @ts-expect-error vega-typings does not include formats
+import { formats } from "vega-loader";
+import { asRemoteURL } from "@/core/runtime/config";
+import type { TopLevelFacetedUnitSpec } from "@/plugins/impl/data-explorer/queries/types";
+import { arrow } from "@/plugins/impl/vega/formats";
+import { parseCsvData } from "@/plugins/impl/vega/loader";
+import { logNever } from "@/utils/assertNever";
+import {
+ byteStringToBinary,
+ extractBase64FromDataURL,
+ isDataURLString,
+ typedAtob,
+} from "@/utils/json/base64";
+import type {
+ BinValues,
+ ColumnHeaderStats,
+ ColumnName,
+ FieldTypes,
+ ValueCounts,
+} from "../types";
+import {
+ getLegacyBooleanSpec,
+ getLegacyNumericSpec,
+ getLegacyTemporalSpec,
+} from "./legacy-chart-spec";
+import { getPartialTimeTooltip } from "./utils";
+
+// We rely on vega's built-in binning to determine bar widths.
+const MAX_BAR_HEIGHT = 20; // px
+
+// If we are concatenating charts, we need to specify each chart's height and width.
+const CHART_HEIGHT = 30;
+const CHART_WIDTH = 70;
+const NULL_BAR_WIDTH = 5;
+
+// Arrow formats have a magic number at the beginning of the file.
+const ARROW_MAGIC_NUMBER = "ARROW1";
+
+// register arrow reader under type 'arrow'
+formats("arrow", arrow);
+
+export class ColumnChartSpecModel<T> {
+ private columnStats = new Map<ColumnName, Partial<ColumnHeaderStats>>();
+ private columnBinValues = new Map<ColumnName, BinValues>();
+ private columnValueCounts = new Map<ColumnName, ValueCounts>();
+
+ public static readonly EMPTY = new ColumnChartSpecModel(
+ [],
+ {},
+ {},
+ {},
+ {},
+ {
+ includeCharts: false,
+ usePreComputedValues: false,
+ },
+ );
+
+ private dataSpec: TopLevelSpec["data"];
+ private sourceName: "data_0" | "source_0";
+
+ constructor(
+ private readonly data: T[] | string,
+ private readonly fieldTypes: FieldTypes,
+ readonly stats: Record<ColumnName, Partial<ColumnHeaderStats>>,
+ readonly binValues: Record<ColumnName, BinValues>,
+ readonly valueCounts: Record<ColumnName, ValueCounts>,
+ private readonly opts: {
+ includeCharts: boolean;
+ usePreComputedValues?: boolean;
+ },
+ ) {
+ // Data may come in from a few different sources:
+ // - A URL
+ // - A CSV data URI (e.g. "data:text/csv;base64,...")
+ // - A CSV string (e.g. "a,b,c\n1,2,3\n4,5,6")
+ // - An array of objects
+ // For each case, we need to set up the data spec and source name appropriately.
+ // If its a file, the source name will be "source_0", otherwise it will be "data_0".
+ // We have a few snapshot tests to ensure that the spec is correct for each case.
+ if (typeof this.data === "string") {
+ if (this.data.startsWith("./@file") || this.data.startsWith("/@file")) {
+ this.dataSpec = { url: asRemoteURL(this.data).href };
+ this.sourceName = "source_0";
+ } else if (isDataURLString(this.data)) {
+ this.sourceName = "data_0";
+ const base64 = extractBase64FromDataURL(this.data);
+ const decoded = typedAtob(base64);
+
+ if (decoded.startsWith(ARROW_MAGIC_NUMBER)) {
+ this.dataSpec = {
+ values: byteStringToBinary(decoded),
+ // @ts-expect-error vega-typings does not include arrow format
+ format: { type: "arrow" },
+ };
+ } else {
+ // Assume it's a CSV string
+ this.parseCsv(decoded);
+ }
+ } else {
+ // Assume it's a CSV string
+ this.parseCsv(this.data);
+ this.sourceName = "data_0";
+ }
+ } else {
+ this.dataSpec = { values: this.data };
+ this.sourceName = "source_0";
+ }
+
+ this.columnBinValues = new Map(Object.entries(binValues));
+ this.columnValueCounts = new Map(Object.entries(valueCounts));
+ this.columnStats = new Map(Object.entries(stats));
+ }
+
+ public getColumnStats(column: string) {
+ return this.columnStats.get(column);
+ }
+
+ public getHeaderSummary(column: string) {
+ return {
+ stats: this.columnStats.get(column),
+ type: this.fieldTypes[column],
+ spec: this.opts.includeCharts ? this.getVegaSpec(column) : undefined,
+ };
+ }
+
+ private parseCsv(data: string) {
+ this.dataSpec = {
+ values: parseCsvData(data) as T[],
+ };
+ }
+
+ private getVegaSpec(column: string): TopLevelFacetedUnitSpec | null {
+ if (!this.data) {
+ return null;
+ }
+
+ const usePreComputedValues = this.opts.usePreComputedValues;
+ const binValues = this.columnBinValues.get(column);
+ const hasBinValues = binValues && binValues.length > 0;
+ const valueCounts = this.columnValueCounts.get(column);
+ const hasValueCounts = valueCounts && valueCounts.length > 0;
+
+ let data = this.dataSpec as TopLevelFacetedUnitSpec["data"];
+ const stats = this.columnStats.get(column);
+
+ if (usePreComputedValues) {
+ if (hasBinValues) {
+ const values = binValues;
+ if (stats?.nulls) {
+ values.push({
+ bin_start: null,
+ bin_end: null,
+ count: stats.nulls as number,
+ });
+ }
+ data = { values, name: "bin_values" };
+ } else if (hasValueCounts) {
+ data = { values: valueCounts, name: "value_counts" };
+ }
+ }
+
+ const base: TopLevelFacetedUnitSpec = {
+ background: "transparent",
+ data,
+ config: {
+ view: {
+ stroke: "transparent",
+ },
+ axis: {
+ domain: false,
+ },
+ },
+ height: 100,
+ } as TopLevelFacetedUnitSpec;
+
+ const type = this.fieldTypes[column];
+
+ // https://github.com/vega/altair/blob/32990a597af7c09586904f40b3f5e6787f752fa5/doc/user_guide/encodings/index.rst#escaping-special-characters-in-column-names
+ // escape periods in column names
+ column = column.replaceAll(".", "\\.");
+ // escape brackets in column names
+ column = column.replaceAll("[", "\\[").replaceAll("]", "\\]");
+ // escape colons in column names
+ column = column.replaceAll(":", "\\:");
+
+ const scale = this.getScale();
+
+ switch (type) {
+ case "date":
+ case "datetime":
+ case "time": {
+ if (!usePreComputedValues || !hasBinValues) {
+ return getLegacyTemporalSpec(column, type, base, scale);
+ }
+
+ const tooltip = getPartialTimeTooltip(binValues);
+ const singleValue = binValues.length === 1;
+
+ // Single value charts can be displayed as a full bar
+ if (singleValue) {
+ return {
+ ...base,
+ mark: { type: "bar", color: mint.mint11 },
+ encoding: {
+ x: {
+ field: "bin_start",
+ type: "nominal",
+ axis: null,
+ },
+ y: {
+ field: "count",
+ type: "quantitative",
+ axis: null,
+ },
+ tooltip: [
+ {
+ field: "bin_start",
+ type: "temporal",
+ ...tooltip,
+ title: `${column} (start)`,
+ },
+ {
+ field: "bin_end",
+ type: "temporal",
+ ...tooltip,
+ title: `${column} (end)`,
+ },
+ ],
+ },
+ };
+ }
+
+ const histogram: TopLevelFacetedUnitSpec = {
+ height: CHART_HEIGHT,
+ width: CHART_WIDTH,
+ // @ts-expect-error 'layer' property not in TopLevelFacetedUnitSpec
+ layer: [
+ {
+ mark: {
+ type: "bar",
+ color: mint.mint11,
+ stroke: mint.mint11,
+ strokeWidth: 0,
+ },
+ params: [
+ {
+ name: "hover",
+ select: {
+ type: "point",
+ on: "mouseover",
+ clear: "mouseout",
+ },
+ },
+ ],
+ encoding: {
+ x: {
+ field: "bin_start",
+ type: "temporal",
+ bin: { binned: true, step: 2 },
+ axis: null,
+ },
+ x2: {
+ field: "bin_end",
+ type: "temporal",
+ axis: null,
+ },
+ y: {
+ field: "count",
+ type: "quantitative",
+ axis: null,
+ },
+ strokeWidth: {
+ condition: {
+ param: "hover",
+ empty: false,
+ value: 0.5,
+ },
+ value: 0,
+ },
+ },
+ },
+
+ // Invisible tooltip layer
+ {
+ mark: {
+ type: "bar",
+ opacity: 0,
+ },
+ encoding: {
+ x: {
+ field: "bin_start",
+ type: "temporal",
+ bin: { binned: true, step: 2 },
+ axis: null,
+ },
+ x2: {
+ field: "bin_end",
+ type: "temporal",
+ bin: { binned: true, step: 2 },
+ axis: null,
+ },
+ y: {
+ aggregate: "max",
+ type: "quantitative",
+ axis: null,
+ },
+ tooltip: [
+ {
+ field: "bin_start",
+ type: "temporal",
+ ...tooltip,
+ title: `${column} (start)`,
+ },
+ {
+ field: "bin_end",
+ type: "temporal",
+ ...tooltip,
+ title: `${column} (end)`,
+ },
+ {
+ field: "count",
+ type: "quantitative",
+ title: "Count",
+ format: ",d",
+ },
+ ],
+ },
+ },
+ ],
+ };
+
+ const nullBar: TopLevelFacetedUnitSpec = {
+ height: CHART_HEIGHT,
+ width: NULL_BAR_WIDTH,
+ // @ts-expect-error 'layer' property not in TopLevelFacetedUnitSpec
+ layer: [
+ {
+ mark: {
+ type: "bar",
+ color: orange.orange11,
+ },
+ encoding: {
+ x: {
+ field: "bin_start",
+ type: "nominal",
+ axis: null,
+ },
+ y: {
+ field: "count",
+ type: "quantitative",
+ axis: null,
+ },
+ },
+ },
+
+ // Invisible tooltip layer with max-height
+ {
+ mark: {
+ type: "bar",
+ opacity: 0,
+ },
+ encoding: {
+ x: {
+ field: "bin_start",
+ type: "nominal",
+ axis: null,
+ },
+ y: {
+ aggregate: "max",
+ type: "quantitative",
+ axis: null,
+ },
+ tooltip: [
+ {
+ field: "count",
+ type: "quantitative",
+ title: "nulls",
+ format: ",d",
+ },
+ ],
+ },
+ },
+ ],
+ transform: [
+ {
+ filter:
+ "datum['bin_start'] === null && datum['bin_end'] === null",
+ },
+ ],
+ };
+
+ let chart: TopLevelFacetedUnitSpec = histogram;
+ let timeBase = base;
+
+ if (stats?.nulls) {
+ timeBase = {
+ ...base,
+ config: {
+ ...base.config,
+ concat: {
+ spacing: 0,
+ },
+ },
+ resolve: {
+ scale: {
+ y: "shared",
+ },
+ },
+ };
+ chart = {
+ // Temporal axis will not show nulls, so we concat 2 charts
+ // @ts-expect-error 'hconcat' property not in TopLevelFacetedUnitSpec
+ hconcat: [nullBar, histogram],
+ };
+ }
+
+ return {
+ ...timeBase,
+ ...chart,
+ };
+ }
+ case "integer":
+ case "number": {
+ // Create a histogram spec that properly handles null values
+ const format = type === "integer" ? ",d" : ".2f";
+
+ if (!usePreComputedValues || !hasBinValues) {
+ return getLegacyNumericSpec(column, format, base);
+ }
+
+ const stats = this.columnStats.get(column);
+
+ const histogram: TopLevelFacetedUnitSpec = {
+ height: CHART_HEIGHT,
+ width: CHART_WIDTH,
+ // @ts-expect-error 'layer' property not in TopLevelFacetedUnitSpec
+ layer: [
+ {
+ mark: {
+ type: "bar",
+ color: mint.mint11,
+ stroke: mint.mint11,
+ strokeWidth: 0,
+ },
+ params: [
+ {
+ name: "hover",
+ select: {
+ type: "point",
+ on: "mouseover",
+ clear: "mouseout",
+ },
+ },
+ ],
+ encoding: {
+ x: {
+ field: "bin_start",
+ type: "quantitative",
+ bin: { binned: true, step: 2 },
+ },
+ x2: {
+ field: "bin_end",
+ axis: null,
+ },
+ y: {
+ field: "count",
+ type: "quantitative",
+ axis: null,
+ },
+ strokeWidth: {
+ condition: {
+ param: "hover",
+ empty: false,
+ value: 0.5,
+ },
+ value: 0,
+ },
+ },
+ },
+
+ // Tooltip layer
+ {
+ mark: {
+ type: "bar",
+ opacity: 0,
+ },
+ encoding: {
+ x: {
+ field: "bin_start",
+ type: "quantitative",
+ bin: { binned: true, step: 2 },
+ axis: {
+ title: null,
+ labelFontSize: 8.5,
+ labelOpacity: 0.5,
+ labelExpr:
+ "(datum.value >= 10000 || datum.value <= -10000) ? format(datum.value, '.2e') : format(datum.value, '.2~f')",
+ // TODO: Tick count provides a better UI, but it did not work
+ values: [
+ stats?.min,
+ stats?.p25,
+ stats?.median,
+ stats?.p75,
+ stats?.p95,
+ stats?.max,
+ ].filter((value): value is number => value !== undefined),
+ },
+ },
+ x2: {
+ field: "bin_end",
+ },
+ y: {
+ aggregate: "max",
+ type: "quantitative",
+ axis: null,
+ },
+ tooltip: [
+ {
+ field: "bin_range",
+ type: "nominal",
+ title: column,
+ },
+ {
+ field: "count",
+ type: "quantitative",
+ title: "Count",
+ format: ",d",
+ },
+ ],
+ },
+ transform: [
+ {
+ calculate: `format(datum.bin_start, '${format}') + ' - ' + format(datum.bin_end, '${format}')`,
+ as: "bin_range",
+ },
+ ],
+ },
+ ],
+ };
+
+ const nullBar: TopLevelFacetedUnitSpec = {
+ height: CHART_HEIGHT,
+ width: NULL_BAR_WIDTH,
+ // @ts-expect-error 'layer' property not in TopLevelFacetedUnitSpec
+ layer: [
+ {
+ mark: {
+ type: "bar",
+ color: orange.orange11,
+ },
+ encoding: {
+ x: {
+ field: "bin_start",
+ type: "nominal",
+ axis: null,
+ },
+ y: {
+ field: "count",
+ type: "quantitative",
+ axis: null,
+ },
+ },
+ },
+ {
+ mark: {
+ type: "bar",
+ opacity: 0,
+ },
+ encoding: {
+ x: {
+ field: "bin_start",
+ type: "nominal",
+ axis: null,
+ },
+ y: {
+ aggregate: "max",
+ type: "quantitative",
+ axis: null,
+ },
+ tooltip: [
+ {
+ field: "count",
+ type: "quantitative",
+ title: "nulls",
+ format: ",d",
+ },
+ ],
+ },
+ },
+ ],
+ transform: [
+ {
+ filter:
+ "datum['bin_start'] === null && datum['bin_end'] === null",
+ },
+ ],
+ };
+
+ let chart: TopLevelFacetedUnitSpec = histogram;
+ let numericBase = base;
+
+ if (stats?.nulls) {
+ numericBase = {
+ ...base,
+ config: {
+ ...base.config,
+ concat: {
+ spacing: 0,
+ },
+ },
+ // So that the null bar and the histogram share the same y-axis
+ resolve: {
+ scale: {
+ y: "shared",
+ },
+ },
+ };
+ chart = {
+ // @ts-expect-error 'hconcat' property not in TopLevelFacetedUnitSpec
+ hconcat: [nullBar, histogram],
+ };
+ }
+
+ return {
+ ...numericBase, // Assuming base contains shared configurations
+ ...chart,
+ };
+ }
+ case "boolean": {
+ if (!usePreComputedValues || !stats?.true || !stats?.false) {
+ return getLegacyBooleanSpec(column, base, MAX_BAR_HEIGHT);
+ }
+
+ const BAR_HEIGHT = stats?.nulls ? 11 : MAX_BAR_HEIGHT;
+
+ const values = [
+ { value: "true", count: stats.true },
+ { value: "false", count: stats.false },
+ ];
+ if (stats?.nulls) {
+ values.push({ value: "null", count: stats.nulls });
+ }
+
+ let countTooltip: StringFieldDef<string> = {
+ field: "count",
+ type: "quantitative",
+ format: ",d",
+ };
+ let transform: TopLevelFacetedUnitSpec["transform"] = [];
+
+ const total =
+ Number(stats.total) ||
+ Number(stats.true) + Number(stats.false) + Number(stats.nulls);
+
+ if (!Number.isNaN(total)) {
+ countTooltip = {
+ field: "count_with_percent",
+ type: "nominal",
+ title: "Count",
+ };
+ transform = [
+ {
+ calculate: `format(datum.count, ',d') + ' (' + format(datum.count / ${total} * 100, '.1f') + '%)'`,
+ as: "count_with_percent",
+ },
+ ];
+ }
+
+ return {
+ ...base,
+ data: {
+ values,
+ name: "boolean_values",
+ },
+ mark: {
+ type: "bar",
+ color: mint.mint11,
+ },
+ encoding: {
+ y: {
+ field: "value",
+ type: "nominal",
+ sort: ["true", "false", "null"],
+ scale: stats?.nulls ? { paddingInner: 1 } : undefined,
+ axis: {
+ labelExpr:
+ "datum.label === 'true' || datum.label === 'True' ? 'True' : datum.label === 'false' || datum.label === 'False' ? 'False' : 'Null'",
+ tickWidth: 0,
+ title: null,
+ labelColor: slate.slate9,
+ },
+ },
+ x: {
+ field: "count",
+ type: "quantitative",
+ axis: null,
+ scale: { type: "linear" },
+ },
+ color: {
+ field: "value",
+ type: "nominal",
+ scale: {
+ domain: ["true", "false", "null"],
+ range: [mint.mint11, mint.mint11, orange.orange11],
+ },
+ legend: null,
+ },
+ tooltip: [
+ { field: "value", type: "nominal", title: column },
+ countTooltip,
+ ],
+ },
+ transform,
+ layer: [
+ {
+ mark: {
+ type: "bar",
+ color: mint.mint11,
+ height: BAR_HEIGHT,
+ },
+ },
+ {
+ mark: {
+ type: "text",
+ align: "left",
+ baseline: "middle",
+ dx: 3,
+ color: slate.slate9,
+ },
+ encoding: {
+ text: {
+ field: "count",
+ type: "quantitative",
+ format: ",d",
+ },
+ },
+ },
+ ],
+ } as TopLevelFacetedUnitSpec; // "layer" not in TopLevelFacetedUnitSpec
+ }
+ case "string": {
+ if (!usePreComputedValues || !hasValueCounts) {
+ return null;
+ }
+
+ const total =
+ Number(stats?.total) ||
+ valueCounts.reduce((acc, curr) => acc + curr.count, 0);
+
+ const xStartField = "xStart";
+ const xEndField = "xEnd";
+ const xMidField = "xMid";
+ const yField = "value";
+
+ // Calculate xStart and xEnd for each value count
+ const newValueCounts: Array<{
+ count: number;
+ value: string;
+ xStart: number;
+ xEnd: number;
+ xMid: number;
+ proportion: number;
+ }> = [];
+ let xStart = 0;
+ for (const valueCount of valueCounts) {
+ const xEnd = xStart + valueCount.count;
+ const xMid = (xStart + xEnd) / 2;
+ const proportion = (xEnd - xStart) / total;
+
+ newValueCounts.push({
+ count: valueCount.count,
+ value: valueCount.value,
+ xStart,
+ xEnd,
+ xMid,
+ proportion,
+ });
+ xStart = xEnd;
+ }
+
+ // Add a transform to calculate the percentage for each value
+ const percentField = "percent";
+ const transforms: TopLevelFacetedUnitSpec["transform"] = [
+ {
+ calculate: total ? `datum.count / ${total}` : "0",
+ as: percentField,
+ },
+ ];
+
+ // Pill-like bar
+ const barChart: Omit<TopLevelFacetedUnitSpec, "data"> = {
+ mark: {
+ type: "bar",
+ // cornerRadiusEnd: 10,
+ // cornerRadius: 10,
+ },
+ params: [
+ {
+ name: "hover_bar",
+ select: {
+ type: "point",
+ on: "mouseover",
+ clear: "mouseout",
+ },
+ },
+ ],
+ encoding: {
+ x: {
+ field: xStartField,
+ type: "quantitative",
+ axis: null,
+ },
+ x2: {
+ field: xEndField,
+ type: "quantitative",
+ },
+ color: {
+ condition: [
+ {
+ param: "hover_bar",
+ value: mint.mint11,
+ },
+ {
+ test: `datum.${yField} == "None" || datum.${yField} == "null"`,
+ value: orange.orange11,
+ },
+ ],
+ value: mint.mint8,
+ legend: null,
+ },
+ tooltip: [
+ {
+ field: yField,
+ type: "nominal",
+ title: column,
+ },
+ {
+ field: "count_with_percent",
+ type: "nominal",
+ title: "Count",
+ },
+ ],
+ },
+ transform: [
+ // Display count and percent together
+ {
+ calculate: `format(datum.count, ',d') + ' (' + format(datum.count / ${total} * 100, '.1f') + '%)'`,
+ as: "count_with_percent",
+ },
+ ],
+ };
+
+ // Text layer with clipping based on bar width
+ const textChart: Omit<TopLevelFacetedUnitSpec, "data"> = {
+ mark: {
+ type: "text",
+ color: "white",
+ fontSize: 8.5,
+ ellipsis: " ", // Don't add ... after clipping
+ clip: true,
+ },
+ encoding: {
+ x: {
+ field: xMidField,
+ type: "quantitative",
+ axis: null,
+ },
+ text: {
+ field: "clipped_text",
+ },
+ },
+ transform: [
+ {
+ calculate: `datum.proportion > 0.5 ? slice(datum.${yField}, 0, 8) : datum.proportion > 0.2 ? slice(datum.${yField}, 0, 3) : datum.proportion > 0.1 ? slice(datum.${yField}, 0, 1) : ''`,
+ as: "clipped_text",
+ },
+ ],
+ };
+
+ return {
+ ...base,
+ data: {
+ values: newValueCounts,
+ name: "value_counts",
+ },
+ // @ts-expect-error 'layer' property not in TopLevelFacetedUnitSpec
+ layer: [barChart, textChart],
+ transform: transforms,
+ };
+ }
+ case "unknown":
+ return null;
+ default:
+ logNever(type);
+ return null;
+ }
+ }
+
+ private getScale() {
+ return {
+ align: 0,
+ paddingInner: 0,
+ paddingOuter: {
+ expr: `length(data('${this.sourceName}')) == 2 ? 1 : length(data('${this.sourceName}')) == 3 ? 0.5 : length(data('${this.sourceName}')) == 4 ? 0 : 0`,
+ },
+ };
+ }
+}
diff --git a/frontend/src/components/data-table/column-summary.tsx b/frontend/src/components/data-table/column-summary/column-summary.tsx
similarity index 92%
rename from frontend/src/components/data-table/column-summary.tsx
rename to frontend/src/components/data-table/column-summary/column-summary.tsx
index bfaa85feec..9fa4eb7ded 100644
--- a/frontend/src/components/data-table/column-summary.tsx
+++ b/frontend/src/components/data-table/column-summary/column-summary.tsx
@@ -5,10 +5,10 @@ import { useTheme } from "@/theme/useTheme";
import { logNever } from "@/utils/assertNever";
import { prettyDate } from "@/utils/dates";
import { prettyNumber, prettyScientificNumber } from "@/utils/numbers";
-import { ChartSkeleton } from "../charts/chart-skeleton";
-import { DelayMount } from "../utils/delay-mount";
+import { DelayMount } from "../../utils/delay-mount";
+import { DatePopover } from "../date-popover";
+import { ChartSkeleton } from "./chart-skeleton";
import { ColumnChartSpecModel } from "./chart-spec-model";
-import { DatePopover } from "./date-popover";
export const ColumnChartContext = React.createContext<
ColumnChartSpecModel<unknown>
@@ -136,11 +136,14 @@ export const TableColumnSummary = <TData, TValue>({
case "time":
return null;
case "string":
- return (
- <div className="flex flex-col whitespace-pre">
- <span>unique: {prettyNumber(stats.unique)}</span>
- </div>
- );
+ if (!spec) {
+ return (
+ <div className="flex flex-col whitespace-pre">
+ <span>unique: {prettyNumber(stats.unique)}</span>
+ </div>
+ );
+ }
+ return null;
case "unknown":
return (
<div className="flex flex-col whitespace-pre">
diff --git a/frontend/src/components/data-table/column-summary/legacy-chart-spec.ts b/frontend/src/components/data-table/column-summary/legacy-chart-spec.ts
new file mode 100644
index 0000000000..9dbdafaff0
--- /dev/null
+++ b/frontend/src/components/data-table/column-summary/legacy-chart-spec.ts
@@ -0,0 +1,242 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+
+// New spec is under a feature flag, we keep this until full migration
+
+import { mint, orange, slate } from "@radix-ui/colors";
+import type { Scale } from "vega-lite/build/src/scale";
+import type { TopLevelFacetedUnitSpec } from "@/plugins/impl/data-explorer/queries/types";
+
+export function getLegacyNumericSpec(
+ column: string,
+ format: string,
+ base: TopLevelFacetedUnitSpec,
+): TopLevelFacetedUnitSpec {
+ return {
+ ...base, // Assuming base contains shared configurations
+ // Two layers: one with the visible bars, and one with invisible bars
+ // that provide a larger tooltip area.
+ // @ts-expect-error 'layer' property not in TopLevelFacetedUnitSpec
+ layer: [
+ {
+ mark: {
+ type: "bar",
+ color: mint.mint11,
+ },
+ encoding: {
+ x: {
+ field: column,
+ type: "quantitative",
+ bin: true,
+ },
+ y: {
+ aggregate: "count",
+ type: "quantitative",
+ axis: null,
+ },
+ },
+ },
+
+ // Tooltip layer
+ {
+ mark: {
+ type: "bar",
+ opacity: 0,
+ },
+ encoding: {
+ x: {
+ field: column,
+ type: "quantitative",
+ bin: true,
+ axis: {
+ title: null,
+ labelFontSize: 8.5,
+ labelOpacity: 0.5,
+ labelExpr:
+ "(datum.value >= 10000 || datum.value <= -10000) ? format(datum.value, '.2e') : format(datum.value, '.2~f')",
+ },
+ },
+ y: {
+ aggregate: "max",
+ type: "quantitative",
+ axis: null,
+ },
+ tooltip: [
+ {
+ field: column,
+ type: "quantitative",
+ bin: true,
+ title: column,
+ format: format,
+ },
+ {
+ aggregate: "count",
+ type: "quantitative",
+ title: "Count",
+ format: ",d",
+ },
+ ],
+ },
+ },
+ ],
+ };
+}
+
+export function getLegacyTemporalSpec(
+ column: string,
+ type: "date" | "datetime" | "time",
+ base: TopLevelFacetedUnitSpec,
+ scale: Scale,
+): TopLevelFacetedUnitSpec {
+ const format =
+ type === "date"
+ ? "%Y-%m-%d"
+ : type === "time"
+ ? "%H:%M:%S"
+ : "%Y-%m-%dT%H:%M:%S";
+
+ return {
+ ...base,
+ // Two layers: one with the visible bars, and one with invisible bars
+ // that provide a larger tooltip area.
+ // @ts-expect-error 'layer' property not in TopLevelFacetedUnitSpec
+ layer: [
+ {
+ mark: {
+ type: "bar",
+ color: mint.mint11,
+ },
+ encoding: {
+ x: {
+ field: column,
+ type: "temporal",
+ axis: null,
+ bin: true,
+ scale: scale,
+ },
+ y: { aggregate: "count", type: "quantitative", axis: null },
+ // Color nulls
+ color: {
+ condition: {
+ test: `datum["bin_maxbins_10_${column}_range"] === "null"`,
+ value: orange.orange11,
+ },
+ value: mint.mint11,
+ },
+ },
+ },
+
+ // 0 opacity full-height bars with tooltips, since it is too hard to trigger
+ // the tooltip for very small bars.
+ {
+ mark: {
+ type: "bar",
+ opacity: 0,
+ },
+ encoding: {
+ x: {
+ field: column,
+ type: "temporal",
+ axis: null,
+ bin: true,
+ scale: scale,
+ },
+ y: { aggregate: "max", type: "quantitative", axis: null },
+ tooltip: [
+ {
+ // Can also use column, but this is more explicit
+ field: `bin_maxbins_10_${column}`,
+ type: "temporal",
+ format: format,
+ bin: { binned: true },
+ title: `${column} (start)`,
+ },
+ {
+ field: `bin_maxbins_10_${column}_end`,
+ type: "temporal",
+ format: format,
+ bin: { binned: true },
+ title: `${column} (end)`,
+ },
+ {
+ aggregate: "count",
+ type: "quantitative",
+ title: "Count",
+ format: ",d",
+ },
+ ],
+ // Color nulls
+ color: {
+ condition: {
+ test: `datum["bin_maxbins_10_${column}_range"] === "null"`,
+ value: orange.orange11,
+ },
+ value: mint.mint11,
+ },
+ },
+ },
+ ],
+ };
+}
+
+export function getLegacyBooleanSpec(
+ column: string,
+ base: TopLevelFacetedUnitSpec,
+ barHeight: number,
+): TopLevelFacetedUnitSpec {
+ return {
+ ...base,
+ mark: { type: "bar", color: mint.mint11 },
+ encoding: {
+ y: {
+ field: column,
+ type: "nominal",
+ axis: {
+ labelExpr:
+ "datum.label === 'true' || datum.label === 'True' ? 'True' : 'False'",
+ tickWidth: 0,
+ title: null,
+ labelColor: slate.slate9,
+ },
+ },
+ x: {
+ aggregate: "count",
+ type: "quantitative",
+ axis: null,
+ scale: { type: "linear" },
+ },
+ tooltip: [
+ { field: column, type: "nominal", title: "Value" },
+ {
+ aggregate: "count",
+ type: "quantitative",
+ title: "Count",
+ format: ",d",
+ },
+ ],
+ },
+ layer: [
+ {
+ mark: {
+ type: "bar",
+ color: mint.mint11,
+ height: barHeight,
+ },
+ },
+ {
+ mark: {
+ type: "text",
+ align: "left",
+ baseline: "middle",
+ dx: 3,
+ color: slate.slate9,
+ },
+ encoding: {
+ text: {
+ aggregate: "count",
+ type: "quantitative",
+ },
+ },
+ },
+ ],
+ } as TopLevelFacetedUnitSpec; // "layer" not in TopLevelFacetedUnitSpec
+}
diff --git a/frontend/src/components/data-table/column-summary/utils.ts b/frontend/src/components/data-table/column-summary/utils.ts
new file mode 100644
index 0000000000..d0170eba0b
--- /dev/null
+++ b/frontend/src/components/data-table/column-summary/utils.ts
@@ -0,0 +1,78 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+
+import type { StringFieldDef } from "vega-lite/build/src/channeldef";
+import { Logger } from "@/utils/Logger";
+import type { BinValues } from "../types";
+
+const READABLE_TIME_FORMAT = "%-I:%M:%S %p"; // e.g., 1:02:30 AM (no leading zero on hour)
+
+export function getPartialTimeTooltip(
+ values: BinValues,
+): Partial<StringFieldDef<string>> {
+ if (values.length === 0) {
+ return {};
+ }
+
+ // Find non-null value
+ const value = values.find((v) => v.bin_start !== null)?.bin_start;
+ if (!value) {
+ return {};
+ }
+
+ // If value is a year (2019, 2020, etc), we return empty as it bugs out when we return a time unit
+ if (typeof value === "number" && value.toString().length === 4) {
+ return {};
+ }
+
+ // If value is just time (00:00:00, 01:00:00, etc)
+ if (typeof value === "string" && value.length === 8) {
+ return {
+ type: "temporal",
+ timeUnit: "hoursminutesseconds",
+ format: READABLE_TIME_FORMAT,
+ };
+ }
+
+ // If value is a date (2019-01-01, 2020-01-01, etc)
+ if (typeof value === "string" && value.length === 10) {
+ return {
+ type: "temporal",
+ timeUnit: "yearmonthdate",
+ };
+ }
+
+ // If value is a datetime (2019-01-01 00:00:00, 2020-01-01 00:00:00, 2023-05-15T01:00:00 etc)
+ if (typeof value === "string" && value.length === 19) {
+ const minimumValue = value; // non-null value
+ const maximumValue = values[values.length - 1].bin_end;
+
+ try {
+ const minimumDate = new Date(minimumValue);
+ const maximumDate = new Date(maximumValue as string);
+ const timeDifference = maximumDate.getTime() - minimumDate.getTime();
+
+ // If time difference is less than 1 day, we use hoursminutesseconds
+ if (timeDifference < 1000 * 60 * 60 * 24) {
+ return {
+ type: "temporal",
+ timeUnit: "hoursminutesseconds",
+ format: READABLE_TIME_FORMAT,
+ };
+ }
+ } catch (error) {
+ Logger.debug("Error parsing date", error);
+ }
+
+ return {
+ type: "temporal",
+ timeUnit: "yearmonthdatehoursminutes",
+ };
+ }
+
+ Logger.debug("Unknown time unit", value);
+
+ return {
+ type: "temporal",
+ timeUnit: "yearmonthdate",
+ };
+}
diff --git a/frontend/src/components/data-table/columns.tsx b/frontend/src/components/data-table/columns.tsx
index 2901b4fd16..0daf058388 100644
--- a/frontend/src/components/data-table/columns.tsx
+++ b/frontend/src/components/data-table/columns.tsx
@@ -15,9 +15,9 @@ import { JsonOutput } from "../editor/output/JsonOutput";
import { Button } from "../ui/button";
import { Checkbox } from "../ui/checkbox";
import { Popover, PopoverContent, PopoverTrigger } from "../ui/popover";
-import type { ColumnChartSpecModel } from "./chart-spec-model";
import { DataTableColumnHeader } from "./column-header";
-import { TableColumnSummary } from "./column-summary";
+import type { ColumnChartSpecModel } from "./column-summary/chart-spec-model";
+import { TableColumnSummary } from "./column-summary/column-summary";
import { DatePopover } from "./date-popover";
import type { FilterType } from "./filters";
import { getMimeValues, MimeCell } from "./mime-cell";
diff --git a/frontend/src/components/data-table/types.ts b/frontend/src/components/data-table/types.ts
index 60c3e756cc..34241f36fe 100644
--- a/frontend/src/components/data-table/types.ts
+++ b/frontend/src/components/data-table/types.ts
@@ -20,7 +20,7 @@ export const ColumnHeaderStatsKeys = [
"p25",
"p75",
"p95",
-];
+] as const;
export type ColumnHeaderStatsKey = (typeof ColumnHeaderStatsKeys)[number];
export type ColumnHeaderStats = Record<
ColumnHeaderStatsKey,
@@ -43,12 +43,18 @@ export function toFieldTypes(
}
interface BinValue {
- bin_start: number;
- bin_end: number;
+ bin_start: number | string | Date | null;
+ bin_end: number | string | Date | null;
count: number;
}
export type BinValues = BinValue[];
+interface ValueCount {
+ value: string;
+ count: number;
+}
+export type ValueCounts = ValueCount[];
+
export const SELECT_COLUMN_ID = "__select__";
export const INDEX_COLUMN_NAME = "_marimo_row_id";
diff --git a/frontend/src/components/datasources/column-preview.tsx b/frontend/src/components/datasources/column-preview.tsx
index fbfb460629..1bf28e766c 100644
--- a/frontend/src/components/datasources/column-preview.tsx
+++ b/frontend/src/components/datasources/column-preview.tsx
@@ -20,6 +20,7 @@ import type { TopLevelFacetedUnitSpec } from "@/plugins/impl/data-explorer/queri
import { type Theme, useTheme } from "@/theme/useTheme";
import { Events } from "@/utils/events";
import { prettyNumber } from "@/utils/numbers";
+import type { ColumnHeaderStatsKey } from "../data-table/types";
import { CopyClipboardIcon } from "../icons/copy-icon";
import { Spinner } from "../icons/spinner";
import { Button } from "../ui/button";
@@ -171,7 +172,9 @@ export function renderPreviewError({
}
export function renderStats(
- stats: Record<string, string | number | boolean | null>,
+ stats: Partial<
+ Record<ColumnHeaderStatsKey, string | number | boolean | null | undefined>
+ >,
dataType: DataType,
) {
return (
@@ -184,7 +187,7 @@ export function renderStats(
return (
<div key={key} className="flex items-center gap-1 group">
<span className="text-xs min-w-[60px] capitalize">
- {convertStatsName(key, dataType)}
+ {convertStatsName(key as ColumnHeaderStatsKey, dataType)}
</span>
<span className="text-xs font-bold text-muted-foreground tracking-wide">
{prettyNumber(value)}
diff --git a/frontend/src/plugins/impl/DataTablePlugin.tsx b/frontend/src/plugins/impl/DataTablePlugin.tsx
index 2ef09f4c9e..279da89a6c 100644
--- a/frontend/src/plugins/impl/DataTablePlugin.tsx
+++ b/frontend/src/plugins/impl/DataTablePlugin.tsx
@@ -24,11 +24,11 @@ import useEvent from "react-use-event-hook";
import { z } from "zod";
import type { CellSelectionState } from "@/components/data-table/cell-selection/types";
import type { CellStyleState } from "@/components/data-table/cell-styling/types";
-import { ColumnChartSpecModel } from "@/components/data-table/chart-spec-model";
import { TablePanel } from "@/components/data-table/charts/charts";
import { hasChart } from "@/components/data-table/charts/storage";
import { ColumnExplorerPanel } from "@/components/data-table/column-explorer-panel/column-explorer";
-import { ColumnChartContext } from "@/components/data-table/column-summary";
+import { ColumnChartSpecModel } from "@/components/data-table/column-summary/chart-spec-model";
+import { ColumnChartContext } from "@/components/data-table/column-summary/column-summary";
import {
type ColumnFilterValue,
filterToFilterCondition,
@@ -45,6 +45,7 @@ import {
TOO_MANY_ROWS,
type TooManyRows,
toFieldTypes,
+ type ValueCounts,
} from "@/components/data-table/types";
import { loadTableData } from "@/components/data-table/utils";
import { ContextAwarePanelItem } from "@/components/editor/chrome/panels/context-aware-panel/context-aware-panel";
@@ -88,6 +89,7 @@ interface ColumnSummaries<T = unknown> {
data: TableData<T> | null | undefined;
stats: Record<ColumnName, ColumnHeaderStats>;
bin_values: Record<ColumnName, BinValues>;
+ value_counts: Record<ColumnName, ValueCounts>;
is_disabled?: boolean;
}
@@ -139,10 +141,17 @@ const columnStats = z.object({
p95: maybeNumber,
});
-const binValues = z.array(
+const binValues: z.ZodType<BinValues> = z.array(
z.object({
- bin_start: z.number(),
- bin_end: z.number(),
+ bin_start: z.union([z.number(), z.string(), z.instanceof(Date)]),
+ bin_end: z.union([z.number(), z.string(), z.instanceof(Date)]),
+ count: z.number(),
+ }),
+);
+
+const valueCounts: z.ZodType<ValueCounts> = z.array(
+ z.object({
+ value: z.string(),
count: z.number(),
}),
);
@@ -265,6 +274,7 @@ export const DataTablePlugin = createPlugin<S>("marimo-table")
.nullable(),
stats: z.record(z.string(), columnStats),
bin_values: z.record(z.string(), binValues),
+ value_counts: z.record(z.string(), valueCounts),
is_disabled: z.boolean().optional(),
}),
),
@@ -566,8 +576,10 @@ export const LoadingDataTableComponent = memo(
const { data: columnSummaries, error: columnSummariesError } = useAsyncData<
ColumnSummaries<T>
>(async () => {
+ // TODO: props.get_column_summaries is always true,
+ // so we are unable to detect if the function is registered
if (props.totalRows === 0 || !props.showColumnSummaries) {
- return { data: null, stats: {}, bin_values: {} };
+ return { data: null, stats: {}, bin_values: {}, value_counts: {} };
}
return props.get_column_summaries({ precompute });
}, [
@@ -723,6 +735,7 @@ const DataTableComponent = ({
fieldTypesWithoutExternalTypes,
columnSummaries.stats,
columnSummaries.bin_values,
+ columnSummaries.value_counts,
{
includeCharts: Boolean(columnSummaries.data),
usePreComputedValues: getFeatureFlag("performant_table_charts"),
diff --git a/frontend/src/plugins/impl/data-frames/DataFramePlugin.tsx b/frontend/src/plugins/impl/data-frames/DataFramePlugin.tsx
index 024fdc937f..76d2cf618e 100644
--- a/frontend/src/plugins/impl/data-frames/DataFramePlugin.tsx
+++ b/frontend/src/plugins/impl/data-frames/DataFramePlugin.tsx
@@ -294,5 +294,10 @@ export const DataFrameComponent = memo(
DataFrameComponent.displayName = "DataFrameComponent";
function getColumnSummaries() {
- return Promise.resolve({ stats: {}, data: null, bin_values: {} });
+ return Promise.resolve({
+ stats: {},
+ data: null,
+ bin_values: {},
+ value_counts: {},
+ });
}
diff --git a/marimo/_data/models.py b/marimo/_data/models.py
index 610392b31f..c80d8134ab 100644
--- a/marimo/_data/models.py
+++ b/marimo/_data/models.py
@@ -140,13 +140,28 @@ class BinValue:
Represents bin values for a column in a data table. This is used for plotting.
Attributes:
- bin_start (float): The start of the bin.
- bin_end (float): The end of the bin.
+ bin_start (NonNestedLiteral): The start of the bin.
+ bin_end (NonNestedLiteral): The end of the bin.
count (int): The count of values in the bin.
"""
- bin_start: float
- bin_end: float
+ bin_start: NonNestedLiteral
+ bin_end: NonNestedLiteral
+ count: int
+
+
+@dataclass
+class ValueCount:
+ """
+ Represents a value and its count in a column in a data table.
+ Currently used for string columns.
+
+ Attributes:
+ value (str): The value.
+ count (int): The count of the value.
+ """
+
+ value: str
count: int
diff --git a/marimo/_plugins/ui/_impl/table.py b/marimo/_plugins/ui/_impl/table.py
index 3e4d8b3704..0e0264afd7 100644
--- a/marimo/_plugins/ui/_impl/table.py
+++ b/marimo/_plugins/ui/_impl/table.py
@@ -18,7 +18,7 @@ from narwhals.typing import IntoDataFrame
import marimo._output.data.data as mo_data
from marimo import _loggers
-from marimo._data.models import BinValue, ColumnStats
+from marimo._data.models import BinValue, ColumnStats, ValueCount
from marimo._data.preview_column import get_column_preview_dataset
from marimo._dependencies.dependencies import DependencyManager
from marimo._messaging.ops import ColumnPreview
@@ -96,13 +96,13 @@ class ColumnSummaries:
data: Union[JSONType, str]
stats: dict[ColumnName, ColumnStats]
bin_values: dict[ColumnName, list[BinValue]]
+ value_counts: dict[ColumnName, list[ValueCount]]
# Disabled because of too many columns/rows
# This will show a banner in the frontend
is_disabled: Optional[bool] = None
DEFAULT_MAX_COLUMNS = 50
-DEFAULT_NUM_BINS = 9
MaxColumnsNotProvided = Literal["inherit"]
MAX_COLUMNS_NOT_PROVIDED: MaxColumnsNotProvided = "inherit"
@@ -829,6 +829,7 @@ class table(
data=None,
stats={},
bin_values={},
+ value_counts={},
# This is not 'disabled' because of too many rows
# so we don't want to display the banner
is_disabled=False,
@@ -843,27 +844,30 @@ class table(
data=None,
stats={},
bin_values={},
+ value_counts={},
is_disabled=True,
)
- # Get column stats if not chart-only mode
- should_get_stats = self._show_column_summaries != "chart"
+ # If we are above the limit to show charts,
+ # or if we are in stats-only mode,
+ # we don't return the chart data
should_get_chart_data = (
self._show_column_summaries != "stats"
and total_rows <= self._column_charts_row_limit
)
# Get column stats if not chart-only mode
+ should_get_stats = self._show_column_summaries != "chart"
stats: dict[ColumnName, ColumnStats] = {}
- # If we are above the limit to show charts,
- # or if we are in stats-only mode,
- # we don't return the chart data
chart_data = None
bin_values: dict[ColumnName, list[BinValue]] = {}
-
+ value_counts: dict[ColumnName, list[ValueCount]] = {}
data = self._searched_manager
+ DEFAULT_BIN_SIZE = 9
+ DEFAULT_VALUE_COUNTS_SIZE = 15
+
for column in self._manager.get_column_names():
if should_get_stats:
try:
@@ -875,16 +879,54 @@ class table(
LOGGER.warning("Failed to get stats for column %s", column)
if should_get_chart_data and args.precompute:
+ if not should_get_stats:
+ LOGGER.warning("Please enable stats to precompute charts")
+
+ # For boolean columns, we can drop the column since we use stats
+ column_type = self._manager.get_field_type(column)
+ if column_type[0] == "boolean":
+ data = data.drop_columns([column])
+
+ # Bin values are only supported for numeric and temporal columns
+ if column_type[0] not in [
+ "integer",
+ "number",
+ "date",
+ "datetime",
+ "time",
+ "string",
+ ]:
+ continue
+
+ # For perf, we only compute value counts for categorical columns
+ external_type = column_type[1].lower()
+ if column_type[0] == "string" and (
+ "cat" in external_type or "enum" in external_type
+ ):
+ try:
+ val_counts = self._get_value_counts(
+ column, DEFAULT_VALUE_COUNTS_SIZE, total_rows
+ )
+ if len(val_counts) > 0:
+ value_counts[column] = val_counts
+ data = data.drop_columns([column])
+ continue
+ except BaseException as e:
+ LOGGER.warning(
+ "Failed to get value counts for column %s: %s",
+ column,
+ e,
+ )
+
try:
- # TODO: Could optimize further by getting all columns lazily
- bins = data.get_bin_values(column, DEFAULT_NUM_BINS)
+ bins = data.get_bin_values(column, DEFAULT_BIN_SIZE)
if len(bins) > 0:
bin_values[column] = bins
- # Charts will use bin_values instead of data, so we drop the column
data = data.drop_columns([column])
- except BaseException:
+ continue
+ except BaseException as e:
LOGGER.warning(
- "Failed to get bin values for column %s", column
+ "Failed to get bin values for column %s: %s", column, e
)
if should_get_chart_data:
@@ -894,9 +936,58 @@ class table(
data=chart_data,
stats=stats,
bin_values=bin_values,
+ value_counts=value_counts,
is_disabled=False,
)
+ def _get_value_counts(
+ self, column: ColumnName, size: int, total_rows: int
+ ) -> list[ValueCount]:
+ """Get value counts for a column. The last item will be 'others' with the count of remaining
+ unique values. If there are only unique values, we return 'unique values' instead.
+
+ Args:
+ column (ColumnName): The column to get value counts for.
+ size (int): The number of value counts to return.
+ total_rows (int): The total number of rows in the table.
+
+ Returns:
+ list[ValueCount]: The value counts.
+ """
+ if size <= 0 or total_rows <= 0:
+ LOGGER.warning("Total rows and size is not valid")
+ return []
+
+ top_k_rows = self._manager.calculate_top_k_rows(column, size)
+ if len(top_k_rows) == 0:
+ return []
+
+ all_unique = top_k_rows[0][1] == 1
+ if all_unique:
+ return [ValueCount(value="unique values", count=total_rows)]
+
+ value_counts = []
+
+ if len(top_k_rows) == size:
+ # reserve 1 for others
+ top_k_rows = top_k_rows[:-1]
+
+ sum_count = 0
+ for value, count in top_k_rows:
+ sum_count += count
+ value = str(value) if value is not None else "null"
+ value_counts.append(ValueCount(value=value, count=count))
+
+ remaining = total_rows - sum_count
+ if remaining > 0:
+ unique_count = ValueCount(value="others", count=remaining)
+ if len(value_counts) == size:
+ value_counts[-1] = unique_count
+ else:
+ value_counts.append(unique_count)
+
+ return value_counts
+
@classmethod
def _to_chart_data_url(
cls, table_manager: TableManager[Any]
diff --git a/marimo/_plugins/ui/_impl/tables/ibis_table.py b/marimo/_plugins/ui/_impl/tables/ibis_table.py
index 67efa0b556..b52399e986 100644
--- a/marimo/_plugins/ui/_impl/tables/ibis_table.py
+++ b/marimo/_plugins/ui/_impl/tables/ibis_table.py
@@ -1,9 +1,11 @@
# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
+import datetime
import functools
-from typing import Any, Optional
+from typing import TYPE_CHECKING, Any, Optional, Union
+from marimo import _loggers
from marimo._data.models import BinValue, ColumnStats, ExternalDataType
from marimo._dependencies.dependencies import DependencyManager
from marimo._plugins.ui._impl.tables.format import (
@@ -26,6 +28,11 @@ from marimo._plugins.ui._impl.tables.table_manager import (
)
from marimo._utils.memoize import memoize_last_value
+LOGGER = _loggers.marimo_logger()
+
+if TYPE_CHECKING:
+ from ibis import DataType # type: ignore
+
class IbisTableManagerFactory(TableManagerFactory):
@staticmethod
@@ -155,15 +162,25 @@ class IbisTableManagerFactory(TableManagerFactory):
return stats
- def get_bin_values(
- self, column: str, num_bins: int
- ) -> list[BinValue]:
- col = self.data[column]
- if not col.type().is_numeric():
- return []
-
+ def _get_numeric_bin_values(
+ self, col: ibis.Column, num_bins: int
+ ) -> ibis.Table:
min_val = col.min().execute()
max_val = col.max().execute()
+
+ # Handle case where all values are the same
+ if min_val == max_val:
+ # Create a single bin with all the data
+ total_count = col.count().execute()
+ return ibis.memtable(
+ {
+ "bin": [0],
+ "count": [total_count],
+ "bin_start": [min_val],
+ "bin_end": [max_val],
+ }
+ ).execute()
+
bin_width = (max_val - min_val) / num_bins
# Assign bins and count occurrences
@@ -186,15 +203,104 @@ class IbisTableManagerFactory(TableManagerFactory):
),
).order_by("bin")
+ return result.execute()
+
+ def get_bin_values(
+ self, column: ColumnName, num_bins: int
+ ) -> list[BinValue]:
+ """Get bin values for a column. Currently supports numeric and temporal columns.
+
+ Args:
+ column (str): The column to get bin values for.
+ num_bins (int): The number of bins to create.
+
+ Returns:
+ list[BinValue]: The bin values.
+ """
+ if column not in self.data.columns:
+ LOGGER.error(f"Column {column} not found in Ibis table")
+ return []
+
+ col = self.data[column]
+ dtype = col.type()
+
+ if dtype.is_temporal():
+ return self._get_bin_values_temporal(
+ column, dtype, num_bins
+ )
+
+ if not dtype.is_numeric():
+ return []
+
+ bin_values = self._get_numeric_bin_values(col, num_bins)
+
return [
BinValue(
bin_start=row.bin_start,
bin_end=row.bin_end,
count=row.count,
)
- for row in result.execute().itertuples(index=False)
+ for row in bin_values.itertuples(index=False)
]
+ def _get_bin_values_temporal(
+ self, column: ColumnName, dtype: DataType, num_bins: int
+ ) -> list[BinValue]:
+ def _convert_ms_to_time(ms: int) -> datetime.time:
+ hours = ms // 3600000
+ minutes = (ms % 3600000) // 60000
+ seconds = (ms % 60000) // 1000
+ microseconds = (ms % 1000) * 1000
+ return datetime.time(hours, minutes, seconds, microseconds)
+
+ col = self.data[column]
+
+ if dtype.is_time():
+ col_agg = (
+ col.hour() * 3600000
+ + col.minute() * 60000
+ + col.second() * 1000
+ + col.microsecond() // 1000
+ )
+ else:
+ col_agg = col.epoch_seconds()
+
+ numeric_bin_values = self._get_numeric_bin_values(
+ col_agg, num_bins
+ )
+
+ bin_values = []
+ bin_start: Union[
+ datetime.datetime, datetime.date, datetime.time
+ ]
+ bin_end: Union[datetime.datetime, datetime.date, datetime.time]
+
+ for row in numeric_bin_values.itertuples(index=False):
+ if dtype.is_date():
+ bin_start = datetime.date.fromtimestamp(row.bin_start)
+ bin_end = datetime.date.fromtimestamp(row.bin_end)
+ elif dtype.is_time():
+ ms = int(row.bin_start)
+ bin_start = _convert_ms_to_time(ms)
+
+ ms = int(row.bin_end)
+ bin_end = _convert_ms_to_time(ms)
+ else:
+ bin_start = datetime.datetime.fromtimestamp(
+ row.bin_start
+ )
+ bin_end = datetime.datetime.fromtimestamp(row.bin_end)
+
+ bin_values.append(
+ BinValue(
+ bin_start=bin_start,
+ bin_end=bin_end,
+ count=row.count,
+ )
+ )
+
+ return bin_values
+
@memoize_last_value
def get_num_rows(self, force: bool = True) -> Optional[int]:
if force:
diff --git a/marimo/_plugins/ui/_impl/tables/narwhals_table.py b/marimo/_plugins/ui/_impl/tables/narwhals_table.py
index 4425689eb8..c5a824ee10 100644
--- a/marimo/_plugins/ui/_impl/tables/narwhals_table.py
+++ b/marimo/_plugins/ui/_impl/tables/narwhals_table.py
@@ -1,6 +1,7 @@
# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
+import datetime
import functools
import io
from functools import cached_property
@@ -40,6 +41,7 @@ from marimo._utils.narwhals_utils import (
)
LOGGER = _loggers.marimo_logger()
+UNSTABLE_API_WARNING = "`Series.hist` is being called from the stable API although considered an unstable feature."
class NarwhalsTableManager(
@@ -438,31 +440,100 @@ class NarwhalsTableManager(
return ColumnStats(**stats_dict)
def get_bin_values(self, column: str, num_bins: int) -> list[BinValue]:
- dtype = self.nw_schema[column]
- if column not in self.nw_schema or not dtype.is_numeric():
+ if column not in self.nw_schema:
+ LOGGER.error(f"Column {column} not found in schema")
return []
- import warnings
+ dtype = self.nw_schema[column]
+
+ if dtype.is_temporal():
+ return self._get_bin_values_temporal(column, dtype, num_bins)
+
+ if not dtype.is_numeric():
+ return []
col = self.as_frame().get_column(column)
bin_start = col.min()
bin_values = []
+ import warnings
+
with warnings.catch_warnings():
warnings.filterwarnings(
- "ignore",
- message="`Series.hist` is being called from the stable API although considered an unstable feature.",
- category=UserWarning,
+ "ignore", message=UNSTABLE_API_WARNING, category=UserWarning
)
- for bin_end, count in col.hist(bin_count=num_bins).iter_rows(
- named=False
- ):
+ hist = col.hist(bin_count=num_bins)
+
+ for bin_end, count in hist.iter_rows(named=False):
+ bin_values.append(
+ BinValue(bin_start=bin_start, bin_end=bin_end, count=count)
+ )
+ bin_start = bin_end
+ return bin_values
+
+ def _get_bin_values_temporal(
+ self, column: str, dtype: Any, num_bins: int
+ ) -> list[BinValue]:
+ """
+ Get bin values for a temporal column.
+
+ nw.hist does not support temporal columns, so we convert to numeric
+ and then convert back to temporal values.
+ """
+ # Convert to timestamp in ms
+ col = self.as_frame().get_column(column)
+
+ if dtype == nw.Time:
+ col_in_ms = (
+ col.dt.hour().cast(nw.Int64) * 3600000
+ + col.dt.minute().cast(nw.Int64) * 60000
+ + col.dt.second().cast(nw.Int64) * 1000
+ + col.dt.microsecond().cast(nw.Int64) // 1000
+ )
+ else:
+ col_in_ms = col.dt.timestamp(time_unit="ms")
+
+ import warnings
+
+ with warnings.catch_warnings():
+ warnings.filterwarnings(
+ "ignore", message=UNSTABLE_API_WARNING, category=UserWarning
+ )
+ hist = col_in_ms.hist(bin_count=num_bins)
+
+ bin_values = []
+ ms_time = 1000
+
+ bin_start = col.min()
+
+ for bin_end, count in hist.iter_rows(named=False):
+ if dtype == nw.Time:
+ hours = bin_end // 3600000
+ minutes = (bin_end % 3600000) // 60000
+ seconds = (bin_end % 60000) // 1000
+ microseconds = (bin_end % 1000) * 1000
+ bin_end = datetime.time(
+ int(hours), int(minutes), int(seconds), int(microseconds)
+ )
+ elif dtype == nw.Date:
+ bin_end = datetime.date.fromtimestamp(bin_end / ms_time)
+ else:
+ bin_end = datetime.datetime.fromtimestamp(bin_end / ms_time)
+
+ # Only append if the count is greater than 0
+ if count > 0:
bin_values.append(
BinValue(bin_start=bin_start, bin_end=bin_end, count=count)
)
- bin_start = bin_end
+ bin_start = bin_end
return bin_values
+ def _sample_indexes(self, size: int, total: int) -> list[int]:
+ """Sample evenly from a list of length `total`"""
+ if total <= size:
+ return list(range(total))
+ return [round(i * (total - 1) / (size - 1)) for i in range(size)]
+
def get_num_rows(self, force: bool = True) -> Optional[int]:
# If force is true, collect the data and get the number of rows
if force:
diff --git a/marimo/_plugins/ui/_impl/tables/table_manager.py b/marimo/_plugins/ui/_impl/tables/table_manager.py
index 1ca77fc5f5..b08c1eecb2 100644
--- a/marimo/_plugins/ui/_impl/tables/table_manager.py
+++ b/marimo/_plugins/ui/_impl/tables/table_manager.py
@@ -163,7 +163,9 @@ class TableManager(abc.ABC, Generic[T]):
pass
@abc.abstractmethod
- def get_bin_values(self, column: str, num_bins: int) -> list[BinValue]:
+ def get_bin_values(
+ self, column: ColumnName, num_bins: int
+ ) -> list[BinValue]:
pass
@abc.abstractmethod
diff --git a/tests/_plugins/ui/_impl/tables/test_ibis_table.py b/tests/_plugins/ui/_impl/tables/test_ibis_table.py
index ce70ecaf7b..135ee7c3ca 100644
--- a/tests/_plugins/ui/_impl/tables/test_ibis_table.py
+++ b/tests/_plugins/ui/_impl/tables/test_ibis_table.py
@@ -434,3 +434,185 @@ class TestIbisTableManagerFactory(unittest.TestCase):
# Not supported for other column types
result = manager.get_bin_values("string", 3)
assert result == []
+
+
[email protected](not HAS_DEPS, reason="optional dependencies not installed")
+class TestTemporalColSummaries(unittest.TestCase):
+ manager: TableManager[Any]
+
+ def setUp(self) -> None:
+ import ibis
+
+ self.factory = IbisTableManagerFactory()
+ self.data = ibis.memtable(
+ {
+ "date": [
+ datetime.date(2021, 1, 1),
+ datetime.date(2021, 1, 2),
+ datetime.date(2021, 1, 3),
+ datetime.date(2021, 1, 4),
+ datetime.date(2021, 1, 5),
+ ],
+ "datetime": [
+ datetime.datetime(2021, 1, 1),
+ datetime.datetime(2021, 1, 2),
+ datetime.datetime(2021, 1, 3),
+ datetime.datetime(2021, 1, 4),
+ datetime.datetime(2021, 1, 5),
+ ],
+ "datetime_with_tz": [
+ datetime.datetime(
+ 2021, 1, 1, tzinfo=datetime.timezone.utc
+ ),
+ datetime.datetime(
+ 2021, 1, 2, tzinfo=datetime.timezone.utc
+ ),
+ datetime.datetime(
+ 2021, 1, 3, tzinfo=datetime.timezone.utc
+ ),
+ datetime.datetime(
+ 2021, 1, 4, tzinfo=datetime.timezone.utc
+ ),
+ datetime.datetime(
+ 2021, 1, 5, tzinfo=datetime.timezone.utc
+ ),
+ ],
+ "time": [
+ datetime.time(1, 2, 3),
+ datetime.time(4, 5, 6),
+ datetime.time(7, 8, 9),
+ datetime.time(10, 11, 12),
+ datetime.time(13, 14, 15),
+ ],
+ "dates_multiple": [
+ datetime.date(2021, 1, 1),
+ datetime.date(2021, 1, 1),
+ datetime.date(2021, 1, 1),
+ datetime.date(2021, 1, 1),
+ datetime.date(2021, 1, 1),
+ ],
+ "timedelta": [
+ datetime.timedelta(days=1),
+ datetime.timedelta(days=2),
+ datetime.timedelta(days=3),
+ datetime.timedelta(days=4),
+ datetime.timedelta(days=5),
+ ],
+ }
+ )
+ self.manager = self.factory.create()(self.data)
+
+ def test_date_column(self) -> None:
+ bin_values = self.manager.get_bin_values("date", 3)
+ assert bin_values == [
+ BinValue(
+ bin_start=datetime.date(2021, 1, 1),
+ bin_end=datetime.date(2021, 1, 2),
+ count=2,
+ ),
+ BinValue(
+ bin_start=datetime.date(2021, 1, 2),
+ bin_end=datetime.date(2021, 1, 4),
+ count=1,
+ ),
+ BinValue(
+ bin_start=datetime.date(2021, 1, 4),
+ bin_end=datetime.date(2021, 1, 5),
+ count=2,
+ ),
+ ]
+
+ def test_datetime_column(self) -> None:
+ bin_values = self.manager.get_bin_values("datetime", 3)
+ assert bin_values == [
+ BinValue(
+ bin_start=datetime.datetime(2021, 1, 1, 8, 0),
+ bin_end=datetime.datetime(2021, 1, 2, 16, 0),
+ count=2,
+ ),
+ BinValue(
+ bin_start=datetime.datetime(2021, 1, 2, 16, 0),
+ bin_end=datetime.datetime(2021, 1, 4, 0, 0),
+ count=1,
+ ),
+ BinValue(
+ bin_start=datetime.datetime(2021, 1, 4, 0, 0),
+ bin_end=datetime.datetime(2021, 1, 5, 8, 0),
+ count=2,
+ ),
+ ]
+
+ def test_time_column(self) -> None:
+ bin_values = self.manager.get_bin_values("time", 3)
+ print(bin_values)
+ assert bin_values == [
+ BinValue(
+ bin_start=datetime.time(1, 2, 3),
+ bin_end=datetime.time(5, 6, 7),
+ count=2,
+ ),
+ BinValue(
+ bin_start=datetime.time(5, 6, 7),
+ bin_end=datetime.time(9, 10, 11),
+ count=1,
+ ),
+ BinValue(
+ bin_start=datetime.time(9, 10, 11),
+ bin_end=datetime.time(13, 14, 15),
+ count=2,
+ ),
+ ]
+
+ def test_dates_multiple(self) -> None:
+ bin_values = self.manager.get_bin_values("dates_multiple", 3)
+ assert bin_values == [
+ BinValue(
+ bin_start=datetime.date(2021, 1, 1),
+ bin_end=datetime.date(2021, 1, 1),
+ count=5,
+ )
+ ]
+
+ @pytest.mark.xfail(reason="datetime with tz is not supported")
+ def test_datetime_with_tz(self) -> None:
+ bin_values = self.manager.get_bin_values("datetime_with_tz", 3)
+ assert bin_values == [
+ BinValue(
+ bin_start=datetime.datetime(
+ 2021, 1, 1, 8, 0, 0, tzinfo=datetime.timezone.utc
+ ),
+ bin_end=datetime.datetime(
+ 2021, 1, 2, 16, 0, 0, tzinfo=datetime.timezone.utc
+ ),
+ count=2,
+ ),
+ BinValue(
+ bin_start=datetime.datetime(
+ 2021, 1, 2, 16, 0, 0, tzinfo=datetime.timezone.utc
+ ),
+ bin_end=datetime.datetime(
+ 2021, 1, 4, 0, 0, 0, tzinfo=datetime.timezone.utc
+ ),
+ count=1,
+ ),
+ BinValue(
+ bin_start=datetime.datetime(
+ 2021, 1, 4, 0, 0, 0, tzinfo=datetime.timezone.utc
+ ),
+ bin_end=datetime.datetime(
+ 2021, 1, 5, 8, 0, 0, tzinfo=datetime.timezone.utc
+ ),
+ count=2,
+ ),
+ ]
+
+ @pytest.mark.xfail(reason="timedelta is not supported")
+ def test_timedelta_column(self) -> None:
+ bin_values = self.manager.get_bin_values("timedelta", 3)
+ assert bin_values == [
+ BinValue(
+ bin_start=datetime.timedelta(days=1),
+ bin_end=datetime.timedelta(days=2),
+ count=2,
+ )
+ ]
diff --git a/tests/_plugins/ui/_impl/tables/test_narwhals.py b/tests/_plugins/ui/_impl/tables/test_narwhals.py
index 24d3eb7f14..e21bd59e5b 100644
--- a/tests/_plugins/ui/_impl/tables/test_narwhals.py
+++ b/tests/_plugins/ui/_impl/tables/test_narwhals.py
@@ -2,6 +2,7 @@ from __future__ import annotations
import datetime
import json
+import time
import unittest
from math import isnan
from typing import Any
@@ -975,6 +976,175 @@ def _round_bin_values(bin_values: list[BinValue]) -> list[BinValue]:
]
[email protected](not HAS_DEPS, reason="optional dependencies not installed")
+ "df",
+ create_dataframes(
+ {
+ "int": [1, 2, 3, 4, 5],
+ "time": [
+ datetime.time(12, 0, 0),
+ datetime.time(13, 0, 0),
+ datetime.time(14, 0, 0),
+ datetime.time(15, 0, 0),
+ datetime.time(16, 0, 0),
+ ],
+ "dates_with_nulls": [
+ datetime.datetime(2021, 1, 1),
+ datetime.datetime(2021, 1, 2),
+ datetime.datetime(2021, 1, 3),
+ None,
+ None,
+ ],
+ "datetime_1_day": [
+ datetime.datetime(2021, 1, 1, 1, 1, 1),
+ datetime.datetime(2021, 1, 1, 2, 2, 2),
+ datetime.datetime(2021, 1, 1, 3, 3, 3),
+ datetime.datetime(2021, 1, 1, 4, 4, 4),
+ datetime.datetime(2021, 1, 1, 5, 5, 5),
+ ],
+ "timedelta": [
+ datetime.timedelta(days=1, hours=1, minutes=1, seconds=1),
+ datetime.timedelta(days=2, hours=2, minutes=2, seconds=2),
+ datetime.timedelta(days=3, hours=3, minutes=3, seconds=3),
+ datetime.timedelta(days=4, hours=4, minutes=4, seconds=4),
+ datetime.timedelta(days=5, hours=5, minutes=5, seconds=5),
+ ],
+ "datetime_with_tz": [
+ datetime.datetime(2021, 1, 1, tzinfo=datetime.timezone.utc),
+ datetime.datetime(2021, 2, 1, tzinfo=datetime.timezone.utc),
+ datetime.datetime(2021, 3, 1, tzinfo=datetime.timezone.utc),
+ datetime.datetime(2021, 4, 1, tzinfo=datetime.timezone.utc),
+ datetime.datetime(2021, 5, 1, tzinfo=datetime.timezone.utc),
+ ],
+ "dates_multiple": [
+ datetime.date(2021, 1, 1),
+ datetime.date(2021, 1, 1),
+ datetime.date(2021, 1, 1),
+ datetime.date(2021, 1, 1),
+ datetime.date(2021, 1, 1),
+ ],
+ },
+ exclude=["ibis", "duckdb"],
+ ),
+)
+class TestGetBinValuesTemporal:
+ # Testing the exact values are quite flaky,
+ # so instead we just test the count and length of the bin values
+
+ def _normalize_bin_values(
+ self, bin_values: list[BinValue]
+ ) -> list[BinValue]:
+ import pandas as pd
+
+ return [
+ BinValue(
+ bin_start=pd.Timestamp(bin_value.bin_start),
+ bin_end=pd.Timestamp(bin_value.bin_end),
+ count=bin_value.count,
+ )
+ for bin_value in bin_values
+ ]
+
+ def test_datetime(self, df: Any) -> None:
+ manager = NarwhalsTableManager.from_dataframe(df)
+ bin_values = manager.get_bin_values("datetime_1_day", 3)
+ assert len(bin_values) == 3
+ assert sum(bin_value.count for bin_value in bin_values) == 5
+
+ assert bin_values[0].count == 2
+ assert bin_values[1].count == 1
+ assert bin_values[2].count == 2
+
+ def test_dates_with_nulls(self, df: Any) -> None:
+ manager = NarwhalsTableManager.from_dataframe(df)
+ bin_values = manager.get_bin_values("dates_with_nulls", 3)
+ assert len(bin_values) == 3
+ assert sum(bin_value.count for bin_value in bin_values) == 3
+
+ assert bin_values[0].count == 1
+ assert bin_values[1].count == 1
+ assert bin_values[2].count == 1
+
+ def test_get_bin_values_time(self, df: Any) -> None:
+ import pandas as pd
+
+ manager = NarwhalsTableManager.from_dataframe(df)
+ bin_values = manager.get_bin_values("time", 3)
+
+ # Pandas doesn't support time types
+ if isinstance(df, pd.DataFrame):
+ assert bin_values == []
+ return
+
+ assert len(bin_values) == 3
+ assert sum(bin_value.count for bin_value in bin_values) == 5
+
+ assert bin_values[0].count == 2
+ assert bin_values[1].count == 1
+ assert bin_values[2].count == 2
+
+ @pytest.mark.xfail(reason="Timedelta is not supported yet", strict=False)
+ def test_timedelta(self, df: Any) -> None:
+ manager = NarwhalsTableManager.from_dataframe(df)
+ bin_values = manager.get_bin_values("timedelta", 3)
+
+ assert bin_values == [
+ BinValue(
+ bin_start=datetime.timedelta(
+ days=1, hours=1, minutes=1, seconds=1
+ ),
+ bin_end=datetime.timedelta(
+ days=2, hours=2, minutes=2, seconds=2
+ ),
+ count=1,
+ )
+ ]
+
+ @pytest.mark.xfail(
+ reason="Datetime with timezone not fully supported, loses timezone info"
+ )
+ def test_datetime_with_tz(self, df: Any) -> None:
+ manager = NarwhalsTableManager.from_dataframe(df)
+ bin_values = manager.get_bin_values("datetime_with_tz", 3)
+ assert bin_values == [
+ BinValue(
+ bin_start=datetime.datetime(
+ 2021, 1, 1, 0, 0, tzinfo=datetime.timezone.utc
+ ),
+ bin_end=datetime.datetime(
+ 2021, 2, 10, 8, 0, tzinfo=datetime.timezone.utc
+ ),
+ count=2,
+ ),
+ BinValue(
+ bin_start=datetime.datetime(
+ 2021, 2, 10, 8, 0, tzinfo=datetime.timezone.utc
+ ),
+ bin_end=datetime.datetime(
+ 2021, 3, 22, 8, 0, tzinfo=datetime.timezone.utc
+ ),
+ count=1,
+ ),
+ BinValue(
+ bin_start=datetime.datetime(
+ 2021, 3, 22, 8, 0, tzinfo=datetime.timezone.utc
+ ),
+ bin_end=datetime.datetime(
+ 2021, 5, 1, 8, 0, tzinfo=datetime.timezone.utc
+ ),
+ count=2,
+ ),
+ ]
+
+ def test_dates_multiple(self, df: Any) -> None:
+ manager = NarwhalsTableManager.from_dataframe(df)
+ bin_values = manager.get_bin_values("dates_multiple", 3)
+
+ assert len(bin_values) == 1
+ assert bin_values[0].count == 5
+
+
@pytest.mark.skipif(not HAS_DEPS, reason="optional dependencies not installed")
@pytest.mark.parametrize(
"df",
@@ -1281,8 +1451,6 @@ def test_get_sample_values_returns_primitives() -> None:
create_dataframes({f"col_{i}": [1, 2, 3] for i in range(2000)}),
)
def test_get_field_types_with_many_columns_is_performant(df: Any) -> None:
- import time
-
manager = get_table_manager(df)
start_time = time.time()
diff --git a/tests/_plugins/ui/_impl/test_table.py b/tests/_plugins/ui/_impl/test_table.py
index 340376462a..1466895dc7 100644
--- a/tests/_plugins/ui/_impl/test_table.py
+++ b/tests/_plugins/ui/_impl/test_table.py
@@ -8,6 +8,7 @@ from unittest.mock import patch
import pytest
+from marimo._data.models import ValueCount
from marimo._dependencies.dependencies import DependencyManager
from marimo._plugins import ui
from marimo._plugins.ui._impl.dataframes.transforms.types import Condition
@@ -971,6 +972,7 @@ def test_show_column_summaries_modes():
assert summaries_stats.is_disabled is False
assert summaries_stats.data is None
assert summaries_stats.bin_values == {}
+ assert summaries_stats.value_counts == {}
assert len(summaries_stats.stats) > 0
# Test chart-only mode
@@ -999,6 +1001,7 @@ def test_show_column_summaries_modes():
assert summaries_disabled.is_disabled is False
assert summaries_disabled.data is None
assert summaries_disabled.bin_values == {}
+ assert summaries_disabled.value_counts == {}
assert len(summaries_disabled.stats) == 0
# Test Default behavior
@@ -1012,6 +1015,55 @@ def test_show_column_summaries_modes():
assert table_default._component_args["show-column-summaries"] is True
+class TestTableGetValueCounts:
+ @pytest.fixture
+ def table(self) -> ui.table:
+ data = {
+ "unique": [1, 2, 3, 4, 5],
+ "repeat": [1, 1, 2, 3, 4],
+ "with_nulls": [None, None, 2, 3, 4],
+ }
+ self.total_rows = len(data["unique"])
+ return ui.table(data)
+
+ def test_all_unique_values(self, table: ui.table) -> None:
+ value_counts = table._get_value_counts(
+ column="unique", size=10, total_rows=self.total_rows
+ )
+ assert value_counts == [ValueCount(value="unique values", count=5)]
+
+ def test_repeated_values(self, table: ui.table) -> None:
+ value_counts = table._get_value_counts(
+ column="repeat", size=10, total_rows=self.total_rows
+ )
+ assert value_counts == [
+ ValueCount(value="1", count=2),
+ ValueCount(value="2", count=1),
+ ValueCount(value="3", count=1),
+ ValueCount(value="4", count=1),
+ ]
+
+ def test_with_nulls(self, table: ui.table) -> None:
+ value_counts = table._get_value_counts(
+ column="with_nulls", size=10, total_rows=self.total_rows
+ )
+ assert value_counts == [
+ ValueCount(value="null", count=2),
+ ValueCount(value="2", count=1),
+ ValueCount(value="3", count=1),
+ ValueCount(value="4", count=1),
+ ]
+
+ def test_with_smaller_limit(self, table: ui.table) -> None:
+ value_counts = table._get_value_counts(
+ column="repeat", size=2, total_rows=self.total_rows
+ )
+ assert value_counts == [
+ ValueCount(value="1", count=2),
+ ValueCount(value="others", count=3),
+ ]
+
+
def test_table_with_frozen_columns() -> None:
data = {
"a": list(range(20)),