#!/usr/bin/env python3
"""Numerical checks for guide chapter 3.2 (Distributions and new physics), and its three data plots.
Every formula the chapter states is tested here; the script exits non-zero if any check fails.
Run:  python3 guide-build/tools/check_3_2.py     (writes assets/guide/3-2-*.svg)"""
import pathlib, sys
import numpy as np
from scipy import integrate, stats
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import matplotlib.ticker

ok = True
def check(name, got, want, tol=1e-6, rel=False):
    """Pass if |got-want| <= tol*max(1,|want|); with rel=True the tolerance is relative to |want| itself."""
    global ok
    good = abs(got - want) <= tol * (abs(want) if rel else max(1.0, abs(want)))
    ok &= good
    print(f"{'PASS' if good else 'FAIL'}  {name}: got {got:.10g}, want {want:.10g}")
def info(s): print("INFO  " + s)

SITE = pathlib.Path(__file__).resolve().parents[2]
FIG = SITE / "assets" / "guide"; FIG.mkdir(parents=True, exist_ok=True)
TEAL, ORANGE, INK, GRID, GREY = "#0e7c7b", "#d96c2c", "#16222e", "#ebe6da", "#8a8f96"
plt.rcParams.update({"font.size": 13, "axes.edgecolor": INK, "axes.labelcolor": INK, "xtick.color": INK,
                     "ytick.color": INK, "text.color": INK, "axes.grid": True, "grid.color": GRID,
                     "figure.facecolor": "white", "axes.facecolor": "white", "svg.fonttype": "path",
                     "legend.frameon": False})
rng = np.random.default_rng(32)

# =================================================================================================
# 1. Matching a heavy scalar onto a contact operator (section 2, derivation D1)
# =================================================================================================
# (a) the classical solution: L(phi) = -1/2 M^2 phi^2 - g phi S is stationary at phi = -g S/M^2, where it equals g^2 S^2/2M^2
for g, M, S in [(0.7, 3.0, 1.3), (1.9, 11.0, -0.4)]:
    ph = -g*S/M**2
    check(f"L(phi*) = g^2 S^2 / 2M^2 (g={g}, M={M})", -0.5*M**2*ph**2 - g*ph*S, g**2*S**2/(2*M**2), 1e-12)
# (b) the same statement as a Gaussian integral (a field theory at a single point, Euclidean weight)
    num = integrate.quad(lambda p: np.exp(-0.5*M**2*p**2 - g*p*S), -np.inf, np.inf)[0]
    den = integrate.quad(lambda p: np.exp(-0.5*M**2*p**2), -np.inf, np.inf)[0]
    check("Gaussian integral over phi = exp(g^2 S^2/2M^2)", num/den, np.exp(g**2*S**2/(2*M**2)), 1e-9)
# (c) the propagator expansion: 1/(M^2 - q^2) = (1/M^2)(1 + q^2/M^2 + ...); the first neglected term is q^2/M^2
M = 5.0
for q2 in (0.25, 1.0):
    exact, lead = 1/(M**2 - q2), 1/M**2
    check(f"relative error of the contact approximation at q^2/M^2={q2/M**2:g}", exact/lead - 1, (q2/M**2)/(1 - q2/M**2), 1e-12)
# (d) tree-level amplitude: exchange gives (-ig)^2 * i/(q^2-M^2) -> i g^2/M^2; a contact term c (psibar psi)^2 gives 2ic
g = 1.3; c = g**2/(2*M**2)
check("2c = g^2/M^2 (two ways to attach the two bilinears)", 2*c, ((-1j*g)**2*1j/(0 - M**2)).imag, 1e-12)

# =================================================================================================
# 2. The W and Y operators (section 4, derivation D2)
# =================================================================================================
met = np.diag([1., -1, -1, -1])
dot = lambda a, b: a @ met @ b
# (a) Abelian identity in momentum space: (d_rho F_mu_nu)^2 = 2 (d^mu F_mu_nu)^2 up to total derivatives.
#     With F_mu_nu = q_mu A_nu - q_nu A_mu:  q^2 F.F = 2 (q^mu F_mu_nu)^2.
for _ in range(3):
    qv, A = rng.normal(size=4), rng.normal(size=4)
    F = np.outer(qv, A) - np.outer(A, qv)                         # F^{mu nu} with upper indices
    FF = np.einsum("ab,cd,ac,bd->", F, F, met, met)
    qF = np.einsum("a,ab,bc->c", qv, met, F)                      # q_mu F^{mu nu}
    check("q^2 F.F = 2 (q.F)^2", dot(qv, qv)*FF, 2*dot(qF, qF), 1e-9)
# (b) the propagator: 1/(q^2 - m^2 + W q^4/mW^2) = 1/(q^2-m^2) - W/mW^2 + pole-like terms, to first order in W
mW, mZ, s2w = 80.38, 91.19, 0.2312
W_ = 1e-4
for q2 in (500.0**2, 2000.0**2):
    full = 1/(q2 - mW**2 + W_*q2**2/mW**2); sm = 1/(q2 - mW**2)
    first = sm - W_*q2**2/(mW**2*(q2 - mW**2)**2)
    contact = sm - W_/mW**2
    check(f"first-order expansion of the modified propagator (q={np.sqrt(q2):g})", full, first, 2*(W_*q2/mW**2)**2, rel=True)
    # q^4/(q^2-m^2)^2 = 1 + 2m^2/(q^2-m^2) + m^4/(q^2-m^2)^2 : the remainder is a shift of the pole's residue and position
    check("q^4/(q^2-m^2)^2 = 1 + 2m^2/(q^2-m^2) + m^4/(q^2-m^2)^2", q2**2/(q2 - mW**2)**2,
          1 + 2*mW**2/(q2 - mW**2) + mW**4/(q2 - mW**2)**2, 1e-12)
    check(f"(modified - SM) propagator / (-W/mW^2) -> 1 at high q (q={np.sqrt(q2):g})", (first - sm)/(-W_/mW**2),
          1.0, 2.1*mW**2/(q2 - mW**2) + 1e-3)
