"""Low-duty n = 13 search using transfer from larger configurations.""" import argparse import itertools import json import time from fractions import Fraction from pathlib import Path import numpy as np import scipy from scipy.optimize import minimize N = 13 CPU_FRACTION = 0.04 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] 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)) class Track: def __init__(self, name, seed, parents): self.name = name self.seed = seed self.rng = np.random.default_rng(seed) self.starts = [parents[list(indices)] for indices in itertools.combinations(range(len(parents)), N)] if parents is not None else [] self.attempts = self.accepted = self.best_attempt = 0 self.best_score = self.current_score = 0.0 self.best = self.current = None def step(self): step = self.attempts if step < len(self.starts): initial = self.starts[step] elif step == 0 or (self.name == "stratified" and step % 12 == 0): initial = stratified_start(self.rng) else: initial = neighbor(self.current, self.rng, step) points = refine(initial) score = fitness(points) self.attempts += 1 if score > self.best_score + 1e-13: self.best, self.best_score, self.best_attempt = points, score, self.attempts print(f"metric: {self.name}_area {score:.13f}", flush=True) print(f"{self.name} best at attempt {self.attempts}", flush=True) phase = self.attempts % 48 temperature = 0.00013 + 0.00105 * (1 - phase / 48) if phase == 0: self.current, self.current_score = self.best, self.best_score elif score >= self.current_score or self.rng.random() < np.exp((score - self.current_score) / temperature): self.current, self.current_score = points, score self.accepted += 1 def summarize(self): lines = coordinates(self.best) return { "track": self.name, "seed": self.seed, "attempts": self.attempts, "accepted": self.accepted, "best_attempt": self.best_attempt, "best_area": float(exact_fitness(lines)), "coordinates": lines, } def save(output, tracks, elapsed, used_cpu, seed): results = [track.summarize() for track in tracks if track.best is not None] winner = max(results, key=lambda result: exact_fitness(result["coordinates"])) (output / "n13.txt").write_text("\n".join(winner["coordinates"]) + "\n") report = { "seed": seed, "wall_seconds": round(elapsed, 3), "process_cpu_seconds": round(used_cpu, 3), "selected": winner["track"], "tracks": results, "numpy": np.__version__, "scipy": scipy.__version__, } (output / "search-summary.json").write_text(json.dumps(report, indent=2) + "\n") return winner def main(): parser = argparse.ArgumentParser(description=__doc__) budget = parser.add_mutually_exclusive_group(required=True) budget.add_argument("--seconds", type=float) budget.add_argument("--rounds", type=int, help="deterministic replay with one attempt per stream per round") 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.rounds is not None and args.rounds <= 0): parser.error("the time or round budget must be positive") source = Path(__file__).resolve().parent args.output_dir.mkdir(parents=True, exist_ok=True) tracks = [ Track("delete14", args.seed, np.loadtxt(source / "seed14.dat")), Track("delete15", args.seed + 1, np.loadtxt(source / "seed15.dat")), Track("stratified", args.seed + 2, None), ] started, cpu_started = time.monotonic(), time.process_time() wall_limit = args.seconds if args.seconds is not None else float("inf") attempt_limit = 3 * args.rounds if args.rounds is not None else float("inf") reported = 0.0 print(f"seed={args.seed} budget={args.seconds} numpy={np.__version__} scipy={scipy.__version__}", flush=True) for attempt, track in enumerate(itertools.cycle(tracks)): elapsed = time.monotonic() - started if attempt >= attempt_limit or (attempt and elapsed >= wall_limit): break track.step() elapsed, used_cpu = time.monotonic() - started, time.process_time() - cpu_started if elapsed - reported >= 30: winner = save(args.output_dir, tracks, elapsed, used_cpu, args.seed) progress = int(100 * min(0.99, elapsed / wall_limit)) if args.seconds else int(100 * attempt / attempt_limit) print(f"progress: {progress}% attempts={attempt + 1} search_cpu={used_cpu:.2f}s " f"best={winner['best_area']:.13f}", flush=True) reported = elapsed delay = min(wall_limit - elapsed, used_cpu / CPU_FRACTION - elapsed) if delay > 0: time.sleep(delay) elapsed, used_cpu = time.monotonic() - started, time.process_time() - cpu_started winner = save(args.output_dir, tracks, elapsed, used_cpu, args.seed) print(f"progress: 100% attempts={sum(track.attempts for track in tracks)} " f"search_cpu={used_cpu:.2f}s selected={winner['track']} area={winner['best_area']:.13f}", flush=True) if __name__ == "__main__": main()