"""Measure a KdV pulse, its threshold state and a periodic cell.

Run with Python 3, SciPy and SymPy. Elliptic functions in SciPy use the
parameter m. All examples use the normalized equation u_t+6uu_x+u_xxx=0.
"""
from math import acosh, cosh, exp, pi, sqrt, tanh

from scipy.integrate import quad
from scipy.optimize import brentq, minimize_scalar
from scipy.special import ellipe, ellipj, ellipk
import sympy as sp


def read_pulse():
    def measured(x, t):
        return -0.5 + 2/cosh(x - t)**2

    half = measured(0, 0) - 1
    left = brentq(lambda x: measured(x, 0) - half, -3, 0)
    right = brentq(lambda x: measured(x, 0) - half, 0, 3)
    crests = []
    for t in (0., 2.):
        fit = minimize_scalar(lambda x: -measured(x, t), bounds=(t-2.1, t+2.5),
                              method="bounded", options={"xatol":1e-12})
        crests.append(fit.x)
    speed = (crests[1] - crests[0])/2
    assert abs(right-left - 2*acosh(sqrt(2))) < 2e-12
    assert abs(speed-1) < 3e-8
    print("Measured half-height width and speed:", right-left, speed)


def first_moment():
    def field(x):
        return (1 - 2*x*x)*exp(-x*x)

    x = sp.symbols("x", real=True)
    u = (1 - 2*x*x)*sp.exp(-x*x)
    rhs = sp.lambdify(x, sp.simplify(-6*u*u.diff(x) - u.diff(x, 3)), "math")
    mass = quad(field, -12, 12, epsabs=1e-13)[0]
    power = quad(lambda x: field(x)**2, -12, 12)[0]
    rate = quad(lambda x: x*rhs(x), -12, 12)[0]
    assert abs(mass) < 1e-13 and abs(rate-3*power) < 1e-13
    assert abs(rate - 9*sqrt(pi/2)/4) < 1e-13
    print("Zero-mass profile, squared-field integral, first-moment rate:", mass, power, rate)


def zero_energy():
    z = sp.symbols("z", real=True)
    f, g = sp.tanh(z), z*sp.tanh(z) - 1
    for y in (f, g):
        assert sp.trigsimp(y.diff(z, 2) + 2*y/sp.cosh(z)**2) == 0
    assert sp.simplify(f*g.diff(z) - g*f.diff(z)) == 1
    for half in (2, 5, 10):
        value = quad(lambda x: tanh(x)**2, -half, half)[0]
        assert abs(value - 2*(half-tanh(half))) < 2e-13
    print("Zero-energy Wronskian in z:", 1)


def periodic_excess():
    for m in (0.5, 0.99, 0.9999):
        half_period = ellipk(m)
        period = 2*half_period
        integrated = quad(lambda x: 2*m*ellipj(x, m)[1]**2, -half_period, half_period)[0]
        exact = 4*(ellipe(m) - (1-m)*half_period)
        assert abs(integrated-exact) < 3e-13
        print("m, fundamental period, excess, mean excess:", m, period,
              integrated, integrated/period)


if __name__ == "__main__":
    read_pulse()
    first_moment()
    zero_energy()
    periodic_excess()
