#!/usr/bin/env python3
"""Numerical checks for guide chapter 1.1 (deep inelastic scattering), and its six 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_1.py     (writes assets/guide/1-1-plane.svg, 1-1-xyplane.svg, 1-1-yweights.svg,
1-1-epsilon.svg, 1-1-spectrum.svg, 1-1-scaling.svg)"""
import itertools, pathlib, sys
import numpy as np
from scipy import integrate, optimize
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt

ok = True
def check(name, got, want, tol=1e-9):
    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}")

rng = np.random.default_rng(11)
Mp = 0.938272                                        # proton mass, GeV
met = np.diag([1., -1, -1, -1])
dot = lambda a, b: a @ met @ b

# explicit Dirac matrices (Dirac representation)
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]      # gamma^mu
g5 = 1j * g[0] @ g[1] @ g[2] @ g[3]
sl = lambda a: sum(g[m] * (met @ a)[m] for m in range(4))
eps4 = np.zeros((4, 4, 4, 4))                        # Levi-Civita with upper indices, eps^{0123} = -1
for perm in itertools.permutations(range(4)):
    eps4[perm] = -np.linalg.det(np.eye(4)[list(perm)])

def lab(E, Ep, th, phi=0.3, M=Mp):
    """Fixed-target momenta: massless lepton along z, deflected by th; proton at rest."""
    k = np.array([E, 0, 0, E]); kp = Ep*np.array([1, np.sin(th)*np.cos(phi), np.sin(th)*np.sin(phi), np.cos(th)])
    return k, kp, np.array([M, 0, 0, 0.])

def invariants(k, kp, P):
    q = k - kp; Q2 = -dot(q, q); nu = dot(P, q)
    return dict(q=q, Q2=Q2, nu=nu, x=Q2/(2*nu), y=nu/dot(P, k), W2=dot(P+q, P+q), s=dot(k+P, k+P), M2=dot(P, P))

# --- sections 2-4, D1: kinematics ----------------------------------------------------------------
E, Ep, th = 200.0, 119.0, np.radians(1.5)            # the fixed-target worked example
k, kp, P = lab(E, Ep, th); v = invariants(k, kp, P)
check("Q^2 = 4 E E' sin^2(theta/2)", v["Q2"], 4*E*Ep*np.sin(th/2)**2)
check("nu = M (E - E')", v["nu"], Mp*(E-Ep))
check("y = 1 - E'/E", v["y"], 1-Ep/E)
check("W^2 = M^2 + 2 nu - Q^2", v["W2"], Mp**2 + 2*v["nu"] - v["Q2"])
check("W^2 = M^2 + Q^2 (1-x)/x", v["W2"], Mp**2 + v["Q2"]*(1-v["x"])/v["x"])
check("Q^2 = x y (s - M^2)", v["Q2"], v["x"]*v["y"]*(v["s"]-Mp**2))
check("s = M^2 + 2 M E", v["s"], Mp**2 + 2*Mp*E)
print(f"INFO  fixed target, E=200, E'=119 GeV, theta=1.5 deg: Q2={v['Q2']:.2f} GeV2, nu/M={v['nu']/Mp:.1f} GeV, y={v['y']:.3f}, "
      f"x={v['x']:.4f}, s={v['s']:.1f} GeV2, W2={v['W2']:.1f} GeV2, W={np.sqrt(v['W2']):.2f} GeV")
ft = v
# the same relations in a randomly boosted and rotated frame (they are invariant)
def boost(vec, beta):
    b2 = beta @ beta; gam = 1/np.sqrt(1-b2); L = np.eye(4)
    L[0, 0] = gam; L[0, 1:] = L[1:, 0] = -gam*beta; L[1:, 1:] += (gam-1)*np.outer(beta, beta)/b2
    return L @ vec
beta = np.array([0.3, -0.5, 0.6])
vb = invariants(*[boost(a, beta) for a in (k, kp, P)])
for key in ("Q2", "x", "y", "W2", "s"):
    check(f"{key} is frame independent", vb[key], v[key], 1e-9)
# range of y at fixed x with the proton mass kept:  y <= 1/(1 + M^2 x/(s - M^2)),  reached at theta = pi
xx = 0.4; ymax = 1/(1 + Mp**2*xx/(v["s"]-Mp**2))
kb, kpb, Pb = lab(E, E*(1-ymax), np.pi); vbk = invariants(kb, kpb, Pb)
check("backward scattering sits at y_max", vbk["x"], xx, 1e-9)
# the Breit frame: boost along q until q^0 = 0; then q = (0, 0, 0, -Q)
qv = v["q"]; bz = qv[0]/np.linalg.norm(qv[1:]); qB = boost(qv, bz*qv[1:]/np.linalg.norm(qv[1:]))
check("Breit frame: q^0 = 0", qB[0], 0, 1e-9); check("Breit frame: |q| = Q", np.linalg.norm(qB[1:]), np.sqrt(v["Q2"]))
hbarc = 0.1973269804                                 # GeV fm
print(f"INFO  resolution hbar c/Q: Q=1 GeV -> {hbarc:.3f} fm; Q=10 GeV -> {hbarc/10:.4f} fm; Q=175 GeV -> {hbarc/175:.5f} fm")
check("hbar c / (1 GeV) in fm", hbarc, 0.197, 2e-3)

