#!/usr/bin/env python3
"""Numerical checks for guide chapter 1.6 (Beyond leading order), 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_1_6.py     (writes assets/guide/1-6-*.svg)"""
import pathlib, sys
import numpy as np
from scipy import integrate, optimize, special
import warnings
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt

CF, CA, TR = 4/3, 3.0, 0.5
warnings.filterwarnings("ignore", category=integrate.IntegrationWarning)   # end-point logarithms; accuracy is tested below
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}")

q = lambda f, a=0, b=1, **kw: integrate.quad(f, a, b, limit=400, epsabs=1e-13, epsrel=1e-12, **kw)[0]
SITE = pathlib.Path(__file__).resolve().parents[2]
FIG = SITE / "assets" / "guide"; FIG.mkdir(parents=True, exist_ok=True)
TEAL, ORANGE, INK, GRID = "#0e7c7b", "#d96c2c", "#16222e", "#ebe6da"
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})

# =================================================================================================
# 1. The running coupling (section 2, derivation D1) and scale variation (section 7)
# =================================================================================================
b_ = lambda nf: (33 - 2*nf)/(12*np.pi)
bp = lambda nf: (153 - 19*nf)/(2*np.pi*(33 - 2*nf))
MZ, MB, MC, Q0, AMZ = 91.2, 4.92, 1.51, 1.65, 0.118

def run_lo(a0, mu0, mu, nf):                       # eq. (1.6.2)
    return a0/(1 + a0*b_(nf)*np.log(mu**2/mu0**2))
def run_nlo(a0, mu0, mu, nf):                      # root of the implicit solution, eq. (1.6.3)
    b, c = b_(nf), bp(nf); t = np.log(mu**2/mu0**2)
    f = lambda a: 1/a - 1/a0 + c*np.log(a*(1 + c*a0)/(a0*(1 + c*a))) - b*t
    return optimize.brentq(f, 1e-3, 5.0, xtol=1e-15)
def run_ode(a0, mu0, mu, nf, two_loop=True):       # direct integration of the beta function
    b, c = b_(nf), bp(nf) if two_loop else 0.0
    s = integrate.solve_ivp(lambda t, a: -b*a*a*(1 + c*a), [np.log(mu0**2), np.log(mu**2)], [a0], rtol=1e-11, atol=1e-13)
    return s.y[0, -1]

check("b(nf=5) = 23/12pi", b_(5), 23/(12*np.pi)); check("b'(nf=5) = 29/23pi", bp(5), 29/(23*np.pi))
check("b'(nf=4) = 77/50pi", bp(4), 77/(50*np.pi))
check("LO closed form = ODE (MZ -> 5 GeV)", run_lo(AMZ, MZ, 5.0, 5), run_ode(AMZ, MZ, 5.0, 5, False), 1e-8)
check("NLO implicit solution = ODE (MZ -> 5 GeV)", run_nlo(AMZ, MZ, 5.0, 5), run_ode(AMZ, MZ, 5.0, 5), 1e-8)
# the integral behind eq. (1.6.3)
a1, a2, c5 = 0.11, 0.31, bp(5)
check("int da / a^2(1+b'a)", q(lambda a: 1/(a*a*(1 + c5*a)), a1, a2),
      1/a1 - 1/a2 + c5*np.log(a1*(1 + c5*a2)/(a2*(1 + c5*a1))))

def alpha(mu, order):
    """alpha_S(mu) from alpha_S(MZ)=0.118: nf=5 above m_b, nf=4 below, continuous at mu=m_b."""
    run = run_lo if order == 0 else run_nlo
    if mu >= MB: return run(AMZ, MZ, mu, 5)
    return run(run(AMZ, MZ, MB, 5), MB, mu, 4)
A_Q0 = {o: alpha(Q0, o) for o in (0, 1)}
A_MB = {o: alpha(MB, o) for o in (0, 1)}
print(f"INFO  alpha_S(m_b=4.92): LO {A_MB[0]:.4f}, NLO {A_MB[1]:.4f}")
print(f"INFO  alpha_S(Q0=1.65):  LO {A_Q0[0]:.4f}, NLO {A_Q0[1]:.4f};   nf=5 all the way: LO {run_lo(AMZ, MZ, Q0, 5):.4f}, NLO {run_nlo(AMZ, MZ, Q0, 5):.4f}")
check("alpha_S(Q0) LO, as quoted", A_Q0[0], 0.289, 2e-3); check("alpha_S(Q0) NLO, as quoted", A_Q0[1], 0.327, 2e-3)
check("alpha_S(m_b) LO, as quoted", A_MB[0], 0.204, 2e-3); check("alpha_S(m_b) NLO, as quoted", A_MB[1], 0.213, 2e-3)
# Lambda: LO definition alpha = 1/(b ln(Q^2/Lambda^2)), eq. (1.6.4)
Lam5 = MZ*np.exp(-1/(2*b_(5)*AMZ)); Lam4 = MB*np.exp(-1/(2*b_(4)*A_MB[0]))
print(f"INFO  LO Lambda(nf=5) = {1e3*Lam5:.1f} MeV, Lambda(nf=4) = {1e3*Lam4:.1f} MeV")
check("LO Lambda(5) in MeV, as quoted", 1e3*Lam5, 88, 1e-2); check("LO Lambda(4) in MeV, as quoted", 1e3*Lam4, 121, 1e-2)
check("1/(b ln(Q^2/Lambda^2)) reproduces LO running", 1/(b_(5)*np.log(30.0**2/Lam5**2)), run_lo(AMZ, MZ, 30.0, 5))
# NLO Lambda in the expanded convention  alpha = [1 - (b'/b) ln L / L] / (b L),  L = ln(Q^2/Lambda^2)
aexp = lambda L, nf: (1 - bp(nf)/b_(nf)*np.log(L)/L)/(b_(nf)*L)
L5 = optimize.brentq(lambda L: aexp(L, 5) - AMZ, 3, 40); Lam5n = MZ*np.exp(-L5/2)
print(f"INFO  NLO Lambda(nf=5), expanded convention = {1e3*Lam5n:.0f} MeV")
check("NLO Lambda(5) in MeV, as quoted", 1e3*Lam5n, 226, 1e-2)
# the expanded form satisfies the two-loop equation up to terms of relative order 1/L^2
for Q in (20.0, 1000.0):
    L = np.log(Q**2/Lam5n**2); print(f"INFO  expanded/exact two-loop coupling at Q={Q:g}: {aexp(L, 5)/run_nlo(AMZ, MZ, Q, 5):.4f}")

