"""Measurements for modulated KdV waves, NLS packets and two-dimensional KP waves.

Run with Python 3.9+, NumPy and SciPy. The tests use local profiles, the
stated limiting equations and exact initial derivatives, without simulating a
full small-dispersion shock or inferring a nonlinear stability theorem.
"""

from math import atan, cos, log, pi, sin, sqrt, tanh

import numpy as np
from numpy.polynomial import Polynomial
from scipy.integrate import dblquad, quad, solve_ivp
from scipy.optimize import brentq, minimize_scalar
from scipy.special import ellipe, ellipj, ellipk


def middle_speed(m):
    K = ellipk(m)
    return 2*(1+m)-4*m*(1-m)*K/(ellipe(m)-(1-m)*K)


def recover_wave():
    # Solve the frozen traveling-wave ODE independently of the elliptic inverse.
    low, high, third_root, epsilon = .25, 1.75, -2.25, .2
    root_sum = low+high+third_root
    pair_sum = low*high+third_root*(low+high)

    def equation(x, state):
        u, slope = state
        return slope, (-3*u*u+2*root_sum*u-pair_sum)/epsilon**2

    def extremum(x, state):
        return state[1]

    track = solve_ivp(equation, (0, 1.1), (high, 0), events=extremum,
                      rtol=2e-12, atol=2e-13, max_step=.02)
    crest, trough = track.y_events[0][:2, 0]
    wavelength = track.t_events[0][2]
    d = (crest-trough)/2
    m = brentq(lambda m: sqrt(m)*ellipk(m)-wavelength*sqrt(d)/(2*epsilon),
               .001, .999)
    r3 = (crest+trough)/2
    r1 = r3-d/m
    assert np.allclose([r1, r1+d, r3], [-1., -.25, 1.], atol=4e-11, rtol=0)
    print(f"Measured frozen wavelength {wavelength:.8f}, recovered parameter {m:.8f}")


def modulation():
    wstar = middle_speed(.5)
    for time in (0., 1., 1.9):
        step = 1e-5
        right = step+time*(wstar-tanh(step/2))
        left = -step+time*(wstar+tanh(step/2))
        slope = -2*tanh(step/2)/(right-left)
        assert abs(slope+1/(2-time)) < 2e-8
        print(f"Middle-speed slope at t={time:g}: {slope:.7f}")

    # Count phases by integrating the interior wave density over velocity rays.
    for count in (512, 1024, 2048):
        m = np.sin(np.linspace(0, pi/2, count+1)[1:-1])**2
        speeds = np.r_[-6., middle_speed(m), 4.]
        wave_numbers = np.r_[2., pi/ellipk(m), 0.]
        integral = np.sum((wave_numbers[1:]+wave_numbers[:-1])*np.diff(speeds))/2
        assert np.all(np.diff(speeds) > 0)
        print(f"Step density, {count} intervals: integral {integral:.8f} (limit 16)")
    assert abs(integral-16) < 2e-5

    # The inverse decreasing flank is -atanh(sqrt(1+u)).
    # High precision avoids cancellation in the third derivative of its inverse.
    from decimal import Decimal, localcontext
    with localcontext() as context:
        context.prec = 60
        u = -Decimal(2)/3
        h = Decimal('0.000001')
        def inverse(w):
            z = (1+w).sqrt()
            return -((1+z)/(1-z)).ln()/2
        k = -(inverse(u+2*h)-2*inverse(u+h)+2*inverse(u-h)-inverse(u-2*h))/(2*h**3)
        assert abs(float(k)-81*sqrt(3)/16) < 2e-9
        print(f"Inverse-flank coefficient {k:.8f}")


