"""Lecture 33, why a ballistic entry has a peak deceleration: SRE-1 (B from the dataset model) entering at 8 km/s on a
path 8 deg below the horizontal, in the first-order solution of the note (exponential air, H = R_E/900, gravity
neglected; flight.entry.ballistic_speed_ratio). Against height: the density and the square of the speed, each divided
by its value at the peak, and their product, the deceleration a = rho V^2/(2B), divided by its largest value. The
vertical scale is logarithmic, so the product is the sum of the two curves. Writes img/fig-33-peak-product.png."""
import numpy as np
from _visual import plt, save, despine, MAROON, BLUE, INK, GREY
import _entry33 as X
from flight import entry as E
from flight.constants import RHO0_SL

V_I, GAMMA = 8000.0, np.radians(-8.0)
B = X.B_of(X.capsule("sre-1"))
H = X.H
HEIGHTS = np.linspace(100e3, 15e3, 600)
RHO = RHO0_SL * np.exp(-HEIGHTS / H)
V = V_I * E.ballistic_speed_ratio(RHO, B, H, GAMMA)
A = RHO * V**2 / (2 * B)
I = int(np.argmax(A))
RHO_STAR = E.ballistic_peak_density(B, GAMMA, H)
H_STAR = H * np.log(RHO0_SL / RHO_STAR)

if __name__ == "__main__":
    fig, ax = plt.subplots(figsize=(10, 5.2))
    ax.semilogx(RHO / RHO_STAR, HEIGHTS / 1e3, color=BLUE, lw=2.6, label="density, $\\rho/\\rho_*$")
    ax.semilogx((V / V[I])**2, HEIGHTS / 1e3, color=MAROON, lw=2.6, label="speed squared, $(V/V_*)^2$")
    ax.semilogx(A / A[I], HEIGHTS / 1e3, color=INK, lw=3.0, label="deceleration, $a/a_{\\max}$")
    ax.axhline(H_STAR / 1e3, color=GREY, lw=1, ls="--")
    ax.text(2e-3, H_STAR / 1e3 + 1.5, "peak deceleration", fontsize=12, color=GREY)
    ax.set_xlim(1e-3, 1e2); ax.set_ylim(15, 100)
    ax.set_xlabel("value divided by its value at the peak"); ax.set_ylabel("height (km)")
    ax.legend(frameon=False, fontsize=12, loc="upper right")
    despine(ax)
    save(fig, "fig-33-peak-product")