# (c) matching a heavy triplet or hypercharge vector: W = g*^2 mW^2/(g^2 M^2); scale probed for g* = g
for Wv in (1e-4, 6e-4, 1e-5):
    info(f"W = {Wv:g} with g* = g corresponds to M = mW/sqrt(W) = {mW/np.sqrt(Wv)/1e3:.2f} TeV")
check("M for W=1e-4, g*=g (TeV)", mW/np.sqrt(1e-4)/1e3, 8.04, 1e-3)
check("M for W=6e-4, g*=g (TeV)", mW/np.sqrt(6e-4)/1e3, 3.28, 2e-3)

# =================================================================================================
# 3. Drell-Yan with W and Y at lowest order (section 5, derivation D3)
# =================================================================================================
c2w = 1 - s2w; t2 = s2w/c2w                                        # t2 = gY^2/g^2
# everything in units of g^2: e^2 = s2w, gY^2 = t2, gZ(f) = (T3 - Q s2w)/cw
ferm = {  # name: (T3, Y)
    "uL": (0.5, 1/6), "dL": (-0.5, 1/6), "uR": (0.0, 2/3), "dR": (0.0, -1/3),
    "eL": (-0.5, -0.5), "eR": (0.0, -1.0), "nuL": (0.5, -0.5)}
Q = lambda f: ferm[f][0] + ferm[f][1]
gZ = lambda f: (ferm[f][0] - Q(f)*s2w)/np.sqrt(c2w)
check("charges from Q = T3 + Y: u, d, e, nu", Q("uL") + Q("uR") + 10*Q("dL") + 10*Q("dR") + 100*Q("eL") + 100*Q("eR") + 1e3*Q("nuL"),
      2/3 + 2/3 - 10/3 - 10/3 - 100 - 100 + 0, 1e-12)
# (a) gauge-basis identity: e^2 Q Q' + gZ gZ' = g^2 T3 T3' + gY^2 Y Y'
for a in ("uL", "uR", "dL", "dR"):
    for b in ("eL", "eR"):
        check(f"e^2QQ' + gZgZ' = g^2T3T3' + gY^2YY' ({a},{b})", s2w*Q(a)*Q(b) + gZ(a)*gZ(b),
              ferm[a][0]*ferm[b][0] + t2*ferm[a][1]*ferm[b][1], 1e-12)
def amps(qk, shat, W=0.0, Y=0.0):
    """Helicity amplitudes A_XY (units of g^2) for q_X qbar -> l_Y lbar, eq. (3.2.13)."""
    out = []
    for a in (qk + "L", qk + "R"):
        for b in ("eL", "eR"):
            sm = s2w*Q(a)*Q(b)/shat + gZ(a)*gZ(b)/(shat - mZ**2)
            ct = -(ferm[a][0]*ferm[b][0]*W + t2*ferm[a][1]*ferm[b][1]*Y)/mW**2
            out.append((sm, ct))
    return np.array(out)
def K_lin(qk, m, W=0.0, Y=0.0):                                    # interference only (linear in W, Y), as in Moore
    a = amps(qk, m*m, W, Y); return 1 + 2*np.sum(a[:, 0]*a[:, 1])/np.sum(a[:, 0]**2)
def K_full(qk, m, W=0.0, Y=0.0):
    a = amps(qk, m*m, W, Y); return np.sum((a[:, 0] + a[:, 1])**2)/np.sum(a[:, 0]**2)
# (a') the chirality traces of derivation D3, with explicit Dirac matrices
I2 = np.eye(2); Z2 = np.zeros((2, 2))
sig = [np.array([[0, 1], [1, 0]]), np.array([[0, -1j], [1j, 0]]), np.array([[1, 0], [0, -1]])]
gam = [np.block([[I2, Z2], [Z2, -I2]])] + [np.block([[Z2, s_], [-s_, Z2]]) for s_ in sig]
g5 = 1j*gam[0] @ gam[1] @ gam[2] @ gam[3]
PL, PR = (np.eye(4) - g5)/2, (np.eye(4) + g5)/2
sl = lambda a: sum(gam[m]*(met @ a)[m] for m in range(4))
E_, th_ = 3.0, 0.7
p1 = np.array([E_, 0, 0, E_]); p2 = np.array([E_, 0, 0, -E_])
k1 = E_*np.array([1, np.sin(th_), 0, np.cos(th_)]); k2 = E_*np.array([1, -np.sin(th_), 0, -np.cos(th_)])
sh_ = dot(p1 + p2, p1 + p2)
def m2(PX, PY):      # sum over spins of |vbar(p2) gamma^mu P_X u(p1)  ubar(k1) gamma_mu P_Y v(k2)|^2
    tot = 0
    for mu in range(4):
        for nu in range(4):
            t1 = np.trace(sl(p2) @ gam[mu] @ PX @ sl(p1) @ gam[nu])
            t2_ = np.trace(sl(k1) @ gam[mu] @ PY @ sl(k2) @ gam[nu])
            tot += t1*t2_*met[mu, mu]*met[nu, nu]
    return tot.real
