"""Checks every number and identity in the answers and solutions of ballistic-questions.qmd
(Ballistic Trajectories: Questions).

Each function below checks one group of questions. The labels it prints use the problem and question
numbers of the page. Run from the sfm-slides directory, or from anywhere:

    python3 codes/ballistic-questions-verify.py
"""
from _verify import check, truth, sym_zero, run

import sys

import os
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from _ballistic import *


def note_exercises():
    """Problems 1, 2, 3, 4, 5, 6, 11, 12, 7, 8, 13, 14 and 9, the exercises that used to end the ballistic note."""
    import sys
    import numpy as np
    import sympy as sp
    from scipy.integrate import solve_ivp
    sys.path.insert(0, "codes")
    D = np.pi / 180

    def integrate(r, v, gam):
        y0 = [r, 0, v * np.sin(gam), v * np.cos(gam)]
        f = lambda t, y: [y[2], y[3], -MU * y[0] / np.hypot(y[0], y[1]) ** 3, -MU * y[1] / np.hypot(y[0], y[1]) ** 3]
        ev = lambda t, y: np.hypot(y[0], y[1]) - r
        ev.terminal = True; ev.direction = -1
        sol = solve_ivp(f, [0, 1e6], y0, events=ev, rtol=1e-12, atol=1e-9, max_step=50)
        y = sol.y_events[0][0]
        return np.arctan2(y[1], y[0]) % (2 * np.pi), sol.t_events[0][0]
    vc = np.sqrt(MU / RE)                         # circular speed at the equatorial radius

    # exercises
    check("P1: Q for r = 1.1 R, v = 0.5 v_c", 0.25 * 1.1, 0.275, 1e-12)
    check("P1: psi_max [deg]", psi_max(0.275) / D, 18.35, 0.005); check("P1: ground range [km]", psi_max(0.275) * RE, 2042.3, 0.05)
    psiE2 = 9334.08 / RE
    check("P2: psi for 9334 km [deg]", psiE2 / D, 83.85, 0.005); check("P2: v_bo at r = R [km/s]", np.sqrt(Qmin(psiE2) * MU / RE), 7.0755, 5e-5)
    check("P2: Q_min", Qmin(psiE2), 0.8011, 5e-5)
    QE5 = 0.83 ** 2 * 1.06
    check("P5: Q = 0.83^2 * 1.06", QE5, 0.7302, 5e-5); check("P5: psi_max [deg]", psi_max(QE5) / D, 70.21, 0.005); check("P5: ground range [km]", psi_max(QE5) * RE, 7816, 1.0)
    psiE6 = 3333.6 / RE
    check("P6: psi [deg]", psiE6 / D, 29.95, 0.005); check("P6: v_bo / v_c", np.sqrt(Qmin(psiE6)), 0.6408, 5e-5); check("P6: v_bo [km/s]", np.sqrt(Qmin(psiE6)) * vc, 5.066, 5e-4)
    rE4 = 21.8e6 * 0.3048 / 1000; psiE4 = (7400 - 140 - 60) * NM / RE
    check("P4: r_bo [km]", rE4, 6644.6, 0.05); check("P4: psi [deg]", psiE4 / D, 119.78, 0.005)
    vE4 = np.sqrt(Qmin(psiE4) * MU / rE4)
    check("P4: v_bo [km/s]", vE4, 7.4597, 5e-4); check("P4: gamma [deg]", gamma_max_range(psiE4) / D, 15.05, 0.005)
    check("P4: t_ff [min]", tff(rE4, vE4, gamma_max_range(psiE4)) / 60, 40.11, 0.005)
    check("P3: eastward gain at 13.7 N [km/s]", site_speed(13.7 * D), 0.4519, 5e-5); check("P3: at 28.5 N [km/s]", site_speed(28.5 * D), 0.4087, 5e-5)
    check("P7: delta C = 1.852 km as an angle [arcsec]", 1.852 / RE / D * 3600, 59.9, 0.05)
    check("P2: gamma = 45 - psi/4 [deg]", gamma_max_range(psiE2) / D, 24.04, 0.005)
    # ------------------------------------------------------------------ Part 8: exercises 11-13 (mean of the two angles, low is faster, the 6000 km flight)
    print()
    g_, p_, Q_ = sp.symbols("gamma psi Q", positive=True)
    lhs = sp.sin(2 * ((sp.pi - p_) / 2 - g_) + p_ / 2) - sp.sin(2 * g_ + p_ / 2)
    check("P13: gamma' = (pi - psi)/2 - gamma satisfies eq-fpa whenever gamma does (sympy)", float(sp.simplify(sp.expand_trig(lhs)) != 0), 0, 0)
    okm = True
    for Qq in np.linspace(0.1, 0.99, 25):
        for frac in np.linspace(0.05, 0.98, 20):
            ps = frac * psi_max(Qq); gl_, gh_ = gammas_of(Qq, ps)
            okm = okm and abs((gl_ + gh_) / 2 - (np.pi / 4 - ps / 4)) < 1e-12
    truth("P13: (gamma_low + gamma_high)/2 = pi/4 - psi/4 on a grid of Q < 1 and psi < psi_max", okm)
    # P14: pi - E_bo = arctan(s/(1-Q)) for Q < 1, and t_ff increases with gamma at fixed Q < 1
    oke, okt = True, True
    for Qq in np.linspace(0.05, 0.99, 30):
        gg = np.linspace(1e-3, np.pi / 2 - 1e-3, 400)
        s_ = np.sqrt(Qq * (2 - Qq)) * np.sin(gg)
        oke = oke and np.allclose(np.pi - np.array([E_burnout(Qq, x) for x in gg]), np.arctan(s_ / (1 - Qq)), atol=1e-12)
        tt = np.array([tff_over_Pcs(Qq, x) for x in gg]); okt = okt and np.all(np.diff(tt) > 0)
        for frac in (0.2, 0.5, 0.9):
            a_, b_ = gammas_of(Qq, frac * psi_max(Qq)); okt = okt and tff_over_Pcs(Qq, a_) < tff_over_Pcs(Qq, b_)
    truth("P14: pi - E_bo = arctan(s/(1 - Q)) for Q < 1 (grid)", oke)
    truth("P14: t_ff/P_cs increases with gamma at fixed Q < 1 over the whole range, and t_low < t_high (grid)", okt)
    # integrate one pair to be sure the low one is faster, independent of eq-tff
    r13, v13 = RE + 300, 6.9
    Q13 = Q_of(r13, v13); ps13 = 6000 / RE
    gl13, gh13 = gammas_of(Q13, ps13)
    _, tl = integrate(r13, v13, gl13); _, th = integrate(r13, v13, gh13)
    truth("P14/13: numerical integration, low flight faster than high", tl < th)
    check("P9: r_bo [km]", r13, 6678.1, 0.05)
    check("P9: Q", Q13, 0.7977, 5e-5)
    check("P9: sin(psi_max/2)", Q13 / (2 - Q13), 0.6634, 5e-5)
    check("P9: psi_max [deg]", psi_max(Q13) / D, 83.12, 0.005)
    check("P9: gamma_max [deg]", 45 - psi_max(Q13) / D / 4, 24.22, 0.005)
    check("P9: max ground range [km]", psi_max(Q13) * RE, 9253, 0.5)
    check("P9: psi [deg]", ps13 / D, 53.90, 0.005)
    rhs13 = (2 - Q13) / Q13 * np.sin(ps13 / 2); A13 = np.arcsin(rhs13)
    check("P9: right side of eq-fpa", rhs13, 0.6831, 5e-5)
    check("P9: A [deg]", A13 / D, 43.09, 0.005)
    check("P9: gamma_low [deg]", gl13 / D, 8.07, 0.005)
    check("P9: (pi - psi)/2 [deg]", (180 - ps13 / D) / 2, 63.05, 0.005)
    check("P9: gamma_high by symmetry [deg]", (180 - ps13 / D) / 2 - gl13 / D, 54.98, 0.005)
    check("P9: gamma_high from the second root of eq-two [deg]", 0.5 * (np.pi - A13 - ps13 / 2) / D, 54.98, 0.005)
    for g13 in (gl13, gh13):
        check("P9: range equation returns psi [deg]", psi_of(Q13, g13) / D, 53.90, 0.005)
    check("P9: low perigee radius [km]", perigee_radius(Q13, gl13, r13), 4196, 0.5)
    P13 = 2 * np.pi * np.sqrt(r13 ** 3 / MU)
    check("P9: P_cs [min]", P13 / 60, 90.52, 0.005)
    for nm, g13, E_s, t_s, pg_s, mg_s, pv_s, mv_s, ha_s, ti in (("low", gl13, 145.81, 16.05, 4.763, 53.0, 1.074, 68.5, 535, tl), ("high", gh13, 104.16, 46.46, -1.409, -15.7, 0.3176, 20.3, 3770, th)):
        check(f"P9 {nm}: E_bo [deg]", E_burnout(Q13, g13) / D, E_s, 0.005)
        check(f"P9 {nm}: t_ff [min]", tff_over_Pcs(Q13, g13) * P13 / 60, t_s, 0.005)
        check(f"P9 {nm}: t_ff from the numerical integration [min]", ti / 60, t_s, 0.005)
        check(f"P9 {nm}: dpsi/dgamma", dpsi_dgamma(ps13, g13), pg_s, 5e-4)
        check(f"P9 {nm}: miss for +0.1 deg [km]", dpsi_dgamma(ps13, g13) * 0.1 * D * RE, mg_s, 0.05)
        check(f"P9 {nm}: dpsi/dv [rad per km/s]", dpsi_dv(r13, v13, ps13, g13), pv_s, 5e-4 if nm == "low" else 5e-5)
        check(f"P9 {nm}: miss for +10 m/s [km]", dpsi_dv(r13, v13, ps13, g13) * 0.010 * RE, mv_s, 0.05)
        check(f"P9 {nm}: apogee altitude [km]", r13 / (2 - Q13) * (1 + ecc(Q13, g13)) - RE, ha_s, 0.5)
    check("P9: 2 gamma_high [deg]", 2 * gh13 / D, 110, 0.5); check("P9: 2 gamma_low [deg]", 2 * gl13 / D, 16, 0.5)
    check("P9: about three times (gamma)", dpsi_dgamma(ps13, gl13) / -dpsi_dgamma(ps13, gh13), 3.4, 0.05)
    check("P9: about three times (v)", dpsi_dv(r13, v13, ps13, gl13) / dpsi_dv(r13, v13, ps13, gh13), 3.4, 0.05)

    # ---- worked solutions of Exercises 1-10
    print()
    from scipy.optimize import minimize_scalar as _ms
    _vc = np.sqrt(MU / RE)
    check("P1: sin(psi/2)", 0.275 / 1.725, 0.15942, 5e-6); check("P1: psi_max", psi_max(0.275) / D, 18.35, 0.005)
    check("P1: psi rad", psi_max(0.275), 0.32021, 5e-6); check("P1: km", psi_max(0.275) * RE, 2042, 0.5); check("P1: gamma", gamma_max_range(psi_max(0.275)) / D, 40.41, 0.005)
    _p2 = 9334 / RE
    check("P2: psi rad", _p2, 1.4634, 5e-5); check("P2: psi", _p2 / D, 83.85, 0.005); check("P2: sin", np.sin(_p2 / 2), 0.66815, 5e-5)
    check("P2: Qmin", Qmin(_p2), 0.8011, 5e-5); check("P2: sqrt", np.sqrt(Qmin(_p2)), 0.8950, 5e-5); check("P2: v", np.sqrt(Qmin(_p2)) * _vc, 7.0755, 5e-5)
    check("P2: gamma", gamma_max_range(_p2) / D, 24.04, 0.005)
    for _ph, _sv in ((0, 0.4651), (13.7, 0.4519), (28.5, 0.4087)):
        check(f"P3: saving at {_ph}", WE * RE * np.cos(_ph * D), _sv, 5e-5)
    check("P3: east-west difference", 2 * WE * RE * np.cos(28.5 * D), 0.817, 5e-4)
    check("P3: fractions", 0.4519 / 0.4651, 0.97, 0.005); check("  ", 0.4087 / 0.4651, 0.88, 0.005)
    _p4 = 7200 * NM / RE; _r4 = 6644.6; _Q4 = Qmin(_p4); _g4 = gamma_max_range(_p4); _v4 = np.sqrt(_Q4 * MU / _r4)
    check("P4: km", 7200 * NM, 13334.4, 0.05); check("P4: psi rad", _p4, 2.0906, 5e-5); check("P4: psi", _p4 / D, 119.78, 0.005)
    check("P4: sin", np.sin(_p4 / 2), 0.86509, 5e-5); check("P4: Q", _Q4, 0.92766, 5e-5); check("P4: v", _v4, 7.4598, 5e-5)
    check("P4: gamma", _g4 / D, 15.05, 0.005); check("P4: E_bo", E_burnout(_Q4, _g4) / D, 105.60, 0.005)
    check("P4: P_cs", 2 * np.pi * np.sqrt(_r4 ** 3 / MU) / 60, 89.84, 0.005); check("P4: t_ff", tff(_r4, _v4, _g4) / 60, 40.1, 0.05)
    check("P4: 96% of circular", np.sqrt(_Q4), 0.96, 0.005)
    _Q5 = 0.83 ** 2 * 1.06
    check("P5: Q", _Q5, 0.7302, 5e-5); check("P5: sin", _Q5 / (2 - _Q5), 0.57509, 5e-5); check("P5: psi", psi_max(_Q5) / D, 70.21, 0.005)
    check("P5: gamma", gamma_max_range(psi_max(_Q5)) / D, 27.45, 0.005); check("P5: psi rad", psi_max(_Q5), 1.22543, 5e-5); check("P5: km", psi_max(_Q5) * RE, 7816, 0.5)
    _opt = _ms(lambda g: -psi_of(_Q5, g), bounds=(0.01, 1.5), method="bounded", options={"xatol": 1e-12})
    check("P5: numerical gamma", _opt.x / D, 27.447, 5e-4); check("P5: numerical psi", psi_of(_Q5, _opt.x) / D, 70.212, 5e-4)
    check("P5: nm sphere radius [km]", NM * 60 * 180 / np.pi, 6367, 0.5); check("P5: in nm", 7816 / NM, 4220, 0.5)
    _p6 = 3334 / RE
    check("P6: psi rad", _p6, 0.52273, 5e-5); check("P6: psi", _p6 / D, 29.95, 0.005); check("P6: sin", np.sin(_p6 / 2), 0.25840, 5e-5)
    check("P6: Q", Qmin(_p6), 0.4107, 5e-5); check("P6: sqrt", np.sqrt(Qmin(_p6)), 0.6408, 5e-5); check("P6: v", np.sqrt(Qmin(_p6)) * _vc, 5.066, 5e-4)
    check("P6: gamma", gamma_max_range(_p6) / D, 37.51, 0.005); check("P6: ratios", 9334 / 3334, 2.8, 0.05); check("  ", 7.0755 / 5.066, 1.40, 0.005)
    _A, _ps = sp.symbols("A psi", positive=True)
    truth("P11: high - low = pi/2 - A", sp.simplify((sp.pi - _A - _ps / 2) / 2 - (_A - _ps / 2) / 2 - (sp.pi / 2 - _A)) == 0)
    _Q8 = 0.7; _p8 = psi_max(_Q8); _g8 = gamma_max_range(_p8)
    check("P12: angle at F' at maximum range [deg]", (np.pi - 2 * _g8 - _p8 / 2) / D, 90, 1e-9)
    check("P12: Q = 1 - e^2 at maximum range", 1 - ecc(_Q8, _g8) ** 2, _Q8, 1e-12)
    check("P12: sin(psi/2) = (1-e^2)/(1+e^2)", np.sin(_p8 / 2), (1 - ecc(_Q8, _g8) ** 2) / (1 + ecc(_Q8, _g8) ** 2), 1e-12)
    check("P7: dA [rad]", NM / RE, 2.904e-4, 5e-8); check("P7: dA [arcsec]", NM / RE / D * 3600, 59.9, 0.05)
    _r10, _v10 = 1.1 * RE, 0.905 * _vc; _Q10 = Q_of(_r10, _v10); _p10 = psi_of(_Q10, 30 * D)
    _sA = (2 - _Q10) / _Q10 * np.sin(_p10 / 2); _gl = 0.5 * (np.arcsin(_sA) - _p10 / 2)
    check("P8: Q", _Q10, 0.9009, 5e-5); check("P8: psi", _p10 / D, 100.53, 0.005); check("P8: sin A", _sA, 0.93811, 5e-5)
    check("P8: A", np.degrees(np.arcsin(_sA)), 69.74, 0.005); check("P8: gamma_low", _gl / D, 9.74, 0.005)
    check("P8: sin 2gamma_low", np.sin(2 * _gl), 0.33338, 5e-5); check("P8: sin(psi + 2 gamma_low)", np.sin(_p10 + 2 * _gl), 0.8660, 5e-5)
    _cg, _cr, _cv = dpsi_dgamma(_p10, _gl), dpsi_dr(_r10, _v10, _p10, _gl), dpsi_dv(_r10, _v10, _p10, _gl)
    check("P8: dpsi/dgamma", _cg, 3.195, 5e-4); check("P8: dpsi/dr", _cr, 1.1225e-3, 5e-7); check("P8: dpsi/dv", _cv, 2.2015, 5e-4)
    _c = (_cg * -1e-4 * RE, _cr * 3.19 * RE, _cv * -0.395e-3 * RE)
    check("P8: gamma term", _c[0], -2.04, 0.005); check("P8: r term", _c[1], 22.84, 0.005); check("P8: v term", _c[2], -5.55, 0.005)
    check("P8: linear miss", sum(_c), 15.3, 0.05)
    check("P8: exact miss", (psi_of(Q_of(_r10 + 3.19, _v10 - 0.395e-3), _gl - 1e-4) - _p10) * RE, 15.27, 0.005)
    check("P8: 2.6 times the high-branch r coefficient", _cr / dpsi_dr(_r10, _v10, _p10, 30 * D), 2.6, 0.005)


