#!/usr/bin/env python3
"""Numerical checks for guide chapter 3.3 (large x, small x, lattice, machine learning, tools), and its three 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_3.py     (writes assets/guide/3-3-*.svg)"""
import pathlib, sys
import numpy as np
from scipy import integrate, special, optimize
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt

CF, CA = 4/3, 3.0
M = 0.938                                             # proton mass in GeV
ok = True
def check(name, got, want, tol=1e-6):
    global ok
    good = abs(got - want) <= tol * 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-12, epsrel=1e-12, **kw)[0]
ASSETS = pathlib.Path(__file__).resolve().parents[2] / "assets" / "guide"
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, "svg.fonttype": "none", "font.family": "sans-serif"})
def style(ax):
    ax.grid(True, color=GRID, lw=1); ax.set_axisbelow(True)
    for s in ("top", "right"): ax.spines[s].set_visible(False)

# ================= D1: a massless parton in a massive target ======================================
met = np.diag([1., -1, -1, -1]); dot = lambda a, b: a @ met @ b
rr = lambda x, Q2: np.sqrt(1 + 4*x*x*M*M/Q2)
xiN = lambda x, Q2: 2*x/(1 + rr(x, Q2))
Pl = 7.0
p = np.array([Pl, 0, 0, Pl]); n = np.array([1/(2*Pl), 0, 0, -1/(2*Pl)])
P = p + 0.5*M*M*n
check("P^2 = M^2", dot(P, P), M*M)
toyq = lambda z: z**-0.5*(1-z)**3                      # toy quark density (illustrative), charge factor dropped
for x, Q2 in [(0.3, 4.0), (0.62, 7.5), (0.85, 3.0)]:
    xi = xiN(x, Q2); r = rr(x, Q2)
    qv = -xi*p + Q2/(2*xi)*n                           # eq. (3.3.3): collinear frame, q = -xi p + (Q^2/2xi) n
    nu = dot(P, qv)
    check(f"q^2 = -Q^2 (x={x})", dot(qv, qv), -Q2)
    check(f"x = Q^2/2nu reproduces the input (x={x})", Q2/(2*nu), x)
    check(f"xi^2 M^2 + 2 nu xi - Q^2 = 0 (x={x})", xi*xi*M*M + 2*nu*xi - Q2, 0, 1e-9)
    k = xi*p; kp = k + qv
    check(f"struck quark on shell (x={x})", dot(kp, kp), 0, 1e-9)
    check(f"1 + xi^2M^2/Q^2 = xi r/x (x={x})", 1 + xi*xi*M*M/Q2, xi*r/x)
    # parton-model hadronic tensor, derivation D1: W = q(xi)/(4 xi p.q) * w,  w = 2[k k' + k' k - g k.k'] (upper indices)
    w = 2*(np.outer(k, kp) + np.outer(kp, k) - met*dot(k, kp))
    W = toyq(xi)/(4*xi*dot(p, qv))*w
    # project F1, F2 out of the tensor decomposition of chapter 1.1, section 6:  g.W = -3F1 + Phat^2 F2/nu ;  P.W.P = -Phat^2 F1 + Phat^4 F2/nu
    Ph2 = M*M + nu*nu/Q2
    gW = np.sum(met*W); PWP = (met@P) @ W @ (met@P)
    F1 = (PWP/Ph2 - gW)/2; F2 = nu*(PWP/Ph2 + F1)/Ph2
    check(f"current conservation q.W = 0 (x={x})", np.abs((met@qv) @ W).max(), 0, 1e-9)
    check(f"F1 = q(xi)/2 (x={x})", F1, toyq(xi)/2, 1e-9)
    check(f"F2 = x/(xi r^2) * xi q(xi) (x={x})", F2, x/(xi*r*r)*xi*toyq(xi), 1e-9)
    check(f"F_L = r^2 F2 - 2x F1 = 0 (x={x})", r*r*F2 - 2*x*F1, 0, 1e-9)
