"""Lecture 15, Hull's subsonic business jet (11,000 lb, the ISBJ polar C_D0 = 0.023, K = 0.073, CJ610 engines with
Hull's tropopause model at P = 0.98; dataset sbj-hull) climbing from sea level to 14 km: the drag curve moves to higher
speeds while the available thrust falls, and the two level-flight speeds close in until they meet at the ceiling.
Stall (C_Lmax 1.24) and Hull's M_max = 0.81 are drawn. Writes img/anim-15-sbj-altitude.gif."""
import numpy as np
from scipy.optimize import brentq
from _visual import plt, save_anim, MAROON, BLUE, GREEN, AMBER, INK, GREY
from flight import performance as PF, atmosphere as A, aero as AE, vehicle
from flight.constants import RHO0_SL

LB = 4.4482216152605
V_ = vehicle.load("sbj-hull")
W = 11000 * LB
S, CD0, K, CLMAX = V_.aero.S, 0.023, 0.073, 1.24
ENGINE = V_.stages[0].engine
M_MAX = 0.81                                 # Hull, eq. 5.14
E_STAR = AE.max_lift_to_drag(CD0, K)[1]


def state(h):
    t, p, rho = A.isa(h)
    sigma = rho / RHO0_SL
    T = ENGINE.thrust(1.0, p, rho, sigma, t / 288.15, 0.0, 0.0)
    vstar = PF.min_drag_speed(W, rho, S, CD0, K)
    tau = T / (W / E_STAR)
    return dict(T=T, vstar=vstar, tau=tau, rho=rho, a=A.speed_of_sound(t),
                vstall=PF.speed_for_cl(W, rho, S, CLMAX))


def speeds(h):
    s = state(h)
    if s["tau"] < 1:
        return None
    u1, u2 = PF.level_speed_ratios(s["tau"])
    return u1 * s["vstar"], u2 * s["vstar"]


CEILING = brentq(lambda h: state(h)["tau"] - 1.0, 5000.0, 20000.0)
H = np.linspace(0.0, 14000.0, 113)

if __name__ == "__main__":
    fig, (a1, a2) = plt.subplots(1, 2, figsize=(11, 5.0), gridspec_kw=dict(width_ratios=[1.2, 1]))
    fig.subplots_adjust(wspace=0.28, bottom=0.14)
    V = np.linspace(40, 330, 400)
    hist = []

    def frame(k):
        a1.clear(); a2.clear()
        h = H[k]; s = state(h)
        d0, di = PF.level_flight_drag(W, s["rho"], V, S, CD0, K)
        a1.plot(V, (d0 + di) / 1e3, color=MAROON, lw=2.5, label="drag")
        a1.axhline(s["T"] / 1e3, color=BLUE, lw=2, label="thrust available")
        a1.axvline(s["vstall"], color=GREY, ls=":", lw=1); a1.axvline(M_MAX * s["a"], color=AMBER, ls=":", lw=1.2)
        sp = speeds(h)
        if sp:
            a1.plot(sp, [s["T"] / 1e3] * 2, "o", color=INK, ms=7)
            hist.append((h, *sp, s["vstall"], M_MAX * s["a"]))
        a1.set_xlim(40, 330); a1.set_ylim(0, 25); a1.set_xlabel("true airspeed (m/s)"); a1.set_ylabel("force (kN)")
        a1.set_title(f"altitude {h / 1e3:.1f} km", fontsize=13, loc="left")
        a1.legend(frameon=False, fontsize=11, loc="upper left")
        if hist:
            hh = np.array(hist)
            a2.plot(hh[:, 1], hh[:, 0] / 1e3, color=GREEN, lw=2.4, label="$V_1$ (low)")
            a2.plot(hh[:, 2], hh[:, 0] / 1e3, color=BLUE, lw=2.4, label="$V_2$ (high)")
            a2.plot(hh[:, 3], hh[:, 0] / 1e3, color=GREY, lw=1.4, ls=":", label="stall")
            a2.plot(hh[:, 4], hh[:, 0] / 1e3, color=AMBER, lw=1.4, ls=":", label="$M_{max}$")
        if h >= CEILING:
            a2.axhline(CEILING / 1e3, color=MAROON, lw=1); a2.text(50, CEILING / 1e3 + 0.3, f"ceiling {CEILING / 1e3:.1f} km", color=MAROON, fontsize=12)
        a2.set_xlim(40, 330); a2.set_ylim(0, 15); a2.set_xlabel("true airspeed (m/s)"); a2.set_ylabel("altitude (km)")
        a2.legend(frameon=False, fontsize=10, loc="lower right")
        for a in (a1, a2):
            for sp_ in ("top", "right"):
                a.spines[sp_].set_visible(False)
        return []

    save_anim(fig, frame, len(H), 12, "anim-15-sbj-altitude", dpi=90, hold=2.5)
