#!/usr/bin/env python3
"""Numerical checks for guide chapter 1.3 (the parton model from field theory), and its data plot.
Every formula the chapter states that can be tested is tested here; the script exits non-zero if any check fails.
Run:  python3 guide-build/tools/check_1_3.py        (writes assets/guide/1-3-scaling.svg)"""
import pathlib, sys
import numpy as np
from scipy import integrate

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

quad = lambda f, a, b, **kw: integrate.quad(f, a, b, limit=400, epsabs=1e-13, epsrel=1e-11, **kw)[0]
rng = np.random.default_rng(13)

# --- Dirac matrices and four-vector helpers (metric +,-,-,-; components (E, px, py, pz)) -----------
I2 = np.eye(2); Z2 = np.zeros((2, 2))
sig = [np.array([[0, 1], [1, 0]]), np.array([[0, -1j], [1j, 0]]), np.array([[1, 0], [0, -1]])]
g = [np.block([[I2, Z2], [Z2, -I2]])] + [np.block([[Z2, s], [-s, Z2]]) for s in sig]
met = np.diag([1., -1, -1, -1])
dot = lambda a, b: a @ met @ b
sl = lambda a: sum(g[m] * (met @ a)[m] for m in range(4))
tr = lambda *ms: np.trace(np.linalg.multi_dot(ms)).real if len(ms) > 1 else np.trace(ms[0]).real

Pz = 40.0
p = np.array([Pz, 0, 0, Pz]); n = np.array([1/(2*Pz), 0, 0, -1/(2*Pz)])
check("p^2 = 0", dot(p, p), 0); check("n^2 = 0", dot(n, n), 0); check("n.p = 1", dot(n, p), 1)

# --- section 1: the time-scale estimate, eq. (1.3.1) ------------------------------------------------
xi, kT, Q2, x = 0.3, 0.4, 50.0, 0.3
Pbig = 1e4
E_pair = np.hypot(xi*Pbig, kT) + np.hypot((1-xi)*Pbig, kT)
check("energy cost of a quark + spectator pair = kT^2 / (2 xi (1-xi) P)", (E_pair - Pbig)*Pbig, kT**2/(2*xi*(1-xi)), 1e-6)
nu = Q2/(2*x)
tau_int, tau_life = 2*Pbig/nu, 2*xi*(1-xi)*Pbig/kT**2
check("ratio of times = 2 kT^2 / ((1-x) Q^2) at xi = x", tau_int/tau_life, 2*kT**2/((1-x)*Q2))
print(f"INFO  ratio of times for kT = 0.4 GeV, x = 0.3: Q2 = 50 GeV^2 -> {2*kT**2/((1-x)*50):.4f}; Q2 = 4 GeV^2 -> {2*kT**2/((1-x)*4):.3f}")

# --- section 3: light-cone dominance, eqs. (1.3.6)-(1.3.9) -----------------------------------------
Mp, hbarc = 0.93827, 0.19733                         # proton mass (GeV), hbar c (GeV fm)
for xB, Q2 in [(0.1, 10.0), (0.01, 10.0), (0.3, 100.0)]:
    q0 = Q2/(2*Mp*xB); q3 = np.sqrt(q0**2 + Q2)       # proton at rest, photon along +z
    qplus, qminus = q0 + q3, q0 - q3
    check(f"q+ q- = -Q^2 (x={xB}, Q2={Q2:g})", qplus*qminus, -Q2)
    nach = 2*xB/(1 + np.sqrt(1 + 4*Mp**2*xB**2/Q2))
    check(f"q- = -M * Nachtmann variable (x={xB}, Q2={Q2:g})", qminus, -Mp*nach)
    print(f"INFO  x={xB}, Q2={Q2:g}: q- = {qminus:.5f} GeV, -Mx = {-Mp*xB:.5f} GeV, q+ = {qplus:.2f} GeV, "
          f"1/(Mx) = {hbarc/(Mp*xB):.2f} fm, 2/Q = {2*hbarc/np.sqrt(Q2):.3f} fm")
check("1/(M x) at x = 0.1 in fm", hbarc/(Mp*0.1), 2.103, 2e-4)
check("1/(M x) at x = 0.01 in fm", hbarc/(Mp*0.01), 21.03, 2e-4)
# z^2 = z+ z- - zT^2 in light-cone components
zv = rng.normal(size=4)
check("z^2 = z+ z- - zT^2", dot(zv, zv), (zv[0]+zv[3])*(zv[0]-zv[3]) - zv[1]**2 - zv[2]**2)
qv = rng.normal(size=4)
check("q.z = (q+ z- + q- z+)/2 - qT.zT", dot(qv, zv),
      ((qv[0]+qv[3])*(zv[0]-zv[3]) + (qv[0]-qv[3])*(zv[0]+zv[3]))/2 - qv[1]*zv[1] - qv[2]*zv[2])

