#!/usr/bin/env python3
"""
verify_P084.py -- Addendum 84: Unified Quark Mass Table.

This verifier recomputes the constants, spectral energies, quark masses,
residuals, RMS residual, and selected mass-ratio claims in
84_Addendum_QuarkMassTable.tex.

It intentionally fails the internally inconsistent top-mass table claim:
the paper's own formula E_t = pi^2 + pi + ln(mu0)/MU gives m_t ~= 176.10 GeV,
not 172.4 GeV. The abstract's older "+2.0%" top result is consistent with
the formula; the later "172.4 GeV / -0.2%" recomputation is not.
"""

import math
import sys
from pathlib import Path

PASS = FAIL = 0
_N = 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}")
    return ok


class Verifier:
    """Target-style output adapter; check/record numerics are unchanged."""

    def __init__(self, name):
        print(name)

    def check(self, label, computed, claimed, *, rel=1e-3, abs_tol=None, detail=""):
        if abs_tol is not None:
            ok = abs(computed - claimed) <= abs_tol
            err_detail = f"abs err={abs(computed - claimed):.6g}, tol={abs_tol:.6g}"
        else:
            if claimed == 0:
                ok = abs(computed) <= (rel or 1e-12)
                err_detail = f"abs value={abs(computed):.6g}, tol={rel:.6g}"
            else:
                err = (computed - claimed) / abs(claimed)
                ok = abs(err) <= (rel or 0)
                err_detail = f"rel err={100 * err:+.6g}%, tol={100 * (rel or 0):.6g}%"
        return self.record(label, ok, computed, claimed,
                           err_detail + (f"; {detail}" if detail else ""))

    def record(self, label, ok, computed="", claimed="", detail=""):
        global _N
        ok = bool(ok)
        desc, extra = label, detail
        if not ok and detail:
            desc, extra = f"{label} -- {detail}", ""
        _N += 1
        check(_N, desc, ok)
        if computed != "" or claimed != "":
            print(f"       computed: {computed}")
            print(f"       claimed : {claimed}")
        if extra:
            print(f"       {extra}")
        return ok

    def summary(self):
        print(f"\n{'='*60}\nRESULT: {PASS} PASS / {FAIL} FAIL")
        return 1 if FAIL else 0


v = Verifier("P084 -- Unified Quark Mass Table")

PI = math.pi
M_E = 0.511  # MeV, as used in the paper.

MU0 = 4 * PI**3 + PI**2 + PI
MU1 = 16 * PI**3 / 5 + 3 * PI**2 / 4 + 2 * PI / 3
MU = MU1 / MU0
LAM = math.sin(PI / 14)

PDG = {
    "u": 2.16,
    "d": 4.67,
    "s": 93.4,
    "c": 1270.0,
    "b": 4180.0,
    "t": 172_760.0,
}

E = {
    "u": PI ** (7 / 5),
    "d": math.log(MU1) / MU,
    "s": PI**2 - 1 / 7,
    "c": PI**2 + PI,
    "b": PI ** (7 / 3),
    "t": PI**2 + PI + math.log(MU0) / MU,
}


def mass_from_e(e):
    return M_E * math.exp(MU * (e - PI))


def e_from_mass(m):
    return PI + math.log(m / M_E) / MU


def residual_pct(pred, actual):
    return 100 * (pred - actual) / actual


v.check("mu0 = 4*pi^3 + pi^2 + pi", MU0, 137.036304, rel=5e-9)
v.check("mu1 = 16*pi^3/5 + 3*pi^2/4 + 2*pi/3", MU1, 108.716684, rel=5e-9)
v.check("MU = mu1/mu0", MU, 0.793342, rel=5e-7)
v.check("lambda = sin(pi/14)", LAM, 0.222520, rel=5e-6)

claimed_empirical_e = {
    "u": 4.9582,
    "d": 5.9309,
    "s": 9.7073,
    "c": 12.9963,
    "b": 14.4979,
    "t": 19.1869,
}

for q, claimed in claimed_empirical_e.items():
    v.check(f"E_{q} empirical from PDG mass", e_from_mass(PDG[q]), claimed, rel=2e-4)

