"""Finite periodic spin-1/2 XXX checks. Requires Python 3, NumPy and SciPy."""
from itertools import combinations
from math import pi, sqrt

import numpy as np
from scipy.linalg import null_space
from scipy.optimize import brentq


def relative_pair(length):
    """K=pi/2. Test the decay ansatz against the physical separation equations."""
    if length < 4 or length % 4:
        raise ValueError("The ring must admit momentum pi/2.")
    sign = (-1)**(length//4)
    cosine = 1/sqrt(2)
    # The odd image has a zero wave at q=1. First test for a nonzero branch.
    if sign == -1 and cosine >= (length-2)/length:
        return None

    def contact(q):
        return (q+sign*q**(length-1))/(1+sign*q**length) - cosine

    q = brentq(contact, 0, 1-1e-8, xtol=1e-15)
    z = np.exp(1j*pi/4)/q
    rapidity = 0.5j*(z+1)/(z-1)
    energy = 2-cosine*(q+1/q)
    size = length-1
    h = np.diag(np.r_[1., np.full(size-2, 2.), 1.])
    h += np.diag(np.full(size-1,-cosine),1) + np.diag(np.full(size-1,-cosine),-1)
    # Reverse separation acts by r -> L-r. A basis of its eigenspace enforces the seam.
    parity = null_space(np.eye(size)[::-1] - sign*np.eye(size))
    physical_levels = np.linalg.eigvalsh(parity.T @ h @ parity)
    assert abs(physical_levels[0]-energy) < 2e-13
    return q, rapidity, energy


def spin_matrices(length, flips):
    positions = list(combinations(range(length), flips))
    index = {state: j for j, state in enumerate(positions)}
    parents = {state: j for j, state in enumerate(combinations(range(length), flips-1))}
    shift = np.zeros((len(index), len(index)))
    h = np.zeros_like(shift)
    raising = np.zeros((len(parents), len(index)))
    for col, state in enumerate(positions):
        shifted = tuple(sorted((site+1) % length for site in state))
        shift[index[shifted],col] = 1
        for site in state:
            raising[parents[tuple(a for a in state if a != site)],col] = 1
        for site in range(length):
            bond = {site, (site+1) % length}
            if len(bond.intersection(state)) == 1:
                exchanged = tuple(sorted(bond.symmetric_difference(state)))
                h[col,col] += 0.5
                h[index[exchanged],col] -= 0.5
    return h, shift, raising


def six_spins():
    h, shift, raising = spin_matrices(6, 3)
    multiplicities = []
    for k in range(6):
        phase = np.exp(2j*pi*k/6)
        states = null_space(np.vstack([shift-phase*np.eye(len(h)), raising]), rcond=1e-12)
        multiplicities.append(states.shape[1])
        if k == 0:
            assert states.shape[1] == 1
            assert np.linalg.norm(h @ states - 3*states) < 2e-14
    assert multiplicities == [1,1,0,2,0,1]
    print("Six-site singlets by translation phase:", multiplicities)
    print("The unique zero-momentum singlet has E/J=3.")


if __name__ == "__main__":
    for n in range(4, 37, 4):
        pair = relative_pair(n)
        if pair is None:
            print(f"L={n}: no positive decaying pair in this parity")
        else:
            q, u, e = pair
            print(f"L={n}: q={q:.9f}  Im(u)-1/2={u.imag-.5:+.9g}  E/J={e:.9f}")
    six_spins()
