"""Checks for the Library article "The algebraic Bethe ansatz".

Periodic spin-1/2 XXX chain in the rational convention of the chapter (Faddeev's lectures): sites n = 1..L with
inhomogeneities theta_n, local operator L_n(u) = (u - theta_n - i/2) I + i P_{an}, monodromy T(u) = L_L(u) ... L_1(u)
with entries A, B, C, D in the auxiliary basis (up, down), transfer matrix t(u) = A(u) + D(u), all-up vacuum |0>,
a(u) = prod (u - theta_n + i/2), d(u) = prod (u - theta_n - i/2), R(u) = u I + i P, g(x) = i/x, f = 1 - g, h = 1 + g.

Checks:
  1. RTT relation R12(u-v) T1(u) T2(v) = T2(v) T1(u) R12(u-v) on an inhomogeneous 4-site chain (1e-12, relative);
  2. exchange relations A(u)B(v) = f B(v)A(u) + g B(u)A(v), D(u)B(v) = h B(v)D(u) - g B(u)D(v), [B(u), B(v)] = 0 as
     operator identities on 5 sites (1e-12); H = (J/2)(L - i t(i/2)^-1 t'(i/2)) on a homogeneous 5-site ring (1e-8,
     with a central-difference derivative);
  3. the off-shell action t(u) B(v_1)...B(v_M)|0> = Lambda(u) |v> + sum_k g(u - v_k) E_k |v; v_k -> u> for random
     complex parameters, M = 3 on 8 sites and M = 4 on 9 sites (1e-12);
  4. every real-root solution of the homogeneous Bethe equations on 12 sites (sum_M C(12 - M, M) = 232 states for
     M = 1..6, labelled by quantum numbers) gives a Bethe vector that is an eigenvector of H = (J/2) sum (1 - P) with
     E = (J/2) sum 1/(v^2 + 1/4), of t(u) with eigenvalue Lambda(u) at two probes, of the shift with eigenvalue
     prod (v + i/2)/(v - i/2), and is annihilated by S^+ (all 1e-10, relative);
  5. the squared norm of each of the 232 vectors equals prod (v^2 + 1/4)^L prod_{a<b} (1 + (v_a - v_b)^-2) det G with
     the Gaudin matrix G (1e-10, relative); the M = 6 state with quantum numbers -5/2..5/2 is the top of the S^z = 0
     spectrum of H by exact diagonalization, the antiferromagnetic ground state when J < 0 (1e-10);
  6. the M = 3 Bethe vector of the 12-site chain is proportional to Bethe's coordinate wavefunction with rapidities
     -v_j and two-body factors (v_a - v_b + i)/(v_a - v_b - i) (1e-10);
  7. quantum inverse problem on an inhomogeneous 4-site chain: E_j^{ab} = U_{j-1} T_{ba}(theta_j + i/2) U_j^{-1},
     U_j = t(theta_1 + i/2) ... t(theta_j + i/2), for every site and matrix unit (1e-10).
Controls: R(u) = u I - i P violates the RTT relation; displacing one root of the 12-site ground state by 0.01 leaves
a vector that no eigenvalue fits and that S^+ does not annihilate; dropping the pair factor from the norm formula
misses every state with M >= 2.
Run with Python 3 and NumPy:  python3 algebraic_bethe_ansatz_check.py   (about 5 seconds)
"""
from itertools import combinations, permutations
from math import comb

import numpy as np

rng = np.random.default_rng(20261125)
g = lambda x: 1j / x
f = lambda x: 1 - 1j / x
h = lambda x: 1 + 1j / x


