"""Finite two-component contact gases. Python 3 with NumPy and SciPy."""
from math import atan, pi, sqrt

import numpy as np
from scipy.optimize import brentq, root


def collision(contrast):
    """Ordered-spin wave after the collision, with contrast c/(2q)."""
    singlet = np.array([1., -1.])/sqrt(2)
    triplet = np.array([1., 1.])/sqrt(2)
    even_phase = (1 - 1j*contrast)/(1 + 1j*contrast)
    scattering = even_phase*np.outer(singlet, singlet) - np.outer(triplet, triplet)
    np.testing.assert_allclose(scattering.conj().T @ scattering, np.eye(2), atol=1e-14)
    return scattering[:, 0]


def box_splitting(g):
    """Dimensionless E_s L² and the gap divided by its leading large-c value."""
    def round_trip(target):
        return brentq(lambda z: z + 2*atan(z/g) - target, 0, target, xtol=1e-14)
    difference, total = [round_trip(n*pi) for n in (1, 3)]
    k1, k2 = (total-difference)/2, (total+difference)/2
    for k, other in [(k1, k2), (k2, k1)]:
        factors = [(k-other+1j*g)/(k-other-1j*g), (k+other+1j*g)/(k+other-1j*g)]
        np.testing.assert_allclose(np.exp(2j*k), np.prod(factors), atol=1e-13, rtol=0)
    energy = k1*k1 + k2*k2
    return energy, (5*pi*pi - energy)*g/(20*pi*pi)


def nested_state(spin_label):
    """Lengths measured in a unit for which L=2π and c=2."""
    charge_labels = np.array([-1.5, -.5, .5])
    def residual(variables):
        k, lam = variables[:3], variables[3]
        phase = 2*np.arctan(k-lam)
        return np.r_[2*pi*(k-charge_labels) + phase, -sum(phase)-2*pi*spin_label]
    solution = root(residual, np.r_[charge_labels, spin_label], tol=1e-12)
    assert solution.success
    k, lam = solution.x[:3], solution.x[3]
    ratio = (k-lam+1j)/(k-lam-1j)
    np.testing.assert_allclose(ratio, np.exp(2j*pi*k), atol=1e-13, rtol=0)
    np.testing.assert_allclose(np.prod(1/ratio), 1, atol=1e-13, rtol=0)
    np.testing.assert_allclose(sum(k), sum(charge_labels)+spin_label, atol=1e-13)
    return k, lam, sum(k), k @ k


if __name__ == "__main__":
    for contrast in (0., 1., 1e6):
        print("c/(2q), ordered spin amplitudes", contrast, collision(contrast))
    for g in (20, 100, 1000):
        print("cL, singlet energy × L², exchange ratio", g, *box_splitting(g))
    for label in (-.5, .5):
        print("spin label, k, spin rapidity, momentum, energy", label, *nested_state(label))
