Spaces:
Sleeping
Sleeping
| /** | |
| * Render the agent's SymPy-grammar equation as KaTeX-friendly LaTeX. | |
| * | |
| * Implementation note: we do NOT run a full SymPy parser in the browser. | |
| * The agent's grammar is small and we transform a handful of common patterns | |
| * with regex substitutions. Edge cases that the regex misses simply render | |
| * as plain text — the reward bar is still authoritative. | |
| */ | |
| import katex from "katex"; | |
| export function renderEquationToLatex(equation: string): string { | |
| if (!equation) return ""; | |
| let latex = equation; | |
| // Second-order LHS: d2y/dt2 -> \\frac{d^2 y}{dt^2} | |
| latex = latex.replace(/\bd2([A-Za-z_][A-Za-z0-9_]*)\/dt2\b/g, "\\frac{d^2 $1}{dt^2}"); | |
| // First-order LHS: dy/dt -> \\frac{d y}{dt} | |
| latex = latex.replace(/\bd([A-Za-z_][A-Za-z0-9_]*)\/dt\b/g, "\\frac{d $1}{dt}"); | |
| // Power: x**2 -> x^{2} | |
| latex = latex.replace(/\*\*\s*([A-Za-z_0-9.]+)/g, "^{$1}"); | |
| // sqrt(x) -> \\sqrt{x} | |
| latex = latex.replace(/\bsqrt\s*\(([^)]*)\)/g, "\\sqrt{$1}"); | |
| // abs(x) -> |x|. Use \\lvert / \\rvert so KaTeX picks the right glyphs. | |
| // (Note: KaTeX doesn't ship \\abs; that's a physics-package macro that | |
| // would render in red.) | |
| latex = latex.replace(/\babs\s*\(([^)]*)\)/g, "\\lvert $1 \\rvert"); | |
| // Trig / exp / log get backslash prefixes. | |
| for (const fn of ["sin", "cos", "tan", "exp", "log"]) { | |
| latex = latex.replace(new RegExp(`\\b${fn}\\b`, "g"), `\\${fn}`); | |
| } | |
| // Multiplication: drop bare `*` between identifiers/numbers for prettier output. | |
| latex = latex.replace(/\s*\*\s*/g, " \\, "); | |
| // Greek-letter swaps. | |
| latex = latex.replace(/\btheta\b/g, "\\theta"); | |
| // Underscores in identifiers (e.g. ``drag_coeff``, ``initial_velocity``) | |
| // must be escaped — KaTeX otherwise treats ``_`` as a subscript operator | |
| // and renders ``drag_coeff`` as ``drag`` with subscript ``coeff``. Run | |
| // this last so transforms above (which produce structural ``_`` only | |
| // inside ``\\frac`` etc.) are not affected. We only escape underscores | |
| // that appear inside identifier-like runs (between word characters). | |
| latex = latex.replace(/(\w)_(\w)/g, "$1\\_$2"); | |
| return latex; | |
| } | |
| export function renderEquationInto(target: HTMLElement, equation: string): void { | |
| const latex = renderEquationToLatex(equation); | |
| try { | |
| katex.render(latex, target, { | |
| throwOnError: false, | |
| displayMode: true, | |
| output: "html", | |
| }); | |
| } catch (error) { | |
| target.innerText = equation; | |
| } | |
| } | |
| export function formatNumber(value: number, digits = 3): string { | |
| if (!Number.isFinite(value)) return "—"; | |
| return Number(value.toFixed(digits)).toString(); | |
| } | |
| export function formatPercent(value: number, digits = 1): string { | |
| return `${(value * 100).toFixed(digits)}%`; | |
| } | |