"""Checks for the Library article "The inverse scattering transform for KdV".

KdV u_t + 6 u u_x + u_xxx = 0 on the line, Schrodinger operator H = -d^2/dx^2 + q with q = -u. Right Jost solution
f_+(x, k) ~ e^{ikx} at +infinity, right reflection coefficient R(k), bound states k = i kappa_j and right norming
constants c_j = [int f_+(x, i kappa_j)^2 dx]^{-1}. In time, R(k) e^{8 i k^3 t} and c_j e^{8 kappa_j^3 t}.
Reconstruction by the Dyson formula u = 2 d^2/dx^2 log det(I + F_x), where F_x has kernel F(y + z) on [x, infinity) and
F(s) = (1/2pi) int R(k) e^{iks} dk + sum_j c_j e^{-kappa_j s}; the soliton terms enter as an exact rank-N block.
Initial data u0 = A sech^2 x, A = s(s + 1).
Checks:
  0. symbolically, [B, L] = L_t for L = -d^2 - u and B = -4 d^3 - 6u d - 3u_x exactly when u solves KdV;
  1. bound states kappa_j = s - j + 1 for A = 2, 3, 4, 6, 12, found from the Jost Wronskian (1e-10);
  2. direct integration gives |R|^2 + |T|^2 = 1, R = 0 for integer s, and agrees with the closed form
     R(k) = Gamma(1+s-ik) Gamma(-s-ik) Gamma(ik) / [Gamma(-ik) Gamma(1+s) Gamma(-s)] at twelve points (1e-11);
  3. the reflectionless wells have norming constants 2; 12, 6; 60, 60, 12 (1e-8);
  4. the Dyson formula rebuilds 4 sech^2 x, which reflects, from its scattering data (1e-6);
  5. evolving the data and rebuilding gives the solution of KdV computed independently by ETDRK4 at t = 0.3, 0.6
     and 1 (1e-4), and the two-soliton solution from 6 sech^2 x (1e-4);
  6. by t = 1 the largest peak is 2 kappa_1^2, the amplitude of the fastest soliton (1e-3).
Controls: dropping the reflection data, or reversing the time evolution, spoils the reconstruction (errors > 0.1).
Run with Python 3, NumPy, SciPy and SymPy:  python3 kdv_ist_check.py   (under a minute)
"""
import numpy as np
from scipy.integrate import quad, solve_ivp
from scipy.interpolate import CubicSpline
from scipy.optimize import brentq
from scipy.special import loggamma

X = 20.0          # half-width of the interval on which Jost solutions are integrated


def well(A):
    return lambda x: -A / np.cosh(x) ** 2


# ------------------------------------------------------------------------------------------------- direct scattering
def scaled_jost(q, kappa, side):
    """g = e^{kappa X} f_(+/-)(x, i kappa) from x = side*X to 0, with a purely relative tolerance."""
    rhs = lambda x, y: [y[1], (q(x) + kappa * kappa) * y[0]]
    return solve_ivp(rhs, (side * X, 0.0), [1.0, -side * kappa], rtol=1e-13, atol=0.0, dense_output=True,
                     method='DOP853')


def wronskian(q, kappa):
    gp, gm = scaled_jost(q, kappa, +1), scaled_jost(q, kappa, -1)
    a, ap, b, bp = gp.y[0, -1], gp.y[1, -1], gm.y[0, -1], gm.y[1, -1]
    return (a * bp - ap * b) / np.hypot(a, ap) / np.hypot(b, bp)


def bound_states(q, kmax, samples=80):
    ks = np.linspace(0.02, kmax, samples)
    w = [wronskian(q, k) for k in ks]
    return sorted([brentq(lambda k: wronskian(q, k), a, b, xtol=1e-15)
                   for a, b, fa, fb in zip(ks[:-1], ks[1:], w[:-1], w[1:]) if fa * fb < 0], reverse=True)


