#!/usr/bin/env python3
"""Numerical checks for guide chapter 2.1 (parametrisation, sum rules, positivity), 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_2_1.py     (writes assets/guide/2-1-*.svg)"""
import pathlib, sys
import numpy as np
from scipy import integrate, special
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt

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}")

def info(s): print("INFO  " + s)

G = special.gamma
I = lambda a, b: G(a + 1) * G(b + 1) / G(a + b + 2)            # int_0^1 x^a (1-x)^b dx, eq. (2.1.15)
def quad_pow(g, a):
    """int_0^1 x^a g(x) dx for a > -1, with x = u^(1/(a+1)) so that the end-point singularity is removed."""
    p = 1.0 / (a + 1.0)
    return integrate.quad(lambda u: g(u ** p), 0, 1, limit=800, epsabs=1e-13, epsrel=1e-12,
                          points=[0.5, 0.9, 0.99, 0.999])[0] * p

# ---------------------------------------------------------------------------------------------------
# section 3: Chebyshev polynomials and the variable y = 1 - 2 sqrt(x)
# ---------------------------------------------------------------------------------------------------
def T(n, y):                                                   # by the recurrence, eq. (2.1.8)
    t0, t1 = np.ones_like(y), y
    if n == 0: return t0
    for _ in range(n - 1): t0, t1 = t1, 2 * y * t1 - t0
    return t1

th = 0.83
for n in (1, 3, 6):
    check(f"T_{n}(cos th) = cos({n} th)", float(T(n, np.cos(th))), np.cos(n * th))
yy = np.array(0.37)
explicit = {1: yy, 2: 2*yy**2 - 1, 3: 4*yy**3 - 3*yy, 4: 8*yy**4 - 8*yy**2 + 1,
            5: 16*yy**5 - 20*yy**3 + 5*yy, 6: 32*yy**6 - 48*yy**4 + 18*yy**2 - 1}
for n, v in explicit.items():
    check(f"explicit polynomial T_{n}", float(v), float(T(n, yy)))
for n in (1, 4, 6):
    check(f"T_{n}(1) = 1  (x -> 0)", float(T(n, np.array(1.0))), 1.0)
    check(f"T_{n}(-1) = (-1)^n  (x -> 1)", float(T(n, np.array(-1.0))), (-1.0) ** n)
# orthogonality with weight 1/sqrt(1-y^2): substitute y = cos(th)
orth = lambda m, n: integrate.quad(lambda t: np.cos(m * t) * np.cos(n * t), 0, np.pi)[0]
check("orthogonality <T_2,T_5> = 0", orth(2, 5), 0.0)
check("norm <T_3,T_3> = pi/2", orth(3, 3), np.pi / 2)

def tau(n):
    """Coefficients of T_n(1 - 2 s) = sum_k tau[k] s^k, from the recurrence of eq. (2.1.16)."""
    c = [1.0]
    for k in range(n):
        c.append(c[-1] * (k * k - n * n) / ((k + 0.5) * (k + 1.0)))
    return np.array(c)

for n in range(1, 9):
    s = 0.2371
    check(f"series for T_{n}(1-2s)", float(np.polyval(tau(n)[::-1], s)), float(T(n, np.array(1 - 2 * s))), 1e-10)
    k = np.arange(n + 1)
    closed = (-1.0) ** k * n * special.factorial(n + k - 1) / (special.factorial(n - k) * special.factorial(2 * k)) * 4.0 ** k
    check(f"closed form of tau_{n},k (max dev)", float(np.max(np.abs(closed - tau(n)) / np.abs(closed))), 0.0, 1e-12)
check("tau_2 = (1,-8,8)", float(np.abs(tau(2) - np.array([1, -8, 8])).max()), 0.0)
check("tau_3 = (1,-18,48,-32)", float(np.abs(tau(3) - np.array([1, -18, 48, -32])).max()), 0.0)
# the hypergeometric equation s(1-s)F'' + (1/2 - s)F' + n^2 F = 0 for F(s) = T_n(1-2s)
n, s = 5, 0.31
F = np.polynomial.Polynomial(tau(n))
check("T_5(1-2s) solves the hypergeometric equation", s * (1 - s) * F.deriv(2)(s) + (0.5 - s) * F.deriv(1)(s) + n * n * F(s), 0.0, 1e-9)