# collider worked example: HERA, 27.5 GeV electrons on 920 GeV protons; electron deflected by vartheta
Ee, EP, Epr, vth = 27.5, 920.0, 20.0, np.radians(30.0)
pz = np.sqrt(EP**2 - Mp**2)
Pc = np.array([EP, 0, 0, pz]); kc = np.array([Ee, 0, 0, -Ee]); kpc = Epr*np.array([1, np.sin(vth), 0, -np.cos(vth)])
c = invariants(kc, kpc, Pc)
check("collider: Q^2 = 4 Ee E' sin^2(vartheta/2)", c["Q2"], 4*Ee*Epr*np.sin(vth/2)**2)
check("collider: y = 1 - (E'/Ee) cos^2(vartheta/2)", c["y"], 1-(Epr/Ee)*np.cos(vth/2)**2, 1e-6)
check("collider: s = 4 Ee Ep", c["s"], 4*Ee*EP, 1e-4)
check("collider: x = Q^2/(s y)", c["x"], c["Q2"]/(4*Ee*EP*c["y"]), 1e-4)
print(f"INFO  HERA, Ee=27.5, Ep=920, E'=20 GeV, deflection 30 deg: Q2={c['Q2']:.1f} GeV2, y={c['y']:.4f}, x={c['x']:.5f}, "
      f"s={c['s']:.0f} GeV2, sqrt(s)={np.sqrt(c['s']):.1f} GeV, W={np.sqrt(c['W2']):.1f} GeV")
print(f"INFO  s: 20 GeV beam {Mp**2+2*Mp*20:.1f}, 280 GeV beam {Mp**2+2*Mp*280:.1f}, HERA {4*Ee*EP:.0f} GeV2; "
      f"fixed-target beam energy equal to HERA: {4*Ee*EP/(2*Mp):.0f} GeV")
# light-cone vectors of chapter 1.4 with the mass kept:  P = p + (M^2/2) n,  q = nu n + q_T
Pl = 50.0; p = np.array([Pl, 0, 0, Pl]); n = np.array([1/(2*Pl), 0, 0, -1/(2*Pl)])
PP = p + Mp**2/2*n; nu0, Q0 = 7.0, 2.2; qq = nu0*n + np.array([0, Q0, 0, 0])
check("light cone: P^2 = M^2", dot(PP, PP), Mp**2); check("light cone: P.q = nu", dot(PP, qq), nu0)
check("light cone: q^2 = -Q^2", dot(qq, qq), -Q0**2); check("light cone: n.q = 0", dot(n, qq), 0)

# --- section 5, D2: the leptonic tensor ------------------------------------------------------------
Lten = lambda k, kp: 2*(np.outer(k, kp) + np.outer(kp, k) - np.linalg.inv(met)*dot(k, kp))     # upper indices
Ltr = np.array([[0.5*np.trace(sl(kp) @ g[a] @ sl(k) @ g[b]) for b in range(4)] for a in range(4)])
check("leptonic tensor: trace = 2(k k' + k' k - g k.k')", np.abs(Ltr - Lten(k, kp)).max(), 0, 1e-9)
check("q_alpha L^{alpha beta} = 0", np.abs((met @ v["q"]) @ Lten(k, kp)).max(), 0, 1e-9)
check("Q^2 = 2 k.k'", v["Q2"], 2*dot(k, kp))
check("-g_{ab} L^{ab} = 2 Q^2", -np.einsum("ab,ab", met, Lten(k, kp)), 2*v["Q2"])

# --- section 6, D4: the decomposition of the hadronic tensor ----------------------------------------
ginv = np.linalg.inv(met)
def Wten(P, q, F1, F2):
    nu = dot(P, q); x = -dot(q, q)/(2*nu); Ph = P + q/(2*x)
    return (-ginv + np.outer(q, q)/dot(q, q))*F1 + np.outer(Ph, Ph)*F2/nu
F1, F2 = 0.83, 0.41
W = Wten(P, v["q"], F1, F2)
check("q_alpha W^{alpha beta} = 0", np.abs((met @ v["q"]) @ W).max(), 0, 1e-9)
# general ansatz  -W1 g + W2 PP + W4 qq + W5 (Pq + qP) + i W6 (Pq - qP):  conservation on both indices
def ansatz(c, P, q):
    return -c[0]*ginv + c[1]*np.outer(P, P) + c[2]*np.outer(q, q) + c[3]*(np.outer(P, q)+np.outer(q, P)) + 1j*c[4]*(np.outer(P, q)-np.outer(q, P))
