"""Checks for the Library article "The complete Bethe spectrum of a finite periodic XXX chain".

Periodic spin-1/2 XXX chain of L sites, H = sum_n (1 - P_{n,n+1}), M down spins. Transfer matrix
T(u) = tr_0 L_{0L}(u) ... L_{01}(u) with L_{0n}(u) = (u - i/2) + i P_{0n}. For each highest-weight eigenvector, Baxter's
relation  Lambda(u) Q(u) = (u + i/2)^L Q(u - i) + (u - i/2)^L Q(u + i)  is solved as a linear system for the monic
degree-M polynomial Q, whose roots are the Bethe roots. Nothing in the method assumes the form of the roots.
Checks, for every sector with 4 <= L <= 12 and 1 <= M <= L/2:
  1. the transfer matrix at u0 = 0.3 + 0.7i has distinct eigenvalues on the highest-weight space (simple spectrum);
  2. every eigenvector gives a Q with relative TQ residual below 1e-10, distinct roots, closed under conjugation;
  3. for states without roots at +-i/2, sum 1/(u^2 + 1/4) equals <H> and prod (u + i/2)/(u - i/2) equals
     Lambda(i/2)/i^L, the eigenvalue of the shift (1e-8);
  4. the number of states whose roots are all real equals C(L - M, M), Bethe's count of real-root quantum numbers;
  5. every state with roots at +i/2 and -i/2 has them to 1e-12 and satisfies (-prod_{other} (u+i/2)/(u-i/2))^L = 1.
For two magnons up to L = 30 the program counts real and complex solutions against the string hypothesis, which
predicts (L - 2)(L - 3)/2 real pairs and L - 3 two-strings; the prediction holds through L = 21 and fails from L = 22
on, with the total unchanged.
Control: dropping the second term of the TQ relation leaves residuals of order one.
Run with Python 3 and NumPy:  python3 complete_bethe_spectra.py   (about a minute)
"""
from itertools import combinations
from math import comb
import numpy as np

U0 = 0.3 + 0.7j


def sector(L, M):
    states = [sum(1 << i for i in c) for c in combinations(range(L), M)]
    return states, {s: i for i, s in enumerate(states)}


class Chain:
    """Sector-restricted action of the transfer matrix and of H on states with M down spins."""

    def __init__(self, L, M):
        self.L, self.M = L, M
        self.S = {m: sector(L, m) for m in (M - 1, M, M + 1) if 0 <= m <= L}
        self.swap = {}
        for m in (M, M + 1):
            if m in self.S and m - 1 in self.S:
                states, _ = self.S[m]
                _, lower = self.S[m - 1]
                for n in range(L):
                    down = np.array([i for i, s in enumerate(states) if (s >> n) & 1], dtype=int)
                    target = np.array([lower[states[i] ^ (1 << n)] for i in down], dtype=int)
                    self.swap[m, n] = (down, target)
        states, index = self.S[M]
        self.bonds = []
        for n in range(L):
            m = (n + 1) % L
            self.bonds.append(np.array([index[s ^ ((1 << n) | (1 << m))] if ((s >> n) & 1) != ((s >> m) & 1) else i
                                        for i, s in enumerate(states)]))

    def T(self, u, v):
        out = np.zeros(len(v), complex)
        for aux_down in (0, 1):
            top = self.M + aux_down               # chain sector of the component with the auxiliary spin up
            A = np.zeros(len(self.S[top][0]) if top in self.S else 0, complex)
            B = np.zeros(len(self.S[top - 1][0]) if top - 1 in self.S else 0, complex)
            if aux_down:
                B[:] = v
            else:
                A[:] = v
            for n in range(self.L):
                PA, PB = A.copy(), B.copy()
                if (top, n) in self.swap:
                    down, target = self.swap[top, n]
                    PA[down], PB[target] = B[target], A[down]
                A, B = (u - 0.5j) * A + 1j * PA, (u - 0.5j) * B + 1j * PB
            out += B if aux_down else A
        return out

    def H(self, v):
        return sum(v - v[b] for b in self.bonds)


