"""Reconstruct and measure a one-gap KdV wave. Requires Python and mpmath.

Here m is the elliptic parameter, the theta argument has real period pi,
and the Schrödinger potential is the negative of the KdV field.
"""
import mpmath as mp


def theta_field(phase, m, kappa=1):
    period = mp.ellipk(m)
    nome = mp.exp(-mp.pi*mp.ellipk(1-m)/period)
    scale = mp.pi/(2*period)
    angle = scale*phase
    theta = mp.jtheta(4, angle, nome)
    first = mp.jtheta(4, angle, nome, 1)/theta
    second = mp.jtheta(4, angle, nome, 2)/theta
    return 2*kappa**2 * (mp.ellipe(m)/period + scale**2*(second-first**2))


def trace_and_sheet():
    m = mp.mpf(".5")
    # Sample away from endpoints so that the Dirichlet sheet is determined.
    for v in [mp.mpf(".1"), mp.mpf(".7"), mp.mpf("2.15")]:
        sn, cn, dn = [mp.ellipfun(f, v, m) for f in ("sn", "cn", "dn")]
        u = 2*dn**2
        up = -4*m*sn*cn*dn
        lam = (6-2*u)/4
        cubic = 16*(lam-mp.mpf(".5"))*(lam-1)*(lam-mp.mpf("1.5"))
        assert abs(theta_field(v, m)-u) < mp.mpf("1e-38")
        assert abs(cubic-up**2) < mp.mpf("1e-38")
    height, trough, period = mp.mpf("2.75"), mp.mpf("1.75"), mp.mpf("3.70814935")
    modulus_parameter = mp.findroot(lambda t: 8*t*mp.ellipk(t)**2 -
                                    (height-trough)*period**2, (.4, .6))
    scale = 2*mp.ellipk(modulus_parameter)/period
    background = height-2*scale**2
    print("from measured heights and period: m, kappa, background",
          *(mp.nstr(x, 10) for x in (modulus_parameter, scale, background)))


def real_ovals_and_degenerations():
    m = mp.mpf(".5")
    for distance in map(mp.mpf, (".1", ".05", ".025")):
        field = theta_field(distance + 1j*mp.ellipk(1-m), m)
        remainder = field + 2/distance**2
        assert abs(mp.im(remainder)) < mp.mpf("1e-35")
        assert abs(mp.re(remainder)-1) < distance**2/8
        print("distance from pole and regularized field", distance, mp.nstr(mp.re(remainder), 12))
    for parameter in (".5", ".99", ".9999"):
        m = mp.mpf(parameter)
        half = mp.ellipk(m)
        integral = 2*mp.quad(lambda x: 2*mp.ellipfun("dn", x, m)**2, [0, half])
        assert abs(integral-4*mp.ellipe(m)) < mp.mpf("1e-36")
        print("parameter, cell mass, mean", m, mp.nstr(integral, 11), mp.nstr(integral/(2*half), 11))


def convention_checks():
    q = mp.exp(-mp.pi)
    old, changed = mp.jtheta(3, 0, q), mp.jtheta(3, 0, -q)
    assert abs(changed-mp.jtheta(4, 0, q)) < mp.mpf("1e-40")
    print("theta constants under tau -> tau+1", mp.nstr(old, 11), mp.nstr(changed, 11))
    delta = mp.mpf(".01")
    leading = mp.log(4/mp.sqrt(delta))
    corrected = leading + delta*(leading-1)/4
    integral = mp.quad(lambda phi: 1/mp.sqrt(1-(1-delta)*mp.sin(phi)**2), [0, mp.pi/2])
    print("K: leading, corrected, direct quadrature", *(mp.nstr(x, 12) for x in (leading, corrected, integral)))
    assert 0 < integral-corrected < mp.mpf(".000036")


if __name__ == "__main__":
    mp.mp.dps = 48
    trace_and_sheet()
    real_ovals_and_degenerations()
    convention_checks()
