Files
isotope-typst/src/isotope_typst/generate.py
T
paultal 4fb7726e4b Use the whole alphabet and Greek alphabet for variables (#14)
Variables are now x/y (45%), any lowercase letter except e and d (35%), any lowercase Greek letter except pi and omicron (15%), or a common uppercase letter like N, F, A (5%). e stays a constant and d is kept for dx and future derivatives.

Hand-test exact 41.2% -> 56.9% (trained without #2), variables category 0% -> 87.5%.

Fixes #4

Co-authored-by: Paul Tal <[email protected]>
2026-11-27 02:40:48 +02:00

272 lines
9.7 KiB
Python

"""Generate (English, Typst) training pairs from random expression trees.
uv run isotope-gen # 200k pairs into data/
uv run isotope-gen -n 5000 # a quick small set
Writes data/{train,valid,test}.jsonl with lines {"en": ..., "typ": ...} and data/stats.txt.
"""
from __future__ import annotations
import argparse
import collections
import hashlib
import json
import pathlib
import random
from typing import ClassVar
from .ast import (
FUNCS,
GREEK,
LATIN,
UPPER,
Add,
Eq,
Frac,
Func,
Integral,
Lim,
Mul,
Neg,
Node,
Num,
Pow,
Sqrt,
Sub,
Sum,
Var,
walk,
)
from .render import to_english, to_typst
from .validate import compiles_many
INF = Var("infinity")
class TreeGen:
def __init__(self, rng: random.Random):
self.rng = rng
# -- leaves ---------------------------------------------------------------------------
def var(self, prefer: str | None = None) -> Var:
if prefer and self.rng.random() < 0.6: # inside "integral ... dx", mostly use x
return Var(prefer)
r = self.rng.random()
if r < 0.45: # x and y stay the most common, as in real maths
return Var("x" if r < 0.33 else "y")
if r < 0.80:
return Var(self.rng.choice(LATIN))
if r < 0.95:
return Var(self.rng.choice(GREEK))
return Var(self.rng.choice(UPPER))
def num(self) -> Num:
r = self.rng.random()
if r < 0.8:
return Num(self.rng.randint(1, 10))
if r < 0.85:
return Num(0)
if r < 0.95:
return Num(self.rng.randint(11, 20))
return Num(self.rng.choice([25, 50, 100, 360, 1000]))
def leaf(self, prefer: str | None = None) -> Node:
r = self.rng.random()
if r < 0.55:
return self.var(prefer)
if r < 0.92:
return self.num()
return Var(self.rng.choice(["pi", "e"]))
# -- expressions without big operators ----------------------------------------------------
KINDS: ClassVar[dict[str, int]] = {
"Add": 12,
"Sub": 8,
"Mul": 12,
"Pow": 14,
"Frac": 10,
"Neg": 4,
"Sqrt": 5,
"Func": 8,
}
def expr(self, depth: int, prefer: str | None = None) -> Node:
r = self.rng
if depth <= 0:
return self.leaf(prefer)
kind = r.choices(list(self.KINDS), list(self.KINDS.values()))[0]
d = depth - 1
small = 0 if r.random() < 0.5 else d # keep one side shallow half the time
match kind:
case "Add" | "Sub":
return (Add if kind == "Add" else Sub)(self.expr(d, prefer), self.expr(small, prefer))
case "Mul":
a = self.num() if r.random() < 0.4 else self.expr(small, prefer)
b = self.expr(d, prefer)
if isinstance(b, Num) and not isinstance(a, Num):
a, b = b, a # "2 x", not "x 2"
return Mul(a, b)
case "Pow":
base = Var("e") if r.random() < 0.15 else self.expr(d if r.random() < 0.25 else 0, prefer)
if isinstance(base, Pow):
base = base.base
x = r.random()
if x < 0.55:
exp: Node = Num(r.choice([2, 2, 2, 3, 3, 4, 5, 10]))
elif x < 0.7:
exp = Var(r.choice(["n", "k", "x", "a", "m", "t"]))
elif x < 0.85:
exp = Neg(self.leaf(prefer))
else:
exp = self.expr(d, prefer)
return Pow(base, exp)
case "Frac":
den = self.expr(small, prefer)
while den == Num(0):
den = self.leaf(prefer)
return Frac(self.expr(d, prefer), den)
case "Neg":
a = self.expr(d, prefer)
while isinstance(a, Neg) or a == Num(0):
a = self.leaf(prefer)
return Neg(a)
case "Sqrt":
return Sqrt(self.expr(d, prefer))
case "Func":
return Func(r.choice(FUNCS + ["sin", "cos", "ln"]), self.expr(small, prefer))
raise AssertionError(kind)
# -- big operators: only ever at the top of a tree -------------------------------------
def big(self, depth: int) -> Node:
r = self.rng
kind = r.choices(["Integral", "Sum", "Lim"], [6, 3, 3])[0]
if kind == "Integral":
v = r.choice(["x"] * 6 + ["t", "u", "y", "theta"])
body = self.expr(max(depth, 1), v)
if r.random() < 0.3:
return Integral(body, v)
lo = r.choice([Num(0)] * 5 + [Num(1)] * 2 + [Neg(Num(1)), Var("a"), Neg(INF)])
hi = r.choice([Num(1)] * 3 + [INF] * 3 + [Num(2), Var("b"), Var("pi"), Var("x"), Frac(Var("pi"), Num(2))])
return Integral(body, v, lo, hi)
if kind == "Sum":
v = r.choice(["i", "k", "n", "j"])
hi = r.choice([Var("n"), Var("N"), INF, Num(10), Num(100)])
if hi == Var(v):
hi = INF
return Sum(self.expr(depth, v), v, r.choice([Num(0), Num(1), Num(1)]), hi)
v = r.choice(["x"] * 4 + ["n", "h", "t"])
to = r.choice([Num(0)] * 4 + [INF] * 4 + [Num(1), Var("a"), Neg(INF)])
return Lim(self.expr(max(depth, 1), v), v, to)
def term(self) -> Node:
"""One textbook-style term: x^2, 3 x, sin(x)^2, y, 7."""
r = self.rng
v = self.var()
match r.choices(["pow", "coef", "trig", "var", "num"], [5, 2, 1, 2, 1])[0]:
case "pow":
return Pow(v, Num(r.choice([2, 2, 2, 3])))
case "coef":
return Mul(Num(r.randint(2, 9)), r.choice([v, Pow(v, Num(2))]))
case "trig":
return Pow(Func(r.choice(["sin", "cos", "tan"]), v), Num(2))
case "var":
return v
return self.num()
def terms(self) -> Node:
"""A flat sum of 2-3 simple terms, like x^2 + y^2 or a x^2 + b x + c.
Random trees almost never produce these shapes, yet they are the most common left sides people say.
"""
r = self.rng
out = self.term()
for _ in range(r.choice([1, 1, 2])):
out = (Add if r.random() < 0.75 else Sub)(out, self.term())
return out
def tree(self) -> Node:
r = self.rng
depth = r.choices([1, 2, 3, 4], [25, 40, 25, 10])[0]
e = self.big(depth - 1) if r.random() < 0.3 else self.expr(depth)
if r.random() < 0.2:
# a long left side too ("x^2 + y^2 = r^2"), not only "y = ...": depth 2+ was never seen before (#2)
x = r.random()
if x < 0.35:
lhs: Node = r.choice([Var("y"), Var("f"), Var("x")])
elif x < 0.65:
lhs = self.terms()
else:
lhs = self.expr(r.choices([0, 1, 2, 3], [2, 3, 3, 2])[0])
return Eq(lhs, e)
return e
def split_of(typ: str) -> str:
"""Split by structure, not by row: the same Typst string always lands in the same split."""
h = int(hashlib.md5(typ.encode()).hexdigest(), 16) % 100
return "valid" if h < 2 else "test" if h < 4 else "train"
def main(argv: list[str] | None = None) -> None:
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("-n", type=int, default=200_000, help="number of pairs to generate")
ap.add_argument("--per-tree", type=int, default=2, help="max English phrasings per tree")
ap.add_argument("--max-chars", type=int, default=150, help="drop trees whose Typst is longer than this")
ap.add_argument("--out", default="data")
ap.add_argument("--seed", type=int, default=0)
args = ap.parse_args(argv)
rng = random.Random(args.seed)
gen = TreeGen(rng)
pairs: list[tuple[str, str, Node]] = []
seen: set[str] = set()
while len(pairs) < args.n:
t = gen.tree()
typ = to_typst(t)
if len(typ) > args.max_chars:
continue
for _ in range(rng.randint(1, args.per_tree)):
en = to_english(t, rng)
if en not in seen:
seen.add(en)
pairs.append((en, typ, t))
distinct = sorted({typ for _, typ, _ in pairs})
print(f"generated {len(pairs):,} pairs ({len(distinct):,} distinct Typst strings); compile-checking ...")
ok = dict(zip(distinct, compiles_many(distinct)))
bad = [s for s in distinct if not ok[s]]
if bad:
print(f"WARNING: dropped {len(bad)} Typst strings that do not compile, e.g.:")
for s in bad[:10]:
print(" ", s)
out = pathlib.Path(args.out)
out.mkdir(parents=True, exist_ok=True)
files = {k: (out / f"{k}.jsonl").open("w") for k in ("train", "valid", "test")}
counts: collections.Counter[str] = collections.Counter()
hist: collections.Counter[str] = collections.Counter()
for en, typ, t in pairs:
if not ok[typ]:
continue
split = split_of(typ)
files[split].write(json.dumps({"en": en, "typ": typ}) + "\n")
counts[split] += 1
if split == "train":
hist.update({type(x).__name__ for x in walk(t)})
for f in files.values():
f.close()
total = counts["train"] or 1
lines = [f"split sizes: {dict(counts)}", "share of training pairs containing each node type:"]
for k, v in hist.most_common():
lines.append(f" {k:<9}{v / total:6.1%} {'#' * int(40 * v / total)}")
report = "\n".join(lines)
print(report)
(out / "stats.txt").write_text(report + "\n")
print(f"wrote {out}/train.jsonl, valid.jsonl, test.jsonl")
if __name__ == "__main__":
main()