#!/usr/bin/env python3
"""Verify every result and number of Assignment 04 (problems and solutions).

Run:  python3 assignment-04-verify.py
Each check prints PASS or FAIL; the script exits with status 1 on any FAIL.

Part 1 of each problem checks the analytical results with sympy (identities,
limits, signs of derivatives). Part 2 recomputes every number quoted in
assignment-04.qmd (problems and folded solutions) and compares it with the
quoted value to the number of digits quoted.
"""
import sys
import numpy as np
import sympy as sp
from scipy.optimize import minimize_scalar

# ---------------------------------------------------------------- constants
MU = 398600.4418          # km^3/s^2, Earth
RE = 6378.137             # km
G0 = 9.80665e-3           # km/s^2
MU_S = 1.32712440018e11   # km^3/s^2, Sun
AU = 1.495978707e8        # km
MU_M, R_M = 42828.37, 3396.2          # Mars
MU_J, R_J = 1.26686534e8, 71492.0     # Jupiter
MU_V, R_V = 324858.59, 6051.8         # Venus
DEG = np.pi / 180

nfail = 0
npass = 0


def check(name, computed, quoted, tol=None, rel=None):
    """Compare a computed value with the quoted one.

    tol: absolute tolerance (default: half a unit in the last quoted digit,
    inferred from the quoted string if it is a string).
    """
    global nfail, npass
    if isinstance(quoted, str):
        q = float(quoted)
        if tol is None and rel is None:
            dec = len(quoted.split(".")[1]) if "." in quoted else 0
            tol = 0.5 * 10 ** (-dec) * 1.0000001
    else:
        q = quoted
    if rel is not None:
        ok = abs(computed - q) <= rel * abs(q)
    else:
        ok = abs(computed - q) <= tol
    if ok:
        npass += 1
    else:
        nfail += 1
    print(f"{'PASS' if ok else 'FAIL'}  {name}: computed {computed:.10g}, quoted {quoted}")


def check_true(name, cond):
    global nfail, npass
    if cond:
        npass += 1
    else:
        nfail += 1
    print(f"{'PASS' if cond else 'FAIL'}  {name}")


def sym_zero(name, expr):
    check_true(name, sp.simplify(expr) == 0)


def kepler_time(a, e, f1, f2, mu=MU):
    """Time from true anomaly f1 forward to f2 on an ellipse."""
    def M(f):
        E = 2 * np.arctan(np.sqrt((1 - e) / (1 + e)) * np.tan(f / 2))
        return E - e * np.sin(E)
    n = np.sqrt(mu / a**3)
    return ((M(f2) - M(f1)) % (2 * np.pi)) / n


# =================================================================== P1
print("\n=== Problem 1: apse-line rotation in steps")
y = sp.symbols("y", positive=True)
# N sin(eta/2N) = (eta/2) sin(y)/y with y = eta/(2N); d/dy (sin y / y) < 0 on (0, pi)
deriv = sp.diff(sp.sin(y) / y, y)
sym_zero("P1 d/dy(sin y/y) = (y cos y - sin y)/y^2", deriv - (y * sp.cos(y) - sp.sin(y)) / y**2)
yy = np.linspace(1e-4, np.pi - 1e-4, 2000)
check_true("P1 y cos y - sin y < 0 on (0, pi)", np.all(yy * np.cos(yy) - np.sin(yy) < 0))
a_, b_ = sp.symbols("alpha beta", nonnegative=True)
sym_zero("P1 sin(a+b) = sin a cos b + cos a sin b",
         sp.expand_trig(sp.sin(a_ + b_)) - (sp.sin(a_) * sp.cos(b_) + sp.cos(a_) * sp.sin(b_)))
N = sp.symbols("N", positive=True)
eta_s = sp.symbols("eta", positive=True)
check_true("P1 limit N sin(eta/2N) = eta/2",
           sp.limit(N * sp.sin(eta_s / (2 * N)), N, sp.oo) == eta_s / 2)

# The eccentricity vector e = v x h / mu - r_hat, in the perifocal frame of the old orbit.
# A radial impulse leaves r and h unchanged, so Delta e = Delta v x h / mu, of length |Delta v| h / mu,
# perpendicular to r_hat. At f = eta/2 the impulse -2 v_r r_hat turns e through exactly eta.
mu_s, p_s, e_s, f_s = sp.symbols("mu p e f", positive=True)
h_s = sp.sqrt(mu_s * p_s)
rhat = sp.Matrix([sp.cos(f_s), sp.sin(f_s), 0])
that = sp.Matrix([-sp.sin(f_s), sp.cos(f_s), 0])
khat = sp.Matrix([0, 0, 1])
r_s = p_s / (1 + e_s * sp.cos(f_s))
vr_s = sp.sqrt(mu_s / p_s) * e_s * sp.sin(f_s)
vt_s = sp.sqrt(mu_s / p_s) * (1 + e_s * sp.cos(f_s))
v_s = vr_s * rhat + vt_s * that
hvec = (r_s * rhat).cross(v_s)
sym_zero("P1 h = r x v = sqrt(mu p) k", sp.simplify(hvec - h_s * khat).norm())
evec = v_s.cross(hvec) / mu_s - rhat
sym_zero("P1 e-vector = (e, 0, 0) (points at perigee)", sp.simplify(evec - sp.Matrix([e_s, 0, 0])).norm())
dv_s = sp.symbols("dv_r", real=True)
dvec = dv_s * rhat
sym_zero("P1 radial impulse leaves h unchanged", sp.simplify((r_s * rhat).cross(dvec)).norm())
de = dvec.cross(hvec) / mu_s
sym_zero("P1 |De|^2 = (h/mu)^2 dv^2", sp.simplify(de.dot(de) - (h_s / mu_s)**2 * dv_s**2))
sym_zero("P1 De . r_hat = 0", sp.simplify(de.dot(rhat)))
e_after = sp.simplify(evec + de.subs(dv_s, -2 * vr_s)).subs(f_s, eta_s / 2)
sym_zero("P1 impulse at f=eta/2 turns e by eta",
         sp.simplify(e_after - e_s * sp.Matrix([sp.cos(eta_s), sp.sin(eta_s), 0])).norm())