# --- section 4: Sudakov decomposition and the projections, eqs. (1.3.10)-(1.3.13) --------------------
kv = rng.normal(size=4)*3
a, b = dot(n, kv), dot(p, kv)
kTv = kv - a*p - b*n
check("n.kT = 0", dot(n, kTv), 0, 1e-9); check("p.kT = 0", dot(p, kTv), 0, 1e-9)
check("kT has no time or z component", abs(kTv[0]) + abs(kTv[3]), 0, 1e-9)
check("k^2 = 2ab - kT^2", dot(kv, kv), 2*a*b + dot(kTv, kTv))
nu, Q = 37.0, 5.0; Q2 = Q*Q; x = Q2/(2*nu)
qTv = np.array([0, Q*np.cos(0.7), Q*np.sin(0.7), 0])
q = nu*n + qTv
check("q^2 = -Q^2", dot(q, q), -Q2); check("p.q = nu", dot(p, q), nu); check("n.q = 0", dot(n, q), 0)
F1, F2 = 0.83, 0.41                                   # arbitrary values of the two structure functions
ginv = met                                            # g^{alpha beta}
W = (-ginv + np.outer(q, q)/dot(q, q))*F1 + np.outer(p + q/(2*x), p + q/(2*x))*F2/nu
nl, pl, ql = met @ n, met @ p, met @ q
check("current conservation q_alpha W^{alpha beta} = 0", np.abs(ql @ W).max(), 0, 1e-9)
check("nu n n W = F2", nu*(nl @ W @ nl), F2)
check("(4x^2/nu) p p W = F2 - 2x F1", 4*x*x/nu*(pl @ W @ pl), F2 - 2*x*F1)
check("-g_{ab} W^{ab} = 3F1 - F2/(2x)", -np.trace(met @ W), 3*F1 - F2/(2*x), 1e-9)

# --- section 5: the handbag, eqs. (1.3.14)-(1.3.22) -------------------------------------------------
xi, k2, phi, kT = 0.37, -0.9, 2.1, 0.65
kTv = np.array([0, kT*np.cos(phi), kT*np.sin(phi), 0])
k = xi*p + (k2 + kT**2)/(2*xi)*n + kTv
check("k^2 from the decomposition (1.3.16)", dot(k, k), k2)
qT_dot_kT = qTv[1]*kTv[1] + qTv[2]*kTv[2]
check("(k+q)^2 = k^2 + 2 xi nu - 2 qT.kT - Q^2", dot(k+q, k+q), k2 + 2*xi*nu - 2*qT_dot_kT - Q2)
l = k + q
check("n.(k+q) = xi", dot(n, l), xi)
check("nslash lslash nslash = 2 (n.l) nslash", np.abs(sl(n) @ sl(l) @ sl(n) - 2*dot(n, l)*sl(n)).max(), 0, 1e-9)
check("pslash lslash pslash = 2 (p.l) pslash", np.abs(sl(p) @ sl(l) @ sl(p) - 2*dot(p, l)*sl(p)).max(), 0, 1e-9)
check("p.l = nu + (k^2 + kT^2)/(2 xi)", dot(p, l), nu + (k2 + kT**2)/(2*xi))
# a free quark of momentum p: B = (2 pi)^4 delta^4(k-p) pslash/4  ->  q(x) = delta(1-x), F_L = 0
check("free quark: Tr[nslash pslash]/4 = 1", tr(sl(n), sl(p))/4, 1)
check("free quark: Tr[pslash pslash] = 0", tr(sl(p), sl(p)), 0, 1e-9)
# general decomposition B = A1 pslash + A2 kslash: the two projections
A1, A2 = 0.7, 1.9
B = A1*sl(p) + A2*sl(k)
check("Tr[nslash B] = 4 (A1 + xi A2)", tr(sl(n), B), 4*(A1 + xi*A2))
check("Tr[pslash B] = 2 A2 (k^2 + kT^2)/xi", tr(sl(p), B), 2*A2*(k2 + kT**2)/xi)

