"""Lecture 21, climbing at constant equivalent airspeed (Hull sec. 5.8): time and fuel for Hull's SBJ from sea level to
35,000 ft at each constant EAS, against the minimum-time climb. Writes img/fig-21-eas.png."""
import numpy as np
from scipy.optimize import minimize_scalar
from _visual import plt, save, despine, MAROON, BLUE, INK
import _climb as C
from flight import performance as PF, atmosphere as A
from flight.constants import FT, KT, RHO0_SL

HS = np.linspace(0, 35000, 701) * FT


def eas_climb(ve):
    def u_of(tau, h):
        return ve / np.sqrt(A.isa(h)[2] / RHO0_SL) / C.scales(C.SBJ, C.W_SBJ, h)[1]
    return PF.climb_integrals(HS, C.climb_state(C.SBJ, C.W_SBJ, u_of))


VES = np.linspace(150, 268, 60)
RES = np.array([[r[-1] for r in eas_climb(v * KT)] for v in VES])
BEST = minimize_scalar(lambda v: eas_climb(v * KT)[1][-1], bounds=(150, 300), method="bounded", options=dict(xatol=0.01))
VE_BEST, T_BEST = BEST.x, BEST.fun
MIN_TIME = PF.climb_integrals(HS, C.climb_state(C.SBJ, C.W_SBJ, C.FASTEST))

if __name__ == "__main__":
    fig, (a1, a2) = plt.subplots(1, 2, figsize=(11, 4.6))
    fig.subplots_adjust(wspace=0.3)
    a1.plot(VES, RES[:, 1] / 60, color=MAROON, lw=2.6, label="constant EAS")
    a1.axhline(MIN_TIME[1][-1] / 60, color=INK, lw=1.4, ls="--", label="fastest climb")
    a1.plot(VE_BEST, T_BEST / 60, "o", color=MAROON, ms=8)
    a1.set_xlabel("equivalent airspeed (kt)"); a1.set_ylabel("time to 35,000 ft (min)"); a1.set_ylim(7, 14)
    a1.legend(frameon=False, fontsize=11, loc="upper center")
    a2.plot(VES, RES[:, 2] / C.LB, color=BLUE, lw=2.6, label="constant EAS")
    a2.axhline(MIN_TIME[2][-1] / C.LB, color=INK, lw=1.4, ls="--", label="fastest climb")
    a2.set_xlabel("equivalent airspeed (kt)"); a2.set_ylabel("fuel (lb)"); a2.set_ylim(400, 700)
    a2.legend(frameon=False, fontsize=11, loc="upper center")
    despine(a1); despine(a2)
    save(fig, "fig-21-eas")