check("xi at x=0.3, Q2=4: 2 per cent below x", xiN(0.3, 4.0)/0.3, 0.9809, 2e-4)
check("xi = x(1 - x^2M^2/Q^2) to first order", xiN(0.1, 50.0), 0.1*(1 - 0.01*M*M/50), 1e-7)
xi1 = xiN(1.0, 4.0)
check("xi at the elastic point x=1, Q2=4", xi1, 0.8435, 2e-4)
W2 = lambda x, Q2: M*M + Q2*(1-x)/x
Q2min = lambda x, W2cut=12.5: (W2cut - M*M)*x/(1-x)
F20 = lambda z: np.where(z < 1, z**0.5*np.clip(1-z, 0, None)**3, 0.0)          # toy valence-like x q(x)
tmr = lambda x, Q2: x/(xiN(x, Q2)*rr(x, Q2)**2)*F20(xiN(x, Q2))/F20(x)
print("INFO  target-mass ratio F2(TM)/F2(M=0), toy shape x^0.5 (1-x)^3:")
tab = {}
for x in (0.3, 0.5, 0.7, 0.75):
    tab[x] = (tmr(x, 3.49), Q2min(x), tmr(x, Q2min(x)), W2(x, 3.49))
    print(f"INFO    x={x}: at Q2=3.49 ratio {tab[x][0]:.3f} (W2={tab[x][3]:.2f}); W2 cut needs Q2>{tab[x][1]:.1f}, ratio there {tab[x][2]:.3f}")
check("Q2 needed at x=0.75 for W2=12.5", Q2min(0.75), 34.86, 1e-3)
check("ratio at x=0.5, Q2=3.49", tab[0.5][0], 0.968, 1e-3)
check("ratio at x=0.7, Q2=3.49", tab[0.7][0], 1.324, 1e-3)
check("ratio at x=0.75, Q2=3.49", tab[0.75][0], 1.613, 1e-3)
check("ratio at x=0.5 on the W2 cut", tab[0.5][2], 0.991, 1e-3)
check("ratio at x=0.7 on the W2 cut", tab[0.7][2], 1.053, 1e-3)
check("ratio at x=0.75 on the W2 cut", tab[0.75][2], 1.076, 1e-3)
check("Q2 needed at x=0.7 for W2=12.5", Q2min(0.7), 27.11, 1e-3)
check("W2 at x=0.7, Q2=3.49", W2(0.7, 3.49), 2.376, 1e-3)

fig, ax = plt.subplots(figsize=(8, 4.6)); style(ax)
xs = np.linspace(0.05, 0.9, 600)
for Q2, col, lab, dx, dy in [(3.49, ORANGE, "Q² = 3.49 GeV²", 0, -0.075), (10.0, TEAL, "10 GeV²", 0, 0.045), (30.0, INK, "30 GeV²", 0.075, -0.105)]:
    y = tmr(xs, Q2); keep = W2(xs, Q2) >= 12.5
    ax.plot(xs[~keep], y[~keep], color=col, lw=1.8, ls=(0, (2, 2)))
    ax.plot(xs[keep], y[keep], color=col, lw=3.2)
    xe = xs[keep][-1]; ax.plot([xe], [tmr(xe, Q2)], "o", color=col, ms=9, zorder=5)
    ax.text(xe + dx, tmr(xe, Q2) + dy, lab, color=col, ha="center", va="center")
ax.text(0.07, 1.66, "solid: kept by the cut W² > 12.5 GeV²\ndotted: removed by it", color=INK, va="top")
ax.axhline(1, color=INK, lw=0.8)
ax.set_ylim(0.85, 1.7); ax.set_xlim(0.05, 0.92)
ax.set_xlabel("Bjorken x"); ax.set_ylabel("F₂ with target mass / F₂ without")
fig.tight_layout(); fig.savefig(ASSETS / "3-3-targetmass.svg", facecolor="white"); plt.close(fig)

