"""Figures for patched-conics.qmd, Examples 2a and 2b (a designed Hohmann and a bi-elliptic transfer to the Moon).

img/fig-pc-moon-phase.png     : the definition of the Moon's polar angle theta_Moon(t) = phi_0 + n_Moon t (Step 2 of Example 2a), with the textbook timing.
img/fig-pc-hohmann-snapshots.png: the spacecraft and the Moon at the same instants for the textbook timing, and the gap between them (Step 3 of Example 2a).
img/fig-pc-hohmann-moon.png   : (a) the Earth's view: the Hohmann ellipse, the Moon's circle, the Moon at injection, at the entry into its sphere of
                                influence (SOI, to scale) and at perilune; (b) the Moon's view: the selenocentric path from the entry point, with the
                                path of the same transfer with the textbook timing, aimed at the Moon's centre, for comparison, and an enlargement of the perilune.
img/fig-pc-bielliptic-moon.png: the same two panels for the bi-elliptic transfer (apoapsis r_b = 2 r_Moon).
img/fig-pc-bielliptic-cost.png: (a) the classical comparison (circularise in an Earth orbit of radius r_Moon), (b) the same for the capture at the
                                Moon (lower bound), (c) the flight time, all against r_b / r_Moon.

Run from the sfm-slides directory:   python3 codes/fig-pc-transfers.py
"""
import warnings
import numpy as np
import _figfont                                # all figure text at one scale
import matplotlib.pyplot as plt
from matplotlib.patches import Circle, Arc
from matplotlib.lines import Line2D
from scipy.integrate import solve_ivp
from _manstyle import INK, MAROON, BLUE, GREEN, AMBER, PURPLE, despine
from _pc_transfer import *
from _pc_transfer import R0, DAY

warnings.filterwarnings("ignore")
D2R = np.pi / 180
R_B = 2.0 * D
DELTA_H = solve_aim(lambda d: hohmann_run(d), 100.0, -24, 24)[0]            # the root with the Moon early (lambda_1 near 60 degrees)
DELTA_B = solve_aim(lambda d: bielliptic_run(d, R_B), 100.0, -30, 30)[0]     # the root with the entry just behind the Moon


def moon_path(L, t_end_factor=2.4, n=600):
    """Selenocentric path from the entry point: two-body motion about the Moon, from the state at the SOI crossing (Moon-centred frame)."""
    y0 = [L["rho"][0], L["rho"][1], L["v2vec"][0], L["v2vec"][1]]
    f = lambda t, y: [y[2], y[3], -MU_M * y[0] / np.hypot(y[0], y[1]) ** 3, -MU_M * y[1] / np.hypot(y[0], y[1]) ** 3]
    hit = lambda t, y: np.hypot(y[0], y[1]) - RM
    hit.terminal = True; hit.direction = -1
    out = lambda t, y: np.hypot(y[0], y[1]) - 1.02 * R_SOI
    out.terminal = True; out.direction = 1
    sol = solve_ivp(f, [0, t_end_factor * L["t_in"] + 3600], y0, events=[hit, out], rtol=1e-11, atol=1e-8, dense_output=True, max_step=300)
    t = np.linspace(0, sol.t[-1], n)
    return sol.sol(t)[:2]


