"""Two repulsive bosons on a ring. Run with Python 3 and mpmath (tested with 1.3.0).

g=cL and q=kL are dimensionless. D=det(G)/L^2 for the logarithmic
Bethe Jacobian. Compare its signed determinant with the full-square
coordinate norm for the unnormalized cosine wave and resolve 2-D.
"""

from mpmath import mp


def check_norm(coupling, digits):
    with mp.workdps(digits):
        g = mp.mpf(coupling)
        scale = mp.sqrt(g)
        s = mp.findroot(lambda s: 2*s*mp.tan(scale*s/2)/scale - 1, (0.8, 1.1))
        q = scale*s
        kernel = 2*g / (g*g + 4*q*q)
        gaudin = mp.matrix([[1 + kernel, -kernel], [-kernel, 1 + kernel]])
        determinant = mp.det(gaudin)
        coordinate = 2*mp.quad(lambda t: mp.cos(q*(t - mp.mpf("0.5")))**2, [0, 1])
        deficit = 2*mp.quad(lambda t: mp.sin(q*(t - mp.mpf("0.5")))**2, [0, 1])
        assert determinant > 0 and deficit > 0
        tolerance = mp.mpf(10)**(5-digits)
        assert abs(determinant - coordinate) < tolerance
        assert abs(determinant + deficit - 2) < tolerance
        assert abs(mp.log(determinant) - mp.log1p(2*kernel)) < tolerance
        print("digits, cL, kL, D, 2-D, (2-D)/(cL):", digits, coupling,
              *(mp.nstr(v, 15) for v in (q, determinant, deficit, deficit/g)))
        return deficit


if __name__ == "__main__":
    for coupling in ("1", "1e-8", "1e-16", "1e-24", "1e-32"):
        coarse = check_norm(coupling, 60)
        fine = check_norm(coupling, 80)
        with mp.workdps(85):
            assert abs(coarse/fine - 1) < mp.mpf("1e-45")
