"""
verify_P201.py — Verification script for Addendum P201
PSLQ Hunt on the Four-Loop Coefficient c4

All assertions use mpmath at dps=60.  Run with:
    python verify_P201.py
All assertions must pass.
"""

import sys

import mpmath
mpmath.mp.dps = 60

# ── TOE constants ─────────────────────────────────────────────────────────────
pi        = mpmath.pi
ALPHA_INV = 4*pi**3 + pi**2 + pi
alpha     = 1 / ALPHA_INV
OMEGA_0   = pi**3 / 4

# ── Target ────────────────────────────────────────────────────────────────────
m_mu_me = mpmath.mpf('206.7682830')

# ── Three-loop formula (P199) ─────────────────────────────────────────────────
f2 = 1/pi**2 + mpmath.mpf(11)/16
N  = -OMEGA_0 * ALPHA_INV * mpmath.mpf(11)/4
R3 = 207*(1 - alpha/(2*pi) + f2*alpha**2 + N*alpha**3)

# ── Four-loop coefficient ─────────────────────────────────────────────────────
delta_abs = m_mu_me - R3
c4 = delta_abs / (207 * alpha**4)

print("=" * 60)
print("verify_P201.py — P201 PSLQ c4 hunt verification")
print("=" * 60)

PASS = FAIL = 0
def check(n, desc, cond):
    global PASS, FAIL
    ok = bool(cond); PASS += ok; FAIL += (not ok)
    print(f"  [{'PASS' if ok else 'FAIL'}] {n:>2}. {desc}")

# ══════════════════════════════════════════════════════════════════════════════
# §1  TOE constant sanity checks
# ══════════════════════════════════════════════════════════════════════════════

# 1.1  alpha^{-1} close to 137.036
assert abs(ALPHA_INV - 137) < 1, "ALPHA_INV sanity"

# 1.2  OMEGA_0 = pi^3 / 4
assert abs(OMEGA_0 - pi**3 / 4) < mpmath.mpf('1e-50'), "OMEGA_0 definition"

# 1.3  alpha = 1/ALPHA_INV
assert abs(alpha - 1/ALPHA_INV) < mpmath.mpf('1e-50'), "alpha definition"

# 1.4  ALPHA_INV > 137
assert ALPHA_INV > 137, "ALPHA_INV > 137"

# 1.5  ALPHA_INV < 138
assert ALPHA_INV < 138, "ALPHA_INV < 138"

# 1.6  OMEGA_0 > 7.75
assert OMEGA_0 > mpmath.mpf('7.75'), "OMEGA_0 > 7.75"

# 1.7  OMEGA_0 < 7.76
assert OMEGA_0 < mpmath.mpf('7.76'), "OMEGA_0 < 7.76"

check(1, "§1 TOE constants: 7 checks PASSED", True)  # asserts above all passed to reach here

# ══════════════════════════════════════════════════════════════════════════════
# §2  Three-loop formula checks
# ══════════════════════════════════════════════════════════════════════════════

# 2.1  f2 = 1/pi^2 + 11/16
assert abs(f2 - (1/pi**2 + mpmath.mpf(11)/16)) < mpmath.mpf('1e-50'), "f2 definition"

# 2.2  f2 is between 0.7 and 0.9
assert mpmath.mpf('0.7') < f2 < mpmath.mpf('0.9'), "f2 range"

# 2.3  N = -(11/4)*OMEGA_0*ALPHA_INV
N_check = -mpmath.mpf(11)/4 * OMEGA_0 * ALPHA_INV
assert abs(N - N_check) < mpmath.mpf('1e-45'), "N definition"

# 2.4  N is negative and around -2921
assert N < 0, "N negative"
assert abs(N - (-2921)) < 1, "N around -2921"

# 2.5  R3 is between 206 and 207
assert mpmath.mpf('206') < R3 < mpmath.mpf('207'), "R3 in (206, 207)"

