#!/usr/bin/env python3
"""Numerical checks for guide chapter 1.4 (DGLAP), and the data for its evolution figure.
Every formula the chapter states is tested here; the script exits non-zero if any check fails.
Run:  python3 guide-build/tools/check_1_4.py        (writes guide-build/content/1-4-evolution.json)"""
import json, pathlib, sys
import numpy as np
from scipy import integrate, special

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 &= 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]

# --- D1: the angular integral and the xi integral of eq. (1.4.9) ---------------------------------
x, z = 0.3, 0.2
xp = x + z - 2*x*z + np.sqrt(4*x*(1-x)*z*(1-z)); xm = x + z - 2*x*z - np.sqrt(4*x*(1-x)*z*(1-z))
# substitute xi = mid + half*sin(u) to remove the end-point singularities
mid, half = (xp+xm)/2, (xp-xm)/2
check("int dxi / sqrt((xi+ - xi)(xi - xi-)) = pi", q(lambda u: 1.0, -np.pi/2, np.pi/2), np.pi)
A = lambda xi: xi - x - z; B = lambda xi: 2*np.sqrt(x*z*(1-xi))
xi0 = mid + 0.37*half
check("B^2 - A^2 = (xi+ - xi)(xi - xi-)", B(xi0)**2 - A(xi0)**2, (xp-xi0)*(xi0-xm))

# --- D2: the trace, with explicit Dirac matrices and the light-cone-gauge polarisation sum --------
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))
P = 50.0
p = np.array([P, 0, 0, P]); n = np.array([1/(2*P), 0, 0, -1/(2*P)])
for xi, k2abs, phi in [(0.3, 0.7, 0.4), (0.62, 2.3, 2.0)]:
    kT = np.sqrt((1-xi)*k2abs)                      # gluon on shell, eq. (1.4.7)
    kTv = np.array([0, kT*np.cos(phi), kT*np.sin(phi), 0])
    k = xi*p + (kT**2 - k2abs)/(2*xi)*n + kTv
    r = p - k
    check(f"k^2 = -|k^2| (xi={xi})", dot(k, k), -k2abs); check("r^2 = 0", dot(r, r), 0, 1e-9)
    # sum over gluon polarisations: -g_mu_nu + (n_mu r_nu + n_nu r_mu)/(n.r), all indices lowered
    nl, rl = met @ n, met @ r
    pol = -met + (np.outer(nl, rl) + np.outer(rl, nl))/dot(n, r)
    S = sum(pol[m, v] * g[m] @ sl(p) @ g[v] for m in range(4) for v in range(4))   # g[m] is gamma^mu
    # l = k + q with n.q = 0, so n.l = xi and  nslash lslash nslash = 2 xi nslash
    T = 2*xi*np.trace(sl(n) @ sl(k) @ S @ sl(k)).real
    want = 16*k2abs*xi*(1+xi**2)/(1-xi)             # so that (1/2) e^2 g^2 CF T/k^4 = 8 e^2 g^2 xi P/|k^2|
    check(f"trace of eq. (1.4.8) (xi={xi})", T, want, 1e-8)

# --- D3, D4: sum rules of the leading-order splitting functions (regular parts + plus + delta) ----
nf = 5
# int f(x)/(1-x)_+ = int (f(x)-f(1))/(1-x)
plus = lambda f: q(lambda x: (f(x) - f(1.0))/(1-x))
check("quark number: int Pqq = 0", CF*(plus(lambda x: 1+x*x) + 1.5), 0)
check("quark momentum: int x(Pqq+Pgq) = 0",
      CF*(plus(lambda x: x*(1+x*x)) + 1.5) + CF*q(lambda x: 1+(1-x)**2), 0)
bgg = (11*CA - 4*nf*TR)/6
check("gluon momentum: int x(2 nf Pqg + Pgg) = 0",
      2*nf*TR*q(lambda x: x*(x*x+(1-x)**2)) + 2*CA*(plus(lambda x: x*x) + q(lambda x: (1-x) + x*x*(1-x))) + bgg, 0)
