r"""
The nuclear shell model: magic numbers from spin-orbit coupling
=================================================================

Nuclei with 2, 8, 20, 28, 50, 82 or 126 protons or neutrons are
unusually stable: more isotopes, larger separation energies, near-zero
quadrupole moments. A nucleon moving in a smooth mean-field well should
fill shells like an electron in an atom, but the obvious wells get the
numbers wrong. The harmonic oscillator closes at 2, 8, 20, 40, 70, 112,
and a rounder Woods-Saxon well does little better. In 1949 Maria Goeppert
Mayer, and independently Haxel, Jensen and Suess, added a strong
spin-orbit force, :math:`V_{\ell s}(r)\,\boldsymbol\ell\cdot\mathbf s`,
that pulls the :math:`j = \ell + 1/2` level of each high-:math:`\ell`
orbit down into the shell below. The :math:`1f_{7/2}`, :math:`1g_{9/2}`,
:math:`1h_{11/2}` and :math:`1i_{13/2}` intruders then make exactly the
observed magic numbers. This example solves the radial Schrodinger
equation in each well with
:func:`~physicskit.nuclear.structure.shell_model_levels` and reads off
the closures and the spin and parity of the last nucleon.
"""

# %%
import matplotlib.pyplot as plt

from physicskit.nuclear.structure import last_nucleon_spin_parity, shell_closures, shell_model_levels

A = 140
wells = {
    "harmonic oscillator": shell_model_levels(A, well="oscillator"),
    "Woods-Saxon": shell_model_levels(A, spin_orbit=False),
    "Woods-Saxon + spin-orbit": shell_model_levels(A),
}
closures = {name: shell_closures(levels, A) for name, levels in wells.items()}
for name, magic in closures.items():
    print(f"{name:26s} closures: {magic}")

# %%
# The three level schemes
# ---------------------------
# Each level holds :math:`2j+1` nucleons; the number above a gap is how
# many nucleons fill everything below it.
hw = 41.0 * A ** (-1 / 3)
fig, axes = plt.subplots(1, 3, figsize=(12, 8))
for ax, (name, levels) in zip(axes, wells.items()):
    filled = 0
    for k, lv in enumerate(levels):
        filled += lv.degeneracy
        upper = levels[k + 1] if k + 1 < len(levels) else None
        if upper is not None and abs(upper.energy - lv.energy) < 0.01 * hw:
            continue  # degenerate levels share one line
        ax.hlines(lv.energy, 0, 1, color="steelblue")
        if name == "harmonic oscillator":
            label = f"N = {2 * (lv.n - 1) + lv.l}"
        else:
            label = lv.label if name.endswith("spin-orbit") else lv.label[:2]
        ax.text(1.03, lv.energy, label, fontsize=7, va="center")
        if upper is not None and upper.energy - lv.energy > 0.3 * hw:
            ax.text(-0.05, (lv.energy + upper.energy) / 2, str(filled), color="firebrick", ha="right", va="center")
    ax.set_xlim(-0.4, 1.5)
    ax.set_xticks([])
    ax.set_title(name)
axes[0].set_ylabel("single-particle energy [MeV]")
fig.suptitle(f"Neutron levels for A = {A}; red: nucleons filled at each shell closure")
fig.tight_layout()

# %%
# The spin and parity of the odd nucleon
# ------------------------------------------
# An odd-A nucleus takes its ground-state spin and parity from the last,
# unpaired nucleon. Oxygen-17 has one neutron outside the N = 8 core, in
# :math:`1d_{5/2}`; lead-209 has one outside N = 126, in :math:`2g_{9/2}`.
jp_O17 = last_nucleon_spin_parity(shell_model_levels(17), 9)
jp_Pb209 = last_nucleon_spin_parity(shell_model_levels(209), 127)
print(f"\nO-17:   {jp_O17}  (measured 5/2+)")
print(f"Pb-209: {jp_Pb209}  (measured 9/2+)")

plt.show()

# %%
# Check
# -----
# The oscillator closes at 2, 8, 20, 40, 70, 112; only with spin-orbit
# coupling do the closures become 2, 8, 20, 28, 50, 82, 126; and the last
# nucleon gives 5/2+ for O-17 and 9/2+ for Pb-209.
assert closures["harmonic oscillator"][:6] == [2, 8, 20, 40, 70, 112]
assert closures["Woods-Saxon + spin-orbit"][:7] == [2, 8, 20, 28, 50, 82, 126]
assert not {28, 50, 82, 126} & set(closures["Woods-Saxon"])
assert jp_O17 == "5/2+" and jp_Pb209 == "9/2+"
