"""Checks for the Library article "The Heisenberg chain from magnons to spinons".

Antiferromagnetic spin-1/2 ring H = J sum_j (S_j . S_{j+1} - 1/4), J = 1, periodic, even length L. The all-up state
has energy zero. A magnon of rapidity lam has momentum k with e^{ik} = (lam + i/2)/(lam - i/2) and energy
-2/(1 + 4 lam^2). M real rapidities solve the logarithmic Bethe equations
    2 L arctan(2 lam_j) = 2 pi I_j + sum_k 2 arctan(lam_j - lam_k),
with I_j half-odd integers when L - M is even and integers when it is odd, |I_j| <= (L - M - 1)/2.

Checks:
  1. exact diagonalization (ED) of the S^z = 0 sector for L = 8..20 equals the Bethe ground state (M = L/2,
     consecutive symmetric I_j) to 1e-10;
  2. the Bethe ground-state energy per site approaches Hulthen's -ln 2, with L^2 (E0/L + ln 2) tending toward
     -pi^2/12 slowly, as the logarithmic corrections of the isotropic chain require;
  3. for L = 16 the lowest S^z = 1 ED level in every momentum sector equals the lowest two-hole Bethe state with
     M = L/2 - 1 real roots at that momentum;
  4. the lowest two-hole energies approach the des Cloizeaux-Pearson edge (pi/2) sin q with a deviation falling like
     1/L; every two-hole energy lies above that edge, and the few that exceed the upper edge pi sin(q/2) do so by
     about 0.11/L.
Control: the spacing ratio <r> of one symmetry-resolved block of the XXZ chain (Delta = 0.6) is Poisson-like,
while adding a next-nearest-neighbor coupling J2 = 0.5 makes it Wigner-Dyson-like (GOE value 0.5307).
Run with Python 3, NumPy and SciPy:  python3 heisenberg_chain_check.py   (two minutes of CPU time)
"""
from itertools import combinations
import numpy as np
from scipy.sparse import coo_matrix
from scipy.sparse.linalg import eigsh

LN2 = np.log(2.0)


# ----------------------------------------------------------------------------------------------- exact diagonalization
def sector_states(L, n_up):
    """All L-bit configurations with n_up up spins, sorted."""
    return np.array(sorted(sum(1 << i for i in c) for c in combinations(range(L), n_up)), dtype=np.int64)


def bond_terms(states, L, i, j, zz, flip):
    """Diagonal values and (source, target, amplitude) for zz S^z_i S^z_j + flip (S^x_i S^x_j + S^y_i S^y_j)."""
    m = (1 << i) | (1 << j)
    x = states & m
    anti = (x != 0) & (x != m)
    diag = np.where(anti, -0.25 * zz, 0.25 * zz)
    return diag, np.nonzero(anti)[0], states[anti] ^ m, 0.5 * flip


def heisenberg_sector(L, n_up):
    """Sparse H = sum_j (S_j.S_{j+1} - 1/4) on a ring, in one magnetization sector."""
    states = sector_states(L, n_up)
    diag = np.zeros(len(states))
    rows, cols, vals = [], [], []
    for i in range(L):
        d, src, tgt, amp = bond_terms(states, L, i, (i + 1) % L, 1.0, 1.0)
        diag += d - 0.25
        rows.append(np.searchsorted(states, tgt)); cols.append(src); vals.append(np.full(len(src), amp))
    rows = np.concatenate(rows + [np.arange(len(states))])
    cols = np.concatenate(cols + [np.arange(len(states))])
    vals = np.concatenate(vals + [diag])
    return coo_matrix((vals, (rows, cols)), shape=(len(states),) * 2).tocsr()