# ================= D2: neutron/proton ratio, d/u, and the deuteron correction =====================
R_of = lambda t: (1 + 4*t)/(4 + t)                     # t = d/u, valence only
t_of = lambda R: (4*R - 1)/(4 - R)
for t in (0.0, 0.2, 0.5, 1.7):
    check(f"d/u -> R -> d/u round trip (d/u={t})", t_of(R_of(t)), t)
check("R(d/u=0) = 1/4", R_of(0), 0.25); check("R(d/u=1/2) = 2/3", R_of(0.5), 2/3)
h = 1e-6
for t in (0.1, 0.2, 0.5):
    R = R_of(t)
    check(f"d(d/u)/dR = 15/(4-R)^2 (d/u={t})", (t_of(R+h) - t_of(R-h))/(2*h), 15/(4-R)**2, 1e-6)
    # F2d = c (F2p+F2n)/2  =>  R = 2 F2d/(c F2p) - 1 ; shift c by a relative eps at fixed data
    c, eps = 0.98, 1e-6; F2p = 1.0; F2d = c*(1+R)/2
    Rs = 2*F2d/(c*(1+eps)*F2p) - 1
    amp = (t_of(Rs) - t)/t/eps
    want = -15*(1+R)/((4-R)**2*t)
    check(f"amplification of a deuteron correction (d/u={t})", amp, want, 1e-4)
    print(f"INFO  d/u={t}: R={R:.4f}, relative change in d/u per unit relative change in c = {want:.2f}")
check("amplification at d/u=0.2 is 8.4", 15*(1+R_of(0.2))/((4-R_of(0.2))**2*0.2), 8.4, 1e-3)
check("amplification at d/u=0.1 is 15.0", 15*(1+R_of(0.1))/((4-R_of(0.1))**2*0.1), 15.03, 1e-3)

# ================= D3: moments of the threshold logarithms ========================================
S1 = lambda N: special.digamma(N+1) + np.euler_gamma
S2 = lambda N: np.pi**2/6 - special.polygamma(1, N+1)
for N in (2, 5.5, 20):
    m1 = q(lambda z: (z**(N-1) - 1)/(1-z))
    m2 = q(lambda z: (z**(N-1) - 1)*np.log(1-z)/(1-z))
    check(f"moment of [1/(1-z)]_+ = -S1(N-1) (N={N})", m1, -S1(N-1), 1e-8)
    check(f"moment of [ln(1-z)/(1-z)]_+ = (S1^2+S2)/2 (N={N})", m2, 0.5*(S1(N-1)**2 + S2(N-1)), 1e-7)
def CqN(N):
    """N-th moment of the MS-bar quark coefficient function of chapter 1.6, section 5, in units of alpha_S/2pi."""
    reg = q(lambda z: z**(N-1)*(-(1+z)*np.log(1-z) - (1+z*z)/(1-z)*np.log(z) + 3 + 2*z))
    return CF*(2*0.5*(S1(N-1)**2 + S2(N-1)) + 1.5*S1(N-1) + reg - (np.pi**2/3 + 4.5))
Lb = lambda N: np.log(N) + np.euler_gamma
lead = lambda N: CF*(Lb(N)**2 + 1.5*Lb(N))                 # the logarithms of eq. (3.3.13)
check("C_q(N=1) = 0 (quark number)", CqN(1.0), 0, 1e-8)
const = CqN(4000.0) - lead(4000.0)
check("constant left after the logarithms: -CF(9/2 + pi^2/6)", const, -CF*(4.5 + np.pi**2/6), 3e-3)
aS = 0.2
for N in (5, 10, 20):
    print(f"INFO  alpha_S=0.2, N={N}: (aS/2pi) Cq(N) = {aS/(2*np.pi)*CqN(N):.3f}; "
          f"double log alone (aS/2pi) CF ln^2(N e^gamma) = {aS/(2*np.pi)*CF*Lb(N)**2:.3f}")
