"""Finite coordinate/ABA comparison and the XXX complex-pair continuation.

Python 3 with NumPy and SciPy. Sites are numbered from one in the manuscript.
"""

from itertools import combinations
import numpy as np
from scipy.optimize import brentq


def bound_pair(length):
    if length < 8 or length % 8:
        raise ValueError("This K=pi/2 continuation uses rings of 8, 16, ... sites.")
    c = np.cos(np.pi/4)
    q = brentq(lambda r: c*(1+r**length)-r-r**(length-1),0,c,xtol=5e-16)
    z = np.exp(1j*np.pi/4)/q
    u = 0.5j*(z+1)/(z-1)
    return q,u


def auxiliary_column(u, state, incoming, shifts=None):
    """Return both outgoing auxiliary components after L_L ... L_1."""
    length = len(state).bit_length() - 1
    if shifts is None:
        shifts = np.zeros(length)
    if len(shifts) != length or 2**length != len(state):
        raise ValueError("Supply one shift per spin-1/2 site.")
    joint = np.zeros((2, len(state)), dtype=complex)
    joint[incoming] = state
    joint = joint.reshape((2,) * (length + 1))
    for site, shift in enumerate(shifts, start=1):
        joint = (u-shift-.5j)*joint + 1j*joint.swapaxes(0,site)
    return joint.reshape(2, -1)


def creation(u, state, shifts=None):
    return auxiliary_column(u, state, 1, shifts)[0]


def transfer(u, state, shifts=None, twist=0):
    a = auxiliary_column(u, state, 0, shifts)[0]
    d = auxiliary_column(u, state, 1, shifts)[1]
    return np.exp(.5j*twist)*a + np.exp(-.5j*twist)*d


def coordinate_check(length):
    q,root = bound_pair(length)
    u,v = -root,-root.conjugate()
    omega = np.zeros(2**length,dtype=complex)
    omega[0] = 1
    algebraic = creation(u,creation(v,omega))
    zu,zv = (u-.5j)/(u+.5j),(v-.5j)/(v+.5j)
    s = (u-v+1j)/(u-v-1j)
    scalar = -(u+.5j)**(length-1)*(v+.5j)**(length-1)*(1-1j/(u-v))/(zu*zv)
    coordinate = 0*omega
    for i,j in combinations(range(length),2):
        mask = (1<<(length-i-1))+(1<<(length-j-1))
        coordinate[mask] = zu**(i+1)*zv**(j+1)+s*zv**(i+1)*zu**(j+1)
    error = np.linalg.norm(algebraic-scalar*coordinate)/np.linalg.norm(algebraic)
    assert error < 2e-13
    phase = algebraic[3 << (length-3)] / algebraic[3 << (length-2)]
    np.testing.assert_allclose(phase, 1j, atol=3e-14)
    register = algebraic.reshape((2,) * length)
    translated = np.moveaxis(register, -1, 0).ravel()
    np.testing.assert_allclose(translated, -1j*algebraic, atol=3e-13)
    acted = np.zeros_like(register)
    for site in range(length):
        acted += .5*(register-register.swapaxes(site, (site+1) % length))
    energy = 2 - np.sqrt(2)*np.cosh(np.log(q))
    h_error = np.linalg.norm(acted.ravel()-energy*algebraic)/np.linalg.norm(algebraic)
    assert h_error < 3e-13
    return scalar, phase, error


def coincident_pair():
    omega = np.eye(16)[:,0]
    state = creation(0, creation(0, omega))
    indices = [2**(4-x) + 2**(4-y) for x, y in combinations(range(1, 5), 2)]
    amplitudes = state[indices]
    np.testing.assert_allclose(32*amplitudes, [1,-3,5,1,-3,1], atol=1e-14)
    return amplitudes


def dimer_trial():
    omega = np.eye(4)[:,0]
    shifts = [-.5, .5]
    trial = creation(.25, omega, shifts)
    trial /= np.linalg.norm(trial)
    triplet = np.array([0,1,1,0]) / np.sqrt(2)
    weight = abs(np.vdot(triplet, trial))**2
    acted = transfer(.75, trial, shifts)
    residual = np.linalg.norm(acted - np.vdot(trial, acted)*trial)
    np.testing.assert_allclose([weight, residual], [1/9, 4*np.sqrt(2)/9])
    return weight, residual


def off_shell_trial(offset):
    omega = np.eye(16)[:,0]
    u = .5
    w = -1/np.sqrt(12)
    v = -w + offset
    a = lambda x: (x+.5j)**4
    d = lambda x: (x-.5j)**4
    f = lambda x: 1-1j/x
    h = lambda x: 1+1j/x
    cv = a(v)*f(v-w) - d(v)*h(v-w)
    cw = a(w)*f(w-v) - d(w)*h(w-v)
    eigenvalue = a(u)*f(u-v)*f(u-w) + d(u)*h(u-v)*h(u-w)
    state = creation(v, creation(w, omega))
    acted = transfer(u, state)
    residual = acted - eigenvalue*state
    replaced = (1j*cv/(u-v)*creation(u, creation(w, omega))
                + 1j*cw/(u-w)*creation(u, creation(v, omega)))
    np.testing.assert_allclose(residual, replaced, atol=1e-14)
    norm = np.linalg.norm(state)
    rayleigh = np.vdot(state, acted) / norm**2
    return (abs(cv), abs(cw), np.linalg.norm(residual)/norm,
            np.linalg.norm(acted-rayleigh*state)/norm)


