"""Measurements on exact KdV, NLS, Benjamin–Ono and Camassa–Holm waves.

Run with Python 3, NumPy, SciPy and mpmath. All coordinates use the
dimensionless conventions of the linked articles.
"""
from math import atan, atanh, cos, exp, log, pi, sin, sqrt, tanh

import mpmath as mp
import numpy as np
from scipy.integrate import quad, solve_ivp
from scipy.special import ellipk


def kdv_measurements():
    with mp.workdps(40):
        for fast in [mp.mpf("1.4"), mp.sqrt(3), mp.mpf(2)]:
            s, d = fast + 1, fast - 1
            def log_tau(x):
                return mp.log(mp.cosh(s*x) + s/d*mp.cosh(d*x))
            height, curvature = [2*mp.diff(log_tau, 0, order) for order in [2, 4]]
            assert abs(height - 2*s*d) < mp.mpf("1e-35")
            assert abs(curvature - 4*s*d*(3-fast**2)) < mp.mpf("1e-35")
            if abs(fast**2-3) < mp.mpf("1e-35"):
                assert abs(2*mp.diff(log_tau, 0, 6)+8*(s*d)**3) < mp.mpf("1e-34")
            print("Symmetric collision, fast scale, center height and curvature:",
                  float(fast), float(height), float(curvature))
    def omega(k):
        return sqrt(k*tanh(k))
    for k in [.4, .2, .1]:
        phase = omega(k)/k
        group = (omega(k+1e-6)-omega(k-1e-6))/2e-6
        exact_group = (tanh(k)+k*(1-tanh(k)**2))/(2*omega(k))
        assert abs(exact_group-group) < 2e-10
        print("kh, phase and group errors in units of c0:", k,
              abs(phase-(1-k*k/6)), abs(exact_group-(1-k*k/2)))
    def bottom(t, state):
        return state[1]
    bottom.direction = 1
    orbit = solve_ivp(lambda t,y: (y[1], 1-3*y[0]**2), (0, 6), [1., 0.],
                      events=bottom, rtol=1e-12, atol=1e-13)
    period = 2*orbit.t_events[0][0]
    assert abs(period-2*ellipk(.5)) < 2e-11
    print("Stationary cnoidal train, measured period:",period)
    m, p = 12., 48.
    s, cube = m/4, 3*p/16
    params = np.roots([1, -s, (s**3-cube)/(3*s)])
    assert np.allclose(params,[2,1])
    print("Reconstructed scales, predicted third integral:",params,32/5*sum(params**5))


def nls_measurements():
    # Evolve the full focusing PDE on a ring of length pi. Delta multiplies
    # a pure phase Fourier component at t=0. h is the real part in the rotating frame.
    n = 64
    x = np.arange(n)*pi/n
    k = np.fft.fftfreq(n, 1/n)*2
    time = .5
    for delta,steps in [(.01,256),(.005,512),(.0025,1024)]:
        q = 1. + 1j*delta*np.cos(2*x)
        dt = time/steps
        linear = np.exp(-.5j*k*k*dt)
        for _ in range(steps):
            q = np.fft.ifft(linear*np.fft.fft(q))
            q *= np.exp(2j*abs(q)**2*dt)
            q = np.fft.ifft(linear*np.fft.fft(q))
        gain = 2*np.mean((q*np.exp(-2j*time)).real*np.cos(2*x))/delta
        assert abs(gain-4*time) < .002
        print("Marginal sideband, initial phase and measured amplitude gain:",delta,gain)
    with mp.workdps(35):
        for nu in [mp.mpf(".5"),mp.mpf("-.5")]:
            beta = mp.sqrt(1-nu**2)
            def f(x):
                return mp.sqrt(beta/4)*mp.sech(beta*x)
            for x in [-1,0,2]:
                phi = beta*mp.tanh(beta*x) + 1j*nu
                matrix = mp.matrix([[1j*nu,phi],[phi.conjugate(),-1j*nu]])
                diff = matrix*mp.matrix([f(x),-f(x)]) - mp.matrix([mp.diff(f,x),-mp.diff(f,x)])
                assert mp.norm(diff)<mp.mpf("1e-30")
            assert abs(mp.quad(lambda x: 2*f(x)**2,[-mp.inf,0,mp.inf])-1)<mp.mpf("1e-30")
    for t in [0, .25, 1]:
        a = 1+16*t*t
        def excess(x):
            return 8*(a-4*x*x)/(a+4*x*x)**2
        bound = sqrt(a)/2
        center = 2*quad(excess,0,bound)[0]
        tails = 2*quad(excess,bound,np.inf)[0]
        assert abs(center+tails)<1e-11 and abs(center-4/sqrt(a))<1e-11
        print("Peregrine time, central excess and exterior deficit:",t,center,tails)
    for dt in [.1,.03,.01,.003]:
        # kappa=1, nu=1/2. Splitting at the shrinking inner scale prevents
        # quadrature from stepping over the emerging pole at x=0.
        t = pi/2-dt
        def norm_on_pair(x):
            return 2*np.cosh(x)/(np.sinh(x)**2+cos(t)**2)
        norm = quad(norm_on_pair,0,dt)[0]+quad(norm_on_pair,dt,40)[0]
        assert abs(norm-pi/sin(dt)) < 3e-8
        print("Time to pole and time times ordinary squared norm:",dt,dt*norm)


def nonlocal_dispersion():
    for widths in [3.,1/np.tan(pi/40)]:
        fraction=quad(lambda z: 1/(1+z*z),-widths,widths)[0]/pi
        assert abs(fraction-2*atan(widths)/pi) < 2e-13
        print("Benjamin–Ono half-widths observed and area fraction:",widths,fraction)
    # Translation changes the phase of all modes. Adding mean m shifts
    # every Hardy eigenvalue by -m and both stationary-frame velocities by 2m.
    n=48
    idx=np.arange(n)
    r=1/sqrt(3)
    potential=r**abs(idx[:,None]-idx)
    np.fill_diagonal(potential,0.)
    base=np.diag(idx)-potential
    for mean in [0.,.25]:
        eig=np.linalg.eigvalsh(base-mean*np.eye(n))[:3]
        assert np.allclose(eig,np.array([-.5,1.,2.])-mean,rtol=0,atol=2e-13)
        print("Mean and first three periodic BO eigenvalues:",mean,eig)
    for time in [-10.,-5.,0.,5.,10.]:
        # Pole velocities 1 and 2, both initial residues one.
        a,b=exp(time),exp(2*time)
        m0,m1,m2=a+b,a+b/2,a+b/4
        q1,q2=log(a*b/(2*m2)),log(2*m0)
        assert 0<exp(q1-q2)<1
        print("Two positive peakons, time and ordered positions:",time,q1,q2)
    tstar=atanh(.5)
    def ode(t,y):
        d,p=y
        return [-2*p*(-np.expm1(-d)),p*p*exp(-d)]
    gaps=[.2,.1,.05]
    times=[tstar-gap for gap in gaps]
    orbit=solve_ivp(ode,(0,times[-1]),[log(4/3),2],t_eval=times,rtol=2e-12,atol=1e-13)
    for dt,(d,p) in zip(gaps,orbit.y.T):
        assert abs(p*tanh(dt)-1) < 2e-10
        assert abs(p*p*(-np.expm1(-d))-1) < 2e-10
        print("Time to peakon collision, gap and maximum field:",dt,d,p*(-np.expm1(-d)))


if __name__ == "__main__":
    kdv_measurements()
    nls_measurements()
    nonlocal_dispersion()