def ground_energy_ed(L):
    H = heisenberg_sector(L, L // 2)
    if H.shape[0] < 400:
        return float(np.linalg.eigvalsh(H.toarray())[0])
    return float(eigsh(H, k=1, which='SA', tol=1e-12)[0][0])


def translation_data(states, L):
    """Representative (minimal rotation), the shift reaching it, and the period of every state."""
    mask = (1 << L) - 1
    rep, shift = states.copy(), np.zeros(len(states), dtype=np.int64)
    period = np.full(len(states), L, dtype=np.int64)
    t = states.copy()
    for r in range(1, L):
        t = ((t << 1) | (t >> (L - 1))) & mask
        better = t < rep
        rep = np.where(better, t, rep); shift = np.where(better, r, shift)
        period = np.where((t == states) & (period == L), r, period)
    return rep, shift, period


def momentum_block(L, n_up, m, bonds):
    """Dense Hamiltonian in the momentum sector k = 2 pi m / L, for bonds given as (offset, zz, flip, const)."""
    states = sector_states(L, n_up)
    rep, shift, period = translation_data(states, L)
    is_rep = rep == states
    reps, R = states[is_rep], period[is_rep]
    allowed = (m * R) % L == 0
    reps, R = reps[allowed], R[allowed]
    index = {int(s): n for n, s in enumerate(reps)}
    k = 2 * np.pi * m / L
    H = np.zeros((len(reps), len(reps)), dtype=complex)
    for offset, zz, flip, const in bonds:
        for i in range(L):
            d, src, tgt, amp = bond_terms(reps, L, i, (i + offset) % L, zz, flip)
            H[np.arange(len(reps)), np.arange(len(reps))] += d + const
            pos = np.searchsorted(states, tgt)
            for a, b in zip(src, pos):
                r = int(rep[b])
                if r in index:
                    n = index[r]
                    H[n, a] += amp * np.exp(-1j * k * shift[b]) * np.sqrt(R[a] / R[n])
    return H


# ------------------------------------------------------------------------------------------------------- Bethe ansatz
def bethe_roots(L, I, lam0=None, tol=1e-13, iterations=100):
    """Real solutions of the logarithmic Bethe equations by Newton's method."""
    I = np.asarray(I, dtype=float)
    lam = 0.5 * np.tan(np.pi * I / L) if lam0 is None else lam0.copy()
    for _ in range(iterations):
        d = lam[:, None] - lam[None, :]
        F = 2 * L * np.arctan(2 * lam) - 2 * np.pi * I - np.sum(2 * np.arctan(d), axis=1)
        K = 2.0 / (1.0 + d ** 2)
        Jm = K.copy()
        Jm[np.diag_indices_from(Jm)] = 4 * L / (1 + 4 * lam ** 2) - (K.sum(axis=1) - 2.0)
        step = np.linalg.solve(Jm, F)
        lam -= step
        if np.max(np.abs(step)) < tol:
            break
    residual = np.max(np.abs(2 * L * np.arctan(2 * lam) - 2 * np.pi * I
                             - np.sum(2 * np.arctan(lam[:, None] - lam[None, :]), axis=1)))
    return lam, residual


def bethe_energy(lam):
    return float(-np.sum(2.0 / (1.0 + 4.0 * lam ** 2)))


def bethe_momentum(L, I):
    return (len(I) * np.pi - 2 * np.pi * np.sum(I) / L) % (2 * np.pi)


def ground_state(L):
    M = L // 2
    I = np.arange(M) - (M - 1) / 2
    lam, res = bethe_roots(L, I)
    return bethe_energy(lam), res, bethe_momentum(L, I)


def two_hole_states(L):
    """All real two-hole states with M = L/2 - 1 roots: (q in [0, pi], excitation energy, residual)."""
    E0, _, P0 = ground_state(L)
    M = L // 2 - 1
    slots = np.arange(L - M) - (L - M - 1) / 2
    out = []
    for h1 in range(len(slots)):
        for h2 in range(h1 + 1, len(slots)):
            I = np.delete(slots, [h1, h2])
            lam, res = bethe_roots(L, I)
            q = (bethe_momentum(L, I) - P0) % (2 * np.pi)
            out.append((min(q, 2 * np.pi - q), bethe_energy(lam) - E0, res))
    return np.array(out)


# ------------------------------------------------------------------------------------------------------ level spacings
def spacing_ratio(levels, keep=0.8):
    e = np.sort(levels)
    n = len(e)
    e = e[int(n * (1 - keep) / 2):int(n * (1 + keep) / 2)]
    s = np.diff(e)
    r = np.minimum(s[1:], s[:-1]) / np.maximum(s[1:], s[:-1])
    return r[np.isfinite(r)]


def xxz_block_levels(L, n_up, m, delta, j2):
    bonds = [(1, delta, 1.0, 0.0)] + ([(2, j2 * delta, j2, 0.0)] if j2 else [])
    return np.linalg.eigvalsh(momentum_block(L, n_up, m, bonds))


def main():
    checks, controls = {}, {}
    # 1. ED against the Bethe ground state.
    worst = 0.0
    print(' L   E0 (ED)            E0 (Bethe)          difference')
    for L in range(8, 21, 2):
        e_ed = ground_energy_ed(L)
        e_ba, res, _ = ground_state(L)
        worst = max(worst, abs(e_ed - e_ba))
        print(f'{L:2d}  {e_ed:.12f}  {e_ba:.12f}   {abs(e_ed - e_ba):.1e}  (Bethe residual {res:.0e})')
    checks['ED and Bethe ground-state energies agree for L = 8..20 (1e-10)'] = worst < 1e-10

    # 2. Thermodynamic limit.
    print(' L      E0/L                 L^2 (E0/L + ln 2)')
    sizes, scaled = [], []
    for p in range(4, 13):
        L = 2 ** p
        e_ba, res, _ = ground_state(L)
        sizes.append(L); scaled.append(L ** 2 * (e_ba / L + LN2))
        print(f'{L:5d}  {e_ba / L:.12f}     {scaled[-1]:.6f}   (residual {res:.0e})')
    e_large = ground_state(4096)[0] / 4096
    checks['E0/L at L = 4096 is within 1e-7 of -ln 2'] = abs(e_large + LN2) < 1e-7
    checks['L^2 (E0/L + ln 2) is negative and increases monotonically toward -pi^2/12'] = (
        all(scaled[i] < scaled[i + 1] for i in range(len(scaled) - 1)) and scaled[-1] < -np.pi ** 2 / 12 + 0.05
        and scaled[-1] < 0)
    print(f'-pi^2/12 = {-np.pi ** 2 / 12:.6f}')

    # 3. Two-hole Bethe states against momentum-resolved ED at L = 16.
    L = 16
    E0 = ground_energy_ed(L)
    _, _, P0 = ground_state(L)
    holes = two_hole_states(L)
    worst, compared, without = 0.0, 0, []
    print(' m   q/pi    lowest S^z=1 (ED)   lowest two-hole (Bethe)')
    for m in range(L):
        Hk = momentum_block(L, L // 2 + 1, m, [(1, 1.0, 1.0, -0.25)])
        e_ed = float(np.linalg.eigvalsh(Hk)[0]) - E0
        q = (2 * np.pi * m / L - P0) % (2 * np.pi)
        q = min(q, 2 * np.pi - q)
        match = holes[np.abs(holes[:, 0] - q) < 1e-9, 1]
        if len(match) == 0:
            # With M = L/2 - 1 roots the holes h1 != h2 give q = pi (h1 + h2) / (L/2) shifted by pi, so q = 0 needs
            # h1 + h2 = +-L/2, which two distinct slots in |h| <= L/4 cannot reach.
            without.append((q, e_ed))
            print(f'{m:2d}  {q / np.pi:.4f}   {e_ed:.10f}       (no real two-hole state)')
            continue
        worst = max(worst, abs(e_ed - match.min()))
        compared += 1
        print(f'{m:2d}  {q / np.pi:.4f}   {e_ed:.10f}       {match.min():.10f}')
    checks['L = 16: in every sector with a real two-hole state the lowest S^z = 1 level is that state (1e-9)'] = (
        worst < 1e-9 and compared == L - 1)
    checks['the only momentum without a real two-hole state is q = 0, and its lowest S^z = 1 level lies higher'] = (
        len(without) == 1 and abs(without[0][0]) < 1e-12 and without[0][1] > holes[:, 1].min())
    checks['all two-hole Bethe states converge (residual below 1e-9)'] = holes[:, 2].max() < 1e-9

    # 4. des Cloizeaux-Pearson edge and the two-spinon continuum.
    print(' L    max |lowest - (pi/2) sin q|   L x it   min(E - (pi/2) sin q)   max(E - pi sin(q/2))   L x it')
    edge_errors, overshoots, lower_ok = [], [], True
    for L in (32, 64, 128):
        h = two_hole_states(L)
        qs = np.unique(np.round(h[:, 0], 12))
        lowest = np.array([h[np.abs(h[:, 0] - q) < 1e-9, 1].min() for q in qs])
        err = np.max(np.abs(lowest - 0.5 * np.pi * np.sin(qs)))
        below = np.min(h[:, 1] - 0.5 * np.pi * np.sin(h[:, 0]))
        over = np.max(h[:, 1] - np.pi * np.sin(h[:, 0] / 2))
        lower_ok = lower_ok and below > 0
        edge_errors.append(err); overshoots.append(over)
        print(f'{L:3d}   {err:.5f}                      {L * err:.3f}    {below:+.5f}               {over:+.5f}              {L * over:.3f}')
    ratios = [edge_errors[i + 1] / edge_errors[i] for i in range(2)]
    checks['the deviation from (pi/2) sin q falls like 1/L (ratio 0.5 +- 0.05 per doubling)'] = all(
        abs(r - 0.5) < 0.05 for r in ratios)
    checks['every two-hole energy lies above (pi/2) sin q'] = lower_ok
    checks['the largest excess over pi sin(q/2) is O(1/L): L times it stays between 0.09 and 0.13'] = all(
        0.09 < L * o < 0.13 for L, o in zip((32, 64, 128), overshoots))

    # Control: level statistics in one symmetry-resolved block (S^z = 1, k = 2 pi 4/18).
    r_int = spacing_ratio(xxz_block_levels(18, 10, 4, 0.6, 0.0))
    r_non = spacing_ratio(xxz_block_levels(18, 10, 4, 0.6, 0.5))
    print(f'<r>: integrable XXZ {r_int.mean():.4f} ({len(r_int)} ratios); with J2 = 0.5 {r_non.mean():.4f}; '
          f'Poisson {2 * LN2 - 1:.4f}, GOE 0.5307')
    controls['integrable XXZ block has Poisson-like <r> (within 0.03 of 0.386)'] = abs(r_int.mean() - (2 * LN2 - 1)) < 0.03
    controls['a next-nearest coupling makes <r> Wigner-Dyson-like (within 0.02 of 0.5307)'] = abs(r_non.mean() - 0.5307) < 0.02

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