"""Lecture 9, density altitude against the outside air temperature at Mumbai (pressure altitude 0) and Leh (pressure
altitude 3254 m, the airport elevation of 3256 m as a geopotential altitude), exact (flight.atmosphere.
density_altitude_from) and by the 36 m per kelvin rule (density_altitude_rule). Writes img/fig-09-density-altitude.png."""
import numpy as np
from _visual import plt, save, despine, MAROON, BLUE, INK, GREY
from flight import atmosphere as A

AIRPORTS = [("Mumbai", 0.0, 35.0, BLUE), ("Leh", A.geopotential(3256.0), 25.0, MAROON)]   # name, h_p, example OAT (C)
OAT = np.linspace(-20.0, 45.0, 131)
RULE = A.density_altitude_rule()

if __name__ == "__main__":
    fig, ax = plt.subplots(figsize=(10, 5.8))
    for name, hp, t_ex, c in AIRPORTS:
        hd = [A.density_altitude_from(hp, t + 273.15) for t in OAT]
        t_std = A.isa(hp)[0] - 273.15
        ax.plot(OAT, np.array(hd) / 1e3, color=c, lw=2.4, label=f"{name}, pressure altitude {hp:.0f} m")
        ax.plot(OAT, (hp + RULE * (OAT - t_std)) / 1e3, color=c, lw=1.3, ls="--")
        ax.plot(t_std, hp / 1e3, "s", color=c, ms=7)
        ax.annotate(f"ISA: {t_std:.1f} °C", (t_std, hp / 1e3), xytext=(-12, 10), textcoords="offset points",
                    fontsize=11, ha="right", color=c)
        hx = A.density_altitude_from(hp, t_ex + 273.15)
        ax.plot(t_ex, hx / 1e3, "o", color=INK, ms=7)
        ax.annotate(f"{t_ex:.0f} °C: {hx:.0f} m", (t_ex, hx / 1e3), xytext=(10, -16), textcoords="offset points", fontsize=11)
    ax.set_xlabel("outside air temperature (°C)")
    ax.set_ylabel("density altitude (km)")
    ax.text(44, -1.3, "dashed lines: the 36 m per kelvin rule", fontsize=11, color=GREY, ha="right")
    ax.legend(frameon=False, fontsize=11, loc="upper left")
    despine(ax)
    save(fig, "fig-09-density-altitude")
