"""Checks for the Library article "Long-time KdV asymptotics on the line".

KdV in the site convention u_t + 6 u u_x + u_xxx = 0 with u(x, 0) = (3/4) sech^2 x. The Schrodinger
potential q = -u has one bound state (kappa = 1/2, a soliton of height 1/2 and speed 1) and reflection
R(k) = Gamma(ik) Gamma(3/2 - ik) Gamma(-1/2 - ik) / (Gamma(-ik) Gamma(-1/2) Gamma(3/2)), |R|^2 = sech^2(pi k).
The nonlinear steepest descent theorem (Grunert and Teschl, Theorem 5.4) predicts on the ray x = -3t
    u(-3t, t) = -(A / sqrt t) sin(2t - nu log(24 t) + delta) + O(t^-alpha),  1/2 < alpha < 1,
with A = sqrt(4 nu k0 / 3), nu = -log(1 - |R(k0)|^2) / (2 pi), k0 = 1/2. The coefficients are recomputed
here as in kdv/mixed_asymptotic_rays.py.

The equation is integrated with a Fourier pseudo-spectral method and fourth-order exponential time
differencing (ETDRK4, Kassam and Trefethen) on a periodic interval of length 8192, and u is evaluated
at x = -3t by spectral interpolation. Checks: the soliton has height 1/2 and its center is at
t + log(2/pi), as in kdv-asymptotic-regions; the integral of u^2 is conserved and its radiation share
equals the integral of 16 nu(k) k^2, which is 1/12; the simulated signal approaches the prediction and
the fitted amplitude approaches A; halving the step and the grid spacing, or doubling the period,
changes nothing visible on the ray. Fast, weak radiation that wraps around the periodic interval
reaches the soliton from the right; on the doubled period the crest matches the prediction.
Controls: the linear evolution of the same hump, the prediction without its logarithmic phase, and the
first-order amplitude all miss.
Run with Python 3, NumPy, SciPy and mpmath:  python3 kdv_radiation_check.py   (about three minutes)
"""
import mpmath as mp
import numpy as np
from scipy.optimize import least_squares, minimize_scalar

K0 = 0.5


def coefficients(digits=30):
    """Reflection R(k0), nu, amplitude A and phase delta, as in the chapter's coefficient program."""
    with mp.workdps(digits):
        k = mp.mpf(K0)
        lam = mp.mpf('1.5')
        R = mp.gamma(1j * k) * mp.gamma(lam - 1j * k) * mp.gamma(1 - lam - 1j * k) / (
            mp.gamma(-1j * k) * mp.gamma(1 - lam) * mp.gamma(lam))
        nu = -mp.log(1 - abs(R) ** 2) / (2 * mp.pi)
        A = mp.sqrt(4 * nu * k / 3)
        log_flux = lambda s: 2 * mp.log(abs(mp.tanh(mp.pi * s)))
        integrand = lambda s: (4 * mp.pi / mp.sinh(2 * mp.pi * k)) if s == k else \
            (log_flux(s) - log_flux(k)) * (1 / (s - k) - 1 / (s + k))
        delta = (mp.pi / 4 - mp.arg(R) + mp.arg(mp.gamma(1j * nu)) + 4 * mp.atan(mp.mpf('0.5') / k)
                 - mp.quad(integrand, [0, k]) / mp.pi)
        delta = mp.arg(mp.exp(1j * delta))
        return complex(R), float(nu), float(A), float(delta)


def etdrk4_kdv(n=2 ** 16, length=8192.0, x_left=-7000.0, dt=0.01, t_end=64.0, sample_every=0.05,
               nonlinear=True):
    """Integrate KdV; return sample times, u(-3t, t), and the final field with its grid."""
    x = x_left + length * np.arange(n) / n
    k = 2 * np.pi * np.fft.fftfreq(n, d=length / n)
    e = np.exp(-2 * np.abs(x))
    u0 = 3.0 * e / (1 + e) ** 2                       # (3/4) sech^2 x without overflow
    v = np.fft.fft(u0)
    Lop = 1j * k ** 3                                   # u_t = -u_xxx  ->  i k^3 in Fourier space
    E, E2 = np.exp(dt * Lop), np.exp(dt * Lop / 2)
    M = 32
    r = np.exp(1j * np.pi * (np.arange(1, M + 1) - 0.5) / M)
    LR = dt * Lop[:, None] + r[None, :]
    # Contour-integral evaluation of the ETDRK4 coefficients (complex, since Lop is imaginary).
    Q = dt * np.mean((np.exp(LR / 2) - 1) / LR, axis=1)
    f1 = dt * np.mean((-4 - LR + np.exp(LR) * (4 - 3 * LR + LR ** 2)) / LR ** 3, axis=1)
    f2 = dt * np.mean((2 + LR + np.exp(LR) * (-2 + LR)) / LR ** 3, axis=1)
    f3 = dt * np.mean((-4 - 3 * LR - LR ** 2 + np.exp(LR) * (4 - LR)) / LR ** 3, axis=1)
    dealias = np.abs(k) < (2 / 3) * np.abs(k).max()
    g = -3j * k * dealias

    def N(vv):
        if not nonlinear:
            return np.zeros_like(vv)
        return g * np.fft.fft(np.real(np.fft.ifft(vv)) ** 2)

    def value_at(vv, x0):
        return float(np.real(np.sum(vv * np.exp(1j * k * (x0 - x_left))) / n))

    steps = int(round(t_end / dt))
    every = int(round(sample_every / dt))
    times, signal = [], []
    for step in range(1, steps + 1):
        Nv = N(v)
        a = E2 * v + Q * Nv
        Na = N(a)
        b = E2 * v + Q * Na
        Nb = N(b)
        c = E2 * a + Q * (2 * Nb - Nv)
        Nc = N(c)
        v = E * v + Nv * f1 + 2 * (Na + Nb) * f2 + Nc * f3
        if step % every == 0:
            t = step * dt
            times.append(t)
            signal.append(value_at(v, -3 * t))
    return np.array(times), np.array(signal), x, np.real(np.fft.ifft(v))


