#!/usr/bin/env python3 """resnull2622.py -- job #2622, route 72 pursuit (rev 5 next step). Matched-support residue-preserving null for the lucky and prime twin-pair counts at X = 10^6. Pre-registered design (fixed before the first run; see report): sites i = 0..N-1, value v = 2i+1, N = X/2 = 500000 (odd-site origin of return #997). T number of i in [0, N-2] with both sites i and i+1 marked (pairs (v, v+2), v+2 <= X-1). strata cell (b, h), b = i // 60, h = i mod 15 (= #997's sc = (j mod 3)*5 + j mod 5 by CRT). tail primary support = all N sites. The 20-site tail block b = 8333 (i = 499980..499999) is its own partial block with the same mod-15 strata (n = 2 for h = 0..4, n = 1 else; n = 1 cells are fixed). Observed T and null T use exactly the same sites and edges. Sensitivity support = truncation of BOTH observed and null to the 8333 whole blocks. null each cell independently receives a uniform subset of its sites of the observed size. moments exact: E[T] = sum_e F(e), Var[T] = sum_(e,f) F(e u f) - F(e)F(f), F(S) = prod_cells (m)_k/(n)_k (#1269's product-hypergeometric inclusion). check R = 2000 independent residue permutations per set (SeedSequence(2622), one child stream per set, so the two sets are independent). Pass iff |z_mean| < 4 and |var_MC/var_exact - 1| < 4 se (se from the sample fourth moment), for both sets. ratio rho = (T_L/T_P)/(E_L/E_P). Null draws rho* = (T_L*/T_P*)/(E_L/E_P) pair the i-th draws of the two independent streams. Zero-denominator policy: any T_P* = 0 invalidates the ratio calibration (reported, not dropped). Reported: MC mean/sd/2.5-97.5% quantiles of rho*, the delta approximation sqrt(V_L/E_L^2 + V_P/E_P^2), the permutation p-value (1 + #{|log rho*| >= |log rho|})/(R + 1), and the descriptive z = (rho - 1)/sd_MC. |z| <= 2 means "no departure detected", never equivalence. Output: one JSON document on stdout (deterministic; progress on stderr). """ import itertools import json import math import sys from collections import Counter, defaultdict from fractions import Fraction import numpy as np X = 10 ** 6 N = X // 2 B = 60 S = 15 R = 2000 SEED = 2622 A000959_20 = [1, 3, 7, 9, 13, 15, 21, 25, 31, 33, 37, 43, 49, 51, 63, 67, 69, 73, 75, 79] def log(*a): print(*a, file=sys.stderr, flush=True) # ---------------------------------------------------------------- sets def lucky_sieve(n): A = list(range(1, n + 1, 2)) k = 1 while k < len(A): s = A[k] if s > len(A): break del A[s - 1::s] k += 1 return A def odd_prime_sites(N): lim = 2 * N sv = bytearray([1]) * (lim + 1) sv[0] = sv[1] = 0 for p in range(2, int(lim ** 0.5) + 1): if sv[p]: sv[p * p::p] = bytearray(len(sv[p * p::p])) return np.frombuffer(bytes(sv[1::2][:N]), dtype=np.uint8).astype(np.int8) def sites_of(values, N): ind = np.zeros(N, dtype=np.int8) for v in values: if v <= 2 * N - 1: ind[(v - 1) // 2] = 1 return ind def T_of(ind): return int(np.dot(ind[:-1].astype(np.int64), ind[1:].astype(np.int64))) # ---------------------------------------------------------------- exact moments (generic number type) def cells_for(nsites, block=B, strata=S): """cell id per site: (i // block) * strata + i mod strata.""" return [(i // block) * strata + (i % strata) for i in range(nsites)] def exact_moments(cell, marks, one=1.0): """cell: list of cell ids per site (sites 0..n-1 on a path); marks: 0/1 per site. Returns (E[T], Var[T]) under independent uniform within-cell permutation, in the type of `one`.""" n = len(cell) size = Counter(cell) m = Counter() for c, x in zip(cell, marks): m[c] += int(x) def F(sites): k = Counter(cell[s] for s in sites) r = one for c, kc in k.items(): if kc > m[c]: return 0 * one for j in range(kc): r = r * (m[c] - j) / (size[c] - j) if isinstance(one, float) else r * Fraction(m[c] - j, size[c] - j) return r edges = [(i, i + 1) for i in range(n - 1)] Fe = [F(e) for e in edges] touch = defaultdict(list) for idx, (a, b) in enumerate(edges): if Fe[idx]: touch[cell[a]].append(idx) if cell[b] != cell[a]: touch[cell[b]].append(idx) E = sum(Fe, 0 * one) V = 0 * one for idx, (a, b) in enumerate(edges): if not Fe[idx]: continue # F(e u f) <= F(e) = 0, so every covariance with e vanishes partners = set(touch[cell[a]]) | set(touch[cell[b]]) for jdx in partners: V += F({a, b} | set(edges[jdx])) - Fe[idx] * Fe[jdx] return E, V def brute_moments(cell, marks): """Exhaustive enumeration over all within-cell subsets (tiny fixtures only).""" groups = defaultdict(list) m = Counter() for s, (c, x) in enumerate(zip(cell, marks)): groups[c].append(s) m[c] += int(x) keys = sorted(groups) choices = [list(itertools.combinations(groups[c], m[c])) for c in keys] hist = Counter() for ch in itertools.product(*choices): mk = set().union(*map(set, ch)) hist[sum(1 for i in range(len(cell) - 1) if i in mk and i + 1 in mk)] += 1 tot = sum(hist.values()) E = sum(Fraction(k * v, tot) for k, v in hist.items()) return E, sum(Fraction(k * k * v, tot) for k, v in hist.items()) - E * E, tot # ---------------------------------------------------------------- permutation sampler def sampler(ind, rng, R, batch=25): """Residue permutations on the full support: whole blocks vectorised, tail cells by hand.""" nb = N // B # 8333 whole blocks full = ind[:nb * B].reshape(nb, B // S, S) # [b, a, h], site = 60b + 15a + h m = full.sum(axis=1) # observed count per cell (b, h) tail = ind[nb * B:] # 20 sites tcell = [(nb * B + t) % S for t in range(len(tail))] tgroups = defaultdict(list) for t, h in enumerate(tcell): tgroups[h].append(t) out = np.empty(R, dtype=np.int64) done = 0 while done < R: k = min(batch, R - done) keys = rng.random((k, nb, B // S, S), dtype=np.float32) rank = np.argsort(np.argsort(keys, axis=2), axis=2) newfull = (rank < m[None, :, None, :]).astype(np.int8).reshape(k, nb * B) for r in range(k): newtail = np.zeros(len(tail), dtype=np.int8) for h, ts in tgroups.items(): mh = int(tail[ts].sum()) if mh: pick = rng.permutation(len(ts))[:mh] newtail[[ts[p] for p in pick]] = 1 x = np.concatenate([newfull[r], newtail]).astype(np.int64) out[done + r] = int(np.dot(x[:-1], x[1:])) done += k log(f" draws {done}/{R}") return out def var_se(sample): s = sample.astype(np.float64) mu = s.mean() v = s.var(ddof=1) m4 = np.mean((s - mu) ** 4) n = len(s) return v, math.sqrt(max(m4 - v * v * (n - 3) / (n - 1), 0.0) / n) # ---------------------------------------------------------------- main def main(): res = {"design": {"X": X, "N_sites": N, "B": B, "strata": "i mod 15 within block i//60", "tail": "partial block 8333 (20 sites) with own strata; sensitivity = whole-block truncation", "R": R, "seed": SEED}} checks = [] def check(name, ok, detail): checks.append({"name": name, "ok": bool(ok), "detail": detail}) log(("PASS " if ok else "FAIL ") + name + " | " + detail) # A. fixtures for the exact-moment implementation c60 = cells_for(60, 60, 15) mk = [0] * 60 mk[0] = mk[1] = 1 # one mark in residue 0, one in residue 1 (#1269) E, V = exact_moments(c60, mk, Fraction(1)) check("A1 #1269 B=60 residue fixture", (E, V) == (Fraction(1, 4), Fraction(3, 16)), f"E={E} V={V}") c2 = cells_for(60, 30, 15) mk = [0] * 60 for s in (0, 14, 30, 44): # one mark in cells 0, 14 (block 0) and 15, 29 (block 1) mk[s] = 1 E, V = exact_moments(c2, mk, Fraction(1)) check("A2 #1269 two-block boundary fixture", (E, V) == (Fraction(3, 4), Fraction(5, 16)), f"E={E} V={V}") frng = np.random.default_rng(SEED + 1) allok = True for t in range(3): # random 3-block, B=30 fixtures, brute force vs formula cc = cells_for(90, 30, 15) marks = [0] * 90 for c in set(cc): sites = [s for s in range(90) if cc[s] == c] mm = int(frng.integers(0, 3)) if c % 4 == 0 else int(frng.choice([0, 2])) for s in sites[:mm]: marks[s] = 1 Eb, Vb, nconf = brute_moments(cc, marks) Ef, Vf = exact_moments(cc, marks, Fraction(1)) allok &= (Eb, Vb) == (Ef, Vf) check("A3 random 3-block fixtures: formula == enumeration (exact)", allok, "3 fixtures") # B. sets and published controls luck = lucky_sieve(X) check("B1 lucky prefix = OEIS A000959", luck[:20] == A000959_20, "20 terms") check("B2 lucky(10^6) = 71918 (corpus / #984)", len(luck) == 71918, f"{len(luck)}") L = sites_of(luck, N) P = odd_prime_sites(N) TL, TP = T_of(L), T_of(P) check("B3 T_lucky = 7669 (OEIS A055724)", TL == 7669, f"{TL}") check("B4 T_prime = 8169 (pi_2(10^6))", TP == 8169, f"{TP}") # C. exact moments on the primary (full) and truncated supports cfull = cells_for(N) ntr = (N // B) * B ex = {} for name, ind in (("lucky", L), ("prime", P)): log(f"exact moments {name} ...") Ef, Vf = exact_moments(cfull, ind.tolist()) Et, Vt = exact_moments(cfull[:ntr], ind[:ntr].tolist()) Tt = T_of(ind[:ntr]) # float implementation against exact Fractions on the first 20 blocks of real data Eq, Vq = exact_moments(cfull[:1200], ind[:1200].tolist(), Fraction(1)) Eg, Vg = exact_moments(cfull[:1200], ind[:1200].tolist()) check(f"C1 {name}: float == Fraction moments on blocks 0..19", abs(Eg - float(Eq)) < 1e-9 and abs(Vg - float(Vq)) < 1e-9, f"E={float(Eq):.6f} V={float(Vq):.6f}") m = ind[:ntr].reshape(ntr // B, B // S, S).sum(axis=1) ex[name] = {"T_obs": int(T_of(ind)), "E": Ef, "Var": Vf, "sd": math.sqrt(Vf), "z_exact": (T_of(ind) - Ef) / math.sqrt(Vf), "empty_cells_whole_blocks": int((m == 0).sum()), "cells_whole_blocks": int(m.size), "truncated": {"T_obs": Tt, "E": Et, "Var": Vt, "sd": math.sqrt(Vt), "z_exact": (Tt - Et) / math.sqrt(Vt)}} # D. independent residue permutations against the exact moments ss = np.random.SeedSequence(SEED).spawn(2) draws = {} for (name, ind), s in zip((("lucky", L), ("prime", P)), ss): log(f"permutations {name} ...") d = sampler(ind, np.random.default_rng(s), R) draws[name] = d e = ex[name] zmean = (d.mean() - e["E"]) / (e["sd"] / math.sqrt(R)) v, se = var_se(d) zvar = (v / e["Var"] - 1) / (se / e["Var"]) e["mc"] = {"mean": float(d.mean()), "var": float(v), "var_se": se, "z_mean": zmean, "var_ratio": v / e["Var"], "z_var": zvar, "min": int(d.min()), "max": int(d.max())} check(f"D1 {name}: MC mean matches exact E", abs(zmean) < 4, f"z={zmean:+.3f}") check(f"D2 {name}: MC variance matches exact Var", abs(zvar) < 4, f"ratio={v / e['Var']:.4f} z={zvar:+.3f}") # E. comparative ratio under independent residue nulls EL, EP = ex["lucky"]["E"], ex["prime"]["E"] zeros = int((draws["prime"] == 0).sum()) check("E1 zero-denominator policy: no T_prime* = 0", zeros == 0, f"zero draws={zeros}, min T_P*={int(draws['prime'].min())}") g0 = EL / EP rho = (TL / TP) / g0 rs = (draws["lucky"] / draws["prime"]) / g0 delta = math.sqrt(ex["lucky"]["Var"] / EL ** 2 + ex["prime"]["Var"] / EP ** 2) sd_mc = float(rs.std(ddof=1)) extreme = int((np.abs(np.log(rs)) >= abs(math.log(rho))).sum()) res["ratio"] = {"G_obs": TL / TP, "G_null_exact": g0, "rho": rho, "rho_star_mean": float(rs.mean()), "rho_star_sd_mc": sd_mc, "rho_star_sd_delta": delta, "rho_star_q025": float(np.quantile(rs, 0.025)), "rho_star_q975": float(np.quantile(rs, 0.975)), "z_descriptive": (rho - 1) / sd_mc, "perm_p_two_sided": (1 + extreme) / (R + 1), "draws_at_least_as_extreme": extreme} res["exact"] = ex res["checks"] = checks res["passed"] = sum(c["ok"] for c in checks) res["total"] = len(checks) print(json.dumps(res, indent=1, sort_keys=True)) return 0 if res["passed"] == res["total"] else 1 if __name__ == "__main__": sys.exit(main())