"""Lecture 25, the V-n diagram of Sadraey's acrobatic GA aircraft (Example 9.15: 2300 kg, S = 19.33 m^2, C_Lmax = 2 and
-1.2, aspect ratio 7, a = 6.3 /rad, V_C = 310 KEAS): the manoeuvre diagram with the FAR 23 acrobatic limits +6/-3
(McCormick p. 465) and V_D = 1.55 V_C (Sadraey eq. 9.200), the gust lines at sea level for 50 ft/s at V_C and 25 ft/s at
V_D (Sadraey Table 9.9; McCormick p. 468) with the FAR 23 gust formula, and the combined envelope.
Writes img/fig-25-vn.png."""
import numpy as np
from _visual import plt, save, despine, MAROON, BLUE, INK, GREY, AMBER
from flight import performance as PF
from flight.constants import KT, FT, G0, RHO0_SL

M, S, CLMAX, CLNEG, AR, A_LIFT, VC_KEAS = 2300.0, 19.33, 2.0, 1.2, 7.0, 6.3, 310.0
W = M * 9.81                                          # Sadraey's g
WS = W / S
SPAN = np.sqrt(AR * S)
CHORD = S / SPAN
NPOS, NNEG = PF.far23_limit_load_factors("acrobatic")
VC = VC_KEAS * KT
VD = PF.DIVE_TO_CRUISE["acrobatic"] * VC
VS = PF.speed_for_cl(W, RHO0_SL, S, CLMAX)           # equivalent airspeeds: sea-level density
VS_NEG = PF.speed_for_cl(W, RHO0_SL, S, CLNEG)
VA = PF.corner_speed(VS, NPOS)
VJ = PF.corner_speed(VS_NEG, -NNEG)
U_C, U_D = 50 * FT, 25 * FT                          # derived gust speeds at V_C and V_D, sea level to 20,000 ft


def gust_lines(rho):
    """Gust load factors (+, -) at V_C and V_D for flight at density rho (K_g from the density at height)."""
    kg, mu = PF.gust_alleviation(WS, rho, CHORD, A_LIFT, g=9.81)
    out = {}
    for name, V, U in (("C", VC, U_C), ("D", VD, U_D)):
        out[name] = (PF.gust_load_factor(V, U, WS, A_LIFT, kg), PF.gust_load_factor(V, -U, WS, A_LIFT, kg))
    return kg, mu, out


KG_SL, MU_SL, G_SL = gust_lines(RHO0_SL)
V = np.linspace(0, VD, 800)
N_MAN_POS = np.minimum(PF.stall_load_factor(V, VS), NPOS)
N_MAN_NEG = np.maximum(-PF.stall_load_factor(V, VS_NEG), NNEG)
N_GUST_POS = np.interp(V, [0, VC, VD], [1, G_SL["C"][0], G_SL["D"][0]])
N_GUST_NEG = np.interp(V, [0, VC, VD], [1, G_SL["C"][1], G_SL["D"][1]])
# the combined envelope: manoeuvre and gust together, but no higher than the wing can lift at that speed
N_TOP = np.minimum(np.maximum(N_MAN_POS, N_GUST_POS), PF.stall_load_factor(V, VS))
N_BOT = np.maximum(np.minimum(N_MAN_NEG, N_GUST_NEG), -PF.stall_load_factor(V, VS_NEG))
N_MAX = N_TOP.max()

if __name__ == "__main__":
    fig, ax = plt.subplots(figsize=(10, 5.6))
    k = 1 / KT
    ax.fill_between(V * k, N_BOT, N_TOP, color=AMBER, alpha=0.15, lw=0)
    ax.plot(V * k, N_MAN_POS, color=MAROON, lw=2.4, label="manoeuvre (FAR 23 acrobatic, +6/−3)")
    ax.plot(V * k, N_MAN_NEG, color=MAROON, lw=2.4)
    ax.plot([VD * k] * 2, [NNEG, NPOS], color=MAROON, lw=2.4)
    ax.plot(V * k, N_GUST_POS, color=BLUE, lw=1.6, ls="--", label="gust lines, sea level (50 ft/s at $V_C$, 25 ft/s at $V_D$)")
    ax.plot(V * k, N_GUST_NEG, color=BLUE, lw=1.6, ls="--")
    for x, n, lab, dy in ((VS, 1, "$V_S$", 0.5), (VA, NPOS, "A", 0.25), (VC, G_SL["C"][0], "C", 0.25), (VD, NPOS, "$V_D$", 0.25),
                          (VJ, NNEG, "J", -0.6)):
        ax.plot(x * k, n, "o", color=INK, ms=6)
        ax.text(x * k - (6 if lab == "$V_S$" else 0), n + dy, f"{lab} ({x * k:.0f})", ha="right" if lab == "$V_S$" else "center", fontsize=11)
    ax.axhline(0, color=GREY, lw=0.8)
    ax.set_xlabel("equivalent airspeed (kt)"); ax.set_ylabel("load factor $n$")
    ax.set_xlim(0, 520); ax.set_ylim(-5.2, 7.4)
    fig.legend(frameon=False, fontsize=11, loc="upper center", ncol=1, bbox_to_anchor=(0.5, 0.0))
    despine(ax)
    save(fig, "fig-25-vn")
