"""Lecture 12, finding the best lift-to-drag ratio on the polar of the HANSA-3-class trainer (fig-12-polar.py): a line
from the origin to a point on the polar has slope C_L/C_D = L/D. As the point moves up the polar the slope first
rises, then falls; the steepest line is the tangent. Writes img/anim-12-tangent.gif."""
import numpy as np
from _visual import plt, save_anim, MAROON, BLUE, 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
CLS, EMAX = AE.max_lift_to_drag(CD0, K)
CL = np.linspace(0.08, CLMAX, 90)

if __name__ == "__main__":
    fig, (a1, a2) = plt.subplots(1, 2, figsize=(11, 5.2), gridspec_kw=dict(width_ratios=[1.2, 1]))
    fig.subplots_adjust(wspace=0.3, bottom=0.14)
    poly = np.linspace(0, CLMAX, 200)

    def frame(k):
        a1.clear(); a2.clear()
        cl = CL[k]; cd = AE.parabolic_cd(cl, CD0, K)
        a1.plot(AE.parabolic_cd(poly, CD0, K), poly, color=MAROON, lw=2.5)
        for j in range(0, k, 8):
            c_, d_ = CL[j], AE.parabolic_cd(CL[j], CD0, K)
            a1.plot([0, d_], [0, c_], color=GREY, lw=0.7, alpha=0.6)
        best = abs(cl - CLS) < 0.03 or k == len(CL) - 1
        a1.plot([0, 1.3 * cd], [0, 1.3 * cl], color=BLUE, lw=2)
        if k > np.argmin(abs(CL - CLS)):
            cds = AE.parabolic_cd(CLS, CD0, K)
            a1.plot([0, 1.6 * cds], [0, 1.6 * CLS], color=INK, lw=2, ls="--")
            a1.plot(cds, CLS, "o", color=INK, ms=8)
            a1.text(cds + 0.003, CLS - 0.12, f"tangent: $C_L^*={CLS:.2f}$", fontsize=12)
        a1.plot(cd, cl, "o", color=BLUE, ms=8)
        a1.set_xlim(0, 0.14); a1.set_ylim(0, 1.6)
        a1.set_xlabel("$C_D$"); a1.set_ylabel("$C_L$")
        a1.set_title(f"$C_L={cl:.2f}$:  slope $C_L/C_D={cl / cd:.1f}$", fontsize=13, loc="left")
        a2.plot(CL[:k + 1], AE.lift_to_drag(CL[:k + 1], CD0, K), color=BLUE, lw=2.5)
        a2.axhline(EMAX, color=GREY, ls=":", lw=1)
        a2.text(0.1, EMAX + 0.3, f"$E_{{max}}={EMAX:.1f}$", fontsize=12)
        a2.set_xlim(0, 1.6); a2.set_ylim(0, 16)
        a2.set_xlabel("$C_L$"); a2.set_ylabel("$L/D$")
        for a in (a1, a2):
            for s in ("top", "right"):
                a.spines[s].set_visible(False)
        return []

    save_anim(fig, frame, len(CL), 12, "anim-12-tangent", dpi=90, hold=2.5)
