"""Lecture 11: Mach number and dynamic pressure against time on the reference PSLV ascent (flight.missions on the course
simulator), first 150 s, with the regime bands of flight.gasdynamics.REGIMES and the instant of largest q.
Writes img/fig-11-pslv-mach.png."""
import numpy as np
from _visual import plt, save, despine, MAROON, BLUE, INK, GREY
from flight import missions, gasdynamics as GD

TR = missions.fly(missions.pslv_c18_like(), t_end=150.0, max_step=0.5)
T_, IDX = np.unique(TR.t, return_index=True)
MACH, Q = TR.mach[IDX], TR.q[IDX]
I_Q = int(np.argmax(Q))


def first_time(M):
    return float(np.interp(M, MACH[:int(np.argmax(MACH >= M)) + 1], T_[:int(np.argmax(MACH >= M)) + 1]))


T_M08, T_M12, T_M5 = first_time(0.8), first_time(1.2), first_time(5.0)

if __name__ == "__main__":
    fig, (a, b) = plt.subplots(2, 1, figsize=(10, 6.0), sharex=True, gridspec_kw=dict(height_ratios=[1.7, 1], hspace=0.12))
    shades = ["#e9eef4", "#f3e3c3", "#e8d7d7", "#ddd3e4"]
    top = 8.0
    for (name, lo, hi), c in zip(GD.REGIMES, shades):
        a.axhspan(lo, min(hi, top), color=c, zorder=0)
        a.text(148, 0.5 * (lo + min(hi, top)), name, ha="right", va="center", fontsize=11.5)
    a.plot(T_, MACH, color=MAROON, lw=2.8); b.plot(T_, Q / 1000, color=BLUE, lw=2.8)
    for ax in (a, b):
        ax.axvline(T_[I_Q], color=INK, lw=1.2, ls="--"); despine(ax)
    a.text(T_[I_Q] - 1.5, 6.9, f"largest $q$\n{T_[I_Q]:.0f} s, Mach {MACH[I_Q]:.1f}", ha="right", fontsize=11.5)
    a.set_ylim(0, top); a.set_ylabel("Mach number"); b.set_ylabel("$q$ (kPa)"); b.set_xlabel("time from lift-off (s)")
    b.set_xlim(0, 150); b.set_ylim(0, None)
    save(fig, "fig-11-pslv-mach")
