"""repair90c.py -- route 90 job #2094: the same repair search with a CORRECT coverage update. WHY THIS FILE EXISTS. `repair90b.py`, whose "exhausted" verdicts carry route 90's negatives (#1121: K <= 4 on the single-hole window; the 10-level calibration), updates coverage with Up = (U ^ mask(k, cur_residue_k)) | mask(k, new_residue_k) XOR removes prime k's contribution from a single OR-mask only if no OTHER prime sets those bits. Masks of one prime at different residues are disjoint, but masks of different primes overlap everywhere: offset i is covered by prime p iff i = +-1 - v (mod p). The audit (`audit-xor-update.py`, this job) finds ALL 1035 single-prime moves inconsistent with a from-scratch recomputation, every one understating coverage. Example: moving prime 2 from residue 0 to 1 in window [227,2296) reports 1035 holes of which 43 are real. Understated coverage means invented holes, and invented holes are what let a depth-limited DFS report "no reassignment covers the window" for a window that is in fact covered. #1121 ran K = 4 with that implementation only (its table shows impl. A unrun at K = 4), so the decisive negative there is not established until it is re-run. WHAT THIS DOES INSTEAD. Coverage is maintained as a PER-OFFSET COUNT over the window -- the object's own definition, one counter per offset, increment on entry and decrement on exit -- so a move cannot erase another prime's contribution. No OR-mask is ever XOR-ed. exhaustK1/K2 : complete enumeration of every single move and every pair of moves on distinct primes, ALL residue values, no "must cover a hole" restriction. Stronger than the DFS: it cannot be biased by the branching rule. A solution found here is a witness; no solution found here is a complete negative at that depth. solve : the DFS of the record (MRV hole choice, chained moves, every candidate that covers an uncovered offset with an unmoved prime), with the corrected counter update. Runs that end without touching a cap are `exhausted: true`. Both `nodes` and the verdict are reported; `aborted` runs claim nothing. """ import argparse import json import os import sys import time import numpy as np HERE = os.path.dirname(os.path.abspath(__file__)) 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] class Cov(object): """Coverage by per-offset counts. Local index j means absolute offset start + j.""" def __init__(self, res, start, R): self.n = len(res) self.res = [int(r) for r in res] self.start = start self.R = R self.pos = {} # (k,v) -> int64 array of local offsets covered self.cnt0 = np.zeros(R, dtype=np.int16) for k in range(self.n): p = PRIMES[k] self.cnt0[self.pos_of(k, self.res[k])] += 1 self.holes0 = int((self.cnt0 == 0).sum()) def pos_of(self, k, v): key = (k, v % PRIMES[k]) a = self.pos.get(key) if a is None: p = PRIMES[k] vv = key[1] c1 = (1 - vv) % p c2 = (p - 1 - vv) % p lo, hi = self.start, self.start + self.R parts = [] for c in {c1, c2}: first = lo + ((c - lo) % p) if first < hi: parts.append(np.arange(first, hi, p, dtype=np.int64) - self.start) a = np.concatenate(parts) if parts else np.zeros(0, dtype=np.int64) self.pos[key] = a return a def moves(self): """Every single-prime move, ALL residue values (no hole restriction).""" out = [] for k in range(self.n): for v in range(PRIMES[k]): if v != self.res[k]: out.append((k, v)) return out def candidates_for(self, i): """Moves whose new mask covers local offset i (exhaustive over residues).""" out = [] for k in range(self.n): p = PRIMES[k] for cl in ((1,) if p == 2 else (1, p - 1)): v = (cl - (self.start + i)) % p if v != self.res[k]: out.append((k, v)) return out def holes_after_batch(cov, base, moves): """Hole counts for many single moves applied to `base`, batched.""" M = len(moves) cnts = np.tile(base, (M, 1)) for t, (k, v) in enumerate(moves): cnts[t, cov.pos_of(k, cov.res[k])] -= 1 cnts[t, cov.pos_of(k, v)] += 1 return (cnts == 0).sum(axis=1) def exhaust_k1(cov, secs=600.0): t0 = time.time() moves = cov.moves() h = holes_after_batch(cov, cov.cnt0, moves) best = int(h.min()) sol = [moves[i] for i in np.flatnonzero(h == 0)] return {"depth": 1, "moves_tried": len(moves), "min_holes": best, "solutions": sol, "exhausted": not sol, "secs": round(time.time() - t0, 2)} def exhaust_k2(cov, secs=600.0, block=256): """All unordered pairs of moves on distinct primes.""" t0 = time.time() moves = cov.moves() M = len(moves) best = 10 ** 9 sol = [] aborted = False for i in range(M): k1 = moves[i][0] js = [j for j in range(M) if j != i and moves[j][0] != k1] js = np.array(js, dtype=np.int64) for s in range(0, len(js), block): blk = js[s:s + block] cnts = np.tile(cov.cnt0, (len(blk) + 1, 1)) k, v = moves[i] cnts[:, cov.pos_of(k, cov.res[k])] -= 1 cnts[:, cov.pos_of(k, v)] += 1 for t, j in enumerate(blk): k2, v2 = moves[j] cnts[t + 1, cov.pos_of(k2, cov.res[k2])] -= 1 cnts[t + 1, cov.pos_of(k2, v2)] += 1 h = (cnts == 0).sum(axis=1) m = int(h.min()) if m < best: best = m for t in np.flatnonzero(h == 0): if t == 0: sol.append([moves[i]]) else: sol.append([moves[i], moves[int(blk[t - 1])]]) if time.time() - t0 > secs: aborted = True break if aborted: break return {"depth": 2, "moves_tried": len(moves), "min_holes": best, "solutions": sol[:20], "n_solutions": len(sol), "exhausted": (not aborted) and (not sol), "aborted": aborted, "secs": round(time.time() - t0, 2)} def solve_dfs(cov, K, node_cap=20000000, secs=500.0, order="hole"): st = {"nodes": 0, "aborted": False, "t0": time.time(), "sol": None} cnt = cov.cnt0.copy() cur = list(cov.res) moved = bytearray(cov.n) def apply(k, v): cnt[cov.pos_of(k, cur[k])] -= 1 cnt[cov.pos_of(k, v)] += 1 def undo(k, v): cnt[cov.pos_of(k, v)] -= 1 cnt[cov.pos_of(k, cur[k])] += 1 def dfs(depth): holes = np.flatnonzero(cnt == 0) if holes.size == 0: st["sol"] = [(k, cur[k]) for k in range(cov.n) if moved[k]] return True st["nodes"] += 1 if st["nodes"] > node_cap or time.time() - st["t0"] > secs: st["aborted"] = True return None if depth >= K: return False # MRV: the uncovered offset with the fewest unmoved covering moves best_i, best_c = None, None for i in holes: cs = [kv for kv in cov.candidates_for(int(i)) if not moved[kv[0]]] if not cs: return False if best_c is None or len(cs) < len(best_c): best_i, best_c = int(i), cs if len(cs) == 1: break if order == "hole": # cheap admissible ordering: how many CURRENT holes each move covers hset = set(int(x) for x in holes) scored = [] for (k, v) in best_c: c = 0 for j in cov.pos_of(k, v): if int(j) in hset: c += 1 scored.append((-c, -PRIMES[k], k, v)) scored.sort() best_c = [(k, v) for (_c, _p, k, v) in scored] else: best_c.sort(key=lambda kv: -PRIMES[kv[0]]) for (k, v) in best_c: old = cur[k] apply(k, v) cur[k] = v moved[k] = 1 r = dfs(depth + 1) moved[k] = 0 cur[k] = old undo(k, v) if r: return True if r is None: return None return False dfs(0) return {"K": K, "solved": st["sol"] is not None, "aborted": st["aborted"], "exhausted": not st["aborted"], "nodes": st["nodes"], "secs": round(time.time() - st["t0"], 3), "moves": st["sol"] or []} def main(): ap = argparse.ArgumentParser() ap.add_argument("mode", choices=["k1", "k2", "solve", "report"]) ap.add_argument("--state", default=os.path.join(HERE, "state-n25.json")) ap.add_argument("--start", type=int, default=227) ap.add_argument("--R", type=int, default=2069) ap.add_argument("--K", type=int, default=4) ap.add_argument("--nodes", type=int, default=20000000) ap.add_argument("--secs", type=float, default=500.0) ap.add_argument("--order", default="hole") ap.add_argument("--out", default=None) a = ap.parse_args() res = json.load(open(a.state, encoding="utf-8"))["residues"] rec = {"mode": a.mode, "start": a.start, "R": a.R, "n": len(res)} if a.mode != "report": cov = Cov(res, a.start, a.R) rec["holes_at_start"] = cov.holes0 t0 = time.time() if a.mode == "k1": rec.update(exhaust_k1(cov, a.secs)) elif a.mode == "k2": rec.update(exhaust_k2(cov, a.secs)) else: rec.update(solve_dfs(cov, a.K, a.nodes, a.secs, a.order)) rec["wall"] = round(time.time() - t0, 2) sys.stderr.write(json.dumps({k: rec[k] for k in rec if k != "solutions"}) + "\n") if a.out: open(a.out, "w", encoding="utf-8", newline="\n").write(json.dumps(rec, indent=1) + "\n") print(json.dumps(rec, indent=1)) return 0 if __name__ == "__main__": sys.exit(main())