#!/usr/bin/env python3 """Full-space exact KKT map of the record configurations, n = 11 to 16 (issue #8). For each record configuration (Tej Stead's table literals), decide in the full 2n-dimensional space whether it is a local maximum of the smallest-triangle area over the unit square's box: active set all triangles whose doubled area ties the exact minimum (the cluster is cut where the gap structure jumps; the cut is reported); gradients exact rational partials of the signed doubled areas; LP max t s.t. s_i grad_i . d >= t for every active triangle, with d_j in [0, 1] for coordinates pinned at 0, [-1, 0] at 1, [-1, 1] interior; verdict t* > margin => a feasible ascent direction exists: the record configuration is NOT a local maximum, and a record chase is justified (the direction is then verified in exact arithmetic); t* <= margin => the record point is first-order stationary: searches around it cannot beat it, do not search there. For stationary cases the script attempts an exact rational certificate: solve for nonnegative weights on the LP's support from the interior-coordinate equations and the normalization, then check the boundary sign conditions exactly. Usage: kkt_map.py FILE:n ... (e.g. 11:/tmp/stead-n11.txt 12:/tmp/stead-n12.txt) """ import json import sys from fractions import Fraction from itertools import combinations from pathlib import Path import numpy as np from scipy.optimize import linprog ZERO, ONE = Fraction(0), Fraction(1) 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("#")] return pts def doubled_area(a, b, c): return (b[0] - a[0]) * (c[1] - a[1]) - (c[0] - a[0]) * (b[1] - a[1]) def grad_doubled(a, b, c): """Partial derivatives of D(a, b, c) w.r.t. the six coordinates, exact.""" return { (a, 0): b[1] - c[1], (a, 1): c[0] - b[0], (b, 0): c[1] - a[1], (b, 1): a[0] - c[0], (c, 0): a[1] - b[1], (c, 1): b[0] - a[0], } def solve_exact(rows, rhs): """Solve rows * w = rhs exactly (square or overdetermined); None if inconsistent.""" aug = [row + [rhs[i]] for i, row in enumerate(rows)] cols = len(rows[0]) for c in range(cols): pivot = next((i for i in range(c, len(aug)) if aug[i][c] != 0), None) if pivot is None: continue 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)] w = [aug[i][cols] for i in range(cols)] for i, row in enumerate(rows): if sum(a * b for a, b in zip(row, w)) != rhs[i]: return None return w def analyze(n, path): points = load_points(path) triples = list(combinations(range(n), 3)) areas, signs = {}, {} for t in triples: d = doubled_area(*(points[i] for i in t)) areas[t], signs[t] = abs(d), (1 if d > 0 else -1) m = min(areas.values()) gaps = sorted(set(v - m for v in areas.values())) # cut the active cluster where the gap structure jumps past 1e-13 cut = next((g for g in gaps if g > Fraction(1, 10**13)), None) active = [t for t, v in areas.items() if v - m < (cut if cut is not None else ONE)] below_cut = [float(g) for g in gaps if g < (cut if cut is not None else ONE)] next_gap = float(cut) if cut is not None else float("inf") interior = [i for i in range(n) if 0 < points[i][0] < 1 or 0 < points[i][1] < 1] boundary_count = 2 * n - sum(1 for i in range(n) for axis in (0, 1) if 0 < points[i][axis] < 1) G = [] for t in active: p = {key: signs[t] * v for key, v in grad_doubled(*(points[i] for i in t)).items()} row = [] for i in range(n): for axis in (0, 1): row.append(p.get((points[i], axis), ZERO)) G.append(row) # LP: max t s.t. grad_i . d >= t, coordinate-dependent bounds on d Gm = np.array([[float(v) for v in row] for row in G]) lo, hi = [], [] for i in range(n): for axis in (0, 1): x = points[i][axis] if x == ZERO: lo.append(0.0); hi.append(1.0) elif x == ONE: lo.append(-1.0); hi.append(0.0) else: lo.append(-1.0); hi.append(1.0) A_ub = np.hstack([-Gm, np.ones((len(active), 1))]) res = linprog(c=np.array([0.0] * (2 * n) + [-1.0]), A_ub=A_ub, b_ub=np.zeros(len(active)), bounds=list(zip(lo, hi)) + [(None, None)], method="highs") t_star = float(res.x[-1]) if res.success else None return dict(n=n, points=points, triples=triples, areas=areas, m=m, active=active, below_cut=below_cut, next_gap=next_gap, boundary_count=boundary_count, G=G, signs=signs, res=res, t_star=t_star, lo=lo, hi=hi) def finite_difference_check(inst, eps=Fraction(1, 10**15)): points = inst["points"] worst = 0.0 for t in inst["active"][:10]: row = inst["G"][inst["active"].index(t)] for idx in range(2 * inst["n"]): i, axis = idx // 2, idx % 2 plus = [list(p) for p in points]; plus[i][axis] += eps minus = [list(p) for p in points]; minus[i][axis] -= eps fd = inst["signs"][t] * (doubled_area(tuple(plus[t[0]]), tuple(plus[t[1]]), tuple(plus[t[2]])) - doubled_area(tuple(minus[t[0]]), tuple(minus[t[1]]), tuple(minus[t[2]])) ) / (2 * eps) worst = max(worst, abs(float(fd - row[idx]))) assert worst < 1e-6, f"finite-difference check failed: {worst}" return worst def certificate(inst): """Exact rational weights on the LP support, or None.""" points, active, G = inst["points"], inst["active"], inst["G"] w_float = np.zeros(len(active)) marg = inst["res"].ineqlin.marginals # <= 0 for <=-rows w_float = -np.array(marg, dtype=float) if w_float.sum() <= 0: return None w_float = w_float / w_float.sum() support = [j for j, w in enumerate(w_float) if w > 1e-10] if not support: return None interior_rows = [] for i in range(inst["n"]): for axis in (0, 1): x = points[i][axis] if ZERO < x < ONE: interior_rows.append([G[j][2 * i + axis] for j in support]) rows = interior_rows + [[ONE] * len(support)] rhs = [ZERO] * len(interior_rows) + [ONE] if len(rows) < len(support): return None w = solve_exact(rows, rhs) if w is None or any(v <= 0 for v in w): return None # boundary sign conditions, exactly for i in range(inst["n"]): for axis in (0, 1): x = points[i][axis] g = sum(w[j] * G[support[j]][2 * i + axis] for j in range(len(support))) if x == ZERO and g > 0: return None if x == ONE and g < 0: return None return support, w def main(): sys.set_int_max_str_digits(200000) # 200-digit record literals give huge exact weights instances = [] for arg in sys.argv[1:]: n, path = arg.split(":") instances.append((int(n), path)) results = [] for n, path in instances: inst = analyze(n, path) fd = finite_difference_check(inst) t = inst["t_star"] verdict = "ASCENT (not a local max)" if t is not None and t > 1e-10 else \ "STATIONARY (do not search here)" if t is not None else "LP failed" cert = None if verdict.startswith("STATIONARY"): cert = certificate(inst) print(f"n = {n}: active {len(inst['active'])} (max tie spread " f"{max(inst['below_cut']):.2e}; next gap {inst['next_gap']:.2e}), " f"boundary coords {inst['boundary_count']}/{2 * n}, LP t* = {t:.3e}, " f"FD check {fd:.1e}") print(f" verdict: {verdict}") if cert: support, w = cert print(f" exact certificate: {len(support)} positive rational weights, " f"e.g. {[float(v) for v in w[:4]]}..., boundary conditions exact") elif verdict.startswith("STATIONARY"): print(" exact certificate: not extracted (support/interior mismatch); " "LP decision stands on its margins") entry = {"n": n, "t_star": t, "active": len(inst["active"]), "boundary": inst["boundary_count"], "verdict": verdict, "exact_certificate": bool(cert)} if cert: support, w = cert entry["weights"] = [[w[j].numerator, w[j].denominator] for j in range(len(w))] entry["support"] = [list(inst["active"][support[j]]) for j in range(len(support))] results.append(entry) print(json.dumps(results, indent=1)) out = Path(__file__).resolve().parent / "kkt-map.json" out.write_text(json.dumps(results, indent=1)) print(f"wrote {out}") if __name__ == "__main__": main()