mishig HF Staff commited on
Commit
eaa00cd
·
verified ·
1 Parent(s): eef3d08

Sync from huggingface/lerobot-dataset-visualizer via hub-sync

Browse files
AGENTS.md CHANGED
@@ -164,7 +164,9 @@ Colours, surfaces and fonts follow the Hub (moon-landing). Tokens live in `src/a
164
  - Lines and fills: `border-line` / `border-line-subtle` / `border-line-strong`, `bg-fill` / `bg-fill-strong` (hover and control fills)
165
  - Charts: `var(--chart-grid)`, `var(--chart-axis)`, `var(--fg-muted)` for ticks; CSS variables work in Recharts' SVG attributes. Three.js needs real colours: read `useTheme()` from `src/utils/theme.ts`
166
  - Chart marks take `--series-1` … `--series-8`, in that order and never cycled past the eighth (fold the rest, or facet). The order is what keeps neighbours apart under colour-vision deficiency, and it was checked on both themes' surfaces: re-run the check before changing a value. A single series is `--series-1`; the accent marks what is selected. Text never takes a series colour.
167
- - `src/components/charts.tsx` has the SVG charts the analysis tabs share: `Histogram` (hover and focus readout, selectable bins, a table for screen readers), `RangeBar`, `niceTicks`. Grids are solid hairlines, bars are rounded at the data end only and separated by a gap rather than an outline
 
 
168
  - Theme: `<html class="dark">`, set before paint by `THEME_INIT_SCRIPT` (`src/utils/theme-init.ts`) from `?__theme=` (what HF Spaces passes), then the saved choice, then the OS; `ThemeToggle` in the tab bar switches it. `dark:` utilities target that class
169
  - Fonts: Source Sans 3 (Source Sans Pro) and IBM Plex Mono via `next/font` in `layout.tsx`, as `font-sans` / `font-mono`
170
  - Accent: `--accent #ff9d00`, LeRobot orange (the logo colour) — primary interactive colour across UI. Use `bg-accent/10`, `border-accent/30`, `text-accent-fg` (a darker/lighter orange with readable contrast per theme), never raw `cyan-*`/`orange-*`
 
164
  - Lines and fills: `border-line` / `border-line-subtle` / `border-line-strong`, `bg-fill` / `bg-fill-strong` (hover and control fills)
165
  - Charts: `var(--chart-grid)`, `var(--chart-axis)`, `var(--fg-muted)` for ticks; CSS variables work in Recharts' SVG attributes. Three.js needs real colours: read `useTheme()` from `src/utils/theme.ts`
166
  - Chart marks take `--series-1` … `--series-8`, in that order and never cycled past the eighth (fold the rest, or facet). The order is what keeps neighbours apart under colour-vision deficiency, and it was checked on both themes' surfaces: re-run the check before changing a value. A single series is `--series-1`; the accent marks what is selected. Text never takes a series colour.
167
+ - `src/components/charts.tsx` has the SVG charts the analysis tabs share: `Histogram` (hover and focus readout, selectable bins, a table for screen readers), `Heatmap`, `RangeBar`, `SeriesLegend`, and the helpers `niceTicks`, `roundBins`, `seriesStyle`, `sequentialColor`. Grids are solid hairlines, bars are rounded at the data end only and separated by a gap rather than an outline
168
+ - More than eight lines in one chart: `seriesStyle(i)` gives the eight hues again, dashed, for series 9 to 16. A magnitude (a heatmap) is one hue from `sequentialColor`, whose zero is the step nearest the page in either theme
169
+ - Verdicts (smooth / moderate / jerky, consistent / high variance) use `text-good-fg` / `text-warning-fg` / `text-critical-fg` for the word and `--status-good` / `--status-warning` / `--status-critical` for a mark. They always sit beside the word, and are never series colours. Don't use raw `green-400` / `red-400`: they are unreadable on the light theme
170
  - Theme: `<html class="dark">`, set before paint by `THEME_INIT_SCRIPT` (`src/utils/theme-init.ts`) from `?__theme=` (what HF Spaces passes), then the saved choice, then the OS; `ThemeToggle` in the tab bar switches it. `dark:` utilities target that class
171
  - Fonts: Source Sans 3 (Source Sans Pro) and IBM Plex Mono via `next/font` in `layout.tsx`, as `font-sans` / `font-mono`
172
  - Accent: `--accent #ff9d00`, LeRobot orange (the logo colour) — primary interactive colour across UI. Use `bg-accent/10`, `border-accent/30`, `text-accent-fg` (a darker/lighter orange with readable contrast per theme), never raw `cyan-*`/`orange-*`
src/app/[org]/[dataset]/[episode]/episode-viewer.tsx CHANGED
@@ -972,6 +972,7 @@ function EpisodeViewerInner({
972
  <ActionInsightsPanel
973
  flatChartData={data.flatChartData}
974
  fps={datasetInfo.fps}
 
975
  crossEpisodeData={crossEpData}
976
  crossEpisodeLoading={crossEpisode.loading}
977
  crossEpisodeProgress={crossEpisode.progress}
 
972
  <ActionInsightsPanel
973
  flatChartData={data.flatChartData}
974
  fps={datasetInfo.fps}
975
+ episodeId={episodeId}
976
  crossEpisodeData={crossEpData}
977
  crossEpisodeLoading={crossEpisode.loading}
978
  crossEpisodeProgress={crossEpisode.progress}
src/app/globals.css CHANGED
@@ -58,6 +58,16 @@
58
  --series-7: #6250d6;
59
  --series-8: #e34948;
60
 
 
 
 
 
 
 
 
 
 
 
61
  --scrollbar: rgba(17, 24, 39, 0.14);
62
  --scrollbar-hover: rgba(17, 24, 39, 0.24);
63
  }
@@ -100,6 +110,10 @@
100
  --series-7: #9085e9;
101
  --series-8: #e66767;
102
 
 
 
 
 
103
  --scrollbar: rgba(255, 255, 255, 0.06);
104
  --scrollbar-hover: rgba(255, 255, 255, 0.12);
105
  }
@@ -121,6 +135,9 @@
121
  --color-fill-strong: var(--fill-strong);
122
  --color-accent-fg: var(--accent-fg);
123
  --color-flag-fg: var(--flag-fg);
 
 
 
124
  --font-sans:
125
  var(--font-source-sans), "Source Sans Pro", ui-sans-serif, system-ui,
126
  sans-serif;
 
58
  --series-7: #6250d6;
59
  --series-8: #e34948;
60
 
61
+ /* Verdicts (smooth / moderate / jerky): a fill for marks and a text colour with readable
62
+ contrast on each theme. Always beside the word it colours, never the only signal, and never
63
+ used as a series colour. */
64
+ --status-good: #0ca30c;
65
+ --status-warning: #fab219;
66
+ --status-critical: #d03b3b;
67
+ --good-fg: #15803d; /* green-700 */
68
+ --warning-fg: #a16207; /* yellow-700 */
69
+ --critical-fg: #b91c1c; /* red-700 */
70
+
71
  --scrollbar: rgba(17, 24, 39, 0.14);
72
  --scrollbar-hover: rgba(17, 24, 39, 0.24);
73
  }
 
110
  --series-7: #9085e9;
111
  --series-8: #e66767;
112
 
113
+ --good-fg: #4ade80; /* green-400 */
114
+ --warning-fg: #facc15; /* yellow-400 */
115
+ --critical-fg: #f87171; /* red-400 */
116
+
117
  --scrollbar: rgba(255, 255, 255, 0.06);
118
  --scrollbar-hover: rgba(255, 255, 255, 0.12);
119
  }
 
135
  --color-fill-strong: var(--fill-strong);
136
  --color-accent-fg: var(--accent-fg);
137
  --color-flag-fg: var(--flag-fg);
138
+ --color-good-fg: var(--good-fg);
139
+ --color-warning-fg: var(--warning-fg);
140
+ --color-critical-fg: var(--critical-fg);
141
  --font-sans:
142
  var(--font-source-sans), "Source Sans Pro", ui-sans-serif, system-ui,
143
  sans-serif;
src/components/__tests__/charts.test.ts CHANGED
@@ -1,5 +1,11 @@
1
  import { describe, expect, test } from "bun:test";
2
- import { niceTicks } from "../charts";
 
 
 
 
 
 
3
 
