"""Lecture 22, the specific excess power of the Tejas-class model at 8500 kg on the Mach-altitude plane (after Filippone
Figs. 10.9-10.12), with full afterburner (left) and military thrust (right): contours of P_s, lines of constant energy
height, and, on the left, the three climb paths of _energy.py from sea level at Mach 0.5 to 11 km at Mach 1.5.
Writes img/fig-22-ps-map.png."""
import numpy as np
from _visual import plt, save, despine, MAROON, BLUE, GREEN, AMBER, INK, GREY
import _energy as E
from flight import performance as PF

MS = np.linspace(0.2, 2.0, 120)
HS = np.linspace(0, 18000, 91)
PS_AB = np.array([[E.ps(m, h, True) for m in MS] for h in HS])
PS_MIL = np.array([[E.ps(m, h, False) for m in MS] for h in HS])
HE = np.array([[PF.energy_height(h, m * E.a_of(h)) for m in MS] for h in HS])
PATHS = {"minimum time": (E.rutowski(), MAROON), "minimum fuel": (E.rutowski(lambda M, h: E.ps(M, h) / E.fuel_flow(M, h)), GREEN),
         "climb, then accelerate": (E.conventional(), BLUE)}
PS_MAX_AB = PS_AB.max()
LEVELS = [0, 50, 100, 150, 200, 250]

if __name__ == "__main__":
    fig, (a1, a2) = plt.subplots(1, 2, figsize=(12, 5.2))
    fig.subplots_adjust(wspace=0.22)
    for ax, P, title in ((a1, PS_AB, "full afterburner"), (a2, PS_MIL, "military thrust")):
        ax.contour(MS, HS / 1e3, HE / 1e3, levels=np.arange(5, 40, 5), colors=[GREY], linewidths=0.8, linestyles=":")
        cs = ax.contour(MS, HS / 1e3, P, levels=LEVELS, colors=[INK], linewidths=1.3)
        ax.clabel(cs, fmt="%d", fontsize=10)
        ax.set_xlabel("Mach number"); ax.set_title(f"$P_s$ (m/s), {title}", fontsize=12, loc="left")
        ax.set_xlim(0.2, 2.0); ax.set_ylim(0, 18)
    for lab, (r, c) in PATHS.items():
        a1.plot(r[1], r[2] / 1e3, color=c, lw=2.4, label=f"{lab}: {r[4][-1]:.0f} s, {r[5][-1]:.0f} kg")
    a1.plot(E.M_TARGET, E.H_TOP / 1e3, "*", color=INK, ms=14)
    a1.set_ylabel("altitude (km)"); fig.legend(frameon=False, fontsize=11, loc="upper center", ncol=3, bbox_to_anchor=(0.5, 0.0))
    despine(a1); despine(a2)
    save(fig, "fig-22-ps-map")