class Chain:
    """Spin-1/2 chain of L sites; a state is a complex array of shape (2,) * L, index 0 = up, 1 = down."""

    def __init__(self, L, theta=None):
        self.L = L
        self.theta = np.zeros(L) if theta is None else np.asarray(theta, dtype=float)

    def site(self, op, n, psi):
        """Apply a one-site operator ('z', '-', '+') to site n (1-based)."""
        x = np.moveaxis(psi, n - 1, 0)
        out = np.zeros_like(x)
        if op == 'z':
            out[0], out[1] = 0.5 * x[0], -0.5 * x[1]
        elif op == '-':
            out[1] = x[0]
        elif op == '+':
            out[0] = x[1]
        return np.moveaxis(out, 0, n - 1)

    def lax(self, n, u, phi):
        """Apply L_n(u) to an auxiliary pair phi = (phi_up, phi_down) of physical states."""
        s = u - self.theta[n - 1]
        up, dn = phi
        zu, zd = self.site('z', n, up), self.site('z', n, dn)
        return (s * up + 1j * zu + 1j * self.site('-', n, dn),
                1j * self.site('+', n, up) + s * dn - 1j * zd)

    def entry(self, alpha, beta, u, psi):
        """T_{alpha beta}(u) psi with alpha, beta in {0 = up, 1 = down}; T = L_L ... L_1 (site 1 acts first)."""
        phi = [np.zeros_like(psi), np.zeros_like(psi)]
        phi[beta] = psi
        for n in range(1, self.L + 1):
            phi = self.lax(n, u, phi)
        return phi[alpha]

    A = lambda self, u, psi: self.entry(0, 0, u, psi)
    B = lambda self, u, psi: self.entry(0, 1, u, psi)
    C = lambda self, u, psi: self.entry(1, 0, u, psi)
    D = lambda self, u, psi: self.entry(1, 1, u, psi)

    def t(self, u, psi):
        return self.A(u, psi) + self.D(u, psi)

    def vacuum(self):
        psi = np.zeros((2,) * self.L, dtype=complex)
        psi[(0,) * self.L] = 1.0
        return psi

    def bethe(self, roots):
        psi = self.vacuum()
        for v in roots:
            psi = self.B(v, psi)
        return psi

    def a(self, u):
        return np.prod(u - self.theta + 0.5j)

    def d(self, u):
        return np.prod(u - self.theta - 0.5j)

    def hamiltonian(self, psi, J=1.0):
        """H = (J/2) sum_n (1 - P_{n,n+1}), periodic."""
        out = np.zeros_like(psi)
        for n in range(self.L):
            m = (n + 1) % self.L
            out += psi - np.swapaxes(psi, n, m)
        return 0.5 * J * out

    def s_plus(self, psi):
        return sum(self.site('+', n, psi) for n in range(1, self.L + 1))

    def dense(self, alpha, beta, u):
        """T_{alpha beta}(u) as a dense 2^L x 2^L matrix (small L only)."""
        N = 2 ** self.L
        cols = [self.entry(alpha, beta, u, np.eye(N, dtype=complex)[k].reshape((2,) * self.L)).ravel()
                for k in range(N)]
        return np.array(cols).T


def rel(x, ref):
    return np.linalg.norm(x) / max(np.linalg.norm(ref), 1e-300)


def eigen_residual(op_psi, psi):
    """min over lambda of |op_psi - lambda psi| / |op_psi|, and the minimizing lambda."""
    lam = np.vdot(psi, op_psi) / np.vdot(psi, psi)
    return rel(op_psi - lam * psi, op_psi), lam


def unwanted(chain, roots, k):
    others = [w for j, w in enumerate(roots) if j != k]
    v = roots[k]
    return chain.a(v) * np.prod([f(v - w) for w in others]) - chain.d(v) * np.prod([h(v - w) for w in others])


def eigenvalue(chain, roots, u):
    return chain.a(u) * np.prod([f(u - v) for v in roots]) + chain.d(u) * np.prod([h(u - v) for v in roots])


