"""
verify_P196.py — Numerical companion to Addendum P196.

Topic: SR3's remaining open step — uniqueness of the exponent p in ζ = α^p.

Verifies:
  1. TOE constants and moment computation.
  2. Mass formula m_ratio(p; ℓ₀, ℓ₁) = exp(μ₁/μ₀ · ΔE(p; ℓ₀, ℓ₁)).
  3. Numerical scan of m_ratio over p ∈ {0.5, 1, 5/4, 3/2, 2, 5/2, 3, 4, 5}
     for representative pairs (0,1), (1,2), (2,3).
  4. Monotonicity of m_ratio(p) in p (for each fixed pair with Δℓ > 0).
  5. Structural gap: for all p ≥ 0 and all pairs with ℓ₀ ≤ 3, ℓ₁ ≤ 4,
     m_ratio(p) ≠ 206.77 (the target m_μ/m_e).
  6. Proof that the equation m_ratio(p) = 206.77 has solution only for p < 0
     (unphysical) for the nearest pairs.
  7. Killing norm |H_{U(1)}|² = 24 consistency check.
  8. Range bounds for pairs (1,2) and (2,3) confirming the gap
     contains 206.77 for all p ≥ 0.

mp.dps = 55 precision. All checks emit PASS/FAIL; script exits 0 iff all pass.

L. F. Vlegels, Independent Researcher
Copyright: Léon Fernando Vlegels. License: MIT. May 2026.
"""

import sys

from mpmath import mp, mpf, pi, exp, log, sqrt, fabs, inf

mp.dps = 55

# ──────────────────────────────────────────────────────────────────────────────
# TOE constants
# ──────────────────────────────────────────────────────────────────────────────

ALPHA_INV = 4*pi**3 + pi**2 + pi          # = μ₀ (P03 identity)
ALPHA     = 1 / ALPHA_INV                  # fine-structure constant
BETA      = 3*pi / 20                      # moment coupling
GAMMA     = mpf('3') / 4                   # layer-cycle coefficient

TARGET_RATIO = mpf('206.77')               # experimental m_μ/m_e (rounded)
# Use more precise value for computations
TARGET_RATIO_PRECISE = mpf('206.7682830')  # CODATA 2018

# ──────────────────────────────────────────────────────────────────────────────
# Geometric moments  μₙ = ∫₀¹ xⁿ ρ(x) dx = 16π³/(n+4) + 3π²/(n+3) + 2π/(n+2)
# ──────────────────────────────────────────────────────────────────────────────

def mu(n):
    n = mpf(n)
    return 16*pi**3/(n+4) + 3*pi**2/(n+3) + 2*pi/(n+2)

MU0 = mu(0)   # = ALPHA_INV ≈ 137.036
MU1 = mu(1)   # ≈ 108.717
MU2 = mu(2)   # ≈ 90.176
MU3 = mu(3)   # ≈ 77.063
MU4 = mu(4)   # ≈ 67.08

RATIO_MU1_MU0 = MU1 / MU0  # ≈ 0.7933  (mass formula exponent scale)

# ──────────────────────────────────────────────────────────────────────────────
# Mass formula as a function of p
# ──────────────────────────────────────────────────────────────────────────────

def s3_eigenvalue(ell):
    """S³ Laplacian eigenvalue: ℓ(ℓ+2)."""
    ell = mpf(ell)
    return ell*(ell + 2)

def delta_E(p, ell0, ell1):
    """
    Within-family energy gap between levels ℓ₀ and ℓ₁.

    ΔE(p; ℓ₀, ℓ₁) = [ℓ₁(ℓ₁+2) − ℓ₀(ℓ₀+2)]
                    + α^p × (ℓ₁ − ℓ₀)
                    + β × (μ_{ℓ₁} − μ_{ℓ₀}) / μ₀

    Notes:
      - γ cancels completely in within-family ratios (P191 §2.3, eq. 2.3).
      - The ζ term contributes α^p × Δℓ.
      - The β term contributes the moment-hierarchy correction.
    """
    p    = mpf(p)
    dS3  = s3_eigenvalue(ell1) - s3_eigenvalue(ell0)
    zeta = ALPHA**p
    dmu  = (mu(ell1) - mu(ell0)) / MU0
    return dS3 + zeta*(ell1 - ell0) + BETA*dmu

