"""Two-sided focusing Zakharov–Shabat matching for sampled complex envelopes.

NumPy and SciPy. Sampled values are held constant on time bins of equal width.
The Jost columns match after the first half of the bins, at zero for even grids.
Continuum checks and pole checks use the same
normalization but independent analytic answers for the clean pulse.
"""
from math import pi
import numpy as np
from scipy.optimize import root


def samples(T, h, center=0., phase=0., ramp=0., noise=0.):
    count=2*round(T/h)
    h=2*T/count
    x=-T+(np.arange(count)+.5)*h
    q=np.exp(1j*(phase+ramp*x))/np.cosh(x-center)
    rng=np.random.default_rng(37)
    offsets=rng.uniform(0,2*pi,8)
    modes=np.exp(1j*(np.arange(1,9)[:,None]*x[None,:]/3+offsets[:,None]))
    q+=noise*np.exp(-(x/6)**2)*np.sum(modes,axis=0)/np.sqrt(8)
    return q,h


def jost(q,h,lam):
    z=np.atleast_1d(np.asarray(lam,dtype=complex))
    T=len(q)*h/2
    left=np.array([np.exp(1j*z*T),np.zeros_like(z)])
    right=np.array([np.zeros_like(z),np.exp(1j*z*T)])
    def step(y,value,dt):
        s=np.sqrt(z*z+abs(value)**2)
        C=np.cos(dt*s)
        S=dt*np.sinc(dt*s/pi)
        a,b=y
        return np.array([C*a+S*(-1j*z*a+value*b),
                         C*b+S*(-value.conjugate()*a+1j*z*b)])
    for value in q[:len(q)//2]:
        left=step(left,value,h)
    for value in q[len(q)//2:][::-1]:
        right=step(right,value,-h)
    return left[0]*right[1]-left[1]*right[0], left, right


def eigen(q,h,seed):
    def residual(pair):
        a=jost(q,h,complex(*pair))[0][0]
        return [a.real,a.imag]
    result=root(residual,[seed.real,seed.imag],tol=1e-11)
    z=complex(*result.x)
    a,left,right=jost(q,h,z)
    if not np.isfinite(z) or z.imag <= 0 or not np.isfinite(a[0]) or abs(a[0])>1e-10:
        raise ArithmeticError(f"Upper-half-plane root did not pass its residual check: {result.message}")
    b=np.vdot(right,left)/np.vdot(right,right)
    eps=1e-5
    pair=jost(q,h,[z+eps,z-eps])[0]
    derivative=(pair[0]-pair[1])/(2*eps)
    return z,b,b/derivative


def winding(q,h,center,radius,n):
    circle=center+radius*np.exp(2j*pi*np.arange(n)/n)
    values=jost(q,h,circle)[0]
    angles=np.angle(np.roll(values,-1)/values)
    return round(sum(angles)/(2*pi)),min(abs(values)),max(abs(angles))


def noise_response():
    """Predict the displacement of a simple sampled root under one smooth perturbation."""
    q, h = samples(12, .05, center=.8, phase=.4, ramp=.6)
    noisy, _ = samples(12, h, center=.8, phase=.4, ramp=.6, noise=1)
    direction = noisy - q
    pole, _, _ = eigen(q, h, -.3 + .5j)
    eps = 1e-5
    a_plus, a_minus = jost(q, h, [pole + eps, pole - eps])[0]
    a_lambda = (a_plus - a_minus) / (2 * eps)
    a_plus = jost(q + eps * direction, h, pole)[0][0]
    a_minus = jost(q - eps * direction, h, pole)[0][0]
    a_noise = (a_plus - a_minus) / (2 * eps)
    slope = -a_noise / a_lambda
    print("Fixed-grid pole sensitivity to the seed-37 field:", slope)
    errors = []
    for amplitude in (.01, .005, .0025):
        observed = eigen(q + amplitude * direction, h, pole)[0]
        remainder = abs(observed - (pole + amplitude * slope))
        errors.append(remainder)
        print("Noise amplitude, linear prediction error:", amplitude, remainder)
    assert all(3.5 < a/b < 4.5 for a, b in zip(errors, errors[1:]))


def propagation_check():
    """Test eigenvalue invariance and the signed norming evolution on a breathing pulse."""
    z, ramp, T = .15, .4, 14
    targets = [-ramp/2 + .5j, -ramp/2 + 1.5j]
    errors = []
    for h in (.05, .025):
        tau = -T + (np.arange(round(2*T/h)) + .5) * h
        launch = 2*np.exp(1j*ramp*tau)/np.cosh(tau)
        x = tau - 2*ramp*z
        output = (4*np.exp(1j*(ramp*tau-ramp**2*z+z))
                  * (np.cosh(3*x)+3*np.exp(8j*z)*np.cosh(x))
                  / (np.cosh(4*x)+4*np.cosh(2*x)+3*np.cos(8*z)))
        max_compensated = 0.
        for target in targets:
            _, b_in, _ = eigen(launch, h, target)
            _, b_out, _ = eigen(output, h, target)
            ratio = b_out / b_in
            law = np.exp(4j*target**2*z)
            compensated = abs(ratio / law - 1)
            reversed_sign = abs(ratio * law - 1)
            max_compensated = max(max_compensated, compensated)
            print("h, target, norming ratio, compensated error, reversed-sign error:",
                  h, target, ratio, compensated, reversed_sign)
            assert compensated < .003 and reversed_sign > .2
        errors.append(max_compensated)
    assert 3.5 < errors[0]/errors[1] < 4.5


def single_bin_check():
    """Test the analytically regular exponential at a repeated bin eigenvalue."""
    h, q = .7, np.array([.6 + .8j])
    # U squared vanishes at i |q|. The exponential is exactly I + h U.
    z = 1j * abs(q[0])
    actual = jost(q, h, z)[0][0]
    expected = np.exp(1j*z*h) * (1 - 1j*z*h)
    assert abs(actual - expected) < 1e-14


def phase_step_check():
    """Two exact half-bin propagators and a uniform-box pole on the imaginary axis."""
    amplitude = 3*pi/4
    uniform = np.array([amplitude, amplitude])
    stepped = np.array([amplitude, -amplitude])
    for field, area in ((uniform, amplitude), (stepped, 0.)):
        a, left, right = jost(field, .5, 0.)
        assert abs(a[0] - np.cos(area)) < 1e-14
        assert abs(np.vdot(right, left) + np.sin(area)) < 1e-14
    z, _, _ = eigen(uniform, .5, 1j)
    assert abs(z - 1.12666382354348j) < 1e-12
    for kappa in (.5, z.imag, amplitude, 3.):
        k = np.sqrt(complex(amplitude**2 - kappa**2))
        c, s = np.cos(k/2), .5*np.sinc(k/(2*pi))
        expected = np.exp(-kappa)*((c+kappa*s)**2 + (amplitude*s)**2)
        observed = jost(stepped, .5, 1j*kappa)[0][0]
        assert abs(observed-expected) < 1e-13 and observed.real > 0
    print("Uniform-box pole; opposite half-pulse phases remove this axis zero:", z)


def reconstructed(x,z,eigenvalue,b):
    xi,eta=eigenvalue.real,eigenvalue.imag
    center=np.log(abs(b))/(2*eta)
    phase=np.angle(-b.conjugate())
    v=-2*xi
    return (2*eta/np.cosh(2*eta*(x-center-2*v*z))
            * np.exp(1j*(v*x+(4*eta**2-v*v)*z+phase)))


def inverse_check():
    T=12.
    q,h=samples(T,.05,center=.8,phase=.4,ramp=.6)
    x=-T+(np.arange(len(q))+.5)*h
    pole,b,_=eigen(q,h,-.3+.5j)
    for label,norming in (("matched",b),("reciprocal modulus",b/abs(b)**2)):
        fitted=reconstructed(x,0,pole,norming)
        print(label,"center and complex relative L2 error:",np.log(abs(norming))/(2*pole.imag),
              np.linalg.norm(fitted-q)/np.linalg.norm(q))
    for delta in (.04,.02,.01):
        def field(x,z):
            return reconstructed(x,z,pole,b)
        z=.3
        points=np.linspace(-6,6,81)
        base=field(points,z)
        dz=(field(points,z+delta)-field(points,z-delta))/(2*delta)
        dxx=(field(points+delta,z)-2*base+field(points-delta,z))/delta**2
        print("Derivative step, NLS sup residual:",delta,max(abs(1j*dz+dxx+2*abs(base)**2*base)))
    for T,h in ((6,.05),(12,.1),(12,.05),(12,.025),(18,.025)):
        q,h=samples(T,h,center=.8,phase=.4,ramp=.6,noise=.01)
        print("One common noise field: T, h, pole:",T,h,eigen(q,h,-.3+.5j)[0])


def checks():
    for T,h in [(6,.1),(12,.1),(12,.05),(12,.025),(18,.025)]:
        q,h=samples(T,h)
        z,b,res=eigen(q,h,.5j)
        a,left,right=jost(q,h,.7)
        b_real=np.vdot(right,left)  # unit-normalized orthogonal basis at real lambda
        print("T, h, pole, b, residue, continuum a error, |b_real|, flux error:",
              T,h,z,b,res,abs(a[0]-(.7-.5j)/(.7+.5j)),abs(b_real),
              abs(abs(a[0])**2+abs(b_real)**2-1))
    q,h=samples(12,.05,center=.8,phase=.4)
    for n in (32,64):
        for center in (.5j,.95j):
            print("Count, min |a|, max phase increment:",n,center,winding(q,h,center,.21,n))
    print("Shift and phase:",eigen(q,h,.5j))
    for ramp,noise in [(0,0),(.6,0),(.6,.01)]:
        q,h=samples(12,.05,center=.8,phase=.4,ramp=ramp,noise=noise)
        print("Ramp, noise, pole data:",ramp,noise,eigen(q,h,-ramp/2+.5j))


if __name__=="__main__":
    single_bin_check()
    phase_step_check()
    checks()
    inverse_check()
    noise_response()
    propagation_check()
