"""Search 15-point configurations with point relocation and signed-area SLSQP.""" import argparse import itertools import json import time from concurrent.futures import FIRST_COMPLETED, ProcessPoolExecutor, wait from fractions import Fraction from pathlib import Path import numpy as np import scipy from scipy.optimize import minimize N = 15 TRACKS = ("deletion", "independent", "record") TRIPLES = list(itertools.combinations(range(N), 3)) I, J, K = np.array(TRIPLES).T ROWS = np.arange(len(I)) PAIR_I, PAIR_J = np.array(list(itertools.combinations(range(N - 1), 2))).T BOUNDS = [(0.0, 1.0)] * (2 * N) + [(0.0, 0.5)] OBJECTIVE_JAC = np.r_[np.zeros(2 * N), -1.0] RECORD_NEXT_DIGIT = Fraction("0.0212105411") def signed_area(points): first = points[J] - points[I] second = points[K] - points[I] return (first[:, 0] * second[:, 1] - first[:, 1] * second[:, 0]) / 2 def fitness(points): return float(np.abs(signed_area(points)).min()) def refine(points): """Locally maximize the smallest area in the starting orientation class.""" areas = signed_area(points) signs = np.where(areas < 0, -1, 1) signed_half = signs / 2 initial = np.r_[points.ravel(), np.abs(areas).min()] def constraints(x): return signs * signed_area(x[:-1].reshape(N, 2)) - x[-1] def jacobian(x): p = x[:-1].reshape(N, 2) ax, ay = p[I].T bx, by = p[J].T cx, cy = p[K].T jac = np.zeros((len(I), 2 * N + 1)) jac[ROWS, 2 * I] = signed_half * (by - cy) jac[ROWS, 2 * I + 1] = signed_half * (cx - bx) jac[ROWS, 2 * J] = signed_half * (cy - ay) jac[ROWS, 2 * J + 1] = signed_half * (ax - cx) jac[ROWS, 2 * K] = signed_half * (ay - by) jac[ROWS, 2 * K + 1] = signed_half * (bx - ax) jac[:, -1] = -1 return jac solved = minimize( lambda x: -x[-1], initial, jac=lambda x: OBJECTIVE_JAC, bounds=BOUNDS, constraints={"type": "ineq", "fun": constraints, "jac": jacobian}, method="SLSQP", options={"ftol": 2e-12, "maxiter": 70}, ) candidate = np.clip(solved.x[:-1].reshape(N, 2), 0, 1) return max((points, candidate), key=fitness) def stratified_start(rng): """Sample one point in each x and y stratum and extend to the square.""" points = (np.column_stack((rng.permutation(N), rng.permutation(N))) + rng.random((N, 2))) / N minimum = points.min(axis=0) return (points - minimum) / (points.max(axis=0) - minimum) def relocate(points, index, rng, probes=192): """Sample alternate positions ranked by clearance from all fixed pair lines.""" fixed = np.delete(points, index, axis=0) first = fixed[PAIR_I] dx, dy = (fixed[PAIR_J] - first).T normals = np.column_stack((-dy, dx)) / 2 offsets = np.einsum("ij,ij->i", normals, first) trial_points = rng.random((probes, 2)) trial_points[: probes // 2 : 2, 0] = rng.integers(2, size=probes // 4) trial_points[1 : probes // 2 : 2, 1] = rng.integers(2, size=probes // 4) trial_points = trial_points[np.linalg.norm(trial_points - points[index], axis=1) > 0.05] if not len(trial_points): return stratified_start(rng)[index] signed = (trial_points[:, 0, None] * normals[:, 0] + trial_points[:, 1, None] * normals[:, 1] - offsets) clearance = np.abs(signed).min(axis=1) return trial_points[np.argmax(clearance)] def neighbor(points, rng, step): new = points.copy() if step % 3: index = rng.integers(N) new[index] = relocate(new, index, rng) if step % 6 == 1: index = rng.integers(N) new[index] = relocate(new, index, rng) else: indices = rng.choice(N, size=1 + step % 4, replace=False) scales = (0.018, 0.045, 0.09, 0.16) new[indices] += rng.normal(0, scales[(step // 3) % len(scales)], (len(indices), 2)) return np.clip(new, 0, 1) def coordinates(points): return [f"{x:.17g} {y:.17g}" for x, y in points] def exact_fitness(lines): points = [tuple(map(Fraction, line.split())) for line in lines] return min(abs((bx - ax) * (cy - ay) - (cx - ax) * (by - ay)) / 2 for (ax, ay), (bx, by), (cx, cy) in itertools.combinations(points, 3)) def run_track(track, seed, seconds, attempts, inputs): rng = np.random.default_rng(seed) start = time.monotonic() deadline = start + seconds if seconds is not None else float("inf") max_attempts = attempts if attempts is not None else float("inf") n16, record = inputs initial = { "deletion": lambda: [np.delete(n16, i, axis=0) for i in range(len(n16))], "independent": lambda: [stratified_start(rng)], "record": lambda: [record], }[track]() first = max(initial, key=fitness) first_value = fitness(first) best, best_score = first, first_value current, current_score = best, best_score completed = accepted = best_attempt = improving = 0 print(f"{track} seed={seed} starting_area={first_value:.13f}", flush=True) while completed < max_attempts and (completed == 0 or time.monotonic() < deadline): if completed < len(initial): start_points = initial[completed] elif track == "independent" and completed % 12 == 0: start_points = stratified_start(rng) else: start_points = neighbor(current, rng, completed) fitted = refine(start_points) score = fitness(fitted) completed += 1 if score > best_score + 1e-13: best, best_score, best_attempt = fitted, score, completed improving += 1 print(f"metric: {track}_area {score:.13f}", flush=True) print(f"{track} improvement at attempt {completed}, area={score:.13f}", flush=True) phase = completed % 48 temperature = 0.00012 + 0.00095 * (1 - phase / 48) if phase == 0: current, current_score = best, best_score elif score >= current_score or rng.random() < np.exp((score - current_score) / temperature): current, current_score = fitted, score accepted += 1 lines = coordinates(best) return { "track": track, "seed": seed, "seconds": round(time.monotonic() - start, 3), "attempts": completed, "accepted": accepted, "improvements": improving, "best_attempt": best_attempt, "starting_area": first_value, "best_area": float(exact_fitness(lines)), "coordinates": lines, } def main(): parser = argparse.ArgumentParser(description=__doc__) budget = parser.add_mutually_exclusive_group(required=True) budget.add_argument("--seconds", type=float) budget.add_argument("--attempts", type=int, nargs=3, metavar=("DELETION", "INDEPENDENT", "RECORD")) parser.add_argument("--seed", type=int, required=True) parser.add_argument("--output-dir", type=Path, required=True) args = parser.parse_args() if (args.seconds is not None and args.seconds <= 0) or (args.attempts and min(args.attempts) <= 0): parser.error("the budget must be positive") route = Path(__file__).resolve().parent inputs = tuple(np.loadtxt(route / f"reference{n}.dat") for n in (16, 15)) limits = args.attempts or (None,) * len(TRACKS) start = time.monotonic() print(f"numpy={np.__version__} scipy={scipy.__version__} seed={args.seed}", flush=True) with ProcessPoolExecutor(max_workers=len(TRACKS)) as pool: futures = [ pool.submit(run_track, track, args.seed + i, args.seconds, limits[i], inputs) for i, track in enumerate(TRACKS) ] pending = set(futures) while pending: finished, pending = wait(pending, timeout=30, return_when=FIRST_COMPLETED) for future in finished: result = future.result() print(f"{result['track']} completed {result['attempts']} attempts, " f"best={result['best_area']:.13f}", flush=True) if args.seconds is not None: elapsed = time.monotonic() - start pct = min(99, int(100 * elapsed / args.seconds)) if pending else 100 print(f"progress: {pct}% elapsed={elapsed:.1f}s streams_complete={len(TRACKS) - len(pending)}", flush=True) results = [future.result() for future in futures] eligible = [r for r in results if r["track"] != "record" or exact_fitness(r["coordinates"]) >= RECORD_NEXT_DIGIT] winner = max(eligible, key=lambda r: exact_fitness(r["coordinates"])) args.output_dir.mkdir(parents=True, exist_ok=True) (args.output_dir / "n15.txt").write_text("\n".join(winner["coordinates"]) + "\n") summary = { "seed": args.seed, "seconds_per_track": args.seconds, "attempt_limits": args.attempts, "selected": winner["track"], "tracks": results, } (args.output_dir / "search-summary.json").write_text(json.dumps(summary, indent=2) + "\n") print(f"selected {winner['track']} area={winner['best_area']:.13f}", flush=True) if __name__ == "__main__": main()