"""Exact rational XXX checks for periodic rows and a reflecting boundary.

Run with Python 3 and SymPy. Tensor basis: 000, 001, ..., 111. R(s)=sI+iP.
"""
import sympy as sp


def swap(spins, a, b):
    size = 2**spins
    operator = sp.zeros(size)
    for column in range(size):
        labels = list(format(column, f"0{spins}b"))
        labels[a], labels[b] = labels[b], labels[a]
        operator[int("".join(labels), 2), column] = 1
    return operator


def r(spins, a, b, u):
    return u*sp.eye(2**spins) + sp.I*swap(spins, a, b)


def boundary_difference(u, v, k, wrong_sum=False):
    spin = sp.eye(2)
    k1, k2 = sp.kronecker_product(k(u), spin), sp.kronecker_product(spin, k(v))
    d = r(2, 0, 1, u-v)
    s = r(2, 0, 1, u+v)
    return (d*k1*(d if wrong_sum else s)*k2-k2*s*k1*d).applyfunc(sp.expand)


if __name__ == "__main__":
    u, v, xi = sp.symbols("u v xi")
    a, b, c = r(3, 0, 1, u-v), r(3, 0, 2, u), r(3, 1, 2, v)
    assert (a*b*c-c*b*a).applyfunc(sp.expand) == sp.zeros(8)
    diagonal = lambda x: sp.diag(xi+x, xi-x)
    assert boundary_difference(u, v, diagonal) == sp.zeros(4)
    wrong = boundary_difference(2, 1, lambda x: sp.diag(4+x, 4-x), True)
    assert wrong != sp.zeros(4)
    numerator = (u+sp.I/2)**4*(u-sp.I)+(u-sp.I/2)**4*(u+sp.I)
    t, remainder = sp.div(sp.expand(numerator), u)
    assert remainder == 0 and t == 2*u**4 + u**2 - sp.Rational(7, 8)
    print("Three-space and boundary exchange identities hold as polynomial matrices.")
    print("Incorrect reflected argument at (u,v,xi)=(2,1,4), entry (0,0):", wrong[0,0])
    print("Four-site one-root transfer eigenvalue:", t)
