"""Independent checks for four local lattice identities. Python 3.9+, NumPy."""
from fractions import Fraction
from itertools import product
from math import cos, cosh, exp, log, pi, prod, sin, sinh, sqrt

import numpy as np


def field_on_star():
    signs = list(product([-1, 1], repeat=3))
    coupling = log(2)/2
    weights = {s: 2*cosh(coupling*(1+sum(s))) for s in signs}
    ratio = (prod(w for s, w in weights.items() if prod(s) == 1)
             / prod(w for s, w in weights.items() if prod(s) == -1))
    assert abs(ratio - float(Fraction(544, 625))) < 1e-15
    print("Central-field three-spin coefficient:", log(ratio)/8)


def returning_face():
    eta, x, y = 0.3, 0.37, 0.14
    t = x-y
    a_weight, b_weight, c_weight = sinh(t+eta), sinh(t), sinh(eta)
    vertex = np.array([[a_weight, 0, 0, 0], [0, b_weight, c_weight, 0],
                       [0, c_weight, b_weight, 0], [0, 0, 0, a_weight]])

    def spin(start, step, rapidity):
        exponent = (-rapidity+step*start*eta)/2
        return np.array([exp(exponent), exp(-exponent)])

    for a in (2, 0.1, 0.01, 0.001):
        direct = vertex @ np.kron(spin(a, 1, x), spin(a+1, -1, y))
        wm = b_weight*sinh((a+1)*eta)/sinh(a*eta)
        wp = c_weight*sinh(a*eta-t)/sinh(a*eta)
        vm = np.kron(spin(a-1, 1, x), spin(a, -1, y))
        vp = np.kron(spin(a+1, -1, x), spin(a, 1, y))
        residual = np.max(abs(wm*(vm-vp)+a_weight*vp-direct))
        assert abs(wm+wp-a_weight) < 1e-13 and residual < 2e-13
        print("Starting height, two coefficients, vector error:", a, wm, wp, residual)


def height_braid():
    angle = pi/4
    beta = 2*cos(angle)
    e = np.diag([sqrt(2), 0])
    f = np.ones((2, 2))/sqrt(2)

    def face(generator, u):
        return (sin(angle-u)*np.eye(2) + sin(u)*generator)/sin(angle)

    def ratio(u):
        return sin(u)/sin(angle-u)

    assert np.allclose(e @ f - f @ e, [[0, 1], [-1, 0]])
    for u, v in [(0.13, 0.24), (angle/3, angle/4)]:
        x, y, z = ratio(u), ratio(u+v), ratio(v)
        assert abs(y*(1-x*z) - (x+z+beta*x*z)) < 8e-16
        residual = face(e, u) @ face(f, u+v) @ face(e, v)
        residual -= face(f, v) @ face(e, u+v) @ face(f, u)
        print("Three-face maximum entry error:", np.max(abs(residual)))
        assert np.max(abs(residual)) < 1e-15


def spin_channels():
    words = list(product([0, 1], repeat=3))

    def exchange(i, j):
        matrix = np.zeros((8, 8))
        for column, bits in enumerate(words):
            swapped = list(bits)
            swapped[i], swapped[j] = swapped[j], swapped[i]
            matrix[words.index(tuple(swapped)), column] = 1
        return matrix

    embed = np.kron([[1, 0, 0], [0, 1/sqrt(2), 0],
                     [0, 1/sqrt(2), 0], [0, 0, 1]], np.eye(2))
    p13, p23 = exchange(0, 2), exchange(1, 2)
    for p, q in [(2, 1), (0.5, -0.5), (1, 1)]:
        full = (q*np.eye(8)+p23) @ (p*np.eye(8)+p13)
        leak = (full[2, 1]-full[4, 1])/sqrt(2)
        assert abs(leak - (p-q-1)/sqrt(2)) < 1e-15
        if p-q == 1:
            fused = embed.T @ full @ embed
            eigenvalues = np.linalg.eigvalsh(fused)
            predicted = sorted([p*(p+1)]*4 + [p*(p-2)]*2)
            np.testing.assert_allclose(eigenvalues, predicted, atol=2e-15)
            print("Rapidity, spin channels:", p-0.5, predicted)
        else:
            print("Singlet amplitude with the wrong shift:", leak)


if __name__ == "__main__":
    field_on_star()
    returning_face()
    height_braid()
    spin_channels()
