"""Reconstruct the dimensionless -3 sech(x)^2/4 well from right scattering data.

Python 3, NumPy and SciPy. Both integrations use Gauss–Legendre quadrature.
The gamma-function reflection amplitude is Eq. (17) of Çevik et al. (2016)
at lambda=3/2. The right norming weight is 2/pi and the pole is at i/2.
"""
import numpy as np
from scipy.special import loggamma, roots_legendre


def interval(order, end):
    nodes, weights = roots_legendre(order)
    return end*(1+nodes)/2, end*weights/2


def reflection(k):
    z = 1j*k
    # Gamma(-1/2) Gamma(3/2) = -pi. The unit phase of Gamma(ik)/Gamma(-ik)
    # carries positional information even though it cancels from the flux.
    return -np.exp(loggamma(z) - loggamma(-z) + loggamma(1.5-z) + loggamma(-.5-z))/np.pi


def reconstruct(x, k, spectral_weights, offsets, spatial_weights, include_reflection=True):
    """Return K(x,x) and q(x) from the shifted equation for K(x,x+s)."""
    # The endpoint itself is an evaluation node with zero integration weight.
    s = np.r_[0., offsets]
    weights = np.r_[0., spatial_weights]
    waves = np.exp(1j*np.outer(s, k))
    measure = spectral_weights*reflection(k)*np.exp(2j*k*x)/np.pi
    if not include_reflection:
        measure = np.zeros_like(measure)
    pole = 2/np.pi * np.exp(-x - .5*(s[:, None]+s[None, :]))
    kernel = pole + ((waves*measure) @ waves.T).real
    derivative = -pole + ((waves*(2j*k*measure)) @ waves.T).real
    matrix = np.eye(len(s)) + kernel*weights
    b = np.linalg.solve(matrix, -kernel[:, 0])
    db = np.linalg.solve(matrix, -derivative[:, 0] - derivative @ (weights*b))
    return b[0], -2*db[0]


if __name__ == "__main__":
    locations = np.linspace(-2, 2, 33)
    for k_end, nk, s_end, ns in [(8, 128, 20, 48), (12, 256, 32, 80)]:
        k, wk = interval(nk, k_end)
        s, ws = interval(ns, s_end)
        recovered = np.array([reconstruct(x, k, wk, s, ws) for x in locations])
        exact = np.column_stack((-.375*(1-np.tanh(locations)), -.75/np.cosh(locations)**2))
        errors = np.max(abs(recovered-exact), axis=0)
        print("Spectral and spatial cutoffs/orders:", k_end, nk, s_end, ns)
        print("Max sampled diagonal and potential errors:", *errors)
        print("Reconstructed q(0), pole-only q(0):", recovered[16, 1],
              reconstruct(0., k, wk, s, ws, include_reflection=False)[1])
