"""Lecture 20, the hodograph of Ojha's glider (_ojha.GLIDER) at 2 km in the ISA: rate of descent against horizontal speed,
from the exact steady glide at each lift coefficient (flight.performance.glide_state). The tangent from the origin marks
the flattest glide; the top of the curve, the least sink, lies beyond the stall (C_L,max = 1.2), dashed.
Writes img/fig-20-hodograph.png."""
import numpy as np
from _visual import plt, save, despine, MAROON, BLUE, GREEN, AMBER, INK, GREY
import _ojha as O
from flight import performance as PF, aero as AE, atmosphere as A

G = O.GLIDER
H = 2000.0
RHO = A.isa(H)[2]


def state(cl):
    return PF.glide_state(G["W"], RHO, G["S"], cl, AE.parabolic_cd(cl, G["CD0"], G["K"]))


CL_ALL = np.linspace(0.12, 1.5, 600)
ST = np.array([state(c) for c in CL_ALL])
CL_STAR, E_MAX = AE.max_lift_to_drag(G["CD0"], G["K"])
CL_MS = PF.min_sink_cl(G["CD0"], G["K"])
FLAT, MS, STALL = state(CL_STAR), state(CL_MS), state(G["CLmax"])

if __name__ == "__main__":
    fig, ax = plt.subplots(figsize=(10, 5.2))
    ok = CL_ALL <= G["CLmax"]
    ax.plot(ST[ok, 3], -ST[ok, 2], color=MAROON, lw=2.7, label="steady glides")
    ax.plot(ST[~ok, 3], -ST[~ok, 2], color=MAROON, lw=2, ls="--", label="beyond the stall")
    xs = np.linspace(0, 60, 2)
    ax.plot(xs, -xs * FLAT[2] / FLAT[3], color=BLUE, lw=1.6, ls=":")
    ax.plot(FLAT[3], -FLAT[2], "o", color=BLUE, ms=9, label=f"flattest glide, $E={E_MAX:.1f}$")
    ax.plot(MS[3], -MS[2], "s", color=GREEN, ms=8, label="least sink (past the stall)")
    ax.plot(STALL[3], -STALL[2], "^", color=AMBER, ms=9, label="stall, $C_{L,\\max}=1.2$")
    ax.set_xlim(0, 50); ax.set_ylim(-2.5, 0.1)
    ax.set_xlabel("horizontal speed (m/s)"); ax.set_ylabel("vertical speed (m/s)")
    ax.legend(frameon=False, fontsize=12, loc="lower left")
    despine(ax)
    save(fig, "fig-20-hodograph")
