r"""
Schönberg and Chandrasekhar's isothermal-core limit
===================================================

A star stays on the main sequence while its core burns hydrogen. When the
hydrogen there is spent, the helium core left behind has no energy source,
so it settles to the temperature of the hydrogen-burning shell around it
and becomes isothermal. In 1942 Mario Schönberg and Subrahmanyan
Chandrasekhar showed that such a core can hold up the envelope above it
only while it is small:

.. math::

    \left(\frac{M_{\rm core}}{M}\right)_{\rm SC}
    \approx 0.37\left(\frac{\mu_{\rm env}}{\mu_{\rm core}}\right)^2
    \approx 0.08.

A core that grows past this fraction contracts on the Kelvin-Helmholtz
time scale, and the star leaves the main sequence. That is why a star
burns only about a tenth of its hydrogen there, and so why its
main-sequence lifetime is :math:`\tau\approx 0.1\times 0.007\,Mc^2/L`,
about 10 Gyr for the Sun and falling as :math:`M^{-2.5}`.

The functions used here are
:func:`~physicskit.astro.stellar_structure.isothermal_core_pressure`,
:func:`~physicskit.astro.stellar_structure.isothermal_core_max_pressure`,
:func:`~physicskit.astro.stellar_structure.schonberg_chandrasekhar_limit`
and :func:`~physicskit.astro.stellar_structure.main_sequence_lifetime`.
"""

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

from physicskit.astro.stellar_structure import (
    isothermal_core_max_pressure,
    isothermal_core_pressure,
    main_sequence_lifetime,
    schonberg_chandrasekhar_limit,
)

# %%
# An isothermal core can push back only so hard
# ---------------------------------------------
# An isothermal sphere of mass :math:`M_c` and sound speed :math:`c_s`,
# cut at the dimensionless radius :math:`\xi_0`, has surface pressure
# :math:`P = f(\xi_0)\,c_s^8/(G^3M_c^2)`. Squeezing the sphere (moving
# :math:`\xi_0` outwards at fixed mass) first raises :math:`f`, then
# lowers it: there is a largest pressure the core can hold.
xi0 = np.linspace(0.05, 30.0, 1500)
f = isothermal_core_pressure(xi0)
P_max, f_max, xi_max = isothermal_core_max_pressure(1.0, 1.0, return_details=True)
print(f"maximum surface pressure: {f_max:.4f} c_s^8 / (G^3 M_c^2), at xi_0 = {xi_max:.3f}")

fig1, ax1 = plt.subplots(figsize=(6, 4.2))
ax1.plot(xi0, f, color="steelblue")
ax1.plot(xi_max, f_max, "o", color="firebrick", label=rf"maximum ${f_max:.3f}$ at $\xi_0={xi_max:.2f}$")
ax1.set_xlabel(r"dimensionless core radius $\xi_0$")
ax1.set_ylabel(r"surface pressure $P\,G^3M_c^2/c_s^8$")
ax1.set_title("An isothermal core has a pressure ceiling")
ax1.legend()
fig1.tight_layout()

# %%
# The limit on the core mass
# --------------------------
# The ceiling falls as :math:`c_s^8/M_c^2\propto T^4/(\mu_{\rm core}^4M_c^2)`,
# while the envelope presses on the core with :math:`P\propto M^2/R^4`
# at a temperature :math:`T\propto\mu_{\rm env}M/R`. Equating the two
# gives :math:`M_c/M\propto(\mu_{\rm env}/\mu_{\rm core})^2`; envelope
# models fix the coefficient at 0.37. A helium core
# (:math:`\mu_{\rm core}\approx 1.3`) under a hydrogen-rich envelope
# (:math:`\mu_{\rm env}\approx 0.6`) can hold about 8% of the mass.
mu_core = np.linspace(0.6, 2.0, 200)
q_sc = schonberg_chandrasekhar_limit(0.6, mu_core)
print(f"Schönberg-Chandrasekhar limit for a helium core: {schonberg_chandrasekhar_limit():.3f} of the stellar mass")

# The same scaling from the pressure ceiling itself: hold the envelope
# fixed, set c_s^2 = T / mu_core with T ~ mu_env, and solve
# P_max(M_c) = P_env for M_c.
c_s = np.sqrt(0.6 / mu_core)
core_mass_from_ceiling = np.sqrt(np.array([isothermal_core_max_pressure(1.0, c) for c in c_s]))
core_mass_from_ceiling *= q_sc[0] / core_mass_from_ceiling[0]

fig2, ax2 = plt.subplots(figsize=(6, 4.2))
ax2.plot(mu_core, q_sc, color="steelblue", label=r"$0.37\,(\mu_{\rm env}/\mu_{\rm core})^2$")
ax2.plot(mu_core[::15], core_mass_from_ceiling[::15], "o", color="0.3", ms=4, label="from the pressure ceiling")
ax2.axvline(1.3, ls=":", color="0.5")
ax2.text(1.32, 0.3, "helium core", color="0.4")
ax2.set_xlabel(r"core molecular weight $\mu_{\rm core}$ ($\mu_{\rm env}=0.6$)")
ax2.set_ylabel(r"largest core mass $M_c/M$")
ax2.set_title("Schönberg-Chandrasekhar limit")
ax2.legend()
fig2.tight_layout()

# %%
# What the limit means for lifetimes
# ----------------------------------
# The star leaves the main sequence once about 10% of its mass -- the
# Schönberg-Chandrasekhar fraction, roughly -- has become helium. With
# :math:`L\propto M^{3.5}` the lifetime is
# :math:`\tau = 0.1\times 0.007\,Mc^2/L\propto M^{-2.5}`.
masses = np.logspace(np.log10(0.5), 1.0, 100)
tau = main_sequence_lifetime(masses)
tau_sun = main_sequence_lifetime(1.0)
print(f"main-sequence lifetime of the Sun: {tau_sun / 1e9:.1f} Gyr")
print(f"main-sequence lifetime of a 10 solar-mass star: {main_sequence_lifetime(10.0) / 1e6:.0f} Myr")

fig3, ax3 = plt.subplots(figsize=(6, 4.2))
ax3.loglog(masses, tau / 1e9, color="firebrick")
ax3.plot(1.0, tau_sun / 1e9, "o", color="goldenrod", label=f"Sun: {tau_sun / 1e9:.1f} Gyr")
ax3.set_xlabel(r"mass ($M_\odot$)")
ax3.set_ylabel("main-sequence lifetime (Gyr)")
ax3.set_title(r"$\tau = 0.1\times0.007\,Mc^2/L \propto M^{-2.5}$")
ax3.legend()
fig3.tight_layout()

plt.show()

# %%
# Check
# -----
assert abs(f_max - 1.398) < 1e-3 and abs(xi_max - 6.451) < 1e-3
assert f_max >= f.max() - 1e-9
np.testing.assert_allclose(q_sc, 0.37 * (0.6 / mu_core) ** 2, rtol=1e-12)
np.testing.assert_allclose(core_mass_from_ceiling, q_sc, rtol=1e-10)
assert abs(schonberg_chandrasekhar_limit() - 0.08) < 0.005
assert 9e9 < tau_sun < 11e9
np.testing.assert_allclose(tau / tau_sun, masses**-2.5, rtol=1e-12)