check("NLO coefficient correction at N=10, alpha_S=0.2", aS/(2*np.pi)*CqN(10), 0.307, 5e-3)
check("NLO coefficient correction at N=20, alpha_S=0.2", aS/(2*np.pi)*CqN(20), 0.527, 5e-3)
check("double logarithm at N=20, alpha_S=0.2", aS/(2*np.pi)*CF*Lb(20)**2, 0.542, 5e-3)

# ================= D4: the leading-log-x anomalous dimension ======================================
psi = special.digamma
chi = lambda g: 2*psi(1) - psi(g) - psi(1-g)
z3, z5, z7 = special.zeta(3), special.zeta(5), special.zeta(7)
check("chi(1/2) = 4 ln 2", chi(0.5), 4*np.log(2))
for g in (0.05, 0.1):
    check(f"chi = 1/g + 2 z3 g^2 + 2 z5 g^4 + 2 z7 g^6 (g={g})", chi(g), 1/g + 2*z3*g*g + 2*z5*g**4 + 2*z7*g**6, 1e-7)
check("ESW 4.218: chi = int du/(1-u) (u^(g-1)+u^(-g)-2)", q(lambda u: (u**(0.3-1) + u**(-0.3) - 2)/(1-u)), chi(0.3), 1e-7)
# Lagrange inversion of gamma = t * phi(gamma), phi = gamma*chi(gamma) = 1 + 2 z3 g^3 + 2 z5 g^5 + 2 z7 g^7 + ...
z9 = special.zeta(9); z11 = special.zeta(11)
phi = np.zeros(13); phi[0] = 1; phi[3] = 2*z3; phi[5] = 2*z5; phi[7] = 2*z7; phi[9] = 2*z9; phi[11] = 2*z11
coef = [0.0]
for nn in range(1, 13):
    pw = np.array([1.0])
    for _ in range(nn): pw = np.convolve(pw, phi)[:13]
    coef.append(pw[nn-1]/nn)
check("c1 = 1", coef[1], 1); check("c2 = 0", coef[2], 0); check("c3 = 0", coef[3], 0)
check("c4 = 2 zeta(3)", coef[4], 2*z3); check("c5 = 0", coef[5], 0)
check("c6 = 2 zeta(5)", coef[6], 2*z5); check("c7 = 12 zeta(3)^2", coef[7], 12*z3*z3)
A33 = coef[4]*(2*CA)**4/6
check("A_3^(3) = 2 zeta(3) (2CA)^4/3! = 519.3 (ESW 4.188 prints 518.4)", A33, 519.3, 1e-4)
check("ESW's printed 518.4 = 432 x 1.2 exactly (zeta(3) = 1.2021 rounded to 1.2 would give it)", 518.4/((2*3)**4/3), 1.2, 1e-12)
check("relative difference between 519.3 and 518.4 = 1 - 1.2/zeta(3) = 0.17%", 1 - 518.4/A33, 1 - 1.2/z3, 1e-12)
ab = 0.2                                                # alpha-bar = CA alpha_S/pi, i.e. alpha_S = 0.209
gam_exact = lambda w: optimize.brentq(lambda g: ab*chi(g) - w, 1e-9, 0.5)
series = lambda w, nmax: sum(coef[k]*(ab/w)**k for k in range(1, nmax+1))
check("series reproduces the exact root at N-1 = 2.0", series(2.0, 12), gam_exact(2.0), 1e-9)
lam = ab*4*np.log(2)
check("lambda = 4 ln2 alpha-bar = 0.5545 for alpha-bar = 0.2", lam, 0.5545, 1e-4)
check("ESW 4.189: 12 ln2 alpha_S/pi = 0.5 at alpha_S = 0.19", 12*np.log(2)*0.19/np.pi, 0.5, 6e-3)
check("gamma at the branch point = 1/2", gam_exact(lam*(1+1e-10)), 0.5, 1e-3)
# Mellin transform of ln^k(1/x)/(k! x):   int_0^1 dx x^(N-1) * (1/x) ln^k(1/x)/k! = 1/(N-1)^(k+1)
for k, N in [(0, 1.7), (3, 1.4)]:
    val = q(lambda L: np.exp(-(N-1)*L)*L**k/special.factorial(k), 0, np.inf)
    check(f"Mellin transform of ln^{k}(1/x)/({k}! x) = 1/(N-1)^{k+1}", val, 1/(N-1)**(k+1), 1e-8)
