"""One ray of a repulsive Lieb–Liniger partitioning protocol.

Run with Python 3, NumPy and SciPy. Units are m = c = hbar = 1. The two
generalized fillings are 3/4 and 1/4 on [-1,1], zero elsewhere.
"""
import numpy as np
from numpy.polynomial.legendre import leggauss
from scipy.optimize import brentq


def junction(points, left=0.75, right=0.25):
    """Return the rapidity switch, particle density and current at x/t = 0."""
    nodes, weights = leggauss(points)

    def dress(switch):
        momenta = np.concatenate(((switch+1)*nodes/2 + (switch-1)/2,
                                  (1-switch)*nodes/2 + (1+switch)/2))
        measure = np.concatenate(((switch+1)*weights*right,
                                  (1-switch)*weights*left)) / (4*np.pi)

        def kernel(targets):
            differences = np.asarray(targets)[:, None] - momenta[None, :]
            return (2 / (1 + differences**2)) * measure

        operator = np.eye(len(momenta)) - kernel(momenta)
        bare = np.column_stack((np.ones_like(momenta), momenta))
        dressed = np.linalg.solve(operator, bare)
        return momenta, measure, kernel, dressed, np.max(abs(operator @ dressed - bare))

    def switch_residual(switch):
        _, _, kernel, dressed, _ = dress(switch)
        return switch + (kernel([switch]) @ dressed[:, 1])[0]

    switch = brentq(switch_residual, -1, 1, xtol=2e-14)
    momenta, measure, _, dressed, linear_residual = dress(switch)
    momentum_derivative, energy_derivative = dressed.T
    assert min(momentum_derivative) > 0
    assert np.all(energy_derivative[:points] < 0)
    assert np.all(energy_derivative[points:] > 0)
    density = measure @ momentum_derivative
    current = measure @ energy_derivative
    # Galilean-invariant flow has particle current equal to momentum density at m=1.
    momentum = measure @ (momenta * momentum_derivative)
    assert abs(current - momentum) < 2e-13
    assert max(linear_residual, abs(switch_residual(switch))) < 2e-13
    return np.array([switch, density, current])


if __name__ == "__main__":
    print("Gauss nodes per interval, switch, density, particle current")
    for points in (12, 24, 48):
        print(points, *("%.12f" % value for value in junction(points)))
    np.testing.assert_allclose(junction(24), junction(48), rtol=0, atol=2e-13)
    switch, density, current = junction(24)
    np.testing.assert_allclose(junction(24, left=0.25, right=0.75),
                               [-switch, density, -current], rtol=0, atol=2e-13)
    print("Passed switch, dressing, Galilean-current, refinement and reversal checks.")