def fit_window(times, signal, lo, hi, nu, with_log=True):
    """Least-squares amplitude and phase of -(a / sqrt t) sin(2t - nu log 24t + d) on [lo, hi]."""
    m = (times >= lo) & (times <= hi)
    t, y = times[m], signal[m]
    model = lambda p: -(p[0] / np.sqrt(t)) * np.sin(2 * t - (nu * np.log(24 * t) if with_log else 0.0) + p[1])
    res = least_squares(lambda p: model(p) - y, x0=[0.13, 0.0])
    return res.x[0], np.angle(np.exp(1j * res.x[1])), np.sqrt(np.mean(res.fun ** 2)) * np.sqrt(np.mean(t))


def crest(x, u):
    """Height and position of the largest value of the spectral interpolant of a periodic grid field."""
    v, k = np.fft.fft(u), 2 * np.pi * np.fft.fftfreq(len(x), d=x[1] - x[0])
    value = lambda x0: float(np.real(np.sum(v * np.exp(1j * k * (x0 - x[0])))) / len(x))
    g = x[np.argmax(u)]
    res = minimize_scalar(lambda x0: -value(x0), bounds=(g - 0.2, g + 0.2), method='bounded', options={'xatol': 1e-10})
    return -res.fun, res.x


def main():
    R, nu, A, delta = coefficients()
    nu_lin = abs(R) ** 2 / (2 * np.pi)
    print(f'R(1/2) = {R.real:.10f}{R.imag:+.10f}i, |R|^2 = {abs(R) ** 2:.10f} (sech^2(pi/2) = {1 / np.cosh(np.pi / 2) ** 2:.10f})')
    print(f'nu = {nu:.10f}, A = {A:.10f}, delta = {delta:.9f}; first-order nu = |R|^2/(2 pi) = {nu_lin:.10f}')
    checks, controls = {}, {}
    checks['|R|^2 = sech^2(pi k0) and the coefficients match the chapter'] = (
        abs(abs(R) ** 2 - 1 / np.cosh(np.pi / 2) ** 2) < 1e-14 and abs(A - 0.1354695021) < 1e-9
        and abs(nu - 0.0275279790) < 1e-9 and abs(delta + 1.218056306) < 1e-8)

    times, signal, x, u_end = etdrk4_kdv()
    # The soliton crest on the spectral interpolant; kdv-asymptotic-regions predicts height 1/2 at x = t + log(2/pi).
    height, center = crest(x, u_end)
    predicted_center = times[-1] + np.log(2 / np.pi)
    print(f'soliton at t = 64: height {height:.8f}, center {center:.6f}; predicted center t + log(2/pi) = {predicted_center:.6f}')
    checks['soliton crest: height 1/2 within 1e-5, center t + log(2/pi) within 1e-3'] = (
        abs(height - 0.5) < 1e-5 and abs(center - predicted_center) < 1e-3)

    # The conserved integral P = int u^2 = 3/4. The soliton (1/2) sech^2(x/2) carries (16/3) kappa^3 = 2/3. Averaging the
    # square of the radiation formula over its oscillations and changing variables by x = -12 k0^2 t gives the radiation
    # share int_0^oo 16 nu(k) k^2 dk, which is 1/12 for |R|^2 = sech^2(pi k).
    with mp.workdps(30):
        p_rad = float(mp.quad(lambda kv: 16 * (-mp.log(mp.tanh(mp.pi * kv) ** 2) / (2 * mp.pi)) * kv ** 2, [0, 1, mp.inf]))
    dx = x[1] - x[0]
    total = np.sum(u_end ** 2) * dx
    behind = np.sum(u_end[x < center - 25] ** 2) * dx
    print(f'int u^2 at t = 64: total {total:.8f} (initial 0.75); behind the soliton (x < {center - 25:.1f}): {behind:.6f}; '
          f'int 16 nu k^2 dk = {p_rad:.12f} (1/12 = {1 / 12:.12f})')
    checks['int u^2 is conserved (1e-6)'] = abs(total - 0.75) < 1e-6
    checks['int_0^oo 16 nu(k) k^2 dk equals 3/4 - 2/3 = 1/12 (1e-12)'] = abs(p_rad - 1 / 12) < 1e-12
    checks['the simulated region behind the soliton holds 1/12 of int u^2 (within 2e-3)'] = abs(behind - 1 / 12) < 2e-3

    pred = lambda t, with_log=True: -(A / np.sqrt(t)) * np.sin(2 * t - (nu * np.log(24 * t) if with_log else 0.0) + delta)
    print('window       max |u - prediction| * sqrt(t)/A   without the log phase   fitted amplitude   fitted delta')
    rows = {}
    for lo, hi in ((4, 8), (8, 16), (16, 32), (32, 64)):
        m = (times >= lo) & (times <= hi)
        err = np.max(np.abs(signal[m] - pred(times[m])) * np.sqrt(times[m])) / A
        err_nolog = np.max(np.abs(signal[m] - pred(times[m], False)) * np.sqrt(times[m])) / A
        amp, d_fit, _ = fit_window(times, signal, lo, hi, nu)
        rows[(lo, hi)] = (err, err_nolog, amp, d_fit)
        print(f'[{lo:2d}, {hi:2d}]      {err:.4f}                            {err_nolog:.4f}                 {amp:.6f}           {d_fit:+.5f}')
    errs = [rows[w][0] for w in rows]
    checks['the relative error falls window by window'] = all(errs[i + 1] < errs[i] for i in range(len(errs) - 1))
    checks['on t in [32, 64] the signal matches the prediction within 3 percent of its amplitude'] = rows[(32, 64)][0] < 0.03
    checks['fitted amplitude on [32, 64] within 1 percent of A'] = abs(rows[(32, 64)][2] / A - 1) < 0.01
    controls['dropping the log phase leaves a larger error on [32, 64]'] = rows[(32, 64)][1] > 3 * rows[(32, 64)][0]
    controls['the first-order amplitude sqrt(4 nu_lin k0/3) is off by more than the fit error'] = (
        abs(np.sqrt(4 * nu_lin * K0 / 3) / rows[(32, 64)][2] - 1) > 3 * abs(rows[(32, 64)][2] / A - 1))

    # Linear control: the same hump under u_t + u_xxx = 0.
    t_lin, s_lin, _, _ = etdrk4_kdv(nonlinear=False, t_end=32.0)
    m = t_lin >= 16
    lin_amp = np.max(np.abs(s_lin[m]) * np.sqrt(t_lin[m]))
    print(f'linear evolution of the same hump: |u(-3t, t)| sqrt(t) reaches {lin_amp:.4f} on [16, 32], against A = {A:.4f}')
    controls['linear dispersion of the same data predicts a much larger signal'] = lin_amp > 2 * A

    # Refinement on [0, 16]: halve the step and the grid spacing of the main run, on the same period.
    t_a, s_a, _, _ = etdrk4_kdv(t_end=16.0)
    t_b, s_b, _, _ = etdrk4_kdv(n=2 ** 17, dt=0.005, t_end=16.0)
    refine = np.max(np.abs(s_a - s_b))
    print(f'refinement on t <= 16 (step 0.01 -> 0.005, grid 0.125 -> 0.0625): largest change of u(-3t, t) {refine:.1e}')
    checks['refinement changes u(-3t, t) by less than 1e-6'] = refine < 1e-6

    # Period: fast, weak radiation leaves through the left end and re-enters on the right. Doubling the period to 16384
    # at the same grid spacing bounds that effect on u(-3t, t) up to t = 64.
    t_c, s_c, x_c, u_c = etdrk4_kdv(n=2 ** 17, length=16384.0, x_left=-15000.0)
    period = np.max(np.abs(s_c - signal) * np.sqrt(times)) / A
    print(f'doubling the period to 16384: largest change of sqrt(t) u(-3t, t) / A on t <= 64 is {period:.1e}')
    checks['doubling the period changes u(-3t, t) by less than 0.1 percent of A / sqrt(t)'] = period < 1e-3
    # The same wrapped radiation reaches the soliton from the right; on the doubled period the crest moves to the
    # prediction.
    height_c, center_c = crest(x_c, u_c)
    print(f'soliton at t = 64 on period 16384: height {height_c:.9f}, center - (t + log(2/pi)) = {center_c - predicted_center:+.1e}')
    checks['on the doubled period the crest has height 1/2 within 1e-6 and center t + log(2/pi) within 5e-5'] = (
        abs(height_c - 0.5) < 1e-6 and abs(center_c - predicted_center) < 5e-5)

    for name, ok in checks.items():
        print(f"{'PASS' if ok else 'FAIL'}  {name}")
    for name, ok in controls.items():
        print(f"{'PASS' if ok else 'FAIL'}  control: {name}")
    if not all(checks.values()) or not all(controls.values()):
        raise SystemExit(1)
    print('The simulated KdV radiation approaches the steepest-descent prediction; all three controls miss.')


if __name__ == '__main__':
    main()