def test_flight():
    """Problem 10, a ballistic test flight."""
    import numpy as np

    # ---------------------------------------------------------------- constants (the handout's table)
    from orbit.constants import MU_EARTH as MU, R_EARTH as RE

    deg = np.degrees

    # ================================================================ Problem 11: a ballistic test flight
    print("\n--- Problem 10")
    rb11, v11 = RE + 200, 5.2
    Q = v11**2*rb11/MU
    check("P10 Q", Q, "0.44624")
    spm = Q/(2 - Q); psim = 2*np.arcsin(spm)
    check("P10 sin(psi_max/2)", spm, "0.28720")
    check("P10 psi_max deg", deg(psim), "33.38"); check("P10 psi_max rad", psim, "0.58261")
    check("P10 max range km", RE*psim, "3716")
    check("P10 gamma for max range", deg((np.pi - psim)/4), "36.65")
    psi = 3000/RE
    check("P10 psi rad", psi, "0.470357"); check("P10 psi deg", deg(psi), "26.949")
    rhs = (2 - Q)/Q*np.sin(psi/2)
    check("P10 rhs", rhs, "0.81133")
    x = np.arcsin(rhs)
    check("P10 arcsin", deg(x), "54.23")
    gl, gh = (x - psi/2)/2, (np.pi - x - psi/2)/2
    check("P10 gamma low", deg(gl), "20.38"); check("P10 gamma high", deg(gh), "56.15")
    a11 = rb11/(2 - Q)
    check("P10 a", a11, "4233.70")
    Pcs = 2*np.pi*np.sqrt(rb11**3/MU)
    check("P10 P_cs min", Pcs/60, "88.49")
    for name, g, qs in (("low", gl, ("0.62506", "501.9", "152.37", "11.23", "1.829")),
                        ("high", gh, ("0.88593", "1606.3", "128.69", "23.08", "1.290"))):
        e = np.sqrt(1 + Q*(Q - 2)*np.cos(g)**2)
        Eb = np.arccos((Q - 1)/e)
        tff = Pcs*(np.pi - Eb + np.sqrt(Q*(2 - Q))*np.sin(g))/(np.pi*(2 - Q)**1.5)
        tff2 = 2*(np.pi - Eb + e*np.sin(Eb))/np.sqrt(MU/a11**3)
        dps = 8*MU*np.sin(psi/2)**2/(v11**3*rb11*np.sin(2*g))
        check(f"P10 {name} e", e, qs[0]); check(f"P10 {name} apogee altitude", a11*(1 + e) - RE, qs[1])
        check(f"P10 {name} E_bo", deg(Eb), qs[2]); check(f"P10 {name} tff min", tff/60, qs[3])
        check(f"P10 {name} tff by Kepler", tff2/60, qs[3])
        check(f"P10 {name} range error km per m/s", RE*dps*1e-3, qs[4])
        tanh = Q*np.sin(g)*np.cos(g)/(1 - Q*np.cos(g)**2)
        check(f"P10 {name} range equation returns psi", deg(2*np.arctan(tanh)), "26.949")
    check("P10 low dpsi/dv rad per km/s", 8*MU*np.sin(psi/2)**2/(v11**3*rb11*np.sin(2*gl)), "0.2868")
    check("P10 high dpsi/dv rad per km/s", 8*MU*np.sin(psi/2)**2/(v11**3*rb11*np.sin(2*gh)), "0.2023")
    Qmin = 2*np.sin(psi/2)/(1 + np.sin(psi/2))
    check("P10 Qmin", Qmin, "0.37796"); check("P10 vmin", np.sqrt(Qmin*MU/rb11), "4.7857")
    check("P10 gamma at vmin", deg((np.pi - psi)/4), "38.26")
    check("P10 speed margin m/s", (v11 - np.sqrt(Qmin*MU/rb11))*1e3, "414", tol=0.5)