4
  describe("niceTicks", () => {
5
  test("covers the maximum with round steps", () => {
@@ -26,3 +32,90 @@ describe("niceTicks", () => {
26
  expect(niceTicks(0, 3)).toEqual([0]);
27
  });
28
  });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import { describe, expect, test } from "bun:test";
2
+ import {
3
+ niceTicks,
4
+ roundBinIndex,
5
+ roundBins,
6
+ sequentialColor,
7
+ seriesStyle,
8
+ } from "../charts";
9
 
10
  describe("niceTicks", () => {
11
  test("covers the maximum with round steps", () => {
 
32
  expect(niceTicks(0, 3)).toEqual([0]);
33
  });
34
  });
35
+
36
+ describe("roundBins", () => {
37
+ test("edges are round and every value is counted once", () => {
38
+ const values = [0.495, 2.1, 3.7, 4.2, 4.5, 4.9, 5.3, 6.9, 13.4];
39
+ const bins = roundBins(values, 9);
40
+
41
+ expect(bins.map((b) => b.lo)).toEqual([0, 2, 4, 6, 8, 10, 12]);
42
+ expect(bins[bins.length - 1].hi).toBe(14);
43
+ expect(bins.reduce((sum, b) => sum + b.count, 0)).toBe(values.length);
44
+ for (const value of values) {
45
+ const bin = bins[roundBinIndex(value, bins)];
46
+ expect(value).toBeGreaterThanOrEqual(bin.lo);
47
+ expect(value).toBeLessThan(bin.hi);
48
+ }
49
+ });
50
+
51
+ test("a largest value on a bin edge still has a bin", () => {
52
+ const bins = roundBins([0, 1, 2, 3, 4], 4);
53
+ expect(bins[bins.length - 1].hi).toBeGreaterThan(4);
54
+ expect(bins.reduce((sum, b) => sum + b.count, 0)).toBe(5);
55
+ });
56
+
57
+ test("small fractional values keep clean edges", () => {
58
+ const bins = roundBins([0.0521, 0.0563, 0.0612, 0.0641, 0.0729], 10);
59
+ for (const bin of bins) {
60
+ expect(String(bin.lo).length).toBeLessThan(8);
61
+ }
62
+ expect(bins.reduce((sum, b) => sum + b.count, 0)).toBe(5);
63
+ });
64
+
65
+ test("identical values make one bin, no values none", () => {
66
+ expect(roundBins([3, 3, 3], 10)).toEqual([{ lo: 3, hi: 3, count: 3 }]);
67
+ expect(roundBins([], 10)).toEqual([]);
68
+ });
69
+ });
70
+
71
+ describe("seriesStyle", () => {
72
+ test("eight hues in order, then the same hues dashed, then muted", () => {
73
+ expect(seriesStyle(0)).toEqual({
74
+ color: "var(--series-1)",
75
+ dash: undefined,
76
+ });
77
+ expect(seriesStyle(7).color).toBe("var(--series-8)");
78
+ expect(seriesStyle(8)).toEqual({ color: "var(--series-1)", dash: "6 4" });
79
+ expect(seriesStyle(15).color).toBe("var(--series-8)");
80
+ expect(seriesStyle(16).color).toBe("var(--fg-faint)");
81
+ });
82
+
83
+ test("no two of the first sixteen series look the same", () => {
84
+ const looks = Array.from({ length: 16 }, (_, i) => {
85
+ const { color, dash } = seriesStyle(i);
86
+ return `${color}/${dash ?? "solid"}`;
87
+ });
88
+ expect(new Set(looks).size).toBe(16);
89
+ });
90
+ });
91
+
92
+ describe("sequentialColor", () => {
93
+ const luminance = (rgb: string) => {
94
+ const [r, g, b] = rgb.match(/\d+/g)!.map(Number);
95
+ return 0.2126 * r + 0.7152 * g + 0.0722 * b;
96
+ };
97
+
98
+ test("zero is the step nearest the surface in each theme", () => {
99
+ // Pale on a light page, deep on a dark one.
100
+ expect(luminance(sequentialColor(0, "light"))).toBeGreaterThan(200);
101
+ expect(luminance(sequentialColor(0, "dark"))).toBeLessThan(70);
102
+ });
103
+
104
+ test("grows steadily away from the surface", () => {
105
+ for (const theme of ["light", "dark"] as const) {
106
+ const steps = [0, 0.2, 0.4, 0.6, 0.8, 1].map((t) =>
107
+ luminance(sequentialColor(t, theme)),
108
+ );
109
+ for (let i = 1; i < steps.length; i++) {
110
+ if (theme === "light") expect(steps[i]).toBeLessThan(steps[i - 1]);
111
+ else expect(steps[i]).toBeGreaterThan(steps[i - 1]);
112
+ }
113
+ }
114
+ });
115
+
116
+ test("values outside 0 to 1, and NaN, are clamped", () => {
117
+ expect(sequentialColor(-3, "light")).toBe(sequentialColor(0, "light"));
118
+ expect(sequentialColor(7, "light")).toBe(sequentialColor(1, "light"));
119
+ expect(sequentialColor(NaN, "dark")).toBe(sequentialColor(0, "dark"));
120
+ });
121
+ });
src/components/action-insights-panel.tsx CHANGED
@@ -7,6 +7,7 @@ import {
7
  XAxis,
8
  YAxis,
9
  CartesianGrid,
 
10
  ResponsiveContainer,
11
  Tooltip,
12
  } from "recharts";
@@ -19,15 +20,26 @@ import type {
19
  JerkyEpisode,
20
  AggAlignment,
21
  } from "@/app/[org]/[dataset]/[episode]/fetch-data";
 
 
 
 
 
 
 
 
 
22
  import {
23
  EpisodeLink,
24
  FlagAllButton,
25
  FlagButton,
26
  InlineLoading,
27
  PageHeader,
 
28
  Switch,
29
  crossEpisodeLoadingLabel,
30
  } from "@/components/ui";
 
31
 
32
  const FullscreenCtx = React.createContext(false);
33
  const useIsFullscreen = () => React.useContext(FullscreenCtx);
@@ -161,6 +173,85 @@ const COLORS = [
161
  "#84cc16",
162
  ];
163
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
164
  function shortName(key: string): string {
165
  const parts = key.split(CHART_CONFIG.SERIES_NAME_DELIMITER);
166
  return parts.length > 1 ? parts[parts.length - 1] : key;
@@ -209,11 +300,14 @@ function AutocorrelationSection({
209
  fps,
210
  agg,
211
  numEpisodes,
 
212
  }: {
213
  data: Record<string, number>[];
214
  fps: number;
215
  agg?: AggAutocorrelation | null;
216
  numEpisodes?: number;
 
 
217
  }) {
218
  const isFs = useIsFullscreen();
219
  const actionKeys = useMemo(
@@ -264,34 +358,38 @@ function AutocorrelationSection({
264
  const { chartData, suggestedChunk, shortKeys } = agg ??
265
  fallback ?? { chartData: [], suggestedChunk: null, shortKeys: [] };
266
  const isAgg = !!agg;
267
- const numEpisodesLabel = isAgg
268
- ? ` (${numEpisodes} episodes sampled)`
269
- : " (current episode)";
270
-
271
- const yDomain = useMemo(() => {
272
- if (chartData.length === 0 || shortKeys.length === 0)
273
- return [-0.2, 1] as [number, number];
274
- let min = Infinity;
 
275
  for (const row of chartData)
276
  for (const k of shortKeys) {
277
  const v = row[k];
278
  if (typeof v === "number" && v < min) min = v;
279
  }
280
- const lo = Math.floor(Math.min(min, 0) * 10) / 10;
281
- return [lo, 1] as [number, number];
282
  }, [chartData, shortKeys]);
 
 
 
 
283
 
284
  if (shortKeys.length === 0)
285
  return <p className="text-fg-faint italic">No action columns found.</p>;
286
 
287
  return (
288
- <div className="bg-[var(--surface-1)]/60 rounded-lg p-5 border border-line space-y-4">
289
  <div>
290
  <div className="flex items-center gap-2">
291
  <h3 className="text-sm font-semibold text-fg">
292
  Action Autocorrelation
293
  <span className="text-xs text-fg-faint ml-2 font-normal">
294
- {numEpisodesLabel}
295
  </span>
296
  </h3>
297
  <InfoToggle>
@@ -346,53 +444,81 @@ function AutocorrelationSection({
346
  <LineChart
347
  key={isAgg ? "agg" : "ep"}
348
  data={chartData}
349
- margin={{ top: 8, right: 16, left: 0, bottom: 16 }}
350
  >
351
- <CartesianGrid strokeDasharray="3 3" stroke="var(--chart-grid)" />
352
  <XAxis
353
  dataKey="lag"
354
- stroke="var(--fg-muted)"
 
 
 
 
 
355
  label={{
356
- value: "Lag (steps)",
357
  position: "insideBottom",
358
- offset: -8,
359
- fill: "var(--fg-muted)",
360
- fontSize: 13,
361
  }}
362
  />
363
  <YAxis
364
- stroke="var(--fg-muted)"
365
- domain={yDomain}
366
- tickFormatter={(v) => Number(v.toFixed(2)).toString()}
 
 
 
 
367
  />
368
  <Tooltip
369
- contentStyle={{
370
- background: "var(--surface-2)",
371
- border: "1px solid var(--line-strong)",
372
- borderRadius: 6,
373
- }}
374
- labelFormatter={(v) =>
375
- `Lag ${v} (${(Number(v) / fps).toFixed(2)}s)`
 
 
376
  }
377
- formatter={(v: number) => v.toFixed(3)}
378
  />
379
- <Line
380
- dataKey={() => 0.5}
381
- stroke="var(--chart-axis)"
382
- strokeDasharray="6 4"
383
- dot={false}
384
- name="0.5 threshold"
385
- legendType="none"
386
- isAnimationActive={false}
 
 
 
387
  />
388
- {shortKeys.map((name, i) => (
 
 
 
 
 
 
 
 
 
 
 
 
389
  <Line
390
  key={name}
391
  dataKey={name}
392
- stroke={COLORS[i % COLORS.length]}
 
 
 
 
 
 
393
  dot={false}
394
- strokeWidth={1.5}
395
- legendType="none"
396
  isAnimationActive={false}
397
  />
398
  ))}
@@ -400,18 +526,11 @@ function AutocorrelationSection({
400
  </ResponsiveContainer>
401
  </div>
402
 
403
- {/* Custom legend */}
404
- <div className="flex flex-wrap gap-x-4 gap-y-1 px-1">
405
- {shortKeys.map((name, i) => (
406
- <div key={name} className="flex items-center gap-1.5">
407
- <span
408
- className="w-3 h-[3px] rounded-full shrink-0"
409
- style={{ background: COLORS[i % COLORS.length] }}
410
- />
411
- <span className="text-xs text-fg-muted">{name}</span>
412
- </div>
413
- ))}
414
- </div>
415
  </div>
416
  );
417
  }
@@ -816,12 +935,25 @@ function VarianceHeatmap({
816
  loading: boolean;
817
  progress?: { done: number; total: number } | null;
818
  }) {
819
- const isFs = useIsFullscreen();
 
 
 
 
 
 
 
 
 
 
 
 
 
820
 
821
  if (loading) {
822
  return (
823
- <div className="bg-[var(--surface-1)]/60 rounded-lg p-5 border border-line">
824
- <h3 className="text-sm font-semibold text-fg mb-2">
825
  Cross-Episode Action Variance
826
  </h3>
827
  <InlineLoading label={crossEpisodeLoadingLabel(progress)} />
@@ -831,8 +963,8 @@ function VarianceHeatmap({
831
 
832
  if (!data) {
833
  return (
834
- <div className="bg-[var(--surface-1)]/60 rounded-lg p-5 border border-line">
835
- <h3 className="text-sm font-semibold text-fg mb-2">
836
  Cross-Episode Action Variance
837
  </h3>
838
  <p className="text-fg-faint italic text-sm">
@@ -841,57 +973,28 @@ function VarianceHeatmap({
841
  </div>
842
  );
843
  }
844
- const { actionNames, timeBins, variance, numEpisodes } = data;
845
- const numDims = actionNames.length;
846
- const numBins = timeBins.length;
847
-
848
- const maxVar = Math.max(...variance.flat(), 1e-10);
849
-
850
- const baseW = isFs ? 1000 : 560;
851
- const baseH = isFs ? 500 : 300;
852
- const cellW = Math.max(
853
- 6,
854
- Math.min(isFs ? 24 : 14, Math.floor(baseW / numBins)),
855
- );
856
- const cellH = Math.max(
857
- 20,
858
- Math.min(isFs ? 56 : 36, Math.floor(baseH / numDims)),
859
- );
860
- const labelW = 100;
861
- const svgW = labelW + numBins * cellW + 60;
862
- const svgH = numDims * cellH + 40;
863
-
864
- function varColor(v: number): string {
865
- const t = Math.sqrt(v / maxVar); // sqrt for better visual spread
866
- // Dark blue → teal → orange
867
- const r = Math.round(t * 249);
868
- const g = Math.round(t < 0.5 ? 80 + t * 200 : 180 - (t - 0.5) * 200);
869
- const b = Math.round((1 - t) * 200 + 30);
870
- return `rgb(${r},${g},${b})`;
871
- }
872
 
873
  return (
874
- <div className="bg-[var(--surface-1)]/60 rounded-lg p-5 border border-line space-y-4">
875
  <div>
876
  <div className="flex items-center gap-2">
877
  <h3 className="text-sm font-semibold text-fg">
878
  Cross-Episode Action Variance
879
  <span className="text-xs text-fg-faint ml-2 font-normal">
880
- ({numEpisodes} episodes sampled)
881
  </span>
882
  </h3>
883
  <InfoToggle>
884
  <p className="text-xs text-fg-muted">
885
- Shows how much each action dimension varies across episodes at
886
- each point in time (normalized 0–100%).
887
- <span className="text-accent-fg">
888
- {" "}
889
- High-variance regions
890
- </span>{" "}
891
  indicate multi-modal or inconsistent demonstrations — generative
892
  policies (diffusion, flow-matching) and action chunking help here
893
- by modeling multiple modes.
894
- <span className="text-blue-400"> Low-variance regions</span>{" "}
895
  indicate consistent behavior across demonstrations.
896
  <br />
897
  <span className="text-fg-faint">
@@ -912,109 +1015,29 @@ function VarianceHeatmap({
912
  </div>
913
  </div>
914
 
915
- <div className="overflow-x-auto">
916
- <svg width={svgW} height={svgH} className="block">
917
- {/* Heatmap cells */}
918
- {variance.map((row, bi) =>
919
- row.map((v, di) => (
920
- <rect
921
- key={`${bi}-${di}`}
922
- x={labelW + bi * cellW}
923
- y={di * cellH}
924
- width={cellW}
925
- height={cellH}
926
- fill={varColor(v)}
927
- stroke="var(--bg)"
928
- strokeWidth={0.5}
929
- >
930
- <title>{`${shortName(actionNames[di])} @ ${(timeBins[bi] * 100).toFixed(0)}%: var=${v.toFixed(5)}`}</title>
931
- </rect>
932
- )),
933
- )}
934
-
935
- {/* Y-axis: action names */}
936
- {actionNames.map((name, di) => (
937
- <text
938
- key={di}
939
- x={labelW - 4}
940
- y={di * cellH + cellH / 2}
941
- textAnchor="end"
942
- dominantBaseline="central"
943
- className="fill-fg-muted"
944
- fontSize={Math.min(11, cellH - 4)}
945
- >
946
- {shortName(name)}
947
- </text>
948
- ))}
949
-
950
- {/* X-axis labels */}
951
- {[0, 0.25, 0.5, 0.75, 1].map((frac) => {
952
- const binIdx = Math.round(frac * (numBins - 1));
953
- return (
954
- <text
955
- key={frac}
956
- x={labelW + binIdx * cellW + cellW / 2}
957
- y={numDims * cellH + 14}
958
- textAnchor="middle"
959
- className="fill-fg-muted"
960
- fontSize={9}
961
- >
962
- {(frac * 100).toFixed(0)}%
963
- </text>
964
- );
965
- })}
966
- <text
967
- x={labelW + (numBins * cellW) / 2}
968
- y={numDims * cellH + 30}
969
- textAnchor="middle"
970
- className="fill-fg-faint"
971
- fontSize={10}
972
- >
973
- Episode progress
974
- </text>
975
-
976
- {/* Color bar */}
977
- {Array.from({ length: 10 }, (_, i) => {
978
- const t = i / 9;
979
- const barX = labelW + numBins * cellW + 16;
980
- const barH = (numDims * cellH) / 10;
981
- return (
982
- <rect
983
- key={i}
984
- x={barX}
985
- y={(9 - i) * barH}
986
- width={12}
987
- height={barH}
988
- fill={varColor(t * maxVar)}
989
- />
990
- );
991
- })}
992
- <text
993
- x={labelW + numBins * cellW + 34}
994
- y={10}
995
- className="fill-fg-faint"
996
- fontSize={8}
997
- dominantBaseline="central"
998
- >
999
- high
1000
- </text>
1001
- <text
1002
- x={labelW + numBins * cellW + 34}
1003
- y={numDims * cellH - 4}
1004
- className="fill-fg-faint"
1005
- fontSize={8}
1006
- dominantBaseline="central"
1007
- >
1008
- low
1009
- </text>
1010
- </svg>
1011
- </div>
1012
  </div>
1013
  );
1014
  }
1015
 
1016
  // ─── Demonstrator Speed Variance ────────────────────────────────
1017
 
 
 
1018
  function SpeedVarianceSection({
1019
  distribution,
1020
  numEpisodes,
@@ -1022,73 +1045,64 @@ function SpeedVarianceSection({
1022
  distribution: SpeedDistEntry[];
1023
  numEpisodes: number;
1024
  }) {
1025
- const isFs = useIsFullscreen();
1026
- const { speeds, mean, std, cv, median, bins, lo, binW, maxBin, verdict } =
1027
- useMemo(() => {
1028
- const sp = distribution.map((d) => d.speed).sort((a, b) => a - b);
1029
- const m = sp.reduce((a, b) => a + b, 0) / sp.length;
1030
- const s = Math.sqrt(sp.reduce((a, v) => a + (v - m) ** 2, 0) / sp.length);
1031
- const c = m > 0 ? s / m : 0;
1032
- const med = sp[Math.floor(sp.length / 2)];
1033
-
1034
- const binCount = Math.min(30, Math.ceil(Math.sqrt(sp.length)));
1035
- const lo = sp[0],
1036
- hi = sp[sp.length - 1];
1037
- const bw = (hi - lo || 1) / binCount;
1038
- const b = new Array(binCount).fill(0);
1039
- for (const v of sp) {
1040
- let i = Math.floor((v - lo) / bw);
1041
- if (i >= binCount) i = binCount - 1;
1042
- b[i]++;
1043
- }
1044
-
1045
- let v: { label: string; color: string; tip: string };
1046
- if (c < 0.2)
1047
- v = {
1048
- label: "Consistent",
1049
- color: "text-green-400",
1050
- tip: "Demonstrators execute at similar speeds — no velocity normalization needed.",
1051
- };
1052
- else if (c < 0.4)
1053
- v = {
1054
- label: "Moderate variance",
1055
- color: "text-yellow-400",
1056
- tip: "Some speed variation across demonstrators. Consider velocity normalization for best results.",
1057
- };
1058
- else
1059
- v = {
1060
- label: "High variance",
1061
- color: "text-red-400",
1062
- tip: "Large speed differences between demonstrations. Velocity normalization before training is strongly recommended.",
1063
- };
1064
-
1065
- return {
1066
- speeds: sp,
1067
- mean: m,
1068
- std: s,
1069
- cv: c,
1070
- median: med,
1071
- bins: b,
1072
- lo,
1073
- binW: bw,
1074
- maxBin: Math.max(...b),
1075
- verdict: v,
1076
  };
1077
- }, [distribution]);
1078
 
1079
- if (speeds.length < 3) return null;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1080
 
1081
- const barH = isFs ? 250 : 100;
1082
- const barW = Math.max(8, Math.floor((isFs ? 900 : 500) / bins.length));
1083
 
1084
  return (
1085
- <div className="bg-[var(--surface-1)]/60 rounded-lg p-5 border border-line space-y-4">
1086
  <div>
1087
  <div className="flex items-center gap-2">
1088
  <h3 className="text-sm font-semibold text-fg">
1089
  Demonstrator Speed Variance
1090
  <span className="text-xs text-fg-faint ml-2 font-normal">
1091
- ({numEpisodes} episodes)
1092
  </span>
1093
  </h3>
1094
  <InfoToggle>
@@ -1112,71 +1126,78 @@ function SpeedVarianceSection({
1112
  </div>
1113
  </div>
1114
 
1115
- <div className="flex gap-4">
1116
- <div className="flex-1 overflow-x-auto">
1117
- <svg width={bins.length * barW} height={barH + 24} className="block">
1118
- {bins.map((count: number, i: number) => {
1119
- const h = maxBin > 0 ? (count / maxBin) * barH : 0;
1120
- const speed = lo + (i + 0.5) * binW;
1121
- const ratio = median > 0 ? speed / median : 1;
1122
- const dev = Math.abs(ratio - 1);
1123
- const color =
1124
- dev < 0.2 ? "#22c55e" : dev < 0.5 ? "#eab308" : "#ef4444";
1125
- return (
1126
- <rect
1127
- key={i}
1128
- x={i * barW}
1129
- y={barH - h}
1130
- width={barW - 1}
1131
- height={Math.max(1, h)}
1132
- fill={color}
1133
- opacity={0.7}
1134
- rx={1}
1135
- >
1136
- <title>{`Speed ${(lo + i * binW).toFixed(3)}–${(lo + (i + 1) * binW).toFixed(3)}: ${count} ep (${ratio.toFixed(2)}× median)`}</title>
1137
- </rect>
1138
- );
1139
- })}
1140
- {[0, 0.25, 0.5, 0.75, 1].map((frac) => {
1141
- const idx = Math.round(frac * (bins.length - 1));
1142
- return (
1143
- <text
1144
- key={frac}
1145
- x={idx * barW + barW / 2}
1146
- y={barH + 14}
1147
- textAnchor="middle"
1148
- className="fill-fg-muted"
1149
- fontSize={9}
1150
- >
1151
- {(lo + idx * binW).toFixed(2)}
1152
- </text>
1153
- );
1154
- })}
1155
- </svg>
1156
- </div>
1157
- <div className="flex flex-col gap-2 text-xs shrink-0 min-w-[120px]">
1158
- <div>
1159
- <span className="text-fg-faint">Mean</span>{" "}
1160
- <span className="text-fg tabular-nums ml-1">{mean.toFixed(4)}</span>
1161
- </div>
1162
- <div>
1163
- <span className="text-fg-faint">Median</span>{" "}
1164
- <span className="text-fg tabular-nums ml-1">
1165
- {median.toFixed(4)}
1166
- </span>
1167
- </div>
1168
- <div>
1169
- <span className="text-fg-faint">Std</span>{" "}
1170
- <span className="text-fg tabular-nums ml-1">{std.toFixed(4)}</span>
1171
- </div>
1172
- <div>
1173
- <span className="text-fg-faint">CV</span>
1174
- <span className={`tabular-nums ml-1 font-bold ${verdict.color}`}>
1175
- {cv.toFixed(3)}
1176
- </span>
1177
  </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1178
  </div>
1179
- </div>
1180
 
1181
  <div className="bg-[var(--surface-0)]/60 rounded-md px-4 py-3 border border-line space-y-1.5">
1182
  <p className="text-sm font-medium text-fg">
@@ -1195,11 +1216,14 @@ function StateActionAlignmentSection({
1195
  fps,
1196
  agg,
1197
  numEpisodes,
 
1198
  }: {
1199
  data: Record<string, number>[];
1200
  fps: number;
1201
  agg?: AggAlignment | null;
1202
  numEpisodes?: number;
 
 
1203
  }) {
1204
  const isFs = useIsFullscreen();
1205
  const result = useMemo(() => {
@@ -1341,28 +1365,46 @@ function StateActionAlignmentSection({
1341
  numPairs,
1342
  fromAgg,
1343
  } = result;
1344
- const scopeLabel = fromAgg
1345
- ? `${numEpisodes} episodes sampled`
1346
- : "current episode";
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1347
 
1348
  return (
1349
- <div className="bg-[var(--surface-1)]/60 rounded-lg p-5 border border-line space-y-4">
1350
  <div>
1351
  <div className="flex items-center gap-2">
1352
  <h3 className="text-sm font-semibold text-fg">
1353
  State–Action Temporal Alignment
1354
  <span className="text-xs text-fg-faint ml-2 font-normal">
1355
- ({scopeLabel}, {numPairs} matched pair{numPairs !== 1 ? "s" : ""})
1356
  </span>
1357
  </h3>
1358
  <InfoToggle>
1359
  <p className="text-xs text-fg-muted">
1360
  Per-dimension cross-correlation between Δaction<sub>d</sub>(t) and
1361
- Δstate<sub>d</sub>(t+lag), aggregated as
1362
- <span className="text-accent-fg"> max</span>,{" "}
1363
- <span className="text-fg">mean</span>, and
1364
- <span className="text-blue-400"> min</span> across all matched
1365
- action–state pairs. The{" "}
1366
  <span className="text-accent-fg">peak lag</span> reveals the
1367
  effective control delay — the time between when an action is
1368
  commanded and when the corresponding state changes.
@@ -1430,98 +1472,81 @@ function StateActionAlignmentSection({
1430
  <ResponsiveContainer width="100%" height="100%">
1431
  <LineChart
1432
  data={ccData}
1433
- margin={{ top: 8, right: 16, left: 0, bottom: 16 }}
1434
  >
1435
- <CartesianGrid strokeDasharray="3 3" stroke="var(--chart-grid)" />
1436
  <XAxis
1437
  dataKey="lag"
1438
- stroke="var(--fg-muted)"
 
 
 
 
 
1439
  label={{
1440
- value: "Lag (steps)",
1441
  position: "insideBottom",
1442
- offset: -8,
1443
- fill: "var(--fg-muted)",
1444
- fontSize: 13,
1445
  }}
1446
  />
1447
  <YAxis
1448
- stroke="var(--fg-muted)"
1449
- domain={[-0.5, 1]}
1450
- tickFormatter={(v) => Number(v.toFixed(2)).toString()}
 
 
 
 
1451
  />
1452
  <Tooltip
1453
- contentStyle={{
1454
- background: "var(--surface-2)",
1455
- border: "1px solid var(--line-strong)",
1456
- borderRadius: 6,
1457
- }}
1458
- labelFormatter={(v) =>
1459
- `Lag ${v} (${(Number(v) / fps).toFixed(3)}s)`
1460
- }
1461
- formatter={(v: number) => v.toFixed(3)}
1462
- />
1463
- <Line
1464
- dataKey="max"
1465
- stroke="#f97316"
1466
- dot={false}
1467
- strokeWidth={2}
1468
- isAnimationActive={false}
1469
- name="max"
1470
- />
1471
- <Line
1472
- dataKey="mean"
1473
- stroke="var(--fg-muted)"
1474
- dot={false}
1475
- strokeWidth={2}
1476
- isAnimationActive={false}
1477
- name="mean"
1478
- />
1479
- <Line
1480
- dataKey="min"
1481
- stroke="#3b82f6"
1482
- dot={false}
1483
- strokeWidth={2}
1484
- isAnimationActive={false}
1485
- name="min"
1486
- />
1487
- <Line
1488
- dataKey={() => 0}
1489
- stroke="var(--chart-axis)"
1490
- strokeDasharray="6 4"
1491
- dot={false}
1492
- name="zero"
1493
- legendType="none"
1494
  isAnimationActive={false}
 
 
 
 
 
 
 
 
 
1495
  />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1496
  </LineChart>
1497
  </ResponsiveContainer>
1498
  </div>
1499
 
1500
- <div className="flex flex-wrap gap-x-4 gap-y-1 px-1">
1501
- <div className="flex items-center gap-1.5">
1502
- <span className="w-3 h-[3px] rounded-full shrink-0 bg-accent" />
1503
- <span className="text-xs text-fg-muted">
1504
- max (peak: lag {maxPeakLag}, r={maxPeakCorr.toFixed(3)})
1505
- </span>
1506
- </div>
1507
- <div className="flex items-center gap-1.5">
1508
- <span className="w-3 h-[3px] rounded-full shrink-0 bg-fg-muted" />
1509
- <span className="text-xs text-fg-muted">
1510
- mean (peak: lag {meanPeakLag}, r={meanPeakCorr.toFixed(3)})
1511
- </span>
1512
- </div>
1513
- <div className="flex items-center gap-1.5">
1514
- <span className="w-3 h-[3px] rounded-full shrink-0 bg-blue-500" />
1515
- <span className="text-xs text-fg-muted">
1516
- min (peak: lag {minPeakLag}, r={minPeakCorr.toFixed(3)})
1517
- </span>
1518
- </div>
1519
- </div>
1520
 
1521
  {meanPeakLag === 0 && (
1522
- <p className="text-xs text-green-400">
1523
  Mean peak correlation at lag 0 (r={meanPeakCorr.toFixed(3)}) — actions
1524
- and state changes are well-aligned in this episode.
 
1525
  </p>
1526
  )}
1527
  </div>
@@ -1533,6 +1558,8 @@ function StateActionAlignmentSection({
1533
  interface ActionInsightsPanelProps {
1534
  flatChartData: Record<string, number>[];
1535
  fps: number;
 
 
1536
  crossEpisodeData: CrossEpisodeVarianceData | null;
1537
  crossEpisodeLoading: boolean;
1538
  crossEpisodeProgress?: { done: number; total: number } | null;
@@ -1541,12 +1568,14 @@ interface ActionInsightsPanelProps {
1541
  function ActionInsightsPanel({
1542
  flatChartData,
1543
  fps,
 
1544
  crossEpisodeData,
1545
  crossEpisodeLoading,
1546
  crossEpisodeProgress,
1547
  }: ActionInsightsPanelProps) {
1548
  const [mode, setMode] = useState<"episode" | "dataset">("dataset");
1549
  const showAgg = mode === "dataset" && !!crossEpisodeData;
 
1550
 
1551
  return (
1552
  <div className="w-full max-w-5xl mx-auto py-6 space-y-6">
@@ -1557,9 +1586,9 @@ function ActionInsightsPanel({
1557
  <Switch
1558
  checked={mode === "dataset"}
1559
  onChange={(all) => setMode(all ? "dataset" : "episode")}
1560
- offLabel="Current Episode"
1561
- onLabel={`All Episodes${crossEpisodeData ? ` (${crossEpisodeData.numEpisodes})` : ""}`}
1562
- ariaLabel="Toggle episode/dataset scope"
1563
  />
1564
  </PageHeader>
1565
 
@@ -1569,6 +1598,7 @@ function ActionInsightsPanel({
1569
  fps={fps}
1570
  agg={showAgg ? crossEpisodeData?.aggAutocorrelation : null}
1571
  numEpisodes={crossEpisodeData?.numEpisodes}
 
1572
  />
1573
  </FullscreenWrapper>
1574
  <FullscreenWrapper>
@@ -1577,6 +1607,7 @@ function ActionInsightsPanel({
1577
  fps={fps}
1578
  agg={showAgg ? crossEpisodeData?.aggAlignment : null}
1579
  numEpisodes={crossEpisodeData?.numEpisodes}
 
1580
  />
1581
  </FullscreenWrapper>
1582
 
 
7
  XAxis,
8
  YAxis,
9
  CartesianGrid,
10
+ ReferenceLine,
11
  ResponsiveContainer,
12
  Tooltip,
13
  } from "recharts";
 
20
  JerkyEpisode,
21
  AggAlignment,
22
  } from "@/app/[org]/[dataset]/[episode]/fetch-data";
23
+ import {
24
+ Heatmap,
25
+ Histogram,
26
+ LineKey,
27
+ SeriesLegend,
28
+ roundBinIndex,
29
+ roundBins,
30
+ seriesStyle,
31
+ } from "@/components/charts";
32
  import {
33
  EpisodeLink,
34
  FlagAllButton,
35
  FlagButton,
36
  InlineLoading,
37
  PageHeader,
38
+ StatCard,
39
  Switch,
40
  crossEpisodeLoadingLabel,
41
  } from "@/components/ui";
42
+ import { useTheme } from "@/utils/theme";
43
 
44
  const FullscreenCtx = React.createContext(false);
45
  const useIsFullscreen = () => React.useContext(FullscreenCtx);
 
173
  "#84cc16",
174
  ];
175
 
176
+ /// Axis and grid styling shared by the line charts: recessive, like the Episodes tab's.
177
+ const AXIS_TICK = { fontSize: 12, fill: "var(--fg-muted)" };
178
+ const AXIS_LABEL = { fontSize: 12, fill: "var(--fg-muted)" };
179
+ const SECTION =
180
+ "bg-[var(--surface-1)]/60 rounded-lg p-5 border border-line space-y-4";
181
+
182
+ /** Tick positions from `from` to `to` in steps of `step`, without floating-point drift. */
183
+ function steps(from: number, to: number, step: number): number[] {
184
+ const ticks: number[] = [];
185
+ for (let value = from; value <= to + step * 1e-6; value += step) {
186
+ ticks.push(Number(value.toFixed(6)));
187
+ }
188
+ return ticks;
189
+ }
190
+
191
+ /**
192
+ * A correlation axis reaching down to `lowest`: the domain stops at the quarter below the data, and
193
+ * the ticks sit on halves (quarters when everything is positive), so no label is an odd number.
194
+ */
195
+ function correlationAxis(lowest: number): {
196
+ domain: [number, number];
197
+ ticks: number[];
198
+ } {
199
+ const floor = Math.floor(Math.min(lowest, 0) / 0.25) * 0.25;
200
+ const step = floor < 0 ? 0.5 : 0.25;
201
+ return {
202
+ domain: [floor, 1],
203
+ ticks: steps(Math.ceil(floor / step) * step, 1, step),
204
+ };
205
+ }
206
+
207
+ /** Lag ticks at round numbers, a handful whatever the horizon. */
208
+ function lagStep(span: number): number {
209
+ return span <= 30 ? 5 : span <= 60 ? 10 : 20;
210
+ }
211
+
212
+ /**
213
+ * The readout under the pointer: every series at that lag, its key beside its name, the value
214
+ * leading. Names stay in text colours; the key carries the series colour.
215
+ */
216
+ function LineTooltip({
217
+ active,
218
+ payload,
219
+ label,
220
+ formatLabel,
221
+ series,
222
+ }: {
223
+ active?: boolean;
224
+ payload?: { name?: string | number; value?: number | string }[];
225
+ label?: number | string;
226
+ formatLabel: (label: number) => string;
227
+ series: { name: string; color: string; dash?: string }[];
228
+ }) {
229
+ if (!active || !payload?.length) return null;
230
+ const values = new Map(
231
+ payload.map((item) => [String(item.name), item.value]),
232
+ );
233
+ return (
234
+ <div className="rounded-md border border-line-strong bg-[var(--surface-2)] px-2.5 py-1.5 text-xs shadow-lg">
235
+ <p className="mb-1 text-fg-muted tabular">{formatLabel(Number(label))}</p>
236
+ <ul className="space-y-0.5">
237
+ {series.map(({ name, color, dash }) => {
238
+ const value = values.get(name);
239
+ if (typeof value !== "number") return null;
240
+ return (
241
+ <li key={name} className="flex items-center gap-2">
242
+ <LineKey color={color} dash={dash} />
243
+ <span className="text-fg-muted">{name}</span>
244
+ <span className="ml-auto pl-4 font-semibold text-fg tabular">
245
+ {value.toFixed(3)}
246
+ </span>
247
+ </li>
248
+ );
249
+ })}
250
+ </ul>
251
+ </div>
252
+ );
253
+ }
254
+
255
  function shortName(key: string): string {
256
  const parts = key.split(CHART_CONFIG.SERIES_NAME_DELIMITER);
257
  return parts.length > 1 ? parts[parts.length - 1] : key;
 
300
  fps,
301
  agg,
302
  numEpisodes,
303
+ scopeLabel,
304
  }: {
305
  data: Record<string, number>[];
306
  fps: number;
307
  agg?: AggAutocorrelation | null;
308
  numEpisodes?: number;
309
+ /** What the chart covers when it is not the dataset: `episode 12`. */
310
+ scopeLabel: string;
311
  }) {
312
  const isFs = useIsFullscreen();
313
  const actionKeys = useMemo(
 
358
  const { chartData, suggestedChunk, shortKeys } = agg ??
359
  fallback ?? { chartData: [], suggestedChunk: null, shortKeys: [] };
360
  const isAgg = !!agg;
361
+ const [highlighted, setHighlighted] = useState<string | null>(null);
362
+
363
+ const series = useMemo(
364
+ () => shortKeys.map((name, i) => ({ name, ...seriesStyle(i) })),
365
+ [shortKeys],
366
+ );
367
+ const lagCount = chartData.length;
368
+ const yAxis = useMemo(() => {
369
+ let min = 0;
370
  for (const row of chartData)
371
  for (const k of shortKeys) {
372
  const v = row[k];
373
  if (typeof v === "number" && v < min) min = v;
374
  }
375
+ return correlationAxis(min);
 
376
  }, [chartData, shortKeys]);
377
+ const xTicks = useMemo(() => {
378
+ const step = lagStep(lagCount);
379
+ return [1, ...steps(step, lagCount, step)];
380
+ }, [lagCount]);
381
 
382
  if (shortKeys.length === 0)
383
  return <p className="text-fg-faint italic">No action columns found.</p>;
384
 
385
  return (
386
+ <div className={SECTION}>
387
  <div>
388
  <div className="flex items-center gap-2">
389
  <h3 className="text-sm font-semibold text-fg">
390
  Action Autocorrelation
391
  <span className="text-xs text-fg-faint ml-2 font-normal">
392
+ {isAgg ? `${numEpisodes} episodes sampled` : scopeLabel}
393
  </span>
394
  </h3>
395
  <InfoToggle>
 
444
  <LineChart
445
  key={isAgg ? "agg" : "ep"}
446
  data={chartData}
447
+ margin={{ top: 18, right: 28, left: 0, bottom: 20 }}
448
  >
449
+ <CartesianGrid stroke="var(--chart-grid)" vertical={false} />
450
  <XAxis
451
  dataKey="lag"
452
+ type="number"
453
+ domain={[1, Math.max(2, lagCount)]}
454
+ ticks={xTicks}
455
+ stroke="var(--chart-axis)"
456
+ tick={AXIS_TICK}
457
+ tickLine={false}
458
  label={{
459
+ value: "Lag (frames)",
460
  position: "insideBottom",
461
+ offset: -12,
462
+ ...AXIS_LABEL,
 
463
  }}
464
  />
465
  <YAxis
466
+ domain={yAxis.domain}
467
+ ticks={yAxis.ticks}
468
+ interval={0}
469
+ stroke="var(--chart-axis)"
470
+ tick={AXIS_TICK}
471
+ tickLine={false}
472
+ width={44}
473
  />
474
  <Tooltip
475
+ isAnimationActive={false}
476
+ cursor={{ stroke: "var(--chart-axis)" }}
477
+ content={
478
+ <LineTooltip
479
+ series={series}
480
+ formatLabel={(lag) =>
481
+ `Lag ${lag} · ${(lag / fps).toFixed(2)}s`
482
+ }
483
+ />
484
  }
 
485
  />
486
+ {/* The threshold the suggestion is read off, labelled where it meets the edge. */}
487
+ <ReferenceLine
488
+ y={0.5}
489
+ stroke="var(--fg-faint)"
490
+ strokeDasharray="4 4"
491
+ label={{
492
+ value: "0.5",
493
+ position: "right",
494
+ fontSize: 11,
495
+ fill: "var(--fg-muted)",
496
+ }}
497
  />
498
+ {suggestedChunk && (
499
+ <ReferenceLine
500
+ x={suggestedChunk}
501
+ stroke="var(--accent)"
502
+ label={{
503
+ value: `chunk ${suggestedChunk}`,
504
+ position: "top",
505
+ fontSize: 11,
506
+ fill: "var(--accent-fg)",
507
+ }}
508
+ />
509
+ )}
510
+ {series.map(({ name, color, dash }) => (
511
  <Line
512
  key={name}
513
  dataKey={name}
514
+ name={name}
515
+ stroke={color}
516
+ strokeDasharray={dash}
517
+ strokeWidth={
518
+ highlighted === name ? 3 : series.length > 8 ? 1.5 : 2
519
+ }
520
+ strokeOpacity={highlighted && highlighted !== name ? 0.15 : 1}
521
  dot={false}
 
 
522
  isAnimationActive={false}
523
  />
524
  ))}
 
526
  </ResponsiveContainer>
527
  </div>
528
 
529
+ <SeriesLegend
530
+ series={series}
531
+ highlighted={highlighted}
532
+ onHighlight={setHighlighted}
533
+ />
 
 
 
 
 
 
 
534
  </div>
535
  );
536
  }
 
935
  loading: boolean;
936
  progress?: { done: number; total: number } | null;
937
  }) {
938
+ const theme = useTheme();
939
+
940
+ // Spread across episodes as a share of each motor's range, so a gripper in percent and a joint
941
+ // in radians are on one scale. The raw variance let the widest-ranging motor set the colours.
942
+ const rows = useMemo(() => {
943
+ if (!data) return [];
944
+ return data.actionNames.map((name, d) => {
945
+ const range = data.aggVelocity[d]?.motorRange || 1;
946
+ return {
947
+ label: shortName(name),
948
+ values: data.variance.map((bin) => Math.sqrt(bin[d]) / range),
949
+ };
950
+ });
951
+ }, [data]);
952
 
953
  if (loading) {
954
  return (
955
+ <div className={SECTION}>
956
+ <h3 className="text-sm font-semibold text-fg">
957
  Cross-Episode Action Variance
958
  </h3>
959
  <InlineLoading label={crossEpisodeLoadingLabel(progress)} />
 
963
 
964
  if (!data) {
965
  return (
966
+ <div className={SECTION}>
967
+ <h3 className="text-sm font-semibold text-fg">
968
  Cross-Episode Action Variance
969
  </h3>
970
  <p className="text-fg-faint italic text-sm">
 
973
  </div>
974
  );
975
  }
976
+ const { timeBins, numEpisodes } = data;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
977
 
978
  return (
979
+ <div className={SECTION}>
980
  <div>
981
  <div className="flex items-center gap-2">
982
  <h3 className="text-sm font-semibold text-fg">
983
  Cross-Episode Action Variance
984
  <span className="text-xs text-fg-faint ml-2 font-normal">
985
+ {numEpisodes} episodes sampled
986
  </span>
987
  </h3>
988
  <InfoToggle>
989
  <p className="text-xs text-fg-muted">
990
+ How much each action dimension differs between episodes at the
991
+ same point of their progress: the standard deviation across
992
+ episodes, as a share of that motor&apos;s range.{" "}
993
+ <span className="text-fg font-medium">High-variance regions</span>{" "}
 
 
994
  indicate multi-modal or inconsistent demonstrations — generative
995
  policies (diffusion, flow-matching) and action chunking help here
996
+ by modeling multiple modes.{" "}
997
+ <span className="text-fg font-medium">Low-variance regions</span>{" "}
998
  indicate consistent behavior across demonstrations.
999
  <br />
1000
  <span className="text-fg-faint">
 
1015
  </div>
1016
  </div>
1017
 
1018
+ <Heatmap
1019
+ rows={rows}
1020
+ theme={theme}
1021
+ ariaLabel="Spread of each action dimension across episodes, by episode progress"
1022
+ xLabel="Episode progress"
1023
+ xTicks={[0, 0.25, 0.5, 0.75, 1].map((at) => ({
1024
+ at,
1025
+ label: `${at * 100}%`,
1026
+ }))}
1027
+ formatValue={(value) => `${(value * 100).toFixed(1)}%`}
1028
+ describeColumn={(i) =>
1029
+ `at ${Math.round(timeBins[i] * 100)}% of the episode`
1030
+ }
1031
+ legend="std across episodes, as a share of the motor's range"
1032
+ />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1033
  </div>
1034
  );
1035
  }
1036
 
1037
  // ─── Demonstrator Speed Variance ────────────────────────────────
1038
 
1039
+ const SPEED_EPISODES_SHOWN = 80;
1040
+
1041
  function SpeedVarianceSection({
1042
  distribution,
1043
  numEpisodes,
 
1045
  distribution: SpeedDistEntry[];
1046
  numEpisodes: number;
1047
  }) {
1048
+ const [selectedBin, setSelectedBin] = useState<number | null>(null);
1049
+ const { mean, std, cv, median, bins, verdict } = useMemo(() => {
1050
+ const sp = distribution.map((d) => d.speed).sort((a, b) => a - b);
1051
+ const m = sp.reduce((a, b) => a + b, 0) / sp.length;
1052
+ const s = Math.sqrt(sp.reduce((a, v) => a + (v - m) ** 2, 0) / sp.length);
1053
+ const c = m > 0 ? s / m : 0;
1054
+
1055
+ let v: { label: string; color: string; tip: string };
1056
+ if (c < 0.2)
1057
+ v = {
1058
+ label: "Consistent",
1059
+ color: "text-good-fg",
1060
+ tip: "Demonstrators execute at similar speeds — no velocity normalization needed.",
1061
+ };
1062
+ else if (c < 0.4)
1063
+ v = {
1064
+ label: "Moderate variance",
1065
+ color: "text-warning-fg",
1066
+ tip: "Some speed variation across demonstrators. Consider velocity normalization for best results.",
1067
+ };
1068
+ else
1069
+ v = {
1070
+ label: "High variance",
1071
+ color: "text-critical-fg",
1072
+ tip: "Large speed differences between demonstrations. Velocity normalization before training is strongly recommended.",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1073
  };
 
1074
 
1075
+ return {
1076
+ mean: m,
1077
+ std: s,
1078
+ cv: c,
1079
+ median: sp[Math.floor(sp.length / 2)],
1080
+ bins: roundBins(sp, Math.min(30, Math.ceil(Math.sqrt(sp.length)))),
1081
+ verdict: v,
1082
+ };
1083
+ }, [distribution]);
1084
+
1085
+ const inBin = useMemo(
1086
+ () =>
1087
+ selectedBin === null
1088
+ ? []
1089
+ : distribution
1090
+ .filter((d) => roundBinIndex(d.speed, bins) === selectedBin)
1091
+ .sort((a, b) => a.speed - b.speed),
1092
+ [distribution, bins, selectedBin],
1093
+ );
1094
 
1095
+ if (distribution.length < 3) return null;
1096
+ const selected = selectedBin !== null ? bins[selectedBin] : null;
1097
 
1098
  return (
1099
+ <div className={SECTION}>
1100
  <div>
1101
  <div className="flex items-center gap-2">
1102
  <h3 className="text-sm font-semibold text-fg">
1103
  Demonstrator Speed Variance
1104
  <span className="text-xs text-fg-faint ml-2 font-normal">
1105
+ {numEpisodes} episodes
1106
  </span>
1107
  </h3>
1108
  <InfoToggle>
 
1126
  </div>
1127
  </div>
1128
 
1129
+ <div className="grid grid-cols-2 gap-3 md:grid-cols-4">
1130
+ <StatCard label="Mean" value={mean.toFixed(4)} />
1131
+ <StatCard label="Median" value={median.toFixed(4)} />
1132
+ <StatCard label="Std dev" value={std.toFixed(4)} />
1133
+ <StatCard
1134
+ label="CV (std ÷ mean)"
1135
+ value={cv.toFixed(3)}
1136
+ detail={<span className={verdict.color}>{verdict.label}</span>}
1137
+ />
1138
+ </div>
1139
+
1140
+ <div>
1141
+ <p className="mb-1 text-xs text-fg-muted">
1142
+ Episodes by mean speed. Select a bar to list its episodes.
1143
+ </p>
1144
+ <Histogram
1145
+ bins={bins}
1146
+ ariaLabel="Episodes by mean speed"
1147
+ formatValue={(value) => Number(value.toPrecision(3)).toString()}
1148
+ describeCount={(count) =>
1149
+ `${count.toLocaleString()} episode${count === 1 ? "" : "s"}`
1150
+ }
1151
+ marker={{
1152
+ value: median,
1153
+ label: `median ${Number(median.toPrecision(3))}`,
1154
+ }}
1155
+ selected={selectedBin}
1156
+ onSelect={setSelectedBin}
1157
+ />
1158
+ </div>
1159
+
1160
+ {selected && (
1161
+ <div className="rounded-md border border-accent/30 bg-accent/5 p-3">
1162
+ <div className="flex flex-wrap items-center justify-between gap-2">
1163
+ <p className="text-xs text-fg-soft tabular">
1164
+ <span className="font-semibold text-fg">
1165
+ {inBin.length.toLocaleString()} episode
1166
+ {inBin.length === 1 ? "" : "s"}
1167
+ </span>{" "}
1168
+ at {(selected.lo / (median || 1)).toFixed(2)}× to{" "}
1169
+ {(selected.hi / (median || 1)).toFixed(2)}× the median speed
1170
+ </p>
1171
+ <div className="flex items-center gap-3">
1172
+ <FlagAllButton ids={inBin.map((e) => e.episodeIndex)} />
1173
+ <button
1174
+ type="button"
1175
+ onClick={() => setSelectedBin(null)}
1176
+ className="text-xs text-fg-faint transition-colors hover:text-fg"
1177
+ >
1178
+ Clear
1179
+ </button>
1180
+ </div>
 
 
 
 
 
 
 
 
 
 
1181
  </div>
1182
+ <ul className="mt-2 flex max-h-28 flex-wrap gap-1.5 overflow-y-auto">
1183
+ {inBin.slice(0, SPEED_EPISODES_SHOWN).map((episode) => (
1184
+ <li key={episode.episodeIndex}>
1185
+ <EpisodeLink
1186
+ episode={episode.episodeIndex}
1187
+ className="block rounded border border-line bg-fill px-1.5 py-0.5 text-xs text-fg-soft"
1188
+ >
1189
+ {episode.episodeIndex}
1190
+ </EpisodeLink>
1191
+ </li>
1192
+ ))}
1193
+ {inBin.length > SPEED_EPISODES_SHOWN && (
1194
+ <li className="px-1.5 py-0.5 text-xs text-fg-faint">
1195
+ +{(inBin.length - SPEED_EPISODES_SHOWN).toLocaleString()} more
1196
+ </li>
1197
+ )}
1198
+ </ul>
1199
  </div>
1200
+ )}
1201
 
1202
  <div className="bg-[var(--surface-0)]/60 rounded-md px-4 py-3 border border-line space-y-1.5">
1203
  <p className="text-sm font-medium text-fg">
 
1216
  fps,
1217
  agg,
1218
  numEpisodes,
1219
+ scopeLabel: episodeLabel,
1220
  }: {
1221
  data: Record<string, number>[];
1222
  fps: number;
1223
  agg?: AggAlignment | null;
1224
  numEpisodes?: number;
1225
+ /** What the chart covers when it is not the dataset: `episode 12`. */
1226
+ scopeLabel: string;
1227
  }) {
1228
  const isFs = useIsFullscreen();
1229
  const result = useMemo(() => {
 
1365
  numPairs,
1366
  fromAgg,
1367
  } = result;
1368
+ const scopeLabel = fromAgg ? `${numEpisodes} episodes sampled` : episodeLabel;
1369
+
1370
+ const lagSpan = ccData.length > 0 ? ccData[ccData.length - 1].lag : 0;
1371
+ const step = lagStep(lagSpan * 2);
1372
+ const xTicks = steps(-Math.floor(lagSpan / step) * step, lagSpan, step);
1373
+ const yAxis = correlationAxis(Math.min(...ccData.map((row) => row.min)));
1374
+ // The envelope across the matched pairs: the mean in the foreground, its bounds around it.
1375
+ const series = [
1376
+ {
1377
+ name: "max",
1378
+ color: "var(--series-2)",
1379
+ note: `peak at lag ${maxPeakLag}, r = ${maxPeakCorr.toFixed(3)}`,
1380
+ },
1381
+ {
1382
+ name: "mean",
1383
+ color: "var(--fg-soft)",
1384
+ note: `peak at lag ${meanPeakLag}, r = ${meanPeakCorr.toFixed(3)}`,
1385
+ },
1386
+ {
1387
+ name: "min",
1388
+ color: "var(--series-1)",
1389
+ note: `peak at lag ${minPeakLag}, r = ${minPeakCorr.toFixed(3)}`,
1390
+ },
1391
+ ];
1392
 
1393
  return (
1394
+ <div className={SECTION}>
1395
  <div>
1396
  <div className="flex items-center gap-2">
1397
  <h3 className="text-sm font-semibold text-fg">
1398
  State–Action Temporal Alignment
1399
  <span className="text-xs text-fg-faint ml-2 font-normal">
1400
+ {scopeLabel}, {numPairs} matched pair{numPairs !== 1 ? "s" : ""}
1401
  </span>
1402
  </h3>
1403
  <InfoToggle>
1404
  <p className="text-xs text-fg-muted">
1405
  Per-dimension cross-correlation between Δaction<sub>d</sub>(t) and
1406
+ Δstate<sub>d</sub>(t+lag), aggregated as max, mean and min across
1407
+ all matched action–state pairs. The{" "}
 
 
 
1408
  <span className="text-accent-fg">peak lag</span> reveals the
1409
  effective control delay — the time between when an action is
1410
  commanded and when the corresponding state changes.
 
1472
  <ResponsiveContainer width="100%" height="100%">
1473
  <LineChart
1474
  data={ccData}
1475
+ margin={{ top: 18, right: 16, left: 0, bottom: 20 }}
1476
  >
1477
+ <CartesianGrid stroke="var(--chart-grid)" vertical={false} />
1478
  <XAxis
1479
  dataKey="lag"
1480
+ type="number"
1481
+ domain={[-lagSpan, lagSpan]}
1482
+ ticks={xTicks}
1483
+ stroke="var(--chart-axis)"
1484
+ tick={AXIS_TICK}
1485
+ tickLine={false}
1486
  label={{
1487
+ value: "Lag (frames): state after action →",
1488
  position: "insideBottom",
1489
+ offset: -12,
1490
+ ...AXIS_LABEL,
 
1491
  }}
1492
  />
1493
  <YAxis
1494
+ domain={yAxis.domain}
1495
+ ticks={yAxis.ticks}
1496
+ interval={0}
1497
+ stroke="var(--chart-axis)"
1498
+ tick={AXIS_TICK}
1499
+ tickLine={false}
1500
+ width={44}
1501
  />
1502
  <Tooltip
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1503
  isAnimationActive={false}
1504
+ cursor={{ stroke: "var(--chart-axis)" }}
1505
+ content={
1506
+ <LineTooltip
1507
+ series={series}
1508
+ formatLabel={(lag) =>
1509
+ `Lag ${lag} · ${(lag / fps).toFixed(3)}s`
1510
+ }
1511
+ />
1512
+ }
1513
  />
1514
+ <ReferenceLine y={0} stroke="var(--chart-axis)" />
1515
+ <ReferenceLine x={0} stroke="var(--chart-axis)" />
1516
+ {meanPeakLag !== 0 && (
1517
+ <ReferenceLine
1518
+ x={meanPeakLag}
1519
+ stroke="var(--accent)"
1520
+ label={{
1521
+ value: `delay ${meanPeakLag}`,
1522
+ position: "top",
1523
+ fontSize: 11,
1524
+ fill: "var(--accent-fg)",
1525
+ }}
1526
+ />
1527
+ )}
1528
+ {series.map(({ name, color }) => (
1529
+ <Line
1530
+ key={name}
1531
+ dataKey={name}
1532
+ name={name}
1533
+ stroke={color}
1534
+ strokeWidth={name === "mean" ? 2.5 : 1.5}
1535
+ dot={false}
1536
+ isAnimationActive={false}
1537
+ />
1538
+ ))}
1539
  </LineChart>
1540
  </ResponsiveContainer>
1541
  </div>
1542
 
1543
+ <SeriesLegend series={series} />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1544
 
1545
  {meanPeakLag === 0 && (
1546
+ <p className="text-xs text-good-fg">
1547
  Mean peak correlation at lag 0 (r={meanPeakCorr.toFixed(3)}) — actions
1548
+ and state changes are well-aligned
1549
+ {fromAgg ? "" : " in this episode"}.
1550
  </p>
1551
  )}
1552
  </div>
 
1558
  interface ActionInsightsPanelProps {
1559
  flatChartData: Record<string, number>[];
1560
  fps: number;
1561
+ /** The episode on screen, which "Current episode" analyses. */
1562
+ episodeId: number;
1563
  crossEpisodeData: CrossEpisodeVarianceData | null;
1564
  crossEpisodeLoading: boolean;
1565
  crossEpisodeProgress?: { done: number; total: number } | null;
 
1568
  function ActionInsightsPanel({
1569
  flatChartData,
1570
  fps,
1571
+ episodeId,
1572
  crossEpisodeData,
1573
  crossEpisodeLoading,
1574
  crossEpisodeProgress,
1575
  }: ActionInsightsPanelProps) {
1576
  const [mode, setMode] = useState<"episode" | "dataset">("dataset");
1577
  const showAgg = mode === "dataset" && !!crossEpisodeData;
1578
+ const scopeLabel = `episode ${episodeId}`;
1579
 
1580
  return (
1581
  <div className="w-full max-w-5xl mx-auto py-6 space-y-6">
 
1586
  <Switch
1587
  checked={mode === "dataset"}
1588
  onChange={(all) => setMode(all ? "dataset" : "episode")}
1589
+ offLabel={`Episode ${episodeId}`}
1590
+ onLabel={`All episodes${crossEpisodeData ? ` (${crossEpisodeData.numEpisodes} sampled)` : ""}`}
1591
+ ariaLabel="Analyse the dataset rather than this episode"
1592
  />
1593
  </PageHeader>
1594
 
 
1598
  fps={fps}
1599
  agg={showAgg ? crossEpisodeData?.aggAutocorrelation : null}
1600
  numEpisodes={crossEpisodeData?.numEpisodes}
1601
+ scopeLabel={scopeLabel}
1602
  />
1603
  </FullscreenWrapper>
1604
  <FullscreenWrapper>
 
1607
  fps={fps}
1608
  agg={showAgg ? crossEpisodeData?.aggAlignment : null}
1609
  numEpisodes={crossEpisodeData?.numEpisodes}
1610
+ scopeLabel={scopeLabel}
1611
  />
1612
  </FullscreenWrapper>
1613
 
src/components/charts.tsx CHANGED
@@ -387,3 +387,350 @@ export function RangeBar({
387
  </div>
388
  );
389
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
387
  </div>
388
  );
389
  }
390
+
391
+ /**
392
+ * How series number `index` is drawn. Eight hues, in their fixed order; past the eighth the same
393
+ * hues come round dashed, so a ninth series is still told from the first by more than position.
394
+ * Past sixteen there is nothing left to tell them apart with: those are drawn muted.
395
+ */
396
+ export function seriesStyle(index: number): {
397
+ color: string;
398
+ dash: string | undefined;
399
+ } {
400
+ if (index >= 16) return { color: "var(--fg-faint)", dash: "2 3" };
401
+ return {
402
+ color: `var(--series-${(index % 8) + 1})`,
403
+ dash: index >= 8 ? "6 4" : undefined,
404
+ };
405
+ }
406
+
407
+ /** A legend entry's key: a short stroke drawn the way the series is. */
408
+ export function LineKey({ color, dash }: { color: string; dash?: string }) {
409
+ return (
410
+ <svg width="18" height="6" aria-hidden="true" className="shrink-0">
411
+ <line
412
+ x1="1"
413
+ x2="17"
414
+ y1="3"
415
+ y2="3"
416
+ stroke={color}
417
+ strokeWidth="2"
418
+ strokeLinecap="round"
419
+ strokeDasharray={dash}
420
+ />
421
+ </svg>
422
+ );
423
+ }
424
+
425
+ /**
426
+ * The legend of a line chart. Pointing at (or focusing) an entry reports it through `onHighlight`,
427
+ * so the chart can lift that line out of the others.
428
+ */
429
+ export function SeriesLegend({
430
+ series,
431
+ highlighted,
432
+ onHighlight,
433
+ }: {
434
+ series: { name: string; color: string; dash?: string; note?: string }[];
435
+ highlighted?: string | null;
436
+ onHighlight?: (name: string | null) => void;
437
+ }) {
438
+ return (
439
+ <ul className="flex flex-wrap gap-x-4 gap-y-1 px-1">
440
+ {series.map(({ name, color, dash, note }) => (
441
+ <li key={name}>
442
+ <button
443
+ type="button"
444
+ tabIndex={onHighlight ? 0 : -1}
445
+ onPointerEnter={() => onHighlight?.(name)}
446
+ onPointerLeave={() => onHighlight?.(null)}
447
+ onFocus={() => onHighlight?.(name)}
448
+ onBlur={() => onHighlight?.(null)}
449
+ className={`flex items-center gap-1.5 rounded text-xs transition-opacity ${
450
+ onHighlight ? "cursor-default" : "pointer-events-none"
451
+ } ${highlighted && highlighted !== name ? "opacity-40" : ""}`}
452
+ >
453
+ <LineKey color={color} dash={dash} />
454
+ <span className="text-fg-muted">
455
+ {name}
456
+ {note && <span className="ml-1 text-fg-faint">{note}</span>}
457
+ </span>
458
+ </button>
459
+ </li>
460
+ ))}
461
+ </ul>
462
+ );
463
+ }
464
+
465
+ /** One hue, light to dark: the steps a magnitude is coloured with. */
466
+ const SEQUENTIAL = [
467
+ "#cde2fb",
468
+ "#b7d3f6",
469
+ "#9ec5f4",
470
+ "#86b6ef",
471
+ "#6da7ec",
472
+ "#5598e7",
473
+ "#3987e5",
474
+ "#2a78d6",
475
+ "#256abf",
476
+ "#1c5cab",
477
+ "#184f95",
478
+ "#104281",
479
+ "#0d366b",
480
+ ].map((hex) => [1, 3, 5].map((i) => parseInt(hex.slice(i, i + 2), 16)));
481
+
482
+ /** The palest step the dark theme uses: the two beyond it glare against a dark page. */
483
+ const DARK_PALEST = 2;
484
+
485
+ /**
486
+ * The colour of magnitude `t` in [0, 1]. Zero is the step nearest the surface, so "nothing" recedes
487
+ * into the background in either theme: pale on light, deep on dark.
488
+ */
489
+ export function sequentialColor(t: number, theme: "light" | "dark"): string {
490
+ const clamped = Math.max(0, Math.min(1, Number.isFinite(t) ? t : 0));
491
+ const last = SEQUENTIAL.length - 1;
492
+ const position =
493
+ theme === "dark" ? last - clamped * (last - DARK_PALEST) : clamped * last;
494
+ const lower = Math.floor(position);
495
+ const upper = Math.min(SEQUENTIAL.length - 1, lower + 1);
496
+ const mix = position - lower;
497
+ const channel = (c: number) =>
498
+ Math.round(
499
+ SEQUENTIAL[lower][c] +
500
+ (SEQUENTIAL[upper][c] - SEQUENTIAL[lower][c]) * mix,
501
+ );
502
+ return `rgb(${channel(0)}, ${channel(1)}, ${channel(2)})`;
503
+ }
504
+
505
+ const HEATMAP_LABEL_WIDTH = 132;
506
+
507
+ /**
508
+ * A grid of magnitudes: one row per label, one column per step along x, coloured from zero to the
509
+ * largest value. Pointing at a cell reads it out.
510
+ */
511
+ export function Heatmap({
512
+ rows,
513
+ theme,
514
+ xTicks,
515
+ xLabel,
516
+ formatValue,
517
+ describeColumn,
518
+ legend,
519
+ ariaLabel,
520
+ }: {
521
+ rows: { label: string; values: number[] }[];
522
+ theme: "light" | "dark";
523
+ /** Positions along x, as fractions of the width, with their labels. */
524
+ xTicks: { at: number; label: string }[];
525
+ xLabel: string;
526
+ formatValue: (value: number) => string;
527
+ /** What column `index` stands for, in the readout: `at 40% of the episode`. */
528
+ describeColumn: (index: number) => string;
529
+ /** What the colour measures, for the scale. */
530
+ legend: string;
531
+ ariaLabel: string;
532
+ }) {
533
+ const [ref, width] = useMeasuredWidth<HTMLDivElement>();
534
+ const [hovered, setHovered] = useState<{ row: number; col: number } | null>(
535
+ null,
536
+ );
537
+ const columns = rows[0]?.values.length ?? 0;
538
+ const max = Math.max(...rows.flatMap((row) => row.values), 0);
539
+ const rowHeight = rows.length <= 8 ? 26 : rows.length <= 16 ? 20 : 14;
540
+ const plotWidth = Math.max(0, width - HEATMAP_LABEL_WIDTH - 4);
541
+ const cellWidth = columns > 0 ? plotWidth / columns : 0;
542
+ const plotHeight = rows.length * rowHeight;
543
+ const height = plotHeight + 34;
544
+ const colorOf = (value: number) =>
545
+ sequentialColor(max > 0 ? value / max : 0, theme);
546
+ const cell = hovered ? rows[hovered.row].values[hovered.col] : 0;
547
+
548
+ return (
549
+ <div className="space-y-2">
550
+ <div ref={ref} className="relative w-full" style={{ height }}>
551
+ {width > 0 && (
552
+ <svg
553
+ width={width}
554
+ height={height}
555
+ role="img"
556
+ aria-label={ariaLabel}
557
+ className="block"
558
+ onPointerLeave={() => setHovered(null)}
559
+ >
560
+ {rows.map((row, r) => (
561
+ <g key={row.label}>
562
+ <text
563
+ x={HEATMAP_LABEL_WIDTH - 8}
564
+ y={r * rowHeight + rowHeight / 2}
565
+ textAnchor="end"
566
+ dominantBaseline="central"
567
+ fontSize={Math.min(12, rowHeight - 3)}
568
+ className={hovered?.row === r ? "fill-fg" : "fill-fg-muted"}
569
+ >
570
+ {row.label.length > 18
571
+ ? `${row.label.slice(0, 17)}…`
572
+ : row.label}
573
+ <title>{row.label}</title>
574
+ </text>
575
+ {row.values.map((value, c) => (
576
+ <rect
577
+ key={c}
578
+ x={HEATMAP_LABEL_WIDTH + c * cellWidth}
579
+ y={r * rowHeight}
580
+ // A hairline of surface between cells, rather than an outline around each.
581
+ width={Math.max(0.5, cellWidth - 1)}
582
+ height={rowHeight - 1}
583
+ fill={colorOf(value)}
584
+ onPointerEnter={() => setHovered({ row: r, col: c })}
585
+ />
586
+ ))}
587
+ </g>
588
+ ))}
589
+ {hovered && (
590
+ <rect
591
+ x={HEATMAP_LABEL_WIDTH + hovered.col * cellWidth - 0.5}
592
+ y={hovered.row * rowHeight - 0.5}
593
+ width={cellWidth}
594
+ height={rowHeight}
595
+ fill="none"
596
+ stroke="var(--fg)"
597
+ strokeWidth={1.5}
598
+ pointerEvents="none"
599
+ />
600
+ )}
601
+ {xTicks.map(({ at, label }) => (
602
+ <text
603
+ key={label}
604
+ x={HEATMAP_LABEL_WIDTH + at * plotWidth}
605
+ y={plotHeight + 14}
606
+ textAnchor={at <= 0 ? "start" : at >= 1 ? "end" : "middle"}
607
+ fontSize={11}
608
+ className="fill-fg-muted tabular"
609
+ >
610
+ {label}
611
+ </text>
612
+ ))}
613
+ <text
614
+ x={HEATMAP_LABEL_WIDTH + plotWidth / 2}
615
+ y={plotHeight + 30}
616
+ textAnchor="middle"
617
+ fontSize={11}
618
+ className="fill-fg-faint"
619
+ >
620
+ {xLabel}
621
+ </text>
622
+ </svg>
623
+ )}
624
+ {hovered && (
625
+ <div
626
+ className="pointer-events-none absolute z-10 -translate-x-1/2 whitespace-nowrap rounded-md border border-line-strong bg-[var(--surface-2)] px-2 py-1 text-xs shadow-lg"
627
+ style={{
628
+ left: Math.min(
629
+ Math.max(
630
+ HEATMAP_LABEL_WIDTH + (hovered.col + 0.5) * cellWidth,
631
+ 90,
632
+ ),
633
+ width - 90,
634
+ ),
635
+ top:
636
+ hovered.row * rowHeight > 46
637
+ ? hovered.row * rowHeight - 46
638
+ : (hovered.row + 1) * rowHeight + 4,
639
+ }}
640
+ >
641
+ <p className="font-semibold text-fg tabular">{formatValue(cell)}</p>
642
+ <p className="text-fg-muted">
643
+ {rows[hovered.row].label} · {describeColumn(hovered.col)}
644
+ </p>
645
+ </div>
646
+ )}
647
+ </div>
648
+
649
+ {/* The scale: what the colour measures, from nothing to the largest value drawn. */}
650
+ <div
651
+ className="flex items-center gap-2 text-[11px] text-fg-muted"
652
+ style={{ paddingLeft: HEATMAP_LABEL_WIDTH }}
653
+ >
654
+ <span className="tabular">{formatValue(0)}</span>
655
+ <div
656
+ className="h-2 w-32 rounded-sm"
657
+ style={{
658
+ background: `linear-gradient(to right, ${[0, 0.25, 0.5, 0.75, 1]
659
+ .map((t) => sequentialColor(t, theme))
660
+ .join(", ")})`,
661
+ }}
662
+ />
663
+ <span className="tabular">{formatValue(max)}</span>
664
+ <span className="ml-1 text-fg-faint">{legend}</span>
665
+ </div>
666
+
667
+ <table className="sr-only">
668
+ <caption>{ariaLabel}</caption>
669
+ <thead>
670
+ <tr>
671
+ <th>Row</th>
672
+ <th>Lowest</th>
673
+ <th>Mean</th>
674
+ <th>Highest</th>
675
+ </tr>
676
+ </thead>
677
+ <tbody>
678
+ {rows.map((row) => (
679
+ <tr key={row.label}>
680
+ <td>{row.label}</td>
681
+ <td>{formatValue(Math.min(...row.values))}</td>
682
+ <td>
683
+ {formatValue(
684
+ row.values.reduce((a, b) => a + b, 0) /
685
+ (row.values.length || 1),
686
+ )}
687
+ </td>
688
+ <td>{formatValue(Math.max(...row.values))}</td>
689
+ </tr>
690
+ ))}
691
+ </tbody>
692
+ </table>
693
+ </div>
694
+ );
695
+ }
696
+
697
+ /**
698
+ * Bins covering `values` with round edges (a width of 1, 2, 2.5 or 5 × 10ⁿ), about `target` of
699
+ * them, for the shared Histogram.
700
+ */
701
+ export function roundBins(values: number[], target: number): HistogramBin[] {
702
+ if (values.length === 0) return [];
703
+ let min = Infinity;
704
+ let max = -Infinity;
705
+ for (const value of values) {
706
+ if (value < min) min = value;
707
+ if (value > max) max = value;
708
+ }
709
+ if (max === min) return [{ lo: min, hi: max, count: values.length }];
710
+ const rough = (max - min) / Math.max(1, target);
711
+ const magnitude = Math.pow(10, Math.floor(Math.log10(rough)));
712
+ const width =
713
+ [1, 2, 2.5, 5, 10].map((m) => m * magnitude).find((w) => w >= rough) ??
714
+ rough;
715
+ const lo = Math.floor(min / width) * width;
716
+ // One more bin when the largest value sits exactly on an edge, so it has a bin to fall in.
717
+ const count = Math.max(1, Math.floor((max - lo) / width) + 1);
718
+ const edge = (i: number) => Number((lo + i * width).toPrecision(12));
719
+ const bins = Array.from({ length: count }, (_, i) => ({
720
+ lo: edge(i),
721
+ hi: edge(i + 1),
722
+ count: 0,
723
+ }));
724
+ for (const value of values) bins[roundBinIndex(value, bins)].count++;
725
+ return bins;
726
+ }
727
+
728
+ /** Which of `roundBins`' bins a value falls in. */
729
+ export function roundBinIndex(value: number, bins: HistogramBin[]): number {
730
+ if (bins.length <= 1) return 0;
731
+ const width = bins[0].hi - bins[0].lo;
732
+ return Math.max(
733
+ 0,
734
+ Math.min(bins.length - 1, Math.floor((value - bins[0].lo) / width)),
735
+ );
736
+ }