basis = [ansatz(np.eye(5)[i], P, v["q"]) for i in range(5)]
ql = met @ v["q"]
A = np.array([np.concatenate([ql @ B, B @ ql]) for B in basis]).T          # 8 equations, 5 unknowns
sv = np.linalg.svd(A, compute_uv=False)
check("conserved tensors built from g, P, q: exactly two", float(np.sum(sv < 1e-9*sv[0])), 2)
nuv, Q2v, xv = v["nu"], v["Q2"], v["x"]
W1, W2 = 0.7, 0.3; W5 = nuv*W2/Q2v; W4 = nuv**2*W2/Q2v**2 - W1/Q2v
T = ansatz([W1, W2, W4, W5, 0], P, v["q"]).real
check("solved ansatz is conserved", np.abs(ql @ T).max(), 0, 1e-9)
check("solved ansatz = two projectors (F1 = W1, F2 = nu W2)", np.abs(T - Wten(P, v["q"], W1, nuv*W2)).max(), 0, 1e-9)
Ph = P + v["q"]/(2*xv); gam2 = 4*Mp**2*xv**2/Q2v
check("Phat.q = 0", dot(Ph, v["q"]), 0, 1e-9); check("Phat^2 = Q^2 (1+gamma^2)/4x^2", dot(Ph, Ph), Q2v*(1+gam2)/(4*xv**2))
# projections with the light-cone vectors (mass kept in P, proton moving along z)
Wl = Wten(PP, qq, F1, F2); nl, pl = met @ n, met @ p; xl = Q0**2/(2*nu0)
check("F2 = nu n_a n_b W^{ab}  (exact in M)", nu0*(nl @ Wl @ nl), F2)
Wl0 = Wten(p, qq, F1, F2)
check("F_L = (4x^2/nu) p_a p_b W^{ab}  (M = 0)", 4*xl**2/nu0*(pl @ Wl0 @ pl), F2 - 2*xl*F1)

# --- section 7, D5: the contraction and the cross-section -------------------------------------------
low = lambda T: met @ T @ met
LW = np.einsum("ab,ab", Lten(k, kp), low(W))
x_, y_, Q2_ = v["x"], v["y"], v["Q2"]
brk = x_*y_**2*F1 + (1 - y_ - Mp**2*x_**2*y_**2/Q2_)*F2
check("L.W = (2Q^2/x y^2)[x y^2 F1 + (1 - y - M^2x^2y^2/Q^2) F2]", LW, 2*Q2_/(x_*y_**2)*brk)
check("L^{ab} P_a P_b = 4 P.k P.k' - M^2 Q^2", (met @ P) @ Lten(k, kp) @ (met @ P), 4*dot(P, k)*dot(P, kp) - Mp**2*Q2_)
check("P.k = Q^2/2xy", dot(P, k), Q2_/(2*x_*y_)); check("P.k' = (Q^2/2xy)(1-y)", dot(P, kp), Q2_/(2*x_*y_)*(1-y_))
check("1 - y - M^2x^2y^2/Q^2 = (E'/E) cos^2(theta/2)", 1 - y_ - Mp**2*x_**2*y_**2/Q2_, Ep/E*np.cos(th/2)**2)
check("M^2 x^2 y^2/Q^2 = M x y/2E", Mp**2*x_**2*y_**2/Q2_, Mp*x_*y_/(2*E))
# Jacobian  d^3k'/E' = M E y dx dy dphi,  by finite differences of (x, y) with respect to (E', cos theta)
def xy(Ep_, ct):
    w = invariants(*lab(E, Ep_, np.arccos(ct))); return np.array([w["x"], w["y"]])
h = 1e-6; ct = np.cos(th)
J = np.column_stack([(xy(Ep+h, ct)-xy(Ep-h, ct))/(2*h), (xy(Ep, ct+h*1e-3)-xy(Ep, ct-h*1e-3))/(2*h*1e-3)])
check("Jacobian: E' dE' dcos(theta) = M E y dx dy", Ep/abs(np.linalg.det(J)), Mp*E*y_, 1e-5)
alpha = 1/137.035999
d_xy = 4*np.pi*alpha**2/(x_*y_*Q2_)*brk                                              # d2sigma/dx dy
d_xy_esw = 8*np.pi*alpha**2*Mp*E/Q2_**2*((1+(1-y_)**2)/2*2*x_*F1 + (1-y_)*(F2-2*x_*F1) - Mp/(2*E)*x_*y_*F2)
check("d2sigma/dxdy equals the form of ESW Eq. (4.2)", d_xy_esw, d_xy)
d_xQ = y_/Q2_*d_xy
FLm = (1+gam2)*F2 - 2*x_*F1
Yp = 1 + (1-y_)**2
check("d2sigma/dxdQ2 = (2 pi a^2/xQ^4)[(Y+ + g^2y^2/2) F2 - y^2 FL]  (mass kept)", d_xQ,
      2*np.pi*alpha**2/(x_*Q2_**2)*((Yp + gam2*y_**2/2)*F2 - y_**2*FLm))
check("massless: x y^2 F1 + (1-y) F2 = [Y+ F2 - y^2 FL]/2", x_*y_**2*F1 + (1-y_)*F2, 0.5*(Yp*F2 - y_**2*(F2-2*x_*F1)))
# laboratory form:  d2sigma/dE' dOmega = alpha^2 cos^2/(4E^2 sin^4) [F2/(E-E') + (2F1/M) tan^2]
lab_form = alpha**2*np.cos(th/2)**2/(4*E**2*np.sin(th/2)**4)*(F2/(E-Ep) + 2*F1/Mp*np.tan(th/2)**2)
check("laboratory form of the cross-section", Ep/(2*np.pi*Mp*E*y_)*d_xy, lab_form)

