"""High-precision substitution checks for three NLS reductions and a branch point.

Run with Python 3 and mpmath. Differentiation uses function evaluations, without
inserting any analytic ODE or field identity used in the manuscripts.
"""
import mpmath as mp


def bright(x, t):
    xi, eta, x0 = mp.mpf("0.5"), mp.mpf("0.8"), mp.mpf("0.3")
    return (2*eta*mp.sech(2*eta*(x+4*xi*t-x0))
            * mp.exp(1j*(-2*xi*x+4*(eta**2-xi**2)*t)))


def dark(x, t):
    amplitude, nu = mp.mpf("1.2"), mp.mpf("0.5")
    beta = mp.sqrt(1-nu**2)
    return amplitude*mp.exp(-2j*amplitude**2*t)*(
        beta*mp.tanh(amplitude*beta*(x-2*amplitude*nu*t))+1j*nu)


def breather(x, t, b):
    z = x+2j*b*t
    h = mp.sqrt(1-b*b)
    cosine = mp.cos(h*z)
    sine = (1+b)*mp.sin(h*z)/h if h else 2*z
    w1, w2 = cosine+sine, cosine-sine
    return -mp.exp(2j*t)*(1+4*b*w1*w2.conjugate()/(abs(w1)**2+abs(w2)**2))


def peregrine(x, t):
    return mp.exp(2j*t)*(1-4*(1+4j*t)/(1+4*x*x+16*t*t))


def reverse_space(x, t):
    kappa, nu = mp.mpf("1.2"), mp.mpf("0.4")
    return mp.exp(-nu*x+1j*(nu**2+kappa**2)*t)*kappa*mp.sech(kappa*(x-2j*nu*t))


def residual(field, x, t, sign, nonlocal_field=False):
    spatial = mp.diff(lambda point: field(point, t), x, 2)
    temporal = mp.diff(lambda time: field(x, time), t)
    partner = field(-x if nonlocal_field else x, t).conjugate()
    return abs(1j*temporal + spatial + 2*sign*field(x,t)**2*partner)


if __name__ == "__main__":
    mp.mp.dps = 50
    points = [(mp.mpf(x),mp.mpf(t)) for x in ["-1","0","0.4"] for t in ["-0.4","0","0.7"]]
    fields = [
        ("bright",bright,1,False), ("dark",dark,-1,False),
        ("space-periodic",lambda x,t: breather(x,t,mp.mpf("0.7")),1,False),
        ("time-periodic",lambda x,t: breather(x,t,mp.mpf("1.2")),1,False),
        ("rational",peregrine,1,False), ("reverse-space",reverse_space,1,True)
    ]
    for name, field, sign, nonlocal_field in fields:
        norm = max(residual(field,x,t,sign,nonlocal_field) for x,t in points)
        print(name, "maximum sampled equation residual", mp.nstr(norm,5))
        assert norm < mp.mpf("1e-44")
    difference = max(abs(breather(x,t,1)-peregrine(x,t)) for x,t in points)
    print("branch-point projector vs rational expression",mp.nstr(difference,5))
    assert difference < mp.mpf("1e-44")
