"""Lecture 9, an aircraft holds an altimeter reading of 5000 m (pressure altitude) while flying from warm air (ISA+15)
into cold air (ISA-25) over a ridge. Its true height follows the 5000 m pressure level, which sinks in the cold air:
"from high to low, look out below". True heights from flight.atmosphere.thickness; the sea-level pressure is standard
throughout. Writes img/anim-09-altimeter.gif."""
import numpy as np
from _visual import plt, save_anim, MAROON, BLUE, INK, GREY, GREEN
from flight import atmosphere as A

HP = 5000.0                                         # what the altimeter shows (pressure altitude, m)
X = np.linspace(0.0, 200.0, 201)                    # distance flown (km)
DT = np.interp(X, [0, 60, 140, 200], [15, 15, -25, -25])     # temperature deviation along the route (K)
H_TRUE = np.array([A.thickness(0.0, HP, d) for d in DT])     # true height of the 5000 m pressure level
RIDGE = 4300.0 * np.exp(-0.5 * ((X - 175.0) / 9.0) ** 2) + 600.0 * np.exp(-0.5 * ((X - 100) / 40) ** 2)

I_CREST = int(np.argmax(RIDGE))
CREST = dict(x=X[I_CREST], ground=RIDGE[I_CREST], true=H_TRUE[I_CREST])

if __name__ == "__main__":
    fig, ax = plt.subplots(figsize=(10, 5.6))
    fig.subplots_adjust(bottom=0.13, top=0.9)
    N = 100
    ks = np.linspace(0, len(X) - 1, N).astype(int)

    def frame(k):
        ax.clear()
        j = ks[k]
        ax.fill_between(X, 0, RIDGE, color="#c9bda8", lw=0)
        ax.plot(X, np.full_like(X, HP), color=GREY, lw=1.2, ls="--")
        ax.text(198, HP + 80, "what the altimeter shows: 5000 m", fontsize=11, color=GREY, ha="right")
        ax.plot(X[:j + 1], H_TRUE[:j + 1], color=MAROON, lw=2.4)
        ax.plot(X[j], H_TRUE[j], ">", color=INK, ms=11)
        ax.text(45, 3300, "warm air, ISA + 15 K", fontsize=12, color=MAROON, ha="center")
        ax.text(120, 2300, "cold air, ISA − 25 K", fontsize=12, color=BLUE, ha="center")
        ax.set_title(f"altimeter 5000 m, true height {H_TRUE[j]:.0f} m", fontsize=12, loc="left")
        if X[j] >= CREST["x"]:
            xc = CREST["x"]
            ax.annotate("", xy=(xc, CREST["ground"]), xytext=(xc, CREST["true"]),
                        arrowprops=dict(arrowstyle="<->", color=BLUE, lw=1.6))
            ax.text(xc - 3, CREST["ground"] - 650,
                    f"over the ridge: {CREST['true'] - CREST['ground']:.0f} m clear,\nnot the {HP - CREST['ground']:.0f} m the altimeter suggests",
                    fontsize=11, color=BLUE, ha="right")
        ax.set_xlim(0, 200)
        ax.set_ylim(0, 6000)
        ax.set_xlabel("distance flown (km)")
        ax.set_ylabel("true height (m)")
        for s in ("top", "right"):
            ax.spines[s].set_visible(False)
        return []

    save_anim(fig, frame, N, 12, "anim-09-altimeter", hold=2.5)
