"""Lecture 17, the best cruise altitude of the jet transport (_transport.py) at Mach 0.80 with constant TSFC: specific
range against pressure altitude at three weights (left), and the optimum altitude, where C_L = C_L*, against weight
(right; flight.performance.optimum_pressure_ratio, flight.atmosphere.pressure_altitude). Writes img/fig-17-altitude.png."""
import numpy as np
from _visual import plt, save, despine, MAROON, BLUE, GREEN, INK, GREY
import _transport as T
from flight import performance as PF, aero as AE, atmosphere as A
from flight.constants import G0, P0_SL

CLS = AE.max_lift_to_drag(T.CD0, T.K)[0]
H = np.linspace(8000, 14000, 241)
MASSES = [(270, MAROON), (245, BLUE), (220, GREEN)]


def sar(m_t, h):
    """Specific air range (km per tonne of fuel) at Mach 0.8 and pressure altitude h."""
    t, p, rho = A.isa(h)
    V = T.MACH * A.speed_of_sound(t)
    W = m_t * 1000 * G0
    d0, di = PF.level_flight_drag(W, rho, V, T.S, T.CD0, T.K)
    return PF.specific_range(V, T.C, d0 + di) * 1000 * G0 / 1000


def h_opt(m_t):
    return A.pressure_altitude(P0_SL * PF.optimum_pressure_ratio(m_t * 1000 * G0, T.S, T.MACH, CLS))


if __name__ == "__main__":
    fig, (a1, a2) = plt.subplots(1, 2, figsize=(11, 4.9))
    fig.subplots_adjust(wspace=0.3)
    for m, c in MASSES:
        a1.plot([sar(m, h) for h in H], H / 1e3, color=c, lw=2.4, label=f"{m} t")
        ho = h_opt(m)
        a1.plot(sar(m, ho), ho / 1e3, "o", color=c, ms=8)
    a1.set_xlabel("specific range (km per tonne of fuel)"); a1.set_ylabel("pressure altitude (km)")
    a1.legend(frameon=False, fontsize=12, loc="lower right"); a1.set_title("Mach 0.80; dots: $C_L=C_L^*$", fontsize=12, loc="left")
    m = np.linspace(270, 220, 101)
    a2.plot(m, [h_opt(x) / 1e3 for x in m], color=INK, lw=2.4)
    a2.set_xlabel("mass (t)"); a2.set_ylabel("best altitude at Mach 0.80 (km)"); a2.invert_xaxis()
    despine(a1); despine(a2)
    save(fig, "fig-17-altitude")
