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 | """Search 15-point configurations with point relocation and signed-area SLSQP.""" |
| 2 | |
| 3 | import argparse |
| 4 | import itertools |
| 5 | import json |
| 6 | import time |
| 7 | from concurrent.futures import FIRST_COMPLETED, ProcessPoolExecutor, wait |
| 8 | from fractions import Fraction |
| 9 | from pathlib import Path |
| 10 | |
| 11 | import numpy as np |
| 12 | import scipy |
| 13 | from scipy.optimize import minimize |
| 14 | |
| 15 | |
| 16 | N = 15 |
| 17 | TRACKS = ("deletion", "independent", "record") |
| 18 | TRIPLES = list(itertools.combinations(range(N), 3)) |
| 19 | I, J, K = np.array(TRIPLES).T |
| 20 | ROWS = np.arange(len(I)) |
| 21 | PAIR_I, PAIR_J = np.array(list(itertools.combinations(range(N - 1), 2))).T |
| 22 | BOUNDS = [(0.0, 1.0)] * (2 * N) + [(0.0, 0.5)] |
| 23 | OBJECTIVE_JAC = np.r_[np.zeros(2 * N), -1.0] |
| 24 | RECORD_NEXT_DIGIT = Fraction("0.0212105411") |
| 25 | |
| 26 | |
| 27 | def signed_area(points): |
| 28 | first = points[J] - points[I] |
| 29 | second = points[K] - points[I] |
| 30 | return (first[:, 0] * second[:, 1] - first[:, 1] * second[:, 0]) / 2 |
| 31 | |
| 32 | |
| 33 | def fitness(points): |
| 34 | return float(np.abs(signed_area(points)).min()) |
| 35 | |
| 36 | |
| 37 | def refine(points): |
| 38 | """Locally maximize the smallest area in the starting orientation class.""" |
| 39 | areas = signed_area(points) |
| 40 | signs = np.where(areas < 0, -1, 1) |
| 41 | signed_half = signs / 2 |
| 42 | initial = np.r_[points.ravel(), np.abs(areas).min()] |
| 43 | |
| 44 | def constraints(x): |
| 45 | return signs * signed_area(x[:-1].reshape(N, 2)) - x[-1] |
| 46 | |
| 47 | def jacobian(x): |
| 48 | p = x[:-1].reshape(N, 2) |
| 49 | ax, ay = p[I].T |
| 50 | bx, by = p[J].T |
| 51 | cx, cy = p[K].T |
| 52 | jac = np.zeros((len(I), 2 * N + 1)) |
| 53 | jac[ROWS, 2 * I] = signed_half * (by - cy) |
| 54 | jac[ROWS, 2 * I + 1] = signed_half * (cx - bx) |
| 55 | jac[ROWS, 2 * J] = signed_half * (cy - ay) |
| 56 | jac[ROWS, 2 * J + 1] = signed_half * (ax - cx) |
| 57 | jac[ROWS, 2 * K] = signed_half * (ay - by) |
| 58 | jac[ROWS, 2 * K + 1] = signed_half * (bx - ax) |
| 59 | jac[:, -1] = -1 |
| 60 | return jac |
| 61 | |
| 62 | solved = minimize( |
| 63 | lambda x: -x[-1], |
| 64 | initial, |
| 65 | jac=lambda x: OBJECTIVE_JAC, |
| 66 | bounds=BOUNDS, |
| 67 | constraints={"type": "ineq", "fun": constraints, "jac": jacobian}, |
| 68 | method="SLSQP", |
| 69 | options={"ftol": 2e-12, "maxiter": 70}, |
| 70 | ) |
| 71 | candidate = np.clip(solved.x[:-1].reshape(N, 2), 0, 1) |
| 72 | return max((points, candidate), key=fitness) |
| 73 | |
| 74 | |
| 75 | def stratified_start(rng): |
| 76 | """Sample one point in each x and y stratum and extend to the square.""" |
| 77 | points = (np.column_stack((rng.permutation(N), rng.permutation(N))) |
| 78 | + rng.random((N, 2))) / N |
| 79 | minimum = points.min(axis=0) |
| 80 | return (points - minimum) / (points.max(axis=0) - minimum) |
| 81 | |
| 82 | |
| 83 | def relocate(points, index, rng, probes=192): |
| 84 | """Sample alternate positions ranked by clearance from all fixed pair lines.""" |
| 85 | fixed = np.delete(points, index, axis=0) |
| 86 | first = fixed[PAIR_I] |
| 87 | dx, dy = (fixed[PAIR_J] - first).T |
| 88 | normals = np.column_stack((-dy, dx)) / 2 |
| 89 | offsets = np.einsum("ij,ij->i", normals, first) |
| 90 | trial_points = rng.random((probes, 2)) |
| 91 | trial_points[: probes // 2 : 2, 0] = rng.integers(2, size=probes // 4) |
| 92 | trial_points[1 : probes // 2 : 2, 1] = rng.integers(2, size=probes // 4) |
| 93 | trial_points = trial_points[np.linalg.norm(trial_points - points[index], axis=1) > 0.05] |
| 94 | if not len(trial_points): |
| 95 | return stratified_start(rng)[index] |
| 96 | signed = (trial_points[:, 0, None] * normals[:, 0] |
| 97 | + trial_points[:, 1, None] * normals[:, 1] - offsets) |
| 98 | clearance = np.abs(signed).min(axis=1) |
| 99 | return trial_points[np.argmax(clearance)] |
| 100 | |
| 101 | |
| 102 | def neighbor(points, rng, step): |
| 103 | new = points.copy() |
| 104 | if step % 3: |
| 105 | index = rng.integers(N) |
| 106 | new[index] = relocate(new, index, rng) |
| 107 | if step % 6 == 1: |
| 108 | index = rng.integers(N) |
| 109 | new[index] = relocate(new, index, rng) |
| 110 | else: |
| 111 | indices = rng.choice(N, size=1 + step % 4, replace=False) |
| 112 | scales = (0.018, 0.045, 0.09, 0.16) |
| 113 | new[indices] += rng.normal(0, scales[(step // 3) % len(scales)], (len(indices), 2)) |
| 114 | return np.clip(new, 0, 1) |
| 115 | |
| 116 | |
| 117 | def coordinates(points): |
| 118 | return [f"{x:.17g} {y:.17g}" for x, y in points] |
| 119 | |
| 120 | |
| 121 | def exact_fitness(lines): |
| 122 | points = [tuple(map(Fraction, line.split())) for line in lines] |
| 123 | return min(abs((bx - ax) * (cy - ay) - (cx - ax) * (by - ay)) / 2 |
| 124 | for (ax, ay), (bx, by), (cx, cy) in itertools.combinations(points, 3)) |
| 125 | |
| 126 | |
| 127 | def run_track(track, seed, seconds, attempts, inputs): |
| 128 | rng = np.random.default_rng(seed) |
| 129 | start = time.monotonic() |
| 130 | deadline = start + seconds if seconds is not None else float("inf") |
| 131 | max_attempts = attempts if attempts is not None else float("inf") |
| 132 | n16, record = inputs |
| 133 | initial = { |
| 134 | "deletion": lambda: [np.delete(n16, i, axis=0) for i in range(len(n16))], |
| 135 | "independent": lambda: [stratified_start(rng)], |
| 136 | "record": lambda: [record], |
| 137 | }[track]() |
| 138 | first = max(initial, key=fitness) |
| 139 | first_value = fitness(first) |
| 140 | best, best_score = first, first_value |
| 141 | current, current_score = best, best_score |
| 142 | completed = accepted = best_attempt = improving = 0 |
| 143 | print(f"{track} seed={seed} starting_area={first_value:.13f}", flush=True) |
| 144 | |
| 145 | while completed < max_attempts and (completed == 0 or time.monotonic() < deadline): |
| 146 | if completed < len(initial): |
| 147 | start_points = initial[completed] |
| 148 | elif track == "independent" and completed % 12 == 0: |
| 149 | start_points = stratified_start(rng) |
| 150 | else: |
| 151 | start_points = neighbor(current, rng, completed) |
| 152 | fitted = refine(start_points) |
| 153 | score = fitness(fitted) |
| 154 | completed += 1 |
| 155 | if score > best_score + 1e-13: |
| 156 | best, best_score, best_attempt = fitted, score, completed |
| 157 | improving += 1 |
| 158 | print(f"metric: {track}_area {score:.13f}", flush=True) |
| 159 | print(f"{track} improvement at attempt {completed}, area={score:.13f}", flush=True) |
| 160 | |
| 161 | phase = completed % 48 |
| 162 | temperature = 0.00012 + 0.00095 * (1 - phase / 48) |
| 163 | if phase == 0: |
| 164 | current, current_score = best, best_score |
| 165 | elif score >= current_score or rng.random() < np.exp((score - current_score) / temperature): |
| 166 | current, current_score = fitted, score |
| 167 | accepted += 1 |
| 168 | |
| 169 | lines = coordinates(best) |
| 170 | return { |
| 171 | "track": track, |
| 172 | "seed": seed, |
| 173 | "seconds": round(time.monotonic() - start, 3), |
| 174 | "attempts": completed, |
| 175 | "accepted": accepted, |
| 176 | "improvements": improving, |
| 177 | "best_attempt": best_attempt, |
| 178 | "starting_area": first_value, |
| 179 | "best_area": float(exact_fitness(lines)), |
| 180 | "coordinates": lines, |
| 181 | } |
| 182 | |
| 183 | |
| 184 | def main(): |
| 185 | parser = argparse.ArgumentParser(description=__doc__) |
| 186 | budget = parser.add_mutually_exclusive_group(required=True) |
| 187 | budget.add_argument("--seconds", type=float) |
| 188 | budget.add_argument("--attempts", type=int, nargs=3, metavar=("DELETION", "INDEPENDENT", "RECORD")) |
| 189 | parser.add_argument("--seed", type=int, required=True) |
| 190 | parser.add_argument("--output-dir", type=Path, required=True) |
| 191 | args = parser.parse_args() |
| 192 | if (args.seconds is not None and args.seconds <= 0) or (args.attempts and min(args.attempts) <= 0): |
| 193 | parser.error("the budget must be positive") |
| 194 | |
| 195 | route = Path(__file__).resolve().parent |
| 196 | inputs = tuple(np.loadtxt(route / f"reference{n}.dat") for n in (16, 15)) |
| 197 | limits = args.attempts or (None,) * len(TRACKS) |
| 198 | start = time.monotonic() |
| 199 | print(f"numpy={np.__version__} scipy={scipy.__version__} seed={args.seed}", flush=True) |
| 200 | with ProcessPoolExecutor(max_workers=len(TRACKS)) as pool: |
| 201 | futures = [ |
| 202 | pool.submit(run_track, track, args.seed + i, args.seconds, limits[i], inputs) |
| 203 | for i, track in enumerate(TRACKS) |
| 204 | ] |
| 205 | pending = set(futures) |
| 206 | while pending: |
| 207 | finished, pending = wait(pending, timeout=30, return_when=FIRST_COMPLETED) |
| 208 | for future in finished: |
| 209 | result = future.result() |
| 210 | print(f"{result['track']} completed {result['attempts']} attempts, " |
| 211 | f"best={result['best_area']:.13f}", flush=True) |
| 212 | if args.seconds is not None: |
| 213 | elapsed = time.monotonic() - start |
| 214 | pct = min(99, int(100 * elapsed / args.seconds)) if pending else 100 |
| 215 | print(f"progress: {pct}% elapsed={elapsed:.1f}s streams_complete={len(TRACKS) - len(pending)}", flush=True) |
| 216 | |
| 217 | results = [future.result() for future in futures] |
| 218 | eligible = [r for r in results if r["track"] != "record" |
| 219 | or exact_fitness(r["coordinates"]) >= RECORD_NEXT_DIGIT] |
| 220 | winner = max(eligible, key=lambda r: exact_fitness(r["coordinates"])) |
| 221 | args.output_dir.mkdir(parents=True, exist_ok=True) |
| 222 | (args.output_dir / "n15.txt").write_text("\n".join(winner["coordinates"]) + "\n") |
| 223 | summary = { |
| 224 | "seed": args.seed, |
| 225 | "seconds_per_track": args.seconds, |
| 226 | "attempt_limits": args.attempts, |
| 227 | "selected": winner["track"], |
| 228 | "tracks": results, |
| 229 | } |
| 230 | (args.output_dir / "search-summary.json").write_text(json.dumps(summary, indent=2) + "\n") |
| 231 | print(f"selected {winner['track']} area={winner['best_area']:.13f}", flush=True) |
| 232 | |
| 233 | |
| 234 | if __name__ == "__main__": |
| 235 | main() |