"""Checks for the Library article "The spectral problem of planar N = 4 super Yang-Mills theory".

Planar SU(2) sector: single traces of L letters Z and X with M letters X, coupling g = sqrt(lambda)/(4 pi).
Through three loops the dilatation operator is D = L + 2g^2 H1 + 4g^4 H2 + 8g^6 H3 + O(g^8), with
    H1 = sum_k (1 - P_{k,k+1}),
    H2 = sum_k (-2 + 3 P_{k,k+1} - [P_{k,k+1} P_{k+1,k+2} + P_{k+1,k+2} P_{k,k+1}] / 2),
    H3 = sum_k (15/2 - 13 P_{k,k+1} + 3 [P_{k,k+1} P_{k+1,k+2} + P_{k+1,k+2} P_{k,k+1}] + P_{k,k+1} P_{k+2,k+3} / 2
                - [P_{k,k+1} P_{k+1,k+2} P_{k+2,k+3} + P_{k+2,k+3} P_{k+1,k+2} P_{k,k+1}] / 2),
acting on cyclic (zero-momentum) highest-weight states. Rayleigh-Schroedinger perturbation theory in g^2, with
degenerate levels treated exactly, gives gamma = 2g^2 E1 + 4g^4 E2 + 8g^6 E3.
The asymptotic Bethe equations of the same sector are
    (x_k^+ / x_k^-)^L = prod_{j != k} (u_k - u_j + i)/(u_k - u_j - i) sigma(u_k, u_j)^2,   prod_k x_k^+/x_k^- = 1,
    gamma = sum_k 2ig (1/x_k^+ - 1/x_k^-),   x + 1/x = u/g on the sheet |x| > 1,   x^(+-) = x(u +- i/2).
Checks:
  1. Konishi (L = 4, M = 2) fixes the normalization: gamma = 12g^2 - 48g^4 + 336g^6 from the operators.
  2. For every two-magnon state with 4 <= L <= 12 the operators and the Bethe equations agree through three loops.
  3. Every degenerate pair of opposite parity at one loop (L <= 12) stays degenerate at two and three loops. On spin 1/2,
     P12 P23 + P23 P12 = P12 + P23 + P13 - 1, and sum_k P_{k,k+2} keeps the pairs at first order, so two loops do not test
     the coefficients of H2; three loops do test those of H3.
  4. The Bethe equations give the asymptotic Konishi coefficient -2820 at four loops, and -2820 - 288 zeta(3) with the
     leading dressing phase 4 zeta(3) g^6 [q2(u_j) q3(u_k) - q3(u_j) q2(u_k)].
  5. At fixed lambda' = lambda/J^2 = 1 the two-magnon energy tends to the BMN value 2(sqrt(1 + lambda') - 1) like 1/J.
Controls: the one-loop momentum equation with the all-loop dispersion gives -36 instead of -48 for Konishi; a
four-site term in H1 removes the one-loop parity pairs; a changed coefficient of P_{k,k+1}P_{k+2,k+3} in H3 splits them at
three loops; a next-nearest exchange in H1, which is not integrable, still leaves the L = 7 pair degenerate.
Run with Python 3, NumPy and mpmath:  python3 planar_n4_spectrum_check.py   (a few seconds)
"""
from itertools import combinations
import mpmath as mp
import numpy as np

H1 = [(1.0, ()), (-1.0, (0,))]
H2 = [(-2.0, ()), (3.0, (0,)), (-0.5, (0, 1)), (-0.5, (1, 0))]
H3 = [(7.5, ()), (-13.0, (0,)), (3.0, (0, 1)), (3.0, (1, 0)), (0.5, (0, 2)), (-0.5, (0, 1, 2)), (-0.5, (2, 1, 0))]


# --------------------------------------------------------------------------------------- planar spin-chain sector
def words(L, M):
    return [sum(1 << i for i in c) for c in combinations(range(L), M)]


def swap(w, i, j):
    return w if ((w >> i) & 1) == ((w >> j) & 1) else w ^ ((1 << i) | (1 << j))


