"""Figure for gauss-variational-equations.qmd (img/fig-gve-frames.png).

Left: the RSW and TNW frames at one point of an ellipse (W out of the page), with the flight-path angle gamma
between S and T.  Centre and right: what an impulse at periapsis does, drawn to scale: along S (= T there) it
changes a and e but not the apse line; along R it keeps a, e and p and turns the apse line backwards, leaving the
body just past its new periapsis.

Run from the sfm-slides directory:   python3 codes/fig-gve-frames.py
"""
import numpy as np
import _figfont                                # all figure text at one scale
import matplotlib.pyplot as plt
from _manstyle import INK, MAROON, BLUE, GREEN, AMBER, PURPLE

MU = 1.0


def conic(p, e, w, n=600):
    f = np.linspace(-np.pi, np.pi, n) if e < 1 else np.linspace(-np.arccos(-1 / e) + 0.05, np.arccos(-1 / e) - 0.05, n)
    r = p / (1 + e * np.cos(f))
    return r * np.cos(f + w), r * np.sin(f + w)


def elements(r, v):
    h = r[0] * v[1] - r[1] * v[0]
    rn = np.hypot(*r)
    ev = np.array([v[1] * h, -v[0] * h]) / MU - r / rn
    return h * h / MU, np.hypot(*ev), np.arctan2(ev[1], ev[0])


def arrow(ax, p, d, c, lab, off, fs=13, lw=2.0):
    ax.annotate("", xy=p + d, xytext=p, arrowprops=dict(arrowstyle="-|>", color=c, lw=lw, shrinkA=0, shrinkB=0))
    ax.text(*(p + d + off), lab, color=c, fontsize=fs, ha="center", va="center")


fig, axs = plt.subplots(1, 3, figsize=(15.5, 5.2), gridspec_kw=dict(width_ratios=[1.25, 1, 1]))

# ---- left: the frames at f = 70 deg on an e = 0.5 ellipse
p, e = 1.0, 0.5
ax = axs[0]
x, y = conic(p, e, 0.0)
ax.plot(x, y, color=INK, lw=1.3)
ax.plot(0, 0, "o", color=AMBER, ms=11, mec=MAROON)
f = np.radians(70)
r = p / (1 + e * np.cos(f))
P = r * np.array([np.cos(f), np.sin(f)])
R = np.array([np.cos(f), np.sin(f)]); S = np.array([-np.sin(f), np.cos(f)])
vR, vS = e * np.sin(f), 1 + e * np.cos(f)
T = (vR * R + vS * S) / np.hypot(vR, vS); N = np.array([-T[1], T[0]])
g = np.arctan2(vR, vS)
ax.plot([0, P[0]], [0, P[1]], color=INK, lw=0.7, ls=":")
L = 0.55
arrow(ax, P, L * R, BLUE, r"$\hat{\mathbf{R}}$", 0.08 * R)
arrow(ax, P, L * S, BLUE, r"$\hat{\mathbf{S}}$", 0.1 * S + np.array([-0.02, 0.03]))
arrow(ax, P, L * T, MAROON, r"$\hat{\mathbf{T}}$", 0.1 * T + np.array([0.06, 0.0]))
arrow(ax, P, L * N, MAROON, r"$\hat{\mathbf{N}}$", 0.1 * N + np.array([0.0, -0.03]))
ax.plot(*P, "o", color=INK, ms=6)
ax.scatter(*(P + np.array([0.13, -0.16])), s=140, facecolors="none", edgecolors=GREEN, lw=1.5)
ax.plot(*(P + np.array([0.13, -0.16])), "o", color=GREEN, ms=3)
ax.text(*(P + np.array([0.24, -0.16])), r"$\hat{\mathbf{W}}$ (out of the page)", color=GREEN, fontsize=11, va="center")
aa = np.linspace(np.arctan2(T[1], T[0]), np.arctan2(S[1], S[0]), 30)
ax.plot(P[0] + 0.3 * np.cos(aa), P[1] + 0.3 * np.sin(aa), color=PURPLE, lw=1.5)
am = aa[len(aa) // 2]
ax.text(P[0] + 0.39 * np.cos(am), P[1] + 0.39 * np.sin(am), r"$\gamma$", color=PURPLE, fontsize=13, ha="center", va="center")
ax.text(0.02, -0.12, "focus", fontsize=10, color=MAROON)
ax.set_title("RSW and TNW at one point of an ellipse", fontsize=12)
ax.set_aspect("equal"); ax.axis("off")
ax.set_xlim(-2.2, 1.0); ax.set_ylim(-1.35, 1.75)

# ---- centre and right: impulses at periapsis
p, e = 1.0, 0.3
rp = p / (1 + e)
r0 = np.array([rp, 0.0]); vp = np.sqrt(MU / p) * (1 + e); v0 = np.array([0.0, vp])
for ax, dv, ttl, lab in ((axs[1], np.array([0.0, 0.10 * vp]), "Along-track burn at periapsis",
                          "$a$ and $e$ grow, apse line fixed"),
                         (axs[2], np.array([0.15 * vp, 0.0]), "Radial burn at periapsis",
                          "$p$ unchanged, $a$ and $e$ unchanged to first order,\napse line turns back")):
    x, y = conic(p, e, 0.0)
    ax.plot(x, y, color=INK, lw=1.3, label="before")
    p2, e2, w2 = elements(r0, v0 + dv)
    x2, y2 = conic(p2, e2, w2)
    ax.plot(x2, y2, color=GREEN, lw=2.0, label="after")
    ax.plot(0, 0, "o", color=AMBER, ms=11, mec=MAROON)
    ax.plot(*r0, "o", color=INK, ms=6)
    u = dv / np.hypot(*dv)
    ax.annotate("", xy=r0 + 0.5 * u, xytext=r0, arrowprops=dict(arrowstyle="-|>", color=MAROON, lw=2.2))
    ax.text(*(r0 + 0.5 * u + 0.12 * u + np.array([0.05, 0.0])), r"$\Delta\mathbf{v}$", color=MAROON, fontsize=13)
    for w_, ee, c, ls in ((0.0, e, INK, ":"), (w2, e2, GREEN, "--")):  # apse lines, focus to periapsis
        rr = (p2 if c == GREEN else p) / (1 + ee)
        ax.plot([0, rr * np.cos(w_)], [0, rr * np.sin(w_)], color=c, lw=1.0, ls=ls)
    ax.set_title(ttl, fontsize=12)
    ax.text(0.5, -0.02, lab, transform=ax.transAxes, ha="center", va="top", fontsize=11, color=GREEN)
    ax.legend(frameon=False, fontsize=10, loc="upper left")
    ax.set_aspect("equal"); ax.axis("off")
    ax.set_xlim(*((-3.3, 1.3) if "Along" in ttl else (-2.2, 1.4))); ax.set_ylim(-1.9, 1.9)
    # sanity: the radial burn keeps p and a; the along-track one keeps the apse line
    if "Radial" in ttl:
        assert abs(p2 - p) < 1e-12 and w2 < 0
    else:
        assert abs(w2) < 1e-12 and e2 > e

fig.tight_layout()
fig.savefig("img/fig-gve-frames.png", dpi=150, bbox_inches="tight")
print("wrote img/fig-gve-frames.png")