sym_zero("P1 cost = sqrt(mu/p) x chord 2 e sin(eta/2)",
         sp.simplify(2 * vr_s.subs(f_s, eta_s / 2) - sp.sqrt(mu_s / p_s) * 2 * e_s * sp.sin(eta_s / 2)))

rp2, ra2 = RE + 500, RE + 20000
a2 = (rp2 + ra2) / 2
e2 = (ra2 - rp2) / (ra2 + rp2)
p2 = a2 * (1 - e2**2)
s2 = np.sqrt(MU / p2)
eta = 30 * DEG
check("P1 a [km]", a2, "16628.1")
check("P1 e", e2, "0.5864")
check("P1 p [km]", p2, "10911.2")
check("P1 sqrt(mu/p) [km/s]", s2, "6.0441")
cost = {Nn: 2 * Nn * s2 * e2 * np.sin(eta / (2 * Nn)) for Nn in (1, 2, 3, 6, 10)}
check("P1 N=1 [km/s]", cost[1], "1.835")
check("P1 N=2 [km/s]", cost[2], "1.850")
check("P1 N=3 [km/s]", cost[3], "1.853")
check("P1 N=6 [km/s]", cost[6], "1.855")
check("P1 N=10 [km/s]", cost[10], "1.855")
check("P1 N=10 short of the limit [m/s]", (s2 * e2 * eta - cost[10]) * 1e3, "0.2")
check("P1 chord vs arc at 120 deg (figure) [%]", (120 * DEG / 2 / np.sin(60 * DEG) - 1) * 100, "20.9")
check("P1 N=inf [km/s]", s2 * e2 * eta, "1.856")
check("P1 N=2 penalty [m/s]", (cost[2] - cost[1]) * 1e3, "15.8")
check("P1 N=3 penalty [m/s]", (cost[3] - cost[1]) * 1e3, "18.8")
check("P1 N=inf penalty [%]", (s2 * e2 * eta / cost[1] - 1) * 100, "1.15")
# unequal split 20 + 10
check("P1 split 20+10 [km/s]", 2 * s2 * e2 * (np.sin(10 * DEG) + np.sin(5 * DEG)), "1.849")
vc2 = np.sqrt(MU / ra2)
va2 = np.sqrt(MU * (2 / ra2 - 1 / a2))
check("P1 two-burn route [km/s]", 2 * (vc2 - va2), "2.774")
t2 = np.sqrt(1 - e2)
check("P1 eta_c [deg]", 2 * np.arcsin(t2 / (1 + t2)) / DEG, "46.1")
# crossings for the single step: f = 15 deg and 195 deg
for name, f, rq, vtq, rateq in (("near", 15 * DEG, "6965.9", "9.467", "4.67"),
                                ("far", 195 * DEG, "25162.7", "2.621", "0.358")):
    rr = p2 / (1 + e2 * np.cos(f))
    vt = s2 * (1 + e2 * np.cos(f))
    check(f"P1 crossing {name} r [km]", rr, rq)
    check(f"P1 crossing {name} v_theta [km/s]", vt, vtq)
    check(f"P1 crossing {name} f-dot [deg/min]", vt / rr / DEG * 60, rateq)
check("P1 |v_r| at crossing [km/s]", s2 * e2 * np.sin(15 * DEG), "0.917")
P1 = 2 * np.pi * np.sqrt(a2**3 / MU)
check("P1 period [h]", P1 / 3600, "5.93")
# burn durations, m0 = 1500 kg, F = 440 N, Isp = 315 s
ve = 315 * G0
for Nn, q in ((1, "78.6"), (2, "45.4"), (3, "31.8")):
    dv1 = 2 * s2 * e2 * np.sin(eta / (2 * Nn))
    tb = 1500 * (1 - np.exp(-dv1 / ve)) * ve * 1e3 / 440
    check(f"P1 first burn N={Nn} [min]", tb / 60, q)
# arc of true anomaly swept during a burn centred on the crossing (Kepler's equation)
from scipy.optimize import brentq


def f_of_M(Mv, e):
    Ev = brentq(lambda E: E - e * np.sin(E) - Mv, -20, 20)
    return 2 * np.arctan(np.sqrt((1 + e) / (1 - e)) * np.tan(Ev / 2))


