Repository Public
1/**2 * The simulation library: one pre-approved, declarative component per kind. A document only names a kind and gives3 * parameter values; it can never supply code. This module has no browser dependency and is safe to import on the server4 * (validation, quality report, exporters).5 */6import { SIM_KINDS, type BlockOf, type SimKind } from "@/schema";7import type { ChartSpec } from "@/renderer/chart/types";8import { attention } from "./kinds/attention";9import { confidenceInterval } from "./kinds/confidence-interval";10import { correlation } from "./kinds/correlation";11import { distribution } from "./kinds/distribution";12import { eventStudy } from "./kinds/event-study";13import { functionPlot } from "./kinds/function-plot";14import { garch } from "./kinds/garch";15import { impulseResponse } from "./kinds/impulse-response";16import { kvCache } from "./kinds/kv-cache";17import { moeRouting } from "./kinds/moe-routing";18import { neuralForward } from "./kinds/neural-forward";19import { randomWalk } from "./kinds/random-walk";20import { regression } from "./kinds/regression";21import type { ParamDef, SimConfig, SimDef } from "./types";2223export type SimBlock = BlockOf<"simulation">;24export type { ParamDef, SimDef, SimConfig, SimParams, ViewProps, L10n } from "./types";25export type { ChartSpec };2627/** Every kind of the schema has a definition: a missing or misspelt key is a type error. */28export const SIMULATIONS: Record<SimKind, SimDef> = {29 "moe-routing": moeRouting,30 "neural-forward": neuralForward,31 "kv-cache": kvCache,32 attention,33 distribution,34 "confidence-interval": confidenceInterval,35 regression,36 correlation,37 garch,38 "random-walk": randomWalk,39 "impulse-response": impulseResponse,40 "event-study": eventStudy,41 "function-plot": functionPlot,42};4344/** Config keys accepted by every kind. `locale` is set by the block itself (default example text). */45export const COMMON_CONFIG_KEYS: readonly string[] = ["locale", "autoplay"];4647type BlockParams = Pick<SimBlock, "kind" | "params"> & { config?: SimBlock["config"] };4849export function isSimKind(kind: unknown): kind is SimKind { return typeof kind === "string" && (SIM_KINDS as readonly string[]).includes(kind); }5051/** The sliders of a block: fixed for most kinds, derived from `config` for distribution, random-walk and function-plot. */52export function paramDefs(kind: SimKind, config: SimConfig = {}): ParamDef[] {53 const def = SIMULATIONS[kind];54 if (!def) return [];55 try { return def.paramsFor ? def.paramsFor(config) : def.params; } catch { return def.params; }56}5758/** A value brought back inside [min, max] and onto the slider grid min + k·step. */59export function snapParam(def: ParamDef, value: number): number {60 const v = Number.isFinite(value) ? value : def.default;61 const k = Math.round((Math.min(def.max, Math.max(def.min, v)) - def.min) / def.step);62 const snapped = Number((def.min + k * def.step).toFixed(10));63 return Math.min(def.max, Math.max(def.min, snapped));64}6566/** Parameters of a block with defaults filled in and every value clamped to its bounds (and rounded to its step). */67export function resolveParams(block: BlockParams): Record<string, number> {68 const out: Record<string, number> = {};69 const given = block.params ?? {};70 for (const def of paramDefs(block.kind, block.config ?? {})) {71 const v = Object.hasOwn(given, def.key) ? given[def.key] : def.default;72 out[def.key] = snapParam(def, typeof v === "number" ? v : def.default);73 }74 return out;75}7677/** Problems in a simulation block (unknown parameter, bad function-plot expression…). Empty when valid. */78export function validateSimulation(block: SimBlock): string[] {79 if (!isSimKind(block.kind)) return [`unknown simulation kind ${JSON.stringify(block.kind)} (available: ${SIM_KINDS.join(", ")})`];80 const def = SIMULATIONS[block.kind];81 const config = block.config ?? {}, params = block.params ?? {};82 const out: string[] = [];83 try { out.push(...(def.validateConfig?.(config) ?? [])); } catch { out.push("config could not be validated"); }84 if (!def.openConfig) {85 const allowed = [...(def.configKeys ?? []), ...COMMON_CONFIG_KEYS];86 for (const k of Object.keys(config)) if (!allowed.includes(k)) out.push(`config.${k}: unknown option for ${block.kind}${def.configKeys?.length ? ` (available: ${def.configKeys.join(", ")})` : " (it takes none)"}`);87 }88 const defs = paramDefs(block.kind, config);89 for (const [key, value] of Object.entries(params)) {90 const d = defs.find((x) => x.key === key);91 if (!d) { out.push(`params.${key}: unknown parameter for ${block.kind}${defs.length ? ` (available: ${defs.map((x) => x.key).join(", ")})` : ""}`); continue; }92 if (typeof value !== "number" || !Number.isFinite(value)) out.push(`params.${key}: expected a finite number`);93 else if (value < d.min || value > d.max) out.push(`params.${key} = ${value} is outside ${d.min} … ${d.max} (it will be clamped)`);94 }95 if (out.length === 0) {96 try { def.compute(resolveParams(block), block.seed ?? 1, config); }97 catch (e) { out.push(e instanceof Error ? e.message : "the simulation could not be computed"); }98 }99 return out;100}101102/** One line of text with the parameter values, for static exports and text alternatives. */103export function describeParams(block: BlockParams, locale: "fr" | "en"): string {104 const values = resolveParams(block);105 const nf = new Intl.NumberFormat(locale, { maximumFractionDigits: 6 });106 return paramDefs(block.kind, block.config ?? {}).map((d) => `${d.label[locale]} = ${nf.format(values[d.key])}${d.unit ? ` ${d.unit}` : ""}`).join(locale === "fr" ? " ; " : "; ");107}108