"""Lecture 4, effective gravity on the WGS-84 ellipsoid at sea level against latitude. Left: the size of the pull of a
point mass at the Earth's centre, with the J2 term added (gravitation), and with the centrifugal term added as well
(effective gravity, flight.gravity.effective); g0 is drawn for reference. Right: the angle between effective gravity
and the line to the Earth's centre. Writes img/fig-04-effective-gravity.png."""
import numpy as np
from _visual import plt, save, despine, MAROON, BLUE, GREEN, INK, GREY
from flight import frames, gravity
from flight.constants import G0

LATS = np.linspace(0.0, 90.0, 181)
PLACES = [(13.7, "Sriharikota"), (28.6, "Delhi"), (34.15, "Leh")]


def parts(lat_deg):
    """Sizes of (point-mass pull, J2 gravitation, effective gravity) and the tilt (arc-minutes) at geodetic latitude."""
    r = frames.ecef_from_geodetic(np.radians(lat_deg), 0.0, 0.0)
    pm, grav, eff = gravity.point_mass(r), gravity.acceleration(r, "J2"), gravity.effective(r, "J2")
    rhat = r / np.linalg.norm(r)
    tilt = np.degrees(np.arccos(np.clip(np.dot(-eff, rhat) / np.linalg.norm(eff), -1, 1))) * 60
    return np.linalg.norm(pm), np.linalg.norm(grav), np.linalg.norm(eff), tilt


VALUES = np.array([parts(l) for l in LATS])
EQ, POLE = parts(0.0), parts(90.0)

if __name__ == "__main__":
    fig, (a, b) = plt.subplots(1, 2, figsize=(10.5, 4.9), gridspec_kw=dict(width_ratios=[1.3, 1]))
    fig.subplots_adjust(wspace=0.32)
    a.plot(LATS, VALUES[:, 0], color=GREY, lw=2, ls="--", label="point mass at the centre")
    a.plot(LATS, VALUES[:, 1], color=BLUE, lw=2.4, label="gravitation with $J_2$")
    a.plot(LATS, VALUES[:, 2], color=MAROON, lw=2.8, label="effective gravity")
    a.axhline(G0, color=GREEN, lw=1.4, ls=":")
    a.text(89, G0 - 0.0028, "$g_0$, a defined number", color=GREEN, fontsize=10.5, ha="right", va="top")
    a.set_xlim(0, 90); a.set_ylim(9.77, 9.905); a.set_xlabel("latitude (deg)"); a.set_ylabel("at sea level (m/s²)")
    a.legend(frameon=False, fontsize=10.5, loc="upper left")
    b.plot(LATS, VALUES[:, 3], color=MAROON, lw=2.8)
    for lat, name in PLACES:
        v = parts(lat)
        a.plot(lat, v[2], "o", color=MAROON, ms=6)
        b.plot(lat, v[3], "o", color=INK, ms=6)
        b.annotate(name, xy=(lat, v[3]), xytext=(lat + 4, v[3] - 0.55), fontsize=10.5)
    b.set_xlim(0, 90); b.set_ylim(0, 13); b.set_xlabel("latitude (deg)")
    b.set_ylabel("angle from the line\nto the centre (arc-minutes)")
    despine(a); despine(b)
    save(fig, "fig-04-effective-gravity")