check("LL trace = 16 (p1.k2)(p2.k1)", m2(PL, PL), 16*dot(p1, k2)*dot(p2, k1), 1e-10, rel=True)
check("LL trace = shat^2 (1+cos)^2", m2(PL, PL), sh_**2*(1 + np.cos(th_))**2, 1e-10, rel=True)
check("RR trace = LL trace", m2(PR, PR), m2(PL, PL), 1e-10, rel=True)
check("LR trace = 16 (p1.k1)(p2.k2) = shat^2 (1-cos)^2", m2(PL, PR), sh_**2*(1 - np.cos(th_))**2, 1e-10, rel=True)
check("RL trace = LR trace", m2(PR, PL), m2(PL, PR), 1e-10, rel=True)
check("tan^2(theta_W) for sin^2 = 0.2312", t2, 0.3007, 1e-4)
Gq = lambda qk: [ferm[a][0]*ferm[b][0] + t2*ferm[a][1]*ferm[b][1] for a in (qk + "L", qk + "R") for b in ("eL", "eR")]
for got, want in zip(Gq("u"), (-0.275, -0.050, -0.100, -0.200)): check("G_XY for u", got, want, 6e-4)
for got, want in zip(Gq("d"), (0.225, -0.050, 0.050, 0.100)): check("G_XY for d", got, want, 6e-4)
check("sum G^2 for u", sum(g_*g_ for g_ in Gq("u")), 0.128, 1e-3)
check("shat/mW^2 at 1 TeV", 1000.0**2/mW**2, 155, 0.5/155, rel=True)
check("shat/mW^2 at 3 TeV", 3000.0**2/mW**2, 1390, 5/1390, rel=True)
# (b) photon only: sigma = shat/(48 pi Nc) sum |A|^2 reproduces 4 pi alpha^2 eq^2/(3 shat Nc)
alpha, shat, eq = 1/128.0, 300.0**2, 2/3
e2 = 4*np.pi*alpha
check("photon-only limit of eq. (3.2.12)", shat/(48*np.pi*3)*4*(e2*eq/shat)**2, 4*np.pi*alpha**2*eq**2/(3*shat*3), 1e-14, rel=True)
check("angular integral of (1 +- cos)^2 = 16 pi/3", 2*np.pi*integrate.quad(lambda c: (1 + c)**2, -1, 1)[0], 16*np.pi/3, 1e-12)
# (c) the high-energy weights of eq. (3.2.15)
def weights(qk):
    G = [], []
    num_w = num_y = den = 0.0
    for a in (qk + "L", qk + "R"):
        for b in ("eL", "eR"):
            gw, gy = ferm[a][0]*ferm[b][0], t2*ferm[a][1]*ferm[b][1]
            num_w += (gw + gy)*gw; num_y += (gw + gy)*gy; den += (gw + gy)**2
    return num_w/den, num_y/den
wu, yu = weights("u"); wd, yd = weights("d")
info(f"weights: w_u={wu:.3f} y_u={yu:.3f}   w_d={wd:.3f} y_d={yd:.3f}")
check("w_u + y_u = 1", wu + yu, 1, 1e-12); check("w_d + y_d = 1", wd + yd, 1, 1e-12)
check("w_u", wu, 0.54, 0.01); check("y_u", yu, 0.46, 0.01); check("w_d", wd, 0.86, 0.01); check("y_d", yd, 0.14, 0.01)
for m in (1000.0, 3000.0):
    r = m*m/mW**2
    check(f"K_u - 1 (linear, W=1e-4) vs -2 w_u W shat/mW^2 at {m:g} GeV", K_lin("u", m, W=1e-4) - 1, -2*wu*1e-4*r, 0.03, rel=True)
    check(f"K_d - 1 (linear, Y=1e-4) vs -2 y_d Y shat/mW^2 at {m:g} GeV", K_lin("d", m, Y=1e-4) - 1, -2*yd*1e-4*r, 0.08, rel=True)
for m in (500.0, 1000.0, 2000.0, 4000.0):
    info(f"m={m:5.0f} GeV, 1e-4: K_u-1 W {100*(K_lin('u', m, W=1e-4)-1):6.2f}%  Y {100*(K_lin('u', m, Y=1e-4)-1):6.2f}%   "
         f"K_d-1 W {100*(K_lin('d', m, W=1e-4)-1):6.2f}%  Y {100*(K_lin('d', m, Y=1e-4)-1):6.2f}%   CC W {100*(-2e-4*(m*m-mW**2)/mW**2):6.2f}%")
check("K_u - 1 at 1 TeV, W = 1e-4 (percent)", 100*(K_lin("u", 1000.0, W=1e-4) - 1), -1.7, 0.03)
check("K_u - 1 at 1 TeV, W = -1e-3", K_lin("u", 1000.0, W=-1e-3) - 1, 0.17, 0.03)
check("K_d - 1 at 1 TeV, W = -1e-3", K_lin("d", 1000.0, W=-1e-3) - 1, 0.27, 0.03)
check("K_u - 1 at 1 TeV, Y = -1e-3", K_lin("u", 1000.0, Y=-1e-3) - 1, 0.14, 0.03)
check("quadratic term at 1 TeV, W=1e-4: K_full - K_lin", K_full("u", 1000.0, W=1e-4) - K_lin("u", 1000.0, W=1e-4), 0.0, 2e-4)
# (d) charged current: K = [1 - W (shat - mW^2)/mW^2]^2
for m in (1000.0, 2500.0):
    sm, ct = 0.5/(m*m - mW**2), -0.5*1e-4/mW**2
    check(f"charged-current K at {m:g} GeV", ((sm + ct)/sm)**2, (1 - 1e-4*(m*m - mW**2)/mW**2)**2, 1e-12)
# (e) energy against precision: the W that a measurement of relative precision delta can see at mass m
sens = lambda delta, m, w=0.6: delta*mW**2/(2*w*m*m)
info(f"10% at 1 TeV sees W ~ {sens(0.10, 1000):.1e};  10% at 3 TeV: {sens(0.10, 3000):.1e}")
check("10% at 1 TeV", sens(0.10, 1000), 5.4e-4, 0.02, rel=True)
check("10% at 3 TeV", sens(0.10, 3000), 6.0e-5, 0.02, rel=True)
# (f) deep inelastic scattering is space-like: the sign flips and the size at HERA's highest Q^2 is per mille
Q2 = 4e4
check("DIS: 2 w |W| Q^2/mW^2 at Q^2 = 4e4 GeV^2, |W| = 1e-4", 2*0.6*1e-4*Q2/mW**2, 7.4e-4, 0.02, rel=True)
# the sign reversal: every helicity amplitude has (contact term)/(SM term) of opposite sign at q^2 = -Q^2 and q^2 = +Q^2
for qk in ("u", "d"):
    a_s, a_t = amps(qk, Q2), amps(qk, -Q2)
    check(f"DIS vs Drell-Yan: sign of the interference flips in all four helicity channels ({qk})",
          float(np.all(np.sign(a_s[:, 0]*a_s[:, 1]) == -np.sign(a_t[:, 0]*a_t[:, 1]))), 1.0)