# --- section 6 / D6: the scalar-spectator model -----------------------------------------------------
Ms, Lam = 0.8, 0.8                                   # spectator mass and form-factor scale (GeV): illustrative
xi = 0.41; kT = 0.55
kap = (kT**2 + xi*Ms**2)/(1-xi)                      # |k^2| when the spectator is on shell
k = xi*p + (-kap + kT**2)/(2*xi)*n + np.array([0, kT*np.cos(1.3), kT*np.sin(1.3), 0])
check("spectator on shell: (p-k)^2 = Ms^2", dot(p-k, p-k), Ms**2)
check("p.k = -(|k^2| + Ms^2)/2", dot(p, k), -(kap + Ms**2)/2)
check("Tr[nslash kslash pslash kslash] = 4 kT^2", tr(sl(n), sl(k), sl(p), sl(k)), 4*kT**2)
check("Tr[pslash kslash pslash kslash] = 8 (p.k)^2", tr(sl(p), sl(k), sl(p), sl(k)), 8*dot(p, k)**2)
# positivity: B gamma^0 is a positive matrix for B = kslash pslash kslash (it is for kslash u ubar kslash)
ev = np.linalg.eigvalsh(sl(k) @ sl(p) @ sl(k) @ g[0])
check("kslash pslash kslash gamma^0 has no negative eigenvalue", min(ev.min(), 0.0), 0, 1e-9)
ev2 = np.linalg.eigvalsh(sl(k) @ g[0])
print(f"INFO  kslash gamma^0 alone has eigenvalues {np.round(ev2, 3)} for space-like k: not an allowed B")

gdip = lambda kap: (Lam**2/(Lam**2 + kap))**2        # |g|^2 / g0^2, damped vertex
gpt = lambda kap: 1.0                                # point-like vertex
# everything below is in units of e_q^2 g0^2 / (16 pi^2)
def q_model(x, gh=gdip, tmax=np.inf):
    f = lambda t: t*gh((t + x*Ms**2)/(1-x))/(t + x*Ms**2)**2
    return (1-x)*quad(f, 0, tmax)
def T_model(x, gh=gdip):                             # int d4k/(2pi)^4 Tr[pslash B] delta(xi - x)
    f = lambda t: (t + Ms**2)**2*gh((t + x*Ms**2)/(1-x))/(t + x*Ms**2)**2
    return quad(f, 0, np.inf)/(2*(1-x))

def xi_pm(kap, x, nu):
    Q2 = 2*nu*x
    b1 = 4*(nu*(Q2 + kap) - Q2*(kap + Ms**2))
    disc = max(b1*b1 - 16*nu*nu*(Q2 - kap)**2, 0.0)
    return (b1 - np.sqrt(disc))/(8*nu*nu), (b1 + np.sqrt(disc))/(8*nu*nu)
ug, uw = np.polynomial.legendre.leggauss(48); ug = ug*np.pi/2; uw = uw*np.pi/2      # nodes for u in (-pi/2, pi/2)
def F2_exact(x, Q2, gh=gdip):
    nu = Q2/(2*x)
    def inner(kap):
        lo, hi = xi_pm(kap, x, nu)
        xis = (lo+hi)/2 + (hi-lo)/2*np.sin(ug)
        return gh(kap)/kap**2*np.sum(uw*xis*((1-xis)*kap - xis*Ms**2))
    k0, k1 = x*Ms**2/(1-x), 2*nu - Ms**2
    f = lambda s: inner(np.exp(s))*np.exp(s)          # log variable: the integrand is spread over decades
    return quad(f, np.log(k0), np.log(k1))/np.pi
def FL_exact(x, Q2, gh=gdip):
    nu = Q2/(2*x)
    f = lambda s: gh(np.exp(s))*(2*nu - np.exp(s) - Ms**2)*(np.exp(s) + Ms**2)**2/np.exp(s)
    return x*x/nu**2*quad(f, np.log(x*Ms**2/(1-x)), np.log(2*nu - Ms**2))

# the angular delta function: B^2 - A^2 = 4 nu^2 (xi+ - xi)(xi - xi-) at a random point
x0, Q20, kap0 = 0.3, 30.0, 2.2; nu0 = Q20/(2*x0); lo, hi = xi_pm(kap0, x0, nu0); xx = lo + 0.31*(hi-lo)
A_ = -kap0 + 2*xx*nu0 - Q20; B2_ = 4*Q20*((1-xx)*kap0 - xx*Ms**2)
check("B^2 - A^2 = 4 nu^2 (xi+ - xi)(xi - xi-)", B2_ - A_**2, 4*nu0**2*(hi-xx)*(xx-lo), 1e-9)
check("xi+- -> x as |k^2|/nu -> 0", sum(xi_pm(1.0, 0.3, 1e9))/2, 0.3, 1e-6)

