r"""
Bethe: stopping power and the Bragg peak
===========================================

A fast charged particle crossing matter slows down by knocking electrons
out of atoms, in many tiny collisions. In 1930 Hans Bethe calculated the
average energy loss per unit length quantum mechanically. In the modern
PDG form,

.. math::  -\frac{1}{\rho}\frac{dE}{dx}=Kz^2\frac{Z}{A}\frac{1}{\beta^2}
   \left[\tfrac12\ln\frac{2m_ec^2\beta^2\gamma^2W_{\max}}{I^2}-\beta^2\right],

with :math:`K=0.307` MeV cm\ :sup:`2`/mol and :math:`I` the material's
mean excitation energy (75 eV for water). The :math:`1/\beta^2` factor
means the slower the particle, the faster it loses energy. A proton
deposits most of its energy in a sharp *Bragg peak* just before it
stops, which is why proton beams can treat deep tumours while sparing the
tissue in front.

This example uses :func:`~physicskit.nuclear.stopping.bethe_stopping_power`,
:func:`~physicskit.nuclear.stopping.csda_range`, and
:func:`~physicskit.nuclear.stopping.bragg_curve` for protons in water,
compared with NIST PSTAR.
"""

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

from physicskit.nuclear.stopping import bethe_stopping_power, bragg_curve, csda_range

# %%
# Stopping power against NIST PSTAR
# -------------------------------------
pstar = {10.0: (45.67, 0.1230), 50.0: (12.45, 2.227), 100.0: (7.289, 7.718), 200.0: (4.492, 25.96)}
print(" T [MeV]   S Bethe   S PSTAR   range Bethe   range PSTAR   [MeV cm^2/g, g/cm^2]")
for T, (S_ref, R_ref) in pstar.items():
    print(f"  {T:6.0f}   {bethe_stopping_power(T):7.3f}   {S_ref:7.3f}   {csda_range(T):11.3f}   {R_ref:11.3f}")

# %%
# Bragg curves of therapy beams
# ---------------------------------
T = np.geomspace(1.0, 1e5, 500)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 4.2))
ax1.loglog(T, bethe_stopping_power(T), color="firebrick", label="Bethe (no shell/density corr.)")
ax1.loglog(list(pstar), [v[0] for v in pstar.values()], "ko", ms=4, label="NIST PSTAR")
ax1.set_xlabel("proton kinetic energy T [MeV]")
ax1.set_ylabel(r"$S=-\frac{1}{\rho}\frac{dE}{dx}$ [MeV cm$^2$/g]")
ax1.set_title(r"Protons in water: $S\propto1/\beta^2$, minimum near $\beta\gamma\approx3$")
ax1.legend(fontsize=8)

peaks = {}
for T0, c in [(70.0, "steelblue"), (110.0, "seagreen"), (150.0, "firebrick")]:
    depth, S, _ = bragg_curve(T0)
    peaks[T0] = (depth, S)
    ax2.plot(depth, S, color=c, label=f"{T0:.0f} MeV, range {depth[-1]:.1f} cm")
ax2.set_xlabel(r"depth in water [g/cm$^2$ = cm]")
ax2.set_ylabel("energy deposited [MeV cm$^2$/g]")
ax2.set_title("Bragg peaks: dose concentrated at the end of range")
ax2.legend(fontsize=8)
fig.tight_layout()

plt.show()

depth, S = peaks[150.0]
print(f"\n150 MeV proton: entrance S = {S[0]:.2f}, peak/entrance ratio = {S.max() / S[0]:.0f} (no straggling)")

# %%
# Check
# -----
# Stopping power and range within 1% of PSTAR from 10 to 200 MeV; the
# deposit peaks at the end of the track.
for T0, (S_ref, R_ref) in pstar.items():
    assert abs(bethe_stopping_power(T0) / S_ref - 1) < 0.01
    if T0 >= 50:
        assert abs(csda_range(T0) / R_ref - 1) < 0.01
assert np.argmax(S) == len(S) - 1 and S.max() > 3 * S[0]