def stage_and_speed():
    """Problems 15 and 16, where a spent stage comes down, and what a little more speed buys."""
    import numpy as np
    import sympy as sp

    # ---------------------------------------------------------------- constants
    from orbit.constants import MU_EARTH as MU, R_EARTH as RE

    DEG = np.pi / 180

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

    # =================================================================== P9
    print("\n=== Problem 16: what a little more speed buys")
    psm = 2 * sp.asin(Qs / (2 - Qs))
    dpsi = sp.simplify(sp.diff(psm, Qs))
    truth("P16 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("P16 dQmin/ds = 2/(1+s)^2", sp.diff(Qmin, s_) - 2 / (1 + s_) ** 2)
    r10 = RE + 200
    vc10 = np.sqrt(MU / r10)
    check("P16 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"P16 Q={Qv} v [km/s]", vv_, q_v)
        check(f"P16 Q={Qv} psi_max [deg]", pm / DEG, q_psi)
        check(f"P16 Q={Qv} range [km]", pm * RE, q_L)
        check(f"P16 Q={Qv} +1% exact [km]", (pm2 - pm) * RE, q_dL)
        check(f"P16 Q={Qv} +1% linear [km]", lin, q_lin)
    check("P16 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"P16 L={L} Q_min", Qm, q_Q)
        check(f"P16 L={L} v/v_c", np.sqrt(Qm), q_ratio)
        check(f"P16 L={L} v [km/s]", np.sqrt(Qm) * vc10, q_v)
        check(f"P16 L={L} gamma [deg]", 45 - ps / DEG / 4, q_g)
    check("P16 half way round [km]", np.pi * RE, "20038")
    check("P16 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("P16 speed 0 -> 10000 km [km/s]", np.sqrt(2 * np.sin(10000 / RE / 2) / (1 + np.sin(10000 / RE / 2))) * vc10, "7.082")

    check("P15 site speed at 13.7 N [km/s]", 7.2921151e-5 * RE * np.cos(13.7 * DEG), "0.45", tol=0.005)
    check("P16 Q_min at 90 deg", 2 * np.sin(np.pi / 4) / (1 + np.sin(np.pi / 4)), "0.828")


BLOCKS = [note_exercises, test_flight, stage_and_speed]


if __name__ == "__main__":
    run(BLOCKS)
