SPB Git

Repository Public

function-plot.tsx 7.9 KB 141 lines tsx

1import type { Locale, Tone } from "@/schema";2import { evaluateExpr, ExprError, linspace, parseExpr, quantile, type ParsedExpr } from "../core";3import { clamp, numberOption, type ParamDef, type SimConfig, type SimDef } from "../types";4import { decimalsOf, fmt } from "../ui/format";5import { Plot, type PlotLayer } from "../ui/Plot";6import { Readouts } from "../ui/Readouts";78export const EXPR_KEYS = ["expr", "expr2", "expr3", "expr4"] as const;9export const MAX_PLOT_PARAMS = 5;10const POINTS = 241;11const TONES: Tone[] = ["blue", "amber", "teal", "violet"];12const FIXED_KEYS = [...EXPR_KEYS, "label", "label2", "label3", "label4", "xMin", "xMax", "yMin", "yMax", "xLabel", "yLabel"];1314interface Parsed { curves: { key: string; expr: ParsedExpr }[]; errors: string[]; names: string[] }1516function parseConfig(config: SimConfig): Parsed {17  const curves: Parsed["curves"] = [], errors: string[] = [], names: string[] = [];18  for (const key of EXPR_KEYS) {19    const src = config[key];20    if (src === undefined || src === "") { if (key === "expr") errors.push("config.expr is required (for example \"a * sin(x)\")"); continue; }21    if (typeof src !== "string") { errors.push(`config.${key}: expected an expression as text`); continue; }22    try {23      const expr = parseExpr(src);24      curves.push({ key, expr });25      for (const v of expr.variables) if (v !== "x" && !names.includes(v)) names.push(v);26    } catch (e) { errors.push(`config.${key}: ${e instanceof ExprError ? e.message : "invalid expression"}`); }27  }28  if (names.length > MAX_PLOT_PARAMS) errors.push(`too many parameters (${names.join(", ")}): at most ${MAX_PLOT_PARAMS} names other than x`);29  return { curves, errors, names };30}3132function niceStep(span: number): number {33  const raw = span / 100;34  const pow = 10 ** Math.floor(Math.log10(raw));35  const f = raw / pow;36  return (f < 1.5 ? 1 : f < 3.5 ? 2 : f < 7.5 ? 5 : 10) * pow;37}3839/** One slider per name found in the expressions (other than x); bounds from config.<name>Min / <name>Max / <name>Step. */40export function functionPlotParams(config: SimConfig): ParamDef[] {41  return parseConfig(config).names.slice(0, MAX_PLOT_PARAMS).map((name) => {42    const min = numberOption(config, `${name}Min`, -5, -1e6, 1e6);43    let max = numberOption(config, `${name}Max`, 5, -1e6, 1e6);44    if (!(max > min)) max = min + 1;45    const stepOpt = numberOption(config, `${name}Step`, NaN);46    const step = stepOpt > 0 && stepOpt <= max - min ? stepOpt : niceStep(max - min);47    return { key: name, label: { fr: name, en: name }, min, max, step, default: clamp(1, min, max) };48  });49}5051export function functionPlotConfigErrors(config: SimConfig): string[] {52  const { errors, names } = parseConfig(config);53  const out = [...errors];54  const xMin = config.xMin, xMax = config.xMax;55  for (const k of ["xMin", "xMax", "yMin", "yMax"]) if (config[k] !== undefined && typeof config[k] !== "number") out.push(`config.${k}: expected a number`);56  if (typeof xMin === "number" && typeof xMax === "number" && !(xMax > xMin)) out.push("config.xMax must be greater than config.xMin");57  if (typeof config.yMin === "number" && typeof config.yMax === "number" && !(config.yMax > config.yMin)) out.push("config.yMax must be greater than config.yMin");58  const allowed = new Set([...FIXED_KEYS, "locale", "autoplay", ...names.flatMap((n) => [`${n}Min`, `${n}Max`, `${n}Step`])]);59  for (const k of Object.keys(config)) if (!allowed.has(k)) out.push(`config.${k}: unknown option`);60  for (const n of names) {61    const lo = config[`${n}Min`], hi = config[`${n}Max`];62    if (typeof lo === "number" && typeof hi === "number" && !(hi > lo)) out.push(`config.${n}Max must be greater than config.${n}Min`);63  }64  return out;65}6667export interface FunctionPlotModel {68  xLabel: string; yLabel: string;69  xDomain: [number, number]; yDomain: [number, number];70  /** One curve per expression; y is null where the value is not a finite number (gap). */71  curves: { label: string; source: string; points: { x: number; y: number | null }[] }[];72  values: { name: string; value: number; step: number }[];73}7475export function computeFunctionPlot(p: Readonly<Record<string, number>>, config: SimConfig): FunctionPlotModel {76  const parsed = parseConfig(config);77  if (parsed.errors.length) throw new Error(parsed.errors.join(" · "));78  const defs = functionPlotParams(config);79  const scope: Record<string, number> = {};80  for (const d of defs) scope[d.key] = typeof p[d.key] === "number" && Number.isFinite(p[d.key]) ? p[d.key] : d.default;81  const xMin = numberOption(config, "xMin", -5, -1e9, 1e9);82  let xMax = numberOption(config, "xMax", 5, -1e9, 1e9);83  if (!(xMax > xMin)) xMax = xMin + 10;84  const xs = linspace(xMin, xMax, POINTS);85  const raw = parsed.curves.map(({ expr }) => xs.map((x) => { const y = evaluateExpr(expr, { ...scope, x }); return Number.isNaN(y) ? null : y; }));86  const finite = raw.flat().filter((y): y is number => y !== null);87  let lo = finite.length ? Math.min(...finite) : -1, hi = finite.length ? Math.max(...finite) : 1;88  if (finite.length) {89    // Curves with poles (1/x, tan x) would flatten everything else: keep the central 96 % of the values in view.90    const q1 = quantile(finite, 0.02), q2 = quantile(finite, 0.98);91    if (q2 > q1 && hi - lo > 4 * (q2 - q1)) { lo = q1 - 0.25 * (q2 - q1); hi = q2 + 0.25 * (q2 - q1); }92  }93  if (!(hi > lo)) { lo -= 1; hi += 1; }94  const pad = 0.05 * (hi - lo);95  const yMin = numberOption(config, "yMin", lo - pad), yMaxOpt = numberOption(config, "yMax", hi + pad);96  const yDomain: [number, number] = [yMin, yMaxOpt > yMin ? yMaxOpt : yMin + 1];97  const curves = parsed.curves.map(({ key, expr }, c) => {98    const label = config[key.replace("expr", "label")];99    const points = xs.map((x, i) => ({ x, y: raw[c][i] }));100    // A jump from above the frame to below it (or back) between two samples is a pole, not a segment to draw.101    for (let i = 1; i < points.length; i++) {102      const a = raw[c][i - 1], b = raw[c][i];103      if (a !== null && b !== null && ((a > yDomain[1] && b < yDomain[0]) || (a < yDomain[0] && b > yDomain[1]))) points[i] = { x: points[i].x, y: null };104    }105    return { label: typeof label === "string" && label ? label : `y = ${expr.source.trim()}`, source: expr.source, points };106  });107  return {108    xLabel: typeof config.xLabel === "string" && config.xLabel ? config.xLabel : "x",109    yLabel: typeof config.yLabel === "string" && config.yLabel ? config.yLabel : "y",110    xDomain: [xMin, xMax], yDomain, curves,111    values: defs.map((d) => ({ name: d.key, value: scope[d.key], step: d.step })),112  };113}114115function FunctionPlotView({ model: m, locale, idPrefix }: { model: FunctionPlotModel; locale: Locale; idPrefix: string }) {116  const layers: PlotLayer[] = m.curves.map((c, i) => ({ type: "line", points: c.points, tone: TONES[i % TONES.length], name: c.label }));117  return (118    <>119      <Plot locale={locale} idPrefix={idPrefix} spec={{ title: m.curves.map((c) => c.label).join(" ; "), xLabel: m.xLabel, yLabel: m.yLabel, xDomain: m.xDomain, yDomain: m.yDomain, layers }} />120      {m.values.length ? <Readouts items={m.values.map((v) => ({ label: v.name, value: fmt(locale, v.value, Math.max(2, decimalsOf(v.step))) }))} /> : null}121    </>122  );123}124125export const functionPlot: SimDef<FunctionPlotModel> = {126  kind: "function-plot",127  title: { fr: "Tracé d'une fonction à paramètres", en: "Plot of a function with parameters" },128  description: {129    fr: "Courbe calculée point par point à partir de la formule de l'auteur (241 points). Les valeurs non définies ou infinies sont laissées en blanc ; près d'un pôle, l'axe vertical est resserré sur l'essentiel des valeurs.",130    en: "Curve computed point by point from the author's formula (241 points). Undefined or infinite values are left blank; near a pole the vertical axis is tightened around the bulk of the values.",131  },132  params: [],133  stochastic: false,134  configKeys: FIXED_KEYS,135  openConfig: true,136  paramsFor: functionPlotParams,137  validateConfig: functionPlotConfigErrors,138  compute: (p, _seed, c) => computeFunctionPlot(p, c),139  View: FunctionPlotView,140};141
Files main
Menu

Theme