"""Lecture 25, why light aircraft feel gusts more: the gust load factor 1 +- K_g rho0 U V a/(2 W/S) (FAR 23.341;
McCormick eq. 7.60) against equivalent airspeed for the HANSA-3 model (750 kg, S = 12 m^2 estimated, span 10.47 m) and the
jet transport of Sadraey's Problem 5.4 (270 t, S = 476 m^2, span estimated), both at sea level in the same 50 ft/s gust,
with lift slopes from the datasets (estimated). Lines: the FAR 23 normal-category limit for a 750 kg aircraft and the FAR 25
limit +2.5 (McCormick pp. 465-466). Writes img/fig-25-gust.png."""
import numpy as np
from _visual import plt, save, despine, MAROON, BLUE, GREY
from flight import vehicle, performance as PF
from flight.constants import KT, FT, G0, RHO0_SL

U = 50 * FT
LB = 0.45359237
CASES = []
for name, label, c, vmax_kt in (("hansa-3", "HANSA-3 model", MAROON, 140), ("transport-sadraey-p5-4", "jet transport (Sadraey P5.4)", BLUE, 350)):
    v = vehicle.load(name)
    m = v.gross_mass
    ws = m * G0 / v.aero.S
    chord = v.aero.S / v.info["aero"]["span"]
    a = v.info["aero"]["CLalpha"]
    kg, mu = PF.gust_alleviation(ws, RHO0_SL, chord, a)
    V = np.linspace(0, vmax_kt * KT, 200)
    CASES.append(dict(label=label, color=c, m=m, ws=ws, chord=chord, a=a, kg=kg, mu=mu, V=V,
                      n=PF.gust_load_factor(V, U, ws, a, kg)))
N23 = PF.far23_limit_load_factors("normal", CASES[0]["m"] / LB)[0]
N25 = PF.FAR25_LIMIT_LOAD_FACTORS[0]

if __name__ == "__main__":
    fig, ax = plt.subplots(figsize=(10, 4.8))
    for c in CASES:
        ax.plot(c["V"] / KT, c["n"], color=c["color"], lw=2.6, label=f"{c['label']}: $W/S$ = {c['ws']:.0f} N/m²")
        ax.plot(c["V"] / KT, 2 - c["n"], color=c["color"], lw=1.4, ls="--")
    ax.axhline(N23, color=MAROON, lw=1, ls=":"); ax.text(345, N23 + 0.08, f"FAR 23 normal minimum, 750 kg: {N23:.1f}", color=MAROON, fontsize=11, ha="right")
    ax.axhline(N25, color=BLUE, lw=1, ls=":"); ax.text(345, N25 + 0.08, "FAR 25 minimum: 2.5", color=BLUE, fontsize=11, ha="right")
    ax.axhline(1, color=GREY, lw=0.8)
    ax.set_xlabel("equivalent airspeed (kt)"); ax.set_ylabel("load factor in a 50 ft/s gust")
    ax.set_xlim(0, 350); ax.set_ylim(-2.5, 4.6)
    fig.legend(frameon=False, fontsize=11, loc="upper center", ncol=1, bbox_to_anchor=(0.5, 0.0))
    despine(ax)
    save(fig, "fig-25-gust")
