"""Lecture 30: the speed relative to the turning Earth that a circular orbit at 867 km needs (heading horizontal at the
surface latitude, spherical Earth, the vector sum alone), against the orbit's inclination, for four launch sites
(latitudes as in Lecture 3). Eastward-going (northbound or southbound) solutions. Writes img/fig-30-required.png."""
import numpy as np
from _visual import plt, save, despine, MAROON, BLUE, GREEN, AMBER, GREY
from flight import rocket as R
from flight.constants import MU, R_EARTH

H = 867e3
VC = np.sqrt(MU / (R_EARTH + H))
SITES = [("Kourou", 5.2, GREEN), ("Sriharikota", 13.72, MAROON), ("Cape Canaveral", 28.5, BLUE), ("Baikonur", 45.9, AMBER)]


def needed(inc_deg, lat_deg):
    """(relative speed, relative heading in deg, inertial heading in deg) for a southbound or polar-going launch."""
    lat = np.radians(lat_deg)
    chi = R.azimuth_for_inclination(np.radians(inc_deg), lat, southbound=True)
    V, _, c = R.relative_from_inertial(VC, 0.0, chi, R_EARTH, lat)
    return V, np.degrees(c) % 360.0, np.degrees(chi)


CURVES = []
for name, lat, col in SITES:
    inc = np.linspace(lat, 110.0, 300)
    CURVES.append(dict(name=name, lat=lat, c=col, inc=inc, V=np.array([needed(i, lat)[0] for i in inc])))

if __name__ == "__main__":
    fig, ax = plt.subplots(figsize=(10, 4.8))
    for cv, w in zip(CURVES, (8.0, 5.5, 3.2, 1.4)):               # nested widths: the curves nearly coincide
        ax.plot(cv["inc"], cv["V"] / 1e3, color=cv["c"], lw=w, label=f"{cv['name']} ({cv['lat']:.1f}° N)")
        ax.plot(cv["inc"][0], cv["V"][0] / 1e3, "o", color=cv["c"], ms=w + 4)
    ax.axhline(VC / 1e3, color=GREY, ls="--", lw=1.2)
    ax.text(2, VC / 1e3 + 0.012, f"orbital speed {VC / 1e3:.2f} km/s (Earth not turning)", fontsize=11, color=GREY)
    ax.set_xlabel("inclination of the orbit (°)"); ax.set_ylabel("ground-relative speed (km/s)")
    ax.set_xlim(0, 110); ax.set_ylim(6.9, 7.6)
    ax.legend(frameon=False, fontsize=11, loc="lower right")
    despine(ax)
    save(fig, "fig-30-required")