mus = np.logspace(np.log10(1.2), np.log10(2000), 300)
fig, ax = plt.subplots(figsize=(8, 4.6))
ax.plot(mus, [alpha(m, 0) for m in mus], color=ORANGE, lw=2.2, ls="--", label="one loop")
ax.plot(mus, [alpha(m, 1) for m in mus], color=TEAL, lw=2.4, label="two loops")
ax.plot([MZ], [AMZ], "o", color=INK, ms=7); ax.annotate(r"input: $\alpha_S(M_Z)=0.118$", (MZ, AMZ), (120, 0.2), fontsize=13,
                                                         arrowprops=dict(arrowstyle="-", color=INK, lw=1))
ax.axvline(Q0, color=INK, lw=1, ls=":"); ax.text(Q0*1.08, 0.415, r"$Q_0=1.65$ GeV", fontsize=13)
ax.axvline(MB, color="#8a8f96", lw=1, ls=":"); ax.text(MB*1.08, 0.37, r"$m_b$: $n_f=4\,|\,5$", fontsize=13, color="#5b6570")
ax.plot([Q0, Q0], [A_Q0[0], A_Q0[1]], "o", color=INK, ms=5)
ax.text(Q0*1.12, A_Q0[1] - 0.004, f"{A_Q0[1]:.3f}", fontsize=13, color=TEAL, va="center")
ax.annotate(f"{A_Q0[0]:.3f}", (Q0, A_Q0[0]), (2.3, 0.185), fontsize=13, color=ORANGE, va="center",
            arrowprops=dict(arrowstyle="-", color=ORANGE, lw=1))
ax.set_xscale("log"); ax.set_xlim(1.2, 2000); ax.set_ylim(0.05, 0.45)
ax.set_xlabel(r"scale $\mu$ (GeV)"); ax.set_ylabel(r"strong coupling $\alpha_S(\mu^2)$"); ax.legend(loc="upper right")
fig.tight_layout(); fig.savefig(FIG / "1-6-alphas.svg"); plt.close(fig)

# scale variation (section 6): the QCD correction to R(e+e-) at Q = MZ, nf = 5, mu in [Q/2, 2Q]
r1 = 1.411                                          # ESW chapter 3: K = 1 + a + 1.411 a^2 + ..., a = alpha_S/pi, nf = 5
dLO = lambda mu: alpha(mu, 1)/np.pi
dNLO = lambda mu: (lambda a: a*(1 + a*(r1 + np.pi*b_(5)*np.log(mu**2/MZ**2))))(alpha(mu, 1)/np.pi)
band = lambda f: (f(MZ/2) - f(2*MZ))
print(f"INFO  first-order values at mu = MZ/2 and 2 MZ: {dLO(MZ/2):.4f}, {dLO(2*MZ):.4f}")
print(f"INFO  second-order values at mu = MZ/2 and 2 MZ: {dNLO(MZ/2):.4f}, {dNLO(2*MZ):.4f}")
check("first-order value at MZ/2, as quoted", dLO(MZ/2), 0.0420, 2e-3, rel=True)
check("first-order value at 2 MZ, as quoted", dLO(2*MZ), 0.0340, 2e-3, rel=True)
check("second-order value at MZ/2, as quoted", dNLO(MZ/2), 0.0398, 2e-3, rel=True)
check("second-order value at 2 MZ, as quoted", dNLO(2*MZ), 0.0387, 2e-3, rel=True)
check("second-order value lies inside the first-order range", float(dLO(2*MZ) < dNLO(MZ) < dLO(MZ/2)), 1.0)
print(f"INFO  R correction at MZ: LO {dLO(MZ):.5f} spread {band(dLO):.5f};  NLO {dNLO(MZ):.5f} spread {band(dNLO):.5f}")
check("LO correction at mu=MZ, as quoted", dLO(MZ), 0.0376, 5e-3, rel=True)
check("LO scale spread, as quoted", band(dLO), 0.0079, 2e-2, rel=True)
check("NLO correction at mu=MZ, as quoted", dNLO(MZ), 0.0396, 5e-3, rel=True)
check("NLO scale spread, as quoted", band(dNLO), 0.0010, 0.06, rel=True)
# review: ESW's rounded coefficient 1.986 - 0.115 nf against the four-figure value 1.9857 - 0.1152 nf
check("R coefficient for nf=5 to four figures, as quoted", 1.9857 - 0.1152*5, 1.410, 5e-4)
_r1p = 1.9857 - 0.1152*5
_dNLOp = lambda mu: (lambda a: a*(1 + a*(_r1p + np.pi*b_(5)*np.log(mu**2/MZ**2))))(alpha(mu, 1)/np.pi)
check("second-order entries shift by about 2e-6 with the four-figure coefficient, as quoted",
      max(abs(_dNLOp(m) - dNLO(m)) for m in (MZ/2, MZ, 2*MZ)), 2e-6, 1e-6)
