"""Reproduce the finite-ring and zero-temperature continuum exercises (NumPy and SciPy)."""

from math import atan, cos, pi, sin, sqrt

import numpy as np
from numpy.polynomial.legendre import leggauss
from scipy.integrate import quad
from scipy.optimize import brentq


def two_particles(length, coupling):
    g = length * coupling
    z = brentq(lambda t: 2 * t * sin(t / 2) - g * cos(t / 2), 0, pi, xtol=5e-15)
    k = z / length
    amplitude = 1 / sqrt(length * (length / 2 + sin(z) / (2 * k)))
    integral = quad(lambda r: length * (amplitude * cos(k * (r - length / 2)))**2,
                    0, length)[0]
    jump = 2 * k * sin(z / 2) - coupling * cos(z / 2)
    assert abs(integral - 1) < 2e-12 and abs(jump) < 2e-11
    return z, 2 * z**2


def ground_state(coupling, density, order):
    nodes, weights = leggauss(order)

    def moments(edge):
        k = edge * nodes
        w = edge * weights
        delta = k[:, None] - k[None, :]
        kernel = coupling * w[None, :] / (pi * (coupling**2 + delta**2))
        rho = np.linalg.solve(np.eye(order) - kernel, np.full(order, 1 / (2 * pi)))
        assert np.linalg.norm(rho - kernel @ rho - 1 / (2 * pi), np.inf) < 2e-14
        return w @ rho, w @ (k * k * rho)

    edge = brentq(lambda q: moments(q)[0] - density, 0, pi * density + 1,
                  xtol=5e-14)
    n, energy = moments(edge)
    assert abs(n - density) < 2e-13
    return edge, energy


if __name__ == "__main__":
    for g in [pi, 10, 100, 1000]:
        z, energy = two_particles(1, g)
        print(f"cL={g:.8g}  kL={z:.10f}  EL^2={energy:.10f}")
    assert abs(two_particles(1, pi)[0] - pi / 2) < 1e-12
    c = 1.0
    length = 2 * pi - 2 * atan(1 / c) - 2 * atan(2 / c)
    roots = np.array([-1., 0., 1.])
    logarithms = roots * length + 2 * np.arctan((roots[:, None] - roots) / c).sum(axis=1)
    print("three-particle circumference and integers:", length, logarithms / (2 * pi))
    assert np.allclose(logarithms, 2 * pi * roots, rtol=0, atol=1e-14)
    for order in (8, 16, 32, 64):
        edge, energy = ground_state(2, 1, order)
        print(f"c=2  n=1  order={order:2}  Q={edge:.12f}  E/L={energy:.12f}")
    scaled_edge, scaled_energy = ground_state(4, 2, 64)
    assert abs(scaled_edge / 2 - edge) < 2e-12
    assert abs(scaled_energy / 8 - energy) < 2e-12
