"""Measure the fast KdV crest at the two separated ends of a collision.

Run with Python, NumPy and SciPy. The four tau terms have spectral
parameters k_fast=2 and k_slow=1 with both phase constants zero.
"""
import numpy as np
from scipy.optimize import brentq
from scipy.special import softmax


def fast_peak(time, asymptotic_center):
    slopes = np.array([0., 4., 2., 6.])

    def gradient(position):
        fast = 4 * (position - 16*time)
        slow = 2 * (position - 4*time)
        weights = softmax([0, fast, slow, fast + slow - np.log(9)])
        centered = slopes - weights @ slopes
        return 2 * (weights @ centered**3)

    # The derivative changes from positive to negative across a local maximum.
    left, right = asymptotic_center - 0.15, asymptotic_center + 0.15
    assert gradient(left) > 0 > gradient(right)
    return brentq(gradient, left, right, xtol=2e-14)


if __name__ == "__main__":
    exact_shift = np.log(3) / 2
    for half_window in (0.2, 0.35, 0.5, 1.0):
        before = fast_peak(-half_window, -16*half_window)
        after = fast_peak(half_window, 16*half_window + exact_shift)
        shift = after - before - 32*half_window
        error = abs(shift - exact_shift)
        print(f"T={half_window:g}, shift={shift:.11f}, error={error:.3e}, "
              f"mean speed={(after-before)/(2*half_window):.8f}")
    assert error < 5e-12