# the residual scale dependence is one order higher: halving alpha_S quarters the LO slope and divides the NLO slope by 8
def slopes(a0):
    aa = lambda mu: run_lo(a0, MZ, mu, 5)/np.pi     # one-loop running is exact for the NLO-truncated series
    lo = lambda mu: aa(mu); nlo = lambda mu: aa(mu)*(1 + aa(mu)*(r1 + np.pi*b_(5)*np.log(mu**2/MZ**2)))
    h = 1e-3; d = lambda f: (f(MZ*np.exp(h/2)) - f(MZ*np.exp(-h/2)))/(2*h)     # derivative in ln mu^2
    return d(lo), d(nlo)
s1, s2 = slopes(0.02), slopes(0.01)
check("d(LO)/dln mu^2 scales as alpha_S^2", s1[0]/s2[0], 4.0, 2e-2)
check("d(NLO)/dln mu^2 scales as alpha_S^3", s1[1]/s2[1], 8.0, 4e-2)
check("d(LO)/dln mu^2 = -pi b a^2", s2[0], -np.pi*b_(5)*(0.01/np.pi)**2, 1e-5, rel=True)

# =================================================================================================
# 2. Dirac algebra in four dimensions: the matrix elements used in sections 3, 7 and 8
# =================================================================================================
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]])]
g = [np.block([[I2, Z2], [Z2, -I2]])] + [np.block([[Z2, s], [-s, Z2]]) for s in sig]
met = np.diag([1., -1, -1, -1])
dot = lambda a, b: a @ met @ b
sl = lambda a: sum(g[m]*(met @ a)[m] for m in range(4))
gl = [sum(met[m, n]*g[n] for n in range(4)) for m in range(4)]      # gamma_mu (lower index)
E4 = np.eye(4)

# --- gamma* q -> q g (both diagrams), the projections in eqs. (1.6.9) and (1.6.17) ----------------------
def real_emission(Q2, z, v):
    shat = Q2*(1 - z)/z; rs = np.sqrt(shat); Ep = (shat + Q2)/(2*rs); ct = 1 - 2*v; st = np.sqrt(1 - ct*ct)
    p = np.array([Ep, 0, 0, Ep]); qv = np.array([rs - Ep, 0, 0, -Ep])
    r = rs/2*np.array([1, st, 0, ct]); l = rs/2*np.array([1, -st, 0, -ct])
    assert abs(dot(qv, qv) + Q2) < 1e-9*Q2 and abs(2*dot(r, p) - Q2*v/z) < 1e-9*Q2
    k = p - r; A = [[g[m] @ sl(k) @ g[a]/dot(k, k) + g[a] @ sl(l + r) @ g[m]/shat for a in range(4)] for m in range(4)]
    Ab = [[g[a] @ sl(k) @ g[m]/dot(k, k) + g[m] @ sl(l + r) @ g[a]/shat for a in range(4)] for m in range(4)]
    T = lambda m, n: sum(-met[a, a]*np.trace(sl(l) @ A[m][a] @ sl(p) @ Ab[n][a]).real for a in range(4))
    Sg = sum(-met[m, m]*T(m, m) for m in range(4))
    pl = met @ p; Spp = sum(pl[m]*pl[n]*T(m, n) for m in range(4) for n in range(4))
    return Sg, Spp
for Q2, z, v in [(10.0, 0.3, 0.2), (55.0, 0.72, 0.61)]:
    Sg, Spp = real_emission(Q2, z, v)
    check(f"-g projection of |M|^2, gamma* q -> q g (z={z}, v={v})", Sg, 8*(v/(1-z) + (1-z)/v + 2*z*(1-v)/(v*(1-z))), 1e-8)
    check(f"p p projection of |M|^2 (z={z}, v={v})", Spp, 4*Q2*(1-v)/z, 1e-8)
# lowest order in d dimensions: -g_{mu nu} gamma^mu pslash gamma^nu = (d-2) pslash, checked at d = 4
pt = np.array([3.0, 1.0, -2.0, 0.5])
check("gamma^mu pslash gamma_mu = -(d-2) pslash at d=4", np.abs(sum(g[m] @ sl(pt) @ gl[m] for m in range(4)) + 2*sl(pt)).max(), 0, 1e-12)

# --- q qbar -> l+ l- (derivation D7) ---------------------------------------------------------------
def dy_trace(ct):
    E = 7.0; st = np.sqrt(1 - ct*ct)
    p1 = E*np.array([1, 0, 0, 1]); p2 = E*np.array([1, 0, 0, -1]); k1 = E*np.array([1, st, 0, ct]); k2 = E*np.array([1, -st, 0, -ct])
    shat = 4*E*E
    return sum(met[m, m]*met[n, n]*np.trace(sl(p2) @ g[m] @ sl(p1) @ g[n]).real*np.trace(sl(k1) @ g[m] @ sl(k2) @ g[n]).real
               for m in range(4) for n in range(4))/(4*shat**2)
for ct in (0.3, -0.8):
    check(f"spin-averaged |M|^2/(e^4 e_q^2) = 1 + cos^2 theta (cos={ct})", dy_trace(ct), 1 + ct*ct, 1e-10)
check("angular integral: int dOmega (1+cos^2) = 16 pi/3", 2*np.pi*q(lambda c: 1 + c*c, -1, 1), 16*np.pi/3)
al = 1/137.036; sh = 50.0
check("sigma(qqbar->ll) = 4 pi alpha^2 e_q^2 / 3 shat (before colour)",
      (4*np.pi*al)**2*(16*np.pi/3)/(64*np.pi**2*sh), 4*np.pi*al**2/(3*sh))
