"""Assignment 04, Problem 1: the radial impulses of an N-step apse rotation drawn as the vectors Delta e_j by
which they change the eccentricity vector (head to tail, all adding up to the chord), and the total cost
against N for the numbers of the problem.

Run from courses/sfm/assignments/:   python3 codes/fig-a04-apse-steps.py
It borrows the figure font and the colours of the notes from ../sfm-slides.
"""
import os
import sys
import numpy as np

HERE = os.path.dirname(os.path.abspath(__file__))
SLIDES = os.path.normpath(os.path.join(HERE, "..", "..", "sfm-slides"))
sys.path.insert(0, os.path.join(SLIDES, "codes"))
import matplotlib
matplotlib.rc_file(os.path.join(SLIDES, "matplotlibrc"))   # Pagella with old-style figures
import _figfont                                             # all figure text at one scale
import matplotlib.pyplot as plt
from _manstyle import INK, MAROON, BLUE, GREEN, AMBER, PURPLE, despine

MU, RE = 398600.4418, 6378.137
rp, ra = RE + 500.0, RE + 20000.0
a = (rp + ra)/2
e = (ra - rp)/(ra + rp)
p = a*(1 - e**2)
SQ = np.sqrt(MU/p)
ETA = np.radians(30.0)

fig, (ax, bx) = plt.subplots(2, 1, figsize=(8.2, 11.4), gridspec_kw=dict(height_ratios=[1.15, 1.0]))

# ---- (a) the impulses as vectors Delta e_j, head to tail; the angle is exaggerated -------------------
# Between burns e does not change; at burn j it jumps by Delta e_j. Every intermediate orbit has the same
# e, so every intermediate e ends on the circle of radius e. The Delta e_j always add up to the chord;
# what grows with N is the sum of their lengths, which is the cost divided by sqrt(mu/p).
eta = np.radians(120.0)
E = 1.0                                        # drawing length of e
GREY = "#9a948a"


def tip(th):
    return np.array([E*np.cos(th), E*np.sin(th)])


def arrow(p0, p1, col, lw, head=True):
    ax.annotate("", xy=tuple(p1), xytext=tuple(p0),
                arrowprops=dict(arrowstyle="-|>" if head else "-", color=col, lw=lw, shrinkA=0, shrinkB=0,
                                mutation_scale=14))


th = np.linspace(-0.3, eta + 0.3, 300)
ax.plot(*tip(th), color=GREY, lw=1.0, ls=":", label=r"circle of radius $e$: where every intermediate $\mathbf{e}$ ends")

# N = 10: thin polygon
k = np.linspace(0, eta, 11)
ax.plot(*tip(k), color=MAROON, lw=1.2, marker="o", ms=3.5, label=r"$N=10$: ten $\Delta\mathbf{e}_j$")

# N = 3: the intermediate e vectors (thin) and the three steps (arrows), head to tail
k3 = np.linspace(0, eta, 4)
for kk in k3[1:-1]:
    arrow((0, 0), tip(kk), PURPLE, 0.8)
for j in range(3):
    arrow(tip(k3[j]), tip(k3[j + 1]), PURPLE, 1.9)
    m = 0.5*(tip(k3[j]) + tip(k3[j + 1]))
    um = m/np.linalg.norm(m)
    ax.text(*(m - 0.14*um), r"$\Delta\mathbf{e}_%d$" % (j + 1), color=PURPLE, fontsize=11,
            ha="center", va="center")
ax.plot([], [], color=PURPLE, lw=1.9, label=r"$N=3$: three $\Delta\mathbf{e}_j$")

# N = 1: one step, the chord
arrow(tip(0), tip(eta), AMBER, 2.6)
ax.plot([], [], color=AMBER, lw=2.6, label=r"$N=1$: one $\Delta\mathbf{e}$, the chord $2e\sin(\eta/2)$")

