"""Lecture 20, what changes along a constant-C_L glide: the transport of anim-20-airliner at C_L* from 11 km. Left: true
and equivalent airspeed, and rate of descent, against altitude. Right: time to reach sea level from each altitude,
integrated in the ISA and from the closed form for an exponential atmosphere (Ojha eq. 7.24, scale 9296 m;
flight.performance.glide_time_exponential). Writes img/fig-20-descent.png."""
import numpy as np
from _visual import plt, save, despine, MAROON, BLUE, GREEN, INK
from _scripts import load
import _transport as T
from flight import performance as PF, aero as AE, atmosphere as A
from flight.constants import KT

AL = load("anim-20-airliner")
HS = AL.HS
CD = AE.parabolic_cd(AL.CLS, T.CD0, T.K)
ST = np.array([PF.glide_state(AL.W, A.isa(h)[2], T.S, AL.CLS, CD) for h in HS])
EAS = ST[:, 0] * np.sqrt(np.array([A.isa(h)[2] for h in HS]) / 1.225)
x, t = AL.RUNS["flattest glide, still air"][0]
T_ISA = t[-1] - t                                               # time to go from each height
T_EXP = np.array([PF.glide_time_exponential(AL.W, T.S, AL.CLS, CD, h, 0.0) for h in HS])
SINK_TOP, SINK_SL = ST[0, 2], ST[-1, 2]

if __name__ == "__main__":
    fig, (a1, a2, a3) = plt.subplots(1, 3, figsize=(12, 4.8))
    fig.subplots_adjust(wspace=0.38)
    a1.plot(ST[:, 0] / KT, HS / 1e3, color=MAROON, lw=2.5, label="true")
    a1.plot(EAS / KT, HS / 1e3, color=BLUE, lw=2.2, ls="--", label="equivalent")
    a1.set_xlabel("airspeed (kt)"); a1.set_ylabel("altitude (km)"); a1.legend(frameon=False, fontsize=11, loc="upper left")
    a2.plot(ST[:, 2] * 60 / 0.3048, HS / 1e3, color=GREEN, lw=2.5)
    a2.set_xlabel("rate of descent (ft/min)")
    a3.plot(T_ISA / 60, HS / 1e3, color=INK, lw=2.5, label="ISA")
    a3.plot(T_EXP / 60, HS / 1e3, color=MAROON, lw=2, ls="--", label="exponential")
    a3.set_xlabel("time to sea level (min)"); a3.legend(frameon=False, fontsize=11, loc="lower right")
    for a in (a1, a2, a3):
        despine(a)
    save(fig, "fig-20-descent")