# colour: average over 3x3 initial colours, only the 3 colour-anticolour-matched pairs annihilate
check("colour factor 1/Nc", sum(1 for i in range(3) for j in range(3) if i == j)/9, 1/3)

# --- gamma* g -> Q Qbar with a quark mass: the massive coefficient function, eq. (1.6.26) ----------
def C_massive(z, lam):
    """O(alpha_S) gluon coefficient function for F2 with quark mass m, lam = m^2/Q^2 (per quark or antiquark)."""
    v2 = 1 - 4*lam*z/(1 - z)
    if v2 <= 0: return 0.0
    v = np.sqrt(v2)
    return TR*((z*z + (1-z)**2 + 4*lam*z*(1 - 3*z) - 8*lam*lam*z*z)*np.log((1 + v)/(1 - v)) + (8*z*(1-z) - 1 - 4*lam*z*(1-z))*v)
Cg = lambda z: TR*((z*z + (1-z)**2)*np.log((1-z)/z) - 1 + 8*z*(1-z))        # eq. (1.6.21)
Pqg = lambda z: TR*(z*z + (1-z)**2)

def C_massive_direct(z, lam, Q2=9.0):
    """The same quantity from explicit Dirac traces and a numerical angular integral."""
    m = np.sqrt(lam*Q2); shat = Q2*(1 - z)/z; rs = np.sqrt(shat); Ep = (shat + Q2)/(2*rs); beta = np.sqrt(1 - 4*m*m/shat)
    p = np.array([Ep, 0, 0, Ep]); qv = np.array([rs - Ep, 0, 0, -Ep]); pl = met @ p
    def S(ct):
        st = np.sqrt(1 - ct*ct); pm = beta*rs/2
        p1 = np.array([rs/2, pm*st, 0, pm*ct]); p2 = np.array([rs/2, -pm*st, 0, -pm*ct])
        d1 = dot(p1 - qv, p1 - qv) - m*m; d2 = dot(p1 - p, p1 - p) - m*m
        N1 = sl(p1 - qv) + m*E4; N2 = sl(p1 - p) + m*E4
        A = [[g[mu] @ N1 @ g[a]/d1 + g[a] @ N2 @ g[mu]/d2 for a in range(4)] for mu in range(4)]
        Ab = [[g[a] @ N1 @ g[mu]/d1 + g[mu] @ N2 @ g[a]/d2 for a in range(4)] for mu in range(4)]
        T = lambda mu, nu: sum(-met[a, a]*np.trace((sl(p1) + m*E4) @ A[mu][a] @ (sl(p2) - m*E4) @ Ab[nu][a]).real for a in range(4))
        Sg = sum(-met[mu, mu]*T(mu, mu) for mu in range(4))
        Spp = sum(pl[mu]*pl[nu]*T(mu, nu) for mu in range(4) for nu in range(4))
        return Sg + 12*z*z/Q2*Spp
    avg = integrate.quad(S, -1, 1, limit=200, epsabs=1e-11, epsrel=1e-11)[0]/2
    return beta/32*avg
for z, lam in [(0.2, 0.05), (0.5, 0.1), (0.05, 1.0), (0.6, 0.004)]:
    check(f"massive gluon coefficient function from Dirac traces (z={z}, m^2/Q^2={lam})", C_massive_direct(z, lam), C_massive(z, lam), 1e-7)
for z in (0.1, 0.45, 0.8):
    lam = 1e-7
    check(f"massless limit: C_massive -> Pqg ln(Q^2/m^2) + Cg (z={z})", C_massive(z, lam), Pqg(z)*np.log(1/lam) + Cg(z), 1e-5)
check("threshold: z_max = 1/(1+4 m^2/Q^2)", C_massive(1/(1 + 4*0.3) + 1e-9, 0.3), 0.0)

# =================================================================================================
# 3. Dimensional regularisation (sections 3 and 4, derivations D2, D3, D4)
# =================================================================================================
G = special.gamma
# D2: solid angle of the unit sphere in d-2 = 2-2eps dimensions; phase-space prefactor at eps = 0
check("Omega(S^1) = 2 pi from 2 pi^(1-eps)/Gamma(1-eps) at eps=0", 2*np.pi**1/G(1.0), 2*np.pi)
check("Omega(S^2) = 4 pi from the same formula at eps=-1/2", 2*np.pi**1.5/G(1.5), 4*np.pi)
eps = -0.37
pref = lambda e: 1/(4*(2*np.pi)**(2 - 2*e))*0.5*(2*np.pi**(1 - e)/G(1 - e))*4**(-e)*2      # times (shat/4)^(-eps)
check("phase-space prefactor = (4 pi)^eps / (8 pi Gamma(1-eps))", pref(eps)*4**eps, (4*np.pi)**eps/(8*np.pi*G(1 - eps)))
# D4: the v integrals.  I(z,eps) = int dv [v(1-v)]^-eps { (1-eps)(v/(1-z) + (1-z)/v) + 2z(1-v)/(v(1-z)) + 2 eps }
def N_of(z, e):                                     # eq. (1.6.11)
    return -(1 - e)*(1 - z)**2/e + (1 - e)/(2*(1 - 2*e)) - 2*z*(1 - e)/(e*(1 - 2*e)) + 2*e*(1 - z)/(1 - 2*e)
