"""Lecture 8, the speed of sound and the kinematic viscosity of the standard atmosphere against altitude, with the Mach
number of an aircraft flying at a constant true airspeed of 250 m/s. From the engine's flight.atmosphere
(a = sqrt(gamma R T), Sutherland's law). Writes img/fig-08-sound-viscosity.png."""
import numpy as np
from _visual import plt, save, despine, MAROON, BLUE, GREEN, INK, GREY
from flight import atmosphere as A

Z = np.linspace(0.0, 20e3, 201)
STATES = [A.ISA.state(z) for z in Z]
SOUND = np.array([s[3] for s in STATES])
NU = np.array([s[4] / s[2] for s in STATES])          # kinematic viscosity mu/rho
V_TAS = 250.0

if __name__ == "__main__":
    fig, (a1, a2) = plt.subplots(1, 2, figsize=(11, 4.8))
    a1.plot(SOUND, Z / 1e3, color=BLUE, lw=2.4)
    a1.set_xlabel("speed of sound $a$ (m/s)")
    a1.set_ylabel("geometric altitude $z$ (km)")
    t = a1.twiny()
    t.plot(V_TAS / SOUND, Z / 1e3, color=MAROON, lw=2.0, ls="--")
    t.set_xlabel(f"Mach number at {V_TAS:.0f} m/s", color=MAROON)
    t.tick_params(axis="x", colors=MAROON)
    a2.plot(NU * 1e6, Z / 1e3, color=GREEN, lw=2.4)
    a2.set_xlabel("kinematic viscosity $\\nu=\\mu/\\rho$ (mm$^2$/s)")
    for a in (a1, a2):
        a.set_ylim(0, 20)
        despine(a)
    t.spines["right"].set_visible(False)
    a1.text(SOUND[40] + 2, Z[40] / 1e3, "speed of sound", color=BLUE, fontsize=11)
    t.text(V_TAS / SOUND[150] - 0.004, Z[150] / 1e3, "Mach number", color=MAROON, fontsize=11, ha="right")
    fig.tight_layout(w_pad=3)
    save(fig, "fig-08-sound-viscosity")
