"""Lecture 15, speed stability as a time history. At a fixed throttle, tau = T/D* = 1.5 (as in fig-15-stability), the
speed obeys (E* V*/g) du/dt = tau - (u^2 + 1/u^2)/2 at constant height, in the units u = V/V* of the note
(flight.performance.drag_ratio). Four starts, 5 % either side of each level-flight speed u1 and u2
(flight.performance.level_speed_ratios): the two near u2 return to it; of the two near u1, the slower one runs away
towards the stall (the run is stopped at u = 0.4) and the faster one runs all the way to u2.
Time is in units of E* V*/g. Writes img/anim-15-reversed-command.gif."""
import numpy as np
from scipy.integrate import solve_ivp
from _visual import plt, save_anim, MAROON, BLUE, GREEN, AMBER, INK, GREY
from flight import performance as PF

TAU = 1.5
U1, U2 = PF.level_speed_ratios(TAU)
U_STOP = 0.4                                   # the run towards the stall is stopped here
S_END = 4.0
S = np.linspace(0.0, S_END, 161)


def rate(s, y):
    return [TAU - PF.drag_ratio(y[0])]


def run(u0):
    stop = lambda s, y: y[0] - U_STOP
    stop.terminal = True
    sol = solve_ivp(rate, (0.0, S_END), [u0], events=stop, dense_output=True, rtol=1e-10, atol=1e-12)
    t_end = sol.t[-1]
    u = np.where(S <= t_end, sol.sol(np.minimum(S, t_end))[0], np.nan)
    return u, t_end


STARTS = [(U2 * 1.05, BLUE, "high-speed side, 5 % fast"), (U2 * 0.95, GREEN, "high-speed side, 5 % slow"),
          (U1 * 1.05, AMBER, "low-speed side, 5 % fast"), (U1 * 0.95, MAROON, "low-speed side, 5 % slow")]
RUNS = [run(u0) for u0, _, _ in STARTS]
T_STALL = RUNS[3][1]                            # time for the slow back-side start to reach u = 0.4
TC_FRONT = U2**3 / (U2**4 - 1)                  # decay time of a small error at u2, from the slope of tau - D/D*
TC_BACK = U1**3 / (1 - U1**4)                   # growth time of a small error at u1

if __name__ == "__main__":
    UC = np.linspace(0.3, 2.4, 400)
    fig, (a1, a2) = plt.subplots(1, 2, figsize=(10.5, 5.0), gridspec_kw=dict(width_ratios=[1, 1.15]))
    fig.subplots_adjust(wspace=0.3, bottom=0.15)

    def frame(k):
        a1.clear(); a2.clear()
        a1.plot(UC, PF.drag_ratio(UC), color=MAROON, lw=2.4, alpha=0.5, label="drag")
        a1.axhline(TAU, color=GREY, lw=1.8, label="thrust (fixed throttle)")
        for (u0, c, lab), (u, _) in zip(STARTS, RUNS):
            uk = u[:k + 1][~np.isnan(u[:k + 1])][-1]
            a1.plot(u0, PF.drag_ratio(u0), "o", mfc="none", mec=c, ms=10, mew=1.8, zorder=4)
            a1.plot(uk, PF.drag_ratio(uk), "o", color=c, ms=10, zorder=5)
            a2.plot(S[:k + 1], u[:k + 1], color=c, lw=2.4, label=lab)
        for ue, name in ((U1, "$u_1$"), (U2, "$u_2$")):
            a2.axhline(ue, color=INK, lw=1, ls="--")
            a2.text(S_END * 1.01, ue, name, va="center", fontsize=13)
        a2.axhline(U_STOP, color=GREY, lw=1, ls=":")
        a2.text(S_END * 0.98, U_STOP + 0.04, "towards the stall", ha="right", fontsize=11, color=GREY)
        a1.set_xlim(0.3, 2.4); a1.set_ylim(0, 3.6); a1.set_xlabel("$u=V/V^*$"); a1.set_ylabel("$D/D^*$, $T/D^*$")
        a1.legend(frameon=False, fontsize=11, loc="upper center")
        a1.text(2.35, 0.25, "open: start,  filled: now", ha="right", fontsize=10, color=GREY)
        a2.set_xlim(0, S_END); a2.set_ylim(0.3, 1.9)
        a2.set_xlabel("time, in units of $E^*V^*/g$"); a2.set_ylabel("$u=V/V^*$")
        a2.legend(frameon=False, fontsize=10, loc="center right")
        for a in (a1, a2):
            for s in ("top", "right"):
                a.spines[s].set_visible(False)
        return []

    save_anim(fig, frame, len(S), 20, "anim-15-reversed-command", dpi=90, hold=3.0)
