Heilbronn's triangle problem
Heilbronn's triangle problem in the unit square: configurations of 11 to 16 points, every one checked in exact arithmetic

| 1 | #!/usr/bin/env python3 |
| 2 | """Full-space exact KKT map of the record configurations, n = 11 to 16 (issue #8). |
| 3 | |
| 4 | For each record configuration (Tej Stead's table literals), decide in the full |
| 5 | 2n-dimensional space whether it is a local maximum of the smallest-triangle area |
| 6 | over the unit square's box: |
| 7 | |
| 8 | active set all triangles whose doubled area ties the exact minimum (the |
| 9 | cluster is cut where the gap structure jumps; the cut is reported); |
| 10 | gradients exact rational partials of the signed doubled areas; |
| 11 | LP max t s.t. s_i grad_i . d >= t for every active triangle, |
| 12 | with d_j in [0, 1] for coordinates pinned at 0, [-1, 0] at 1, |
| 13 | [-1, 1] interior; |
| 14 | verdict t* > margin => a feasible ascent direction exists: the record |
| 15 | configuration is NOT a local maximum, and a record chase is |
| 16 | justified (the direction is then verified in exact arithmetic); |
| 17 | t* <= margin => the record point is first-order stationary: |
| 18 | searches around it cannot beat it, do not search there. |
| 19 | |
| 20 | For stationary cases the script attempts an exact rational certificate: solve for |
| 21 | nonnegative weights on the LP's support from the interior-coordinate equations and |
| 22 | the normalization, then check the boundary sign conditions exactly. |
| 23 | |
| 24 | Usage: kkt_map.py FILE:n ... (e.g. 11:/tmp/stead-n11.txt 12:/tmp/stead-n12.txt) |
| 25 | """ |
| 26 | |
| 27 | import json |
| 28 | import sys |
| 29 | from fractions import Fraction |
| 30 | from itertools import combinations |
| 31 | from pathlib import Path |
| 32 | |
| 33 | import numpy as np |
| 34 | from scipy.optimize import linprog |
| 35 | |
| 36 | ZERO, ONE = Fraction(0), Fraction(1) |
| 37 | |
| 38 | |
| 39 | def load_points(path): |
| 40 | pts = [tuple(map(Fraction, line.split())) for line in Path(path).read_text().splitlines() |
| 41 | if line.strip() and not line.lstrip().startswith("#")] |
| 42 | return pts |
| 43 | |
| 44 | |
| 45 | def doubled_area(a, b, c): |
| 46 | return (b[0] - a[0]) * (c[1] - a[1]) - (c[0] - a[0]) * (b[1] - a[1]) |
| 47 | |
| 48 | |
| 49 | def grad_doubled(a, b, c): |
| 50 | """Partial derivatives of D(a, b, c) w.r.t. the six coordinates, exact.""" |
| 51 | return { |
| 52 | (a, 0): b[1] - c[1], (a, 1): c[0] - b[0], |
| 53 | (b, 0): c[1] - a[1], (b, 1): a[0] - c[0], |
| 54 | (c, 0): a[1] - b[1], (c, 1): b[0] - a[0], |
| 55 | } |
| 56 | |
| 57 | |
| 58 | def solve_exact(rows, rhs): |
| 59 | """Solve rows * w = rhs exactly (square or overdetermined); None if inconsistent.""" |
| 60 | aug = [row + [rhs[i]] for i, row in enumerate(rows)] |
| 61 | cols = len(rows[0]) |
| 62 | for c in range(cols): |
| 63 | pivot = next((i for i in range(c, len(aug)) if aug[i][c] != 0), None) |
| 64 | if pivot is None: |
| 65 | continue |
| 66 | aug[c], aug[pivot] = aug[pivot], aug[c] |
| 67 | unit = [v / aug[c][c] for v in aug[c]] |
| 68 | aug[c] = unit |
| 69 | for i, row in enumerate(aug): |
| 70 | if i != c and row[c]: |
| 71 | f = row[c] |
| 72 | aug[i] = [a - f * b for a, b in zip(row, unit)] |
| 73 | w = [aug[i][cols] for i in range(cols)] |
| 74 | for i, row in enumerate(rows): |
| 75 | if sum(a * b for a, b in zip(row, w)) != rhs[i]: |
| 76 | return None |
| 77 | return w |
| 78 | |
| 79 | |
| 80 | def analyze(n, path): |
| 81 | points = load_points(path) |
| 82 | triples = list(combinations(range(n), 3)) |
| 83 | areas, signs = {}, {} |
| 84 | for t in triples: |
| 85 | d = doubled_area(*(points[i] for i in t)) |
| 86 | areas[t], signs[t] = abs(d), (1 if d > 0 else -1) |
| 87 | m = min(areas.values()) |
| 88 | gaps = sorted(set(v - m for v in areas.values())) |
| 89 | # cut the active cluster where the gap structure jumps past 1e-13 |
| 90 | cut = next((g for g in gaps if g > Fraction(1, 10**13)), None) |
| 91 | active = [t for t, v in areas.items() if v - m < (cut if cut is not None else ONE)] |
| 92 | below_cut = [float(g) for g in gaps if g < (cut if cut is not None else ONE)] |
| 93 | next_gap = float(cut) if cut is not None else float("inf") |
| 94 | interior = [i for i in range(n) if 0 < points[i][0] < 1 or 0 < points[i][1] < 1] |
| 95 | boundary_count = 2 * n - sum(1 for i in range(n) for axis in (0, 1) |
| 96 | if 0 < points[i][axis] < 1) |
| 97 | |
| 98 | G = [] |
| 99 | for t in active: |
| 100 | p = {key: signs[t] * v for key, v in grad_doubled(*(points[i] for i in t)).items()} |
| 101 | row = [] |
| 102 | for i in range(n): |
| 103 | for axis in (0, 1): |
| 104 | row.append(p.get((points[i], axis), ZERO)) |
| 105 | G.append(row) |
| 106 | |
| 107 | # LP: max t s.t. grad_i . d >= t, coordinate-dependent bounds on d |
| 108 | Gm = np.array([[float(v) for v in row] for row in G]) |
| 109 | lo, hi = [], [] |
| 110 | for i in range(n): |
| 111 | for axis in (0, 1): |
| 112 | x = points[i][axis] |
| 113 | if x == ZERO: |
| 114 | lo.append(0.0); hi.append(1.0) |
| 115 | elif x == ONE: |
| 116 | lo.append(-1.0); hi.append(0.0) |
| 117 | else: |
| 118 | lo.append(-1.0); hi.append(1.0) |
| 119 | A_ub = np.hstack([-Gm, np.ones((len(active), 1))]) |
| 120 | res = linprog(c=np.array([0.0] * (2 * n) + [-1.0]), A_ub=A_ub, |
| 121 | b_ub=np.zeros(len(active)), |
| 122 | bounds=list(zip(lo, hi)) + [(None, None)], method="highs") |
| 123 | t_star = float(res.x[-1]) if res.success else None |
| 124 | return dict(n=n, points=points, triples=triples, areas=areas, m=m, active=active, |
| 125 | below_cut=below_cut, next_gap=next_gap, boundary_count=boundary_count, |
| 126 | G=G, signs=signs, res=res, t_star=t_star, lo=lo, hi=hi) |
| 127 | |
| 128 | |
| 129 | def finite_difference_check(inst, eps=Fraction(1, 10**15)): |
| 130 | points = inst["points"] |
| 131 | worst = 0.0 |
| 132 | for t in inst["active"][:10]: |
| 133 | row = inst["G"][inst["active"].index(t)] |
| 134 | for idx in range(2 * inst["n"]): |
| 135 | i, axis = idx // 2, idx % 2 |
| 136 | plus = [list(p) for p in points]; plus[i][axis] += eps |
| 137 | minus = [list(p) for p in points]; minus[i][axis] -= eps |
| 138 | fd = inst["signs"][t] * (doubled_area(tuple(plus[t[0]]), tuple(plus[t[1]]), tuple(plus[t[2]])) |
| 139 | - doubled_area(tuple(minus[t[0]]), tuple(minus[t[1]]), tuple(minus[t[2]])) |
| 140 | ) / (2 * eps) |
| 141 | worst = max(worst, abs(float(fd - row[idx]))) |
| 142 | assert worst < 1e-6, f"finite-difference check failed: {worst}" |
| 143 | return worst |
| 144 | |
| 145 | |
| 146 | def certificate(inst): |
| 147 | """Exact rational weights on the LP support, or None.""" |
| 148 | points, active, G = inst["points"], inst["active"], inst["G"] |
| 149 | w_float = np.zeros(len(active)) |
| 150 | marg = inst["res"].ineqlin.marginals # <= 0 for <=-rows |
| 151 | w_float = -np.array(marg, dtype=float) |
| 152 | if w_float.sum() <= 0: |
| 153 | return None |
| 154 | w_float = w_float / w_float.sum() |
| 155 | support = [j for j, w in enumerate(w_float) if w > 1e-10] |
| 156 | if not support: |
| 157 | return None |
| 158 | interior_rows = [] |
| 159 | for i in range(inst["n"]): |
| 160 | for axis in (0, 1): |
| 161 | x = points[i][axis] |
| 162 | if ZERO < x < ONE: |
| 163 | interior_rows.append([G[j][2 * i + axis] for j in support]) |
| 164 | rows = interior_rows + [[ONE] * len(support)] |
| 165 | rhs = [ZERO] * len(interior_rows) + [ONE] |
| 166 | if len(rows) < len(support): |
| 167 | return None |
| 168 | w = solve_exact(rows, rhs) |
| 169 | if w is None or any(v <= 0 for v in w): |
| 170 | return None |
| 171 | # boundary sign conditions, exactly |
| 172 | for i in range(inst["n"]): |
| 173 | for axis in (0, 1): |
| 174 | x = points[i][axis] |
| 175 | g = sum(w[j] * G[support[j]][2 * i + axis] for j in range(len(support))) |
| 176 | if x == ZERO and g > 0: |
| 177 | return None |
| 178 | if x == ONE and g < 0: |
| 179 | return None |
| 180 | return support, w |
| 181 | |
| 182 | |
| 183 | def main(): |
| 184 | sys.set_int_max_str_digits(200000) # 200-digit record literals give huge exact weights |
| 185 | instances = [] |
| 186 | for arg in sys.argv[1:]: |
| 187 | n, path = arg.split(":") |
| 188 | instances.append((int(n), path)) |
| 189 | results = [] |
| 190 | for n, path in instances: |
| 191 | inst = analyze(n, path) |
| 192 | fd = finite_difference_check(inst) |
| 193 | t = inst["t_star"] |
| 194 | verdict = "ASCENT (not a local max)" if t is not None and t > 1e-10 else \ |
| 195 | "STATIONARY (do not search here)" if t is not None else "LP failed" |
| 196 | cert = None |
| 197 | if verdict.startswith("STATIONARY"): |
| 198 | cert = certificate(inst) |
| 199 | print(f"n = {n}: active {len(inst['active'])} (max tie spread " |
| 200 | f"{max(inst['below_cut']):.2e}; next gap {inst['next_gap']:.2e}), " |
| 201 | f"boundary coords {inst['boundary_count']}/{2 * n}, LP t* = {t:.3e}, " |
| 202 | f"FD check {fd:.1e}") |
| 203 | print(f" verdict: {verdict}") |
| 204 | if cert: |
| 205 | support, w = cert |
| 206 | print(f" exact certificate: {len(support)} positive rational weights, " |
| 207 | f"e.g. {[float(v) for v in w[:4]]}..., boundary conditions exact") |
| 208 | elif verdict.startswith("STATIONARY"): |
| 209 | print(" exact certificate: not extracted (support/interior mismatch); " |
| 210 | "LP decision stands on its margins") |
| 211 | entry = {"n": n, "t_star": t, "active": len(inst["active"]), |
| 212 | "boundary": inst["boundary_count"], "verdict": verdict, |
| 213 | "exact_certificate": bool(cert)} |
| 214 | if cert: |
| 215 | support, w = cert |
| 216 | entry["weights"] = [[w[j].numerator, w[j].denominator] for j in range(len(w))] |
| 217 | entry["support"] = [list(inst["active"][support[j]]) for j in range(len(support))] |
| 218 | results.append(entry) |
| 219 | print(json.dumps(results, indent=1)) |
| 220 | out = Path(__file__).resolve().parent / "kkt-map.json" |
| 221 | out.write_text(json.dumps(results, indent=1)) |
| 222 | print(f"wrote {out}") |
| 223 | |
| 224 | |
| 225 | if __name__ == "__main__": |
| 226 | main() |