r"""
The Lieb-Liniger Bose gas
=========================

Lieb and Liniger (1963) solved :math:`N` bosons on a ring with a contact
interaction :math:`2c\sum_{i<j}\delta(x_i-x_j)` exactly by Bethe's ansatz
(units :math:`\hbar = 2m = 1`). At density :math:`n` the physics depends
only on :math:`\gamma = c/n`. The ground-state energy per particle is
:math:`n^2 e(\gamma)`, where :math:`e(\gamma)` comes from Lieb's linear
integral equation for the density of rapidities. Weak coupling recovers
Bogoliubov's :math:`e\approx\gamma - 4\gamma^{3/2}/(3\pi)`. Infinite
coupling gives the Tonks-Girardeau gas of impenetrable bosons, whose energy
:math:`\pi^2/3` is that of free fermions.

The functions used here are in :mod:`physicskit.statphys.chapters.lieb_liniger`.
"""

# %%
import matplotlib.pyplot as plt
import numpy as np

from physicskit.statphys.chapters.lieb_liniger import (
    lieb_liniger_bethe_rapidities,
    lieb_liniger_coupling,
    lieb_liniger_energy,
    lieb_liniger_pair_correlation,
    lieb_liniger_rapidity_density,
    lieb_liniger_strong_coupling_energy,
    lieb_liniger_weak_coupling_energy,
    tonks_girardeau_energy,
)

# %%
# Ground-state energy from weak to strong coupling
# ------------------------------------------------
# The exact :math:`e(\gamma)` interpolates between the Bogoliubov series and
# the strong-coupling expansion about the Tonks-Girardeau value.
gammas = np.logspace(-3, 3, 40)
e = np.array([lieb_liniger_energy(g) for g in gammas])
weak = lieb_liniger_weak_coupling_energy(gammas)
strong = lieb_liniger_strong_coupling_energy(gammas)

fig1, ax = plt.subplots(figsize=(6.5, 4.2))
ax.loglog(gammas, e, "k-", lw=2, label="Bethe ansatz (exact)")
ax.loglog(gammas[gammas < 3], weak[gammas < 3], "--", color="royalblue", label="Bogoliubov series")
ax.loglog(gammas[gammas > 3], strong[gammas > 3], "--", color="firebrick", label="strong-coupling series")
ax.axhline(tonks_girardeau_energy(), color="0.5", ls=":", label=r"Tonks-Girardeau $\pi^2/3$")
ax.set_xlabel(r"$\gamma = c/n$")
ax.set_ylabel(r"$e(\gamma) = E/(N n^2)$")
ax.legend(fontsize=8)
fig1.tight_layout()

# %%
# Rapidities: from a semicircle to a Fermi sea
# --------------------------------------------
# With rapidities scaled to the Fermi rapidity :math:`q`, the density
# :math:`g(k/q)` is a semicircle at weak coupling and flattens to the
# free-fermion value :math:`1/(2\pi)` as :math:`\gamma\to\infty`. Each
# curve is normalized to unit area to compare shapes.
fig2, ax = plt.subplots(figsize=(6.5, 4.2))
for gamma, color in [(1e-3, "royalblue"), (0.1, "teal"), (1.0, "goldenrod"), (10.0, "darkorange"), (1e3, "firebrick")]:
    x, w, g = lieb_liniger_rapidity_density(lieb_liniger_coupling(gamma))
    ax.plot(x, g / (w @ g), color=color, label=rf"$\gamma={gamma:g}$")
xs = np.linspace(-1, 1, 201)
ax.plot(xs, 2 / np.pi * np.sqrt(1 - xs**2), "k:", label="semicircle")
ax.set_xlabel(r"$k/q$")
ax.set_ylabel("normalized rapidity density")
ax.legend(fontsize=8)
fig2.tight_layout()

# %%
# Fermionization: the bosons stop meeting
# ---------------------------------------
# The probability of finding two bosons at the same point,
# :math:`g_2(0) = de/d\gamma`, falls from 1 (a condensate) to
# :math:`4\pi^2/(3\gamma^2)`: at large :math:`\gamma` the bosons avoid each
# other as if obeying Pauli exclusion.
g2_gammas = np.logspace(-2.5, 3, 25)
g2 = np.array([lieb_liniger_pair_correlation(g) for g in g2_gammas])
fig3, ax = plt.subplots(figsize=(6.5, 4.2))
ax.loglog(g2_gammas, g2, "ko", mfc="none", label="exact")
ax.loglog(g2_gammas[g2_gammas < 0.3], 1 - 2 * np.sqrt(g2_gammas[g2_gammas < 0.3]) / np.pi, "--", color="royalblue", label=r"$1-2\sqrt{\gamma}/\pi$")
ax.loglog(g2_gammas[g2_gammas > 3], 4 * np.pi**2 / (3 * g2_gammas[g2_gammas > 3] ** 2), "--", color="firebrick", label=r"$4\pi^2/(3\gamma^2)$")
ax.set_xlabel(r"$\gamma$")
ax.set_ylabel(r"$g_2(0)$")
ax.legend(fontsize=8)
fig3.tight_layout()

# %%
# Finite rings converge to the thermodynamic limit
# ------------------------------------------------
# Solving the Bethe equations for :math:`N` bosons on a ring of length
# :math:`L=N` (unit density, :math:`\gamma=1`) gives an energy per particle
# that approaches :math:`e(1)` as :math:`1/N^2`.
Ns = np.array([4, 8, 16, 32, 64, 128])
eN = np.array([np.sum(lieb_liniger_bethe_rapidities(N, float(N), 1.0) ** 2) / N for N in Ns])
e1 = lieb_liniger_energy(1.0)
fig4, ax = plt.subplots(figsize=(6.5, 4.2))
ax.loglog(Ns, np.abs(eN - e1), "ko-", label=r"$|E_N/N - e(1)|$")
ax.loglog(Ns, np.abs(eN[-1] - e1) * (Ns[-1] / Ns) ** 2, "--", color="0.5", label=r"$\propto N^{-2}$")
ax.set_xlabel(r"$N$")
ax.set_ylabel("finite-size error")
ax.legend(fontsize=8)
fig4.tight_layout()
plt.show()
print(f"e(1) = {e1:.10f}; Tonks-Girardeau pi^2/3 = {tonks_girardeau_energy():.10f}")

# %%
# Check
# -----
# The exact energy matches the Bogoliubov series at weak coupling and the
# strong-coupling series near the Tonks-Girardeau limit; finite rings with
# infinite coupling reproduce free fermions; :math:`g_2(0)` decreases
# monotonically to its fermionized limit; and the finite-size error falls
# as :math:`1/N^2`.
assert abs(e[0] - weak[0]) < 1e-9
assert abs(e[-1] - strong[-1]) < 1e-7 and e[-1] < tonks_girardeau_energy()
assert np.all(np.diff(e) > 0)
for N in (3, 6):
    k = lieb_liniger_bethe_rapidities(N, float(N), 1e12)
    assert abs(np.sum(k**2) / N - tonks_girardeau_energy(N)) < 1e-9
assert np.all(np.diff(g2) < 0) and abs(g2[-1] / (4 * np.pi**2 / 3e6) - 1) < 1e-2
ratios = np.abs(eN[:-1] - e1) / np.abs(eN[1:] - e1)
assert np.all(np.abs(ratios[2:] - 4) < 0.1)
