"""Squared KdV remainder after subtracting the fast outgoing soliton.

Run with Python 3.9 or later. Normalized units, speeds 1 and 4, cut x=2t.
The quadrature uses the exact two-soliton field, without a PDE time step.
"""
from math import cosh, exp, fsum


def fast_pulse(x, time):
    return 2 / cosh(x - 4 * time) ** 2


def remainder(x, time):
    """Evaluate 2*d_x^2 log(tau/tau_fast) directly."""
    slow_exponential = exp(x - time)
    fast_fraction = 1 / (1 + exp(-2 * (x - 4 * time)))
    product = fast_fraction * (1 - fast_fraction)
    g = 1 + 8 * fast_fraction
    g_prime = 16 * product
    g_second = 32 * product * (1 - 2 * fast_fraction)
    numerator = slow_exponential * (g + g_second - 2 * g_prime)
    numerator += g * g_second - g_prime ** 2
    return 2 * numerator / (slow_exponential + g) ** 2


def squared_remainder(left, right, time, spacing):
    """Composite Simpson quadrature using an even number of intervals."""
    pairs = max(1, round((right - left) / (2 * spacing)))
    step = (right - left) / (2 * pairs)
    values = (remainder(left + i * step, time) ** 2 for i in range(1, 2 * pairs))
    interior = fsum((4 if i % 2 else 2) * y for i, y in enumerate(values, 1))
    ends = remainder(left, time) ** 2 + remainder(right, time) ** 2
    return step * (ends + interior) / 3


def norms(time, padding=32, spacing=1 / 16):
    right = 4 * time + padding
    return (squared_remainder(-padding, right, time, spacing),
            squared_remainder(2 * time, right, time, spacing))


if __name__ == "__main__":
    print("time    whole-line squared norm    x>=2t squared norm")
    for time in (2, 4, 8):
        coarse = norms(time)
        fine = norms(time, padding=48, spacing=1 / 32)
        assert max(abs(a - b) for a, b in zip(coarse, fine)) < 1e-7
        print(f"{time:4d}    {fine[0]:22.12g}    {fine[1]:18.12g}")