for z, e in [(0.3, -0.37), (0.8, -0.11)]:
    I = q(lambda v: (v*(1 - v))**(-e)*((1 - e)*(v/(1 - z) + (1 - z)/v) + 2*z*(1 - v)/(v*(1 - z)) + 2*e))
    check(f"v integral = Gamma(1-eps)^2/Gamma(1-2eps) N/(1-z)  (z={z}, eps={e})", I, G(1 - e)**2/G(1 - 2*e)*N_of(z, e)/(1 - z), 1e-8)
# Laurent coefficients of N, eq. (1.6.12)
Nm1 = lambda z: -(1 + z*z); N0 = lambda z: z*z - 4*z + 1.5; N1 = lambda z: 2.5 - 6*z
for z in (0.25, 1.0):
    e = 1e-4
    check(f"N = N(-1)/eps + N(0) + eps N(1) (z={z})", N_of(z, e) - Nm1(z)/e - N0(z), e*N1(z), 1e-6)
check("N(-1)(1), N(0)(1), N(1)(1) = -2, -3/2, -7/2", Nm1(1) + 10*N0(1) + 100*N1(1), -2 - 15 - 350)

# D3: the distributional identity (1.6.13), tested against a smooth function at eps < 0 where everything converges
ftest = lambda z: np.exp(-z)*(1 + z**3) + 0.5*np.cos(3*z)
def lhs(e, f):                                      # int_0^1 z^eps (1-z)^(-1-eps) f(z), eps<0, via subtraction at z=1
    return q(lambda z: z**e*(1 - z)**(-1 - e)*(f(z) - f(1.0))) + f(1.0)*G(1 + e)*G(-e)
def rhs(e, f, order=1):
    plus0 = q(lambda z: (f(z) - f(1.0))/(1 - z))
    plus1 = q(lambda z: np.log(1 - z)*(f(z) - f(1.0))/(1 - z))
    lz = q(lambda z: np.log(z)/(1 - z)*f(z))
    return -f(1.0)/e + plus0 - e*(plus1 - lz)
check("int z^eps (1-z)^(-1-eps) dz = Gamma(1+eps)Gamma(-eps)", q(lambda z: z**-0.3*(1 - z)**-0.7), G(0.7)*G(0.3), 1e-7)
errs = [lhs(e, ftest) - rhs(e, ftest) for e in (-0.02, -0.01)]
check("identity (1.6.13): remainder is O(eps^2) (ratio of remainders at eps and eps/2)", errs[0]/errs[1], 4.0, 3e-2)
check("identity (1.6.13): remainder small at eps=-0.01", errs[1], 0.0, 2e-4)
check("int ln z/(1-z) = -pi^2/6", q(lambda z: np.log(z)/(1 - z)), -np.pi**2/6)
# the delta coefficient: B(1+eps,-eps) = -1/eps + O(eps), no constant term
e = -1e-4; check("Gamma(1+eps)Gamma(-eps) + 1/eps = O(eps)", G(1 + e)*G(-e) + 1/e, 0.0, 1e-3)

# D4: the real-emission Laurent expansion (1.6.14): poles and finite part against the exact integral
def real_exact(e, f):                               # int z^eps (1-z)^(-1-eps) N(z,eps) f(z)
    h = lambda z: N_of(z, e)*f(z)
    return q(lambda z: z**e*(1 - z)**(-1 - e)*(h(z) - h(1.0))) + h(1.0)*G(1 + e)*G(-e)
def real_series(e, f):
    plus = lambda w: q(lambda z: (w(z)*f(z) - w(1.0)*f(1.0))/(1 - z))
    fin = (3.5*f(1.0) + q(lambda z: (3 - z)*f(z)) - 1.5*plus(lambda z: 1.0)
           + q(lambda z: np.log(1 - z)*((1 + z*z)*f(z) - 2*f(1.0))/(1 - z)) - q(lambda z: (1 + z*z)*np.log(z)/(1 - z)*f(z)))
    return 2*f(1.0)/e**2 + (1.5*f(1.0) - plus(lambda z: 1 + z*z))/e + fin
errs = [real_exact(e, ftest) - real_series(e, ftest) for e in (-0.004, -0.002)]
check("real emission (1.6.14): remainder is O(eps)", errs[0]/errs[1], 2.0, 3e-2)
check("real emission (1.6.14): remainder small", errs[1], 0.0, 0.05)
# prefactor: Gamma(1-eps)/Gamma(1-2eps) (4 pi)^eps = 1 + eps (ln 4pi - gamma_E) + ...
e = 1e-5; check("c_eps expansion", (G(1 - e)/G(1 - 2*e)*(4*np.pi)**e - 1)/e, np.log(4*np.pi) - np.euler_gamma, 1e-4)
check("Gamma(1+eps)Gamma(1-eps) = 1 + pi^2 eps^2/6", (G(1 + 1e-3)*G(1 - 1e-3) - 1)/1e-6, np.pi**2/6, 1e-4)

# =================================================================================================
# 4. Coefficient functions (section 5)
# =================================================================================================
plus = lambda w, f: q(lambda z: (w(z)*f(z) - w(1.0)*f(1.0))/(1 - z))          # int [w/(1-z)]_+ ... with f
plusln = lambda w, f: q(lambda z: np.log(1 - z)*(w(z)*f(z) - w(1.0)*f(1.0))/(1 - z))
def Cq_on(f):                                       # int_0^1 C_q^MSbar(z) f(z) dz, eq. (1.6.20)
    return CF*(2*plusln(lambda z: 1.0, f) - 1.5*plus(lambda z: 1.0, f) - q(lambda z: (1 + z)*np.log(1 - z)*f(z))
               - q(lambda z: (1 + z*z)/(1 - z)*np.log(z)*f(z)) + q(lambda z: (3 + 2*z)*f(z)) - (np.pi**2/3 + 4.5)*f(1.0))