def operator(L, M, terms):
    """Matrix of sum_k sum_terms c * P_{k+b1,k+b1+1} ... P_{k+bn,k+bn+1} on words with M letters X."""
    basis = words(L, M)
    index = {w: n for n, w in enumerate(basis)}
    A = np.zeros((len(basis), len(basis)))
    for w in basis:
        for k in range(L):
            for c, bonds in terms:
                v = w
                for b in reversed(bonds):            # the rightmost permutation acts first
                    v = swap(v, (k + b) % L, (k + b + 1) % L)
                A[index[v], index[w]] += c
    return A


def cyclic_highest_weight(L, M):
    """Orthonormal basis of translation-invariant states annihilated by the SU(2) raising operator."""
    basis = words(L, M)
    index = {w: n for n, w in enumerate(basis)}
    mask = (1 << L) - 1
    seen, cols = set(), []
    for w in basis:
        if w in seen:
            continue
        orbit, v = [], w
        while v not in orbit:
            orbit.append(v)
            v = ((v << 1) | (v >> (L - 1))) & mask
        seen.update(orbit)
        col = np.zeros(len(basis))
        col[[index[v] for v in orbit]] = 1.0
        cols.append(col / np.linalg.norm(col))
    Z = np.array(cols).T
    if M == 0:
        return Z
    lower = {w: n for n, w in enumerate(words(L, M - 1))}
    raise_ = np.zeros((len(lower), len(basis)))
    for w in basis:
        for i in range(L):
            if (w >> i) & 1:
                raise_[lower[w ^ (1 << i)], index[w]] += 1.0
    _, sv, vt = np.linalg.svd(raise_ @ Z)
    return Z @ vt[int(np.sum(sv > 1e-10)):].T


def parity(L, M):
    basis = words(L, M)
    index = {w: n for n, w in enumerate(basis)}
    R = np.zeros((len(basis), len(basis)))
    for w in basis:
        R[index[sum(1 << (L - 1 - i) for i in range(L) if (w >> i) & 1)], index[w]] = 1.0
    return R


def clusters(values, tol=1e-8):
    order = np.argsort(values)
    groups, current = [], [order[0]]
    for a, b in zip(order[:-1], order[1:]):
        if values[b] - values[a] < tol:
            current.append(b)
        else:
            groups.append(current)
            current = [b]
    groups.append(current)
    return groups


def perturbative_levels(L, M, h1_terms=H1, h2_terms=H2, h3_terms=H3):
    """Levels (E1, E2, E3, parity) of the cyclic highest-weight sector, degenerate levels treated exactly."""
    W = cyclic_highest_weight(L, M)
    if W.shape[1] == 0:
        return []
    h1, h2, h3 = (W.T @ operator(L, M, t) @ W for t in (h1_terms, h2_terms, h3_terms))
    par = W.T @ parity(L, M) @ W
    e1, V = np.linalg.eigh(h1)
    levels = []
    for group in clusters(e1):
        Vg = V[:, group]
        outside = [b for b in range(len(e1)) if b not in group]
        R = sum(np.outer(V[:, b], V[:, b]) / (e1[group[0]] - e1[b]) for b in outside) if outside else 0 * h1
        # parity commutes with every H: diagonalize it first, then each order within each parity block
        pe, pv = np.linalg.eigh(Vg.T @ par @ Vg)
        for sign in (1.0, -1.0):
            U = Vg @ pv[:, np.abs(pe - sign) < 1e-8]
            if U.shape[1] == 0:
                continue
            e2, X = np.linalg.eigh(U.T @ h2 @ U)
            U = U @ X
            for sub in clusters(e2):
                Us = U[:, sub]
                e3 = np.linalg.eigvalsh(Us.T @ (h3 + h2 @ R @ h2) @ Us)
                levels += [(e1[group[0]], e2[sub[0]], x, sign) for x in e3]
    return levels


