r"""
Langevin and Curie: diamagnetism, paramagnetism and Curie's law
===============================================================

Curie (1895) found that the susceptibility of paramagnetic salts falls as
:math:`1/T`. Langevin (1905) explained it with permanent moments aligned
against thermal agitation, :math:`M \propto L(\mu B/k_BT)`
(:func:`~physicskit.condensed.magnetism.langevin_function`), and derived
the small negative diamagnetism of closed shells,
:math:`\chi = -\mu_0 nZe^2\langle r^2\rangle/6m`
(:func:`~physicskit.condensed.magnetism.langevin_diamagnetic_susceptibility`).
Quantised moments replace Langevin's function by Brillouin's
(:func:`~physicskit.condensed.magnetism.brillouin_function`); in weak
fields both give Curie's law
:math:`\chi = \mu_0 n g^2\mu_B^2 J(J+1)/3k_BT`
(:func:`~physicskit.condensed.magnetism.curie_susceptibility`). The
conduction electrons of a metal are the quantum exception: their Pauli spin
susceptibility is independent of temperature and Landau's orbital
diamagnetism cancels a third of it
(:func:`~physicskit.condensed.magnetism.pauli_susceptibility`,
:func:`~physicskit.condensed.magnetism.landau_susceptibility`).
"""

import matplotlib.pyplot as plt
import numpy as np
from scipy.constants import N_A, physical_constants

from physicskit.condensed.magnetism import (
    MU_B,
    brillouin_function,
    curie_susceptibility,
    landau_susceptibility,
    langevin_diamagnetic_susceptibility,
    langevin_function,
    paramagnetic_magnetization,
    pauli_susceptibility,
)

K_B = physical_constants["Boltzmann constant"][0]

# %%
# Brillouin functions saturate; Langevin's is the classical limit
# ---------------------------------------------------------------

x = np.linspace(0, 6, 300)
fig, axes = plt.subplots(1, 2, figsize=(12, 4.5))
for J in [0.5, 1.5, 3.5]:
    axes[0].plot(x, brillouin_function(J, x), lw=2, label=f"$B_J$, J = {J}")
axes[0].plot(x, langevin_function(x), "k--", lw=1.5, label=r"Langevin $L(x)$, $J\to\infty$")
axes[0].set_xlabel(r"$x = g\mu_B J B / k_BT$")
axes[0].set_ylabel(r"$M / M_s$")
axes[0].legend(fontsize=8)
axes[0].set_title("Paramagnetic saturation")

# %%
# Magnetization depends on B and T only through B/T
# -------------------------------------------------
#
# A spin-7/2 ion (Gd\ :sup:`3+`) at several temperatures falls on one curve,
# and :math:`1/\chi` is a straight line through the origin: Curie's law.

n, J = 1e28, 3.5
B = np.linspace(0, 7, 200)
for T in [1.3, 2.0, 3.0, 4.2]:
    M = paramagnetic_magnetization(n, J, B, T)
    axes[1].plot(B / T, M / (n * 2 * J * MU_B), lw=2, label=f"T = {T} K")
axes[1].set_xlabel("B / T  (T/K)")
axes[1].set_ylabel(r"$M / M_s$")
axes[1].legend(fontsize=8)
axes[1].set_title("Gd$^{3+}$-like moments, J = 7/2")
fig.tight_layout()

# %%
# Susceptibilities compared
# -------------------------

Ts = np.linspace(1, 300, 200)
chi_curie = curie_susceptibility(n, J, Ts)
n_Na = 2.65e28
chi_dia = langevin_diamagnetic_susceptibility(n_Na, Z=10, r2_mean=(0.5e-10) ** 2)
fig2, ax2 = plt.subplots(figsize=(7, 4.5))
ax2.plot(Ts, 1 / chi_curie, lw=2, label=r"$1/\chi$, Curie paramagnet")
ax2.set_xlabel("T (K)")
ax2.set_ylabel(r"$1/\chi$")
ax2.set_title(
    f"Pauli (Na): {pauli_susceptibility(n_Na):.1e}, Landau: {landau_susceptibility(n_Na):.1e}, core diamagnetism: {chi_dia:.1e}",
    fontsize=9,
)
ax2.legend(fontsize=8)
fig2.tight_layout()

# %%
# Check
# -----
# B_{1/2} = tanh, the Curie constant from the small-field slope of M(B),
# 1/chi linear in T, and chi_Landau = -chi_Pauli / 3. Atomic hydrogen
# (<r^2> = 3 a0^2) has chi_molar = -2.36e-6 cm^3/mol in CGS.
np.testing.assert_allclose(brillouin_function(0.5, x), np.tanh(x), atol=1e-14)
chi_from_M = 4e-7 * np.pi * paramagnetic_magnetization(n, J, 1e-4, 10.0) / 1e-4
assert abs(chi_from_M / curie_susceptibility(n, J, 10.0) - 1) < 1e-6
assert np.allclose(np.polyfit(Ts, 1 / chi_curie, 1)[1], 0.0, atol=1e-8 * (1 / chi_curie[-1]))
assert abs(landau_susceptibility(n_Na) + pauli_susceptibility(n_Na) / 3) < 1e-20
a0 = physical_constants["Bohr radius"][0]
chi_H = langevin_diamagnetic_susceptibility(N_A, Z=1, r2_mean=3 * a0**2) / (4 * np.pi * 1e-6)
assert abs(chi_H / -2.36e-6 - 1) < 0.01
