First full draft of the Volve-DIA paper in paper/ (13 LaTeX sections, 44 pages), four figures built from outputs/ with assertions, a checker that traces every number to plan.md or outputs/, and a source audit with its fixes. Correct the pooled T2(b) values in the notes to the primary values and sync the plan, README, overview and progress page. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
437 lines
18 KiB
Python
437 lines
18 KiB
Python
#!/usr/bin/env python3
|
||
"""Check that every number in paper/sections/*.tex appears in the project's result registry.
|
||
|
||
python paper/check_numbers.py full report, grouped by file and line; exit 1 if anything is unmatched
|
||
python paper/check_numbers.py --summary counts per file only
|
||
|
||
Registry: every number in docs/plan.md, docs/technical_overview.md and AGENTS.md (Vietnamese formats are normalised:
|
||
0,151 -> 0.151 and 1.376 -> 1376; an ambiguous token such as 1.376 or 1,376 enters with both readings), and every
|
||
number in outputs/**/report.json, outputs/**/summary.json, outputs/m5/**/*.csv and outputs/m34/*.csv. A paper number
|
||
with d decimals matches a registry value r when |r| rounds to it at d decimals (signs are ignored, because the paper
|
||
writes differences with an explicit sign or a minus sign). A number marked as a percentage (15.1\\%, 15.1 per cent)
|
||
matches only when 100 * r rounds to it; a percentage in the docs (2,40%) enters as its fraction (0.024).
|
||
paper/number_allowlist.txt holds hand-checked derived values, one 'number # reason' per line.
|
||
|
||
Ignored in the .tex: comments, \\label, \\ref-like commands, citations, \\todo, \\includegraphics, \\input, \\url,
|
||
lengths (2pt, 0.8\\textwidth), tabular column specs, tikzpicture environments, dates (20/11/2026, 2026-11-20,
|
||
20 November 2026), version strings (3.11.2), well names (15/9-F-15) and digits glued to letters or underscores
|
||
(T4, v6, protocol_v1, hash fragments such as 3c8021f9). Standard library only.
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import argparse
|
||
import bisect
|
||
import csv
|
||
import json
|
||
import re
|
||
import sys
|
||
from dataclasses import dataclass, field
|
||
from pathlib import Path
|
||
|
||
ROOT = Path(__file__).resolve().parents[1]
|
||
DOCS = ("docs/plan.md", "docs/technical_overview.md", "AGENTS.md")
|
||
JSON_GLOBS = ("outputs/**/report.json", "outputs/**/summary.json")
|
||
CSV_GLOBS = ("outputs/m5/**/*.csv", "outputs/m34/*.csv")
|
||
EPS = 1e-9
|
||
|
||
# ---------------------------------------------------------------- registry
|
||
|
||
DOC_TOKEN = re.compile(r"\d+(?:[.,]\d+)*")
|
||
|
||
|
||
def doc_readings(token):
|
||
"""All plausible values of a number written in English or Vietnamese style."""
|
||
seps = re.findall(r"[.,]", token)
|
||
groups = re.split(r"[.,]", token)
|
||
if not seps:
|
||
return {float(token)}
|
||
out = set()
|
||
if len(seps) == 1:
|
||
head, tail = groups
|
||
out.add(float(f"{head}.{tail}"))
|
||
if len(tail) == 3 and not head.startswith("0"): # 1.376 or 1,376 may be thousands
|
||
out.add(float(head + tail))
|
||
return out
|
||
if len(set(seps)) == 1:
|
||
if all(len(g) == 3 for g in groups[1:]) and not groups[0].startswith("0"):
|
||
out.add(float("".join(groups)))
|
||
else: # version-like (3.11.2): keep the components
|
||
out.update(float(g) for g in groups)
|
||
return out
|
||
last = max(token.rfind("."), token.rfind(","))
|
||
whole = re.sub(r"[.,]", "", token[:last])
|
||
out.add(float(f"{whole}.{token[last + 1:]}"))
|
||
return out
|
||
|
||
|
||
def numbers_from_text(text):
|
||
vals = set()
|
||
for m in DOC_TOKEN.finditer(text):
|
||
readings = doc_readings(m.group(0))
|
||
if DOC_PERCENT.match(text, m.end()): # 2,40% enters as the fraction 0.024 only
|
||
readings = {r / 100 for r in readings}
|
||
vals |= readings
|
||
return vals
|
||
|
||
|
||
DOC_PERCENT = re.compile(r"\s?(?:%|\\%|per ?cent\b|phần trăm)")
|
||
|
||
|
||
def numbers_from_json(obj, vals):
|
||
if isinstance(obj, bool) or obj is None:
|
||
return
|
||
if isinstance(obj, (int, float)):
|
||
if obj == obj and abs(obj) != float("inf"):
|
||
vals.add(float(obj))
|
||
elif isinstance(obj, str):
|
||
_strnum(obj, vals)
|
||
elif isinstance(obj, dict):
|
||
for k, v in obj.items():
|
||
_strnum(k, vals)
|
||
numbers_from_json(v, vals)
|
||
elif isinstance(obj, list):
|
||
for v in obj:
|
||
numbers_from_json(v, vals)
|
||
|
||
|
||
NUM_IN_CELL = re.compile(r"-?\d+(?:\.\d+)?(?:[eE][-+]?\d+)?")
|
||
|
||
|
||
def _strnum(s, vals):
|
||
if len(s) > 2000: # long free text (model answers) is not a result
|
||
return
|
||
for m in NUM_IN_CELL.finditer(s):
|
||
try:
|
||
vals.add(float(m.group(0)))
|
||
except ValueError:
|
||
pass
|
||
|
||
|
||
def numbers_from_csv(path, vals):
|
||
csv.field_size_limit(sys.maxsize)
|
||
with open(path, newline="", encoding="utf-8", errors="replace") as fh:
|
||
for row in csv.reader(fh):
|
||
for cell in row:
|
||
_strnum(cell, vals)
|
||
|
||
|
||
@dataclass
|
||
class Registry:
|
||
values: list = field(default_factory=list)
|
||
sources: dict = field(default_factory=dict)
|
||
missing: list = field(default_factory=list)
|
||
|
||
def finish(self, vals):
|
||
self.values = sorted({abs(v) for v in vals})
|
||
|
||
def contains(self, value, decimals):
|
||
"""True if some registry value rounds to |value| at the given number of decimals."""
|
||
half = 0.5 * 10 ** -decimals
|
||
lo, hi = abs(value) - half - EPS, abs(value) + half + EPS
|
||
i = bisect.bisect_left(self.values, lo)
|
||
return i < len(self.values) and self.values[i] <= hi
|
||
|
||
|
||
def build_registry(root=ROOT, docs=DOCS, json_globs=JSON_GLOBS, csv_globs=CSV_GLOBS):
|
||
reg, vals = Registry(), set()
|
||
root = Path(root)
|
||
for rel in docs:
|
||
p = root / rel
|
||
if not p.exists():
|
||
reg.missing.append(rel)
|
||
continue
|
||
found = numbers_from_text(p.read_text(encoding="utf-8", errors="replace"))
|
||
reg.sources[rel] = len(found)
|
||
vals |= found
|
||
for pattern, reader in [(g, "json") for g in json_globs] + [(g, "csv") for g in csv_globs]:
|
||
paths = sorted(root.glob(pattern))
|
||
if not paths:
|
||
reg.missing.append(pattern)
|
||
for p in paths:
|
||
found = set()
|
||
try:
|
||
if reader == "json":
|
||
numbers_from_json(json.loads(p.read_text(encoding="utf-8")), found)
|
||
else:
|
||
numbers_from_csv(p, found)
|
||
except (OSError, ValueError) as exc:
|
||
reg.missing.append(f"{p.relative_to(root)} ({exc.__class__.__name__})")
|
||
continue
|
||
reg.sources[str(p.relative_to(root))] = len(found)
|
||
vals |= found
|
||
reg.finish(vals)
|
||
return reg
|
||
|
||
|
||
# ---------------------------------------------------------------- LaTeX scanning
|
||
|
||
# command -> number of mandatory arguments to blank (optional [..] arguments before them are blanked too)
|
||
BLANK_COMMANDS = {
|
||
"label": 1, "ref": 1, "eqref": 1, "cref": 1, "Cref": 1, "autoref": 1, "pageref": 1, "nameref": 1, "vref": 1,
|
||
"cite": 1, "citep": 1, "citet": 1, "citealp": 1, "citealt": 1, "citeauthor": 1, "citeyear": 1, "citeyearpar": 1,
|
||
"parencite": 1, "textcite": 1, "nocite": 1, "todo": 1, "includegraphics": 1, "input": 1, "include": 1, "url": 1,
|
||
"href": 1, "hyperref": 0, "bibliography": 1, "bibliographystyle": 1, "usepackage": 1, "documentclass": 1,
|
||
"setcounter": 2, "addtocounter": 2, "setlength": 2, "addtolength": 2, "vspace": 1, "hspace": 1, "vskip": 0,
|
||
"linenumbers": 0, "multicolumn": 2, "multirow": 2, "cmidrule": 1, "cline": 1, "rule": 2, "resizebox": 2,
|
||
"scalebox": 1, "fontsize": 2, "color": 1, "textcolor": 1, "definecolor": 3, "colorbox": 1, "newcommand": 1,
|
||
"renewcommand": 2, "arraystretch": 0, "linespread": 1, "raisebox": 1, "makebox": 0, "parbox": 1,
|
||
"columnwidth": 0, "graphicspath": 1, "ding": 1, "cellcolor": 1, "rowcolor": 1,
|
||
}
|
||
ENV_ARGS = {"tabular": 1, "tabular*": 2, "tabularx": 2, "tabulary": 2, "longtable": 1, "array": 1, "minipage": 1,
|
||
"wrapfigure": 2, "subfigure": 1, "multicols": 1, "tblr": 1}
|
||
BLANK_ENVS = ("tikzpicture", "comment", "verbatim", "lstlisting", "filecontents")
|
||
MONTHS = ("January|February|March|April|May|June|July|August|September|October|November|December|"
|
||
"Jan|Feb|Mar|Apr|Jun|Jul|Aug|Sep|Sept|Oct|Nov|Dec")
|
||
PATTERNS = [
|
||
re.compile(r"(?<!\\)%.*"), # comments
|
||
re.compile(r"\d*\.?\d+(?:pt|cm|mm|in|em|ex|bp|sp|pc)\b"), # lengths 2pt, 0.5em
|
||
re.compile(r"\d*\.?\d+\s*\\(?:textwidth|linewidth|columnwidth|textheight|baselineskip|paperwidth|hsize)"),
|
||
re.compile(r"\b\d{1,2}/\d{1,2}/(?:19|20)\d{2}\b"), # 20/11/2026
|
||
re.compile(r"\b(?:19|20)\d{2}-\d{2}-\d{2}(?:[T ]\d{2}:\d{2}(?::\d{2})?)?\b"), # 2026-11-20
|
||
re.compile(rf"\b\d{{1,2}}(?:st|nd|rd|th)?(?:~|\s)+(?:{MONTHS})\.?(?:,?(?:~|\s)+(?:19|20)\d{{2}})?\b"),
|
||
re.compile(rf"\b(?:{MONTHS})\.?(?:~|\s)+\d{{1,2}}(?:,?(?:~|\s)+(?:19|20)\d{{2}})?\b"),
|
||
re.compile(rf"\b(?:{MONTHS})\.?(?:~|\s)+(?:19|20)\d{{2}}\b"),
|
||
re.compile(r"\b\d{1,2}:\d{2}(?::\d{2})?\s*(?:UTC|h)?\b"), # times 06:32 UTC
|
||
re.compile(r"\b\d+/\d+-(?:[A-Z]+-)?\d+(?:\s?(?:A|B|C|S|T2|BT2|SR|ST2|ST3)\b)?"), # well names 15/9-F-15 S
|
||
re.compile(r"\b\d+(?:\.\d+){2,}\b"), # versions 3.11.2
|
||
]
|
||
NUMBER = re.compile(r"(?<![\w.\\])(\d{1,3}(?:,\d{3})+(?!\d)|\d+)(\.\d+)?(?![\w])(?!\.\d)")
|
||
PERCENT_AFTER = re.compile(r"\s*(?:\\%|%|(?:~|\s)per(?:~|\s)?cent\b|(?:~|\s)percent\b)")
|
||
|
||
|
||
def _blank(chars, start, end):
|
||
for i in range(start, end):
|
||
if chars[i] != "\n":
|
||
chars[i] = " "
|
||
|
||
|
||
def _match_group(text, i, open_c, close_c):
|
||
"""Index just past the group starting at text[i] == open_c, honouring nesting and escapes."""
|
||
depth, j = 0, i
|
||
while j < len(text):
|
||
c = text[j]
|
||
if c == "\\":
|
||
j += 2
|
||
continue
|
||
if c == open_c:
|
||
depth += 1
|
||
elif c == close_c:
|
||
depth -= 1
|
||
if depth == 0:
|
||
return j + 1
|
||
j += 1
|
||
return len(text)
|
||
|
||
|
||
def _skip_args(text, j, mandatory):
|
||
"""Skip whitespace, *, [..] and (..) groups and `mandatory` {..} groups starting at j; return the new index."""
|
||
n = 0
|
||
while j < len(text):
|
||
k = j
|
||
while k < len(text) and text[k] in " \t":
|
||
k += 1
|
||
if k < len(text) and text[k] == "*":
|
||
j = k + 1
|
||
continue
|
||
if k < len(text) and text[k] == "[" and (n < mandatory or (mandatory == 0 and n == 0)):
|
||
j = _match_group(text, k, "[", "]")
|
||
n += mandatory == 0
|
||
continue
|
||
if k < len(text) and text[k] == "{" and n < mandatory:
|
||
j = _match_group(text, k, "{", "}")
|
||
n += 1
|
||
continue
|
||
break
|
||
return j
|
||
|
||
|
||
def mask_tex(text):
|
||
"""Return text of the same length with ignored material replaced by spaces (newlines kept)."""
|
||
chars = list(text)
|
||
for pat in PATTERNS[:1]:
|
||
for m in pat.finditer(text):
|
||
_blank(chars, m.start(), m.end())
|
||
text = "".join(chars)
|
||
for env in BLANK_ENVS:
|
||
for m in re.finditer(rf"\\begin\{{{re.escape(env)}\}}.*?\\end\{{{re.escape(env)}\}}", text, re.S):
|
||
_blank(chars, m.start(), m.end())
|
||
text = "".join(chars)
|
||
for m in re.finditer(r"\\begin\{([^}]+)\}", text):
|
||
env = m.group(1)
|
||
end = _skip_args(text, m.end(), ENV_ARGS.get(env, 0))
|
||
_blank(chars, m.start(), end)
|
||
for m in re.finditer(r"\\end\{[^}]+\}", text):
|
||
_blank(chars, m.start(), m.end())
|
||
text = "".join(chars)
|
||
for pat in PATTERNS[1:]: # lengths, dates, well names and versions, before control words are dropped
|
||
for m in pat.finditer(text):
|
||
_blank(chars, m.start(), m.end())
|
||
for m in re.finditer(r"\\([A-Za-z]+)", text):
|
||
name = m.group(1)
|
||
if name in BLANK_COMMANDS:
|
||
_blank(chars, m.start(), _skip_args(text, m.end(), BLANK_COMMANDS[name]))
|
||
elif chars[m.start()] == "\\": # other control words (\pm0.02, \times10): drop the name only
|
||
_blank(chars, m.start(), m.end())
|
||
return "".join(chars)
|
||
|
||
|
||
def _normalise(text):
|
||
"""Same-length rewrites: 1{,}376 and 23\\,447 become 1,376 / 23,447; \\_ becomes _ ; ~ becomes a space."""
|
||
text = re.sub(r"(\d)\{,\}(\d{3})", lambda m: m.group(1) + "," + m.group(2) + " ", text)
|
||
text = re.sub(r"(\d)\\,(\d{3})", lambda m: m.group(1) + "," + m.group(2) + " ", text)
|
||
text = re.sub(r"(\d)\{\.\}(\d)", lambda m: m.group(1) + "." + m.group(2) + " ", text)
|
||
return text.replace("\\_", "__").replace("~", " ")
|
||
|
||
|
||
TABLE = re.compile(r"\\begin\{(tabular\*?|tabularx|tabulary|longtable|tblr)\}(.*?)\\end\{\1\}", re.S)
|
||
|
||
|
||
def percent_columns(text):
|
||
"""Spans of table cells below a header cell that contains \\%, e.g. a 'CER (\\%)' column."""
|
||
spans = []
|
||
for t in TABLE.finditer(text):
|
||
cols, pos, body = set(), t.start(2), t.group(2)
|
||
for row in re.split(r"(\\\\)", body):
|
||
start, cells = pos, row.split("&")
|
||
pos += len(row)
|
||
if row == "\\\\" or not row.strip():
|
||
continue
|
||
if any("\\%" in c for c in cells):
|
||
cols = {i for i, c in enumerate(cells) if "\\%" in c}
|
||
continue
|
||
for i, c in enumerate(cells):
|
||
if i in cols:
|
||
spans.append((start, start + len(c)))
|
||
start += len(c) + 1
|
||
return spans
|
||
|
||
|
||
@dataclass
|
||
class Found:
|
||
file: str
|
||
line: int
|
||
token: str
|
||
value: float
|
||
decimals: int
|
||
percent: bool
|
||
context: str
|
||
status: str = ""
|
||
|
||
|
||
def extract_numbers(text, fname="<text>"):
|
||
masked = mask_tex(_normalise(text))
|
||
pct_cells = percent_columns(_normalise(text))
|
||
lines = text.split("\n")
|
||
starts = [0]
|
||
for ln in lines:
|
||
starts.append(starts[-1] + len(ln) + 1)
|
||
out = []
|
||
for m in NUMBER.finditer(masked):
|
||
raw = m.group(0)
|
||
int_part, frac = m.group(1), m.group(2) or ""
|
||
if "," in int_part and re.fullmatch(r"\d{1,3}(?:,\d{3})+", int_part) is None:
|
||
continue
|
||
# thousands written with spaces that _normalise turned into ', ' are not matched by NUMBER; fine
|
||
value = float(int_part.replace(",", "") + frac)
|
||
decimals = len(frac) - 1 if frac else 0
|
||
percent = bool(PERCENT_AFTER.match(masked, m.end())) or any(a <= m.start() < b for a, b in pct_cells)
|
||
line = bisect.bisect_right(starts, m.start()) - 1
|
||
src = lines[line]
|
||
col = m.start() - starts[line]
|
||
context = src[max(0, col - 50): col + len(raw) + 50].strip()
|
||
out.append(Found(fname, line + 1, raw, value, decimals, percent, context))
|
||
return out
|
||
|
||
|
||
# ---------------------------------------------------------------- allowlist and checking
|
||
|
||
|
||
def read_allowlist(path):
|
||
entries, problems = [], []
|
||
p = Path(path)
|
||
if not p.exists():
|
||
return entries, problems
|
||
for i, line in enumerate(p.read_text(encoding="utf-8").splitlines(), 1):
|
||
stripped = line.strip()
|
||
if not stripped or stripped.startswith("#"):
|
||
continue
|
||
num, _, reason = stripped.partition("#")
|
||
num, reason = num.strip(), reason.strip()
|
||
m = re.fullmatch(r"[-+−]?(\d+)(?:\.(\d+))?(\\?%)?", num.replace(",", ""))
|
||
if not m or not reason:
|
||
problems.append(f"{p.name}:{i}: expected 'number # reason', got {line!r}")
|
||
continue
|
||
entries.append((float(m.group(1) + ("." + m.group(2) if m.group(2) else "")), len(m.group(2) or "")))
|
||
return entries, problems
|
||
|
||
|
||
def classify(found, registry, allow):
|
||
if found.percent: # 15.1\% is the quantity 0.151 and nothing else
|
||
if registry.contains(found.value / 100, found.decimals + 2):
|
||
return "matched-percent"
|
||
elif registry.contains(found.value, found.decimals):
|
||
return "matched"
|
||
for value, decimals in allow:
|
||
if decimals == found.decimals and abs(value - found.value) < 0.5 * 10 ** -decimals - EPS:
|
||
return "allowlisted"
|
||
return "unmatched"
|
||
|
||
|
||
def check(tex_paths, registry, allow):
|
||
results = {}
|
||
for p in tex_paths:
|
||
p = Path(p)
|
||
items = extract_numbers(p.read_text(encoding="utf-8", errors="replace"), str(p))
|
||
for f in items:
|
||
f.status = classify(f, registry, allow)
|
||
results[str(p)] = items
|
||
return results
|
||
|
||
|
||
def report(results, registry, problems, summary, out=None):
|
||
out = out or sys.stdout
|
||
total = {"matched": 0, "matched-percent": 0, "allowlisted": 0, "unmatched": 0}
|
||
print(f"Registry: {len(registry.values)} distinct values from {len(registry.sources)} files.", file=out)
|
||
for miss in registry.missing:
|
||
print(f" warning: registry source not found: {miss}", file=out)
|
||
for prob in problems:
|
||
print(f" warning: allowlist entry ignored: {prob}", file=out)
|
||
if not results:
|
||
print("No .tex files found.", file=out)
|
||
for fname, items in results.items():
|
||
counts = {k: sum(f.status == k for f in items) for k in total}
|
||
for k in total:
|
||
total[k] += counts[k]
|
||
print(f"\n{fname}: {len(items)} numbers, {counts['matched'] + counts['matched-percent']} matched, "
|
||
f"{counts['allowlisted']} allowlisted, {counts['unmatched']} unmatched", file=out)
|
||
if summary:
|
||
continue
|
||
for f in items:
|
||
if f.status == "unmatched":
|
||
kind = " (percent)" if f.percent else ""
|
||
print(f" L{f.line}: {f.token}{kind} ... {f.context} ...", file=out)
|
||
print(f"\nTotal: {sum(total.values())} numbers, {total['matched'] + total['matched-percent']} matched, "
|
||
f"{total['allowlisted']} allowlisted, {total['unmatched']} unmatched", file=out)
|
||
return total["unmatched"]
|
||
|
||
|
||
def main(argv=None):
|
||
ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||
ap.add_argument("--root", type=Path, default=ROOT, help="repository root (registry sources are relative to it)")
|
||
ap.add_argument("--sections", type=Path, default=None, help="directory of .tex files (default paper/sections)")
|
||
ap.add_argument("--allowlist", type=Path, default=None, help="default paper/number_allowlist.txt")
|
||
ap.add_argument("--summary", action="store_true", help="counts per file only")
|
||
args = ap.parse_args(argv)
|
||
sections = args.sections or args.root / "paper/sections"
|
||
allowlist = args.allowlist or args.root / "paper/number_allowlist.txt"
|
||
registry = build_registry(args.root)
|
||
allow, problems = read_allowlist(allowlist)
|
||
tex = sorted(sections.glob("*.tex")) if sections.is_dir() else []
|
||
unmatched = report(check(tex, registry, allow), registry, problems, args.summary)
|
||
return 1 if unmatched else 0
|
||
|
||
|
||
if __name__ == "__main__":
|
||
sys.exit(main())
|