# (g) comparison with the published forms (reviewer's check).
# Torre, Ricci, Wulzer (arXiv:2008.12978, eqs. 11-12) define W, Y as the coefficients of the contact terms (3.2.9):
#   rho_n = |1 + aW W + aY Y|^2,  aW = -g^2 T3 T3'/(mW^2 C_SM),  aY = -gY^2 Y Y'/(mW^2 C_SM),  rho_c = (1 - W (s - mW^2)/mW^2)^2,
# which is eq. (3.2.13) and eq. (3.2.16) term by term (amps() above is that formula).
# Farina et al. (arXiv:1609.08157, eq. 1) start from the oblique form (3.2.8) and give modified propagators in the (photon, Z) basis:
def amps_farina(qk, q2, W=0.0, Y=0.0, mZ2=None):
    mZ2 = mW**2/c2w if mZ2 is None else mZ2                        # tree-level relation, needed for the constant terms to match
    t, e = np.sqrt(t2), np.sqrt(s2w)
    Pgg = lambda W, Y: 1/q2 - (t2*W + Y)/mZ2
    PgZ = lambda W, Y: t*(Y*c2w + s2w*W)/((c2w - s2w)*(q2 - mZ2)) + t*(Y - W)/mZ2
    PZZ = lambda W, Y: (1 - W - t2*Y)/(q2 - mZ2) - (t2*Y + W)/mZ2
    A = lambda a, b, W, Y: e*e*Q(a)*Q(b)*Pgg(W, Y) + e*(Q(a)*gZ(b) + gZ(a)*Q(b))*PgZ(W, Y) + gZ(a)*gZ(b)*PZZ(W, Y)
    return np.array([(A(a, b, 0, 0), A(a, b, W, Y) - A(a, b, 0, 0)) for a in (qk + "L", qk + "R") for b in ("eL", "eR")])
def const_farina(a, b, W, Y):                                      # the q^2-independent part of Farina's amplitude
    t, e, mZ2 = np.sqrt(t2), np.sqrt(s2w), mW**2/c2w
    return -e*e*Q(a)*Q(b)*(t2*W + Y)/mZ2 + e*(Q(a)*gZ(b) + gZ(a)*Q(b))*t*(Y - W)/mZ2 - gZ(a)*gZ(b)*(t2*Y + W)/mZ2
for a in ("uL", "uR", "dL", "dR"):
    for b in ("eL", "eR"):
        check(f"Farina et al. constant terms = contact terms of eq. (3.2.13) ({a},{b})", const_farina(a, b, 3e-4, -2e-4),
              -(ferm[a][0]*ferm[b][0]*3e-4 + t2*ferm[a][1]*ferm[b][1]*(-2e-4))/mW**2, 1e-15)
def K_lin_farina(qk, m, W=0.0, Y=0.0):
    a = amps_farina(qk, m*m, W, Y); return 1 + 2*np.sum(a[:, 0]*a[:, 1])/np.sum(a[:, 0]**2)
def K_lin_tree(qk, m, W=0.0, Y=0.0):                               # eq. (3.2.13) with the same tree-level mZ, for a like-for-like comparison
    mZ2 = mW**2/c2w; out = []
    for a in (qk + "L", qk + "R"):
        for b in ("eL", "eR"):
            out.append((s2w*Q(a)*Q(b)/(m*m) + gZ(a)*gZ(b)/(m*m - mZ2), -(ferm[a][0]*ferm[b][0]*W + t2*ferm[a][1]*ferm[b][1]*Y)/mW**2))
    out = np.array(out); return 1 + 2*np.sum(out[:, 0]*out[:, 1])/np.sum(out[:, 0]**2)
for qk in ("u", "d"):
    for kw in ({"W": 1e-4}, {"Y": 1e-4}):
        d = [K_lin_farina(qk, m, **kw) - K_lin_tree(qk, m, **kw) for m in (1000.0, 2000.0, 4000.0)]
        g = [K_lin_tree(qk, m, **kw) - 1 for m in (1000.0, 2000.0, 4000.0)]
        info(f"Farina - contact-only, {qk}, {kw}: difference/1e-4 = {d[0]/1e-4:+.3f}, {d[1]/1e-4:+.3f}, {d[2]/1e-4:+.3f};  "
             f"relative to the growing term: {d[0]/g[0]:+.4f}, {d[1]/g[1]:+.4f}, {d[2]/g[2]:+.4f}")
        check(f"pole-term corrections of Farina et al. do not grow with energy ({qk}, {list(kw)[0]}): |diff| < 3 x coefficient",
              float(max(abs(x) for x in d) < 3e-4), 1.0)
        check(f"... and are a shrinking fraction of the growing term ({qk}, {list(kw)[0]})", float(abs(d[2]/g[2]) < abs(d[0]/g[0])), 1.0)
# charged current: Farina's P_C = [1 + ((-W - t2 Y) + 2 t2 (W + Y))/(1 - t2)]/(q^2 - mW^2) - W/mW^2  (S = T = 0)
for m in (1000.0, 3000.0):
    resid = lambda W, Y: ((-W - t2*Y) + 2*t2*(W + Y))/(1 - t2)
    kF = (1 + resid(1e-4, 0) - 1e-4*(m*m - mW**2)/mW**2)**2; kC = (1 - 1e-4*(m*m - mW**2)/mW**2)**2
    info(f"charged current at {m:g} GeV, W=1e-4: K-1 contact-only {kC-1:+.5f}, Farina et al. {kF-1:+.5f}")
    check(f"charged current: Farina's amplitude ratio exceeds the contact-only one by a constant of order W ({m:g} GeV)",
          (np.sqrt(kF) - np.sqrt(kC))/1e-4, resid(1, 0), 1e-9)
    check(f"... which is under 1% of the growing term ({m:g} GeV)", float(abs((kF - kC)/(kC - 1)) < 0.01), 1.0)

