LAMPSUI / frontend /src /components /StudyReport.tsx
Ilya
agents
818964a
Raw History Blame Contribute Delete
13.4 kB
import { useEffect, useState } from "react";
import {
Stack,
Group,
Text,
Title,
Divider,
Table,
Badge,
Loader,
Center,
SimpleGrid,
} from "@mantine/core";
import {
StudyReport as Report,
CorrelationEntry,
HistoryObjective,
ImportanceObjective,
SliceObjective,
getStudyReport,
} from "../api";
interface Props {
studyId: string;
/** Bumps when trials count grows so we re-fetch. */
refreshTick: number;
/** Hide the analysis panel until at least this many trials have completed. */
minTrials?: number;
nCompleted: number;
}
export function StudyReport({ studyId, refreshTick, minTrials = 3, nCompleted }: Props) {
const [report, setReport] = useState<Report | null>(null);
const [loading, setLoading] = useState(false);
useEffect(() => {
if (nCompleted < minTrials) {
setReport(null);
return;
}
setLoading(true);
getStudyReport(studyId)
.then(setReport)
.catch(() => setReport(null))
.finally(() => setLoading(false));
}, [studyId, refreshTick, nCompleted, minTrials]);
if (nCompleted < minTrials) {
return (
<Stack gap={4}>
<Divider label="Analysis" labelPosition="left" />
<Text size="xs" c="dimmed">
Analysis (parameter importance, history, slice plots, correlations)
will appear after {minTrials} trials complete. Currently: {nCompleted}.
</Text>
</Stack>
);
}
return (
<Stack gap="md">
<Divider label="Analysis" labelPosition="left" />
{loading && !report && (
<Center py="md">
<Loader size="sm" />
</Center>
)}
{report && (
<>
{report.importances.length > 0 && (
<ImportanceSection importances={report.importances} />
)}
{report.history.length > 0 && (
<HistorySection histories={report.history} />
)}
{report.correlations.length > 0 && (
<CorrelationSection correlations={report.correlations} />
)}
{Object.keys(report.slices).length > 0 && (
<SliceSection slices={report.slices} />
)}
</>
)}
</Stack>
);
}
// ── Parameter importance ───────────────────────────────────────────────
function ImportanceSection({
importances,
}: {
importances: ImportanceObjective[];
}) {
return (
<Stack gap="xs">
<Title order={6}>Parameter importance (fANOVA)</Title>
<Text size="xs" c="dimmed">
Fraction of variance in each objective explained by each parameter.
Higher = the optimization mostly turns on that knob.
</Text>
<SimpleGrid cols={{ base: 1, md: importances.length === 1 ? 1 : 2 }} spacing="md">
{importances.map((imp, i) => (
<ImportanceBars key={i} imp={imp} />
))}
</SimpleGrid>
</Stack>
);
}
function ImportanceBars({ imp }: { imp: ImportanceObjective }) {
if (imp.scores.length === 0) {
return (
<Stack gap={2}>
<Text size="sm" fw={500}>
{imp.objective} ({imp.direction})
</Text>
<Text size="xs" c="dimmed">
{imp.error ?? "Not enough data to compute importance yet."}
</Text>
</Stack>
);
}
const max = Math.max(...imp.scores.map((s) => s.score), 0.001);
return (
<Stack gap={2}>
<Text size="sm" fw={500}>
{imp.objective} ({imp.direction})
</Text>
<Stack gap={2}>
{imp.scores.map((s) => {
const w = (s.score / max) * 100;
return (
<Group key={s.param} gap={6} wrap="nowrap">
<Text size="xs" ff="monospace" style={{ width: 90 }}>
{s.param}
</Text>
<div
style={{
flex: 1,
height: 12,
background: "var(--mantine-color-gray-1)",
borderRadius: 2,
position: "relative",
overflow: "hidden",
}}
>
<div
style={{
width: `${w}%`,
height: "100%",
background: "var(--mantine-color-blue-5)",
}}
/>
</div>
<Text size="10px" ff="monospace" c="dimmed" style={{ width: 50 }}>
{(s.score * 100).toFixed(1)}%
</Text>
</Group>
);
})}
</Stack>
</Stack>
);
}
// ── Best-so-far history ─────────────────────────────────────────────────
function HistorySection({ histories }: { histories: HistoryObjective[] }) {
return (
<Stack gap="xs">
<Title order={6}>Optimization history</Title>
<Text size="xs" c="dimmed">
Best-so-far value per trial. A flat line = the search has converged
(or got stuck).
</Text>
<SimpleGrid cols={{ base: 1, md: histories.length === 1 ? 1 : 2 }} spacing="md">
{histories.map((h, i) => (
<HistoryChart key={i} h={h} />
))}
</SimpleGrid>
</Stack>
);
}
function HistoryChart({ h }: { h: HistoryObjective }) {
const W = 360;
const H = 140;
const M = { l: 50, r: 8, t: 6, b: 22 };
if (h.points.length === 0) return null;
const xs = h.points.map((p) => p.trial);
const ysAll = h.points.map((p) => p.value);
const ysBest = h.points.map((p) => p.best);
const xMin = Math.min(...xs);
const xMax = Math.max(...xs);
const yMin = Math.min(...ysAll, ...ysBest);
const yMax = Math.max(...ysAll, ...ysBest);
const xR = Math.max(1, xMax - xMin);
const yR = Math.max(1e-12, yMax - yMin);
const px = (x: number) => M.l + ((x - xMin) / xR) * (W - M.l - M.r);
const py = (y: number) => M.t + (1 - (y - yMin) / yR) * (H - M.t - M.b);
const allPoly = h.points.map((p) => `${px(p.trial)},${py(p.value)}`).join(" ");
const bestPoly = h.points.map((p) => `${px(p.trial)},${py(p.best)}`).join(" ");
return (
<Stack gap={2}>
<Text size="sm" fw={500}>
{h.objective} ({h.direction})
</Text>
<svg
viewBox={`0 0 ${W} ${H}`}
preserveAspectRatio="xMidYMid meet"
style={{ width: "100%", height: 140, background: "#fafafa", borderRadius: 4 }}
>
{/* Axes */}
<line x1={M.l} x2={M.l} y1={M.t} y2={H - M.b} stroke="#adb5bd" />
<line x1={M.l} x2={W - M.r} y1={H - M.b} y2={H - M.b} stroke="#adb5bd" />
{/* All trial values (light) */}
<polyline points={allPoly} fill="none" stroke="#adb5bd" strokeWidth={1} opacity={0.6} />
{h.points.map((p, i) => (
<circle key={i} cx={px(p.trial)} cy={py(p.value)} r={2.5} fill="#adb5bd" />
))}
{/* Best so far */}
<polyline points={bestPoly} fill="none" stroke="#1c7ed6" strokeWidth={1.5} />
{/* Y range labels */}
<text x={M.l - 4} y={M.t + 8} textAnchor="end" fontSize={10} fill="#868e96">
{fmt(yMax)}
</text>
<text x={M.l - 4} y={H - M.b} textAnchor="end" fontSize={10} fill="#868e96">
{fmt(yMin)}
</text>
<text x={M.l} y={H - M.b + 12} textAnchor="middle" fontSize={10} fill="#868e96">
{xMin}
</text>
<text x={W - M.r} y={H - M.b + 12} textAnchor="end" fontSize={10} fill="#868e96">
trial {xMax}
</text>
</svg>
</Stack>
);
}
// ── Correlations ────────────────────────────────────────────────────────
function CorrelationSection({
correlations,
}: {
correlations: CorrelationEntry[];
}) {
// Group by objective for a compact wide layout
const byObj: Record<string, CorrelationEntry[]> = {};
for (const c of correlations) {
(byObj[c.objective] ??= []).push(c);
}
return (
<Stack gap="xs">
<Title order={6}>Linear correlations (Pearson r)</Title>
<Text size="xs" c="dimmed">
Sign and magnitude of the linear relationship between each parameter and
each objective. Complements (and sometimes contradicts) the importance
scores: importance is non-linear, correlation is linear.
</Text>
<Table verticalSpacing={4} striped withTableBorder>
<Table.Thead>
<Table.Tr>
<Table.Th>Parameter</Table.Th>
{Object.keys(byObj).map((o) => (
<Table.Th key={o}>{o}</Table.Th>
))}
</Table.Tr>
</Table.Thead>
<Table.Tbody>
{paramOrder(correlations).map((p) => (
<Table.Tr key={p}>
<Table.Td>
<Text size="xs" ff="monospace">
{p}
</Text>
</Table.Td>
{Object.keys(byObj).map((o) => {
const c = byObj[o].find((x) => x.param === p);
if (!c) return <Table.Td key={o}>—</Table.Td>;
return (
<Table.Td key={o}>
<CorrCell r={c.r} n={c.n} />
</Table.Td>
);
})}
</Table.Tr>
))}
</Table.Tbody>
</Table>
</Stack>
);
}
function CorrCell({ r, n }: { r: number; n: number }) {
const abs = Math.abs(r);
const color = r >= 0 ? "blue" : "red";
const variant = abs >= 0.7 ? "filled" : abs >= 0.3 ? "light" : "outline";
return (
<Group gap={6} wrap="nowrap">
<Badge size="xs" color={color} variant={variant} ff="monospace">
{(r >= 0 ? "+" : "") + r.toFixed(3)}
</Badge>
<Text size="10px" c="dimmed">
n={n}
</Text>
</Group>
);
}
function paramOrder(correlations: CorrelationEntry[]): string[] {
const seen: string[] = [];
for (const c of correlations) if (!seen.includes(c.param)) seen.push(c.param);
return seen;
}
// ── Slice plots ─────────────────────────────────────────────────────────
function SliceSection({
slices,
}: {
slices: Record<string, SliceObjective[]>;
}) {
const params = Object.keys(slices);
return (
<Stack gap="xs">
<Title order={6}>Slice plots</Title>
<Text size="xs" c="dimmed">
How each objective varies with each individual parameter, holding the
others at whatever values the sampler chose. A clear trend = strong
sensitivity; scatter = the parameter does not matter on its own.
</Text>
{params.map((p) => (
<Stack key={p} gap={2}>
<Text size="sm" ff="monospace" fw={500}>
{p}
</Text>
<SimpleGrid cols={{ base: 1, md: slices[p].length }} spacing="sm">
{slices[p].map((slice, i) => (
<SliceChart key={i} param={p} slice={slice} />
))}
</SimpleGrid>
</Stack>
))}
</Stack>
);
}
function SliceChart({
param,
slice,
}: {
param: string;
slice: SliceObjective;
}) {
const W = 360;
const H = 130;
const M = { l: 50, r: 8, t: 6, b: 22 };
if (slice.points.length === 0) return null;
const xs = slice.points.map((p) => p.x);
const ys = slice.points.map((p) => p.y);
const xMin = Math.min(...xs);
const xMax = Math.max(...xs);
const yMin = Math.min(...ys);
const yMax = Math.max(...ys);
const xR = Math.max(1e-12, xMax - xMin);
const yR = Math.max(1e-12, yMax - yMin);
const px = (x: number) => M.l + ((x - xMin) / xR) * (W - M.l - M.r);
const py = (y: number) => M.t + (1 - (y - yMin) / yR) * (H - M.t - M.b);
return (
<Stack gap={0}>
<Text size="11px" c="dimmed">
{slice.objective} ({slice.direction})
</Text>
<svg
viewBox={`0 0 ${W} ${H}`}
preserveAspectRatio="xMidYMid meet"
style={{ width: "100%", height: 130, background: "#fafafa", borderRadius: 4 }}
>
<line x1={M.l} x2={M.l} y1={M.t} y2={H - M.b} stroke="#adb5bd" />
<line x1={M.l} x2={W - M.r} y1={H - M.b} y2={H - M.b} stroke="#adb5bd" />
{slice.points.map((p, i) => (
<circle key={i} cx={px(p.x)} cy={py(p.y)} r={3} fill="#1c7ed6" opacity={0.7} />
))}
<text x={M.l - 4} y={M.t + 8} textAnchor="end" fontSize={10} fill="#868e96">
{fmt(yMax)}
</text>
<text x={M.l - 4} y={H - M.b} textAnchor="end" fontSize={10} fill="#868e96">
{fmt(yMin)}
</text>
<text x={M.l} y={H - M.b + 12} textAnchor="middle" fontSize={10} fill="#868e96">
{fmt(xMin)}
</text>
<text x={W - M.r} y={H - M.b + 12} textAnchor="end" fontSize={10} fill="#868e96">
{fmt(xMax)} ({param})
</text>
</svg>
</Stack>
);
}
// ── helpers ─────────────────────────────────────────────────────────────
function fmt(v: number): string {
if (!isFinite(v)) return String(v);
const a = Math.abs(v);
if (a !== 0 && (a < 0.01 || a >= 10000)) return v.toExponential(2);
return Number(v.toPrecision(4)).toString();
}