"""Synthetic fiber checks in Python 3 with NumPy and SciPy.

For a standalone download, save the two-sided solver beside this file:
    /computations/scattering/optical_pulse.py
Then run python3 fiber_pulses.py. The site checkout locates the solver in the
neighboring scattering directory. All signals and calibrations are synthetic.
"""
from pathlib import Path
import sys
import numpy as np
from scipy.ndimage import gaussian_filter1d
from scipy.optimize import least_squares

# Reuse the site's two-sided Jost-column normalization and matching implementation.
sys.dont_write_bytecode = True
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "scattering"))
from optical_pulse import eigen


def collision():
    """Known separated asymptotes, bandwidth-limited intensity, independent reference."""
    rng = np.random.default_rng(731)
    t = np.arange(-22, 22.05, .05)
    windows = np.r_[[-6.,-5.,-4.,-3.],[3.,4.,5.,6.]]
    def center(data, estimate):
        mask = abs(t-estimate) < 3.5
        def residual(params):
            height, pos, background = params
            templ = gaussian_filter1d(1/np.cosh(t-pos)**2, 3)
            return (height*templ+background-data)[mask]
        return least_squares(residual, [1,estimate,0]).x[1]
    estimates = []
    for _ in range(20):
        differences = []
        for z in windows:
            delta = np.sign(z)*np.log(2)/2
            pair = sum(1/np.cosh(t-sign*(2*z+delta))**2 for sign in (-1,1))
            ref = 1/np.cosh(t-2*z)**2
            records = [gaussian_filter1d(d, 3)+.015*rng.standard_normal(t.size)
                       for d in (pair, ref)]
            differences.append(center(records[0],2*z)-center(records[1],2*z))
        left = np.polyfit(windows[:4], differences[:4], 1)
        right = np.polyfit(windows[4:], differences[4:], 1)
        estimates.append(right[1]-left[1])
    print(f"Synthetic fast shift (T0 units), mean and single-shot SD: "
          f"{np.mean(estimates):.7f}, {np.std(estimates,ddof=1):.7f}")


def perturbation(n, steps, loss, d3):
    """Symmetric split step with physical optical convention exp(-i Omega T)."""
    t = np.arange(n)*32/n-16
    k = 2*np.pi*np.fft.fftfreq(n, 32/n)  # spatial FFT uses exp(+i*k*t)
    omega = -k
    q = 1/np.cosh(t)
    dz = 2/steps                         # z here is physical Z divided by L_D
    lin = np.exp((-.5*loss-.5j*k**2-1j*d3*k**3)*dz/2)
    for _ in range(steps):
        q = np.fft.ifft(lin*np.fft.fft(q))
        q *= np.exp(1j*dz*abs(q)**2)
        q = np.fft.ifft(lin*np.fft.fft(q))
    S = abs(np.fft.fft(q))**2
    asym = (sum(S[omega>0])-sum(S[omega<0]))/sum(S)
    return np.sum(abs(q)**2)*32/n, asym


def two_poles():
    """Exact two-pole breather; hold the continuous noise realization fixed on refinement."""
    ramp = .4
    z = .15
    offsets = np.random.default_rng(81).uniform(0,2*np.pi,8)
    for T,h,noise in ((10,.05,0),(14,.05,0),(14,.025,0),(14,.025,.005),(18,.025,.005)):
        tau = -T+(np.arange(round(2*T/h))+.5)*h
        x = tau-2*ramp*z
        q = (np.exp(1j*(ramp*tau-ramp*ramp*z+z))*4 *
             (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)))
        perturb = sum(np.exp(1j*((l+1)*tau/3+ph)) for l,ph in enumerate(offsets))
        q += noise*np.exp(-(tau/6)**2)*perturb/np.sqrt(8)
        print("T,h,noise and poles:",T,h,noise,
              *(eigen(q,h,-.2+eta*1j)[0] for eta in (.5,1.5)))


def modulation():
    """Convolve finite-length power excess with a three-point carrier jitter law."""
    def gain(omega):
        return 10*abs(omega)*np.sqrt(np.maximum(0, 1-omega**2))
    shifts = np.array([-.10,0.,.10])
    weights = np.array([.25,.5,.25])
    for omega in (0,1/np.sqrt(2),1.05):
        clean = np.expm1(2*gain(omega)*.10)
        measured = weights @ np.expm1(2*gain(omega-shifts)*.10)
        print(f"Omega={omega:.7f}: ideal excess={clean:.7f}, mixed excess={measured:.7f}")


if __name__ == "__main__":
    collision()
    attenuation = np.log(10)*.2/10*.2
    for n,steps in ((512,200),(1024,400),(2048,800)):
        for loss,d3 in ((0,0),(attenuation,0),(0,.0005),(attenuation,.0005)):
            print("N, steps, alpha L_D, d3, energy and imbalance:",
                  n,steps,loss,d3,*perturbation(n,steps,loss,d3))
    two_poles()
    modulation()
