"""Lecture 9: density ratio sigma (solid) and density altitude (dashed) over pressure altitude and the deviation of the
temperature from ISA (flight.atmosphere.at_pressure_altitude, density_altitude). Marked days: Mumbai at 35 C and Leh
at 25 C and -15 C, each with its airfield elevation taken as the pressure altitude. Writes img/fig-09-sigma-map.png."""
import numpy as np
from _visual import plt, save, despine, MAROON, BLUE, INK, GREY
from flight import atmosphere as A
from flight.constants import RHO0_SL

HP = np.linspace(0, 5000, 101)
DT = np.linspace(-30, 35, 66)


def sigma(hp, dT):
    return A.at_pressure_altitude(hp, dT)[2] / RHO0_SL


def day(hp, oat_c):
    """(dT, sigma, density altitude) for pressure altitude hp and outside air temperature in deg C."""
    dT = oat_c + 273.15 - A.ISA.standard_tp(hp)[0]
    rho = A.at_pressure_altitude(hp, dT)[2]
    return dT, rho / RHO0_SL, float(A.density_altitude(rho))


MARKS = [(12.0, 35.0, "Mumbai, 35 °C"), (3254.0, 25.0, "Leh, 25 °C"), (3254.0, -15.0, "Leh, −15 °C")]

if __name__ == "__main__":
    X, Y = np.meshgrid(DT, HP)
    S = np.array([[sigma(h, d) for d in DT] for h in HP])
    DA = np.array([[float(A.density_altitude(sigma(h, d) * RHO0_SL)) for d in DT] for h in HP])
    fig, ax = plt.subplots(figsize=(10, 5.6))
    cs = ax.contour(X, Y / 1000, S, levels=np.arange(0.55, 1.1, 0.05), colors=[MAROON], linewidths=1.8)
    ax.clabel(cs, fmt=lambda v: f"σ = {v:.2f}", fontsize=10.5)
    cd = ax.contour(X, Y / 1000, DA, levels=[0, 1000, 2000, 3000, 4000, 5000], colors=[BLUE], linewidths=1.2, linestyles="--")
    ax.clabel(cd, fmt=lambda v: f"{v / 1000:.0f} km", fontsize=10.5, manual=[(-24, 0.8), (-24, 1.75), (-24, 2.7), (-24, 3.65), (-24, 4.55)])
    for hp, t, lab in MARKS:
        dT, s, da = day(hp, t)
        ax.plot(dT, hp / 1000, "o", color=INK, ms=9, zorder=5)
        ax.annotate(f"{lab}\nσ = {s:.3f}", (dT, hp / 1000), xytext=(-112, 8) if dT > 25 else ((8, 26) if hp < 100 else (8, 7)), textcoords="offset points", fontsize=11.5,
                    bbox=dict(boxstyle="round", fc="#fbfaf6", ec=GREY, lw=0.6))
    ax.set_xlabel("temperature above the standard value for that pressure altitude (K)"); ax.set_ylabel("pressure altitude (km)")
    ax.set_xlim(-30, 35); ax.set_ylim(0, 5)
    save(fig, "fig-09-sigma-map")