b0 = (33 - 2*nf)/(12*np.pi)
check("delta coefficient of Pgg = 2 pi b", bgg, 2*np.pi*b0)

# --- D5: anomalous dimensions against direct numerical moments -----------------------------------
H = lambda N: special.digamma(N+1) + np.euler_gamma           # harmonic sum, analytic in N
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=nf: 2*CA*(11/12 + 1/(N*(N-1)) + 1/((N+1)*(N+2)) - H(N)) - 2*nf*TR/3
for N in (2, 3.5, 6):
    check(f"gamma_qq({N})", CF*(plus(lambda x: x**(N-1)*(1+x*x)) + 1.5), g_qq(N))
    check(f"gamma_qg({N})", TR*q(lambda x: x**(N-1)*(x*x+(1-x)**2)), g_qg(N))
    check(f"gamma_gq({N})", CF*q(lambda x: x**(N-2)*(1+(1-x)**2)), g_gq(N))
    check(f"gamma_gg({N})", 2*CA*(plus(lambda x: x**N) + q(lambda x: x**(N-2)*(1-x) + x**N*(1-x))) + bgg, g_gg(N))
check("gamma_qq(1) = 0", g_qq(1.0), 0)
check("gamma_qq(2) = -(4/3) CF", g_qq(2.0), -4*CF/3)
check("gamma_qq(2) + gamma_gq(2) = 0", g_qq(2.0) + g_gq(2.0), 0)
check("2 nf gamma_qg(2) + gamma_gg(2) = 0", 2*nf*g_qg(2.0) + g_gg(2.0), 0)

# --- the evolution figure: exact leading-order solution in moment space, nf = 4 -------------------
nf4, Lam2 = 4, 0.04                                 # Lambda = 0.2 GeV: an illustrative leading-order value
b4 = (33 - 2*nf4)/(12*np.pi)
alpha = lambda Q2: 1/(b4*np.log(Q2/Lam2))
Q02 = 1.65**2
# toy input at Q0 (NOT a fit): valence-like, sea-like and gluon shapes  x f = A x^a (1-x)^c
Av = 3/special.beta(0.5, 4.0)                       # three valence quarks:  int v dx = 3
shapes = {"v": (Av, 0.5, 3.0), "s": (None, -0.2, 7.0), "g": (None, -0.2, 5.0)}
mom = lambda a, c, N: np.exp(special.loggamma(N - 1 + a) + special.loggamma(c + 1) - special.loggamma(N + a + c))          # int x^(N-1) [x^a (1-x)^c / x] dx
m2v = Av*mom(0.5, 3.0, 2)
As = 0.15/mom(-0.2, 7.0, 2); Ag = (1 - m2v - 0.15)/mom(-0.2, 5.0, 2)     # momentum: v + sea + g = 1
shapes["s"] = (As, -0.2, 7.0); shapes["g"] = (Ag, -0.2, 5.0)
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)

def evolve(N, Q2):
    """Moments (valence, singlet, gluon) at Q2 from the input at Q0^2, eqs. (1.4.28) and (1.4.29)."""
    zeta = np.log(alpha(Q02)/alpha(Q2)); d = lambda gam: gam/(2*np.pi*b4)
    v = vN(N)*np.exp(d(g_qq(N))*zeta)
    a, bq, c, dd = g_qq(N), 2*nf4*g_qg(N), g_gq(N), g_gg(N, nf4)
    disc = np.sqrt((a-dd)**2 + 4*bq*c); lp, lm = (a+dd+disc)/2, (a+dd-disc)/2
    S0, G0 = vN(N) + sN(N), gN(N)
    # projectors onto the two eigenvectors of the 2x2 matrix [[a, bq], [c, dd]]
    Pp = np.array([[a-lm, bq], [c, dd-lm]])/(lp-lm); Pm = np.array([[lp-a, -bq], [-c, lp-dd]])/(lp-lm)
    ep, em = np.exp(d(lp)*zeta), np.exp(d(lm)*zeta)
    S = (Pp[0, 0]*ep + Pm[0, 0]*em)*S0 + (Pp[0, 1]*ep + Pm[0, 1]*em)*G0
    G = (Pp[1, 0]*ep + Pm[1, 0]*em)*S0 + (Pp[1, 1]*ep + Pm[1, 1]*em)*G0
    return v, S, G

