#!/usr/bin/env python3
"""Numerical checks for guide chapter 1.2 (the parton model and Bjorken scaling), 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_2.py     (writes assets/guide/1-2-*.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 &= good
    print(f"{'PASS' if good else 'FAIL'}  {name}: got {got:.10g}, want {want:.10g}")

q = 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(12)

# --- Dirac algebra with explicit matrices ---------------------------------------------------------
I2 = np.eye(2); Z2 = np.zeros((2, 2))
sig = [np.array([[0, 1], [1, 0]]), np.array([[0, -1j], [1j, 0]]), np.array([[1, 0], [0, -1]])]
g = [np.block([[I2, Z2], [Z2, -I2]])] + [np.block([[Z2, s], [-s, Z2]]) for s in sig]
g5 = 1j * g[0] @ g[1] @ g[2] @ g[3]
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, v] * g[v] for v in range(4)) for m in range(4)]        # gamma_mu (index lowered)
ONE = np.eye(4); PL = (ONE - g5) / 2; PR = (ONE + g5) / 2

def two_to_two(E, th):
    """Massless 2 -> 2 momenta in the centre-of-mass frame: k + p -> k' + p'."""
    k = np.array([E, 0, 0, E]); p = np.array([E, 0, 0, -E])
    k1 = np.array([E, E*np.sin(th), 0, E*np.cos(th)]); p1 = k + p - k1
    return k, p, k1, p1

def contract(A, B, C, D, XA=ONE, XB=ONE):
    """Tr[A g^mu B g^nu XA] Tr[C g_mu D g_nu XB]"""
    return sum(np.trace(A @ g[m] @ B @ g[v] @ XA) * np.trace(C @ gl[m] @ D @ gl[v] @ XB)
               for m in range(4) for v in range(4)).real

for E, th in [(3.0, 0.7), (11.0, 2.1)]:
    k, p, k1, p1 = two_to_two(E, th)
    s, t, u = 2*dot(k, p), -2*dot(k, k1), -2*dot(k1, p)
    check(f"s + t + u = 0 (theta={th})", s + t + u, 0, 1e-9)
    # D1: spin-averaged |M|^2 / (e^4 e_q^2) = (1/4) L.Q / t^2 = 2 (s^2+u^2)/t^2
    LQ = contract(sl(k1), sl(k), sl(p1), sl(p))
    check("lepton x quark trace = 8 (s^2 + u^2)", LQ, 8*(s*s + u*u), 1e-9)
    check("spin-averaged |M|^2 = 2 (s^2+u^2)/t^2", 0.25*LQ/t**2, 2*(s*s + u*u)/t**2, 1e-9)
    # helicity pieces: equal chiralities give s^2, opposite give u^2
    check("equal helicities: 4 s^2", contract(sl(k1), sl(k), sl(p1), sl(p), PL, PL), 4*s*s, 1e-9)
    check("opposite helicities: 4 u^2", contract(sl(k1), sl(k), sl(p1), sl(p), PL, PR), 4*u*u, 1e-9)
    # centre-of-mass angle:  1 - y = -u/s = cos^2(theta/2)
    check("1 - y = cos^2(theta/2)", -u/s, np.cos(th/2)**2)
    # D3: scalar parton, vertex (p+p')^mu:  L^{mu nu} V_mu V_nu = -8 s u
    V = p + p1
    LVV = sum(np.trace(sl(k1) @ g[m] @ sl(k) @ g[v]) * (met @ V)[m] * (met @ V)[v] for m in range(4) for v in range(4)).real
    check("scalar parton: L.VV = -8 s u", LVV, -8*s*u, 1e-9)
    # D4: V-A charged current. neutrino on quark -> 256 (k.p)(k'.p'), on antiquark -> 256 (k.p')(k'.p)
    X = ONE - g5
    Tq = sum(np.trace(sl(k1) @ g[m] @ X @ sl(k) @ g[v] @ X) * np.trace(sl(p1) @ gl[m] @ X @ sl(p) @ gl[v] @ X)
             for m in range(4) for v in range(4)).real
    Tqb = sum(np.trace(sl(k1) @ g[m] @ X @ sl(k) @ g[v] @ X) * np.trace(sl(p) @ gl[m] @ X @ sl(p1) @ gl[v] @ X)
              for m in range(4) for v in range(4)).real
    check("V-A, neutrino-quark: 256 (k.p)(k'.p') = 64 s^2", Tq, 64*s*s, 1e-9)
    check("V-A, neutrino-antiquark: 256 (k.p')(k'.p) = 64 u^2", Tqb, 64*u*u, 1e-9)

# --- cross-sections: from |M|^2 to d sigma / dQ^2 --------------------------------------------------
alpha = 1/137.036; eq2 = 4/9
for y in (0.15, 0.6):
    s_hat = 40.0; u_hat = -s_hat*(1-y); t_hat = -(s_hat + u_hat); Q2 = -t_hat
    M2 = 2*eq2*(4*np.pi*alpha)**2*(s_hat**2 + u_hat**2)/t_hat**2
    check(f"spin-1/2: d sigma/dQ^2 = 2 pi alpha^2 e_q^2 [1+(1-y)^2]/Q^4 (y={y})",
          M2/(16*np.pi*s_hat**2), 2*np.pi*alpha**2*eq2*(1 + (1-y)**2)/Q2**2)
    M2s = 0.5*eq2*(4*np.pi*alpha)**2*(-8*s_hat*u_hat)/t_hat**2
    check(f"spin-0: d sigma/dQ^2 = 4 pi alpha^2 e_q^2 (1-y)/Q^4 (y={y})",
          M2s/(16*np.pi*s_hat**2), 4*np.pi*alpha**2*eq2*(1-y)/Q2**2)
    # matching to  (4 pi alpha^2/Q^4) [ y^2 F1 + (1-y) F2/x ]  with weights w1 = F1, w2 = F2/x
    check("spin-1/2 matching: F1 = 1/2, F2/x = 1", y*y*0.5 + (1-y)*1.0, 0.5*(1 + (1-y)**2))
    check("spin-0 matching: F1 = 0, F2/x = 1", y*y*0.0 + (1-y)*1.0, (1-y))
    # the two forms of the cross-section bracket (ESW 4.5 and the y^2 F1 form), random F1, F2
    F1, F2, x = rng.uniform(0.2, 2), rng.uniform(0.2, 2), rng.uniform(0.1, 0.9)
    check("[1+(1-y)^2] F1 + (1-y)(F2-2xF1)/x = y^2 F1 + (1-y) F2/x",
          (1 + (1-y)**2)*F1 + (1-y)*(F2 - 2*x*F1)/x, y*y*F1 + (1-y)*F2/x)
    # neutrino: (1/2)[(1-y)F2 + y^2 xF1 +- y(1-y/2) xF3] with F2 = 2xF1 = 2x(a+b), xF3 = 2x(a-b)
    a, b = rng.uniform(0.1, 2), rng.uniform(0.1, 2)
    F2n, xF3 = 2*x*(a + b), 2*x*(a - b)
    check("neutrino bracket = 2x [a + (1-y)^2 b]", 0.5*((1-y)*F2n + y*y*F2n/2 + y*(1-y/2)*xF3)*2, 2*x*(a + (1-y)**2*b))
    check("antineutrino bracket = 2x [(1-y)^2 a + b]", 0.5*((1-y)*F2n + y*y*F2n/2 - y*(1-y/2)*xF3)*2, 2*x*((1-y)**2*a + b))
check("two-body phase space: int dt/(8 pi s) over -s<t<0 = 1/(8 pi)", q(lambda t: 1/(8*np.pi*7.0), -7.0, 0), 1/(8*np.pi))
check("int_0^1 (1-y)^2 dy = 1/3", q(lambda y: (1-y)**2), 1/3)
check("int_0^1 [1+(1-y)^2]/2 dy = 2/3", q(lambda y: (1 + (1-y)**2)/2), 2/3)

# --- DIS kinematics of the struck parton -----------------------------------------------------------
Pm = 400.0
P = np.array([Pm, 0, 0, Pm]); k = np.array([30.0, 0, 0, -30.0])
S = 2*dot(k, P)
for x, y in [(0.25, 0.4), (0.05, 0.8)]:
    Q2 = x*y*S
    # outgoing lepton: k' = (1-y) k + x y P + kT, with kT^2 = (1-y) Q^2, satisfies k'^2 = 0
    kT = np.sqrt((1-y)*Q2); k1 = (1-y)*k + x*y*P + np.array([0, kT, 0, 0]); qv = k - k1
    check(f"k'^2 = 0 (x={x})", dot(k1, k1), 0, 1e-9)
    check("Q^2 = x y s", -dot(qv, qv), Q2, 1e-9)
    check("y = q.P/k.P", dot(qv, P)/dot(k, P), y, 1e-9)
    check("x = Q^2/2nu", Q2/(2*dot(P, qv)), x, 1e-9)
    xi = x; pq = xi*P
    check("on-shell struck parton at xi = x", dot(pq + qv, pq + qv), 0, 1e-9)
    check("s_hat = xi s", 2*dot(k, pq), xi*S, 1e-9)
    check("u_hat = -s_hat (1-y)", -2*dot(pq, k1), -xi*S*(1-y), 1e-9)
# target-mass version of the on-shell condition: xi^2 M^2 + 2 xi nu - Q^2 = 0
M = 0.938
for x, Q2 in [(0.3, 4.0), (0.6, 20.0)]:
    nu = Q2/(2*x)
    xi = 2*x/(1 + np.sqrt(1 + 4*x*x*M*M/Q2))
    check(f"xi = 2x/(1+sqrt(1+4x^2M^2/Q^2)) solves the on-shell condition (x={x})", xi*xi*M*M + 2*xi*nu - Q2, 0, 1e-9)
    print(f"INFO  target mass: x={x}, Q2={Q2}: xi/x = {xi/x:.4f}, leading correction 1 - x^2M^2/Q^2 = {1 - x*x*M*M/Q2:.4f}")
check("xi/x at x=0.3, Q2=4", 2/(1 + np.sqrt(1 + 4*0.09*M*M/4.0)), 0.981, 2e-3)

# --- D2: time scales in the fast-moving frame ---------------------------------------------------------
Pz = 1000.0; xis = np.array([0.5, 0.3, 0.2]); kTs = np.array([0.3, 0.3, 0.0]); ms = np.array([0.3, 0.3, 0.3])
# transverse momenta: two partons back to back with 0.3 GeV, the third at rest transversely
exact = np.sum(np.sqrt((xis*Pz)**2 + kTs**2 + ms**2)) - np.sqrt(Pz**2 + M**2)
Delta = np.sum((kTs**2 + ms**2)/xis) - M**2
check("energy defect of a configuration / (Delta/2P) = 1", exact/(Delta/(2*Pz)), 1, 1e-6)
x, Q2 = 0.25, 20.0
ratio = 2*x*Delta/Q2
print(f"INFO  Delta = {Delta:.4f} GeV^2; tau_int/tau_fluct = 2 x Delta/Q^2 = {ratio:.4f} at x={x}, Q2={Q2}")
check("Delta for the example configuration", Delta, 0.18/0.5 + 0.18/0.3 + 0.09/0.2 - M*M)
check("tau_int/tau_fluct (worked number)", ratio, 0.0133, 2e-2)
# photon q = nu n + qT in the frame of chapter 1.4: energy nu/(2P)
nu = Q2/(2*x); p_lc = np.array([Pz, 0, 0, Pz]); n_lc = np.array([1/(2*Pz), 0, 0, -1/(2*Pz)])
qv = nu*n_lc + np.array([0, np.sqrt(Q2), 0, 0])
check("q^2 = -Q^2 for q = nu n + qT", dot(qv, qv), -Q2); check("p.q = nu", dot(p_lc, qv), nu)
check("photon energy = nu/2P = Q^2/(4xP)", qv[0], Q2/(4*x*Pz))

# --- form factor of an extended charge (dipole) -------------------------------------------------------
hc2 = 0.19733**2                                    # (hbar c)^2 in GeV^2 fm^2
GD = lambda Q2: (1 + Q2/0.71)**-2
r2 = 12/0.71*hc2
check("dipole: <r^2> = 12/0.71 GeV^-2 = 0.66 fm^2", r2, 0.658, 2e-3)
check("dipole: rms radius 0.81 fm", np.sqrt(r2), 0.811, 2e-3)
h = 1e-6; check("<r^2> = -6 dG/dQ^2 at 0", -6*(GD(h) - GD(0))/h, 12/0.71, 1e-4)
check("G_D(20 GeV^2) = 1.2e-3", GD(20.0), 1.18e-3, 1e-2)
check("G_D^2(20 GeV^2) = 1.4e-6", GD(20.0)**2, 1.38e-6, 1e-2)
# exponential charge density  rho ~ exp(-a r)  has exactly the dipole form factor (1+Q^2/a^2)^-2
a = np.sqrt(0.71); Qv = 1.3
ff = integrate.quad(lambda r: 4*np.pi*r*r*(a**3/(8*np.pi))*np.exp(-a*r)*np.sin(Qv*r)/(Qv*r), 0, 80, limit=400)[0]
check("Fourier transform of exp(-a r) density = dipole", ff, GD(Qv**2), 1e-7)

# --- toy distributions (NOT a fit): shapes x f = A x^a (1-x)^c, normalised by the sum rules ----------
B = special.beta
Au, Ad = 2/B(0.5, 4), 1/B(0.5, 5)
xuv = lambda x: Au*x**0.5*(1-x)**3
xdv = lambda x: Ad*x**0.5*(1-x)**4
ADel = 11*0.148                                     # int (dbar - ubar) dx = 0.148, the NMC central value
xDel = lambda x: ADel*x*(1-x)**10                   # x (dbar - ubar)
sea_mom = 0.17
As = sea_mom/(5*B(0.8, 8))
xS = lambda x: As*x**-0.2*(1-x)**7                  # x (ubar + dbar)/2
xub = lambda x: xS(x) - xDel(x)/2
xdb = lambda x: xS(x) + xDel(x)/2
xs = lambda x: 0.5*xS(x)                            # x s = x sbar, half the light-sea average
mom_val = q(xuv) + q(xdv)
Ag = (1 - mom_val - sea_mom)/B(0.8, 6)
xg = lambda x: Ag*x**-0.2*(1-x)**5
check("toy: int u_v dx = 2", q(lambda x: xuv(x)/x), 2, 1e-7)
check("toy: int d_v dx = 1", q(lambda x: xdv(x)/x), 1, 1e-7)
check("toy: u_v momentum = 2/9", q(xuv), 2/9); check("toy: d_v momentum = 1/11", q(xdv), 1/11)
mom_sea = 2*q(lambda x: xub(x) + xdb(x) + xs(x))
check("toy: sea momentum", mom_sea, sea_mom)
mom_q = mom_val + mom_sea
check("toy: momentum sum rule", mom_q + q(xg), 1.0)
print(f"INFO  toy momentum fractions: valence {mom_val:.3f}, sea {mom_sea:.3f}, all quarks {mom_q:.3f}, gluon {q(xg):.3f}")
xx = np.linspace(1e-4, 1, 4001)
check("toy: ubar >= 0 everywhere", float(np.min(xub(xx)) >= 0), 1)
check("toy: int (dbar - ubar) dx = 0.148", q(lambda x: xDel(x)/x), 0.148)
xU = lambda x: xuv(x) + 2*xub(x); xD = lambda x: xdv(x) + 2*xdb(x); xSS = lambda x: 2*xs(x)   # x(q + qbar)
F2p = lambda x: (4*xU(x) + xD(x) + xSS(x))/9
F2n = lambda x: (4*xD(x) + xU(x) + xSS(x))/9
print(f"INFO  toy: int F2p = {q(F2p):.3f}, int F2n = {q(F2n):.3f}; peaks x u_v {xuv(1/7):.3f} at 1/7, x d_v {xdv(1/9):.3f} at 1/9")
check("toy: x u_v peaks at x = 1/7", xx[np.argmax(xuv(xx))], 1/7, 2e-3)

# momentum audit with the textbook integrals 0.18 and 0.12
eu, ed = np.linalg.solve(np.array([[4/9, 1/9], [1/9, 4/9]]), np.array([0.18, 0.12]))
check("momentum audit: epsilon_u = 0.36", eu, 0.36); check("momentum audit: epsilon_d = 0.18", ed, 0.18)
check("momentum audit: quarks carry 0.54", eu + ed, 0.54)
check("(18/5)(0.18+0.12)/2 = 0.54", 18/5*0.15, 0.54)

# --- F2n/F2p bounds ------------------------------------------------------------------------------------
for _ in range(4):
    U, D, Sx = rng.exponential(1, 3)
    r = (4*D + U + Sx)/(4*U + D + Sx)
    check("1/4 <= F2n/F2p <= 4 (random non-negative densities)", float(0.25 <= r <= 4), 1)
    check("r - 1/4 = (15 D + 3 S)/(4 (4U + D + S))", r - 0.25, (15*D + 3*Sx)/(4*(4*U + D + Sx)))
    check("4 - r = (15 U + 3 S)/(4U + D + S)", 4 - r, (15*U + 3*Sx)/(4*U + D + Sx))
rat = lambda x: F2n(x)/F2p(x)
check("toy: F2n/F2p -> 1 at small x", rat(1e-8), 1, 1e-2)
check("toy: F2n/F2p -> 1/4 as x -> 1", rat(1 - 1e-6), 0.25, 1e-3)
check("no sea, d_v = u_v/2: ratio = 2/3", (4*0.5 + 1)/(4 + 0.5), 2/3)
print(f"INFO  toy ratio F2n/F2p at x = 0.1, 0.3, 0.5, 0.7: " + ", ".join(f"{rat(v):.3f}" for v in (0.1, 0.3, 0.5, 0.7)))

# --- Gottfried, GLS, Adler, 5/18 -------------------------------------------------------------------------
SG = q(lambda x: (F2p(x) - F2n(x))/x)
check("toy Gottfried sum = 1/3 - (2/3) 0.148", SG, 1/3 - 2/3*0.148)
check("Gottfried integrand = (x/3)(u_v - d_v) + (2x/3)(ubar - dbar)", F2p(0.2) - F2n(0.2),
      (xuv(0.2) - xdv(0.2))/3 - 2*xDel(0.2)/3)
check("NMC: int (dbar - ubar) = (3/2)(1/3 - 0.235) = 0.148", 1.5*(1/3 - 0.235), 0.148, 2e-3)
check("NMC: its uncertainty (3/2) 0.026 = 0.039", 1.5*0.026, 0.039)
for _ in range(3):
    u, ub, d, db, st, sb, c, cb = rng.exponential(1, 8)
    x = 0.3
    F2nu_p, F2nu_n = 2*x*(d + st + ub + cb), 2*x*(u + st + db + cb)
    xF3nu_p, xF3nu_n = 2*x*(d + st - ub - cb), 2*x*(u + st - db - cb)
    xF3nb_p, xF3nb_n = 2*x*(u + c - db - sb), 2*x*(d + c - ub - sb)
    F2nb_p = 2*x*(u + c + db + sb)
    check("isoscalar xF3, nu and nubar averaged = x(u_v + d_v + s - sbar + c - cbar)",
          (xF3nu_p + xF3nu_n + xF3nb_p + xF3nb_n)/4, x*(u - ub + d - db + st - sb + c - cb))
    check("Adler integrand: F2(nubar p) - F2(nu p) = 2x(u_v - d_v + c - cbar - s + sbar)",
          F2nb_p - F2nu_p, 2*x*(u - ub - d + db + c - cb - st + sb))
    # symmetric s = sbar, c = cbar for the 5/18 relation
    s2, c2 = st, c
    Sig = u + ub + d + db + 2*s2 + 2*c2
    F2eN = x*(5/18*(u + ub + d + db) + 2*s2/9 + 8*c2/9)
    F2nuN = x*(u + ub + d + db + 2*s2 + 2*c2)
    check("F2(nu N) = x Sigma for s = sbar, c = cbar", (2*x*(d + s2 + ub + c2) + 2*x*(u + s2 + db + c2))/2, F2nuN)
    check("F2(eN)/F2(nuN) = (5/18)[1 - (3/5)(s+sbar-c-cbar)/Sigma]", F2eN/F2nuN, 5/18*(1 - 0.6*(2*s2 - 2*c2)/Sig))
check("mean squared charge of u and d = 5/18", (4/9 + 1/9)/2, 5/18)
check("toy GLS: int (u_v + d_v) dx = 3", q(lambda x: (xuv(x) + xdv(x))/x), 3, 1e-7)
kap = q(xSS)/q(lambda x: xU(x) + xD(x) + xSS(x))
print(f"INFO  toy: strange momentum share (s+sbar)/Sigma = {kap:.3f}; integrated F2eN/F2nuN = {5/18*(1 - 0.6*kap):.4f} vs 5/18 = {5/18:.4f}")
check("toy: 5/18 ratio with strange correction, from the integrals",
      q(lambda x: (F2p(x) + F2n(x))/2)/q(lambda x: xU(x) + xD(x) + xSS(x)), 5/18*(1 - 0.6*kap))
# total neutrino cross-section ratio on an isoscalar target and the antiquark share
R = 0.5; check("Qbar/Q = (3R-1)/(3-R) = 0.2 at R = 0.5", (3*R - 1)/(3 - R), 0.2)
Qm, Qbm = 1.0, 0.2; check("R from Qbar/Q = 0.2", (Qbm + Qm/3)/(Qm + Qbm/3), 0.5)
Qt = q(lambda x: xuv(x) + xdv(x) + xub(x) + xdb(x)); Qbt = q(lambda x: xub(x) + xdb(x))
print(f"INFO  toy: Qbar/Q = {Qbt/Qt:.3f}, giving sigma(nubar)/sigma(nu) = {(Qbt + Qt/3)/(Qt + Qbt/3):.3f} (strange neglected)")
check("GLS with the leading QCD correction at alpha_S = 0.3: 3(1 - alpha_S/pi)", 3*(1 - 0.3/np.pi), 2.714, 1e-3)

# --- plots -------------------------------------------------------------------------------------------------
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, "axes.spines.top": False, "axes.spines.right": False, "svg.fonttype": "path",
                     "font.family": "sans-serif", "figure.facecolor": "white", "axes.facecolor": "white"})
def base():
    fig, ax = plt.subplots(figsize=(8, 4.6)); ax.grid(True, color=GRID, lw=1); ax.set_axisbelow(True); return fig, ax

# 1. extended charge against point charge
fig, ax = base()
Q2s = np.logspace(-1, 2, 300)
ax.loglog(Q2s, np.ones_like(Q2s), color=TEAL, lw=2.6)
ax.loglog(Q2s, GD(Q2s)**2, color=ORANGE, lw=2.6)
ax.text(0.13, 2.2, "point charge: no suppression at any $Q^2$", color=TEAL, fontsize=14)
ax.text(0.13, 1.2e-7, "extended charge of radius 0.81 fm:\nsuppression $G_D^2(Q^2)$", color=ORANGE, fontsize=14)
ax.set_xlabel("momentum transfer squared, $Q^2$ (GeV$^2$)"); ax.set_ylabel("elastic rate relative to a point charge")
ax.set_ylim(1e-9, 30); ax.set_xlim(0.1, 100)
fig.tight_layout(); fig.savefig(OUT / "1-2-formfactor.svg"); plt.close(fig)

# 2. the toy distributions
fig, ax = base()
xp = np.linspace(0.005, 1, 600)
for f, lab, col, ls in [(xg, "gluon, $x\\,g$", INK, "-"), (xuv, "up valence, $x\\,u_v$", TEAL, "-"),
                        (xdv, "down valence, $x\\,d_v$", ORANGE, "-"), (xdb, "anti-down, $x\\,\\bar d$", ORANGE, "--"),
                        (xub, "anti-up, $x\\,\\bar u$", TEAL, "--"), (xs, "strange, $x\\,s=x\\,\\bar s$", MUTED, ":")]:
    ax.plot(xp, f(xp), color=col, lw=2.4, ls=ls, label=lab)
ax.legend(loc="upper right", frameon=False, fontsize=14, handlelength=2.6)
ax.set_xlim(0, 1); ax.set_ylim(0, 1.0)
ax.set_xlabel("momentum fraction $x$"); ax.set_ylabel("momentum density $x\\,f(x)$")
ax.text(0.52, 0.30, "illustrative shapes fixed by the\nsum rules, not a fit to data", color=MUTED, fontsize=13)
fig.tight_layout(); fig.savefig(OUT / "1-2-toy-pdfs.svg"); plt.close(fig)

# 3. the neutron-to-proton ratio and its bounds
fig, ax = base()
xr = np.linspace(0.002, 0.999, 500)
ax.axhspan(0.25, 1.05, color=TEAL, alpha=0.07, lw=0)
ax.axhline(0.25, color=INK, lw=1.4, ls="--"); ax.axhline(2/3, color=MUTED, lw=1.4, ls=":")
ax.plot(xr, rat(xr), color=TEAL, lw=2.6)
nosea = lambda x: (4*xdv(x) + xuv(x))/(4*xuv(x) + xdv(x))
ax.plot(xr, nosea(xr), color=ORANGE, lw=2.2, ls="--")
ax.text(0.03, 0.27, "lower bound 1/4: only $u$ quarks", color=INK, fontsize=13)
ax.text(0.58, 0.685, "2/3: no sea and $d_v=u_v/2$", color=MUTED, fontsize=13)
ax.text(0.30, 0.90, "toy set with sea", color=TEAL, fontsize=14)
ax.text(0.04, 0.53, "toy valence only", color=ORANGE, fontsize=14)
ax.set_xlim(0, 1); ax.set_ylim(0.2, 1.05)
ax.set_xlabel("momentum fraction $x$"); ax.set_ylabel("ratio $F_2^n/F_2^p$")
fig.tight_layout(); fig.savefig(OUT / "1-2-ratio.svg"); plt.close(fig)

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