# size of successive terms of x P_gg (leading logs only) at x = 1e-4
L = np.log(1e4); terms = {k: coef[k]*(ab*L)**(k-1)/special.factorial(k-1) for k in (1, 4, 6, 7)}
print("INFO  LLx terms of x P_gg / alpha-bar at x=1e-4, alpha-bar=0.2:", {k: round(float(v), 3) for k, v in terms.items()})
check("alpha-bar ln(1/x) at x=1e-4", ab*L, 1.842, 1e-3)
check("fourth-order term relative to the first at x=1e-4", terms[4], 2.50, 5e-3)
check("forward kinematics: (5/13000) e^-4.5", 5/13000*np.exp(-4.5), 4.27e-6, 5e-3)
check("double-asymptotic-scaling slope 2 gamma = 12/sqrt(33-2nf) = 2.4 for nf=4", 12/np.sqrt(33-8), 2.4)
check("gamma^2 = N/(pi b), N=3, nf=4", 3/(np.pi*(33-8)/(12*np.pi)), 1.2**2)
# saturation estimate, ESW (4.228)
Rp = 5.0; check("pi R^2 for R = 5 GeV^-1", np.pi*Rp**2, 78.54, 1e-4)
check("x g needed at mu2 = 4 GeV2, alpha_S = 0.3", np.pi*Rp**2*4/0.3, 1047, 1e-3)

fig, ax = plt.subplots(figsize=(8, 4.6)); style(ax)
ws = np.linspace(lam*1.0005, 1.6, 500)
ax.plot(ws, [gam_exact(w) for w in ws], color=INK, lw=3, label="all orders (leading logarithms)")
wt = np.linspace(0.3, 1.6, 400)
ax.plot(wt, series(wt, 1), color=TEAL, lw=2.4, label="first order")
ax.plot(wt, series(wt, 4), color=ORANGE, lw=2.4, label="through fourth order")
ax.plot(wt, series(wt, 7), color=ORANGE, lw=2.0, ls=(0, (5, 3)), label="through seventh order")
ax.axvline(lam, color=INK, lw=1, ls=":"); ax.plot([lam], [0.5], "o", color=INK, ms=8)
ax.text(lam + 0.02, 0.06, "N − 1 = λ = 0.55", color=INK)
ax.text(lam + 0.03, 0.515, "branch point, γ = ½", color=INK, va="bottom")
ax.set_ylim(0, 0.8); ax.set_xlim(0.3, 1.6)
ax.set_xlabel("moment variable N − 1"); ax.set_ylabel("gluon anomalous dimension γ")
ax.legend(frameon=False, loc="upper right", fontsize=13)
fig.tight_layout(); fig.savefig(ASSETS / "3-3-smallx.svg", facecolor="white"); plt.close(fig)
check("fourth-order truncation at N-1 = lambda", series(lam, 4), 0.401, 3e-3)
check("first-order truncation at N-1 = lambda", series(lam, 1), 1/(4*np.log(2)), 1e-9)