def T_on(f):                                        # the -g projection: R(z) of eq. (1.6.16)
    return CF*(plusln(lambda z: 1 + z*z, f) - 1.5*plus(lambda z: 1.0, f) - q(lambda z: (1 + z*z)/(1 - z)*np.log(z)*f(z))
               + q(lambda z: (3 - z)*f(z)) - (np.pi**2/3 + 4.5)*f(1.0))
check("C_q = (-g projection) + 3z C_F: the F_L term supplies 3 - z -> 3 + 2z", Cq_on(ftest), T_on(ftest) + CF*q(lambda z: 3*z*ftest(z)))
# Moore's compact form:  C_F [ (1+z^2)/(1-z) (ln((1-z)/z) - 3/4) + (9+5z)/4 ]_+
w = lambda z: (1 + z*z)/(1 - z)*(np.log((1 - z)/z) - 0.75) + (9 + 5*z)/4
check("compact plus form of C_q (Moore Eq. 1.79) on a test function", CF*q(lambda z: w(z)*(ftest(z) - ftest(1.0))), Cq_on(ftest), 1e-7)
one = lambda z: 1.0
check("int C_q^MSbar = 0 (quark number; fixes the delta term)", Cq_on(one), 0.0)
check("the same, from the virtual loop: 7/2 - 8 - pi^2/3 = -(9/2 + pi^2/3)", 3.5 - 8 - np.pi**2/3, -(4.5 + np.pi**2/3))
Cq2 = Cq_on(lambda z: z); Cg2 = q(lambda z: z*Cg(z)); CL2q = q(lambda z: z*2*CF*z); CL2g = q(lambda z: z*4*TR*z*(1 - z))
print(f"INFO  second moments: C_q(2) = {Cq2:.6f}, C_g(2) = {Cg2:.6f}, C_Lq(2) = {CL2q:.6f}, C_Lg(2) = {CL2g:.6f}")
check("C_q(N=2) = C_F/6 = 2/9", Cq2, CF/6); check("C_g(N=2) = -T_R/4 = -1/8", Cg2, -TR/4, 1e-7)
check("C_Lq(N=2) = 2 C_F/3, C_Lg(N=2) = T_R/3", CL2q + 10*CL2g, 2*CF/3 + 10*TR/3)
# worked number: the O(alpha_S) change of the second moment of a non-singlet F2 at Q0
print(f"INFO  alpha_S(Q0)/2pi * C_q(2) = {A_Q0[1]/(2*np.pi)*Cq2:.4f}")
check("alpha_S C_q(2)/2pi at Q0, as quoted", A_Q0[1]/(2*np.pi)*Cq2, 0.0116, 1e-2, rel=True)

# scheme change (D5), in moment space with numerical moments
def mom(N):
    return dict(cq=Cq_on(lambda z: z**(N - 1)), cg=q(lambda z: z**(N - 1)*Cg(z)),
                lq=q(lambda z: z**(N - 1)*2*CF*z), lg=q(lambda z: z**(N - 1)*4*TR*z*(1 - z)))
def scheme_gap(a, N=3.0, nf=4):
    """F_L moment computed from MS-bar distributions minus the same from DIS-scheme distributions (one charge set to 1)."""
    m = mom(N); S, g0 = 0.7, 1.3                    # arbitrary singlet and gluon moments (all quarks equal, e_q = 1)
    S_dis = S + a*(m["cq"]*S + 2*nf*m["cg"]*g0); g_dis = g0 - a*(m["cq"]*S + 2*nf*m["cg"]*g0)
    FL = lambda S_, g_: a*(m["lq"]*S_ + 2*nf*m["lg"]*g_)
    return FL(S, g0) - FL(S_dis, g_dis), (S + g0) - (S_dis + g_dis)
g1, mcons = scheme_gap(0.04); g2, _ = scheme_gap(0.02)
check("F_L in the two schemes differs at O(alpha_S^2): ratio for alpha and alpha/2", g1/g2, 4.0, 1e-9)
check("the DIS-scheme gluon keeps the total momentum", mcons, 0.0)
# non-singlet evolution in the DIS scheme: gamma^(1) shifts by -2 pi b C_q(N)
CQ3 = mom(3.0)["cq"]
def ns_shift(a0, N=3.0, nf=4):
    """Remainder of  d ln q_DIS/d ln mu^2 - [a gamma0 - 2 pi b a^2 C_q]  at coupling a = alpha_S/2pi = a0."""
    gam0 = CF*(1.5 + 1/(N*(N + 1)) - 2*(special.digamma(N + 1) + np.euler_gamma)); b = b_(nf)
    a = lambda t: a0/(1 + 2*np.pi*a0*b*t)             # one-loop running, t = ln mu^2/mu0^2
    lnq = lambda t: np.log(1 + a(t)*CQ3) + gam0/(2*np.pi*b)*np.log(a(0)/a(t))
    h = 1e-3
    return (lnq(h) - lnq(-h))/(2*h) - (a0*gam0 - 2*np.pi*b*a0**2*CQ3)