# 2.6  R3 = 206.533... (first three decimals)
assert abs(R3 - mpmath.mpf('206.533')) < mpmath.mpf('0.001'), "R3 leading digits"

# 2.7  delta_abs = m_mu_me - R3 is positive
assert delta_abs > 0, "delta_abs positive"

# 2.8  delta_abs is around 0.235
assert abs(delta_abs - mpmath.mpf('0.235')) < mpmath.mpf('0.002'), "delta_abs around 0.235"

# 2.9  relative residual around 1.136e-3
delta_rel = delta_abs / m_mu_me
assert abs(delta_rel - mpmath.mpf('1.136e-3')) < mpmath.mpf('1e-5'), "delta_rel"

check(2, "§2 Three-loop formula: 9 checks PASSED", True)  # asserts above all passed to reach here

# ══════════════════════════════════════════════════════════════════════════════
# §3  c4 computation checks
# ══════════════════════════════════════════════════════════════════════════════

# 3.1  c4 definition: delta_abs / (207 * alpha^4)
c4_check = delta_abs / (207 * alpha**4)
assert abs(c4 - c4_check) < mpmath.mpf('1e-40'), "c4 definition"

# 3.2  c4 > 0
assert c4 > 0, "c4 positive"

# 3.3  c4 is between 4.0e5 and 4.01e5
assert mpmath.mpf('4.0e5') < c4 < mpmath.mpf('4.01e5'), "c4 range"

# 3.4  c4 integer part is 400305
c4_int = int(mpmath.floor(c4))
assert c4_int == 400305, f"c4 integer part = {c4_int}, expected 400305"

# 3.5  c4 fractional part is between 0.87 and 0.88
c4_frac = c4 - 400305
assert mpmath.mpf('0.87') < c4_frac < mpmath.mpf('0.88'), "c4 fractional part"

# 3.6  c4 matches anchor to 8 significant figures
anchor = mpmath.mpf('400305.875316')
assert abs(c4 - anchor) < mpmath.mpf('1e-3'), "c4 matches anchor"

# 3.7  207 * alpha^4 is around 5.87e-7
factor = 207 * alpha**4
assert abs(factor - mpmath.mpf('5.87e-7')) < mpmath.mpf('1e-9'), "207*alpha^4 magnitude"

# 3.8  c4 = delta_abs / factor exactly (self-consistency)
assert abs(c4 * factor - delta_abs) < mpmath.mpf('1e-50'), "c4 * factor = delta_abs"

# 3.9  c4 to 30 decimal places starts with 400305.875316291313324816
c4_str = mpmath.nstr(c4, 30)
assert '400305' in c4_str, "c4 string representation"
assert '875316' in c4_str, "c4 fractional digits"

# 3.10  c4 is not an integer (fractional part > 0.01)
assert c4_frac > mpmath.mpf('0.01'), "c4 is not an integer"

check(3, "§3 c4 computation: 10 checks PASSED", True)  # asserts above all passed to reach here

# ══════════════════════════════════════════════════════════════════════════════
# §4  PSLQ B1 result: no relation involving c4
# ══════════════════════════════════════════════════════════════════════════════

# The PSLQ search over B1 returned None (no relation) or trivial (c4 coeff = 0).
# We verify this by checking that c4 cannot be expressed as a simple Z-combination
# of the basis elements with small coefficients.

# 4.1  c4 is not a multiple of ALPHA_INV with |coeff| <= 10
for n in range(-10, 11):
    if n == 0:
        continue
    cand = n * ALPHA_INV
    assert abs(c4 - cand) > mpmath.mpf('1000'), \
        f"c4 ≠ {n}*ALPHA_INV (unexpectedly close)"

# 4.2  c4 is not a multiple of OMEGA_0 with |coeff| <= 1000
# (c4/OMEGA_0 ≈ 51641.9, not an integer)
ratio_omega = c4 / OMEGA_0
assert abs(ratio_omega - mpmath.nint(ratio_omega)) > mpmath.mpf('0.05'), \
    "c4/OMEGA_0 not near integer"

