"""Lecture 12, drag polars C_L against C_D for four aircraft, with the tangent from the origin that marks the maximum
lift-to-drag ratio (flight.aero.max_lift_to_drag).
  HANSA-3 class: span 10.47 m (Raol & Singh, App. A12); wing area 12 m^2 ASSUMED; Oswald factor from Sadraey
    eq. 3.11; C_D0 = 0.030, inside Sadraey's Table 3.2 range for a small aircraft with fixed gear (0.025-0.04);
    C_Lmax 1.5, inside Sadraey's 1-1.6 for a clean wing.
  Hull's subsonic business jet and Sadraey's jet transport (Problem 5.4): from the dataset, sourced.
  Glider: the dataset's representative glider (estimated).
Writes img/fig-12-polar.png."""
import numpy as np
from _visual import plt, save, despine, MAROON, BLUE, GREEN, AMBER, INK, GREY
from flight import aero as AE, vehicle

SPAN_H, S_H, CD0_H, CLMAX_H = 10.47, 12.0, 0.030, 1.5
AR_H = AE.aspect_ratio(SPAN_H, S_H)
E_H = AE.oswald_straight(AR_H)
K_H = AE.induced_drag_factor(AR_H, E_H)


def _from(name):
    a = vehicle.load(name).aero
    return a.cd0(0.0), a.k(0.0), a.clmax(0.0)


AIRCRAFT = [("HANSA-3 class (estimated)", CD0_H, K_H, CLMAX_H, MAROON)]
for lab, nm, c in (("Hull's business jet", "sbj-hull", BLUE), ("Sadraey's jet transport", "transport-sadraey-p5-4", GREEN),
                   ("glider (representative)", "glider-representative", AMBER)):
    AIRCRAFT.append((lab, *_from(nm), c))
EMAX = {lab: AE.max_lift_to_drag(cd0, k) for lab, cd0, k, _, _ in AIRCRAFT}

if __name__ == "__main__":
    fig, ax = plt.subplots(figsize=(10, 5.8))
    for lab, cd0, k, clmax, c in AIRCRAFT:
        cl = np.linspace(0, min(clmax, 1.6), 200)
        ax.plot(AE.parabolic_cd(cl, cd0, k), cl, color=c, lw=2.5, label=f"{lab}: $E_{{max}}={EMAX[lab][1]:.1f}$")
        cls, em = EMAX[lab]
        cds = AE.parabolic_cd(cls, cd0, k)
        ax.plot([0, 1.35 * cds], [0, 1.35 * cls], color=c, lw=1, ls="--")
        ax.plot(cds, cls, "o", color=c, ms=7)
    ax.set_xlim(0, 0.2); ax.set_ylim(0, 1.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-12-polar")
