r"""
Baryon magnetic moments from three quarks
===========================================

If the baryons are made of quarks (Gell-Mann; Zweig, 1964), their
magnetic moments should follow from the quarks' own. Treat each quark as
a Dirac particle with :math:`\mu_q = Q_q (m_p/m_q)\,\mu_N` and combine the
spins with the symmetric SU(6) spin-flavour wavefunction. The proton is
then :math:`(4\mu_u - \mu_d)/3` and the neutron :math:`(4\mu_d - \mu_u)/3`,
so with :math:`m_u = m_d` the ratio is :math:`\mu_n/\mu_p = -2/3`,
parameter-free, against the measured :math:`-0.685` (Beg, Lee and Pais,
1964). It was among the first quantitative successes of quarks as real
constituents. This example computes the octet moments with
:func:`~physicskit.particle.quark_model.baryon_magnetic_moment`.
"""

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

from physicskit.particle.quark_model import baryon_magnetic_moment

# Measured moments in nuclear magnetons (Particle Data Group)
measured = {
    "p": 2.7928,
    "n": -1.9130,
    "Lambda": -0.613,
    "Sigma+": 2.458,
    "Sigma-": -1.160,
    "Xi0": -1.250,
    "Xi-": -0.6507,
}
predicted = {name: baryon_magnetic_moment(name) for name in measured}
for name in measured:
    print(f"{name:7s} quark model {predicted[name]:+.3f}   measured {measured[name]:+.3f}")
ratio = predicted["n"] / predicted["p"]
print(f"\nmu_n / mu_p: quark model {ratio:.4f}, measured {measured['n'] / measured['p']:.4f}")

# %%
# Prediction against measurement
# ----------------------------------
fig, ax = plt.subplots(figsize=(6, 5))
x = np.array(list(measured.values()))
y = np.array(list(predicted.values()))
ax.plot([-2.5, 3.2], [-2.5, 3.2], color="0.7", zorder=0)
ax.scatter(x, y, color="steelblue")
for name, xi, yi in zip(measured, x, y):
    ax.annotate(name, (xi, yi), textcoords="offset points", xytext=(5, -10), fontsize=8)
ax.set_xlabel(r"measured $\mu$ [$\mu_N$]")
ax.set_ylabel(r"quark model $\mu$ [$\mu_N$]")
ax.set_title(r"Octet magnetic moments: $m_u = m_d = 336$, $m_s = 509$ MeV")
fig.tight_layout()

plt.show()

# %%
# Check
# -----
# mu_n / mu_p = -2/3 exactly, within 0.03 of the measured -0.685; every
# octet moment has the measured sign and lies within 0.3 nuclear magnetons.
assert abs(ratio - (-2 / 3)) < 1e-10
assert abs(ratio - measured["n"] / measured["p"]) < 0.03
assert np.all(np.sign(x) == np.sign(y)) and np.all(np.abs(x - y) < 0.3)
