"""Leading polynomial Bethe vector of the singular pair on six periodic XXX sites.
Run: python3 six_site_singular_pair.py  (NumPy). Coefficients through epsilon^6
are small Gaussian integers and all asserted identities here are exact.
"""
import numpy as np

L = 6


def apply_b(ket, branch, correction=0j):
    """Apply an upper-right monodromy block to a truncated vector polynomial."""
    work = np.zeros((L+1, 2, *([2]*L)), dtype=complex)
    work[:,1] = ket
    for site in range(L):
        # L(u)=(u-i/2)I+iP; site zero is distinct from the auxiliary spin.
        new = 1j * np.swapaxes(work,1,2+site)
        if branch == 'minus':
            new = new-1j*work
        new[1:] += work[:-1]
        if branch == 'plus':
            new[L] += correction*work[0]
        work = new
    return work[:,0]


def main():
    vacuum=np.zeros((L+1,*([2]*L)),complex)
    vacuum[(0,)*(L+1)]=1
    second=apply_b(vacuum,'minus')
    target=np.zeros([2]*L)
    for j in range(L):
        bits=[int(k in {j,(j+1)%L}) for k in range(L)]
        target[tuple(bits)]=(-1)**j
    for c in (-2j, 0j):
        coeff=apply_b(second,'plus',c)
        assert not np.any(coeff[:L])
        v=coeff[L]
        hv=sum((v-np.swapaxes(v,j,(j+1)%L))/2 for j in range(L))
        print(f'correction={c}: leading norm {np.linalg.norm(v):.8f}, '
              f'H/J-1 relative residual {np.linalg.norm(hv-v)/np.linalg.norm(v):.8f}')
        if c:
            scale=np.vdot(target,v)/np.vdot(target,target)
            assert np.array_equal(v,scale*target) and scale != 0
            assert np.array_equal(hv,v)
            print('coefficient of the alternating adjacent-pair vector:',scale)
        else:
            assert np.any(hv-v)

if __name__=='__main__':
    main()
