"""Critical A-type face operators, planar link patterns, and a vertex–face move.

Requires Python 3 and NumPy. The path basis stores distinct heights, including
the two endpoints. All examples and parameters are dimensionless.
"""
from itertools import product
from math import exp, pi, sin, sinh, sqrt

import numpy as np


def paths(length, ceiling):
    return [p for p in product(range(1, ceiling + 1), repeat=length + 1)
            if all(abs(a - b) == 1 for a, b in zip(p, p[1:]))]


def height_generator(states, site, angle):
    result = np.zeros((len(states), len(states)))
    for i, top in enumerate(states):
        for j, bottom in enumerate(states):
            if (top[:site] == bottom[:site] and top[site+1:] == bottom[site+1:]
                    and top[site-1] == top[site+1]):
                result[i, j] = (sqrt(sin(angle*top[site])*sin(angle*bottom[site]))
                                / sin(angle*top[site-1]))
    return result


def path_and_loop_checks():
    angle = pi / 4
    fugacity = 2 * np.cos(angle)
    states = paths(3, 3)
    print("A3 length-two paths:", paths(2, 3))
    e1 = height_generator(states, 1, angle)
    e2 = height_generator(states, 2, angle)
    link1 = np.array([[fugacity, 1], [0, 0]])
    link2 = np.array([[0, 0], [1, fugacity]])
    for a, b in ((e1, e2), (link1, link2)):
        np.testing.assert_allclose(a @ a, fugacity*a, atol=1e-14)
        np.testing.assert_allclose(a @ b @ a, a, atol=1e-14)
        def face(operator, u):
            return (sin(angle-u)*np.eye(len(operator)) + sin(u)*operator)/sin(angle)
        u, v = 0.13, 0.24
        left = face(a, u) @ face(b, u+v) @ face(a, v)
        right = face(b, v) @ face(a, u+v) @ face(b, u)
        print("Braid error:", np.linalg.norm(left-right, ord=np.inf))
        np.testing.assert_allclose(left, right, atol=1e-14)
    bad_angle = pi/5
    bad = height_generator(states, 1, bad_angle)
    print("Truncation at a generic angle:", np.linalg.norm(
        bad @ bad - 2*np.cos(bad_angle)*bad, ord=np.inf))


def vertex_face():
    eta, x, y = 0.3, 0.37, 0.14
    h = 2
    def psi(a, b, u):
        exponent = (-u + (b-a)*a*eta)/2
        return np.array([exp(exponent), exp(-exponent)])
    t = x-y
    A, B, C = sinh(t+eta), sinh(t), sinh(eta)
    R = np.array([[A,0,0,0], [0,B,C,0], [0,C,B,0], [0,0,0,A]])
    incoming = np.kron(psi(h,h+1,x), psi(h+1,h,y))
    words = [np.kron(psi(d,h,x), psi(h,d,y)) for d in (h-1,h+1)]
    weights = [B*sinh((h+1)*eta)/sinh(h*eta), C*sinh(h*eta-t)/sinh(h*eta)]
    residual = R@incoming - np.array(weights)@words
    print("Returning face weights:", weights)
    print("All four components:", R@incoming, "max error", max(abs(residual)))
    np.testing.assert_allclose(residual, np.zeros(4), atol=2e-15)


if __name__ == "__main__":
    path_and_loop_checks()
    vertex_face()
