"""Lecture 13, the drag polar of Hull's subsonic business jet at five Mach numbers through the drag rise (Hull 2007,
Table 3.4, the data of fig-13-sbj-mach.py), each with its tangent from the origin, whose slope C_L/C_D is E_max
(flight.aero.parabolic_cd, max_lift_to_drag). Writes img/fig-13-sbj-polars.png."""
import numpy as np
from _visual import plt, save, despine, INK, GREY
import _scripts
from flight import aero

T = _scripts.load("fig-13-sbj-mach")
MACHS = [0.6, 0.75, 0.8, 0.85, 0.9]
COLOURS = ["#c9a27e", "#b87a5e", "#9c5243", "#7d3030", "#4a1416"]
CL = np.linspace(0.0, 0.62, 200)
ROWS = []
for m in MACHS:
    row = T.HULL_3_4[np.argmin(np.abs(T.M - m))]
    cls, em = aero.max_lift_to_drag(row[1], row[2])
    ROWS.append(dict(M=m, cd0=row[1], k=row[2], cls=cls, em=em))

if __name__ == "__main__":
    fig, ax = plt.subplots(figsize=(10, 5.6))
    for r, c in zip(ROWS, COLOURS):
        ax.plot(aero.parabolic_cd(CL, r["cd0"], r["k"]), CL, color=c, lw=2.5,
                label=f"M = {r['M']:g}:  $E_{{max}}$ = {r['em']:.1f}")
        cd_s = aero.parabolic_cd(r["cls"], r["cd0"], r["k"])
        ax.plot([0, cd_s], [0, r["cls"]], color=c, lw=1, ls="--")
        ax.plot(cd_s, r["cls"], "o", color=c, ms=7)
    ax.set_xlim(0, 0.095); ax.set_ylim(0, 0.65)
    ax.set_xlabel("drag coefficient $C_D$"); ax.set_ylabel("lift coefficient $C_L$")
    ax.legend(frameon=False, fontsize=12, loc="lower right")
    despine(ax)
    save(fig, "fig-13-sbj-polars")