def encounter_panel(ax, L, L_alt, col, title, zoom_rect):
    """The Moon's view (Moon at the origin, the Earth to the left, the Moon moving up the page)."""
    ax.add_patch(Circle((0, 0), R_SOI, color="#f3efe6", ec=INK, lw=0.9, ls=(0, (5, 3)), zorder=1))
    ax.add_patch(Circle((0, 0), RM * 3.0, color="#b9b3a6", ec=INK, lw=0.6, zorder=3))
    xy = moon_path(L)
    ax.plot(xy[0], xy[1], color=col, lw=2.4, zorder=5)
    if L_alt is not None:
        xa = moon_path(L_alt)
        ax.plot(xa[0], xa[1], color=INK, lw=1.2, ls=(0, (4, 3)), zorder=4)
        ax.text(0.05 * R_SOI, 0.66 * R_SOI, "textbook timing\n(dashed): aimed at\nthe centre, a hit", fontsize=8.5, ha="left", va="top", color=INK)
    P = L["rho"]
    ax.scatter(*P, color=AMBER, s=46, zorder=7)
    ax.annotate("", xy=(0, 0.9 * R_SOI), xytext=(0, 0), arrowprops=dict(arrowstyle="-|>", color=BLUE, lw=1.2), zorder=2)
    ax.annotate("", xy=(-0.9 * R_SOI, 0), xytext=(0, 0), arrowprops=dict(arrowstyle="-|>", color=GREEN, lw=1.2), zorder=2)
    ax.text(-0.97 * R_SOI, -0.1 * R_SOI, "to the Earth", color=GREEN, fontsize=9.5)
    ax.text(0.03 * R_SOI, 0.85 * R_SOI, r"Moon's velocity", color=BLUE, fontsize=9.5)
    # lambda_1 at the Moon: between the direction to the Earth (-x) and the direction to the patch point
    a0 = 180.0
    a1 = np.degrees(np.arctan2(P[1], P[0]))
    th1, th2 = min(a1 % 360, a0), max(a1 % 360, a0)
    ax.add_patch(Arc((0, 0), 0.6 * R_SOI, 0.6 * R_SOI, theta1=th1, theta2=th2, color=PURPLE, lw=1.6, zorder=6))
    am = np.radians(0.5 * (th1 + th2))
    ax.text(0.40 * R_SOI * np.cos(am), 0.40 * R_SOI * np.sin(am), r"$\lambda_1$", color=PURPLE, fontsize=12, ha="center", va="center")
    ax.text(P[0] * 1.08, P[1] * 1.08, "patch point", color=AMBER, fontsize=10, ha="center", va="center")
    ax.set_aspect("equal"); ax.set_xlim(-1.2 * R_SOI, 1.2 * R_SOI); ax.set_ylim(-1.22 * R_SOI, 1.16 * R_SOI); ax.axis("off")
    ax.set_title(title, fontsize=11.5, loc="left")
    # enlargement of the perilune
    zx = ax.inset_axes(zoom_rect)
    zx.add_patch(Circle((0, 0), RM, color="#b9b3a6", ec=INK, lw=0.8))
    zx.plot(xy[0], xy[1], color=col, lw=2.2)
    zx.scatter([L["rp"] * np.cos(0)], [0], s=0)
    k = np.argmin(np.hypot(xy[0], xy[1]))
    zx.scatter([xy[0][k]], [xy[1][k]], color=MAROON, s=36, zorder=6)
    zx.set_aspect("equal"); lim = 4.2 * RM
    zx.set_xlim(-lim, lim); zx.set_ylim(-lim, lim)
    zx.set_xticks([]); zx.set_yticks([])
    for sp in zx.spines.values():
        sp.set_color(INK); sp.set_linewidth(0.8)
    zx.text(0.04, 0.95, f"perilune: $r_p={L['rp']:.0f}$ km\n(altitude {L['rp'] - RM:.0f} km)", transform=zx.transAxes, fontsize=8.5, va="top", color=MAROON)
    return xy


