"""Lecture 24, the sustained level turns of Hull's SBJ at 11,000 lb with P = 0.98 at 0, 20,000 and 40,000 ft, from the
ideal-airplane formulas (Hull sec. 7.8): load factor, bank angle, turn rate and turn radius against airspeed, the
quantities of Hull's Figs. 7.5-7.8. Dots: the fastest (u = 1) and the tightest (u = 1/sqrt(tau)) sustained turns. Dashed: the part of each curve that needs
more than C_Lmax = 1.24, which the wing cannot give.
Writes img/fig-24-sbj.png."""
import numpy as np
from _visual import plt, save, despine, MAROON, BLUE, GREEN, INK
import _climb as C
import _turns as T
from flight import performance as PF, atmosphere as A
from flight.constants import FT

HEIGHTS = [(0.0, MAROON), (20000 * FT, BLUE), (40000 * FT, GREEN)]
CURVES = {}
OPT = {}
for h, c in HEIGHTS:
    tau, vs, es = C.scales(T.SBJ, T.W_SBJ, h)
    u = np.linspace(0.15, 3.2, 1500)
    n, mu, r, R = T.sbj_sustained(h, u * vs)
    CL = PF.cl_for_load_factor(n, T.W_SBJ, A.isa(h)[2], u * vs, T.SBJ.aero.S)
    CURVES[h] = (u * vs, n, mu, r, R, CL)
    uf, ut = PF.U_FASTEST_SUSTAINED, PF.tightest_sustained_u(tau)
    OPT[h] = dict(tau=tau, vstar=vs, fast=(uf * vs,) + tuple(T.sbj_sustained(h, uf * vs)),
                  tight=(ut * vs,) + tuple(T.sbj_sustained(h, ut * vs)),
                  nmax=(PF.max_load_factor_u(tau) * vs, tau))

if __name__ == "__main__":
    fig, axs = plt.subplots(2, 2, figsize=(11, 8.2))
    fig.subplots_adjust(hspace=0.32, wspace=0.28)
    (a1, a2), (a3, a4) = axs
    for (h, c) in HEIGHTS:
        V, n, mu, r, R, CL = CURVES[h]
        lab = f"{h / FT:,.0f} ft"
        ok = CL <= T.CLMAX_SBJ
        bad = ~ok
        bad[1:] |= bad[:-1].copy()               # join the dashed part to the solid one
        for a, y in ((a1, n), (a2, np.degrees(mu)), (a3, np.degrees(r)), (a4, R / 1e3)):
            a.plot(V[ok], y[ok], color=c, lw=2.4, label=lab if a is a1 else None)
            a.plot(np.where(bad, V, np.nan), y, color=c, lw=1.6, ls="--")
        f, t = OPT[h]["fast"], OPT[h]["tight"]
        a3.plot(f[0], np.degrees(f[3]), "o", color=c, ms=8)
        a4.plot(t[0], t[4] / 1e3, "s", color=c, ms=8)
    a1.set_ylabel("load factor $n$"); a2.set_ylabel("bank angle (deg)")
    a3.set_ylabel("turn rate (deg/s)"); a4.set_ylabel("turn radius (km)")
    a4.set_ylim(0, 6)
    fig.legend(frameon=False, fontsize=11, loc="upper center", ncol=3, bbox_to_anchor=(0.5, 0.0))
    for a in axs.flat:
        a.set_xlim(0, 290); despine(a)
    for a in (a3, a4):
        a.set_xlabel("airspeed (m/s)")
    save(fig, "fig-24-sbj")