# --- section 8, D6: photon polarisation -------------------------------------------------------------
qv = v["q"]; q0, qz = qv[0], np.linalg.norm(qv[1:]); zh = qv[1:]/qz
eL = np.concatenate([[qz], q0*zh])/np.sqrt(Q2_)
e1 = np.concatenate([[0], np.cross(zh, [1, 0, 0])]); e1 /= np.sqrt(-dot(e1, e1)); e2 = np.concatenate([[0], np.cross(zh, e1[1:])])
check("eps_L . q = 0", dot(eL, qv), 0, 1e-9); check("eps_L^2 = +1", dot(eL, eL), 1)
check("eps_L = Phat/sqrt(Phat^2)", np.abs(eL - Ph/np.sqrt(dot(Ph, Ph))).max(), 0, 1e-9)
compl = np.outer(e1, e1) + np.outer(e2, e2) - np.outer(eL, eL)
check("completeness: sum_T ee - eL eL = -g + qq/q^2", np.abs(compl - (-ginv + np.outer(qv, qv)/dot(qv, qv))).max(), 0, 1e-9)
lw = low(W)
check("W_T = F1", e1 @ lw @ e1, F1); check("W_L = F_L/2x  (F_L with the mass term)", eL @ lw @ eL, FLm/(2*x_))
ll = low(Lten(k, kp))
LL = eL @ ll @ eL; LT = e1 @ ll @ e1 + e2 @ ll @ e2
check("L_L = (4Q^2/y^2)(1 - y - g^2y^2/4)/(1+g^2)", LL, 4*Q2_/y_**2*(1-y_-gam2*y_**2/4)/(1+gam2))
check("L_T = (4Q^2/y^2)(1 - y + y^2/2 + g^2y^2/4)/(1+g^2)", LT, 4*Q2_/y_**2*(1-y_+y_**2/2+gam2*y_**2/4)/(1+gam2))
epsf = lambda y, g2: (1-y-g2*y*y/4)/(1-y+y*y/2+g2*y*y/4)
check("epsilon = L_L/L_T", LL/LT, epsf(y_, gam2))
check("L.W = L_T F1 + L_L F_L/2x", LW, LT*F1 + LL*FLm/(2*x_))
R = FLm/(2*x_*F1)
check("d2sigma/dxdQ2 = (2 pi a^2 y^2/Q^6) L_T F1 (1 + eps R)", d_xQ, 2*np.pi*alpha**2*y_**2/Q2_**3*LT*F1*(1+epsf(y_, gam2)*R))
e_ = epsf(y_, gam2); sT = 4*np.pi**2*alpha/(v["nu"]*(1-x_))*F1; sL = 4*np.pi**2*alpha/(v["nu"]*(1-x_))*FLm/(2*x_)
check("d2sigma/dxdQ2 = Gamma (sigma_T + eps sigma_L), Gamma = a(1-x)y^2/(2 pi x Q^2 (1-eps))", d_xQ,
      alpha*(1-x_)*y_**2/(2*np.pi*x_*Q2_*(1-e_))*(sT + e_*sL))
check("L_T = 2Q^2/(1-eps)", LT, 2*Q2_/(1-e_))
check("M K = (W^2 - M^2)/2 = nu (1-x)", (v["W2"]-Mp**2)/2, v["nu"]*(1-x_))
check("massless epsilon = 2(1-y)/Y+", epsf(0.37, 0), 2*(1-0.37)/(1+0.63**2))
# transverse-photon tensor in the frame where q is along z: the two transverse weights
print(f"INFO  fixed-target example: gamma^2 = {gam2:.5f}, epsilon = {epsf(y_, gam2):.4f}; eps(y=0.1)={epsf(0.1,0):.4f}, eps(0.5)={epsf(0.5,0):.4f}, eps(0.9)={epsf(0.9,0):.4f}")

# --- section 9, D7: the elastic limit ----------------------------------------------------------------
# hadronic tensor of a spin-1/2 particle with Dirac and Pauli form factors, against the stated structure functions
Q2e = 1.7; nue = Q2e/2; qe = np.array([nue/Mp, 0, 0, np.sqrt((nue/Mp)**2 + Q2e)]); Pe = np.array([Mp, 0, 0, 0.]); Pf = Pe + qe
check("elastic: (P+q)^2 = M^2 at x = 1", dot(Pf, Pf), Mp**2)
tau = Q2e/(4*Mp**2)
for GE, GM in [(1.0, 1.0), (0.42, 1.15)]:
    Fd = (GE + tau*GM)/(1+tau); Fp = (GM - GE)/(1+tau)                       # Dirac and Pauli form factors
    sigq = lambda a: sum(0.5j*(g[a] @ g[b] - g[b] @ g[a])*(met @ qe)[b] for b in range(4))     # sigma^{a b} q_b
    Gam = [Fd*g[a] + 1j*Fp/(2*Mp)*sigq(a) for a in range(4)]
    bar = lambda Mx: g[0] @ Mx.conj().T @ g[0]
    one = np.eye(4)
    T = np.array([[0.5*np.trace((sl(Pf)+Mp*one) @ Gam[a] @ (sl(Pe)+Mp*one) @ bar(Gam[b])) for b in range(4)] for a in range(4)])
    # W = (1/4pi) 2pi delta((P+q)^2 - M^2) T = T delta(1-x)/(4 nu);  compare coefficients of delta(1-x)
    want = Wten(Pe, qe, GM**2/2, (GE**2 + tau*GM**2)/(1+tau))
    check(f"elastic tensor: F1 = GM^2/2, F2 = (GE^2 + tau GM^2)/(1+tau)  (GE={GE}, GM={GM})", np.abs(T/(4*nue) - want).max(), 0, 1e-9)
