"""Lecture 14, thrust and power available against true airspeed at sea level, full throttle, per unit weight so that
very different aircraft share one pair of axes: the HANSA-3 trainer (piston propeller), the ATR 72-600 (turboprop) and
the HJT-16 Kiran (turbojet), from the course dataset (flight.vehicle, flight.propulsion: Propeller thrust = eta P/V
capped by the static thrust; Jet thrust independent of speed). Left: T/W. Right: T V/W, the power available per unit
weight, in m/s. Writes img/fig-14-thrust-power.png."""
import numpy as np
from _visual import plt, save, despine, MAROON, BLUE, GREEN
from flight import vehicle
from flight.constants import G0

RHO, CASES = 1.225, []
for name, label, vmax, c in (("hansa-3", "HANSA-3, piston propeller", 75.0, GREEN),
                             ("atr72-600", "ATR 72-600, turboprop", 160.0, BLUE),
                             ("hjt-16-kiran", "Kiran, turbojet", 200.0, MAROON)):
    v = vehicle.load(name)
    eng = v.stages[0].engine
    W = v.gross_mass * G0
    V = np.linspace(1.0, vmax, 300)
    T = np.array([eng.thrust(1.0, 101325.0, RHO, 1.0, 1.0, x, x / 340.3) for x in V])
    CASES.append(dict(name=name, label=label, c=c, V=V, TW=T / W, PW=T * V / W, W=W))


def at(name, speed, key):
    cs = next(c for c in CASES if c["name"] == name)
    return float(np.interp(speed, cs["V"], cs[key]))


if __name__ == "__main__":
    fig, (a1, a2) = plt.subplots(1, 2, figsize=(10.5, 4.9))
    fig.subplots_adjust(wspace=0.3)
    for cs in CASES:
        a1.plot(cs["V"], cs["TW"], color=cs["c"], lw=2.6, label=cs["label"])
        a2.plot(cs["V"], cs["PW"], color=cs["c"], lw=2.6)
    a1.set_xlabel("true airspeed (m/s)"); a1.set_ylabel("thrust per unit weight, $T/W$")
    a2.set_xlabel("true airspeed (m/s)"); a2.set_ylabel("power per unit weight, $TV/W$ (m/s)")
    a1.set_xlim(0, 200); a1.set_ylim(0, 0.75); a2.set_xlim(0, 200); a2.set_ylim(0, 80)
    a1.legend(frameon=False, fontsize=11, loc="upper right")
    despine(a1); despine(a2)
    save(fig, "fig-14-thrust-power")
