"""Lecture 12, the two levers on the best lift-to-drag ratio: contours of E_max = 0.5 sqrt(pi (e AR) / C_D0) over the
effective aspect ratio e AR = 1/(pi K) and the zero-lift drag coefficient C_D0 (the note's E_max = 1/(2 sqrt(K C_D0))).
The points are the polars used in the course: the HANSA-3 estimate of this note (C_D0 = 0.030, K = 0.0447) and the
dataset polars of Sadraey's transport, Hull's business jet, the ATR 72-600, the glider and the Tejas-class model
(flight.vehicle, flight.aero). Writes img/fig-12-emax-map.png."""
import numpy as np
from _visual import plt, save, despine, MAROON, BLUE, INK, GREY
from flight import vehicle, aero as AE


def point(label, cd0, k, dx, dy, ha="left"):
    return dict(label=label, cd0=cd0, k=k, ear=1 / (np.pi * k), emax=AE.max_lift_to_drag(cd0, k)[1], dx=dx, dy=dy, ha=ha)


def from_set(name, label, dx, dy, ha="left"):
    a = vehicle.load(name).aero
    return point(label, a.cd0(0.0), a.k(0.0), dx, dy, ha)


POINTS = [point("HANSA-3", 0.030, 0.0447, 0.4, 0.0006),
          from_set("transport-sadraey-p5-4", "jet transport", 0.4, -0.0014),
          from_set("sbj-hull", "business jet", -0.4, -0.0006, "right"),
          from_set("atr72-600", "ATR 72-600", 0.4, 0.0006),
          from_set("glider-representative", "glider", -0.4, 0.0008, "right"),
          from_set("tejas-class", "Tejas-class fighter", 0.0, -0.0028)]


def emax(ear, cd0):
    return 0.5 * np.sqrt(np.pi * ear / cd0)


if __name__ == "__main__":
    fig, ax = plt.subplots(figsize=(10, 6))
    X, Y = np.meshgrid(np.linspace(0.8, 24, 300), np.linspace(0.008, 0.042, 300))
    cs = ax.contour(X, Y, emax(X, Y), levels=[6, 8, 10, 12, 15, 20, 25, 30, 40, 50], colors=GREY, linewidths=1.2)
    ax.clabel(cs, fmt=lambda v: f"{v:.0f}", fontsize=10)
    for p in POINTS:
        ax.plot(p["ear"], p["cd0"], "o", color=MAROON, ms=9, zorder=5)
        ax.text(p["ear"] + p["dx"], p["cd0"] + p["dy"], f"{p['label']}, {p['emax']:.1f}", fontsize=11, color=INK, ha=p["ha"], zorder=6)
    for xy, txt, d in (((13.5, 0.0392), "more slender wings", (6.0, 0.0)), ((22.5, 0.033), "cleaner", (0.0, -0.012))):
        ax.annotate("", xy=(xy[0] + d[0], xy[1] + d[1]), xytext=xy, arrowprops=dict(arrowstyle="-|>", color=BLUE, lw=2.5))
        ax.text(xy[0] + (3.0 if d[0] else -0.4), xy[1] + (0.0008 if d[0] else -0.006), txt, color=BLUE, fontsize=12,
                ha="center" if d[0] else "right")
    ax.set_xlim(0.8, 24); ax.set_ylim(0.008, 0.042)
    ax.set_xlabel("effective aspect ratio $e\\,AR = 1/(\\pi K)$"); ax.set_ylabel("zero-lift drag coefficient $C_{D_0}$")
    ax.set_title("contours of the best lift-to-drag ratio $E_{\\max}$", fontsize=12, loc="left")
    despine(ax)
    save(fig, "fig-12-emax-map")
