"""Checks for the Library article "Solitons in optical fibers".

Dimensionless focusing NLS of the chapter: i q_z + q_tt + 2|q|^2 q = 0 with tau = T/T0, z = Z/(2 L_D), q = A/sqrt(P*),
P* = |beta2|/(gamma T0^2). Third-order dispersion adds - i delta q_ttt with delta = beta3/(3|beta2| T0).
Zakharov-Shabat problem v' = [[-i lam, q], [-conj(q), i lam]] v; bound states are eigenvalues lam with Im lam > 0, found
here by Fourier collocation of lam v = [[i d/dtau, -i q], [-i conj(q), -i d/dtau]] v.
Checks:
  1. Satsuma-Yajima: A sech(tau) has the bound states lam = i(A - j + 1/2) for j < A + 1/2, for six amplitudes (1e-8).
  2. Split-step propagation of 2 sech(tau) matches the exact breather at z = pi/8, with second-order convergence.
  3. N sech(tau), N = 2, 3, 4, returns to its initial modulus after z = pi/4 (fourth-order steps, 1e-5).
  4. After z = 0.6 the propagated 3 sech(tau) still has the bound states i/2, 3i/2, 5i/2 (1e-6).
  5. With delta = 0.025, 0.035 and 0.05, the first pulse to leave 3 sech(tau) has a peak within 3% of 5 = 2 Im(5i/2), the
     amplitude of the largest bound state, and a finer grid changes it by less than 2%.
Controls: A = 0.45 has no bound state and its peak decays; with delta = 0.05 the bound states move by more than 1e-2.
Run with Python 3 and NumPy:  python3 fiber_soliton_check.py   (about a minute)
"""
import numpy as np

W1 = 1 / (2 - 2 ** (1 / 3))           # Yoshida weights for a fourth-order composition of Strang steps
W0 = -2 ** (1 / 3) / (2 - 2 ** (1 / 3))