def chirped_packet():
    size = 2048
    x = np.arange(-size//2, size//2)*80/size
    frequencies = 2*pi*np.fft.fftfreq(size, 80/size)
    def second(q):
        return np.fft.ifft(-frequencies**2*np.fft.fft(q))
    for mu, epsilon in ((2., .5), (3., .5), (0., 1.)):
        q = -np.exp(-1j*mu*np.log(np.cosh(x))/epsilon)/np.cosh(x)
        density = abs(q)**2
        qt = 1j*(epsilon*second(q)+2*density*q/epsilon)
        density_t = 2*(q.conj()*qt).real
        qtt = 1j*(epsilon*second(qt)+2*(density_t*q+density*qt)/epsilon)
        density_tt = 2*(abs(qt)**2+(q.conj()*qtt).real)
        observed = [density_t[size//2], density_tt[size//2]]
        assert np.allclose(observed, [2*mu, 8*(1+mu**2-epsilon**2)], atol=2e-7)
        print(f"Chirp {mu:g}, dispersion {epsilon:g}: central derivatives {observed[0]:.7f}, {observed[1]:.7f}")


def transverse_measurements():
    period = 2*ellipk(.5)
    def wave(x):
        return 1.5-ellipj(x, .5)[0]**2
    for tilt, mismatch in ((.5, 0.), (.25, 1.)):
        assert abs(wave(0)-wave(tilt*2*period)-mismatch) < 2e-14

    def y_wave(x, y):
        weights = np.exp([y-x, 0., y+x])
        weights /= sum(weights)
        k = np.array([-1., 0., 1.])
        return 2*((weights @ (k*k))-(weights @ k)**2)
    maximum = minimize_scalar(lambda x: -y_wave(x, -log(8)), bounds=(0., 4.),
                              method="bounded", options={"xatol": 1e-12})
    assert abs(maximum.x-np.arccosh(3.5)) < 8e-8
    assert abs(maximum.fun+8/15) < 8e-14
    print(f"KP-II horizontal peaks at ±{maximum.x:.7f}, height {-maximum.fun:.8f}")

    for A, B in ((10., 5.), (10., 10.), (10., 20.)):
        def lump(y, x):
            return 4*(1+y*y-x*x)/(1+y*y+x*x)**2
        value, _ = dblquad(lump, -A, A, lambda x: -B, lambda x: B,
                           epsabs=2e-9, epsrel=2e-9)
        expected = 16*A/sqrt(1+A*A)*atan(B/sqrt(1+A*A))
        assert abs(value-expected) < 1e-9
        print(f"KP-I rectangular mass, half-widths {A:g},{B:g}: {value:.8f}")

    for a, b in ((2., 1.), (1., 2.), (1., 1.)):
        # Integrate in physical Fourier polar coordinates after doing the radial
        # Gaussian integral. The independent angular weight is then nonuniform.
        value = quad(lambda t: -cos(2*t)/(a*a*cos(t)**2+b*b*sin(t)**2),
                     0, 2*pi)[0]*a*b/(2*pi)
        assert abs(value-(a-b)/(a+b)) < 2e-13
        print(f"DS center, widths {a:g},{b:g}: {value:.8f}")


def cylinder():
    # W is the second derivative of exp(mu*X/2)*(1-z), z=tanh(X/2).
    # Divide out the common exponential and test every polynomial coefficient.
    z = Polynomial([0., 1.])
    for q in (1/12, 2/12, 3/16, 1/4):
        mu = 1+sqrt(1-4*q)
        growth = 2*q*sqrt(1-4*q)
        def derivative(p):
            return mu/2*p+(1-z*z)/2*p.deriv()
        W = derivative(derivative(1-z))
        K = (3*(1-z*z)-1)*W
        fourth = derivative(derivative(derivative(derivative(W))))
        residual = growth*derivative(W)+derivative(derivative(K))+fourth+3*q*q*W
        assert max(abs(residual.coef)) < 2e-12
        print(f"KP-I cylinder q={q:.7f}: rate {growth:.7f}, polynomial residual {max(abs(residual.coef)):.2g}")


def breaking_front():
    def amplitude(xi):
        s = brentq(lambda v: v**3/(1+v*v)-xi, 0, 1, xtol=1e-15)
        return 2*s/(3*(1+s*s))
    for h in (1e-3, 1e-5, 1e-7):
        horizontal = log(amplitude(h)/amplitude(h/2))/log(2)
        tangent = log(amplitude(h*h/9)/amplitude(h*h/36))/log(2)
        print(f"dKP displacement {h:g}, horizontal/tangent exponents {horizontal:.7f}, {tangent:.7f}")
    assert abs(horizontal-1/3) < 1e-4 and abs(tangent-2/3) < 1e-5


def model_probes():
    # A beat between nearby plane waves gives the directional frequency slope.
    for sign, k, l, vx, vy in ((-1, 1., .5, -2.25, -3.),
                               (1, 1., .5, -3.75, 3.), (-1, 1., -1., 0., 6.)):
        def frequency(kx, ky):
            return -kx**3+3*sign*ky**2/kx
        h = 1e-5
        xbeat = (frequency(k+h, l)-frequency(k-h, l))/(2*h)
        ybeat = (frequency(k, l+h)-frequency(k, l-h))/(2*h)
        assert max(abs(xbeat-vx), abs(ybeat-vy)) < 5e-10
        print(f"KP sign {sign:+d}, carrier {k:g},{l:g}: beat velocity ({xbeat:.7f},{ybeat:.7f})")

    # Time-differentiate the complex DS-I equation with initially uniform q.
    # An arbitrary real Phi_t contributes only to the imaginary part of q_tt.
    n = 32
    angle = np.arange(n)*(2*pi/n)
    x, y = np.meshgrid(angle, angle, indexing="ij")
    mode = np.cos(x+y)
    k = np.fft.fftfreq(n, 1/n)
    lap = -(k[:, None]**2+k[None, :]**2)
    for a in (0., .25):
        V = 2*(1+a*mode)
        qt = 1j*V
        qtt = 1j*(np.fft.ifft2(lap*np.fft.fft2(qt))+V*qt+2*np.sin(x-3*y))
        density_tt = 2*(abs(qt)**2+qtt.real)
        coefficient = 2*np.mean(mode*density_tt)
        assert abs(coefficient-8*a) < 2e-14
        print(f"DS-I initial mean amplitude {a:g}: density acceleration in characteristic cosine {coefficient:.8f}")


if __name__ == "__main__":
    recover_wave()
    modulation()
    chirped_packet()
    transverse_measurements()
    cylinder()
    breaking_front()
    model_probes()
