"""Resolve a KdV critical sample with Fourier interpolation and two resolutions.

Run with Python 3, NumPy and SciPy. The periodic interval is [-12,12] and
time stops at first Hopf breaking. The initial pulse there is below 2e-10.
"""
import numpy as np
from scipy.fft import fft, ifft, fftfreq


def critical_reading(epsilon, count, step_bound, half_length=12.):
    x = np.linspace(-half_length, half_length, count, endpoint=False)
    wavenumber = 2*np.pi*fftfreq(count, 2*half_length/count)
    retain = np.abs(wavenumber) < np.pi*count/(3*half_length)
    field = fft(-1/np.cosh(x)**2) * retain
    ucrit = -2/3
    tcrit = np.sqrt(3)/8
    xcrit = -np.arctanh(1/np.sqrt(3)) - np.sqrt(3)/2
    k = 81*np.sqrt(3)/16
    nsteps = int(np.ceil(tcrit/step_bound))
    dt = tcrit/nsteps
    linear_half = np.exp(.5j*dt*epsilon**2*wavenumber**3)
    linear = linear_half**2

    def nonlinear(fourier):
        return -3j*wavenumber*retain*fft(ifft(fourier).real**2)

    for _ in range(nsteps):
        first = nonlinear(field)
        second = nonlinear(linear_half*(field+dt*first/2))
        third = nonlinear(linear_half*field+dt*second/2)
        fourth = nonlinear(linear*field+dt*linear_half*third)
        field = linear*field + dt*(linear*first+2*linear_half*(second+third)+fourth)/6

    normalized_positions = np.array([-1., 0., 1.])
    samples = xcrit + (8*k*epsilon**6)**(1/7)*normalized_positions
    phase = np.exp(1j*np.outer(samples+half_length, wavenumber))
    amplitude = (2*epsilon**2/k**2)**(1/7)
    return ((phase @ field).real/count-ucrit)/amplitude


if __name__ == "__main__":
    previous = None
    for epsilon, count in [(.064, 1024), (.032, 2048), (.016, 4096), (.008, 8192)]:
        coarse = critical_reading(epsilon, count, 1.6/count)
        fine = critical_reading(epsilon, 2*count, .8/count)
        print("epsilon / three rescaled readings / resolution change / successive max difference:",
              epsilon, fine, np.max(abs(fine-coarse)),
              None if previous is None else np.max(abs(fine-previous)))
        previous = fine
    wider = critical_reading(.008, 20480, .8/8192, half_length=15.)
    print("Change when moving boundaries from 12 to 15 at fixed spacing:",
          np.max(abs(wider-previous)))
