"""Checks for the Library article "The Lieb-Liniger gas in the thermodynamic limit".

Bosons on a ring with H = -sum d^2/dx_j^2 + 2c sum delta(x_i - x_j), units hbar = 2m = 1, density n = N/L, gamma = c/n.
Lieb's equation on the scaled interval [-1, 1] with lam = c/q:
    g(x) - (1/2pi) int_{-1}^{1} 2 lam g(y) / (lam^2 + (x - y)^2) dy = 1/(2pi),
    gamma = lam / int g,   e(gamma) = (gamma/lam)^3 int x^2 g,   E/L = n^3 e(gamma).
Checks:
  1. the Nystrom solution of Lieb's equation is converged: doubling the nodes changes e by less than 1e-12 at
     lam = 0.2 to 50 (composite Gauss-Legendre panels);
  2. finite rings: ground-state Bethe roots for N = 40 to 320 at n = 1 give E/L that, extrapolated in 1/L^2,
     agrees with n^3 e(gamma) to 1e-9 at gamma = 0.5, 2, 10;
  3. the coefficient of 1/L^2 in E/L is -pi v / 6 (conformal field theory with c = 1), with
     v = n sqrt(2 (6e - 4 gamma e' + gamma^2 e'')), to 1e-4 relative;
  4. the energy of the smallest-momentum excitation, Delta E L / (2 pi), tends to the same v (1e-3 relative at N = 320,
     after extrapolation in 1/L);
  5. strong coupling: e(gamma) - (pi^2/3)(gamma/(gamma+2))^2 falls like gamma^-3 (slope in log-log between -3.2 and
     -2.8 for gamma from 50 to 400), and e -> pi^2/3;
  6. weak coupling: e(gamma) - [gamma - 4 gamma^{3/2}/(3 pi) + (1/6 - 1/pi^2) gamma^2] is smaller than the gamma^2 term
     and falls faster than gamma^2 as gamma -> 0 (gamma = 0.04 to 0.4);
  7. the pair correlation g2 = de/dgamma matches 1 - 2 sqrt(gamma)/pi + (1/3 - 2/pi^2) gamma at gamma = 0.05 (1e-4) and
     4 pi^2/(3 gamma^2) at gamma = 400 (5 percent).
Controls: the mean-field energy e = gamma is 30 percent high at gamma = 1; the hard-core value pi^2/3 is more than
25 percent high at gamma = 10; the Bogoliubov sound velocity 2 n sqrt(gamma) misses v by more than 30 percent at
gamma = 10.
Run with Python 3, NumPy and SciPy:  python3 lieb_liniger_ground_state_check.py   (about 10 seconds)
"""
import numpy as np
from scipy.optimize import brentq


def lieb(lam, panels=40, nodes=20):
    """Solve Lieb's equation by composite Gauss-Legendre Nystrom; return gamma, e(gamma), nodes, weights, g."""
    edges = np.linspace(-1.0, 1.0, panels + 1)
    t, w = np.polynomial.legendre.leggauss(nodes)
    half, mid = np.diff(edges)[:, None] / 2, (edges[:-1, None] + edges[1:, None]) / 2
    x, wt = (mid + half * t).ravel(), (half * w).ravel()
    K = (1 / (2 * np.pi)) * 2 * lam / (lam ** 2 + (x[:, None] - x[None, :]) ** 2)
    g = np.linalg.solve(np.eye(len(x)) - K * wt[None, :], np.full(len(x), 1 / (2 * np.pi)))
    norm = wt @ g
    gamma = lam / norm
    e = (gamma / lam) ** 3 * (wt @ (x ** 2 * g))
    return gamma, e


def e_of_gamma(gamma, **kw):
    lam = brentq(lambda l: lieb(l, **kw)[0] - gamma, 1e-3, 1e5, xtol=1e-15, rtol=1e-15)
    return lieb(lam, **kw)[1]


def derivatives(gamma, h=None, **kw):
    """e, e', e'' by a five-point stencil in log gamma."""
    h = h or 2e-3
    s = np.log(gamma)
    vals = [e_of_gamma(np.exp(s + k * h), **kw) for k in (-2, -1, 0, 1, 2)]
    d1 = (vals[0] - 8 * vals[1] + 8 * vals[3] - vals[4]) / (12 * h)
    d2 = (-vals[0] + 16 * vals[1] - 30 * vals[2] + 16 * vals[3] - vals[4]) / (12 * h ** 2)
    e1 = d1 / gamma
    e2 = (d2 - d1) / gamma ** 2
    return vals[2], e1, e2