claimed_spectral_e = {
    "u": 4.9672,
    "d": 5.9114,
    "s": 9.7267,
    "c": 13.0112,
    "b": 14.455,
    "t": 19.2131,
}

for q, claimed in claimed_spectral_e.items():
    v.check(f"E_{q} TOE spectral formula", E[q], claimed, rel=4e-4)

claimed_masses = {
    "u": 2.173,
    "d": 4.600,
    "s": 95.2,
    "c": 1287.0,
    "b": 4046.0,
    # The table states 172.4 GeV; the formula gives about 176.1 GeV.
    "t_table_late_GeV": 172.4,
    # The abstract / Addendum 45 value is formula-consistent.
    "t_formula_GeV": 176.1,
}

pred_mass = {q: mass_from_e(E[q]) for q in E}
for q in ["u", "d", "s", "c", "b"]:
    tol = 5e-3 if q == "s" else 3e-3
    v.check(f"m_{q} from spectral formula", pred_mass[q], claimed_masses[q], rel=tol)

v.check(
    "m_t from spectral formula agrees with 176.1 GeV formula value",
    pred_mass["t"] / 1000,
    claimed_masses["t_formula_GeV"],
    rel=5e-4,
)
v.check(
    "m_t from spectral formula vs late table claim 172.4 GeV",
    pred_mass["t"] / 1000,
    claimed_masses["t_table_late_GeV"],
    rel=5e-3,
    detail="Expected fail: late P84 recomputation/table uses inconsistent exponent arithmetic.",
)

claimed_residuals = {
    "u_table": 0.6,
    "d_table": -1.5,
    "s_table": 1.9,
    "c_table": 1.3,
    "b_table": -3.2,
    "t_abstract": 2.0,
    "t_late_table": -0.2,
}

actual_residuals = {q: residual_pct(pred_mass[q], PDG[q]) for q in E}
v.check("u residual vs PDG", actual_residuals["u"], claimed_residuals["u_table"], rel=2e-1)
v.check("d residual vs PDG", actual_residuals["d"], claimed_residuals["d_table"], rel=1e-1)
v.check("s residual vs PDG", actual_residuals["s"], claimed_residuals["s_table"], rel=2e-1)
v.check("c residual vs PDG", actual_residuals["c"], claimed_residuals["c_table"], rel=1e-1)
v.check("b residual vs PDG", actual_residuals["b"], claimed_residuals["b_table"], rel=1e-1)
v.check("t residual matches abstract +2.0% value", actual_residuals["t"], claimed_residuals["t_abstract"], rel=5e-2)
v.check(
    "t residual vs late table -0.2% claim",
    actual_residuals["t"],
    claimed_residuals["t_late_table"],
    rel=5e-1,
    detail="Expected fail: same inconsistency as m_t table value.",
)

rms = math.sqrt(sum(x * x for x in actual_residuals.values()) / len(actual_residuals))
v.check("RMS residual over six quarks", rms, 2.0, rel=1e-1)

v.check("m_d/m_u Weyl-step formula", math.exp(2 * MU * LAM**2 * PI**2), 2.17, rel=2e-3)
v.check("PDG m_d/m_u ratio", PDG["d"] / PDG["u"], 2.16, rel=2e-3)
v.check("m_s/m_mu = exp(-MU/7)", math.exp(-MU / 7), 0.8927, rel=5e-4)
v.check("m_b/m_t formula ratio", math.exp(MU * (E["b"] - E["t"])), 0.02293, rel=1e-3)
v.check("m_t/m_c = mu0", MU0, 137.036, rel=3e-6)
v.check("PDG m_t/m_c ratio", PDG["t"] / PDG["c"], 136.03, rel=2e-5)
v.check("m_s/m_d formula ratio", math.exp(MU * (E["s"] - E["d"])), 20.61, rel=3e-3)
v.check("m_b/m_s formula ratio", math.exp(MU * (E["b"] - E["s"])), 42.43, rel=4e-3)

sys.exit(v.summary())