# Rosenbluth: integrate the laboratory form over E' across the elastic peak
Eb, thb = 4.0, np.radians(25.0); GE, GM = 0.3, 0.8
Epel = Eb/(1 + 2*Eb/Mp*np.sin(thb/2)**2)
check("elastic peak: E' = E/(1 + (2E/M) sin^2(theta/2))", invariants(*lab(Eb, Epel, thb))["x"], 1.0)
xofE = lambda e: invariants(*lab(Eb, e, thb))["x"]
dxdE = (xofE(Epel+1e-6) - xofE(Epel-1e-6))/2e-6
check("dx/dE' at the peak = E/(E' (E-E'))", dxdE, Eb/(Epel*(Eb-Epel)), 1e-6)
Q2r = 4*Eb*Epel*np.sin(thb/2)**2; taur = Q2r/(4*Mp**2)
# int dE' delta(1-x) f(E') = f/|dx/dE'|
el = alpha**2*np.cos(thb/2)**2/(4*Eb**2*np.sin(thb/2)**4)*((GE**2+taur*GM**2)/(1+taur)/(Eb-Epel) + GM**2/Mp*np.tan(thb/2)**2)/dxdE
ros = alpha**2*np.cos(thb/2)**2/(4*Eb**2*np.sin(thb/2)**4)*Epel/Eb*((GE**2+taur*GM**2)/(1+taur) + 2*taur*GM**2*np.tan(thb/2)**2)
check("Rosenbluth formula from the elastic structure functions", el, ros)
print(f"INFO  dipole form factor (1+Q2/0.71)^-2: Q2=1 -> {(1+1/0.71)**-2:.4f}, squared {(1+1/0.71)**-4:.4f}; Q2=10 -> squared {(1+10/0.71)**-4:.2e}")
print(f"INFO  W at pion threshold: {Mp+0.13957:.3f} GeV;  W^2 = 12.5 GeV2 is W = {np.sqrt(12.5):.2f} GeV;  x at W2=12.5, Q2=3.49: {3.49/(3.49+12.5-Mp**2):.3f}")

# --- section 10: weak currents ------------------------------------------------------------------------
# neutrino leptonic tensor with explicit (1 - gamma5), contracted with the F3 term  -i eps^{abrs} P_r q_s F3/(2 nu)
F3 = 0.57
Wfull = low(W) + 0j
Pl_, ql_ = met @ P, met @ v["q"]
W3 = -1j*np.einsum("abrs,r,s->ab", eps4, Pl_, ql_)*F3/(2*v["nu"])                     # upper indices
for sign, name in ((+1, "neutrino"), (-1, "antineutrino")):
    proj = np.eye(4) - sign*g5
    Lnu = np.array([[np.trace(sl(kp) @ g[a] @ proj @ sl(k) @ g[b] @ proj) for b in range(4)] for a in range(4)])
    check(f"{name}: symmetric part of the leptonic tensor = 4 L", np.abs((Lnu + Lnu.T)/2 - 4*Lten(k, kp)).max(), 0, 1e-9)
    Lanti = (Lnu - Lnu.T)/2
    check(f"{name}: antisymmetric part = {'-' if sign>0 else '+'} 8i eps^(abrs) k_r k'_s", np.abs(Lanti + sign*8j*np.einsum("abrs,r,s->ab", eps4, met @ k, met @ kp)).max(), 0, 1e-9)
    check(f"{name}: antisymmetric part . F3 term = {'+' if sign>0 else '-'} (4Q^2/y)(2-y) F3", np.einsum("ab,ab", Lanti, low(W3)).real, sign*4*Q2_/y_*(2-y_)*F3)
    con = np.einsum("ab,ab", Lnu, low(W + W3)).real
    want = 8*Q2_/(x_*y_**2)*(brk + sign*y_*(1-y_/2)*x_*F3)
    check(f"{name}: L.W = (8Q^2/x y^2)[... {'+' if sign>0 else '-'} y(1-y/2) x F3]", con, want)
yy = 0.37; xF3 = 0.23; F2n = 0.61
check("helicity form: (1-y+y^2/2)F2 + y(1-y/2)xF3 = [(F2+xF3) + (1-y)^2 (F2-xF3)]/2",
      (1-yy+yy**2/2)*F2n + yy*(1-yy/2)*xF3, 0.5*((F2n+xF3) + (1-yy)**2*(F2n-xF3)))