def m_ratio(p, ell0, ell1):
    """
    Mass ratio m(ℓ₁)/m(ℓ₀) = exp(μ₁/μ₀ · ΔE(p; ℓ₀, ℓ₁)).
    """
    return exp(RATIO_MU1_MU0 * delta_E(p, ell0, ell1))

def p_star(ell0, ell1):
    """
    Solve m_ratio(p; ℓ₀, ℓ₁) = TARGET_RATIO for p.

    From ΔE(p) = ln(TARGET) / (μ₁/μ₀) = ΔE_target:
      α^p × Δℓ = ΔE_target − ΔE_base
    where ΔE_base = dS3 + β·Δμ/μ₀.

    So: p = log(rhs) / log(α)  (note log(α) < 0).
    Returns p (may be negative = unphysical).
    """
    target_dE = log(TARGET_RATIO_PRECISE) / RATIO_MU1_MU0
    dS3  = s3_eigenvalue(ell1) - s3_eigenvalue(ell0)
    dmu  = (mu(ell1) - mu(ell0)) / MU0
    dE_base = dS3 + BETA*dmu
    delta_l = mpf(ell1 - ell0)
    if delta_l == 0:
        return None
    zeta_needed = (target_dE - dE_base) / delta_l
    if zeta_needed <= 0:
        return None   # impossible for real p
    return log(zeta_needed) / log(ALPHA)

# ──────────────────────────────────────────────────────────────────────────────
# Checks
# ──────────────────────────────────────────────────────────────────────────────

PASS = FAIL = 0

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

print("verify_P196.py  —  SR3 ζ-exponent uniqueness, mp.dps =", mp.dps)

# ── Check 1: TOE constants ────────────────────────────────────────────────────
print("\nS1  TOE constants")
check("1a  α⁻¹ = μ₀ = 4π³+π²+π",
      fabs(ALPHA_INV - mpf('137.036')) < mpf('0.001'))
check("1b  α = 1/μ₀ ≈ 7.297e-3",
      fabs(ALPHA - mpf('7.2974e-3')) < mpf('1e-6'))
check("1c  β = 3π/20 ≈ 0.47124",
      fabs(BETA - mpf('0.47124')) < mpf('1e-5'))

# ── Check 2: Moments ──────────────────────────────────────────────────────────
print("\nS2  Moments μₙ")
check("2a  μ₀ = α⁻¹ (P03 identity)",
      fabs(MU0 - ALPHA_INV) < mpf('1e-50'))
check("2b  μ₁ ≈ 108.717",
      fabs(MU1 - mpf('108.717')) < mpf('0.001'))
check("2c  μ₂ ≈ 90.176",
      fabs(MU2 - mpf('90.176')) < mpf('0.001'))
check("2d  μ₁/μ₀ ≈ 0.7933",
      fabs(RATIO_MU1_MU0 - mpf('0.7933')) < mpf('1e-4'))
check("2e  μ₀ > μ₁ > μ₂ > μ₃ > μ₄ (moments strictly decreasing)",
      MU0 > MU1 > MU2 > MU3 > MU4)

# ── Check 3: Canonical ζ = α^{5/4} ───────────────────────────────────────────
print("\nS3  Canonical ζ = α^{5/4}")
ZETA_CAN = ALPHA**(mpf('5')/4)
check("3a  ζ_can = α^{5/4} ≈ 2.133e-3",
      fabs(ZETA_CAN - mpf('2.133e-3')) < mpf('1e-5'))
check("3b  exponent 5/4 = 1 + 1/dim(B⁴) = 1 + 1/4",
      fabs(mpf('5')/4 - (1 + mpf(1)/4)) < mpf('1e-15'))
