#!/usr/bin/env python3
"""Numerical checks for guide chapter 1.5 (solving the evolution equations), and its three data plots.
Two independent leading-order solvers are implemented here: one in moment (Mellin) space and one on a grid in x.
Every formula the chapter states is tested; the script exits non-zero if any check fails.
Run:  python3 guide-build/tools/check_1_5.py        (writes assets/guide/1-5-*.svg)"""
import pathlib, sys
import numpy as np
from numpy.polynomial.legendre import leggauss
from scipy import integrate, special, linalg

CF, CA, TR = 4/3, 3.0, 0.5
ok = True
def check(name, got, want, tol=1e-6):
    global ok
    good = abs(got - want) <= tol * max(1.0, abs(want))
    ok &= bool(good)
    print(f"{'PASS' if good else 'FAIL'}  {name}: got {got:.10g}, want {want:.10g}")
info = lambda s: print("INFO  " + s)
quad = lambda f, a=0, b=1: integrate.quad(f, a, b, limit=400, epsabs=1e-12, epsrel=1e-12)[0]
rng = np.random.default_rng(15)
bcoef = lambda nf: (33 - 2*nf)/(12*np.pi)

# =====================================================================================================
# Section 2: the evolution basis
# =====================================================================================================
# light flavours: (u, ubar, d, dbar, s, sbar) -> (Sigma, V, V3, V8, T3, T8), eq. (1.5.6)
R = np.array([[1, 1, 1, 1, 1, 1], [1, -1, 1, -1, 1, -1], [1, -1, -1, 1, 0, 0],
              [1, -1, 1, -1, -2, 2], [1, 1, -1, -1, 0, 0], [1, 1, 1, 1, -2, -2]], float)
D = R @ R.T
check("rows of R are orthogonal (off-diagonal of R R^T)", np.abs(D - np.diag(np.diag(D))).max(), 0)
check("R R^T = diag(6,6,4,12,4,12)", np.abs(np.diag(D) - np.array([6, 6, 4, 12, 4, 12])).max(), 0)
Rinv = R.T @ np.diag(1/np.diag(D))
check("R^-1 = R^T D^-1", np.abs(Rinv @ R - np.eye(6)).max(), 0, 1e-14)
Rinv_text = np.array([[2, 2, 3, 1, 3, 1], [2, -2, -3, -1, 3, 1], [2, 2, -3, 1, -3, 1],
                      [2, -2, 3, -1, -3, 1], [2, 2, 0, -2, 0, -2], [2, -2, 0, 2, 0, -2]])/12
check("explicit inverse of eq. (1.5.7)", np.abs(Rinv_text - Rinv).max(), 0, 1e-14)
f6 = rng.uniform(0.1, 2, 6); e6 = R @ f6
F2_flav = 4/9*(f6[0]+f6[1]) + 1/9*(f6[2]+f6[3]) + 1/9*(f6[4]+f6[5])
check("F2/x = (2/9) Sigma + (1/6) T3 + (1/18) T8", 2/9*e6[0] + e6[4]/6 + e6[5]/18, F2_flav)
F2n = 4/9*(f6[2]+f6[3]) + 1/9*(f6[0]+f6[1]) + 1/9*(f6[4]+f6[5])      # neutron by isospin: u <-> d
check("F2p - F2n = (x/3) T3", F2_flav - F2n, e6[4]/3)

# six flavours: the 12 quark rows of the 14-component basis (Sigma, V, V3..V35, T3..T35)
def tower(sign):
    """rows T3,T8,T15,T24,T35 (sign=+1) or V3..V35 (sign=-1) acting on (u,ubar,d,dbar,...,t,tbar)"""
    rows = []
    for n in range(2, 7):
        r = np.zeros(12)
        for i in range(n - 1): r[2*i], r[2*i+1] = 1, sign
        r[2*(n-1)], r[2*(n-1)+1] = -(n-1), -(n-1)*sign
        rows.append(r)
    return rows
R12 = np.array([np.ones(12), np.tile([1., -1.], 6)] + tower(-1) + tower(+1))
D12 = R12 @ R12.T
check("12x12 rotation: rows orthogonal", np.abs(D12 - np.diag(np.diag(D12))).max(), 0)
check("12x12 rotation: norms 12,12 then 2n(n-1) twice",
      np.abs(np.diag(D12) - np.array([12, 12] + [2*n*(n-1) for n in range(2, 7)]*2)).max(), 0)
f12 = np.concatenate([rng.uniform(0.1, 2, 6), np.zeros(6)]); e12 = R12 @ f12   # no c, b, t
check("no heavy quarks: T15 = T24 = T35 = Sigma", max(abs(e12[k] - e12[0]) for k in (9, 10, 11)), 0)
check("no heavy quarks: V15 = V24 = V35 = V", max(abs(e12[k] - e12[1]) for k in (4, 5, 6)), 0)