def arc(fc, tb_min):
    Ec = 2 * np.arctan(np.sqrt((1 - e2) / (1 + e2)) * np.tan(fc / 2))
    Mc = Ec - e2 * np.sin(Ec)
    dM = np.sqrt(MU / a2**3) * tb_min * 60 / 2
    return ((f_of_M(Mc + dM, e2) - f_of_M(Mc - dM, e2)) / DEG) % 360


check("P1 arc N=1 near [deg]", arc(15 * DEG, 78.6), "219", tol=1)
check("P1 arc N=1 far [deg]", arc(195 * DEG, 78.6), "29.2", tol=0.1)
check("P1 arc N=3 near [deg]", arc(15 * DEG, 31.8), "128", tol=1)
check("P1 arc N=3 far [deg]", arc(195 * DEG, 31.8), "11.4", tol=0.1)
check("P1 mass left N=1 [%]", np.exp(-cost[1] / ve) * 100, "55.2")
check("P1 mass left N=3 [%]", np.exp(-cost[3] / ve) * 100, "54.9")

# =================================================================== P2
print("\n=== Problem 2: folding a small plane change into an orbit raise")
v, vp_, dl = sp.symbols("v v' delta", positive=True)
lhs = v**2 + vp_**2 - 2 * v * vp_ * sp.cos(dl)
rhs = (vp_ - v) ** 2 + 4 * v * vp_ * sp.sin(dl / 2) ** 2
sym_zero("P2 law of cosines split", sp.expand(sp.expand_trig(lhs - rhs).rewrite(sp.cos)))
A, B = sp.symbols("A B", positive=True)
# saving fraction 1 - sqrt(A^2+B^2)/(A+B), maximum at A = B
rho = sp.symbols("rho", positive=True)
fr = 1 - sp.sqrt(1 + rho**2) / (1 + rho)
crit = sp.solve(sp.diff(fr, rho), rho)
check_true("P2 saving fraction stationary only at rho = 1", crit == [1])
sym_zero("P2 max saving = 1 - 1/sqrt 2", fr.subs(rho, 1) - (1 - 1 / sp.sqrt(2)))
# equal split of a small raise and small turn: 2 sqrt((H/2)^2 + (v di/2)^2) = sqrt(H^2 + (v di)^2)
H_, di_ = sp.symbols("H Delta_i", positive=True)
sym_zero("P2 equal split gives Pythagorean sum",
         2 * sp.sqrt((H_ / 2) ** 2 + (v * di_ / 2) ** 2) - sp.sqrt(H_**2 + (v * di_) ** 2))

r31, r32 = RE + 500, RE + 520


def hoh(di1=0.0, di2=0.0):
    at = (r31 + r32) / 2
    c1, c2 = np.sqrt(MU / r31), np.sqrt(MU / r32)
    t1, t2_ = np.sqrt(MU * (2 / r31 - 1 / at)), np.sqrt(MU * (2 / r32 - 1 / at))
    b1 = np.sqrt(c1**2 + t1**2 - 2 * c1 * t1 * np.cos(di1))
    b2 = np.sqrt(t2_**2 + c2**2 - 2 * t2_ * c2 * np.cos(di2))
    return b1, b2, c1, c2, t1, t2_


b1, b2, c1, c2, t1, t2_ = hoh()
H = b1 + b2
check("P2 v_c1 [km/s]", c1, "7.6126")
check("P2 v_c2 [km/s]", c2, "7.6016")
check("P2 dv1 Hohmann [m/s]", b1 * 1e3, "5.52")
check("P2 dv2 Hohmann [m/s]", b2 * 1e3, "5.52")
check("P2 Hohmann total [m/s]", H * 1e3, "11.04")
check("P2 v_t1 [km/s]", t1, "7.6181")
check("P2 v_t2 [km/s]", t2_, "7.5960")
res = {}
for diD in (0.01, 0.1, 1.0):
    di = diD * DEG
    sep = H + 2 * c2 * np.sin(di / 2)
    all1 = sum(hoh(di, 0)[:2])
    all2 = sum(hoh(0, di)[:2])
    half = sum(hoh(di / 2, di / 2)[:2])
    opt = minimize_scalar(lambda z: sum(hoh(z, di - z)[:2]), bounds=(0, di),
                          method="bounded", options={"xatol": 1e-15})
    pyth = np.sqrt(H**2 + (c1 * di) ** 2)
    res[diD] = dict(plane=2 * c2 * np.sin(di / 2), sep=sep, all1=all1, all2=all2,
                    half=half, opt=opt.fun, dstar=opt.x / di, pyth=pyth)