def invert(x, Q2):
    """x f(x) from the moments: the contour N = c + t e^{i phi}, phi = 3 pi/4."""
    c, phi = 1.8, 0.75*np.pi; e = np.exp(1j*phi)
    def f(t, i):
        N = c + t*e
        return (e * x**(1-N) * evolve(N, Q2)[i]).imag/np.pi
    return [integrate.quad(f, 0, 45, args=(i,), limit=400, epsabs=1e-10, epsrel=1e-9)[0] for i in range(3)]

# the inversion reproduces the input at Q0, and momentum is conserved at every scale
for xx in (1e-3, 0.1, 0.5):
    v, S, G = invert(xx, Q02)
    check(f"inversion returns the input valence at x={xx}", v, Av*xx**0.5*(1-xx)**3, 1e-5)
    check(f"inversion returns the input gluon at x={xx}", G, Ag*xx**-0.2*(1-xx)**5, 1e-5)
for Q2 in (10.0, 1e4):
    v, S, G = evolve(2.0, Q2); check(f"momentum sum at Q2={Q2:g}", (S+G).real, 1.0)
    v1, _, _ = evolve(1.0+1e-9, Q2); check(f"valence number at Q2={Q2:g}", v1.real, 3.0, 1e-6)
# small-x: the double-logarithmic rise of eq. (1.4.32) against the exact moment-space gluon
for Q2 in (1e2, 1e4):
    zeta = np.log(alpha(Q02)/alpha(Q2))
    g5, g6 = invert(1e-5, Q2)[2], invert(1e-6, Q2)[2]
    slope = np.log(g6/g5)/np.log(10.0)
    print(f"INFO  small-x gluon at Q2={Q2:g}: effective power x^-{slope:.3f} between 1e-5 and 1e-6; "
          f"momentum fraction of gluons {evolve(2.0, Q2)[2].real:.3f}")
print(f"INFO  gluon momentum fraction at Q0: {gN(2.0):.3f}; asymptotic 16/(16+3nf) = {16/(16+3*nf4):.3f}")
check("asymptotic quark fraction 3nf/(16+3nf)", (2*nf4*g_qg(2.0))/(2*nf4*g_qg(2.0) - g_qq(2.0)), 3*nf4/(16+3*nf4))

xs = np.concatenate([np.logspace(-4, -1, 31)[:-1], np.linspace(0.1, 0.95, 35)])
Q2s = [Q02, 4, 6, 10, 20, 40, 100, 300, 1000, 3000, 1e4, 1e5]
out = {"x": [round(float(v), 6) for v in xs], "Q2": [round(float(v), 4) for v in Q2s], "nf": nf4, "Lambda": 0.2,
       "curves": [], "momentum": []}
for Q2 in Q2s:
    rows = np.array([invert(xx, Q2) for xx in xs])
    out["curves"].append({k: [round(float(v), 5) for v in rows[:, i]] for i, k in enumerate(("v", "S", "g"))})
    out["momentum"].append(round(float(evolve(2.0, Q2)[2].real), 4))
pathlib.Path(__file__).resolve().parents[1].joinpath("content", "1-4-evolution.json").write_text(json.dumps(out))
print("wrote 1-4-evolution.json;", "ALL CHECKS PASS" if ok else "SOME CHECKS FAILED")
sys.exit(0 if ok else 1)
