#!/usr/bin/env python3
"""
verify_P140.py — Verification script for Addendum P140
Geometric Mean Prescription and Quark Continuum Decoupling

Verifies the key numerical and structural claims of P140:

  1. TOE constants (ALPHA_INV, ALPHA)
  2. VMD decay constants f²_V (P117–P119)
  3. NWA resonance contributions Δα_had^V (ρ, ω, φ)  from P136 Table 1
  4. Light-meson NWA sum = 4.522×10⁻³
  5. GS dispersive integral for ρ = 2.943×10⁻³ (P137 cross-check)
  6. GS light-meson total = 3.731×10⁻³
  7. Geometric mean of NWA and GS = 4.107×10⁻³  (within 0.07% of target 4.110×10⁻³)
  8. Arithmetic mean comparison (GM is tighter than AM)
  9. Hurwitz measure on S⁷: marginal d_μ ∝ s^(7/2) ds  (not log-flat)
 10. PDG/TOE factor ≈ 6.7 and three pillars of quark continuum decoupling

Sources:
  P140 — primary (Geometric Mean Prescription and Quark Continuum Decoupling)
  P137 — GS dispersive integral for ρ
  P136 — NWA resonance contributions
  P119, P118, P117 — TOE-derived VMD decay constants

Copyright: Léon Fernando Vlegels. License: MIT.
"""

import math
import sys

try:
    from scipy import integrate as sci_int
    HAS_SCIPY = True
except ImportError:
    HAS_SCIPY = False

# ── TOE constants (frozen — kernel/math/quat_s3.py) ──────────────────────────
ALPHA_INV = 4*math.pi**3 + math.pi**2 + math.pi   # 4π³ + π² + π  (P35 T1)
ALPHA     = 1.0 / ALPHA_INV

# ── Physical constants (PDG) ──────────────────────────────────────────────────
M_Z   = 91.1876    # GeV  (Z-boson mass)
M_PI  = 0.13957    # GeV  (charged pion mass)

# Light vector meson masses (PDG)
M_RHO   = 0.77526   # GeV
M_OMEGA = 0.78266   # GeV
M_PHI   = 1.01946   # GeV

# ρ resonance parameters for GS integral (P137)
GAMMA_RHO = 0.1474   # GeV  (147.4 MeV)

# Hadronic branching ratios (PDG)
BR_RHO   = 1.000
BR_OMEGA = 0.892   # three-pion mode (excluding π⁰γ)
BR_PHI   = 0.994

# ── TOE-derived VMD decay constants (P117–P119) ───────────────────────────────
ALPHA_S  = 0.1186    # strong coupling at M_Z  (P106)
MU_VAL   = 0.79334   # Peirce spectral moment μ₁/μ₀  (P80)

# f²_ρ = 8π(1 − πα)                (P119)
F2_RHO   = 8*math.pi * (1 - math.pi*ALPHA)
# f²_ω = 72π/(1 − α_s)²            (P118)
F2_OMEGA = 72*math.pi / (1 - ALPHA_S)**2
# f²_φ = 36π/MU²                   (P117)
F2_PHI   = 36*math.pi / MU_VAL**2

# TOE leptonic width of ρ (P119/P137): Γ_ee = 4πα²M_ρ/(3f²_ρ)
GAMMA_EE_RHO = 4*math.pi * ALPHA**2 * M_RHO / (3*F2_RHO)

# Pion c.m. momentum at M_ρ (Blatt-Weisskopf anchor, P137 §2)
P0_RHO = math.sqrt(M_RHO**2/4.0 - M_PI**2)

# ── Fermi target and PDG reference (P135/P136, P140 §1) ──────────────────────
DAHAD_TARGET = 4.110e-3   # Fermi route target (P135/P136)
DAHAD_PDG    = 0.02750    # SM dispersive total (PDG)


# ─────────────────────────────────────────────────────────────────────────────
# NWA formula (P136 eq. 10)
# Δα_had^V = 4πα · Br_had / f_V² · M_Z²/(M_Z² − M_V²)
# ─────────────────────────────────────────────────────────────────────────────
def nwa_contrib(M_V, f2_V, Br_had):
    """Narrow-width-approximation contribution to Δα_had from resonance V."""
    kinematic = M_Z**2 / (M_Z**2 - M_V**2)
    return 4*math.pi * ALPHA * Br_had / f2_V * kinematic