x = 0.3
qx = q_model(x); Tx = T_model(x)
print(f"INFO  model at x = 0.3: q(x) = {qx:.6f}, x q(x) = {x*qx:.6f}, T(x) = {Tx:.6f}  (units g0^2/16 pi^2)")
for Q2, tol in [(1e2, 0.05), (1e4, 1e-3), (1e6, 2e-5)]:
    f2 = F2_exact(x, Q2)
    print(f"INFO  damped vertex: F2(x, Q2={Q2:g}) / (x q(x)) = {f2/(x*qx):.6f}")
    check(f"damped vertex scales: F2(x,Q2={Q2:g}) -> x q(x)", f2, x*qx, tol)
for Q2, tol in [(1e4, 2e-3), (1e6, 5e-5)]:
    fl = FL_exact(x, Q2)
    check(f"damped vertex: Q2 F_L(Q2={Q2:g}) -> 8 x^3 T(x)", Q2*fl, 8*x**3*Tx, tol)
    print(f"INFO  damped vertex: F_L/F_2 at Q2={Q2:g} = {fl/F2_exact(x, Q2):.3e}")
# the kT-weighted reading of F_L:  F_L/F_2 -> 4 <kT^2 + ...>/Q^2 with the model's own average
avg = 2*x*Tx/qx                                      # 4 <.>/Q^2 = 8 x^3 T / (x q Q^2)  =>  <.> = 2 x^2 T / q
print(f"INFO  damped vertex: Q2 F_L/F_2 -> {8*x**3*Tx/(x*qx):.4f} GeV^2")
# point-like vertex: F2 grows like x(1-x) ln Q2, F_L tends to a constant 2x^2
s1 = (F2_exact(x, 1e7, gpt) - F2_exact(x, 1e5, gpt))/np.log(100.0)
check("point-like vertex: dF2/dlnQ2 -> x(1-x)", s1, x*(1-x), 2e-4)
check("point-like vertex: F_L -> 2 x^2 (not suppressed)", FL_exact(x, 1e7, gpt), 2*x*x, 1e-4)
# the model's distribution: number and momentum of the quark, with g0 fixed by one quark
num = quad(lambda y: q_model(y), 0, 1); mom = quad(lambda y: y*q_model(y), 0, 1)
print(f"INFO  model: int q dx = {num:.5f} (g0^2/16pi^2 = {1/num:.4f} for one quark); quark momentum fraction {mom/num:.4f}, "
      f"spectator {1-mom/num:.4f}")

# --- section 7 / D7: the operator definition, moments and sum rules --------------------------------
# a test distribution on 0 < x < 1 (quarks only); f(lam) = <P| psibar(0) nslash psi(lam n) |P> = 2 int dx q(x) e^{-i lam x}
xg, xw = np.polynomial.legendre.leggauss(600); xg = (xg+1)/2; xw = xw/2
qt = lambda x: 60*x**2*(1-x)**3                      # int = 1, int x q = 3/7
f_lam = lambda lam: 2*np.sum(xw*qt(xg)*np.exp(-1j*np.outer(np.atleast_1d(lam), xg)), axis=1)
check("first moment: f(0)/2 = int q", (f_lam(0.0)[0]/2).real, 1.0)
h = 1e-4
d1 = (f_lam(h)[0] - f_lam(-h)[0])/(2*h)
check("second moment: (i/2) f'(0) = int x q", (0.5j*d1).real, 3/7, 1e-7)
d2 = (f_lam(h)[0] - 2*f_lam(0.0)[0] + f_lam(-h)[0])/h**2
check("third moment: (1/2)(i d/dlam)^2 f(0) = int x^2 q", (-0.5*d2).real, quad(lambda y: y*y*qt(y), 0, 1), 1e-5)
lam = np.arange(-600, 600, 0.02); fl_ = f_lam(lam)
inv = lambda x0: (np.sum(np.exp(1j*lam*x0)*fl_)*0.02/(4*np.pi)).real
check("inverse transform returns q(0.35)", inv(0.35), qt(0.35), 1e-4)
check("support: transform vanishes at x = 1.4", inv(1.4), 0, 1e-4)
check("support: transform vanishes at x = -0.3 (no antiquarks in the test function)", inv(-0.3), 0, 1e-4)
# the projector: gamma^0 nslash = (1/P) Pi_+ with Pi_+ = (1 + gamma^0 gamma^3)/2 a hermitian projector
Pi = (np.eye(4) + g[0] @ g[3])/2
check("gamma^0 nslash = Pi_+ / P", np.abs(g[0] @ sl(n) - Pi/Pz).max(), 0, 1e-12)
check("Pi_+^2 = Pi_+", np.abs(Pi @ Pi - Pi).max(), 0, 1e-12)
check("Pi_+ hermitian", np.abs(Pi - Pi.conj().T).max(), 0, 1e-12)
check("Pi_+ has rank 2", np.trace(Pi).real, 2)
# number sum rule from <P| j^mu |P> = 2 p^mu N:  (1/2) n_mu 2 p^mu N = N ; momentum: (1/2) n n 2 A p p = A
check("(1/2) n_mu (2 p^mu N) = N", 0.5*dot(n, 2*p*2.0), 2.0)
check("(1/2) n_mu n_nu (2 A p^mu p^nu) = A", 0.5*2*0.54*dot(n, p)**2, 0.54)
# ESW eq. (4.24) sum rules with a simple illustrative valence shape: numbers 2 and 1
from scipy.special import beta as Beta
uv = lambda x: 2*x**-0.5*(1-x)**3/Beta(0.5, 4); dv = lambda x: x**-0.5*(1-x)**4/Beta(0.5, 5)
check("int u_v = 2 (illustrative shape)", quad(uv, 0, 1), 2, 1e-6)
check("int d_v = 1 (illustrative shape)", quad(dv, 0, 1), 1, 1e-6)

