#!/usr/bin/env python3 """inc97.py — route 97 pursuit #4139: incremental/cached star-Hunter prune inside Wang's DFS. The search semantics are IDENTICAL to the served `dfs97.py` (sha 13ada477...): model block k <-> integer 6k; p >= 5 kills k iff (k + s) = +-6^-1 (mod p); a = 6R + 5 masks kill_masks(p, T) built class by class in r = 0..p-1 order, duplicates merged centre rule c = max(S, key=(capacity, p)) (ties -> larger p) dedup per node, classes of the next prime whose `m & U` was already seen are skipped nodes one count per dfs() call (root included); totals summed over T = 1..R+1 prune bound(U, S) < |U| -> infeasible Fast path (same values, fewer operations): * int.bit_count() instead of bin(x).count("1") * one (m & V).bit_count() per (centre-class, leaf-class) pair instead of two popcounts * mask lists without multiplicity (the bounds ignore the multiplicities, as dfs97 does) Parallel mode decomposes one T into one task per deduped root class and reconstructs the sequential node total by summing tasks in class order up to the first success, so the reported totals equal the sequential totals by construction. Usage: python inc97.py --single N PRUNE [--out F] # one ladder row, single core python inc97.py --row N PRUNE [--jobs J] [--out F] python inc97.py --task N PRUNE T K0 # one parallel task (diagnostic) python inc97.py --probe N PRUNE --T T [--nodecap M] [--wall S] python inc97.py --validate [--jobs J] """ import argparse import json import multiprocessing as mp import os import sys import time PUBLISHED = {7: 107, 8: 149, 9: 203, 10: 257, 11: 347, 12: 527, 13: 545, 14: 617, 15: 707} NTH_PRIME = [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, 101, 103, 107, 109, 113] def primes_upto(y): return [n for n in range(2, y + 1) if all(n % q for q in range(2, int(n ** 0.5) + 1))] def kill_masks(p, T): """distinct masks over U=[0,T) for residue r = s mod p; same order/dedup as dfs97.""" a = pow(6, -1, p) cls = {a % p, (p - a) % p} d = {} for r in range(p): m = 0 for c in cls: k = (c - r) % p while k < T: m |= 1 << k k += p d[m] = d.get(m, 0) + 1 return list(d.items()) class Searcher: def __init__(self, n, prune, T, nodecap=None): self.Q = [q for q in primes_upto(NTH_PRIME[n - 1]) if q >= 5] self.prune = prune self.T = T self.nodecap = nodecap self.nodes = 0 self.masks = {p: [m for m, _ in kill_masks(p, T)] for p in self.Q} self.full = (1 << T) - 1 def bound_cap(self, U, i): masks = self.masks bc = int.bit_count Q = self.Q tot = 0 for j in range(i, len(Q)): best = 0 for m in masks[Q[j]]: c = bc(m & U) if c > best: best = c tot += best return tot def bound_hunter(self, U, i): masks = self.masks bc = int.bit_count Q = self.Q caps = [] for j in range(i, len(Q)): best = 0 for m in masks[Q[j]]: c = bc(m & U) if c > best: best = c caps.append((best, Q[j])) c = max(caps)[1] # max capacity, ties -> larger prime best_total = 0 for mc in masks[c]: cU = mc & U val = bc(cU) V = U & ~cU for j in range(i, len(Q)): p = Q[j] if p == c: continue best = 0 for m in masks[p]: b = bc(m & V) if b > best: best = b val += best if val > best_total: best_total = val return best_total def bound(self, U, i): if self.prune == "cap": return self.bound_cap(U, i) return self.bound_hunter(U, i) def dfs(self, U, i): self.nodes += 1 if U == 0: return True if self.nodecap is not None and self.nodes > self.nodecap: raise RuntimeError("nodecap") if i >= len(self.Q): return False if self.bound(U, i) < U.bit_count(): return False p = self.Q[i] seen = set() for m in self.masks[p]: nm = m & U if nm in seen: continue seen.add(nm) if self.dfs(U & ~m, i + 1): return True return False def feasible(self): return self.dfs(self.full, 0) def root_classes(self): """the root's deduped class list, in the order dfs() would try it.""" U = self.full out = [] seen = set() for m in self.masks[self.Q[0]]: nm = m & U if nm in seen: continue seen.add(nm) out.append(m) return out def find_R(n, prune, nodecap=None, wall=None): """target-above-max, exact dfs97 order (T = 1, 2, ... until infeasible).""" best = 0 T = 1 t0 = time.time() nodes_total = 0 rows = [] while True: s = Searcher(n, prune, T, nodecap) try: ok = s.feasible() nodes_total += s.nodes except RuntimeError: rows.append({"T": T, "feasible": None, "nodes": s.nodes, "aborted": "nodecap"}) return best, nodes_total, time.time() - t0, "NODECAP@T=%d" % T, rows rows.append({"T": T, "feasible": ok, "nodes": s.nodes}) if wall is not None and time.time() - t0 > wall: return best, nodes_total, time.time() - t0, "WALLCAP@T=%d" % T, rows if ok: best = T T += 1 else: break return best, nodes_total, time.time() - t0, "done", rows # ---------------------------------------------------------------- parallel path _N = None _PRUNE = None def _winit(n, prune): global _N, _PRUNE _N, _PRUNE = n, prune def _wtask(args): """(T, mask) -> (success, nodes, seconds) for the subtree obtained by taking that root class.""" T, m = args s = Searcher(_N, _PRUNE, T) s.nodes = 0 t1 = time.perf_counter() # the depth-1 node is counted by _dfs_body itself, exactly as dfs() does on entry ok = s._dfs_body(s.full & ~m, 1) return (bool(ok), s.nodes, time.perf_counter() - t1) class _Body: pass def _dfs_body(self, U, i): self.nodes += 1 if U == 0: return True if self.nodecap is not None and self.nodes > self.nodecap: raise RuntimeError("nodecap") if i >= len(self.Q): return False if self.bound(U, i) < U.bit_count(): return False p = self.Q[i] seen = set() for m in self.masks[p]: nm = m & U if nm in seen: continue seen.add(nm) if self._dfs_body(U & ~m, i + 1): return True return False Searcher._dfs_body = _dfs_body def upper_T(n): """a safe T bound from the published a(n), or None when a(n) is not in the table.""" a = PUBLISHED.get(n) return None if a is None else (a - 5) // 6 + 2 def row_parallel(n, prune, jobs, out=None, tmax=None): """Full ladder with ONE flat task list over all T (pool stays busy), combined per T in class order with the sequential early exit. The first infeasible T ends the sequential procedure; deeper T's were computed anyway and are checked infeasible.""" t0 = time.time() if tmax is None: tmax = upper_T(n) if tmax is None: raise SystemExit("no published a(n) to bound T; pass --tmax") tasks = [] meta = [] for T in range(1, tmax + 1): s = Searcher(n, prune, T) if s.bound(s.full, 0) < T: meta.append((T, True, 0)) continue classes = s.root_classes() idx0 = len(tasks) tasks += [(T, m) for m in classes] meta.append((T, False, (idx0, len(tasks)))) with mp.Pool(processes=jobs, initializer=_winit, initargs=(n, prune)) as pool: res = pool.map(_wtask, tasks, chunksize=1) cpu = sum(r[2] for r in res) rows = [] for T, pruned, rng in meta: if pruned: cnt, ok = 1, False else: cnt, ok = 1, False for i in range(rng[0], rng[1]): succ, c, _dt = res[i] cnt += c if succ: ok = True break rows.append({"T": T, "feasible": ok, "nodes": cnt}) first_inf = next((i for i, r in enumerate(rows) if not r["feasible"]), None) if first_inf is None: raise SystemExit("every T <= %d was feasible; raise --tmax" % tmax) if any(r["feasible"] for r in rows[first_inf + 1:]): raise SystemExit("monotonicity violated above T=%d" % rows[first_inf]["T"]) best = rows[first_inf - 1]["T"] if first_inf > 0 else 0 nodes_total = sum(r["nodes"] for r in rows[:first_inf + 1]) dt = time.time() - t0 result = {"n": n, "prune": prune, "jobs": jobs, "R": best, "a": 6 * best + 5, "published": PUBLISHED.get(n), "nodes": nodes_total, "wall_s": dt, "cpu_s": cpu, "tasks": len(tasks), "tmax": tmax, "rows": rows} if out: with open(out, "w", encoding="utf-8", newline="\n") as fh: json.dump(result, fh, indent=1) fh.write("\n") print(json.dumps({k: v for k, v in result.items() if k != "rows"}, indent=1)) return result def main(): ap = argparse.ArgumentParser() ap.add_argument("--single", nargs=2, metavar=("N", "PRUNE")) ap.add_argument("--row", nargs=2, metavar=("N", "PRUNE")) ap.add_argument("--task", nargs=4, metavar=("N", "PRUNE", "T", "K0")) ap.add_argument("--probe", nargs=2, metavar=("N", "PRUNE")) ap.add_argument("--validate", action="store_true") ap.add_argument("--T", type=int) ap.add_argument("--nodecap", type=int) ap.add_argument("--wall", type=float) ap.add_argument("--jobs", type=int, default=max(1, min(12, (os.cpu_count() or 4) - 2))) ap.add_argument("--tmax", type=int) ap.add_argument("--out") a = ap.parse_args() if a.single: n, prune = int(a.single[0]), a.single[1] R, nodes, dt, why, rows = find_R(n, prune) out = {"n": n, "prune": prune, "R": R, "a": 6 * R + 5, "published": PUBLISHED.get(n), "nodes": nodes, "wall_s": dt, "why": why, "rows": rows} if a.out: json.dump(out, open(a.out, "w", encoding="utf-8", newline="\n"), indent=1) print(json.dumps({k: v for k, v in out.items() if k != "rows"}, indent=1)) return 0 if a.row: n, prune = int(a.row[0]), a.row[1] row_parallel(n, prune, a.jobs, a.out, tmax=a.tmax) return 0 if a.task: n, prune, T, k0 = int(a.task[0]), a.task[1], int(a.task[2]), int(a.task[3]) _winit(n, prune) s = Searcher(n, prune, T) classes = s.root_classes() m = classes[k0] succ, cnt = _wtask((T, m)) print(json.dumps({"n": n, "prune": prune, "T": T, "k0": k0, "classes": len(classes), "success": succ, "nodes": cnt})) return 0 if a.probe: n, prune = int(a.probe[0]), a.probe[1] T = a.T or 1 R, nodes, dt, why, rows = find_R(n, prune, nodecap=a.nodecap, wall=a.wall) out = {"n": n, "prune": prune, "R": R, "a": 6 * R + 5, "nodes": nodes, "wall_s": dt, "why": why, "nodecap": a.nodecap, "wallcap": a.wall, "rate_nodes_per_s": (nodes / dt) if dt > 0 else None} if a.out: json.dump(out, open(a.out, "w", encoding="utf-8", newline="\n"), indent=1) print(json.dumps(out, indent=1)) return 0 if a.validate: # published rows: n = 7..13 both prunes, n = 14 capacity (sequential) rows_pub = {7: (512, 300), 8: (1944, 928), 9: (5235, 2568), 10: (30873, 14755), 11: (111527, 52854), 12: (230923, 90439), 13: (1285505, 427609)} all_ok = True report = [] for n in range(7, 14): for prune in ("cap", "hunter"): R, nodes, dt, why, _ = find_R(n, prune) want = rows_pub[n][0 if prune == "cap" else 1] ok = (nodes == want) and (6 * R + 5 == PUBLISHED.get(n)) all_ok &= ok report.append({"n": n, "prune": prune, "R": R, "a": 6 * R + 5, "nodes": nodes, "want_nodes": want, "match": ok, "wall_s": round(dt, 2), "rate": round(nodes / dt) if dt > 0 else None}) print(json.dumps(report[-1]), flush=True) R, nodes, dt, why, _ = find_R(14, "cap") ok = nodes == 9115262 and R == 102 all_ok &= ok report.append({"n": 14, "prune": "cap", "R": R, "a": 6 * R + 5, "nodes": nodes, "want_nodes": 9115262, "match": ok, "wall_s": round(dt, 2), "rate": round(nodes / dt) if dt > 0 else None}) print(json.dumps(report[-1]), flush=True) if a.out: json.dump(report, open(a.out, "w", encoding="utf-8", newline="\n"), indent=1) print("VALIDATE", "PASS" if all_ok else "FAIL") return 0 if all_ok else 1 ap.error("nothing to do") if __name__ == "__main__": sys.exit(main())