"""Checks for the Library article "The thermodynamic Bethe ansatz".

Part A, the repulsive Bose gas (Lieb-Liniger), hbar = 2m = k_B = 1, contact strength 2c, kernel a(u) = c/(pi(c^2+u^2)):
    eps(k) = k^2 - mu - T (a * log(1 + e^{-eps/T}))(k),   p = (T/2pi) int log(1 + e^{-eps/T}) dk,
    rho_t = 1/(2pi) + a * rho_p,  rho_p = rho_t / (1 + e^{eps/T}).
  A1. the density int rho_p equals dp/dmu, and the Yang-Yang entropy equals dp/dT (thermodynamic consistency);
  A2. at low fugacity z the pressure gives the second virial coefficient
      b2 = (1/sqrt 2) (e^{x^2} erfc x - 1/2), x = c/sqrt(2T), which runs from the ideal Bose value 2^{-3/2} at c = 0
      to the free-fermion value -2^{-3/2} as c -> infinity;
  A3. as T -> 0 at fixed mu the density and energy approach Lieb's ground state, computed independently, with
      differences falling like T^2.
Part B, the spin-1/2 XXX chain H = J sum (S_j.S_{j+1} - 1/4), J = 1, in Takahashi's string form at zero field:
    log eta_1 = -(pi J/T) s + s * log(1 + eta_2),   log eta_n = s * log[(1 + eta_{n-1})(1 + eta_{n+1})],  n >= 2,
    f = -J log 2 - T int s(lam) log(1 + eta_1(lam)) dlam,   s(lam) = 1/(2 cosh(pi lam)).
  B1. the free energy per site agrees with exact diagonalization of rings of 12, 14 and 16 sites, which converge
      toward it as the ring grows (with --precise, 240 strings reproduce the 16-site ring to 1e-9 at T = 1);
  B2. at high temperature it reproduces the series -f/T = log 2 + J/(4T) + 3J^2/(32T^2) + J^3/(64 T^3) + ...
Controls: counting Bose-gas quasiparticles as bosons breaks the Tonks-Girardeau limit of b2, and keeping only real
roots (one string type) gives an infinite-temperature entropy log((1 + sqrt 5)/2) = 0.481, short of log 2, in agreement
with Bethe's count of real-root configurations, sum_M (N - 2M + 1) C(N - M, M).
Run with Python 3, NumPy and SciPy:  python3 thermodynamic_bethe_ansatz_check.py [--precise]
(about two minutes; the precise option adds about five)
"""
import sys
from math import comb, log
from pathlib import Path
import numpy as np
from scipy.optimize import brentq
from scipy.special import erfcx, expit

sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'quantum-many-body'))
from heisenberg_chain_check import momentum_block  # noqa: E402

# ------------------------------------------------------------------------------------------------------- Bose gas
def gl_grid(K, n):
    x, w = np.polynomial.legendre.leggauss(n)
    return K * x, K * w


def yang_yang(mu, T, c, n=500, statistics='fermi'):
    """Solve the Yang-Yang equation on a Gauss-Legendre grid; return k, weights, eps, pressure."""
    K = np.sqrt(max(mu, 0.0) + 60 * T) + 4.0
    k, w = gl_grid(K, n)
    A = (c / np.pi) / (c ** 2 + (k[:, None] - k[None, :]) ** 2) * w[None, :]
    eps = k ** 2 - mu
    for _ in range(5000):
        if statistics == 'fermi':
            ell = T * np.logaddexp(0.0, -eps / T)
        else:                                   # control: bosonic counting, T log 1/(1 - e^{-eps/T})
            ell = -T * np.log1p(-np.exp(-eps / T))
        new = k ** 2 - mu - A @ ell
        if np.max(np.abs(new - eps)) < 1e-15 * max(1.0, np.max(np.abs(eps))):
            eps = new
            break
        eps = new
    p = np.sum(w * ell) / (2 * np.pi)
    return k, w, eps, p, A


def densities(mu, T, c, n=500):
    k, w, eps, p, A = yang_yang(mu, T, c, n)
    theta = expit(-eps / T)
    rho_t = np.linalg.solve(np.eye(len(k)) - A * theta[None, :], np.full(len(k), 1 / (2 * np.pi)))
    rho_p, rho_h = theta * rho_t, (1 - theta) * rho_t
    def xlogx(x):
        return np.where(x > 0, x * np.log(np.where(x > 0, x, 1.0)), 0.0)
    s = np.sum(w * (xlogx(rho_t) - xlogx(rho_p) - xlogx(rho_h)))
    return {'p': p, 'n': np.sum(w * rho_p), 'e': np.sum(w * k ** 2 * rho_p), 's': s}


