"""Lecture 35: flights computed earlier in the course on one map of height against speed (log axis): a Kiran loop, Hull's
business jet taking off and at one cruise point, the reference PSLV ascent, the SRE-1 entry at an ASSUMED 5 deg, and a
simulated L/D = 1 equilibrium glide. Vertical lines: constant u = V^2/(g r). Thin curves: constant dynamic pressure
(ISA, to 80 km). Speeds are relative to the air. Writes img/fig-35-flight-map.png."""
import numpy as np
from _visual import plt, save, despine, MAROON, BLUE, GREEN, AMBER, PURPLE, INK, GREY
from _scripts import load
import _ascent, _entry33 as E33
import _takeoff as TO
from flight import atmosphere as A
from flight.constants import MU, R_EARTH, FT

LOOP = load("anim-25-kiran-loop").TR
PSLV = _ascent.reference()[1]
SRE = E33.sre(-5.0)
GLIDE = E33.glide(1.0)
V_LO = float(TO.takeoff(A.isa(0.0)[2])["vlo"])
CRUISE = (0.7 * A.speed_of_sound(A.isa(35000 * FT)[0]), 35000 * FT)
US = [0.001, 0.1, 0.5, 1.0]


def speed_of_u(u, h=0.0):
    return float(np.sqrt(u * MU / (R_EARTH + h)))


def u_of(V, h):
    return V**2 * (R_EARTH + h) / MU


if __name__ == "__main__":
    fig, ax = plt.subplots(figsize=(10.5, 6.2))
    for u in US:
        x = speed_of_u(u, 50e3)
        ax.axvline(x, color=GREY, lw=1, ls=":")
        ax.text(x * 1.02, 128, f"$u$ = {u:g}", rotation=90, va="top", fontsize=11, color=INK)
    hh = np.linspace(0, 80e3, 200)
    rho = np.array([A.isa(h)[2] for h in hh])
    for q in (1e3, 10e3, 40e3):
        ax.plot(np.sqrt(2 * q / rho), hh / 1e3, color=GREY, lw=0.9)
        i = int(np.argmin(abs(np.sqrt(2 * q / rho) - 3600)))
        ax.text(3600, hh[i] / 1e3 + 0.8, f"$q$ = {q / 1000:.0f} kPa", fontsize=10, color=GREY, ha="center", va="bottom")
    sel = PSLV.V > 40
    for tr_v, tr_h, c, lab, lw in ((PSLV.V[sel], PSLV.h[sel], MAROON, "PSLV model ascent", 2.8), (SRE.V, SRE.h, BLUE, "SRE-1 model entry, 5° assumed", 2.8),
                                   (GLIDE.V, GLIDE.h, PURPLE, "equilibrium glide, $L/D$ = 1", 2.8), (LOOP.V, LOOP.h, GREEN, "Kiran loop", 3.4)):
        ax.plot(tr_v, tr_h / 1e3, color=c, lw=lw, label=lab)
    ax.plot(V_LO, 0.0, "s", color=AMBER, ms=10, clip_on=False, label="Hull's jet: lift-off")
    ax.plot(CRUISE[0], CRUISE[1] / 1e3, "D", color=AMBER, ms=9, label="Hull's jet: Mach 0.7 at 35,000 ft")
    ax.set_xscale("log"); ax.set_xlim(40, 9000); ax.set_ylim(0, 130)
    ax.set_xticks([50, 100, 200, 500, 1000, 2000, 5000], ["50", "100", "200", "500", "1000", "2000", "5000"]); ax.minorticks_off()
    ax.set_xlabel("speed relative to the air (m/s)"); ax.set_ylabel("height (km)")
    fig.legend(frameon=False, fontsize=11, ncol=3, loc="upper center", bbox_to_anchor=(0.5, 0.02))
    despine(ax)
    save(fig, "fig-35-flight-map")
