"""Lecture 20: glide hodographs at 2 km of a representative sailplane (dataset), Ojha's glider, the Kiran model and the
jet transport at 230 t, on a logarithmic speed axis, with the rate of descent also logarithmic so that rays of equal
glide ratio are parallel straight lines. Curves run from C_L = 0.2 to each aircraft's C_Lmax (1.2 assumed for the
transport). Writes img/fig-20-hodograph-classes.png."""
import numpy as np
from _visual import plt, save, despine, MAROON, BLUE, GREEN, AMBER, INK, GREY
from flight import performance as PF, aero as AE, atmosphere as A, vehicle
from flight.constants import G0
import _transport as TR
import _ojha as O

RHO = A.isa(2000.0)[2]
sail, kiran = vehicle.load("glider-representative"), vehicle.load("hjt-16-kiran")
CRAFT = [("sailplane, 450 kg", 450 * G0, sail.aero.S, float(sail.aero.cd0(0.0)), float(sail.aero.k(0.0)), 1.4, GREEN),
         ("Ojha's glider", O.GLIDER["W"], O.GLIDER["S"], O.GLIDER["CD0"], O.GLIDER["K"], O.GLIDER["CLmax"], BLUE),
         ("Kiran model, 4950 kg", 4950 * G0, kiran.aero.S, float(kiran.aero.cd0(0.0)), float(kiran.aero.k(0.0)), 1.2, AMBER),
         ("transport, 230 t", 230e3 * G0, TR.S, TR.CD0, TR.K, 1.2, MAROON)]
BEST = []
for name, W, S, cd0, k, clmax, c in CRAFT:
    cls, em = AE.max_lift_to_drag(cd0, k)
    BEST.append(dict(name=name, E=em, st=PF.glide_state(W, RHO, S, cls, AE.parabolic_cd(cls, cd0, k))))

if __name__ == "__main__":
    fig, ax = plt.subplots(figsize=(10, 5.4))
    for (name, W, S, cd0, k, clmax, c), b in zip(CRAFT, BEST):
        d = np.array([PF.glide_state(W, RHO, S, x, AE.parabolic_cd(x, cd0, k)) for x in np.linspace(0.2, clmax, 300)])
        ax.plot(d[:, 3], d[:, 2], color=c, lw=2.8, label=f"{name}: $E_{{max}}$ = {b['E']:.1f}")
        V, g, sink, vx = b["st"]
        ax.plot(vx, sink, "o", color=c, ms=8, zorder=5)
        xx = np.array([vx / 1.9, vx * 1.9]); ax.plot(xx, xx * sink / vx, color=c, lw=1, ls="--")
    ax.set_xscale("log"); ax.set_yscale("log"); ax.set_xlim(15, 400); ax.set_ylim(60, 0.3)
    ax.set_xticks([20, 50, 100, 200], ["20", "50", "100", "200"]); ax.set_yticks([0.5, 1, 2, 5, 10, 20, 50], ["0.5", "1", "2", "5", "10", "20", "50"])
    ax.set_xlabel("horizontal speed (m/s)"); ax.set_ylabel("rate of descent (m/s), downwards")
    ax.legend(frameon=False, fontsize=11, loc="lower left")
    despine(ax)
    save(fig, "fig-20-hodograph-classes")
