#!/usr/bin/env python3 # -*- coding: utf-8 -*- """cover90.py — job #2731 (route 90 rescue): a from-scratch, sound instrument for the project's own covering semantics, plus a fixed-target search for a covered run of R = 2454 at n = 25. Semantics (the project's own, quoted from return #1137 / #1149 and the route record): position i (an offset from the state's x) is COVERED by prime p with residue v iff (i + v) mod p in {1, p-1} For odd p this is two residue classes; for p = 2 the two coincide, so exactly one. A "covered run" is a maximal set of consecutive covered positions. The target of this job is one explicit covered run of length >= 2454 (the base-10 bar), which would move the window's floor from ln(30/11) to ln(G2/900) with G2 >= 2455. Gates (run before any measurement): the served n = 25 tuple must reproduce, from scratch, the hole geometry TWO independent records published: [17,2489) -> 9 holes 196,226,2254,2296,2302,2326,2374,2386,2452 (route 90 obstacle) [227,2296) -> 1 hole 2254 (#1137 / #1149) the best run in the state near the origin -> 2027, window start 227 (check-2043 summary) """ import argparse import json import os import sys import time import numpy as np PRIMES = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97] N = len(PRIMES) STATE_RESIDUES = [0, 2, 1, 3, 10, 1, 16, 11, 4, 26, 11, 8, 22, 37, 15, 52, 37, 14, 14, 36, 16, 18, 74, 62, 93] STATE_SHA256 = "0d77773d01631d9eb70b76b18588c13b1d76b2bca5a0e4ff22b52c5887630600" PUBLISHED_HOLES_17_2489 = [196, 226, 2254, 2296, 2302, 2326, 2374, 2386, 2452] PUBLISHED_HOLE_227_2296 = [2254] PUBLISHED_RUN = 2027 PUBLISHED_RUN_START = 227 R_TARGET = 2454 FULL_PRIMES = list(PRIMES) def set_level(k): """Set the prime set to the first k primes (levels <= 25), so the SAME instrument can be run at a level whose ladder value is published. Mutates PRIMES IN PLACE so every module that imported the list sees the change, and RESTORES from the full list first -- an earlier version truncated destructively, so a later larger level silently kept the smaller prime set (caught by the level printed in its own output on 2026-09-20).""" global N PRIMES[:] = FULL_PRIMES[:k] N = len(PRIMES) return N def classes(p, v): """The residue classes of i (mod p) that prime p with residue v covers.""" a = (1 - v) % p b = (-1 - v) % p return (a,) if a == b else (a, b) def coverage(residues, X, dtype=np.int16): """cnt[i] = number of primes covering offset i, for 0 <= i < X. One slice per class: no OR-masks, no XOR updates, nothing incremental — recomputed from scratch.""" cnt = np.zeros(X, dtype=dtype) for k, p in enumerate(PRIMES): for a in classes(p, residues[k]): cnt[a:X:p] += 1 return cnt def holes_over(residues, lo, hi, X=None): """Exact hole list on [lo, hi).""" X = X or hi cnt = coverage(residues, X) idx = np.flatnonzero(cnt[lo:hi] == 0) + lo return [int(i) for i in idx] def window_holes(prefix, R, X): """min hole count over all windows [s, s+R) with 0 <= s <= X-R, and its argmin.""" if X <= R: return int(prefix[-1]), 0 w = prefix[R:] - prefix[:-R] # w[s] = holes in [s, s+R) m = int(w.min()) return m, int(np.argmin(w)) def prefix_of(cnt): z = np.zeros(1, dtype=np.int64) return np.concatenate([z, np.cumsum(cnt == 0, dtype=np.int64)]) def best_run(residues, X): """Longest covered run inside [0, X), and where it starts.""" cnt = coverage(residues, X) h = (cnt == 0) best = cur = 0 best_start = start = 0 for i in range(X): if h[i]: if cur > best: best, best_start = cur, start cur, start = 0, i + 1 else: cur += 1 if cur > best: best, best_start = cur, start return best, best_start def gate(state_path, X=3000, verbose=True): """The pre-registered gates. Nothing is measured before these pass.""" out = {"gate": "cover90", "at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "checks": []} def ck(name, ok, observed, expected=None): out["checks"].append({"check": name, "pass": bool(ok), "observed": observed, "expected": expected}) if verbose: print(("PASS " if ok else "FAIL ") + name + " observed=" + json.dumps(observed)) import hashlib raw = open(state_path, "rb").read() sha = hashlib.sha256(raw).hexdigest() ck("input state sha256 == route's declared input", sha == STATE_SHA256, sha[:16], STATE_SHA256[:16]) v = STATE_RESIDUES ck("residues in range for their primes", all(0 <= v[k] < PRIMES[k] for k in range(N)), True) odd_holes = [i for i in holes_over(v, 1, 599, 599) if i % 2 == 1] ck("prime 2 at residue 0 -> NO odd offset is ever a hole", odd_holes == [], odd_holes, []) h9 = holes_over(v, 17, 2489, 2489) ck("[17,2489) hole list == the route's 9 published holes", h9 == PUBLISHED_HOLES_17_2489, h9, PUBLISHED_HOLES_17_2489) h1 = holes_over(v, 227, 2296, 2296) ck("[227,2296) hole list == #1137/#1149's single hole", h1 == PUBLISHED_HOLE_227_2296, h1, PUBLISHED_HOLE_227_2296) h0 = holes_over(v, 227, 2028, 2028) ck("[227,2028) fully covered (#1137's 1-hole window's inner part)", h0 == [], h0, []) br, bs = best_run(v, X) ck("best run in the state (X=%d) == published 2027" % X, br == PUBLISHED_RUN, {"run": br, "start": bs}, {"run": PUBLISHED_RUN, "start": PUBLISHED_RUN_START}) out["passed"] = sum(1 for c in out["checks"] if c["pass"]) out["total"] = len(out["checks"]) out["ok"] = out["passed"] == out["total"] if verbose: print("GATE %d/%d %s" % (out["passed"], out["total"], "OK" if out["ok"] else "FAILED")) return out # --------------------------------------------------------------------------- search def evaluate(residues, X, R): """Objective: holes in the BEST window of length R over [0, X). 0 == target met.""" cnt = coverage(residues, X) pref = prefix_of(cnt) return window_holes(pref, R, X) def one_prime_sweep(residues, X, R, best_holes, rng, order=None): """Coordinate descent: for each prime try EVERY residue and keep the best. Full re-evaluation from scratch each time (sound), no incremental arithmetic.""" improved = False ks = list(range(N)) if order is None else order for k in ks: p = PRIMES[k] cur = residues[k] for w in range(p): if w == cur: continue trial = list(residues) trial[k] = w h, s = evaluate(trial, X, R) if h < best_holes: residues = trial best_holes = h cur = w improved = True if h == 0: return residues, h, s, improved return residues, best_holes, None, improved def search(X, R, seconds, seed, start_residues, log): """Iterated local search on the best-window objective, with hole-driven moves and random kicks. Every accepted state is scored by a from-scratch evaluation.""" rng = np.random.default_rng(seed) residues = list(start_residues) best_holes, best_start = evaluate(residues, X, R) best_res = list(residues) t0 = time.time() it = 0 kicks = 0 traj = [(0.0, best_holes)] while time.time() - t0 < seconds: it += 1 # 1. coordinate descent to a local optimum residues, h, _s, _imp = one_prime_sweep(residues, X, R, best_holes, rng) h, s = evaluate(residues, X, R) if h < best_holes: best_holes, best_start, best_res = h, s, list(residues) traj.append((round(time.time() - t0, 1), best_holes)) log({"event": "improve", "holes": h, "start": s, "iter": it, "t": round(time.time() - t0, 1), "residues": list(residues)}) if h == 0: return best_res, 0, best_start, traj, it, kicks # 2. kick: perturb a few primes at random, preferring large primes (small damage) r = int(rng.integers(1, 5)) for _ in range(r): k = int(rng.integers(0, N)) residues[k] = int(rng.integers(0, PRIMES[k])) kicks += 1 # 3. re-descend; accept only if not worse than the incumbent (else restart) residues, h2, _s2, _i2 = one_prime_sweep(residues, X, R, h + 1, rng) h2, _s3 = evaluate(residues, X, R) if h2 <= best_holes + 1: if h2 < best_holes: best_holes, best_start, best_res = h2, _s3, list(residues) traj.append((round(time.time() - t0, 1), best_holes)) log({"event": "improve_after_kick", "holes": h2, "iter": it, "t": round(time.time() - t0, 1), "residues": list(residues)}) if h2 == 0: return best_res, 0, best_start, traj, it, kicks else: residues = list(best_res) # restart from the incumbent return best_res, best_holes, best_start, traj, it, kicks def cmd_gate(a): o = gate(a.state, X=a.X) if a.out: json.dump(o, open(a.out, "w", encoding="utf-8"), indent=1) return 0 if o["ok"] else 1 def cmd_run(a): t0 = time.time() fh = open(a.log, "w", encoding="utf-8") if a.log else None def log(rec): if fh: fh.write(json.dumps(rec) + "\n") fh.flush() start = json.loads(a.start) if a.start else STATE_RESIDUES res, holes, start_at, traj, it, kicks = search(a.X, a.R, a.seconds, a.seed, start, log) cnt = coverage(res, a.X) pref = prefix_of(cnt) h, s = window_holes(pref, a.R, a.X) # independent re-check of the reported window with an explicit per-offset count win = [int(i) for i in np.flatnonzero(cnt[s:s + a.R] == 0) + s] out = {"tool": "cover90/1", "at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "X": a.X, "R": a.R, "seconds_requested": a.seconds, "seconds_elapsed": round(time.time() - t0, 1), "seed": a.seed, "iterations": it, "kicks": kicks, "start_residues": start, "best_residues": res, "best_window_holes": h, "best_window_start": s, "best_window_hole_list": win, "found_witness": h == 0, "best_window_len": a.R, "trajectory": traj} if holes == 0: run_len, run_start = best_run(res, a.X) out["covered_run_in_range"] = {"length": run_len, "start": run_start} json.dump(out, open(a.out, "w", encoding="utf-8"), indent=1) if fh: fh.close() print(json.dumps({k: out[k] for k in ("best_window_holes", "best_window_start", "best_window_hole_list", "found_witness", "iterations", "kicks", "seconds_elapsed")}, indent=1)) return 0 def main(): ap = argparse.ArgumentParser() sub = ap.add_subparsers(dest="cmd", required=True) g = sub.add_parser("gate") g.add_argument("--state", required=True) g.add_argument("--X", type=int, default=3000) g.add_argument("--out") g.set_defaults(fn=cmd_gate) r = sub.add_parser("run") r.add_argument("--start", help="JSON file with a residue list; default = served state") r.add_argument("--X", type=int, default=12000) r.add_argument("--R", type=int, default=R_TARGET) r.add_argument("--seconds", type=float, default=300) r.add_argument("--seed", type=int, default=1) r.add_argument("--out", required=True) r.add_argument("--log") r.set_defaults(fn=cmd_run) a = ap.parse_args() sys.exit(a.fn(a)) if __name__ == "__main__": main()