import { useEffect, useMemo, useState } from "react"; import { Stack, Group, Title, Text, Button, TextInput, NumberInput, Select, ActionIcon, Badge, Table, Alert, Code, Divider, Tooltip, } from "@mantine/core"; import { IconTrash, IconPlus, IconPlayerPlay, IconPlayerStop, IconInfoCircle, } from "@tabler/icons-react"; import { StudyReport } from "./StudyReport"; import { notifications } from "@mantine/notifications"; import { listStudies, startStudy, stopStudy, StudyState, ParamSpec, SearchSpaceEntry, Objective, Reducer, Direction, Sampler, TARGET_REDUCERS, } from "../api"; interface Props { example: string | null; schema: ParamSpec[]; } interface SpaceRow { name: string; low: number; high: number; /** Optional discretization step. Empty/zero = continuous (or default 1 for ints). */ step: number | ""; } const REDUCERS: { value: Reducer; label: string }[] = [ { value: "abs_last", label: "abs(last) — drive value → 0" }, { value: "last", label: "last — final sample" }, { value: "mean", label: "mean — average over trace" }, { value: "abs_mean", label: "abs(mean)" }, { value: "stability", label: "stability — std-dev of 2nd half" }, { value: "mae", label: "MAE — mean absolute error vs target" }, { value: "mape", label: "MAPE % — mean absolute percent error vs target" }, ]; function isTargetReducer(r: Reducer): boolean { return (TARGET_REDUCERS as Reducer[]).includes(r); } const STATUS_COLOR: Record = { queued: "gray", running: "blue", done: "teal", cancelled: "yellow", failed: "red", }; const SAMPLER_LABELS: Record = { tpe: "TPE (Bayesian)", random: "Random", cmaes: "CMA-ES (single-objective only)", nsga2: "NSGA-II (multi-objective, default)", nsga3: "NSGA-III (3+ objectives)", }; const METRIC_OPTIONS = ["Step", "Temp", "Press", "Volume", "PotEng", "KinEng", "TotEng"]; function fmtTime(t: number): string { if (!t) return "—"; return new Date(t * 1000).toLocaleString(undefined, { month: "short", day: "numeric", hour: "2-digit", minute: "2-digit", }); } function fmtNum(v: number): string { if (!isFinite(v)) return String(v); const a = Math.abs(v); if (a !== 0 && (a < 0.01 || a >= 1000)) return v.toExponential(3); return Number(v.toPrecision(4)).toString(); } export function OptimizePanel({ example, schema }: Props) { // Configuration state const [name, setName] = useState("opt-study"); const [nTrials, setNTrials] = useState(10); const [sampler, setSampler] = useState("tpe"); const [objectives, setObjectives] = useState([ { metric: "Press", reduce: "abs_last", direction: "minimize" }, ]); const [rows, setRows] = useState([]); // Studies & active study const [studies, setStudies] = useState([]); const [activeId, setActiveId] = useState(null); const [submitting, setSubmitting] = useState(false); const numericParams = useMemo( () => schema.filter((p) => p.type === "float" || p.type === "int"), [schema] ); function refresh() { listStudies() .then(setStudies) .catch(() => setStudies([])); } useEffect(refresh, []); // Auto-pick sampler when number of objectives changes useEffect(() => { if (objectives.length >= 2 && (sampler === "tpe" || sampler === "cmaes")) { setSampler("nsga2"); } if (objectives.length === 1 && (sampler === "nsga2" || sampler === "nsga3")) { setSampler("tpe"); } }, [objectives.length]); // eslint-disable-line react-hooks/exhaustive-deps useEffect(() => { if (activeId !== null) return; const running = studies.find((s) => s.status === "running"); if (running) setActiveId(running.id); else if (studies.length > 0) setActiveId(studies[0].id); }, [studies, activeId]); const active = studies.find((s) => s.id === activeId) ?? null; const liveStudy = active && active.status === "running" ? active : null; useEffect(() => { if (!liveStudy) return; const t = setInterval(refresh, 2000); return () => clearInterval(t); }, [liveStudy?.id]); // eslint-disable-line react-hooks/exhaustive-deps // ---- objective row helpers ---- function addObjective() { setObjectives([ ...objectives, { metric: "Temp", reduce: "stability", direction: "minimize", target: null }, ]); } function changeReducer(i: number, newReducer: Reducer) { const o = objectives[i]; const next: Objective = { ...o, reduce: newReducer }; if (isTargetReducer(newReducer) && (o.target == null || o.target === undefined)) { // give the user a sensible starting value rather than an empty box next.target = 0; } setObjectives(objectives.map((x, ix) => (ix === i ? next : x))); } function updateObjective(i: number, patch: Partial) { setObjectives(objectives.map((o, ix) => (ix === i ? { ...o, ...patch } : o))); } function removeObjective(i: number) { if (objectives.length <= 1) return; setObjectives(objectives.filter((_, ix) => ix !== i)); } // ---- search space row helpers ---- /** Sensible default low/high/step for a freshly-picked parameter. */ function defaultsFor(spec: ParamSpec): { low: number; high: number; step: number | "" } { const isInt = spec.type === "int"; if (isInt) { return { low: spec.min ?? 1, high: (spec.min ?? 1) + 99, step: spec.step ?? 1 }; } const step = spec.step ?? 0.1; const lo = spec.min ?? 0; return { low: lo, high: lo + step * 10, step: "" }; } function addRow() { const used = new Set(rows.map((r) => r.name)); const next = numericParams.find((p) => !used.has(p.name)); if (!next) return; setRows([...rows, { name: next.name, ...defaultsFor(next) }]); } function changeRowParam(i: number, newName: string) { const oldRow = rows[i]; const oldSpec = numericParams.find((p) => p.name === oldRow.name); const newSpec = numericParams.find((p) => p.name === newName); if (!newSpec) return; // Reset bounds whenever the type changes (int <-> float). Otherwise keep // the user's bounds — they may have just renamed the parameter. if (oldSpec?.type !== newSpec.type) { setRows( rows.map((r, ix) => ix === i ? { name: newName, ...defaultsFor(newSpec) } : r ) ); } else { setRows(rows.map((r, ix) => (ix === i ? { ...r, name: newName } : r))); } } function updateRow(i: number, patch: Partial) { setRows(rows.map((r, ix) => (ix === i ? { ...r, ...patch } : r))); } function removeRow(i: number) { setRows(rows.filter((_, ix) => ix !== i)); } async function onStart() { if (!example) { notifications.show({ title: "Pick an example first", message: "Use the dropdown in the top toolbar.", color: "yellow", }); return; } if (rows.length === 0) { notifications.show({ title: "Empty search space", message: "Add at least one parameter to vary.", color: "yellow", }); return; } const space: Record = {}; for (const r of rows) { const spec = numericParams.find((p) => p.name === r.name); if (!spec) continue; const entry: SearchSpaceEntry = { type: spec.type === "int" ? "int" : "float", low: r.low, high: r.high, }; if (typeof r.step === "number" && r.step > 0) { entry.step = r.step; } space[r.name] = entry; } setSubmitting(true); try { const s = await startStudy({ name, example, fixed: {}, space, objectives, n_trials: nTrials, sampler, }); setActiveId(s.id); refresh(); notifications.show({ title: "Optimization started", message: `${s.n_trials} trials with ${SAMPLER_LABELS[s.sampler]}`, color: "teal", }); } catch (e) { notifications.show({ title: "Could not start study", message: String(e), color: "red", }); } finally { setSubmitting(false); } } async function onStop() { if (!active) return; try { await stopStudy(active.id); refresh(); } catch (e) { notifications.show({ title: "Stop failed", message: String(e), color: "red", }); } } return ( Set up an optimization } styles={{ message: { fontSize: 12 } }} > Each trial launches a run with parameters chosen by the sampler, then reduces the run's thermo trace to one value per objective. Add a second objective for trade-off optimisation (NSGA-II/III) — for example, minimise pressure deviation and maximise stability. Trials show up in the right-hand "Recent runs" panel — click any trial row below to inspect that run. setName(e.currentTarget.value)} placeholder="my-sweep" maxLength={80} /> setNTrials(typeof v === "number" ? v : 10)} min={1} max={500} /> v && updateObjective(i, { metric: v })} searchable /> v && updateObjective(i, { direction: v as Direction }) } /> removeObjective(i)} disabled={objectives.length <= 1} > ); })} {objectives.length >= 2 && ( Multi-objective active — Optuna will return a Pareto front of non-dominated trials, not a single best. )} {rows.length === 0 ? ( No parameters to vary yet. Add one with the button below. ) : ( Parameter Low High Step {rows.map((r, i) => { const spec = numericParams.find((p) => p.name === r.name); const isInt = spec?.type === "int"; const decimals = isInt ? 0 : spec?.decimals ?? 6; const stepInput = spec?.step ?? (isInt ? 1 : 0.1); const usedElsewhere = new Set( rows.filter((_, ix) => ix !== i).map((x) => x.name) ); const options = numericParams .filter((p) => !usedElsewhere.has(p.name)) .map((p) => ({ value: p.name, label: `${p.label} (${p.name})`, })); return (
)} {liveStudy && ( )} Example: {example ?? "—"}
Studies {studies.length} {studies.length > 0 && (