"""Lecture 3: on the WGS-84 ellipsoid, geodetic minus geocentric latitude (left) and the height of the surface below
the equatorial radius (right), the error in altitude if the Earth is taken as a sphere of that radius.
Writes img/fig-03-latitude-gap.png."""
import numpy as np
from _visual import plt, save, despine, MAROON, BLUE, INK
from flight import frames
from flight.constants import A_EARTH

LAT = np.linspace(0, 90, 361)
PLACES = [(5.2, "Kourou"), (13.7, "Sriharikota"), (34.15, "Leh")]


def gap_deg(lat):
    return lat - np.degrees(frames.geocentric_from_geodetic_surface(np.radians(lat)))


def radius_deficit_km(lat):
    return (A_EARTH - np.linalg.norm(frames.ecef_from_geodetic(np.radians(lat), 0.0, 0.0))) / 1e3


if __name__ == "__main__":
    fig, (a, b) = plt.subplots(1, 2, figsize=(10.5, 4.6), gridspec_kw=dict(wspace=0.28))
    for ax, f, c, fmt, lab in ((a, gap_deg, MAROON, "{:.2f}°", "geodetic minus geocentric\nlatitude (deg)"),
                               (b, radius_deficit_km, BLUE, "{:.1f} km", "surface below the\nequatorial radius (km)")):
        ax.plot(LAT, [f(x) for x in LAT], color=c, lw=2.8)
        for x, name in PLACES:
            ax.plot(x, f(x), "o", color=INK, ms=6)
            ax.annotate(f"{name}: {fmt.format(f(x))}", (x, f(x)), xytext={"Kourou": (14, -13), "Sriharikota": (10, -9), "Leh": (9, -6)}[name], textcoords="offset points", fontsize=11)
        ax.set_xlim(0, 90); ax.set_ylim(0 if ax is a else -2.0, None); ax.set_xlabel("geodetic latitude (deg)"); ax.set_ylabel(lab, fontsize=12); despine(ax)
    save(fig, "fig-03-latitude-gap")