# ------------------------------------------------------------------ the Moon's phase and the snapshots (Steps 2 and 3 of Example 2a)
GREY = "#8a8478"
CREAM_ = "#fcfbf7"
HT, HTE, HTL = hohmann_run(0.0)                                  # the textbook timing: the Moon at A when the spacecraft is there
ellT = HT["ell"]
PHI0_TB = np.pi - N_MOON * ellT.T / 2
Dk = D / 1e3
fig, A = plt.subplots(figsize=(7.6, 6.8))
th = np.linspace(0, 2 * np.pi, 600)
A.plot(Dk * np.cos(th), Dk * np.sin(th), color=GREY, lw=0.9, ls=(0, (5, 3)), zorder=1)
fs_ = np.linspace(0, 2 * np.pi, 1500)
r_e = ellT.p / (1 + ellT.e * np.cos(fs_))
A.plot(r_e * np.cos(fs_) / 1e3, r_e * np.sin(fs_) / 1e3, color=INK, lw=0.9, ls=(0, (1, 2.4)), zorder=2)
A.plot([0, 190], [0, 0], color=INK, lw=1.1, ls=(0, (6, 3)), zorder=2)
A.text(192, -4, "perigee direction\n(the injection point)", fontsize=9.5, va="center")
A.plot([-Dk, 0], [0, 0], color=INK, lw=0.7, ls=":", zorder=2)
A.scatter(0, 0, color=INK, s=34, zorder=6); A.text(8, -22, "Earth", fontsize=10)
A.scatter(-Dk, 0, color=PURPLE, s=48, zorder=7); A.text(-Dk - 6, -34, "A (apogee)\n$\\theta=180^\\circ$", color=PURPLE, fontsize=10, ha="center", va="top")
t_ill = 40.0 * 3600.0
M0 = Dk * np.array([np.cos(PHI0_TB), np.sin(PHI0_TB)])
th1 = PHI0_TB + N_MOON * t_ill
M1 = Dk * np.array([np.cos(th1), np.sin(th1)])
for M, col in ((M0, BLUE), (M1, MAROON)):
    A.plot([0, M[0]], [0, M[1]], color=col, lw=1.2, zorder=3)
    A.scatter(*M, color=col, s=70, zorder=7)
A.annotate("Moon at injection, $t=0$", M0, xytext=(-70, 36), textcoords="offset points", color=BLUE, fontsize=10.5, arrowprops=dict(arrowstyle="-", color=BLUE, lw=0.7), ha="right")
A.annotate("Moon at a later time $t$", M1, xytext=(-80, 30), textcoords="offset points", color=MAROON, fontsize=10.5, arrowprops=dict(arrowstyle="-", color=MAROON, lw=0.7), ha="right")
# the angles, measured from the perigee direction
A.add_patch(Arc((0, 0), 2 * 85, 2 * 85, theta1=0, theta2=np.degrees(PHI0_TB), color=BLUE, lw=1.8, zorder=4))
A.text(85 * np.cos(0.5 * PHI0_TB) + 6, 85 * np.sin(0.5 * PHI0_TB), "$\\phi_0$", color=BLUE, fontsize=15, va="center")
A.add_patch(Arc((0, 0), 2 * 165, 2 * 165, theta1=0, theta2=np.degrees(th1), color=MAROON, lw=1.8, zorder=4))
A.text(165 * np.cos(0.55 * th1) + 8, 165 * np.sin(0.55 * th1) + 10, "$\\theta_{\\rm Moon}(t)=\\phi_0+n_{\\rm Moon}t$", color=MAROON, fontsize=12.5, va="center")
# the Moon's travel in the time t, along its circle
ang = np.linspace(PHI0_TB, th1, 80)
A.plot(Dk * np.cos(ang), Dk * np.sin(ang), color=MAROON, lw=3.4, zorder=5, solid_capstyle="round")
mid = 0.5 * (PHI0_TB + th1)
A.text(Dk * 1.10 * np.cos(mid), Dk * 1.10 * np.sin(mid), "$n_{\\rm Moon}\\,t$", color=MAROON, fontsize=13, ha="center", va="center")
# the textbook timing: the Moon reaches A when the spacecraft does
ang2 = np.linspace(th1, np.pi, 80)
A.plot(Dk * np.cos(ang2), Dk * np.sin(ang2), color=BLUE, lw=1.6, ls=(0, (1, 1.6)), zorder=4)
A.text(-290, -88, "dotted blue arc: the textbook timing, the Moon reaches A\nwhen the spacecraft does, $\\phi_0+n_{\\rm Moon}T_{\\rm H}/2=180^\\circ$", color=BLUE, fontsize=10, ha="left", va="center")
A.annotate("", xy=(Dk * np.cos(PHI0_TB + 0.5), Dk * np.sin(PHI0_TB + 0.5)), xytext=(Dk * np.cos(PHI0_TB + 0.35), Dk * np.sin(PHI0_TB + 0.35)), arrowprops=dict(arrowstyle="-|>", color=GREY, lw=1.3), zorder=3)
A.set_aspect("equal"); A.set_xlim(-470, 300); A.set_ylim(-130, 430); A.axis("off")
A.plot([170, 270], [395, 395], color=INK, lw=1.6); A.text(220, 402, "$100\\,000$ km", fontsize=9.5, ha="center", va="bottom")
fig.tight_layout()
fig.savefig("img/fig-pc-moon-phase.png", dpi=150, bbox_inches="tight")
plt.close(fig)