# how the two candidate variables spread the data region over [-1, 1]  (table in section 3)
for x in (1e-4, 1e-2, 0.1, 0.5):
    info(f"x = {x:g}:  1-2sqrt(x) = {1 - 2*np.sqrt(x):.3f},   1-2x = {1 - 2*x:.4f}")
check("fraction of [-1,1] given to 1e-4<x<1e-2 by 1-2sqrt(x)", (2*np.sqrt(1e-2) - 2*np.sqrt(1e-4)) / 2, 0.09)
check("fraction of [-1,1] given to 1e-4<x<1e-2 by 1-2x", (2e-2 - 2e-4) / 2, 0.0099)

# ---------------------------------------------------------------------------------------------------
# sections 2 and 5: the Beta integral and the Chebyshev moments
# ---------------------------------------------------------------------------------------------------
check("Gamma(a)Gamma(b) = Gamma(a+b) B(a,b)", G(1.7) * G(2.6), G(4.3) * special.beta(1.7, 2.6))
for a, b in ((-0.66, 3.75), (0.34, 3.75), (-0.01, 7.04)):
    check(f"I({a},{b}) against quadrature", I(a, b), quad_pow(lambda x: (1 - x) ** b, a), 1e-9)
check("I(a,b) = B(a+1,b+1)", I(0.3, 2.2), special.beta(1.3, 3.2))
for d in (1e-2, 1e-4):
    info(f"delta * I(delta-1, 3.75) = {d * I(d - 1, 3.75):.5f} at delta = {d:g}  (-> 1: the number integral diverges as 1/delta)")
check("delta I(delta-1,eta) -> 1 as delta -> 0", 1e-6 * I(1e-6 - 1, 3.75), 1.0, 1e-5)

def Ic(n, a, b):                                               # first line of eq. (2.1.17)
    return sum(t * I(a + 0.5 * k, b) for k, t in enumerate(tau(n)))
def cheb_int(a, b, c):                                         # J(a,b;c), second line of eq. (2.1.17)
    return I(a, b) + sum(ci * Ic(i + 1, a, b) for i, ci in enumerate(c))
for n in (1, 2, 4, 6):
    for a, b in ((-0.66, 3.75), (0.67, 5.25)):
        num = quad_pow(lambda x: (1 - x) ** b * T(n, 1 - 2 * np.sqrt(x)), a)
        check(f"Chebyshev moment n={n}, a={a}, b={b}", Ic(n, a, b), num, 1e-8)
# the binomial route used in the project's code agrees with the series route
a, b = -0.66, 3.75
Iy2 = I(a, b) - 4 * I(a + .5, b) + 4 * I(a + 1, b)
Iy4 = I(a, b) - 8 * I(a + .5, b) + 24 * I(a + 1, b) - 32 * I(a + 1.5, b) + 16 * I(a + 2, b)
check("code route: Ic4 = 8 Iy4 - 8 Iy2 + I", 8 * Iy4 - 8 * Iy2 + I(a, b), Ic(4, a, b), 1e-10)

# ---------------------------------------------------------------------------------------------------
# sections 4 and 5: the MSHT20 form at the publication parameter point of the project's port
# (values copied from analysis/msht20/msht20_model/msht20_model/input_mshtfit_publication_shortmin.dat)
# ---------------------------------------------------------------------------------------------------
uv = dict(d=0.34359110680421356, e=3.748657630257328,
          c=[-1.4485203963068545, 0.7414364465358945, -0.3388642818301362, 0.2280848321195746, -0.09711848793057141, 0.0])
dv = dict(d=0.1282679461193071, e=3.979488631894834,
          c=[-0.6458627025417831, -1.0084703291029582, 0.9089438747936651, -0.037370288283984136, -0.13569928165046855, 0.18212207494760163])
S = dict(A=41.58449323857026, d=-0.009876269835192724, e=7.04310422436405,
         c=[-1.7767116962046965, 1.3784164636765508, -0.8889378927790684, 0.46253485385558746, -0.1714246671894168, 0.03857700228145249])
sp = dict(A=0.3507526996185292, d=S["d"], e=3.3216182269099597,
          c=[-0.12325713325327833, 0.7069012358154876, -0.01869621773020992, -0.01803450004502132, 0.16233132301019212, -0.11341329021966999])
