"""Lecture 21, propeller and jet climb on one picture: rate of climb against u = V/V* at sea level and full throttle for
the HANSA-3 (piston propeller, constant power above the static-thrust cap) and the Kiran (turbojet, constant thrust),
from the course dataset (flight.vehicle, flight.propulsion, flight.aero, flight.performance.min_drag_speed). Each rate
of climb is divided by its own largest value, so the two shapes can be compared. The fastest climb of the jet sits
above u = 1 and that of the propeller aircraft below it. Writes img/fig-21-prop-jet-climb.png."""
import numpy as np
from _visual import plt, save, despine, MAROON, GREEN, GREY
from flight import vehicle, performance as PF
from flight.constants import G0

RHO = 1.225
CASES = []
for name, label, c in (("hansa-3", "HANSA-3, propeller", GREEN), ("hjt-16-kiran", "Kiran, jet", MAROON)):
    v = vehicle.load(name)
    eng, a = v.stages[0].engine, v.aero
    W = v.gross_mass * G0
    cd0, k = a.cd0(0.0), a.k(0.0)
    vstar = PF.min_drag_speed(W, RHO, a.S, cd0, k)
    vstall = np.sqrt(2 * W / (RHO * a.S * a.clmax(0.0)))
    V = np.linspace(vstall, 3.0 * vstar, 600)
    q = 0.5 * RHO * V**2
    cl = W / (q * a.S)
    D = q * a.S * (cd0 + k * cl**2)
    T = np.array([eng.thrust(1.0, 101325.0, RHO, 1.0, 1.0, x, x / 340.3) for x in V])
    roc = (T - D) * V / W
    i = int(np.argmax(roc))
    j = int(np.argmax((T - D) / W))                          # steepest climb: largest sin(gamma)
    CASES.append(dict(name=name, label=label, c=c, u=V / vstar, roc=roc, i=i, j=j, vstar=vstar, V=V, vstall=vstall))

if __name__ == "__main__":
    fig, ax = plt.subplots(figsize=(10, 5.2))
    for cs in CASES:
        y = cs["roc"] / cs["roc"][cs["i"]]
        ax.plot(cs["u"], y, color=cs["c"], lw=2.6, label=cs["label"])
        ax.plot(cs["u"][cs["i"]], 1.0, "s", color=cs["c"], ms=9)
        ax.plot(cs["u"][cs["j"]], y[cs["j"]], "o", color=cs["c"], ms=9)
    ax.axvline(1.0, color=GREY, lw=1, ls="--")
    ax.text(1.02, 0.08, "$V^*$, least drag", fontsize=12, color=GREY)
    ax.set_xlim(0.4, 2.6); ax.set_ylim(0, 1.1)
    ax.set_xlabel("$u=V/V^*$"); ax.set_ylabel("rate of climb / its largest value")
    ax.legend(frameon=False, fontsize=12, loc="lower right", title="squares: fastest climb\ndots: steepest climb", title_fontsize=11)
    despine(ax)
    save(fig, "fig-21-prop-jet-climb")
