"""Lecture 18, the drag polar of the Tejas-class fighter built from its geometry (flight.aero.FighterAero): zero-lift
drag against Mach number with its three pieces (Filippone's drag rise, the cubic join, Sadraey's volume wave drag)
and the F-16 with Sadraey's own volume (left); the induced-drag factor K with its two limits (right).
Writes img/fig-18-polar-model.png."""
import numpy as np
from _visual import plt, save, despine, MAROON, BLUE, GREEN, AMBER, INK, GREY
import _fighter as F
from flight import aero as AE

M = np.linspace(0.3, 2.4, 600)
A = F.TEJ.aero
CD0 = np.array([A.cd0(x) for x in M])
PEAK_M = M[np.argmax(CD0)]
PEAK = CD0.max()
RATIO_12 = A.cd0(1.2) / A.cd0_sub
F16_RATIO_12 = F.F16.aero.cd0(1.2) / F.F16.aero.cd0_sub

if __name__ == "__main__":
    fig, (a1, a2) = plt.subplots(1, 2, figsize=(11, 4.8))
    fig.subplots_adjust(wspace=0.3)
    a1.axvspan(A.mdd, A.m_join, color=AMBER, alpha=0.15, lw=0)
    a1.text((A.mdd + A.m_join) / 2, 0.006, "join", ha="center", fontsize=12, color=AMBER)
    a1.text(0.6, 0.006, "rise", ha="center", fontsize=12, color=GREY)
    a1.text(1.8, 0.006, "Sadraey eq. 3.57", ha="center", fontsize=12, color=GREY)
    a1.plot(M, CD0, color=MAROON, lw=2.6, label="Tejas class (model)")
    a1.plot(M, [F.F16.aero.cd0(x) for x in M], color=BLUE, lw=2.2, ls="--", label="F-16, Sadraey's volume")
    a1.axhline(A.cd0_sub, color=GREY, lw=1, ls=":")
    a1.plot(PEAK_M, PEAK, "o", color=MAROON, ms=7)
    a1.set_ylim(0, 0.056); a1.set_xlabel("Mach number"); a1.set_ylabel("$C_{D_0}$")
    a1.legend(frameon=False, fontsize=12, loc="upper right")
    a2.plot(M, [A.k(x) for x in M], color=MAROON, lw=2.6, label="$K(M)$, the join")
    a2.axhline(A.k_sub, color=GREEN, lw=1.6, ls="--", label=f"subsonic $K={A.k_sub:.3f}$")
    a2.plot(M[M > 1], [AE.supersonic_induced_factor(x) for x in M[M > 1]], color=BLUE, lw=1.6, ls="--", label="$\\beta/4$ (Lecture 13)")
    a2.set_ylim(0, 0.6); a2.set_xlabel("Mach number"); a2.set_ylabel("$K$"); a2.legend(frameon=False, fontsize=12, loc="upper left")
    despine(a1); despine(a2)
    save(fig, "fig-18-polar-model")