def real_roots(L, I, steps=8, tol=1e-14):
    """Solve L*2 atan(2 v_k) - sum_j 2 atan(v_k - v_j) = 2 pi I_k by damped Newton with a continuation in the
    scattering term; the Jacobian is the Gaudin matrix."""
    I = np.asarray(I, dtype=float)
    v = 0.5 * np.tan(np.pi * I / L)
    for alpha in np.linspace(0.0, 1.0, steps + 1)[1:]:
        for _ in range(100):
            diff = v[:, None] - v[None, :]
            F = 2 * L * np.arctan(2 * v) - alpha * np.sum(2 * np.arctan(diff), axis=1) - 2 * np.pi * I
            K = 2 / (1 + diff ** 2)
            G = alpha * K
            G[np.diag_indices(len(v))] = 4 * L / (1 + 4 * v ** 2) - alpha * (np.sum(K, axis=1) - 2)
            step = np.linalg.solve(G, F)
            lam = 1.0
            while lam > 1e-4:
                trial = v - lam * step
                dt = trial[:, None] - trial[None, :]
                Ft = 2 * L * np.arctan(2 * trial) - alpha * np.sum(2 * np.arctan(dt), axis=1) - 2 * np.pi * I
                if np.linalg.norm(Ft) < np.linalg.norm(F) or np.linalg.norm(F) < tol:
                    break
                lam /= 2
            v = trial
            if np.linalg.norm(Ft) < tol:
                break
    return np.sort(v), np.linalg.norm(Ft)


def gaudin(L, v):
    diff = v[:, None] - v[None, :]
    K = 2 / (1 + diff ** 2)
    G = K.copy()
    G[np.diag_indices(len(v))] = L / (v ** 2 + 0.25) - (np.sum(K, axis=1) - 2)
    pair = np.prod([1 + 1 / (v[a] - v[b]) ** 2 for a, b in combinations(range(len(v)), 2)]) if len(v) > 1 else 1.0
    return np.prod((v ** 2 + 0.25) ** L), pair, np.linalg.det(G)


