"""Lecture 23, the absolute ceiling against weight for the Kiran model (thrust proportional to density): numerically, where the
greatest rate of climb vanishes, and from the closed form sigma = W/(E_max T_SL) (Vinh eq. 6.43). Writes img/fig-23-weight.png."""
import numpy as np
from _visual import plt, save, despine, MAROON, BLUE, INK
import _climb as C
from flight import performance as PF, aero as AE, atmosphere as A
from flight.constants import G0, RHO0_SL

MASSES = np.linspace(3800, 5600, 13)
CD0, K = C.polar(C.KIRAN)
EMAX = AE.max_lift_to_drag(CD0, K)[1]
NUMERIC = np.array([PF.ceiling(lambda h, m=m: C.max_roc(C.KIRAN, m * G0, h), 0.0, 0.0, 20000.0) for m in MASSES])
CLOSED = np.array([A.density_altitude(RHO0_SL * PF.absolute_ceiling_density_ratio(m * G0, EMAX, 18400.0)) for m in MASSES])

if __name__ == "__main__":
    fig, ax = plt.subplots(figsize=(10, 4.6))
    ax.plot(MASSES, NUMERIC / 1e3, "o", color=MAROON, ms=8, label="rate of climb = 0 (numerical)")
    ax.plot(MASSES, CLOSED / 1e3, color=BLUE, lw=2.2, label="$\\sigma=W/(E_{\\max}T_{SL})$ (Vinh eq. 6.43)")
    ax.set_xlabel("mass (kg)"); ax.set_ylabel("absolute ceiling (km)"); ax.legend(frameon=False, fontsize=12, loc="upper right")
    despine(ax)
    save(fig, "fig-23-weight")