# ---- Figure 2: the energy growth ----------------------------------------------------------------
ms = np.linspace(200, 4000, 300)
fig, ax = plt.subplots(figsize=(8, 4.6))
ax.plot(ms/1e3, [100*(K_lin("u", m, W=-1e-4) - 1) for m in ms], color=TEAL, lw=2.4, label=r"$u\bar u\to l^+l^-$,  $\hat W=-10^{-4}$")
ax.plot(ms/1e3, [100*(K_lin("d", m, W=-1e-4) - 1) for m in ms], color=TEAL, lw=2.4, ls="--", label=r"$d\bar d\to l^+l^-$,  $\hat W=-10^{-4}$")
ax.plot(ms/1e3, [100*(K_lin("u", m, Y=-1e-4) - 1) for m in ms], color=ORANGE, lw=2.4, label=r"$u\bar u\to l^+l^-$,  $\hat Y=-10^{-4}$")
ax.plot(ms/1e3, [100*(K_lin("d", m, Y=-1e-4) - 1) for m in ms], color=ORANGE, lw=2.4, ls="--", label=r"$d\bar d\to l^+l^-$,  $\hat Y=-10^{-4}$")
ax.plot(ms/1e3, [100*2e-4*(m*m - mW**2)/mW**2 for m in ms], color=INK, lw=1.8, ls=":", label=r"$u\bar d\to l\nu$,  $\hat W=-10^{-4}$")
ax.set_xlim(0.2, 4); ax.set_ylim(0, 50)
ax.set_xlabel("invariant mass of the lepton pair (TeV)"); ax.set_ylabel("change in cross-section (%)")
ax.legend(loc="upper left", fontsize=13)
fig.tight_layout(); fig.savefig(FIG / "3-2-growth.svg"); plt.close(fig)

# =================================================================================================
# 4. Fixed, profiled and contaminated fits in the linear model (sections 6 and 10, derivations D4, D5)
# =================================================================================================
# (a) block-matrix identities at random points
for npar in (2, 5):
    Mx = rng.normal(size=(npar + 1, npar + 6)); Fm = Mx @ Mx.T          # a random positive-definite Fisher matrix
    Ftt, Ftc, Fcc = Fm[:npar, :npar], Fm[:npar, npar], Fm[npar, npar]
    rho2 = Ftc @ np.linalg.solve(Ftt, Ftc)/Fcc
    check(f"(F^-1)_cc = 1/[F_cc (1-rho^2)]  ({npar} PDF parameters)", np.linalg.inv(Fm)[npar, npar], 1/(Fcc*(1 - rho2)), 1e-9, rel=True)
    check("0 <= rho^2 < 1", float(0 <= rho2 < 1), 1.0)
# (b) broadening <-> rho^2 for Moore's tables (95% CL widths, SM PDFs without PDF uncertainty vs SMEFT PDFs)
wid = lambda iv: iv[1] - iv[0]; mid = lambda iv: 0.5*(iv[0] + iv[1])
T34 = {  # Table 3.4, units 1e-4: (SM no PDF unc, SM with PDF unc, SMEFT, quoted shifts, quoted broadenings in %)
    "W68": ((-3.0, 2.2), (-4.3, 3.8), (-3.5, 2.4), (-0.2, -0.3), (13, -27)),
    "W95": ((-5.5, 4.7), (-6.8, 6.3), (-6.4, 5.3), (-0.2, -0.3), (15, -11)),
    "Y68": ((-4.4, 4.7), (-6.7, 7.5), (-3.4, 6.9), (1.6, 1.4), (13, -27)),
    "Y95": ((-8.8, 9.2), (-11.1, 12.0), (-8.3, 11.8), (1.6, 1.3), (12, -13))}
T35 = {  # Table 3.5, units 1e-5
    "W68": ((-0.7, 0.5), (-1.0, 0.9), (-4.5, 6.9), (1.3, 1.3), (850, 500)),
    "W95": ((-1.0, 0.8), (-1.4, 1.2), (-8.1, 10.6), (1.4, 1.4), (940, 620)),
    "Y68": ((-1.8, 3.2), (-3.7, 4.7), (-6.4, 8.0), (0.1, 0.3), (190, 70)),
    "Y95": ((-3.4, 4.7), (-5.3, 6.3), (-11.1, 12.6), (0.1, 0.3), (190, 110))}
for nm, T in (("3.4", T34), ("3.5", T35)):
    for k, (a, bq, e, sh, br) in T.items():
        for j, iv in enumerate((a, bq)):
            got = 100*(wid(e)/wid(iv) - 1)
            check(f"Table {nm} {k}: broadening {'with' if j else 'without'} PDF unc. (%), from the intervals", got, br[j],
                  0.5 + 0.08*abs(br[j]) + 3)                                       # rounding of the quoted intervals
            check(f"Table {nm} {k}: best-fit shift from interval mid-points", mid(e) - mid(iv), sh[j], 0.16)
for lab, T, k in (("current, W", T34, "W95"), ("current, Y", T34, "Y95"), ("HL-LHC, W", T35, "W95"), ("HL-LHC, Y", T35, "Y95")):
    f = wid(T[k][2])/wid(T[k][0])
    info(f"{lab}: width ratio {f:.2f}  ->  equivalent rho^2 = {1 - 1/f**2:.3f}")
