"""Lecture 18, weight and height enter only through W/delta: the drag of the Tejas-class fighter (_fighter.py) against
Mach number in three conditions (left), and the drag per unit weight (right), where the two conditions with the same
W/delta (8500 kg at 11 km, 6000 kg higher up) fall on one curve (flight.performance.drag_per_weight_mach).
Writes img/fig-18-collapse.png."""
import numpy as np
from _visual import plt, save, despine, MAROON, BLUE, GREEN, INK
import _fighter as F
from flight import atmosphere as A, performance as PF

M = np.linspace(0.3, 2.2, 400)
H1 = 11000.0
M_LIGHT = 6000.0
P2 = A.isa(H1)[1] * M_LIGHT / F.M_REF            # same W/p, so the same W/delta
H2 = A.pressure_altitude(P2)
CASES = [(F.M_REF, H1, MAROON, "-"), (M_LIGHT, H2, BLUE, "--"), (F.M_REF, 6000.0, GREEN, "-")]


def label(m, h):
    return f"{m:,.0f} kg at {h / 1e3:.2f} km".replace(".00 km", " km")


if __name__ == "__main__":
    fig, (a1, a2) = plt.subplots(1, 2, figsize=(11, 4.8))
    fig.subplots_adjust(wspace=0.3)
    v = F.TEJ
    for m, h, c, ls in CASES:
        a1.plot(M, [F.drag(v, x, m, h) / 1e3 for x in M], color=c, ls=ls, lw=2.5, label=label(m, h))
        w = F.omega(v, m, h)
        a2.plot(M, [PF.drag_per_weight_mach(x, w, v.aero.cd0(x), v.aero.k(x)) for x in M], color=c, ls=ls, lw=2.5,
                label=f"$\\omega={w:.3f}$")
    a1.set_xlabel("Mach number"); a1.set_ylabel("drag (kN)"); a1.set_ylim(0, 260); a1.legend(frameon=False, fontsize=12, loc="upper left")
    a2.set_xlabel("Mach number"); a2.set_ylabel("$D/W$"); a2.set_ylim(0, 0.6)
    a2.legend(frameon=False, fontsize=12, loc="lower right")
    despine(a1); despine(a2)
    save(fig, "fig-18-collapse")