# ================= D5: lattice, the reach in Ioffe time ===========================================
GEVFM = 5.0677                                         # 1 fm = 5.0677 GeV^-1
numax = lambda Pz, zmax_fm: Pz*zmax_fm*GEVFM
check("nu_max for Pz = 2.6 GeV, z_max = 1 fm", numax(2.6, 1.0), 13.18, 1e-3)
check("nu_max for Pz = 1.4 GeV, z_max = 1 fm", numax(1.4, 1.0), 7.09, 1e-3)
Aq = 1/special.beta(0.5, 4.0)
qt = lambda x: Aq*x**-0.5*(1-x)**3                      # toy isovector-like density, unit normalised (illustrative)
# Ioffe-time distribution and its exact first two Taylor coefficients (moments)
Mio = lambda nu: (integrate.quad(lambda x: qt(x)*np.cos(nu*x), 0, 1, limit=400)[0]
                  - 1j*integrate.quad(lambda x: qt(x)*np.sin(nu*x), 0, 1, limit=400)[0])     # M(nu,0) = int dx e^{-i nu x} q(x)
m1 = special.beta(1.5, 4.0)/special.beta(0.5, 4.0); m2 = special.beta(2.5, 4.0)/special.beta(0.5, 4.0)
hh = 1e-3
check("M(0) = first moment = 1", Mio(0).real, 1.0, 1e-8)
check("dM/dnu at 0 = -i <x>", ((Mio(hh) - Mio(-hh))/(2*hh)).imag, -m1, 1e-5)
check("d2M/dnu2 at 0 = -<x^2>", ((Mio(hh) + Mio(-hh) - 2*Mio(0))/hh**2).real, -m2, 1e-4)
def qrec(x, nm):
    """Inverse transform cut off at |nu| < nm: the density folded with sin(nm(x-x'))/(pi(x-x'))."""
    f = lambda xp: qt(xp)*nm/np.pi*np.sinc(nm*(x-xp)/np.pi)
    return integrate.quad(f, 0, 1, limit=2000, points=[x])[0]
check("resolution pi/nu_max at nu_max = 13.2", np.pi/13.2, 0.238, 2e-3)
trunc = integrate.quad(lambda nu: (np.exp(0.3j*nu)*Mio(nu)).real, -13.2, 13.2, limit=200)[0]/(2*np.pi)
check("cut-off Fourier integral = density folded with the sinc kernel (x=0.3, nu_max=13.2)", trunc, qrec(0.3, 13.2), 1e-6)
big = integrate.quad(lambda x: qrec(x, 400.0), 0.2, 0.4, limit=200)[0]/integrate.quad(qt, 0.2, 0.4)[0]
check("inversion converges as nu_max grows (integral over 0.2<x<0.4, nu_max=400)", big, 1.0, 1e-2)

# ================= D6: the interpolation grid =====================================================
ymap = lambda x: np.log(1/x) + 5*(1-x)                 # a node-spacing variable (our illustrative choice)
def xof(y):
    return optimize.brentq(lambda x: ymap(x) - y, 1e-12, 1.0)
