"""Lecture 8, gravity and the geopotential altitude: g/g0 against the geometric altitude z (left), and the gap z - h
between the geometric and the geopotential altitude (right), from the engine's flight.atmosphere.gravity_ratio and
geopotential (h = r0 z/(r0 + z), r0 = 6356.766 km). Writes img/fig-08-geopotential.png."""
import numpy as np
from _visual import plt, save, despine, MAROON, BLUE, INK, GREY
from flight import atmosphere as A

Z = np.linspace(0.0, 100e3, 501)
MARKS = (11e3, 86e3)                           # the tropopause and the top of the 1976 layers

if __name__ == "__main__":
    fig, (a1, a2) = plt.subplots(1, 2, figsize=(11, 4.8))
    a1.plot(A.gravity_ratio(Z), Z / 1e3, color=BLUE, lw=2.4)
    a1.set_xlabel("$g/g_0$")
    a1.set_ylabel("geometric altitude $z$ (km)")
    a2.plot((Z - A.geopotential(Z)) / 1e3, Z / 1e3, color=MAROON, lw=2.4)
    a2.set_xlabel("$z-h$ (km)")
    for z in MARKS:
        d = z - A.geopotential(z)
        a2.plot(d / 1e3, z / 1e3, "o", color=INK, ms=6)
        a2.annotate(f"$z$ = {z / 1e3:.0f} km: $z-h$ = {d:.0f} m", (d / 1e3, z / 1e3), xytext=(12, -4),
                    textcoords="offset points", fontsize=11)
        a1.plot(A.gravity_ratio(z), z / 1e3, "o", color=INK, ms=6)
        a1.annotate(f"{A.gravity_ratio(z):.3f}", (A.gravity_ratio(z), z / 1e3), xytext=(10, -4),
                    textcoords="offset points", fontsize=11)
    a2.set_xlim(0, 2.2)
    for a in (a1, a2):
        a.set_ylim(0, 100)
        despine(a)
    fig.tight_layout(w_pad=3)
    save(fig, "fig-08-geopotential")