check("equivalent rho^2, HL-LHC W", 1 - (wid(T35["W95"][0])/wid(T35["W95"][2]))**2, 0.991, 1e-3)
check("equivalent rho^2, HL-LHC Y", 1 - (wid(T35["Y95"][0])/wid(T35["Y95"][2]))**2, 0.88, 5e-3)
check("equivalent rho^2, current W", 1 - (wid(T34["W95"][0])/wid(T34["W95"][2]))**2, 0.24, 1e-2)
check("width ratio, HL-LHC W", wid(T35["W95"][2])/wid(T35["W95"][0]), 10.4, 1e-2)
check("width ratio, HL-LHC Y", wid(T35["Y95"][2])/wid(T35["Y95"][0]), 2.9, 2e-2)
check("width ratio with PDF uncertainty, HL-LHC W", wid(T35["W95"][2])/wid(T35["W95"][1]), 7.2, 1e-2)
check("width ratio with PDF uncertainty, HL-LHC Y", wid(T35["Y95"][2])/wid(T35["Y95"][1]), 2.0, 3e-2)
check("current-data Y best-fit shift / 68% half-width of the simultaneous fit", 1.6/(wid(T34["Y68"][2])/2), 1/3, 0.03)
# Table 3.7 (injected (W, Y) = (4, 8) x 1e-5): which intervals contain the injected point and which contain zero
T37 = {"SM": ((-1.5, 1.2), (-3.1, 8.7)), "cons": ((3.1, 5.0), (5.8, 13.6)), "SMEFT": ((-5.3, 9.0), (-0.2, 26.7))}
inside = lambda v, iv: iv[0] <= v <= iv[1]
check("Table 3.7 SM PDFs: W interval excludes the injected 4", float(inside(4, T37["SM"][0])), 0.0)
check("Table 3.7 SM PDFs: Y interval contains the injected 8", float(inside(8, T37["SM"][1])), 1.0)
check("Table 3.7 conservative: both contain the injected point", float(inside(4, T37["cons"][0]) and inside(8, T37["cons"][1])), 1.0)
check("Table 3.7 conservative: both exclude zero", float(not inside(0, T37["cons"][0]) and not inside(0, T37["cons"][1])), 1.0)
check("Table 3.7 SMEFT PDFs: both contain the injected point", float(inside(4, T37["SMEFT"][0]) and inside(8, T37["SMEFT"][1])), 1.0)
check("Table 3.7 SMEFT PDFs: both contain zero", float(inside(0, T37["SMEFT"][0]) and inside(0, T37["SMEFT"][1])), 1.0)
check("Table 3.7: SMEFT/conservative width ratio for W", wid(T37["SMEFT"][0])/wid(T37["cons"][0]), 7.5, 0.01, rel=True)
# data counts quoted from Tables 3.1 and 3.2
info(f"Table 3.1 rows as printed sum to {15+89+85+29+28+9+30+6+61+22+82+32+22+5+5+28+22+5+9+29+17+30}; the table quotes a total of 659")
check("Table 3.2 totals", 13+46+127+41+43, 270); check("Table 3.2 total with separate channels", 13+46+127+41+43+43, 313)
# confidence levels
check("Delta chi^2 = 4 is 95.45% for one parameter", stats.chi2.cdf(4, 1), 0.9545, 1e-4)
check("95% for one parameter is Delta chi^2 = 3.84", stats.chi2.ppf(0.95, 1), 3.84, 1e-3)
check("95% for two parameters is Delta chi^2 = 5.99", stats.chi2.ppf(0.95, 2), 5.99, 1e-3)

# (c) the toy: 12 high-mass bins at 14 TeV, a three-parameter smooth change of the luminosity, one Wilson coefficient
SQS = 14000.0
Mi = 500.0*8.0**(np.arange(12)/11.0); xb = Mi/SQS
x0 = 0.3
phi = lambda x: np.stack([np.ones_like(x), x/x0, (x/x0)**2], axis=1)
WQ = 0.6                                                           # mean weight of W between the u and d channels
bvec = lambda M: -2*WQ*M**2/mW**2*1e-5                              # response to c = W x 1e5
err_hi = np.sqrt(0.005**2 + (0.002*(Mi/500.0)**1.7)**2)
err_lo = 0.02*(xb/xb[0])**1.3
info(f"toy: x from {xb[0]:.3f} to {xb[-1]:.3f}; high-mass errors {100*err_hi[0]:.1f}% to {100*err_hi[-1]:.0f}%; "
     f"low-energy errors {100*err_lo[0]:.0f}% to {100*err_lo[-1]:.0f}%; EFT response at 4 TeV for c=1: {100*bvec(Mi[-1]):.1f}%")
def setup(low=True, second=False, lowscale=1.0):
    A = [phi(xb)]; b = [bvec(Mi)]; e = [err_hi]; tag = [np.ones(12, bool)]
    if low: A.append(phi(xb)); b.append(np.zeros(12)); e.append(err_lo*lowscale); tag.append(np.zeros(12, bool))
    if second: A.append(phi(xb)); b.append(bvec(Mi/2)); e.append(3*err_hi); tag.append(np.ones(12, bool))
    return np.vstack(A), np.concatenate(b), np.concatenate(e), np.concatenate(tag)
def fisher(A, b, e):
    w = 1/e**2
    return (A.T*w) @ A, (A.T*w) @ b, np.sum(w*b*b)
res = {}
for name, kw in (("high-mass only", dict(low=False)), ("with low-energy data", dict()),
                 ("low-energy errors x3", dict(lowscale=3.0)), ("plus a second collider energy", dict(second=True))):
    A, b, e, tag = setup(**kw); Ftt, Ftc, Fcc = fisher(A, b, e)
    if name == "high-mass only":
        ev = np.linalg.eigvalsh(np.block([[Ftt, Ftc[:, None]], [Ftc[None, :], np.array([[Fcc]])]]))
        check("high-mass only: the joint Fisher matrix has a zero eigenvalue (exact degeneracy)", ev[0]/ev[-1], 0.0, 1e-10)
        res[name] = (1/np.sqrt(Fcc), np.inf, 1.0, np.nan); continue
    rho2 = Ftc @ np.linalg.solve(Ftt, Ftc)/Fcc
    lo = ~tag if (~tag).any() else None
    Flow = (A[lo].T/e[lo]**2) @ A[lo]
    hi = tag; bh = (A[hi].T/e[hi]**2) @ b[hi]                       # conservative PDFs: fitted to the low-energy data only
    s_cons = np.sqrt(1/Fcc + bh @ np.linalg.solve(Flow, bh)/Fcc**2)
    res[name] = (1/np.sqrt(Fcc), 1/np.sqrt(Fcc*(1 - rho2)), rho2, s_cons)
    info(f"toy [{name}]: sigma fixed {res[name][0]:.3f}, simultaneous {res[name][1]:.3f}, conservative {s_cons:.3f} (x1e-5); "
         f"rho^2 = {rho2:.4f}; broadening x{res[name][1]/res[name][0]:.2f}")
    check(f"toy [{name}]: simultaneous <= conservative (with PDF uncertainty)", float(res[name][1] <= s_cons*(1 + 1e-12)), 1.0)