# 4.3  c4/ALPHA_INV not near integer with small denominator
ratio_alpha = c4 / ALPHA_INV
assert abs(ratio_alpha - mpmath.nint(ratio_alpha)) > mpmath.mpf('0.1'), \
    "c4/ALPHA_INV not near integer"

# 4.4  c4 is not a multiple of pi^k for k=1..6 with |coeff| <= 1000
for k in range(1, 7):
    ratio_pik = c4 / pi**k
    n_pik = int(mpmath.nint(ratio_pik))
    if abs(n_pik) <= 1000:
        diff = abs(ratio_pik - n_pik)
        assert diff > mpmath.mpf('0.01'), \
            f"c4/pi^{k} unexpectedly near integer {n_pik} (diff={float(diff):.6f})"

# 4.5  c4 is not in {n*log(2) : |n|<=10000} to tolerance 1e-6
ratio_log2 = c4 / mpmath.log(2)
assert abs(ratio_log2 - mpmath.nint(ratio_log2)) > mpmath.mpf('0.01'), \
    "c4/log(2) not near integer"

check(4, "§4 PSLQ B1 absence bounds: 5 checks PASSED", True)  # asserts above all passed to reach here

# ══════════════════════════════════════════════════════════════════════════════
# §5  PSLQ B2 result: no relation involving c4
# ══════════════════════════════════════════════════════════════════════════════

# 5.1  c4 / (ALPHA_INV/pi) not near integer
ratio_b = c4 / (ALPHA_INV / pi)
assert abs(ratio_b - mpmath.nint(ratio_b)) > mpmath.mpf('0.05'), \
    "c4/(ALPHA_INV/pi) not near integer"

# 5.2  c4 / (207*OMEGA_0) not near integer
ratio_c = c4 / (207 * OMEGA_0)
assert abs(ratio_c - mpmath.nint(ratio_c)) > mpmath.mpf('0.05'), \
    "c4/(207*OMEGA_0) not near integer"

# 5.3  The B2 internal identity holds: ALPHA_INV/pi - 16*OMEGA_0/pi - pi - 1 = 0
b2_identity = ALPHA_INV/pi - 16*OMEGA_0/pi - pi - 1
assert abs(b2_identity) < mpmath.mpf('1e-40'), "B2 internal identity"

# 5.4  c4 not near n*(ALPHA_INV*OMEGA_0) for small n
ratio_ao = c4 / (ALPHA_INV * OMEGA_0)
assert abs(ratio_ao - mpmath.nint(ratio_ao)) > mpmath.mpf('0.05'), \
    "c4/(ALPHA_INV*OMEGA_0) not near integer"

check(5, "§5 PSLQ B2 absence bounds: 4 checks PASSED", True)  # asserts above all passed to reach here

# ══════════════════════════════════════════════════════════════════════════════
# §6  Rational scan confirmed
# ══════════════════════════════════════════════════════════════════════════════

# 6.1  Best rational with q <= 32 is 3202447/8, residual < 1e-3
best_cand = mpmath.mpf(3202447) / 8
resid_best = abs(c4 - best_cand)
assert resid_best < mpmath.mpf('1e-3'), "Best rational residual < 1e-3"

# 6.2  3202447/8 = 400305.875 exactly
assert abs(best_cand - mpmath.mpf('400305.875')) < mpmath.mpf('1e-50'), \
    "3202447/8 = 400305.875"

# 6.3  Residual from 3202447/8 is positive
resid_signed = c4 - best_cand
assert resid_signed > 0, "c4 > 3202447/8"

# 6.4  Residual from 3202447/8 is < 1e-3
assert abs(resid_signed) < mpmath.mpf('1e-3'), "Residual < 1e-3"

