tokenfabrikker/rapport/lag_vedlegg.py
Kjell Tore Guttormsen 339161df18
docs(rapport): LaTeX skeleton of the report, the summary and the carousel, with placeholders for every result
Foreword, chapters 1, 2 and 8 and the appendix from equation to code are
written from the pre-registration, the review log and the map; the rest are
stubs. bygg.sh builds with a time limit per LaTeX run. Not yet read against
the sources by the session.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-14 09:29:57 +01:00

189 lines
6.8 KiB
Python

# ruff: noqa: INP001
"""Write appendix A of the report: from equation number to function.
Reads ``modell/kart.md`` (written by ``tokenfabrikker.kart``) and the equation
tags in ``modell/spesifikasjon.md``, and writes ``rapport/vedlegg_kart.tex``: one
row per equation S1..S54 with the chapter of the specification it stands in, the
functions that compute it, and the functions that put it together over the
years or the draws.
Standard library only. The output depends only on the two input files: same
input, same bytes. The script stops with an error, and writes nothing, when the
map does not hold exactly S1..S54 in order, when an equation has no chapter, when
a function name is not a plain dotted Python name, or when the counts do not
match the line the map states them in.
Run from anywhere: ``python3 rapport/lag_vedlegg.py``.
"""
from __future__ import annotations
import re
import sys
from pathlib import Path
ROT = Path(__file__).resolve().parent.parent
KART = ROT / "modell" / "kart.md"
SPEK = ROT / "modell" / "spesifikasjon.md"
UT = ROT / "rapport" / "vedlegg_kart.tex"
ANTALL = 54
KOLONNER = 3
SLAG_LIGNING = "ligning"
SLAG_SAMMENSATT = "setter sammen"
RAD = re.compile(r"^\|\s*(S\d+)\s*\|")
NAVN = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*)+$")
OVERSKRIFT = re.compile(r"^#{2,3} (\d+(?:\.\d+)?)\.? ")
MERKE = re.compile(r"\\tag\{(S\d+)\}")
OPPSUMMERING = re.compile(
r"^(\d+) ligninger, (\d+) funksjoner med nummeret i navnet og (\d+) oppføringer"
)
Rad = tuple[str, list[str], list[str]]
HODE = r"Ligning & Kapittel & Regner ligningen & Setter den sammen \\"
TEKST = (
r"Fra ligning til funksjon. Kapittel er kapitlet i modellspesifikasjonen der ligningen står."
)
class KartError(Exception):
"""The input does not have the expected form."""
def les_rad(linje: str) -> Rad:
"""Return (S-number, functions that compute it, functions that put it together) for a row."""
deler = [d.strip() for d in linje.strip().strip("|").split("|")]
if len(deler) < KOLONNER:
msg = f"row with fewer than three columns: {linje!r}"
raise KartError(msg)
nummer, funksjoner, slag = deler[0], deler[1], deler[2]
navn = [f.strip().strip("`") for f in funksjoner.split("<br>")]
typer = [s.strip() for s in slag.split("<br>")]
if len(navn) != len(typer):
msg = f"{nummer}: {len(navn)} functions but {len(typer)} kinds"
raise KartError(msg)
regner: list[str] = []
setter: list[str] = []
for n, s in zip(navn, typer, strict=True):
if not NAVN.match(n):
msg = f"{nummer}: not a plain dotted name: {n!r}"
raise KartError(msg)
if s == SLAG_LIGNING:
regner.append(n)
elif s == SLAG_SAMMENSATT:
setter.append(n)
else:
msg = f"{nummer}: unknown kind {s!r}"
raise KartError(msg)
return nummer, regner, setter
def les_kart(tekst: str) -> tuple[list[Rad], tuple[int, int, int]]:
"""Return the rows of the map and the three counts its text states."""
rader = [les_rad(linje) for linje in tekst.splitlines() if RAD.match(linje)]
forventet = [f"S{i}" for i in range(1, ANTALL + 1)]
if [r[0] for r in rader] != forventet:
msg = "the map does not hold exactly S1..S54 in order"
raise KartError(msg)
for linje in tekst.splitlines():
m = OPPSUMMERING.match(linje)
if m:
return rader, (int(m.group(1)), int(m.group(2)), int(m.group(3)))
msg = "the map has no line with the counts"
raise KartError(msg)
def les_kapitler(tekst: str) -> dict[str, str]:
"""Return the chapter number of the specification each equation tag stands under."""
kapittel: str | None = None
funnet: dict[str, str] = {}
for linje in tekst.splitlines():
m = OVERSKRIFT.match(linje)
if m:
kapittel = m.group(1)
for nummer in MERKE.findall(linje):
if nummer in funnet:
continue
if kapittel is None:
msg = f"{nummer} stands before the first chapter"
raise KartError(msg)
funnet[nummer] = kapittel
return funnet
def tex_navn(navn: str) -> str:
r"""A function name in \texttt, with break points after dots and underscores."""
brutt = navn.replace("_", r"\_\allowbreak{}").replace(".", r".\allowbreak{}")
return r"\texttt{" + brutt + "}"
def tex_liste(navn: list[str]) -> str:
"""The names one per line in the cell, or a dash when there are none."""
if not navn:
return "--"
return r"\newline ".join(tex_navn(n) for n in navn)
def lag(kart: str, spek: str) -> str:
"""Return the LaTeX of the appendix table."""
rader, (n_lign, n_navn, n_sammensatt) = les_kart(kart)
kapitler = les_kapitler(spek)
mangler = [r[0] for r in rader if r[0] not in kapitler]
if mangler:
msg = f"no chapter in the specification for {', '.join(mangler)}"
raise KartError(msg)
unike_regner = {n for _, regner, _ in rader for n in regner}
sum_sammensatt = sum(len(setter) for _, _, setter in rader)
talt = (len(rader), len(unike_regner), sum_sammensatt)
if talt != (n_lign, n_navn, n_sammensatt):
msg = f"counts {talt} do not match the map's {(n_lign, n_navn, n_sammensatt)}"
raise KartError(msg)
innledning = (
rf"\noindent Kartet har {n_lign} ligninger, {n_navn} funksjoner som har nummeret i navnet,"
rf" og {n_sammensatt} oppføringer for funksjoner som setter sammen. En funksjon kan stå"
r" ved flere ligninger."
)
ut = [
"% Laget av rapport/lag_vedlegg.py fra modell/kart.md og modell/spesifikasjon.md.",
"% Rettes ikke for hånd: kjør skriptet på nytt.",
innledning,
"",
r"{\footnotesize",
r"\setlength{\tabcolsep}{4pt}",
r"\renewcommand{\arraystretch}{1.12}",
r"\begin{xltabular}{\linewidth}{@{}P{11mm}P{13mm}LL@{}}",
r"\caption{" + TEKST + r"}\label{tab:kart}\\",
r"\toprule",
HODE,
r"\midrule",
r"\endfirsthead",
r"\toprule",
HODE,
r"\midrule",
r"\endhead",
r"\bottomrule",
r"\endfoot",
]
for nummer, regner, setter in rader:
celler = [nummer, kapitler[nummer], tex_liste(regner), tex_liste(setter)]
ut.append(" & ".join(celler) + r" \\")
ut += [r"\end{xltabular}", "}", ""]
return "\n".join(ut)
def main() -> int:
"""Write the appendix table; return 0, or 1 with a message on error."""
try:
tekst = lag(KART.read_text(encoding="utf-8"), SPEK.read_text(encoding="utf-8"))
except (KartError, OSError) as e:
sys.stderr.write(f"lag_vedlegg: {e}\n")
return 1
UT.write_text(tekst, encoding="utf-8", newline="\n")
sys.stdout.write(f"lag_vedlegg: skrev {UT.relative_to(ROT)}\n")
return 0
if __name__ == "__main__":
sys.exit(main())