R = res[0.1]
check("P2 0.1 plane alone [m/s]", R["plane"] * 1e3, "13.27")
check("P2 0.1 separate [m/s]", R["sep"] * 1e3, "24.31")
check("P2 0.1 all in burn 1 [m/s]", R["all1"] * 1e3, "19.91")
check("P2 0.1 all in burn 2 [m/s]", R["all2"] * 1e3, "19.89")
check("P2 0.1 equal split [m/s]", R["half"] * 1e3, "17.27")
check("P2 0.1 optimum [m/s]", R["opt"] * 1e3, "17.27")
check("P2 0.1 optimum share", R["dstar"], "0.498")
check("P2 0.1 Pythagorean [m/s]", R["pyth"] * 1e3, "17.28")
check("P2 0.1 saving vs separate [%]", (1 - R["half"] / R["sep"]) * 100, "29.0")
check("P2 0.1 v_c1 * di [m/s]", c1 * 0.1 * DEG * 1e3, "13.29")
for diD, q_sep, q_half, q_sav in ((0.01, "12.37", "11.12", "10.1"),
                                  (1.0, "143.71", "133.23", "7.3")):
    R = res[diD]
    check(f"P2 {diD} separate [m/s]", R["sep"] * 1e3, q_sep)
    check(f"P2 {diD} equal split [m/s]", R["half"] * 1e3, q_half)
    check(f"P2 {diD} saving [%]", (1 - R["half"] / R["sep"]) * 100, q_sav)
check("P2 1.0 optimum [m/s]", res[1.0]["opt"] * 1e3, "133.22")
check("P2 1.0 Pythagorean [m/s]", res[1.0]["pyth"] * 1e3, "133.32")
check("P2 1.0 plane alone [m/s]", res[1.0]["plane"] * 1e3, "132.67")
check("P2 1.0 raise hidden in the turn [m/s]", (res[1.0]["opt"] - res[1.0]["plane"]) * 1e3, "0.54")
check("P2 1.0 optimum share", res[1.0]["dstar"], "0.42")
# ratio of the two jobs
check("P2 ratio b/a at 0.1 deg", c1 * 0.1 * DEG / H, "1.20")
check("P2 0.1 deg in-plane/out-of-plane equal at di [deg]", H / c1 / DEG, "0.083")
# propellant, 700 kg, Isp 220 s
ve3 = 220 * G0
mp = lambda dv: 700 * (1 - np.exp(-dv / ve3))
check("P2 propellant separate [kg]", mp(res[0.1]["sep"]), "7.84")
check("P2 propellant combined [kg]", mp(res[0.1]["half"]), "5.58")

# =================================================================== P3
print("\n=== Problem 3: a plane change on an eccentric orbit")
e_, om_, p_ = sp.symbols("e omega p", positive=True)
r_an = p_ / (1 + e_ * sp.cos(om_))
r_dn = p_ / (1 - e_ * sp.cos(om_))
sym_zero("P3 cost ratio AN/DN = r_DN/r_AN", (r_dn / r_an) - (1 + e_ * sp.cos(om_)) / (1 - e_ * sp.cos(om_)))
rp4, ra4 = 7000.0, 21000.0
a4 = (rp4 + ra4) / 2
e4 = (ra4 - rp4) / (ra4 + rp4)
p4 = a4 * (1 - e4**2)
s4 = np.sqrt(MU / p4)
om4 = 50 * DEG
di4 = 6 * DEG
check("P3 e", e4, "0.5")
check("P3 p [km]", p4, "10500")
check("P3 sqrt(mu/p) [km/s]", s4, "6.1613")
vals = {}
for nm, f in (("AN", -om4), ("DN", np.pi - om4)):
    rr = p4 / (1 + e4 * np.cos(f))
    vt = s4 * (1 + e4 * np.cos(f))
    vr = s4 * e4 * np.sin(f)
    vals[nm] = dict(r=rr, vt=vt, vr=vr, v=np.hypot(vr, vt), dv=2 * vt * np.sin(di4 / 2),
                    wrong=2 * np.hypot(vr, vt) * np.sin(di4 / 2))
check("P3 AN r [km]", vals["AN"]["r"], "7946.2")
check("P3 DN r [km]", vals["DN"]["r"], "15472.9")
check("P3 AN v_theta [km/s]", vals["AN"]["vt"], "8.1415")
check("P3 DN v_theta [km/s]", vals["DN"]["vt"], "4.1811")
check("P3 |v_r| [km/s]", abs(vals["AN"]["vr"]), "2.3599")
check("P3 AN v [km/s]", vals["AN"]["v"], "8.4767")
check("P3 DN v [km/s]", vals["DN"]["v"], "4.8011")
check("P3 AN dv [km/s]", vals["AN"]["dv"], "0.852")
check("P3 DN dv [km/s]", vals["DN"]["dv"], "0.438")
check("P3 ratio", vals["AN"]["dv"] / vals["DN"]["dv"], "1.947")
check("P3 ratio formula", (1 + e4 * np.cos(om4)) / (1 - e4 * np.cos(om4)), "1.947")
check("P3 DN wrong (full v) [km/s]", vals["DN"]["wrong"], "0.503")
check("P3 DN wrong overestimate [%]", (vals["DN"]["wrong"] / vals["DN"]["dv"] - 1) * 100, "14.8")
va4 = np.sqrt(MU * (2 / ra4 - 1 / a4))
check("P3 v_a [km/s]", va4, "3.0807")
check("P3 node at apoapsis dv [km/s]", 2 * va4 * np.sin(di4 / 2), "0.322")
ve4 = 315 * G0
check("P3 mass left AN [%]", np.exp(-vals["AN"]["dv"] / ve4) * 100, "75.9")
check("P3 mass left DN [%]", np.exp(-vals["DN"]["dv"] / ve4) * 100, "86.8")
# time from AN to DN (f = 310 deg -> 130 deg)
check("P3 time AN -> DN [min]", kepler_time(a4, e4, -om4, np.pi - om4) / 60, "68.6")
check("P3 period [min]", 2 * np.pi * np.sqrt(a4**3 / MU) / 60, "274.8")
# radial component unchanged -> same r, same speed, so same a; same h -> same p, e
check_true("P3 v_theta at DN equals h/r", abs(vals["DN"]["vt"] - np.sqrt(MU * p4) / vals["DN"]["r"]) < 1e-12)

