"""Lecture 22, the energy-share factor (Filippone sec. 10.5.1, Fig. 10.8): the fraction of the specific excess power that
goes into climbing, 1/(1 + (V/g) dV/dh), for climbs at constant Mach number and at constant calibrated airspeed, in the
troposphere (6 km) and the stratosphere (12 km), standard day (flight.performance.energy_share_factor, numerical, and
energy_share_constant_mach). Writes img/fig-22-share.png."""
import numpy as np
from _visual import plt, save, despine, MAROON, BLUE, GREEN, AMBER, INK
from flight import performance as PF, airspeed as AS, atmosphere as A

M = np.linspace(0.1, 0.95, 120)


def a(h):
    return A.speed_of_sound(A.isa(h)[0])


def cas_of(m, h):
    return AS.cas_from_impact(A.isa(h)[1] * AS.impact_ratio(m))


def factor_cas(m, h):
    vc = cas_of(m, h)
    return PF.energy_share_factor(lambda hh: AS.mach_at_cas(vc, hh) * a(hh), h)


CURVES = {"constant Mach, stratosphere": np.array([PF.energy_share_factor(lambda hh: m * a(hh), 12000.0) for m in M]),
          "constant Mach, troposphere": np.array([PF.energy_share_constant_mach(m) for m in M]),
          "constant CAS, stratosphere": np.array([factor_cas(m, 12000.0) for m in M]),
          "constant CAS, troposphere": np.array([factor_cas(m, 6000.0) for m in M])}
COLORS = [INK, BLUE, AMBER, MAROON]

if __name__ == "__main__":
    fig, ax = plt.subplots(figsize=(10, 5))
    for (lab, y), c in zip(CURVES.items(), COLORS):
        ax.plot(M, y, color=c, lw=2.5, label=lab)
    ax.set_xlabel("Mach number"); ax.set_ylabel("energy-share factor"); ax.set_ylim(0.4, 1.15)
    ax.legend(frameon=False, fontsize=12, loc="lower left")
    despine(ax)
    save(fig, "fig-22-share")