# (d) Monte Carlo over pseudo-experiments in the baseline toy, with an injected signal
A, b, e, tag = setup(); Ftt, Ftc, Fcc = fisher(A, b, e)
s_fix, s_sim, rho2, s_cons = res["with low-energy data"]
cstar = 4.0
NMC = 40000
D = cstar*b + e*rng.normal(size=(NMC, len(e)))                      # relative deviations from the true Standard Model prediction
Wt = 1/e**2
th_sm = np.linalg.solve(Ftt, (A.T*Wt) @ D.T).T                      # step 1: fit the PDFs assuming c = 0
R = D - th_sm @ A.T
chi2_sm = np.sum(Wt*R*R, axis=1)
c_fix = (R*Wt) @ b/Fcc                                             # step 2: fit c with those PDFs held fixed
J = np.column_stack([A, b]); FJ = (J.T*Wt) @ J
sol = np.linalg.solve(FJ, (J.T*Wt) @ D.T).T                         # simultaneous fit
c_sim = sol[:, 3]
lo = ~tag; Flow = (A[lo].T*Wt[lo]) @ A[lo]
th_lo = np.linalg.solve(Flow, (A[lo].T*Wt[lo]) @ D[:, lo].T).T      # conservative PDFs
c_con = ((D[:, tag] - th_lo @ A[tag].T)*Wt[tag]) @ b[tag]/Fcc
se = lambda x: x.std()/np.sqrt(NMC)
check("contaminated fixed-PDF fit: <c> = c*(1 - rho^2)", c_fix.mean(), cstar*(1 - rho2), 4*se(c_fix) + 1e-4)
check("contaminated fixed-PDF fit: scatter = sqrt(1-rho^2)/sqrt(F_cc)", c_fix.std(), np.sqrt(1 - rho2)*s_fix, 0.02, rel=True)
check("simultaneous fit: <c> = c*", c_sim.mean(), cstar, 4*se(c_sim))
check("simultaneous fit: scatter = 1/sqrt(F_cc(1-rho^2))", c_sim.std(), s_sim, 0.02, rel=True)
check("conservative PDFs: <c> = c*", c_con.mean(), cstar, 4*se(c_con))
check("conservative PDFs: scatter", c_con.std(), s_cons, 0.02, rel=True)
ndof = len(e) - 3
check("SM-only fit: <chi2_min> = N - p + (c*/sigma_sim)^2", chi2_sm.mean(), ndof + (cstar/s_sim)**2, 4*se(chi2_sm), rel=False)
cover_fix = np.mean(np.abs(c_fix - cstar) < 1.96*s_fix)
cover_sim = np.mean(np.abs(c_sim - cstar) < 1.96*s_sim)
excl0_fix = np.mean(np.abs(c_fix) > 1.96*s_fix); excl0_sim = np.mean(np.abs(c_sim) > 1.96*s_sim); excl0_con = np.mean(np.abs(c_con) > 1.96*s_cons)
info(f"toy, injected c* = {cstar}: rho^2 = {rho2:.3f}; <c_fixed> = {c_fix.mean():.2f} +- quoted {s_fix:.2f}; "
     f"<c_sim> = {c_sim.mean():.2f} +- {s_sim:.2f}; conservative +- {s_cons:.2f}")
info(f"toy: 95% interval contains the truth: fixed {100*cover_fix:.1f}%, simultaneous {100*cover_sim:.1f}%; "
     f"zero excluded at 95%: fixed {100*excl0_fix:.0f}%, simultaneous {100*excl0_sim:.0f}%, conservative {100*excl0_con:.0f}%")
info(f"toy: <chi2_min>/dof of the SM-only fit = {chi2_sm.mean()/ndof:.3f}  (dof = {ndof}); noncentrality {(cstar/s_sim)**2:.2f}; "
     f"naive significance if PDFs were known: {cstar/s_fix:.1f} sigma; simultaneous: {cstar/s_sim:.2f} sigma")
check("simultaneous-fit coverage of the truth is 95%", cover_sim, 0.95, 0.006)
check("fixed-PDF 95% interval contains the truth in no pseudo-experiment", float(np.sum(np.abs(c_fix - cstar) < 1.96*s_fix)), 0.0)
check("toy: signal at 4 TeV = -12%", 100*cstar*bvec(Mi[-1]), -12, 0.02)
check("toy: chi2/dof of the SM-only fit", chi2_sm.mean()/ndof, 1.03, 0.004)
check("toy: mean fixed-PDF estimate", c_fix.mean(), 0.15, 0.02); check("toy: rho^2", rho2, 0.963, 1e-3)
check("toy: sigma fixed", s_fix, 0.97, 0.01); check("toy: sigma simultaneous", s_sim, 5.05, 0.01); check("toy: sigma conservative", s_cons, 5.18, 0.01)
check("toy: naive significance", cstar/s_fix, 4.1, 0.02)
# with no signal: the fixed-PDF error bar is too small only as a statement about c, its pull is narrower than quoted
D0 = e*rng.normal(size=(NMC, len(e)))
R0 = D0 - np.linalg.solve(Ftt, (A.T*Wt) @ D0.T).T @ A.T
c0 = (R0*Wt) @ b/Fcc
check("no signal: scatter of the fixed-PDF estimate = sqrt(1-rho^2) x quoted error", c0.std()/s_fix, np.sqrt(1 - rho2), 0.02, rel=True)

