#!/usr/bin/env python3 """Job #1464: THE EXACT MATCHED-DENSITY NULL, AND WHAT IT DOES TO THE CORPUS'S c. = QUESTION ===================================================================================== The corpus's Poisson-extremes law (docs/research/two-class-lower-bounds.md # 6, read in a sibling's mirror at bf4-911665bf27f8081b1e/evidence/job1454/adv/) normalises the tile's maximum gap by pred(D) = m * ln D , m = W/D the exact mean gap, W = x#, D = |T_x| or phi(W) and reports c = G/pred as a MEASURED constant with a 7% coefficient of variation, fitted over 46 one-class exact terms and 20 two-class ones. My job1464/density-normalized-maxgap.py arrived at the same normalisation from a different direction (a 2000-draw matched-density null) and its simulated null mean does NOT equal m*lnD: at (W,D) = (2310,135) the simulation reads 91.60 against m*lnD = 83.92 (+9.1%), while at (2310,480) it reads 29.544 against 29.71 (-0.6%). Those two readings cannot both be m*lnD at a sampling error of 0.1. So: WHAT IS THE EXACT MEAN OF THE MATCHED-DENSITY NULL, and is the corpus's m*lnD the right normaliser? This is decided exactly, with no simulation, for the sizes where the tile's own ladder is calibrated. = THE OBJECT, EXACTLY ========================================================================== The null: D distinct positions drawn uniformly from the W integers of the cycle Z/W. Equivalently D cyclic gaps g_1..g_D with g_i >= 1 and sum g_i = W, uniform over the compositions. Writing max = max g_i, P(max <= k) = (W/D) * N(W,D,k) / C(W,D), N(W,D,k) = #{(g_1..g_D) : 1 <= g_i <= k, sum = W} = sum_{j>=0} (-1)^j C(D,j) C(W - jk - 1, D - 1), (inclusion-exclusion) E[max] = sum_{k>=0} P(max > k) = sum_k (1 - P(max <= k)), the (W/D) factor because each composition is shared by D rotations. All of it is exact integer arithmetic; no float enters P. The sum is truncated where 1-P < 1e-13 (contributing 0) or P < 1e-11 (contributing 1), with the window located by the geometric estimate P ~ exp(-D e^{-k/m}) and widened by a factor of two. = WHAT IS TESTED =============================================================================== Three normalisers against the exact E[max], at the (W,D) pairs that carry the corpus's c values: m*lnD the corpus's asymptotic Poisson form, pred_corpus m*(lnD + gamma) the same with the extreme-value exponential mean correction (H_D ~ lnD + gamma) m*H_D = W*H_D/D, the exact E[max] for D points on a CONTINUOUS cycle The last is what the earlier job1464 script's docstring assumed; its simulation contradicted it. Whichever wins is reported with the ratio rho(D) = E_exact / pred_corpus, which is the correction factor the corpus's c values carry. CUSTODY. (a) Exact E[max] is validated against exhaustive subset enumeration for every (W,D) with W <= 22. (b) The tile maximum G2(x) is recomputed here for x = 5,7,11,13,17,19 and compared with the corpus's published exact ladder (two-class-lower-bounds.md # 5b and # 6a: 12, 30, 42, 66, 108, 150, 204 at x = 5..23); any disagreement is printed, not smoothed over. (c) The one-class control is A048670 (OEIS b-file, the Jacobsthal function of the primorial) cross-checked against this file's own brute-force maximum at x <= 19. NO ASYMPTOTIC CLAIM. Everything below is a statement about finite (W,D). Levels reached are printed with every number. """ import importlib.util import json import math import pathlib import sys import time import numpy as np HERE = pathlib.Path(__file__).resolve().parent LC = pathlib.Path("D:/AI/TwinPrimeProject/.solveathome/twin-primes/runs/lc-63a9a60e07335b40") T0 = time.time() GAMMA = 0.5772156649015329 def log(m): sys.stderr.write("[%7.2fs] %s\n" % (time.time() - T0, m)) sys.stderr.flush() # ---------------------------------------------------------------- exact matched-density null mean # each exact term costs one math.comb of a number of log2(C(W,D)) bits, so the budget is on # (number of terms) x (bit size). 2310#-scale pairs are seconds; 510510#-scale pairs are hours. WORK_BUDGET = 1.0e10 def exact_null_mean(W, D, eps_lo=1e-11, eps_hi=1e-13): """Exact E[max cyclic gap] for D uniform distinct positions on the W-cycle. Integer arithmetic.""" if D <= 0 or D >= W: return float(W) m = W / D kmin = -(-W // D) # ceil(W/D): the smallest possible max gap # locate the k window with the geometric estimate P ~ exp(-D exp(-k/m)) k0, kc = kmin, W - D + 1 for k in range(kmin, kmin + 4 * int(m * (math.log(D) + GAMMA + 8.0)) + 8): p = math.exp(-D * math.exp(-k / m)) if p < eps_lo: k0 = k + 1 elif p > 1.0 - eps_hi: kc = k break terms = sum(min(D, (W - D) // k) + 1 for k in range(k0, kc)) log_cwd = math.lgamma(W + 1) - math.lgamma(D + 1) - math.lgamma(W - D + 1) cost = terms * log_cwd / math.log(2) if cost > WORK_BUDGET: raise MemoryError("cost %.3g exceeds budget %.3g for (W=%d,D=%d)" % (cost, WORK_BUDGET, W, D)) total = float(k0) # k < k0: exactly kmin terms are 1 (max >= ceil(W/D)) and the rest # are 1 to within eps_lo; E[max] = sum_k P(max > k) starts at k = 0 for k in range(k0, kc): n = 0 for j in range(0, min(D, (W - D) // k) + 1): term = math.comb(D, j) * math.comb(W - j * k - 1, D - 1) n += term if (j % 2 == 0) else -term if n <= 0: raise ArithmeticError("nonpositive composition count at W=%d D=%d k=%d" % (W, D, k)) p = math.exp(math.log(n) + math.log(W) - math.log(D) - log_cwd) total += 1.0 - p return total def brute_null_mean(W, D): """Exhaustive: every D-subset of the W-cycle, its max cyclic gap. Only for tiny W.""" from itertools import combinations if D <= 0 or D >= W: return float(W) tot, cnt = 0, 0 for c in combinations(range(W), D): ext = list(c) + [c[0] + W] tot += max(ext[i + 1] - ext[i] for i in range(D)) cnt += 1 return tot / cnt def candidates(W, D): m = W / D return {"m_lnD": m * math.log(D), "m_lnD_gamma": m * (math.log(D) + GAMMA), "m_H_D": m * sum(1.0 / i for i in range(1, D + 1))} # -------------------------------------------------------------------------------------- the tiles spec = importlib.util.spec_from_file_location("det", str(LC / "work" / "readings" / "determine.py")) det = importlib.util.module_from_spec(spec) spec.loader.exec_module(det) # corpus published exact G2 ladder (two-class-lower-bounds.md # 5b: G2(x#) - 1 = 1,5,11,29,41,65,...) CORPUS_G2 = {2: 2, 3: 6, 5: 12, 7: 30, 11: 42, 13: 66, 17: 108, 19: 150, 23: 204, 29: 258, 31: 348, 37: 528, 41: 546, 43: 618} # A048670 b-file (Jacobsthal function of the primorial), n = pi(x) A048670 = [2, 4, 6, 10, 14, 22, 26, 34, 40, 46, 58, 66, 74, 90, 100, 106, 118, 132, 152, 174, 190, 200, 216, 234, 258, 264, 282, 300, 312, 330, 354, 378, 388, 414, 432, 450, 476, 492, 510, 538, 550, 574, 600, 616, 642, 660, 686, 718, 742, 762, 798, 810, 834, 858, 876, 908, 926, 954, 978, 1002, 1030, 1058, 1098, 1110] PRIMES = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311] def tile_max(level): """G2(level#) from the corpus's own tile (determine.tile), independent of the ladder.""" pos, W = det.tile(level) pos = np.asarray(pos, dtype=np.int64) g = np.diff(np.concatenate([pos, [pos[0] + W]])) return int(g.max()), int(pos.size), W def coprime_max(level): """g(level#) = max gap between integers coprime to level#, by a plain sieve.""" W = det.primorial(level) hit = np.ones(W, dtype=bool) for p in PRIMES: if p > level: break hit[::p] = False pos = np.flatnonzero(hit) g = np.diff(np.concatenate([pos, [pos[0] + W]])) return int(g.max()), int(pos.size), W def main(): rep = {"tool": "job1464/exact-null-normalizer", "gamma": GAMMA, "prereg": {"question": "is the corpus's pred(D)=m*lnD the exact matched-density null mean?", "decided_by": "exact integer enumeration of P(max<=k), no simulation", "kills_m_lnD": "|rho(D)-1| > 1e-6 where rho = E_exact/(m*lnD)", "kills_m_H_D": "|E_exact/(m*H_D) - 1| > 1e-6"}, "validation": [], "null_means": [], "two_class_ladder": [], "one_class_ladder": []} # (a) validation of the exact routine against exhaustive enumeration log("validation: exact vs exhaustive for W <= 22") for W in range(3, 23): for D in range(1, W): ex, br = exact_null_mean(W, D), brute_null_mean(W, D) ok = abs(ex - br) < 1e-9 rep["validation"].append({"W": W, "D": D, "exact": round(ex, 10), "brute": round(br, 10), "match": bool(ok)}) if not ok: log(" MISMATCH W=%d D=%d exact=%.10f brute=%.10f" % (W, D, ex, br)) n_bad = sum(0 if r["match"] else 1 for r in rep["validation"]) log(" %d/%d exact subcases match exhaustive enumeration" % (len(rep["validation"]) - n_bad, len(rep["validation"]))) # (b) exact null mean at the sizes that carry the corpus's c values targets = [(30, 8), (30, 3), (210, 48), (210, 15), (2310, 480), (2310, 135), (30030, 5760), (30030, 1485), (510510, 22275)] log("null means at the ladder's own (W,D) pairs") for W, D in targets: t = time.time() try: ex = exact_null_mean(W, D) except (MemoryError, OverflowError) as e: log(" (W=%d D=%d) skipped: %s" % (W, D, e)) continue cand = candidates(W, D) rec = {"W": W, "D": D, "m": round(W / D, 6), "lnD": round(math.log(D), 6), "exact_null_mean": round(ex, 6), "seconds": round(time.time() - t, 2), **{k: round(v, 6) for k, v in cand.items()}, **{("rho_" + k): round(ex / v, 6) for k, v in cand.items()}} rep["null_means"].append(rec) log(" W=%-9d D=%-9d m=%-8.4f exact=%-10.4f | rho(m lnD)=%.5f rho(m(lnD+g))=%.5f " "rho(m H_D)=%.5f [%.1fs]" % (W, D, W / D, ex, rec["rho_m_lnD"], rec["rho_m_lnD_gamma"], rec["rho_m_H_D"], rec["seconds"])) # (c) two-class ladder: recompute G2 from the tile and re-read c under each normaliser log("two-class ladder: recomputing G2 from determine.tile") levels = [5, 7, 11, 13, 17, 19] for lv in levels: g2, D2, W = tile_max(lv) g1, D1, _ = coprime_max(lv) agree = ("agree" if CORPUS_G2.get(lv) == g2 else "DISAGREE corpus=%s" % CORPUS_G2.get(lv)) rep["two_class_ladder"].append({"x": lv, "W": W, "D2": D2, "G2": g2, "corpus_G2": CORPUS_G2.get(lv), "custody": agree, "D1": D1, "G1": g1}) log(" x=%-3d D2=%-9d G2=%-5d corpus=%-5s %s | D1=%-9d G1=%-5d" % (lv, D2, g2, CORPUS_G2.get(lv), agree, D1, g1)) # (d) the corpus's own exact diagonal c2' ladder, re-read under the exact normaliser where the # exact null mean is computable, and under rho(D) extrapolation where it is not diag = [(11, 17.11, 4.905, 42), (13, 20.22, 7.303, 66), (17, 22.92, 10.011, 108), (19, 25.61, 12.844, 150), (23, 28.05, 15.889, 204), (29, 30.13, 19.185, 258), (31, 32.21, 22.552, 348), (37, 34.05, 26.107, 528), (41, 35.80, 29.771, 546)] rep["corpus_diagonal"] = [] for x, m, lnD, G2 in diag: rep["corpus_diagonal"].append({"x": x, "m": m, "lnD": lnD, "G2": G2, "c_corpus_m_lnD": round(G2 / (m * lnD), 4)}) log(" x=%-3d corpus c2'=%.4f" % (x, G2 / (m * lnD))) # (e) the ratio rho(D) at D = 135 and D = 480, and its D-dependence: the correction the corpus's # c values carry if m*lnD is not the exact null mean small = [r for r in rep["null_means"] if r["D"] <= 600] rep["rho_summary"] = [{"D": r["D"], "rho_m_lnD": r["rho_m_lnD"], "rho_m_H_D": r["rho_m_H_D"]} for r in small] (HERE / "exact-null-normalizer.json").write_text( json.dumps(rep, indent=1, sort_keys=True), encoding="utf-8", newline="\n") log("wrote exact-null-normalizer.json in %.1fs" % (time.time() - T0)) return 0 if __name__ == "__main__": sys.exit(main())