"""Lecture 20, water ballast: the hodograph of Ojha's glider at 2 km at its own weight and with 50 % more weight
(an illustrative ballast). Every point moves out along its ray from the origin by sqrt(1.5): the flattest glide keeps
its angle and glide ratio but is flown 22 % faster. Writes img/fig-20-ballast.png."""
import numpy as np
from _visual import plt, save, despine, MAROON, BLUE, INK
import _ojha as O
from flight import performance as PF, aero as AE, atmosphere as A

G = O.GLIDER
RHO = A.isa(2000.0)[2]
CL = np.linspace(0.15, G["CLmax"], 400)
CLS, E = AE.max_lift_to_drag(G["CD0"], G["K"])
FACTOR = 1.5


def curve(w):
    return np.array([PF.glide_state(w, RHO, G["S"], c, AE.parabolic_cd(c, G["CD0"], G["K"])) for c in CL])


LIGHT, HEAVY = curve(G["W"]), curve(FACTOR * G["W"])
BEST = {lab: PF.glide_state(w, RHO, G["S"], CLS, AE.parabolic_cd(CLS, G["CD0"], G["K"])) for lab, w in
        (("light", G["W"]), ("heavy", FACTOR * G["W"]))}

if __name__ == "__main__":
    fig, ax = plt.subplots(figsize=(10, 5))
    for st, c, lab in ((LIGHT, MAROON, f"{G['W']:.0f} N"), (HEAVY, BLUE, f"{FACTOR * G['W']:.0f} N (ballast)")):
        ax.plot(st[:, 3], -st[:, 2], color=c, lw=2.6, label=lab)
    for lab, c in (("light", MAROON), ("heavy", BLUE)):
        b = BEST[lab]
        ax.plot(b[3], -b[2], "o", color=c, ms=9)
    ax.plot([0, 70], [0, -70 / E], color=INK, lw=1.4, ls=":", label=f"glide ratio {E:.1f}")
    ax.set_xlim(0, 70); ax.set_ylim(-4, 0.2); 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-ballast")