def parity_pairs(levels, order):
    """Number of degenerate opposite-parity pairs at one loop and the largest splitting of their higher orders."""
    one = np.array([lv[0] for lv in levels])
    pairs, worst = 0, 0.0
    for group in clusters(one):
        plus = sorted((levels[i][1], levels[i][2]) for i in group if levels[i][3] > 0)
        minus = sorted((levels[i][1], levels[i][2]) for i in group if levels[i][3] < 0)
        n = min(len(plus), len(minus))
        pairs += n
        for a, b in zip(plus[:n], minus[:n]):
            worst = max(worst, abs(a[order - 2] - b[order - 2]) if order > 1 else 0.0)
    return pairs, worst


# ----------------------------------------------------------------------------------------- asymptotic Bethe ansatz
def xf(v, g):
    """x(v) with x + 1/x = v/g on the physical sheet |x| > 1; the cut is [-2g, 2g]."""
    return (v + mp.sqrt(v - 2 * g) * mp.sqrt(v + 2 * g)) / (2 * g)


def two_magnon(L, n, g, dressing=False, naive=False, u0=None):
    """Symmetric roots (u, -u): returns gamma and u."""
    half = mp.mpf(1) / 2
    q2 = lambda v: 1 / (v ** 2 + half ** 2)
    q3 = lambda v: v / (v ** 2 + half ** 2) ** 2

    def momentum(u):
        if naive:                      # control: one-loop momentum relation, e^{ip} = (u + i/2)/(u - i/2)
            return mp.im(mp.log((u + 0.5j) / (u - 0.5j)))
        return mp.im(mp.log(xf(u + 0.5j, g) / xf(u - 0.5j, g)))

    def equation(u):
        phase = mp.im(mp.log((2 * u + 1j) / (2 * u - 1j)))
        if dressing:
            phase += 2 * 4 * mp.zeta(3) * g ** 6 * (q2(u) * q3(-u) - q3(u) * q2(-u))
        return L * momentum(u) - phase - 2 * mp.pi * n

    u = mp.findroot(equation, u0 if u0 is not None else mp.cot(mp.pi * n / (L - 1)) / 2)
    if naive:
        p = momentum(u)
        return 2 * (mp.sqrt(1 + 16 * g ** 2 * mp.sin(p / 2) ** 2) - 1), u
    xp, xm = xf(u + 0.5j, g), xf(u - 0.5j, g)
    return 2 * mp.re(2j * g * (1 / xp - 1 / xm)), u


def weak_series(L, n, orders=4, **kw):
    """Coefficients of g^2, g^4, ... from exact solutions at g^2 = k 10^-6, k = 1..orders+6, by polynomial fit."""
    hs = [mp.mpf(k) / 10 ** 6 for k in range(1, orders + 7)]
    values = [two_magnon(L, n, mp.sqrt(h), **kw)[0] for h in hs]
    A = mp.matrix([[h ** k for k in range(1, len(hs) + 1)] for h in hs])
    c = mp.lu_solve(A, mp.matrix(values))
    return [c[i] for i in range(orders)]


def bmn_energy(J, n, lam_prime, steps=40):
    """Two-magnon gamma at lambda = lambda' J^2, followed from weak coupling; also min |x^(+-)|."""
    L = J + 2
    g_final = mp.sqrt(lam_prime) * J / (4 * mp.pi)
    u = mp.cot(mp.pi * n / (L - 1)) / 2
    for s in range(1, steps + 1):
        gamma, u = two_magnon(L, n, g_final * s / steps, u0=u)
    smallest = min(abs(xf(u + 0.5j, g_final)), abs(xf(u - 0.5j, g_final)))
    return gamma, smallest