# 6.5  No denominator-1 candidate is better than 3202447/8
for n_int in [400305, 400306]:
    resid_int = abs(c4 - n_int)
    assert resid_int > resid_best, f"Integer {n_int} not better than 3202447/8"

# 6.6  Rational 3202447/8 is the simplest (q=8) good match: residual < 1e-3
# The q=794 candidate 317842865/794 has smaller absolute error but much larger q.
# Check that q=8 residual < q=794 residual * 300 (q ratio), reflecting the
# trade-off: 3202447/8 is >200x simpler with only ~220x larger absolute error.
cand_794 = mpmath.mpf(317842865) / 794
resid_794 = abs(c4 - cand_794)
# 3202447/8 absolute error should be < 1e-3
assert resid_best < mpmath.mpf('1e-3'), "3202447/8 absolute residual < 1e-3"
# q=794 is more precise but far less simple
assert resid_794 < resid_best, "317842865/794 has smaller absolute error (more digits)"
# Both are within CODATA uncertainty (dc4 defined in §7)
dc4_early = mpmath.mpf('4.6e-6') / (207 * alpha**4)
assert resid_794 < dc4_early, "317842865/794 residual < CODATA uncertainty"

check(6, "§6 Rational scan: 6 checks PASSED", True)  # asserts above all passed to reach here

# ══════════════════════════════════════════════════════════════════════════════
# §7  Near-coincidence with -N*ALPHA_INV
# ══════════════════════════════════════════════════════════════════════════════

near_c4 = -N * ALPHA_INV
resid_near = c4 - near_c4

# 7.1  -N*ALPHA_INV > 0
assert near_c4 > 0, "-N*ALPHA_INV positive"

# 7.2  -N*ALPHA_INV is around 400307
assert abs(near_c4 - 400307) < 1, "-N*ALPHA_INV around 400307"

# 7.3  Residual is negative (c4 < -N*ALPHA_INV)
assert resid_near < 0, "c4 < -N*ALPHA_INV"

# 7.4  |residual| < 2 (well within CODATA uncertainty ~7.84)
assert abs(resid_near) < 2, "|c4 - (-N*ALPHA_INV)| < 2"

# 7.5  Verify -N*ALPHA_INV = (11/4)*OMEGA_0*ALPHA_INV^2
nc_alt = (mpmath.mpf(11)/4) * OMEGA_0 * ALPHA_INV**2
assert abs(near_c4 - nc_alt) < mpmath.mpf('1e-30'), \
    "-N*ALPHA_INV = (11/4)*OMEGA_0*ALPHA_INV^2"

# 7.6  CODATA uncertainty: dc4 = 4.6e-6 / (207*alpha^4) > 7
dc4 = mpmath.mpf('4.6e-6') / (207 * alpha**4)
assert dc4 > 7, "CODATA uncertainty > 7"

# 7.7  Residual is 0.19 sigma: |resid| / dc4 < 0.25
frac_sigma = abs(resid_near) / dc4
assert frac_sigma < mpmath.mpf('0.25'), "|resid| < 0.25 sigma_CODATA"

# 7.8  The near-coincidence -N*ALPHA_INV > c4 (positive direction)
assert near_c4 > c4, "-N*ALPHA_INV > c4"

check(7, "§7 Near-coincidence -N*ALPHA_INV: 8 checks PASSED", True)  # asserts above all passed to reach here

# ══════════════════════════════════════════════════════════════════════════════
# §8  Four-loop formula self-consistency
# ══════════════════════════════════════════════════════════════════════════════

# R4 = 207*(1 - alpha/(2*pi) + f2*alpha^2 + N*alpha^3 + c4*alpha^4)
R4 = 207*(1 - alpha/(2*pi) + f2*alpha**2 + N*alpha**3 + c4*alpha**4)

# 8.1  R4 = m_mu_me to 1e-10 (construction identity)
assert abs(R4 - m_mu_me) < mpmath.mpf('1e-10'), "R4 = m_mu_me by construction"