def virial_b2(T, c, statistics='fermi'):
    """Richardson-extrapolated (p lambda / T - z)/z^2 at z -> 0, with 1/lambda = sqrt(T/(4 pi))."""
    inv_lam = np.sqrt(T / (4 * np.pi))
    vals = []
    for z in (1e-3, 2e-3):
        p = yang_yang(T * np.log(z), T, c, 600, statistics)[3]
        vals.append((p / (T * inv_lam) - z) / z ** 2)
    return 2 * vals[0] - vals[1]


def b2_exact(T, c):
    """(e^{x^2} erfc x - 1/2)/sqrt 2 with x = c/sqrt(2T), using the scaled complementary error function."""
    x = c / np.sqrt(2 * T)
    return (erfcx(x) - 0.5) / np.sqrt(2)


def lieb_ground_state(mu, c, n=400):
    """Zero temperature: dressed energy eps0 = k^2 - mu + int_{-q}^{q} a eps0 with eps0(+-q) = 0; returns n, e."""
    def solve(q):
        x, w = np.polynomial.legendre.leggauss(n)
        k, w = q * x, q * w
        A = (c / np.pi) / (c ** 2 + (k[:, None] - k[None, :]) ** 2) * w[None, :]
        eps = np.linalg.solve(np.eye(n) - A, k ** 2 - mu)
        rho = np.linalg.solve(np.eye(n) - A, np.full(n, 1 / (2 * np.pi)))
        eps_q = q ** 2 - mu + np.sum((c / np.pi) / (c ** 2 + (q - k) ** 2) * w * eps)
        return eps_q, np.sum(w * rho), np.sum(w * k ** 2 * rho)
    q = brentq(lambda q: solve(q)[0], 1e-6, np.sqrt(mu) * 4 + 2)
    _, dens, energy = solve(q)
    return dens, energy


# -------------------------------------------------------------------------------------------------------- XXX chain
def half_sech(x):
    """1/(2 cosh x) without overflow."""
    e = np.exp(-np.abs(x))
    return e / (1 + e * e)


def xxx_tba_free_energy(T, nmax=120, Lam=40.0, h=0.1, tol=1e-12, history=12):
    """Takahashi's decoupled string TBA at zero field on |lam| <= Lam, solved with Anderson acceleration.

    Beyond the window every eta_n takes its |lam| -> infinity value (n+1)^2 - 1, and the hierarchy is closed by
    1 + eta_{nmax+1} = eta_nmax^2 / (1 + eta_{nmax-1}), exact for lam-independent tails. The trapezoid rule converges
    exponentially here because s has its nearest poles at +-i/2."""
    lam = np.arange(-Lam, Lam + h / 2, h)
    w = np.full(len(lam), h); w[0] = w[-1] = h / 2
    s = half_sech(np.pi * lam)
    S = half_sech(np.pi * (lam[:, None] - lam[None, :])) * w[None, :]
    tail = 0.5 - S.sum(axis=1)               # mass of s outside the window, where the functions are constant
    n = np.arange(1, nmax + 1)
    asym = np.log((n + 2.0) ** 2) + np.log(np.maximum(n, 1.0) ** 2) * (n > 1)
    drive = -(np.pi / T) * s
    shape = (nmax, len(lam))

    def G(x):
        loge = x.reshape(shape)
        l1 = np.logaddexp(0.0, loge)
        top = 2 * loge[-1] - l1[-2]
        both = np.vstack([l1[1:], top[None, :]]) + np.vstack([np.zeros((1, len(lam))), l1[:-1]])
        new = (S @ both.T).T + tail[None, :] * asym[:, None]
        new[0] += drive
        return new.ravel()

    x = np.tile(np.log((n + 1.0) ** 2 - 1)[:, None], (1, len(lam))).ravel()
    xs, fs = [], []
    for _ in range(10000):
        g = G(x)
        f = g - x
        if np.max(np.abs(f)) < tol:
            x = g
            break
        xs.append(x.copy()); fs.append(f.copy())
        xs, fs = xs[-(history + 1):], fs[-(history + 1):]
        if len(fs) > 1:
            dF = np.array([fs[i + 1] - fs[i] for i in range(len(fs) - 1)]).T
            dG = np.array([(xs[i + 1] + fs[i + 1]) - (xs[i] + fs[i]) for i in range(len(fs) - 1)]).T
            x = g - dG @ np.linalg.lstsq(dF, f, rcond=None)[0]
        else:
            x = g
    else:
        raise RuntimeError(f'string TBA did not converge to {tol} at T = {T}')
    l1 = np.logaddexp(0.0, x.reshape(shape)[0])
    return -np.log(2.0) - T * (np.sum(w * s * l1) + (0.5 - np.sum(w * s)) * np.log(4.0))