# ─────────────────────────────────────────────────────────────────────────────
# GS running width (P137 eq. 17)
# Γ_ρ(s) = Γ_ρ · (s/M_ρ²) · (p(s)/p₀)³ · (M_ρ² + p₀²)/(s + p²(s))
# p(s) = sqrt(s/4 − m_π²),  p₀ = p(M_ρ²) = 0.3616 GeV
# ─────────────────────────────────────────────────────────────────────────────
def rho_running_width(s):
    """GS running width Γ_ρ(s) with Blatt-Weisskopf barrier factor."""
    if s <= 4.0*M_PI**2:
        return 0.0
    p_sq = s/4.0 - M_PI**2
    p    = math.sqrt(p_sq)
    bw   = (M_RHO**2 + P0_RHO**2) / (s + p_sq)    # Blatt-Weisskopf factor
    return GAMMA_RHO * (s / M_RHO**2) * (p / P0_RHO)**3 * bw


# ─────────────────────────────────────────────────────────────────────────────
# GS dispersive integrand (P137 eq. 21)
# Δα_ρ^GS = (α/3π) ∫ R_ρ(s)/s · M_Z²/(M_Z²−s) ds
#           = (3Γ_ee/(πα)) ∫ Γ_ρ(s)·M_Z² / [(s−M_ρ²)² + M_ρ²Γ_ρ²(s)] / (M_Z²−s) ds
# ─────────────────────────────────────────────────────────────────────────────
def gs_integrand(s):
    """Integrand for the GS dispersive integral over the ρ lineshape."""
    gam      = rho_running_width(s)
    bw_denom = (s - M_RHO**2)**2 + M_RHO**2 * gam**2
    kinematic = M_Z**2 / (M_Z**2 - s)
    return 3.0 * GAMMA_EE_RHO * gam / (math.pi * ALPHA * bw_denom) * kinematic


def integrate_gs_rho():
    """Integrate GS lineshape from pion threshold to s_cut = (1 GeV)²."""
    s_lo  = (2.0*M_PI)**2   # pion pair threshold
    s_cut = 1.0             # (1 GeV)²

    if HAS_SCIPY:
        result, err = sci_int.quad(
            gs_integrand, s_lo, s_cut,
            limit=2000, epsabs=1e-15, epsrel=1e-12,
            points=[M_RHO**2]   # steer integrator around the peak
        )
        return result, err
    else:
        # Composite Simpson's rule with 30 000 subintervals
        n = 30000
        h = (s_cut - s_lo) / n
        total = gs_integrand(s_lo) + gs_integrand(s_cut)
        for i in range(1, n):
            coeff = 4 if i % 2 == 1 else 2
            total += coeff * gs_integrand(s_lo + i*h)
        return total * h / 3.0, None


