#!/usr/bin/env python3 """job68-check.py -- independent verification of the numbers in research_history_staging_import-thinning.md and research_history_staging_attack-foldL-04-amortized.md Tasks 1. Moebius group law M_a o M_b = M_ab and the geometric pgf. 2. Null law: brute-force pmf recursion vs closed form (folds 5..29). 3. c_null(p) and the OLS refit of ln r_null(p). 4. Exact tiles T_5..T_29, Merge Rate / Consumption / Fold Moment identities, run-length spectra, c'_min table, K = Psi/Phi^2. 5. Total runtime. 6. Gamma = (1/N) sum_R F_R from the kill runs; Gamma = Omega + Delta, F_R >= 0, and (p-2)(Phi_new - N_p Phi) = 2(Psi - Phi^2) + Gamma - 4Phi(Phi-1)^2/(p-2Phi). No network, no files outside the check directory are read. """ import os for _v in ("OMP_NUM_THREADS", "OPENBLAS_NUM_THREADS", "MKL_NUM_THREADS", "VECLIB_MAXIMUM_THREADS", "NUMEXPR_NUM_THREADS"): os.environ[_v] = "4" import sys, time, math, random from fractions import Fraction import numpy as np T0 = time.perf_counter() def elapsed(): return time.perf_counter() - T0 def hdr(s): print("\n" + "=" * 78 + "\n" + s + "\n" + "=" * 78, flush=True) def sub(s): print("\n--- " + s + " ---", flush=True) PRIMES_LADDER = [5, 7, 11, 13, 17, 19, 23, 29] G2_LADDER = {5: 12, 7: 30, 11: 42, 13: 66, 17: 108, 19: 150, 23: 204, 29: 258} U_MAIN = [0.25, 0.5, 0.75, 0.9] U_SMALL = [0.01, 0.05] def primes_upto(n): 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(x) for x in np.flatnonzero(s)] # ============================================================================= hdr("TASK 1: group law M_a o M_b = M_ab, and the geometric pgf") # ============================================================================= # 1a. Symbolic check via exact multivariate polynomial arithmetic in (a, b, w). # M_a(M_b(w)) = M_b(w) / (a - (a-1) M_b(w)), M_b(w) = w / (b - (b-1) w). # Multiply numerator and denominator by (b - (b-1) w): # M_a(M_b(w)) = w / [ a (b - (b-1) w) - (a-1) w ]. # So the composition equals M_ab(w) = w / [ab - (ab-1) w] iff the polynomial # a (b - (b-1) w) - (a-1) w - (ab - (ab-1) w) == 0 identically. class Poly: # dict {(i,j,k): coeff} for a^i b^j w^k, coefficients exact Fractions def __init__(self, d=None): self.d = {k: v for k, v in (d or {}).items() if v != 0} @staticmethod def const(c): return Poly({(0, 0, 0): Fraction(c)}) @staticmethod def var(name): return Poly({{"a": (1, 0, 0), "b": (0, 1, 0), "w": (0, 0, 1)}[name]: Fraction(1)}) def __add__(self, o): d = dict(self.d) for k, v in o.d.items(): d[k] = d.get(k, 0) + v return Poly(d) def __neg__(self): return Poly({k: -v for k, v in self.d.items()}) def __sub__(self, o): return self + (-o) def __mul__(self, o): d = {} for k1, v1 in self.d.items(): for k2, v2 in o.d.items(): k = (k1[0] + k2[0], k1[1] + k2[1], k1[2] + k2[2]) d[k] = d.get(k, 0) + v1 * v2 return Poly(d) def is_zero(self): return len(self.d) == 0 def __repr__(self): if not self.d: return "0" return " + ".join(f"{v}*a^{k[0]}b^{k[1]}w^{k[2]}" for k, v in sorted(self.d.items())) A, B, Wv, ONE = Poly.var("a"), Poly.var("b"), Poly.var("w"), Poly.const(1) den_comp = A * (B - (B - ONE) * Wv) - (A - ONE) * Wv # denominator of M_a(M_b(w)) after clearing den_ab = A * B - (A * B - ONE) * Wv # denominator of M_ab(w) diff = den_comp - den_ab print("Symbolic (exact polynomial in a,b,w):") print(" denom of M_a(M_b(w)) after clearing =", den_comp) print(" denom of M_ab(w) =", den_ab) print(" difference =", diff) print(" GROUP LAW symbolic: ", "PASS (identically zero, numerators both = w)" if diff.is_zero() else "FAIL") # 1b. Exact rational arithmetic at 36 random rational points (exact equality). def M(alpha, w): return w / (alpha - (alpha - 1) * w) rng = random.Random(20260911) exact_ok = 0 for _ in range(36): a = Fraction(rng.randint(1, 10 ** 6), rng.randint(1, 10 ** 6)) + 1 b = Fraction(rng.randint(1, 10 ** 6), rng.randint(1, 10 ** 6)) + 1 w = Fraction(rng.randint(-10 ** 6, 10 ** 6), rng.randint(1, 10 ** 6)) try: exact_ok += (M(a, M(b, w)) == M(a * b, w)) except ZeroDivisionError: exact_ok += 1 # pole hit, skip (astronomically unlikely) print(f"Exact rational check at 36 random points: {exact_ok}/36 exact equalities") # 1c. Floating point at 36 random triples. rngf = np.random.default_rng(20260911) maxdev = 0.0 for _ in range(36): a = float(rngf.uniform(1.0, 8.0)); b = float(rngf.uniform(1.0, 8.0)); w = float(rngf.uniform(-0.95, 0.95)) maxdev = max(maxdev, abs(M(a, M(b, w)) - M(a * b, w))) print(f"Float check over 36 random triples: max |M_a(M_b(w)) - M_ab(w)| = {maxdev:.3e} (record: 3.7e-16)") print(" GROUP LAW numeric:", "PASS" if maxdev < 1e-14 else "FAIL") # 1d. pgf of the geometric on {1,2,...} with mean alpha: # sum_k (1/alpha)(1-1/alpha)^(k-1) w^k = (w/alpha) / (1 - (1-1/alpha) w) = w/(alpha - (alpha-1) w). # Exact: closed form of the partial sum S_K, checked against M_alpha(w) - tail. sub("pgf of Geometric(mean alpha) on {1,2,...} equals M_alpha(w)") pgf_ok = True; pgf_maxdev = 0.0 for _ in range(12): alpha = Fraction(rng.randint(2, 50), rng.randint(1, 10)) + 1 w = Fraction(rng.randint(-99, 99), 100) rho = 1 - 1 / alpha K = 60 S = sum((1 / alpha) * rho ** (k - 1) * w ** k for k in range(1, K + 1)) # exact tail of the geometric series: sum_{k>K} = (1/alpha) w^{K+1} rho^K / (1 - rho w) tail = (1 / alpha) * w ** (K + 1) * rho ** K / (1 - rho * w) pgf_ok &= (S + tail == M(alpha, w)) pgf_maxdev = max(pgf_maxdev, abs(float(S) - float(M(alpha, w)))) print(f" exact partial-sum + exact tail == M_alpha(w): {'PASS' if pgf_ok else 'FAIL'} (12 random rational (alpha,w))") print(f" float: max |partial sum (60 terms) - M_alpha(w)| = {pgf_maxdev:.3e}") # mean of the geometric = M'(1) = alpha; check by exact derivative: d/dw [w/(alpha-(alpha-1)w)] at w=1 = alpha/(alpha-(alpha-1))^2 = alpha print(" mean = M_alpha'(1) = alpha/(alpha-(alpha-1)*1)^2 = alpha (exact)") print(f"[task 1 done at {elapsed():.1f} s]") # ============================================================================= hdr("TASK 2: null law by brute-force pmf recursion, folds 5..29") # ============================================================================= KMAX = 4000 def null_recursion(dtype): f = np.zeros(KMAX + 1, dtype=dtype); f[1] = 1 # delta_1 alpha = 1.0 out = [] for p in PRIMES_LADDER: q = dtype(1) - dtype(2) / dtype(p); r = dtype(2) / dtype(p) fn = np.zeros(KMAX + 1, dtype=dtype) for k in range(1, KMAX + 1): # f_new(k) = q f(k) + r sum_{j 1e-300 rel = np.abs(ff[mask] - closed[mask]) / closed[mask] kmax_at = int(ks[mask][rel.argmax()]) rel100 = rel[ff[mask] > 1e-100].max() rel30 = rel[ff[mask] > 1e-30].max() mean_k = float(np.dot(ks.astype(np.float64), ff)) out.append((p, alpha, rho, rel.max(), kmax_at, rel100, rel30, mean_k)) return out for dtype, name in ((np.float64, "float64"), (np.longdouble, f"longdouble ({np.finfo(np.longdouble).bits}-bit)")): print(f"\nrecursion in {name}:") print("fold alpha rho max_rel(f>1e-300) at k max_rel(f>1e-100) max_rel(f>1e-30) mean(kappa) alpha-mean") worst_overall = 0.0 for p, alpha, rho, mx, kat, r100, r30, mean_k in null_recursion(dtype): worst_overall = max(worst_overall, mx) print(f"{p:4d} {alpha:.12f} {rho:.12f} {mx:.3e} {kat:4d} {r100:.3e} {r30:.3e} {mean_k:.10f} {alpha - mean_k:+.2e}") print(f"MAX relative deviation over folds 5..29 ({name}, f>1e-300): {worst_overall:.3e} (record: 1.02e-14)") print(f"[task 2 done at {elapsed():.1f} s]") # ============================================================================= hdr("TASK 3: c_null(p) and the refit of r_null(p)") # ============================================================================= plist = primes_upto(1600) mbar_before = {} # 6 * prod_{5<=q 0 and (g % 6 == 0).all() # ---- killed matrix (p, N): candidate s + kW killed iff (s+kW) mod p in {0, p-2} Smod = (S % p).astype(np.int32) Wmod = W % p killed = np.empty((p, N), dtype=bool) for k in range(p): r = (Smod + (k * Wmod) % p) % p killed[k] = (r == 0) | (r == p - 2) per_slot = killed.sum(axis=0, dtype=np.int32) each_slot_twice = bool((per_slot == 2).all()) total_killed = int(per_slot.sum()) # ---- kill runs on the cyclic flat order (k-major, i-minor == sorted order of all copies) flat = killed.ravel() PN = flat.size prev = np.empty_like(flat); prev[1:] = flat[:-1]; prev[0] = flat[-1] starts = np.flatnonzero(flat & ~prev); del prev nxt = np.empty_like(flat); nxt[:-1] = flat[1:]; nxt[-1] = flat[0] ends = np.flatnonzero(flat & ~nxt) wrapped = bool(flat[0] and flat[-1]) if wrapped: ends = np.roll(ends, -1) lengths = ((ends - starts) % PN + 1).astype(np.int64) Mruns = starts.size Lmax = int(lengths.max()) spectrum = np.bincount(lengths) X_runs = int((lengths - 1).sum()) # ---- Merge Rate Identity: destroyed copies per old gap destroyed = (flat | nxt).reshape(p, N).sum(axis=0, dtype=np.int32) del nxt gm = g % p omega = np.where(gm == 0, 2, np.where((gm == 2) | (gm == p - 2), 1, 0)).astype(np.int64) mr_full_ok = bool((destroyed == 4 - omega).all()) n_mr_bad = int((destroyed != 4 - omega).sum()) rs = np.random.default_rng(p).choice(N, size=min(10000, N), replace=False) mr_sample_ok = bool((destroyed[rs] == 4 - omega[rs]).all()) Q0 = int((gm == 0).sum()); Qp = int((gm == 2).sum()); Qm = int((gm == p - 2).sum()) X_cons = 2 * Q0 + Qp + Qm X_sum_omega = int(omega.sum()) # ---- spans of runs: run [a,b] of length l merges the l+1 old gaps g[(a-1+t) mod N], t=0..l i0 = (starts - 1) % N spans = np.zeros(Mruns, dtype=np.int64) for t in range(Lmax + 1): m = lengths >= t # t <= l (t = 0..l) spans[m] += g[(i0[m] + t) % N] # ---- old moments old = {} for lam in lams: old[lam] = moments_old(g, omega, lam) # ---- new gap word, chunked by copy k (never materializes the full new tile unless asked) Nnew = 0 sums_new = {lam: 0.0 for lam in lams} G2new = 0 first_surv = None carry = None pieces = [] if materialize else None Wnew = W * p surv_counts = 0 for k in range(p): sv = S[~killed[k]] + k * W if sv.size == 0: continue if first_surv is None: first_surv = int(sv[0]) if carry is not None: gseq = np.concatenate(([sv[0] - carry], np.diff(sv))) else: gseq = np.diff(sv) carry = int(sv[-1]) Nnew += gseq.size if gseq.size: G2new = max(G2new, int(gseq.max())) gf = gseq.astype(np.float64) for lam in lams: sums_new[lam] += np.exp(lam * gf).sum() if materialize: pieces.append(sv) # wrap gap gw = first_surv + Wnew - carry Nnew += 1 G2new = max(G2new, gw) for lam in lams: sums_new[lam] += math.exp(lam * gw) Snew = np.concatenate(pieces) if materialize else None # ---- Task 6: merged gaps h_0..h_l of every run (h_t = g[(i0+t) mod N], valid for t <= l) H = [g[(i0 + t) % N].astype(np.float64) for t in range(Lmax + 1)] valid = [lengths >= t for t in range(Lmax + 1)] # h_t exists iff t <= l # ---- Fold Moment Identity fmi = {} for lam in lams: Phi, Psi, Om = old[lam] Phi_new = sums_new[lam] / Nnew run_term = np.exp(lam * spans.astype(np.float64)).sum() / N Delta = run_term - 2.0 * Psi lhs = (p - 2) * Phi_new rhs = (p - 4) * Phi + Om + 2.0 * Psi + Delta # Task 6: F_R = prod_{j=0}^{l} x_j - sum_{j=1}^{l} x_{j-1} x_j + sum_{j=1}^{l-1} x_j # (i) polynomial form in float64, product taken literally over the x_j (so l=1 gives exactly 0) Xs = [np.where(valid[t], np.exp(lam * H[t]), 1.0) for t in range(Lmax + 1)] prod = np.ones(Mruns) for t in range(Lmax + 1): prod *= Xs[t] pairsum = np.zeros(Mruns) for t in range(1, Lmax + 1): pairsum += np.where(valid[t], Xs[t - 1] * Xs[t], 0.0) interior = np.zeros(Mruns) for t in range(1, Lmax): interior += np.where(lengths >= t + 1, Xs[t], 0.0) # interior x_t exists iff t <= l-1 F_poly = prod - pairsum + interior # (ii) numerically stable evaluation: l=1 -> 0 exactly; l=2 -> x_1 (x_0-1)(x_2-1) via expm1; # l>=3 -> polynomial form in 40-digit Decimal arithmetic F_st = np.zeros(Mruns) m2 = lengths == 2 if m2.any(): F_st[m2] = Xs[1][m2] * np.expm1(lam * H[0][m2]) * np.expm1(lam * H[2][m2]) import decimal ctx = decimal.Context(prec=40) for idx in np.flatnonzero(lengths >= 3): l = int(lengths[idx]) xs = [ctx.exp(ctx.multiply(decimal.Decimal(lam), decimal.Decimal(int(H[t][idx])))) for t in range(l + 1)] pr = decimal.Decimal(1) for xv in xs: pr = ctx.multiply(pr, xv) ps = sum((ctx.multiply(xs[j - 1], xs[j]) for j in range(1, l + 1)), decimal.Decimal(0)) it = sum((xs[j] for j in range(1, l)), decimal.Decimal(0)) F_st[idx] = float(pr - ps + it) Gamma = F_st.sum() / N Gamma_poly = F_poly.sum() / N fmi[lam] = dict(Phi=Phi, Psi=Psi, Om=Om, Phi_new=Phi_new, Delta=Delta, lhs=lhs, rhs=rhs, abs_res=abs(lhs - rhs), rel_res=abs(lhs - rhs) / abs(lhs), Gamma=Gamma, Gamma_poly=Gamma_poly, Fmin=float(F_st.min()), Fmin_poly=float(F_poly.min()), Fdev=float(np.abs(F_poly - F_st).max())) del H, valid return dict(N=N, Nnew=Nnew, Wnew=Wnew, G2new=G2new, g=g, each_slot_twice=each_slot_twice, total_killed=total_killed, Mruns=Mruns, Lmax=Lmax, spectrum=spectrum, X_runs=X_runs, mr_full_ok=mr_full_ok, n_mr_bad=n_mr_bad, mr_sample_ok=mr_sample_ok, Q0=Q0, Qp=Qp, Qm=Qm, X_cons=X_cons, X_sum_omega=X_sum_omega, wrapped=wrapped, spans=spans, lengths=lengths, fmi=fmi, Snew=Snew, mean_gap_old=W / N, mean_gap_new=Wnew / Nnew) # --- base tile S, W = sieve_tile(5) print("T_5 by direct sieve:", S.tolist(), " W =", W, " N =", S.size, " gaps =", gaps_of(S, W).tolist()) assert S.tolist() == [11, 17, 29] Nprod = 3 RECORD = { 7: dict(spec={1: 2, 2: 2}, X=2, L=2), 11: dict(spec={1: 30}, X=0, L=1), 13: dict(spec={1: 258, 2: 6}, X=6, L=2), 17: dict(spec={1: 2826, 2: 72}, X=72, L=2), 19: dict(spec={1: 42374, 2: 1088}, X=1088, L=2), 23: dict(spec={1: 733672, 2: 11746, 3: 62}, X=11870, L=3), 29: dict(spec={1: 15416706, 2: 243822}, X=243822, L=2), } REC_CMIN = {7: (1.9181, 1.8105, 1.6722, 1.5743), 11: (1.8553, 1.6797, 1.4763, 1.3441), 13: (1.9010, 1.7796, 1.6321, 1.5297), 17: (1.9434, 1.8772, 1.7922, 1.7252), 19: (1.9508, 1.8866, 1.7909, 1.7066), 23: (1.9490, 1.8769, 1.7636, 1.6621), 29: (1.9524, 1.8785, 1.7537, 1.6389)} REC_DELTA_SHARE = {13: -3.78e-3, 17: -1.43e-3, 19: -9.53e-4, 23: -1.11e-3, 29: -1.10e-3} results = {} Kcells = [] cmin_rows_old = {}; cmin_rows_new = {} t6_cells = [] stopped_early = False for p in PRIMES_LADDER[1:]: tfold = time.perf_counter() if p == 29 and elapsed() > 420: print(f"\n*** fold 29 skipped: elapsed {elapsed():.0f}s exceeds budget; stopping at fold 23 ***") stopped_early = True break mbar_old = W / S.size mbar_new = mbar_old * p / (p - 2) lams_old = {u: u / mbar_old for u in U_MAIN + U_SMALL} lams_new = {u: u / mbar_new for u in U_MAIN} lam_list = sorted(set(list(lams_old.values()) + list(lams_new.values()))) materialize = (p <= 23) R = fold(S, W, p, lam_list, materialize, None) results[p] = R Nprod *= (p - 2) sub(f"fold by p={p}: T_{PRIMES_LADDER[PRIMES_LADDER.index(p)-1]} (N={R['N']}, W={W}, mbar={mbar_old:.6f}) -> T_{p}") print(f" N_new = {R['Nnew']} prod(q-2) = {Nprod} (p-2)N = {(p-2)*R['N']} " f"{'PASS' if R['Nnew'] == Nprod == (p-2)*R['N'] else 'FAIL'}") print(f" G2(T_{p}) = {R['G2new']} expected {G2_LADDER[p]} {'PASS' if R['G2new'] == G2_LADDER[p] else 'FAIL'}") print(f" mean gap new = {R['mean_gap_new']:.6f} = mbar_old*p/(p-2) = {mbar_new:.6f}") print(f" each old slot killed in exactly 2 of p copies: {'PASS' if R['each_slot_twice'] else 'FAIL'} " f"total killed = {R['total_killed']} (2N = {2*R['N']})") print(f" Merge Rate Identity (destroyed copies == 4 - omega): whole word {'PASS' if R['mr_full_ok'] else 'FAIL'} " f"(mismatches {R['n_mr_bad']} of {R['N']}); random sample of {min(10000, R['N'])}: {'PASS' if R['mr_sample_ok'] else 'FAIL'}") print(f" Consumption: Q0={R['Q0']} Q+={R['Qp']} Q-={R['Qm']} 2Q0+Q++Q- = {R['X_cons']} sum(omega) = {R['X_sum_omega']} " f"2N-M = {2*R['N']-R['Mruns']} sum(l-1) over runs = {R['X_runs']} " f"{'PASS' if R['X_cons'] == R['X_sum_omega'] == 2*R['N']-R['Mruns'] == R['X_runs'] else 'FAIL'}") spec = {i: int(c) for i, c in enumerate(R['spectrum']) if i > 0 and c > 0} rec = RECORD[p] print(f" runs M = {R['Mruns']} L = {R['Lmax']} spectrum = {spec} wrapped-run present: {R['wrapped']}") print(f" record: spectrum = {rec['spec']} X = {rec['X']} L = {rec['L']} " f"{'PASS' if spec == rec['spec'] and R['X_cons'] == rec['X'] and R['Lmax'] == rec['L'] else 'FAIL'}") # longest runs and their spans Lm = R['Lmax'] big = np.flatnonzero(R['lengths'] == Lm) print(f" spans of the {big.size} run(s) of maximal length {Lm}: max span = {int(R['spans'][big].max())}, " f"max span over all runs = {int(R['spans'].max())}") # Fold Moment Identity print(" Fold Moment Identity (p-2)Phi_new = (p-4)Phi + Omega + 2Psi + Delta, lambda = u/mbar_old:") print(" u Phi Psi Omega Phi_new Delta abs_res rel_res") for u in U_MAIN: d = R['fmi'][lams_old[u]] print(f" {u:5.2f} {d['Phi']:.10f} {d['Psi']:.10f} {d['Om']:.10f} {d['Phi_new']:.10f} {d['Delta']:+.6e} {d['abs_res']:.2e} {d['rel_res']:.2e}") # ---- Task 6: Gamma from the kill runs print(" TASK 6: Gamma = (1/N) sum_R F_R from the kill runs; checks Gamma = Omega + Delta, F_R >= 0, and") print(" (p-2)(Phi_new - N_p Phi) = 2(Psi - Phi^2) + Gamma - 4Phi(Phi-1)^2/(p-2Phi), N_p Phi = (1-2/p)Phi/(1-2Phi/p)") print(" u Gamma Omega Delta 2(Psi-Phi^2) 4Phi(Phi-1)^2/(p-2Phi) |Gamma-(Om+Delta)| min F_R |lhs-rhs| rel") for u in U_MAIN: d = R['fmi'][lams_old[u]] Phi, Psi = d['Phi'], d['Psi'] Gam = d['Gamma'] g1 = abs(Gam - (d['Om'] + d['Delta'])) NpPhi = (1 - 2.0 / p) * Phi / (1 - 2.0 * Phi / p) lhs6 = (p - 2) * (d['Phi_new'] - NpPhi) term = 4 * Phi * (Phi - 1) ** 2 / (p - 2 * Phi) rhs6 = 2 * (Psi - Phi ** 2) + Gam - term d['t6'] = (g1, lhs6, rhs6, abs(lhs6 - rhs6) / max(abs(lhs6), 1e-300)) t6_cells.append((p, u, g1, d['Fmin'], d['Fmin_poly'], abs(lhs6 - rhs6), d['t6'][3], d['Fdev'], abs(Gam - d['Gamma_poly']))) print(f" {u:5.2f} {Gam:+.6e} {d['Om']:.6e} {d['Delta']:+.6e} {2*(Psi-Phi**2):+.6e} {term:.6e} " f"{g1:.2e} {d['Fmin']:+.2e} {abs(lhs6-rhs6):.2e} {d['t6'][3]:.2e}" f" [poly-form: min F_R {d['Fmin_poly']:+.2e}, max|F_poly-F_stable| {d['Fdev']:.2e}, |Gamma_poly-Gamma| {abs(Gam-d['Gamma_poly']):.2e}]") d = R['fmi'][lams_old[0.5]] share = d['Delta'] / ((p - 2) * d['Phi_new']) print(f" Delta/((p-2)Phi_new) at u=0.5 = {share:+.3e}" + (f" (record {REC_DELTA_SHARE[p]:+.2e})" if p in REC_DELTA_SHARE else "")) # c'_min and K row_old = []; row_new = [] for u in U_MAIN: d = R['fmi'][lams_old[u]] cm = p * (d['Phi_new'] - d['Phi']) / (d['Phi'] * (d['Phi_new'] - 1.0)) K = d['Psi'] / d['Phi'] ** 2 row_old.append((cm, K)); Kcells.append((p, u, K)) d2 = R['fmi'][lams_new[u]] row_new.append(p * (d2['Phi_new'] - d2['Phi']) / (d2['Phi'] * (d2['Phi_new'] - 1.0))) small = [] for u in U_SMALL: d = R['fmi'][lams_old[u]] small.append(p * (d['Phi_new'] - d['Phi']) / (d['Phi'] * (d['Phi_new'] - 1.0))) cmin_rows_old[p] = (row_old, small); cmin_rows_new[p] = row_new print(f" c'_min (lambda=u/mbar_old): " + " ".join(f"{c:.4f}" for c, _ in row_old) + f" record: " + " ".join(f"{c:.4f}" for c in REC_CMIN[p])) print(f" c'_min (lambda=u/mbar_new): " + " ".join(f"{c:.4f}" for c in row_new)) print(f" c'_min at u=0.01, 0.05 (mbar_old): " + " ".join(f"{c:.5f}" for c in small)) print(f" K = Psi/Phi^2: " + " ".join(f"{K:.8f}" for _, K in row_old)) # custody: direct sieve cross-check for small W if materialize: Snew, Wnew = R['Snew'], R['Wnew'] assert Snew.size == R['Nnew'] assert (np.diff(Snew) > 0).all() if Wnew <= 10_000_000: Ssv, Wsv = sieve_tile(p) ok = (Wsv == Wnew) and Ssv.size == Snew.size and bool((Ssv == Snew).all()) print(f" direct sieve of T_{p} (W={Wnew}) equals folded tile: {'PASS' if ok else 'FAIL'}") S, W = Snew, Wnew print(f" [fold {p} took {time.perf_counter() - tfold:.1f} s; elapsed {elapsed():.1f} s]", flush=True) R['Snew'] = None; R['g'] = None; R['spans'] = None; R['lengths'] = None sub("c'_min table, lambda = u/mbar_old (record values in parentheses)") print("fold u=0.25 0.50 0.75 0.90 | u=0.01 0.05") for p, (row, small) in cmin_rows_old.items(): print(f"{p:4d} " + " ".join(f"{c:.4f} ({r:.4f})" for (c, _), r in zip(row, REC_CMIN[p])) + f" | {small[0]:.5f} {small[1]:.5f}") worst = max(abs(c - r) for p, (row, _) in cmin_rows_old.items() for (c, _k), r in zip(row, REC_CMIN[p])) print(f"max |c'_min - record| over the {4*len(cmin_rows_old)} cells (mbar_old): {worst:.2e}") worst2 = max(abs(c - r) for p, row in cmin_rows_new.items() for c, r in zip(row, REC_CMIN[p])) print(f"max |c'_min - record| over the {4*len(cmin_rows_new)} cells (mbar_new variant): {worst2:.2e}") sub("K = Psi/Phi^2 over all cells") for p, u, K in Kcells: print(f" fold {p:2d} u={u:4.2f} K = {K:.8f} {'<1' if K < 1 else '>=1 !!'}") Ks = [K for _, _, K in Kcells] print(f"K min = {min(Ks):.8f} max = {max(Ks):.8f} over {len(Ks)} cells (record: 0.89362755 to 0.99894799, all < 1) " f"{'all < 1' if max(Ks) < 1 else 'NOT all < 1'}") worst_res = max(d['rel_res'] for R in results.values() for d in R['fmi'].values()) print(f"Fold Moment Identity: max relative residual over all folds and lambdas = {worst_res:.2e}") sub("TASK 6 summary over the 28 cells (folds 7..29 x u in {0.25,0.5,0.75,0.9})") print(f" (a) max |Gamma - (Omega + Delta)| = {max(c[2] for c in t6_cells):.2e}") print(f" (b) min F_R (stable evaluation) over all runs and cells = {min(c[3] for c in t6_cells):+.2e} ({'all >= 0' if min(c[3] for c in t6_cells) >= 0 else 'NEGATIVE F_R FOUND'})") print(f" min F_R (float64 polynomial form) = {min(c[4] for c in t6_cells):+.2e}; max |F_poly - F_stable| over all runs = {max(c[7] for c in t6_cells):.2e}; " f"max |Gamma_poly - Gamma| = {max(c[8] for c in t6_cells):.2e} (roundoff of the difference form)") print(f" (c) max |lhs-rhs| of (p-2)(Phi_new - N_p Phi) identity = {max(c[5] for c in t6_cells):.2e}, max relative = {max(c[6] for c in t6_cells):.2e}") if stopped_early: print("NOTE: stopped at fold 23 (fold 29 skipped for time).") print(f"[task 4 done at {elapsed():.1f} s]") # ============================================================================= hdr("TASK 5: runtime") # ============================================================================= print(f"TOTAL RUNTIME: {elapsed():.1f} s")