#!/usr/bin/env python3
"""
ym_massgap_status.py
====================================================================
Honest, theorem-grade reproduction of the DFD strong-sector ledger:
  - the alpha-tower confinement scale  Lambda_DFD = M_P * alpha^(19/2)
  - the MSbar 5-flavour partner         Lambda_MSbar5 = sqrt(4*pi) * Lambda_DFD
  - alpha_s(M_Z) by two-loop dimensional transmutation (consistency check)
  - the executed quenched SU(3) lattice comparison (r0 = 0.5 fm external input)
  - the conditional spectral lower bounds (geometric / Planckian floors)

This script REPRODUCES NUMBERS, it does not prove the Clay Yang-Mills mass gap.
The Clay statement is explicitly NOT claimed: it is INHERITED + lattice-validated.

Outputs:
  - console ledger (derived / validated / inherited)
  - figure: fig_ym_massgap_status.png  (ledger panel + Lambda_QCD vs lattice panel)
====================================================================
"""

import numpy as np
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from matplotlib.patches import Patch

# --------------------------------------------------------------------
# 0. Locked DFD ledger constants (topological / microsector; NOT fitted)
# --------------------------------------------------------------------
ALPHA_INV   = 137.036                     # alpha^-1, microsector-derived (sub-ppm)
ALPHA       = 1.0 / ALPHA_INV
M_P_GeV     = 1.220890e19                  # reduced Planck mass [GeV]
M_P_MeV     = M_P_GeV * 1.0e3
N_GEN       = 3                            # generations (topological)
K_MAX       = 60                           # microsector mode cap (topological)
HBARC_MeV_fm = 197.3269804                 # hbar*c [MeV*fm]
R0_fm       = 0.5                          # Sommer scale [fm] -- EXTERNAL INPUT

# The confinement exponent.  19/2 = 57/6 = (k_max - N_gen)/(2 N_gen).
# Rigidity-selected, contingent on the cube-law lemma -- NOT independently proved.
EXP_CONF    = (K_MAX - N_GEN) / (2 * N_GEN)   # = 9.5 exactly

# --------------------------------------------------------------------
# 1. DERIVED: the alpha-tower confinement scale
# --------------------------------------------------------------------
Lambda_DFD_MeV    = M_P_MeV * ALPHA**EXP_CONF              # ~ 61.20 MeV
Lambda_MSbar5_MeV = np.sqrt(4 * np.pi) * Lambda_DFD_MeV    # ~ 216.95 MeV

# DFD ledger TARGETS (scaling derived; absolute normalisation an OPEN item)
sqrt_sigma_DFD_MeV  = 440.0
sqrt_sigma_DFD_err  = 25.0
m_glueball_DFD_GeV  = 1.69
Lambda_QCD3_DFD_MeV = 332.0   # genuine 3-flavour value (tau-checked)

# --------------------------------------------------------------------
# 2. alpha_s(M_Z) by two-loop dimensional transmutation (consistency check)
#    Run alpha_s up from Lambda_MSbar5 to M_Z with the 5-flavour beta function.
# --------------------------------------------------------------------
def alpha_s_two_loop(mu_MeV, Lambda_MeV, nf=5):
    """Standard two-loop MSbar running from Lambda to scale mu."""
    b0 = 11.0 - 2.0/3.0 * nf
    b1 = 102.0 - 38.0/3.0 * nf
    t  = np.log((mu_MeV / Lambda_MeV)**2)
    # leading + NLL correction; alpha_s = 4*pi/(b0 t) [1 - (b1/b0^2) ln t / t]
    a_LO = 4.0 * np.pi / (b0 * t)
    a_NLO = a_LO * (1.0 - (b1 / b0**2) * np.log(t) / t)
    return a_LO, a_NLO

M_Z_MeV = 91187.6
asMZ_LO, asMZ_NLO = alpha_s_two_loop(M_Z_MeV, Lambda_MSbar5_MeV, nf=5)
asMZ_DFD_quoted = 0.1187           # corpus dimensional-transmutation value
asMZ_PDG, asMZ_PDG_err = 0.1180, 0.0009
asMZ_pull = (asMZ_DFD_quoted - asMZ_PDG) / asMZ_PDG_err

