#!/usr/bin/env python3 """job 2754 / route 116 -- the repointed step of return #1371. Does an ARRANGEMENT statistic of the winning union run bound the killer marginal, where every function of single-step data (A, q1, q2) was refuted by #1371 and by #1370? For a row (P, R, E), U = R u E, L = P*prod(U), K = K*(P,U), A = K*(P,R): W = the maximal U-killed run of length K with the SMALLEST first slot (tie-break fixed in prereg-arrangement.md; the identities are window-independent, the statistics are not) F = number of maximal R-killed stretches of consecutive alive positions inside W (the FRAGMENT COUNT) S = |W| - #(R-killed positions of W) (the ENTERING-PRIME KILLS inside W) sigma = slot span of W = (last - first) (the CHAIN SPAN) rho = P / #(alive slots per period) (mean alive-slot gap) Everything is pre-registered in job2732/prereg-arrangement.md, hashed before any statistic was computed; every measurement mode re-verifies that hash first and refuses to report without it. The window is materialised by WALKING the alive sequence from its first slot (gcd conditions only, no masks), which is exact for a cyclically wrapping run too; in the direct mode the walked window is required to reproduce the mask-based window's slot set, so the two constructions cheque each other. MODES --mode gates custody: the five published K* values, direct and windowed --mode crosscheck walked window vs mask window on a 2.2e8-slot modulus --mode composite #1365's composite sweep (P in {30,210}, |R|<=2, E={q1,q2}, 3282 rows) --mode class-r5 the 12 |R|=5 rows of return #1370 --mode class-p30030 the four P=30030, |R|=3 rows of return #1370 (6.47e9 slots) Exit 3 if a must-hold claim (A1-A4, A7) is violated: that is an instrument defect, not evidence. Exit 4 if the windowed scan is still incomplete (resumable: pass --state). """ import argparse import hashlib import importlib.util import itertools import json import os import sys import time import numpy as np HERE = os.path.dirname(os.path.abspath(__file__)) VERSION = "1.0.0" def note(*a, **kw): """Diagnostics to STDERR. stdout is the artifact and must reproduce byte for byte elsewhere; per-run progress and timings never can. This is the whole of the repair: no value, threshold, order or arithmetic changes. A caller's `flush=True` (left in place by the minimal diff) is accepted and absorbed. """ kw.pop("flush", None) print(*a, file=sys.stderr, flush=True, **kw) PREREG = "prereg-arrangement.md" spec = importlib.util.spec_from_file_location("km", os.path.join(HERE, "killer-marginal.py")) km = importlib.util.module_from_spec(spec) spec.loader.exec_module(km) slot_pattern, killed_mask, max_cyclic_run = km.slot_pattern, km.killed_mask, km.max_cyclic_run GATES, PRIMES = km.GATES, km.PRIMES MUST_HOLD = ("A1_partition", "A2_identity", "A3_S_ge_F_minus_1", "A4_counting", "A7_marg_le_Fminus1_A_plus_S") # --------------------------------------------------------------------- runs in alive-index space def run_list(flags): n = int(flags.size) idx = np.flatnonzero(flags) if idx.size == 0: return [], False if int(idx.size) == n: return [(0, n - 1, n)], False brk = np.flatnonzero(np.diff(idx) != 1) starts = np.concatenate(([0], brk + 1)) ends = np.concatenate((brk, [idx.size - 1])) runs = [(int(idx[s]), int(idx[e]), int(idx[e]) - int(idx[s]) + 1) for s, e in zip(starts, ends)] wraps = bool(len(runs) > 1 and runs[0][0] == 0 and runs[-1][1] == n - 1) return runs, wraps def winning_window(alive_idx, flags, L): """Max length, then smallest first SLOT. Returns (K, first_slot, slot set).""" runs, wraps = run_list(flags) if not runs: return None cand = list(runs) if wraps: cand.append((runs[-1][0], runs[0][1], runs[0][2] + runs[-1][2])) best = None for (s, e, ln) in cand: if s <= e: win = alive_idx[s:e + 1] else: win = np.concatenate((alive_idx[s:], alive_idx[:e + 1])) key = (ln, -int(win[0])) if best is None or key > best[0]: best = (key, ln, int(win[0]), win) return best[1], best[2], set(int(v) for v in best[3]) def walk_window(P, first, K, L): """The K consecutive alive slots starting at the alive slot `first`; linear, wrap-safe, exact.""" out, x = [], first while len(out) < K: if int(np.gcd(x % L, P)) == 1 and int(np.gcd((x + 2) % L, P)) == 1: out.append(x % L) x += 1 return np.array(out, dtype=np.int64) def decompose_slots(P, R, E, slots, K, A, L): """F, S, sigma, and the pre-registered quantities, from the window's own slots.""" fR = np.zeros(slots.size, dtype=bool) for q in R: fR |= (slots % q == 0) | ((slots + 2) % q == 0) frags = sorted((ln for (_, _, ln) in run_list(fR)[0]), reverse=True) sigma = int(slots[-1] - slots[0]) return {"frag_count": len(frags), "frags": frags, "frag_sum": int(sum(frags)), "S": int((~fR).sum()), "killed_by_R": int(fR.sum()), "sigma": sigma, "window_len": int(slots.size), "K": K, "A": A, "marginal": K - A, "first_slot": int(slots[0]), "last_slot": int(slots[-1]), "rho": P / float(int(slot_pattern(P).sum())), "modulus": L, "P": P, "R": list(sorted(R)), "E": list(sorted(E)), "U": list(sorted(set(R) | set(E)))} # -------------------------------------------------------------------------- row builders def masks_row(P, R, E, L): alive = np.tile(slot_pattern(P), L // P) aidx = np.flatnonzero(alive) return alive, aidx, killed_mask(L, tuple(sorted(set(R) | set(E)))) def direct_row(P, R, E, want_K=None, want_A=None): U = tuple(sorted(set(R) | set(E))) L = P for q in U: L *= q alive, aidx, killU = masks_row(P, R, E, L) w = winning_window(aidx, killU[aidx], L) if w is None: raise AssertionError("no killed alive run at all") K, first, wset = w walked = walk_window(P, first, K, L) assert set(int(v) for v in walked) == wset, "walked window != mask window (P=%d U=%s)" % (P, U) d = decompose_slots(P, R, E, walked, K, km.kstar(P, tuple(sorted(R))), L) d["method"] = "direct" if want_K is not None and d["K"] != want_K: raise AssertionError("K mismatch: %s vs %s" % (d["K"], want_K)) if want_A is not None and d["A"] != want_A: raise AssertionError("A mismatch: %s vs %s" % (d["A"], want_A)) return d def composite_rows(cap, maxR=2, progress=500): """#1365's enumeration, recomputed, with A and the composite rise T for custody.""" out = [] cache = {} t0 = time.time() for P in (30, 210): cand = [q for q in PRIMES if P % q] for size in range(0, maxR + 1): for R in itertools.combinations(cand, size): M = P for q in R: M *= q A = km.kstar(P, tuple(R)) # exact on modulus M, periodic => same on Mp basep = [q for q in cand if q not in R] for q1, q2 in itertools.combinations(basep, 2): if M * q1 * q2 > cap: continue Mp = M * q1 * q2 U = tuple(sorted(R + (q1, q2))) key = (P, Mp) if key not in cache: alive = np.tile(slot_pattern(P), Mp // P) cache[key] = (alive, np.flatnonzero(alive)) alive, aidx = cache[key] killR = killed_mask(Mp, tuple(R)) killQ = np.zeros(Mp, dtype=bool) for q in (q1, q2): killQ[0::q] = True killQ[(-2) % q::q] = True w = winning_window(aidx, (killR | killQ)[aidx], Mp) K, first, wset = w walked = walk_window(P, first, K, Mp) assert set(int(v) for v in walked) == wset d = decompose_slots(P, R, (q1, q2), walked, K, A, Mp) d["T"] = max_cyclic_run( np.tile(slot_pattern(P * q1 * q2), Mp // (P * q1 * q2)), killR, Mp) - A d["method"] = "direct" d["Mp"] = Mp out.append(d) if progress and len(out) % progress == 0: note(" %d rows %.1fs" % (len(out), time.time() - t0)) note(" enumerated %d rows in %.1fs" % (len(out), time.time() - t0)) return out # ------------------------------------------------------- windowed scan tracking run POSITIONS def pos_scan_block(B, S, L, window, a0, a1, st): best, carry, first_run, total_alive = st["best"], st["carry"], st["first_run"], st["total_alive"] a = a0 while a < a1: W = min(window, a1 - a) x = np.arange(a, a + W, dtype=np.int64) alive = (np.gcd(x, B) == 1) & (np.gcd(x + 2, B) == 1) killed = np.zeros(W, dtype=bool) for s in S: killed[(-a) % s::s] = True killed[((-2 - a) % s) % s::s] = True flags = killed[alive] n = int(flags.size) total_alive += n if n: runs, _ = run_list(flags) al = np.flatnonzero(alive) opens, closes = bool(flags[0]), bool(flags[-1]) runsl = [(ln, a + int(al[s]), a + int(al[e])) for (s, e, ln) in runs] if opens and carry: runsl[0] = (runsl[0][0] + carry[0], carry[1], runsl[0][2]) if first_run is None and opens and a == 0: first_run = runsl[0] if closes: cl = runsl[-1] carry = (cl[0], cl[1]) rest = runsl[:-1] else: carry = None rest = runsl for t in rest: if best is None or t[0] > best[0] or (t[0] == best[0] and t[1] < best[1]): best = t else: carry = None a += W return {"best": best, "carry": carry, "first_run": first_run, "total_alive": total_alive, "a": a} def pos_scan_finalize(st, L): best, carry, first_run, total_alive = st["best"], st["carry"], st["first_run"], st["total_alive"] win = best[0:3] if best else (0, 0, 0) if carry and carry[0] > win[0]: win = (carry[0], carry[1], L - 1) if first_run is not None and carry and first_run[1] == 0: merged = min(first_run[0] + carry[0], total_alive) if merged > win[0]: win = (merged, carry[1], first_run[2]) return win def pos_scan(B, S, L, window, state_path=None, maxsecs=1e9): st = {"best": None, "carry": None, "first_run": None, "total_alive": 0, "a": 0} if state_path and os.path.exists(state_path): d = json.load(open(state_path, encoding="utf-8")) st = {"best": tuple(d["best"]) if d["best"] else None, "carry": tuple(d["carry"]) if d["carry"] else None, "first_run": tuple(d["first_run"]) if d["first_run"] else None, "total_alive": d["total_alive"], "a": d["a"]} t0 = time.time() while st["a"] < L and time.time() - t0 < maxsecs: a1 = min(L, st["a"] + window * 8) st = pos_scan_block(B, S, L, window, st["a"], a1, st) if state_path: json.dump({k: (list(v) if isinstance(v, tuple) else v) for k, v in st.items()}, open(state_path, "w", encoding="utf-8")) note("scanned %d/%d (%.2f%%) best=%s %.1fs" % (st["a"], L, 100.0 * st["a"] / L, st["best"], time.time() - t0), flush=True) if st["a"] < L: return None, st return pos_scan_finalize(st, L), st # ------------------------------------------------------------------------------- claim verdicts def verdicts(rows): v = lambda f: [r for r in rows if f(r)] # noqa: E731 A1 = v(lambda r: r["frag_sum"] + r["S"] != r["window_len"]) A2 = v(lambda r: r["marginal"] != r["frag_sum"] + r["S"] - r["A"]) A3 = v(lambda r: r["S"] < r["frag_count"] - 1) A4 = v(lambda r: r["S"] > sum(2 * (r["sigma"] // q + 1) for q in r["E"])) A5 = v(lambda r: r["S"] >= r["frag_count"] + 2) A6 = v(lambda r: r["sigma"] > r["rho"] * r["window_len"]) A7 = v(lambda r: r["marginal"] > (r["frag_count"] - 1) * r["A"] + r["S"]) A9 = v(lambda r: r["frag_count"] > r["A"]) A10 = v(lambda r: r["marginal"] > (r["frag_count"] - 1) * (r["A"] + 1) + 1) claims = {} for cid, bad in (("A1_partition", A1), ("A2_identity", A2), ("A3_S_ge_F_minus_1", A3), ("A4_counting", A4), ("A5_S_le_F_plus_1", A5), ("A6_sigma_le_rho_K", A6), ("A7_marg_le_Fminus1_A_plus_S", A7), ("A9_F_le_A", A9), ("A10_marg_le_Fminus1_Aplus1_plus1", A10)): entry = {"violations": len(bad), "of": len(rows)} if bad: entry["example"] = {k: bad[0][k] for k in ("P", "R", "E", "A", "K", "marginal", "frag_count", "S", "sigma")} if cid == "A5_S_le_F_plus_1": entry["worst_excess"] = max(r["S"] - r["frag_count"] - 1 for r in bad) if cid == "A6_sigma_le_rho_K": entry["worst_ratio"] = round(max(r["sigma"] / (r["rho"] * r["window_len"]) for r in bad), 3) if cid == "A9_F_le_A": entry["worst_excess"] = max(r["frag_count"] - r["A"] for r in bad) if cid == "A10_marg_le_Fminus1_Aplus1_plus1": entry["worst_excess"] = max(r["marginal"] - (r["frag_count"] - 1) * (r["A"] + 1) - 1 for r in bad) claims[cid] = entry two = [r for r in rows if len(r["E"]) == 2] if two: cells = {} for r in two: cells.setdefault((r["A"], r["E"][0], r["E"][1]), set()).add(r["frag_count"]) multi = sum(1 for s in cells.values() if len(s) > 1) claims["A8_F_not_determined_by_A_q1_q2"] = { "cells": len(cells), "cells_with_two_frag_counts": multi, "verdict": ("FAIL -- F is single-step data (no cell splits)" if multi == 0 else "PASS -- F is not single-step data")} ratios = sorted(r["sigma"] / (r["rho"] * r["window_len"]) for r in rows) or [0.0] dist = {"F_hist": {str(k): sum(1 for r in rows if r["frag_count"] == k) for k in sorted({r["frag_count"] for r in rows})}, "S_hist": {str(k): sum(1 for r in rows if r["S"] == k) for k in sorted({r["S"] for r in rows})}, "max_F": max((r["frag_count"] for r in rows), default=None), "max_S": max((r["S"] for r in rows), default=None), "max_marginal": max((r["marginal"] for r in rows), default=None), "sigma_over_rhoK": {"min": round(ratios[0], 3), "median": round(ratios[len(ratios) // 2], 3), "max": round(ratios[-1], 3)}} return {"rows": len(rows), "claims": claims, "distributions": dist, "must_hold_violations": {k: claims[k]["violations"] for k in MUST_HOLD}} def write_out(out_path, obj): with open(os.path.join(HERE, out_path), "w", encoding="utf-8", newline="\n") as fh: json.dump(obj, fh, indent=1, sort_keys=True) fh.write("\n") note("wrote " + out_path) def check_prereg(): """The recorded hash file: `-sha.txt`, because the artefact server rejects `.sha256` and `.sha`.""" h = hashlib.sha256(open(os.path.join(HERE, PREREG), "rb").read()).hexdigest() for cand in (PREREG.replace(".md", "-sha.txt"), PREREG.replace(".md", ".sha")): p = os.path.join(HERE, cand) if os.path.exists(p): break rec = open(p, encoding="utf-8").read().split()[0] ok = h == rec note("prereg %s sha256 %s recorded %s %s" % (PREREG, h[:16], rec[:16], "MATCH" if ok else "MISMATCH")) return h, ok # -------------------------------------------------------------------------------------- modes def mode_gates(): ok = True for (B, S, want) in GATES: L = B for q in S: L *= q got, got2 = km.kstar(B, S), km.blocked_kstar(B, S, L, 1 << 25) good = got == want == got2 ok = ok and good note("K*(%-4d,%-18s) want %2d direct %2d windowed %2d %s" % (B, "{" + ",".join(map(str, S)) + "}", want, got, got2, "PASS" if good else "FAIL")) note("gates all pass: %s" % ok) return 0 if ok else 3 def mode_crosscheck(): P, R, E = 30, (7, 11, 13, 17, 19), (23,) d = direct_row(P, R, E) L = d["modulus"] K2, st = pos_scan(P, tuple(d["U"]), L, 1 << 25) if K2 is None: note("incomplete scan"); return 4 walked = walk_window(P, K2[1], K2[0], L) w = decompose_slots(P, R, E, walked, K2[0], d["A"], L) same = all(d[k] == w[k] for k in ("window_len", "first_slot", "frag_count", "S", "frag_sum", "sigma", "K")) print(json.dumps({"mode": "crosscheck", "modulus": L, "scan_K": K2, "direct": {k: d[k] for k in ("K", "A", "window_len", "first_slot", "last_slot", "frag_count", "frags", "S", "frag_sum", "sigma")}, "windowed": {k: w[k] for k in ("K", "A", "window_len", "first_slot", "last_slot", "frag_count", "frags", "S", "frag_sum", "sigma")}, "agree": same}, indent=1)) return 0 if same else 3 def mode_composite(out_path, cap=2_000_000): rec = json.load(open(os.path.join(HERE, "compose-2e6.json"), encoding="utf-8")) rows = composite_rows(cap) t_hist = {} for r in rows: t_hist[str(r["T"])] = t_hist.get(str(r["T"]), 0) + 1 custody = { "rows": [len(rows), rec["rows"]], "rows_match": len(rows) == rec["rows"], "T_hist": [t_hist, rec["T_hist"]], "T_hist_match": t_hist == rec["T_hist"], "max_T": [max(r["T"] for r in rows), rec["max_T"]], "max_marginal": [max(r["marginal"] for r in rows), rec["max_marg2"]], "rise_le_marginal_all": sum(1 for r in rows if r["T"] <= r["marginal"]), "rows": len(rows), } custody["maths_match"] = (custody["max_T"][0] == custody["max_T"][1] and custody["max_marginal"][0] == custody["max_marginal"][1]) custody["all_match"] = (custody["rows_match"] and custody["T_hist_match"] and custody["maths_match"] and custody["rise_le_marginal_all"] == len(rows)) print(json.dumps(custody, indent=1)) if not custody["all_match"]: note("REFUSING: recomputation does not reproduce #1365's recorded composite statistics.") return 3 res = {"tool": "job2732/arrangement-stats.py", "version": VERSION, "mode": "composite", "cap": cap, "custody": custody, "rows": rows, "verdicts": verdicts(rows)} print(json.dumps(res["verdicts"], indent=1, sort_keys=True)) write_out(out_path, res) return 0 def mode_class_r5(out_path): d = json.load(open(os.path.join(HERE, "rows-r5.json"), encoding="utf-8")) rows = [] for r in d["rows"]: x = direct_row(r["P"], tuple(r["R"]), (r["p"],), want_K=r["K"], want_A=r["A"]) assert x["marginal"] == r["marginal"], (x, r) rows.append(x) note("P=%-4d R=%-18s q=%-3d A=%-3d K=%-3d marg=%-3d F=%-2d S=%-2d sigma=%-5d frags=%s" % (r["P"], r["R"], r["p"], x["A"], x["K"], x["marginal"], x["frag_count"], x["S"], x["sigma"], x["frags"])) res = {"tool": "job2732/arrangement-stats.py", "version": VERSION, "mode": "class-r5", "source": "rows-r5.json (return #1370's served |R|=5 class)", "rows": rows, "verdicts": verdicts(rows)} write_out(out_path, res) print(json.dumps(res["verdicts"], indent=1, sort_keys=True)) return 0 def mode_class_p30030(out_path, state_path, maxsecs, window): P, U = 30030, (17, 19, 23, 29) L = P for q in U: L *= q src = json.load(open(os.path.join(HERE, "margin-p30030.json"), encoding="utf-8")) fresh = [r for r in src["fresh_rows_detail"] if r["nR"] == 3] A_by = {(tuple(r["R"]), r["q"]): r["A"] for r in fresh} K_rec = 10 # recorded by #1370 for K*(30030,{17,19,23,29}) note("rows in class: %d A values: %s" % (len(A_by), sorted(A_by.values()))) win, st = pos_scan(P, U, L, window, state_path, maxsecs) if win is None: print(json.dumps({"mode": "class-p30030", "incomplete": True, "scanned": st["a"], "of": L, "state": state_path})) return 4 walked = walk_window(P, win[1], win[0], L) note("scan complete: K=%d (recorded %d) window first=%d last=%d len=%d" % (win[0], K_rec, win[1], win[2], walked.size)) if win[0] != K_rec: note("REFUSING: windowed scan disagrees with the recorded K*") return 3 rows = [decompose_slots(P, tuple(R), (q,), walked, win[0], A_by[(R, q)], L) for (R, q) in sorted(A_by)] res = {"tool": "job2732/arrangement-stats.py", "version": VERSION, "mode": "class-p30030", "source": "margin-p30030.json (return #1370's served |R|=3 class)", "modulus": L, "U": list(U), "K_star": win[0], "window": {"first": win[1], "last": win[2], "len": int(walked.size)}, "rows": rows, "verdicts": verdicts(rows)} write_out(out_path, res) for r in rows: note("R=%-18s q=%-3d A=%-3d K=%-3d marg=%-3d F=%-2d S=%-2d sigma=%-5d frags=%s" % (r["R"], r["E"][0], r["A"], r["K"], r["marginal"], r["frag_count"], r["S"], r["sigma"], r["frags"])) print(json.dumps(res["verdicts"], indent=1, sort_keys=True)) return 0 def main(): ap = argparse.ArgumentParser() ap.add_argument("--mode", required=True) ap.add_argument("--out", default=None) ap.add_argument("--cap", type=int, default=2_000_000) ap.add_argument("--state", default=None) ap.add_argument("--maxsecs", type=float, default=1e9) ap.add_argument("--window", type=int, default=1 << 25) a = ap.parse_args() if a.mode == "gates": return mode_gates() _, okp = check_prereg() if not okp: print(json.dumps({"ok": False, "stage": "prereg hash mismatch"}, indent=1)) return 3 if a.mode == "crosscheck": return mode_crosscheck() if a.mode == "composite": return mode_composite(a.out or "arrangement-composite.json", a.cap) if a.mode == "class-r5": return mode_class_r5(a.out or "arrangement-r5.json") if a.mode == "class-p30030": return mode_class_p30030(a.out or "arrangement-p30030.json", a.state, a.maxsecs, a.window) raise SystemExit("unknown mode " + a.mode) if __name__ == "__main__": sys.exit(main())