"""Lecture 9, the local density scale height of the standard atmosphere, R T/(g0 + R lambda) (left), and the error of
two exponential atmospheres rho0 exp(-z/H) against the ISA (right): Hull's single scale height of 26,600 ft and the
7.2 km of the course's entry model. From flight.atmosphere. Writes img/fig-09-scale-height.png."""
import numpy as np
from _visual import plt, save, despine, MAROON, BLUE, GREEN, INK, GREY
from flight import atmosphere as A
from flight.constants import FT, RHO0_SL

Z = np.linspace(0.0, 86e3, 861)
H_LOCAL = []
for z in Z:
    h = A.geopotential(z)
    i = A.ISA._index(min(h, A.H_TOP - 1.0))
    H_LOCAL.append(A.local_scale_height(A.ISA.state(z)[0], A.ISA.lam[i]))
H_LOCAL = np.array(H_LOCAL)
RHO = np.array([A.ISA.state(z)[2] for z in Z])
FITS = [(26600 * FT, 20e3, "Hull: $H$ = 8.11 km", GREEN), (7200.0, 86e3, "entry model: $H$ = 7.2 km", MAROON)]

if __name__ == "__main__":
    fig, (a1, a2) = plt.subplots(1, 2, figsize=(11, 5.0), sharey=True)
    a1.plot(H_LOCAL / 1e3, Z / 1e3, color=BLUE, lw=2.4)
    a1.set_xlabel("local density scale height (km)")
    a1.set_ylabel("geometric altitude $z$ (km)")
    a1.set_xlim(5, 11)
    for H, ztop, lab, c in FITS:
        m = Z <= ztop
        a2.plot(100 * (RHO0_SL * np.exp(-Z[m] / H) / RHO[m] - 1), Z[m] / 1e3, color=c, lw=2.2, label=lab)
    a2.axvline(0, color=GREY, lw=0.8)
    a2.set_xlabel("error of the exponential density (%)")
    a2.legend(frameon=False, fontsize=11, loc="center left", bbox_to_anchor=(0.0, 0.47))
    for a in (a1, a2):
        a.set_ylim(0, 88)
        despine(a)
    fig.tight_layout(w_pad=2)
    save(fig, "fig-09-scale-height")
