"""Lecture 5, the rotation and curvature terms against heading at 13.7 deg N, for the two vehicles of the term table:
the airliner (11 km, 250 m/s, level) and the rocket (60 km, 3 km/s, gamma 20 deg). Left column: the n_gamma components
(upward) of Coriolis and curvature. Right column: the n_chi component (to the right of the path) of Coriolis. All from
flight.eom.term_breakdown. Writes img/fig-05-heading-terms.png."""
import numpy as np
from _visual import plt, save, despine, MAROON, BLUE, INK, GREY
from flight import eom
from flight.constants import R_EARTH

LAT = np.radians(13.7)
CHI = np.linspace(0.0, 360.0, 361)
CASES = [("airliner: 250 m/s, level", R_EARTH + 11e3, 250.0, 0.0), ("rocket: 3 km/s, climbing at 20°", R_EARTH + 60e3, 3000.0, 20.0)]


def terms(r, V, gam_deg, chi_deg):
    d = eom.term_breakdown(r, LAT, 0.0, V, np.radians(gam_deg), np.radians(chi_deg))
    return d["coriolis"][1], d["curvature"][1], d["coriolis"][2]


DATA = [np.array([terms(r, V, g, c) for c in CHI]) for _, r, V, g in CASES]

if __name__ == "__main__":
    fig, axs = plt.subplots(2, 2, figsize=(10.5, 6.6), sharex=True)
    fig.subplots_adjust(hspace=0.22, wspace=0.28)
    limits = [(-0.095, 0.05), (-0.6, 1.6)]
    for i, ((name, *_), d) in enumerate(zip(CASES, DATA)):
        up, side = axs[i]
        up.plot(CHI, d[:, 0], color=MAROON, lw=2.6, label="Coriolis")
        up.plot(CHI, d[:, 1], color=BLUE, lw=2.2, ls="--", label="curvature $V^2\\cos\\gamma/r$")
        side.plot(CHI, d[:, 2], color=MAROON, lw=2.6)
        for ax in (up, side):
            ax.axhline(0, color=GREY, lw=1)
            ax.set_ylim(*limits[i]); despine(ax)
        up.set_title(f"upward, {name}", fontsize=11.5)
        side.set_title("Coriolis to the right of the path", fontsize=11.5)
        up.set_ylabel("m/s²")
    axs[0, 0].legend(frameon=False, fontsize=10, loc="lower left")
    for ax in axs[1]:
        ax.set_xticks([0, 90, 180, 270, 360], ["north\n0°", "east\n90°", "south\n180°", "west\n270°", "north\n360°"])
        ax.set_xlim(0, 360)
    axs[1, 0].set_xlabel("heading $\\chi$"); axs[1, 1].set_xlabel("heading $\\chi$")
    save(fig, "fig-05-heading-terms")