g = dict(e=5.251270998324863, d=0.6697611015665883,
         c=[-0.7692192888244083, 1.053858946235386, -0.2945725663935634, 0.18899337352783627],
         Am=-0.36797267610953976, em=1.34544084908059, dm=-0.2780248209456775)
sm = dict(A=-0.00020242971145737493, d=0.0014906899461692123, e=7.459056728811248)
rho = dict(A=3.2658603567888016, e=2.7349338912295797,
           c=[-0.5233663315323309, -1.1131362882747111, 1.5019462076096963, -1.154365488496816, 0.5317645918880659, -0.13328110490804296])

n_free = (2 + 6) + (2 + 6) + (3 + 6) + (2 + 6) + (2 + 4 + 3) + 2 + (2 + 6)
check("free parameters: 8+8+9+8+9+2+8", n_free, 52)
check("slots: 9+9+9+9+10+10+8+9", 9 + 9 + 9 + 9 + 10 + 10 + 8 + 9, 73)
check("73 slots - 9 charm - 4 sum rules - 1 tie - 7 frozen", 73 - 9 - 4 - 1 - 7, 52)

series = lambda x, c: 1 + sum(ci * T(i + 1, 1 - 2 * np.sqrt(x)) for i, ci in enumerate(c))
shape = lambda x, p: x ** p["d"] * (1 - x) ** p["e"] * series(x, p["c"])       # x f / A

# the four constraints, in the order the code applies them (derivation D4)
x0 = I(sm["d"], sm["e"]) / I(sm["d"] - 1, sm["e"])                              # eq. (2.1.19)
A_uv = 2 / cheb_int(uv["d"] - 1, uv["e"], uv["c"])                              # eq. (2.1.18)
A_dv = 1 / cheb_int(dv["d"] - 1, dv["e"], dv["c"])
m_uv = A_uv * cheb_int(uv["d"], uv["e"], uv["c"])                               # momentum fractions <x>_f
m_dv = A_dv * cheb_int(dv["d"], dv["e"], dv["c"])
m_S = S["A"] * cheb_int(S["d"], S["e"], S["c"])
m_sp = sp["A"] * cheb_int(sp["d"], sp["e"], sp["c"])
g1 = cheb_int(g["d"], g["e"], g["c"]); g2 = g["Am"] * I(g["dm"], g["em"])
A_g = (1 - m_uv - m_dv - m_S - g2) / g1                                         # eq. (2.1.20)
info(f"publication point: A_uv = {A_uv:.4f}, A_dv = {A_dv:.4f}, A_g = {A_g:.4f}, x0 = {x0:.4e}")
info(f"momentum fractions: u_v {m_uv:.4f}, d_v {m_dv:.4f}, sea S {m_S:.4f} (of which s+ {m_sp:.4f}), "
     f"gluon {A_g*g1 + g2:.4f} = {A_g*g1:.4f} + ({g2:.4f})")
info(f"bare number integral of u_v without Chebyshev terms: I = {I(uv['d']-1, uv['e']):.4f}; with them: {2/A_uv:.4f}")

xu = lambda x: A_uv * shape(x, uv); xd = lambda x: A_dv * shape(x, dv)
xS = lambda x: S["A"] * shape(x, S); xsp = lambda x: sp["A"] * shape(x, sp)
xg = lambda x: A_g * x ** g["d"] * (1 - x) ** g["e"] * series(x, g["c"]) + g["Am"] * x ** g["dm"] * (1 - x) ** g["em"]
xsm = lambda x: sm["A"] * x ** sm["d"] * (1 - x) ** sm["e"] * (1 - x / x0)
ratio = lambda x: rho["A"] * (1 - x) ** rho["e"] * series(x, rho["c"])           # dbar/ubar

# the sum rules, by direct quadrature of the assembled shapes
check("valence sum rule: int u_v dx = 2", A_uv * quad_pow(lambda x: (1 - x) ** uv["e"] * series(x, uv["c"]), uv["d"] - 1), 2.0, 1e-8)
check("valence sum rule: int d_v dx = 1", A_dv * quad_pow(lambda x: (1 - x) ** dv["e"] * series(x, dv["c"]), dv["d"] - 1), 1.0, 1e-8)
n1 = quad_pow(lambda x: (1 - x) ** sm["e"], sm["d"] - 1); n2 = quad_pow(lambda x: (1 - x) ** sm["e"], sm["d"])
check("strangeness: int (s - sbar) dx = 0  (relative to either term)", (n1 - n2 / x0) / n1, 0.0, 1e-7)
check("x0 = delta/(delta+eta+1)", x0, sm["d"] / (sm["d"] + sm["e"] + 1), 1e-12)
mom = sum(integrate.quad(f, 0, 1, limit=800, points=[1e-6, 1e-3, 0.1])[0] for f in (xu, xd, xS, xg))
check("momentum sum rule: int x (Sigma + g) dx = 1", mom, 1.0, 1e-8)
check("momentum fraction of u_v by quadrature", integrate.quad(xu, 0, 1, limit=400)[0], m_uv, 1e-8)

