"""Job #2560 -- "Leads: new statistic". THE SHORT-WINDOW UNION-BOUND DEFECT. Everything above the code block marked PRE-REGISTRATION is written BEFORE the first run of this file. Nothing below it was used to choose a prediction, a band or a threshold. -------------------------------------------------------------------------------------------- THE STATISTIC -------------------------------------------------------------------------------------------- Level x, offset class tau, period W = x# (primorial). The killed set of return #693 (job #1486) is K(tau) = union_{p<=x} {r : r = 0 or r = -tau (mod p)}, and with w(r) = #{p <= x : p | r or p | (r+tau)} the exact identity of that return is |K| = W - hist[0] = sum_{k>=1} (-1)^(k-1) S_k, S_k := sum_r C(w(r), k), defect := S_1 - |K| = S_2 - S_3 + S_4 - ... #693 measured S_k and the defect over ONE FULL PERIOD and disclosed the gap in its own words: "the ladder above measures the defect over one full period W -- the long-window limit. Costello-Watts need *short* windows: at x = 11, cover(2) = 41 against W = 2310, so m ~ 41 ...". No retained census carries a window-conditioned quantity, so the retained censuses cannot decide what follows; the period ladder is the only thing on the record. NEW STATISTIC. For a window length m and an alignment omega (circular, omega in [0, W)), let S_k(omega) = sum_{r in [omega, omega+m)} C(w(r), k), Kw(omega) = m - #(w == 0 in window), defect(omega) = S_1(omega) - Kw(omega), P_k(omega) = the alternating partial sum through k, order(omega) = min k with |P_k(omega) - Kw(omega)| <= 0.1 * Kw(omega) ("order @10%", #693's rule), and define the density-scaled window ratio and the alignment spread R(omega) = defect(omega) / ( (m/W) * defect_W ) [defect_W = the period value of #693] SPREAD(m) = max_omega R / min_omega R, MED(m) = median_omega R, ORD90(m) = the 90th percentile of order(omega) vs order_W (the period's order @10%). THE DECISION IT INFORMS. Whether the period ladder may stand in for the short-window ladder in a bound of the Costello-Watts shape (arXiv:1208.5342, used by routes 112 and by #693's own re-aimed next step): if the window defect is proportional to the window's share of the period and its truncation order is stable, the period cost model transfers and a short-window bound can be priced from published numbers; if either fails, every short-window bound must be computed per window and #693's cost model -- which is a cost measured at the wrong scale -- must be repaired before it is used to price anything. -------------------------------------------------------------------------------------------- PRE-REGISTRATION (frozen before the run; levels, lengths, falsifiers, controls, and the gate) -------------------------------------------------------------------------------------------- Levels: x in {5, 7, 11, 13} first, then {17, 19} if the memory/time budget permits; tau in {0, 2}. Window lengths: m1 = cover(tau)+1, m2 = 2*m1, m3 = 8*m1, m4 = the largest power of two dividing down from W with at least 64 windows per period (fixing the ladder before the numbers exist). Window lengths are FIXED by the ladder rule, not chosen after seeing R. FALSIFIERS (a failure is a result, not a repair target): F1 MED(m) in [0.5, 2.0] for every (x, tau, m) cell -- R is order-unity. F2 ORD90(m) <= order_W + 1 for every cell -- order is stable. F3 SPREAD(m) <= 4 at the smallest length m1 in every cell -- alignment is mild. F1 fails => the period defect does not scale to a window: the short-window bound needs its own measurement and the period ladder is not a substitute. F2 fails => the truncation order a window needs exceeds the period's, so the cost model of #693 (order ~ lambda from the period ladder) understates the short-window cost. F3 fails => the alignment (the analogue of Costello-Watts's free window position b) is a large dial, and a bound must be uniform over it rather than evaluated at one position. MATCHED CONTROLS (both destroy the arithmetic structure while preserving the window machinery): C1 independent thinning: replace K by a Bernoulli(p_hat) random set, p_hat = |K|/W, seeded. C2 permutation: uniformly permute the W slots of the word (exact same |K|, no iid assumption). For each control draw the identical R/SPREAD/ORD90 statistics are recomputed; the control's own spread gives the null for "does the residue structure, rather than finite-sample noise, set the window fluctuation". SCALE AT WHICH THE EFFECT WOULD BE VISIBLE: at x >= 13 the period holds W/m >= 1000 windows at m1 (W = 30030 at x = 13, 510510 at x = 17, 9699690 at x = 19), so the standard error of MED is about 1.25 * sd(R)/sqrt(n) and a departure of 20% or more from 1 is visible; at x = 11 with m1 ~ 41 the window count is ~56, so x = 11 is a low-power cell and is reported as such. CUSTODY GATE (G1, must pass before any new number is believed): the same instrument must reproduce, to the last printed digit, the period values of #693 at x = 5, 7, 11, 13, 17, 19 for both tau: S_1/W, defect/W, S_2/defect, S_3/S_2, order @10%. G2: the computed cover(2) at x = 11 must be the published 41 of #693's text (A144311(5)); the same convention is then used everywhere. G3: |K| = W - hist[0] and the identity P_k -> |K| must hold at every cell (exact arithmetic). Nothing is claimed about the covering run K* itself. Run: python windefect2560.py --levels 5,7,11,13 [--levels 17,19] --out windefect2560.json """ import argparse import json import math import sys import time import numpy as np VERSION = "windefect2560/1.0.0" # Published period values of return #693 (job #1486) -- the custody gate G1. PUBLISHED = { (5, 2): dict(S1_over_W=1.5667, defect_over_W=0.6667, S2_over_defect=1.2000, S3_over_S2=0.1667, order10=3), (7, 2): dict(S1_over_W=1.8524, defect_over_W=0.9238, S2_over_defect=1.3505, S3_over_S2=0.2901, order10=3), (11, 2): dict(S1_over_W=2.0342, defect_over_W=1.0926, S2_over_defect=1.4501, S3_over_S2=0.3716, order10=4), (13, 2): dict(S1_over_W=2.1880, defect_over_W=1.2375, S2_over_defect=1.5332, S3_over_S2=0.4388, order10=4), (17, 2): dict(S1_over_W=2.3057, defect_over_W=1.3493, S2_over_defect=1.5969, S3_over_S2=0.4899, order10=4), (19, 2): dict(S1_over_W=2.4110, defect_over_W=1.4500, S2_over_defect=1.6534, S3_over_S2=0.5350, order10=4), (5, 0): dict(defect_over_W=0.3000, S3_over_S2=0.1000, order10=2), (7, 0): dict(defect_over_W=0.4048, S3_over_S2=0.1683, order10=2), (11, 0): dict(defect_over_W=0.4749, S3_over_S2=0.2121, order10=3), (13, 0): dict(defect_over_W=0.5358, S3_over_S2=0.2479, order10=3), (17, 0): dict(defect_over_W=0.5834, S3_over_S2=0.2750, order10=3), (19, 0): dict(defect_over_W=0.6265, S3_over_S2=0.2988, order10=3), } def primes_upto(x): out = [] for n in range(2, x + 1): if all(n % p for p in out if p * p <= n): out.append(n) return out def primorial(ps): w = 1 for p in ps: w *= p return w def build_w(x, tau, ps, W): """w[r] = #{p <= x : p | r or p | (r + tau)} for r = 0..W-1 (uint8).""" w = np.zeros(W, dtype=np.uint8) r = np.arange(W, dtype=np.int64) for p in ps: hit = (r % p == 0) if tau % p != 0: # the two classes are distinct exactly when p does not divide tau hit |= ((r + tau) % p == 0) w += hit.astype(np.uint8) return w def window_stats(w, m, ps, order_tol=0.10): """Per-alignment window statistics over every circular alignment. Returns dict of numpy arrays: defect, Kw, order (and S_k columns are aggregated on the way). """ W = w.size nk = len(ps) # C(w,k) is zero for k > len(ps) counts = np.empty((W, nk + 1), dtype=np.int64) # counts[:, v] = 1 where w == v for v in range(nk + 1): counts[:, v] = (w == v) hist = np.zeros((nk + 1, W + 1), dtype=np.int64) # cumulative window histogram for v in range(nk + 1): hist[v, 1:] = np.cumsum(counts[:, v]) # circular window count of value v, for every alignment at once starts = np.arange(W) wrap = starts + m > W total = np.empty((nk + 1, W), dtype=np.int64) for v in range(nk + 1): head = hist[v, np.minimum(starts + m, W)] - hist[v, starts] tail = (hist[v, W] - hist[v, starts]) + hist[v, starts + m - W] total[v] = np.where(wrap, tail, head) # K inside the window = m - count of w == 0 Kw = m - total[0] # S_k = sum_v total[v] * C(v, k) comb = np.zeros((nk + 1, nk + 1), dtype=np.int64) for v in range(nk + 1): for k in range(0, v + 1): comb[v, k] = math.comb(v, k) S = np.zeros((nk + 1, W), dtype=np.int64) # S[k] = S_k(omega), k = 0..nk for k in range(1, nk + 1): acc = np.zeros(W, dtype=np.int64) for v in range(k, nk + 1): acc += total[v] * comb[v, k] S[k] = acc defect = S[1] - Kw # alternating partial sums and the order @10% sign = np.zeros(nk + 1, dtype=np.int64) for k in range(1, nk + 1): sign[k] = 1 if k % 2 == 1 else -1 order = np.full(W, -1, dtype=np.int64) partial = np.zeros(W, dtype=np.int64) tol = np.maximum(1.0, order_tol * np.abs(Kw)) for k in range(1, nk + 1): partial = partial + sign[k] * S[k] ok = (np.abs(partial - Kw) <= tol) & (order < 0) order[ok] = k return dict(S=S, Kw=Kw, defect=defect, order=order) def period_values(w, ps, tau, order_tol=0.10): """#693's period ladder, computed by the same instrument (custody gate G1).""" W = w.size nk = len(ps) hist = np.bincount(w, minlength=nk + 1).astype(np.int64) Kabs = int(W - hist[0]) S = {} for k in range(1, nk + 1): S[k] = int(sum(int(hist[v]) * math.comb(v, k) for v in range(k, nk + 1))) defect = S[1] - Kabs partial, order = 0, None for k in range(1, nk + 1): partial += (1 if k % 2 == 1 else -1) * S[k] if order is None and abs(partial - Kabs) <= order_tol * abs(Kabs): order = k return dict(W=W, K=Kabs, S=S, defect=defect, order=order, S1_over_W=S[1] / W, defect_over_W=defect / W, S2_over_defect=(S[2] / defect) if defect else None, S3_over_S2=(S[3] / S[2]) if S[2] else None) def longest_circular_run(mask): """Longest circular run of True slots in a boolean word.""" W = mask.size if mask.all(): return W if not mask.any(): return 0 idx = np.flatnonzero(~mask) # a False slot must exist to break the circle x2 = np.concatenate([mask, mask]) best = run = 0 for v in x2: run = run + 1 if v else 0 if run > best: best = run return min(best, W) def cover_of(w): """The corpus's cover(tau) = maxwrapgap(adm) - 1, i.e. the LONGEST run of KILLED slots. #693's text fixes the convention with a published value: cover(2) = 41 at x = 11 (A144311(5)), which the same instrument must reproduce (gate G2). The admissible run of the complement is reported too, so the convention is visible rather than assumed. """ killed = longest_circular_run(w > 0) adm = longest_circular_run(w == 0) return killed, adm def stats_of(defect, m, defect_W, W, order): R = defect / ((m / W) * defect_W) med = float(np.median(R)) spread = float(R.max() / R.min()) if R.min() > 0 else float("inf") return dict(median_R=med, mean_R=float(R.mean()), min_R=float(R.min()), max_R=float(R.max()), spread=spread, sd_R=float(R.std(ddof=1)), windows=int(R.size), ord90=int(np.percentile(order, 90)), ord_median=int(np.median(order))) def control_stats(w, m, ps, defect_W, rng, kind, draws): W = w.size out = [] for _ in range(draws): if kind == "iid": # independent draws from the EMPIRICAL multiplicity distribution: the marginal of w is # preserved (in law), every spatial correlation of the kill pattern is destroyed vals, counts = np.unique(w, return_counts=True) probs = counts / counts.sum() wc = rng.choice(vals, size=W, p=probs).astype(np.uint8) else: # permutation of the slots: the multiset is preserved EXACTLY wc = w[rng.permutation(W)].copy() st = window_stats(wc, m, ps) R = st["defect"] / ((m / W) * defect_W) out.append((float(np.median(R)), float(R.max() / R.min()) if R.min() > 0 else float("inf"), int(np.percentile(st["order"], 90)))) return dict(kind=kind, draws=draws, median_R_mean=float(np.mean([o[0] for o in out])), median_R_sd=float(np.std([o[0] for o in out], ddof=1)) if draws > 1 else None, spread_mean=float(np.mean([o[1] for o in out])), ord90_mean=float(np.mean([o[2] for o in out]))) def main(): ap = argparse.ArgumentParser() ap.add_argument("--levels", default="5,7,11,13") ap.add_argument("--out", default="windefect2560.json") ap.add_argument("--seed", type=int, default=25600) ap.add_argument("--draws", type=int, default=20) a = ap.parse_args() levels = [int(t) for t in a.levels.split(",") if t.strip()] rng = np.random.default_rng(a.seed) res = {"tool": VERSION, "job": 2560, "at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "prereg": "windefect2560.py header (statistic, decision, F1-F3, C1-C2, scale, G1-G3)", "cells": [], "gates": [], "checks": []} t0 = time.time() ok_all = True for x in levels: ps = primes_upto(x) W = primorial(ps) for tau in (0, 2): w = build_w(x, tau, ps, W) pv = period_values(w, ps, tau) cover, adm_run = cover_of(w) cell = {"x": x, "tau": tau, "W": W, "K": pv["K"], "period": { "S1_over_W": round(pv["S1_over_W"], 4), "defect_over_W": round(pv["defect_over_W"], 4), "S2_over_defect": None if pv["S2_over_defect"] is None else round(pv["S2_over_defect"], 4), "S3_over_S2": None if pv["S3_over_S2"] is None else round(pv["S3_over_S2"], 4), "order10": pv["order"]}, "cover": cover, "admissible_run": adm_run, "windows": []} # G1 custody pub = PUBLISHED.get((x, tau)) if pub and pv["defect"]: for key, got in (("S1_over_W", cell["period"]["S1_over_W"]), ("defect_over_W", cell["period"]["defect_over_W"]), ("S2_over_defect", cell["period"]["S2_over_defect"]), ("S3_over_S2", cell["period"]["S3_over_S2"]), ("order10", pv["order"])): exp = pub.get(key) if exp is not None: same = (got == exp) if key == "order10" else (abs(got - exp) <= 5e-5) res["checks"].append({"gate": "G1", "x": x, "tau": tau, "field": key, "expected": exp, "got": got, "ok": bool(same)}) ok_all &= bool(same) res["checks"].append({"gate": "G3", "x": x, "tau": tau, "ok": bool(pv["K"] == W - int(np.bincount(w, minlength=len(ps) + 1)[0]))}) ok_all &= bool(pv["K"] == W - int(np.bincount(w, minlength=len(ps) + 1)[0])) if x == 11 and tau == 2: # G2: the published convention value g2 = bool(cover == 41) res["checks"].append({"gate": "G2", "x": x, "tau": tau, "expected_cover_2_at_x11": 41, "got": cover, "ok": g2}) ok_all &= g2 m1 = cover + 1 lengths = [m1, 2 * m1, 8 * m1, 32 * m1] lengths = sorted(set(l for l in lengths if 1 <= l < W)) for m in lengths: st = window_stats(w, m, ps) s = stats_of(st["defect"], m, pv["defect"], W, st["order"]) ctl = [control_stats(w, m, ps, pv["defect"], rng, k, a.draws) for k in ("iid", "permutation")] cell["windows"].append({"m": m, "stats": s, "controls": ctl}) res["cells"].append(cell) res["runtime_seconds"] = round(time.time() - t0, 2) # verdicts for c in res["cells"]: for win in c["windows"]: s = win["stats"] win["F1"] = bool(0.5 <= s["median_R"] <= 2.0) win["F2"] = bool(s["ord90"] <= (c["period"]["order10"] or 0) + 1) win["F3"] = bool(s["spread"] <= 4.0) res["ok"] = bool(ok_all) print(json.dumps({k: res[k] for k in ("tool", "job", "runtime_seconds", "ok")}, indent=1)) for c in res["cells"]: print("x=%2d tau=%d W=%-8d K=%-8d cover=%-4d adm=%-4d period(defect/W=%.4f order=%s) %s" % (c["x"], c["tau"], c["W"], c["K"], c["cover"], c["admissible_run"], c["period"]["defect_over_W"], c["period"]["order10"], "G1/" + ("ok" if all(ch["ok"] for ch in res["checks"] if ch["gate"] == "G1" and ch["x"] == c["x"] and ch["tau"] == c["tau"]) else "FAIL"))) for win in c["windows"]: s = win["stats"] print(" m=%-7d wins=%-7d MED_R=%.3f spread=%.2f ord90=%-3d | F1=%s F2=%s F3=%s | iid med=%.3f spread=%.2f ord90=%.1f | perm med=%.3f spread=%.2f ord90=%.1f" % (win["m"], s["windows"], s["median_R"], s["spread"], s["ord90"], win["F1"], win["F2"], win["F3"], win["controls"][0]["median_R_mean"], win["controls"][0]["spread_mean"], win["controls"][0]["ord90_mean"], win["controls"][1]["median_R_mean"], win["controls"][1]["spread_mean"], win["controls"][1]["ord90_mean"])) with open(a.out, "w", encoding="utf-8", newline="\n") as fh: fh.write(json.dumps(res, indent=1)) print("wrote", a.out) return 0 if res["ok"] else 2 if __name__ == "__main__": sys.exit(main())