#!/usr/bin/env python3 """Job #1843 (route 64): merge the census shards, cross-check the two engines, tabulate rigidity. Three jobs in one pass: 1. MERGE. Combine the per-shard JSON written by job1838-ext.py (the implementation return #970 wrote from the definition) into one census artifact. The artifact carries no timing field, so re-running reproduces it byte for byte. 2. CROSS-CHECK. Compare that census against the independently written Rust engine (rust/kstar_census.rs): analysed count, the full max_cover histogram, the best value, and every window at max_cover >= 29 with its start, capacity, max_cover and nine-prime phase vector. Two implementations that agree on the histogram of 8,232 windows and on every phase of every near-miss are much stronger evidence than one. 3. RIGIDITY. For every window short of 30 by one slot, rebuild its 30 natal survivors from scratch by trial division - no bitsets, no engine, no shared code with either search - recount the kills of the recorded phase vector, and tabulate, per prime, the chosen phase, its total kills, its private kills, and the marginal gain of each phase that would kill the uncovered slot. Then ask the route's actual question across windows: is one prime binding in all of them, and does every prime hold private slots in every optimum? Usage: python merge_census.py --shards 'shards/first-*.json' --rust rust-first.json \ --out census-first.json --table rigidity-first.txt """ import argparse import glob import json import sys from collections import Counter Q = (41, 43, 47, 53, 59, 61, 67, 71, 73) L = 30 PRIMES = (5, 7, 11, 13, 17, 19, 23, 29, 31, 37) FULL = (1 << L) - 1 def window_survivors(start): """The 30 natal survivors of the window beginning at `start`, rebuilt by trial division. Scans x = 6i+5 upward from just below `start` testing primality of x and x+2 against 5..37, with no sieve array and no imported code. The 30 survivors of a window span ~170 in x (the survivor density is ~0.176 per unit x), so the loop is short by construction. """ out = [] i = max(0, (start - 60) // 6) while len(out) < L: x = 6 * i + 5 i += 1 if x < start: continue if all(x % p and (x + 2) % p for p in PRIMES): out.append(x) if out[0] != start: raise AssertionError("start %d is not a natal survivor" % start) return out def kills(xv, q, a): """Slots of the window killed by one scour prime at one phase: x = a or x+2 = a (mod q).""" return [i for i, x in enumerate(xv) if x % q == a or (x + 2) % q == a] def recheck(xv, phases): """Engine-free recount: how many of the 30 slots the recorded phase vector kills.""" killed = sorted({i for q in Q for i in kills(xv, q, phases[str(q)])}) return len(killed), [i for i in range(L) if i not in killed] def rigidity(start, phases): """The route's per-window table: private sets and the marginal gain of reaching the gap.""" xv = window_survivors(start) ks = {q: kills(xv, q, phases[str(q)]) for q in Q} union = sorted({i for q in Q for i in ks[q]}) uncovered = [i for i in range(L) if i not in union] covered = len(union) mult = {i: sum(1 for q in Q if i in ks[q]) for i in range(L)} mult_hist = {} for i in range(L): mult_hist[mult[i]] = mult_hist.get(mult[i], 0) + 1 priv = {} for q in Q: priv[q] = [i for i in ks[q] if all(i not in ks[qq] for qq in Q if qq != q)] rows = [] for u in uncovered: per = [] for q in Q: others = {i for qq in Q if qq != q for i in ks[qq]} base = len(others | set(ks[q])) cand = sorted({xv[u] % q, (xv[u] + 2) % q}) gains = [] for b in cand: kb = set(kills(xv, q, b)) gains.append(len(others | kb) - base) per.append({"q": q, "chosen_phase": phases[str(q)], "chosen_kills": len(ks[q]), "chosen_private": len(priv[q]), "would_kill_phases": cand, "marginal_gain": gains}) rows.append({"slot": u, "value": xv[u], "per_prime": per}) binding = sorted(({"q": r["q"], "best_gain": max(r["marginal_gain"])} for r in rows[0]["per_prime"]), key=lambda d: -d["best_gain"]) if rows else [] return {"start": start, "slots": xv, "phases": phases, "covered": covered, "uncovered_slots": uncovered, "uncovered_values": [xv[i] for i in uncovered], "private_slots_per_prime": {str(q): len(priv[q]) for q in Q}, "private_total": sum(len(v) for v in priv.values()), "kill_multiplicity_histogram": {str(k): mult_hist[k] for k in sorted(mult_hist)}, "shared_slots": sum(1 for i in range(L) if mult[i] >= 2), "every_prime_has_a_private_slot": all(len(priv[q]) >= 1 for q in Q), "binding_by_marginal_gain": binding, "rows": rows} def main(): ap = argparse.ArgumentParser() ap.add_argument("--shards", required=True) ap.add_argument("--rust", required=True) ap.add_argument("--out", required=True) ap.add_argument("--table", required=True) a = ap.parse_args() files = sorted(glob.glob(a.shards)) if not files: print(json.dumps({"ok": False, "reason": "no shard files matched " + a.shards})) return 2 hist = Counter() analysed = 0 best = 0 near = [] ranges = [] for f in files: d = json.load(open(f, encoding="utf-8")) analysed += d["analysed"] best = max(best, d["best_max_cover"]) for k, v in d["max_cover_histogram"].items(): hist[int(k)] += v for rec in d["near_misses"]: near.append(rec) ranges.append([d["lo"], d["hi"]]) near.sort(key=lambda r: r["start"]) rust = json.load(open(a.rust, encoding="utf-8")) rust_near = sorted(rust["near_miss_starts"], key=lambda r: r["start"]) checks = [] checks.append(("analysed", analysed == rust["analysed"], analysed, rust["analysed"])) checks.append(("best_max_cover", best == rust["best_max_cover"], best, rust["best_max_cover"])) py_hist = {str(k): hist[k] for k in sorted(hist)} checks.append(("histogram", py_hist == rust["max_cover_histogram"], py_hist, rust["max_cover_histogram"])) checks.append(("near_miss_count", len(near) == len(rust_near), len(near), len(rust_near))) # Per-window agreement. The value, the start and the capacity must match exactly. The phase # vector need not: a window can carry more than one optimal assignment, and demanding the same # one would be a stronger claim than the mathematics supports. Where they differ, both vectors # are recounted separately below by the engine-free trial-division check, so neither engine is # taken on trust; the window is recorded as carrying an alternative optimum. alternate = [] same = len(near) == len(rust_near) if same: for p, r in zip(near, rust_near): key = ("start", "capacity", "max_cover") if tuple(p[k] for k in key) != tuple(r[k] for k in key): same = False checks.append(("near_miss_%d" % p["start"], False, {k: p[k] for k in key}, {k: r[k] for k in key})) elif p["phases"] != r["phases"]: alternate.append({"start": p["start"], "python": p["phases"], "rust": r["phases"]}) checks.append(("near_miss_value_agreement", same, len(near), len(rust_near))) for alt in alternate: xv = window_survivors(alt["start"]) alt["python_recount"] = recheck(xv, alt["python"])[0] alt["rust_recount"] = recheck(xv, alt["rust"])[0] alt["both_are_valid_optima"] = (alt["python_recount"] == alt["rust_recount"]) checks.append(("alternative_optimum_%d" % alt["start"], bool(alt["both_are_valid_optima"]), alt["python_recount"], alt["rust_recount"])) # engine-free recheck of every near-miss, and the cross-window rigidity table windows = [] for rec in near: xv = window_survivors(rec["start"]) n, unc = recheck(xv, rec["phases"]) assert n == rec["max_cover"], (rec["start"], n, rec["max_cover"]) rid = rigidity(rec["start"], rec["phases"]) assert rid["slots"] == xv assert rid["uncovered_slots"] == unc rid["capacity"] = rec["capacity"] rid["max_cover"] = rec["max_cover"] windows.append(rid) binding_sets = [] for w in windows: b = [d["q"] for d in w["binding_by_marginal_gain"] if d["best_gain"] == w["binding_by_marginal_gain"][0]["best_gain"]] binding_sets.append({"start": w["start"], "best_gain": w["binding_by_marginal_gain"][0]["best_gain"], "primes": b}) all_private = all(w["private_total"] == w["max_cover"] for w in windows) common = set(binding_sets[0]["primes"]) if binding_sets else set() for b in binding_sets[1:]: common &= set(b["primes"]) artifact = { "mode": "max_cover_census", "object": ("natal survivors x = 6i+5 with no prime 5..37 dividing x or x+2; a window is 30 " "consecutive survivors; scour primes Q = 41..73 with one phase a_q per prime; a " "slot is killed iff x = a_q or x+2 = a_q (mod q); capacity = the admissible " "union bound sum_q max_a |kill(q,a)|; max_cover = the exact maximum, by branch " "and bound over the capacity >= 33 windows"), "min_capacity": 33, "blocks": ranges, "analysed": analysed, "max_cover_histogram": py_hist, "best_max_cover": best, "slots_short_of_L": L - best, "near_miss_count": len(near), "window_count": len(windows), "windows": windows, "cross_engine": { "engines": ["job1838-ext.py (python, return #970's implementation)", "kstar_census.rs (rust, written this job from the definition)"], "checks": [{"name": n, "ok": bool(ok), "python": p, "rust": r} for n, ok, p, r in checks], "all_ok": all(ok for _, ok, _, _ in checks), "windows_with_alternative_optima": alternate, }, "rigidity_summary": { "all_optima_are_private_partitions": all_private, "every_prime_has_a_private_slot_in_every_window": all(w["every_prime_has_a_private_slot"] for w in windows), "binding_primes_per_window": binding_sets, "prime_binding_in_every_window": sorted(common), }, } text = json.dumps(artifact, indent=1, sort_keys=False) with open(a.out, "w", encoding="utf-8", newline="\n") as fh: fh.write(text + "\n") lines = [] lines.append("windows = %d, analysed = %d, best = %d (short by %d)" % (len(windows), analysed, best, L - best)) lines.append("") lines.append("start cap max uncovered(slot,value) private counts 41/43/47/53/59/61/67/71/73" " best-gain binding") for w in windows: priv = "/".join(str(w["private_slots_per_prime"][str(q)]) for q in Q) b = [d for d in w["binding_by_marginal_gain"] if d["best_gain"] == w["binding_by_marginal_gain"][0]["best_gain"]] lines.append("%-10d %-4d %-4d (slot %d, %d) %s %+d %s" % (w["start"], w["capacity"], w["max_cover"], w["uncovered_slots"][0], w["uncovered_values"][0], priv, b[0]["best_gain"], ",".join(str(d["q"]) for d in b))) lines.append("") lines.append("covered slots split privately (sum of private counts = max_cover): %s" % all_private) lines.append("every prime holds >= 1 private slot, in every window: %s" % all(w["every_prime_has_a_private_slot"] for w in windows)) lines.append("kill multiplicity per window (slots killed by 1 / 2 / 3 primes, uncovered):") for w in windows: h = w["kill_multiplicity_histogram"] lines.append(" start %-10d %s" % (w["start"], " ".join("%sx%s" % (k, h[k]) for k in sorted(h, key=int)))) lines.append("primes binding (max marginal gain) in EVERY window: %s" % (sorted(common) if common else "none")) lines.append("") lines.append("per-prime rigidity across the %d windows:" % len(windows)) lines.append(" q private-count vector (one entry per window) binding-in") for q in Q: vec = [w["private_slots_per_prime"][str(q)] for w in windows] nb = sum(1 for b in binding_sets if q in b["primes"]) lines.append(" %-4d %-42s %d" % (q, str(vec), nb)) lines.append("") lines.append("cross-engine checks:") for n, ok, p, r in checks: lines.append(" %-22s %s" % (n, "OK" if ok else "MISMATCH: %r vs %r" % (p, r))) with open(a.table, "w", encoding="utf-8", newline="\n") as fh: fh.write("\n".join(lines) + "\n") print("\n".join(lines)) return 0 if artifact["cross_engine"]["all_ok"] else 1 if __name__ == "__main__": raise SystemExit(main())