Files
isotope-typst/src/isotope_typst/ast.py
T
paultal 5afbfd3165 Add clean Path A proof of concept
Spoken-English math to Typst with a small from-scratch encoder-decoder
Transformer, following the build guide: compile-checked synthetic data
generator, shared BPE tokenizer, nn.Transformer model, training loop with
an overfit sanity check, greedy decoding CLI, and evaluation on synthetic
and hand-written test sets. ./run.sh runs the whole pipeline.
2026-11-27 00:15:59 +02:00

120 lines
2.0 KiB
Python

"""Math expression trees. Every training pair is one tree rendered two ways (see render.py)."""
from __future__ import annotations
from dataclasses import dataclass
class Node:
pass
# -- leaves --------------------------------------------------------------------------------
@dataclass(frozen=True)
class Var(Node):
name: str # "x", "alpha", "pi", "e", "infinity", ...
@dataclass(frozen=True)
class Num(Node):
value: int
# -- operators -----------------------------------------------------------------------------
@dataclass(frozen=True)
class Neg(Node):
arg: Node
@dataclass(frozen=True)
class Add(Node):
left: Node
right: Node
@dataclass(frozen=True)
class Sub(Node):
left: Node
right: Node
@dataclass(frozen=True)
class Mul(Node):
left: Node
right: Node
@dataclass(frozen=True)
class Pow(Node):
base: Node
exp: Node
@dataclass(frozen=True)
class Frac(Node):
num: Node
den: Node
@dataclass(frozen=True)
class Sqrt(Node):
arg: Node
@dataclass(frozen=True)
class Func(Node):
name: str # one of FUNCS
arg: Node
# -- big operators -------------------------------------------------------------------------
@dataclass(frozen=True)
class Integral(Node):
body: Node
var: str
lo: Node | None = None # both None = indefinite integral
hi: Node | None = None
@dataclass(frozen=True)
class Sum(Node):
body: Node
var: str
lo: Node
hi: Node
@dataclass(frozen=True)
class Lim(Node):
body: Node
var: str
to: Node
# -- top level -----------------------------------------------------------------------------
@dataclass(frozen=True)
class Eq(Node):
left: Node
right: Node
GREEK = ["alpha", "beta", "gamma", "delta", "theta", "lambda", "mu", "sigma", "phi", "omega"]
FUNCS = ["sin", "cos", "tan", "ln", "log", "exp"]
BIG_OPS = (Integral, Sum, Lim)
def walk(n: Node):
"""Yield every node of the tree, parents before children."""
yield n
for v in vars(n).values():
if isinstance(v, Node):
yield from walk(v)