check("d ln q_DIS/d ln mu^2 = a gamma0 - 2 pi b a^2 C_q, remainder O(a^3)", ns_shift(0.02)/ns_shift(0.01), 8.0, 3e-2)
# Drell-Yan in the DIS scheme: delta coefficient 2pi^2/3 - 8 + 2(pi^2/3 + 9/2) = 1 + 4pi^2/3
check("DY delta term: MS-bar -> DIS gives 1 + 4 pi^2/3", 2*np.pi**2/3 - 8 + 2*(np.pi**2/3 + 4.5), 1 + 4*np.pi**2/3)
check("DY delta terms at alpha_S=0.2: -6% (MS-bar)", 0.2/(2*np.pi)*CF*(2*np.pi**2/3 - 8), -0.06, 0.03, rel=True)
check("DY delta terms at alpha_S=0.2: +60% (DIS)", 0.2/(2*np.pi)*CF*(1 + 4*np.pi**2/3), 0.60, 0.01, rel=True)
print(f"INFO  DIS-scheme DY: (alpha_S/2pi) C_F (1+4pi^2/3) at alpha_S=0.2: {0.2/(2*np.pi)*CF*(1 + 4*np.pi**2/3):.3f}")

# =================================================================================================
# 5. Heavy quarks (section 7): massive vs massless-limit charm structure function, toy gluon
# =================================================================================================
Ag = 1.7                                            # toy gluon  x g = Ag x^-0.2 (1-x)^5  (illustrative, not a fit)
xg = lambda x: Ag*x**-0.2*(1 - x)**5
ec2 = 4/9
def F2c(x, Q2, kind):
    lam = MC**2/Q2; aS = alpha(max(np.sqrt(Q2), 1.3), 1)
    if kind == "massive":
        zmax = 1/(1 + 4*lam); ker = lambda z: C_massive(z, lam)
    else:
        zmax = 1.0; ker = lambda z: Pqg(z)*np.log(1/lam) + Cg(z)
    # F2 = 2 e_c^2 (alpha_S/2pi) x int_x^zmax dz/z C(z) g(x/z) = ... int dz C(z) [x/z g(x/z)]
    return 2*ec2*aS/(2*np.pi)*integrate.quad(lambda z: ker(z)*xg(x/z), x, zmax, limit=300)[0]
xc = 0.01; Q2s = np.logspace(np.log10(3), 4, 60)
Fm = np.array([F2c(xc, Q2, "massive") for Q2 in Q2s]); F0 = np.array([F2c(xc, Q2, "massless") for Q2 in Q2s])
for Q2 in (5.0, 20.0, 100.0, 1e4):
    print(f"INFO  F2c toy at x=0.01, Q2={Q2:g}: massive {F2c(xc, Q2, 'massive'):.4f}, massless limit {F2c(xc, Q2, 'massless'):.4f}, ratio {F2c(xc, Q2, 'massive')/F2c(xc, Q2, 'massless'):.3f}")
check("massive/massless-limit at Q2=5 GeV2 (toy), as quoted", F2c(xc, 5.0, "massive")/F2c(xc, 5.0, "massless"), 0.64, 0.01)
check("massive/massless-limit at Q2=100 GeV2 (toy), as quoted", F2c(xc, 100.0, "massive")/F2c(xc, 100.0, "massless"), 0.93, 0.01)
check("massive/massless-limit at Q2=1e4 GeV2 (toy), as quoted", F2c(xc, 1e4, "massive")/F2c(xc, 1e4, "massless"), 1.00, 0.002)
fig, ax = plt.subplots(figsize=(8, 4.6))
ax.plot(Q2s, F0, color=ORANGE, lw=2.2, ls="--", label=r"massless limit $F^{(3,0)}$: logarithm and constant only")
ax.plot(Q2s, Fm, color=TEAL, lw=2.4, label=r"massive $F^{(3)}$: full dependence on $m_c$")
ax.fill_between(Q2s, Fm, F0, color=ORANGE, alpha=0.12, lw=0)
ax.annotate(r"terms of order $m_c^2/Q^2$", (9, 0.5*(np.interp(9, Q2s, Fm) + np.interp(9, Q2s, F0))), (25, 0.012), fontsize=13,
            arrowprops=dict(arrowstyle="-", color=INK, lw=1))
ax.axvline(MC**2, color=INK, lw=1, ls=":"); 
ax.set_xscale("log"); ax.set_xlim(3, 1e4); ax.set_ylim(0, None)
ax.set_xlabel(r"$Q^2$ (GeV$^2$)"); ax.set_ylabel(r"charm structure function $F_2^c$ at $x=0.01$")
ax.legend(loc="upper left"); ax.set_title("Illustrative: toy gluon, $O(\\alpha_S)$, $m_c=1.51$ GeV", fontsize=13, loc="right")
fig.tight_layout(); fig.savefig(FIG / "1-6-charm.svg"); plt.close(fig)

# =================================================================================================
# 6. Hadron colliders (section 8): Drell-Yan kinematics, luminosities, the x-Q2 map
# =================================================================================================
s = 13000.0**2
x12 = lambda M, y, s_=s: (M/np.sqrt(s_)*np.exp(y), M/np.sqrt(s_)*np.exp(-y))
x1, x2 = x12(91.2, 2.5); check("x1 x2 s = M^2", x1*x2*s, 91.2**2); check("y = (1/2) ln(x1/x2)", 0.5*np.log(x1/x2), 2.5)
# Jacobian d(x1,x2)/d(M^2,y) = 1/s
h = 1e-5; M2, y = 91.2**2, 1.3
X = lambda M2, y: np.array(x12(np.sqrt(M2), y))
J = np.column_stack([(X(M2*(1 + h), y) - X(M2*(1 - h), y))/(2*h*M2), (X(M2, y + h) - X(M2, y - h))/(2*h)])
check("Jacobian dx1 dx2 = dM^2 dy / s", abs(np.linalg.det(J))*s, 1.0, 1e-6)
# integrating d sigma/dM2 dy over y gives the luminosity form: int dy f(x1) h(x2) = int_tau^1 dx/x f(x) h(tau/x)
fq = lambda x: x**-0.5*(1 - x)**3; fb = lambda x: 0.3*x**-1.1*(1 - x)**7; tau = 0.004
ymax = 0.5*np.log(1/tau)
check("int dy q(x1) qbar(x2) = int dx/x q(x) qbar(tau/x)",
      q(lambda y: fq(np.sqrt(tau)*np.exp(y))*fb(np.sqrt(tau)*np.exp(-y)), -ymax, ymax), q(lambda x: fq(x)*fb(tau/x)/x, tau, 1), 1e-8)
