"""Recover a filtered repulsive profile from its complex right reflection amplitude.

Run with Python 3 and NumPy. The scattering ODE uses plane-wave amplitudes
with left Jost normalization. The comparator uses the exact Fourier transform
of a translated sech-squared profile and never calls the scattering routine.
"""

import numpy as np


CENTER = 0.8


def right_reflection(k, strength, radius, step, center=CENTER):
    # f_-(x,k) = a(x) exp(-ikx) + b(x) exp(ikx) with the usual
    # variation-of-parameters condition on a' and b'.
    def rates(x, a, b):
        q = strength / np.cosh(x - center)**2
        phase = np.exp(2j * k * x)
        amplitude = q * (a + b * phase) / (2j * k)
        return -amplitude, amplitude / phase

    a = np.ones_like(k, dtype=complex)
    b = np.zeros_like(a)
    count = round(2 * radius / step)
    step = 2 * radius / count
    for index in range(count):
        x = -radius + index * step
        da1, db1 = rates(x, a, b)
        da2, db2 = rates(x + step / 2, a + step * da1 / 2, b + step * db1 / 2)
        da3, db3 = rates(x + step / 2, a + step * da2 / 2, b + step * db2 / 2)
        da4, db4 = rates(x + step, a + step * da3, b + step * db3)
        a += step * (da1 + 2 * da2 + 2 * da3 + da4) / 6
        b += step * (db1 + 2 * db2 + 2 * db3 + db4) / 6
    return b / a, np.max(np.abs(np.abs(a)**2 - np.abs(b)**2 - 1))


def profiles(strength, radius=16, step=0.02, intervals=192):
    # The compact cutoff and its derivatives vanish at both endpoints.
    # Midpoint integration needs only k>0 by the reality symmetry.
    kmin, kmax = 0.4, 1.4
    dk = (kmax - kmin) / intervals
    k = kmin + (np.arange(intervals) + 0.5) * dk
    s = (2*k - kmin - kmax) / (kmax - kmin)
    weight = np.exp(1 - 1/(1 - s**2))
    r, current_error = right_reflection(k, strength, radius, step)
    xi = 2*k
    exact = strength * np.exp(-1j*xi*CENTER) * np.pi*xi / np.sinh(np.pi*xi/2)
    points = np.linspace(-8, 8, 641)
    inverse = (2*dk/np.pi) * np.exp(1j*np.outer(points, xi)) * weight
    return (inverse @ exact).real, (inverse @ (2j*k*r)).real, current_error


if __name__ == "__main__":
    print("strength  target_at_center  reconstructed_at_center  max_error  flux_defect")
    for strength in [0.08, 0.04, 0.02, 0.01]:
        target, recovered, defect = profiles(strength)
        print(f"{strength:.3f} {target[352]:.10f} {recovered[352]:.10f} "
              f"{np.max(np.abs(target - recovered)):.6e} {defect:.2e}")
    base_target, base, _ = profiles(0.04)
    fine_target, fine, fine_flux = profiles(0.04, radius=20, step=0.01, intervals=384)
    print("refinement of target, reconstruction, refined flux defect:",
          np.max(np.abs(base_target-fine_target)), np.max(np.abs(base-fine)), fine_flux)
