"""Finite checks for four planar amplitudes, correlator and Regge readings.

Requires Python 3, NumPy, SciPy and SymPy. The Wick count enumerates the
individual labeled propagators before imposing the planar color-face count.
"""

from fractions import Fraction
from math import exp, expm1, log, pi, sqrt

import numpy as np
import sympy as sp
from scipy.integrate import quad
from scipy.special import digamma, zeta


def check_dual_inversion():
    spinors = [sp.Matrix(v) for v in [(1, 0), (0, 1), (1, 1), (1, -1)]]
    conjugates = [sp.Matrix(v) for v in [(-1, -1), (-1, 1), (1, 0), (0, 1)]]
    cusps = [sp.diag(3, 2)]
    for spinor, conjugate in zip(spinors, conjugates):
        cusps.append(cusps[-1] - spinor * conjugate.T)
    assert cusps.pop() == cusps[0]
    inverted = [cusp.inv() for cusp in cusps]
    new_spinors = [cusp * spinor for cusp, spinor in zip(inverted, spinors)]

    def denominator(chiral):
        return sp.prod(
            sp.Matrix.hstack(chiral[i], chiral[(i + 1) % 4]).det()
            for i in range(4)
        )

    def ratio(points):
        return (points[0] - points[2]).det() / (points[1] - points[3]).det()

    assert [c.det() for c in cusps] == [6, 8, 3, 3]
    assert denominator(spinors) == 2
    assert denominator(new_spinors) == sp.Rational(2, 432)
    r, inverted_r = ratio(cusps), ratio(inverted)
    assert r == -2 and inverted_r == sp.Rational(-8, 3)
    print("Cyclic deformation before and after inversion:", r + 1/r, inverted_r + 1/inverted_r)


def planar_pairings():
    """Enumerate normal-ordered Wick contractions of three four-field traces."""
    def pair(remaining, pairs):
        if not remaining:
            yield pairs
            return
        first, *others = remaining
        for i, second in enumerate(others):
            if first // 4 != second // 4:
                yield from pair(others[:i] + others[i + 1:], pairs + [(first, second)])

    for pairs in pair(list(range(12)), []):
        partner = {}
        for a, b in pairs:
            partner[a], partner[b] = b, a
        unseen = set(partner)
        faces = 0
        while unseen:
            slot = next(iter(unseen))
            faces += 1
            while slot in unseen:
                unseen.remove(slot)
                other = partner[slot]
                slot = 4 * (other // 4) + (other + 1) % 4
        if faces == 5:
            yield pairs


def check_scalar_overlap():
    contractions = list(planar_pairings())
    half = Fraction(1, 2)
    # Each row gives U projections onto (Z,X), V projections, and U dot V.
    # The first uses unnormalized U and V; restore its 1/16 after summing.
    for u, v, uv, expected in (
        ((1, 0), (0, 1), 1, (16, 0)),
        ((half, half), (half, half), half, (1, 1)),
        ((half, half), (-half, half), half, (0, -1)),
    ):
        sums = []
        for word in ("ZZXX", "ZXZX"):
            total = 0
            for pairs in contractions:
                weight = 1
                for a, b in pairs:
                    if a < 4:
                        projections = u if b < 8 else v
                        weight *= projections[int(word[a] == "X")]
                    else:
                        weight *= uv
                total += weight
            sums.append(total)
        assert tuple(sums) == expected
        assert sums[0] - sums[1] == 16 * uv**2 * (u[0]*v[1] - u[1]*v[0])**2
        print("Planar color-stripped Wick weights for A, B:", *sums)


def check_fishnet_poles():
    delta, coupling, nu = sp.symbols("delta coupling nu")
    squared = (delta - 2)**2
    polynomial = (squared - 4) * (squared - 16) - 16 * coupling
    contour = polynomial.subs(delta, 2 + 2 * sp.I * nu)
    assert sp.factor(contour.subs(coupling, (1 + nu**2) * (4 + nu**2))) == 0
    for value, expected in ((4, 0), (sp.Rational(85, 16), -sp.Rational(1))):
        roots = sp.roots(polynomial.subs(coupling, value), delta)
        if value == 4:
            assert roots[2] == 2
        else:
            assert roots[2 + sp.I] == roots[2 - sp.I] == 1
        assert 10 - sp.sqrt(36 + 16 * value) == expected
    print("Spin-two contour collision at xi^4=4; at 85/16, delta=2 +/- i")


def characteristic(n, nu):
    a = (1 + abs(n)) / 2
    return 2 * (digamma(1) - digamma(a + 1j * nu).real)


def check_bfkl_projection():
    for n, nu in ((0, 0), (0, 0.8), (1, 0.4), (2, 0.2)):
        # Substitute t=exp(-x) in the real-virtual integral on (0,1).
        a = (1 + abs(n)) / 2
        def integrand(x):
            return 2 * (exp(-a*x) * np.cos(nu*x) - exp(-x)) / (-expm1(-x))
        assert abs(quad(integrand, 0, np.inf, epsabs=2e-12)[0] - characteristic(n, nu)) < 2e-11

    diffusion = 14 * zeta(3)
    for time in (5, 20, 80):
        def projected(moment, upper):
            def integrand(nu):
                exponent = -nu**2 + time * (characteristic(0, nu) - 4 * log(2))
                return nu**moment * exp(exponent) / pi
            return quad(integrand, 0, upper, epsabs=1e-14, epsrel=5e-13)[0]

        j0, j2 = (projected(m, 8) for m in (0, 2))
        assert abs(j0 - projected(0, 6)) < 1e-13 and abs(j2 - projected(2, 6)) < 1e-13
        print(f"T={time:2d}: scaled J0 {sqrt(4*pi*diffusion*time)*j0:.5f}, "
              f"scaled J2/J0 {2*diffusion*time*j2/j0:.5f}")


if __name__ == "__main__":
    check_dual_inversion()
    check_scalar_overlap()
    check_fishnet_poles()
    check_bfkl_projection()