# flavour assembly (section 4): the sea S is the whole sea, and the quark total is u_v + d_v + S
x = np.array([1e-4, 1e-3, 1e-2, 0.1, 0.3, 0.6])
light = (xS(x) - xsp(x)) / 2                                   # x(ubar + dbar)
ub = light / (1 + ratio(x)); db = light * ratio(x) / (1 + ratio(x))
s, sb = (xsp(x) + xsm(x)) / 2, (xsp(x) - xsm(x)) / 2
u, d = xu(x) + ub, xd(x) + db
Sigma = u + ub + d + db + s + sb
check("Sigma = u_v + d_v + S on the grid", float(np.max(np.abs(Sigma - (xu(x) + xd(x) + xS(x))))), 0.0, 1e-12)
check("dbar/ubar = rho on the grid", float(np.max(np.abs(db / ub - ratio(x)))), 0.0, 1e-12)
T3, T8, V, V3, V8 = (u + ub) - (d + db), (u + ub) + (d + db) - 2 * (s + sb), (u - ub) + (d - db) + (s - sb), (u - ub) - (d - db), (u - ub) + (d - db) - 2 * (s - sb)
check("V = u_v + d_v + s_- on the grid", float(np.max(np.abs(V - (xu(x) + xd(x) + xsm(x))))), 0.0, 1e-12)
check("T8 = Sigma - 3 s_+ on the grid", float(np.max(np.abs(T8 - (Sigma - 3 * xsp(x))))), 0.0, 1e-12)
check("V8 = V - 3 s_- on the grid", float(np.max(np.abs(V8 - (V - 3 * xsm(x))))), 0.0, 1e-12)

# small-x limits used in section 6: every T_n -> 1, so the series tends to 1 + sum(c)
rho0 = rho["A"] * (1 + sum(rho["c"]))
check("dbar/ubar at x -> 0 equals A_rho (1 + sum c)", float(ratio(np.array(1e-14))), rho0, 1e-5)
light0 = (S["A"] * (1 + sum(S["c"])) - sp["A"] * (1 + sum(sp["c"]))) / 2
info(f"rho(0) = {rho0:.3f}; x(ubar+dbar) -> {light0:.3f} x^delta_S, so x(dbar-ubar) -> {light0*(rho0-1)/(1+rho0):.3f} x^({S['d']:.4f}): it does not vanish")
check("x(dbar - ubar) x^-delta_S at x = 1e-12 against its limit", float((light[0]*0 + (xS(np.array(1e-12)) - xsp(np.array(1e-12))) / 2 * (ratio(np.array(1e-12)) - 1) / (1 + ratio(np.array(1e-12)))) * 1e-12 ** (-S["d"])), light0 * (rho0 - 1) / (1 + rho0), 1e-4)

# derivation D6 and eq. (2.1.6): large x is large N, and the valence power grows under evolution
eta_, Nbig = 3.0, 1e5
check("moment of (1-x)^eta -> Gamma(eta+1) N^(-eta-1)", float(np.exp(special.gammaln(Nbig) + special.gammaln(eta_ + 1) - special.gammaln(Nbig + eta_ + 1)) / (G(eta_ + 1) * Nbig ** (-eta_ - 1))), 1.0, 1e-3)
CF = 4 / 3; b4 = (33 - 2 * 4) / (12 * np.pi)
check("C_F/(pi b) = 16/25 for n_f = 4", CF / (np.pi * b4), 0.64)
check("shift of eta when the coupling halves: 0.64 ln 2", CF / (np.pi * b4) * np.log(2), 0.4436, 1e-4)
Hn = special.digamma(Nbig + 1) + np.euler_gamma
check("gamma_qq(N) / (-2 C_F ln N) -> 1 at large N", CF * (1.5 + 1 / (Nbig * (Nbig + 1)) - 2 * Hn) / (-2 * CF * np.log(Nbig)), 1.0, 5e-2)

