"""Lecture 29, the reference PSLV mission (flight.missions.pslv_c18_like) counted in energy instead of speed: against
time, the gain since lift-off in kinetic energy v_I^2/2, in potential energy -mu/r and in their sum, the orbital
energy per unit mass. Shaded: the coast between the third and fourth stages. Writes img/fig-29-energy-budget.png."""
import numpy as np
from _visual import plt, save, despine, MAROON, BLUE, INK, GREY
from flight import missions
from flight.constants import MU

TR = missions.fly(missions.pslv_c18_like())
_, U = np.unique(TR.t, return_index=True)
T = TR.t[U]
VI = TR.V_inertial[U]
R = np.linalg.norm(TR.r[U], axis=1)
KE = (VI**2 - VI[0]**2) / 2 / 1e6                           # gains since lift-off, MJ/kg
PE = (-MU / R + MU / R[0]) / 1e6
TOTAL = KE + PE
E_ABS = (VI**2 / 2 - MU / R) / 1e6
T_COAST0 = [t for t, n in TR.events if n.startswith("separation:PS3")][0]
T_COAST1 = [t for t, n in TR.events if n.startswith("ignition:PS4")][0]


def at(arr, t):
    return float(np.interp(t, T, arr))


if __name__ == "__main__":
    fig, ax = plt.subplots(figsize=(10, 5.4))
    ax.axvspan(T_COAST0, T_COAST1, color=GREY, alpha=0.18)
    ax.text((T_COAST0 + T_COAST1) / 2, 37.2, "coast: no engine", ha="center", fontsize=12, color=GREY)
    ax.plot(T, KE, color=MAROON, lw=2.6, label="kinetic, $\\Delta(v_I^2/2)$")
    ax.plot(T, PE, color=BLUE, lw=2.6, label="potential, $\\Delta(-\\mu/r)$")
    ax.plot(T, TOTAL, color=INK, lw=3, label="their sum, orbital energy gained")
    ax.set_xlim(0, T[-1]); ax.set_ylim(0, 40)
    ax.set_xlabel("time after lift-off (s)"); ax.set_ylabel("gain since lift-off (MJ/kg)")
    ax.legend(frameon=False, fontsize=12, loc="upper left")
    despine(ax)
    save(fig, "fig-29-energy-budget")