def sound_velocity(gamma, n=1.0, **kw):
    e, e1, e2 = derivatives(gamma, **kw)
    return n * np.sqrt(2 * (6 * e - 4 * gamma * e1 + gamma ** 2 * e2))


def bethe_roots(N, L, c, I):
    """Solve L k_j + sum_l 2 arctan((k_j - k_l)/c) = 2 pi I_j by Newton's method."""
    k = 2 * np.pi * np.asarray(I, float) / (L + 2 * N / c)
    for _ in range(100):
        d = k[:, None] - k[None, :]
        F = L * k + np.sum(2 * np.arctan(d / c), axis=1) - 2 * np.pi * np.asarray(I)
        Kmat = 2 * c / (c ** 2 + d ** 2)
        J = -Kmat
        J[np.diag_indices(N)] = L + np.sum(Kmat, axis=1) - 2 / c
        step = np.linalg.solve(J, F)
        k -= step
        if np.max(np.abs(step)) < 1e-15:
            break
    return k


def ground(N, L, c):
    I = np.arange(N) - (N - 1) / 2
    return np.sum(bethe_roots(N, L, c, I) ** 2), I


def main():
    checks, controls = {}, {}

    conv = []
    for lam in (0.2, 1.0, 5.0, 50.0):
        _, e1 = lieb(lam)
        _, e2 = lieb(lam, panels=80, nodes=20)
        conv.append(abs(e1 - e2))
    print('node doubling changes e by at most', f'{max(conv):.1e}')
    checks['Nystrom solution converged: doubling the nodes changes e by < 1e-12'] = max(conv) < 1e-12

    table = {}
    print(' gamma        e(gamma)          g2 = de/dgamma      v/n')
    for gamma in (0.1, 0.5, 1.0, 2.0, 10.0, 100.0):
        e, e1, e2 = derivatives(gamma)
        v = np.sqrt(2 * (6 * e - 4 * gamma * e1 + gamma ** 2 * e2))
        table[gamma] = (e, e1, v)
        print(f'{gamma:6.1f}  {e:.12f}  {e1:.10f}  {v:.8f}')

    worst_e, worst_v, worst_x = 0.0, 0.0, 0.0
    for gamma in (0.5, 2.0, 10.0):
        e, _, v = table.get(gamma) or (None, None, None)
        if e is None:
            e, e1, e2 = derivatives(gamma)
            v = np.sqrt(2 * (6 * e - 4 * gamma * e1 + gamma ** 2 * e2))
        Ns = np.array([40, 80, 160, 320])
        dens = np.array([ground(N, float(N), gamma)[0] / N for N in Ns])
        Ls = Ns.astype(float)
        A = np.vstack([np.ones_like(Ls), Ls ** -2, Ls ** -4]).T
        coef = np.linalg.lstsq(A, dens, rcond=None)[0]
        worst_e = max(worst_e, abs(coef[0] - e))
        worst_v = max(worst_v, abs(coef[1] / (-np.pi * v / 6) - 1))
        exc = []
        for N in (80, 160, 320):
            E0, I = ground(N, float(N), gamma)
            I1 = I.copy()
            I1[-1] += 1
            E1 = np.sum(bethe_roots(N, float(N), gamma, I1) ** 2)
            exc.append((E1 - E0) * N / (2 * np.pi))
        exc = np.array(exc)
        fit = np.polyfit(1.0 / np.array([80, 160, 320]), exc, 1)
        worst_x = max(worst_x, abs(fit[1] / v - 1))
        print(f'gamma = {gamma}: extrapolated E/L {coef[0]:.12f} vs e {e:.12f}; 1/L^2 coefficient {coef[1]:.6f} vs '
              f'-pi v/6 = {-np.pi * v / 6:.6f}; excitation slope {exc[-1]:.6f} at N = 320, extrapolated {fit[1]:.6f}')
    checks['finite rings extrapolate to n^3 e(gamma) (1e-9)'] = worst_e < 1e-9
    checks['1/L^2 coefficient equals -pi v/6 (1e-4 relative)'] = worst_v < 1e-4
    checks['smallest excitation energy L/(2 pi) tends to v (1e-3 relative)'] = worst_x < 1e-3

    big = np.array([50.0, 100.0, 200.0, 400.0])
    resid = np.array([e_of_gamma(g) - np.pi ** 2 / 3 * (g / (g + 2)) ** 2 for g in big])
    slope = np.polyfit(np.log(big), np.log(np.abs(resid)), 1)[0]
    print('strong coupling: e - (pi^2/3)(gamma/(gamma+2))^2 =', ' '.join(f'{r:.3e}' for r in resid),
          f'(log-log slope {slope:.3f}); e(400) = {e_of_gamma(400.0):.8f}, pi^2/3 = {np.pi ** 2 / 3:.8f}')
    checks['strong coupling: residual of (pi^2/3)(gamma/(gamma+2))^2 falls like gamma^-3'] = -3.2 < slope < -2.8

    small = np.array([0.04, 0.1, 0.2, 0.4])
    kw = {}
    ws = []
    for g in small:
        e = e_of_gamma(g, **kw)
        two = g - 4 * g ** 1.5 / (3 * np.pi)
        three = two + (1 / 6 - 1 / np.pi ** 2) * g ** 2
        ws.append((e, e - two, e - three))
    ws = np.array(ws)
    print('weak coupling: e - [gamma - 4 gamma^1.5/(3 pi)] =', ' '.join(f'{r:.3e}' for r in ws[:, 1]),
          '; minus also (1/6 - 1/pi^2) gamma^2:', ' '.join(f'{r:.3e}' for r in ws[:, 2]))
    ratio = np.abs(ws[:, 2]) / ((1 / 6 - 1 / np.pi ** 2) * small ** 2)
    checks['weak coupling: the gamma^2 term (1/6 - 1/pi^2) accounts for the residual, which then falls faster than gamma^2'] = (
        np.all(ratio < 0.5) and ratio[0] < ratio[-1])

    g2_weak = derivatives(0.05, **kw)[1]
    g2_strong = derivatives(400.0)[1]
    weak_pred = 1 - 2 * np.sqrt(0.05) / np.pi + (1 / 3 - 2 / np.pi ** 2) * 0.05
    print(f'g2(0.05) = {g2_weak:.6f} vs 1 - 2 sqrt(gamma)/pi + (1/3 - 2/pi^2) gamma = {weak_pred:.6f} '
          f'(two terms: {1 - 2 * np.sqrt(0.05) / np.pi:.6f}); '
          f'g2(400) = {g2_strong:.4e} vs 4 pi^2/(3 gamma^2) = {4 * np.pi ** 2 / (3 * 400 ** 2):.4e}')
    checks['g2 limits: weak-coupling expansion (1e-4) and 4 pi^2/(3 gamma^2) (5 percent)'] = (
        abs(g2_weak - weak_pred) < 1e-4 and abs(g2_strong / (4 * np.pi ** 2 / (3 * 400 ** 2)) - 1) < 0.05)

    e1 = table[1.0][0]
    e10, _, v10 = table[10.0]
    print(f'controls: mean field gamma = 1 vs e(1) = {e1:.6f}; pi^2/3 vs e(10) = {e10:.6f}; '
          f'Bogoliubov 2 sqrt(10) = {2 * np.sqrt(10):.4f} vs v(10) = {v10:.4f}')
    controls['mean-field e = gamma is more than 30 percent high at gamma = 1'] = 1.0 / e1 - 1 > 0.3
    controls['hard-core e = pi^2/3 is more than 25 percent high at gamma = 10'] = (np.pi ** 2 / 3) / e10 - 1 > 0.25
    controls['Bogoliubov v = 2 n sqrt(gamma) misses v by more than 30 percent at gamma = 10'] = (
        abs(2 * np.sqrt(10) / v10 - 1) > 0.3)

    for name, ok in checks.items():
        print(f"{'PASS' if ok else 'FAIL'}  {name}")
    for name, ok in controls.items():
        print(f"{'PASS' if ok else 'FAIL'}  control: {name}")
    if not all(checks.values()) or not all(controls.values()):
        raise SystemExit(1)


if __name__ == '__main__':
    main()
