"""Lecture 6: specific energy V^2/2 - mu/r and specific angular momentum |r x V| along one free flight with no air (start
at 100 km, 5 km/s, 45 deg above the horizontal, heading north-east, at 13.7 deg N), on the course simulator with: point
gravity and no rotation; J2 gravity and no rotation; point gravity on the turning Earth, with V measured relative to
the Earth. Changes relative to the start. Writes img/fig-06-invariants.png."""
import numpy as np
from _visual import plt, save, despine, MAROON, BLUE, INK, GREY
from flight import vehicle, guidance, simulate, eom, atmosphere
from flight.constants import MU

VAC = atmosphere.ExponentialAtmosphere(1e-30, 8000.0)
CAP = vehicle.load("capsule-ballistic")
INIT = dict(lat_deg=13.7, lon_deg=80.0, h=100e3, V=5000.0, gamma_deg=45.0, chi_deg=45.0)
CASES = [("point gravity, Earth not turning", dict(gravity="point", coriolis=False, centrifugal=False), INK, "-"),
         ("with $J_2$, Earth not turning", dict(gravity="J2", coriolis=False, centrifugal=False), BLUE, "--"),
         ("turning Earth, speed relative to the ground", dict(gravity="point", coriolis=True, centrifugal=True), MAROON, "-")]
RUNS = []
for lab, kw, c, ls in CASES:
    tr = simulate.simulate(CAP, INIT, guidance.Constant(0.0, 0.0, 0.0), eom.Options(earth="sphere", atmosphere=VAC, **kw), t_end=600.0, max_step=2.0)
    r = np.linalg.norm(tr.r, axis=1)
    v = np.asarray(tr.v_ecef) if hasattr(tr, "v_ecef") else np.asarray(tr.v)
    E = 0.5 * np.sum(v**2, axis=1) - MU / r
    h = np.linalg.norm(np.cross(tr.r, v), axis=1)
    RUNS.append(dict(label=lab, c=c, ls=ls, t=tr.t, dE=E / abs(E[0]) - E[0] / abs(E[0]), dh=h / h[0] - 1))

if __name__ == "__main__":
    fig, (a, b) = plt.subplots(2, 1, figsize=(10, 6.0), sharex=True, gridspec_kw=dict(hspace=0.12))
    for r in RUNS:
        a.plot(r["t"], 100 * r["dE"], color=r["c"], ls=r["ls"], lw=2.6, label=r["label"])
        b.plot(r["t"], 100 * r["dh"], color=r["c"], ls=r["ls"], lw=2.6)
    a.set_ylabel("change of energy (%)"); b.set_ylabel("change of angular\nmomentum (%)"); b.set_xlabel("time (s)"); b.set_xlim(0, 600)
    fig.legend(*a.get_legend_handles_labels(), frameon=False, fontsize=11.5, loc="upper center", ncol=2, bbox_to_anchor=(0.5, 0.01))
    despine(a); despine(b)
    save(fig, "fig-06-invariants")