# positivity at this parameter point (section 6)
xs = np.logspace(-6, np.log10(0.99), 4000)
cross = xs[np.where(np.diff(np.sign(xg(xs))))[0]]
info(f"x g changes sign at x = {', '.join(f'{c:.4f}' for c in cross)}; x g(1e-4) = {float(xg(np.array(1e-4))):.3f}, x g(1e-2) = {float(xg(np.array(1e-2))):.3f}")
for nm, f in (("x d_v", xd), ("x(ubar+dbar)", lambda x: (xS(x) - xsp(x)) / 2), ("dbar/ubar", ratio), ("x u_v", xu), ("x S", xS), ("x s+", xsp)):
    cr = xs[np.where(np.diff(np.sign(f(xs))))[0]]
    info(f"{nm}: sign changes on 1e-6 < x < 0.99 at x = {', '.join(f'{c:.3f}' for c in cr) or 'none'}; minimum {f(xs).min():.3g}")
xg0 = float(cross[0]) if len(cross) else float("nan")
check("x g < 0 below the crossing, > 0 above", float(np.sign(xg(np.array(xg0 / 3))) - np.sign(xg(np.array(xg0 * 3)))), -2.0)
info(f"min of x u_v, x d_v, x S, x s+, x(ubar+dbar), dbar/ubar on 1e-6<x<0.99: "
     f"{xu(xs).min():.2e}, {xd(xs).min():.2e}, {xS(xs).min():.2e}, {xsp(xs).min():.2e}, {((xS(xs)-xsp(xs))/2).min():.2e}, {ratio(xs).min():.2e}")
# ELU penalty of eq. (2.1.22): linear for negative observables, saturating for positive ones
elu = lambda t, al: np.where(t > 0, t, al * (np.exp(t) - 1))
check("ELU(-(-0.3)) = 0.3: a negative observable is penalised linearly", float(elu(0.3, 1e-7)), 0.3)
check("ELU(-(+5)) = -alpha(1-e^-5): a positive one costs at most alpha", float(elu(-5.0, 1e-7)), -1e-7 * (1 - np.exp(-5)), 1e-12)

# effective exponents (section 2): the nominal powers are reached only at the end-points
def eff(f, x, wrt):
    """d ln f / d ln x at x (wrt='x'), or d ln f / d ln(1-x) at 1-x = x (wrt='1-x'; pass u = 1-x)."""
    h = 1e-5
    if wrt == "x":
        return (np.log(abs(f(x * (1 + h)))) - np.log(abs(f(x * (1 - h))))) / (np.log1p(h) - np.log1p(-h))
    return (np.log(abs(f(1 - x * (1 + h)))) - np.log(abs(f(1 - x * (1 - h))))) / (np.log1p(h) - np.log1p(-h))
for xv in (0.5, 0.9, 0.99, 0.9999):
    info(f"effective large-x power of x u_v at x = {xv}: {eff(xu, 1 - xv, '1-x'):.3f}  (eta = {uv['e']:.3f})")
for xv in (1e-2, 1e-4, 1e-8):
    info(f"effective small-x power of x u_v at x = {xv:g}: {eff(xu, xv, 'x'):.3f}  (delta = {uv['d']:.3f})")
check("effective large-x power -> eta as x -> 1", eff(xu, 1e-6, "1-x"), uv["e"], 1e-4)
check("effective small-x power -> delta as x -> 0", eff(xu, 1e-14, "x"), uv["d"], 1e-4)
info(f"counting rule 2 n_s - 1: valence 3, gluon 5, sea 7; port values eta_uv {uv['e']:.2f}, eta_dv {dv['e']:.2f}, eta_g {g['e']:.2f}, eta_S {S['e']:.2f}")

# ---------------------------------------------------------------------------------------------------
# section 7: FK tables as matrices on a grid (toy kernels; the grid of 50 nodes is illustrative)
# ---------------------------------------------------------------------------------------------------
nodes = np.concatenate([np.logspace(-5, -1, 26)[:-1], np.linspace(0.1, 1.0, 25)])
check("toy grid has 50 nodes", len(nodes), 50)
tgrid = np.log(nodes)
def w(k, z):                                                   # piecewise-linear interpolation in ln x, w_k(x_j) = delta_jk
    e = np.zeros(len(nodes)); e[k] = 1.0
    return np.interp(np.log(z), tgrid, e, left=0.0, right=0.0)
