"""Lecture 23, the buffet boundary and the coffin corner of a DC-9-class airliner (_dc9.py) at an assumed cruise mass of
45,000 kg: the usable C_L against Mach number (read off Filippone Fig. 4.25) and the lift coefficient needed for a 1.3 g
manoeuvre at four altitudes (Filippone eq. 4.89); the corner is where the needed curve just touches the boundary
(flight.performance.coffin_corner_pressure). Writes img/fig-23-buffet.png."""
import numpy as np
from _visual import plt, save, despine, MAROON, BLUE, GREEN, AMBER, PURPLE, INK
import _dc9 as D
from flight import performance as PF, atmosphere as A
from flight.constants import G0, FT

MASS = 45000.0
W = MASS * G0
MB = np.array([m for m, _ in D.BUFFET]); CB = np.array([c for _, c in D.BUFFET])


def cl_buffet(M):
    return float(np.interp(M, MB, CB))


P_CORNER, M_CORNER = PF.coffin_corner_pressure(D.N_BUFFET, W, D.S, cl_buffet)
H_CORNER = A.pressure_altitude(P_CORNER)
P1, _ = PF.coffin_corner_pressure(1.0, W, D.S, cl_buffet)
H_CORNER_1G = A.pressure_altitude(P1)
ALTS = [(25000 * FT, GREEN), (30000 * FT, BLUE), (H_CORNER, MAROON), (38000 * FT, PURPLE)]
BUFFET_AT = {h: PF.buffet_machs(D.N_BUFFET, W, D.S, A.isa(h)[1], cl_buffet) for h, _ in ALTS}

if __name__ == "__main__":
    fig, ax = plt.subplots(figsize=(10, 5.2))
    M = np.linspace(0.3, 0.9, 300)
    ax.plot(MB, CB, color=INK, lw=2.8, label="buffet boundary (DC9-80, Filippone Fig. 4.25)")
    for h, c in ALTS:
        p = A.isa(h)[1]
        need = D.N_BUFFET * W / (0.7 * p * M**2 * D.S)
        ax.plot(M, need, color=c, lw=2.0, ls="--", label=f"1.3 g needs, {h / FT:,.0f} ft")
        for mb in BUFFET_AT[h]:
            ax.plot(mb, cl_buffet(mb), "o", color=c, ms=7)
    ax.set_xlim(0.3, 0.9); ax.set_ylim(0, 1.6); ax.set_xlabel("Mach number"); ax.set_ylabel("lift coefficient")
    ax.legend(frameon=False, fontsize=10, loc="lower left")
    despine(ax)
    save(fig, "fig-23-buffet")
