"""Lecture 9, how much lighter moist air is than dry air at sea-level pressure, against the temperature, for four
relative humidities, from flight.atmosphere.moist_density and saturation_vapour_pressure (Magnus).
Writes img/fig-09-humidity.png."""
import numpy as np
from _visual import plt, save, despine, MAROON, BLUE, GREEN, AMBER, INK
from flight import atmosphere as A
from flight.constants import P0_SL, R_AIR

TC = np.linspace(0.0, 45.0, 91)
RHS = [(0.25, GREEN), (0.5, BLUE), (0.75, AMBER), (1.0, MAROON)]
EXAMPLE = (35.0, 0.70)       # Mumbai, the worked example


def drop(t_c, rh):
    T = t_c + 273.15
    return 100 * (1 - A.moist_density(P0_SL, T, rh * A.saturation_vapour_pressure(T)) / (P0_SL / (R_AIR * T)))


if __name__ == "__main__":
    fig, ax = plt.subplots(figsize=(10, 5.4))
    for rh, c in RHS:
        ax.plot(TC, drop(TC, rh), color=c, lw=2.3, label=f"relative humidity {rh * 100:.0f} %")
    t, rh = EXAMPLE
    ax.plot(t, drop(t, rh), "o", color=INK, ms=7)
    ax.annotate(f"{t:.0f} °C, {rh * 100:.0f} %: {drop(t, rh):.2f} %", (t, drop(t, rh)), xytext=(37, 0.25),
                textcoords="data", ha="center", fontsize=11, arrowprops=dict(arrowstyle="-", color=INK, lw=0.8))
    ax.set_xlabel("temperature (°C)")
    ax.set_ylabel("density lower than dry air (%)")
    ax.legend(frameon=False, fontsize=11, loc="upper left")
    despine(ax)
    save(fig, "fig-09-humidity")
