"""Job #2651 (route 35 rev 11, pursue): the slot-level test. For every admissible twin slot r of T_x (x = 19, 23, 29) over the exposures of #1028/#1297 (8, 2, 2 complete periods), census covariates are accumulated by streaming the period in 128 blocks (tile never held whole), together with the slot's twin indicator per period: D_W = number of admissible slots within +-W integers of r (W = 60, 300, 1500; the slot itself included), ordinal; RES = n mod q_next for the integer n = kM + r of period k (q_next = 23, 29, 31), nominal; the pre-registered power control (the classes n = 0 and n = q_next - 2 can never carry a twin above q_next, so the chi-square MUST fire if the test has power). Class sizes therefore depend on the period; the null is drawn per period with its own sizes. Tests (pre-registered in this file before the first run; seed 2651, 400 draws): ordinal: exact values merged in order into <= 10 mass-balanced groups; response = occupancy rate per group (twins over slots x periods); statistic = Spearman rho of rate against group order; null = exact label-permutation null in closed form (multivariate hypergeometric per period); two-sided rank-p. Falsifier F-slot per covariate: p <= 0.01 at >= 2 of the 3 levels with one sign of rho. nominal: chi-square of twins across classes against expectation proportional to slots; same null; rank-p. Added, labelled as such (not pre-registered): RES with the two killed classes removed (uniformity across the q_next - 2 admissible classes), and a planted-effect power curve for D_300: null draws thinned by a linear gradient of relative size eps across the groups, detection fraction at p <= 0.01 for eps in {2%, 1%, 0.5%, 0.2%, 0.1%}; and a slots-weighted linear trend statistic (Cochran-Armitage type) beside the registered Spearman, since the rank statistic on <= 10 groups cannot detect small monotone gradients (its null |rho| 0.99-quantile is about 0.9). Gates: G0 pi_2(10^6) = 8169; G1 streamed slot count = D(T_x); G1e accumulated twins = sieved twins; conservation of the covariate tables. Stdout: ledger + verdict (deterministic); stderr: progress. RUN: python job2651-slotlevel.py --levels 19,23,29 --out job2651-slotlevel.json """ import argparse, json, math, sys, time import numpy as np from importlib.machinery import SourceFileLoader bg = SourceFileLoader("bg", "../job1936/job1936-blockgrain.py").load_module() PERIODS = {19: 8, 23: 2, 29: 2}; QNEXT = {19: 23, 23: 29, 29: 31} D_T = {19: 378675, 23: 7952175, 29: 214708725} WS = [60, 300, 1500]; WMAX = max(WS); FINE = 128; DRAWS, SEED = 400, 2651; NGROUPS = 10 def block_bool(lo, hi, qs): """ok[i] for r = lo + i in [lo, hi): r odd and r, r + 2 coprime to every q in qs (periodic mod x#, so lo may be negative).""" n = hi - lo; ok = np.ones(n, dtype=bool) ok[(-lo) % 2:: 2] = False for q in qs: for kill in (0, (q - 2) % q): ok[(kill - lo) % q:: q] = False return ok def mass_groups(vals, cnt, ngroups): target = cnt.sum() / ngroups; groups = np.zeros(len(vals), dtype=int); g = 0; acc = 0 for i in range(len(vals)): if acc >= target and g < ngroups - 1: g += 1; acc = 0 groups[i] = g; acc += cnt[i] return groups, g + 1 def ordinal_test(slots_c, tw_c, periods, rng, draws): """slots_c, tw_c: per exact covariate value (arrays over values), tw_c shape (periods, nvals).""" vals = np.flatnonzero(slots_c); cnt = slots_c[vals] groups, ng = mass_groups(vals, cnt, NGROUPS) slots_g = np.array([cnt[groups == i].sum() for i in range(ng)], dtype=float) tw_kg = np.array([[tw_c[k, vals[groups == i]].sum() for i in range(ng)] for k in range(periods)], dtype=float) rate = tw_kg.sum(axis=0) / (slots_g * periods); order = np.arange(ng) obs = bg.spearman(rate, order); obs_t = wtrend(rate, order, slots_g) nrng = np.random.default_rng(rng.next()); null = []; null_t = [] for _ in range(draws): tot = np.zeros(ng) for k in range(periods): tot += nrng.multivariate_hypergeometric(slots_g.astype(np.int64), int(tw_kg[k].sum())) r = tot / (slots_g * periods); null.append(bg.spearman(r, order)); null_t.append(wtrend(r, order, slots_g)) null = np.array(null); p = (int((np.abs(null) >= abs(obs) - 1e-15).sum()) + 1) / (draws + 1) null_t = np.array(null_t); p_t = (int((np.abs(null_t) >= abs(obs_t) - 1e-15).sum()) + 1) / (draws + 1) return dict(groups=ng, group_value_ranges=[[int(vals[groups == i].min()), int(vals[groups == i].max())] for i in range(ng)], slots_per_group=slots_g.tolist(), twins_per_group=tw_kg.sum(axis=0).tolist(), rate_per_group=rate.tolist(), rho=obs, perm_p=p, z_fisher=bg.fisher_z(obs, ng), null_abs_rho_q99=float(np.quantile(np.abs(null), 0.99)), trend_added=dict(statistic="slots-weighted Pearson correlation of group rate with group order (a Cochran-Armitage-type trend), added after run 1, not pre-registered", value=obs_t, perm_p=p_t, null_abs_q99=float(np.quantile(np.abs(null_t), 0.99)), relative_gradient=float((rate[-1] - rate[0]) / rate.mean())), distinct_values=int(len(vals)), draws=draws), (slots_g, tw_kg, null, null_t) def wtrend(rate, order, w): w = np.asarray(w, float); mo = (w * order).sum() / w.sum(); mr = (w * rate).sum() / w.sum() cov = (w * (order - mo) * (rate - mr)).sum(); vo = (w * (order - mo) ** 2).sum(); vr = (w * (rate - mr) ** 2).sum() return 0.0 if vo == 0 or vr == 0 else float(cov / math.sqrt(vo * vr)) def chisq(t, e): m = e > 0 return float(((t[m] - e[m]) ** 2 / e[m]).sum()) def nominal_test(slots_kc, tw_kc, periods, rng, draws, drop=()): """slots_kc, tw_kc: shape (periods, classes). Chi-square of total twins per class against the expectation sum_k T_k s_kc / S_k, null = multivariate hypergeometric per period with that period's class sizes.""" keep = np.ones(slots_kc.shape[1], dtype=bool) for d in drop: keep[d] = False s = slots_kc[:, keep].astype(float); t = tw_kc[:, keep].astype(float) tot = t.sum(axis=0); e = sum(t[k].sum() * s[k] / s[k].sum() for k in range(periods)) obs = chisq(tot, e) nrng = np.random.default_rng(rng.next()); null = [] for _ in range(draws): tt = np.zeros(s.shape[1]) for k in range(periods): tt += nrng.multivariate_hypergeometric(s[k].astype(np.int64), int(t[k].sum())) null.append(chisq(tt, e)) null = np.array(null); p = (int((null >= obs - 1e-12).sum()) + 1) / (draws + 1) return dict(classes=int(s.shape[1]), dropped=list(drop), slots_per_class_total=s.sum(axis=0).tolist(), twins_per_class=tot.tolist(), rate_per_class=(tot / s.sum(axis=0)).tolist(), chi_square=obs, perm_p=p, null_chi_square_q99=float(np.quantile(null, 0.99)), dof=int(s.shape[1] - 1), draws=draws) def planted_power(slots_g, tw_kg, null_rho, null_t, periods, rng, eps_list, reps=50): """Detection fraction at p <= 0.01 (statistic above the null's 0.99 quantile of its absolute value) when null draws are thinned by a linear gradient: group i keeps twins with probability 1 - eps * i / (G - 1); for the registered Spearman statistic and for the added weighted trend.""" ng = len(slots_g); q99 = float(np.quantile(np.abs(null_rho), 0.99)); q99t = float(np.quantile(np.abs(null_t), 0.99)); order = np.arange(ng) nrng = np.random.default_rng(rng.next()); out = {}; out_t = {} for eps in eps_list: hits = 0; hits_t = 0 for _ in range(reps): tot = np.zeros(ng) for k in range(periods): draw = nrng.multivariate_hypergeometric(slots_g.astype(np.int64), int(tw_kg[k].sum())) keep = 1 - eps * order / (ng - 1) tot += nrng.binomial(draw.astype(np.int64), keep) r = tot / (slots_g * periods) if abs(bg.spearman(r, order)) > q99: hits += 1 if abs(wtrend(r, order, slots_g)) > q99t: hits_t += 1 out[str(eps)] = hits / reps; out_t[str(eps)] = hits_t / reps return dict(q99_null_abs_rho=q99, detection_fraction_spearman=out, q99_null_abs_trend=q99t, detection_fraction_trend=out_t, reps=reps, gradient="group i thinned by eps*i/(G-1)") def main(): ap = argparse.ArgumentParser(); ap.add_argument("--out", required=True); ap.add_argument("--levels", default="19,23,29"); ap.add_argument("--draws", type=int, default=DRAWS) a = ap.parse_args(); log = sys.stderr; levels = [int(v) for v in a.levels.split(",")] out = {"instrument": "job2651-slotlevel.py", "job": 2651, "route": 35, "preregistered": {"covariates": ["D_60", "D_300", "D_1500", "RES mod q_next (control)"], "falsifier_slot": "p<=0.01 at >=2 of 3 levels with one sign of rho (ordinal covariates)", "draws": a.draws, "seed": SEED, "groups": NGROUPS, "null": "multivariate hypergeometric per period (exact label permutation)"}, "checks": [], "ledger": [], "levels": {}} def check(tag, ok, detail): out["checks"].append({"check": tag, "pass": bool(ok), "detail": detail}); out["ledger"].append(f"{'PASS' if ok else 'FAIL'} {tag} :: {detail}") sp0 = bg.primes_to(int(math.isqrt(10 ** 6)) + 1); tw0 = bg.twins_in(sp0, 3, 10 ** 6 - 1) check("G0_pi2_1e6", len(tw0) == 8169, f"observed {len(tw0)} published 8169") for x in levels: t0 = time.time(); qs = [int(q) for q in bg.primes_to(x) if q > 2]; M = 2 for q in qs: M *= q P = PERIODS[x]; qn = QNEXT[x]; hi = (P + 1) * M sp = bg.primes_to(int(math.isqrt(hi)) + 1) check(f"G1c_sieve_primes_x{x}", int(sp[-1]) < M, f"largest marking prime {int(sp[-1])} < M={M}") tpts = bg.twins_in(sp, M, hi, log=log) per_k = {k: int(((tpts >= k * M) & (tpts < (k + 1) * M)).sum()) for k in range(1, P + 1)}; tot_tw = sum(per_k.values()) print(f"x={x}: twins {tot_tw} {time.time() - t0:.1f}s", file=log, flush=True) L = M // FINE; edges = [b * L for b in range(FINE)] + [M] dens_slots = {W: np.zeros(2 * W + 2, dtype=np.int64) for W in WS}; dens_tw = {W: np.zeros((P, 2 * W + 2), dtype=np.int64) for W in WS} res_slots = np.zeros((P, qn), dtype=np.int64); res_tw = np.zeros((P, qn), dtype=np.int64) slots_total = 0; first_slot = None; last_slot = None for b in range(FINE): lo, hi_b = edges[b], edges[b + 1] ok = block_bool(lo - WMAX, hi_b + WMAX, qs) core = ok[WMAX: WMAX + (hi_b - lo)] pos = np.flatnonzero(core) # positions within the block offs = pos + lo; n = len(offs); slots_total += n if n: if first_slot is None: first_slot = int(offs[0]) last_slot = int(offs[-1]) pre = np.concatenate([[0], np.cumsum(ok, dtype=np.int64)]) ppos = pos + WMAX # position in the extended array tw_ind = np.zeros((P, n), dtype=bool) for k in range(1, P + 1): sel = (tpts >= k * M + lo) & (tpts < k * M + hi_b) off = tpts[sel] - k * M j = np.searchsorted(offs, off) assert (offs[np.minimum(j, n - 1)] == off).all(), "twin outside the tile word" tw_ind[k - 1, j] = True for W in WS: d = pre[ppos + W + 1] - pre[ppos - W] dens_slots[W] += np.bincount(d, minlength=2 * W + 2)[:2 * W + 2] for k in range(P): dens_tw[W][k] += np.bincount(d[tw_ind[k]], minlength=2 * W + 2)[:2 * W + 2] for k in range(P): rr = (offs + (k + 1) * M) % qn # residue of the integer n = (k+1) M + r res_slots[k] += np.bincount(rr, minlength=qn) res_tw[k] += np.bincount(rr[tw_ind[k]], minlength=qn) if b % 16 == 15: print(f"x={x} block {b + 1}/{FINE} slots {slots_total} {time.time() - t0:.1f}s", file=log, flush=True) check(f"G1_slots_x{x}", slots_total == D_T[x], f"streamed {slots_total} vs D(T_{x}) {D_T[x]}") check(f"G1b_period_x{x}", first_slot == 29 and last_slot == M - 1, f"first {first_slot} last {last_slot} M-1 {M - 1}") for W in WS: check(f"G1d_dens{W}_conservation_x{x}", int(dens_slots[W].sum()) == slots_total and int(dens_tw[W].sum()) == tot_tw, f"slots {int(dens_slots[W].sum())} twins {int(dens_tw[W].sum())}") check(f"G1e_res_conservation_x{x}", int(res_slots.sum()) == P * slots_total and int(res_tw.sum()) == tot_tw, f"slot-periods {int(res_slots.sum())} vs {P * slots_total}; twins {int(res_tw.sum())}") lv = {"M": int(M), "periods": P, "q_next": qn, "slots_per_period": int(slots_total), "twins": int(tot_tw), "twins_per_k": {str(k): per_k[k] for k in per_k}, "lambda_hat": tot_tw / (P * slots_total), "covariates": {}} rng = bg.LCG(SEED) for W in WS: res, aux = ordinal_test(dens_slots[W], dens_tw[W], P, rng, a.draws) lv["covariates"][f"D_{W}"] = res if W == 300: lv["covariates"]["D_300_planted_power"] = planted_power(aux[0], aux[1], aux[2], aux[3], P, rng, [0.02, 0.01, 0.005, 0.002, 0.001]) print(f"x={x} D_{W}: rho {res['rho']:+.3f} p {res['perm_p']:.3f}; trend {res['trend_added']['value']:+.3f} p {res['trend_added']['perm_p']:.3f} grad {res['trend_added']['relative_gradient']:+.5f} {time.time() - t0:.1f}s", file=log, flush=True) lv["covariates"]["RES_all_classes_control"] = nominal_test(res_slots, res_tw, P, rng, a.draws) lv["covariates"]["RES_admissible_classes_added"] = nominal_test(res_slots, res_tw, P, rng, a.draws, drop=(0, qn - 2)) print(f"x={x} RES control chi2 {lv['covariates']['RES_all_classes_control']['chi_square']:.1f} p {lv['covariates']['RES_all_classes_control']['perm_p']:.3f}; admissible-only chi2 {lv['covariates']['RES_admissible_classes_added']['chi_square']:.1f} p {lv['covariates']['RES_admissible_classes_added']['perm_p']:.3f}", file=log, flush=True) killed = int(res_tw[:, 0].sum() + res_tw[:, qn - 2].sum()) check(f"G1f_killed_classes_x{x}", killed == 0, f"twins in classes n = 0, {qn - 2} (mod {qn}): {killed}") out["levels"][str(x)] = lv json.dump(out, open(a.out, "w"), indent=1) verdict = {} for W in WS: fired = []; signs = [] for x in levels: r = out["levels"][str(x)]["covariates"][f"D_{W}"]; fired.append(r["perm_p"] <= 0.01); signs.append(1 if r["rho"] > 0 else -1) same = [s for f, s in zip(fired, signs) if f] verdict[f"D_{W}"] = {"levels_fired": dict(zip([str(x) for x in levels], fired)), "falsifier_fired": sum(fired) >= 2 and len(set(same)) == 1} verdict["control_fired_all_levels"] = all(out["levels"][str(x)]["covariates"]["RES_all_classes_control"]["perm_p"] <= 0.01 for x in levels) verdict["admissible_residue_classes_fired"] = {str(x): out["levels"][str(x)]["covariates"]["RES_admissible_classes_added"]["perm_p"] <= 0.01 for x in levels} out["verdict"] = verdict json.dump(out, open(a.out, "w"), indent=1) print("\n".join(out["ledger"])); print("VERDICT " + json.dumps(verdict, sort_keys=True)) return 0 if __name__ == "__main__": sys.exit(main())