check("Y- = 1-(1-y)^2 = 2y(1-y/2)", 1-(1-yy)**2, 2*yy*(1-yy/2))
check("eps^(abrs) eps_(abmn) k_r k'_s P^m q^n = -2[(k.P)(k'.q) - (k.q)(k'.P)]",
      np.einsum("abrs,ab->rs", eps4, low(np.einsum("abmn,m,n->ab", eps4, Pl_, ql_))) @ (met @ kp) @ (met @ k),
      -2*(dot(k, P)*dot(kp, v["q"]) - dot(k, v["q"])*dot(kp, P)))
check("k.q = -Q^2/2", dot(k, v["q"]), -Q2_/2); check("k'.q = +Q^2/2", dot(kp, v["q"]), Q2_/2)
GF, MW, sw2 = 1.1663788e-5, 80.377, 0.2312
print(f"INFO  Q2 at which the W propagator halves the cross-section: {(np.sqrt(2)-1)*MW**2:.0f} GeV2; "
      f"photon/W strength equal near Q2 ~ MW^2 = {MW**2:.0f} GeV2")
check("G_F/sqrt2 = pi alpha/(2 sin^2 MW^2) to 5% (tree level, alpha at zero momentum)", GF/np.sqrt(2), np.pi*alpha/(2*sw2*MW**2), 0.07)

# --- plots ----------------------------------------------------------------------------------------------
TEAL, ORANGE, INK, GRID = "#0e7c7b", "#d96c2c", "#16222e", "#ebe6da"
plt.rcParams.update({"font.size": 13, "axes.edgecolor": INK, "axes.labelcolor": INK, "xtick.color": INK, "ytick.color": INK,
                     "font.family": "DejaVu Sans", "svg.fonttype": "path"})
out = pathlib.Path(__file__).resolve().parents[2] / "assets" / "guide"; out.mkdir(parents=True, exist_ok=True)

# 1. the kinematic plane
fig, ax = plt.subplots(figsize=(8, 5.0)); fig.patch.set_facecolor("white")
xs = np.logspace(-6, 0, 400)
beams = [("HERA, 27.5 GeV on 920 GeV", 4*27.5*920.0, TEAL),
         ("280 GeV beam, fixed target", 2*Mp*280, ORANGE),
         ("20 GeV beam, fixed target", 2*Mp*20, INK)]
for label, sM, col in beams:                         # sM = s - M^2
    ax.fill_between(xs, 0.01*xs*sM, xs*sM, color=col, alpha=0.16, lw=0)
    ax.plot(xs, xs*sM, color=col, lw=2.2, label=label)
xw = np.linspace(0.02, 0.9995, 600)
ax.plot(xw, (12.5-Mp**2)*xw/(1-xw), color=INK, lw=1.8, ls="--", label="W² = 12.5 GeV²")
ax.axhline(3.49, color=INK, lw=1.8, ls=":", label="Q² = 3.49 GeV²")
ax.plot([c["x"], ft["x"]], [c["Q2"], ft["Q2"]], "o", ms=9, mfc="white", mec=INK, mew=2.2, zorder=6, ls="none", label="the two worked events")
ax.set_xscale("log"); ax.set_yscale("log"); ax.set_xlim(1e-6, 1); ax.set_ylim(0.1, 1e6)
ax.set_xlabel("Bjorken x"); ax.set_ylabel("photon virtuality Q²  (GeV²)")
ax.grid(True, color=GRID, lw=0.8); ax.set_axisbelow(True)
ax.legend(frameon=False, fontsize=13, loc="upper left", handlelength=2.2, labelspacing=0.35, borderaxespad=0.6)
fig.tight_layout(); fig.savefig(out / "1-1-plane.svg", facecolor="white"); plt.close(fig)

# 1b. one machine's plane: lines of constant y and constant W, with the fixed-target worked event (200 GeV muons)
fig, ax = plt.subplots(figsize=(8, 5.0)); fig.patch.set_facecolor("white")
sM = ft["s"] - Mp**2
xs = np.logspace(-2.6, 0, 400)
ax.fill_between(xs, xs*sM, 1e4, color=INK, alpha=0.08, lw=0)
ax.set_xscale("log"); ax.set_yscale("log"); ax.set_xlim(0.0025, 1.0); ax.set_ylim(0.05, 1500)
ax.set_xlabel("Bjorken x"); ax.set_ylabel("photon virtuality Q²  (GeV²)")
ax.grid(True, color=GRID, lw=0.8); ax.set_axisbelow(True)
fig.tight_layout()
xw = np.linspace(0.003, 0.9999, 4000); W2line = (2.0**2-Mp**2)*xw/(1-xw)
ax.fill_between(xw, 1e-3, np.minimum(W2line, xw*sM), color=ORANGE, alpha=0.16, lw=0)
ax.plot(xw, W2line, color=ORANGE, lw=1.8)
ax.axvline(1.0, color=ORANGE, lw=4)
rot = lambda x0, f: np.degrees(np.arctan2(*(ax.transData.transform((x0*1.2, f(x0*1.2))) - ax.transData.transform((x0, f(x0))))[::-1]))
for yv, lw_, xl, txt in ((1.0, 2.4, 0.0035, "y = 1: the limit"), (ft["y"], 2.0, 0.0035, "y = 0.405"), (0.1, 1.4, 0.0035, "y = 0.1")):
    f = lambda x, yv=yv: x*yv*sM
    ax.plot(xs, f(xs), color=TEAL, lw=lw_)
    ax.text(xl, f(xl)*1.22, txt, color=TEAL, fontsize=13, rotation=rot(xl, f), rotation_mode="anchor", ha="left", va="bottom")