def norming(q, kappa):
    """c = [int f_+(x, i kappa)^2 dx]^{-1}, matching f_+ = gamma f_- at x = 0."""
    gp, gm = scaled_jost(q, kappa, +1), scaled_jost(q, kappa, -1)
    gamma = gp.y[0, -1] / gm.y[0, -1]
    right = quad(lambda x: gp.sol(x)[0] ** 2, 0, X, limit=500, epsrel=1e-13)[0]
    left = quad(lambda x: gm.sol(x)[0] ** 2, -X, 0, limit=500, epsrel=1e-13)[0]
    return np.exp(2 * kappa * X) / (right + gamma ** 2 * left)


def reflection_transmission(q, k):
    """Integrate f_+(x, k) from +X to -X and read f_+ = alpha e^{ikx} + beta e^{-ikx} there."""
    rhs = lambda x, y: [y[1], (q(x) - k * k) * y[0]]
    sol = solve_ivp(rhs, (X, -X), np.array([np.exp(1j * k * X), 1j * k * np.exp(1j * k * X)], complex),
                    rtol=1e-12, atol=1e-14, method='DOP853')
    f, fp = sol.y[0, -1], sol.y[1, -1]
    alpha = 0.5 * (f + fp / (1j * k)) * np.exp(1j * k * X)
    beta = 0.5 * (f - fp / (1j * k)) * np.exp(-1j * k * X)
    return -np.conj(beta) / alpha, 1 / alpha


def R_closed(s, k):
    k = np.asarray(k, complex)
    s = np.asarray(s, complex)
    return np.exp(loggamma(1 + s - 1j * k) + loggamma(-s - 1j * k) + loggamma(1j * k) - loggamma(-1j * k)
                  - loggamma(1 + s) - loggamma(-s))


# -------------------------------------------------------------------------------------------------------- inverse
def F_continuous(Rfun, t, smin, smax, h=0.004, kmax=10.0, dk=0.002):
    """(1/2pi) int R(k) e^{8ik^3 t} e^{iks} dk = (1/pi) Re int_0^inf ..., tabulated and splined in s."""
    k = np.arange(dk / 2, kmax, dk)
    Rt = Rfun(k) * np.exp(8j * k ** 3 * t)
    sg = np.arange(smin, smax + h, h)
    vals = np.concatenate([(np.exp(1j * np.outer(sg[i:i + 2000], k)) @ Rt).real * dk / np.pi
                           for i in range(0, len(sg), 2000)])
    return CubicSpline(sg, vals)


def dyson(Fc, kappas, cs, t, xs, Y=25.0, n=160):
    """u = 2 d^2/dx^2 log det(I + F_x) by Gauss-Legendre Nystrom on [x, x + Y]; solitons as a rank-N block."""
    g, w = np.polynomial.legendre.leggauss(n)
    kap = np.array(kappas)
    ct = np.array([c * np.exp(8 * k ** 3 * t) for c, k in zip(cs, kappas)])
    logdet = []
    for x in xs:
        z = x + (g + 1) * Y / 2
        sw = np.sqrt(w * Y / 2)
        I = np.eye(n)
        C = sw[:, None] * Fc(z[:, None] + z[None, :]) * sw[None, :] if Fc is not None else 0 * I
        ld = np.linalg.slogdet(I + C)[1]
        if len(kap):
            Phi = sw[:, None] * np.exp(-np.outer(z, kap))
            ld += np.linalg.slogdet(np.eye(len(kap)) + ct[:, None] * (Phi.T @ np.linalg.solve(I + C, Phi)))[1]
        logdet.append(ld)
    logdet = np.array(logdet)
    h = xs[1] - xs[0]
    d2 = (-logdet[:-4] + 16 * logdet[1:-3] - 30 * logdet[2:-2] + 16 * logdet[3:-1] - logdet[4:]) / (12 * h * h)
    return xs[2:-2], 2 * d2