check("3c  5/4 = 1 + dim(S¹)/dim(B⁴)",
      fabs(mpf('5')/4 - (1 + mpf('1')/4)) < mpf('1e-15'))

# ── Check 4: m_ratio at canonical p=5/4, key pairs ───────────────────────────
print("\nS4  m_ratio at canonical p = 5/4")
p_can = mpf('5') / 4
r01 = m_ratio(p_can, 0, 1)
r12 = m_ratio(p_can, 1, 2)
r23 = m_ratio(p_can, 2, 3)
print(f"       pair (0,1): m_ratio = {float(r01):.4f}")
print(f"       pair (1,2): m_ratio = {float(r12):.4f}")
print(f"       pair (2,3): m_ratio = {float(r23):.4f}")
check("4a  pair (0,1) at p=5/4 gives ratio ≈ 10 (well below 206.77)",
      r01 < 20)
check("4b  pair (1,2) at p=5/4 gives ratio ≈ 50 (below 206.77)",
      r12 < 100)
check("4c  pair (2,3) at p=5/4 gives ratio ≈ 249 (above 206.77)",
      r23 > 207 and r23 < 300)
check("4d  canonical pair (1,2) matches P191 Thm 5.1(b) finding ≈50",
      fabs(r12 - 50) < 5)
check("4e  canonical pair (2,3) matches P191 Thm 5.1(d) finding ≈249",
      fabs(r23 - 249) < 5)

# ── Check 5: m_ratio(p) is monotone decreasing in p (for Δℓ > 0) ─────────────
print("\nS5  Monotonicity: m_ratio(p) decreasing in p for fixed pair")
p_vals = [mpf(v) for v in ['0.5', '1', '5/4', '3/2', '2', '3', '5']]
# Check for pair (1,2)
ratios_12 = [m_ratio(p, 1, 2) for p in p_vals]
mono_12 = all(ratios_12[i] > ratios_12[i+1] for i in range(len(ratios_12)-1))
check("5a  m_ratio(p; 1,2) strictly decreasing in p", mono_12)
# Check for pair (2,3)
ratios_23 = [m_ratio(p, 2, 3) for p in p_vals]
mono_23 = all(ratios_23[i] > ratios_23[i+1] for i in range(len(ratios_23)-1))
check("5b  m_ratio(p; 2,3) strictly decreasing in p", mono_23)
# Check for pair (0,1)
ratios_01 = [m_ratio(p, 0, 1) for p in p_vals]
mono_01 = all(ratios_01[i] > ratios_01[i+1] for i in range(len(ratios_01)-1))
check("5c  m_ratio(p; 0,1) strictly decreasing in p", mono_01)

# ── Check 6: Range bounds for pairs (1,2) and (2,3) ──────────────────────────
print("\nS6  Range bounds confirming structural gap at 206.77")
# Pair (1,2): range for p>0 is (ratio_inf_12, ratio_p0_12)
# As p→∞: ζ→0, ΔE_base(1,2) = 5 + β(μ₂−μ₁)/μ₀
dE_base_12 = 5 + BETA*(MU2-MU1)/MU0
ratio_inf_12 = exp(RATIO_MU1_MU0 * dE_base_12)
# As p→0+: ζ→1, ΔE = dE_base + 1
ratio_sup_12 = exp(RATIO_MU1_MU0 * (dE_base_12 + 1))
print(f"       pair (1,2): p→∞ limit = {float(ratio_inf_12):.3f},"
      f" p→0+ limit = {float(ratio_sup_12):.3f}")
check("6a  pair (1,2) infimum (p→∞) < 206.77",
      ratio_inf_12 < TARGET_RATIO_PRECISE)
check("6b  pair (1,2) supremum (p→0+) < 206.77",
      ratio_sup_12 < TARGET_RATIO_PRECISE,
      f"sup={float(ratio_sup_12):.3f}")