# snapshots: the spacecraft and the Moon at the same instants (textbook timing)
fig, A = plt.subplots(figsize=(10.4, 6.6))
A.plot(Dk * np.cos(th), Dk * np.sin(th), color=GREY, lw=0.9, ls=(0, (5, 3)), zorder=1)
A.plot(r_e * np.cos(fs_) / 1e3, r_e * np.sin(fs_) / 1e3, color=INK, lw=0.9, ls=(0, (1, 2.4)), zorder=2)
tt_ = np.linspace(0, HTE, 600); arcT = np.array([ellT.state(t)[0] for t in tt_])
A.plot(arcT[:, 0] / 1e3, arcT[:, 1] / 1e3, color=MAROON, lw=2.2, zorder=3)
SN = [(0.0, "#7f98c4"), (25 * 3600.0, "#4f7ab6"), (50 * 3600.0, GREEN), (75 * 3600.0, AMBER), (HTE, MAROON)]
for t, col in SN:
    Msn = moon_state(t, np.pi, ellT.T / 2)[0] / 1e3
    Ssc = ellT.state(t)[0] / 1e3
    A.add_patch(Circle(Msn, R_SOI / 1e3, color=col, alpha=0.09, ec=col, lw=0.9, zorder=2))
    A.plot([Msn[0], Ssc[0]], [Msn[1], Ssc[1]], color=col, lw=1.3, zorder=4)
    A.scatter(*Msn, color=col, s=64, zorder=6, edgecolor=INK, linewidths=0.5)
    A.scatter(*Ssc, color=col, s=44, zorder=6, marker="D", edgecolor=INK, linewidths=0.5)
    gap = np.linalg.norm(Msn - Ssc)
    lab = f"t = {t / 3600:.0f} h" if t != HTE else f"t$_1$ = {t / 3600:.2f} h"
    mid_ = Msn + (0.55 if t == 0.0 else 0.5) * (Ssc - Msn)
    A.text(mid_[0] + 10, mid_[1], f"{lab}:  {gap * 1e3:,.0f} km".replace(",", "\u2009"), color=col, fontsize=10.5, ha="left", va="center", weight="bold",
           bbox=dict(boxstyle="round,pad=0.18", fc=CREAM_, ec="none", alpha=0.9), zorder=8)
A.scatter(0, 0, color=INK, s=30, zorder=6); A.text(8, -22, "Earth", fontsize=10)
A.legend(handles=[Line2D([0], [0], marker="o", color="none", markerfacecolor="#888", markeredgecolor=INK, ms=8, label="the Moon (circle: its sphere of influence)"),
                  Line2D([0], [0], marker="D", color="none", markerfacecolor="#888", markeredgecolor=INK, ms=6, label="the spacecraft, at the same instant"),
                  Line2D([0], [0], color=MAROON, lw=2.2, label="the Hohmann ellipse flown up to $t_1$")], loc="upper center", bbox_to_anchor=(0.5, 0.02), ncol=1, fontsize=9.5, frameon=False)
