r"""
The 21 cm line: hyperfine splitting of hydrogen
===============================================

The electron and proton spins in the hydrogen ground state couple, through
Fermi's contact interaction, to a triplet :math:`F = 1` and a singlet
:math:`F = 0`. :func:`~physicskit.quantum.chapters.angular_momentum.hyperfine_splitting_hydrogen`
gives the splitting, :math:`5.88\times10^{-6}` eV, a photon of 1420 MHz
and 21.1 cm. Van de Hulst predicted in 1944 that interstellar hydrogen
should glow at this wavelength; Ewen and Purcell detected it in 1951.
Below, the same spin Hamiltonian is diagonalized with the coupled basis of
:func:`~physicskit.quantum.chapters.angular_momentum.couple_spins` in a
magnetic field, which separates the triplet (the Breit-Rabi diagram).
"""

import matplotlib.pyplot as plt
import numpy as np
import scipy.constants as sc

from physicskit.quantum.chapters.angular_momentum import couple_spins, hyperfine_splitting_hydrogen
from physicskit.quantum.core.operators import spin_operator

hf = hyperfine_splitting_hydrogen()
hf_corr = hyperfine_splitting_hydrogen(corrected=True)
print(f"Fermi formula:        {hf.energy_ev:.4e} eV, {hf.frequency_hz / 1e6:.2f} MHz, {hf.wavelength_m * 100:.2f} cm")
print(f"with g_e and m_red:   {hf_corr.frequency_hz / 1e6:.2f} MHz (measured 1420.41 MHz)")

# %%
# Triplet and singlet in a magnetic field
# ---------------------------------------
#
# :math:`H = A\,\mathbf S_e\cdot\mathbf S_p + 2\mu_B B\,S_{e,z}` (the
# proton's Zeeman term is 660 times smaller and left out). At :math:`B = 0`
# the levels are :math:`A/4` (three-fold) and :math:`-3A/4`.

A = hf.energy_ev
basis = couple_spins(0.5, 0.5)
Sez = np.kron(spin_operator("z"), np.eye(2))
muB = sc.physical_constants["Bohr magneton in eV/T"][0]
B = np.linspace(0, 0.15, 300)  # tesla
levels = np.array([np.linalg.eigvalsh(A * basis.s1_dot_s2_operator() + 2 * muB * b * Sez) for b in B])

x = 2 * muB * B / A
breit_rabi_pm = -A / 4 + np.outer(np.sqrt(1 + x**2), [-A / 2, A / 2])

fig, ax = plt.subplots(figsize=(8, 5))
ax.plot(B * 1e3, levels / A, lw=2)
ax.plot(B * 1e3, breit_rabi_pm / A, "k:", lw=1, label="Breit-Rabi formula")
ax.annotate("F = 1", (2, 0.33))
ax.annotate("F = 0", (2, -0.68))
ax.set_xlabel("B (mT)")
ax.set_ylabel("E / A")
ax.set_title(f"Hydrogen 1s hyperfine levels, A = {A * 1e6:.2f} µeV ↔ {hf.wavelength_m * 100:.1f} cm")
ax.legend()
fig.tight_layout()

# %%
# Check
# -----
# Splitting 5.88e-6 eV, 1421 MHz and 21.1 cm from the Fermi formula; with
# the electron's anomaly and the reduced mass it is within 1e-4 of the
# measured 1420.405751 MHz. At B = 0 the levels are A/4 (three times) and
# -3A/4, and the two M = 0 levels follow the Breit-Rabi formula
# -A/4 +- (A/2) sqrt(1 + x^2) at every field.
assert abs(hf.energy_ev - 5.88e-6) < 0.01e-6
assert abs(hf.wavelength_m - 0.211) < 0.001
assert abs(hf_corr.frequency_hz / 1420.405751e6 - 1) < 1e-4
assert np.allclose(levels[0] / A, [-0.75, 0.25, 0.25, 0.25])
assert np.allclose(levels[:, 0] / A, breit_rabi_pm[:, 0] / A)
assert np.max(np.min(np.abs(levels - breit_rabi_pm[:, [1]]), axis=1)) / A < 1e-10