# ─────────────────────────────────────────────────────────────────────────────
# Main verification
# ─────────────────────────────────────────────────────────────────────────────
def main():
    BAR      = "=" * 66
    THIN_BAR = "─" * 66
    PF = {"pass": 0, "fail": 0, "n": 0}

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

    def chk(label, computed, ref, tol_pct, note=""):
        err_pct = (computed - ref) / ref * 100.0
        suffix  = f"  [{note}]" if note else ""
        return check(f"{label}: {computed:.4e}  ref={ref:.4e}  err={err_pct:+.3f}%{suffix}",
                     abs(err_pct) < tol_pct)

    print(BAR)
    print("  P140  Geometric Mean Prescription & Quark Continuum Decoupling")
    print(BAR)

    # ── 1. TOE constants ──────────────────────────────────────────────────────
    print(f"\n{THIN_BAR}")
    print("  1. TOE constants")
    print(THIN_BAR)
    print(f"  ALPHA_INV = {ALPHA_INV:.6f}   (4π³ + π² + π,  P35 T1)")
    print(f"  ALPHA     = {ALPHA:.8e}   (1/ALPHA_INV)")
    print(f"  PDG α⁻¹   = 137.036        TOE α⁻¹ = {ALPHA_INV:.4f}")
    check("ALPHA within 3e-5 of 1/137.036", abs(ALPHA - 1.0/137.036) < 3e-5)

    # ── 2. VMD decay constants (P117–P119) ────────────────────────────────────
    print(f"\n{THIN_BAR}")
    print("  2. VMD decay constants (P117–P119)")
    print(THIN_BAR)
    print(f"  f²_ρ  = {F2_RHO:.4f}   (8π(1−πα),        P119; PDG 24.56)")
    print(f"  f²_ω  = {F2_OMEGA:.3f} (72π/(1−α_s)²,    P118; PDG 290.97)")
    print(f"  f²_φ  = {F2_PHI:.3f} (36π/MU²,         P117; PDG 179.1)")
    chk("f²_ρ",  F2_RHO,   24.557,  0.2, "P119")
    chk("f²_ω",  F2_OMEGA, 291.163, 0.2, "P118")
    chk("f²_φ",  F2_PHI,   179.693, 0.2, "P117")

    # ── 3. NWA resonance contributions (P136 Table 1) ─────────────────────────
    print(f"\n{THIN_BAR}")
    print("  3. NWA resonance contributions  Δα_had^V = 4πα·Br_had/f_V²·M_Z²/(M_Z²−M_V²)")
    print(THIN_BAR)
    da_rho_nwa   = nwa_contrib(M_RHO,   F2_RHO,   BR_RHO)
    da_omega_nwa = nwa_contrib(M_OMEGA, F2_OMEGA, BR_OMEGA)
    da_phi_nwa   = nwa_contrib(M_PHI,   F2_PHI,   BR_PHI)
    da_lm_nwa    = da_rho_nwa + da_omega_nwa + da_phi_nwa

    chk("Δα^ρ   (NWA)", da_rho_nwa,   3.735e-3, 0.5, "P136")
    chk("Δα^ω   (NWA)", da_omega_nwa, 2.810e-4, 0.5, "P136")
    chk("Δα^φ   (NWA)", da_phi_nwa,   5.073e-4, 0.5, "P136")
    chk("Δα^lm  (NWA)", da_lm_nwa,    4.522e-3, 0.2, "P136/P140 eq. 3")
    nwa_dev_pct = (da_lm_nwa - DAHAD_TARGET) / DAHAD_TARGET * 100.0
    print(f"  Deviation from Fermi target: {nwa_dev_pct:+.2f}%  (claimed +10.0%)")
    check(f"NWA overshoot ≈ +10.0% (computed {nwa_dev_pct:+.2f}%)",
          not (abs(nwa_dev_pct - 10.0) > 1.0))

    # ── 4. GS dispersive integral for ρ (P137 cross-check) ───────────────────
    print(f"\n{THIN_BAR}")
    print("  4. GS dispersive integral for ρ  (P137 cross-check)")
    print(THIN_BAR)
    print(f"  Γ_ρ      = {GAMMA_RHO*1e3:.1f} MeV  (P137)")
    print(f"  Γ_ee^TOE = {GAMMA_EE_RHO*1e6:.4f}×10⁻⁶ GeV  (P137: 7.042×10⁻⁶ GeV)")
    print(f"  p₀       = {P0_RHO*1e3:.2f} MeV  (P137: 361.6 MeV)")
    chk("Γ_ee^TOE", GAMMA_EE_RHO, 7.042e-6, 0.3, "P119/P137")
    chk("p₀      ", P0_RHO, 0.3616, 0.1, "P137")

    print(f"  Integrating GS lineshape from 2m_π = {2*M_PI*1e3:.1f} MeV to 1 GeV ...")
    da_rho_gs, int_err = integrate_gs_rho()

    if HAS_SCIPY and int_err is not None:
        print(f"  scipy.quad error estimate: {int_err:.2e}")
    else:
        print(f"  (composite Simpson fallback, n=30000)")

    chk("Δα^ρ   (GS)", da_rho_gs, 2.943e-3, 1.0, "P137 numerical (1% tol)")

    # Verify sub-total contributions roughly match P137 Table 2
    # [0.279, 0.548]: [s=(2mπ)², (0.548)²]
    # [0.548, 0.708]: [(0.548)², (0.708)²]
    # [0.708, 0.775]: [(0.708)², (0.775)²]
    # [0.775, 0.846]: [(0.775)², (0.846)²]
    # [0.846, 1.000]: [(0.846)², 1.000]
    if HAS_SCIPY:
        sub_bounds = [
            ((2*M_PI)**2,  0.548**2),
            (0.548**2,     0.708**2),
            (0.708**2,     0.775**2),
            (0.775**2,     0.846**2),
            (0.846**2,     1.000),
        ]
        sub_refs = [0.134e-3, 0.596e-3, 0.884e-3, 0.783e-3, 0.546e-3]
        sub_labels = [
            "[2mπ, 0.548]", "[0.548, 0.708]", "[0.708, 0.775]",
            "[0.775, 0.846]", "[0.846, 1.000]",
        ]
        print(f"\n  Sub-interval contributions (P137 Table 2) in units of 10⁻³:")
        sub_total = 0.0
        for (a, b), ref, lbl in zip(sub_bounds, sub_refs, sub_labels):
            val, _ = sci_int.quad(gs_integrand, a, b,
                                  limit=500, epsabs=1e-16, epsrel=1e-12)
            sub_total += val
            check(f"√s ∈ {lbl} GeV: {val*1e3:.3f} (ref {ref*1e3:.3f}) ×10⁻³",
                  abs(val - ref)/ref < 0.02)   # 2% per sub-interval
        print(f"           Sub-total: {sub_total*1e3:.3f} ×10⁻³  (ref: 2.943)")

    # ── 5. GS light-meson total (P137/P140) ──────────────────────────────────
    print(f"\n{THIN_BAR}")
    print("  5. GS light-meson total  (ω,φ use NWA;  Γ/M ≤ 0.8%)")
    print(THIN_BAR)
    # ω and φ are narrow — NWA is excellent (Γ/M ≤ 0.8%)
    da_lm_gs   = da_rho_gs + da_omega_nwa + da_phi_nwa
    gs_dev_pct = (da_lm_gs - DAHAD_TARGET) / DAHAD_TARGET * 100.0
    chk("Δα^lm  (GS)", da_lm_gs, 3.731e-3, 0.5, "P140 eq. 3")
    print(f"  Deviation from Fermi target: {gs_dev_pct:+.2f}%  (claimed −9.2%)")
    check(f"GS undershoot ≈ −9.2% (computed {gs_dev_pct:+.2f}%)",
          not (abs(gs_dev_pct + 9.2) > 1.0))

    # ── 6. Geometric mean vs arithmetic mean (P140 §1, eq. 4) ────────────────
    print(f"\n{THIN_BAR}")
    print("  6. Geometric mean prescription  (P140 §1, eq. 4)")
    print(THIN_BAR)
    nwa    = da_lm_nwa
    gs     = da_lm_gs
    gm     = math.sqrt(nwa * gs)
    am     = (nwa + gs) / 2.0
    target = DAHAD_TARGET

    gm_dev_pct  = (gm  - target) / target * 100.0
    am_dev_pct  = (am  - target) / target * 100.0
    nwa_dev_t   = (nwa - target) / target * 100.0
    gs_dev_t    = (gs  - target) / target * 100.0

    print(f"  NWA  = {nwa:.4e}  ({nwa_dev_t:+.2f}% vs target)")
    print(f"  GS   = {gs:.4e}  ({gs_dev_t:+.2f}%  vs target)")
    print(f"  AM   = {am:.4e}  ({am_dev_pct:+.3f}% vs target)")
    print(f"  GM   = {gm:.4e}  ({gm_dev_pct:+.3f}% vs target)")
    print(f"  Target = {target:.4e}  (Fermi route, P135/P136)")

    chk("Geometric mean", gm, 4.107e-3, 0.5, "P140 eq. 4, claimed 4.107×10⁻³")

    # GM must be within 0.15% of target (P140 claims 0.07%)
    check(f"GM deviation {abs(gm_dev_pct):.3f}% < 0.15% threshold  (claimed 0.07%)",
          abs(gm_dev_pct) < 0.15)

    # GM must be tighter than AM
    ratio = abs(am_dev_pct) / max(abs(gm_dev_pct), 1e-10)
    check(f"GM ({abs(gm_dev_pct):.3f}%) closer than AM ({abs(am_dev_pct):.3f}%)"
          f"  [{ratio:.1f}× improvement]",
          abs(gm_dev_pct) < abs(am_dev_pct))

    # Symmetric bracketing: NWA overshoots, GS undershoots
    check(f"NWA (+{nwa_dev_t:.2f}%) and GS ({gs_dev_t:.2f}%) bracket target symmetrically",
          nwa_dev_t > 0 and gs_dev_t < 0)

    # ── 7. Hurwitz measure on S⁷ (P140 §2.1, Prop. 1) ───────────────────────
    print(f"\n{THIN_BAR}")
    print("  7. Hurwitz measure on S⁷  (P140 §2.1, Proposition 1)")
    print(THIN_BAR)
    print("  Fibration: R₊ × S⁷,  radial Hurwitz measure: r⁷ dr")
    print("  Spectral map: s = r² M_ρ²  →  r = (s/M_ρ²)^(½)")
    print("  Substitution: r⁷ dr = (s/M_ρ²)^(7/2) · ds/(2M_ρ²)")
    print("  Marginal: d_μ_Hurwitz(s) ∝ s^(7/2) ds  [power-law, exponent = +3.5]")
    print("  Log-flat: d_μ_logflat(s) ∝ s^(-1) ds   [log-flat, exponent = -1.0]")

    exp_hurwitz = 7.0/2.0     # +3.5
    exp_logflat = -1.0

    # Structural check: Hurwitz ≠ log-flat
    check(f"Hurwitz exponent {exp_hurwitz} ≠ log-flat exponent {exp_logflat}",
          exp_hurwitz > 0 and exp_logflat < 0
          and abs(exp_hurwitz - exp_logflat) > 1.0)

    # Numerical check: weight ratio at s=2 vs s=1
    r_hurwitz = 2.0**exp_hurwitz    # = 2^(7/2) = 8√2 ≈ 11.31
    r_logflat = 2.0**exp_logflat    # = 1/2 = 0.5
    check(f"Weight ratio s=2 vs s=1:  Hurwitz {r_hurwitz:.3f} (grows), log-flat {r_logflat:.3f} (falls)",
          abs(r_hurwitz - 8*math.sqrt(2)) < 1e-10 and abs(r_logflat - 0.5) < 1e-12)
    print(f"  Consequence: Cauchy-Schwarz saturation in log-s space does NOT follow")
    print(f"               from the Hurwitz measure alone  (P140 Prop. 1)")

    # Verify the log-symmetry blocking sub-problem statement
    # The blocking problem is to show <e^{-u}>_GS = <e^u>_GS to order (Γ/M)²
    gamma_over_M = GAMMA_RHO / M_RHO
    order_sq     = gamma_over_M**2
    print(f"\n  Log-symmetry accuracy order: (Γ_ρ/M_ρ)² = ({gamma_over_M:.3f})² = {order_sq:.4f} ≈ {order_sq*100:.1f}%")
    print(f"  The 0.07% GM precision is {order_sq/0.0007:.0f}× better than this leading order — ")
    print(f"  the blocking sub-problem (P140 §2.3) asks why the residual is so small.")

    # ── 8. PDG factor and quark continuum decoupling (P140 §3) ───────────────
    print(f"\n{THIN_BAR}")
    print("  8. PDG factor and quark continuum decoupling  (P140 §3)")
    print(THIN_BAR)
    factor = DAHAD_PDG / DAHAD_TARGET
    print(f"  Δα_had^PDG    = {DAHAD_PDG:.5f}  (SM full dispersive)")
    print(f"  Δα_had^target = {DAHAD_TARGET:.5f}  (TOE Fermi route, P135/P136)")
    print(f"  Ratio         = {factor:.3f}  (P140: ~6.7)")
    chk("PDG/TOE factor", factor, 6.69, 1.5, "P140 §3.1")

    # SM decomposition (P140 §3.1 approximate breakdown)
    da_light  = 0.00411    # light vector resonances (≈ TOE Fermi target)
    da_piFF   = 0.00590    # pion form factor below M_ρ
    da_jpsi   = 0.00580    # J/ψ + Υ
    da_pqcd   = 0.01169    # pQCD continuum above charm threshold
    da_check  = da_light + da_piFF + da_jpsi + da_pqcd
    print(f"\n  SM Δα_had decomposition (P140 §3.1, approximate):")
    print(f"    light vector resonances:  {da_light:.5f}")
    print(f"    pion FF below M_ρ:        {da_piFF:.5f}   ← absent from TOE J₃(𝕆) poles")
    print(f"    J/ψ + Υ (quarkonia):      {da_jpsi:.5f}   ← TOE eigenvalues, VMD coupling open")
    print(f"    pQCD continuum:           {da_pqcd:.5f}   ← G₂ sector, not EW Peirce block")
    print(f"    {'─'*42}")
    print(f"    Sum ≈                     {da_check:.5f}  (PDG: {DAHAD_PDG:.5f})")
    check(f"SM sum {da_check:.5f} consistent with PDG {DAHAD_PDG:.5f}  (diff < 0.003)",
          abs(da_check - DAHAD_PDG) < 3e-3)

    print(f"\n  Three pillars of quark continuum decoupling (P140 Theorem 1):")
    print(f"  Pillar I   — J₃(𝕆) spectral filter:")
    print(f"               Π_had^TOE(q²) sums only over discrete vector-meson J₃(𝕆)")
    print(f"               eigenvalues. QCD Fock-space states (π⁺π⁻, multi-pion, etc.)")
    print(f"               have no pole in S^{{J₃(𝕆)}}_had → absent from TOE self-energy.")
    print(f"  Pillar II  — EW matching at M_W:")
    print(f"               TOE Fermi constraint uses algebraic Δα_had (J₃(𝕆)-classified).")
    print(f"               Full QCD hadronic running not part of the algebraic self-energy.")
    print(f"  Pillar III — Appelquist-Carazzone:")
    print(f"               pQCD continuum above charm threshold decouples at the")
    print(f"               G₂-invariant matching scale. Absorbed into running α_s;")
    print(f"               does not appear as additive hadronic running in the EW Peirce block.")

    # ── 9. Final summary ──────────────────────────────────────────────────────
    print(f"\n{BAR}")
    print("  P140 — Summary of key numerical claims")
    print(BAR)
    rows = [
        ("NWA  Δα_had^lm",  da_lm_nwa,  "4.522×10⁻³", "P136"),
        ("GS   Δα_had^lm",  da_lm_gs,   "3.731×10⁻³", "P137"),
        ("Geometric mean",  gm,          "4.107×10⁻³", "P140 eq. 4"),
        ("Arithmetic mean", am,          "---",         "reference"),
        ("PDG/TOE factor",  factor,      "~6.7",        "P140 §3.1"),
    ]
    for label, val, claimed, source in rows:
        print(f"  {label:<22} = {val:>12.4e}   claimed: {claimed:<14}  [{source}]")
    print(f"  {'GM dev from tgt':<22} = {abs(gm_dev_pct):>11.3f}%   claimed: {'≤ 0.07%':<14}  [P140 §1]")
    print(f"  {'AM dev from tgt':<22} = {abs(am_dev_pct):>11.3f}%   claimed: {'> GM dev':<14}  [reference]")
    print(f"\n  Hurwitz exponent    = +{exp_hurwitz}   (power-law; log-flat requires −1.0)")
    print(f"  (Γ_ρ/M_ρ)²         =  {order_sq:.4f}  ≈ {order_sq*100:.1f}%   (leading order for log-sym.)")

    print(f"\n{'='*60}\nRESULT: {PF['pass']} PASS / {PF['fail']} FAIL")
    return 0 if PF["fail"] == 0 else 1


if __name__ == "__main__":
    sys.exit(main())