# =================================================================== P4
print("\n=== Problem 4: leaving the Earth from an elliptic orbit")
vi, rp_s, mu_e, ee = sp.symbols("v_inf r_p mu e", positive=True)
dv5 = sp.sqrt(vi**2 + 2 * mu_e / rp_s) - sp.sqrt(mu_e * (1 + ee) / rp_s)
check_true("P4 d(dv)/de < 0", sp.simplify(sp.diff(dv5, ee) + sp.sqrt(mu_e / rp_s) / (2 * sp.sqrt(1 + ee))) == 0)
ve_s = sp.symbols("v_e", positive=True)   # local escape speed
lim = sp.sqrt(vi**2 + ve_s**2) - ve_s
sym_zero("P4 e->1 limit rationalised", sp.simplify(lim - vi**2 / (sp.sqrt(vi**2 + ve_s**2) + ve_s)))
ser5 = sp.series(lim.subs(vi, sp.Symbol("eps") * ve_s), sp.Symbol("eps"), 0, 3).removeO()
sym_zero("P4 small v_inf: limit ~ v_inf^2/(2 v_e)", sp.simplify(ser5 - (sp.Symbol("eps") * ve_s) ** 2 / (2 * ve_s)))

rp5 = RE + 250
vinf5 = 2.945
vesc5 = np.sqrt(2 * MU / rp5)
vp5 = np.sqrt(vinf5**2 + vesc5**2)
eh5 = 1 + rp5 * vinf5**2 / MU
check("P4 v_esc [km/s]", vesc5, "10.967")
check("P4 v_p hyperbola [km/s]", vp5, "11.356")
check("P4 e_h", eh5, "1.1442")
check("P4 f_inf [deg]", np.arccos(-1 / eh5) / DEG, "150.9")
check("P4 e->1 limit [km/s]", vp5 - vesc5, "0.389")
check("P4 small-v_inf estimate [km/s]", vinf5**2 / (2 * vesc5), "0.395")
for ha, q_e, q_v0, q_dv, q_m in ((250, "0", "7.755", "3.601", "31.2"),
                                 (23000, "0.632", "9.906", "1.449", "62.6"),
                                 (35786, "0.728", "10.195", "1.161", "68.7"),
                                 (200000, "0.938", "10.795", "0.561", "83.4")):
    ra5 = RE + ha
    a5 = (rp5 + ra5) / 2
    e5 = (ra5 - rp5) / (ra5 + rp5)
    v0 = np.sqrt(MU * (2 / rp5 - 1 / a5))
    dv = vp5 - v0
    check(f"P4 h_a={ha} e", e5, q_e)
    check(f"P4 h_a={ha} v0 [km/s]", v0, q_v0)
    check(f"P4 h_a={ha} dv [km/s]", dv, q_dv)
    check(f"P4 h_a={ha} mass left [%]", np.exp(-dv / (315 * G0)) * 100, q_m)
check("P4 period of 250 x 200000 orbit [h]",
      2 * np.pi * np.sqrt(((rp5 + RE + 200000) / 2) ** 3 / MU) / 3600, "96.1")

# =================================================================== P5
print("\n=== Problem 5: the cheapest capture orbit at Mars")
X, vv, eps_e = sp.symbols("x v_inf e", positive=True)   # x = mu/r_p
f6 = sp.sqrt(vv**2 + 2 * X) - sp.sqrt((1 + eps_e) * X)
xs = sp.solve(sp.Eq(sp.diff(f6, X), 0), X)
check_true("P5 stationary x = (1+e) v^2 / (2(1-e))",
           any(sp.simplify(s - (1 + eps_e) * vv**2 / (2 * (1 - eps_e))) == 0 for s in xs))
xst = (1 + eps_e) * vv**2 / (2 * (1 - eps_e))
sym_zero("P5 optimal cost = v sqrt((1-e)/2)",
         sp.simplify(f6.subs(X, xst) - vv * sp.sqrt((1 - eps_e) / 2)).subs(eps_e, sp.Rational(1, 3)))
for ev in (0, sp.Rational(1, 3), sp.Rational(9, 10)):
    val = sp.simplify(f6.subs(X, xst) - vv * sp.sqrt((1 - eps_e) / 2)).subs(eps_e, ev)
    check_true(f"P5 optimal cost identity at e = {ev}", sp.simplify(val) == 0)
    d2 = sp.simplify(sp.diff(f6, X, 2).subs(X, xst).subs(eps_e, ev))
    check_true(f"P5 second derivative > 0 at e = {ev}", bool(sp.simplify(d2 * vv**3) > 0))
