r"""
The Geiger-Nuttall law: alpha decay as tunnelling
===================================================

In 1911 Geiger and Nuttall noticed that the alpha emitters with the
longest ranges, the most energetic alphas, had the shortest lives, and
that the logarithm of the decay constant fell on a straight line against
the logarithm of the range. Across the even-even isotopes from polonium
to uranium, a factor of two in alpha energy spans more than twenty
orders of magnitude in half-life. Written in terms of the decay energy,
the law is

.. math::

    \log_{10} t_{1/2} = a\,\frac{Z}{\sqrt{Q}} + b.

Nobody could say why until 1928, when quantum tunnelling through the
Coulomb barrier explained it. This example fits the law to measured
half-lives with :func:`~physicskit.nuclear.alpha_decay.geiger_nuttall_fit`
and compares them with the WKB half-lives of
:func:`~physicskit.nuclear.alpha_decay.alpha_half_life`, whose Gamow factor
(:func:`~physicskit.nuclear.alpha_decay.gamow_factor`) grows as
:math:`Z/\sqrt{Q}`.
"""

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

from physicskit.nuclear.alpha_decay import alpha_half_life, geiger_nuttall_fit

YEAR, DAY, MINUTE = 3.15576e7, 86400.0, 60.0
# Even-even alpha emitters: (Z, A, Q [MeV], half-life [s]). Half-lives from NUBASE2020.
DATA = {
    "Po": [(84, 210, 5.4075, 138.376 * DAY), (84, 212, 8.954, 294.4e-9), (84, 214, 7.8335, 163.47e-6),
           (84, 216, 6.9063, 0.1437), (84, 218, 6.1147, 3.097 * MINUTE)],
    "Rn": [(86, 218, 7.2625, 33.75e-3), (86, 220, 6.4047, 55.6), (86, 222, 5.5903, 3.8215 * DAY)],
    "Ra": [(88, 224, 5.7887, 3.6316 * DAY), (88, 226, 4.8706, 1600 * YEAR)],
    "Th": [(90, 228, 5.5201, 1.9125 * YEAR), (90, 230, 4.7700, 7.54e4 * YEAR), (90, 232, 4.0816, 1.40e10 * YEAR)],
    "U": [(92, 232, 5.4136, 68.9 * YEAR), (92, 234, 4.8575, 2.455e5 * YEAR), (92, 236, 4.5733, 2.342e7 * YEAR),
          (92, 238, 4.2697, 4.463e9 * YEAR)],
}  # fmt: skip

# %%
# One straight line per element
# ---------------------------------
fits = {}
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 4.8))
for element, rows in DATA.items():
    Z, A, Q, t = (np.array(c, dtype=float) for c in zip(*rows))
    fits[element] = geiger_nuttall_fit(Z - 2, Q, t)
    slope, intercept, r = fits[element]
    x = (Z - 2) / np.sqrt(Q)
    (line,) = ax1.plot(x, np.log10(t), "o", label=element)
    xs = np.linspace(x.min(), x.max(), 2)
    ax1.plot(xs, slope * xs + intercept, color=line.get_color(), lw=1)
    print(f"{element}: slope {slope:.2f}, r = {r:.4f}")
ax1.set_xlabel(r"$Z_\mathrm{daughter}/\sqrt{Q}$  [MeV$^{-1/2}$]")
ax1.set_ylabel(r"$\log_{10} t_{1/2}$ [s]")
ax1.set_title("Geiger-Nuttall law")
ax1.legend()

# %%
# Tunnelling reproduces the measured half-lives
# -------------------------------------------------
# The WKB half-life misses by at most a couple of decades, across a range
# of more than 24.
all_rows = [row for rows in DATA.values() for row in rows]
Z, A, Q, t_meas = (np.array(c, dtype=float) for c in zip(*all_rows))
t_wkb = np.array([alpha_half_life(int(z), int(a), q) for z, a, q in zip(Z, A, Q)])
ax2.loglog(t_meas, t_wkb, "o", color="steelblue")
lim = [1e-8, 1e19]
ax2.plot(lim, lim, color="k", lw=1)
ax2.fill_between(lim, np.array(lim) / 100, np.array(lim) * 100, color="0.9", label="factor of 100")
ax2.set_xlabel("measured $t_{1/2}$ [s]")
ax2.set_ylabel("WKB (Gamow) $t_{1/2}$ [s]")
ax2.set_title("Gamow-Gurney-Condon tunnelling")
ax2.legend()
fig.tight_layout()

t_U238 = alpha_half_life(92, 238, 4.2697)
t_Po212 = alpha_half_life(84, 212, 8.954)
print(f"\nU-238:  WKB {t_U238 / YEAR:.2e} yr, measured 4.46e9 yr")
print(f"Po-212: WKB {t_Po212 * 1e6:.3f} us, measured 0.294 us")

plt.show()

# %%
# Check
# -----
# log10 t is linear in Z/sqrt(Q) for every element from Po to U, and the
# WKB half-lives of U-238 and Po-212, 24 decades apart, are each within
# a factor of 100 of the measured ones.
assert all(r > 0.99 and slope > 0 for slope, _, r in fits.values())
assert abs(np.log10(t_U238 / (4.463e9 * YEAR))) < 2
assert abs(np.log10(t_Po212 / 294.4e-9)) < 2
assert np.log10(t_meas.max() / t_meas.min()) > 24
