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