#!/usr/bin/env python3 """Own search for n = 13, issue #7 (zcode-zp1, 2026-11-28). From-scratch only by default: starts are stratified random, no literature or route coordinates are fed in. Design ideas credited to prior routes, each reimplemented here: stratified starts and clearance-guided relocation from hongdy22-codex-n15-search; the orientation-sign-fixed max-min refinement with analytic signed-area Jacobians from wangyuan-mac/n13-search; annealing acceptance and periodic restarts as in both. Usage: search.py --seconds S --seed N [--start FILE] [--out PREFIX] [--workers K] [--start-credit NOTE] --start FILE optionally seeds every track from a 13-line configuration (its provenance must be stated in --start-credit and in the route notes). """ import argparse import json import time from itertools import combinations from pathlib import Path import numpy as np from scipy.optimize import minimize N = 13 TRIPLES = np.array(list(combinations(range(N), 3))) A_IDX, B_IDX, C_IDX = TRIPLES.T NTRIPLES = len(TRIPLES) BOUNDS = [(0.0, 1.0)] * (2 * N) + [(1e-12, 0.7)] OBJ_JAC = np.zeros(2 * N + 1) OBJ_JAC[-1] = -1.0 def doubled_areas(points): """Signed doubled areas of all 286 triangles, vectorized.""" a, b, c = points[A_IDX], points[B_IDX], points[C_IDX] return ((b[:, 0] - a[:, 0]) * (c[:, 1] - a[:, 1]) - (c[:, 0] - a[:, 0]) * (b[:, 1] - a[:, 1])) def area_jacobian(points): """d(doubled area of triple t)/d(coordinate) as a (NTRIPLES, 2N+1) matrix. D = (bx-ax)(cy-ay) - (cx-ax)(by-ay) is bilinear; with the other coordinates fixed each partial is linear in the moved coordinate: d/d(ax) = by - cy d/d(ay) = cx - bx d/d(bx) = cy - ay d/d(by) = ax - cx d/d(cx) = ay - by d/d(cy) = bx - ax (checked at startup against finite differences). """ a, b, c = points[A_IDX], points[B_IDX], points[C_IDX] jac = np.zeros((NTRIPLES, 2 * N + 1)) jac[np.arange(NTRIPLES), 2 * A_IDX] = b[:, 1] - c[:, 1] jac[np.arange(NTRIPLES), 2 * A_IDX + 1] = c[:, 0] - b[:, 0] jac[np.arange(NTRIPLES), 2 * B_IDX] = c[:, 1] - a[:, 1] jac[np.arange(NTRIPLES), 2 * B_IDX + 1] = a[:, 0] - c[:, 0] jac[np.arange(NTRIPLES), 2 * C_IDX] = a[:, 1] - b[:, 1] jac[np.arange(NTRIPLES), 2 * C_IDX + 1] = b[:, 0] - a[:, 0] return jac def selftest(rng, eps=1e-7): points = stratified_start(rng) for _ in range(20): moved = points.copy() v, axis = rng.integers(N), rng.integers(2) moved[v, axis] += eps * (1 if rng.random() < 0.5 else -1) numeric = (doubled_areas(moved) - doubled_areas(points)) / (moved[v, axis] - points[v, axis]) analytic = area_jacobian(points)[:, 2 * v + axis] assert np.abs(numeric - analytic).max() < 1e-6, "jacobian selftest failed" def stratified_start(rng): """One point per x and y stratum, jittered, scaled back into the square.""" pts = (np.column_stack((rng.permutation(N), rng.permutation(N))) + rng.random((N, 2))) / N return (pts - pts.min(axis=0)) / (pts.max(axis=0) - pts.min(axis=0)) def refine(points, signs, maxiter=250): """Maximize the smallest sign-fixed signed doubled area (epigraph SLSQP).""" d0 = signs * doubled_areas(points) z0 = np.r_[points.ravel(), d0.min()] def con_fun(z, s=signs): return s * doubled_areas(z[:2 * N].reshape(N, 2)) - z[-1] def con_jac(z, s=signs): jac = s[:, None] * area_jacobian(z[:2 * N].reshape(N, 2)) jac[:, -1] = -1.0 return jac cons = [{"type": "ineq", "fun": con_fun, "jac": con_jac}] result = minimize(lambda z: -z[-1], z0, jac=lambda z: OBJ_JAC, bounds=BOUNDS, constraints=cons, method="SLSQP", options={"maxiter": maxiter, "ftol": 1e-14}) fitted = np.clip(result.x[:2 * N].reshape(N, 2), 0.0, 1.0) return fitted def relocate(points, rng, probes=192): """Reposition a point of a smallest triangle by clearance from pair lines.""" d = np.abs(doubled_areas(points)) worst = np.flatnonzero(d <= d.min() + 1e-12) triple = TRIPLES[rng.choice(worst)] index = int(rng.choice(triple)) fixed = np.delete(points, index, axis=0) first, second = fixed[np.array(list(combinations(range(N - 1), 2)))].transpose(1, 0, 2) dx, dy = second[:, 0] - first[:, 0], second[:, 1] - first[:, 1] norms = np.hypot(dx, dy) keep = norms > 1e-12 nx, ny = (-dy[keep] / norms[keep]), (dx[keep] / norms[keep]) off = nx * first[keep, 0] + ny * first[keep, 1] trial = rng.random((probes, 2)) clear = np.abs(trial[:, 0, None] * nx + trial[:, 1, None] * ny - off).min(axis=1) near = np.linalg.norm(trial[:, None, :] - fixed[None, :, :], axis=2).min(axis=1) clear[near < 0.04] = -1.0 best = int(np.argmax(clear)) moved = points.copy() moved[index] = trial[best] return moved, index def run_track(seed, seconds, start=None): rng = np.random.default_rng(seed) selftest(rng) start_time = time.monotonic() deadline = start_time + seconds scales = [0.12, 0.06, 0.03, 0.015] temps = [0.002, 0.0004, 0.00005] current = stratified_start(rng) if start is None else start.copy() current = refine(current, np.where(doubled_areas(current) < 0, -1.0, 1.0)) current_score = float(np.abs(doubled_areas(current)).min()) best, best_score, best_attempt = current.copy(), current_score, 0 completed = accepted = improving = 0 log = [] while time.monotonic() < deadline: completed += 1 if completed == 1 or completed % 15 == 0: attempt = stratified_start(rng) elif completed % 4 == 0: attempt, _ = relocate(current, rng) else: attempt = current.copy() for v in rng.choice(N, size=int(rng.integers(1, 5)), replace=False): attempt[v] += rng.normal(0.0, scales[completed % len(scales)], size=2) attempt = np.clip(attempt, 0.0, 1.0) fitted = refine(attempt, np.where(doubled_areas(attempt) < 0, -1.0, 1.0)) score = float(np.abs(doubled_areas(fitted)).min()) completed_note = completed if score > best_score: best, best_score, best_attempt = fitted.copy(), score, completed_note improving += 1 log.append({"attempt": completed_note, "area": score}) print(f"improvement at attempt {completed_note}: {score:.13f}", flush=True) temperature = temps[completed % len(temps)] if score >= current_score or rng.random() < np.exp((score - current_score) / temperature): current, current_score = fitted, score accepted += 1 return {"seed": int(seed), "seconds": round(time.monotonic() - start_time, 3), "attempts": completed, "accepted": accepted, "improvements": improving, "best_attempt": best_attempt, "best_area": best_score, "coordinates": [f"{x:.17g} {y:.17g}" for x, y in best], "log": log[-12:]} def main(): parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser.add_argument("--seconds", type=float, required=True) parser.add_argument("--seed", type=int, required=True) parser.add_argument("--start", type=Path, default=None) parser.add_argument("--start-credit", default="") parser.add_argument("--out", default="") args = parser.parse_args() start = np.loadtxt(args.start).reshape(N, 2) if args.start else None if args.start: print(f"start credit: {args.start_credit}", flush=True) result = run_track(args.seed, args.seconds, start) result["start_credit"] = args.start_credit text = json.dumps(result, indent=1) if args.out: Path(args.out).write_text(text) print(text) if __name__ == "__main__": main()