"""Exact finite checks for quantum-group actions and rational transfer polynomials.

Run with Python 3 and SymPy. Slots are ordered left to right; up has bit zero.
"""
from itertools import product
from math import comb
import sympy as s

half = s.Rational(1, 2)


def swap(count, first, second):
    result = s.zeros(2**count)
    for col, word in enumerate(product((0, 1), repeat=count)):
        output = list(word)
        output[first], output[second] = output[second], output[first]
        row = sum(digit*2**(count-1-j) for j, digit in enumerate(output))
        result[row, col] = 1
    return result


def symmetric_transfer(points, sites, k):
    """Trace the product of complete monodromies in the symmetric auxiliary block."""
    n = len(points)
    l = len(sites)
    dimension = 2**(n+l)
    whole = s.eye(dimension)
    for a, x in enumerate(points):
        mono = s.eye(dimension)
        for j, xi in enumerate(sites):
            local = (x-xi-half)*s.eye(dimension) + swap(n+l, a, n+j)
            mono = local*mono
        whole = whole*mono
    out = s.zeros(2**l)
    for b in range(2**n):
        m = bin(b).count("1")
        weight = k**(n-2*m)/comb(n, m)
        for c in range(2**n):
            if m == bin(c).count("1"):
                out += weight*whole[b*2**l:(b+1)*2**l, c*2**l:(c+1)*2**l]
    return s.simplify(out)


def next_fusion_step():
    x = s.Integer(4)
    k = s.Integer(2)
    sites = [0, 2]
    def d(z):
        return s.prod((z-a)**2-1 for a in sites)
    a, b, c = [symmetric_transfer([y], sites, k) for y in (x-1, x, x+1)]
    three = symmetric_transfer([x-1, x, x+1], sites, k)
    left = symmetric_transfer([x-1, x], sites, k)
    right = symmetric_transfer([x, x+1], sites, k)
    assert three == a*b*c-d(x-half)*c-d(x+half)*a
    assert left*right-b*three == d(x-half)*d(x+half)*s.eye(4)
    print("Spin 3/2 raw transfer on two quantum spins:", three)
    print("Scalar second fusion residual:", d(x-half)*d(x+half))


def spin_and_fusion():
    q = s.Integer(2)
    delta = q-1/q
    checked = s.Matrix([[q,0,0,0],[0,0,1,0],[0,1,delta,0],[0,0,0,q]])
    b1, b2 = s.kronecker_product(checked,s.eye(2)), s.kronecker_product(s.eye(2),checked)
    t1, t2 = s.eye(8)+b1, s.eye(8)+b2
    assert b1*b2*b1 == b2*b1*b2
    defect = t1*t2*t1-t2*t1*t2
    assert defect == (1+delta)*(b1-b2)
    # Test both off-diagonal blocks at the exact fusion separation.
    z = s.symbols("z")
    z2, z1 = z, z+s.I
    row = (z2*s.eye(8)+s.I*swap(3,1,2))*(z1*s.eye(8)+s.I*swap(3,0,2))
    symmetric = (s.eye(8)+swap(3,0,1))/2
    assert ((s.eye(8)-symmetric)*row*symmetric).applyfunc(s.cancel) == s.zeros(8)
    obstruction = s.simplify((row[1,2]-row[1,4])/s.sqrt(2))
    assert obstruction == -s.sqrt(2)
    print("Intertwiner braid defect entry (001,001):", defect[1,1])
    print("Singlet to top-triplet transition at fusion:", obstruction)


def exceptional_point():
    x = s.symbols("x")
    k = s.Integer(2)
    xi = [2*s.I/3, -2*s.I/3]
    t = symmetric_transfer([x], xi, k)[1:3,1:3]
    traceless = t-s.trace(t)*s.eye(2)/2
    assert traceless**2 == s.zeros(2) and traceless.rank() == 1
    a = s.prod(x-z+half for z in xi)
    d = s.prod(x-z-half for z in xi)
    equation = s.factor(k*a-d/k)
    assert s.factor(equation-s.Rational(3,2)*(x+s.Rational(5,6))**2) == 0
    print("Exceptional traceless transfer:", traceless)
    print("One-root equation:", equation)


def oscillator_cutoff():
    n = 4
    r = s.Rational(1,4)
    weights = [r**j/sum(r**i for i in range(n+1)) for j in range(n+1)]
    mean = sum(j*w for j,w in enumerate(weights))
    boundary = (n+1)*weights[-1]
    print("Partial trace of N, top-state term:", mean, boundary)
    assert 1+mean-4*mean == boundary


def colliding_gaudin_sites():
    # |singlet,up> and the spin-half vector obtained from the triplet pair.
    singlet = s.zeros(8,1)
    triplet = s.zeros(8,1)
    singlet[2], singlet[4] = 1/s.sqrt(2), -1/s.sqrt(2)
    triplet[1] = 2/s.sqrt(6)
    triplet[2] = triplet[4] = -1/s.sqrt(6)
    eps = s.symbols("epsilon", positive=True)
    o13 = swap(3,0,2)/2-s.eye(8)/4
    o23 = swap(3,1,2)/2-s.eye(8)/4
    mixing = s.factor((singlet.T*(-o13-o23/(1-eps))*triplet)[0])
    assert s.simplify(mixing**2 - 3*eps**2/(16*(1-eps)**2)) == 0
    print("Gaudin channel mixing with indicated state phases:", mixing)


if __name__ == "__main__":
    spin_and_fusion()
    oscillator_cutoff()
    next_fusion_step()
    exceptional_point()
    colliding_gaudin_sites()