# --- section 9: the infinite-momentum frame ---------------------------------------------------------
Rp = 0.84                                            # proton charge radius, fm
xw_ = hbarc/(2*Rp*Mp)
check("wee threshold x = 1/(2 R M)", xw_, 0.1252, 1e-3)
print(f"INFO  x below which 1/(xP) exceeds the disc thickness 2RM/P: {xw_:.4f}")
Pp = 920.0                                           # HERA proton beam momentum, GeV
print(f"INFO  at P = 920 GeV: disc thickness 2RM/P = {2*Rp*Mp/Pp:.5f} fm; 1/(xP) at x=1e-4: {hbarc/(1e-4*Pp):.3f} fm")
check("disc thickness at P = 920 GeV (fm)", 2*Rp*Mp/Pp, 0.001713, 1e-3)
check("1/(xP) at x = 1e-4, P = 920 GeV (fm)", hbarc/(1e-4*Pp), 2.145, 1e-3)

# --- the data plot: approach to scaling in the model ------------------------------------------------
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
plt.rcParams.update({"font.size": 14, "font.family": ["Helvetica Neue", "Arial", "DejaVu Sans"], "svg.fonttype": "none"})
Q2s = np.logspace(0.5, 5, 28)
damp = np.array([F2_exact(x, Q2) for Q2 in Q2s]); pt = np.array([F2_exact(x, Q2, gpt) for Q2 in Q2s])
f10d, f10p = F2_exact(x, 10.0), F2_exact(x, 10.0, gpt)
print(f"INFO  damped vertex: F2(Q2=10)/(x q) = {f10d/(x*qx):.4f}; point-like: F2(1e5)/F2(10) = {F2_exact(x, 1e5, gpt)/f10p:.3f}")
fig, ax = plt.subplots(figsize=(8, 4.6))
ax.axhline(x*qx/f10d, color="#16222e", lw=1.2, ls="--")
ax.plot(Q2s, damp/f10d, color="#0e7c7b", lw=2.6); ax.plot(Q2s, pt/f10p, color="#d96c2c", lw=2.6)
ax.set_xscale("log"); ax.set_xlim(Q2s[0], Q2s[-1]); ax.set_ylim(0, 4.5)
ax.set_xlabel("photon virtuality  Q²  (GeV²)", fontsize=14)
ax.set_ylabel("model F₂(x = 0.3, Q²) / F₂(x = 0.3, 10 GeV²)", fontsize=13)
ax.text(1.2e3, 0.3, "damped vertex:\nF₂ → x q(x), scaling", color="#0e7c7b", fontsize=14)
ax.text(12, 3.3, "point-like vertex:\nF₂ rises as x(1−x) ln Q²", color="#d96c2c", fontsize=14)
ax.grid(True, color="#ebe6da", lw=0.8); ax.set_axisbelow(True)
for s in ("top", "right"): ax.spines[s].set_visible(False)
fig.tight_layout()
out = pathlib.Path(__file__).resolve().parents[2] / "assets" / "guide"
out.mkdir(parents=True, exist_ok=True)
fig.savefig(out / "1-3-scaling.svg", facecolor="white")
print(f"INFO  plot range: damped {damp.min():.3f}..{damp.max():.3f}, point-like {pt.min():.3f}..{pt.max():.3f}")
print("wrote assets/guide/1-3-scaling.svg;", "ALL CHECKS PASS" if ok else "SOME CHECKS FAILED")
sys.exit(0 if ok else 1)