# --------------------------------------------------------------------
# 3. VALIDATED: executed quenched SU(3) lattice (external r0 = 0.5 fm)
# --------------------------------------------------------------------
# Dimensionless lattice OUTPUT (DFD-independent):
r0_sqrt_sigma_20  = 1.178        # 20^4, beta=6.2 (largest box)
# convert to MeV using the EXTERNAL ruler r0 = 0.5 fm:
sqrt_sigma_lat_MeV = r0_sqrt_sigma_20 / R0_fm * HBARC_MeV_fm
sqrt_sigma_lat_best = 470.0      # best quenched estimate across beta=5.8,6.0,6.2
sqrt_sigma_lat_err  = 10.0
m_glueball_lat_GeV  = 1.71
m_glueball_lat_err  = 0.17

# agreement of DFD target vs lattice (combined sigma)
diff = sqrt_sigma_lat_best - sqrt_sigma_DFD_MeV
comb_err = np.hypot(sqrt_sigma_DFD_err, sqrt_sigma_lat_err)
sigma_agreement = diff / comb_err
pct_agreement = 100.0 * diff / sqrt_sigma_DFD_MeV

# --------------------------------------------------------------------
# 4. The string-tension normalisation defect (honest, reproduced)
# --------------------------------------------------------------------
# printed chain: (Lambda_QCD3 / 2pi) * sqrt(k_max/N_gen) * sqrt(4pi)
norm_chain_MeV = (Lambda_QCD3_DFD_MeV / (2*np.pi)) * np.sqrt(K_MAX/N_GEN) * np.sqrt(4*np.pi)
required_bridge = sqrt_sigma_DFD_MeV / ((Lambda_QCD3_DFD_MeV/(2*np.pi))*np.sqrt(K_MAX/N_GEN)*np.sqrt(4*np.pi)) * (norm_chain_MeV/sqrt_sigma_DFD_MeV)
# (the printed chain evaluates to ~838 MeV; the ledger target is 440 MeV)

# --------------------------------------------------------------------
# 5. CONDITIONAL spectral lower bounds (genuine partial advance; NOT Clay)
#    These are curvature/UV floors, 30-40 orders from the hadronic scale.
# --------------------------------------------------------------------
# (a) finite Toeplitz / KK gap ~ sqrt(alpha) * M_P
toeplitz_gap_GeV = np.sqrt(ALPHA) * M_P_GeV
# (b) galactic deep-field geometric IR floor ~ 1e-30 eV (App AR specialization)
deepfield_floor_eV = 1.0e-30

# --------------------------------------------------------------------
# 6. Console report
# --------------------------------------------------------------------
line = "=" * 70
print(line)
print("DFD STRONG-SECTOR LEDGER  (honest: derived / validated / inherited)")
print(line)
print("\n[DERIVED]  parameter-free, from the alpha-tower (alpha fixed first):")
print(f"  alpha^-1                 = {ALPHA_INV:.3f}   (microsector, sub-ppm)")
print(f"  exponent 19/2 = 57/6     = {EXP_CONF:.4f}   (rigidity-selected, 1 open lemma)")
print(f"  Lambda_DFD = M_P alpha^(19/2)        = {Lambda_DFD_MeV:8.2f} MeV   (corpus 61.20)")
print(f"  Lambda_MSbar^(5) = sqrt(4pi) Lambda  = {Lambda_MSbar5_MeV:8.2f} MeV   (corpus 216.95)")
print(f"  Lambda_QCD,3 (tau-checked)           = {Lambda_QCD3_DFD_MeV:8.2f} MeV")
print(f"  alpha_s(M_Z) [corpus dim.transmut.]  = {asMZ_DFD_quoted:.4f}")
print(f"  alpha_s(M_Z) [my 2-loop check]       = {asMZ_NLO:.4f}  (LO {asMZ_LO:.4f})")
print(f"     PDG world avg = {asMZ_PDG} +/- {asMZ_PDG_err}  -> DFD pull = {asMZ_pull:+.2f} sigma")

print("\n[TARGET]  scaling derived, ABSOLUTE NORMALISATION OPEN (honest defect):")
print(f"  sqrt(sigma)_DFD target   = {sqrt_sigma_DFD_MeV:.0f} +/- {sqrt_sigma_DFD_err:.0f} MeV")
print(f"  m_0++ target             = {m_glueball_DFD_GeV:.2f} GeV")
print(f"  printed norm chain       = {norm_chain_MeV:8.1f} MeV  != 440  (does NOT close)")
print(f"     -> required bridge factor ~ {sqrt_sigma_DFD_MeV/((Lambda_QCD3_DFD_MeV/(2*np.pi))*np.sqrt(K_MAX/N_GEN)):.3f} unaccounted")

