"""Lecture 22, the Rutowski construction one energy level at a time: for the Tejas-class model at 8500 kg with full
afterburner (_energy.ps), the specific excess power along four lines of constant energy height, 5, 10, 15 and 20 km,
against the Mach number at which each point is flown (the height on the level found from h + V^2/2g = h_E). The dot on
each curve is the best point of that level, where the minimum-time path crosses it. Writes img/fig-22-energy-levels.png."""
import numpy as np
from scipy.optimize import brentq
from _visual import plt, save, despine, MAROON, BLUE, GREEN, AMBER
import _energy as EN
from flight.constants import G0

LEVELS = [(5e3, GREEN), (10e3, BLUE), (15e3, AMBER), (20e3, MAROON)]


def height_on_level(he, M):
    f = lambda h: h + (M * EN.a_of(h))**2 / (2 * G0) - he
    if f(0.0) > 0:
        return np.nan                                # this Mach number needs more energy than the level has, even at sea level
    return brentq(f, 0.0, he)


CURVES = []
for he, c in LEVELS:
    M = np.linspace(0.3, 2.0, 341)
    h = np.array([height_on_level(he, m) for m in M])
    ok = ~np.isnan(h) & (h <= 20000.0)
    ps = np.array([EN.ps(m, hh) if k else np.nan for m, hh, k in zip(M, h, ok)])
    i = int(np.nanargmax(ps))
    CURVES.append(dict(he=he, c=c, M=M, h=h, ps=ps, i=i))

if __name__ == "__main__":
    fig, ax = plt.subplots(figsize=(10, 5.4))
    for cv in CURVES:
        ax.plot(cv["M"], cv["ps"], color=cv["c"], lw=2.6, label=f"$h_E$ = {cv['he'] / 1e3:.0f} km")
        ax.plot(cv["M"][cv["i"]], cv["ps"][cv["i"]], "o", color=cv["c"], ms=10)
    ax.axhline(0, color="#8a8378", lw=0.8)
    ax.set_xlim(0.3, 2.0); ax.set_ylim(-150, 300)
    ax.set_xlabel("Mach number at which the energy level is flown"); ax.set_ylabel("specific excess power $P_s$ (m/s)")
    ax.legend(frameon=False, fontsize=12, loc="upper right")
    despine(ax)
    save(fig, "fig-22-energy-levels")