vinf6 = 2.649
rs = 2 * MU_M / vinf6**2
check("P5 r* [km]", rs, "12207")
check("P5 r* altitude [km]", rs - R_M, "8810")
check("P5 dv* [km/s]", vinf6 / np.sqrt(2), "1.873")
circ = lambda rr: np.sqrt(vinf6**2 + 2 * MU_M / rr) - np.sqrt(MU_M / rr)
check("P5 dv circle 300 km [km/s]", circ(R_M + 300), "2.091")
check("P5 dv circle at r* [km/s]", circ(rs), "1.873")
check("P5 penalty of 300 km circle [m/s]", (circ(R_M + 300) - vinf6 / np.sqrt(2)) * 1e3, "218")
rp6, ra6 = R_M + 421.7, R_M + 76993.6
e6 = (ra6 - rp6) / (ra6 + rp6)
dv6 = np.sqrt(vinf6**2 + 2 * MU_M / rp6) - np.sqrt(MU_M * (1 + e6) / rp6)
check("P5 ellipse e", e6, "0.9093")
check("P5 ellipse dv [km/s]", dv6, "0.799")
check("P5 ellipse period [h]", 2 * np.pi * np.sqrt(((rp6 + ra6) / 2) ** 3 / MU_M) / 3600, "72.86")
check("P5 optimal r_p for e = 0.9093 [km]", 2 * MU_M * (1 - e6) / ((1 + e6) * vinf6**2), "580")
check("P5 unreachable optimum cost [km/s]", vinf6 * np.sqrt((1 - e6) / 2), "0.564")
# mass, Isp 315 s
ve6 = 315 * G0
check("P5 mass left circle 300 [%]", np.exp(-circ(R_M + 300) / ve6) * 100, "50.8")
check("P5 mass left circle r* [%]", np.exp(-vinf6 / np.sqrt(2) / ve6) * 100, "54.5")
check("P5 mass left ellipse [%]", np.exp(-dv6 / ve6) * 100, "77.2")

# =================================================================== P6
print("\n=== Problem 6: the largest velocity change a flyby can give")
w, rpp, mu7 = sp.symbols("v_inf r_p mu", positive=True)
g7 = 2 * w / (1 + rpp * w**2 / mu7)
crit7 = sp.solve(sp.diff(g7, w), w)
check_true("P6 stationary at v_inf = sqrt(mu/r_p)", crit7 == [sp.sqrt(mu7 / rpp)])
sym_zero("P6 maximum = sqrt(mu/r_p)", g7.subs(w, sp.sqrt(mu7 / rpp)) - sp.sqrt(mu7 / rpp))
sym_zero("P6 e = 2 at the optimum", (1 + rpp * w**2 / mu7).subs(w, sp.sqrt(mu7 / rpp)) - 2)
for nm, m, Rb, rpv, q in (("Venus", MU_V, R_V, R_V + 300, "7.15"),
                          ("Earth", MU, RE, RE + 300, "7.73"),
                          ("Mars", MU_M, R_M, R_M + 300, "3.40"),
                          ("Jupiter", MU_J, R_J, 3 * R_J, "24.3")):
    check(f"P6 {nm} max dV = optimal v_inf [km/s]", np.sqrt(m / rpv), q)
check("P6 Jupiter at the cloud tops [km/s]", np.sqrt(MU_J / R_J), "42.1")
v7 = 2.649
e7 = 1 + (R_M + 300) * v7**2 / MU_M
check("P6 Mars e", e7, "1.6056")
check("P6 Mars turn [deg]", 2 * np.arcsin(1 / e7) / DEG, "77.0")
check("P6 Mars dV [km/s]", 2 * v7 / e7, "3.300")
check("P6 Mars fraction of max [%]", 2 * v7 / e7 / np.sqrt(MU_M / (R_M + 300)) * 100, "96.9")
# Jupiter at v_inf = 5.643 (the note's example), r_p = 3 R_J
v7j = 5.643
e7j = 1 + 3 * R_J * v7j**2 / MU_J
check("P6 Jupiter e at 5.643", e7j, "1.0539")
check("P6 Jupiter dV at 5.643 [km/s]", 2 * v7j / e7j, "10.71")
check("P6 Jupiter turn at 5.643 [deg]", 2 * np.arcsin(1 / e7j) / DEG, "143.2")

# =================================================================== P7
print("\n=== Problem 7: a round trip to Mars")
r81, r82 = AU, 1.52368 * AU
at8 = (r81 + r82) / 2
t12 = np.pi * np.sqrt(at8**3 / MU_S) / 86400
nE = np.sqrt(MU_S / r81**3) * 86400 / DEG
nM = np.sqrt(MU_S / r82**3) * 86400 / DEG
check("P7 t12 [d]", t12, "258.9")
check("P7 T_E [d]", 360 / nE, "365.26")
check("P7 T_M [d]", 360 / nM, "686.97")
check("P7 n_E [deg/d]", nE, "0.98561")
check("P7 n_M [deg/d]", nM, "0.52404")
check("P7 phi0 [deg]", 180 - nM * t12, "44.3")
check("P7 n_E t12 [deg]", nE * t12, "255.1")
check("P7 Earth lead at arrival [deg]", nE * t12 - 180, "75.1")
check("P7 lead needed for return [deg]", 180 - nE * t12, "-75.1")
tw = ((180 - nE * t12) - (nE * t12 - 180)) % 360 / (nE - nM)
check("P7 change of lead needed [deg]", ((180 - nE * t12) - (nE * t12 - 180)) % 360, "209.7")
check("P7 wait [d]", tw, "454.4")
check("P7 total [d]", 2 * t12 + tw, "972.1")
check("P7 total [yr]", (2 * t12 + tw) / 365.25, "2.66")
S = 360 / (nE - nM)
check("P7 synodic [d]", S, "779.9")
check("P7 synodic [months]", S / 30.44, "25.6")
# wait-time formula: t_w = (2 pi N - 2 n_E t12)/(n_E - n_M), smallest whole N with t_w > 0
check("P7 formula N=1", (360 - 2 * nE * t12) / (nE - nM), "-325.6")
check("P7 formula N=2", (720 - 2 * nE * t12) / (nE - nM), "454.4")
check("P7 2 n_E t12 [deg]", 2 * nE * t12, "510.3")
check("P7 n_E - n_M [deg/d]", nE - nM, "0.46157")
# MOM launch 5 Nov 2013 + S
import datetime as _dt
nxt = _dt.date(2013, 11, 5) + _dt.timedelta(days=S)
check_true(f"P7 5 Nov 2013 + S = {nxt} (late December 2015)", nxt == _dt.date(2015, 12, 24))

