File size: 2,728 Bytes
0e24aff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
/**
 * 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)}%`;
}