"""Lecture 18, breaking through: the Tejas-class fighter at 11 km and 8500 kg, with the thrust raised from 45 % to 100 %
of full afterburner and then brought back (left: tau_a and tau_r; right: the level-flight Mach number). The aircraft
stays on a stable solution (tau_a - tau_r falling with Mach) next to the one it was on, so it jumps where its branch
ends, at a different thrust going up and coming down. Writes img/anim-18-throttle.gif."""
import numpy as np
from _visual import plt, save_anim, MAROON, BLUE, GREEN, AMBER, INK, GREY
import _fighter as F

V, H, MASS = F.TEJ, 11000.0, F.M_REF
M = np.linspace(0.3, 2.2, 500)
TAU_R = np.array([F.tau_r(V, x, MASS, H) for x in M])
UP = np.linspace(0.45, 1.0, 56)
LEVELS = np.concatenate([UP, UP[::-1][1:]])


def stable_roots(f):
    out = []
    for r in F.level_machs(V, MASS, H, True, f, lo=0.6, n=1500):
        e = 1e-4
        g = lambda x: F.tau_a(V, x, H, True, f) - F.tau_r(V, x, MASS, H)
        if g(r + e) - g(r - e) < 0:
            out.append(r)
    return out


def track():
    m, path = None, []
    for f in LEVELS:
        rs = stable_roots(f)
        m = max(rs) if m is None else min(rs, key=lambda r: abs(r - m))
        path.append(m)
    return np.array(path)


PATH = track()
JUMP_UP = [(LEVELS[i], PATH[i], PATH[i + 1]) for i in range(len(UP) - 1) if PATH[i + 1] - PATH[i] > 0.1]
JUMP_DOWN = [(LEVELS[i + 1], PATH[i], PATH[i + 1]) for i in range(len(UP) - 1, len(LEVELS) - 1) if PATH[i] - PATH[i + 1] > 0.1]

if __name__ == "__main__":
    fig, (a1, a2) = plt.subplots(1, 2, figsize=(11, 4.9), gridspec_kw=dict(width_ratios=[1.2, 1]))
    fig.subplots_adjust(wspace=0.28, bottom=0.14)

    def frame(k):
        a1.clear(); a2.clear()
        f = LEVELS[k]
        up = k < len(UP)
        a1.plot(M, TAU_R, color=MAROON, lw=2.6, label="required")
        a1.plot(M, [F.tau_a(V, x, H, True, f) for x in M], color=BLUE, lw=2.2, ls="--", label="available")
        a1.plot(PATH[k], F.tau_r(V, PATH[k], MASS, H), "o", color=INK, ms=9, zorder=5)
        a1.set_xlim(0.6, 2.2); a1.set_ylim(0, 0.2); a1.set_xlabel("Mach number"); a1.set_ylabel("$\\tau$")
        a1.set_title(f"thrust {100 * f:.0f} % of full afterburner, {'rising' if up else 'falling'}", fontsize=13, loc="left")
        a1.legend(frameon=False, fontsize=12, loc="upper left")
        n_up = min(k + 1, len(UP))
        a2.plot(100 * LEVELS[:n_up], PATH[:n_up], color=GREEN, lw=2.5, label="thrust rising")
        if not up:
            a2.plot(100 * LEVELS[len(UP) - 1:k + 1], PATH[len(UP) - 1:k + 1], color=AMBER, lw=2.5, ls="--", label="thrust falling")
        a2.plot(100 * f, PATH[k], "o", color=INK, ms=8)
        a2.set_xlim(43, 102); a2.set_ylim(0.8, 1.8); a2.set_xlabel("thrust (% of full afterburner)"); a2.set_ylabel("Mach number")
        a2.legend(frameon=False, fontsize=12, loc="upper left")
        for a in (a1, a2):
            for s in ("top", "right"):
                a.spines[s].set_visible(False)
        return []

    save_anim(fig, frame, len(LEVELS), 10, "anim-18-throttle", dpi=90, hold=2.5)
