"""Finite measurements for the nonlinear-wave models and learning examples.

Run with Python 3, NumPy, and SciPy.
"""
from math import atanh, cos, cosh, exp, log, pi, sqrt, tanh
import numpy as np
from scipy.integrate import quad, solve_ivp
from scipy.special import airy


def model_measurements():
    magnitudes = [2*quad(lambda x: 1/(1+x*x/4),0,np.inf,weight="cos",wvar=k,
                         epsabs=1e-11)[0] for k in (1,2)]
    assert abs(magnitudes[1]/magnitudes[0]-exp(-2)) < 2e-13
    print("Benjamin–Ono Fourier magnitudes:",magnitudes)

    # Independent component norms and overlap in the fixed polarization basis.
    entries = [quad(lambda x: exp(-x*x), -10, 10)[0],
               quad(lambda x: sqrt(2)*x*exp(-x*x), -10, 10)[0],
               quad(lambda x: 2*x*x*exp(-x*x), -10, 10)[0]]
    assert np.allclose(entries,[sqrt(pi),0,sqrt(pi)],rtol=1e-13,atol=1e-15)
    print("Polarization matrix entries C11, C12, C22:",entries)

    for k in [.5,1.]:
        w2 = k*k*(k*k-.5)
        ivp=solve_ivp(lambda t,y: [y[1],-w2*y[0]], (0,2),[1,0],rtol=1e-12,atol=1e-13)
        prediction=cosh(2*sqrt(-w2)) if w2<0 else cos(2*sqrt(w2))
        assert abs(ivp.y[0,-1]-prediction)<1e-12
        print("Boussinesq wave number and measured amplitude at time two:",k,ivp.y[0,-1])

    for drift in [-2.,0.,3.5]:
        def omega(k):
            return k-k*k/tanh(k)+drift*k
        difference=omega(2)-2*omega(1)
        assert abs(atanh(-difference/2)-1)<3e-15
        print("ILW drift, difference and recovered depth:",drift,difference,atanh(-difference/2))

    def triad(t,y):
        x,z,w = y
        return (z*w,x*w,-x*z)
    def depleted(t,y):
        return y[2]
    depleted.terminal=True
    orbit=solve_ivp(triad,(0,1),[1,1,1],rtol=2e-12,atol=1e-13,events=depleted)
    time=orbit.t_events[0][0]
    assert abs(time-atanh(1/sqrt(2))/sqrt(2)) < 2e-12
    assert np.allclose(orbit.y_events[0][0]**2,[2,2,0],rtol=2e-12)
    print("Three-wave depletion time and intensities:",time,orbit.y_events[0][0]**2)


def learning_measurements():
    # Right Jost tail of the level -1. The unnormalized wave is sqrt(sech(2x)).
    norm = quad(lambda x: 1/(2*cosh(2*x)), -40,40)[0]
    area=quad(lambda x: 3/cosh(2*x)**2, -40,40)[0]
    assert abs(1/norm-4/pi)<1e-12 and abs(area-3)<1e-12
    print("Bound coefficient, well area, matched one-pole center:",1/norm,area,.5*log(2/pi))

    # Fourier transform of the normalized Gaussian is exp(-p²). Its
    # derivative excites the derivative of the Airy Green function.
    def scaled_signal(t, derivative):
        scale=(3*t)**(1/3)
        return quad(lambda y: exp(-y*y/4)/sqrt(4*pi)*airy(-y/scale)[derivative],-14,14)[0]
    for t in [10,100,1000]:
        print("Airy time, scaled Gaussian and derivative signals:",t,
              scaled_signal(t,0),scaled_signal(t,1))
    assert abs(scaled_signal(1000,0)-airy(0)[0]) < 1e-5
    assert abs(scaled_signal(1000,1)-airy(0)[1]) < .002


if __name__ == "__main__":
    model_measurements()
    learning_measurements()
