"""Lecture 19, the range factor in Mach-number form for the Tejas-class model (_fighter.py). Left: the best lift-to-drag
ratio E_max(M) and the product M E_max(M), whose subsonic maximum, transonic minimum and supersonic rise follow Miele
(ch. 11, sec. 10.3). Right: the Breguet range factor a M E_max / c in the stratosphere (a = 295.07 m/s) with a constant
TSFC, with the TSFC rising with Mach number on dry thrust, and with afterburner. Writes img/fig-19-range-factor.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

V = F.TEJ
A_ = V.aero
M = np.linspace(0.4, 2.4, 801)
E = np.array([AE.max_lift_to_drag(A_.cd0(x), A_.k(x))[1] for x in M])
ME = M * E
i_max = np.argmax(np.where(M < 1.0, ME, 0)); i_min = np.argmin(np.where((M > 0.95) & (M < 1.4), ME, 1e9))
M_SUB, ME_SUB = M[i_max], ME[i_max]
M_MIN, ME_MIN = M[i_min], ME[i_min]
M_EQUAL = M[(M > 1.2) & (ME >= ME_SUB)][0]          # where the supersonic M E_max regains the subsonic peak
H = 11000.0
A11 = F.speed_of_sound(H)
C0 = F.tsfc(V, 0.0, H, False)                         # constant-TSFC reference: the dry value at rest, 11 km


def range_factor(c):
    return A11 * ME / c / 1e3                           # km


RF_CONST = range_factor(C0)
RF_DRY = range_factor(np.array([F.tsfc(V, x, H, False) for x in M]))
RF_WET = range_factor(np.array([F.tsfc(V, x, H, True) for x in M]))

if __name__ == "__main__":
    fig, (a1, a2) = plt.subplots(1, 2, figsize=(11, 4.8))
    fig.subplots_adjust(wspace=0.3)
    a1.plot(M, E, color=GREY, lw=2, ls="--", label="$E_{\\max}$")
    a1.plot(M, ME, color=MAROON, lw=2.6, label="$M\\,E_{\\max}$")
    a1.plot([M_SUB, M_MIN], [ME_SUB, ME_MIN], "o", color=MAROON, ms=7)
    a1.set_xlabel("Mach number"); a1.set_ylim(0, 12); a1.legend(frameon=False, fontsize=12, loc="upper right")
    a2.plot(M, RF_CONST, color=INK, lw=2, ls=":", label="constant TSFC")
    a2.plot(M, RF_DRY, color=GREEN, lw=2.5, label="TSFC rising, dry")
    a2.plot(M, RF_WET, color=BLUE, lw=2.5, ls="--", label="TSFC rising, afterburner")
    a2.set_xlabel("Mach number"); a2.set_ylabel("$aME_{\\max}/c$ (km)"); a2.set_ylim(0, 23000)
    a2.legend(frameon=False, fontsize=12, loc="upper left")
    despine(a1); despine(a2)
    save(fig, "fig-19-range-factor")