# D1: with the general flavour structure of eq. (1.5.3) the evolution matrix block-diagonalises.
# In moment space a convolution is a product, so random numbers stand in for the kernels.
nf = 3
PVqq, PVqb, PSqq, PSqb, Pqg, Pgq, Pgg = rng.uniform(-1, 1, 7)
M = np.zeros((7, 7))                                  # flavour basis (u, ubar, d, dbar, s, sbar, g)
for i in range(6):
    for k in range(6):
        same_kind = (i % 2) == (k % 2)                # quark-quark or antiquark-antiquark
        M[i, k] = (PVqq if same_kind else PVqb)*(i//2 == k//2) + (PSqq if same_kind else PSqb)
    M[i, 6] = Pqg; M[6, i] = Pgq
M[6, 6] = Pgg
R7 = linalg.block_diag(R, 1.0)
Me = R7 @ M @ linalg.inv(R7)                          # order: Sigma, V, V3, V8, T3, T8, g
Pp, Pm = PVqq + PVqb, PVqq - PVqb
check("D1: T3, T8 evolve with P+", max(abs(Me[4, 4] - Pp), abs(Me[5, 5] - Pp)), 0, 1e-12)
check("D1: V3, V8 evolve with P-", max(abs(Me[2, 2] - Pm), abs(Me[3, 3] - Pm)), 0, 1e-12)
check("D1: V evolves with P- + nf (PSqq - PSqqbar)", Me[1, 1], Pm + nf*(PSqq - PSqb), 1e-12)
check("D1: Sigma-Sigma entry P+ + nf (PSqq + PSqqbar)", Me[0, 0], Pp + nf*(PSqq + PSqb), 1e-12)
check("D1: Sigma-g entry 2 nf Pqg", Me[0, 6], 2*nf*Pqg, 1e-12)
check("D1: g-Sigma entry Pgq", Me[6, 0], Pgq, 1e-12)
blk = Me.copy()
for i in range(1, 6): blk[i, i] = 0
blk[0, 0] = blk[0, 6] = blk[6, 0] = blk[6, 6] = 0
check("D1: every other entry of the rotated matrix vanishes", np.abs(blk).max(), 0, 1e-12)

# =====================================================================================================
# Leading-order anomalous dimensions (chapter 1.4, eq. 1.4.26), analytic in N
# =====================================================================================================
H = lambda N: special.digamma(N + 1) + np.euler_gamma
g_qq = lambda N: CF*(1.5 + 1/(N*(N+1)) - 2*H(N))
g_qg = lambda N: TR*(2 + N + N*N)/(N*(N+1)*(N+2))
g_gq = lambda N: CF*(2 + N + N*N)/(N*(N*N-1))
g_gg = lambda N, nf: 2*CA*(11/12 + 1/(N*(N-1)) + 1/((N+1)*(N+2)) - H(N)) - 2*nf*TR/3

# eq. (1.5.16): the harmonic sum continued to complex N
Nc = 2.3 + 1.7j
Hint = quad(lambda x: ((1 - x**Nc)/(1 - x)).real) + 1j*quad(lambda x: ((1 - x**Nc)/(1 - x)).imag)
check("H(N) = psi(N+1) + gamma_E at complex N (real part)", H(Nc).real, Hint.real, 1e-9)
check("H(N) = psi(N+1) + gamma_E at complex N (imaginary part)", H(Nc).imag, Hint.imag, 1e-9)
check("H(7) = 1 + 1/2 + ... + 1/7", H(7.0), sum(1/k for k in range(1, 8)), 1e-12)
check("H(N) = H(N-1) + 1/N at complex N", abs(H(Nc) - H(Nc - 1) - 1/Nc), 0, 1e-12)

# D2: projectors and the 2x2 matrix exponential, eqs. (1.5.13), (1.5.14)
def singlet_parts(N, nf):
    a, bq, c, d = g_qq(N), 2*nf*g_qg(N), g_gq(N), g_gg(N, nf)
    disc = np.sqrt((a - d)**2 + 4*bq*c); lp, lm = (a + d + disc)/2, (a + d - disc)/2
    return a, bq, c, d, lp, lm
def E_singlet(N, zeta, nf):
    """the four entries of exp[zeta Gamma/(2 pi b)], Gamma = [[g_qq, 2 nf g_qg], [g_gq, g_gg]]"""
    a, bq, c, d, lp, lm = singlet_parts(N, nf); k = zeta/(2*np.pi*bcoef(nf))
    ep, em = np.exp(lp*k), np.exp(lm*k)
    p11, p12, p21, p22 = (a - lm)/(lp - lm), bq/(lp - lm), c/(lp - lm), (d - lm)/(lp - lm)
    return p11*ep + (1 - p11)*em, p12*(ep - em), p21*(ep - em), p22*ep + (1 - p22)*em
E_ns = lambda N, zeta, nf: np.exp(g_qq(N)*zeta/(2*np.pi*bcoef(nf)))
a, bq, c, d, lp, lm = singlet_parts(Nc, 4)
G = np.array([[a, bq], [c, d]]); Pp_ = (G - lm*np.eye(2))/(lp - lm); Pm_ = (lp*np.eye(2) - G)/(lp - lm)
check("projectors: P+ P+ = P+", np.abs(Pp_ @ Pp_ - Pp_).max(), 0, 1e-12)
check("projectors: P+ P- = 0", np.abs(Pp_ @ Pm_).max(), 0, 1e-12)
check("projectors: P+ + P- = 1", np.abs(Pp_ + Pm_ - np.eye(2)).max(), 0, 1e-12)
check("projectors: Gamma = g+ P+ + g- P-", np.abs(lp*Pp_ + lm*Pm_ - G).max(), 0, 1e-12)
zt = 0.83
for nf_ in (4, 5):
    a, bq, c, d, lp, lm = singlet_parts(2.0, nf_); G2 = np.array([[a, bq], [c, d]])
    check(f"N=2 projector P+ = [[3nf, 3nf], [16, 16]]/(16 + 3nf), nf={nf_}",
          np.abs((G2 - lm*np.eye(2))/(lp - lm) - np.array([[3*nf_, 3*nf_], [16, 16]])/(16 + 3*nf_)).max(), 0, 1e-12)
check("singlet solution = matrix exponential (complex N)",
      np.abs(np.array(E_singlet(Nc, zt, 4)).reshape(2, 2) - linalg.expm(G*zt/(2*np.pi*bcoef(4)))).max(), 0, 1e-12)
z1, z2 = 0.31, 0.52
E1, E2, E12 = (np.array(E_singlet(Nc, z, 4)).reshape(2, 2) for z in (z1, z2, z1 + z2))
check("composition E(zeta1 + zeta2) = E(zeta2) E(zeta1) in moment space", np.abs(E2 @ E1 - E12).max(), 0, 1e-12)
check("identity at Q = Q0", np.abs(np.array(E_singlet(Nc, 0.0, 4)).reshape(2, 2) - np.eye(2)).max(), 0, 1e-14)
for nf_ in (3, 4, 5):
    a, bq, c, d, lp, lm = singlet_parts(2.0, nf_)
    check(f"N=2 eigenvalues 0 and -(4CF/3 + nf/3), nf={nf_}", abs(lp) + abs(lm + 4*CF/3 + nf_/3), 0, 1e-12)

# =====================================================================================================
# The toy input (the same shapes as chapter 1.4): x f = A x^a (1-x)^c at the starting scale
# =====================================================================================================
mom = lambda a, c, N: np.exp(special.loggamma(N - 1 + a) + special.loggamma(c + 1) - special.loggamma(N + a + c))
Av = 3/special.beta(0.5, 4.0)
As = 0.15/mom(-0.2, 7.0, 2); Ag = (1 - Av*mom(0.5, 3.0, 2) - 0.15)/mom(-0.2, 5.0, 2)
vN = lambda N: Av*mom(0.5, 3.0, N); sN = lambda N: As*mom(-0.2, 7.0, N); gN = lambda N: Ag*mom(-0.2, 5.0, N)
SN = lambda N: vN(N) + sN(N)
xV0 = lambda x: Av*x**0.5*(1-x)**3; xS0 = lambda x: xV0(x) + As*x**-0.2*(1-x)**7; xg0 = lambda x: Ag*x**-0.2*(1-x)**5

nf4, Lam2, Q02 = 4, 0.04, 1.65**2                    # Lambda = 0.2 GeV, an illustrative leading-order value
aLO = lambda Q2, nf=nf4: 1/(bcoef(nf)*np.log(Q2/Lam2))
zeta_of = lambda Q2: np.log(aLO(Q02)/aLO(Q2))

# D6: Mellin inversion on the bent contour N = c + t e^{i phi}, eq. (1.5.15), by Gauss-Legendre panels
GX, GW = leggauss(24)
def mellin_inv(FN, x, c=1.8, phi=0.75*np.pi):
    """x f(x) = (1/pi) int_0^inf dt Im[e^{i phi} x^{1-N} f(N)],  N = c + t e^{i phi}"""
    L = np.log(1/x); edges = np.concatenate([[0], 0.5/max(1.0, L)*1.6**np.arange(1, 34)])
    lo, hi = edges[:-1, None], edges[1:, None]
    t = 0.5*(hi + lo) + 0.5*(hi - lo)*GX[None, :]; w = 0.5*(hi - lo)*GW[None, :]
    e = np.exp(1j*phi); N = c + t*e
    return float(np.sum(w*(e*np.exp((N - 1)*L)*FN(N)).imag)/np.pi)
for xx in (1e-4, 0.1, 0.5, 0.9):
    check(f"inversion returns the input valence at x={xx}", mellin_inv(vN, xx), xV0(xx), 1e-8)
    check(f"inversion returns the input gluon at x={xx}", mellin_inv(gN, xx), xg0(xx), 1e-8)
# the result must not depend on the contour
fv = lambda N: vN(N)*E_ns(N, 1.0, 4)
check("contour independence: c=1.8, phi=3pi/4 against c=1.2, phi=0.6pi",
      mellin_inv(fv, 0.03), mellin_inv(fv, 0.03, c=1.2, phi=0.6*np.pi), 1e-8)
ref = integrate.quad(lambda t: (np.exp((1.8 + 1j*t - 1)*np.log(1/0.03))*fv(1.8 + 1j*t)).real/np.pi,
                     0, 4000, limit=4000, epsabs=1e-9, epsrel=1e-9)[0]
check("bent contour against the straight line Re N = 1.8 (slowly convergent)", mellin_inv(fv, 0.03), ref, 1e-7)
info(f"bent - straight contour: {mellin_inv(fv, 0.03) - ref:.2e}")

def mellin_solution(x, Q2, nf=nf4, zeta=None):
    """(x V, x Sigma, x g) at Q2 from the moment-space solution, eqs. (1.4.28) and (1.5.13)"""
    z = zeta_of(Q2) if zeta is None else zeta
    def Sg(N, row):
        e11, e12, e21, e22 = E_singlet(N, z, nf)
        return e11*SN(N) + e12*gN(N) if row == 0 else e21*SN(N) + e22*gN(N)
    return (mellin_inv(lambda N: vN(N)*E_ns(N, z, nf), x), mellin_inv(lambda N: Sg(N, 0), x),
            mellin_inv(lambda N: Sg(N, 1), x))

# =====================================================================================================
# Section 6: the x-space solver.  D3: the discretised convolution with the plus distribution
# =====================================================================================================
# eq. (1.5.24): the plus distribution on a restricted range
gfun = lambda z: (1 + z*z)*np.cos(2*z); x0 = 0.37
lhs = quad(lambda z: (gfun(z)*(z > x0) - gfun(1.0))/(1 - z), 0, x0) + quad(lambda z: (gfun(z) - gfun(1.0))/(1 - z), x0, 1)
rhs = quad(lambda z: (gfun(z) - gfun(1.0))/(1 - z), x0, 1) + gfun(1.0)*np.log(1 - x0)
check("int_x^1 g/(1-z)_+ = int_x^1 (g - g(1))/(1-z) + g(1) ln(1-x)", lhs, rhs, 1e-10)

def make_grid(n_small, n_large):
    return np.concatenate([np.logspace(-5, -1, n_small + 1)[:-1], np.linspace(0.1, 1.0, n_large + 1)])
def build_K(xg, A, B, C, ngl=12):
    """K with  x (P (x) f)(x_i) = sum_j K_ij F_j,  F = x f,  for P(z) = A(z)/(1-z)_+ + B(z) + C delta(1-z).
    F is interpolated linearly in ln x between the nodes; the last node is x = 1, where F = 0.  Eq. (1.5.25)."""
    n = len(xg) - 1; lx = np.log(xg); K = np.zeros((n, n)); gx, gw = leggauss(ngl); A1 = float(A(np.array(1.0)))
    for i in range(n):
        k = np.arange(i, n)                                    # y = x_i/z lies in [x_k, x_k+1]
        zlo, zhi = xg[i]/xg[k+1], xg[i]/xg[k]                  # zhi[0] = 1
        z = 0.5*(zhi + zlo)[:, None] + 0.5*(zhi - zlo)[:, None]*gx[None, :]
        w = 0.5*(zhi - zlo)[:, None]*gw[None, :]
        w1 = (np.log(xg[i]/z) - lx[k][:, None])/(lx[k+1] - lx[k])[:, None]     # weight of node k+1
        w0 = 1 - w1                                            # weight of node k
        Az, Bz = A(z), B(z); full = Az/(1 - z) + Bz
        c0, c1 = full*w0*w, full*w1*w
        c0[0] = ((Az[0]*w0[0] - A1)/(1 - z[0]) + Bz[0]*w0[0])*w[0]             # the subtraction, first interval only
        K[i, k] += c0.sum(1)
        kk = k + 1; keep = kk < n
        K[i, kk[keep]] += c1.sum(1)[keep]
        K[i, i] += A1*np.log(1 - zlo[0]) + C
    return K
zero = lambda z: 0*z
def kernels(xg, nf):
    Kqq = build_K(xg, lambda z: CF*(1 + z*z), zero, 1.5*CF)
    Kqg = build_K(xg, zero, lambda z: TR*(z*z + (1-z)**2), 0.0)
    Kgq = build_K(xg, zero, lambda z: CF*(1 + (1-z)**2)/z, 0.0)
    Kgg = build_K(xg, lambda z: 2*CA*z, lambda z: 2*CA*((1-z)/z + z*(1-z)), (11*CA - 4*nf*TR)/6)
    return Kqq, np.block([[Kqq, 2*nf*Kqg], [Kgq, Kgg]])

# the discretised convolution against an exact one:  f = x^-0.5 (1-x)^3, F = x f
xg = make_grid(80, 160); n = len(xg) - 1; xs = xg[:-1]
Kqq, Ksing = kernels(xg, nf4)
Ftest = xs**0.5*(1 - xs)**3
def exact_conv_qq(x):
    F = lambda y: y**0.5*(1 - y)**3
    gz = lambda z: (1 + z*z)*F(x/z)
    return CF*(quad(lambda z: (gz(z) - gz(1.0))/(1 - z), x, 1) + gz(1.0)*np.log(1 - x) + 1.5*F(x))
for i in (10, 60, 120, 200):
    check(f"discretised x(Pqq (x) f) at x={xs[i]:.4g}", (Kqq @ Ftest)[i], exact_conv_qq(xs[i]), 2e-3)
check("K is upper triangular: only y >= x feeds x", np.abs(np.tril(Kqq, -1)).max(), 0)

# the leading-order evolution operator on the grid, eq. (1.5.26): E = exp[zeta K/(2 pi b)]
def expm_ss(A, squarings=7, order=14):
    """matrix exponential by scaling and squaring with a Taylor series.  (scipy's expm takes a special path for
    triangular matrices that loses accuracy here, where long runs of diagonal entries are equal.)"""
    B = A/2**squarings; E = np.eye(len(A)); T = np.eye(len(A))
    for k in range(1, order + 1): T = T @ B/k; E = E + T
    for _ in range(squarings): E = E @ E
    return E
def E_grid(K, zeta, nf): return expm_ss(K*zeta/(2*np.pi*bcoef(nf)))
FV0, FS0, Fg0 = xV0(xs), xS0(xs), xg0(xs)
def compare(Q2, xg_, kern, step=6):
    xs_ = xg_[:-1]; n_ = len(xs_); z = zeta_of(Q2)
    V = E_grid(kern[0], z, nf4) @ xV0(xs_); SG = E_grid(kern[1], z, nf4) @ np.concatenate([xS0(xs_), xg0(xs_)])
    idx = [i for i in range(n_) if 1e-4 <= xs_[i] <= 0.7][::step]
    ex = np.array([mellin_solution(xs_[i], Q2) for i in idx])
    gr = np.array([[V[i], SG[i], SG[n_ + i]] for i in idx])
    return xs_[idx], ex, gr, np.abs(gr/ex - 1).max(axis=0)
cmp = {}
for Q2 in (100.0, 1e4):
    cmp[Q2] = compare(Q2, xg, (Kqq, Ksing))
    dV, dS, dG = cmp[Q2][3]
    info(f"x-space against Mellin at Q2={Q2:g}, 240 nodes, 1e-4<x<0.7: max relative difference "
         f"valence {dV:.2e}, singlet {dS:.2e}, gluon {dG:.2e}")
    check(f"x-space solver (240 nodes) agrees with Mellin solver to 0.4% at Q2={Q2:g}", max(dV, dS, dG), 0, 4e-3)
    check(f"... and to 0.1% for the valence and singlet quarks", max(dV, dS), 0, 1e-3)
xg2 = make_grid(160, 320); kern2 = kernels(xg2, nf4)
d2 = compare(1e4, xg2, kern2, 12)[3]
info(f"same with 480 nodes: valence {d2[0]:.2e}, singlet {d2[1]:.2e}, gluon {d2[2]:.2e}; "
     f"ratio to 240 nodes {cmp[1e4][3].max()/d2.max():.2f} (4 expected for a second-order method)")
check("halving the spacing reduces the error by about 4", cmp[1e4][3].max()/d2.max(), 4.0, 0.25)
check("480-node grid agrees with Mellin to 0.12%", d2.max(), 0, 1.2e-3)

# composition and universality of the grid operator
Ea, Eb, Eab = E_grid(Kqq, z1, nf4), E_grid(Kqq, z2, nf4), E_grid(Kqq, z1 + z2, nf4)
check("composition of grid operators", np.abs(Eb @ Ea - Eab).max(), 0, 1e-10)
check("evolution operator is upper triangular", np.abs(np.tril(Eab, -1)).max(), 0, 1e-14)
# the same operator applied to a different input: x f = x^0.8 (1-x)^4
z = zeta_of(1e4); Eop = E_grid(Kqq, z, nf4); alt = lambda N: mom(0.8, 4.0, N)
for i in (40, 100, 140):
    check(f"same operator, different input, x={xs[i]:.3g}", (Eop @ (xs**0.8*(1-xs)**4))[i],
          mellin_inv(lambda N: alt(N)*E_ns(N, z, nf4), xs[i]), 2e-3)

# stepping in ln Q^2: Euler and fourth-order Runge-Kutta against the matrix exponential
def step_solve(K, F0, Q2, nsteps, method):
    t0, t1 = np.log(Q02), np.log(Q2); h = (t1 - t0)/nsteps; F = F0.copy()
    rhs = lambda t, F: aLO(np.exp(t))/(2*np.pi)*(K @ F)
    for s in range(nsteps):
        t = t0 + s*h
        if method == "euler": F = F + h*rhs(t, F)
        else:
            k1 = rhs(t, F); k2 = rhs(t + h/2, F + h/2*k1); k3 = rhs(t + h/2, F + h/2*k2); k4 = rhs(t + h, F + h*k3)
            F = F + h/6*(k1 + 2*k2 + 2*k3 + k4)
    return F
exactV = Eop @ FV0; sel = (xs > 1e-4) & (xs < 0.7)
err = lambda F: np.abs(F[sel]/exactV[sel] - 1).max()
eE = [err(step_solve(Kqq, FV0, 1e4, m, "euler")) for m in (40, 80)]
eR = [err(step_solve(Kqq, FV0, 1e4, m, "rk4")) for m in (10, 20)]
info(f"Euler, 40 and 80 steps in ln Q2: {eE[0]:.2e}, {eE[1]:.2e} (ratio {eE[0]/eE[1]:.2f}); "
     f"RK4, 10 and 20 steps: {eR[0]:.2e}, {eR[1]:.2e} (ratio {eR[0]/eR[1]:.1f})")
check("Euler is first order: error halves", eE[0]/eE[1], 2.0, 0.15)
check("RK4 is fourth order: error falls by about 16", eR[0]/eR[1], 16.0, 0.35)
check("RK4 with 20 steps reproduces the matrix exponential to 1e-5", eR[1], 0, 1e-5)

# momentum on the grid: weights m_j = int w_j(x) dx for the interpolant linear in ln x
def mom_weights(xg_):
    n_ = len(xg_) - 1; m = np.zeros(n_ + 1); gx, gw = leggauss(8)
    for k in range(n_):
        xx = 0.5*(xg_[k+1] + xg_[k]) + 0.5*(xg_[k+1] - xg_[k])*gx; w = 0.5*(xg_[k+1] - xg_[k])*gw
        w1 = np.log(xx/xg_[k])/np.log(xg_[k+1]/xg_[k]); m[k] += np.sum(w*(1 - w1)); m[k+1] += np.sum(w*w1)
    return m[:-1]
mw = mom_weights(xg); SG = E_grid(Ksing, zeta_of(1e4), nf4) @ np.concatenate([FS0, Fg0])
info(f"momentum above x=1e-5 on the grid: {mw @ (FS0 + Fg0):.5f} at Q0, {mw @ (SG[:n] + SG[n:]):.5f} at Q2=1e4")
zz = zeta_of(1e4)
below = 1e-5*mellin_inv(lambda N: (lambda e: (e[0] + e[2])*SN(N) + (e[1] + e[3])*gN(N))(E_singlet(N, zz, 4))/(2 - N), 1e-5)
info(f"momentum below x=1e-5 at Q2=1e4, from the moment-space solution: {below:.5f}")
check("momentum on the grid at Q2=1e4 = 1 - (momentum below x=1e-5)", mw @ (SG[:n] + SG[n:]), 1 - below, 2e-3)
check("momentum sum in moment space at Q2=1e4", (lambda e: e[0]*SN(2.0) + e[1]*gN(2.0) + e[2]*SN(2.0) + e[3]*gN(2.0))(
      E_singlet(2.0, zeta_of(1e4), 4)), 1.0, 1e-10)

# =====================================================================================================
# Section 5: two-loop coupling and the next-to-leading-order non-singlet solution (D4)
# =====================================================================================================
bp = lambda nf: (153 - 19*nf)/(2*np.pi*(33 - 2*nf))
def run2(a0, t0, t1, nf):
    """two-loop running from ln mu^2 = t0 to t1, eq. (1.5.17), by direct integration"""
    s = integrate.solve_ivp(lambda t, a: -bcoef(nf)*a*a*(1 + bp(nf)*a), (t0, t1), [a0], rtol=1e-12, atol=1e-14)
    return s.y[0, -1]
MZ, mb, mc, Q0 = 91.2, 4.92, 1.51, 1.65   # M_Z as in the theory card (Qref 91.2 GeV) and chapter 1.6
a_mb = run2(0.118, 2*np.log(MZ), 2*np.log(mb), 5)
a_Q0 = run2(a_mb, 2*np.log(mb), 2*np.log(Q0), 4)
a_100 = run2(0.118, 2*np.log(MZ), 2*np.log(100.0), 5)
info(f"two-loop coupling from alpha_S(MZ)=0.118: alpha_S(mb=4.92)={a_mb:.4f}, alpha_S(Q0=1.65)={a_Q0:.4f}")
implicit = lambda a, nf: 1/a + bp(nf)*np.log(bp(nf)*a/(1 + bp(nf)*a))
check("implicit two-loop solution, eq. (1.5.18), nf=5 from MZ to mb",
      implicit(a_mb, 5) - implicit(0.118, 5), bcoef(5)*2*np.log(mb/MZ), 1e-9)
check("implicit two-loop solution, nf=4 from mb to Q0",
      implicit(a_Q0, 4) - implicit(a_mb, 4), bcoef(4)*2*np.log(Q0/mb), 1e-9)
check("b' for nf=5 is 29/(23 pi)... (153-95)/(2 pi 23)", bp(5), 58/(46*np.pi), 1e-14)
a_mb_1 = 1/(1/0.118 + bcoef(5)*2*np.log(mb/MZ)); a_Q0_1 = 1/(1/a_mb_1 + bcoef(4)*2*np.log(Q0/mb))
info(f"one-loop running of the same input: alpha_S(mb)={a_mb_1:.4f}, alpha_S(Q0)={a_Q0_1:.4f}")
info(f"slope of 1/alpha_S in ln mu^2 at one loop: b(4)={bcoef(4):.4f}, b(5)={bcoef(5):.4f}, ratio {bcoef(5)/bcoef(4):.3f}")

# the NLO non-singlet splitting functions of ESW eqs. (4.107), (4.108), (4.119), in units (alpha_S/2 pi)^2
z3 = special.zeta(3.0)
Li2 = lambda z: special.spence(1 - z)
S2 = lambda x: -2*Li2(-x) + 0.5*np.log(x)**2 - 2*np.log(x)*np.log(1 + x) - np.pi**2/6
pqq = lambda x: 2/(1 - x) - 1 - x
def PV1_parts(nf):
    Tf = TR*nf
    def c1(x):  return CF*CF*(-(2*np.log(x)*np.log(1-x) + 1.5*np.log(x)))
    def c2(x):  return CF*CA*(0.5*np.log(x)**2 + 11/6*np.log(x) + 67/18 - np.pi**2/6)
    def c3(x):  return CF*Tf*(-(2/3*np.log(x) + 10/9))
    def full(x):                                           # for x < 1, with a plain 1/(1-x)
        return ((c1(x) + c2(x) + c3(x))*pqq(x)
                + CF*CF*(-(1.5 + 3.5*x)*np.log(x) - 0.5*(1 + x)*np.log(x)**2 - 5*(1 - x))
                + CF*CA*((1 + x)*np.log(x) + 20/3*(1 - x)) + CF*Tf*(-4/3*(1 - x)))
    A1 = 2*(CF*CA*(67/18 - np.pi**2/6) - CF*Tf*10/9)       # coefficient of 1/(1-x)_+ at x = 1
    delta = CF*CF*(3/8 - np.pi**2/2 + 6*z3) + CF*CA*(17/24 + 11*np.pi**2/18 - 3*z3) - CF*Tf*(1/6 + 2*np.pi**2/9)
    qqb = lambda x: CF*(CF - CA/2)*(2*pqq(-x)*S2(x) + 2*(1 + x)*np.log(x) + 4*(1 - x))
    return full, A1, delta, qqb
def gamma1(N, nf, sign):
    """N-th moment of P^(1)+- = P^V(1)_qq +- P^V(1)_qqbar"""
    full, A1, delta, qqb = PV1_parts(nf)
    f = lambda x: x**(N-1)*full(x) - A1/(1 - x) + sign*x**(N-1)*qqb(x)
    return integrate.quad(f, 0, 1, limit=400, epsabs=1e-11, epsrel=1e-11)[0] + delta
for nf_ in (3, 4, 5):
    check(f"fermion number: first moment of P^(1)- vanishes, nf={nf_} (ESW eq. 4.115)", gamma1(1.0, nf_, -1), 0, 1e-7)
kap = CA*(67/18 - np.pi**2/6) - TR*4*10/9
check("large-x coefficient of P^(1): A(1) = 2 CF kappa (ESW eqs. 4.123, 4.124)", PV1_parts(4)[1], 2*CF*kap, 1e-12)
g1p2 = gamma1(2.0, 4, +1); want = -(94/27*CA*CF - 28/27*CF*CF - 32/27*CF*TR*4)
check("second moment of P^(1)+, nf=4, against the closed form", g1p2, want, 1e-6)
g1m = {N: gamma1(float(N), 4, -1) for N in (2, 4, 8)}
info("gamma^(1)-(N), nf=4: " + ", ".join(f"N={N}: {v:.4f}" for N, v in g1m.items())
     + "; gamma^(0)(N): " + ", ".join(f"{g_qq(float(N)):.4f}" for N in g1m))

# D4: the closed-form (iterated) solution against direct integration, and the truncated solution
def R01(g0, g1, nf): return g0/(2*np.pi*bcoef(nf)), (g1/(2*np.pi) - bp(nf)*g0)/(2*np.pi*bcoef(nf))
def iterated(g0, g1, a0, a, nf):
    r0, r1 = R01(g0, g1, nf); return (a0/a)**r0*((1 + bp(nf)*a0)/(1 + bp(nf)*a))**(r1/bp(nf))
def truncated(g0, g1, a0, a, nf):
    r0, r1 = R01(g0, g1, nf); return (a0/a)**r0*(1 + r1*(a0 - a))
def direct(g0, g1, a0, t0, t1, nf):
    rhs = lambda t, y: [-bcoef(nf)*y[0]**2*(1 + bp(nf)*y[0]), y[0]/(2*np.pi)*(g0 + y[0]/(2*np.pi)*g1)*y[1]]
    s = integrate.solve_ivp(rhs, (t0, t1), [a0, 1.0], rtol=1e-12, atol=1e-14); return s.y[1, -1], s.y[0, -1]
for N in (2, 8):
    g0, g1 = g_qq(float(N)), g1m[N]
    qd, a_end = direct(g0, g1, a_Q0, 2*np.log(Q0), 2*np.log(mb), 4)
    check(f"iterated NLO solution, eq. (1.5.20), against direct integration, N={N}", iterated(g0, g1, a_Q0, a_end, 4), qd, 1e-9)
    it, tr, lo = iterated(g0, g1, a_Q0, a_mb, 4), truncated(g0, g1, a_Q0, a_mb, 4), (a_Q0/a_mb)**(g0/(2*np.pi*bcoef(4)))
    info(f"valence moment N={N}, Q0 -> mb (nf=4): LO factor {lo:.4f}, NLO iterated {it:.4f}, NLO truncated {tr:.4f}, "
         f"truncated/iterated - 1 = {tr/it - 1:+.2e}")
check("alpha_S(mb) from the coupled integration equals the two-loop running", a_end, a_mb, 1e-9)
# the two NLO solutions differ at relative order alpha_S^2: scale both couplings by 1/2 and the difference falls by 4
g0, g1 = g_qq(4.0), g1m[4]
dd = [truncated(g0, g1, s*0.30, s*0.20, 4)/iterated(g0, g1, s*0.30, s*0.20, 4) - 1 for s in (0.02, 0.01)]
check("truncated - iterated is second order in alpha_S", dd[0]/dd[1], 4.0, 2e-2)

# the singlet U-matrix, eq. (1.5.22): random 2x2 matrices R0, R1
R0 = rng.uniform(-1, 1, (2, 2)); R1 = rng.uniform(-1, 1, (2, 2))
ev, Vv = np.linalg.eig(R0); Vi = np.linalg.inv(Vv)
proj = [np.outer(Vv[:, i], Vi[i, :]) for i in range(2)]
U1 = -sum(proj[i] @ R1 @ proj[j]/(1 + ev[i] - ev[j]) for i in range(2) for j in range(2))
check("U1 solves U1 + [R0, U1] = -R1", np.abs(U1 + R0 @ U1 - U1 @ R0 + R1).max(), 0, 1e-12)
def U_err(scale):
    a0_, a_ = 0.3*scale, 0.2*scale
    s = integrate.solve_ivp(lambda a, y: (-(R0 + a*R1)/a @ y.reshape(2, 2)).ravel(), (a0_, a_), np.eye(2).ravel(),
                            rtol=1e-12, atol=1e-14)
    exact = s.y[:, -1].reshape(2, 2)
    L = Vv @ np.diag((a0_/a_)**ev) @ Vi
    approx = (np.eye(2) + a_*U1) @ L @ np.linalg.inv(np.eye(2) + a0_*U1)
    return np.abs(approx - exact).max()
uu = [U_err(0.02), U_err(0.01)]
check("U-matrix solution is exact up to terms of order alpha_S^2", (uu[0]/uu[1]).real, 4.0, 3e-2)

# =====================================================================================================
# Section 7: thresholds.  Charm generated radiatively at leading order from zero at mu = m_c
# =====================================================================================================
aLO_from = lambda a0, mu0, mu, nf: 1/(1/a0 + bcoef(nf)*2*np.log(mu/mu0))
check("one-loop coupling is continuous at a threshold but its slope is not",
      aLO_from(0.2, mb, mb, 4) - aLO_from(0.2, mb, mb, 5), 0, 1e-15)
a_mc = aLO(mc**2)                                       # toy leading-order coupling, as in section 6
def charm_moment(N, zeta):
    """c + cbar = (Sigma - T15)/4 with T15(m_c) = Sigma(m_c); four flavours above m_c"""
    e11, e12, _, _ = E_singlet(N, zeta, 4)
    return (e11*SN(N) + e12*gN(N) - E_ns(N, zeta, 4)*SN(N))/4
zc = lambda mu: np.log(a_mc/aLO(mu*mu))
eps = 1e-4
for N in (2.0, 3.5):
    check(f"first-order charm: d c+(N)/d zeta = 2 gamma_qg g/(2 pi b) at threshold, N={N}",
          charm_moment(N, eps)/eps, 2*g_qg(N)*gN(N)/(2*np.pi*bcoef(4)), 1e-3)
# x space: c+ just above threshold against (alpha_S/2 pi) ln(mu^2/mc^2) 2 Pqg (x) g
mu1 = 1.02*mc; xx = 0.01
conv = quad(lambda z: TR*(z*z + (1-z)**2)*xg0(xx/z), xx, 1)          # x (Pqg (x) g)(x)
first = a_mc/(2*np.pi)*np.log(mu1**2/mc**2)*2*conv
check("x c+(x) just above threshold against eq. (1.5.29)", mellin_inv(lambda N: charm_moment(N, zc(mu1)), xx), first, 3e-2)
cm = {mu: charm_moment(2.0, zc(mu)).real for mu in (3.0, 10.0, 100.0)}
info("momentum carried by radiatively generated c + cbar (leading order, toy input placed at m_c=1.51 GeV): "
     + ", ".join(f"mu={mu:g} GeV: {100*v:.2f}%" for mu, v in cm.items()))
check("charm momentum comes out of the light partons: total stays 1",
      (lambda e: (e[0] + e[2])*SN(2.0) + (e[1] + e[3])*gN(2.0))(E_singlet(2.0, zc(100.0), 4)).real, 1.0, 1e-10)

# =====================================================================================================
# Section 8: large x (D5)
# =====================================================================================================
for N in (50.0, 400.0):
    check(f"gamma_qq(N) -> CF (3/2 - 2 ln N - 2 gamma_E), N={N:g}", g_qq(N), CF*(1.5 - 2*np.log(N) - 2*np.euler_gamma), 3/N)
check("moments of (1-x)^a: Gamma(a+1) N^-(a+1) at large N", special.beta(300.0, 4.0)*300.0**4/special.gamma(4.0), 1.0, 3e-2)
p_ = 4.7; check("inverse Mellin transform of N^-p is ln(1/x)^(p-1)/Gamma(p)",
                quad(lambda x: x**(6.0 - 1)*np.log(1/x)**(p_ - 1)/special.gamma(p_)), 6.0**-p_, 1e-9)
shift = lambda zeta, nf=nf4: CF*zeta/(np.pi*bcoef(nf))
check("exponent shift for nf=4 is (16/25) zeta", shift(1.0), 16/25, 1e-12)
def V_large_x(x, zeta, a=3.0):
    """eq. (1.5.31) for the toy valence, V = Av x^-0.5 (1-x)^3; returns x V"""
    dl = shift(zeta)
    return x*Av*np.exp((0.75 - np.euler_gamma)*dl)*special.gamma(a + 1)/special.gamma(a + 1 + dl)*(1 - x)**(a + dl)
for Q2 in (100.0, 1e4):
    z = zeta_of(Q2); ex = {x: mellin_inv(lambda N: vN(N)*E_ns(N, z, 4), x) for x in (0.9, 0.95, 0.98)}
    slope = np.log(ex[0.98]/ex[0.95])/np.log(0.02/0.05)
    info(f"large x at Q2={Q2:g}: zeta={z:.3f}, predicted exponent {3 + shift(z):.3f}, measured between x=0.95 and 0.98 "
         f"{slope:.3f}; exact/asymptotic at x=0.98: {ex[0.98]/V_large_x(0.98, z):.3f}")
    check(f"effective large-x exponent at Q2={Q2:g} against 3 + CF zeta/(pi b)", slope, 3 + shift(z), 2e-2)
    check(f"normalisation of eq. (1.5.31) at x=0.98, Q2={Q2:g}", ex[0.98]/V_large_x(0.98, z), 1.0, 6e-2)

# =====================================================================================================
# Section 9: small x
# =====================================================================================================
check("gamma_gg -> 2CA/(N-1) near N=1", g_gg(1.001, 4)*0.001, 2*CA, 2e-2)
check("gamma_gq -> 2CF/(N-1) near N=1", g_gq(1.001)*0.001, 2*CF, 2e-2)
A33 = 2*z3*(2*CA)**4/6
info(f"leading ln(1/x) coefficient at fourth order: 2 zeta(3) (2CA)^4/3! = {A33:.1f} (ESW eq. 4.188 quotes 518.4 = 2.4 x 216)")
check("ESW's 518.4 is the same number with zeta(3) rounded to 1.2", 2*1.2*(2*CA)**4/6, 518.4, 1e-12)
check("int x^(N-1) [ln^3(1/x)/3!]/x dx = 1/(N-1)^4", quad(lambda x: x**(1.7 - 2)*np.log(1/x)**3/6), 1/0.7**4, 1e-8)
lam = lambda a: 12*np.log(2)*a/np.pi
info(f"BFKL exponent 12 ln2 alpha_S/pi: {lam(0.2):.3f} at alpha_S=0.2; equals 0.5 at alpha_S={0.5*np.pi/(12*np.log(2)):.3f}")
check("12 ln 2 / pi = 4 ln 2 x CA/pi", 12*np.log(2)/np.pi, 4*np.log(2)*CA/np.pi, 1e-14)
for Q2 in (100.0, 1e4):
    g5, g6 = mellin_solution(1e-5, Q2)[2], mellin_solution(1e-6, Q2)[2]
    info(f"toy gluon at Q2={Q2:g}: effective power x^-{np.log(g6/g5)/np.log(10):.3f} between x=1e-5 and 1e-6; "
         f"alpha_S ln(1/x) at x=1e-5: {aLO(Q2)*np.log(1e5):.2f}")

# =====================================================================================================
# Plots
# =====================================================================================================
import matplotlib; matplotlib.use("Agg")
import matplotlib.pyplot as plt
OUT = pathlib.Path(__file__).resolve().parents[2] / "assets" / "guide"; OUT.mkdir(parents=True, exist_ok=True)
TEAL, ORANGE, INK, GRID, MUTED = "#0e7c7b", "#d96c2c", "#16222e", "#ebe6da", "#6b7480"
plt.rcParams.update({"font.size": 14, "axes.edgecolor": INK, "axes.labelcolor": INK, "xtick.color": INK, "ytick.color": INK,
                     "text.color": INK, "legend.frameon": False,
                     "figure.facecolor": "white", "axes.facecolor": "white", "savefig.facecolor": "white"})
def style(ax): ax.grid(True, color=GRID, lw=1); ax.set_axisbelow(True)

# 1. the two solvers
fig, (a1, a2) = plt.subplots(2, 1, figsize=(8, 6.2), sharex=True, gridspec_kw={"height_ratios": [2.3, 1], "hspace": 0.08})
xl = np.concatenate([np.logspace(-4, -1, 40)[:-1], np.linspace(0.1, 0.9, 33)])
line = np.array([mellin_solution(x, 1e4) for x in xl])
SGp = E_grid(Ksing, zeta_of(1e4), nf4) @ np.concatenate([FS0, Fg0]); Vp = E_grid(Kqq, zeta_of(1e4), nf4) @ FV0
pick = np.array([i for i in range(n) if 1e-4 <= xs[i] <= 0.9][::8])
for col, lab, f0, i, gridv in ((TEAL, "gluon", xg0, 2, SGp[n:]), (ORANGE, "all quarks", xS0, 1, SGp[:n]), (INK, "valence", xV0, 0, Vp)):
    a1.plot(xl, f0(xl), color=col, lw=1.3, ls=(0, (4, 3)), alpha=0.75)
    a1.plot(xl, line[:, i], color=col, lw=2.2, label=lab)
    a1.plot(xs[pick], gridv[pick], "o", color=col, ms=5.5, mfc="white", mew=1.6)
a1.plot([], [], color=MUTED, lw=2.2, label="moment space"); a1.plot([], [], "o", color=MUTED, mfc="white", mew=1.6, label="$x$ grid")
a1.plot([], [], color=MUTED, lw=1.3, ls=(0, (4, 3)), label="input at $Q_0$")
a1.set_xscale("log"); a1.set_yscale("log"); a1.set_ylim(0.003, 150); a1.set_xlim(1e-4, 1); style(a1)
a1.set_ylabel("momentum density  $x\\,f(x)$"); a1.legend(ncol=3, loc="lower left", fontsize=13, columnspacing=1.0, handlelength=1.4, handletextpad=0.5)
a1.set_title("Toy input evolved to $Q^2=10^4$ GeV$^2$ at leading order (illustrative)", fontsize=14)
xc, ex_, gr_, _ = compare(1e4, xg, (Kqq, Ksing), 3)
for col, i in ((TEAL, 2), (ORANGE, 1), (INK, 0)): a2.plot(xc, 100*(gr_[:, i]/ex_[:, i] - 1), color=col, lw=2)
a2.axhline(0, color=MUTED, lw=1); a2.set_ylim(-0.1, 0.45); style(a2)
a2.set_ylabel("grid / moment − 1  (%)", fontsize=13); a2.set_xlabel("momentum fraction  $x$")
fig.align_ylabels(); fig.savefig(OUT / "1-5-solvers.svg", bbox_inches="tight"); plt.close(fig)

# 2. thresholds: the coupling, and charm generated from zero
fig, (a1, a2) = plt.subplots(1, 2, figsize=(9.2, 4.6), gridspec_kw={"wspace": 0.34})
mus = np.logspace(np.log10(Q0), np.log10(200), 60); a1.set_xlim(1.4, 240)
inv = [1/(run2(0.118, 2*np.log(MZ), 2*np.log(m), 5) if m >= mb else run2(a_mb, 2*np.log(mb), 2*np.log(m), 4)) for m in mus]
inv5 = [1/run2(a_mb, 2*np.log(mb), 2*np.log(m), 5) for m in mus if m <= mb]
a1.plot(mus, inv, color=TEAL, lw=2.4); a1.plot([m for m in mus if m <= mb], inv5, color=MUTED, lw=1.6, ls=(0, (4, 3)))
a1.axvline(mb, color=ORANGE, lw=1.4); a1.text(mb*1.12, 9.2, "$m_b$", color=ORANGE, fontsize=15)
a1.text(1.62, 5.3, "$n_f=4$", color=TEAL, fontsize=14); a1.text(30, 5.9, "$n_f=5$", color=TEAL, fontsize=14)
a1.annotate("five flavours\ncontinued down", xy=(2.1, 1/run2(a_mb, 2*np.log(mb), 2*np.log(2.1), 5)), xytext=(9, 3.25),
            fontsize=13, color=MUTED, arrowprops={"arrowstyle": "-", "color": MUTED})
a1.set_xscale("log"); a1.set_xlabel("scale  $\\mu$  (GeV)"); a1.set_ylabel("inverse coupling  $1/\\alpha_S$"); style(a1)
a1.set_title("Two-loop coupling", fontsize=14); a1.set_ylim(2.8, 10)
xl2 = np.logspace(-4, np.log10(0.6), 60)
for mu, col, ls in ((2.0, INK, "-"), (10.0, ORANGE, "-"), (100.0, TEAL, "-")):
    a2.plot(xl2, [mellin_inv(lambda N: charm_moment(N, zc(mu)), x) for x in xl2], color=col, lw=2.2, ls=ls, label=f"$\\mu$ = {mu:g} GeV")
a2.set_xscale("log"); a2.set_xlabel("momentum fraction  $x$"); a2.set_ylabel("$x\\,(c+\\bar c)$"); style(a2)
a2.legend(fontsize=13, loc="upper right"); a2.set_title("Charm generated from zero at $m_c$", fontsize=14); a2.set_ylim(0, None)
fig.savefig(OUT / "1-5-thresholds.svg", bbox_inches="tight"); plt.close(fig)

# 3. the large-x exponent
fig, ax = plt.subplots(figsize=(8, 4.6)); style(ax)
Q2l = np.logspace(np.log10(Q02), 5, 60); ax.plot(Q2l, 3 + shift(zeta_of(Q2l)), color=TEAL, lw=2.4, label="Eq. (1.5.31):  $3+C_F\\zeta/\\pi b$")
Q2p = np.array([Q02, 6, 15, 40, 100, 300, 1e3, 3e3, 1e4, 3e4, 1e5])
def slope(Q2, xa, xb):
    z = zeta_of(Q2); fa, fb = (mellin_inv(lambda N: vN(N)*E_ns(N, z, 4), x) for x in (xa, xb))
    return np.log(fb/fa)/np.log((1 - xb)/(1 - xa))
ax.plot(Q2p, [slope(q, 0.95, 0.98) for q in Q2p], "o", color=INK, ms=7, mfc="white", mew=1.8, label="exact solution, $0.95<x<0.98$")
ax.plot(Q2p, [slope(q, 0.6, 0.7) for q in Q2p], "s", color=ORANGE, ms=6.5, mfc="white", mew=1.8, label="exact solution, $0.6<x<0.7$")
ax.set_xscale("log"); ax.set_xlabel("scale  $Q^2$  (GeV$^2$)"); ax.set_ylabel("effective exponent of $(1-x)$")
ax.legend(fontsize=13, loc="upper left"); ax.set_title("Valence distribution at large $x$: toy input $(1-x)^3$ at $Q_0$", fontsize=14)
fig.savefig(OUT / "1-5-largex.svg", bbox_inches="tight"); plt.close(fig)
info(f"large-x exponents at Q2=1e4: 0.95-0.98: {slope(1e4, 0.95, 0.98):.3f}; 0.6-0.7: {slope(1e4, 0.6, 0.7):.3f}; formula {3 + shift(zeta_of(1e4)):.3f}")

print("wrote 3 plots to assets/guide;", "ALL CHECKS PASS" if ok else "SOME CHECKS FAILED")
sys.exit(0 if ok else 1)
