#!/usr/bin/env python3 """Equivalence-error census: D_y - D^(e1) = T^top - P^top at matched conventions (job #4298). Implements, for each j: * the moving census D_y of moving-cutoff-parity (9)/(10) with the exact conventions of the served centered-discrepancy-measurement.js (y = ceil(x^(12/25)), Q = floor(x/y), a_e = max(x/2, e y)), computed as acc1 - P in the script's arrangement; * the fixed-endpoint D^(e1) of centered-discrepancy-estimate (1) / fixed-endpoint-discrepancy (2.1) at the prescribed e1 = floor(x^(1/2+eps)), eps = 0.01, split as P_low + P_band and the exact density projections Q_R; * the difference Delta = D^(e1) - D_y, the admissibility diagnostic (e1 <= x/(2y)+1), the exact miscut term C, T^top/P^top, and the admissible-cutoff instrument (e1* = floor(x/(2y))+1); * the blocking control against the served script's embedded published column. No asymptotic claim is made; every number is a finite sum at one dyadic x. See PREREG-4298.md. """ import gc import json import math import os import sys import time from decimal import Decimal, getcontext import numpy as np getcontext().prec = 60 HERE = os.path.dirname(os.path.abspath(__file__)) RUN = os.path.normpath(os.path.join(HERE, "..", "..")) DOC = os.path.join(RUN, "work", "j3310", "doc", "centered-discrepancy-measurement.js") OUT = os.path.join(HERE, "out") os.makedirs(OUT, exist_ok=True) EPS = Decimal("0.01") THETA = 12.0 / 25.0 C2 = 0.6601618158468695739 def primes_upto(n): s = bytearray(b"\x01") * (n + 1) s[0:2] = b"\x00\x00" out = [] for i in range(2, n + 1): if s[i]: out.append(i) s[i * i:: i] = b"\x00" * (((n - i * i) // i) + 1) return out def small_tables(N): phi = np.arange(N + 1, dtype=np.int64) mu = np.ones(N + 1, dtype=np.int64) for p in primes_upto(N): phi[p::p] -= phi[p::p] // p mu[p::p] *= -1 pp = p * p if pp <= N: mu[pp::pp] = 0 return phi, mu def floor_pow2_frac(j, num, den): """floor(2^(j*num/den)) exactly (num/den rational, via 60-digit Decimal).""" e = Decimal(j) * Decimal(num) / Decimal(den) return int((Decimal(2) ** e).to_integral_value(rounding="ROUND_FLOOR")) def parse_control(): """Parse the served script's embedded MAIN TABLE rows (j, y, Q, M/x, D_y/x, acc1/x, P/x).""" rows = {} for line in open(DOC, encoding="utf-8"): line = line.strip() if not line.startswith("// ") or "|" not in line: continue parts = [p.strip() for p in line[3:].split("|")] if len(parts) < 10 or not parts[0].isdigit(): continue try: j = int(parts[0]) rows[j] = { "x": int(parts[1]), "y": int(parts[2]), "Q": int(parts[3]), "nOddSqfE": int(parts[4]), "support": int(parts[5]), "M_x": float(parts[6]), "D_x": float(parts[7]), "acc1_x": float(parts[8]), "P_x": float(parts[9]), } except (ValueError, IndexError): continue return rows def run_j(j, ctl): t0 = time.time() x = 1 << j y = math.ceil(math.pow(2.0, THETA * j)) Q = x // y lo1 = x // 2 + 1 L = x - x // 2 # |J| lo2 = lo1 - 2 # window for Lambda(n-2) hi2 = x - 2 sq = math.isqrt(x) primes = primes_upto(sq) e1 = floor_pow2_frac(j, 51, 100) # floor(x^(1/2+eps)), eps = 0.01 e0 = floor_pow2_frac(j, 49, 100) # floor(x^(1/2-eps)) e1s = x // (2 * y) + 1 # largest admissible cutoff adm = e1 <= x // (2 * y) + 1 if j in ctl: assert ctl[j]["x"] == x and ctl[j]["y"] == y and ctl[j]["Q"] == Q, (j, ctl[j]) # ---- Lambda(m), m = n - 2 over [lo2, hi2] --------------------------- lam = np.zeros(L, dtype=np.float64) comp = np.zeros(L, dtype=bool) for p in primes: if p * p > hi2: break start = max(p * p, ((lo2 + p - 1) // p) * p) if start <= hi2: comp[start - lo2:: p] = True idx = np.nonzero(~comp)[0] lam[idx] = np.log(idx + lo2) del comp, idx for p in primes: pk = p * p if pk > hi2: break lp = math.log(p) while pk <= hi2: if pk >= lo2: lam[pk - lo2] = lp pk *= p # ---- mu(n) over J --------------------------------------------------- prod = np.ones(L, dtype=np.float64) omega = np.zeros(L, dtype=np.int16) sqf = np.zeros(L, dtype=bool) for p in primes: start = ((lo1 + p - 1) // p) * p prod[start - lo1:: p] *= p omega[start - lo1:: p] += 1 pp = p * p if pp <= x: s2 = ((lo1 + pp - 1) // pp) * pp if s2 <= x: sqf[s2 - lo1:: pp] = True nvals = np.arange(lo1, x + 1, dtype=np.float64) cof = nvals / prod tot = omega.astype(np.int32) + (cof > 1.5) mu = np.where(sqf, 0.0, 1.0 - 2.0 * np.mod(tot, 2)) del prod, omega, sqf, cof, tot f = mu * lam del mu, lam logn = np.log(nvals) gc.collect() M = float(f.sum()) F1 = float((f * logn).sum()) # suffix sums: sufF[i] = sum_{k>=i} f_k ; sufFL[i] = sum_{k>=i} f_k log n_k sufF = np.zeros(L + 1, dtype=np.float64) sufFL = np.zeros(L + 1, dtype=np.float64) sufF[:L] = f[::-1].cumsum()[::-1] sufFL[:L] = (f * logn)[::-1].cumsum()[::-1] def first_mult_index(e, c): """First index i with n = lo1+i a multiple of e and n > c (c >= x/2).""" n0 = (c // e + 1) * e return n0 - lo1 def dens_index(c): """First index i with n = lo1+i > c (the density sum is over all n, not multiples).""" return c + 1 - lo1 def prog(e, i0, le): """sum_{n > c, e|n} f(n) log(e/n) as a slice sum.""" if i0 >= L: return 0.0 sl = slice(i0, L, e) return float(((le - logn[sl]) * f[sl]).sum()) def dens(i0, le): """sum_{n > c} f(n) log(e/n) via suffix sums.""" if i0 >= L: return 0.0 return le * sufF[i0] - sufFL[i0] phi, mu_e = small_tables(max(Q, e1) + 1) log_e = np.log(np.arange(max(Q, e1) + 1, dtype=np.float64)) def G(e, c): i0 = first_mult_index(e, c) return float(mu_e[e]) * (prog(e, i0, log_e[e]) - dens(dens_index(c), log_e[e]) / float(phi[e])) # ---- moving side: acc1, P, D_y ------------------------------------- acc1 = 0.0 Pmov = 0.0 nOdd = 0 for e in range(1, Q + 1, 2): if mu_e[e] == 0: continue nOdd += 1 c = max(x // 2, e * y) i0 = first_mult_index(e, c) acc1 += float(mu_e[e]) * prog(e, i0, log_e[e]) Pmov += float(mu_e[e]) / float(phi[e]) * dens(dens_index(c), log_e[e]) D = acc1 - Pmov # ---- fixed side at the prescribed e1 -------------------------------- def fixed_prefix(upper): """P_R and Q_R (progression part, density projection) for odd e < upper, endpoint x/2.""" PR = 0.0 S0 = 0.0 S1 = 0.0 for e in range(1, upper, 2): if mu_e[e] == 0: continue i0 = first_mult_index(e, x // 2) PR += float(mu_e[e]) * prog(e, i0, log_e[e]) S0 += float(mu_e[e]) / float(phi[e]) S1 += float(mu_e[e]) * log_e[e] / float(phi[e]) return PR, S0, S1 Plow, S0l, S1l = fixed_prefix(e0) Pband, S0b, S1b = fixed_prefix(e1) Pband -= Plow S0b -= S0l S1b -= S1l Qlow = M * S1l - F1 * S0l Qband = M * S1b - F1 * S0b Dfix = Plow - Qlow + Pband - Qband # ---- convention diagnostics ----------------------------------------- Cmisc = 0.0 for e in range(1, e1, 2): if mu_e[e] == 0 or e * y <= x // 2: continue Cmisc += G(e, x // 2) - G(e, e * y) Ttop = 0.0 Ptop = 0.0 odd_from_e1 = e1 if e1 % 2 == 1 else e1 + 1 for e in range(odd_from_e1, Q + 1, 2): if mu_e[e] == 0: continue c = max(x // 2, e * y) i0 = first_mult_index(e, c) Ttop += float(mu_e[e]) * prog(e, i0, log_e[e]) Ptop += float(mu_e[e]) / float(phi[e]) * dens(dens_index(c), log_e[e]) delta = Dfix - D resid = delta - (Cmisc - Ttop + Ptop) # ---- admissible instrument ------------------------------------------ Da = 0.0 for e in range(1, e1s, 2): if mu_e[e] == 0: continue Da += G(e, x // 2) Ta = 0.0 Pa = 0.0 odd_from_e1s = e1s if e1s % 2 == 1 else e1s + 1 for e in range(odd_from_e1s, Q + 1, 2): if mu_e[e] == 0: continue c = max(x // 2, e * y) i0 = first_mult_index(e, c) Ta += float(mu_e[e]) * prog(e, i0, log_e[e]) Pa += float(mu_e[e]) / float(phi[e]) * dens(dens_index(c), log_e[e]) resid_a = D - (Da + Ta - Pa) delta_a = Da - D row = { "j": j, "x": x, "y": y, "Q": Q, "e0": e0, "e1": e1, "e1star": e1s, "admissible_e1": bool(adm), "adm_ratio_e1_over_x2y": e1 / (x / (2 * y)), "n_odd_sqfree_e": nOdd, "M": M, "F1": F1, "acc1": acc1, "P": Pmov, "D": D, "D_x": D / x, "Plow": Plow, "Pband": Pband, "Qlow": Qlow, "Qband": Qband, "Dfix": Dfix, "Dfix_x": Dfix / x, "delta": delta, "delta_x": delta / x, "Cmisc": Cmisc, "Ttop": Ttop, "Ptop": Ptop, "resid_delta_identity": resid, "resid_rel": abs(resid) / max(1.0, abs(delta)), "Da": Da, "Ta": Ta, "Pa": Pa, "delta_a": delta_a, "delta_a_x": delta_a / x, "resid_a": resid_a, "resid_a_rel": abs(resid_a) / max(1.0, abs(Da) + abs(D)), "seconds": time.time() - t0, } if j in ctl: row["control"] = { k: {"mine": row[{"M_x": "M", "D_x": "D", "acc1_x": "acc1", "P_x": "P"}[k]] / x, "served": ctl[j][k]} for k in ("M_x", "D_x", "acc1_x", "P_x") } row["control_max_abs_diff"] = max( abs(v["mine"] - v["served"]) for v in row["control"].values()) return row def fit_k(rows, key): """Fit log(|Delta|/x) = c - k log log x; return k and its standard error.""" pts = [(math.log(math.log(r["x"])), math.log(abs(r[key]) / r["x"])) for r in rows if abs(r[key]) > 0] n = len(pts) mx = sum(p[0] for p in pts) / n my = sum(p[1] for p in pts) / n sxx = sum((u - mx) ** 2 for u, _ in pts) sxy = sum((u - mx) * (v - my) for u, v in pts) k = -sxy / sxx resid = [v - (my + (sxy / sxx) * (u - mx)) for u, v in pts] if n > 2: s2 = sum(r * r for r in resid) / (n - 2) se = math.sqrt(s2 / sxx) else: se = float("nan") return k, se def main(): jmin = int(sys.argv[1]) if len(sys.argv) > 1 else 16 jmax = int(sys.argv[2]) if len(sys.argv) > 2 else 24 ctl = parse_control() rows = [] for j in range(jmin, jmax + 1): row = run_j(j, ctl) rows.append(row) json.dump(row, open(os.path.join(OUT, f"equiv-j{j}.json"), "w", encoding="utf-8"), indent=1, default=float) tag = "" if "control_max_abs_diff" in row: tag = " ctl_max_diff=%.3e" % row["control_max_abs_diff"] print("j=%2d x=%9d y=%5d Q=%5d e0=%5d e1=%5d e1*=%5d adm=%d D_y/x=%+.6f " "Dfix/x=%+.6f Dfixs/x=%+.6f D/x=%+.6f C/x=%+.6f Ttop/x=%+.6f " "Ptop/x=%+.6f resid_rel=%.1e %.1fs%s" % (j, row["x"], row["y"], row["Q"], row["e0"], row["e1"], row["e1star"], int(row["admissible_e1"]), row["D_x"], row["Dfix_x"], row["Da"] / row["x"], row["delta_x"], row["Cmisc"] / row["x"], row["Ttop"] / row["x"], row["Ptop"] / row["x"], row["resid_rel"], row["seconds"], tag), flush=True) gc.collect() big = [r for r in rows if r["j"] >= 16] kd, sed = fit_k(big, "delta") ka, sea = fit_k(big, "delta_a") summary = { "jmin": jmin, "jmax": jmax, "fit_delta": {"k": kd, "se": sed}, "fit_delta_admissible": {"k": ka, "se": sea}, "F_A_violation_prescribed": [r["j"] for r in big if r["delta_x"] < -0.1204], "F_A_violation_admissible": [r["j"] for r in big if r["delta_a_x"] < -0.1204], "admissible": [r["admissible_e1"] for r in big], "rows": rows, "control_ok": all("control_max_abs_diff" in r and r["control_max_abs_diff"] <= 1e-6 for r in rows), "scope": "finite measurement at dyadic x; no asymptotic estimate proved or supported", } json.dump(summary, open(os.path.join(OUT, "equiv-summary.json"), "w", encoding="utf-8"), indent=1, default=float) print("\nFITS k(Delta)=%.3f +- %.3f k(Delta_admissible)=%.3f +- %.3f" % (kd, sed, ka, sea)) print("CONTROL: %s" % ("all j=16..%d within 1e-6" % jmax if summary["control_ok"] else "FAILED")) print("F_A (prescribed): %s ; (admissible): %s" % (summary["F_A_violation_prescribed"] or "no violation", summary["F_A_violation_admissible"] or "no violation")) if __name__ == "__main__": main()