fgrid = xu(nodes[:-1]); fgrid = np.append(fgrid, 0.0)          # x u_v at the nodes (zero at x = 1)
# DIS-like: T(x) = int_x^1 dz/z C(x/z) f(z), with a smooth toy coefficient function C(z) = z(1 + z)
C = lambda z: z * (1 + z)
xI = 0.02
def FK_dis(k):
    lo, hi = max(xI, nodes[max(k - 1, 0)]), nodes[min(k + 1, len(nodes) - 1)]
    if hi <= lo: return 0.0
    return integrate.quad(lambda z: C(xI / z) * w(k, z) / z, lo, hi, points=[nodes[k]] if lo < nodes[k] < hi else None, limit=200)[0]
FK = np.array([FK_dis(k) for k in range(len(nodes))])
f_int = lambda z: np.interp(np.log(z), tgrid, fgrid)           # the interpolant the table assumes
inside = [float(v) for v in nodes if xI < v < 1]
exact_int = integrate.quad(lambda z: C(xI / z) * f_int(z) / z, xI, 1, points=inside, limit=400)[0]
direct = integrate.quad(lambda z: C(xI / z) * xu(z) / z, xI, 1, limit=400)[0]
check("T = FK . f is exact for the interpolated distribution", FK @ fgrid, exact_int, 1e-9)
info(f"toy DIS point: FK . f = {FK @ fgrid:.6f}, convolution with the true shape = {direct:.6f}; "
     f"the difference, {abs(FK @ fgrid / direct - 1):.1e}, is the error of linear interpolation on 50 nodes")
check("interpolation error of the toy table is at the per-cent level", FK @ fgrid, direct, 2e-2)
check("number of FK entries below x_I is zero (only z >= x contributes)", float(np.abs(FK[nodes < nodes[np.searchsorted(nodes, xI) - 1]]).sum()), 0.0)
# hadronic: L(tau) = int_tau^1 dx/x f(x) f(tau/x) = sum_kl f_k FK_kl f_l
tau_h = 0.01
def FK_had(k, l):
    lo, hi = max(tau_h, nodes[max(k - 1, 0)]), nodes[min(k + 1, len(nodes) - 1)]
    lo = max(lo, tau_h / nodes[min(l + 1, len(nodes) - 1)]); hi = min(hi, tau_h / nodes[max(l - 1, 0)])
    if hi <= lo: return 0.0
    brk = sorted({b for b in (nodes[k], tau_h / nodes[l]) if lo < b < hi})
    return integrate.quad(lambda z: w(k, z) * w(l, tau_h / z) / z, lo, hi, points=brk or None, limit=100)[0]
FK2 = np.array([[FK_had(k, l) for l in range(len(nodes))] for k in range(len(nodes))])
brk = sorted({float(v) for v in list(nodes) + list(tau_h / nodes) if tau_h < v < 1})
exact2 = sum(integrate.quad(lambda z: f_int(z) * f_int(tau_h / z) / z, lo, hi, epsabs=1e-13, epsrel=1e-12)[0]
             for lo, hi in zip([tau_h] + brk, brk + [1.0]))
direct2 = integrate.quad(lambda z: xu(z) * xu(tau_h / z) / z, tau_h, 1, limit=400)[0]
check("T = f . FK . f is exact for the interpolated distribution", fgrid @ FK2 @ fgrid, exact2, 1e-8)
info(f"toy hadronic point: f . FK . f = {fgrid @ FK2 @ fgrid:.6f}, with the true shape = {direct2:.6f} (difference {abs(fgrid @ FK2 @ fgrid / direct2 - 1):.1e})")
check("hadronic table is symmetric for identical partons", float(np.abs(FK2 - FK2.T).max()), 0.0, 1e-9)
check("multiplications per DIS point: 14 x 50", 14 * 50, 700)
check("multiplications per hadronic point: (14 x 50)^2", (14 * 50) ** 2, 490000)
# linearity in the PDF but not in the parameters: prediction at theta+dtheta vs first order (Jacobian by the chain rule)
def pred(dl):                                                  # vary delta_uv, renormalising through the sum rule
    p = dict(uv, d=dl); A = 2 / cheb_int(dl - 1, p["e"], p["c"])
    f = np.append(A * shape(nodes[:-1], p), 0.0); return FK @ f, f