# =================================================================== P8
print("\n=== Problem 8: where a spent stage comes down")
Qs, gs, rs_ = sp.symbols("Q gamma r", positive=True)
e2s = 1 + Qs * (Qs - 2) * sp.cos(gs) ** 2
# apogee height above burnout: r (e + Q - 1)/(2 - Q); flat-Earth limit r Q sin^2 / 2
eps = sp.symbols("epsilon", positive=True)
hser = sp.series((sp.sqrt(e2s) + Qs - 1).subs(Qs, eps * Qs), eps, 0, 2).removeO()
sym_zero("P8 e + Q - 1 = Q sin^2 gamma + O(Q^2)", sp.simplify(hser - eps * Qs * sp.sin(gs) ** 2))
# ellipse: r_a = a(1+e) with a = r/(2-Q)
r9 = RE + 150
v9 = 4.0
g9 = 25 * DEG


def flight(rr, vv_, gg):
    Q = vv_**2 * rr / MU
    a = rr / (2 - Q)
    e = np.sqrt(1 + Q * (Q - 2) * np.cos(gg) ** 2)
    psi = 2 * np.arctan2(Q * np.sin(gg) * np.cos(gg), 1 - Q * np.cos(gg) ** 2)
    Ebo = np.arctan2(np.sqrt(Q * (2 - Q)) * np.sin(gg), Q - 1)
    Pcs = 2 * np.pi * np.sqrt(rr**3 / MU)
    tff = Pcs * (np.pi - Ebo + np.sqrt(Q * (2 - Q)) * np.sin(gg)) / (np.pi * (2 - Q) ** 1.5)
    return dict(Q=Q, a=a, e=e, psi=psi, tff=tff, ra=a * (1 + e), rp=a * (1 - e), Ebo=Ebo)


F = flight(r9, v9, g9)
check("P8 Q", F["Q"], "0.2620")
check("P8 a [km]", F["a"], "3756.2")
check("P8 e", F["e"], "0.7912")
check("P8 psi [deg]", F["psi"] / DEG, "14.58")
check("P8 ground range [km]", F["psi"] * RE, "1623")
check("P8 apogee alt [km]", F["ra"] - RE, "349.8")
check("P8 perigee radius [km]", F["rp"], "784")
check("P8 E_bo [deg]", F["Ebo"] / DEG, "158.87")
check("P8 t_ff [s]", F["tff"], "477")
Q9 = F["Q"]
psi9 = F["psi"]
Aang = np.arcsin((2 - Q9) / Q9 * np.sin(psi9 / 2))
check("P8 (2-Q)/Q sin(psi/2)", (2 - Q9) / Q9 * np.sin(psi9 / 2), "0.8414")
check("P8 A [deg]", Aang / DEG, "57.29")
gl, gh = (Aang - psi9 / 2) / 2, (np.pi - Aang - psi9 / 2) / 2
check("P8 gamma low [deg]", gl / DEG, "25.00")
check("P8 gamma high [deg]", gh / DEG, "57.71")
check("P8 symmetry angle [deg]", 45 - psi9 / DEG / 4, "41.36")
F2 = flight(r9, v9, gh)
check("P8 high: psi [deg]", F2["psi"] / DEG, "14.58")
check("P8 high: apogee alt [km]", F2["ra"] - RE, "881.7")
check("P8 high: t_ff [s]", F2["tff"], "896")
check("P8 high: e", F2["e"], "0.9328")
gloc = MU / r9**2
check("P8 g at burnout [m/s^2]", gloc * 1e3, "9.35")
check("P8 flat range [km]", v9**2 * np.sin(2 * g9) / gloc, "1310")
check("P8 flat apogee height [km]", v9**2 * np.sin(g9) ** 2 / (2 * gloc), "152.8")
check("P8 flat time [s]", 2 * v9 * np.sin(g9) / gloc, "361")
check("P8 round apogee height above burnout [km]", F["ra"] - r9, "199.8")
check("P8 round/flat range [%]", (F["psi"] * RE / (v9**2 * np.sin(2 * g9) / gloc) - 1) * 100, "23.8")
check_true("P8 comes down (r_p < R_E)", F["rp"] < RE and F2["rp"] < RE)

