"""Lecture 14: overall efficiency eta_o = g0 V/(c h) against true airspeed for Sadraey's TSFC ranges (Table 4.7:
turbojet 0.8-0.9, low-bypass 0.7-0.8, high-bypass 0.4-0.5 per hour), h = 42 MJ/kg
(flight.propulsion.overall_efficiency), and for the HANSA-3's piston engine and propeller (dataset values, ESTIMATED),
whose efficiency does not change with speed when the propeller efficiency is constant.
Writes img/fig-14-overall-efficiency.png."""
import numpy as np
from _visual import plt, save, despine, MAROON, BLUE, GREEN, AMBER, INK, GREY
from flight import propulsion as P, performance as PF, vehicle
from flight.constants import G0

CLASSES = [("turbojet, 0.8–0.9 per hour", 0.8, 0.9, MAROON), ("low-bypass turbofan, 0.7–0.8", 0.7, 0.8, BLUE),
           ("high-bypass turbofan, 0.4–0.5", 0.4, 0.5, GREEN)]
HAN = vehicle.load("hansa-3").stages[0].engine


def eta_jet(V, c_per_hour):
    """Overall efficiency for 1 N of thrust: fuel mass flow c T/(g0 3600)."""
    return P.overall_efficiency(1.0, V, c_per_hour / 3600.0 / G0)


def eta_prop(V):
    c = PF.equivalent_tsfc_prop(V, HAN.eta, HAN.psfc)
    return P.overall_efficiency(1.0, V, c / G0)


if __name__ == "__main__":
    V = np.linspace(20, 300, 300)
    fig, ax = plt.subplots(figsize=(10, 5.2))
    for lab, c0, c1, c in CLASSES:
        vv = V[V >= 100]
        ax.fill_between(vv, eta_jet(vv, c1), eta_jet(vv, c0), color=c, alpha=0.35, label=lab)
        ax.plot(vv, eta_jet(vv, 0.5 * (c0 + c1)), color=c, lw=1.2)
    vp = np.linspace(25, 70, 20)
    ax.plot(vp, [eta_prop(v) for v in vp], color=AMBER, lw=4, label="HANSA-3, piston and propeller (estimated)")
    for v, c, lab, off in ((236.0, 0.5, "0.40", (6, 8)), (236.0, 0.9, "0.22", (6, -16))):
        ax.plot(v, eta_jet(v, c), "o", color=INK, ms=8)
        ax.annotate(lab, (v, eta_jet(v, c)), xytext=off, textcoords="offset points", fontsize=12.5)
    ax.axvline(236, color=GREY, lw=1, ls=":"); ax.text(238, 0.015, "Mach 0.8 at 11 km", rotation=90, ha="left", va="bottom", fontsize=11)
    ax.set_xlim(0, 300); ax.set_ylim(0, 0.65); ax.set_xlabel("true airspeed (m/s)"); ax.set_ylabel("overall efficiency $\\eta_o$")
    ax.legend(frameon=False, fontsize=11.5, loc="upper left")
    despine(ax)
    save(fig, "fig-14-overall-efficiency")