def highest_weight(L, M):
    states, index = sector(L, M)
    lower_states, lower = sector(L, M - 1)
    raise_ = np.zeros((len(lower_states), len(states)))
    for i, s in enumerate(states):
        for n in range(L):
            if (s >> n) & 1:
                raise_[lower[s ^ (1 << n)], i] += 1
    _, sv, vt = np.linalg.svd(raise_)
    return vt[int(np.sum(sv > 1e-10)):].T


def solve_q(lam_at, nodes, L, M, second_term=True):
    """Least-squares solution of the TQ relation at the nodes for monic Q of degree M; returns roots, residual."""
    A = np.zeros((len(nodes), M), complex)
    b = np.zeros(len(nodes), complex)
    for r, z in enumerate(nodes):
        for m in range(M + 1):
            col = lam_at[r] * z ** m - (z + 0.5j) ** L * (z - 1j) ** m
            if second_term:
                col -= (z - 0.5j) ** L * (z + 1j) ** m
            if m < M:
                A[r, m] = col
            else:
                b[r] = -col
    q, *_ = np.linalg.lstsq(A, b, rcond=None)
    Q = np.poly1d(np.r_[1.0, q[::-1]])
    a = np.array([(z + 0.5j) ** L * Q(z - 1j) for z in nodes])
    d = np.array([(z - 0.5j) ** L * Q(z + 1j) for z in nodes]) if second_term else 0 * a
    # residual relative to the size of the terms of the relation, not of their (possibly cancelling) sum
    residual = np.max(np.abs(lam_at * Q(nodes) - a - d)) / np.max(np.abs(a) + np.abs(d))
    return Q.roots, residual


def census(L, M, second_term=True):
    """All highest-weight states of the sector: list of dicts with roots and checks."""
    chain = Chain(L, M)
    W = highest_weight(L, M)
    d = W.shape[1]
    T0 = W.T @ np.column_stack([chain.T(U0, W[:, j]) for j in range(d)])
    eigenvalues, V = np.linalg.eig(T0)
    vectors = W @ V
    K = L + M + 3
    nodes = 1.7 * np.exp(2j * np.pi * (np.arange(K) + 0.25) / K)
    gaps = np.abs(eigenvalues[:, None] - eigenvalues[None, :]) + np.eye(d) * 1e300
    states = []
    for a in range(d):
        v = vectors[:, a]
        norm = v.conj() @ v
        lam = np.array([(v.conj() @ chain.T(z, v)) / norm for z in nodes])
        roots, residual = solve_q(lam, nodes, L, M, second_term)
        energy = ((v.conj() @ chain.H(v)) / norm).real
        shift = (v.conj() @ chain.T(0.5j, v)) / norm / 1j ** L
        states.append({'roots': roots, 'residual': residual, 'energy': energy, 'shift': shift})
    return states, d, gaps.min()


def classify(roots):
    plus = np.min(np.abs(roots - 0.5j))
    minus = np.min(np.abs(roots + 0.5j))
    if plus < 1e-6 and minus < 1e-6:
        return 'singular'
    return 'real' if np.all(np.abs(roots.imag) < 1e-9) else 'complex'