# numbers quoted in the text (13 TeV)
for M, y in [(91.2, 0.0), (91.2, 2.5), (91.2, 4.5), (80.4, 0.0), (345.0, 0.0), (10.0, 0.0), (10.0, 4.5), (2000.0, 0.0)]:
    a, b = x12(M, y); print(f"INFO  13 TeV: M={M:g} GeV, y={y:g}:  x1={a:.3g}, x2={b:.3g}")
check("x at M_Z, y=0, 13 TeV, as quoted", x12(91.2, 0)[0], 0.0070, 5e-3, rel=True)
check("x1 at M_Z, y=2.5, as quoted", x12(91.2, 2.5)[0], 0.085, 1e-2, rel=True); check("x2 at M_Z, y=2.5, as quoted", x12(91.2, 2.5)[1], 5.8e-4, 1e-2, rel=True)
check("x1 at M_Z, y=4.5, as quoted", x12(91.2, 4.5)[0], 0.63, 1e-2, rel=True); check("x2 at M_Z, y=4.5, as quoted", x12(91.2, 4.5)[1], 7.8e-5, 1e-2, rel=True)
check("x at 2 m_t = 345 GeV, y=0, as quoted", x12(345.0, 0)[0], 0.027, 2e-2, rel=True)
# DIS reach at the Q2 cut of our fits (Q2 > 3.49 GeV2): x > Q2/s
check("HERA reach at Q2=3.49: x ~ 3e-5, as quoted", 3.49/318.0**2, 3e-5, 0.2, rel=True)
check("fixed-target reach at Q2=3.49, 280 GeV beam: x ~ 0.007, as quoted", 3.49/(2*0.938*280), 0.007, 0.06, rel=True)
check("Q2 at the Z: 8e3 GeV2, as quoted", 91.2**2, 8e3, 0.05, rel=True)
# Drell-Yan prefactor in conventional units at M = 10 GeV... (kept dimensionless here): 4 pi alpha^2 / 9 = sigma0/Nc * M^2
check("4 pi alpha^2/(3 Nc) = 4 pi alpha^2/9", 4*np.pi*al**2/(3*3), 4*np.pi*al**2/9)
# W charge asymmetry at central rapidity, LO, toy inputs: A = (u dbar - d ubar)/(u dbar + d ubar) -> (u-d)/(u+d) when ubar = dbar
u, d, sea = 0.62, 0.35, 0.20
check("A_W(y=0) with ubar=dbar reduces to (u-d)/(u+d)", (u*sea - d*sea)/(u*sea + d*sea), (u - d)/(u + d))

fig, ax = plt.subplots(figsize=(8, 5.0))
xs = np.logspace(-6, 0, 200)
ax.fill_between(xs, 0.5, np.maximum(xs*318.0**2, 0.5), color=TEAL, alpha=0.16, lw=0)
ax.fill_between(xs, 0.5, np.maximum(xs*2*0.938*280, 0.5), color=ORANGE, alpha=0.30, lw=0)
ax.text(3.7e-3, 8.5, "HERA", fontsize=14, color="#0a5857"); ax.text(0.03, 0.9, "fixed-target DIS", fontsize=13, color="#9c4a17")
Ms = np.logspace(0, np.log10(13000), 200)
for y, ls in [(0, "-"), (2, "--"), (4, ":")]:
    for sgn in ((1, -1) if y else (1,)):
        xx = Ms/13000*np.exp(sgn*y); ok_ = xx <= 1
        ax.plot(xx[ok_], Ms[ok_]**2, color=INK, lw=1.8, ls=ls, label=(f"LHC 13 TeV, $|y|={y}$" if sgn == 1 else None))
for M, lab in [(91.2, "$M_Z$"), (345.0, "$2m_t$"), (10.0, "10 GeV")]:
    a = M/13000; xx = np.logspace(np.log10(a*np.exp(-4.5)), np.log10(min(1, a*np.exp(4.5))), 50)
    ax.plot(xx, 0*xx + M*M, color=ORANGE, lw=2.6, solid_capstyle="butt")
    ax.text(a*np.exp(-4.5)*0.75, M*M, lab, fontsize=13, color="#9c4a17", ha="right", va="center")
ax.axhline(Q0**2, color=INK, lw=1, ls=":"); ax.text(1.3e-6, Q0**2*1.5, "$Q_0^2$", fontsize=13)
ax.set_xscale("log"); ax.set_yscale("log"); ax.set_xlim(1e-6, 1); ax.set_ylim(0.5, 3e8)
ax.set_xlabel("momentum fraction $x$"); ax.set_ylabel("scale $Q^2$ or $M^2$ (GeV$^2$)")
ax.legend(loc="upper left", fontsize=13)
fig.tight_layout(); fig.savefig(FIG / "1-6-kinematics.svg"); plt.close(fig)

print("wrote 1-6-alphas.svg, 1-6-charm.svg, 1-6-kinematics.svg;", "ALL CHECKS PASS" if ok else "SOME CHECKS FAILED")
sys.exit(0 if ok else 1)
