#!/usr/bin/env python3 """ verify_poncelet.py — Standalone First-Principles Verifier & 14-Point Negative-Mutation Self-Test for Atelier XI: "The Billiard Table, the Sliding Ladder & Poncelet's Ring" """ import copy import json import math import sys from fractions import Fraction from pathlib import Path DATA_PATH = Path(__file__).parent / "public" / "data" / "poncelet_data.json" if not DATA_PATH.exists(): DATA_PATH = Path(__file__).parent / "data" / "poncelet_data.json" def poncelet_step(theta, d, r): vx = d - math.cos(theta) vy = -math.sin(theta) L = math.hypot(vx, vy) if L <= r or r <= 0: raise AssertionError(f"Invalid Poncelet geometry L={L}, r={r}") phi = math.atan2(vy, vx) alpha = math.asin(r / L) ray_ang = phi - alpha ux, uy = math.cos(ray_ang), math.sin(ray_ang) s = -2.0 * (math.cos(theta) * ux + math.sin(theta) * uy) nx = math.cos(theta) + s * ux ny = math.sin(theta) + s * uy nt = math.atan2(ny, nx) diff = (nt - theta) % (2.0 * math.pi) return theta + diff def verify_all(data): s1 = data["studio1"] s2 = data["studio2"] s3 = data["studio3"] s4 = data["studio4"] # 1. Coprime p x q 45-degree rectangular billiard bounce & parity law rects = s1["rectangles"] assert len(rects) >= 6, "Expected >= 6 rectangle presets" for rec in rects: p, q = rec["p"], rec["q"] assert math.gcd(p, q) == 1, f"({p},{q}) not coprime" assert rec["lcm_length"] == p * q, "lcm mismatch" assert rec["bounces"] == p + q - 2, "bounces != p + q - 2" assert rec["crossings"] == (p - 1) * (q - 1) // 2, "crossings != (p-1)(q-1)/2" ex = p if (q % 2 == 1) else 0 ey = q if (p % 2 == 1) else 0 assert rec["exit_corner"] == [ex, ey], f"exit corner mismatch: {rec['exit_corner']} vs {[ex, ey]}" verts = rec["vertices"] assert len(verts) == rec["bounces"] + 2, "vertex count != bounces + 2" assert verts[0][:2] == [0, 0] and verts[-1][:2] == [ex, ey], "endpoint mismatch" for i in range(len(verts) - 1): dx = abs(verts[i+1][0] - verts[i][0]) dy = abs(verts[i+1][1] - verts[i][1]) dt = verts[i+1][2] - verts[i][2] assert dx == dy == dt and dt > 0, "non-45-degree segment" # 2. Bézout Jug Billiard Cycle Length 2*(A/g + B/g) - 1 & Action Decomposition jugs = s1["jugs"] assert len(jugs) >= 6, "Expected >= 6 jug presets" for j in jugs: A, B = j["A"], j["B"] g = math.gcd(A, B) assert j["gcd"] == g, "gcd mismatch" Ab, Bb = A // g, B // g exp_cyc = 2 * (Ab + Bb) - 1 assert j["cycle_len"] == exp_cyc, f"cycle_len {j['cycle_len']} != {exp_cyc}" assert j["fills"] == Bb and j["empties"] == Ab and j["pours"] == Ab + Bb - 1, "action split mismatch" # 3. Time-Reversal Duality between Policy A-first and Policy B-first for j in jugs: pA = [[u[0], u[1]] for u in j["path_A"]] pB = [[u[0], u[1]] for u in j["path_B"]] assert len(pA) == j["cycle_len"] + 1, "path_A len mismatch" assert pA == list(reversed(pB)), "path_A is not exact reverse of path_B" # Check legal transitions along path_A A, B = j["A"], j["B"] for i in range(len(pA) - 1): x0, y0 = pA[i] x1, y1 = pA[i+1] is_fill = (x0 == 0 and x1 == A and y1 == y0) is_empty = ((y0 == B or i == len(pA) - 2) and y1 == 0 and x1 == x0) is_pour = (x0 + y0 == x1 + y1 and x1 < x0 and (x1 == 0 or y1 == B)) assert is_fill or is_empty or is_pour, f"Illegal jug transition {(x0,y0)}->{(x1,y1)}" # 4. Plate 1471 (5, 3) -> Target 4 in 6 vs 8 steps & Even-Ideal (6, 4) Negative Control j53 = next(j for j in jugs if j["A"] == 5 and j["B"] == 3) t4 = next(t for t in j53["targets"] if t["T"] == 4) assert t4["reachable"] is True and t4["step_A_first"] == 6 and t4["step_B_first"] == 8, "Plate 1471 (5,3)->4 mismatch" assert t4["step_A_clean"] + t4["step_B_clean"] == 15, "step sum != 15" j64 = next(j for j in jugs if j["A"] == 6 and j["B"] == 4) for t in j64["targets"]: if t["T"] % 2 == 1: assert t["reachable"] is False and t["step_A_first"] is None and t["step_B_first"] is None, "Odd volume reached in (6,4)!" else: assert t["reachable"] is True and t["step_A_first"] is not None, "Even volume missed in (6,4)!" # 5. Reachable Clean-Jug Sum Law: step_A(T,0) + step_B(T,0) == 2(A/g + B/g) - 1 for j in jugs: for t in j["targets"]: if t["reachable"]: assert t["step_A_clean"] + t["step_B_clean"] == j["cycle_len"], "Clean-jug sum law failed" # 6. Sliding Ladder L = 100 Lattice Placements & Thales Midpoint Circle R = 50 assert s2["L"] == 100 and s2["midpoint_radius"] == 50, "Ladder L/R mismatch" lp = s2["lattice_placements"] assert [(u["a"], u["b"]) for u in lp] == [(100, 0), (96, 28), (80, 60), (60, 80), (28, 96), (0, 100)], "Pythagorean ladder list mismatch" for u in lp: a, b = u["a"], u["b"] assert a * a + b * b == 10000, "a^2 + b^2 != 10000" mx, my = Fraction(a, 2), Fraction(b, 2) assert mx * mx + my * my == 2500 and u["midpoint_r2"] == 2500, "Midpoint off Thales circle r=50" # 7. Quarter-Point Elliptic Trammel Negative Control (x/25)^2 + (y/75)^2 == 1, off r=50 for interior placements assert s2["quarter_semi_axes"] == [25, 75], "Quarter semi-axes mismatch" for u in lp: a, b = u["a"], u["b"] qx, qy = Fraction(a, 4), Fraction(3 * b, 4) assert Fraction(qx * qx, 625) + Fraction(qy * qy, 5625) == 1, "Quarter point off (25,75) ellipse" r2 = qx * qx + qy * qy assert abs(u["quarter_r"] - math.sqrt(float(r2))) < 1e-5, "quarter_r mismatch" if 0 < a < 100: assert r2 != 2500, "Interior quarter-point falsely on r=50 circle!" # 8. Astroid Envelope x^(2/3) + y^(2/3) = L^(2/3), Rational Arc Length 6L, & Area (3/8) pi L^2 L = s2["L"] assert s2["first_quadrant_astroid_arc"] == (3 * L) // 2 and s2["full_astroid_arc"] == 6 * L, "Astroid arc length mismatch" assert Fraction(s2["first_quadrant_astroid_area_over_pi"]) == Fraction(3 * L * L, 32), "Astroid area mismatch" for u in lp: tx, ty = u["astroid_touch"] val = (tx ** (2.0 / 3.0)) + (ty ** (2.0 / 3.0)) assert abs(val - (L ** (2.0 / 3.0))) < 1e-3, f"Astroid touch off curve: {val}" # 9. Holditch's Chord Theorem: Swept Area = pi * a * b independent of outer convex curve for h in s2["holditch_examples"]: a, b = h["a"], h["b"] assert a + b == L and h["chord"] == L, "Holditch chord != L" assert h["area_over_pi"] == a * b, "Holditch area != pi*a*b" # 10. Poncelet n = 3 Chapple–Euler Exact Formula: R^2 - d^2 = 2 R r (R = 1) fam3 = next(f for f in s3 if f["n"] == 3 and f["w"] == 1) for pr in fam3["presets"]: d, r = pr["d"], pr["r"] assert abs((1.0 - d * d) - 2.0 * r) < 1e-12, f"Euler n=3 violated at d={d}: r={r}" # 11. Poncelet n = 4 Nicolaus Fuss Exact Formula: (R^2 - d^2)^2 = 2 r^2 (R^2 + d^2) fam4 = next(f for f in s3 if f["n"] == 4 and f["w"] == 1) for pr in fam4["presets"]: d, r = pr["d"], pr["r"] lhs = (1.0 - d * d) ** 2 rhs = 2.0 * (r * r) * (1.0 + d * d) assert abs(lhs - rhs) < 1e-12, f"Fuss n=4 violated at d={d}" # 12. Universal Poncelet Starting-Angle Closure across ALL 9 Families (n = 3..8, including stars {5/2}, {7/2}, {7/3}) assert len(s3) == 9, "Expected 9 Poncelet families" for fam in s3: n, w = fam["n"], fam["w"] assert math.gcd(n, w) == 1 and 1 <= w < n / 2, "Invalid (n, w)" for pr in fam["presets"]: d, r = pr["d"], pr["r"] for k in range(19): th0 = 2.0 * math.pi * k / 19.0 th = th0 for _ in range(n): th = poncelet_step(th, d, r) err = abs((th - th0) - 2.0 * math.pi * w) assert err < 1e-10, f"Poncelet closure failed for n={n},w={w},d={d}: err={err}" # 13. Slit-Scan Inscribed-Angle Constancy (±tan 19°) along Circular Arc assert s4["lamp_angles_deg"] == [128, 90, 52] and s4["inscribed_half_angle_deg"] == 19.0 assert abs(s4["tan_19"] - math.tan(math.radians(19.0))) < 1e-15 assert s4["max_arc_thread_deviation"] < 1e-13 # Independently check 17 camera positions along 220°..320° for i in range(17): th = math.radians(220.0 + 100.0 * i / 16.0) px, py = math.cos(th), math.sin(th) ux, uy = -px, 1.0 - py for ang, sign in [(128.0, -1.0), (90.0, 0.0), (52.0, +1.0)]: qx, qy = math.cos(math.radians(ang)), math.sin(math.radians(ang)) vx, vy = qx - px, qy - py off = (uy * vx - ux * vy) / (ux * vx + uy * vy) assert abs(off - sign * s4["tan_19"]) < 1e-13, "Inscribed angle drifted along arc!" # 14. Exact Antipodal Piano Crossings on Arc & Horizontal Secant Chord arc_c = s4["arc_piano_crossings_t"] assert arc_c == {"blue_52": 0.12, "rose_90": 0.50, "green_128": 0.88}, "Arc crossings mismatch" ch_c = s4["chord_piano_crossings_t"] assert abs(ch_c["blue_52"] + ch_c["green_128"] - 1.0) < 1e-6 and ch_c["rose_90"] == 0.5, "Chord symmetry broken" exp_blue = 0.5 * (1.0 - math.tan(math.radians(40.0)) / math.tan(math.radians(52.0))) assert abs(ch_c["blue_52"] - round(exp_blue, 6)) < 1e-9, "Secant blue crossing mismatch" def run_self_tests(base_data): mutations = [ ("1. Corrupt (5,3) rectangle bounce count", lambda d: d["studio1"]["rectangles"][0].__setitem__("bounces", 7)), ("2. Flip (7,4) rectangle exit corner parity", lambda d: d["studio1"]["rectangles"][1].__setitem__("exit_corner", [7, 4])), ("3. Spoof Bézout (5,3) cycle length to 16", lambda d: d["studio1"]["jugs"][0].__setitem__("cycle_len", 16)), ("4. Break Policy A/B time-reversal symmetry", lambda d: d["studio1"]["jugs"][0]["path_B"][2].__setitem__(0, 4)), ("5. Claim odd mark T=3 reachable in (6,4) even-ideal", lambda d: d["studio1"]["jugs"][5]["targets"][2].__setitem__("reachable", True)), ("6. Violate clean-jug step sum law on (7,4)", lambda d: d["studio1"]["jugs"][1]["targets"][0].__setitem__("step_B_clean", 99)), ("7. Push L=100 midpoint off Thales r=50 circle", lambda d: d["studio2"]["lattice_placements"][1].__setitem__("midpoint_r2", 2501)), ("8. Corrupt quarter-point semi-axes from [25,75]", lambda d: d["studio2"].__setitem__("quarter_semi_axes", [25, 50])), ("9. Perturb rational 6L astroid arc length", lambda d: d["studio2"].__setitem__("full_astroid_arc", 602)), ("10. Spoof Holditch chord area pi*a*b", lambda d: d["studio2"]["holditch_examples"][1].__setitem__("area_over_pi", 1900)), ("11. Violate Chapple–Euler R^2-d^2=2Rr at n=3", lambda d: d["studio3"][0]["presets"][2].__setitem__("r", 0.44)), ("12. Violate Nicolaus Fuss bicentric quad law at n=4", lambda d: d["studio3"][1]["presets"][2].__setitem__("r", 0.61)), ("13. Detune Poncelet {7/2} heptagram radius by 1e-4", lambda d: d["studio3"][6]["presets"][2].__setitem__("r", d["studio3"][6]["presets"][2]["r"] + 1e-4)), ("14. Shift slit-camera secant chord crossing", lambda d: d["studio4"]["chord_piano_crossings_t"].__setitem__("blue_52", 0.18)), ] caught = 0 for name, fn in mutations: bad = copy.deepcopy(base_data) fn(bad) try: verify_all(bad) except Exception as exc: caught += 1 print(f" [PASS] Caught mutation {name} -> {exc}") else: raise SystemExit(f" [FAIL] Mutation NOT caught: {name}") print(f"\nSelf-test summary: {caught}/{len(mutations)} deliberate corruptions caught.") def main(): data = json.loads(DATA_PATH.read_text()) verify_all(data) print("Primary verification: 14/14 mathematical suites PASSED.") if "--self-test" in sys.argv: run_self_tests(data) if __name__ == "__main__": main()