#!/usr/bin/env python3 """k2fold.py -- route 82 successor: exact fold-kill statistic on the primorial tile T_x. Reuses, verbatim where it matters, the validated sieve / statistic / null definitions of job1930-k2.py sha256 7dd0f10aff725054035d6973cb3b9d693d680a461e95923639f94342417e9fa2 (return #1296, job #1930) -- a direct segmented sieve on the 6-wheel r = 6j+5, two strided marks per odd prime 5 <= q <= x, constant memory, exact integer arithmetic. ONE bounded addition, which is exactly what route 82's pre-registered next experiment asks for ("split the ... CPU-h across the cores by contiguous j-blocks and stitch the boundary gaps centrally"), plus a representation change that makes the full p <= 300 spectrum free: (a) the pass is split into contiguous j-ranges run as separate processes; each worker returns its own D, histogram, pair-transition matrix, max gap and first/last residue; the parent stitches the (n-1) cross-boundary gaps and the wrap gap, and asserts the exact identities sum(hist) = D, sum(T) = D, row sums = column sums = hist. (b) gap values are indexed by h = g/6 (every tile gap is a multiple of 6 because all admissible residues are == 5 mod 6), so the pair-transition matrix is 200x200 instead of 1024x1024 and stays cheap for a 2.18e11-gap word. Objects (route 82, returns #1025 / #1026 / #1296): T_x = { r in [0, x#) : gcd(r,x#) = gcd(r+2,x#) = 1 }, D = prod_{3<=p<=x}(p-2) cyclic gap word g_i = r_{i+1} - r_i (last gap wraps: r_D = r_0 + x#) kill class at fold p : S_p = { g : g mod p in {0, 2, p-2} } m_p = #{i : g_i in S_p}; K2(T_x,p) = #{i : g_i, g_{i+1} both in S_p} Lambda = K2 / E, E = m(m-1)/(D-1) under a uniform random cyclic permutation, repeat ratio R / E_rep with R = #{i : g_i = g_{i+1}} and E_rep = sum_g h_g(h_g-1)/(D-1), h_g = multiplicity of gap value g. Usage: k2fold.py validate [workers] # T23, T29, T31 against every published anchor k2fold.py tile [workers] # one tile, full prime spectrum <= 300, JSON to stdout """ import json import sys import time from fractions import Fraction from multiprocessing import get_context import numpy as np H = 200 # gap-value bins: h = g/6, so gaps up to 6*199 = 1194 are representable # --------------------------------------------------------------- shared definitions def primes_upto(n): if n < 2: return [] s = np.ones(n + 1, dtype=bool) s[:2] = False for i in range(2, int(n ** 0.5) + 1): if s[i]: s[i * i:: i] = False return [int(v) for v in np.flatnonzero(s)] def primorial(x): r = 1 for p in primes_upto(x): r *= p return r def D_tile(x): d = 1 for p in primes_upto(x): if p >= 3: d *= (p - 2) return d def null_stats(D, m): """Exact E and Var of K2 under a uniform random cyclic permutation (job1930-k2.py).""" if m < 2 or D < 2: return Fraction(0), Fraction(0) p1 = Fraction(m * (m - 1), D * (D - 1)) E = D * p1 p_adj = Fraction(m * (m - 1) * (m - 2), D * (D - 1) * (D - 2)) if D >= 3 and m >= 3 else Fraction(0) p_far = (Fraction(m * (m - 1) * (m - 2) * (m - 3), D * (D - 1) * (D - 2) * (D - 3)) if D >= 4 and m >= 4 else Fraction(0)) Var = D * p1 + 2 * D * p_adj + (D * (D - 1) - 2 * D) * p_far - E ** 2 return E, Var def marks_of(x): P = primorial(x) M = P // 6 qs = [q for q in primes_upto(x) if q >= 5] i6 = {q: pow(6, -1, q) for q in qs} marks = [(q, (-5 * i6[q]) % q, (-7 * i6[q]) % q) for q in qs] return P, M, marks # --------------------------------------------------------------------------- worker def solve_range(payload): """Exact statistics of ONE contiguous j-range, gaps internal to the range only.""" x, jlo, jhi, chunk, verbose = payload P, M, marks = marks_of(x) hist = np.zeros(H, dtype=np.int64) T = np.zeros((H, H), dtype=np.int64) D_loc = 0 maxgap = 0 first_res = first_gap = last_res = last_gap = None prev_gp_last = None prev_last_h = None j = jlo nchunk = 0 t0 = time.time() while j < jhi: C = min(chunk, jhi - j) a = np.ones(C, dtype=bool) for q, a0, b0 in marks: s = (a0 - j) % q if s < C: a[s::q] = False s = (b0 - j) % q if s < C: a[s::q] = False idx = np.flatnonzero(a) if idx.size: gp = 6 * (j + idx.astype(np.int64)) + 5 if prev_gp_last is None: if gp.size >= 2: gaps = np.diff(gp) first_res = int(gp[0]) first_gap = int(gaps[0]) else: gaps = np.empty(0, dtype=np.int64) first_res = int(gp[0]) else: gaps = np.empty(gp.size, dtype=np.int64) gaps[0] = int(gp[0]) - prev_gp_last if gp.size > 1: gaps[1:] = np.diff(gp) if gaps.size: if first_gap is None: # the 1-residue tail of an earlier chunk first_res = prev_gp_last first_gap = int(gaps[0]) if int(gaps.min()) % 6 != 0 or int(gaps.max()) % 6 != 0: raise AssertionError("non-multiple-of-6 gap") hs = gaps // 6 if int(hs.max()) >= H: raise AssertionError("gap %d exceeds bin bound" % int(gaps.max())) mg = int(gaps.max()) if mg > maxgap: maxgap = mg D_loc += int(gaps.size) hist += np.bincount(hs, minlength=H) if hs.size >= 2: code = hs[:-1] * H + hs[1:] T += np.bincount(code, minlength=H * H).reshape(H, H) if prev_last_h is not None: T[prev_last_h, int(hs[0])] += 1 prev_last_h = int(hs[-1]) last_gap = int(gaps[-1]) last_res = int(gp[-1]) prev_gp_last = int(gp[-1]) j += C nchunk += 1 if verbose and nchunk % 400 == 0: print(" worker j=%d/%d D=%d %.1fs" % (jlo, j, D_loc, time.time() - t0), file=sys.stderr, flush=True) return {"jlo": jlo, "jhi": jhi, "D_loc": D_loc, "maxgap": maxgap, "first_res": first_res, "first_gap": first_gap, "last_res": last_res, "last_gap": last_gap, "hist": hist.tolist(), "T": T.tolist(), "wall_s": round(time.time() - t0, 2)} # --------------------------------------------------------------------------- stitching def combine(results, P): nw = len(results) for r in results: assert r["D_loc"] > 0 and r["first_res"] is not None and r["last_res"] is not None, r D = sum(r["D_loc"] for r in results) hist = np.zeros(H, dtype=np.int64) T = np.zeros((H, H), dtype=np.int64) for r in results: hist += np.asarray(r["hist"], dtype=np.int64) T += np.asarray(r["T"], dtype=np.int64).reshape(H, H) maxgap = max(r["maxgap"] for r in results) bounds = [] for k in range(nw - 1): W = results[k + 1]["first_res"] - results[k]["last_res"] assert W > 0 and W % 6 == 0, W h = W // 6 hist[h] += 1 D += 1 bounds.append(W) if W > maxgap: maxgap = W T[results[k]["last_gap"] // 6, h] += 1 T[h, results[k + 1]["first_gap"] // 6] += 1 wrap = results[0]["first_res"] + P - results[-1]["last_res"] assert wrap > 0 and wrap % 6 == 0, wrap h = wrap // 6 hist[h] += 1 D += 1 if wrap > maxgap: maxgap = wrap T[results[-1]["last_gap"] // 6, h] += 1 T[h, results[0]["first_gap"] // 6] += 1 assert int(hist.sum()) == D, (int(hist.sum()), D) assert int(T.sum()) == D, (int(T.sum()), D) assert np.array_equal(T.sum(axis=1), hist), "row sums != hist" assert np.array_equal(T.sum(axis=0), hist), "col sums != hist" return D, hist, T, maxgap, bounds, wrap def spectrum_from(hist, T, D, plist): """m_p, K2_p, Lambda, z for every p in plist, straight out of the small matrices.""" out = [] for p in plist: S = [h for h in range(H) if hist[h] and ((6 * h) % p in (0, 2, p - 2))] mp = int(sum(int(hist[h]) for h in S)) k2 = int(sum(int(T[g, h2]) for g in S for h2 in S)) E, Var = null_stats(D, mp) sd = float(Var) ** 0.5 if Var > 0 else 0.0 lam = (Fraction(k2, 1) / E) if E > 0 else Fraction(0) out.append({"p": p, "m": mp, "K2": k2, "E": float(E), "sd": sd, "lambda": float(lam), "z": ((k2 - float(E)) / sd if sd > 0 else 0.0), "support": sorted(6 * h for h in S), "m_over_D": mp / D if D else 0.0}) return out def repeat_stats(hist, T, D): R = int(np.trace(T)) E_rep = float(sum(Fraction(int(hist[g]) * (int(hist[g]) - 1), D - 1) for g in range(H) if hist[g] >= 2)) return {"R": R, "E_repeat": E_rep, "ratio": (R / E_rep if E_rep > 0 else 0.0)} # --------------------------------------------------------------------------- driver def run_tile(x, workers=8, chunk=1 << 24, plist=None, verbose=False, dump=False): t0 = time.time() P, M, _ = marks_of(x) edges = [M * i // workers for i in range(workers + 1)] edges[-1] = M payloads = [(x, edges[i], edges[i + 1], chunk, verbose) for i in range(workers)] if verbose: print("T%d: M=%d j-positions, %d workers, chunk=%d" % (x, M, workers, chunk), file=sys.stderr, flush=True) ctx = get_context("spawn") with ctx.Pool(workers) as pool: results = pool.map(solve_range, payloads) D, hist, T, maxgap, bounds, wrap = combine(results, P) assert D == D_tile(x), "D mismatch %d vs %d" % (D, D_tile(x)) if plist is None: plist = [int(p) for p in primes_upto(300)] out = {"x": x, "D": D, "D_expected": D_tile(x), "maxgap": maxgap, "P": P, "workers": workers, "chunk": chunk, "boundary_gaps": bounds, "wrap_gap": wrap, "worker_wall_s": [r["wall_s"] for r in results], "wall_s": round(time.time() - t0, 2), "repeat": repeat_stats(hist, T, D), "folds": spectrum_from(hist, T, D, plist)} if dump: # the per-gap-value decomposition of the repeat core: for each occurring gap value g, # h_g = occurrences and R_g = T[g,g] = adjacent EQUAL pairs, against its own # exchangeable expectation h_g(h_g-1)/(D-1). vals = [] for h in range(H): if hist[h] >= 2: hg = int(hist[h]) Eg = hg * (hg - 1) / (D - 1) vals.append({"g": 6 * h, "h_g": hg, "R_g": int(T[h, h]), "E_g": Eg, "ratio": (int(T[h, h]) / Eg) if Eg > 0 else 0.0}) vals.sort(key=lambda v: -v["h_g"]) out["diag"] = { "values": vals, "R_from_diag": sum(v["R_g"] for v in vals), "E_from_diag": sum(v["E_g"] for v in vals), "contribution_top10_R": sum(v["R_g"] for v in vals[:10]), "contribution_top10_E": sum(v["E_g"] for v in vals[:10]), } return out # anchors: every published number this route can be checked against ANCHORS = { 23: {"D": 7952175, "maxgap": 204, "rep": 0.63621, "folds": {29: (243816, 288, 0.03853), 31: (248058, 564, 0.07289), 37: (None, 64, 0.05534)}}, 29: {"D": 214708725, "maxgap": 258, "rep": 0.63892, "folds": {29: (7872378, 32712, 0.1133), 31: (8022924, 44478, 0.1484), 37: (3286190, 6966, 0.1385)}}, 31: {"D": 6226553025, "maxgap": 348, "rep": 0.64230, "folds": {31: (269774040, 2647568, 0.22651), 37: (114848070, 502708, 0.23731), 41: (39607204, 2, 0.0000079), 43: (38692278, 0, 0.0), 47: (34193180, 0, 0.0)}}, } def validate(workers=8, chunk=1 << 24): checks = [] for x in (23, 29, 31): a = ANCHORS[x] r = run_tile(x, workers=workers, chunk=chunk, plist=sorted(a["folds"])) f = {v["p"]: v for v in r["folds"]} line = "T%-3d D=%d (exp %d) maxgap=%d (exp %d) R/E_rep=%.5f (exp %.5f) wall=%.1fs" % ( x, r["D"], a["D"], r["maxgap"], a["maxgap"], r["repeat"]["ratio"], a["rep"], r["wall_s"]) print(line) checks.append(("T%d D" % x, r["D"] == a["D"], r["D"])) checks.append(("T%d maxgap" % x, r["maxgap"] == a["maxgap"], r["maxgap"])) checks.append(("T%d R/E_rep" % x, abs(r["repeat"]["ratio"] - a["rep"]) < 5e-5, round(r["repeat"]["ratio"], 5))) for p, (mm, kk, lam) in sorted(a["folds"].items()): v = f[p] if mm is not None: checks.append(("T%d m_%d=%d" % (x, p, mm), v["m"] == mm, v["m"])) checks.append(("T%d K2_%d=%d" % (x, p, kk), v["K2"] == kk, v["K2"])) checks.append(("T%d Lambda_%d=%.5f" % (x, p, lam), abs(v["lambda"] - lam) <= max(1e-4, 2e-4 * abs(lam)), round(v["lambda"], 6))) npass = sum(1 for _, ok, _ in checks if ok) print("\n== anchors ==") for name, ok, val in checks: if not ok: print(" [FAIL] %s -> %s" % (name, val)) print(" %d/%d passed" % (npass, len(checks))) return npass, len(checks) def main(): mode = sys.argv[1] if len(sys.argv) > 1 else "validate" if mode == "validate": workers = int(sys.argv[2]) if len(sys.argv) > 2 else 8 npass, ntot = validate(workers=workers) sys.exit(0 if npass == ntot else 2) elif mode in ("tile", "diag"): x = int(sys.argv[2]) workers = int(sys.argv[3]) if len(sys.argv) > 3 else 8 out = sys.argv[4] if len(sys.argv) > 4 else None r = run_tile(x, workers=workers, plist=[int(p) for p in primes_upto(300)], verbose=True, dump=(mode == "diag")) blob = json.dumps(r) if out: # the bounding wrapper truncates the child's stdout with open(out, "w", encoding="utf-8") as fh: fh.write(blob) print("wrote %s (%d bytes)" % (out, len(blob))) else: print(blob) print("T%d D=%d maxgap=%d R/E_rep=%.5f wall=%.1fs" % ( x, r["D"], r["maxgap"], r["repeat"]["ratio"], r["wall_s"]), file=sys.stderr) else: print(__doc__) if __name__ == "__main__": from multiprocessing import freeze_support freeze_support() main()