"""Lecture 20: C_L/C_D and C_L^(3/2)/C_D against C_L for Ojha's glider (_ojha.GLIDER), each divided by its largest
value, with the stall. Writes img/fig-20-factors.png."""
import numpy as np
from _visual import plt, save, despine, MAROON, BLUE, INK, GREY
import _ojha as O
from flight import aero as AE

G = O.GLIDER
CL = np.linspace(0.02, 2.2, 500)


def factor(n, cl):
    return cl**n / AE.parabolic_cd(cl, G["CD0"], G["K"])


CL1, CL32 = float(AE.best_cl_power(1.0, G["CD0"], G["K"])), float(AE.best_cl_power(1.5, G["CD0"], G["K"]))

if __name__ == "__main__":
    fig, ax = plt.subplots(figsize=(10, 4.9))
    for n, best, c, lab in ((1.0, CL1, BLUE, "$C_L/C_D$: flattest glide"), (1.5, CL32, MAROON, "$C_L^{3/2}/C_D$: least sink")):
        ok = CL <= G["CLmax"]
        y = factor(n, CL) / factor(n, best)
        ax.plot(CL[ok], y[ok], color=c, lw=2.8, label=lab); ax.plot(CL[~ok], y[~ok], color=c, lw=1.8, ls="--")
        ax.plot(best, 1.0, "o", color=c, ms=9, zorder=5)
        ax.plot([best, best], [0, 1.0], color=c, lw=1, ls=":")
        ax.text(best, 1.04, f"$C_L$ = {best:.2f}", ha="center", fontsize=12, color=c)
    ax.axvline(G["CLmax"], color=GREY, lw=1.2); ax.text(G["CLmax"] + 0.03, 0.45, "stall (dashed beyond)", fontsize=11.5)
    ax.set_xlim(0, 2.2); ax.set_ylim(0, 1.15); ax.set_xlabel("lift coefficient $C_L$"); ax.set_ylabel("fraction of its largest value")
    ax.legend(frameon=False, fontsize=12, loc="lower right")
    despine(ax)
    save(fig, "fig-20-factors")
