"""Differentiate the full isotropic Ising free energy with mpmath."""
import mpmath as mp


def specific_heat(delta):
    critical = mp.asinh(1)/2
    K = critical+delta
    def density(x):
        dual = -mp.log(mp.tanh(x))/2
        gap = mp.sinh(dual-x)**2
        def integrand(q):
            return mp.asinh(mp.sqrt(gap+mp.sin(q/2)**2))
        points = [0, abs(delta), mp.mpf(".01"), mp.mpf(".3"), mp.pi]
        return mp.log(2*mp.sinh(2*x))/2 + mp.quad(integrand,points)/mp.pi
    return K*K*mp.diff(density,K,2)


def critical_cylinder_heat(width):
    critical = mp.asinh(1) / 2
    sines = [mp.sin(mp.pi * (j + mp.mpf(".5")) / width) for j in range(width)]
    def cylinder_density(coupling):
        delta = -mp.log(mp.tanh(coupling)) / 2 - coupling
        modes = (mp.asinh(mp.sqrt(mp.sinh(delta)**2 + s*s)) for s in sines)
        return mp.log(2*mp.sinh(2*coupling))/2 + mp.fsum(modes)/width

    direct = critical**2 * mp.diff(cylinder_density, critical, 2)
    endpoint_sum = mp.fsum(1 / (s * mp.sqrt(1 + s*s)) for s in sines)
    result = critical**2 * (-2 + 4 * endpoint_sum / width)
    assert mp.almosteq(direct, result)
    return result


if __name__ == "__main__":
    for offset in (".001",".0001",".00001"):
        with mp.workdps(32):
            low = specific_heat(mp.mpf(offset))
        with mp.workdps(45):
            high = specific_heat(mp.mpf(offset))
            assert abs(high-low)<mp.mpf("1e-22")
            print(offset,mp.nstr(high,16))
    with mp.workdps(40):
        for width in (16, 32, 64):
            print("Critical cylinder width and heat per spin:", width,
                  mp.nstr(critical_cylinder_heat(width), 16))
