"""Compare Fourier aliasing and temporal order on periodic KdV solutions.

Requires NumPy and SciPy. Fourier coefficients are divided by the grid size.
Nyquist modes are projected out of the comparison spaces.
"""
from math import pi
import numpy as np
from scipy.special import ellipj, ellipk


def symbols(n,length):
    modes = np.rint(np.fft.fftfreq(n)*n).astype(int)
    k = modes*2*pi/length
    return modes,k


def derivative(v,k,pad):
    n = len(v)
    size = 3*n//2 if pad else n
    indices = np.rint(np.fft.fftfreq(n)*n).astype(int)%size
    buffer = np.zeros(size, complex)
    buffer[indices] = v
    u = np.fft.ifft(buffer).real * size
    result = -3j*k*(np.fft.fft(u*u)/size)[indices]
    result[n//2]=0
    return result


def stepper(k,h,pad):
    z = 1j*k**3*h
    E, E2 = np.exp(z), np.exp(z/2)
    # Full circular mean: imaginary coefficients must survive for KdV.
    w = z[:,None]+np.exp(2j*pi*(np.arange(48)+0.5)/48)
    Q=h*np.mean(np.expm1(w/2)/w,axis=1)
    p1=np.expm1(w)/w
    p2=(p1-1)/w
    p3=(p2-0.5)/w
    f1=h*np.mean(p1-3*p2+4*p3,axis=1)
    f2=h*np.mean(p2-2*p3,axis=1)
    f3=h*np.mean(4*p3-p2,axis=1)
    def step(v):
        Nv=derivative(v,k,pad)
        a=E2*v+Q*Nv
        Na=derivative(a,k,pad)
        b=E2*v+Q*Na
        Nb=derivative(b,k,pad)
        c=E2*a+Q*(2*Nb-Nv)
        return E*v+f1*Nv+2*f2*(Na+Nb)+f3*derivative(c,k,pad)
    return step


def evolve(u,length,time,steps,pad=True):
    n=len(u)
    _,k=symbols(n,length)
    v=np.fft.fft(u)/n
    v[n//2]=0
    step=stepper(k,time/steps,pad)
    for _ in range(steps):
        v=step(v)
    return np.fft.ifft(v).real*n


def alias():
    n=24
    x=2*pi*np.arange(n)/n
    u=np.cos(9*x)
    t=0.005
    exact=np.cos(9*x+729*t)
    for pad in (False,True):
        value=evolve(u,2*pi,t,100,pad)
        mode=np.fft.fft(value)/n
        print("Padding, spurious mode-6 magnitude, sup error:",pad,abs(mode[6]),max(abs(value-exact)))


def order():
    m=0.8
    length=2*ellipk(m)
    t=0.2
    speed=4*(2*m-1)
    def data(x):
        return 2*m*ellipj(x,m)[1]**2
    n=96
    x=np.arange(n)*length/n
    for perturb in (False,True):
        u=data(x)
        if perturb:
            u+=0.06*np.cos(4*pi*x/length)
            ref=evolve(u,length,t,2048)
            print("Perturbed reference refinement:",max(abs(ref-evolve(u,length,t,1024))))
        else:
            ref=data(x-speed*t)
        errors = []
        for steps in (16,32,64,128,256):
            v=evolve(u,length,t,steps)
            errors.append(np.linalg.norm(v-ref)/np.linalg.norm(ref))
        print("Perturbed, relative L2 errors:",perturb,errors)


def galilean_shift():
    parameter, background, time = 0.8, 0.25, 0.2
    length = 2*ellipk(parameter)
    wave_speed = 4*(2*parameter-1)
    first_k = 2*pi/length
    displacement = 6*background*time

    def profile(x):
        return 2*parameter*ellipj(x, parameter)[1]**2

    grids = (12, 16, 24, 32, 48)
    for count in grids:
        x = np.arange(count)*length/count
        initial = profile(x)+background
        exact_wave = profile(x-wave_speed*time-displacement)
        computed = evolve(initial, length, time, 1024)
        error = np.linalg.norm(computed-background-exact_wave)/np.linalg.norm(exact_wave)
        print("Nodes, boosted wave relative error at 1024 steps:", count, error)
        assert abs(computed.mean()-initial.mean()) < 2e-14

    # Compare the boosted and unboosted first harmonics on the finest grid.
    base = evolve(profile(x), length, time, 1024)
    first_mode_ratio = np.fft.rfft(computed)[1]/np.fft.rfft(base)[1]
    np.testing.assert_allclose(first_mode_ratio, np.exp(-1j*first_k*displacement),
                               rtol=0, atol=4e-12)
    print("Additional displacement from the first harmonic:", -np.angle(first_mode_ratio)/first_k)
    refined = evolve(initial, length, time, 2048)
    refined_error = np.linalg.norm(refined-background-exact_wave)/np.linalg.norm(exact_wave)
    assert 10 < error/refined_error < 22
    print("Boosted wave relative error at 48 nodes and 2048 steps:", refined_error)


if __name__ == "__main__":
    alias()
    order()
    galilean_shift()
