"""Lecture 8, why the dynamic pressure peaks on the PSLV ascent (flight.missions.pslv_c18_like, as in Lecture 4): on a
log scale against time, the density and the square of the air-relative speed, each divided by its value at the
moment of maximum q, and their product q/q_max. On a log scale the product is the sum of the two curves, so q peaks
where the density falls as fast, in proportion, as V_a^2 rises. Writes img/fig-08-maxq-product.png."""
import numpy as np
from _visual import plt, save, despine, MAROON, BLUE, INK, GREY
from flight import missions

TR = missions.fly(missions.pslv_c18_like(), t_end=125.0)
_, U = np.unique(TR.t, return_index=True)                 # drop repeated samples at stage events
K = U[(TR.t[U] > 1.0) & (TR.t[U] <= 120.0)]
T, VA, Q = TR.t[K], TR.Va[K], TR.q[K]
RHO = 2 * Q / VA**2                                         # the density the simulator used
I = int(np.argmax(Q))
T_MAX, H_MAX = T[I], TR.h[K][I]
R_RHO, R_V2, R_Q = RHO / RHO[I], (VA / VA[I])**2, Q / Q[I]
# slopes of ln(rho) and ln(V_a^2) at the peak: equal and opposite
D_LN_RHO = np.gradient(np.log(RHO), T)[I]
D_LN_V2 = np.gradient(np.log(VA**2), T)[I]
J = np.searchsorted(T, 30.0)
RATIO_30 = (np.gradient(np.log(VA**2), T)[J], np.gradient(np.log(RHO), T)[J])

if __name__ == "__main__":
    fig, ax = plt.subplots(figsize=(10, 5.2))
    ax.semilogy(T, R_RHO, color=BLUE, lw=2.6, label="density, $\\rho/\\rho_*$")
    ax.semilogy(T, R_V2, color=MAROON, lw=2.6, label="speed squared, $(V_a/V_{a*})^2$")
    ax.semilogy(T, R_Q, color=INK, lw=3.0, label="their product, $q/q_{\\max}$")
    ax.axvline(T_MAX, color=GREY, lw=1, ls="--")
    ax.text(T_MAX + 1.5, 30, f"max $q$: {T_MAX:.0f} s, {H_MAX / 1e3:.1f} km", fontsize=12, color=GREY)
    ax.set_xlim(0, 120); ax.set_ylim(1e-2, 1e2)
    ax.set_xlabel("time after lift-off (s)"); ax.set_ylabel("value divided by its value at max $q$")
    ax.legend(frameon=False, fontsize=12, loc="lower right")
    despine(ax)
    save(fig, "fig-08-maxq-product")
