#!/usr/bin/env python3 # ============================================================================ # job #1927 (explore / discovery / stage discover, ROUTELESS) -- "new statistic" # # QUESTION. Design one finite statistic a run could decide something about, where # the retained censuses (return #1023 and the ladder behind it: D(T_x) = prod(q-2), # the T_x gap histogram, the per-fold kill-graph component census by size, PAIRS) # could not, and pre-register its falsifier and matched control before any run. # # THE STATISTIC. For a fold p let S_p = { g : g = 0, +-2 (mod p) } be the kill # class of gap VALUES (the served okPair reading), with m_p = |S_p| OCCURRENCES in # the T_x gap word g_0..g_{D-1} (cyclic). Define the *adjacent kill-pair count* # # K2(T_x, p) = #{ i : g_i in S_p and g_{i+1} in S_p } (cyclic) # # i.e. the number of two-step kill runs, or equivalently the number of adjacent # pairs inside the set of kill positions. #1023's census edges are single-step # kill positions; K2 is the two-step object, and it is exactly the input the # size->=3 entries of a census need. # # WHY IT IS NOT ALREADY DECIDED. K2 is a *two-gap consecutive* statistic: it is not # a function of the gap histogram (the multiset), and it is not a function of the # per-fold census by size either -- the script exhibits two words with the SAME # histogram, the SAME m_p and the SAME PAIRS at every fold whose K2 differ. # # THE EXACT NULL (exchangeability). The matched control is a uniform random # permutation of the gap multiset: it preserves the histogram, hence every # histogram functional (all m_p, all PAIRS, all #161-style weight sums) EXACTLY, # and destroys only the order. Under that null the count of adjacent pairs both # in a fixed set of m = m_p positions among D is a hypergeometric-type count with # E[K2] = m(m-1)/(D-1) # Var = D*p1 + 2D*p_adj + (D(D-1)-2D)*p_far - E^2 # p1 = m(m-1)/(D(D-1)) # p_adj = m(m-1)(m-2)/(D(D-1)(D-2)) (cyclic distance 1 and D-1) # p_far = m(m-1)(m-2)(m-3)/(D(D-1)(D-2)(D-3)) (distance 2..D-2) # The permutation control in this script validates that closed form empirically. # # DECISION IT INFORMS. Lambda_p := K2 / E[K2] is the exchangeability ratio of the # fold-kill positions. Lambda = 1 for every fold means the fold structure is, in # the only order-sensitive sense the retained census needs, TYPICAL of its own # histogram -- i.e. #161's column needs no order explanation and the census is a # histogram-plus-noise object. Lambda > 1 is pre-registered evidence that the # fold kills CLUSTER along the word beyond what the histogram can express, which # is the order content a successor run must then measure at T29. # # PRE-REGISTERED FALSIFIER (written before the measurement below; unchanged). # H1: Lambda_p > 1.05 for p = 29, 31, 37 on the true T23 word (clustering). # FALSIFIER: a measured Lambda_p inside [0.95, 1.05] for ALL THREE folds # falsifies H1 and instead supports "the census's order content is negligible # at the two-fold level", which would make the fourth census entry (4 at # T29/p=31) near-null and would retire the order hypothesis for this lane. # CONTROL FALSIFIER: if the permutation control does not reproduce the closed # form E +/- 3*sd/sqrt(n_perm) then the closed form is wrong and no Lambda is # reported. # # SCALE. Lambda is dimensionless; the effect is visible when the excess # K2 - E exceeds a few sd, sd ~ sqrt(2 m^2 / D) * sqrt(1 + ...) ~ m*sqrt(2/D): # T23 (D = 7 952 175, m ~ 2.4e5): sd ~ 3.8e3 pairs on E ~ 7.4e3 (below). # T29 (D = 214 708 725, m_p=31 = 8 022 924): sd ~ 2.4e4 on E ~ 3.0e5 -- one # constant-memory segmented pass (~11-16 s, README gotcha 47) decides it, i.e. # the statistic is cheap enough to run at the scale where it matters. # # Cost: in-memory T23 only, ~10 s. Timings go to stderr (README gotcha: a wall # time on stdout makes the artifact non-reproducible and draws a server note). # ============================================================================ import json, sys, time import numpy as np T0 = time.time() CHECKS = [] def check(name, cond, detail=""): ok = bool(cond) CHECKS.append({"name": name, "pass": ok, "detail": detail}) print(("PASS " if ok else "FAIL ") + name + ((" " + detail) if detail else ""), flush=True) return ok def note(msg): print(" " + msg, flush=True) def build_tile(x): """Residues a mod P_x with gcd(a(a+2), P_x) = 1; the reviewed T_x build (job #1922).""" P, res = 2, [1] for q in range(3, x + 1): if any(q % d == 0 for d in range(2, int(q ** 0.5) + 1)): continue new = [] for r in res: for k in range(q): v = r + k * P m = v % q if m != 0 and m != q - 2: new.append(v) P *= q res = new return P, np.array(sorted(res), dtype=np.int64) def null_k2(D, m): """Closed form E and Var of the number of cyclic adjacent pairs both inside a fixed set of m positions of a uniformly random permutation of D slots.""" if m < 2: return 0.0, 0.0 p1 = m * (m - 1) / (D * (D - 1)) p_adj = m * (m - 1) * (m - 2) / (D * (D - 1) * (D - 2)) if m >= 3 else 0.0 p_far = (m * (m - 1) * (m - 2) * (m - 3) / (D * (D - 1) * (D - 2) * (D - 3)) if m >= 4 else 0.0) E = D * p1 E2 = D * p1 + 2 * D * p_adj + (D * (D - 1) - 2 * D) * p_far return E, max(E2 - E * E, 0.0) def k2_of_word(gaps, p): """K2 = # i with g_i and g_{i+1} both in S_p, with an independent run-based recount. Method A: count positions where the kill mask and its one-step shift are both set. Method B: a cyclic kill run of length L contributes L-1 adjacent pairs, so K2 = m - (#maximal cyclic runs) and #runs = # slots that are kill with a non-kill predecessor. Two different formulas, one vectorised pass each. """ t = gaps % p mask = (t == 0) | (t == 2) | (t == p - 2) m = int(np.count_nonzero(mask)) if m == 0: return 0, 0, 0 k2_shift = int(np.count_nonzero(mask & np.roll(mask, -1))) nruns = int(np.count_nonzero(mask & ~np.roll(mask, 1))) return k2_shift, m - nruns, m def k2_bruteforce(mask): """Third method, for the small tiles only: walk the cyclic mask and sum (L-1) per run.""" D = mask.size runs, cur = 0, 0 if mask.all(): return D start = int(np.flatnonzero(~mask)[0]) for k in range(D): if mask[(start + k) % D]: cur += 1 else: runs += max(cur - 1, 0) cur = 0 runs += max(cur - 1, 0) return runs def pairs_formula(gaps, p): t = gaps % p h0 = int(np.count_nonzero(t == 0)) hm = int(np.count_nonzero(t == 2)) + int(np.count_nonzero(t == p - 2)) return 2 * h0 + hm, h0 + hm def main(): out = {} # ---- 0. closed form vs Monte-Carlo on a small surrogate ----------------- rng = np.random.default_rng(20260918) Ds, ms, nperm = 2000, 100, 400 xs = [] for _ in range(nperm): arr = np.zeros(Ds, dtype=bool) arr[rng.choice(Ds, ms, replace=False)] = True xs.append(int(np.count_nonzero(arr & np.roll(arr, -1)))) E0, V0 = null_k2(Ds, ms) empm, emps = float(np.mean(xs)), float(np.std(xs, ddof=1)) check("closed form E/Var for the adjacent-pair count reproduce Monte-Carlo on a D=2000, m=100 surrogate", abs(empm - E0) < 3 * emps / np.sqrt(nperm) + 1e-9 and abs(emps - np.sqrt(V0)) < 0.05 * np.sqrt(V0), f"analytic E={E0:.3f} sd={np.sqrt(V0):.3f} | MC mean={empm:.3f} sd={emps:.3f} ({nperm} perms)") # ---- 1. the T23 word ---------------------------------------------------- P23, res23 = build_tile(23) D23 = res23.size g23 = np.diff(np.concatenate([res23, res23[:1] + P23])).astype(np.int64) note(f"T23: D={D23} P={P23} sum={int(g23.sum())} min={int(g23.min())} max={int(g23.max())}") check("T23 tile rebuild: D = 7 952 175, sum(gaps) = P23, min 6, G2 = 204 (A144311+1), all gaps = 0 mod 6", D23 == 7952175 and int(g23.sum()) == P23 and int(g23.min()) == 6 and int(g23.max()) == 204 and bool(np.all(g23 % 6 == 0))) # small-tile cross-validation of the two vectorised K2 formulas against a literal walk ok_small = True small = [] for x, ps in ((13, (7, 11, 13, 17)), (17, (19, 23, 29))): Px, rx = build_tile(x) gx = np.diff(np.concatenate([rx, rx[:1] + Px])).astype(np.int64) for p in ps: tx = gx % p mx = (tx == 0) | (tx == 2) | (tx == p - 2) a, b, m = k2_of_word(gx, p) c = k2_bruteforce(mx) small.append({"T": x, "p": p, "k2": a, "m": m, "lambda": a / null_k2(gx.size, m)[0]}) ok_small = ok_small and (a == b == c) check("small tiles T13/T17: both vectorised K2 formulas equal a literal cyclic run walk (7 folds)", ok_small, " ".join(f"T{s['T']}/p={s['p']}: K2={s['k2']} Lambda={s['lambda']:.3f}" for s in small)) PUB_W1 = {29: 243816, 31: 248058} # return #1018's A, restated in #1023 PUB_PAIRS = {29: 243822, 31: 248078, 37: 95896} # #1023's T23 PAIRS PUB_CENSUS = {29: {"n2": 243822}, 31: {"n2": 247526, "n3": 276}} # #1023 / #1922 follow-up rows = {} for p in (29, 31, 37): k2_shift, k2_runs, m = k2_of_word(g23, p) pairs, w1 = pairs_formula(g23, p) E, V = null_k2(D23, m) sd = float(np.sqrt(V)) rows[p] = {"m": m, "w1": w1, "pairs": pairs, "k2": k2_shift, "E": E, "sd": sd, "lambda": k2_shift / E if E else None, "z": (k2_shift - E) / sd if sd else None} note(f"T23/p={p}: m={m} w1={w1} PAIRS={pairs} K2={k2_shift} null E={E:.1f} sd={sd:.1f} " f"Lambda={k2_shift/E:.4f} z={(k2_shift-E)/sd:.1f}") check(f"T23/p={p}: the two K2 methods agree (shifted-mask vs cyclic run sum)", k2_shift == k2_runs, f"shift={k2_shift} runs={k2_runs}") check("T23: weight-1 kill-class occurrence counts reproduce #1018's A = 243 816 / 248 058", rows[29]["w1"] == PUB_W1[29] and rows[31]["w1"] == PUB_W1[31]) check("T23: PAIRS = 2*hist(g=0 mod p) + hist(g=+-2 mod p) reproduce #1023 (243 822 / 248 078 / 95 896)", [rows[p]["pairs"] for p in (29, 31, 37)] == [PUB_PAIRS[p] for p in (29, 31, 37)]) check("T23: K2 <= PAIRS at every fold (a two-step kill run contains a one-step kill position)", all(rows[p]["k2"] <= rows[p]["pairs"] for p in (29, 31, 37))) # ---- 2. the matched control: uniform permutation, histogram exact ------- hist = np.bincount(g23, minlength=4096)[:4096] ctrl = {} for seed in (1, 2, 3, 4): rg = np.random.default_rng(seed) perm = rg.permutation(g23) same_hist = np.array_equal(np.bincount(perm, minlength=4096)[:4096], hist) k2p, _, mp = k2_of_word(perm, 31) ctrl[seed] = {"k2": k2p, "m": mp, "hist_identical": bool(same_hist)} cks = [v["k2"] for v in ctrl.values()] cmean, csd = float(np.mean(cks)), float(np.std(cks, ddof=1)) E31, V31 = rows[31]["E"], rows[31]["sd"] ** 2 check("permutation control preserves the histogram exactly (4 shuffles) and m_p = |S_p| at p=31", all(v["hist_identical"] and v["m"] == rows[31]["m"] for v in ctrl.values())) check("permutation control: its K2 mean matches the closed-form null E (3*sd/sqrt(n)) -- the null is validated", abs(cmean - E31) < 3 * np.sqrt(V31) / np.sqrt(len(cks)) + 1e-9, f"control mean={cmean:.1f} (values {sorted(cks)}) vs analytic E={E31:.1f} sd={np.sqrt(V31):.1f}") # ---- 3. non-redundancy witness ------------------------------------------ perm = np.random.default_rng(7).permutation(g23) witness = {} for p in (29, 31, 37): pr, w1p = pairs_formula(perm, p) k2p, _, mp = k2_of_word(perm, p) witness[p] = {"w1": w1p, "pairs": pr, "m": mp, "k2": k2p} same_hist = np.array_equal(np.bincount(perm, minlength=4096)[:4096], hist) same_marginals = all(witness[p]["m"] == rows[p]["m"] and witness[p]["pairs"] == rows[p]["pairs"] for p in (29, 31, 37)) moved = any(witness[p]["k2"] != rows[p]["k2"] for p in (29, 31, 37)) check("NON-REDUNDANCY: two words with the same histogram, same m_p and same PAIRS at all three folds ", same_hist and same_marginals, f"hist_identical={bool(same_hist)} marginals_identical={same_marginals}") check("NON-REDUNDANCY: ... whose K2 differs -- K2 is not a histogram functional", moved, "orig " + str({p: rows[p]["k2"] for p in (29, 31, 37)}) + " | perm " + str({p: witness[p]["k2"] for p in (29, 31, 37)})) # and the retained census of #1023 is a different object from K2 as well: K2 >= #components of size >= 3 n3_31 = PUB_CENSUS[31]["n3"] check("K2 is not the census: T23/p=31 K2 (two-step kill runs) vs #1023's n3 = 276 size-3 components", rows[31]["k2"] > n3_31, f"K2={rows[31]['k2']} n3={n3_31} ratio={rows[31]['k2']/n3_31:.1f}") # ---- 4. independent-resample ('independent thinning of the order') ------ rg = np.random.default_rng(11) vals = np.repeat(np.nonzero(hist)[0], hist[np.nonzero(hist)[0]]).astype(np.int64) iid = rg.permutation(vals) # i.i.d. drawing from the histogram == exchangeable order k2i, _, mi = k2_of_word(iid, 31) check("independent-resample control (order replaced by an i.i.d. draw from the histogram) sits at the null too", abs(k2i - E31) < 4 * np.sqrt(V31) and mi == rows[31]["m"], f"iid K2={k2i} vs E={E31:.1f} sd={np.sqrt(V31):.1f}") # ---- 5. the pre-registered decision ------------------------------------ lams = {p: rows[p]["lambda"] for p in (29, 31, 37)} h1 = all(l > 1.05 for l in lams.values()) falsified = all(0.95 <= l <= 1.05 for l in lams.values()) note("PRE-REGISTERED FALSIFIER EVALUATION: Lambda = " + str({p: round(rows[p]["lambda"], 4) for p in (29, 31, 37)})) note(" H1 (Lambda > 1.05 at all three folds) = " + str(h1) + " ; falsifier (all Lambda in [0.95, 1.05]) = " + str(falsified)) check("the pre-registered statistic is decided (neither H1 nor its falsifier left ambiguous)", h1 != falsified, "H1 holds" if h1 else ("falsifier holds" if falsified else "MIXED: report per-fold")) out = {"word": "T23", "D": D23, "P": int(P23), "rows": {str(k): v for k, v in rows.items()}, "perm_control_p31": cks, "perm_control_mean": cmean, "perm_control_sd": csd, "iid_control_p31": k2i, "nonredundancy": {"hist_identical": bool(same_hist), "marginals_identical": bool(same_marginals), "k2_moved": bool(moved), "perm_k2": {str(p): witness[p]["k2"] for p in (29, 31, 37)}}, "prereg": {"H1_lambda_gt_1.05_all_folds": bool(h1), "falsifier_all_in_0.95_1.05": bool(falsified), "lambda": {str(p): lams[p] for p in (29, 31, 37)}}, "checks": CHECKS, "pass": sum(1 for c in CHECKS if c["pass"]), "fail": sum(1 for c in CHECKS if not c["pass"])} with open("job1927-result.json", "w", encoding="utf-8") as f: json.dump(out, f, indent=1, sort_keys=True) print(f"ALL_PASS={out['fail'] == 0} ({out['pass']} pass / {out['fail']} fail)", flush=True) print(f"ledger wall {time.time()-T0:.1f}s -> stderr", file=sys.stderr, flush=True) if __name__ == "__main__": main()