def twist_check():
    omega = np.eye(16)[:,0]
    lowered = np.zeros(16)
    lowered[[8,4,2,1]] = 1
    acted = transfer(0, lowered, twist=np.pi)
    np.testing.assert_allclose(acted, -2j*creation(0, omega), atol=1e-15)
    return np.linalg.norm(acted)


def create_color(u, color, vector):
    """B_color(u) from the three-color monodromy L_L ... L_1."""
    joint = np.zeros((3, *vector.shape), dtype=complex)
    joint[color] = vector
    for site in range(1, vector.ndim + 1):
        joint = (u - .5j)*joint + 1j*joint.swapaxes(0, site)
    return joint[0]


def nested_products(length, first_root, second_root):
    vacuum = np.zeros((3,)*length)
    vacuum[(0,)*length] = 1
    first = create_color(first_root, 1, create_color(second_root, 2, vacuum))
    second = create_color(first_root, 2, create_color(second_root, 1, vacuum))
    return first, second


def color_hamiltonian(vector):
    """Apply H/J by direct periodic bond permutations."""
    return sum(vector - vector.swapaxes(j, (j+1) % vector.ndim)
               for j in range(vector.ndim))


def nested_singlet():
    u = 1/np.sqrt(12)
    first, second = nested_products(3, u, -u)
    singlet = first-second
    for i,j in [(0,1),(1,2),(0,2)]:
        np.testing.assert_allclose(singlet.swapaxes(i,j),-singlet,atol=1e-14)
    np.testing.assert_allclose(np.vdot(singlet,singlet),8/9,atol=1e-14)
    np.testing.assert_allclose(np.linalg.norm(first+second)**2, 16/27)
    expected = [-5/18 - 1j/(6*np.sqrt(3)), 1/18 + 1j/(6*np.sqrt(3))]
    np.testing.assert_allclose([first[0,1,2], second[0,1,2]], expected)
    return first[0,1,2], second[0,1,2]


def displaced_color_root():
    u = 1/np.sqrt(12)
    w = 0.5
    first, second = nested_products(3, u, -u)
    singlet = first - second
    state = 1j*(w-u-.5j)*first + 1j*(w+u+.5j)*second
    state /= np.linalg.norm(state)
    fidelity = abs(np.vdot(singlet, state))**2 / np.linalg.norm(singlet)**2
    acted = color_hamiltonian(state)
    energy = np.vdot(state, acted).real
    spread = np.linalg.norm(acted - energy*state)
    np.testing.assert_allclose([fidelity, energy, spread], [2/3, 5, np.sqrt(2)])
    return fidelity, energy, spread


def moving_color_pair():
    length = 4
    coordinate = np.zeros((3,)*length, dtype=complex)
    for x, y in combinations(range(length), 2):
        direct = np.exp(1j*np.pi*(x/2+y))
        exchange = np.exp(1j*np.pi*(y/2+x))
        amplitude = (direct-exchange)/(length*np.sqrt(2))
        sites = [0]*length
        sites[x], sites[y] = 1, 2
        coordinate[tuple(sites)] = amplitude
        sites[x], sites[y] = 2, 1
        coordinate[tuple(sites)] = -amplitude
    np.testing.assert_allclose(np.linalg.norm(coordinate), 1)
    np.testing.assert_allclose(color_hamiltonian(coordinate), 6*coordinate, atol=1e-14)
    checks = []
    for v, translation, expected in [(-.5, 1j, 1), (.5, -1j, 0)]:
        first, second = nested_products(length, v, 0)
        ray = (first - second)/np.linalg.norm(first - second)
        fidelity = abs(np.vdot(ray, coordinate))**2
        rotated = np.moveaxis(ray, -1, 0)
        np.testing.assert_allclose(rotated, translation*ray, atol=1e-14)
        np.testing.assert_allclose(fidelity, expected, atol=1e-14)
        checks.append((v, translation, fidelity))
    return checks


if __name__ == '__main__':
    for n in [8,16,24,32]:
        q,u = bound_pair(n)
        print(n,q,u,2-np.sqrt(2)*np.cosh(np.log(q)))
    print("L=8 coordinate convention",coordinate_check(8))
    print("L=4 coincident zero-root amplitudes", coincident_pair())
    print("Dimer triplet weight, transfer residual", dimer_trial())
    for offset in [0, .01, .005]:
        print("Root shift, unwanted coefficients, formal and best-scalar residuals",
              offset, off_shell_trial(offset))
    print("Twisted transfer on lowered vacuum, norm", twist_check())
    print("three-color ordered products",nested_singlet())
    print("Displaced color root: fidelity, mean energy, spread", displaced_color_root())
    print("Four-site algebraic root, shift and coordinate fidelity", moving_color_pair())
