Spaces:
Running on CPU Upgrade
Running on CPU Upgrade
Sync from huggingface/lerobot-dataset-visualizer via hub-sync
Browse filesFiles changed (6)
163 unmodified lines164165166167168169170163 unmodified lines- Lines and fills: `border-line` / `border-line-subtle` / `border-line-strong`, `bg-fill` / `bg-fill-strong` (hover and control fills)- 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`- 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.- `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- 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- Fonts: Source Sans 3 (Source Sans Pro) and IBM Plex Mono via `next/font` in `layout.tsx`, as `font-sans` / `font-mono`- 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-*`163 unmodified lines164165166167168169170171172163 unmodified lines- Lines and fills: `border-line` / `border-line-subtle` / `border-line-strong`, `bg-fill` / `bg-fill-strong` (hover and control fills)- 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`- 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.- `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- 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- 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- 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- Fonts: Source Sans 3 (Source Sans Pro) and IBM Plex Mono via `next/font` in `layout.tsx`, as `font-sans` / `font-mono`- 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-*`
971 unmodified lines972973974975976977971 unmodified lines<ActionInsightsPanelflatChartData={data.flatChartData}fps={datasetInfo.fps}crossEpisodeData={crossEpData}crossEpisodeLoading={crossEpisode.loading}crossEpisodeProgress={crossEpisode.progress}971 unmodified lines972973974975976977978971 unmodified lines<ActionInsightsPanelflatChartData={data.flatChartData}fps={datasetInfo.fps}episodeId={episodeId}crossEpisodeData={crossEpData}crossEpisodeLoading={crossEpisode.loading}crossEpisodeProgress={crossEpisode.progress}
57 unmodified lines58596061626336 unmodified lines10010110210310410515 unmodified lines12112212312412512657 unmodified lines--series-7: #6250d6;--series-8: #e34948;--scrollbar: rgba(17, 24, 39, 0.14);--scrollbar-hover: rgba(17, 24, 39, 0.24);}36 unmodified lines--series-7: #9085e9;--series-8: #e66767;--scrollbar: rgba(255, 255, 255, 0.06);--scrollbar-hover: rgba(255, 255, 255, 0.12);}15 unmodified lines--color-fill-strong: var(--fill-strong);--color-accent-fg: var(--accent-fg);--color-flag-fg: var(--flag-fg);--font-sans:var(--font-source-sans), "Source Sans Pro", ui-sans-serif, system-ui,sans-serif;57 unmodified lines5859606162636465666768697071727336 unmodified lines11011111211311411511611711811915 unmodified lines13513613713813914014114214357 unmodified lines--series-7: #6250d6;--series-8: #e34948;/* Verdicts (smooth / moderate / jerky): a fill for marks and a text colour with readablecontrast on each theme. Always beside the word it colours, never the only signal, and neverused as a series colour. */--status-good: #0ca30c;--status-warning: #fab219;--status-critical: #d03b3b;--good-fg: #15803d; /* green-700 */--warning-fg: #a16207; /* yellow-700 */--critical-fg: #b91c1c; /* red-700 */--scrollbar: rgba(17, 24, 39, 0.14);--scrollbar-hover: rgba(17, 24, 39, 0.24);}36 unmodified lines--series-7: #9085e9;--series-8: #e66767;--good-fg: #4ade80; /* green-400 */--warning-fg: #facc15; /* yellow-400 */--critical-fg: #f87171; /* red-400 */--scrollbar: rgba(255, 255, 255, 0.06);--scrollbar-hover: rgba(255, 255, 255, 0.12);}15 unmodified lines--color-fill-strong: var(--fill-strong);--color-accent-fg: var(--accent-fg);--color-flag-fg: var(--flag-fg);--color-good-fg: var(--good-fg);--color-warning-fg: var(--warning-fg);--color-critical-fg: var(--critical-fg);--font-sans:var(--font-source-sans), "Source Sans Pro", ui-sans-serif, system-ui,sans-serif;
1234520 unmodified lines262728import { describe, expect, test } from "bun:test";import { niceTicks } from "../charts";describe("niceTicks", () => {test("covers the maximum with round steps", () => {20 unmodified linesexpect(niceTicks(0, 3)).toEqual([0]);});});123456789101120 unmodified lines3233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121import { describe, expect, test } from "bun:test";import {niceTicks,roundBinIndex,roundBins,sequentialColor,seriesStyle,} from "../charts";describe("niceTicks", () => {test("covers the maximum with round steps", () => {20 unmodified linesexpect(niceTicks(0, 3)).toEqual([0]);});});describe("roundBins", () => {test("edges are round and every value is counted once", () => {const values = [0.495, 2.1, 3.7, 4.2, 4.5, 4.9, 5.3, 6.9, 13.4];const bins = roundBins(values, 9);expect(bins.map((b) => b.lo)).toEqual([0, 2, 4, 6, 8, 10, 12]);expect(bins[bins.length - 1].hi).toBe(14);expect(bins.reduce((sum, b) => sum + b.count, 0)).toBe(values.length);for (const value of values) {const bin = bins[roundBinIndex(value, bins)];expect(value).toBeGreaterThanOrEqual(bin.lo);expect(value).toBeLessThan(bin.hi);}});test("a largest value on a bin edge still has a bin", () => {const bins = roundBins([0, 1, 2, 3, 4], 4);expect(bins[bins.length - 1].hi).toBeGreaterThan(4);expect(bins.reduce((sum, b) => sum + b.count, 0)).toBe(5);});test("small fractional values keep clean edges", () => {const bins = roundBins([0.0521, 0.0563, 0.0612, 0.0641, 0.0729], 10);for (const bin of bins) {expect(String(bin.lo).length).toBeLessThan(8);}expect(bins.reduce((sum, b) => sum + b.count, 0)).toBe(5);});test("identical values make one bin, no values none", () => {expect(roundBins([3, 3, 3], 10)).toEqual([{ lo: 3, hi: 3, count: 3 }]);expect(roundBins([], 10)).toEqual([]);});});describe("seriesStyle", () => {test("eight hues in order, then the same hues dashed, then muted", () => {expect(seriesStyle(0)).toEqual({color: "var(--series-1)",dash: undefined,});expect(seriesStyle(7).color).toBe("var(--series-8)");expect(seriesStyle(8)).toEqual({ color: "var(--series-1)", dash: "6 4" });expect(seriesStyle(15).color).toBe("var(--series-8)");expect(seriesStyle(16).color).toBe("var(--fg-faint)");});test("no two of the first sixteen series look the same", () => {const looks = Array.from({ length: 16 }, (_, i) => {const { color, dash } = seriesStyle(i);return `${color}/${dash ?? "solid"}`;});expect(new Set(looks).size).toBe(16);});});describe("sequentialColor", () => {const luminance = (rgb: string) => {const [r, g, b] = rgb.match(/\d+/g)!.map(Number);return 0.2126 * r + 0.7152 * g + 0.0722 * b;};test("zero is the step nearest the surface in each theme", () => {// Pale on a light page, deep on a dark one.expect(luminance(sequentialColor(0, "light"))).toBeGreaterThan(200);expect(luminance(sequentialColor(0, "dark"))).toBeLessThan(70);});test("grows steadily away from the surface", () => {for (const theme of ["light", "dark"] as const) {const steps = [0, 0.2, 0.4, 0.6, 0.8, 1].map((t) =>luminance(sequentialColor(t, theme)),);for (let i = 1; i < steps.length; i++) {if (theme === "light") expect(steps[i]).toBeLessThan(steps[i - 1]);else expect(steps[i]).toBeGreaterThan(steps[i - 1]);}}});test("values outside 0 to 1, and NaN, are clamped", () => {expect(sequentialColor(-3, "light")).toBe(sequentialColor(0, "light"));expect(sequentialColor(7, "light")).toBe(sequentialColor(1, "light"));expect(sequentialColor(NaN, "dark")).toBe(sequentialColor(0, "dark"));});});
6 unmodified lines7891011126 unmodified lines192021222324252627282930313233127 unmodified lines16116216316416516642 unmodified lines20921021121221321421521621721821944 unmodified lines26426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629748 unmodified lines3463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973981 unmodified line400401402403404405406407408409410411412413414415416417398 unmodified lines8168178188198208218228238248258268273 unmodified lines8318328338348358368378382 unmodified lines84184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689714 unmodified lines9129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201 unmodified line102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109417 unmodified lines1112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118212 unmodified lines11951196119711981199120012011202120312041205135 unmodified lines134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136861 unmodified lines143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615275 unmodified lines1533153415351536153715382 unmodified lines1541154215431544154515461547154815491550155115524 unmodified lines1557155815591560156115621563156415653 unmodified lines1569157015711572157315742 unmodified lines1577157815791580158115826 unmodified linesXAxis,YAxis,CartesianGrid,ResponsiveContainer,Tooltip,} from "recharts";6 unmodified linesJerkyEpisode,AggAlignment,} from "@/app/[org]/[dataset]/[episode]/fetch-data";import {EpisodeLink,FlagAllButton,FlagButton,InlineLoading,PageHeader,Switch,crossEpisodeLoadingLabel,} from "@/components/ui";const FullscreenCtx = React.createContext(false);const useIsFullscreen = () => React.useContext(FullscreenCtx);127 unmodified lines"#84cc16",];function shortName(key: string): string {const parts = key.split(CHART_CONFIG.SERIES_NAME_DELIMITER);return parts.length > 1 ? parts[parts.length - 1] : key;42 unmodified linesfps,agg,numEpisodes,}: {data: Record<string, number>[];fps: number;agg?: AggAutocorrelation | null;numEpisodes?: number;}) {const isFs = useIsFullscreen();const actionKeys = useMemo(44 unmodified linesconst { chartData, suggestedChunk, shortKeys } = agg ??fallback ?? { chartData: [], suggestedChunk: null, shortKeys: [] };const isAgg = !!agg;const numEpisodesLabel = isAgg? ` (${numEpisodes} episodes sampled)`: " (current episode)";const yDomain = useMemo(() => {if (chartData.length === 0 || shortKeys.length === 0)return [-0.2, 1] as [number, number];let min = Infinity;for (const row of chartData)for (const k of shortKeys) {const v = row[k];if (typeof v === "number" && v < min) min = v;}const lo = Math.floor(Math.min(min, 0) * 10) / 10;return [lo, 1] as [number, number];}, [chartData, shortKeys]);if (shortKeys.length === 0)return <p className="text-fg-faint italic">No action columns found.</p>;return (<div className="bg-[var(--surface-1)]/60 rounded-lg p-5 border border-line space-y-4"><div><div className="flex items-center gap-2"><h3 className="text-sm font-semibold text-fg">Action Autocorrelation<span className="text-xs text-fg-faint ml-2 font-normal">{numEpisodesLabel}</span></h3><InfoToggle>48 unmodified lines<LineChartkey={isAgg ? "agg" : "ep"}data={chartData}margin={{ top: 8, right: 16, left: 0, bottom: 16 }}><CartesianGrid strokeDasharray="3 3" stroke="var(--chart-grid)" /><XAxisdataKey="lag"stroke="var(--fg-muted)"label={{value: "Lag (steps)",position: "insideBottom",offset: -8,fill: "var(--fg-muted)",fontSize: 13,}}/><YAxisstroke="var(--fg-muted)"domain={yDomain}tickFormatter={(v) => Number(v.toFixed(2)).toString()}/><TooltipcontentStyle={{background: "var(--surface-2)",border: "1px solid var(--line-strong)",borderRadius: 6,}}labelFormatter={(v) =>`Lag ${v} (${(Number(v) / fps).toFixed(2)}s)`}formatter={(v: number) => v.toFixed(3)}/><LinedataKey={() => 0.5}stroke="var(--chart-axis)"strokeDasharray="6 4"dot={false}name="0.5 threshold"legendType="none"isAnimationActive={false}/>{shortKeys.map((name, i) => (<Linekey={name}dataKey={name}stroke={COLORS[i % COLORS.length]}dot={false}strokeWidth={1.5}legendType="none"isAnimationActive={false}/>))}1 unmodified line</ResponsiveContainer></div>{/* Custom legend */}<div className="flex flex-wrap gap-x-4 gap-y-1 px-1">{shortKeys.map((name, i) => (<div key={name} className="flex items-center gap-1.5"><spanclassName="w-3 h-[3px] rounded-full shrink-0"style={{ background: COLORS[i % COLORS.length] }}/><span className="text-xs text-fg-muted">{name}</span></div>))}</div></div>);}398 unmodified linesloading: boolean;progress?: { done: number; total: number } | null;}) {const isFs = useIsFullscreen();if (loading) {return (<div className="bg-[var(--surface-1)]/60 rounded-lg p-5 border border-line"><h3 className="text-sm font-semibold text-fg mb-2">Cross-Episode Action Variance</h3><InlineLoading label={crossEpisodeLoadingLabel(progress)} />3 unmodified linesif (!data) {return (<div className="bg-[var(--surface-1)]/60 rounded-lg p-5 border border-line"><h3 className="text-sm font-semibold text-fg mb-2">Cross-Episode Action Variance</h3><p className="text-fg-faint italic text-sm">2 unmodified lines</div>);}const { actionNames, timeBins, variance, numEpisodes } = data;const numDims = actionNames.length;const numBins = timeBins.length;const maxVar = Math.max(...variance.flat(), 1e-10);const baseW = isFs ? 1000 : 560;const baseH = isFs ? 500 : 300;const cellW = Math.max(6,Math.min(isFs ? 24 : 14, Math.floor(baseW / numBins)),);const cellH = Math.max(20,Math.min(isFs ? 56 : 36, Math.floor(baseH / numDims)),);const labelW = 100;const svgW = labelW + numBins * cellW + 60;const svgH = numDims * cellH + 40;function varColor(v: number): string {const t = Math.sqrt(v / maxVar); // sqrt for better visual spread// Dark blue → teal → orangeconst r = Math.round(t * 249);const g = Math.round(t < 0.5 ? 80 + t * 200 : 180 - (t - 0.5) * 200);const b = Math.round((1 - t) * 200 + 30);return `rgb(${r},${g},${b})`;}return (<div className="bg-[var(--surface-1)]/60 rounded-lg p-5 border border-line space-y-4"><div><div className="flex items-center gap-2"><h3 className="text-sm font-semibold text-fg">Cross-Episode Action Variance<span className="text-xs text-fg-faint ml-2 font-normal">({numEpisodes} episodes sampled)</span></h3><InfoToggle><p className="text-xs text-fg-muted">Shows how much each action dimension varies across episodes ateach point in time (normalized 0–100%).<span className="text-accent-fg">{" "}High-variance regions</span>{" "}indicate multi-modal or inconsistent demonstrations — generativepolicies (diffusion, flow-matching) and action chunking help hereby modeling multiple modes.<span className="text-blue-400"> Low-variance regions</span>{" "}indicate consistent behavior across demonstrations.<br /><span className="text-fg-faint">14 unmodified lines</div></div><div className="overflow-x-auto"><svg width={svgW} height={svgH} className="block">{/* Heatmap cells */}{variance.map((row, bi) =>row.map((v, di) => (<rectkey={`${bi}-${di}`}x={labelW + bi * cellW}y={di * cellH}width={cellW}height={cellH}fill={varColor(v)}stroke="var(--bg)"strokeWidth={0.5}><title>{`${shortName(actionNames[di])} @ ${(timeBins[bi] * 100).toFixed(0)}%: var=${v.toFixed(5)}`}</title></rect>)),)}{/* Y-axis: action names */}{actionNames.map((name, di) => (<textkey={di}x={labelW - 4}y={di * cellH + cellH / 2}textAnchor="end"dominantBaseline="central"className="fill-fg-muted"fontSize={Math.min(11, cellH - 4)}>{shortName(name)}</text>))}{/* X-axis labels */}{[0, 0.25, 0.5, 0.75, 1].map((frac) => {const binIdx = Math.round(frac * (numBins - 1));return (<textkey={frac}x={labelW + binIdx * cellW + cellW / 2}y={numDims * cellH + 14}textAnchor="middle"className="fill-fg-muted"fontSize={9}>{(frac * 100).toFixed(0)}%</text>);})}<textx={labelW + (numBins * cellW) / 2}y={numDims * cellH + 30}textAnchor="middle"className="fill-fg-faint"fontSize={10}>Episode progress</text>{/* Color bar */}{Array.from({ length: 10 }, (_, i) => {const t = i / 9;const barX = labelW + numBins * cellW + 16;const barH = (numDims * cellH) / 10;return (<rectkey={i}x={barX}y={(9 - i) * barH}width={12}height={barH}fill={varColor(t * maxVar)}/>);})}<textx={labelW + numBins * cellW + 34}y={10}className="fill-fg-faint"fontSize={8}dominantBaseline="central">high</text><textx={labelW + numBins * cellW + 34}y={numDims * cellH - 4}className="fill-fg-faint"fontSize={8}dominantBaseline="central">low</text></svg></div></div>);}// ─── Demonstrator Speed Variance ────────────────────────────────function SpeedVarianceSection({distribution,numEpisodes,1 unmodified linedistribution: SpeedDistEntry[];numEpisodes: number;}) {const isFs = useIsFullscreen();const { speeds, mean, std, cv, median, bins, lo, binW, maxBin, verdict } =useMemo(() => {const sp = distribution.map((d) => d.speed).sort((a, b) => a - b);const m = sp.reduce((a, b) => a + b, 0) / sp.length;const s = Math.sqrt(sp.reduce((a, v) => a + (v - m) ** 2, 0) / sp.length);const c = m > 0 ? s / m : 0;const med = sp[Math.floor(sp.length / 2)];const binCount = Math.min(30, Math.ceil(Math.sqrt(sp.length)));const lo = sp[0],hi = sp[sp.length - 1];const bw = (hi - lo || 1) / binCount;const b = new Array(binCount).fill(0);for (const v of sp) {let i = Math.floor((v - lo) / bw);if (i >= binCount) i = binCount - 1;b[i]++;}let v: { label: string; color: string; tip: string };if (c < 0.2)v = {label: "Consistent",color: "text-green-400",tip: "Demonstrators execute at similar speeds — no velocity normalization needed.",};else if (c < 0.4)v = {label: "Moderate variance",color: "text-yellow-400",tip: "Some speed variation across demonstrators. Consider velocity normalization for best results.",};elsev = {label: "High variance",color: "text-red-400",tip: "Large speed differences between demonstrations. Velocity normalization before training is strongly recommended.",};return {speeds: sp,mean: m,std: s,cv: c,median: med,bins: b,lo,binW: bw,maxBin: Math.max(...b),verdict: v,};}, [distribution]);if (speeds.length < 3) return null;const barH = isFs ? 250 : 100;const barW = Math.max(8, Math.floor((isFs ? 900 : 500) / bins.length));return (<div className="bg-[var(--surface-1)]/60 rounded-lg p-5 border border-line space-y-4"><div><div className="flex items-center gap-2"><h3 className="text-sm font-semibold text-fg">Demonstrator Speed Variance<span className="text-xs text-fg-faint ml-2 font-normal">({numEpisodes} episodes)</span></h3><InfoToggle>17 unmodified lines</div></div><div className="flex gap-4"><div className="flex-1 overflow-x-auto"><svg width={bins.length * barW} height={barH + 24} className="block">{bins.map((count: number, i: number) => {const h = maxBin > 0 ? (count / maxBin) * barH : 0;const speed = lo + (i + 0.5) * binW;const ratio = median > 0 ? speed / median : 1;const dev = Math.abs(ratio - 1);const color =dev < 0.2 ? "#22c55e" : dev < 0.5 ? "#eab308" : "#ef4444";return (<rectkey={i}x={i * barW}y={barH - h}width={barW - 1}height={Math.max(1, h)}fill={color}opacity={0.7}rx={1}><title>{`Speed ${(lo + i * binW).toFixed(3)}–${(lo + (i + 1) * binW).toFixed(3)}: ${count} ep (${ratio.toFixed(2)}× median)`}</title></rect>);})}{[0, 0.25, 0.5, 0.75, 1].map((frac) => {const idx = Math.round(frac * (bins.length - 1));return (<textkey={frac}x={idx * barW + barW / 2}y={barH + 14}textAnchor="middle"className="fill-fg-muted"fontSize={9}>{(lo + idx * binW).toFixed(2)}</text>);})}</svg></div><div className="flex flex-col gap-2 text-xs shrink-0 min-w-[120px]"><div><span className="text-fg-faint">Mean</span>{" "}<span className="text-fg tabular-nums ml-1">{mean.toFixed(4)}</span></div><div><span className="text-fg-faint">Median</span>{" "}<span className="text-fg tabular-nums ml-1">{median.toFixed(4)}</span></div><div><span className="text-fg-faint">Std</span>{" "}<span className="text-fg tabular-nums ml-1">{std.toFixed(4)}</span></div><div><span className="text-fg-faint">CV</span><span className={`tabular-nums ml-1 font-bold ${verdict.color}`}>{cv.toFixed(3)}</span></div></div></div><div className="bg-[var(--surface-0)]/60 rounded-md px-4 py-3 border border-line space-y-1.5"><p className="text-sm font-medium text-fg">12 unmodified linesfps,agg,numEpisodes,}: {data: Record<string, number>[];fps: number;agg?: AggAlignment | null;numEpisodes?: number;}) {const isFs = useIsFullscreen();const result = useMemo(() => {135 unmodified linesnumPairs,fromAgg,} = result;const scopeLabel = fromAgg? `${numEpisodes} episodes sampled`: "current episode";return (<div className="bg-[var(--surface-1)]/60 rounded-lg p-5 border border-line space-y-4"><div><div className="flex items-center gap-2"><h3 className="text-sm font-semibold text-fg">State–Action Temporal Alignment<span className="text-xs text-fg-faint ml-2 font-normal">({scopeLabel}, {numPairs} matched pair{numPairs !== 1 ? "s" : ""})</span></h3><InfoToggle><p className="text-xs text-fg-muted">Per-dimension cross-correlation between Δaction<sub>d</sub>(t) andΔstate<sub>d</sub>(t+lag), aggregated as<span className="text-accent-fg"> max</span>,{" "}<span className="text-fg">mean</span>, and<span className="text-blue-400"> min</span> across all matchedaction–state pairs. The{" "}<span className="text-accent-fg">peak lag</span> reveals theeffective control delay — the time between when an action iscommanded and when the corresponding state changes.61 unmodified lines<ResponsiveContainer width="100%" height="100%"><LineChartdata={ccData}margin={{ top: 8, right: 16, left: 0, bottom: 16 }}><CartesianGrid strokeDasharray="3 3" stroke="var(--chart-grid)" /><XAxisdataKey="lag"stroke="var(--fg-muted)"label={{value: "Lag (steps)",position: "insideBottom",offset: -8,fill: "var(--fg-muted)",fontSize: 13,}}/><YAxisstroke="var(--fg-muted)"domain={[-0.5, 1]}tickFormatter={(v) => Number(v.toFixed(2)).toString()}/><TooltipcontentStyle={{background: "var(--surface-2)",border: "1px solid var(--line-strong)",borderRadius: 6,}}labelFormatter={(v) =>`Lag ${v} (${(Number(v) / fps).toFixed(3)}s)`}formatter={(v: number) => v.toFixed(3)}/><LinedataKey="max"stroke="#f97316"dot={false}strokeWidth={2}isAnimationActive={false}name="max"/><LinedataKey="mean"stroke="var(--fg-muted)"dot={false}strokeWidth={2}isAnimationActive={false}name="mean"/><LinedataKey="min"stroke="#3b82f6"dot={false}strokeWidth={2}isAnimationActive={false}name="min"/><LinedataKey={() => 0}stroke="var(--chart-axis)"strokeDasharray="6 4"dot={false}name="zero"legendType="none"isAnimationActive={false}/></LineChart></ResponsiveContainer></div><div className="flex flex-wrap gap-x-4 gap-y-1 px-1"><div className="flex items-center gap-1.5"><span className="w-3 h-[3px] rounded-full shrink-0 bg-accent" /><span className="text-xs text-fg-muted">max (peak: lag {maxPeakLag}, r={maxPeakCorr.toFixed(3)})</span></div><div className="flex items-center gap-1.5"><span className="w-3 h-[3px] rounded-full shrink-0 bg-fg-muted" /><span className="text-xs text-fg-muted">mean (peak: lag {meanPeakLag}, r={meanPeakCorr.toFixed(3)})</span></div><div className="flex items-center gap-1.5"><span className="w-3 h-[3px] rounded-full shrink-0 bg-blue-500" /><span className="text-xs text-fg-muted">min (peak: lag {minPeakLag}, r={minPeakCorr.toFixed(3)})</span></div></div>{meanPeakLag === 0 && (<p className="text-xs text-green-400">Mean peak correlation at lag 0 (r={meanPeakCorr.toFixed(3)}) — actionsand state changes are well-aligned in this episode.</p>)}</div>5 unmodified linesinterface ActionInsightsPanelProps {flatChartData: Record<string, number>[];fps: number;crossEpisodeData: CrossEpisodeVarianceData | null;crossEpisodeLoading: boolean;crossEpisodeProgress?: { done: number; total: number } | null;2 unmodified linesfunction ActionInsightsPanel({flatChartData,fps,crossEpisodeData,crossEpisodeLoading,crossEpisodeProgress,}: ActionInsightsPanelProps) {const [mode, setMode] = useState<"episode" | "dataset">("dataset");const showAgg = mode === "dataset" && !!crossEpisodeData;return (<div className="w-full max-w-5xl mx-auto py-6 space-y-6">4 unmodified lines<Switchchecked={mode === "dataset"}onChange={(all) => setMode(all ? "dataset" : "episode")}offLabel="Current Episode"onLabel={`All Episodes${crossEpisodeData ? ` (${crossEpisodeData.numEpisodes})` : ""}`}ariaLabel="Toggle episode/dataset scope"/></PageHeader>3 unmodified linesfps={fps}agg={showAgg ? crossEpisodeData?.aggAutocorrelation : null}numEpisodes={crossEpisodeData?.numEpisodes}/></FullscreenWrapper><FullscreenWrapper>2 unmodified linesfps={fps}agg={showAgg ? crossEpisodeData?.aggAlignment : null}numEpisodes={crossEpisodeData?.numEpisodes}/></FullscreenWrapper>6 unmodified lines789101112136 unmodified lines2021222324252627282930313233343536373839404142434445127 unmodified lines17317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625742 unmodified lines30030130230330430530630730830931031131231344 unmodified lines35835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439548 unmodified lines4444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235241 unmodified line526527528529530531532533534535536398 unmodified lines9359369379389399409419429439449459469479489499509519529539549559569579589593 unmodified lines9639649659669679689699702 unmodified lines973974975976977978979980981982983984985986987988989990991992993994995996997998999100014 unmodified lines101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431 unmodified line104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110817 unmodified lines11261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312 unmodified lines12161217121812191220122112221223122412251226122712281229135 unmodified lines136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141061 unmodified lines1472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115525 unmodified lines155815591560156115621563156415652 unmodified lines156815691570157115721573157415751576157715781579158015814 unmodified lines1586158715881589159015911592159315943 unmodified lines15981599160016011602160316042 unmodified lines16071608160916101611161216136 unmodified linesXAxis,YAxis,CartesianGrid,ReferenceLine,ResponsiveContainer,Tooltip,} from "recharts";6 unmodified linesJerkyEpisode,AggAlignment,} from "@/app/[org]/[dataset]/[episode]/fetch-data";import {Heatmap,Histogram,LineKey,SeriesLegend,roundBinIndex,roundBins,seriesStyle,} from "@/components/charts";import {EpisodeLink,FlagAllButton,FlagButton,InlineLoading,PageHeader,StatCard,Switch,crossEpisodeLoadingLabel,} from "@/components/ui";import { useTheme } from "@/utils/theme";const FullscreenCtx = React.createContext(false);const useIsFullscreen = () => React.useContext(FullscreenCtx);127 unmodified lines"#84cc16",];/// Axis and grid styling shared by the line charts: recessive, like the Episodes tab's.const AXIS_TICK = { fontSize: 12, fill: "var(--fg-muted)" };const AXIS_LABEL = { fontSize: 12, fill: "var(--fg-muted)" };const SECTION ="bg-[var(--surface-1)]/60 rounded-lg p-5 border border-line space-y-4";/** Tick positions from `from` to `to` in steps of `step`, without floating-point drift. */function steps(from: number, to: number, step: number): number[] {const ticks: number[] = [];for (let value = from; value <= to + step * 1e-6; value += step) {ticks.push(Number(value.toFixed(6)));}return ticks;}/*** A correlation axis reaching down to `lowest`: the domain stops at the quarter below the data, and* the ticks sit on halves (quarters when everything is positive), so no label is an odd number.*/function correlationAxis(lowest: number): {domain: [number, number];ticks: number[];} {const floor = Math.floor(Math.min(lowest, 0) / 0.25) * 0.25;const step = floor < 0 ? 0.5 : 0.25;return {domain: [floor, 1],ticks: steps(Math.ceil(floor / step) * step, 1, step),};}/** Lag ticks at round numbers, a handful whatever the horizon. */function lagStep(span: number): number {return span <= 30 ? 5 : span <= 60 ? 10 : 20;}/*** The readout under the pointer: every series at that lag, its key beside its name, the value* leading. Names stay in text colours; the key carries the series colour.*/function LineTooltip({active,payload,label,formatLabel,series,}: {active?: boolean;payload?: { name?: string | number; value?: number | string }[];label?: number | string;formatLabel: (label: number) => string;series: { name: string; color: string; dash?: string }[];}) {if (!active || !payload?.length) return null;const values = new Map(payload.map((item) => [String(item.name), item.value]),);return (<div className="rounded-md border border-line-strong bg-[var(--surface-2)] px-2.5 py-1.5 text-xs shadow-lg"><p className="mb-1 text-fg-muted tabular">{formatLabel(Number(label))}</p><ul className="space-y-0.5">{series.map(({ name, color, dash }) => {const value = values.get(name);if (typeof value !== "number") return null;return (<li key={name} className="flex items-center gap-2"><LineKey color={color} dash={dash} /><span className="text-fg-muted">{name}</span><span className="ml-auto pl-4 font-semibold text-fg tabular">{value.toFixed(3)}</span></li>);})}</ul></div>);}function shortName(key: string): string {const parts = key.split(CHART_CONFIG.SERIES_NAME_DELIMITER);return parts.length > 1 ? parts[parts.length - 1] : key;42 unmodified linesfps,agg,numEpisodes,scopeLabel,}: {data: Record<string, number>[];fps: number;agg?: AggAutocorrelation | null;numEpisodes?: number;/** What the chart covers when it is not the dataset: `episode 12`. */scopeLabel: string;}) {const isFs = useIsFullscreen();const actionKeys = useMemo(44 unmodified linesconst { chartData, suggestedChunk, shortKeys } = agg ??fallback ?? { chartData: [], suggestedChunk: null, shortKeys: [] };const isAgg = !!agg;const [highlighted, setHighlighted] = useState<string | null>(null);const series = useMemo(() => shortKeys.map((name, i) => ({ name, ...seriesStyle(i) })),[shortKeys],);const lagCount = chartData.length;const yAxis = useMemo(() => {let min = 0;for (const row of chartData)for (const k of shortKeys) {const v = row[k];if (typeof v === "number" && v < min) min = v;}return correlationAxis(min);}, [chartData, shortKeys]);const xTicks = useMemo(() => {const step = lagStep(lagCount);return [1, ...steps(step, lagCount, step)];}, [lagCount]);if (shortKeys.length === 0)return <p className="text-fg-faint italic">No action columns found.</p>;return (<div className={SECTION}><div><div className="flex items-center gap-2"><h3 className="text-sm font-semibold text-fg">Action Autocorrelation<span className="text-xs text-fg-faint ml-2 font-normal">{isAgg ? `${numEpisodes} episodes sampled` : scopeLabel}</span></h3><InfoToggle>48 unmodified lines<LineChartkey={isAgg ? "agg" : "ep"}data={chartData}margin={{ top: 18, right: 28, left: 0, bottom: 20 }}><CartesianGrid stroke="var(--chart-grid)" vertical={false} /><XAxisdataKey="lag"type="number"domain={[1, Math.max(2, lagCount)]}ticks={xTicks}stroke="var(--chart-axis)"tick={AXIS_TICK}tickLine={false}label={{value: "Lag (frames)",position: "insideBottom",offset: -12,...AXIS_LABEL,}}/><YAxisdomain={yAxis.domain}ticks={yAxis.ticks}interval={0}stroke="var(--chart-axis)"tick={AXIS_TICK}tickLine={false}width={44}/><TooltipisAnimationActive={false}cursor={{ stroke: "var(--chart-axis)" }}content={<LineTooltipseries={series}formatLabel={(lag) =>`Lag ${lag} · ${(lag / fps).toFixed(2)}s`}/>}/>{/* The threshold the suggestion is read off, labelled where it meets the edge. */}<ReferenceLiney={0.5}stroke="var(--fg-faint)"strokeDasharray="4 4"label={{value: "0.5",position: "right",fontSize: 11,fill: "var(--fg-muted)",}}/>{suggestedChunk && (<ReferenceLinex={suggestedChunk}stroke="var(--accent)"label={{value: `chunk ${suggestedChunk}`,position: "top",fontSize: 11,fill: "var(--accent-fg)",}}/>)}{series.map(({ name, color, dash }) => (<Linekey={name}dataKey={name}name={name}stroke={color}strokeDasharray={dash}strokeWidth={highlighted === name ? 3 : series.length > 8 ? 1.5 : 2}strokeOpacity={highlighted && highlighted !== name ? 0.15 : 1}dot={false}isAnimationActive={false}/>))}1 unmodified line</ResponsiveContainer></div><SeriesLegendseries={series}highlighted={highlighted}onHighlight={setHighlighted}/></div>);}398 unmodified linesloading: boolean;progress?: { done: number; total: number } | null;}) {const theme = useTheme();// Spread across episodes as a share of each motor's range, so a gripper in percent and a joint// in radians are on one scale. The raw variance let the widest-ranging motor set the colours.const rows = useMemo(() => {if (!data) return [];return data.actionNames.map((name, d) => {const range = data.aggVelocity[d]?.motorRange || 1;return {label: shortName(name),values: data.variance.map((bin) => Math.sqrt(bin[d]) / range),};});}, [data]);if (loading) {return (<div className={SECTION}><h3 className="text-sm font-semibold text-fg">Cross-Episode Action Variance</h3><InlineLoading label={crossEpisodeLoadingLabel(progress)} />3 unmodified linesif (!data) {return (<div className={SECTION}><h3 className="text-sm font-semibold text-fg">Cross-Episode Action Variance</h3><p className="text-fg-faint italic text-sm">2 unmodified lines</div>);}const { timeBins, numEpisodes } = data;return (<div className={SECTION}><div><div className="flex items-center gap-2"><h3 className="text-sm font-semibold text-fg">Cross-Episode Action Variance<span className="text-xs text-fg-faint ml-2 font-normal">{numEpisodes} episodes sampled</span></h3><InfoToggle><p className="text-xs text-fg-muted">How much each action dimension differs between episodes at thesame point of their progress: the standard deviation acrossepisodes, as a share of that motor's range.{" "}<span className="text-fg font-medium">High-variance regions</span>{" "}indicate multi-modal or inconsistent demonstrations — generativepolicies (diffusion, flow-matching) and action chunking help hereby modeling multiple modes.{" "}<span className="text-fg font-medium">Low-variance regions</span>{" "}indicate consistent behavior across demonstrations.<br /><span className="text-fg-faint">14 unmodified lines</div></div><Heatmaprows={rows}theme={theme}ariaLabel="Spread of each action dimension across episodes, by episode progress"xLabel="Episode progress"xTicks={[0, 0.25, 0.5, 0.75, 1].map((at) => ({at,label: `${at * 100}%`,}))}formatValue={(value) => `${(value * 100).toFixed(1)}%`}describeColumn={(i) =>`at ${Math.round(timeBins[i] * 100)}% of the episode`}legend="std across episodes, as a share of the motor's range"/></div>);}// ─── Demonstrator Speed Variance ────────────────────────────────const SPEED_EPISODES_SHOWN = 80;function SpeedVarianceSection({distribution,numEpisodes,1 unmodified linedistribution: SpeedDistEntry[];numEpisodes: number;}) {const [selectedBin, setSelectedBin] = useState<number | null>(null);const { mean, std, cv, median, bins, verdict } = useMemo(() => {const sp = distribution.map((d) => d.speed).sort((a, b) => a - b);const m = sp.reduce((a, b) => a + b, 0) / sp.length;const s = Math.sqrt(sp.reduce((a, v) => a + (v - m) ** 2, 0) / sp.length);const c = m > 0 ? s / m : 0;let v: { label: string; color: string; tip: string };if (c < 0.2)v = {label: "Consistent",color: "text-good-fg",tip: "Demonstrators execute at similar speeds — no velocity normalization needed.",};else if (c < 0.4)v = {label: "Moderate variance",color: "text-warning-fg",tip: "Some speed variation across demonstrators. Consider velocity normalization for best results.",};elsev = {label: "High variance",color: "text-critical-fg",tip: "Large speed differences between demonstrations. Velocity normalization before training is strongly recommended.",};return {mean: m,std: s,cv: c,median: sp[Math.floor(sp.length / 2)],bins: roundBins(sp, Math.min(30, Math.ceil(Math.sqrt(sp.length)))),verdict: v,};}, [distribution]);const inBin = useMemo(() =>selectedBin === null? []: distribution.filter((d) => roundBinIndex(d.speed, bins) === selectedBin).sort((a, b) => a.speed - b.speed),[distribution, bins, selectedBin],);if (distribution.length < 3) return null;const selected = selectedBin !== null ? bins[selectedBin] : null;return (<div className={SECTION}><div><div className="flex items-center gap-2"><h3 className="text-sm font-semibold text-fg">Demonstrator Speed Variance<span className="text-xs text-fg-faint ml-2 font-normal">{numEpisodes} episodes</span></h3><InfoToggle>17 unmodified lines</div></div><div className="grid grid-cols-2 gap-3 md:grid-cols-4"><StatCard label="Mean" value={mean.toFixed(4)} /><StatCard label="Median" value={median.toFixed(4)} /><StatCard label="Std dev" value={std.toFixed(4)} /><StatCardlabel="CV (std ÷ mean)"value={cv.toFixed(3)}detail={<span className={verdict.color}>{verdict.label}</span>}/></div><div><p className="mb-1 text-xs text-fg-muted">Episodes by mean speed. Select a bar to list its episodes.</p><Histogrambins={bins}ariaLabel="Episodes by mean speed"formatValue={(value) => Number(value.toPrecision(3)).toString()}describeCount={(count) =>`${count.toLocaleString()} episode${count === 1 ? "" : "s"}`}marker={{value: median,label: `median ${Number(median.toPrecision(3))}`,}}selected={selectedBin}onSelect={setSelectedBin}/></div>{selected && (<div className="rounded-md border border-accent/30 bg-accent/5 p-3"><div className="flex flex-wrap items-center justify-between gap-2"><p className="text-xs text-fg-soft tabular"><span className="font-semibold text-fg">{inBin.length.toLocaleString()} episode{inBin.length === 1 ? "" : "s"}</span>{" "}at {(selected.lo / (median || 1)).toFixed(2)}× to{" "}{(selected.hi / (median || 1)).toFixed(2)}× the median speed</p><div className="flex items-center gap-3"><FlagAllButton ids={inBin.map((e) => e.episodeIndex)} /><buttontype="button"onClick={() => setSelectedBin(null)}className="text-xs text-fg-faint transition-colors hover:text-fg">Clear</button></div></div><ul className="mt-2 flex max-h-28 flex-wrap gap-1.5 overflow-y-auto">{inBin.slice(0, SPEED_EPISODES_SHOWN).map((episode) => (<li key={episode.episodeIndex}><EpisodeLinkepisode={episode.episodeIndex}className="block rounded border border-line bg-fill px-1.5 py-0.5 text-xs text-fg-soft">{episode.episodeIndex}</EpisodeLink></li>))}{inBin.length > SPEED_EPISODES_SHOWN && (<li className="px-1.5 py-0.5 text-xs text-fg-faint">+{(inBin.length - SPEED_EPISODES_SHOWN).toLocaleString()} more</li>)}</ul></div>)}<div className="bg-[var(--surface-0)]/60 rounded-md px-4 py-3 border border-line space-y-1.5"><p className="text-sm font-medium text-fg">12 unmodified linesfps,agg,numEpisodes,scopeLabel: episodeLabel,}: {data: Record<string, number>[];fps: number;agg?: AggAlignment | null;numEpisodes?: number;/** What the chart covers when it is not the dataset: `episode 12`. */scopeLabel: string;}) {const isFs = useIsFullscreen();const result = useMemo(() => {135 unmodified linesnumPairs,fromAgg,} = result;const scopeLabel = fromAgg ? `${numEpisodes} episodes sampled` : episodeLabel;const lagSpan = ccData.length > 0 ? ccData[ccData.length - 1].lag : 0;const step = lagStep(lagSpan * 2);const xTicks = steps(-Math.floor(lagSpan / step) * step, lagSpan, step);const yAxis = correlationAxis(Math.min(...ccData.map((row) => row.min)));// The envelope across the matched pairs: the mean in the foreground, its bounds around it.const series = [{name: "max",color: "var(--series-2)",note: `peak at lag ${maxPeakLag}, r = ${maxPeakCorr.toFixed(3)}`,},{name: "mean",color: "var(--fg-soft)",note: `peak at lag ${meanPeakLag}, r = ${meanPeakCorr.toFixed(3)}`,},{name: "min",color: "var(--series-1)",note: `peak at lag ${minPeakLag}, r = ${minPeakCorr.toFixed(3)}`,},];return (<div className={SECTION}><div><div className="flex items-center gap-2"><h3 className="text-sm font-semibold text-fg">State–Action Temporal Alignment<span className="text-xs text-fg-faint ml-2 font-normal">{scopeLabel}, {numPairs} matched pair{numPairs !== 1 ? "s" : ""}</span></h3><InfoToggle><p className="text-xs text-fg-muted">Per-dimension cross-correlation between Δaction<sub>d</sub>(t) andΔstate<sub>d</sub>(t+lag), aggregated as max, mean and min acrossall matched action–state pairs. The{" "}<span className="text-accent-fg">peak lag</span> reveals theeffective control delay — the time between when an action iscommanded and when the corresponding state changes.61 unmodified lines<ResponsiveContainer width="100%" height="100%"><LineChartdata={ccData}margin={{ top: 18, right: 16, left: 0, bottom: 20 }}><CartesianGrid stroke="var(--chart-grid)" vertical={false} /><XAxisdataKey="lag"type="number"domain={[-lagSpan, lagSpan]}ticks={xTicks}stroke="var(--chart-axis)"tick={AXIS_TICK}tickLine={false}label={{value: "Lag (frames): state after action →",position: "insideBottom",offset: -12,...AXIS_LABEL,}}/><YAxisdomain={yAxis.domain}ticks={yAxis.ticks}interval={0}stroke="var(--chart-axis)"tick={AXIS_TICK}tickLine={false}width={44}/><TooltipisAnimationActive={false}cursor={{ stroke: "var(--chart-axis)" }}content={<LineTooltipseries={series}formatLabel={(lag) =>`Lag ${lag} · ${(lag / fps).toFixed(3)}s`}/>}/><ReferenceLine y={0} stroke="var(--chart-axis)" /><ReferenceLine x={0} stroke="var(--chart-axis)" />{meanPeakLag !== 0 && (<ReferenceLinex={meanPeakLag}stroke="var(--accent)"label={{value: `delay ${meanPeakLag}`,position: "top",fontSize: 11,fill: "var(--accent-fg)",}}/>)}{series.map(({ name, color }) => (<Linekey={name}dataKey={name}name={name}stroke={color}strokeWidth={name === "mean" ? 2.5 : 1.5}dot={false}isAnimationActive={false}/>))}</LineChart></ResponsiveContainer></div><SeriesLegend series={series} />{meanPeakLag === 0 && (<p className="text-xs text-good-fg">Mean peak correlation at lag 0 (r={meanPeakCorr.toFixed(3)}) — actionsand state changes are well-aligned{fromAgg ? "" : " in this episode"}.</p>)}</div>5 unmodified linesinterface ActionInsightsPanelProps {flatChartData: Record<string, number>[];fps: number;/** The episode on screen, which "Current episode" analyses. */episodeId: number;crossEpisodeData: CrossEpisodeVarianceData | null;crossEpisodeLoading: boolean;crossEpisodeProgress?: { done: number; total: number } | null;2 unmodified linesfunction ActionInsightsPanel({flatChartData,fps,episodeId,crossEpisodeData,crossEpisodeLoading,crossEpisodeProgress,}: ActionInsightsPanelProps) {const [mode, setMode] = useState<"episode" | "dataset">("dataset");const showAgg = mode === "dataset" && !!crossEpisodeData;const scopeLabel = `episode ${episodeId}`;return (<div className="w-full max-w-5xl mx-auto py-6 space-y-6">4 unmodified lines<Switchchecked={mode === "dataset"}onChange={(all) => setMode(all ? "dataset" : "episode")}offLabel={`Episode ${episodeId}`}onLabel={`All episodes${crossEpisodeData ? ` (${crossEpisodeData.numEpisodes} sampled)` : ""}`}ariaLabel="Analyse the dataset rather than this episode"/></PageHeader>3 unmodified linesfps={fps}agg={showAgg ? crossEpisodeData?.aggAutocorrelation : null}numEpisodes={crossEpisodeData?.numEpisodes}scopeLabel={scopeLabel}/></FullscreenWrapper><FullscreenWrapper>2 unmodified linesfps={fps}agg={showAgg ? crossEpisodeData?.aggAlignment : null}numEpisodes={crossEpisodeData?.numEpisodes}scopeLabel={scopeLabel}/></FullscreenWrapper>
386 unmodified lines387388389386 unmodified lines</div>);}386 unmodified lines387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736386 unmodified lines</div>);}/*** How series number `index` is drawn. Eight hues, in their fixed order; past the eighth the same* hues come round dashed, so a ninth series is still told from the first by more than position.* Past sixteen there is nothing left to tell them apart with: those are drawn muted.*/export function seriesStyle(index: number): {color: string;dash: string | undefined;} {if (index >= 16) return { color: "var(--fg-faint)", dash: "2 3" };return {color: `var(--series-${(index % 8) + 1})`,dash: index >= 8 ? "6 4" : undefined,};}/** A legend entry's key: a short stroke drawn the way the series is. */export function LineKey({ color, dash }: { color: string; dash?: string }) {return (<svg width="18" height="6" aria-hidden="true" className="shrink-0"><linex1="1"x2="17"y1="3"y2="3"stroke={color}strokeWidth="2"strokeLinecap="round"strokeDasharray={dash}/></svg>);}/*** The legend of a line chart. Pointing at (or focusing) an entry reports it through `onHighlight`,* so the chart can lift that line out of the others.*/export function SeriesLegend({series,highlighted,onHighlight,}: {series: { name: string; color: string; dash?: string; note?: string }[];highlighted?: string | null;onHighlight?: (name: string | null) => void;}) {return (<ul className="flex flex-wrap gap-x-4 gap-y-1 px-1">{series.map(({ name, color, dash, note }) => (<li key={name}><buttontype="button"tabIndex={onHighlight ? 0 : -1}onPointerEnter={() => onHighlight?.(name)}onPointerLeave={() => onHighlight?.(null)}onFocus={() => onHighlight?.(name)}onBlur={() => onHighlight?.(null)}className={`flex items-center gap-1.5 rounded text-xs transition-opacity ${onHighlight ? "cursor-default" : "pointer-events-none"} ${highlighted && highlighted !== name ? "opacity-40" : ""}`}><LineKey color={color} dash={dash} /><span className="text-fg-muted">{name}{note && <span className="ml-1 text-fg-faint">{note}</span>}</span></button></li>))}</ul>);}/** One hue, light to dark: the steps a magnitude is coloured with. */const SEQUENTIAL = ["#cde2fb","#b7d3f6","#9ec5f4","#86b6ef","#6da7ec","#5598e7","#3987e5","#2a78d6","#256abf","#1c5cab","#184f95","#104281","#0d366b",].map((hex) => [1, 3, 5].map((i) => parseInt(hex.slice(i, i + 2), 16)));/** The palest step the dark theme uses: the two beyond it glare against a dark page. */const DARK_PALEST = 2;/*** The colour of magnitude `t` in [0, 1]. Zero is the step nearest the surface, so "nothing" recedes* into the background in either theme: pale on light, deep on dark.*/export function sequentialColor(t: number, theme: "light" | "dark"): string {const clamped = Math.max(0, Math.min(1, Number.isFinite(t) ? t : 0));const last = SEQUENTIAL.length - 1;const position =theme === "dark" ? last - clamped * (last - DARK_PALEST) : clamped * last;const lower = Math.floor(position);const upper = Math.min(SEQUENTIAL.length - 1, lower + 1);const mix = position - lower;const channel = (c: number) =>Math.round(SEQUENTIAL[lower][c] +(SEQUENTIAL[upper][c] - SEQUENTIAL[lower][c]) * mix,);return `rgb(${channel(0)}, ${channel(1)}, ${channel(2)})`;}const HEATMAP_LABEL_WIDTH = 132;/*** A grid of magnitudes: one row per label, one column per step along x, coloured from zero to the* largest value. Pointing at a cell reads it out.*/export function Heatmap({rows,theme,xTicks,xLabel,formatValue,describeColumn,legend,ariaLabel,}: {rows: { label: string; values: number[] }[];theme: "light" | "dark";/** Positions along x, as fractions of the width, with their labels. */xTicks: { at: number; label: string }[];xLabel: string;formatValue: (value: number) => string;/** What column `index` stands for, in the readout: `at 40% of the episode`. */describeColumn: (index: number) => string;/** What the colour measures, for the scale. */legend: string;ariaLabel: string;}) {const [ref, width] = useMeasuredWidth<HTMLDivElement>();const [hovered, setHovered] = useState<{ row: number; col: number } | null>(null,);const columns = rows[0]?.values.length ?? 0;const max = Math.max(...rows.flatMap((row) => row.values), 0);const rowHeight = rows.length <= 8 ? 26 : rows.length <= 16 ? 20 : 14;const plotWidth = Math.max(0, width - HEATMAP_LABEL_WIDTH - 4);const cellWidth = columns > 0 ? plotWidth / columns : 0;const plotHeight = rows.length * rowHeight;const height = plotHeight + 34;const colorOf = (value: number) =>sequentialColor(max > 0 ? value / max : 0, theme);const cell = hovered ? rows[hovered.row].values[hovered.col] : 0;return (<div className="space-y-2"><div ref={ref} className="relative w-full" style={{ height }}>{width > 0 && (<svgwidth={width}height={height}role="img"aria-label={ariaLabel}className="block"onPointerLeave={() => setHovered(null)}>{rows.map((row, r) => (<g key={row.label}><textx={HEATMAP_LABEL_WIDTH - 8}y={r * rowHeight + rowHeight / 2}textAnchor="end"dominantBaseline="central"fontSize={Math.min(12, rowHeight - 3)}className={hovered?.row === r ? "fill-fg" : "fill-fg-muted"}>{row.label.length > 18? `${row.label.slice(0, 17)}…`: row.label}<title>{row.label}</title></text>{row.values.map((value, c) => (<rectkey={c}x={HEATMAP_LABEL_WIDTH + c * cellWidth}y={r * rowHeight}// A hairline of surface between cells, rather than an outline around each.width={Math.max(0.5, cellWidth - 1)}height={rowHeight - 1}fill={colorOf(value)}onPointerEnter={() => setHovered({ row: r, col: c })}/>))}</g>))}{hovered && (<rectx={HEATMAP_LABEL_WIDTH + hovered.col * cellWidth - 0.5}y={hovered.row * rowHeight - 0.5}width={cellWidth}height={rowHeight}fill="none"stroke="var(--fg)"strokeWidth={1.5}pointerEvents="none"/>)}{xTicks.map(({ at, label }) => (<textkey={label}x={HEATMAP_LABEL_WIDTH + at * plotWidth}y={plotHeight + 14}textAnchor={at <= 0 ? "start" : at >= 1 ? "end" : "middle"}fontSize={11}className="fill-fg-muted tabular">{label}</text>))}<textx={HEATMAP_LABEL_WIDTH + plotWidth / 2}y={plotHeight + 30}textAnchor="middle"fontSize={11}className="fill-fg-faint">{xLabel}</text></svg>)}{hovered && (<divclassName="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"style={{left: Math.min(Math.max(HEATMAP_LABEL_WIDTH + (hovered.col + 0.5) * cellWidth,90,),width - 90,),top:hovered.row * rowHeight > 46? hovered.row * rowHeight - 46: (hovered.row + 1) * rowHeight + 4,}}><p className="font-semibold text-fg tabular">{formatValue(cell)}</p><p className="text-fg-muted">{rows[hovered.row].label} · {describeColumn(hovered.col)}</p></div>)}</div>{/* The scale: what the colour measures, from nothing to the largest value drawn. */}<divclassName="flex items-center gap-2 text-[11px] text-fg-muted"style={{ paddingLeft: HEATMAP_LABEL_WIDTH }}><span className="tabular">{formatValue(0)}</span><divclassName="h-2 w-32 rounded-sm"style={{background: `linear-gradient(to right, ${[0, 0.25, 0.5, 0.75, 1].map((t) => sequentialColor(t, theme)).join(", ")})`,}}/><span className="tabular">{formatValue(max)}</span><span className="ml-1 text-fg-faint">{legend}</span></div><table className="sr-only"><caption>{ariaLabel}</caption><thead><tr><th>Row</th><th>Lowest</th><th>Mean</th><th>Highest</th></tr></thead><tbody>{rows.map((row) => (<tr key={row.label}><td>{row.label}</td><td>{formatValue(Math.min(...row.values))}</td><td>{formatValue(row.values.reduce((a, b) => a + b, 0) /(row.values.length || 1),)}</td><td>{formatValue(Math.max(...row.values))}</td></tr>))}</tbody></table></div>);}/*** Bins covering `values` with round edges (a width of 1, 2, 2.5 or 5 × 10ⁿ), about `target` of* them, for the shared Histogram.*/export function roundBins(values: number[], target: number): HistogramBin[] {if (values.length === 0) return [];let min = Infinity;let max = -Infinity;for (const value of values) {if (value < min) min = value;if (value > max) max = value;}if (max === min) return [{ lo: min, hi: max, count: values.length }];const rough = (max - min) / Math.max(1, target);const magnitude = Math.pow(10, Math.floor(Math.log10(rough)));const width =[1, 2, 2.5, 5, 10].map((m) => m * magnitude).find((w) => w >= rough) ??rough;const lo = Math.floor(min / width) * width;// One more bin when the largest value sits exactly on an edge, so it has a bin to fall in.const count = Math.max(1, Math.floor((max - lo) / width) + 1);const edge = (i: number) => Number((lo + i * width).toPrecision(12));const bins = Array.from({ length: count }, (_, i) => ({lo: edge(i),hi: edge(i + 1),count: 0,}));for (const value of values) bins[roundBinIndex(value, bins)].count++;return bins;}/** Which of `roundBins`' bins a value falls in. */export function roundBinIndex(value: number, bins: HistogramBin[]): number {if (bins.length <= 1) return 0;const width = bins[0].hi - bins[0].lo;return Math.max(0,Math.min(bins.length - 1, Math.floor((value - bins[0].lo) / width)),);}
AGENTS.md+3-1
src/app/[org]/[dataset]/[episode]/episode-viewer.tsx+1
src/app/globals.css+17
src/components/__tests__/charts.test.ts+94-1
src/components/action-insights-panel.tsx+431-400
src/components/charts.tsx+347