"""Twisted four-site XXX roots. Run with Python 3 and mpmath (tested with 1.3.0).

The local bond is (I-P)/2 in units of J. The two-root Bethe equations use
the seam factor exp(-i beta), as in Nepomechie and Wang, arXiv:1409.7382,
Eq. (9). The one-magnon comparison uses phi=-beta.
"""

from itertools import combinations

from mpmath import mp


def bond_block(beta, down_spins):
    """Build a four-site block with the rotated seam S^-_5=exp(-i beta) S^-_1."""
    states = list(combinations(range(4), down_spins))
    block = mp.matrix(len(states))
    for col, state in enumerate(states):
        for left in range(4):
            right = (left + 1) % 4
            if (left in state) == (right in state):
                continue
            target = tuple(sorted(set(state) ^ {left, right}))
            phase = 1
            if right == 0:
                phase = mp.exp(mp.j * beta * (-1 if left in state else 1))
            block[col, col] += mp.mpf("0.5")
            block[states.index(target), col] -= phase / 2
    assert mp.norm(block - block.H) == 0
    return block


def singular_pair(beta):
    def equations(center, splitting):
        x = beta * center
        y = beta**4 * splitting
        phase = center**2 + beta**2 * splitting * (1 + y)
        phase -= center * mp.tan(beta / 4) / beta
        modulus = splitting * (x*x + (1 + y)**2)**2
        modulus -= (1 + y) * (center**2 + beta**6 * splitting**2)**2
        return phase, modulus

    center, splitting = mp.findroot(equations, (mp.mpf(1)/4, mp.mpf(1)/256))
    x, y = beta * center, beta**4 * splitting
    upper = x + mp.j * (mp.mpf("0.5") + y)
    lower = mp.conj(upper)
    errors = []
    for u, v in ((upper, lower), (lower, upper)):
        a = (u + mp.j/2)**4 * (u - v - mp.j)
        b = mp.exp(-mp.j*beta) * (u - mp.j/2)**4 * (u - v + mp.j)
        errors.append(abs(a-b) / (abs(a)+abs(b)))
    energy = sum(1 / (2*(u*u + mp.mpf("0.25"))) for u in (upper, lower))
    spectrum = mp.eighe(bond_block(beta, 2), eigvals_only=True)
    energy_error = min(abs(eigenvalue - energy) for eigenvalue in spectrum)
    # Reversing the seam leaves the spectrum invariant. Test its sign against
    # a named plane wave, for which the Bethe and coordinate phases are opposite.
    p = (2*mp.pi - beta)/4
    wave = mp.matrix([mp.exp(-mp.j*p*site)/2 for site in range(4)])
    assert mp.norm(bond_block(beta, 1)*wave - (1 - mp.cos(p))*wave) < mp.mpf("1e-60")
    assert max(errors) < mp.mpf("1e-60") and energy_error < mp.mpf("1e-60")
    print("beta, 2y/x^4, relative Bethe error, spectral distance in J:",
          *(mp.nstr(v, 12) for v in (beta, 2*y/x**4, max(errors), energy_error)))


def one_magnon(digits, branch):
    with mp.workdps(digits):
        phi = mp.mpf("1e-8")
        rhs = mp.exp(mp.j * phi)
        z = mp.mpc(1) if branch == 0 else mp.j
        for _ in range(6):
            z -= (z**4 - rhs) / (4*z**3)
        u = mp.j * (z+1) / (2*(z-1))
        residual = abs(z**4 - rhs)
    with mp.workdps(85):
        angle = (2*mp.pi*branch + mp.mpf("1e-8")) / 8
        error = abs(u - mp.cot(angle)/2)
        print("digits, branch, rapidity error, equation residual:",
              digits, branch, mp.nstr(error, 7), mp.nstr(residual, 7))


if __name__ == "__main__":
    with mp.workdps(70):
        for angle in ("0.1", "0.01"):
            singular_pair(mp.mpf(angle))
    for precision in (16, 32):
        for branch_index in (0, 1):
            one_magnon(precision, branch_index)