h = 1e-5
(Tp, fp), (Tm, fm) = pred(uv["d"] + h), pred(uv["d"] - h)
check("dT/dtheta = FK . df/dtheta (chain rule, eq. 2.1.26)", (Tp - Tm) / (2 * h), FK @ ((fp - fm) / (2 * h)), 1e-9)

# ---------------------------------------------------------------------------------------------------
# section 9: neural-network parameter counts (Ubiali eq. 3.10)
# ---------------------------------------------------------------------------------------------------
npar = lambda arch: sum(arch[j + 1] * (1 + arch[j]) for j in range(len(arch) - 1))
check("2-5-3-1 network has 37 parameters", npar([2, 5, 3, 1]), 37)
check("1-2-1 network has 7 parameters", npar([1, 2, 1]), 7)
check("five networks: 185 parameters", 5 * npar([2, 5, 3, 1]), 185)
check("seven networks: 259 parameters", 7 * npar([2, 5, 3, 1]), 259)

# ---------------------------------------------------------------------------------------------------
# section 8 and derivation D5: bias and variance of a linear fit, analytic and simulated (a toy)
# ---------------------------------------------------------------------------------------------------
rng = np.random.default_rng(21)
N = 60
xd_ = np.logspace(-3, np.log10(0.75), N)                       # where the toy "data" are
truth = lambda x: 2.2 * x ** 0.5 * (1 - x) ** 3 * (1 + 3 * x)  # NOT in the fitted family
sig = 0.03 * truth(xd_)                                        # 3% uncorrelated errors
basis = lambda x, p: np.array([x ** 0.34 * (1 - x) ** 3.75 * T(j, 1 - 2 * np.sqrt(x)) for j in range(p)]).T
x_out = np.array([1e-5, 0.1, 0.95])                            # extrapolation, data region, extrapolation
rows = []
for p in range(1, 10):                                         # p = 1 normalisation + (p - 1) Chebyshev terms
    J = basis(xd_, p) / sig[:, None]; b = truth(xd_) / sig     # whitened design matrix and truth
    Cth = np.linalg.inv(J.T @ J); P = J @ Cth @ J.T
    bias2 = float(b @ (np.eye(N) - P) @ b)                     # bias term of eq. (2.1.28)
    chi2 = []
    for _ in range(4000):
        dvec = b + rng.standard_normal(N)
        th_hat = Cth @ J.T @ dvec
        chi2.append(float(np.sum((dvec - J @ th_hat) ** 2)))
    B = basis(x_out, p)
    fit0 = B @ (Cth @ J.T @ b)                                 # mean fitted curve
    err = np.sqrt(np.einsum("ij,jk,ik->i", B, Cth, B))         # one-sigma band, eq. (2.1.29)
    rows.append((p, bias2, np.mean(chi2), np.trace(P), err / truth(x_out), fit0 / truth(x_out) - 1))
    se = np.std(chi2) / np.sqrt(len(chi2))
    check(f"p={p}: <chi2_min> = N - p + bias term (simulated vs eq. 2.1.28)", np.mean(chi2), N - p + bias2, max(4 * se / (N - p + bias2), 1e-3))
    check(f"p={p}: trace of the projector = p", np.trace(P), p, 1e-6)
    check(f"p={p}: mean prediction variance at the data = p/N", float(np.mean(np.diag(P))), p / N, 1e-6)
for p, bias2, c2, _, err, shift in rows:
    info(f"p={p}: bias term {bias2:9.2f}, <chi2>/N {c2/N:7.3f}; relative band at x=1e-5, 0.1, 0.95: "
         f"{err[0]:.3f}, {err[1]:.4f}, {err[2]:.3f}; relative shift of the mean fit there: {shift[0]:+.3f}, {shift[1]:+.4f}, {shift[2]:+.3f}")

# ---------------------------------------------------------------------------------------------------
# plots
# ---------------------------------------------------------------------------------------------------
TEAL, ORANGE, INK, GRID = "#0e7c7b", "#d96c2c", "#16222e", "#ebe6da"
plt.rcParams.update({"font.size": 14, "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": "none", "font.family": "sans-serif", "legend.frameon": False})
out = pathlib.Path(__file__).resolve().parents[2] / "assets" / "guide"
out.mkdir(parents=True, exist_ok=True)