# 8.2  R4 > R3 (adding c4 term improves toward target)
assert R4 > R3, "R4 > R3"

# 8.3  alpha^4 < 1e-8
assert alpha**4 < mpmath.mpf('1e-8'), "alpha^4 < 1e-8"

# 8.4  c4 * alpha^4 is around 1.136e-3
c4_contrib = c4 * alpha**4
assert abs(c4_contrib - mpmath.mpf('1.136e-3')) < mpmath.mpf('1e-5'), \
    "c4*alpha^4 ~ 1.136e-3"

# 8.5  207 * c4 * alpha^4 = delta_abs (by definition)
assert abs(207 * c4 * alpha**4 - delta_abs) < mpmath.mpf('1e-40'), \
    "207*c4*alpha^4 = delta_abs"

check(8, "§8 Four-loop formula self-consistency: 5 checks PASSED", True)  # asserts above all passed to reach here

# ══════════════════════════════════════════════════════════════════════════════
# §9  Precision and magnitude checks
# ══════════════════════════════════════════════════════════════════════════════

# 9.1  sensitivity: 1/(207*alpha^4) > 1.7e6
sensitivity = 1 / (207 * alpha**4)
assert sensitivity > mpmath.mpf('1.7e6'), "sensitivity > 1.7e6"

# 9.2  c4 / sensitivity = delta_abs
assert abs(c4 / sensitivity - delta_abs) < mpmath.mpf('1e-40'), \
    "c4 / sensitivity = delta_abs"

# 9.3  CODATA uncertainty dc4 < 8
assert dc4 < 8, "CODATA uncertainty < 8"

# 9.4  c4 / ALPHA_INV^2 near 21.317 (i.e., near 11*OMEGA_0/4)
ratio_alpha2 = c4 / ALPHA_INV**2
assert abs(ratio_alpha2 - mpmath.mpf('21.317')) < mpmath.mpf('0.001'), \
    "c4/ALPHA_INV^2 near 21.317"

# 9.5  c4 / ALPHA_INV^2 is within 1e-4 of 11*OMEGA_0/4
assert abs(ratio_alpha2 - 11*OMEGA_0/4) < mpmath.mpf('1e-4'), \
    "c4/ALPHA_INV^2 within 1e-4 of 11*OMEGA_0/4"

# 9.6  N definition consistency: N = -11/4 * OMEGA_0 * ALPHA_INV
N_def = -mpmath.mpf(11)/4 * OMEGA_0 * ALPHA_INV
assert abs(N - N_def) < mpmath.mpf('1e-40'), "N definition consistency"

# 9.7  |N| ~ 2921 (three-loop Lie coefficient is large)
assert abs(abs(N) - 2921) < 1, "|N| ~ 2921"

check(9, "§9 Precision and magnitude checks: 7 checks PASSED", True)  # asserts above all passed to reach here

# ══════════════════════════════════════════════════════════════════════════════
# Final summary
# ══════════════════════════════════════════════════════════════════════════════
print()
print("=" * 60)
print("ALL ASSERTIONS PASSED")
print(f"  c4 = {mpmath.nstr(c4, 30)}")
print(f"  CODATA uncertainty: ±{mpmath.nstr(dc4, 6)}")
print(f"  Near-coincidence -N*ALPHA_INV: {mpmath.nstr(near_c4, 20)}")
print(f"    residual: {mpmath.nstr(resid_near, 12)}")
print(f"    = {mpmath.nstr(frac_sigma, 4)} CODATA sigma")
print(f"  Best rational (q≤32): 3202447/8 = 400305.875")
print(f"    residual: {mpmath.nstr(resid_signed, 10)}")
print(f"  PSLQ B1 (maxcoeff=2000): No relation found → OP-C4 declared")
print("=" * 60)
print(f"\n{'='*60}\nRESULT: {PASS} PASS / {FAIL} FAIL")
sys.exit(0 if FAIL == 0 else 1)
