r"""
Weiss's molecular field: spontaneous magnetization of a ferromagnet
===================================================================

Weiss (1907) proposed that each moment in a ferromagnet feels an internal
"molecular field" proportional to the magnetization itself. The paramagnet
then has to be consistent with its own field,
:math:`\sigma = B_S(3S\sigma T_c/(S+1)T)`, and below the Curie temperature
:math:`T_c = 2zJS(S+1)/3` (:func:`~physicskit.condensed.magnetism.curie_temperature`)
a nonzero root appears: spontaneous magnetization
(:func:`~physicskit.condensed.magnetism.weiss_magnetization`). Just below
:math:`T_c` it rises as :math:`\sqrt{T_c - T}`, the mean-field exponent
:math:`\beta = 1/2`; above :math:`T_c` the susceptibility follows the
Curie-Weiss law :math:`\chi \propto 1/(T - T_c)`. The 2D Ising model
(:class:`physicskit.statphys.chapters.ising_lattice.Ising2D`) is the exactly
solvable counterpart, with :math:`\beta = 1/8`.
"""

import matplotlib.pyplot as plt
import numpy as np

from physicskit.condensed.magnetism import brillouin_function, curie_temperature, weiss_magnetization

J, z = 1.0, 6

# %%
# The graphical solution
# ----------------------
#
# Self-consistency is where the line :math:`\sigma` crosses
# :math:`B_{1/2}(\sigma T_c/T) = \tanh(\sigma T_c/T)`.

sig = np.linspace(0, 1.2, 300)
fig, axes = plt.subplots(1, 2, figsize=(12, 4.5))
for t in [0.5, 0.8, 1.0, 1.5]:
    axes[0].plot(sig, brillouin_function(0.5, sig / t), lw=2, label=f"$T/T_c$ = {t}")
axes[0].plot(sig, sig, "k--", lw=1, label=r"$\sigma$")
axes[0].set_xlabel(r"$\sigma$")
axes[0].set_ylabel(r"$B_{1/2}(\sigma T_c / T)$")
axes[0].legend(fontsize=8)
axes[0].set_title("Self-consistency, S = 1/2")

# %%
# Spontaneous magnetization for several spins
# -------------------------------------------

t = np.linspace(0.01, 1.2, 300)
for S in [0.5, 1.0, 3.5]:
    Tc = curie_temperature(J, S, z)
    axes[1].plot(t, weiss_magnetization(t * Tc, J, S, z), lw=2, label=f"S = {S}")
axes[1].plot(t[t < 1], np.sqrt(3 * (1 - t[t < 1])), "k:", lw=1, label=r"$\sqrt{3(1-T/T_c)}$")
axes[1].set_ylim(0, 1.05)
axes[1].set_xlabel(r"$T / T_c$")
axes[1].set_ylabel(r"$M(T) / M(0)$")
axes[1].legend(fontsize=8)
axes[1].set_title("Weiss mean field")
fig.tight_layout()

# %%
# Curie-Weiss susceptibility above T_c
# ------------------------------------

S = 0.5
Tc = curie_temperature(J, S, z)
h = 1e-6
T_above = np.linspace(1.1, 3.0, 30) * Tc
chi = np.array([weiss_magnetization(T, J, S, z, field=h) for T in T_above]) / h
fig2, ax2 = plt.subplots(figsize=(7, 4.5))
ax2.plot(T_above / Tc, 1 / chi, "o-", lw=1.5)
ax2.set_xlabel(r"$T / T_c$")
ax2.set_ylabel(r"$1/\chi$ (reduced)")
ax2.set_title(r"Curie-Weiss law: $1/\chi \propto T - T_c$")
fig2.tight_layout()

# %%
# Check
# -----
# T_c = 2zJS(S+1)/3; sigma vanishes above T_c and saturates at T -> 0;
# the S = 1/2 onset follows sqrt(3(1 - T/T_c)); 1/chi extrapolates to
# zero at T_c.
assert curie_temperature(J, 0.5, z) == 3.0
assert weiss_magnetization(1.01 * Tc, J, S, z) == 0.0
assert abs(weiss_magnetization(1e-3 * Tc, J, S, z) - 1) < 1e-9
assert abs(weiss_magnetization(0.9999 * Tc, J, S, z) / np.sqrt(3e-4) - 1) < 1e-3
slope, intercept = np.polyfit(T_above, 1 / chi, 1)
assert abs(-intercept / slope / Tc - 1) < 1e-3
