"""Lecture 12: the points of a parabolic polar at which C_L^n / C_D is largest, for n = 1/2, 1 and 3/2, on the
HANSA-3-class polar. For the parabolic polar the closed forms are C_L = sqrt(n C_D0/((2-n) K)).
Writes img/fig-12-polar-points.png."""
import numpy as np
from _visual import plt, save, despine, MAROON, BLUE, GREEN, INK, GREY
from _scripts import load
from flight import aero as AE

P = load("fig-12-polar")
CD0, K, CLMAX = P.CD0_H, P.K_H, P.CLMAX_H
NS = [(0.5, "1/2", GREEN, "jet: longest range"), (1.0, "1", BLUE, "flattest glide; least drag"),
      (1.5, "3/2", MAROON, "least power; least sink")]


def best_cl(n):
    return float(AE.best_cl_power(n, CD0, K))


if __name__ == "__main__":
    fig, ax = plt.subplots(figsize=(10, 5.6))
    cl = np.linspace(0, CLMAX, 300)
    ax.plot(AE.parabolic_cd(cl, CD0, K), cl, color=INK, lw=3)
    for n, lab, c, use in NS:
        x = best_cl(n); cd = AE.parabolic_cd(x, CD0, K)
        ax.plot(cd, x, "o", color=c, ms=11, zorder=5)
        ax.annotate(f"largest $C_L^{{{lab}}}/C_D$: $C_L$ = {x:.2f}\n{use}", (cd, x), xytext=(-14, 8) if n > 1.2 else (18, -14), ha="right" if n > 1.2 else "left", textcoords="offset points", fontsize=12, color=c)
    x = best_cl(1.0); ax.plot([0, AE.parabolic_cd(x, CD0, K)], [0, x], color=BLUE, lw=1.2, ls="--")
    ax.set_xlim(0, 0.15); ax.set_ylim(0, 1.55); ax.set_xlabel("drag coefficient $C_D$"); ax.set_ylabel("lift coefficient $C_L$")
    despine(ax)
    save(fig, "fig-12-polar-points")