# Pair (2,3): range for p>0
dE_base_23 = 7 + BETA*(MU3-MU2)/MU0
ratio_inf_23 = exp(RATIO_MU1_MU0 * dE_base_23)
ratio_sup_23 = exp(RATIO_MU1_MU0 * (dE_base_23 + 1))
print(f"       pair (2,3): p→∞ limit = {float(ratio_inf_23):.3f},"
      f" p→0+ limit = {float(ratio_sup_23):.3f}")
check("6c  pair (2,3) infimum (p→∞) > 206.77",
      ratio_inf_23 > TARGET_RATIO_PRECISE)
check("6d  pair (2,3) infimum > 206.77 even as ζ→0",
      ratio_inf_23 > TARGET_RATIO_PRECISE)

# Pair (0,2): infimum
dE_base_02 = 8 + BETA*(MU2-MU0)/MU0
ratio_inf_02 = exp(RATIO_MU1_MU0 * dE_base_02)
print(f"       pair (0,2): p→∞ limit = {float(ratio_inf_02):.3f} (way above)")
check("6e  pair (0,2) infimum >> 206.77",
      ratio_inf_02 > 400)

# Pair (0,1): supremum
dE_base_01 = 3 + BETA*(MU1-MU0)/MU0
ratio_sup_01 = exp(RATIO_MU1_MU0 * (dE_base_01 + 1))
print(f"       pair (0,1): p→0+ limit = {float(ratio_sup_01):.3f} (way below)")
check("6f  pair (0,1) supremum << 206.77",
      ratio_sup_01 < 50)

# ── Check 7: p* for each canonical pair ───────────────────────────────────────
print("\nS7  p* values (where m_ratio = 206.77) — all should be negative")
for pair in [(0,1), (1,2), (2,3)]:
    ps = p_star(*pair)
    if ps is None:
        print(f"       pair {pair}: p* = None (ΔE_base already exceeds target)")
        check(f"7  pair {pair}: no positive p* (ΔE_base > target)", True)
    else:
        print(f"       pair {pair}: p* = {float(ps):.4f}")
        check(f"7  pair {pair}: p* < 0 (unphysical)",
              ps < 0)

# Extra: pair (1,3)
for pair in [(1,3), (0,2)]:
    ps = p_star(*pair)
    if ps is None:
        print(f"       pair {pair}: p* = None (ΔE_base already exceeds target)")
        check(f"7  pair {pair}: no positive p* (ΔE_base > target)", True)
    else:
        print(f"       pair {pair}: p* = {float(ps):.4f}")
        check(f"7  pair {pair}: p* < 0 (unphysical)",
              ps < 0)

# ── Check 8: Full scan — exhaustive pairs ℓ₀ ≤ 3, ℓ₁ ≤ 4 ─────────────────────
print("\nS8  Exhaustive scan: all pairs (ℓ₀,ℓ₁) with 0 ≤ ℓ₀ < ℓ₁ ≤ 4, all p ∈ [0,10]")
all_excluded = True
problem_pairs = []
test_p_vals   = [mpf(v)/4 for v in range(0, 41)]  # p = 0, 0.25, 0.5, ..., 10
for l0 in range(5):
    for l1 in range(l0+1, 5):
        for pv in test_p_vals:
            r = m_ratio(pv, l0, l1)
            if fabs(r - TARGET_RATIO_PRECISE) < mpf('1.0'):
                problem_pairs.append((l0, l1, float(pv), float(r)))
                all_excluded = False
check("8a  No canonical pair (ℓ₀<ℓ₁≤4) achieves m_ratio≈206.77 for any p∈[0,10]",
      all_excluded,
      f"problem pairs: {problem_pairs}")

# ── Check 9: Killing norm |H_{U(1)}|² = 24 (from P182) ──────────────────────
print("\nS9  Killing norm check")
KILLING_NORM_SQ = mpf('24')   # |H_{U(1)}|² = 24 = 2|Φ_{G₂}| (P182)
# |ζ·H_{U(1)}|² = ζ² × 24 = α^{5/2} × 24
killing_norm_sq_op = ZETA_CAN**2 * KILLING_NORM_SQ
check("9a  |H_{U(1)}|² = 24 (P182: 24 = 2×|Φ_{G₂}|)",
      fabs(KILLING_NORM_SQ - 24) < mpf('1e-15'))