# the old and the new eccentricity vector
for ang, col, lab, off in ((0.0, BLUE, r"$\mathbf{e}$ before", (0.04, -0.09)),
                           (eta, GREEN, r"$\mathbf{e}$ after", (-0.30, 0.06))):
    arrow((0, 0), tip(ang), col, 2.2)
    x, y = tip(ang)
    ax.text(x + off[0], y + off[1], lab, color=col, fontsize=11.5)
arc = np.linspace(0, eta, 60)
ax.plot(0.22*np.cos(arc), 0.22*np.sin(arc), color=INK, lw=1.0)
ax.text(0.31*np.cos(0.3*eta), 0.31*np.sin(0.3*eta), r"$\eta$", fontsize=13, ha="center", va="center")
ax.plot(0, 0, "o", color=INK, ms=6)
ax.text(0.03, -0.06, "focus", fontsize=10, va="top")

# step 2 of the N = 3 plan: Delta e is perpendicular to r_hat, so the burn point lies on the bisector
j0, j1 = eta/3, 2*eta/3
mid = 0.5*(tip(j0) + tip(j1))
u = mid/np.linalg.norm(mid)
ax.plot([0, 1.12*u[0]], [0, 1.12*u[1]], color=PURPLE, lw=0.9, ls="--")
ax.text(1.12*u[0] + 0.04, 1.12*u[1] - 0.02, "direction of the burn\npoint of step 2, " + r"$\hat{\mathbf{r}}$",
        color=PURPLE, fontsize=10, ha="left", va="bottom")
s = 0.05
t = np.array([-u[1], u[0]])
corner = [mid + s*t, mid + s*t - s*u, mid - s*u]
ax.plot([c[0] for c in corner], [c[1] for c in corner], color=PURPLE, lw=0.9)

ax.set_title(r"(a) the impulses as steps $\Delta\mathbf{e}_j$, head to tail ($\eta$ drawn as $120^\circ$)",
             fontsize=12, loc="left")
ax.legend(loc="lower left", fontsize=10, frameon=False, bbox_to_anchor=(-0.04, -0.04))
ax.set_xlim(-1.05, 1.45); ax.set_ylim(-0.86, 1.30)
ax.set_aspect("equal"); ax.axis("off")

# ---- (b) the cost for the numbers of the problem -------------------------------------------------
Ns = np.arange(1, 21)
cost = 2*Ns*SQ*e*np.sin(ETA/(2*Ns))
lim = SQ*e*ETA
bx.axhline(lim, color=INK, lw=1.2, ls="--")
bx.text(20.3, lim + 0.0006, r"$N\to\infty$: $\sqrt{\mu/p}\,e\,\eta=%.3f$ km/s" % lim, ha="right", va="bottom",
        fontsize=10.5)
bx.plot(Ns, cost, color=MAROON, lw=1.2, marker="o", ms=5)
for N, col in ((1, AMBER), (3, PURPLE), (10, MAROON)):
    c = 2*N*SQ*e*np.sin(ETA/(2*N))
    bx.plot(N, c, "o", color=col, ms=9, zorder=5)
    bx.annotate(r"$N=%d$: %.3f km/s" % (N, c), xy=(N, c), xytext=(N + 0.9, c - 0.0045),
                fontsize=10.5, color=col, arrowprops=dict(arrowstyle="-", color=col, lw=0.8))
bx.set_xlabel("number of equal steps $N$")
bx.set_ylabel("total cost (km/s)")
bx.set_xlim(0, 20.5); bx.set_ylim(1.825, 1.862)
bx.set_xticks([1, 2, 3, 5, 10, 15, 20])
bx.set_title(r"(b) Problem 1: $e=%.4f$, $\eta=30^\circ$" % e, fontsize=12, loc="left")
despine(bx)

fig.tight_layout()
out = os.path.join("img", "fig-a04-apse-steps.png")
fig.savefig(out, dpi=160, bbox_inches="tight")
print("wrote", out)
