#!/usr/bin/env python3 """pairs2783.py -- job 2783: where the fold-kill lag-1 deficit and lag-2 excess sit, by gap-value pair. For fold p and lag L in {1, 2}: K_L - E = sum over (a, b) in S_p x S_p of (M_L[a][b] - N_ab), with M_L the measured count of (g_i, g_{i+L}) = (a, b) over the cyclic word and N_ab its exact exchangeable expectation h_a h_b / (D-1) (a != b), h_a (h_a - 1) / (D-1) (a = b); these N_ab sum to E = m(m-1)/(D-1) exactly. Also: local-obstruction test for lag-1 pairs: (a, b) is forced to 0 if for some prime q <= x no r mod q has r, r+a, r+a+b all outside {0, q-2} mod q (the pair rule behind #1355's forced class g = +-1 mod 5). usage: pairs2783.py -> JSON on stdout """ import json, sys from fractions import Fraction as Fr x, L, folds = int(sys.argv[1]), json.load(open(sys.argv[2])), [int(v) for v in sys.argv[3].split(",")] D = L["D"]; h = {int(g): v for g, v in L["hist"].items()} M = {lag: {(a, b): c for a, b, c in L[f"pairs{lag}"]} for lag in (1, 2)} primes = [q for q in range(3, x + 1) if all(q % d for d in range(2, q))] def forced1(a, b): for q in primes: if not any(all((r + s) % q not in (0, q - 2) for s in (0, a, a + b)) for r in range(q)): return q return None out = {"x": x, "D": D, "folds": {}} for p in folds: S = sorted(g for g in h if g % p in (0, 2, p - 2)) m = sum(h[g] for g in S) rec = {"S_p": S, "m": m, "E": float(Fr(m * (m - 1), D - 1))} for lag in (1, 2): cells = [] for a in S: for b in S: N = Fr(h[a] * (h[b] - (a == b)), D - 1) c = M[lag].get((a, b), 0) cells.append((a, b, c, N)) tot = sum(c - N for _, _, c, N in cells) diag = sum(c - N for a, b, c, N in cells if a == b) top = sorted(cells, key=lambda t: abs(t[2] - t[3]), reverse=True)[:6] r = {"excess": float(tot), "diagonal_share": float(diag / tot) if tot else None, "top": [{"pair": [a, b], "count": c, "null": round(float(N), 1), "ratio": round(c / float(N), 4) if N else None, "share": round(float((c - N) / tot), 4)} for a, b, c, N in top]} if lag == 1: fz = [(a, b, c, N) for a, b, c, N in cells if forced1(a, b)] r["forced_pairs"] = len(fz); r["forced_pairs_nonzero"] = sum(1 for t in fz if t[2]) r["forced_share_of_deficit"] = float(sum(c - N for _, _, c, N in fz) / tot) if tot else None rec[f"lag{lag}"] = r out["folds"][str(p)] = rec print(json.dumps(out, indent=1))