"""Gaussian pairing counts, two local spectral residues and bilinear KP checks.

Run with Python 3 and SymPy. The contour check uses the periodic trapezoid rule.
"""

import cmath
from collections import Counter
from fractions import Fraction
from math import comb, pi, prod

import sympy as sp


def pairings(indices):
    if not indices:
        yield ()
        return
    first, *others = indices
    for i, other in enumerate(others):
        for rest in pairings(others[:i] + others[i + 1:]):
            yield ((first, other),) + rest


def cycles_after_trace(pairing):
    n = 2 * len(pairing)
    advance = {}
    for i, j in pairing:
        advance[i], advance[j] = (j + 1) % n, (i + 1) % n
    remaining = set(advance)
    count = 0
    while remaining:
        i = next(iter(remaining))
        while i in remaining:
            remaining.remove(i)
            i = advance[i]
        count += 1
    return count


def gaussian_moments():
    for k, expected in [(2, {3: 2, 1: 1}), (3, {4: 5, 2: 10})]:
        counts = Counter(cycles_after_trace(p) for p in pairings(list(range(2*k))))
        assert counts == expected
    # For N=2 write M=tI+v.sigma. The four real coordinates have variance 1/4.
    # Average (t+|v|)^6 and (t-|v|)^6; |v|^2 is a scaled chi-square with 3 df.
    def chi_square_moment(dimension, power):
        return Fraction(prod(dimension + 2*j for j in range(power)), 4**power)

    value = sum(comb(6, 2*j) * chi_square_moment(1, 3-j)
                * chi_square_moment(3, j) for j in range(4))
    assert value == 5 + Fraction(10, 2**2)
    print("Sixth moment at N=2 from four independent Gaussian coordinates:", value)


def circle_residue(f, radius, nodes):
    total = 0j
    for j in range(nodes):
        z = radius * cmath.exp(2j * pi * j / nodes)
        total += z * f(z)
    return total / nodes


def local_residues():
    p, q, r = 2, 1, 3
    max_error = 0
    for b, c in [(0, 0), (2, .25), (-1, .5)]:
        def y(z):
            return z + b*z**2 + c*z**3

        def kernel(z):
            return -1 / ((p**2-z**2) * (y(z)-y(-z)))

        def genus_one(z):
            return -kernel(z) / (4*z**2)

        def triple(z):
            direct = 1 / ((z-q)**2 * (-z-r)**2)
            exchanged = 1 / ((z-r)**2 * (-z-q)**2)
            return -kernel(z) * (direct + exchanged)

        for radius, nodes in [(.2, 48), (.25, 96)]:
            for f, answer in [(triple, (p*q*r)**-2),
                              (genus_one, (p**-4 - c*p**-2)/8)]:
                error = abs(circle_residue(f, radius, nodes) - answer)
                max_error = max(error, max_error)
                assert error < 5e-14
    print(f"Largest absolute contour error, both radii and node counts: {max_error:.2g}")


def bilinear_checks():
    times = sp.symbols("x y t s")
    offsets = [sp.Dummy(name) for name in ("dx", "dy", "dt", "ds")]
    x, y, t, s = times

    def residual(tau, operator):
        factors = []
        for sign in (1, -1):
            factors.append(tau.xreplace(dict(zip(times, [q+sign*h for q, h in zip(times, offsets)]))))
        product = factors[0] * factors[1]
        value = sum(coeff * sp.diff(product, *(offsets[i] for i in indices))
                    for coeff, indices in operator)
        return sp.expand(value.subs(dict.fromkeys(offsets, 0)))

    kp = [(1, (0, 0, 0, 0)), (3, (1, 1)), (-4, (0, 2))]
    next_flow = [(1, (0, 0, 0, 1)), (2, (1, 2)), (-3, (0, 3))]
    for freq in (14, 15):
        wave = sp.exp(x+3*y+7*t+freq*s)
        assert residual(1+wave, kp) == 0
        assert sp.simplify(residual(1+wave, next_flow)/wave) == 6*(15-freq)
    c = sp.symbols("c")
    schur = x**4/12+y**2-x*t
    assert residual(schur, kp) == 0
    assert residual(1+c*schur, kp) == 24*c
    print("Bilinear checks passed for fourth frequencies 14 and 15 and the (2,2) superposition.")


if __name__ == "__main__":
    gaussian_moments()
    local_residues()
    bilinear_checks()