# ---- Figure 3: the contaminated fit ---------------------------------------------------------------
k = int(np.argmax(np.all(np.abs(D[:, tag] - cstar*b[tag]) < 1.3*e[tag], axis=1)))   # a typical pseudo-experiment (no point beyond 1.3 sigma)
hi = tag
fig, ax = plt.subplots(figsize=(8, 4.6))
Mf = np.linspace(450, 4200, 200); xf = Mf/SQS
ax.axhline(1, color=GREY, lw=1.2)
ax.errorbar(Mi/1e3, 1 + D[k, hi], yerr=e[hi], fmt="o", color=INK, ms=5, lw=1.3, capsize=3, label="pseudo-data, one experiment", zorder=3)
ax.plot(Mf/1e3, 1 + cstar*bvec(Mf), color=ORANGE, lw=2.4, label=r"truth: Standard Model $\times\,K_{\rm EFT}$, $\hat W=4\times10^{-5}$")
ax.plot(Mf/1e3, 1 + phi(xf) @ th_sm.mean(axis=0), color=TEAL, lw=2.4, ls="--", label="Standard Model fit with shifted distributions")
ax.text(0.55, 1.04, "true distributions, no new physics", color=GREY, fontsize=13)
ax.set_xscale("log"); ax.set_xticks([0.5, 1, 2, 4]); ax.set_xticklabels(["0.5", "1", "2", "4"]); ax.set_xlim(0.45, 4.6)
ax.xaxis.set_minor_formatter(matplotlib.ticker.NullFormatter())
ax.set_ylim(0.62, 1.22)
ax.set_xlabel("invariant mass of the lepton pair (TeV)"); ax.set_ylabel("ratio to the true Standard Model")
ax.legend(loc="lower left", fontsize=13)
fig.tight_layout(); fig.savefig(FIG / "3-2-absorb.svg"); plt.close(fig)
check("toy: mean absorbed shift reproduces the signal in the 2 TeV bin to within its error",
      abs((phi(xb) @ th_sm.mean(axis=0) - cstar*bvec(Mi))[7])/err_hi[7] < 0.5, 1.0)

# =================================================================================================
# 5. Pseudo-data and the finite-replica bootstrap (sections 7 and 9)
# =================================================================================================
# eq. (3.2.25): sigma_i (1 + lambda dL + r_i d_i) has covariance T_i T_j (dL^2 + delta_ij d_i^2), and chi2 averages to n
n = 12; T0 = 1000.0*(Mi/500.0)**-4.0; dL = 0.015
C = np.outer(T0, T0)*dL**2 + np.diag((T0*err_hi)**2)
P = T0*(1 + dL*rng.normal(size=(20000, 1)) + err_hi*rng.normal(size=(20000, n)))
Ci = np.linalg.inv(C); dv = P - T0
chi = np.einsum("ki,ij,kj->k", dv, Ci, dv)
check("pseudo-data: <chi2>/n = 1 with the covariance of eq. (3.2.25)", chi.mean()/n, 1.0, 4*chi.std()/np.sqrt(len(chi))/n + 1e-3)
check("pseudo-data: sample covariance element (0,1)", np.cov(P.T)[0, 1], C[0, 1], 0.08, rel=True)
check("statistical error of N events = 1/sqrt(N)", rng.poisson(900, 200000).std()/900, 1/30, 0.01, rel=True)
# bootstrap: the scatter of the replica mean under resampling is sigma/sqrt(N_rep)
Nrep = 100; reps = rng.normal(1.0, 0.05, size=Nrep)
boot = reps[rng.integers(0, Nrep, size=(10000, Nrep))].mean(axis=1)
check("bootstrap error of the mean of 100 replicas", boot.std(), reps.std()/np.sqrt(Nrep), 0.03, rel=True)

# ---- Figure 4: the bounds of Moore's Tables 3.4 and 3.5 (quoted numbers, 95% CL) ------------------
fig, axs = plt.subplots(1, 2, figsize=(8, 4.6))
rows = [("fixed PDFs", 0, GREY), ("with PDF error", 1, INK), ("simultaneous", 2, TEAL)]
for ax, T, unit, ttl in ((axs[0], T34, r"$\times10^{4}$", "current data"), (axs[1], T35, r"$\times10^{5}$", "HL-LHC projection")):
    for ip, (par, off) in enumerate((("W95", 0.0), ("Y95", -4.0))):
        for j, (lab, idx, col) in enumerate(rows):
            iv = T[par][idx]; y = off - j
            ax.plot(iv, [y, y], color=col, lw=5, solid_capstyle="butt")
            ax.plot([mid(iv)], [y], "o", color="white", ms=5, mec=col, mew=1.5)
    ax.axvline(0, color=ORANGE, lw=1.4, ls="--")
    ax.set_yticks([0, -1, -2, -4, -5, -6]); ax.set_ylim(-6.8, 1.6)
    ax.set_yticklabels([r[0] for r in rows]*2 if ax is axs[0] else [""]*6, fontsize=13)
    ax.text(0.03, 0.965, r"$\hat W$", transform=ax.transAxes, fontsize=15, va="top"); ax.text(0.03, 0.47, r"$\hat Y$", transform=ax.transAxes, fontsize=15, va="top")
    ax.set_xlabel(f"95% interval ({unit})"); ax.set_title(ttl, fontsize=14)
    ax.grid(axis="y", visible=False)
fig.tight_layout(); fig.savefig(FIG / "3-2-bounds.svg"); plt.close(fig)

print("wrote 3-2-growth.svg, 3-2-absorb.svg, 3-2-bounds.svg;", "ALL CHECKS PASS" if ok else "SOME CHECKS FAILED")
sys.exit(0 if ok else 1)