# --------------------------------------------------------------------------------------------- independent solver
def kdv_etdrk4(u0, L, times, dt, M=64):
    """Periodic pseudo-spectral ETDRK4 (Kassam-Trefethen); the contour is a full circle since i k^3 is imaginary."""
    n = len(u0)
    k = 2 * np.pi * np.fft.fftfreq(n, d=L / n)
    Lk = 1j * k ** 3
    E, E2 = np.exp(dt * Lk), np.exp(dt * Lk / 2)
    r = np.exp(2j * np.pi * (np.arange(1, M + 1) - 0.5) / M)
    LR = dt * Lk[:, None] + r[None, :]
    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)
    g = -3j * k
    N = lambda v: g * np.fft.fft(np.real(np.fft.ifft(v)) ** 2)
    v, t, out = np.fft.fft(u0), 0.0, {}
    for target in sorted(times):
        for _ in range(int(round((target - t) / dt))):
            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
        t = target
        out[target] = np.fft.fft(np.real(np.fft.ifft(v))) / n
    return out


def fourier_eval(coeffs, L, x):
    k = 2 * np.pi * np.fft.fftfreq(len(coeffs), d=L / len(coeffs))
    return np.real(np.exp(1j * np.outer(x + L / 2, k)) @ coeffs)


def lax_commutator_ok():
    import sympy as sp
    x = sp.symbols('x')
    u, f = sp.Function('u')(x), sp.Function('f')(x)
    L = lambda g: -sp.diff(g, x, 2) - u * g
    B = lambda g: -4 * sp.diff(g, x, 3) - 6 * u * sp.diff(g, x) - 3 * sp.diff(u, x) * g
    # L_t f = -u_t f and u_t = -6 u u_x - u_xxx, so L_t f = (6 u u_x + u_xxx) f
    return sp.simplify(sp.expand(B(L(f)) - L(B(f))) - (6 * u * sp.diff(u, x) + sp.diff(u, x, 3)) * f) == 0