A.set_aspect("equal"); A.set_xlim(-480, 150); A.set_ylim(-100, 440); A.axis("off")
fig.tight_layout()
fig.savefig("img/fig-pc-hohmann-snapshots.png", dpi=150, bbox_inches="tight")
plt.close(fig)

# ------------------------------------------------------------------ the Hohmann transfer
H, teH, LH = hohmann_run(DELTA_H)
_, _, LH0 = hohmann_run(0.0)
ell = H["ell"]
vehH = lambda t: ell.state(t)
t_ref = ell.T / 2 + DELTA_H
fig, ax = plt.subplots(1, 2, figsize=(13.4, 6.4), gridspec_kw={"width_ratios": [1.08, 1]})
A = ax[0]
fs = np.linspace(0, 2 * np.pi, 1500)
rr = ell.p / (1 + ell.e * np.cos(fs))
ex, ey = rr * np.cos(fs), rr * np.sin(fs)
tt = np.linspace(0, teH, 600)
arc = np.array([vehH(t)[0] for t in tt])
A.plot(ex / 1e3, ey / 1e3, color=INK, lw=0.8, ls=(0, (1, 2.4)), zorder=2)
A.plot(arc[:, 0] / 1e3, arc[:, 1] / 1e3, color=MAROON, lw=2.6, zorder=4)
th = np.linspace(0, 2 * np.pi, 400)
A.plot(D * np.cos(th) / 1e3, D * np.sin(th) / 1e3, color="#8a8478", lw=0.9, ls=(0, (5, 3)), zorder=1)
for t, lab, ha in ((0.0, "Moon at injection", "center"), (teH, "Moon at the SOI entry", "center"), (teH + LH["t_in"], "Moon at perilune", "center")):
    M, VM, thM = moon_state(t, np.pi, t_ref)
    A.scatter(M[0] / 1e3, M[1] / 1e3, color=BLUE, s=70 if t == teH else 38, zorder=6)
    if t == teH:
        A.add_patch(Circle((M[0] / 1e3, M[1] / 1e3), R_SOI / 1e3, color=BLUE, alpha=0.12, ec=BLUE, lw=1.0, zorder=3))
    off = {0.0: (14, 20), teH: (-170, 40), teH + LH["t_in"]: (-60, -60)}[t]
    A.annotate(lab, (M[0] / 1e3, M[1] / 1e3), xytext=off, textcoords="offset points", color=BLUE, fontsize=10, arrowprops=dict(arrowstyle="-", color=BLUE, lw=0.7))
ms = np.linspace(0, teH + LH["t_in"], 200)
mp = np.array([moon_state(t, np.pi, t_ref)[0] for t in ms])
A.plot(mp[:, 0] / 1e3, mp[:, 1] / 1e3, color=BLUE, lw=2.0, zorder=5)
P_in = vehH(teH)[0]
A.scatter(P_in[0] / 1e3, P_in[1] / 1e3, color=AMBER, s=44, zorder=8)
A.scatter(0, 0, color=INK, s=30, zorder=6); A.text(8, -22, "Earth", fontsize=10)
A.text(R0 / 1e3 + 10, 12, "injection\n(perigee)", fontsize=9.5)
A.set_aspect("equal"); A.set_xlim(-470, 40); A.set_ylim(-340, 410); A.axis("off")
A.plot([-460, -360], [-325, -325], color=INK, lw=1.6); A.text(-410, -318, "$100\\,000$ km", fontsize=9.5, ha="center", va="bottom")
A.set_title("(a)  the Earth's view", fontsize=11.5, loc="left")
encounter_panel(ax[1], LH, LH0, MAROON, "(b)  the Moon's view", [0.60, 0.04, 0.38, 0.38])
fig.tight_layout()
fig.savefig("img/fig-pc-hohmann-moon.png", dpi=150, bbox_inches="tight")
plt.close(fig)