ax.text(0.0032, 300, "not reachable with a 200 GeV beam", color=INK, fontsize=13, va="center")
ax.text(0.085, 0.075, "W below 2 GeV: resonances", color=ORANGE, fontsize=13, ha="left")
ax.annotate("W = M: elastic", (1.0, 600), xytext=(-125, 0), textcoords="offset points", color=ORANGE, fontsize=13, va="center",
            arrowprops=dict(arrowstyle="-", color=ORANGE, lw=1.2))
ax.plot([ft["x"]], [ft["Q2"]], "o", ms=10, mfc="white", mec=INK, mew=2.4, zorder=6)
ax.annotate("worked event", (ft["x"], ft["Q2"]), xytext=(-150, 42), textcoords="offset points", fontsize=13, color=INK,
            ha="center", va="center", arrowprops=dict(arrowstyle="-", color=INK, lw=1.2, shrinkB=7, shrinkA=4))
check("worked event lies on its y line", ft["x"]*ft["y"]*sM, ft["Q2"])
fig.savefig(out / "1-1-xyplane.svg", facecolor="white"); plt.close(fig)

# 1c. the two weights in the cross-section as functions of y (massless proton), and the mass-kept F2 weight
fig, ax = plt.subplots(figsize=(8, 4.6)); fig.patch.set_facecolor("white")
ys = np.linspace(0, 1, 400)
ax.plot(ys, 1-ys, color=TEAL, lw=2.4, label="weight of F₂:  1 − y")
ax.plot(ys, ys**2/2, color=ORANGE, lw=2.4, label="weight of 2xF₁:  y²/2")
g2 = 4*Mp**2*0.6**2/4.0; ymx = (-1 + np.sqrt(1 + g2))/(g2/2); ys2 = np.linspace(0, ymx, 300)
ax.plot(ys2, 1-ys2-g2*ys2**2/4, color=TEAL, lw=2.0, ls="--", label="F₂ weight with the mass term\n(x = 0.6, Q² = 4 GeV²)")
for yv, nm in ((c["y"], "collider\nevent"), (ft["y"], "fixed-target\nevent")):
    ax.axvline(yv, color=INK, lw=1.2, ls=":")
ax.text(c["y"]-0.012, 0.36, "collider\nevent", color=INK, fontsize=13, ha="right", va="top")
ax.text(ft["y"]+0.012, 0.36, "fixed-target\nevent", color=INK, fontsize=13, ha="left", va="top")
check("weights cross where 1 - y = y^2/2, y = sqrt(3) - 1", optimize.brentq(lambda y: 1-y-y*y/2, 0, 1), np.sqrt(3)-1)
print(f"INFO  weights at the worked events: fixed target y={ft['y']:.3f}: {1-ft['y']:.3f} and {ft['y']**2/2:.3f}; "
      f"collider y={c['y']:.3f}: {1-c['y']:.3f} and {c['y']**2/2:.3f}; crossing at y={np.sqrt(3)-1:.3f}")
ax.set_xlabel("inelasticity y"); ax.set_ylabel("weight in the cross-section")
ax.set_xlim(0, 1); ax.set_ylim(0, 1.05); ax.grid(True, color=GRID, lw=0.8); ax.set_axisbelow(True)
ax.legend(frameon=False, fontsize=13, loc="upper right", borderaxespad=0.6)
fig.tight_layout(); fig.savefig(out / "1-1-yweights.svg", facecolor="white"); plt.close(fig)

# 2. the polarisation parameter epsilon(y)
fig, ax = plt.subplots(figsize=(8, 4.6)); fig.patch.set_facecolor("white")
ys = np.linspace(0, 1, 400)
ax.plot(ys, epsf(ys, 0), color=TEAL, lw=2.4, label="massless proton")
g2 = 4*Mp**2*0.6**2/4.0                               # x = 0.6, Q2 = 4 GeV2
ym = (-1 + np.sqrt(1 + g2))/(g2/2)                    # root of 1 - y - g2 y^2/4
ys2 = np.linspace(0, ym, 300)
ax.plot(ys2, epsf(ys2, g2), color=ORANGE, lw=2.4, ls="--", label=f"x = 0.6, Q² = 4 GeV²  (γ² = {g2:.2f})")
check("y_max from 1 - y - gamma^2 y^2/4 = 0 equals 1/(1 + M^2x/(s-M^2))", ym, 1/(1 + Mp**2*0.6/(4.0/(0.6*ym))), 1e-9)
ax.set_xlabel("inelasticity y"); ax.set_ylabel("longitudinal-to-transverse photon flux  ε")
ax.set_xlim(0, 1); ax.set_ylim(0, 1.05); ax.grid(True, color=GRID, lw=0.8); ax.set_axisbelow(True)
ax.legend(frameon=False, fontsize=13, loc="lower left", borderaxespad=0.8)
ax.text(0.04, 0.74, "small y:\nboth polarisations", color=INK, fontsize=13)
ax.text(0.80, 0.05, "y → 1:\ntransverse only", color=INK, fontsize=13, ha="right")
fig.tight_layout(); fig.savefig(out / "1-1-epsilon.svg", facecolor="white"); plt.close(fig)
print(f"INFO  epsilon plot: gamma^2 = {g2:.3f}, y_max = {ym:.3f}")

