"""Lecture 8, a probe rising through the standard atmosphere from the ground to 86 km, drawing the temperature, the
pressure and the density as it climbs, with its current readings. All values from the engine's flight.atmosphere
(USSA 1976). Writes img/anim-08-sonde.gif."""
import numpy as np
from _visual import plt, save_anim, MAROON, BLUE, GREEN, INK, GREY
from flight import atmosphere as A

Z = np.linspace(0.0, 86e3, 431)
S = np.array([A.ISA.state(z)[:3] for z in Z])        # T, p, rho

if __name__ == "__main__":
    fig, axs = plt.subplots(1, 3, figsize=(12, 5.6), sharey=True)
    fig.subplots_adjust(bottom=0.16, top=0.88, wspace=0.12)

    def sci(x):
        e = int(np.floor(np.log10(x)))
        return f"{x:.3g}" if -1 <= e <= 4 else f"{x / 10**e:.2f}$\\times10^{{{e}}}$"
    N = 90
    idx = np.unique(np.round(np.linspace(1, len(Z) - 1, N)).astype(int))

    def frame(k):
        j = idx[k]
        for ax in axs:
            ax.clear()
        cols = (MAROON, BLUE, GREEN)
        for ax, col, c, lab in zip(axs, range(3), cols, ("temperature (K)", "pressure (Pa)", "density (kg/m$^3$)")):
            ax.plot(S[:j + 1, col], Z[:j + 1] / 1e3, color=c, lw=2.6)
            ax.plot(S[j, col], Z[j] / 1e3, "o", color=INK, ms=8)
            ax.set_xlabel(lab)
            for sp in ("top", "right"):
                ax.spines[sp].set_visible(False)
        axs[1].set_xscale("log")
        axs[2].set_xscale("log")
        axs[0].set_xlim(170, 300)
        axs[1].set_xlim(0.2, 2e5)
        axs[2].set_xlim(3e-6, 2.0)
        axs[0].set_ylabel("altitude (km)")
        axs[0].set_ylim(0, 88)
        T, p, rho = S[j]
        axs[0].set_title(f"{Z[j] / 1e3:4.1f} km:  {T:.0f} K", fontsize=12, loc="left")
        axs[1].set_title(f"{sci(p)} Pa", fontsize=12, loc="left")
        axs[2].set_title(f"{sci(rho)} kg/m$^3$", fontsize=12, loc="left")
        return []

    save_anim(fig, frame, len(idx), 12, "anim-08-sonde", hold=2.5)