def xxx_ed_free_energies(L, temps):
    """Free energy per site of the periodic ring from its complete spectrum, block by block."""
    levels = []
    for n_up in range(L + 1):
        for m in range(L):
            H = momentum_block(L, n_up, m, [(1, 1.0, 1.0, -0.25)])
            if H.shape[0]:
                levels.append(np.linalg.eigvalsh(H))
    E = np.concatenate(levels)
    assert len(E) == 2 ** L
    out = []
    for T in temps:
        e0 = E.min()
        out.append((e0 - T * np.log(np.sum(np.exp(-(E - e0) / T)))) / L)
    return np.array(out)


def main():
    checks, controls = {}, {}
    # A1. Thermodynamic consistency of the Bose gas.
    mu, T, c = 1.0, 1.0, 2.0
    d = densities(mu, T, c)
    hmu, hT = 1e-4, 1e-4
    dp_dmu = (densities(mu + hmu, T, c)['p'] - densities(mu - hmu, T, c)['p']) / (2 * hmu)
    dp_dT = (densities(mu, T + hT, c)['p'] - densities(mu, T - hT, c)['p']) / (2 * hT)
    gibbs = d['p'] - (-d['e'] + T * d['s'] + mu * d['n'])
    print(f"Bose gas mu = 1, T = 1, c = 2: p = {d['p']:.11f}, n = {d['n']:.11f} (dp/dmu = {dp_dmu:.11f}), "
          f"s = {d['s']:.10f} (dp/dT = {dp_dT:.10f}), p + e - Ts - mu n = {gibbs:.1e}")
    checks['Bose gas: density equals dp/dmu and Yang-Yang entropy equals dp/dT (1e-8)'] = (
        abs(d['n'] - dp_dmu) < 1e-8 and abs(d['s'] - dp_dT) < 1e-8 and abs(gibbs) < 1e-10)
    checks['Bose gas: pressure matches the chapter value 0.59519811736 at T = 1, mu = 1, c = 2 (1e-10)'] = (
        abs(d['p'] - 0.59519811736) < 1e-10)

    # A2. Second virial coefficient.
    print(' c/sqrt(2T)    b2 (TBA)        b2 (formula)     b2 (bosonic counting)')
    worst = 0.0
    # c >= 0.2 keeps the Lorentzian kernel (width c) resolved by the grid; the quadrature error is ~ exp(-2 pi c/h).
    for c in (0.2, 0.5, 2.0, 8.0, 40.0):
        num, ex, bos = virial_b2(1.0, c), b2_exact(1.0, c), virial_b2(1.0, c, 'bose')
        worst = max(worst, abs(num - ex))
        print(f'{c / np.sqrt(2):10.4f}   {num:+.8f}    {ex:+.8f}     {bos:+.8f}')
    checks['second virial coefficient from the TBA equals (e^{x^2} erfc x - 1/2)/sqrt 2 (1e-6)'] = worst < 1e-6
    big = virial_b2(1.0, 400.0)
    approach = 400.0 * (big + 2 ** -1.5) * np.sqrt(np.pi / 1.0)
    print(f'c = 400: b2 = {big:.8f}; c (b2 + 2^-3/2) sqrt(pi/T) = {approach:.6f} (free fermions approached like 1/c)')
    checks['strong coupling approaches the free-fermion -2^{-3/2} like 1/c: c (b2 + 2^{-3/2}) sqrt(pi/T) -> 1 (1e-3 at c = 400)'] = (
        abs(approach - 1) < 1e-3)
    controls['bosonic counting gives b2 near +2^{-3/2}, the wrong sign for the Tonks-Girardeau gas, at c = 400'] = (
        abs(virial_b2(1.0, 400.0, 'bose') - 2 ** -1.5) < 2e-3 and big < 0)

    # A3. Zero-temperature limit.
    mu, c = 1.0, 2.0
    n0, e0 = lieb_ground_state(mu, c)
    print(f"Lieb ground state at mu = 1, c = 2: n = {n0:.10f}, e = {e0:.10f}")
    diffs = []
    for T in (0.08, 0.04, 0.02):
        dT = densities(mu, T, c, n=900)
        diffs.append(abs(dT['n'] - n0))
        print(f"  T = {T:.2f}: n = {dT['n']:.10f}  |n - n0| = {diffs[-1]:.2e}   e = {dT['e']:.10f}")
    checks['as T -> 0 the TBA density approaches Lieb\'s, with differences falling like T^2'] = (
        diffs[-1] < 1e-3 and all(0.15 < diffs[i + 1] / diffs[i] < 0.35 for i in range(2)))

    # B1. XXX chain against exact diagonalization.
    temps = np.array([0.5, 1.0, 2.0])
    f_tba = np.array([xxx_tba_free_energy(T) for T in temps])
    eds = {L: xxx_ed_free_energies(L, temps) for L in (12, 14, 16)}
    print(' T     f (TBA, 120 strings)   f (ED, L=12)     f (ED, L=14)     f (ED, L=16)')
    for i, T in enumerate(temps):
        print(f'{T:.1f}   {f_tba[i]:.12f}       {eds[12][i]:.10f}   {eds[14][i]:.10f}   {eds[16][i]:.10f}')
    gap = np.abs(eds[16] - f_tba)
    toward = all(abs(eds[16][i] - f_tba[i]) < abs(eds[14][i] - f_tba[i]) < abs(eds[12][i] - f_tba[i]) for i in (0,))
    checks['XXX: exact rings agree with the string TBA (5e-8 at T = 1 and 2)'] = bool(np.all(gap[1:] < 5e-8))
    checks['XXX: at T = 0.5 the rings of 12, 14, 16 sites approach the TBA value monotonically (16 sites within 5e-7)'] = (
        toward and gap[0] < 5e-7)
    if '--precise' in sys.argv:
        fp = xxx_tba_free_energy(1.0, nmax=240, Lam=80.0)
        print(f'precise TBA (240 strings, |lam| <= 80) at T = 1: {fp:.12f}, difference from L = 16: {fp - eds[16][1]:+.1e}')
        checks['XXX (precise run): 240 strings on |lam| <= 80 agree with the 16-site ring to 2e-9 at T = 1'] = (
            abs(fp - eds[16][1]) < 2e-9)

    # B2. High-temperature series.
    Ths = np.array([20.0, 40.0])
    f_high = np.array([xxx_tba_free_energy(T, nmax=60) for T in Ths])
    series = -Ths * (np.log(2) + 1 / (4 * Ths) + 3 / (32 * Ths ** 2) + 1 / (64 * Ths ** 3))
    print('high T: f (TBA) - series =', ' '.join(f'{a - b:+.1e}' for a, b in zip(f_high, series)))
    checks['XXX: high-temperature series through T^-3 matches the TBA (1e-6 at T = 20 and 40)'] = bool(
        np.all(np.abs(f_high - series) < 1e-6))

    # Control: real roots only. With one string type the infinite-temperature equation for eta = rho^h/rho is
    # log eta = (int a_2) log(1 + 1/eta) = log(1 + 1/eta), and the entropy is int a_1 log(1 + 1/eta) = log(1 + 1/eta).
    # Bethe's count of real-root configurations, C(N - M, M) highest-weight states of N - 2M + 1 members each, grows
    # at the same rate.
    eta = 1.0
    for _ in range(200):
        eta = 1 + 1 / eta
    s_real = np.log(1 + 1 / eta)
    def real_root_count(N):
        return sum((N - 2 * M + 1) * comb(N - M, M) for M in range(N // 2 + 1))
    growth = log(real_root_count(4002) / real_root_count(4000)) / 2
    print(f'one string type at infinite temperature: eta = {eta:.6f}, entropy {s_real:.6f}; growth of the real-root '
          f'count at N = 4000: {growth:.6f}; log 2 = {np.log(2):.6f}; real-root states of 4 sites: {real_root_count(4)} of 16')
    controls['keeping only real roots gives entropy log((1 + sqrt 5)/2) = 0.481, short of log 2, as the real-root count confirms'] = (
        abs(s_real - np.log((1 + np.sqrt(5)) / 2)) < 1e-12 and abs(growth - s_real) < 1e-3 and np.log(2) - s_real > 0.2)

    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()
