#!/usr/bin/env python3 """Exact analysis of the quarter-turn family maximum for n = 12 (issue #8). The C4 family: 12 points = three orbits of the quarter turn R(x, y) = (1 - y, x). Every boundary orbit can be written with representative (a, 0), giving points (a, 0), (1, a), (1 - a, 1), (0, 1 - a); the interior orbit has representative (px, py) with images (1 - py, px), (1 - px, 1 - py), (py, 1 - px). Every coordinate is an affine function of the four parameters with integer coefficients, so each of the 220 doubled triangle areas is an integer-coefficient quadratic polynomial over Z[a, b, px, py]. This script rebuilds the family from the record table's literals (Tej Stead, math.tejstead.com/heilbronn/square/12/points.txt), finds the active (tied) triangles at the record point in exact arithmetic, and runs the KKT test: does a nonnegative combination of the active signed-area gradients vanish? If yes, the record point is stationary for the family maximum and its activation value should satisfy the record's defining cubic 64t^3 + 80t^2 + 28t - 1 (checked exactly on the literals). If no, an ascent direction exists and the record is beatable inside the family - a record for issue #8. Usage: family_max.py STEAD-n12.txt [OUTDIR] """ import sys from fractions import Fraction from itertools import combinations from pathlib import Path ZERO, ONE = Fraction(0), Fraction(1) TOL = Fraction(1, 10**20) PARAMS = ("a", "b", "px", "py") def quarter_turn(p): return (1 - p[1], p[0]) def load_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)) == 12 return pts def near(p, q): return abs(p[0] - q[0]) <= TOL and abs(p[1] - q[1]) <= TOL def build_orbits(points): unseen = list(points) orbits = [] while unseen: orbit = [unseen.pop(0)] for _ in range(3): nxt = quarter_turn(orbit[-1]) match = [p for p in unseen if near(p, nxt)] assert len(match) == 1, f"orbit closure fails near {float(nxt[0]):.15f}" orbit.append(match[0]) unseen.remove(match[0]) orbits.append(orbit) return orbits def affine(x): """An integer-coefficient affine form: {monomial: coeff}. x is (name, coef) for a parameter term, or a Fraction/int constant (stored as the empty monomial), or None for zero.""" out = {} if x is None: return out if isinstance(x, tuple): if x[0] is None: # (None, coef) means the constant coef out[()] = out.get((), 0) + x[1] else: out[(x[0],)] = out.get((x[0],), 0) + x[1] return out out[()] = out.get((), 0) + Fraction(x) return out def poly_mul(p, q): out = {} for m1, c1 in p.items(): for m2, c2 in q.items(): key = tuple(sorted(m1 + m2)) out[key] = out.get(key, 0) + c1 * c2 return {m: c for m, c in out.items() if c} def poly_sub(p, q): out = dict(p) for m, c in q.items(): out[m] = out.get(m, 0) - c return {m: c for m, c in out.items() if c} def doubled_poly(ca, cb, cc): """D = (bx-ax)(cy-ay) - (cx-ax)(by-ay) from three coordinate affine forms.""" return poly_sub(poly_mul(poly_sub(cb[0], ca[0]), poly_sub(cc[1], ca[1])), poly_mul(poly_sub(cc[0], ca[0]), poly_sub(cb[1], ca[1]))) def poly_eval(p, values): total = Fraction(0) for m, c in p.items(): term = c for name in m: term *= values[name] total += term return total def poly_grad_at(p, values): grad = {} for m, c in p.items(): for k, name in enumerate(m): factor = c for kk, other in enumerate(m): if kk != k: factor *= values[other] grad[name] = grad.get(name, ZERO) + factor return grad def nullspace(matrix): """Exact rational nullspace basis of a list of rows.""" rows = [list(row) for row in matrix] if not rows: return [] cols = len(rows[0]) pivots, r = [], 0 for c in range(cols): pivot = next((i for i in range(r, len(rows)) if rows[i][c] != 0), None) if pivot is None: continue rows[r], rows[pivot] = rows[pivot], rows[r] unit = [v / rows[r][c] for v in rows[r]] rows[r] = unit for i, row in enumerate(rows): if i != r and row[c]: f = row[c] rows[i] = [a - f * b for a, b in zip(row, unit)] pivots.append(c) r += 1 if r == len(rows): break basis = [] for f in [c for c in range(cols) if c not in pivots]: vec = [ZERO] * cols vec[f] = ONE for ri, pc in enumerate(pivots): vec[pc] = -rows[ri][f] basis.append(vec) return basis def main(): points = load_points(sys.argv[1]) orbits = build_orbits(points) rep_list = [] # (rep, orbit), boundary orbits first, interior last for orbit in orbits: bottom = [p for p in orbit if p[1] == ZERO] if bottom: rep_list.append(((bottom[0][0], ZERO), orbit)) else: interior = [p for p in orbit if 0 < p[0] < 1 and 0 < p[1] < 1] assert len(interior) == 4 rep_list.append((None, orbit)) rep_list.sort(key=lambda item: item[0] is None) # interior rep: any member; prefer one whose coordinates are interior if rep_list[2][0] is None: orbit = rep_list[2][1] interior = [p for p in orbit if 0 < p[0] < 1 and 0 < p[1] < 1] rep_list[2] = (interior[0], orbit) kinds = ["boundary", "boundary", "interior"] print(f"1. orbits rebuilt from the literals: {kinds}") reps = [rep for rep, _ in rep_list] a, b = reps[0][0], reps[1][0] px, py = reps[2] values = {"a": a, "b": b, "px": px, "py": py} print(f"2. family parameters at the record: a = {float(a):.16f}, b = {float(b):.16f}, " f"px = {float(px):.16f}, py = {float(py):.16f}") def orbit_forms(rep, name): """Integer-coefficient affine forms of the four slots' (x, y). Boundary rep (name, 0): slots (name, 0), (1, name), (1-name, 1), (0, 1-name). Interior rep (px, py): slots (px, py), (1-py, px), (1-px, 1-py), (py, 1-px).""" rx, ry = rep if ry == ZERO: A = affine((name, ONE)) C1, C0 = affine((None, ONE)), affine(None) return [(A, C0), (C1, A), (poly_sub(C1, A), C1), (C0, poly_sub(C1, A))] PX, PY = affine(("px", ONE)), affine(("py", ONE)) C1, C0 = affine((None, ONE)), affine(None) one_minus = lambda f: poly_sub(C1, f) return [(PX, PY), (one_minus(PY), PX), (one_minus(PX), one_minus(PY)), (PY, one_minus(PX))] names = ["a", "b", None] forms = [orbit_forms(rep, name) for rep, name in zip(reps, names)] family_pts, lit_of = [], [] for k, (rep, orbit) in enumerate(rep_list): for s in range(4): x_form, y_form = forms[k][s] pt = (poly_eval(x_form, values), poly_eval(y_form, values)) family_pts.append(pt) dmin, qlit = min((abs(pt[0] - q[0]) + abs(pt[1] - q[1]), q) for q in orbit) assert dmin <= TOL, (f"orbit {k} slot {s}: family point ({float(pt[0]):.15f}, " f"{float(pt[1]):.15f}) has no literal within {float(TOL):.0e} " f"(nearest distance {float(dmin):.2e}; orbit literals " f"{[(float(q[0]), float(q[1])) for q in orbit]})") lit_of.append(qlit) print(f"3. family built: {len(family_pts)} points from integer-coefficient slot forms; " "literals matched to slots") triples = list(combinations(range(12), 3)) polys, lit_areas, lit_signs = {}, {}, {} for t in triples: fa, fb, fc = family_pts[t[0]], family_pts[t[1]], family_pts[t[2]] polys[t] = doubled_poly(forms[t[0] // 4][t[0] % 4], forms[t[1] // 4][t[1] % 4], forms[t[2] // 4][t[2] % 4]) assert poly_eval(polys[t], values) == (fb[0] - fa[0]) * (fc[1] - fa[1]) - (fc[0] - fa[0]) * (fb[1] - fa[1]) p0, p1, p2 = lit_of[t[0]], lit_of[t[1]], lit_of[t[2]] d = (p1[0] - p0[0]) * (p2[1] - p0[1]) - (p2[0] - p0[0]) * (p1[1] - p0[1]) lit_areas[t], lit_signs[t] = abs(d), (1 if d > 0 else -1) print(f"4. {len(triples)} doubled-area polynomials over Z[a, b, px, py]; evaluation matches " "the family points exactly (all 220 checked)") lit_min = min(lit_areas.values()) active = [t for t, v in lit_areas.items() if v - lit_min <= Fraction(1, 10**24)] spread = max(lit_areas[t] for t in active) - lit_min print(f"5. exact minimum doubled area at the literals {float(lit_min):.16f}; active triangles " f"{len(active)}: {active}, cluster spread {float(spread):.3e}") G = [] for name in PARAMS: row = [] for t in active: g = poly_grad_at(polys[t], values) row.append(lit_signs[t] * g.get(name, ZERO)) G.append(row) basis = nullspace(G) print(f"6. KKT: {len(PARAMS)} stationarity equations x {len(active)} active gradients; " f"nullspace dimension {len(basis)}") holds = False for vec in basis: if all(v >= 0 for v in vec) and any(v > 0 for v in vec): weights = [v / sum(vec) for v in vec] holds = True elif all(v <= 0 for v in vec) and any(v < 0 for v in vec): weights = [-v / sum(vec) for v in vec] holds = True else: weights = None print(f" kernel vector {[float(v) for v in vec]}" + (f" -> nonnegative weights {[float(w) for w in weights]}" if weights else " -> mixed signs, not a KKT combination")) if holds: t_star = lit_min / 2 residual = 64 * t_star**3 + 80 * t_star**2 + 28 * t_star - 1 print(f"7. KKT HOLDS: the record point is stationary for the family maximum. " f"Activation t = {float(t_star):.17f}; cubic residual 64t^3+80t^2+28t-1 at t: " f"{float(residual):.3e} (zero to the literals' 30-digit precision, i.e. t is the " "record's defining-cubic root)") else: print("7. KKT FAILS: no nonnegative combination of the active gradients vanishes -> " "an ascent direction exists inside the family; the record is beatable there") if len(sys.argv) > 2 and holds: outdir = Path(sys.argv[2]) outdir.mkdir(parents=True, exist_ok=True) lines = [] for pt in family_pts: lines.append(f"{pt[0].numerator}/{pt[0].denominator} {pt[1].numerator}/{pt[1].denominator}") (outdir / "n12.txt").write_text("\n".join(lines) + "\n") print(f"8. wrote the exactly-orbit-closed family point at the record parameters to " f"{outdir / 'n12.txt'} (30-digit literals as exact rationals)") if __name__ == "__main__": main()