"""Verify the KdV modulation eigenvectors against the three averaged currents.

Requires Python 3 and NumPy. All derivatives of the averaged currents are
central differences of fresh quadratures, independent of the period formula
used for the predicted characteristic speeds. Units are dimensionless.
"""

import numpy as np


def frozen_wave(branches, quadrature):
    low, middle, high = branches
    nodes, weights = np.polynomial.legendre.leggauss(quadrature)
    angle = (nodes + 1)*np.pi/4
    weights = weights*np.pi/4
    s2 = np.sin(angle)**2
    c2 = np.cos(angle)**2
    radicand = high-low*c2-middle*s2
    period = 2*np.sum(weights/np.sqrt(radicand))
    dl = np.array([np.sum(weights*factor/radicand**1.5)
                   for factor in [c2, s2, -np.ones_like(c2)]])
    wave_speed = 2*sum(branches)
    v = wave_speed - 2*period/dl
    angular_k = 2*np.pi/period
    profile = high + middle-low - 2*(middle-low)*s2
    slope_squared = 16*(middle-low)**2 * s2*c2 * radicand
    avg_weight = 2*weights/(period*np.sqrt(radicand))
    mean = np.sum(avg_weight*profile)
    m2 = np.sum(avg_weight*profile**2)
    flux2 = np.sum(avg_weight*(4*profile**3-3*slope_squared))
    densities = np.array([mean, m2, angular_k])
    fluxes = np.array([3*m2, flux2, angular_k*wave_speed])
    return densities, fluxes, v


def check(quadrature, increment):
    branches = np.array([0., .5, 1.])
    densities, _, speeds = frozen_wave(branches, quadrature)
    defects = []
    for j in range(3):
        direction = increment*np.eye(3)[j]
        dplus, fplus, _ = frozen_wave(branches+direction, quadrature)
        dminus, fminus, _ = frozen_wave(branches-direction, quadrature)
        discrepancy = ((fplus-fminus) - speeds[j]*(dplus-dminus))/(2*increment)
        defects.extend(abs(discrepancy))
    print(f"N={quadrature} h={increment:g} mean,k={densities[[0,2]]}"
          f" speeds={speeds} max eigenvector defect={max(defects):.3e}")


if __name__ == "__main__":
    check(32, 1e-4)
    check(64, 1e-5)
