"""Lecture 24: load factor of a level turn and the factor on the stall speed, sqrt(n), against bank angle, with limit
load factors 2.5, 4.5 and 9 for reference (flight.performance.bank_for_load_factor). Writes img/fig-24-load-bank.png."""
import numpy as np
from _visual import plt, save, despine, MAROON, BLUE, INK, GREY
from flight import performance as PF

BANK = np.linspace(0, 85, 600)


def load(bank_deg):
    return PF.stall_load_factor(1.0, np.sqrt(np.cos(np.radians(bank_deg))))      # n = 1/cos(bank)


LIMITS = [(2.5, "transport limit 2.5"), (4.5, "Hull's business jet 4.5"), (9.0, "fighter 9")]
BANK_AT = {n: float(np.degrees(PF.bank_for_load_factor(n))) for n, _ in LIMITS}

if __name__ == "__main__":
    fig, ax = plt.subplots(figsize=(10, 5.2))
    ax.plot(BANK, load(BANK), color=MAROON, lw=2.8, label="load factor $n$")
    ax.plot(BANK, np.sqrt(load(BANK)), color=BLUE, lw=2.8, label="stall speed in the turn / in level flight, $\\sqrt{n}$")
    for n, lab in LIMITS:
        ax.axhline(n, color=GREY, lw=1, ls="--")
        ax.text(2, n + 0.12, f"{lab}: {BANK_AT[n]:.0f}° of bank", fontsize=11, color=INK)
    for s in (30, 45, 60, 80):
        ax.plot(s, load(s), "o", color=MAROON, ms=7)
        ax.annotate(f"{load(s):.2f}", (s, load(s)), xytext=(-6, 6), textcoords="offset points", ha="right", fontsize=11.5, color=MAROON)
    ax.set_xlim(0, 85); ax.set_ylim(0, 11.5); ax.set_xlabel("bank angle (deg)"); ax.set_ylabel("ratio")
    ax.legend(frameon=False, fontsize=11.5, loc="upper left", bbox_to_anchor=(0, 0.78))
    despine(ax)
    save(fig, "fig-24-load-bank")
