| @@ -0,0 +1,287 @@ |
| 1 | +"""Independent second-pair verification of PR #24's n = 15 claims (issue #25). |
| 2 | + |
| 3 | +Written from scratch by zcode-zp1 against the definitions in hongdy22's |
| 4 | +CERTIFICATES.md, not by adapting their code. Every quantity is recomputed |
| 5 | +in exact rational arithmetic; the certificate inputs (witness weights, |
| 6 | +targets, radius) are taken from the PR and verified to work. |
| 7 | + |
| 8 | +Usage: |
| 9 | + python3 verify_independent.py INDIR POLISHED.txt |
| 10 | + |
| 11 | +INDIR holds: raw.dat (job 101 n15.txt), reference15.dat, reference16.dat, |
| 12 | +search-summary.json, polish-report.json, deletion-certificate.dat, |
| 13 | +pr-n15.txt (the PR route's n15.txt). POLISHED.txt is the replayed file. |
| 14 | +""" |
| 15 | + |
| 16 | +import hashlib |
| 17 | +import json |
| 18 | +import sys |
| 19 | +from fractions import Fraction |
| 20 | +from itertools import combinations |
| 21 | +from math import sqrt |
| 22 | +from pathlib import Path |
| 23 | + |
| 24 | +R = Fraction(1, 10**42) |
| 25 | + |
| 26 | + |
| 27 | +def show(value, places=40): |
| 28 | + """A rational as a decimal string, cut (never rounded) to `places` places.""" |
| 29 | + value = Fraction(value) |
| 30 | + sign = "-" if value < 0 else "" |
| 31 | + scaled = abs(value) * 10**places |
| 32 | + whole = scaled.numerator // scaled.denominator |
| 33 | + text = str(whole).zfill(places + 1) |
| 34 | + return f"{sign}{text[:-places]}.{text[-places:]}" |
| 35 | + |
| 36 | + |
| 37 | +TARGET_DELETION = Fraction(31, 1485) |
| 38 | +TRIPLES = tuple(combinations(range(15), 3)) |
| 39 | + |
| 40 | + |
| 41 | +WITNESSES = ( |
| 42 | + {(0, 6, 14): Fraction(8, 225), (1, 6, 10): Fraction(31, 225), |
| 43 | + (4, 8, 12): Fraction(31, 45), (10, 12, 14): Fraction(31, 225)}, |
| 44 | + {(0, 2, 9): Fraction(2, 33), (3, 7, 9): Fraction(31, 33)}, |
| 45 | +) |
| 46 | + |
| 47 | + |
| 48 | +def read_points(path): |
| 49 | + pts = [tuple(map(Fraction, line.split())) for line in Path(path).read_text().splitlines() |
| 50 | + if line.strip() and not line.lstrip().startswith("#")] |
| 51 | + assert len(pts) == len(set(pts)) == 15, path |
| 52 | + assert all(0 <= c <= 1 for p in pts for c in p), path |
| 53 | + return pts |
| 54 | + |
| 55 | + |
| 56 | +def signed_area(a, b, c): |
| 57 | + (ax, ay), (bx, by), (cx, cy) = a, b, c |
| 58 | + return ((bx - ax) * (cy - ay) - (cx - ax) * (by - ay)) / 2 |
| 59 | + |
| 60 | + |
| 61 | +def all_signed_areas(pts): |
| 62 | + return {t: signed_area(*(pts[i] for i in t)) for t in TRIPLES} |
| 63 | + |
| 64 | + |
| 65 | +def area_gradient(triple, pts): |
| 66 | + """Gradient of the signed area in all 30 coordinates (exact, affine check below).""" |
| 67 | + (i, j, k), row = triple, [Fraction(0)] * 30 |
| 68 | + for me, after, before in ((i, j, k), (j, k, i), (k, i, j)): |
| 69 | + row[2 * me] = (pts[after][1] - pts[before][1]) / 2 |
| 70 | + row[2 * me + 1] = (pts[before][0] - pts[after][0]) / 2 |
| 71 | + return row |
| 72 | + |
| 73 | + |
| 74 | +def check_gradients(pts, triples, eps=Fraction(1, 10**6)): |
| 75 | + """Signed area is affine in each single coordinate: exact spot checks.""" |
| 76 | + for t in triples: |
| 77 | + for coord in range(30): |
| 78 | + base = signed_area(*(pts[i] for i in t)) |
| 79 | + moved = list(map(list, pts)) |
| 80 | + moved[coord // 2][coord % 2] += eps |
| 81 | + shifted = signed_area(*(map(tuple, (moved[t[0]], moved[t[1]], moved[t[2]])))) |
| 82 | + assert shifted - base == area_gradient(t, pts)[coord] * eps, (t, coord) |
| 83 | + |
| 84 | + |
| 85 | +def inverse(matrix): |
| 86 | + """Gauss-Jordan with partial pivoting by magnitude (their code picks the first nonzero).""" |
| 87 | + size = len(matrix) |
| 88 | + rows = [list(map(Fraction, row)) + [Fraction(i == j) for j in range(size)] for i, row in enumerate(matrix)] |
| 89 | + for col in range(size): |
| 90 | + pivot = max(range(col, size), key=lambda r: abs(rows[r][col])) |
| 91 | + assert rows[pivot][col] != 0, "singular jacobian" |
| 92 | + rows[col], rows[pivot] = rows[pivot], rows[col] |
| 93 | + unit = [v / rows[col][col] for v in rows[col]] |
| 94 | + rows[col] = unit |
| 95 | + for r, row in enumerate(rows): |
| 96 | + if r != col and row[col]: |
| 97 | + f = row[col] |
| 98 | + rows[r] = [a - f * b for a, b in zip(row, unit)] |
| 99 | + return [row[size:] for row in rows] |
| 100 | + |
| 101 | + |
| 102 | +def exact_min(points): |
| 103 | + areas = all_signed_areas(points) |
| 104 | + smallest = min(abs(v) for v in areas.values()) |
| 105 | + hits = [t for t, v in areas.items() if abs(v) == smallest] |
| 106 | + return smallest, hits, areas |
| 107 | + |
| 108 | + |
| 109 | +def certificate(pts, area_center, tight, signs): |
| 110 | + """The strict-local-maximum numbers, recomputed from the definitions.""" |
| 111 | + grads = [[signs[t] * v for v in area_gradient(t, pts)] for t in tight] |
| 112 | + free = [i for i in range(30) if 0 < pts[i // 2][i % 2] < 1] |
| 113 | + fixed = [i for i in range(30) if pts[i // 2][i % 2] in (Fraction(0), Fraction(1))] |
| 114 | + assert all(R < pts[i // 2][i % 2] < 1 - R for i in free) |
| 115 | + assert len(free) + len(fixed) == 30 |
| 116 | + jacobian = [[g[i] for i in free] + [Fraction(-1)] for g in grads] |
| 117 | + a = inverse(jacobian) |
| 118 | + for i in range(len(a)): |
| 119 | + for j, col in enumerate(zip(*jacobian)): |
| 120 | + assert sum(x * y for x, y in zip(a[i], col)) == (i == j) |
| 121 | + norm = max(sum(abs(v) for v in row) for row in a) |
| 122 | + |
| 123 | + |
| 124 | + q = 6 * R * norm |
| 125 | + areas = all_signed_areas(pts) |
| 126 | + residual = [signs[t] * areas[t] - area_center for t in tight] |
| 127 | + correction = max(abs(sum(x * y for x, y in zip(row, residual))) for row in a) |
| 128 | + assert q < 1 and correction + q * R <= R |
| 129 | + gap = min(abs(v) for t, v in areas.items() if t not in signs) - area_center |
| 130 | + assert gap > 7 * R and area_center > R |
| 131 | + weights = [-v for v in a[-1]] |
| 132 | + assert sum(weights) == 1 |
| 133 | + weighted = [sum(w * g[i] for w, g in zip(weights, grads)) for i in range(30)] |
| 134 | + assert all(weighted[i] == 0 for i in free) |
| 135 | + inv_err = norm * q / (1 - q) |
| 136 | + weight_margin = min(weights) - inv_err |
| 137 | + boundary_margin = min(weighted[i] * (2 * pts[i // 2][i % 2] - 1) for i in fixed) |
| 138 | + boundary_margin -= inv_err / 2 + R |
| 139 | + assert weight_margin > 0 and boundary_margin > 0 |
| 140 | + direction_bound = max(1 / boundary_margin, |
| 141 | + (norm + inv_err) * (1 / weight_margin + 1 / (2 * boundary_margin))) |
| 142 | + from_margin = 1 / (6 * direction_bound) |
| 143 | + from_area = (area_center - R) / 6 |
| 144 | + radius = min(from_margin, from_area) |
| 145 | + assert radius > Fraction(38, 10**7) |
| 146 | + print(f" free {len(free)} / fixed {len(fixed)}, ||A*J - I||_inf exactly 0 (asserted elementwise)") |
| 147 | + print(f" inverse norm {float(norm):.12g}; q {float(q):.12g}; correction {float(correction):.12g};" |
| 148 | + f" inactive gap {float(gap):.12g}") |
| 149 | + print(f" weight margin {float(weight_margin):.12g}; boundary margin {float(boundary_margin):.12g}") |
| 150 | + print(f" direction bound {float(direction_bound):.6f} = max(1/b, M(1/w + 1/(2b))) with" |
| 151 | + f" M {float(norm + inv_err):.3f}, w {float(weight_margin):.6g}, b {float(boundary_margin):.6g}") |
| 152 | + print(f" radius from margins 1/(6L) {float(from_margin):.6g} vs from area (A-r)/6" |
| 153 | + f" {float(from_area):.6g} -> binding: {'1/(6L)' if from_margin < from_area else 'area cap'}") |
| 154 | + print(f" strict-local radius {show(radius, 12)} > 3.8e-6") |
| 155 | + |
| 156 | + |
| 157 | +def axis_bound(pts, axis, weights): |
| 158 | + """Max over the unit box of a convex combination of oriented areas (other axis fixed). |
| 159 | + |
| 160 | + With the other axis fixed the oriented area is linear in the axis coordinates, so the |
| 161 | + combination is g(p) = sum_i coeffs[i] * p[i] with coeffs from the exact (affine-checked) |
| 162 | + gradients. g(u0) = the common area (each oriented area there equals the minimum and the |
| 163 | + weights sum to one), so if max over the box also equals the minimum, no axis-only |
| 164 | + displacement can lift the minimum above it: the minimum never exceeds the weighted average. |
| 165 | + """ |
| 166 | + assert sum(weights.values()) == 1 and min(weights.values()) > 0 |
| 167 | + coeffs = [Fraction(0)] * 15 |
| 168 | + for t, w in weights.items(): |
| 169 | + value = signed_area(*(pts[i] for i in t)) |
| 170 | + assert abs(value) == TARGET_DELETION |
| 171 | + sign = 1 if value > 0 else -1 |
| 172 | + row = area_gradient(t, pts) |
| 173 | + for i in range(15): |
| 174 | + coeffs[i] += w * sign * row[2 * i + axis] |
| 175 | + at_placement = sum(c * p[axis] for c, p in zip(coeffs, pts)) |
| 176 | + assert at_placement == TARGET_DELETION |
| 177 | + return sum(max(Fraction(0), c) for c in coeffs), coeffs |
| 178 | + |
| 179 | + |
| 180 | +def minimum_cover(pts, target): |
| 181 | + areas = {t: abs(v) for t, v in all_signed_areas(pts).items()} |
| 182 | + for kept in range(15, 0, -1): |
| 183 | + good = [s for s in combinations(range(15), kept) |
| 184 | + if all(areas[t] >= target for t in combinations(s, 3))] |
| 185 | + if good: |
| 186 | + return 15 - kept, len(good) |
| 187 | + raise AssertionError("no cover") |
| 188 | + |
| 189 | + |
| 190 | +def seeding(indir): |
| 191 | + """How the three tracks of job 101 were started, per the saved summary and code.""" |
| 192 | + import numpy as np |
| 193 | + summary = json.loads((indir / "search-summary.json").read_text()) |
| 194 | + got = {} |
| 195 | + n16 = np.loadtxt(indir / "reference16.dat") |
| 196 | + n15 = np.loadtxt(indir / "reference15.dat") |
| 197 | + |
| 198 | + def min_area(pts): |
| 199 | + return min(abs((b[0] - a[0]) * (c[1] - a[1]) - (c[0] - a[0]) * (b[1] - a[1])) / 2 |
| 200 | + for a, b, c in combinations(pts, 3)) |
| 201 | + |
| 202 | + for track in summary["tracks"]: |
| 203 | + got[track["track"]] = track["starting_area"] |
| 204 | + assert got["deletion"] == float(max(min_area(np.delete(n16, i, axis=0)) for i in range(16))), \ |
| 205 | + "deletion start is not the best 15-subset of reference16" |
| 206 | + assert got["record"] == float(min_area(n15)), "record start is not reference15.dat" |
| 207 | + |
| 208 | + def stratified(rng): |
| 209 | + pts = (np.column_stack((rng.permutation(15), rng.permutation(15))) + rng.random((15, 2))) / 15 |
| 210 | + return (pts - pts.min(axis=0)) / (pts.max(axis=0) - pts.min(axis=0)) |
| 211 | + |
| 212 | + start = stratified(np.random.default_rng(20261123)) |
| 213 | + value = min_area(start) |
| 214 | + assert got["independent"] == value, (got["independent"], value) |
| 215 | + print(f" deletion start {got['deletion']:.13f} = best 15-subset of reference16 (7/341 basin)") |
| 216 | + print(f" record start {got['record']:.13f} = reference15.dat itself") |
| 217 | + print(f" independent start {got['independent']:.13f} = stratified_start(default_rng(20261123)):" |
| 218 | + " a random start, five orders below the record value") |
| 219 | + |
| 220 | + |
| 221 | +def main(): |
| 222 | + indir, polished_path = Path(sys.argv[1]), Path(sys.argv[2]) |
| 223 | + pr_path = indir / "pr-n15.txt" |
| 224 | + sha = lambda p: hashlib.sha256(Path(p).read_bytes()).hexdigest() |
| 225 | + replay_sha, pr_sha = sha(polished_path), sha(pr_path) |
| 226 | + print(f"1. replayed polish.py output vs the PR's n15.txt: {'SAME BYTES' if replay_sha == pr_sha else 'DIFFER'}" |
| 227 | + f" (sha256 {replay_sha[:16]}...)") |
| 228 | + |
| 229 | + raw = read_points(indir / "raw.dat") |
| 230 | + polished = read_points(polished_path) |
| 231 | + reference = read_points(indir / "reference15.dat") |
| 232 | + summary = json.loads((indir / "search-summary.json").read_text()) |
| 233 | + track = next(t for t in summary["tracks"] if t["track"] == "independent") |
| 234 | + independent = [tuple(map(Fraction, line.split())) for line in track["coordinates"]] |
| 235 | + print(f"2. raw job 101 == the summary's independent track: {raw == independent}") |
| 236 | + |
| 237 | + rotated = [(y, 1 - x) for x, y in raw] |
| 238 | + nearest = [min(((x - u) ** 2 + (y - v) ** 2, (u, v)) for u, v in reference) for x, y in rotated] |
| 239 | + assert len({p for _, p in nearest}) == 15 |
| 240 | + worst_sq = max(d for d, _ in nearest) |
| 241 | + print(f"3. rotation (x, y) -> (y, 1 - x) matches reference15.dat one-to-one," |
| 242 | + f" max residual {sqrt(float(worst_sq)):.12g}") |
| 243 | + |
| 244 | + raw_areas = all_signed_areas(raw) |
| 245 | + raw_min = min(abs(v) for v in raw_areas.values()) |
| 246 | + tight = [t for t, v in raw_areas.items() if abs(v) <= raw_min + Fraction(1, 10**9)] |
| 247 | + assert len(tight) == 25 |
| 248 | + signs = {t: 1 if raw_areas[t] > 0 else -1 for t in tight} |
| 249 | + check_gradients(polished, tight) |
| 250 | + print(f"4. tight triangles {len(tight)} on the raw output (within 1e-9 of its minimum);" |
| 251 | + f" gradients exact-affine in all 25 x 30 coordinates") |
| 252 | + |
| 253 | + area_center = Fraction(json.loads((indir / "polish-report.json").read_text())["independent"]["area_center"]) |
| 254 | + smallest, hits, _ = exact_min(polished) |
| 255 | + print(f"5. polished exact minimum {show(smallest, 30)} over {len(hits)} triangles") |
| 256 | + print(f" certificate target A (area_center) {show(area_center, 30)}") |
| 257 | + certificate(polished, area_center, tight, signs) |
| 258 | + |
| 259 | + deletion = read_points(indir / "deletion-certificate.dat") |
| 260 | + smallest, hits, _ = exact_min(deletion) |
| 261 | + assert smallest == TARGET_DELETION |
| 262 | + print(f"6. deletion placement: exact minimum {TARGET_DELETION} on {len(hits)} of 455 triangles") |
| 263 | + import random |
| 264 | + rng = random.Random(20261128) |
| 265 | + for axis, label in enumerate("xy"): |
| 266 | + bound, coeffs = axis_bound(deletion, axis, WITNESSES[axis]) |
| 267 | + assert bound == TARGET_DELETION |
| 268 | + worst = max(sum(c * Fraction(rng.randint(0, 10**12), 10**12) for c in coeffs) |
| 269 | + for _ in range(2000)) |
| 270 | + assert worst <= TARGET_DELETION |
| 271 | + print(f" varying {label} alone (other axis, orientations fixed): max of the witness" |
| 272 | + f" combination over the unit box = {bound} == the minimum;" |
| 273 | + f" 2000 random box points all stay <= it") |
| 274 | + |
| 275 | + for name, target, expected in (("reference15", Fraction("0.0212105411"), (6, 7)), |
| 276 | + ("deletion", Fraction("0.0208754209"), (7, 2))): |
| 277 | + moves, count = minimum_cover(reference if name == "reference15" else deletion, target) |
| 278 | + assert (moves, count) == expected |
| 279 | + print(f"7. {name} at target {target}: at least {moves} points must move;" |
| 280 | + f" {count} minimum covers of the triangles below target") |
| 281 | + |
| 282 | + seeding(indir) |
| 283 | + print("ALL CHECKS PASSED") |
| 284 | + |
| 285 | + |
| 286 | +if __name__ == "__main__": |
| 287 | + main() |