"""Pointwise KdV asymptotic coefficients for q(x,0)=-3 sech(x)^2/4.

Run with Python 3, NumPy and mpmath. The companion radiating_band.py
must be in the same directory. The scattering check integrates the
initial spatial equation independently of the gamma-function solution.
"""

import mpmath as mp
import numpy as np

from radiating_band import right_reflection


def coefficients(digits):
    with mp.workdps(digits):
        k = mp.mpf("0.5")
        pole = k
        lam = mp.mpf("1.5")
        reflection = (mp.gamma(1j*k) * mp.gamma(lam-1j*k) * mp.gamma(1-lam-1j*k)
                      / (mp.gamma(-1j*k) * mp.gamma(1-lam) * mp.gamma(lam)))
        nu = -mp.log(1-abs(reflection)**2) / (2*mp.pi)
        amplitude = mp.sqrt(4*nu*k/3)

        def log_flux(s):
            return 2*mp.log(abs(mp.tanh(mp.pi*s)))

        # Fold the symmetric interval about zero. The quotient at s=k is
        # removable and the logarithmic singularity at s=0 is integrable.
        def integrand(s):
            if s == k:
                return 4*mp.pi/mp.sinh(2*mp.pi*k)
            return (log_flux(s)-log_flux(k)) * (1/(s-k) - 1/(s+k))

        phase = (mp.pi/4 - mp.arg(reflection) + mp.arg(mp.gamma(1j*nu))
                 + 4*mp.atan(pole/k) - mp.quad(integrand, [0, k])/mp.pi)
        phase = mp.arg(mp.exp(1j*phase))
        return complex(reflection), float(nu), float(amplitude), float(phase)


if __name__ == "__main__":
    base = coefficients(30)
    fine = coefficients(60)
    print("R, nu, radiation amplitude, phase (mod 2π):", fine)
    print("30/60-digit maximum coefficient change:", max(abs(a-b) for a,b in zip(base, fine)))
    for length, step in [(14, .02), (18, .01)]:
        result, flux = right_reflection(np.array([.5]), -.75, length, step, center=0)
        print(f"L={length} dx={step} |R_ODE-R_exact|={abs(result[0]-fine[0]):.3e}"
              f" flux defect={flux:.3e}")
