r"""
Larson and Penston's collapsing protostar
=========================================

A cold cloud with no pressure collapses homologously. Every shell reaches
the centre at the same moment, the free-fall time
:math:`t_\mathrm{ff}=\sqrt{3\pi/(32G\rho_0)}`. Real clouds have pressure.
In 1969 Richard Larson computed the collapse of an isothermal sphere
numerically, and Michael Penston found the same behaviour analytically.
The collapse runs away at the centre: a dense core shrinks while a
:math:`\rho\propto r^{-2}` envelope is left behind. Just before the
central singularity the flow follows a self-similar solution in
:math:`x=r/(c_s|t|)`. Hunter (1977) pinned down its numbers: central
density :math:`\alpha(0)=1.667`, an envelope 4.43 times denser than the
singular isothermal sphere, and gas falling in at 3.28 times the sound
speed.

The functions used here are in
:mod:`physicskit.astro.gravitational_collapse`.
"""

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

from physicskit.astro.gravitational_collapse import (
    free_fall_time,
    larson_penston_asymptotes,
    larson_penston_eigenvalue,
    larson_penston_profile,
    pressure_free_collapse,
)

# %%
# Pressure-free collapse
# ----------------------
# Each shell follows the cycloid :math:`r=r_0\cos^2\beta`. The sphere spends
# most of :math:`t_\mathrm{ff}` near its starting radius, then plunges.
rho0 = 1.0
tff = float(free_fall_time(rho0))
t = np.linspace(0, tff, 400)
r, rdot = pressure_free_collapse(t, rho0)
print(f"t_ff = {tff:.6f}  (sqrt(3 pi / 32) = {np.sqrt(3 * np.pi / 32):.6f})")

fig1, ax = plt.subplots(figsize=(6, 4))
ax.plot(t / tff, r, color="k", label=r"$r/r_0$")
ax.plot(t / tff, (rho0 / r**3) / 1e3, color="firebrick", label=r"$\rho/(10^3\rho_0)$")
ax.set_ylim(0, 1.05)
ax.set_xlabel(r"$t/t_\mathrm{ff}$")
ax.set_title("Homologous pressure-free collapse")
ax.legend()
fig1.tight_layout()

# %%
# The Larson-Penston similarity solution
# --------------------------------------
# With :math:`\rho=\alpha(x)/(4\pi Gt^2)` and :math:`u=c_s v(x)`, only one
# solution starts regular at the centre and passes smoothly through the
# sonic point :math:`x+v=1`. Near the centre it falls in as
# :math:`v=-2x/3`, like the pressure-free collapse above. Far out,
# :math:`x^2\alpha\to A`, compared with :math:`A=2` for the static singular
# isothermal sphere.
a0, xs = larson_penston_eigenvalue()
A, v_inf = larson_penston_asymptotes()
print(f"alpha(0) = {a0:.4f}, sonic point x* = {xs:.4f}, A = {A:.3f} = {A / 2:.3f} x SIS, v_inf = {v_inf:.4f}")

x = np.logspace(-2, 4, 600)
alpha, v = larson_penston_profile(x)
fig2, (ax1, ax2) = plt.subplots(1, 2, figsize=(11, 4))
ax1.loglog(x, alpha, color="k", label="Larson-Penston")
ax1.loglog(x, 2 / x**2, "--", color="0.5", label="singular isothermal sphere")
ax1.loglog(x, A / x**2, ":", color="firebrick", label=rf"$A/x^2$, $A={A:.2f}$")
ax1.axvline(xs, color="royalblue", lw=0.8)
ax1.set_xlabel(r"$x=r/(c_s|t|)$")
ax1.set_ylabel(r"$\alpha=4\pi Gt^2\rho$")
ax1.legend(fontsize=8)
ax2.semilogx(x, -v, color="k", label=r"$-v$")
ax2.semilogx(x, 2 * x / 3, "--", color="0.5", label=r"$2x/3$ (homologous)")
ax2.axhline(-v_inf, ls=":", color="firebrick", label=rf"$-v_\infty={-v_inf:.2f}$")
ax2.axvline(xs, color="royalblue", lw=0.8, label="sonic point")
ax2.set_ylim(0, 4)
ax2.set_xlabel(r"$x=r/(c_s|t|)$")
ax2.set_ylabel(r"infall speed $-u/c_s$")
ax2.legend(fontsize=8)
fig2.tight_layout()

# %%
# The density at fixed times
# --------------------------
# In physical units (:math:`c_s=G=1`) the profile at
# :math:`t=-1,-0.1,-0.01` shows a flat core of radius about :math:`c_s|t|`
# shrinking inside an :math:`r^{-2}` envelope that stays fixed.
rr = np.logspace(-3, 1, 400)
fig3, ax = plt.subplots(figsize=(6, 4))
for tau in (1.0, 0.1, 0.01):
    a_t, _ = larson_penston_profile(rr / tau)
    ax.loglog(rr, a_t / (4 * np.pi * tau**2), label=rf"$t=-{tau:g}$")
ax.loglog(rr, A / (4 * np.pi * rr**2), ":", color="k", label=r"$A/(4\pi r^2)$")
ax.set_xlabel(r"$r$")
ax.set_ylabel(r"$\rho$")
ax.set_title("Runaway collapse of the core")
ax.legend(fontsize=8)
fig3.tight_layout()
plt.show()

# %%
# Check
# -----
# The free-fall time and cycloid match their closed forms; the central
# density, envelope and infall speed match Hunter's values; the sonic point
# sits where :math:`x+v=1` with :math:`\alpha=2/x`; and the gas near the
# centre falls in homologously.
assert abs(tff - np.sqrt(3 * np.pi / 32)) < 1e-12
assert abs(r[0] - 1) < 1e-12 and r[-1] < 1e-12
assert abs(a0 - 1.667) < 2e-3 and abs(A / 2 - 4.43) < 1e-2 and abs(v_inf + 3.28) < 3e-3
a_s, v_s = larson_penston_profile([xs])
assert abs(xs + v_s[0] - 1) < 1e-12 and abs(a_s[0] - 2 / xs) < 1e-12
assert np.allclose(v[:20], -2 * x[:20] / 3, rtol=1e-3)
assert np.allclose(x[-50:] ** 2 * alpha[-50:], A, rtol=2e-3)
