"""Lecture 25, the load factor around a circular loop flown at constant speed, n = cos(theta) + V^2/(g R) with theta
from the bottom (Ojha eq. 11.48), for three values of V^2/(g R): the bottom always carries 2 g more than the top
(Sadraey eq. 9.171). Writes img/fig-25-loop-n.png."""
import numpy as np
from _visual import plt, save, despine, MAROON, BLUE, GREEN, INK, GREY
from flight import performance as PF

THETA = np.linspace(0, 2 * np.pi, 361)
CASES = [(1.0, GREEN), (2.0, BLUE), (4.0, MAROON)]          # V^2/(g R)


def n_of(k):
    """n(theta) for V^2/(g R) = k: the engine's loop_load_factor with V = sqrt(k), g = R = 1."""
    return PF.loop_load_factor(THETA, np.sqrt(k), 1.0, g=1.0)


if __name__ == "__main__":
    fig, (a1, a2) = plt.subplots(1, 2, figsize=(11, 4.6), gridspec_kw=dict(width_ratios=[1, 1.5]))
    fig.subplots_adjust(wspace=0.3)
    a1.plot(np.sin(THETA), 1 - np.cos(THETA), color=INK, lw=2)
    for th, lab in ((0, "bottom\n$n=1+V^2/gR$"), (np.pi, "top\n$n=V^2/gR-1$"), (np.pi / 2, "side\n$n=V^2/gR$")):
        a1.plot(np.sin(th), 1 - np.cos(th), "o", color=MAROON, ms=8)
        a1.text(np.sin(th) + (0.12 if th == np.pi / 2 else 0), 1 - np.cos(th) + (-0.75 if th == 0 else 0.15 if th == np.pi else -0.05),
                lab, ha="left" if th == np.pi / 2 else "center", fontsize=11)
    a1.set_aspect("equal"); a1.set_xlim(-1.4, 2.4); a1.set_ylim(-0.9, 2.6); a1.axis("off")
    for k, c in CASES:
        a2.plot(np.degrees(THETA), n_of(k), color=c, lw=2.4, label=f"$V^2/gR={k:g}$")
    a2.axhline(0, color=GREY, lw=0.8)
    a2.set_xlabel("angle from the bottom (deg)"); a2.set_ylabel("load factor $n$")
    a2.set_xticks([0, 90, 180, 270, 360])
    fig.legend(frameon=False, fontsize=11, ncol=3, loc="upper center", bbox_to_anchor=(0.62, 0.0))
    despine(a2)
    save(fig, "fig-25-loop-n")