# figure 1: the Chebyshev polynomials seen in x, for the two choices of variable
xp = np.logspace(-5, 0, 1200)
fig, ax = plt.subplots(1, 2, figsize=(8, 4.3), sharey=True)
shades = [INK, TEAL, ORANGE]
for a, (ymap, title) in zip(ax, ((lambda x: 1 - 2 * np.sqrt(x), "variable 1 − 2√x  (MSHT20)"), (lambda x: 1 - 2 * x, "variable 1 − 2x"))):
    for n, col in zip((2, 4, 6), shades):
        a.plot(xp, T(n, ymap(xp)), color=col, lw=2.2, label=f"order {n}")
    a.set_xscale("log"); a.set_xlabel("momentum fraction x"); a.set_title(title, fontsize=14)
    a.set_xticks([1e-5, 1e-3, 1e-1]); a.set_ylim(-1.15, 1.15)
ax[0].set_ylabel("Chebyshev polynomial"); ax[1].legend(loc="lower left", fontsize=13)
fig.tight_layout(); fig.savefig(out / "2-1-chebyshev.svg"); plt.close(fig)

# figure 2: the input distributions at the publication parameter point, sum rules imposed
xp = np.logspace(-5, np.log10(0.95), 800)
fig, ax = plt.subplots(figsize=(8, 4.6))
ax.axhline(0, color=INK, lw=0.8)
ax.plot(xp, xg(xp), color=TEAL, lw=2.4, label="gluon")
ax.plot(xp, xS(xp), color=ORANGE, lw=2.4, label="sea S")
ax.plot(xp, xu(xp), color=INK, lw=2.4, label="up valence")
ax.plot(xp, xd(xp), color=INK, lw=2.4, ls="--", label="down valence")
ax.plot(xp, xsp(xp), color=ORANGE, lw=2.0, ls=":", label="strange s + s̄")
ax.set_xscale("log"); ax.set_ylim(-1.0, 2.6); ax.set_xlim(1e-5, 1)
ax.set_xlabel("momentum fraction x"); ax.set_ylabel("momentum density at the input scale")
ax.legend(loc="upper right", fontsize=13, ncol=2)
if len(cross):
    ax.annotate("gluon negative\nbelow x ≈ %.3f" % cross[0], xy=(cross[0], 0), xytext=(1.6e-2, -0.75), fontsize=13,
                arrowprops=dict(arrowstyle="->", color=INK))
fig.tight_layout(); fig.savefig(out / "2-1-input.svg"); plt.close(fig)

# figure 4: bias against variance in the toy linear fit
ps = np.array([r[0] for r in rows])
fig, ax = plt.subplots(1, 2, figsize=(8, 4.6))
ax[0].plot(ps, [(N - r[0] + r[1]) / N for r in rows], color=TEAL, lw=2.2, label="expected")
ax[0].plot(ps, [r[2] / N for r in rows], "o", color=ORANGE, ms=7, label="4000 toy fits")
ax[0].axhline(1, color=INK, lw=0.8, ls=":")
ax[0].set_yscale("log"); ax[0].set_xlabel("number of parameters"); ax[0].set_ylabel("minimum χ² per data point")
ax[0].legend(fontsize=13, loc="upper right")
ax[1].plot(ps, [100 * r[4][1] for r in rows], color=INK, lw=2.2, marker="o", label="x = 0.1 (inside)")
ax[1].plot(ps, [100 * r[4][0] for r in rows], color=TEAL, lw=2.2, marker="o", label="x = 10⁻⁵ (below)")
ax[1].plot(ps, [100 * r[4][2] for r in rows], color=ORANGE, lw=2.2, marker="o", label="x = 0.95 (above)")
ax[1].set_yscale("log"); ax[1].set_xlabel("number of parameters"); ax[1].set_ylabel("one-sigma band, per cent")
ax[1].legend(fontsize=13, loc="lower right")
fig.suptitle("Illustrative toy: 60 pseudo-data points, 3% errors", fontsize=13, y=0.99)
fig.tight_layout(); fig.savefig(out / "2-1-bias.svg"); plt.close(fig)

print("wrote 2-1-chebyshev.svg, 2-1-input.svg, 2-1-bias.svg;", "ALL CHECKS PASS" if ok else "SOME CHECKS FAILED")
sys.exit(0 if ok else 1)