def lagrange_weights(xm, nodes_y, deg=3):
    """For each sample x_m: indices of the deg+1 nearest nodes and the Lagrange weights E_i(x_m) in y."""
    y = ymap(xm); hstep = nodes_y[1] - nodes_y[0]
    i0 = np.clip(np.floor((y - nodes_y[0])/hstep).astype(int) - (deg-1)//2, 0, len(nodes_y) - deg - 1)
    idx = i0[:, None] + np.arange(deg+1)[None, :]
    yy = nodes_y[idx]; wts = np.ones_like(yy)
    for a in range(deg+1):
        for b in range(deg+1):
            if a != b: wts[:, a] *= (y - yy[:, b])/(yy[:, a] - yy[:, b])
    return idx, wts
rng = np.random.default_rng(33)
xmin = 1e-3
Msamp = 200000
ym = rng.uniform(ymap(1.0), ymap(xmin), Msamp)         # "events": sampled flat in y
xm = np.array([xof(v) for v in ym[:4000]])             # exact inversion is slow; tabulate and interpolate for the rest
ytab = np.linspace(ymap(1.0), ymap(xmin), 20001); xtab = np.array([xof(v) for v in ytab])
xm = np.interp(ym, ytab, xtab)
jac = 1/(1/xm + 5)                                     # dx/dy
sig = lambda x: np.exp(-0.5*((np.log(x) + 2.5)/0.9)**2)*(1 + 3*x)       # toy hard cross-section (illustrative)
wm = (ymap(xmin) - ymap(1.0))/Msamp*jac*sig(xm)        # Monte Carlo weight times cross-section for each event
pdfs = {"A": lambda x: x**-1.2*(1-x)**3, "B": lambda x: x**-0.6*(1-x)**5*(1 + 4*x)}
direct = {k: np.sum(wm*f(xm)) for k, f in pdfs.items()}
exact = {k: q(lambda x: sig(x)*f(x), xmin, 1) for k, f in pdfs.items()}
print("INFO  Monte Carlo against quadrature (statistical, not interpolation): "
      + ", ".join(f"{k}: {direct[k]/exact[k]-1:+.2e}" for k in pdfs))
errs = {}
for nn in (10, 15, 20, 30, 50, 80):
    ny = np.linspace(ymap(1.0), ymap(xmin), nn); nx = np.array([xof(v) for v in ny]); nx[0] = 1.0
    idx, wts = lagrange_weights(xm, ny)
    check(f"interpolating functions sum to one ({nn} nodes)", np.abs(wts.sum(1) - 1).max(), 0, 1e-10)
    grid = np.zeros(nn); np.add.at(grid, idx, wts*wm[:, None])          # eq. (3.3.31): fill once
    errs[nn] = {k: abs(np.dot(grid, f(nx))/direct[k] - 1) for k, f in pdfs.items()}   # eq. (3.3.30): reuse
    print(f"INFO  grid with {nn} nodes: relative error A {errs[nn]['A']:.2e}, B {errs[nn]['B']:.2e}")
check("grid of 30 nodes reproduces the event sum to better than 0.1% (A)", errs[30]["A"], 0, 1e-3)
check("grid of 30 nodes reproduces the event sum to better than 0.1% (B)", errs[30]["B"], 0, 1e-3)
slope = np.log(errs[80]["A"]/errs[20]["A"])/np.log(20/80)
print(f"INFO  error falls as (number of nodes)^-{slope:.2f} between 20 and 80 nodes (cubic interpolation: 4 expected)")
check("fourth-order convergence of cubic interpolation", slope, 4.0, 0.2)
check("hadron-collider flavour channels 11 x 11", 11*11, 121)

fig, ax = plt.subplots(figsize=(8, 4.6)); style(ax)
ns = sorted(errs)
ax.loglog(ns, [errs[k]["A"] for k in ns], "o-", color=TEAL, lw=2.6, ms=8, label="steep distribution A")
ax.loglog(ns, [errs[k]["B"] for k in ns], "s-", color=ORANGE, lw=2.6, ms=8, label="distribution B")
ref = errs[20]["A"]*(20/np.array(ns, float))**4
ax.loglog(ns, ref, color=INK, lw=1.2, ls="--", label="(number of nodes)⁻⁴")
ax.axhline(1e-3, color=INK, lw=1, ls=":"); ax.text(10.3, 1.25e-3, "0.1%", color=INK)
ax.set_xticks(ns); ax.set_xticklabels([str(k) for k in ns]); ax.minorticks_off()
ax.set_xlabel("number of grid nodes in x"); ax.set_ylabel("relative error of the grid result")
ax.legend(frameon=False, loc="lower left", fontsize=13)
fig.tight_layout(); fig.savefig(ASSETS / "3-3-grid.svg", facecolor="white"); plt.close(fig)

print("wrote 3-3-targetmass.svg, 3-3-smallx.svg, 3-3-grid.svg;", "ALL CHECKS PASS" if ok else "SOME CHECKS FAILED")
sys.exit(0 if ok else 1)
