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

issue 7: search.py - stratified starts, epigraph SLSQP, clearance relocation
Browse filesChecks
verify Program
Details
+188 −0 routes/zcodezp1-n13-search/search.py added View file
| @@ -0,0 +1,188 @@ | ||
| 1 | +#!/usr/bin/env python3 | |
| 2 | +"""Own search for n = 13, issue #7 (zcode-zp1, 2026-11-28). | |
| 3 | + | |
| 4 | +From-scratch only by default: starts are stratified random, no literature or | |
| 5 | +route coordinates are fed in. Design ideas credited to prior routes, each | |
| 6 | +reimplemented here: stratified starts and clearance-guided relocation from | |
| 7 | +hongdy22-codex-n15-search; the orientation-sign-fixed max-min refinement with | |
| 8 | +analytic signed-area Jacobians from wangyuan-mac/n13-search; annealing | |
| 9 | +acceptance and periodic restarts as in both. | |
| 10 | + | |
| 11 | +Usage: | |
| 12 | + search.py --seconds S --seed N [--start FILE] [--out PREFIX] | |
| 13 | + [--workers K] [--start-credit NOTE] | |
| 14 | + | |
| 15 | +--start FILE optionally seeds every track from a 13-line configuration (its | |
| 16 | +provenance must be stated in --start-credit and in the route notes). | |
| 17 | +""" | |
| 18 | + | |
| 19 | +import argparse | |
| 20 | +import json | |
| 21 | +import time | |
| 22 | +from itertools import combinations | |
| 23 | +from pathlib import Path | |
| 24 | + | |
| 25 | +import numpy as np | |
| 26 | +from scipy.optimize import minimize | |
| 27 | + | |
| 28 | +N = 13 | |
| 29 | +TRIPLES = np.array(list(combinations(range(N), 3))) | |
| 30 | +A_IDX, B_IDX, C_IDX = TRIPLES.T | |
| 31 | +NTRIPLES = len(TRIPLES) | |
| 32 | +BOUNDS = [(0.0, 1.0)] * (2 * N) + [(1e-12, 0.7)] | |
| 33 | +OBJ_JAC = np.zeros(2 * N + 1) | |
| 34 | +OBJ_JAC[-1] = -1.0 | |
| 35 | + | |
| 36 | + | |
| 37 | +def doubled_areas(points): | |
| 38 | + """Signed doubled areas of all 286 triangles, vectorized.""" | |
| 39 | + a, b, c = points[A_IDX], points[B_IDX], points[C_IDX] | |
| 40 | + return ((b[:, 0] - a[:, 0]) * (c[:, 1] - a[:, 1]) | |
| 41 | + - (c[:, 0] - a[:, 0]) * (b[:, 1] - a[:, 1])) | |
| 42 | + | |
| 43 | + | |
| 44 | +def area_jacobian(points): | |
| 45 | + """d(doubled area of triple t)/d(coordinate) as a (NTRIPLES, 2N+1) matrix. | |
| 46 | + | |
| 47 | + D = (bx-ax)(cy-ay) - (cx-ax)(by-ay) is bilinear; with the other | |
| 48 | + coordinates fixed each partial is linear in the moved coordinate: | |
| 49 | + d/d(ax) = by - cy d/d(ay) = cx - bx | |
| 50 | + d/d(bx) = cy - ay d/d(by) = ax - cx | |
| 51 | + d/d(cx) = ay - by d/d(cy) = bx - ax | |
| 52 | + (checked at startup against finite differences). | |
| 53 | + """ | |
| 54 | + a, b, c = points[A_IDX], points[B_IDX], points[C_IDX] | |
| 55 | + jac = np.zeros((NTRIPLES, 2 * N + 1)) | |
| 56 | + jac[np.arange(NTRIPLES), 2 * A_IDX] = b[:, 1] - c[:, 1] | |
| 57 | + jac[np.arange(NTRIPLES), 2 * A_IDX + 1] = c[:, 0] - b[:, 0] | |
| 58 | + jac[np.arange(NTRIPLES), 2 * B_IDX] = c[:, 1] - a[:, 1] | |
| 59 | + jac[np.arange(NTRIPLES), 2 * B_IDX + 1] = a[:, 0] - c[:, 0] | |
| 60 | + jac[np.arange(NTRIPLES), 2 * C_IDX] = a[:, 1] - b[:, 1] | |
| 61 | + jac[np.arange(NTRIPLES), 2 * C_IDX + 1] = b[:, 0] - a[:, 0] | |
| 62 | + return jac | |
| 63 | + | |
| 64 | + | |
| 65 | +def selftest(rng, eps=1e-7): | |
| 66 | + points = stratified_start(rng) | |
| 67 | + for _ in range(20): | |
| 68 | + moved = points.copy() | |
| 69 | + v, axis = rng.integers(N), rng.integers(2) | |
| 70 | + moved[v, axis] += eps * (1 if rng.random() < 0.5 else -1) | |
| 71 | + numeric = (doubled_areas(moved) - doubled_areas(points)) / (moved[v, axis] - points[v, axis]) | |
| 72 | + analytic = area_jacobian(points)[:, 2 * v + axis] | |
| 73 | + assert np.abs(numeric - analytic).max() < 1e-6, "jacobian selftest failed" | |
| 74 | + | |
| 75 | + | |
| 76 | +def stratified_start(rng): | |
| 77 | + """One point per x and y stratum, jittered, scaled back into the square.""" | |
| 78 | + pts = (np.column_stack((rng.permutation(N), rng.permutation(N))) + rng.random((N, 2))) / N | |
| 79 | + return (pts - pts.min(axis=0)) / (pts.max(axis=0) - pts.min(axis=0)) | |
| 80 | + | |
| 81 | + | |
| 82 | +def refine(points, signs, maxiter=250): | |
| 83 | + """Maximize the smallest sign-fixed signed doubled area (epigraph SLSQP).""" | |
| 84 | + d0 = signs * doubled_areas(points) | |
| 85 | + z0 = np.r_[points.ravel(), d0.min()] | |
| 86 | + | |
| 87 | + def con_fun(z, s=signs): | |
| 88 | + return s * doubled_areas(z[:2 * N].reshape(N, 2)) - z[-1] | |
| 89 | + | |
| 90 | + def con_jac(z, s=signs): | |
| 91 | + jac = s[:, None] * area_jacobian(z[:2 * N].reshape(N, 2)) | |
| 92 | + jac[:, -1] = -1.0 | |
| 93 | + return jac | |
| 94 | + | |
| 95 | + cons = [{"type": "ineq", "fun": con_fun, "jac": con_jac}] | |
| 96 | + result = minimize(lambda z: -z[-1], z0, jac=lambda z: OBJ_JAC, | |
| 97 | + bounds=BOUNDS, constraints=cons, method="SLSQP", | |
| 98 | + options={"maxiter": maxiter, "ftol": 1e-14}) | |
| 99 | + fitted = np.clip(result.x[:2 * N].reshape(N, 2), 0.0, 1.0) | |
| 100 | + return fitted | |
| 101 | + | |
| 102 | + | |
| 103 | +def relocate(points, rng, probes=192): | |
| 104 | + """Reposition a point of a smallest triangle by clearance from pair lines.""" | |
| 105 | + d = np.abs(doubled_areas(points)) | |
| 106 | + worst = np.flatnonzero(d <= d.min() + 1e-12) | |
| 107 | + triple = TRIPLES[rng.choice(worst)] | |
| 108 | + index = int(rng.choice(triple)) | |
| 109 | + fixed = np.delete(points, index, axis=0) | |
| 110 | + first, second = fixed[np.array(list(combinations(range(N - 1), 2)))].transpose(1, 0, 2) | |
| 111 | + dx, dy = second[:, 0] - first[:, 0], second[:, 1] - first[:, 1] | |
| 112 | + norms = np.hypot(dx, dy) | |
| 113 | + keep = norms > 1e-12 | |
| 114 | + nx, ny = (-dy[keep] / norms[keep]), (dx[keep] / norms[keep]) | |
| 115 | + off = nx * first[keep, 0] + ny * first[keep, 1] | |
| 116 | + trial = rng.random((probes, 2)) | |
| 117 | + clear = np.abs(trial[:, 0, None] * nx + trial[:, 1, None] * ny - off).min(axis=1) | |
| 118 | + near = np.linalg.norm(trial[:, None, :] - fixed[None, :, :], axis=2).min(axis=1) | |
| 119 | + clear[near < 0.04] = -1.0 | |
| 120 | + best = int(np.argmax(clear)) | |
| 121 | + moved = points.copy() | |
| 122 | + moved[index] = trial[best] | |
| 123 | + return moved, index | |
| 124 | + | |
| 125 | + | |
| 126 | +def run_track(seed, seconds, start=None): | |
| 127 | + rng = np.random.default_rng(seed) | |
| 128 | + selftest(rng) | |
| 129 | + start_time = time.monotonic() | |
| 130 | + deadline = start_time + seconds | |
| 131 | + scales = [0.12, 0.06, 0.03, 0.015] | |
| 132 | + temps = [0.002, 0.0004, 0.00005] | |
| 133 | + current = stratified_start(rng) if start is None else start.copy() | |
| 134 | + current = refine(current, np.where(doubled_areas(current) < 0, -1.0, 1.0)) | |
| 135 | + current_score = float(np.abs(doubled_areas(current)).min()) | |
| 136 | + best, best_score, best_attempt = current.copy(), current_score, 0 | |
| 137 | + completed = accepted = improving = 0 | |
| 138 | + log = [] | |
| 139 | + while time.monotonic() < deadline: | |
| 140 | + completed += 1 | |
| 141 | + if completed == 1 or completed % 15 == 0: | |
| 142 | + attempt = stratified_start(rng) | |
| 143 | + elif completed % 4 == 0: | |
| 144 | + attempt, _ = relocate(current, rng) | |
| 145 | + else: | |
| 146 | + attempt = current.copy() | |
| 147 | + for v in rng.choice(N, size=int(rng.integers(1, 5)), replace=False): | |
| 148 | + attempt[v] += rng.normal(0.0, scales[completed % len(scales)], size=2) | |
| 149 | + attempt = np.clip(attempt, 0.0, 1.0) | |
| 150 | + fitted = refine(attempt, np.where(doubled_areas(attempt) < 0, -1.0, 1.0)) | |
| 151 | + score = float(np.abs(doubled_areas(fitted)).min()) | |
| 152 | + completed_note = completed | |
| 153 | + if score > best_score: | |
| 154 | + best, best_score, best_attempt = fitted.copy(), score, completed_note | |
| 155 | + improving += 1 | |
| 156 | + log.append({"attempt": completed_note, "area": score}) | |
| 157 | + print(f"improvement at attempt {completed_note}: {score:.13f}", flush=True) | |
| 158 | + temperature = temps[completed % len(temps)] | |
| 159 | + if score >= current_score or rng.random() < np.exp((score - current_score) / temperature): | |
| 160 | + current, current_score = fitted, score | |
| 161 | + accepted += 1 | |
| 162 | + return {"seed": int(seed), "seconds": round(time.monotonic() - start_time, 3), | |
| 163 | + "attempts": completed, "accepted": accepted, "improvements": improving, | |
| 164 | + "best_attempt": best_attempt, "best_area": best_score, | |
| 165 | + "coordinates": [f"{x:.17g} {y:.17g}" for x, y in best], "log": log[-12:]} | |
| 166 | + | |
| 167 | + | |
| 168 | +def main(): | |
| 169 | + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) | |
| 170 | + parser.add_argument("--seconds", type=float, required=True) | |
| 171 | + parser.add_argument("--seed", type=int, required=True) | |
| 172 | + parser.add_argument("--start", type=Path, default=None) | |
| 173 | + parser.add_argument("--start-credit", default="") | |
| 174 | + parser.add_argument("--out", default="") | |
| 175 | + args = parser.parse_args() | |
| 176 | + start = np.loadtxt(args.start).reshape(N, 2) if args.start else None | |
| 177 | + if args.start: | |
| 178 | + print(f"start credit: {args.start_credit}", flush=True) | |
| 179 | + result = run_track(args.seed, args.seconds, start) | |
| 180 | + result["start_credit"] = args.start_credit | |
| 181 | + text = json.dumps(result, indent=1) | |
| 182 | + if args.out: | |
| 183 | + Path(args.out).write_text(text) | |
| 184 | + print(text) | |
| 185 | + | |
| 186 | + | |
| 187 | +if __name__ == "__main__": | |
| 188 | + main() | |