def main():
    mp.mp.dps = 60
    checks, controls = {}, {}

    # 1. Konishi from the operators.
    kon = perturbative_levels(4, 2)
    assert len(kon) == 1
    e1, e2, e3, _ = kon[0]
    print(f'Konishi from the operators: gamma = {2 * e1:.10f} g^2 {4 * e2:+.10f} g^4 {8 * e3:+.10f} g^6')
    checks['Konishi from H1, H2, H3: 12 g^2 - 48 g^4 + 336 g^6'] = (
        abs(2 * e1 - 12) < 1e-10 and abs(4 * e2 + 48) < 1e-9 and abs(8 * e3 - 336) < 1e-8)

    # 2. Two-magnon states: operators against the Bethe equations through three loops.
    worst, count = 0.0, 0
    print(' L  n   gamma_1 (Bethe)      gamma_2 (Bethe)      gamma_3 (Bethe)       largest difference')
    for L in range(4, 13):
        levels = perturbative_levels(L, 2)
        for n in range(1, (L - 2) // 2 + 1):
            c = weak_series(L, n, orders=3)
            match = [lv for lv in levels if abs(2 * lv[0] - float(c[0])) < 1e-8]
            assert len(match) == 1
            e1, e2, e3, _ = match[0]
            diff = max(abs(2 * e1 - float(c[0])), abs(4 * e2 - float(c[1])), abs(8 * e3 - float(c[2])))
            worst, count = max(worst, diff), count + 1
            print(f'{L:2d} {n:2d}  {float(c[0]):18.12f} {float(c[1]):20.12f} {float(c[2]):20.12f}   {diff:.1e}')
    checks[f'all {count} two-magnon states with 4 <= L <= 12: operators equal the Bethe equations through g^6 (1e-8)'] = worst < 1e-8

    # 3. Parity pairs through three loops, and the controls.
    full = lambda i, j: np.array([[1.0 if swap(a, i, j) == b else 0.0 for a in range(8)] for b in range(8)])
    P12, P23, P13 = full(0, 1), full(1, 2), full(0, 2)
    checks['spin 1/2: P12 P23 + P23 P12 = P12 + P23 + P13 - 1 on three sites'] = (
        np.abs(P12 @ P23 + P23 @ P12 - P12 - P23 - P13 + np.eye(8)).max() == 0)
    bad_h3 = [t if t[1] != (0, 2) else (0.6, (0, 2)) for t in H3]      # coefficient of P_{k,k+1}P_{k+2,k+3}: 1/2 -> 0.6
    total, split2, split3, bad_split, nnn_split = 0, 0.0, 0.0, 0.0, 0.0
    print(' L  parity pairs at one loop')
    for L in range(4, 13):
        pairs_L = 0
        for M in range(2, L // 2 + 1):
            levels = perturbative_levels(L, M)
            if not levels:
                continue
            p2, s2 = parity_pairs(levels, 2)
            _, s3 = parity_pairs(levels, 3)
            pairs_L += p2
            split2, split3 = max(split2, s2), max(split3, s3)
            if p2:
                bad_split = max(bad_split, parity_pairs(perturbative_levels(L, M, h3_terms=bad_h3), 3)[1])
                # first order in a next-nearest exchange sum_k P_{k,k+2} = sum_k P_{k,k+1}P_{k+1,k+2}P_{k,k+1}
                nnn_split = max(nnn_split, parity_pairs(perturbative_levels(L, M, h2_terms=[(1.0, (0, 1, 0))]), 2)[1])
        total += pairs_L
        print(f'{L:2d}  {pairs_L:4d}')
    print(f'largest splittings of the {total} pairs: two loops {split2:.1e}, three loops {split3:.1e}; '
          f'first order in sum P_(k,k+2): {nnn_split:.1e}; three loops with coefficient 0.6: {bad_split:.3f}')
    checks[f'all {total} one-loop parity pairs with L <= 12 stay degenerate at two and three loops (1e-8)'] = (
        total > 0 and split2 < 1e-8 and split3 < 1e-8)
    checks['a next-nearest exchange sum P_(k,k+2) leaves every pair degenerate at first order (1e-8)'] = nnn_split < 1e-8
    controls['changing the coefficient of P_(k,k+1)P_(k+2,k+3) in H3 from 1/2 to 0.6 splits the pairs at three loops'] = (
        bad_split > 1e-3)

    def pairs_of(terms_h1):
        count, where = 0, []
        for L in range(4, 13):
            for M in range(2, L // 2 + 1):
                W = cyclic_highest_weight(L, M)
                if W.shape[1] == 0:
                    continue
                h, par = W.T @ operator(L, M, terms_h1) @ W, W.T @ parity(L, M) @ W
                e, V = np.linalg.eigh(h)
                for group in clusters(e):
                    pe = np.linalg.eigvalsh(V[:, group].T @ par @ V[:, group])
                    n = int(min(np.sum(pe > 0), np.sum(pe < 0)))
                    count += n
                    where += [(L, M)] * n
        return count, where
    n_quartic, _ = pairs_of(H1 + [(0.3, (0, 2))])
    n_nnn, where = pairs_of(H1 + [(0.3, ()), (-0.3, (0, 1, 0))])
    print(f'one-loop deformations: 0.3 sum P_(k,k+1)P_(k+2,k+3) leaves {n_quartic} pairs; '
          f'0.3 sum (1 - P_(k,k+2)) leaves {n_nnn} at (L, M) = {where}')
    controls['adding 0.3 sum P_(k,k+1)P_(k+2,k+3) to H1 leaves no parity pair with L <= 12'] = n_quartic == 0
    controls['adding 0.3 sum (1 - P_(k,k+2)) to H1 keeps only the shortest pair, at L = 7'] = where == [(7, 3)]

    # 4. Konishi from the Bethe equations through four loops, with and without the leading dressing phase.
    c = weak_series(4, 1, orders=4)
    cd = weak_series(4, 1, orders=4, dressing=True)
    full = -2496 + 576 * mp.zeta(3) - 1440 * mp.zeta(5)
    print('Konishi from the Bethe equations:', ', '.join(mp.nstr(x, 15) for x in c),
          '| with dressing, g^8:', mp.nstr(cd[3], 15), '| plus wrapping 324 + 864 zeta(3) - 1440 zeta(5):',
          mp.nstr(cd[3] + 324 + 864 * mp.zeta(3) - 1440 * mp.zeta(5), 15), '=', mp.nstr(full, 15))
    checks['Bethe equations: Konishi 12, -48, 336, -2820 (1e-20)'] = max(
        abs(c[0] - 12), abs(c[1] + 48), abs(c[2] - 336), abs(c[3] + 2820)) < 1e-20
    checks['leading dressing phase adds -288 zeta(3) at g^8 and leaves g^2..g^6 unchanged (1e-20)'] = (
        abs(cd[3] - c[3] + 288 * mp.zeta(3)) < 1e-20 and max(abs(cd[i] - c[i]) for i in range(3)) < 1e-20)
    naive = weak_series(4, 1, orders=2, naive=True)
    print(f'control: one-loop momentum relation with the all-loop dispersion gives g^4 coefficient {mp.nstr(naive[1], 12)}')
    controls['the one-loop momentum relation with the all-loop dispersion gives -36, not -48, at g^4'] = abs(naive[1] + 36) < 1e-20

    # 5. BMN limit at lambda' = 1.
    mp.mp.dps = 30
    target = 2 * (mp.sqrt(2) - 1)
    devs, sheet = [], []
    for J in (25, 50, 100, 200):
        gamma, smallest = bmn_energy(J, 1, 1)
        devs.append(gamma - target)
        sheet.append(smallest)
        print(f'BMN, J = {J:3d}: gamma = {mp.nstr(gamma, 12)}, minus 2(sqrt 2 - 1): {mp.nstr(gamma - target, 6)}, '
              f'J times that: {mp.nstr(J * (gamma - target), 8)}, min |x| = {mp.nstr(smallest, 5)}')
    ratios = [devs[i] / devs[i + 1] for i in range(3)]
    checks['two magnons at lambda\' = 1 tend to 2(sqrt(1 + lambda\') - 1) like 1/J (ratio 1.9-2.05 per doubling), |x| > 1'] = (
        all(1.9 < r < 2.05 for r in ratios) and min(sheet) > 1)

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