print("\n[VALIDATED]  executed quenched SU(3) lattice (EXTERNAL input r0=0.5 fm):")
print(f"  r0*sqrt(sigma) (20^4)    = {r0_sqrt_sigma_20:.3f}   (dimensionless, DFD-independent)")
print(f"  -> sqrt(sigma)           = {sqrt_sigma_lat_MeV:7.1f} MeV  (at r0=0.5 fm)")
print(f"  best quenched estimate   = {sqrt_sigma_lat_best:.0f} +/- {sqrt_sigma_lat_err:.0f} MeV")
print(f"  0++ glueball (lattice)   = {m_glueball_lat_GeV:.2f} +/- {m_glueball_lat_err:.2f} GeV  (target {m_glueball_DFD_GeV})")
print(f"  AGREEMENT DFD vs lattice : {pct_agreement:+.1f}%  ({sigma_agreement:+.2f} sigma combined)")

print("\n[SPECTRAL]  conditional positive lower bounds (genuine; NOT the QCD/Clay gap):")
print(f"  Toeplitz/KK gap ~ sqrt(alpha)*M_P    = {toeplitz_gap_GeV:.3e} GeV  (Planckian)")
print(f"  galactic deep-field IR floor         ~ {deepfield_floor_eV:.0e} eV   (App AR)")
print(f"  -> {abs(np.log10(toeplitz_gap_GeV*1e9) - np.log10(sqrt_sigma_DFD_MeV*1e6)):.0f}+ orders above hadronic; curvature/UV floor, not confinement")

print("\n[INHERITED / NOT CLAIMED]")
print("  Nonperturbative confinement = generator-closed lattice sector")
print("  Clay pure-YM mass gap on flat R^4 = NOT PROVEN, NOT CLAIMED")
print(line)

# --------------------------------------------------------------------
# 7. Figure
# --------------------------------------------------------------------
fig = plt.figure(figsize=(14, 6.2))
gs = fig.add_gridspec(1, 2, width_ratios=[1.25, 1.0], wspace=0.28)

# ---- Panel A: derived/validated/inherited ledger ----
axL = fig.add_subplot(gs[0, 0])
axL.axis("off")
axL.set_title("DFD strong-sector ledger: derived / validated / inherited",
              fontsize=12, fontweight="bold", loc="left")

rows = [
    ("alpha^-1 = 137.036",                       "DERIVED",   "-0.006 ppm; topological integers"),
    ("Lambda_DFD = M_P alpha^(19/2)",            "DERIVED*",  f"{Lambda_DFD_MeV:.2f} MeV  (*1 open lemma: 19/2)"),
    ("Lambda_MSbar5 = sqrt(4pi) Lambda_DFD",     "DERIVED",   f"{Lambda_MSbar5_MeV:.2f} MeV"),
    ("alpha_s(M_Z)",                             "DERIVED",   f"{asMZ_DFD_quoted:.4f}  ({asMZ_pull:+.1f}o vs PDG)"),
    ("Lambda_QCD,3  (tau-checked)",              "DERIVED",   f"{Lambda_QCD3_DFD_MeV:.0f} MeV"),
    ("theta-bar = 0  (no axion)",                "DERIVED",   "strong-CP, structural"),
    ("sqrt(sigma) = 440+/-25 MeV",               "TARGET",    "scaling derived; norm. OPEN"),
    ("m_0++ = 1.69 GeV",                         "TARGET",    "scaling derived; norm. OPEN"),
    ("IR floor  lambda_1 >= Lambda_DFD",         "COND.PROVED","~1e-30 eV; NOT the QCD gap"),
    ("r0*sqrt(sigma)=1.178 -> 465 MeV",          "VALIDATED", "external r0=0.5 fm; ~1o"),
    ("0++ glueball 1.71 GeV",                    "VALIDATED", "overlaps 1.69 target"),
    ("Nonperturbative confinement",              "INHERITED", "generator-closed lattice"),
    ("CLAY pure-YM mass gap",                    "NOT CLAIMED","inherited + lattice-validated"),
]
colors = {
    "DERIVED":    "#1b7837", "DERIVED*": "#1b7837",
    "TARGET":     "#b8860b", "COND.PROVED": "#2166ac",
    "VALIDATED":  "#4393c3", "INHERITED": "#888888",
    "NOT CLAIMED":"#b2182b",
}
y = 0.95
dy = 0.95 / (len(rows) + 0.5)
for name, status, basis in rows:
    c = colors[status]
    axL.text(0.005, y, name, fontsize=9.2, va="center", family="monospace")
    axL.text(0.52, y, status, fontsize=8.8, va="center", fontweight="bold",
             color="white",
             bbox=dict(boxstyle="round,pad=0.18", fc=c, ec="none"))
    axL.text(0.70, y, basis, fontsize=8.2, va="center", color="#333333")
    y -= dy