def main():
    checks, controls = {}, {}
    checks['[B, L] = L_t symbolically for KdV u_t + 6 u u_x + u_xxx = 0'] = lax_commutator_ok()

    # 1-3. Direct scattering.
    worst_k, worst_c, worst_unit, worst_closed, worst_refl = 0.0, 0.0, 0.0, 0.0, 0.0
    expected_c = {2.0: [2.0], 6.0: [12.0, 6.0], 12.0: [60.0, 60.0, 12.0]}
    for A in (2.0, 3.0, 4.0, 6.0, 12.0):
        s = (-1 + np.sqrt(1 + 4 * A)) / 2
        q = well(A)
        kap = bound_states(q, np.sqrt(A) + 1)
        predicted = [s - j + 1 for j in range(1, int(np.ceil(s)) + 1) if s - j + 1 > 1e-12]
        worst_k = max(worst_k, np.max(np.abs(np.array(kap) - predicted)) if len(kap) == len(predicted) else np.inf)
        cs = [norming(q, k) for k in kap]
        if A in expected_c:
            worst_c = max(worst_c, np.max(np.abs(np.array(cs) - expected_c[A]) / np.array(expected_c[A])))
        for k in (0.3, 0.7, 1.5, 3.0):
            R, T = reflection_transmission(q, k)
            worst_unit = max(worst_unit, abs(abs(R) ** 2 + abs(T) ** 2 - 1))
            if abs(s - round(s)) < 1e-12:
                worst_refl = max(worst_refl, abs(R))
            else:
                worst_closed = max(worst_closed, abs(R - R_closed(s, k)))
        print(f'A = {A:4.1f}: kappa', ' '.join(f'{k:.12f}' for k in kap), '  c', ' '.join(f'{c:.10f}' for c in cs))
    print(f'flux {worst_unit:.1e}; closed-form R {worst_closed:.1e}; reflectionless |R| {worst_refl:.1e}')
    checks['bound states kappa_j = s - j + 1 for A = 2, 3, 4, 6, 12 (1e-10)'] = worst_k < 1e-10
    checks['|R|^2 + |T|^2 = 1, R = 0 for integer s, R equals the closed gamma-function form (1e-11)'] = (
        worst_unit < 1e-11 and worst_refl < 1e-11 and worst_closed < 1e-11)
    checks['reflectionless wells: norming constants 2; 12, 6; 60, 60, 12 (relative 1e-8)'] = worst_c < 1e-8

    # 4. Reconstruction at t = 0 of a reflecting well.
    A = 4.0
    s = (-1 + np.sqrt(1 + 4 * A)) / 2
    q = well(A)
    kap = bound_states(q, np.sqrt(A) + 1)
    cs = [norming(q, k) for k in kap]
    xs = np.arange(-4.0, 12.0001, 0.02)
    smin, smax = 2 * xs[0] - 1, 2 * xs[-1] + 2 * 25.0 + 1
    Rfun = lambda k: R_closed(s, k)
    xm, u0r = dyson(F_continuous(Rfun, 0.0, smin, smax), kap, cs, 0.0, xs)
    err0 = np.max(np.abs(u0r - A / np.cosh(xm) ** 2))
    _, u_bound_only = dyson(None, kap, cs, 0.0, xs)
    err_nor = np.max(np.abs(u_bound_only - A / np.cosh(xm) ** 2))
    print(f'4 sech^2: kappa {kap[0]:.10f}, {kap[1]:.10f}; c {cs[0]:.10f}, {cs[1]:.10f}; '
          f'rebuilt at t = 0 to {err0:.1e}; without reflection {err_nor:.3f}')
    checks['the Dyson formula rebuilds 4 sech^2 x from kappa, c and R (1e-6)'] = err0 < 1e-6
    controls['dropping the reflection data leaves an error above 0.1'] = err_nor > 0.1

    # 5-6. Time evolution against ETDRK4.
    L, n = 160.0, 2048
    xg = (np.arange(n) - n // 2) * L / n
    times = (0.3, 0.6, 1.0)
    ref = kdv_etdrk4(A / np.cosh(xg) ** 2, L, times, 1e-4)
    errs, peak = [], None
    for t in times:
        xm, u = dyson(F_continuous(Rfun, t, smin, smax), kap, cs, t, xs)
        errs.append(np.max(np.abs(u - fourier_eval(ref[t], L, xm))))
        peak = u.max()
    print('4 sech^2: IST against ETDRK4 at t = 0.3, 0.6, 1:', ' '.join(f'{e:.1e}' for e in errs),
          f'; peak at t = 1 {peak:.6f} against 2 kappa_1^2 = {2 * kap[0] ** 2:.6f}')
    ref6 = kdv_etdrk4(6 / np.cosh(xg) ** 2, L, (0.3,), 1e-4)
    xm, u6 = dyson(None, [2.0, 1.0], [12.0, 6.0], 0.3, xs)
    err6 = np.max(np.abs(u6 - fourier_eval(ref6[0.3], L, xm)))
    print(f'6 sech^2: two-soliton reconstruction against ETDRK4 at t = 0.3: {err6:.1e}')
    checks['evolved scattering data rebuild the ETDRK4 solution from 4 sech^2 x at t = 0.3, 0.6, 1 (1e-4)'] = max(errs) < 1e-4
    checks['the two-soliton solution from 6 sech^2 x agrees with ETDRK4 at t = 0.3 (1e-4)'] = err6 < 1e-4
    checks['the largest peak at t = 1 equals 2 kappa_1^2 (1e-3)'] = abs(peak - 2 * kap[0] ** 2) < 1e-3
    xm, uw = dyson(F_continuous(Rfun, -0.6, smin, smax), kap, [c * np.exp(-16 * k ** 3 * 0.6) for c, k in zip(cs, kap)],
                   0.6, xs)
    err_w = np.max(np.abs(uw - fourier_eval(ref[0.6], L, xm)))
    print(f'control: reversed time evolution at t = 0.6 differs by {err_w:.2f}')
    controls['reversing the time evolution of the data leaves an error above 0.1 at t = 0.6'] = err_w > 0.1

    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)


if __name__ == '__main__':
    main()