# ------------------------------------------------------------------ the bi-elliptic transfer
B, teB, LB = bielliptic_run(DELTA_B, R_B)
_, _, LB0 = bielliptic_run(0.0, R_B)
vehB, t_burn, t_per = bielliptic_vehicle(B)
t_refB = t_per + DELTA_B
fig, ax = plt.subplots(1, 2, figsize=(13.4, 6.4), gridspec_kw={"width_ratios": [1.08, 1]})
A = ax[0]
for E, col, lab in ((B["e1"], BLUE, "ellipse I"), (B["e2"], MAROON, "ellipse II")):
    fs = np.linspace(0, 2 * np.pi, 1500)
    rr = E.p / (1 + E.e * np.cos(fs))
    A.plot(rr * np.cos(fs) / 1e3, rr * np.sin(fs) / 1e3, color=col, lw=1.0, ls=(0, (1, 2.4)), zorder=2)
tt = np.linspace(0, t_burn, 800); a1 = np.array([vehB(t)[0] for t in tt])
A.plot(a1[:, 0] / 1e3, a1[:, 1] / 1e3, color=BLUE, lw=2.2, zorder=4)
tt = np.linspace(t_burn, teB, 800); a2 = np.array([vehB(t)[0] for t in tt])
A.plot(a2[:, 0] / 1e3, a2[:, 1] / 1e3, color=MAROON, lw=2.2, zorder=4)
th = np.linspace(0, 2 * np.pi, 400)
A.plot(D * np.cos(th) / 1e3, D * np.sin(th) / 1e3, color="#8a8478", lw=0.9, ls=(0, (5, 3)), zorder=1)
M, VM, thM = moon_state(teB, 0.0, t_refB)
A.scatter(M[0] / 1e3, M[1] / 1e3, color=BLUE, s=70, zorder=6)
A.add_patch(Circle((M[0] / 1e3, M[1] / 1e3), R_SOI / 1e3, color=BLUE, alpha=0.12, ec=BLUE, lw=1.0, zorder=3))
A.annotate("Moon at the SOI entry", (M[0] / 1e3, M[1] / 1e3), xytext=(40, 52), textcoords="offset points", color=BLUE, fontsize=10, arrowprops=dict(arrowstyle="-", color=BLUE, lw=0.7))
M0 = moon_state(0.0, 0.0, t_refB)[0]
A.scatter(M0[0] / 1e3, M0[1] / 1e3, color=BLUE, s=38, zorder=6); A.annotate("Moon at injection", (M0[0] / 1e3, M0[1] / 1e3), xytext=(-50, -30), textcoords="offset points", color=BLUE, fontsize=10)
A.scatter(-R_B / 1e3, 0, color=PURPLE, s=44, zorder=7); A.text(-R_B / 1e3 + 14, 24, "burn 2\n($\\Delta v_2$, apoapsis)", color=PURPLE, fontsize=9.5)
A.scatter(R0 / 1e3, 0, color=AMBER, s=44, zorder=7); A.text(40, 24, "burn 1 ($\\Delta v_1$)", color=AMBER, fontsize=9.5)
A.scatter(0, 0, color=INK, s=30, zorder=6); A.text(-25, -60, "Earth", fontsize=10)
A.plot([-780 + 20, -780 + 220], [-560, -560], color=INK, lw=1.6); A.text(-780 + 120, -548, "$200\\,000$ km", fontsize=9.5, ha="center", va="bottom")
A.legend(handles=[Line2D([0], [0], color=BLUE, lw=2.2, label="ellipse I: $r_0\\to r_b=2r_{\\rm Moon}$"), Line2D([0], [0], color=MAROON, lw=2.2, label="ellipse II: $r_b\\to r_{\\rm Moon}$ (periapsis)")],
         loc="lower right", fontsize=9.5, frameon=False)
A.set_aspect("equal"); A.set_xlim(-800, 470); A.set_ylim(-600, 520); A.axis("off")
A.set_title("(a)  the Earth's view", fontsize=11.5, loc="left")
encounter_panel(ax[1], LB, None, MAROON, "(b)  the Moon's view", [0.66, 0.02, 0.32, 0.32])
fig.tight_layout()
fig.savefig("img/fig-pc-bielliptic-moon.png", dpi=150, bbox_inches="tight")
plt.close(fig)

