"""Lecture 8, the pressure and density ratios of the standard atmosphere against altitude, on a logarithmic scale,
with the heights below which half, nine tenths and ninety-nine hundredths of the air's mass lie (p/p0 = 1/2, 1/10,
1/100: the pressure at a height is the weight of the air above it). From the engine's flight.atmosphere.
Writes img/fig-08-pressure-density.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 P0_SL

Z = np.linspace(0.0, 86e3, 861)
DELTA = np.array([A.ISA.ratios(z)[1] for z in Z])
SIGMA = np.array([A.ISA.ratios(z)[2] for z in Z])
FRACTIONS = [(0.5, "half"), (0.1, "90 %"), (0.01, "99 %")]
LEVELS = [(f, lab, A.geometric(A.pressure_altitude(f * P0_SL))) for f, lab in FRACTIONS]

if __name__ == "__main__":
    fig, ax = plt.subplots(figsize=(10, 6.0))
    ax.semilogx(DELTA, Z / 1e3, color=MAROON, lw=2.4, label="pressure ratio $\\delta=p/p_0$")
    ax.semilogx(SIGMA, Z / 1e3, color=BLUE, lw=2.4, ls="--", label="density ratio $\\sigma=\\rho/\\rho_0$")
    for f, lab, z in LEVELS:
        ax.plot(f, z / 1e3, "o", color=INK, ms=6)
        ax.annotate(f"{lab} of the air lies below {z / 1e3:.1f} km", (f, z / 1e3), xytext=(-12, -2),
                    textcoords="offset points", fontsize=11, ha="right", va="center")
    ax.set_xlim(1e-6, 1.5)
    ax.set_ylim(0, 88)
    ax.set_xlabel("ratio to the sea-level value")
    ax.set_ylabel("geometric altitude $z$ (km)")
    ax.legend(frameon=False, fontsize=11, loc="upper right")
    despine(ax)
    save(fig, "fig-08-pressure-density")
