"""Free adjoint Wick contractions and a normalized Seiberg–Witten period.

Uses Python 3 and SciPy. The color checks strip the polarization and spacetime
factors. The period check uses real positive delta and the magnetic orientation.
"""
from itertools import product
from math import cos, pi, sin, sqrt

from scipy.integrate import quad
from scipy.special import hyp2f1


def wick_pairings(slots):
    if not slots:
        yield ()
        return
    first, *rest = slots
    for idx, other in enumerate(rest):
        if first[0] != other[0]:
            remaining = rest[:idx] + rest[idx+1:]
            for pairs in wick_pairings(remaining):
                yield ((first, other),) + pairs


def color_coefficient(insertions, dimension):
    slots = [(vertex, slot) for vertex in range(insertions) for slot in range(2)]
    count = 0
    for pairs in wick_pairings(slots):
        for colors in product(range(dimension), repeat=insertions):
            count += all(colors[a[0]] == colors[b[0]] for a, b in pairs)
    return count / 2**insertions


def magnetic_ratio(eta):
    integrand = lambda t: sin(t)**2 / sqrt(1 + eta*cos(t)**2/2)
    value = (4/pi)*quad(integrand, 0, pi/2, epsabs=1e-14, epsrel=1e-13)[0]
    # Euler's integral for the hypergeometric function gives a second evaluation.
    independently = hyp2f1(0.5, 0.5, 2, -eta/2)
    assert abs(value - independently) < 2e-14
    return value


if __name__ == "__main__":
    for n in (2, 3, 4):
        d = n*n - 1
        two, three = [color_coefficient(length, d) for length in (2, 3)]
        assert (two, three) == (d/2, d)
        print("N, normalized three-point coefficient:", n, three/two**1.5)
    for eta in (0.1, 0.01, 0.001):
        ratio = magnetic_ratio(eta)
        # Taylor's theorem bounds the positive quadratic remainder by its
        # value using the second derivative at zero, times the cos^4 average.
        assert 0 < ratio - (1 - eta/16) <= 3*eta**2/256
        print("eta, period ratio, (1-ratio)/eta:", eta, ratio, (1-ratio)/eta)
