#!/usr/bin/env python3 """ Standalone Mathematical Verifier for Joy Creation #12 (Atelier XII): "The Peg Pagoda, Conway's Golden Soldiers & the Reversal Lattice" Runs 14 primary checks + 14 negative-mutation --self-test checks. """ import copy import json import sys from fractions import Fraction from itertools import product import os _HERE = os.path.dirname(os.path.abspath(__file__)) DATA_PATH = ( os.path.join(_HERE, "public", "data", "peg_pagoda_data.json") if os.path.exists(os.path.join(_HERE, "public", "data", "peg_pagoda_data.json")) else os.path.join(_HERE, "data", "peg_pagoda_data.json") ) def gf2_rank(holes, jumps): V = len(holes); M = len(jumps) mat = [[0]*M for _ in range(V)] for j, (a, b, c) in enumerate(jumps): mat[a][j] ^= 1; mat[b][j] ^= 1; mat[c][j] ^= 1 r = 0 for col in range(M): piv = next((row for row in range(r, V) if mat[row][col]), None) if piv is not None: mat[r], mat[piv] = mat[piv], mat[r] for row in range(V): if row != r and mat[row][col]: mat[row] = [mat[row][k] ^ mat[r][k] for k in range(M)] r += 1 return r def v4_elem(c0, c1, c2): p = (c0 & 1, c1 & 1, c2 & 1) if p in [(0,0,0), (1,1,1)]: return 0 if p in [(1,0,0), (0,1,1)]: return 1 if p in [(0,1,0), (1,0,1)]: return 2 if p in [(0,0,1), (1,1,0)]: return 3 raise ValueError(p) def state_v4(holes, inds): cp = [0, 0, 0]; cm = [0, 0, 0] for i in inds: x, y = holes[i] cp[(x + y) % 3] += 1 cm[(x - y) % 3] += 1 return [v4_elem(*cp), v4_elem(*cm)] def zsig_pow(k): if k >= 0: cur = (1, 0) for _ in range(k): cur = (cur[1], cur[0] - cur[1]) return cur cur = (1, 0) for _ in range(-k): cur = (cur[0] + cur[1], cur[0]) return cur def verify_all(data): s1 = data["studio1"] s2 = data["studio2"] s3 = data["studio3"] s4 = data["studio4"] h33, j33 = s1["holes33"], s1["jumps33"] h37, j37 = s1["holes37"], s1["jumps37"] idx33 = {tuple(p): i for i, p in enumerate(h33)} idx37 = {tuple(p): i for i, p in enumerate(h37)} # 1. Exact GF(2) Corank 4 on English 33 & French 37 if len(h33) != 33 or len(j33) != 76 or gf2_rank(h33, j33) != 29: raise AssertionError("Check 1 failed: English 33 GF(2) corank != 4") if len(h37) != 37 or len(j37) != 92 or gf2_rank(h37, j37) != 33: raise AssertionError("Check 1 failed: French 37 GF(2) corank != 4") # 2. 9-in-16 Ghost Grid & 21 Dead French Holes vs 33/33 Self-Complementary English Holes if state_v4(h33, range(33)) != [0, 0] or state_v4(h37, range(37)) != [1, 1]: raise AssertionError("Check 2 failed: Full_33 / Full_37 V4 invariant mismatch") for a in range(4): for b in range(4): eng_cell = s1["grid_eng_single"][a][b] eur_cell = s1["grid_eur_single"][a][b] if (a == 0 or b == 0) and (len(eng_cell) != 0 or len(eur_cell) != 0): raise AssertionError("Check 2 failed: Ghost class inhabited by single hole") if a > 0 and b > 0 and (len(eng_cell) == 0 or len(eur_cell) == 0): raise AssertionError("Check 2 failed: Non-zero V4xV4 cell empty") if len(s1["dead_eur_holes"]) != 21 or len(s1["live_eur_holes"]) != 16: raise AssertionError("Check 2 failed: French dead/live hole split != 21/16") # 3. All 21 English Orbits (125 pairs) & All 10 French Orbits (64 pairs) Legal Replay if len(s1["eng33_orbits"]) != 21 or sum(o["multiplicity"] for o in s1["eng33_orbits"]) != 125: raise AssertionError("Check 3 failed: English orbit count/sum != 21 / 125") for orb in s1["eng33_orbits"]: u, v = idx33[tuple(orb["u"])], idx33[tuple(orb["v"])] occ = set(range(33)) - {u} if len(orb["moves"]) != 31: raise AssertionError("Check 3 failed: English move length != 31") for a, b, c in orb["moves"]: if [a, b, c] not in j33 or a not in occ or b not in occ or c in occ: raise AssertionError(f"Check 3 failed: Illegal jump in ENG orbit {orb['orbit']}") occ.remove(a); occ.remove(b); occ.add(c) if occ != {v}: raise AssertionError("Check 3 failed: Wrong final peg in ENG orbit") if len(s1["eur37_orbits"]) != 10 or sum(o["multiplicity"] for o in s1["eur37_orbits"]) != 64: raise AssertionError("Check 4 failed: French orbit count/sum != 10 / 64") for orb in s1["eur37_orbits"]: u, v = idx37[tuple(orb["u"])], idx37[tuple(orb["v"])] occ = set(range(37)) - {u} if len(orb["moves"]) != 35: raise AssertionError("Check 4 failed: French move length != 35") for a, b, c in orb["moves"]: if [a, b, c] not in j37 or a not in occ or b not in occ or c in occ: raise AssertionError(f"Check 4 failed: Illegal jump in EUR orbit {orb['orbit']}") occ.remove(a); occ.remove(b); occ.add(c) if occ != {v}: raise AssertionError("Check 4 failed: Wrong final peg in EUR orbit") # 5. Bergholt 18-Sweep (31-Jump) World Record & Leibniz Complementation Reversal sws = s1["bergholt_18_sweeps"] if len(sws) != 18: raise AssertionError("Check 5 failed: Bergholt sweep count != 18") occ = set(range(33)) - {16} jcnt = 0 rev_jumps = [] for sw in sws: if len(sw) < 2: raise AssertionError("Check 5 failed: Empty sweep") for k in range(len(sw) - 1): a, c = sw[k], sw[k+1] ax, ay = h33[a]; cx, cy = h33[c] b = idx33.get(((ax + cx)//2, (ay + cy)//2), -1) if [a, b, c] not in j33 or a not in occ or b not in occ or c in occ: raise AssertionError("Check 5 failed: Illegal Bergholt sweep jump") occ.remove(a); occ.remove(b); occ.add(c) rev_jumps.append([c, b, a]) jcnt += 1 if jcnt != 31 or occ != {16}: raise AssertionError("Check 5 failed: Bergholt end state != {16}") # Leibniz complementation check: starting from complement of {16} (= Full \ {16}), reversed jumps [c,b,a]? # Wait: complement of step t -> t+1 (`a,b -> c` on S) corresponds to `c,b -> a`? Wait: # In S: a=1,b=1,c=0 -> a=0,b=0,c=1. # In V\S (going BACKWARD from V\S_{t+1} to V\S_t): in V\S_{t+1}, a=1,b=1,c=0 -> in V\S_t, a=0,b=0,c=1 — THE EXACT SAME JUMP `[a, b, c]` IN REVERSE ORDER!! occ_dual = set(range(33)) - {16} for a, b, c in reversed(s1["bergholt_31_jumps"]): if a not in occ_dual or b not in occ_dual or c in occ_dual: raise AssertionError("Check 5 failed: Leibniz complementation reversal failed") occ_dual.remove(a); occ_dual.remove(b); occ_dual.add(c) if occ_dual != {16}: raise AssertionError("Check 5 failed: Leibniz dual end != {16}") # 6. Fool's 6-Jump Deadlock (26 Stranded Pegs, 0 Legal Jumps) fools = s1["fools_6_jumps"] if len(fools) != 6: raise AssertionError("Check 6 failed: Fool's jump count != 6") occ_f = set(range(33)) - {16} for a, b, c in fools: if [a, b, c] not in j33 or a not in occ_f or b not in occ_f or c in occ_f: raise AssertionError("Check 6 failed: Illegal Fool's jump") occ_f.remove(a); occ_f.remove(b); occ_f.add(c) if len(occ_f) != 26 or any((a in occ_f and b in occ_f and c not in occ_f) for a, b, c in j33): raise AssertionError("Check 6 failed: Fool's state not a 26-peg deadlock") # 7. Exact 660 D4-Symmetric {-1,0,1,2} Pagodas & Pagoda Inequality p_c <= p_a + p_b across all 76 jumps d4_orbs = sorted({tuple(sorted((abs(x), abs(y)))) for x, y in h33}) cnt660 = 0 for vals in product([-1, 0, 1, 2], repeat=7): if max(vals) <= 0: continue wm = dict(zip(d4_orbs, vals)) p = [wm[tuple(sorted((abs(x), abs(y))))] for x, y in h33] if all(p[c] <= p[a] + p[b] for a, b, c in j33): cnt660 += 1 if cnt660 != s2["d4_pagoda_census_count"] or cnt660 != 660: raise AssertionError("Check 7 failed: D4 Pagoda count != 660") for pk, pinfo in s2["pagodas"].items(): w = pinfo["weights"] if len(w) != 33 or sum(w) != pinfo["full_sum"] or w[16] != pinfo["center_val"]: raise AssertionError(f"Check 7 failed: Pagoda metadata mismatch on {pk}") if not all(w[c] <= w[a] + w[b] for a, b, c in j33): raise AssertionError(f"Check 7 failed: Pagoda inequality violated on {pk}") # 8. Four Complementary GF(2)-Valid Pagoda Mirages if len(s2["mirages"]) != 4: raise AssertionError("Check 8 failed: Expected 4 mirages") seen_patterns = set() for m in s2["mirages"]: inds = m["indices"] if len(inds) != m["pegs"] or len(set(inds)) != m["pegs"]: raise AssertionError("Check 8 failed: Duplicate/mismatched mirage pegs") if state_v4(h33, inds) != [1, 1]: raise AssertionError("Check 8 failed: Mirage does not match {(0,0)} in V4xV4") leg = sum(1 for a, b, c in j33 if a in inds and b in inds and c not in inds) if leg != m["legal_openings"] or leg < 2: raise AssertionError("Check 8 failed: Mirage legal openings mismatch") kills = [] for pk in ["corner_bell", "quincunx", "axial_beasley"]: w = s2["pagodas"][pk]["weights"] sc = sum(w[i] for i in inds) if sc != m["pagoda_scores"][pk]["init"] or (sc < w[16]) != m["pagoda_scores"][pk]["kills"]: raise AssertionError("Check 8 failed: Mirage pagoda score mismatch") kills.append(sc < w[16]) if not any(kills): raise AssertionError("Check 8 failed: Mirage not killed by any pagoda") seen_patterns.add(tuple(kills)) if len(seen_patterns) != 4: raise AssertionError("Check 8 failed: 4 mirages do not exhibit 4 distinct kill signatures") # 9. Conway Golden Soldiers Exact Z[sigma] 19-Cell Weight == 1 & Zero-Loss Jam trap19 = s3["trap19_h4"] if len(trap19) != 19 or len({tuple(p) for p in trap19}) != 19 or not all(y <= 0 for x, y in trap19): raise AssertionError("Check 9 failed: Invalid trap19_h4") zw = (0, 0) for x, y in trap19: pk = zsig_pow(4 - y + abs(x)) zw = (zw[0] + pk[0], zw[1] + pk[1]) if zw != (1, 0): raise AssertionError(f"Check 9 failed: trap19 Z[sigma] weight {zw} != (1, 0)") # 10. Orthogonal Golden Troops h = 0..4 (1, 2, 4, 8, 20 Soldiers -> {(0, h)}) expected_sz = {"0": 1, "1": 2, "2": 4, "3": 8, "4": 20} for hk, sz in expected_sz.items(): tr = s3["orthogonal_troops"][hk] h = int(hk) occ = {tuple(p) for p in tr["soldiers"]} if len(occ) != sz or not all(y <= 0 for x, y in occ) or len(tr["moves"]) != sz - 1: raise AssertionError(f"Check 10 failed: Soldier size/line mismatch at h={h}") for a, b, c in tr["moves"]: a, b, c = tuple(a), tuple(b), tuple(c) dx, dy = b[0] - a[0], b[1] - a[1] if (b[0]+dx, b[1]+dy) != c or abs(dx) + abs(dy) != 1: raise AssertionError(f"Check 10 failed: Non-orthogonal jump at h={h}") if a not in occ or b not in occ or c in occ: raise AssertionError(f"Check 10 failed: Illegal jump at h={h}") occ.remove(a); occ.remove(b); occ.add(c) if occ != {(0, h)}: raise AssertionError(f"Check 10 failed: Final state != {{(0,{h})}}") # 11. 8-Direction King Soldiers Breaking y = 5 (15 Soldiers -> {(0, 5)}) + Chebyshev Wall at y = 9 k5 = s3["king_h5"] occk = {tuple(p) for p in k5["soldiers"]} if len(occk) != 15 or not all(y <= 0 for x, y in occk) or len(k5["moves"]) != 14: raise AssertionError("Check 11 failed: King h=5 troop size != 15") for a, b, c in k5["moves"]: a, b, c = tuple(a), tuple(b), tuple(c) dx, dy = b[0] - a[0], b[1] - a[1] if (b[0]+dx, b[1]+dy) != c or max(abs(dx), abs(dy)) != 1: raise AssertionError("Check 11 failed: Invalid King jump geometry") if a not in occk or b not in occk or c in occk: raise AssertionError("Check 11 failed: Illegal King jump") occk.remove(a); occk.remove(b); occk.add(c) if occk != {(0, 5)}: raise AssertionError("Check 11 failed: King troop did not reach {(0,5)}") # Verify Chebyshev half-plane weight formula (2h + 4*phi + 1)*sigma^{h-2}: > 1 at h=8, < 1 at h=9! sig_f = (5**0.5 - 1) / 2 phi_f = (5**0.5 + 1) / 2 w8 = (16 + 4*phi_f + 1) * (sig_f**6) w9 = (18 + 4*phi_f + 1) * (sig_f**7) grid9 = sum(sig_f**max(abs(x), 9 - y) for y in range(0, -55, -1) for x in range(-85, 86)) if not (w8 > 1.308 and w9 < 0.878 and abs(w9 - grid9) < 1e-8): raise AssertionError("Check 11 failed: Chebyshev half-plane wall mismatch") # 12. Triangular Solitaire T3..T6 Solvability Counts (0, 6, 54, 147) & Replay of ALL 207 Witnesses exp_tri = {"T3": (6, 6, 0), "T4": (10, 18, 6), "T5": (15, 36, 54), "T6": (21, 60, 147)} for tk, (v_exp, j_exp, s_exp) in exp_tri.items(): tb = s4["boards"][tk] if tb["V"] != v_exp or tb["njumps"] != j_exp or tb["solvable_count"] != s_exp or len(tb["witnesses"]) != s_exp: raise AssertionError(f"Check 12 failed: Metadata mismatch on {tk}") jset = {tuple(jp) for jp in tb["jumps"]} for pair_k, seq in tb["witnesses"].items(): u_s, v_s = pair_k.split("->") u, v = int(u_s), int(v_s) occ = set(range(v_exp)) - {u} if len(seq) != v_exp - 2: raise AssertionError(f"Check 12 failed: Witness length mismatch on {tk} {pair_k}") for a, b, c in seq: if (a, b, c) not in jset or a not in occ or b not in occ or c in occ: raise AssertionError(f"Check 12 failed: Illegal witness jump on {tk} {pair_k}") occ.remove(a); occ.remove(b); occ.add(c) if occ != {v}: raise AssertionError(f"Check 12 failed: Wrong end peg on {tk} {pair_k}") # 13. Five-Tier Obstruction Certificates (T3 Pagoda, T4 Half-Integral LP, T4 & T5 Integer Flows) if len(s4["obstruction_exhibits"]) != 5: raise AssertionError("Check 13 failed: Expected 5 obstruction exhibits") for ex in s4["obstruction_exhibits"]: tb = s4["boards"][ex["board"]] idx_t = {tuple(p): i for i, p in enumerate(tb["holes"])} u, v = idx_t[tuple(ex["u"])], idx_t[tuple(ex["v"])] if f"{u}->{v}" in tb["witnesses"]: raise AssertionError(f"Check 13 failed: Obstruction {ex['id']} is actually solvable!") if ex["certificate_type"] == "pagoda": pw = ex["pagoda_weights"] if not all(pw[c] <= pw[a] + pw[b] for a, b, c in tb["jumps"]): raise AssertionError("Check 13 failed: Invalid T3 pagoda") if sum(pw[i] for i in range(tb["V"]) if i != u) >= pw[v]: raise AssertionError("Check 13 failed: T3 pagoda does not separate init from goal") else: bal = [Fraction(0)] * tb["V"] jset = {tuple(jp) for jp in tb["jumps"]} has_frac = False for jp, val_s in ex["flow"]: if tuple(jp) not in jset: raise AssertionError("Check 13 failed: Invalid jump in flow certificate") fv = Fraction(val_s) if fv <= 0: raise AssertionError("Check 13 failed: Non-positive flow entry") if fv.denominator != 1: has_frac = True a, b, c = jp bal[a] += fv; bal[b] += fv; bal[c] -= fv rhs = [Fraction((1 if i != u else 0) - (1 if i == v else 0)) for i in range(tb["V"])] if bal != rhs: raise AssertionError(f"Check 13 failed: Flow does not balance A x = b on {ex['id']}") if ex["certificate_type"] == "integer_flow_temporal" and has_frac: raise AssertionError(f"Check 13 failed: Expected integer flow on {ex['id']}") if ex["certificate_type"] == "fractional_flow" and not has_frac: raise AssertionError(f"Check 13 failed: Expected fractional flow on {ex['id']}") # 14. Cracker-Barrel T5 Sweep-Minimum Orbit Spectrum {9, 10, 11} tb5 = s4["boards"]["T5"] idx5 = {tuple(p): i for i, p in enumerate(tb5["holes"])} jset5 = {tuple(jp) for jp in tb5["jumps"]} exp_sw = {"mid_edge_9": 9, "apex_10": 10, "interior_11": 11} for rk, sw_exp in exp_sw.items(): rec = s4["t5_sweep_records"][rk] u, v = idx5[tuple(rec["u"])], idx5[tuple(rec["v"])] occ = set(range(15)) - {u} sweeps = 0; last_c = -1 for a, b, c in rec["jumps"]: if (a, b, c) not in jset5 or a not in occ or b not in occ or c in occ: raise AssertionError(f"Check 14 failed: Illegal jump in T5 sweep record {rk}") if a != last_c: sweeps += 1 last_c = c occ.remove(a); occ.remove(b); occ.add(c) if occ != {v} or sweeps != sw_exp or rec["sweeps"] != sw_exp: raise AssertionError(f"Check 14 failed: Sweep count mismatch on {rk}") def run_self_tests(base_data): mutations = [ ("M1_corank_jump_drop", lambda d: d["studio1"]["jumps33"].pop()), ("M2_ghost_grid_leak", lambda d: d["studio1"]["grid_eng_single"][0][1].append([0, 0])), ("M3_eng_orbit_tamper", lambda d: d["studio1"]["eng33_orbits"][0]["moves"][0].__setitem__(2, 0)), ("M4_eur_orbit_tamper", lambda d: d["studio1"]["eur37_orbits"][-1]["moves"][-1].__setitem__(0, 0)), ("M5_bergholt_tamper", lambda d: d["studio1"]["bergholt_18_sweeps"][0].__setitem__(1, 0)), ("M6_fools_non_dead", lambda d: d["studio1"]["fools_6_jumps"].pop()), ("M7_pagoda_violation", lambda d: d["studio2"]["pagodas"]["corner_bell"]["weights"].__setitem__(16, 9)), ("M8_mirage_score_lie", lambda d: d["studio2"]["mirages"][1]["pagoda_scores"]["quincunx"].__setitem__("init", 3)), ("M9_trap19_weight", lambda d: d["studio3"]["trap19_h4"].__setitem__(0, [-4, -4])), ("M10_orth4_jump_lie", lambda d: d["studio3"]["orthogonal_troops"]["4"]["moves"][5].__setitem__(2, [0, 4])), ("M11_king5_tamper", lambda d: d["studio3"]["king_h5"]["moves"][-1].__setitem__(2, [0, 4])), ("M12_tri_witness_lie", lambda d: d["studio4"]["boards"]["T5"]["witnesses"]["0->0"][0].__setitem__(2, 14)), ("M13_flow_unbalanced", lambda d: d["studio4"]["obstruction_exhibits"][3]["flow"][0].__setitem__(1, "3")), ("M14_t5_sweep_lie", lambda d: d["studio4"]["t5_sweep_records"]["mid_edge_9"].__setitem__("sweeps", 8)), ] passed = 0 for name, fn in mutations: mut = copy.deepcopy(base_data) fn(mut) caught = False try: verify_all(mut) except AssertionError: caught = True if not caught: raise RuntimeError(f"SELF-TEST FAILURE: Mutation {name} was NOT caught!") passed += 1 print(f" [SELF-TEST PASS {passed:2d}/14] Caught negative mutation: {name}") print(f"ALL {passed}/14 NEGATIVE-MUTATION SELF-TESTS PASSED!") def main(): with open(DATA_PATH) as f: data = json.load(f) verify_all(data) print("ALL 14/14 PRIMARY MATHEMATICAL VERIFICATION CHECKS PASSED!") if "--self-test" in sys.argv: run_self_tests(data) if __name__ == "__main__": main()