# ------------------------------------------------------------------ the cost of the bi-elliptic transfer against r_b
Hh = hohmann()
CAP_MIN = capture_dv(-MU_M / R_SOI, RM + 100.0)
_, teH_, LH_ = hohmann_run(DELTA_H)
cap_H = capture_dv(LH_["eps2"], LH_["rp"])
ks = np.linspace(1.05, 3.0, 40)
cl = [bielliptic(k * D)["dv1"] + bielliptic(k * D)["dv2"] + bielliptic(k * D)["dv3_circ"] for k in ks]
low = [bielliptic(k * D)["dv1"] + bielliptic(k * D)["dv2"] + CAP_MIN for k in ks]
tof = [bielliptic(k * D)["tof"] / DAY for k in ks]
kk = (6.0 / 1.0)
R_SOI_E = 925.0e3 * 1.0                                                       # radius of the Earth's SOI about the Sun, km (see the note)
fig, ax = plt.subplots(1, 3, figsize=(13.6, 4.3))
for a_ in ax:
    a_.axvspan(R_SOI_E / D, 3.0, color="#e9e4d8", zorder=0)
    a_.set_xlim(1.0, 3.0); a_.set_xlabel(r"$r_b/r_{\rm Moon}$"); despine(a_)
ax[0].plot(ks, cl, color=MAROON, lw=2.4, label="bi-elliptic")
ax[0].axhline(Hh["dv1"] + Hh["dv2_circ"], color=INK, lw=1.4, ls="--", label="Hohmann")
ax[0].set_ylabel(r"$\Delta v$ [km/s]"); ax[0].set_title("(a)  circularise in an Earth orbit of radius $r_{\\rm Moon}$", fontsize=11, loc="left")
ax[0].legend(frameon=False, fontsize=10)
ax[1].plot(ks, low, color=MAROON, lw=2.4, label="bi-elliptic (best possible capture)")
ax[1].axhline(Hh["dv1"] + cap_H, color=INK, lw=1.4, ls="--", label="Hohmann (Example 2a)")
B2 = bielliptic(2.0 * D); _, te2, L2 = bielliptic_run(DELTA_B, 2.0 * D)
ax[1].scatter([2.0], [B2["dv1"] + B2["dv2"] + capture_dv(L2["eps2"], L2["rp"])], color=AMBER, s=48, zorder=6, label="Example 2b")
ax[1].set_title("(b)  capture into a $100$ km lunar orbit", fontsize=11, loc="left")
ax[1].legend(frameon=False, fontsize=10, loc="upper right")
ax[2].plot(ks, tof, color=MAROON, lw=2.4, label="bi-elliptic")
ax[2].axhline(Hh["tof"] / DAY, color=INK, lw=1.4, ls="--", label="Hohmann")
ax[2].set_ylabel("time to $r_{\\rm Moon}$ [days]"); ax[2].set_title("(c)  flight time", fontsize=11, loc="left")
ax[2].legend(frameon=False, fontsize=10, loc="upper left")
for a_, fy in zip(ax, (0.45, 0.62, 0.30)):
    a_.text(0.5 * (R_SOI_E / D + 3.0), a_.get_ylim()[0] + fy * (a_.get_ylim()[1] - a_.get_ylim()[0]), "beyond the\nEarth's SOI", fontsize=8.5, ha="center", va="bottom", color="#6a6459")
fig.tight_layout()
fig.savefig("img/fig-pc-bielliptic-cost.png", dpi=150, bbox_inches="tight")
plt.close(fig)
print("Hohmann delta = %.3f h, lambda_1 = %.3f deg; bi-elliptic delta = %.3f h, lambda_1 = %.3f deg" % (DELTA_H / 3600, LH["lam1"] / D2R, DELTA_B / 3600, LB["lam1"] / D2R))