def grid(length, n):
    tau = (np.arange(n) - n // 2) * (length / n)
    k = 2 * np.pi * np.fft.fftfreq(n, d=length / n)
    return tau, k


def bound_states(q, length, max_real=5.0, min_imag=0.05):
    """Zakharov-Shabat eigenvalues in the upper half plane by Fourier collocation (spurious edge modes discarded)."""
    n = len(q)
    k = 2 * np.pi * np.fft.fftfreq(n, d=length / n)
    D = np.fft.ifft(1j * k[:, None] * np.fft.fft(np.eye(n), axis=0), axis=0)
    Q = np.diag(q)
    ev = np.linalg.eigvals(np.block([[1j * D, -1j * Q], [-1j * np.conj(Q), -1j * D]]))
    keep = ev[(ev.imag > min_imag) & (np.abs(ev.real) < max_real)]
    return keep[np.argsort(-keep.imag)]


def strang(q, k, z, dz, delta=0.0):
    steps = int(round(z / dz))
    dz = z / steps
    half = np.exp(-1j * (k ** 2 + delta * k ** 3) * dz / 2)
    for _ in range(steps):
        q = np.fft.ifft(half * np.fft.fft(q))
        q = q * np.exp(2j * np.abs(q) ** 2 * dz)
        q = np.fft.ifft(half * np.fft.fft(q))
    return q


def yoshida(q, k, z, dz, delta=0.0):
    steps = int(round(z / dz))
    dz = z / steps
    half = {w: np.exp(-1j * (k ** 2 + delta * k ** 3) * w * dz / 2) for w in (W1, W0)}
    for _ in range(steps):
        for w in (W1, W0, W1):
            q = np.fft.ifft(half[w] * np.fft.fft(q))
            q = q * np.exp(2j * np.abs(q) ** 2 * w * dz)
            q = np.fft.ifft(half[w] * np.fft.fft(q))
    return q


def breather(z, tau):
    """Satsuma-Yajima two-soliton bound state with initial value 2 sech(tau)."""
    return (4 * np.exp(1j * z) * (np.cosh(3 * tau) + 3 * np.exp(8j * z) * np.cosh(tau))
            / (np.cosh(4 * tau) + 4 * np.cosh(2 * tau) + 3 * np.cos(8 * z)))


def pulses(tau, q, threshold=0.3, separation=1.5):
    """Peak positions and heights of separated pulses, largest first."""
    a = np.abs(q)
    found = []
    for i in np.argsort(a)[::-1]:
        if a[i] < threshold:
            break
        if all(abs(tau[i] - tau[j]) > separation for j in found):
            found.append(i)
    return [(tau[i], a[i]) for i in found]


def window_bound_states(tau, q, center, half_width=4.0):
    mask = np.abs(tau - center) < half_width
    return bound_states(q[mask], (tau[1] - tau[0]) * mask.sum())


def main():
    checks, controls = {}, {}

    # 1. Satsuma-Yajima spectrum.
    tau, k = grid(160.0, 1024)
    worst = 0.0
    for A in (0.75, 1.0, 1.3, 2.0, 2.3, 3.0):
        found = bound_states(A / np.cosh(tau), 160.0)
        predicted = np.array([1j * (A - j + 0.5) for j in range(1, int(np.ceil(A - 0.5)) + 1)])
        ok = len(found) == len(predicted)
        err = np.max(np.abs(found - predicted)) if ok else np.inf
        worst = max(worst, err)
        print(f'A = {A:4.2f}: bound states', ' '.join(f'{x.imag:.10f}i' for x in found), f' (largest error {err:.1e})')
    checks['A sech(tau) has bound states i(A - j + 1/2), j < A + 1/2, for A = 0.75 ... 3 (1e-8)'] = worst < 1e-8
    none = bound_states(0.45 / np.cosh(tau), 160.0)
    tau2, k2 = grid(160.0, 4096)
    peak = np.max(np.abs(strang(0.45 / np.cosh(tau2), k2, 5.0, 2e-3)))
    print(f'A = 0.45: {len(none)} bound states; peak after z = 5: {peak:.4f}')
    controls['A = 0.45 has no bound state and its peak falls below 0.25 by z = 5'] = len(none) == 0 and peak < 0.25

    # 2. The two-soliton breather against the exact solution.
    tau, k = grid(40.0, 1024)
    errors = [np.max(np.abs(strang(2 / np.cosh(tau), k, np.pi / 8, dz) - breather(np.pi / 8, tau)))
              for dz in (2e-3, 1e-3, 5e-4)]
    ratios = [errors[0] / errors[1], errors[1] / errors[2]]
    print('breather at z = pi/8, Strang steps 2e-3, 1e-3, 5e-4: errors', ' '.join(f'{e:.2e}' for e in errors),
          ' ratios', ' '.join(f'{r:.3f}' for r in ratios))
    checks['2 sech(tau) matches the exact breather, with second-order convergence (ratios 3.9-4.1, error < 3e-4)'] = (
        all(3.9 < r < 4.1 for r in ratios) and errors[-1] < 3e-4)

    # 3. Common period pi/4 of the integer-order solitons.
    tau, k = grid(40.0, 4096)
    period = {}
    for N, dz in ((2, 1e-3), (3, 2.5e-4), (4, 1.25e-4)):
        q0 = N / np.cosh(tau)
        period[N] = np.max(np.abs(np.abs(yoshida(q0, k, np.pi / 4, dz)) - np.abs(q0)))
    print('return to |q(0)| after z = pi/4:', ', '.join(f'N = {N}: {e:.1e}' for N, e in period.items()))
    checks['N sech(tau), N = 2, 3, 4, returns to its initial modulus after z = pi/4 (1e-5)'] = max(period.values()) < 1e-5

    # 4. Conservation of the discrete spectrum, and its failure with third-order dispersion.
    tau, k = grid(40.0, 1024)
    target = np.array([2.5j, 1.5j, 0.5j])
    after = bound_states(yoshida(3 / np.cosh(tau), k, 0.6, 2.5e-4), 40.0)
    drift = np.max(np.abs(after - target)) if len(after) == 3 else np.inf
    tod = bound_states(yoshida(3 / np.cosh(tau), k, 0.6, 2.5e-4, delta=0.05), 40.0)
    tod_drift = np.max(np.abs(tod - target)) if len(tod) == 3 else np.inf
    print('bound states of 3 sech after z = 0.6:', ' '.join(f'{x.real:+.2e}{x.imag:+.9f}i' for x in after),
          f'(largest change {drift:.1e}); with delta = 0.05:',
          ' '.join(f'{x.real:+.4f}{x.imag:+.4f}i' for x in tod), f'(largest change {tod_drift:.3f})')
    checks['propagation keeps the bound states i/2, 3i/2, 5i/2 of 3 sech(tau) (1e-6 at z = 0.6)'] = drift < 1e-6
    controls['with delta = 0.05 the bound states move by more than 1e-2 by z = 0.6'] = tod_drift > 1e-2

    # 5. Fission under third-order dispersion.
    leads = {}
    tau, k = grid(160.0, 8192)
    for delta, z in ((0.05, 4.0), (0.035, 5.0), (0.025, 7.0)):
        q = yoshida(3 / np.cosh(tau), k, z, 2e-3, delta=delta)
        found = pulses(tau, q, threshold=0.6, separation=2.0)
        leads[delta] = found[0]
        print(f'delta = {delta}, z = {z}: pulses (position, peak)', ', '.join(f'({a:.2f}, {b:.4f})' for a, b in found[:3]))
        if delta == 0.05:
            lam = window_bound_states(tau, q, found[0][0])
            print(f'  NLS bound state of the leading pulse: {lam[0].real:+.3f}{lam[0].imag:+.3f}i '
                  '(its carrier has moved, so it is no longer an NLS soliton)')
    taus, ks = grid(240.0, 16384)
    fine = pulses(taus, yoshida(3 / np.cosh(taus), ks, 4.0, 1e-3, delta=0.05), threshold=0.6, separation=2.0)[0]
    print(f'delta = 0.05 on a finer grid (window 240, 16384 points, step 1e-3): leading peak {fine[1]:.4f}')
    checks['delta = 0.025, 0.035, 0.05: the first pulse to leave 3 sech(tau) has a peak within 3% of 5; a finer grid moves it < 2%'] = (
        all(abs(p[1] - 5) < 0.15 for p in leads.values()) and abs(fine[1] - leads[0.05][1]) < 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()
