"""Point intensity and whole-line mass in two exact focusing NLS fields.

Each row holds a vacuum or dressed column at one point on the line. Compare
the trapezoidal mass on two windows with the exact scattering trace, 8.
Requires Python 3 and NumPy.
"""
import numpy as np


def field(x, relative_sign):
    first = np.stack((np.exp(x / 2), np.exp(-x / 2)), axis=-1)
    second = np.stack((np.exp(1.5 * x), relative_sign * np.exp(-1.5 * x)), axis=-1)
    norm1 = np.sum(first**2, axis=-1, keepdims=True)
    projection = first * np.sum(first * second, axis=-1, keepdims=True) / norm1
    dressed = second - projection / 2
    return (2 * first[..., 0] * first[..., 1] / norm1[..., 0]
            + 6 * dressed[..., 0] * dressed[..., 1] / np.sum(dressed**2, axis=-1))


if __name__ == "__main__":
    detector = np.array([field(0.0, sign)**2 for sign in (1, -1)])
    print("detector intensities, mean, second moment", detector, detector.mean(),
          (detector**2).mean())
    assert np.allclose(detector, [16, 4])
    for half_width, spacing in ((12, 0.01), (20, 0.005)):
        x = np.linspace(-half_width, half_width, round(2 * half_width / spacing) + 1)
        for sign in (1, -1):
            intensity = field(x, sign)**2
            mass = spacing * (intensity.sum() - (intensity[0] + intensity[-1]) / 2)
            print(f"L={half_width} dx={spacing} phase sign={sign:+} mass={mass:.13f}")
            assert abs(mass - 8) < 1e-8