def main():
    checks, controls = {}, {}

    # 1. RTT relation.
    ch4 = Chain(4, theta=rng.normal(size=4) * 0.3)
    u, v = 0.37 + 0.21j, -0.52 + 0.13j
    N = 16
    T_u = np.block([[ch4.dense(0, 0, u), ch4.dense(0, 1, u)], [ch4.dense(1, 0, u), ch4.dense(1, 1, u)]])
    T_v = np.block([[ch4.dense(0, 0, v), ch4.dense(0, 1, v)], [ch4.dense(1, 0, v), ch4.dense(1, 1, v)]])
    I2, IN = np.eye(2), np.eye(N)
    P = np.zeros((4, 4))
    for i in range(2):
        for j in range(2):
            P[2 * i + j, 2 * j + i] = 1

    def embed(Tm, slot):
        """Monodromy in auxiliary slot 1 or 2 of aux1 (x) aux2 (x) physical."""
        out = np.zeros((4 * N, 4 * N), dtype=complex)
        for al in range(2):
            for be in range(2):
                blk = Tm[al * N:(al + 1) * N, be * N:(be + 1) * N]
                for c in range(2):
                    if slot == 1:
                        r, s = 2 * al + c, 2 * be + c
                    else:
                        r, s = 2 * c + al, 2 * c + be
                    out[r * N:(r + 1) * N, s * N:(s + 1) * N] = blk
        return out

    T1, T2 = embed(T_u, 1), embed(T_v, 2)
    rtt = []
    for sign in (+1, -1):
        R = np.kron((u - v) * np.eye(4) + sign * 1j * P, IN)
        rtt.append(rel(R @ T1 @ T2 - T2 @ T1 @ R, R @ T1 @ T2))
    print(f'RTT relation on 4 inhomogeneous sites: relative residual {rtt[0]:.1e}; with R = u - iP {rtt[1]:.2f}')
    checks['RTT relation with R(u) = u + iP (1e-12)'] = rtt[0] < 1e-12
    controls['R(u) = u - iP violates the RTT relation (residual > 0.1)'] = rtt[1] > 0.1

    # 2. Exchange relations.
    ch5 = Chain(5, theta=rng.normal(size=5) * 0.3)
    A_u, B_u, D_u = ch5.dense(0, 0, u), ch5.dense(0, 1, u), ch5.dense(1, 1, u)
    A_v, B_v, D_v = ch5.dense(0, 0, v), ch5.dense(0, 1, v), ch5.dense(1, 1, v)
    x = u - v
    ex = [rel(A_u @ B_v - f(x) * B_v @ A_u - g(x) * B_u @ A_v, A_u @ B_v),
          rel(D_u @ B_v - h(x) * B_v @ D_u + g(x) * B_u @ D_v, D_u @ B_v),
          rel(B_u @ B_v - B_v @ B_u, B_u @ B_v)]
    print('exchange relations on 5 sites: AB {:.1e}, DB {:.1e}, [B, B] {:.1e}'.format(*ex))
    checks['exchange relations AB, DB and [B, B] = 0 (1e-12)'] = max(ex) < 1e-12

    # Hamiltonian from the logarithmic derivative of t(u) at u = i/2 on a homogeneous 5-site ring.
    hom = Chain(5)
    tm = lambda w: hom.dense(0, 0, w) + hom.dense(1, 1, w)
    eps = 1e-5
    dt = (tm(0.5j + eps) - tm(0.5j - eps)) / (2 * eps)
    H5 = np.array([hom.hamiltonian(np.eye(32, dtype=complex)[k].reshape((2,) * 5)).ravel() for k in range(32)]).T
    from_t = 0.5 * (5 * np.eye(32) - 1j * np.linalg.solve(tm(0.5j), dt))
    log_err = rel(from_t - H5, H5)
    print(f'H = (J/2)(L - i t(i/2)^-1 t\'(i/2)) on 5 sites: relative error {log_err:.1e} (central difference, step 1e-5)')
    checks['H = (J/2)(L - i d ln t/du at u = i/2) (1e-8, finite-difference derivative)'] = log_err < 1e-8

    # 3. Off-shell action with random complex parameters.
    off = []
    for L, M in ((8, 3), (9, 4)):
        ch = Chain(L, theta=rng.normal(size=L) * 0.2)
        roots = list(rng.normal(size=M) + 1j * rng.normal(size=M) * 0.5)
        probe = 0.3 - 0.4j
        psi = ch.bethe(roots)
        lhs = ch.t(probe, psi)
        rhs = eigenvalue(ch, roots, probe) * psi
        for k in range(M):
            replaced = [probe if j == k else w for j, w in enumerate(roots)]
            rhs = rhs + g(probe - roots[k]) * unwanted(ch, roots, k) * ch.bethe(replaced)
        off.append(rel(lhs - rhs, lhs))
    print('off-shell action, random complex roots: M = 3 on 8 sites {:.1e}, M = 4 on 9 sites {:.1e}'.format(*off))
    checks['off-shell action for M = 3 and 4 with inhomogeneous sites (1e-12)'] = max(off) < 1e-12

    # 4-5. Every real-root state of the 12-site chain.
    L = 12
    ch = Chain(L)
    shift = lambda psi: np.moveaxis(psi, 0, -1)          # candidate shift; identified below from t(i/2)
    probe_psi = rng.normal(size=(2,) * L) + 1j * rng.normal(size=(2,) * L)
    t_half = ch.t(0.5j, probe_psi) / 1j ** L
    which = rel(t_half - shift(probe_psi), t_half), rel(t_half - np.moveaxis(probe_psi, -1, 0), t_half)
    U = shift if which[0] < which[1] else (lambda psi: np.moveaxis(psi, -1, 0))
    print(f't(i/2) = i^L U with U = {"moveaxis(0, -1)" if which[0] < which[1] else "moveaxis(-1, 0)"} '
          f'(residuals {which[0]:.1e}, {which[1]:.1e})')
    worst = dict(newton=0.0, bae=0.0, H=0.0, t=0.0, shift=0.0, splus=0.0, norm=0.0)
    count, norms, records = 0, [], []
    for M in range(1, L // 2 + 1):
        half = (L - M - 1) / 2
        allowed = np.arange(-half, half + 0.5, 1.0)
        for I in combinations(allowed, M):
            roots, res = real_roots(L, I)
            worst['newton'] = max(worst['newton'], res)
            bae = max(abs(ch.a(r) / ch.d(r) - np.prod([(r - w + 1j) / (r - w - 1j) for w in roots if w != r])) for r in roots)
            worst['bae'] = max(worst['bae'], bae)
            psi = ch.bethe(roots)
            E = 0.5 * np.sum(1 / (roots ** 2 + 0.25))
            Hpsi = ch.hamiltonian(psi)
            worst['H'] = max(worst['H'], rel(Hpsi - E * psi, Hpsi))
            for pr in (0.31 + 0.17j, -1.3):
                tpsi = ch.t(pr, psi)
                worst['t'] = max(worst['t'], rel(tpsi - eigenvalue(ch, roots, pr) * psi, tpsi))
            mom = np.prod((roots + 0.5j) / (roots - 0.5j))
            worst['shift'] = max(worst['shift'], rel(U(psi) - mom * psi, psi))
            worst['splus'] = max(worst['splus'], rel(ch.s_plus(psi), psi))
            nrm = np.vdot(psi, psi).real
            vac, pair, detG = gaudin(L, roots)
            worst['norm'] = max(worst['norm'], abs(nrm / (vac * pair * detG) - 1))
            norms.append((M, nrm, vac * pair * detG, vac * detG))
            records.append((M, tuple(I), roots, E))
            count += 1
    expected = sum(comb(L - M, M) for M in range(1, L // 2 + 1))
    print(f'{count} real-root states on {L} sites (expected {expected}); worst: Newton {worst["newton"]:.1e}, '
          f'Bethe equations {worst["bae"]:.1e}, H {worst["H"]:.1e}, t(u) {worst["t"]:.1e}, shift {worst["shift"]:.1e}, '
          f'S+ {worst["splus"]:.1e}, norm formula {worst["norm"]:.1e}')
    checks['232 real-root states on 12 sites: eigenvectors of H, t(u) and the shift, annihilated by S+ (1e-10)'] = (
        count == expected == 232 and max(worst['H'], worst['t'], worst['shift'], worst['splus']) < 1e-10)
    checks['Gaudin-Korepin norm for all 232 states (1e-10)'] = worst['norm'] < 1e-10
    missing_pair = [abs(n / q - 1) for M, n, _, q in norms if M >= 2]
    print(f'norm formula without the pair factor: smallest relative error {min(missing_pair):.3f} over M >= 2')
    controls['dropping the pair factor misses every state with M >= 2 (relative error > 1e-3)'] = min(missing_pair) > 1e-3

    gs = [r for r in records if r[0] == 6][0]
    sector = [c for c in combinations(range(L), 6)]
    index = {c: k for k, c in enumerate(sector)}
    Hs = np.zeros((len(sector), len(sector)))
    for k, c in enumerate(sector):
        basis = np.zeros((2,) * L)
        basis[tuple(1 if q in c else 0 for q in range(L))] = 1.0
        out = ch.hamiltonian(basis).real
        for idx in zip(*np.nonzero(out)):
            Hs[index[tuple(q for q in range(L) if idx[q] == 1)], k] = out[idx]
    top = np.linalg.eigvalsh(Hs)[-1]
    print('M = 6 state with I = -5/2..5/2: roots', ' '.join(f'{x:.10f}' for x in gs[2]),
          f'; E = {gs[3]:.10f} J; largest eigenvalue of H in the S^z = 0 sector {top:.10f} J; '
          f'sum S.S = {L / 4 - gs[3]:.10f}')
    checks['the M = 6 Bethe state is the top of the S^z = 0 spectrum of H (1e-10)'] = abs(top - gs[3]) < 1e-10

    # control: displace one root of the M = 6 state.
    roots = np.array(gs[2]).copy()
    roots[0] += 0.01
    psi = ch.bethe(roots)
    res_t, _ = eigen_residual(ch.t(0.31 + 0.17j, psi), psi)
    res_H, _ = eigen_residual(ch.hamiltonian(psi), psi)
    sp = rel(ch.s_plus(psi), psi)
    print(f'one root displaced by 0.01: eigen-residuals t {res_t:.2e}, H {res_H:.2e}; |S+ psi|/|psi| {sp:.2e}')
    controls['a displaced root gives no eigenvector and S+ psi != 0 (residuals > 1e-4)'] = min(res_t, res_H, sp) > 1e-4

    # 6. Coordinate wavefunction for M = 3.
    M3 = [r for r in records if r[0] == 3][7]
    roots = M3[2]
    psi = ch.bethe(roots)
    z = (roots - 0.5j) / (roots + 0.5j)
    amps, coords = [], []
    for xs in combinations(range(1, L + 1), 3):
        coord = 0
        for perm in permutations(range(3)):
            amp = 1.0
            for p_, q_ in combinations(range(3), 2):
                if perm[p_] > perm[q_]:
                    a_, b_ = perm[q_], perm[p_]
                    amp *= (roots[a_] - roots[b_] + 1j) / (roots[a_] - roots[b_] - 1j)
            coord += amp * np.prod([z[perm[j]] ** xs[j] for j in range(3)])
        idx = [0] * L
        for x_ in xs:
            idx[x_ - 1] = 1
        amps.append(psi[tuple(idx)])
        coords.append(coord)
    amps, coords = np.array(amps), np.array(coords)
    scale = np.vdot(coords, amps) / np.vdot(coords, coords)
    spread = rel(amps - scale * coords, amps)
    print(f'M = 3 Bethe vector against the coordinate wavefunction: {len(amps)} amplitudes, relative residual after '
          f'one fitted constant {spread:.1e}')
    checks['M = 3 Bethe vector equals the coordinate wavefunction up to one constant (1e-10)'] = spread < 1e-10

    # 7. Quantum inverse problem.
    chq = Chain(4, theta=np.array([0.13, -0.41, 0.77, -0.05]))
    Nq = 16
    xi = chq.theta + 0.5j
    tm = [chq.dense(0, 0, z_) + chq.dense(1, 1, z_) for z_ in xi]
    worst_q = 0.0
    for j in range(1, 5):
        Uprev = np.eye(Nq, dtype=complex)
        for s in range(j - 1):
            Uprev = Uprev @ tm[s]
        Uj = Uprev @ tm[j - 1]
        for a_ in range(2):
            for b_ in range(2):
                E = np.zeros((Nq, Nq), dtype=complex)
                for k in range(Nq):
                    bits = [(k >> (3 - q)) & 1 for q in range(4)]
                    if bits[j - 1] == b_:
                        bits2 = bits.copy()
                        bits2[j - 1] = a_
                        E[sum(bb << (3 - q) for q, bb in enumerate(bits2)), k] = 1
                rec = Uprev @ chq.dense(b_, a_, xi[j - 1]) @ np.linalg.inv(Uj)
                worst_q = max(worst_q, np.max(np.abs(rec - E)))
    print(f'quantum inverse problem on 4 inhomogeneous sites: worst entry error {worst_q:.1e}')
    checks['E_j^ab = U_{j-1} T_ba(theta_j + i/2) U_j^-1 for all sites and matrix units (1e-10)'] = worst_q < 1e-10

    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()
