#!/usr/bin/env python3 """Independent reader of the explicit data in the SweepAcycloid Lean library. Draft 3 companion to recompute.py. This script shares no code with recompute.py and imports nothing from the paper folder: it reads the .lean sources as text, extracts every piece of explicit data they serialize, and re-checks that data with its own enumeration code. 1. Tamura's C_0 (Defs.lean `tamuraC0Circuit`, `reorientAt2`): the definition body and its docstring list the same five circuits; the topes of C_0 reoriented at element 3 are exactly the star restriction of T_W(6,3) (Proposition 21). 2. The da Silva block function (Defs.lean `daSilvaBlock`): the ordered partition ({1}, {3..n}, {2}) is a potential sweep and not a sweep of W(n, m) for every 6 <= n <= 8, 3 <= m <= n/2 (Theorem 18). 3. The two-element system `parallelOM2` (Defs.lean): it satisfies the covector axioms (V0)-(V3), its topes have full support, the second element is not a loop, no Y has both extensions as topes, and the zero vector is a tope of the contraction (Lemma 15(c)). 4. The closed sanity equalities of Examples.lean and the InWindow sanity witnesses of Sanity.lean, evaluated from their printed arguments. 5. Verify.lean against axioms.out: the same declaration set, standard axioms only, no sorryAx, every claim declaration of trust-boundary.json present, and a `_nonvacuous` witness for each claim in Sanity.lean. Run: python3 certificate.py > certificate.out (exit 0 iff every check holds) """ # Standard Library import hashlib from itertools import permutations, product import json from pathlib import Path import re import sys HERE = Path(__file__).resolve().parent LEAN = HERE / 'lean' / 'SweepAcycloid' STANDARD = {'propext', 'Classical.choice', 'Quot.sound'} SIGN = {'Sign.neg': -1, 'Sign.zero': 0, 'Sign.pos': 1} CHAR = {'+': 1, '-': -1, '0': 0} def source(name): return (LEAN / name).read_text(encoding='utf-8') def definition(text, name): """The body of `def ... :=` up to the next blank line.""" hit = re.search(rf'^def {re.escape(name)}\b[^\n]*:=\n(.*?)(?:\n\n|\Z)', text, re.M | re.S) if hit is None: raise SystemExit(f'certificate: def {name} not found') return ' '.join(hit.group(1).split()) # 1. Tamura's C_0 ------------------------------------------------------------ def tamura_table(defs): body = definition(defs, 'tamuraC0Circuit') hit = re.fullmatch(r'if i = c then (Sign\.\w+) else if i\.val = (\d+) ' r'then (Sign\.\w+) else (Sign\.\w+)', body) if hit is None: raise SystemExit(f'certificate: unexpected tamuraC0Circuit body {body!r}') on_diag, k, special, other = hit.groups() k = int(k) return [tuple(SIGN[on_diag] if i == c else SIGN[special] if i == k else SIGN[other] for i in range(5)) for c in range(5)] def tamura_docstring(defs): hit = re.search(r'Prop\. 7\.7, p\. 262\):\n`([^`]+)`, `([^`]+)`, `([^`]+)`, ' r'`([^`]+)`, `([^`]+)`\. -/\ndef tamuraC0Circuit', defs) if hit is None: raise SystemExit('certificate: tamuraC0Circuit docstring not found') return [tuple(CHAR[ch] for ch in word) for word in hit.groups()] def reorient_coord(defs): body = definition(defs, 'reorientAt2') hit = re.fullmatch(r'if i\.val = (\d+) then \(v i\)\.negate else v i', body) if hit is None: raise SystemExit(f'certificate: unexpected reorientAt2 body {body!r}') return int(hit.group(1)) def conforms(x, y): return all(a == 0 or a == b for a, b in zip(x, y)) def tamura_topes(circuits): signed = circuits + [tuple(-a for a in c) for c in circuits] return {v for v in product((1, -1), repeat=5) if not any(conforms(c, v) for c in signed)} def star_restriction(n, m): """Star vectors (sign of (i, n) for i < n) of the words of W(n, m), by direct enumeration of permutations (0-based letters, x = n - 1).""" out = set() for p in permutations(range(n)): t = p.index(n - 1) if m - 1 <= t <= n - m: out.add(tuple(1 if p.index(i) < t else -1 for i in range(n - 1))) return out def check_tamura(defs): table = tamura_table(defs) assert table == tamura_docstring(defs), 'definition and docstring differ' k = reorient_coord(defs) c0 = tamura_topes(table) flipped = {tuple(-a if i == k else a for i, a in enumerate(v)) for v in c0} band = star_restriction(6, 3) assert flipped == band, 'reoriented C_0 differs from the W(6,3) star band' assert c0 != band, 'C_0 equals the band without reorientation' assert {sum(a > 0 for a in v) for v in band} == {2, 3} return (f'tamura: 5 circuits from the definition equal the docstring list; ' f'{len(c0)} topes, reoriented at element {k + 1} = star restriction ' f'of T_W(6,3) ({len(band)} vectors)') # 2. da Silva ------------------------------------------------------------------ def dasilva_block(defs): body = definition(defs, 'daSilvaBlock') hit = re.fullmatch(r'if i\.val = (\d+) then (\d+) else if i\.val = (\d+) ' r'then (\d+) else (\d+)', body) if hit is None: raise SystemExit(f'certificate: unexpected daSilvaBlock body {body!r}') a, ba, b, bb, rest = map(int, hit.groups()) return lambda i: ba if i == a else bb if i == b else rest def compose(block, word): """I o word: letters sorted by block, ties broken by position in word.""" pos = {v: t for t, v in enumerate(word)} return tuple(sorted(word, key=lambda v: (block(v), pos[v]))) def refines(block, word): return all(block(word[s]) <= block(word[t]) for s in range(len(word)) for t in range(s + 1, len(word))) def check_dasilva(defs): block = dasilva_block(defs) rows = [] for n, m in ((6, 3), (7, 3), (8, 3), (8, 4)): assert 2 * m <= n words = {p for p in permutations(range(n)) if m - 1 <= p.index(n - 1) <= n - m} refined = [w for w in words if refines(block, w)] potential = bool(refined) and all(compose(block, w[::-1]) in words for w in refined) sweep = all(compose(block, w) in words for w in words) assert potential and not sweep, (n, m) rows.append(f'({n},{m})') blocks = [block(i) for i in range(6)] return ('dasilva: block ranks from the definition (n = 6, 0-based) ' f'{blocks}; potential sweep and not a sweep at ' + ', '.join(rows)) # 3. Lemma 15(c) --------------------------------------------------------------- def parallel_om2(defs): body = definition(defs, 'parallelOM2') pairs = re.findall(r'X ⟨0, [^⟩]*⟩ = (Sign\.\w+) ∧ X ⟨1, [^⟩]*⟩ = (Sign\.\w+)', body) if len(pairs) != 3: raise SystemExit(f'certificate: unexpected parallelOM2 body {body!r}') return {(SIGN[a], SIGN[b]) for a, b in pairs} def comp(x, y): return tuple(a if a != 0 else b for a, b in zip(x, y)) def is_om(system): zero = tuple(0 for _ in next(iter(system))) if zero not in system or any(tuple(-a for a in x) not in system for x in system): return False if any(comp(x, y) not in system for x in system for y in system): return False for x in system: for y in system: for e in range(len(x)): if x[e] != 0 and x[e] == -y[e]: xy = comp(x, y) if not any(z[e] == 0 and all( z[f] == xy[f] for f in range(len(x)) if x[f] != -y[f] or x[f] == y[f] == 0) for z in system): return False return True def topes(system): def below(x, y): return all(a == 0 or a == b for a, b in zip(x, y)) return {x for x in system if not any(y != x and below(x, y) for y in system)} def check_parallel(defs): system = parallel_om2(defs) assert system == {(0, 0), (1, 1), (-1, -1)} assert is_om(system) tp = topes(system) assert all(0 not in t for t in tp) assert any(x[1] != 0 for x in system), 'second element is a loop' both = {(y,) for (y,) in {(t[0],) for t in tp} if (y, 1) in tp and (y, -1) in tp} assert not both contraction = {x[:1] for x in system if x[1] == 0} assert is_om(contraction) and topes(contraction) == {(0,)} return ('parallelOM2: {00, ++, --} satisfies (V0)-(V3); contracting the ' 'second element leaves {0}, whose only tope is the zero vector') # 4. Closed sanity equalities ------------------------------------------------------ def check_examples(examples, sanity, defs): """Evaluate each closed statement from its printed arguments.""" checks = { r'theorem example_fact_5 :\s*fact (\d+) = (\d+)': lambda a, b: b == __import__('math').factorial(a), r'theorem example_daSilvaBlock_1 :\s*daSilvaBlock \(⟨(\d+), by decide⟩ ' r': Fin (\d+)\) = (\d+)': lambda i, n, v: dasilva_block(defs)(i) == v and i < n, r'theorem example_tamuraC0Circuit_0_2 :\s*tamuraC0Circuit ⟨(\d+), by ' r'decide⟩ ⟨(\d+), by decide⟩ = (Sign\.\w+)': lambda c, i, s: tamura_table(defs)[c][i] == SIGN[s], r'theorem example_reorientAt2_pos :\s*reorientAt2 \(fun _ => Sign\.pos\) ' r'⟨(\d+), by decide⟩ = (Sign\.\w+)': lambda i, s: (-1 if i == reorient_coord(defs) else 1) == SIGN[s], r'theorem example_invDist_rev3 :\s*invDist \(Perm\.id (\d+)\) ' r'\(revPerm \(Perm\.id (\d+)\)\) = (\d+)': lambda n, n2, d: n == n2 and d == n * (n - 1) // 2, r'theorem example_invDist_id3 :\s*invDist \(Perm\.id (\d+)\) ' r'\(Perm\.id (\d+)\) = (\d+)': lambda n, n2, d: n == n2 and d == 0, } for pattern, test in checks.items(): hit = re.search(pattern, examples) if hit is None: raise SystemExit(f'certificate: example not found: {pattern[:40]}') args = [g if g.startswith('Sign') else int(g) for g in hit.groups()] assert test(*args), pattern[:40] # InWindow 6 3 on a transposition of the identity and on the identity. pos = re.search(r'theorem sanity_inWindow_pos : InWindow (\d+) (\d+) ' r'\(Perm\.swap ⟨(\d+), by decide⟩ ⟨(\d+), by decide⟩\)', sanity) neg = re.search(r'theorem sanity_inWindow_neg : ¬ InWindow (\d+) (\d+) ' r'\(Perm\.id (\d+)\)', sanity) if pos is None or neg is None: raise SystemExit('certificate: InWindow sanity witnesses not found') def in_window(n, m, word): t = word.index(n - 1) + 1 return m <= t and t - 1 + m <= n n, m, a, b = map(int, pos.groups()) word = list(range(n)) word[a], word[b] = word[b], word[a] assert in_window(n, m, word) n, m, n2 = map(int, neg.groups()) assert n == n2 and not in_window(n, m, list(range(n))) return (f'examples: {len(checks)} closed equalities of Examples.lean and ' 'the 2 InWindow witnesses of Sanity.lean re-evaluated') # 5. Verify.lean, axioms.out, claims ------------------------------------------------ def axiom_records(text): records = [] for line in text.splitlines(): if not line.strip(): continue if line.startswith("'") or not records: records.append(line) else: records[-1] += ' ' + line.strip() out = {} for rec in records: name = re.match(r"^'([^']+)'", rec).group(1) used = re.search(r'\[(.*)\]', rec) out[name] = ({a.strip() for a in used.group(1).split(',')} if used else set()) return out def check_receipt(): verify = re.findall(r'^#print axioms (\S+)', source('Verify.lean'), re.M) axioms = axiom_records(source('axioms.out')) assert len(verify) == len(set(verify)) == len(axioms) assert set(verify) == set(axioms) bad = {n: a for n, a in axioms.items() if not a <= STANDARD} assert not bad, bad assert 'sorryAx' not in source('axioms.out') manifest = json.loads((HERE / 'trust-boundary.json').read_text(encoding='utf-8')) decls = [c['lean_decl'] for c in manifest['claims']] assert all(d in axioms for d in decls), [d for d in decls if d not in axioms] sanity = source('Sanity.lean') witnessed = [d for d in decls if re.search( rf'^theorem {re.escape(d.split(".")[-1])}_nonvacuous\b', sanity, re.M)] assert len(witnessed) == len(decls) return (f'receipt: {len(verify)} declarations in Verify.lean = axioms.out, ' f'standard axioms only; {len(decls)} claim declarations present, ' f'each with a _nonvacuous witness') def main(): defs = source('Defs.lean') lines = [check_tamura(defs), check_dasilva(defs), check_parallel(defs), check_examples(source('Examples.lean'), source('Sanity.lean'), defs), check_receipt()] for name in ('Defs.lean', 'Examples.lean', 'Sanity.lean', 'Verify.lean', 'axioms.out'): digest = hashlib.sha256((LEAN / name).read_bytes()).hexdigest() lines.append(f'sha256 {name} {digest}') print('\n'.join(lines)) print('certificate: every check holds') return 0 if __name__ == '__main__': sys.exit(main())