# =================================================================== P9
print("\n=== Problem 9: what a little more speed buys")
psm = 2 * sp.asin(Qs / (2 - Qs))
dpsi = sp.simplify(sp.diff(psm, Qs))
check_true("P9 d psi_max/dQ = 2/((2-Q) sqrt(1-Q)) on a grid",
           all(abs(float(dpsi.subs(Qs, qv)) - 2 / ((2 - qv) * np.sqrt(1 - qv))) < 1e-12
               for qv in (0.1, 0.3, 0.5, 0.8, 0.95)))
s_ = sp.symbols("s", positive=True)
Qmin = 2 * s_ / (1 + s_)
sym_zero("P9 dQmin/ds = 2/(1+s)^2", sp.diff(Qmin, s_) - 2 / (1 + s_) ** 2)
r10 = RE + 200
vc10 = np.sqrt(MU / r10)
check("P9 v_c [km/s]", vc10, "7.784")
for Qv, q_v, q_psi, q_L, q_dL, q_lin in ((0.5, "5.504", "38.94", "4335", "122", "120"),
                                         (0.8, "6.962", "83.62", "9309", "393", "380"),
                                         (0.9, "7.385", "109.81", "12224", "702", "660"),
                                         (0.95, "7.587", "129.58", "14425", "1173", "1032")):
    pm = 2 * np.arcsin(Qv / (2 - Qv))
    vv_ = np.sqrt(Qv) * vc10
    Q2 = (1.01 * vv_) ** 2 * r10 / MU
    pm2 = 2 * np.arcsin(Q2 / (2 - Q2))
    lin = 4 * Qv / ((2 - Qv) * np.sqrt(1 - Qv)) * 0.01 * RE
    check(f"P9 Q={Qv} v [km/s]", vv_, q_v)
    check(f"P9 Q={Qv} psi_max [deg]", pm / DEG, q_psi)
    check(f"P9 Q={Qv} range [km]", pm * RE, q_L)
    check(f"P9 Q={Qv} +1% exact [km]", (pm2 - pm) * RE, q_dL)
    check(f"P9 Q={Qv} +1% linear [km]", lin, q_lin)
check("P9 Q=0.99 +1% gives Q above 1", 1.0201 * 0.99, "1.0099")
for L, q_Q, q_ratio, q_v, q_g in ((1000, "0.1453", "0.381", "2.967", "42.75"),
                                  (5000, "0.5528", "0.744", "5.788", "33.77"),
                                  (10000, "0.8277", "0.910", "7.082", "22.54"),
                                  (15000, "0.9600", "0.980", "7.627", "11.31")):
    ps = L / RE
    sn = np.sin(ps / 2)
    Qm = 2 * sn / (1 + sn)
    check(f"P9 L={L} Q_min", Qm, q_Q)
    check(f"P9 L={L} v/v_c", np.sqrt(Qm), q_ratio)
    check(f"P9 L={L} v [km/s]", np.sqrt(Qm) * vc10, q_v)
    check(f"P9 L={L} gamma [deg]", 45 - ps / DEG / 4, q_g)
check("P9 half way round [km]", np.pi * RE, "20038")
check("P9 speed 10000 -> half way [km/s]", vc10 - np.sqrt(2 * np.sin(10000 / RE / 2) / (1 + np.sin(10000 / RE / 2))) * vc10, "0.702")
check("P9 speed 0 -> 10000 km [km/s]", np.sqrt(2 * np.sin(10000 / RE / 2) / (1 + np.sin(10000 / RE / 2))) * vc10, "7.082")

# ---------------------------------------------------------------- extra prose numbers
print("\n=== Numbers quoted in the prose of the solutions")
check("P1 rate ratio near/far", 4.672268 / 0.358066, "13.0")
check("P1 half-arc of the far single burn [deg]", 29.15 / 2, "14.6")
check("P2 LEO-GEO transfer speeds [km/s]", np.sqrt(MU * (2 / (RE + 300) - 2 / (RE + 300 + 42164))), "10.2")
check("P5 MOM r_p [km]", R_M + 421.7, "3817.9")
check("P5 MOM r_a [km]", R_M + 76993.6, "80389.8")
check("P8 site speed at 13.7 N [km/s]", 7.2921151e-5 * RE * np.cos(13.7 * DEG), "0.45", tol=0.005)
check("P9 Q_min at 90 deg", 2 * np.sin(np.pi / 4) / (1 + np.sin(np.pi / 4)), "0.828")
check("P1 v_c at apogee [km/s]", vc2, "3.8873")
check("P1 v_a [km/s]", va2, "2.5001")
check("P1 first burn N=3 [km/s]", 2 * s2 * e2 * np.sin(eta / 6), "0.618")
check("v_e at Isp 315 s [km/s]", 315 * G0, "3.089")
check("P2 max saving", 1 - 1 / np.sqrt(2), "0.293")
check("P6 3 R_J [km]", 3 * R_J, "214476")
check("P4 circle to 200000 km orbit [km/s]", 10.795029 - 7.754845, "3.040")

print(f"\n{npass} passed, {nfail} failed")
sys.exit(1 if nfail else 0)
