#!/usr/bin/env python3 """The decisive test for issue #8's quarter-turn-family question. Asks whether 0 lies in the convex hull of the active signed-area gradients at the record point (KKT / first-order family-optimality), with exact rational verification of the LP's answer in both directions: - if 0 IS in the hull, an exact rational weight vector is produced (support solved in Fractions), and the activation value is checked against the record's defining cubic - the family maximum is stationary at the record; - if 0 is NOT in the hull, the separating direction is an ascent direction: the script then maximizes the family minimum along it and beyond (SLSQP on the 4-parameter family), and if the family's exact minimum exceeds the record's, writes a candidate configuration for a new record. Usage: conv_test.py STEAD-n12.txt """ import sys from collections import OrderedDict from fractions import Fraction from itertools import combinations from pathlib import Path import numpy as np from scipy.optimize import linprog, minimize sys.path.insert(0, str(Path(__file__).resolve().parent)) from family_max import (ZERO, ONE, TOL, PARAMS, load_points, build_orbits, affine, poly_mul, poly_sub, poly_eval, poly_grad_at, nullspace) def doubled_poly(ca, cb, cc): 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 orbit_forms(rep, name): rx, ry = rep if ry == ZERO: A = affine((name, ONE)) C1, C0 = affine(ONE), affine(ZERO) 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(ONE), affine(ZERO) 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))] def setup(path): points = load_points(path) orbits = build_orbits(points) rep_list = [] 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: rep_list.append((None, orbit)) rep_list.sort(key=lambda item: item[0] is None) orbit = rep_list[2][1] rep_list[2] = (next(p for p in orbit if 0 < p[0] < 1 and 0 < p[1] < 1), orbit) reps = [rep for rep, _ in rep_list] values = {"a": reps[0][0], "b": reps[1][0], "px": reps[2][0], "py": reps[2][1]} names = ["a", "b", None] forms = [orbit_forms(rep, name) for rep, name in zip(reps, names)] family_pts, lit_of = [], [] for k, (rep, orb) in enumerate(rep_list): for s in range(4): pt = (poly_eval(forms[k][s][0], values), poly_eval(forms[k][s][1], values)) family_pts.append(pt) lit_of.append(min(orb, key=lambda q: abs(pt[0] - q[0]) + abs(pt[1] - q[1]))) triples = list(combinations(range(12), 3)) polys, lit_areas, lit_signs = {}, {}, {} for t in triples: 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]) 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) lit_min = min(lit_areas.values()) active = [t for t, v in lit_areas.items() if v - lit_min <= Fraction(1, 10**24)] grads = {} for name in PARAMS: for t in active: grads.setdefault(t, {})[name] = lit_signs[t] * poly_grad_at(polys[t], values).get(name, ZERO) return values, polys, lit_areas, lit_min, active, grads, family_pts def main(): values, polys, lit_areas, lit_min, active, grads, family_pts = setup(sys.argv[1]) print(f"active triangles {len(active)}, exact minimum doubled area {float(lit_min):.16f}") # group identical gradient columns (symmetric twins share one) groups = OrderedDict() for t in active: col = tuple(grads[t][name] for name in PARAMS) groups.setdefault(col, []).append(t) cols = list(groups.keys()) print(f"distinct gradient columns: {len(cols)} (twins grouped: " f"{[[groups[c][:2]] for c in cols if len(groups[c]) > 1]})") C = np.array([[float(col[r]) for col in cols] for r in range(4)]) A_eq = np.vstack([C, np.ones((1, len(cols)))]) b_eq = np.array([0.0] * 4 + [1.0]) res = linprog(c=np.zeros(len(cols)), A_eq=A_eq, b_eq=b_eq, bounds=[(0, None)] * len(cols), method="highs") print(f"LP 0-in-hull: {'feasible' if res.success else 'INFEASIBLE'}") if res.success: support = [j for j, w in enumerate(res.x) if w > 1e-10] print(f"LP support columns {support} (weights {[float(res.x[j]) for j in support]})") # exact solve: G_g w = 0 on the support with sum(w) = 1 (square system if the # support has exactly as many columns as rows + 1, else nullspace) rows = [[cols[j][r] for j in support] for r in range(4)] + [[ONE] * len(support)] rhs = [ZERO] * 4 + [ONE] # Gaussian elimination on [rows | rhs] aug = [row + [rhs[i]] for i, row in enumerate(rows)] n = len(support) rank_consistent = True for c in range(n): pivot = next((i for i in range(c, len(aug)) if aug[i][c] != 0), None) if pivot is None: rank_consistent = False break aug[c], aug[pivot] = aug[pivot], aug[c] unit = [v / aug[c][c] for v in aug[c]] aug[c] = unit for i, row in enumerate(aug): if i != c and row[c]: f = row[c] aug[i] = [a - f * b for a, b in zip(row, unit)] exact_w = None if rank_consistent: w = [aug[i][n] for i in range(n)] if all(v > 0 for v in w): exact_w = w if exact_w is None: print("no strictly positive exact weight vector on the LP support; " "try a different support or report the near-boundary case") return residual = [sum(exact_w[j] * cols[support[j]][r] for j in range(len(support))) for r in range(4)] assert all(v == 0 for v in residual), residual print(f"KKT HOLDS EXACTLY: weights {[float(w) for w in exact_w]} on columns " f"{support}, stationarity residual exactly 0") t_star = lit_min / 2 cubic = 64 * t_star**3 + 80 * t_star**2 + 28 * t_star - 1 print(f"activation t = {float(t_star):.17f}; cubic residual {float(cubic):.3e} " "-> t is the record's defining-cubic root (to the literals' precision)") print("CONCLUSION: the record point is a stationary point of the family maximum; " "beating the record requires leaving the quarter-turn family") return # separating/ascent direction: maximize t s.t. grad_i . d >= t (all active), |d| <= 1 Gm = np.array([[float(grads[t][name]) for name in PARAMS] for t in active]) A_ub = np.hstack([-Gm, np.ones((len(active), 1))]) # G.d - t <= 0 b_ub = np.zeros(len(active)) c = np.array([0.0, 0.0, 0.0, 0.0, -1.0]) # maximize t bounds = [(-1, 1)] * 4 + [(None, None)] res = linprog(c=c, A_ub=A_ub, b_ub=b_ub, bounds=bounds, method="highs") assert res.success d, t_star = res.x[:4], res.x[4] print(f"ascent direction d = {[float(v) for v in d]}, min signed-area increase t = {t_star:.6f}") if t_star <= 1e-9: print("ascent margin at float noise level: the point is degenerate; refine first") return # chase: exact family evaluation at params + step * d, exact rational arithmetic def exact_min_at(params): areas = [abs(poly_eval(polys[t], params)) for t in polys] return min(areas) step = Fraction(1, 1000) best = None for k in range(1, 60): trial = dict(values) for name, dv in zip(PARAMS, d): trial[name] = values[name] + Fraction(int(round(dv * k * 1000)), 1000 * (1 if dv >= 0 else 1)) \ if False else values[name] + Fraction(int(round(dv * 10**9)) * k, 1000 * 10**9) m = exact_min_at(trial) if best is None or m > best[1]: best = (dict(trial), m, k) if m > lit_min: print(f"step {k}/1000: exact minimum doubled area {float(m):.16f} > record " f"{float(lit_min):.16f} - THE RECORD IS BEATABLE IN THE FAMILY") if best: print(f"best along the ray: step {best[2]}/1000, doubled area {float(best[1]):.16f} " f"(record {float(lit_min):.16f})") else: print("no improvement along the ray despite positive LP margin - investigate") if __name__ == "__main__": main()