"""Lecture 15, speed stability at the two level-flight speeds with a fixed throttle (tau = 1.5): a gust that speeds the
aircraft up on the high-speed side meets more drag than thrust and slows it back; on the low-speed side it meets less
drag and keeps accelerating, and a slow-down keeps slowing (flight.performance). Writes img/fig-15-stability.png."""
import numpy as np
from matplotlib.patches import FancyArrowPatch
from _visual import plt, save, despine, MAROON, BLUE, GREEN, INK, GREY
from flight import performance as PF

TAU = 1.5
U1, U2 = PF.level_speed_ratios(TAU)
U = np.linspace(0.3, 2.4, 400)

if __name__ == "__main__":
    fig, ax = plt.subplots(figsize=(10, 5.2))
    ax.plot(U, PF.drag_ratio(U), color=MAROON, lw=2.6, label="drag")
    ax.axhline(TAU, color=BLUE, lw=2, label="thrust (fixed throttle)")
    for u0, c, lab in ((U1, GREEN, "unstable: a disturbance grows"), (U2, INK, "stable: the aircraft returns")):
        ax.plot(u0, TAU, "o", color=c, ms=9, zorder=5)
        sign = 1 if u0 > 1 else -1
        for du in (-0.12, 0.12):
            u = u0 + du
            d = PF.drag_ratio(u)
            back = (d > TAU)          # drag larger than thrust: decelerates
            v = -0.1 if back else 0.1
            ax.add_patch(FancyArrowPatch((u, d), (u + v, d), arrowstyle="-|>", mutation_scale=16, color=c, lw=2))
        ax.text(1.75 if u0 > 1 else 0.85, 1.1 if u0 > 1 else 0.6, lab, ha="center", fontsize=12, color=c)
    ax.set_xlim(0.3, 2.4); ax.set_ylim(0, 3); ax.set_xlabel("$u=V/V^*$"); ax.set_ylabel("$D/D^*$, $T/D^*$")
    ax.legend(frameon=False, fontsize=12, loc="upper center")
    despine(ax)
    save(fig, "fig-15-stability")