check("9b  |ζ·H_{U(1)}|² = α^{5/2} × 24",
      fabs(killing_norm_sq_op - ALPHA**(mpf('5')/2) * 24) < mpf('1e-40'))
print(f"       |ζ·H_{{U(1)}}|² = {float(killing_norm_sq_op):.6e}")

# ── Check 10: Dimensional formula p = 1 + dim(S¹)/dim(B⁴) ──────────────────
print("\nS10  Dimensional formula for p")
dim_B4 = mpf('4')
dim_S1 = mpf('1')
p_dim  = 1 + dim_S1/dim_B4
check("10a  p_dim = 1 + dim(S¹)/dim(B⁴) = 5/4",
      fabs(p_dim - mpf('5')/4) < mpf('1e-15'))
check("10b  p_dim = 1 + 1/dim(B⁴) (equivalent form)",
      fabs(p_dim - (1 + 1/dim_B4)) < mpf('1e-15'))
# Also check P18's form: 5/4 = 1 + 3/(4×3)
p_p18 = 1 + mpf('3')/(4*3)
check("10c  P18 form: 5/4 = 1 + 3/(4×3)",
      fabs(p_p18 - mpf('5')/4) < mpf('1e-15'))

# ── Check 11: p=5/4 uniqueness via E₆/F₄ — gap characterization ─────────────
print("\nS11  E₆/F₄ uniqueness gap characterization")
# The gap: what additional constraint would close uniqueness
# The Killing norm |ζ·H_{U(1)}|² = ζ²·24 = α^(5/2)·24
# This is satisfied by ζ = α^{5/4}, but also by ζ = c·α^{5/4} for any c>0
# The dimensional argument selects c=1 (no extra factor)
# Verify that the normalization c=1 is what the formula gives
c_factor = ZETA_CAN / ALPHA**(mpf('5')/4)
check("11a  ζ_can / α^{5/4} = 1 (normalization c=1, no extra factor)",
      fabs(c_factor - 1) < mpf('1e-50'))
# Verify that p=5/4 is the unique solution of the dimensional formula
check("11b  p=5/4 is the unique solution of 1 + dim(S¹)/dim(B⁴)",
      fabs(p_dim - mpf('5')/4) < mpf('1e-15'))

# ── Check 12: Scan table printed for paper verification ──────────────────────
print("\nS12  Full scan table: p vs m_ratio for pairs (0,1), (1,2), (2,3)")
print(f"\n  {'p':>6}  {'ζ=α^p':>12}  {'ratio(0,1)':>12}  {'ratio(1,2)':>12}  {'ratio(2,3)':>12}")
scan_p_list = [mpf(v) for v in ['1', '5/4', '3/2', '2', '5/2', '3', '4', '5']]
for pv in scan_p_list:
    zv  = ALPHA**pv
    r01 = m_ratio(pv, 0, 1)
    r12 = m_ratio(pv, 1, 2)
    r23 = m_ratio(pv, 2, 3)
    print(f"  {float(pv):>6.3f}  {float(zv):>12.4e}  {float(r01):>12.4f}  "
          f"{float(r12):>12.4f}  {float(r23):>12.4f}")

# Check that all entries respect the structural gap
all_correct = True
for pv in scan_p_list:
    r01 = m_ratio(pv, 0, 1)
    r12 = m_ratio(pv, 1, 2)
    r23 = m_ratio(pv, 2, 3)
    if not (r01 < TARGET_RATIO_PRECISE and r12 < TARGET_RATIO_PRECISE
            and r23 > TARGET_RATIO_PRECISE):
        all_correct = False
check("12a  All scan entries: pairs (0,1),(1,2) < 206.77 < pair (2,3)",
      all_correct)

# ── Summary ───────────────────────────────────────────────────────────────────
print(f"\n{'='*60}\nRESULT: {PASS} PASS / {FAIL} FAIL")
sys.exit(0 if FAIL == 0 else 1)