def main():
    checks, controls = {}, {}
    worst = {'gap': np.inf, 'residual': 0.0, 'energy': 0.0, 'shift': 0.0, 'conj': 0.0, 'singular': 0.0, 'nw': 0.0}
    distinct, counts_ok, total = True, True, 0
    print(' L  M  states  real (Bethe count)  complex  singular')
    for L in range(4, 13):
        for M in range(1, L // 2 + 1):
            states, d, gap = census(L, M)
            assert d == comb(L, M) - comb(L, M - 1)
            total += d
            worst['gap'] = min(worst['gap'], gap)
            kinds = {'real': 0, 'complex': 0, 'singular': 0}
            for s in states:
                r = s['roots']
                kind = classify(r)
                kinds[kind] += 1
                worst['residual'] = max(worst['residual'], s['residual'])
                separations = np.abs(r[:, None] - r[None, :]) + np.eye(M) * 1e300
                distinct &= separations.min() > 1e-6
                worst['conj'] = max(worst['conj'], max(np.min(np.abs(r - np.conj(x))) for x in r))
                if kind == 'singular':
                    worst['singular'] = max(worst['singular'], np.min(np.abs(r - 0.5j)), np.min(np.abs(r + 0.5j)))
                    others = [x for x in r if min(abs(x - 0.5j), abs(x + 0.5j)) > 1e-6]
                    nw = (-np.prod([(x + 0.5j) / (x - 0.5j) for x in others])) ** L
                    worst['nw'] = max(worst['nw'], abs(nw - 1))
                else:
                    worst['energy'] = max(worst['energy'], abs(np.sum(1 / (r ** 2 + 0.25)).real - s['energy']))
                    worst['shift'] = max(worst['shift'], abs(np.prod((r + 0.5j) / (r - 0.5j)) - s['shift']))
            counts_ok &= kinds['real'] == comb(L - M, M)
            print(f"{L:2d} {M:2d}  {d:5d}   {kinds['real']:4d} ({comb(L - M, M):4d})       {kinds['complex']:4d}     {kinds['singular']:4d}")
    print(f'{total} highest-weight states; smallest eigenvalue gap of T(u0) {worst["gap"]:.2e}; largest TQ residual '
          f'{worst["residual"]:.1e}; energy {worst["energy"]:.1e}; shift {worst["shift"]:.1e}; conjugation {worst["conj"]:.1e}; '
          f'singular roots {worst["singular"]:.1e}; singular condition {worst["nw"]:.1e}')
    checks['T(u0) has a simple spectrum on every highest-weight space with L <= 12 (gap > 1e-6)'] = worst['gap'] > 1e-6
    checks['every highest-weight state gives a monic Q of degree M: TQ residual < 1e-10, distinct roots, closed under conjugation'] = (
        worst['residual'] < 1e-10 and distinct and worst['conj'] < 1e-8)
    checks['regular states: sum 1/(u^2 + 1/4) = <H> and prod (u + i/2)/(u - i/2) = shift eigenvalue (1e-8)'] = (
        worst['energy'] < 1e-8 and worst['shift'] < 1e-8)
    checks['the number of all-real states equals C(L - M, M) in every sector with L <= 12'] = counts_ok
    checks['singular states have roots +-i/2 to 1e-12 and satisfy (-prod (u+i/2)/(u-i/2))^L = 1 (1e-8)'] = (
        worst['singular'] < 1e-12 and worst['nw'] < 1e-8)

    # Two magnons against the string hypothesis.
    print(' L  real (string hypothesis)  complex (string hypothesis)  singular')
    agree, from22 = [], []
    for L in (12, 16, 20, 21, 22, 23, 24, 26, 30):
        states, d, _ = census(L, 2)
        kinds = [classify(s['roots']) for s in states]
        real, cplx = kinds.count('real'), d - kinds.count('real')
        print(f'{L:2d}  {real:4d} ({(L - 2) * (L - 3) // 2:4d})             {cplx:3d} ({L - 3:3d})                 {kinds.count("singular")}')
        (agree if L <= 21 else from22).append((real, cplx, (L - 2) * (L - 3) // 2, L - 3))
    checks['two magnons: the string-hypothesis counts hold for L <= 21; from L = 22 two strings become real pairs'] = (
        all(r == rp and c == cp for r, c, rp, cp in agree) and all(r == rp + 2 and c == cp - 2 for r, c, rp, cp in from22))

    # Control: an incomplete Baxter relation.
    states, _, _ = census(8, 3, second_term=False)
    bad = min(s['residual'] for s in states)
    print(f'control: without the second TQ term the smallest residual in L = 8, M = 3 is {bad:.2f}')
    controls['dropping the second term of the TQ relation leaves residuals above 1e-2'] = bad > 1e-2

    for name, ok in checks.items():
        print(f"{'PASS' if ok else 'FAIL'}  {name}")
    for name, ok in controls.items():
        print(f"{'PASS' if ok else 'FAIL'}  control: {name}")
    if not all(checks.values()) or not all(controls.values()):
        raise SystemExit(1)


if __name__ == '__main__':
    main()
