"""Independent second-pair verification of PR #24's n = 15 claims (issue #25). Written from scratch by zcode-zp1 against the definitions in hongdy22's CERTIFICATES.md, not by adapting their code. Every quantity is recomputed in exact rational arithmetic; the certificate inputs (witness weights, targets, radius) are taken from the PR and verified to work. Usage: python3 verify_independent.py INDIR POLISHED.txt INDIR holds: raw.dat (job 101 n15.txt), reference15.dat, reference16.dat, search-summary.json, polish-report.json, deletion-certificate.dat, pr-n15.txt (the PR route's n15.txt). POLISHED.txt is the replayed file. """ import hashlib import json import sys from fractions import Fraction from itertools import combinations from math import sqrt from pathlib import Path R = Fraction(1, 10**42) # the certificate's radius def show(value, places=40): """A rational as a decimal string, cut (never rounded) to `places` places.""" value = Fraction(value) sign = "-" if value < 0 else "" scaled = abs(value) * 10**places whole = scaled.numerator // scaled.denominator text = str(whole).zfill(places + 1) return f"{sign}{text[:-places]}.{text[-places:]}" TARGET_DELETION = Fraction(31, 1485) TRIPLES = tuple(combinations(range(15), 3)) # Witness weights of the two per-axis certificates, verbatim from PR #17 # (routes/hongdy22-codex-n15-search/verify_deletion.py, 1-based vertices). WITNESSES = ( {(0, 6, 14): Fraction(8, 225), (1, 6, 10): Fraction(31, 225), (4, 8, 12): Fraction(31, 45), (10, 12, 14): Fraction(31, 225)}, {(0, 2, 9): Fraction(2, 33), (3, 7, 9): Fraction(31, 33)}, ) def read_points(path): pts = [tuple(map(Fraction, line.split())) for line in Path(path).read_text().splitlines() if line.strip() and not line.lstrip().startswith("#")] assert len(pts) == len(set(pts)) == 15, path assert all(0 <= c <= 1 for p in pts for c in p), path return pts def signed_area(a, b, c): (ax, ay), (bx, by), (cx, cy) = a, b, c return ((bx - ax) * (cy - ay) - (cx - ax) * (by - ay)) / 2 def all_signed_areas(pts): return {t: signed_area(*(pts[i] for i in t)) for t in TRIPLES} def area_gradient(triple, pts): """Gradient of the signed area in all 30 coordinates (exact, affine check below).""" (i, j, k), row = triple, [Fraction(0)] * 30 for me, after, before in ((i, j, k), (j, k, i), (k, i, j)): row[2 * me] = (pts[after][1] - pts[before][1]) / 2 row[2 * me + 1] = (pts[before][0] - pts[after][0]) / 2 return row def check_gradients(pts, triples, eps=Fraction(1, 10**6)): """Signed area is affine in each single coordinate: exact spot checks.""" for t in triples: for coord in range(30): base = signed_area(*(pts[i] for i in t)) moved = list(map(list, pts)) moved[coord // 2][coord % 2] += eps shifted = signed_area(*(map(tuple, (moved[t[0]], moved[t[1]], moved[t[2]])))) assert shifted - base == area_gradient(t, pts)[coord] * eps, (t, coord) def inverse(matrix): """Gauss-Jordan with partial pivoting by magnitude (their code picks the first nonzero).""" size = len(matrix) rows = [list(map(Fraction, row)) + [Fraction(i == j) for j in range(size)] for i, row in enumerate(matrix)] for col in range(size): pivot = max(range(col, size), key=lambda r: abs(rows[r][col])) assert rows[pivot][col] != 0, "singular jacobian" rows[col], rows[pivot] = rows[pivot], rows[col] unit = [v / rows[col][col] for v in rows[col]] rows[col] = unit for r, row in enumerate(rows): if r != col and row[col]: f = row[col] rows[r] = [a - f * b for a, b in zip(row, unit)] return [row[size:] for row in rows] def exact_min(points): areas = all_signed_areas(points) smallest = min(abs(v) for v in areas.values()) hits = [t for t, v in areas.items() if abs(v) == smallest] return smallest, hits, areas def certificate(pts, area_center, tight, signs): """The strict-local-maximum numbers, recomputed from the definitions.""" grads = [[signs[t] * v for v in area_gradient(t, pts)] for t in tight] free = [i for i in range(30) if 0 < pts[i // 2][i % 2] < 1] fixed = [i for i in range(30) if pts[i // 2][i % 2] in (Fraction(0), Fraction(1))] assert all(R < pts[i // 2][i % 2] < 1 - R for i in free) assert len(free) + len(fixed) == 30 jacobian = [[g[i] for i in free] + [Fraction(-1)] for g in grads] a = inverse(jacobian) for i in range(len(a)): # A must be the exact inverse for j, col in enumerate(zip(*jacobian)): assert sum(x * y for x, y in zip(a[i], col)) == (i == j) norm = max(sum(abs(v) for v in row) for row in a) # A is the exact rational inverse, so ||I - A*J||_inf is exactly 0 (asserted above); # CERTIFICATES.md's q = ||I - AJ|| + 6r||A|| therefore reduces to 6r||A||. q = 6 * R * norm areas = all_signed_areas(pts) residual = [signs[t] * areas[t] - area_center for t in tight] correction = max(abs(sum(x * y for x, y in zip(row, residual))) for row in a) assert q < 1 and correction + q * R <= R gap = min(abs(v) for t, v in areas.items() if t not in signs) - area_center assert gap > 7 * R and area_center > R weights = [-v for v in a[-1]] assert sum(weights) == 1 # last jacobian column is all -1 weighted = [sum(w * g[i] for w, g in zip(weights, grads)) for i in range(30)] assert all(weighted[i] == 0 for i in free) # stationarity in the free coordinates inv_err = norm * q / (1 - q) weight_margin = min(weights) - inv_err boundary_margin = min(weighted[i] * (2 * pts[i // 2][i % 2] - 1) for i in fixed) boundary_margin -= inv_err / 2 + R assert weight_margin > 0 and boundary_margin > 0 direction_bound = max(1 / boundary_margin, (norm + inv_err) * (1 / weight_margin + 1 / (2 * boundary_margin))) from_margin = 1 / (6 * direction_bound) from_area = (area_center - R) / 6 radius = min(from_margin, from_area) assert radius > Fraction(38, 10**7) print(f" free {len(free)} / fixed {len(fixed)}, ||A*J - I||_inf exactly 0 (asserted elementwise)") print(f" inverse norm {float(norm):.12g}; q {float(q):.12g}; correction {float(correction):.12g};" f" inactive gap {float(gap):.12g}") print(f" weight margin {float(weight_margin):.12g}; boundary margin {float(boundary_margin):.12g}") print(f" direction bound {float(direction_bound):.6f} = max(1/b, M(1/w + 1/(2b))) with" f" M {float(norm + inv_err):.3f}, w {float(weight_margin):.6g}, b {float(boundary_margin):.6g}") print(f" radius from margins 1/(6L) {float(from_margin):.6g} vs from area (A-r)/6" f" {float(from_area):.6g} -> binding: {'1/(6L)' if from_margin < from_area else 'area cap'}") print(f" strict-local radius {show(radius, 12)} > 3.8e-6") def axis_bound(pts, axis, weights): """Max over the unit box of a convex combination of oriented areas (other axis fixed). With the other axis fixed the oriented area is linear in the axis coordinates, so the combination is g(p) = sum_i coeffs[i] * p[i] with coeffs from the exact (affine-checked) gradients. g(u0) = the common area (each oriented area there equals the minimum and the weights sum to one), so if max over the box also equals the minimum, no axis-only displacement can lift the minimum above it: the minimum never exceeds the weighted average. """ assert sum(weights.values()) == 1 and min(weights.values()) > 0 coeffs = [Fraction(0)] * 15 for t, w in weights.items(): value = signed_area(*(pts[i] for i in t)) assert abs(value) == TARGET_DELETION sign = 1 if value > 0 else -1 row = area_gradient(t, pts) for i in range(15): coeffs[i] += w * sign * row[2 * i + axis] at_placement = sum(c * p[axis] for c, p in zip(coeffs, pts)) assert at_placement == TARGET_DELETION return sum(max(Fraction(0), c) for c in coeffs), coeffs def minimum_cover(pts, target): areas = {t: abs(v) for t, v in all_signed_areas(pts).items()} for kept in range(15, 0, -1): good = [s for s in combinations(range(15), kept) if all(areas[t] >= target for t in combinations(s, 3))] if good: return 15 - kept, len(good) raise AssertionError("no cover") def seeding(indir): """How the three tracks of job 101 were started, per the saved summary and code.""" import numpy as np summary = json.loads((indir / "search-summary.json").read_text()) got = {} n16 = np.loadtxt(indir / "reference16.dat") n15 = np.loadtxt(indir / "reference15.dat") def min_area(pts): return min(abs((b[0] - a[0]) * (c[1] - a[1]) - (c[0] - a[0]) * (b[1] - a[1])) / 2 for a, b, c in combinations(pts, 3)) for track in summary["tracks"]: got[track["track"]] = track["starting_area"] assert got["deletion"] == float(max(min_area(np.delete(n16, i, axis=0)) for i in range(16))), \ "deletion start is not the best 15-subset of reference16" assert got["record"] == float(min_area(n15)), "record start is not reference15.dat" def stratified(rng): pts = (np.column_stack((rng.permutation(15), rng.permutation(15))) + rng.random((15, 2))) / 15 return (pts - pts.min(axis=0)) / (pts.max(axis=0) - pts.min(axis=0)) start = stratified(np.random.default_rng(20261123)) value = min_area(start) assert got["independent"] == value, (got["independent"], value) print(f" deletion start {got['deletion']:.13f} = best 15-subset of reference16 (7/341 basin)") print(f" record start {got['record']:.13f} = reference15.dat itself") print(f" independent start {got['independent']:.13f} = stratified_start(default_rng(20261123)):" " a random start, five orders below the record value") def main(): indir, polished_path = Path(sys.argv[1]), Path(sys.argv[2]) pr_path = indir / "pr-n15.txt" sha = lambda p: hashlib.sha256(Path(p).read_bytes()).hexdigest() replay_sha, pr_sha = sha(polished_path), sha(pr_path) print(f"1. replayed polish.py output vs the PR's n15.txt: {'SAME BYTES' if replay_sha == pr_sha else 'DIFFER'}" f" (sha256 {replay_sha[:16]}...)") raw = read_points(indir / "raw.dat") polished = read_points(polished_path) reference = read_points(indir / "reference15.dat") summary = json.loads((indir / "search-summary.json").read_text()) track = next(t for t in summary["tracks"] if t["track"] == "independent") independent = [tuple(map(Fraction, line.split())) for line in track["coordinates"]] print(f"2. raw job 101 == the summary's independent track: {raw == independent}") rotated = [(y, 1 - x) for x, y in raw] nearest = [min(((x - u) ** 2 + (y - v) ** 2, (u, v)) for u, v in reference) for x, y in rotated] assert len({p for _, p in nearest}) == 15 worst_sq = max(d for d, _ in nearest) print(f"3. rotation (x, y) -> (y, 1 - x) matches reference15.dat one-to-one," f" max residual {sqrt(float(worst_sq)):.12g}") raw_areas = all_signed_areas(raw) raw_min = min(abs(v) for v in raw_areas.values()) tight = [t for t, v in raw_areas.items() if abs(v) <= raw_min + Fraction(1, 10**9)] assert len(tight) == 25 signs = {t: 1 if raw_areas[t] > 0 else -1 for t in tight} check_gradients(polished, tight) print(f"4. tight triangles {len(tight)} on the raw output (within 1e-9 of its minimum);" f" gradients exact-affine in all 25 x 30 coordinates") area_center = Fraction(json.loads((indir / "polish-report.json").read_text())["independent"]["area_center"]) smallest, hits, _ = exact_min(polished) print(f"5. polished exact minimum {show(smallest, 30)} over {len(hits)} triangles") print(f" certificate target A (area_center) {show(area_center, 30)}") certificate(polished, area_center, tight, signs) deletion = read_points(indir / "deletion-certificate.dat") smallest, hits, _ = exact_min(deletion) assert smallest == TARGET_DELETION print(f"6. deletion placement: exact minimum {TARGET_DELETION} on {len(hits)} of 455 triangles") import random rng = random.Random(20261128) for axis, label in enumerate("xy"): bound, coeffs = axis_bound(deletion, axis, WITNESSES[axis]) assert bound == TARGET_DELETION worst = max(sum(c * Fraction(rng.randint(0, 10**12), 10**12) for c in coeffs) for _ in range(2000)) assert worst <= TARGET_DELETION print(f" varying {label} alone (other axis, orientations fixed): max of the witness" f" combination over the unit box = {bound} == the minimum;" f" 2000 random box points all stay <= it") for name, target, expected in (("reference15", Fraction("0.0212105411"), (6, 7)), ("deletion", Fraction("0.0208754209"), (7, 2))): moves, count = minimum_cover(reference if name == "reference15" else deletion, target) assert (moves, count) == expected print(f"7. {name} at target {target}: at least {moves} points must move;" f" {count} minimum covers of the triangles below target") seeding(indir) print("ALL CHECKS PASSED") if __name__ == "__main__": main()