# 3. schematic excitation spectrum (toy model, NOT data): elastic peak, three resonance bumps, continuum
fig, ax = plt.subplots(figsize=(8, 4.6)); fig.patch.set_facecolor("white")
Ws = np.linspace(0.8, 4.3, 1800); thr = Mp + 0.13957
bw = lambda W0, G, A: A*(G/2)**2/((Ws-W0)**2 + (G/2)**2)
cont = np.where(Ws > thr, 1.0*(1-np.exp(-(Ws-thr)/0.55))**2, 0)
turn_on = np.where(Ws > thr, 1-np.exp(-(Ws-thr)/0.05), 0)
spec = cont + turn_on*(bw(1.232, 0.117, 2.6) + bw(1.52, 0.12, 1.0) + bw(1.69, 0.13, 0.9))
ax.plot(Ws, spec, color=TEAL, lw=2.4)
ax.plot([Mp, Mp], [0, 3.6], color=ORANGE, lw=3)
ax.axvspan(np.sqrt(12.5), 4.3, color=TEAL, alpha=0.10, lw=0)
ax.axvline(np.sqrt(12.5), color=INK, lw=1.4, ls="--")
ax.text(Mp+0.03, 3.45, "elastic,\nW = M", color=ORANGE, fontsize=13, va="top")
ax.text(1.30, 2.75, "Δ(1232)", color=INK, fontsize=13)
ax.text(1.42, 2.02, "higher\nresonances", color=INK, fontsize=13, ha="left")
ax.text(2.2, 1.25, "continuum", color=INK, fontsize=13)
ax.text(3.92, 3.42, "kept by\nthe cut\nW² > 12.5\nGeV²", color=INK, fontsize=13, ha="center", va="top")
ax.set_xlim(0.8, 4.3); ax.set_ylim(0, 3.7); ax.set_yticks([])
ax.set_xlabel("invariant mass of the hadronic final state, W  (GeV)"); ax.set_ylabel("cross-section at fixed Q²  (schematic)")
ax.grid(True, axis="x", color=GRID, lw=0.8); ax.set_axisbelow(True)
fig.tight_layout(); fig.savefig(out / "1-1-spectrum.svg", facecolor="white"); plt.close(fig)

# 4. elastic against inelastic as Q^2 grows: the dipole form factor squared (real formula) and a flat line (schematic)
fig, ax = plt.subplots(figsize=(8, 4.6)); fig.patch.set_facecolor("white")
Q2s = np.logspace(-1, np.log10(30), 300); dip2 = (1 + Q2s/0.71)**-4
ax.plot(Q2s, dip2, color=ORANGE, lw=2.4)
ax.plot(Q2s, np.ones_like(Q2s), color=TEAL, lw=2.4)
for q2 in (1.0, 10.0):
    ax.plot([q2], [(1+q2/0.71)**-4], "o", ms=8, mfc="white", mec=ORANGE, mew=2.2, zorder=6)
check("dipole squared at Q2 = 1 GeV2", (1+1/0.71)**-4, 0.030, 0.02)
check("dipole squared at Q2 = 10 GeV2", (1+10/0.71)**-4, 2e-5, 0.03)
ax.text(1.25, 0.045, "0.030", color=ORANGE, fontsize=13); ax.text(11.5, 3.2e-5, "2 × 10⁻⁵", color=ORANGE, fontsize=13)
ax.text(0.12, 2e-5, "elastic: form factor squared\n(dipole formula)", color=ORANGE, fontsize=13)
ax.text(0.12, 1.7, "inelastic structure function at fixed x (schematic)", color=TEAL, fontsize=13)
ax.set_xscale("log"); ax.set_yscale("log"); ax.set_xlim(0.1, 30); ax.set_ylim(3e-6, 8)
ax.set_xlabel("photon virtuality Q²  (GeV²)"); ax.set_ylabel("relative to the value at low Q²")
ax.grid(True, color=GRID, lw=0.8); ax.set_axisbelow(True)
fig.tight_layout(); fig.savefig(out / "1-1-scaling.svg", facecolor="white"); plt.close(fig)

print("wrote 1-1-plane.svg, 1-1-xyplane.svg, 1-1-yweights.svg, 1-1-scaling.svg, 1-1-epsilon.svg, 1-1-spectrum.svg;", "ALL CHECKS PASS" if ok else "SOME CHECKS FAILED")
sys.exit(0 if ok else 1)
