"""Lecture 7, how the full equations settle onto the quasi-steady glide: the HANSA-3 (partly estimated dataset) flying
level at 45 m/s at 2000 m has its engine cut and then holds the lift coefficient of its best lift-to-drag ratio
(flight.simulate, flat-Earth form; flight.guidance.ConstantCL). The quasi-steady glide at each height
(flight.performance.glide_state) is drawn dashed, and the two acceleration terms that quasi-steady flight drops,
|m V-dot| and |m V gamma-dot|, are shown divided by the weight. Writes img/anim-07-quasi-steady.gif."""
import numpy as np
from _visual import plt, save_anim, MAROON, BLUE, INK, GREY, AMBER
from flight import vehicle, guidance, simulate, eom, atmosphere as A, performance as PF, aero as AE
from flight.constants import G0

V_ = vehicle.load("hansa-3")
W = V_.gross_mass * G0
CD0, K = V_.aero.cd0(0.0), V_.aero.k(0.0)
CL, E = AE.max_lift_to_drag(CD0, K)
H0, V0 = 2000.0, 45.0
TR = simulate.simulate(V_, dict(h=H0, V=V0, gamma_deg=0.0, chi_deg=0.0), guidance.ConstantCL(CL, throttle=0.0),
                       eom.Options(gravity="flat"), t_end=200.0, max_step=0.2, form="flat")
_, U = np.unique(TR.t, return_index=True)
T, V, GAM, H, X = TR.t[U], TR.V[U], TR.gamma[U], TR.h[U], TR.x[U]
QS = [PF.glide_state(W, A.isa(h)[2], V_.aero.S, CL, AE.parabolic_cd(CL, CD0, K)) for h in H]
V_QS = np.array([q[0] for q in QS])
GAM_QS = np.degrees(QS[0][1])
ACC_V = np.abs(np.gradient(V, T)) / G0                        # |m Vdot| / W
ACC_G = np.abs(V * np.gradient(GAM, T)) / G0                  # |m V gammadot| / W


def largest_after(arr, t0):
    return float(arr[T >= t0].max())


PERIOD_EST = np.pi * np.sqrt(2.0) * V_QS[0] / G0

if __name__ == "__main__":
    fig = plt.figure(figsize=(10.5, 6.2))
    a = fig.add_axes([0.09, 0.15, 0.37, 0.76])
    b = fig.add_axes([0.58, 0.68, 0.39, 0.25]); c = fig.add_axes([0.58, 0.39, 0.39, 0.25]); d = fig.add_axes([0.58, 0.11, 0.39, 0.22])
    N = 140
    times = np.linspace(0.5, T[-1], N)

    def frame(k):
        for ax in (a, b, c, d):
            ax.clear()
        m = T <= times[k]
        a.plot(X[m] / 1e3, H[m], color=MAROON, lw=2.4)
        a.plot(X[m][-1] / 1e3, H[m][-1], "o", color=MAROON, ms=8)
        a.set_xlim(0, X[-1] / 1e3 * 1.03); a.set_ylim(1440, 2060)
        a.set_xlabel("distance (km)"); a.set_ylabel("height (m)")
        b.plot(T, np.full_like(T, GAM_QS), color=INK, lw=1.4, ls="--"); b.plot(T[m], np.degrees(GAM[m]), color=BLUE, lw=2.2)
        b.set_ylim(-15, 10); b.set_ylabel("$\\gamma$ (deg)"); b.text(198, 4.5, f"quasi-steady {GAM_QS:.1f}°", ha="right", fontsize=10.5)
        c.plot(T, V_QS, color=INK, lw=1.4, ls="--"); c.plot(T[m], V[m], color=MAROON, lw=2.2)
        c.set_ylim(32, 47); c.set_ylabel("$V$ (m/s)")
        d.semilogy(T[m], np.maximum(ACC_V[m], 1e-4), color=MAROON, lw=1.6, label="$|m\\dot V|/W$")
        d.semilogy(T[m], np.maximum(ACC_G[m], 1e-4), color=AMBER, lw=1.6, label="$|mV\\dot\\gamma|/W$")
        d.set_ylim(1e-3, 1.0); d.set_xlabel("time (s)"); d.set_ylabel("dropped / $W$")
        d.legend(frameon=False, fontsize=10, loc="upper right", ncol=2)
        for ax in (b, c, d):
            ax.set_xlim(0, T[-1])
        for ax in (b, c):
            ax.set_xticklabels([])
        for ax in (a, b, c, d):
            for s in ("top", "right"):
                ax.spines[s].set_visible(False)
        return []

    save_anim(fig, frame, N, 18, "anim-07-quasi-steady", dpi=90, hold=3.0)
