r"""
Wilson and Fisher's epsilon expansion
=====================================

Landau theory gives the same critical exponents in every dimension, and
they are wrong below four. Wilson and Fisher (1972) computed the
corrections by treating the dimension as a continuous parameter and
expanding in :math:`\epsilon = 4 - d`. Integrating out a momentum shell of
the Landau-Ginzburg-Wilson model of an :math:`n`-component field, to first
order in the quartic coupling :math:`u`, gives the flow (Kardar,
*Statistical Physics of Fields*, eq. 5.38)

.. math::

    \frac{dt}{d\ell} = 2t + \frac{4u(n+2)K_d}{1+t}, \qquad
    \frac{du}{d\ell} = \epsilon u - \frac{4u^2(n+8)K_d}{(1+t)^2}.

Above four dimensions :math:`u` is irrelevant and the critical surface
flows into the Gaussian fixed point, so Landau's exponents are exact.
Below four, :math:`u` grows, and the flow runs to a new fixed point at
:math:`u^* K_d = \epsilon/(4(n+8))`, the Wilson-Fisher point. Its one
relevant eigenvalue :math:`y_t = 2 - \frac{n+2}{n+8}\epsilon` gives

.. math::

    \nu = \frac{1}{2} + \frac{n+2}{4(n+8)}\,\epsilon, \qquad \eta = 0
    \qquad (+\,O(\epsilon^2)).
"""

import matplotlib.pyplot as plt
import numpy as np

from physicskit.statphys.chapters.epsilon_expansion import (
    epsilon_expansion_exponents,
    lgw_angular_factor,
    lgw_beta_functions,
    lgw_critical_t,
    lgw_flow,
    lgw_scaling_eigenvalues,
    wilson_fisher_fixed_point,
)

# %%
# The flow of the Ising model (n = 1) in three dimensions
# --------------------------------------------------------
# Streamlines show the flow in the plane of :math:`t` and the rescaled
# coupling :math:`u K_d`. The critical trajectory (black) starts next to the
# Gaussian point, on the critical surface found by bisection, and runs into
# the Wilson-Fisher point; it is drawn up to its closest approach. Starts
# just off the critical surface follow it to the fixed point and then run
# away along the relevant direction, to the ordered (:math:`t \to -\infty`,
# blue) or disordered (:math:`t \to +\infty`, red) phase.
n, d = 1, 3.0
K_d = lgw_angular_factor(d)
t_star, u_star = wilson_fisher_fixed_point(n, d)

T, U = np.meshgrid(np.linspace(-0.45, 0.3, 40), np.linspace(0.0, 0.05, 40))
dT, dU = lgw_beta_functions(T, U / K_d, n, d)
fig, ax = plt.subplots(figsize=(7, 5))
ax.streamplot(T, U, dT, dU * K_d, color="0.7", density=1.2, linewidth=0.8)

u0 = 1e-3
t_c = lgw_critical_t(u0, n, d)
l, t, u = lgw_flow(t_c, u0, n, d, l_max=40.0, num=2000)
i_wf = np.argmin(np.hypot(t - t_star, u - u_star))
ax.plot(t[: i_wf + 1], u[: i_wf + 1] * K_d, "k-", lw=2, label="critical trajectory")
for dt0, color in [(1e-10, "tab:red"), (-1e-10, "tab:blue")]:
    _, t_off, u_off = lgw_flow(t_c + dt0, u0, n, d, l_max=40.0, num=2000)
    ax.plot(t_off, u_off * K_d, color=color, lw=1.2)
ax.plot(0, 0, "o", color="tab:green", ms=9, label="Gaussian")
ax.plot(t_star, u_star * K_d, "*", color="tab:orange", ms=16, label="Wilson-Fisher")
ax.set(xlim=(-0.45, 0.3), ylim=(0, 0.05), xlabel="$t$", ylabel="$u K_d$", title="One-loop RG flow, $n=1$, $d=3$")
ax.legend(loc="upper right")
plt.tight_layout()

# %%
# The correlation-length exponent
# -------------------------------
# :math:`\nu = 1/y_t` from linearizing the flow at the Wilson-Fisher point
# (dots) follows the first-order formula (lines) as :math:`\epsilon \to 0`.
# Extrapolated to :math:`\epsilon = 1` the formula already moves Landau's
# 1/2 more than halfway to the three-dimensional values from simulations
# and the conformal bootstrap (crosses). Higher orders in :math:`\epsilon`
# close most of the rest.
eps_grid = np.linspace(0.0, 1.0, 101)
eps_dots = np.array([0.05, 0.1, 0.2, 0.3, 0.5])
nu_3d = {1: 0.630, 2: 0.672, 3: 0.711}
fig, ax = plt.subplots(figsize=(7, 5))
for n_comp, color in zip((1, 2, 3), ("tab:blue", "tab:orange", "tab:green")):
    nu_formula = [epsilon_expansion_exponents(n_comp, e)["nu"] for e in eps_grid]
    ax.plot(eps_grid, nu_formula, color=color, label=f"$n={n_comp}$")
    nu_lin = [1 / lgw_scaling_eigenvalues(*wilson_fisher_fixed_point(n_comp, 4 - e), n_comp, 4 - e)[0] for e in eps_dots]
    ax.plot(eps_dots, nu_lin, "o", color=color, ms=5)
    ax.plot(1.0, nu_3d[n_comp], "x", color=color, ms=10, mew=2)
ax.axhline(0.5, color="0.5", ls=":", label="Landau")
ax.set(xlabel=r"$\epsilon = 4 - d$", ylabel=r"$\nu$", title=r"$\nu = 1/2 + (n+2)\epsilon / (4(n+8))$")
ax.legend()
plt.tight_layout()
plt.show()

# %%
# Check
# -----
# The fixed point and the exponents agree with the first-order formulas to
# O(epsilon^2), the critical trajectory starts at the Gaussian point and
# reaches the Wilson-Fisher one, and eta = 0 at this order.
for n_comp in (1, 2, 3):
    eps = 1e-3
    y_t, y_u = lgw_scaling_eigenvalues(*wilson_fisher_fixed_point(n_comp, 4 - eps), n_comp, 4 - eps)
    exps = epsilon_expansion_exponents(n_comp, eps)
    assert abs(1 / y_t - (0.5 + (n_comp + 2) * eps / (4 * (n_comp + 8)))) < eps**2
    assert abs(1 / y_t - exps["nu"]) < eps**2
    assert y_u < 0 < y_t
    assert exps["eta"] == 0.0

assert np.allclose(sorted(lgw_scaling_eigenvalues(0.0, 0.0, n, d)), [1.0, 2.0])  # u relevant at d = 3
assert np.hypot(t[0], u[0]) < 0.01 * u_star
assert np.min(np.hypot(t - t_star, u - u_star)) < 1e-3 * u_star
assert abs(epsilon_expansion_exponents(1, 1.0)["nu"] - 7 / 12) < 1e-12