axL.set_xlim(0, 1)
axL.set_ylim(0, 1)

legend_handles = [
    Patch(fc="#1b7837", label="DERIVED (parameter-free)"),
    Patch(fc="#b8860b", label="TARGET (normalisation open)"),
    Patch(fc="#2166ac", label="CONDITIONAL spectral gap (not Clay)"),
    Patch(fc="#4393c3", label="VALIDATED (external r0)"),
    Patch(fc="#888888", label="INHERITED"),
    Patch(fc="#b2182b", label="NOT CLAIMED"),
]
axL.legend(handles=legend_handles, loc="lower left", fontsize=7.4,
           ncol=2, frameon=False, bbox_to_anchor=(0.0, -0.02))

# ---- Panel B: Lambda_QCD / sqrt(sigma) vs lattice ----
axR = fig.add_subplot(gs[0, 1])
axR.set_title("Confinement scale: alpha-tower vs executed lattice",
              fontsize=12, fontweight="bold", loc="left")

# DFD target band
axR.axhspan(sqrt_sigma_DFD_MeV - sqrt_sigma_DFD_err,
            sqrt_sigma_DFD_MeV + sqrt_sigma_DFD_err,
            color="#1b7837", alpha=0.18, zorder=0,
            label=f"DFD alpha-tower target {sqrt_sigma_DFD_MeV:.0f}+/-{sqrt_sigma_DFD_err:.0f}")

xs = [0, 1, 2, 3]
labels = ["DFD\ntarget", "lattice\n16^4 avg", "lattice\n20^4 (r0)", "lattice\nbest"]
vals  = [sqrt_sigma_DFD_MeV, 470.0, sqrt_sigma_lat_MeV, sqrt_sigma_lat_best]
errs  = [sqrt_sigma_DFD_err, 10.0, 7.0, sqrt_sigma_lat_err]
cols  = ["#1b7837", "#4393c3", "#4393c3", "#2166ac"]
for x, v, e, c in zip(xs, vals, errs, cols):
    axR.errorbar(x, v, yerr=e, fmt="o", ms=9, color=c, capsize=5,
                 elinewidth=2, mec="black", mew=0.7, zorder=3)
    axR.text(x, v + e + 6, f"{v:.0f}", ha="center", fontsize=9, fontweight="bold")

axR.set_xticks(xs)
axR.set_xticklabels(labels, fontsize=9)
axR.set_ylabel(r"$\sqrt{\sigma}$  [MeV]", fontsize=11)
axR.set_xlim(-0.5, 3.5)
axR.set_ylim(400, 510)
axR.grid(axis="y", ls=":", alpha=0.5)
axR.legend(loc="lower right", fontsize=8.5, frameon=True)

# annotate the agreement + the honest caveats
axR.text(0.02, 0.97,
         f"agreement: {pct_agreement:+.1f}%  ({sigma_agreement:+.2f}o)\n"
         f"lattice MeV needs EXTERNAL r0=0.5 fm\n"
         f"dimensionless output r0*sqrt(s)=1.178 (DFD-indep.)",
         transform=axR.transAxes, fontsize=8.0, va="top",
         bbox=dict(boxstyle="round,pad=0.3", fc="#fff7e6", ec="#b8860b"))

axR.text(0.02, 0.03,
         "Clay YM mass gap: NOT claimed (inherited)",
         transform=axR.transAxes, fontsize=8.5, va="bottom", fontweight="bold",
         color="#b2182b",
         bbox=dict(boxstyle="round,pad=0.25", fc="#fde7e7", ec="#b2182b"))

fig.suptitle("DFD Yang--Mills / QCD mass-gap status  -  derived: confinement scale (~5% lattice agreement);  "
             "inherited + NOT claimed: Clay mass gap",
             fontsize=11.5, y=0.995)

out = "./fig_ym_massgap_status.png"
fig.savefig(out, dpi=150, bbox_inches="tight")
print(f"\nFigure written: {out}")
