"""Checks every number and identity in the answers and solutions of two-body-questions.qmd
(The Two-body Problem: 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/two-body-questions-verify.py
"""
from _verify import check, truth, Objective, run


def objective():
    """The 48 objective questions: numbering, options and answer key, and every number in an answer, recomputed and found in the option the page marks as correct."""
    import numpy as np
    from scipy.optimize import brentq

    # data, as in the page's data box
    mu = 398600.0

    num = Objective("two-body-questions.qmd", 48).num

    num(8, 2 * np.pi * np.sqrt(6678 ** 3 / mu) / 60, "90.5")
    num(9, np.sqrt(mu / 7000), "7.55")
    num(16, (mu * (23.934 * 3600) ** 2 / (4 * np.pi ** 2)) ** (1 / 3), "42\\,164", tol=1)
    truth("Q16  distractor 42 241 km is the 24 h radius",
          abs((mu * (24 * 3600) ** 2 / (4 * np.pi ** 2)) ** (1 / 3) - 42241) < 1)
    num(19, 1.5 / 0.5, "3")
    num(22, np.sqrt(2 * mu * 14000 / (7000 * 21000)), "8.71")
    truth("Q23  gamma at L is arctan(0.5) = 26.6 deg", abs(np.degrees(np.arctan(0.5)) - 26.57) < 0.01)
    num(23, np.degrees(np.arcsin(0.5)), "30^\\circ", tol=1e-9)
    num(25, np.sqrt(144 - 2 * mu / 7000), "5.49")
    num(26, np.degrees(2 * np.arcsin(0.5)), "60^\\circ", tol=1e-9)
    num(27, (1 / np.sqrt(1 + 1 / 81.3) - 1) * 100, "-0.6")
    num(28, np.sqrt(1 + 2 * (-20) * 60000 ** 2 / mu ** 2), "0.31")
    num(29, 1 / (2 / 8000 - 64 / mu), "11\\,180", tol=5)
    num(31, 1 + 7000 * 9 / mu, "1.16")
    e = 0.5
    E = 2 * np.arctan(np.sqrt((1 - e) / (1 + e)))
    num(35, (E - e * np.sin(E)) / (2 * np.pi), "0.098")
    num(36, 0.5 - e / np.pi, "0.34")
    nu = 7000 * 8.266 ** 2 / mu
    truth("Q37  r v^2/mu = 1.2", abs(nu - 1.2) < 1e-3)
    num(37, np.sqrt(1 - 1.2 * 0.8 * np.cos(np.radians(10)) ** 2), "0.26")
    num(38, 1 + 0.6 ** 2 / 2, "1.18")
    E1 = 1 + 0.1 * np.sin(1) / (1 - 0.1 * np.cos(1))
    num(39, E1, "1.0890")
    truth("Q39  converged root 1.0886", abs(brentq(lambda x: x - 0.1 * np.sin(x) - 1, 0, 3) - 1.0886) < 5e-5)
    num(41, 27.32 / (4 * np.sqrt(2)), "4.8")
    num(42, np.degrees(np.arccos(-1 / np.sqrt(2))), "135^\\circ", tol=1e-9)
    num(43, np.degrees(np.arccos(-0.8)), "143.1")
    num(44, 7000 * np.sqrt(1 + 2 * mu / (7000 * 9)), "25\\,900", tol=50)
    num(46, (2 / 3) * 14000 ** 1.5 / np.sqrt(mu) / 60, "29.2")


def note_exercises():
    """Problems 1, 2, 3, 15, 4, 5, 6 and 7, the exercises that used to end the two-body note."""
    import numpy as np
    import sympy as sp

    ok = lambda label, cond: print(f"  [{'ok' if cond else 'FAIL'}] {label}")
    close = lambda x, y, tol: abs(x - y) <= tol
    from orbit.constants import MU_EARTH as MU_E, MU_SUN as MU_S, AU

    ok(f"P4: fall into the Sun from 1 AU in {0.5**1.5/2*365.25:.1f} days", close(0.5**1.5/2*365.25, 64.6, 0.05))
    _rs = 5.2026*AU/1048.6
    ok(f"P1: the Sun's wobble radius {_rs:.0f} km = {_rs/6.96e5:.2f} R_sun, speed {13.06/1048.6*1000:.1f} m/s",
       close(_rs/6.96e5, 1.07, 0.01) and close(13.06/1048.6*1000, 12.5, 0.05))
    print("Worked solutions of Exercises 1-8")
    ok(f"P1: r_sun {_rs:.0f} km (742200), v {13.06e3/1048.6:.1f} m/s", close(_rs, 742200, 50) and close(13.06e3/1048.6, 12.5, 0.05))
    _mu = MU_E; _r2 = np.array([7000.0, 0, 0]); _v2 = np.array([1.0, 7.5, 1.0])
    _h2 = np.cross(_r2, _v2); _e2 = ((_v2 @ _v2 - _mu/7000)*_r2 - (_r2 @ _v2)*_v2)/_mu; _eps2 = _v2 @ _v2/2 - _mu/7000
    ok(f"P2: h {_h2}, |h| {np.linalg.norm(_h2):.1f}", np.allclose(_h2, [0, -7000, 52500]) and close(np.linalg.norm(_h2), 52964.6, 0.05))
    ok(f"P2: mu/r {_mu/7000:.4f} (56.9429)", close(_mu/7000, 56.9429, 5e-5))
    ok(f"P2: e {np.round(_e2, 6)}, |e| {np.linalg.norm(_e2):.5f}", np.allclose(_e2, [0.005393, -0.131711, -0.017561], atol=6e-7) and close(np.linalg.norm(_e2), 0.13299, 5e-6))
    ok(f"P2: eps {_eps2:.4f}, a {-_mu/(2*_eps2):.2f}, p {np.linalg.norm(_h2)**2/_mu:.2f}",
       close(_eps2, -27.8179, 5e-5) and close(-_mu/(2*_eps2), 7164.45, 0.005) and close(np.linalg.norm(_h2)**2/_mu, 7037.75, 0.005))
    _cf = _e2 @ _r2/(np.linalg.norm(_e2)*7000)
    ok(f"P2: cos f {_cf:.5f}, f {np.degrees(np.arccos(_cf)):.2f}", close(_cf, 0.04055, 5e-6) and close(np.degrees(np.arccos(_cf)), 87.68, 0.005))
    ok(f"P2: Casimir h.e = {_h2 @ _e2:.1e}; mu^2(e^2-1) = {_mu**2*(_e2 @ _e2 - 1):.4e} = 2 eps h^2 = {2*_eps2*(_h2 @ _h2):.4e}",
       abs(_h2 @ _e2) < 1e-9 and close(_mu**2*(_e2 @ _e2 - 1), -1.5607e11, 5e6) and close(2*_eps2*(_h2 @ _h2), -1.5607e11, 5e6))
    _R = 6378.137; _eps3 = 32 - _mu/_R; _a3 = -_mu/(2*_eps3)
    ok(f"P3: mu/R {_mu/_R:.3f} (62.495), eps {_eps3:.3f}, a {_a3:.1f}", close(_mu/_R, 62.495, 5e-4) and close(_eps3, -30.495, 5e-4) and close(_a3, 6535.5, 0.05))
    for _g, _hh, _pp, _ee, _rp, _rf in ((45, 36080, 3265.9, 0.7073, 1912.9, 11158), (0, 51025, 6531.8, 0.0241, 6378.1, 6693.0)):
        _hc = _R*8*np.cos(np.radians(_g)); _pc = _hc**2/_mu; _ec = np.sqrt(1 - _pc/_a3)
        ok(f"P3: gamma {_g}: h {_hc:.0f}, p {_pc:.1f}, e {_ec:.4f}, r_p {_a3*(1-_ec):.1f}, far {_a3*(1+_ec):.1f}",
           close(_hc, _hh, 0.5) and close(_pc, _pp, 0.05) and close(_ec, _ee, 5e-5) and close(_a3*(1 - _ec), _rp, 0.05) and close(_a3*(1 + _ec), _rf, 0.5))
    ok(f"P3: vertical apex 2a {2*_a3:.0f} (13071), v_c {np.sqrt(_mu/_R):.3f} (7.905), horizontal apex altitude {2*_a3 - 2*_R:.0f} (315)",
       close(2*_a3, 13071, 0.5) and close(np.sqrt(_mu/_R), 7.905, 5e-4) and close(2*_a3 - 2*_R, 315, 0.5))
    _rp_, _ra_, _m = sp.symbols("r_p r_a mu", positive=True)
    _hsq = 2*_m*_rp_*_ra_/(_rp_ + _ra_)
    ok("P15: h^2 from energy + momentum satisfies the energy equation", sp.simplify(_hsq/_rp_**2/2 - _m/_rp_ - (_hsq/_ra_**2/2 - _m/_ra_)) == 0)
    ok("P15: v_p v_a = mu/a with a = (r_p + r_a)/2", sp.simplify(_hsq/(_rp_*_ra_) - _m/((_rp_ + _ra_)/2)) == 0)
    _t5 = np.pi*np.sqrt((0.5*AU)**3/MU_S)/86400
    ok(f"P4: fall time {_t5:.1f} d (64.6), ratio {_t5/365.25:.4f} = 1/(4 sqrt 2)", close(_t5, 64.6, 0.05) and close(0.5**1.5, 0.35355, 5e-6) and close(1/(4*np.sqrt(2)), 0.1768, 5e-5))
    def _newt(E, M=0.05, e=0.99, n=9):
        out = [E]
        for _k in range(n):
            E = E - (E - e*np.sin(E) - M)/(1 - e*np.cos(E)); out.append(E)
        return out
    _A, _B = _newt(0.05), _newt(np.pi)
    _tA = [0.050000, 4.453160, 0.177995, 2.022329, 1.267049, 0.880102, 0.698660, 0.649478, 0.645910]
    _tB = [3.141593, 1.588029, 1.049047, 0.771172, 0.663733, 0.646329, 0.645892, 0.645891, 0.645891]
    ok("P5: both columns of the Newton table", np.allclose(_A[:9], _tA, atol=6e-7) and np.allclose(_B[:9], _tB, atol=6e-7))
    ok(f"P5: slope at M {1 - 0.99*np.cos(0.05):.4f} (0.0112)", close(1 - 0.99*np.cos(0.05), 0.0112, 5e-5))
    for _rp7, _f, _D, _q, _sc, _days in ((0.1, 143.13, 3.0, 12.0, 2.247e5, 62.4), (0.9, 36.87, 1/3, 0.3457, 6.066e6, 48.5)):
        _ff = np.arccos(2*_rp7 - 1); _DD = np.tan(_ff/2); _s = np.sqrt(2*(_rp7*AU)**3/MU_S)
        _tt = 2*_s*(_DD + _DD**3/3)/86400
        ok(f"P6: r_p {_rp7}: f {np.degrees(_ff):.2f}, D {_DD:.4f}, scale {_s:.4g}, days {_tt:.1f}",
           close(np.degrees(_ff), _f, 0.005) and close(_DD, _D, 5e-5) and close(_DD + _DD**3/3, _q, 5e-5) and close(_s/_sc, 1, 1e-3) and close(_tt, _days, 0.05))
    _e8 = 1 + 3590*2.6**2/42828; _A8 = 42828/2.6**2; _b8 = _A8*np.sqrt(_e8**2 - 1)
    ok(f"P7: e {_e8:.4f} (1.5666), delta {2*np.degrees(np.arcsin(1/_e8)):.1f} (79.3), |a| {_A8:.1f} (6335.5), Delta {_b8:.0f} (7640)",
       close(_e8, 1.5666, 5e-5) and close(2*np.degrees(np.arcsin(1/_e8)), 79.3, 0.05) and close(_A8, 6335.5, 0.05) and close(_b8, 7640, 0.5))
    ok("P7: same Delta from h = r_p v_p", close(3590*np.sqrt(2.6**2 + 2*42828/3590)/2.6, _b8, 1e-6))


def tutorial():
    """Problems 9, 17 and 10, the debris, the Sun's gravity well, and one ellipse in full."""
    import numpy as np
    from scipy.integrate import quad

    ok = lambda label, cond: print(f"  [{'ok' if cond else 'FAIL'}] {label}")
    close = lambda x, y, tol: abs(x - y) <= tol
    d2r = np.pi/180

    print("Problem 9")
    mu = 398600.44
    r = np.array([10000.0, 0, 0]); v = np.array([0, 5.15494, 0])
    h = np.cross(r, v); hn = np.linalg.norm(h)
    eps = v @ v/2 - mu/10000
    a = -mu/(2*eps)
    e = np.sqrt(1 + 2*eps*hn**2/mu**2)
    ok(f"h = {hn:.1f}, v^2 = {v @ v:.4f}, eps = {eps:.4f}, a = {a:.1f}, e = {e:.4f}", close(hn, 51549.4, 0.05) and close(v @ v, 26.5734, 1e-4) and close(eps, -26.5734, 1e-4) and close(a, 7500, 0.1) and close(e, 1/3, 1e-4))
    rp = a*(1 - e); p = hn**2/mu
    ok(f"r_p = {rp:.1f}, p = {p:.1f}", close(rp, 5000, 0.5) and close(p, 6666.7, 0.05))
    RE5 = 6378.0
    cf = (p/RE5 - 1)/e
    fimp = np.degrees(np.arccos(cf))
    vimp = np.sqrt(mu*(2/RE5 - 1/a))
    gimp = np.degrees(np.arctan2(e*np.sin(-fimp*d2r), 1 + e*cf))
    print(f"     impact: cos f = {cf:.4f}, f = +-{fimp:.1f} deg, v = {vimp:.2f} km/s, gamma = {gimp:.1f} deg")
    ok("impact at f = 277.8 deg (i.e. -82.2), v = 8.48 km/s (the deck had 122 deg and 9.7 km/s)",
       close(cf, 0.1358, 1e-4) and close(fimp, 82.2, 0.05) and close(vimp, 8.48, 0.005))
    ok(f"impact flight path angle {gimp:.1f} deg (descending)", close(gimp, -17.5, 0.05))
    ok("  e sin f = -0.3302, 1 + e cos f = 1.0453, tan gamma = -0.3159",
       close(e*np.sin(-fimp*d2r), -0.3302, 5e-5) and close(1 + e*cf, 1.0453, 5e-5) and close(np.tan(np.radians(gimp)), -0.3159, 5e-5))
    ok(f"dips {RE5 - rp:.0f} km below the surface", close(RE5 - rp, 1378, 0.5))

    print("Problem 17 (Sun)")
    muS_km, AU, RS = 1.3271e11, 1.496e8, 6.957e5
    PhiS, PhiE = -muS_km/RS, -muS_km/AU
    ok(f"Phi(R_S) = {PhiS:.4g}, Phi(1 AU) = {PhiE:.1f}, ratio {PhiS/PhiE:.0f}", close(PhiS, -1.908e5, 0.001e5) and close(PhiE, -887.1, 0.05) and close(PhiS/PhiE, 215, 0.5))
    ok(f"fraction of the climb done at 1 AU: {100*(1 - PhiE/PhiS):.1f}%", close(100*(1 - PhiE/PhiS), 99.5, 0.05))
    ok(f"v_esc surface {np.sqrt(-2*PhiS):.1f}, at 1 AU {np.sqrt(-2*PhiE):.1f}, v_E {np.sqrt(-PhiE):.1f}",
       close(np.sqrt(-2*PhiS), 617.7, 0.1) and close(np.sqrt(-2*PhiE), 42.1, 0.05) and close(np.sqrt(-PhiE), 29.8, 0.05))
    vE = np.sqrt(-PhiE)
    ok(f"(sqrt2 - 1) v_E = {(np.sqrt(2) - 1)*vE:.1f}", close((np.sqrt(2) - 1)*vE, 12.3, 0.05))
    va = np.sqrt(2*muS_km*RS/(AU*(AU + RS)))
    ok(f"graze: v_a = {va:.2f}, dv = {vE - va:.1f}; ratio to escape {(vE - va)/((np.sqrt(2) - 1)*vE):.2f}, radial fall {vE/((np.sqrt(2)-1)*vE):.1f}",
       close(va, 2.87, 0.005) and close(vE - va, 26.9, 0.05) and close(vE/((np.sqrt(2) - 1)*vE), 2.4, 0.05))
    r7, v7 = AU, 10.0
    eps7 = v7**2/2 - muS_km/r7
    h7 = r7*v7
    a7 = -muS_km/(2*eps7)
    e7 = np.sqrt(1 + 2*eps7*h7**2/muS_km**2)
    rp7 = a7*(1 - e7); p7 = h7**2/muS_km
    ok(f"(h) eps {eps7:.1f}, h {h7:.3e}, a {a7:.3e} = {a7/AU:.2f} AU, e {e7:.3f}, r_p {rp7:.3e} = {rp7/AU:.3f} AU = {rp7/RS:.1f} R_S",
       close(eps7, -837.1, 0.05) and close(a7, 7.93e7, 0.005e7) and close(a7/AU, 0.53, 0.005) and close(e7, 0.887, 0.0005)
       and close(rp7, 8.94e6, 0.005e6) and close(rp7/AU, 0.060, 0.0005) and close(rp7/RS, 12.8, 0.05))
    ok(f"  2 eps h^2/mu^2 = {2*eps7*h7**2/muS_km**2:.4f}, p = {p7:.3e}, p/(1+e) = {p7/(1 + e7):.3e}", close(2*eps7*h7**2/muS_km**2, -0.2128, 1e-4) and close(p7, 1.686e7, 0.001e7) and close(p7/(1 + e7), rp7, 1))
    ok(f"  burn {vE - 10:.1f} km/s, two-thirds of v_E ({(vE - 10)/vE:.2f})", close(vE - 10, 19.8, 0.05) and close((vE - 10)/vE, 0.66, 0.01))

    print("Problem 10")
    mu8, RE8 = 398600.0, 6378.0
    rp8, ra8 = RE8 + 400, RE8 + 4000
    e8 = (ra8 - rp8)/(ra8 + rp8); a8 = (rp8 + ra8)/2; p8 = 2*rp8*ra8/(rp8 + ra8); h8 = np.sqrt(mu8*p8)
    ok(f"e {e8:.5f}, p {p8:.2f}, h {h8:.1f}", close(e8, 0.20984, 1e-5) and close(p8, 8200.29, 0.01) and close(h8, 57172, 1))
    vp8, va8 = h8/rp8, h8/ra8
    ok(f"v_p {vp8:.3f}, v_a {va8:.3f}, v_p v_a {vp8*va8:.2f} = mu/a {mu8/a8:.2f}", close(vp8, 8.435, 0.001) and close(va8, 5.509, 0.001) and close(vp8*va8, 46.47, 0.01) and close(mu8/a8, 46.47, 0.01))
    T8 = 2*np.pi*np.sqrt(a8**3/mu8)
    ok(f"a {a8}, T {T8:.1f} s = {T8/60:.2f} min = {T8/3600:.3f} h", close(a8, 8578, 1e-9) and close(T8, 7906.6, 0.1) and close(T8/60, 131.78, 0.01) and close(T8/3600, 2.196, 0.001))
    I, _ = quad(lambda f: 1/(1 + e8*np.cos(f)), 0, 2*np.pi)
    rbar = p8*I/(2*np.pi)
    ok(f"true-anomaly average r = {rbar:.2f} = b = {a8*np.sqrt(1 - e8**2):.2f} = sqrt(r_p r_a) = {np.sqrt(rp8*ra8):.2f}; alt {rbar - RE8:.0f}",
       close(rbar, 8387.02, 0.01) and close(a8*np.sqrt(1 - e8**2), rbar, 1e-6) and close(np.sqrt(rp8*ra8), rbar, 1e-6) and close(rbar - RE8, 2009, 0.5))
    tbar = quad(lambda M: a8*(1 - e8*np.cos(__import__('scipy.optimize', fromlist=['brentq']).brentq(lambda E: E - e8*np.sin(E) - M, 0, 2*np.pi))), 0, 2*np.pi)[0]/(2*np.pi)
    ok(f"time-averaged r = {tbar:.1f} = a(1 + e^2/2) = {a8*(1 + e8**2/2):.1f}", close(tbar, 8766.9, 0.1) and close(a8*(1 + e8**2/2), 8766.9, 0.1))
    ok("time average via E: (a/2pi) int (1 - e cos E)^2 dE = a(1 + e^2/2)",
       close(quad(lambda E: a8*(1 - e8*np.cos(E))**2, 0, 2*np.pi)[0]/(2*np.pi), a8*(1 + e8**2/2), 1e-6))
    cf8 = (p8/rbar - 1)/e8
    f8 = np.degrees(np.arccos(cf8))
    ok(f"cos f = {cf8:.5f}, f = {f8:.2f}, {360 - f8:.2f}", close(cf8, -0.10610, 1e-5) and close(f8, 96.09, 0.01) and close(360 - f8, 263.91, 0.01))
    v8 = np.sqrt(mu8*(2/rbar - 1/a8))
    tg = e8*np.sin(f8*d2r)/(1 + e8*np.cos(f8*d2r))
    ok(f"v {v8:.3f}, tan gamma {tg:.5f}, gamma {np.degrees(np.arctan(tg)):.2f}", close(v8, 6.970, 0.001) and close(tg, 0.21341, 1e-5) and close(np.degrees(np.arctan(tg)), 12.05, 0.005))
    fg = np.degrees(np.arccos(-e8))
    ok(f"gamma_max at f = {fg:.2f} ({360 - fg:.2f}), gamma_max = {np.degrees(np.arcsin(e8)):.2f}", close(fg, 102.11, 0.005) and close(360 - fg, 257.89, 0.005) and close(np.degrees(np.arcsin(e8)), 12.11, 0.005))


def ellipse_and_hyperbola():
    """Problems 13 and 14, an elliptic orbit with Kepler's equation, and Apophis."""
    import numpy as np

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

    R_GEO = 42164.0

    deg = np.degrees

    def vis(mu, r, a):
        return np.sqrt(mu*(2/r - 1/a))

    # ================================================================ Problem 2: an Earth orbit before the Moon
    print("\n--- Problem 13")
    rp, ra = RE + 200, RE + 71000
    a = (rp + ra)/2
    e = (ra - rp)/(ra + rp)
    p = a*(1 - e**2)
    h = np.sqrt(MU*p)
    T = 2*np.pi*np.sqrt(a**3/MU)
    check("P13 rp", rp, "6578.137"); check("P13 ra", ra, "77 378.137")
    check("P13 a", a, "41 978.137"); check("P13 e", e, "0.84330")
    check("P13 p", p, "12 125.45"); check("P13 h", h, "69 521.3")
    check("P13 energy", -MU/(2*a), "-4.7477")
    check("P13 T, s", T, "85 594", tol=0.5); check("P13 T, h", T/3600, "23.776")
    check("P13 vp", h/rp, "10.5685"); check("P13 va", h/ra, "0.8985")
    check("P13 vp/va", (h/rp)/(h/ra), "11.76")
    r = R_GEO
    cf = (p/r - 1)/e
    f = np.arccos(cf)
    check("P13 cos f", cf, "-0.84481"); check("P13 f deg", deg(f), "147.651"); check("P13 f rad", f, "2.57700")
    E = 2*np.arctan(np.sqrt((1 - e)/(1 + e))*np.tan(f/2))
    check("P13 tan(f/2)", np.tan(f/2), "3.4478")
    check("P13 sqrt((1-e)/(1+e))", np.sqrt((1 - e)/(1 + e)), "0.29157")
    check("P13 E rad", E, "1.57605")
    check("P13 cos E from r", (1 - r/a)/e, "-0.00525", tol=5e-6)
    M = E - e*np.sin(E)
    check("P13 e sin E", e*np.sin(E), "0.84328")
    check("P13 M rad", M, "0.73276")
    n = 2*np.pi/T
    check("P13 n rad/s (x1e-5)", n*1e5, "7.3406")
    t = M/n
    check("P13 t, s", t, "9982", tol=0.5); check("P13 t, h", t/3600, "2.773"); check("P13 t, min", t/60, "166.4")
    check("P13 speed at GEO radius", vis(MU, r, a), "3.0679")
    check("P13 gamma", deg(np.arctan(e*np.sin(f)/(1 + e*cf))), "57.49")
    check("P13 hours inside GEO radius", 2*t/3600, "5.546"); check("P13 fraction %", 100*2*t/T, "23.3")
    check("P13 v_GEO circular", np.sqrt(MU/R_GEO), "3.0747")

    # ================================================================ Problem 3: Apophis
    print("\n--- Problem 14")
    rp3, vinf3 = 38012.0, 5.84
    a3 = MU/vinf3**2
    e3 = 1 + rp3*vinf3**2/MU
    vp3 = np.sqrt(vinf3**2 + 2*MU/rp3)
    check("P14 |a|", a3, "11 687"); check("P14 e", e3, "4.2524")
    check("P14 vesc at rp", np.sqrt(2*MU/rp3), "4.5796")
    check("P14 vp", vp3, "7.4215")
    delta = 2*np.arcsin(1/e3)
    check("P14 1/e", 1/e3, "0.23516"); check("P14 turning angle deg", deg(delta), "27.20")
    check("P14 f_inf deg", deg(np.arccos(-1/e3)), "103.60")
    b = rp3*np.sqrt(1 + 2*MU/(rp3*vinf3**2))
    check("P14 b", b, "48 306"); check("P14 b via a sqrt(e^2-1)", a3*np.sqrt(e3**2 - 1), "48 306")
    check("P14 altitude of closest approach", rp3 - RE, "31 634")
    check("P14 inside GEO by", R_GEO - rp3, "4152")

    check("P14 gravity bends by km", b - rp3, "10 000", tol=800)


def assignment_one():
    """Problems 18, 19, 11 and 12, the linear force law, the circular speed on an ellipse, a circular-orbit test, and elements from tracking data."""
    import numpy as np
    import sympy as sp

    ok = lambda label, cond: print(f"  [{'ok' if cond else 'FAIL'}] {label}")
    close = lambda x, y, tol: abs(x - y) <= tol

    print("A force that grows with distance")
    t, a, b, W = sp.symbols("t a b Omega", positive=True)
    x, y = a * sp.cos(W * t), b * sp.sin(W * t)
    ok("x = a cos, y = b sin solve r'' = -Omega^2 r",
       sp.simplify(sp.diff(x, t, 2) + W**2 * x) == 0 and sp.simplify(sp.diff(y, t, 2) + W**2 * y) == 0)
    ok("h = x y' - y x' = a b Omega", sp.simplify(x * sp.diff(y, t) - y * sp.diff(x, t) - a * b * W) == 0)
    eps = (sp.diff(x, t)**2 + sp.diff(y, t)**2) / 2 + W**2 * (x**2 + y**2) / 2
    ok("energy = Omega^2 (a^2 + b^2)/2", sp.simplify(eps - W**2 * (a**2 + b**2) / 2) == 0)
    th = sp.symbols("theta")
    r2 = 1 / (sp.cos(th)**2 / a**2 + sp.sin(th)**2 / b**2)
    xx, yy = sp.sqrt(r2) * sp.cos(th), sp.sqrt(r2) * sp.sin(th)
    ok("polar form 1/r^2 = cos^2/a^2 + sin^2/b^2 lies on the ellipse", sp.simplify(xx**2 / a**2 + yy**2 / b**2 - 1) == 0)
    m1, m2, k = sp.symbols("m1 m2 k", positive=True)
    ok("relative equation: Omega^2 = k (m1 + m2)", sp.simplify(k * m2 + k * m1 - k * (m1 + m2)) == 0)

    print("Where the speed equals the circular speed")
    mu, aa, e, r = sp.symbols("mu a e r", positive=True)
    ok("v^2 = mu/r on the ellipse only at r = a", sp.solve(sp.Eq(mu * (2 / r - 1 / aa), mu / r), r) == [aa])
    f = sp.acos(-e)
    ok("r = a at cos f = -e", sp.simplify(aa * (1 - e**2) / (1 + e * sp.cos(f)) - aa) == 0)
    tg = e * sp.sin(f) / (1 + e * sp.cos(f))
    ok("tan gamma = e/sqrt(1-e^2), so sin gamma = e", sp.simplify(tg - e / sp.sqrt(1 - e**2)) == 0)
    ok("focus to end of minor axis = a", sp.simplify(sp.sqrt(aa**2 * (1 - e**2) + (aa * e)**2) - aa) == 0)
    ok("e = 0.5: f = 120 deg, gamma = 30 deg",
       close(np.degrees(np.arccos(-0.5)), 120, 1e-9) and close(np.degrees(np.arcsin(0.5)), 30, 1e-9))
    ok("arccos(-e) = 90 deg + arcsin e (e = 0.3)", close(np.arccos(-0.3), np.pi / 2 + np.arcsin(0.3), 1e-12))

    print("Is the orbit circular?")
    MU, R = 0.00553, 1.05 ** (2 / 3)
    n = np.sqrt(MU / R**3)
    ok(f"r^3 = 1.05^2 ({R**3:.6f})", close(R**3, 1.1025, 1e-12))
    ok(f"n = {n:.6f} rad/min (0.070823), {np.degrees(n):.4f} deg/min (4.0578)",
       close(n, 0.070823, 5e-7) and close(np.degrees(n), 4.0578, 5e-5))
    ok(f"period {2*np.pi/n:.2f} min (88.72), 60 deg in {2*np.pi/n/6:.2f} min (14.79)",
       close(2 * np.pi / n, 88.72, 0.005) and close(2 * np.pi / n / 6, 14.79, 0.005))
    ok(f"16 min sweep {n*16:.4f} rad (1.1332) = {np.degrees(n*16):.2f} deg (64.93)",
       close(n * 16, 1.1332, 5e-5) and close(np.degrees(n * 16), 64.93, 0.005))
    ok(f"mu in ER^3/min^2 = {398600*3600/6378.137**3:.5f} (0.00553)", close(398600 * 3600 / 6378.137**3, 0.00553, 5e-6))

    print("Elements from tracking data")
    MU, RE = 398600.0, 6378.0
    r, vr, vt = RE + 600, 3.5, 7.0
    h = r * vt; v2 = vr**2 + vt**2; eps = v2 / 2 - MU / r; a = -MU / (2 * eps); p = h * h / MU
    ec, es = p / r - 1, h * vr / MU; e = np.hypot(ec, es); f = np.degrees(np.arctan2(es, ec))
    T = 2 * np.pi * np.sqrt(a**3 / MU)
    ok(f"r = {r} km, h = {h:.0f} (48846), v^2 = {v2} (61.25)", r == 6978 and close(h, 48846, 1e-9) and close(v2, 61.25, 1e-12))
    ok(f"mu/r = {MU/r:.4f} (57.1224 -> 30.625 - 57.122), eps = {eps:.3f} (-26.497)", close(eps, -26.497, 5e-4))
    ok(f"a = {a:.1f} (7521.5)", close(a, 7521.5, 0.05))
    ok(f"T = {T:.0f} s (6492) = {T/60:.1f} min (108.2)", close(T, 6492, 0.5) and close(T / 60, 108.2, 0.05))
    ok(f"p = {p:.1f} (5985.8)", close(p, 5985.8, 0.05))
    ok(f"e cos f = {ec:.5f} (-0.14219), e sin f = {es:.5f} (0.42890)", close(ec, -0.14219, 5e-6) and close(es, 0.42890, 5e-6))
    ok(f"e = {e:.4f} (0.4519), check from energy {np.sqrt(1 + 2*eps*h*h/MU**2):.4f}",
       close(e, 0.4519, 5e-5) and close(np.sqrt(1 + 2 * eps * h * h / MU**2), e, 1e-12))
    ok(f"f = {f:.2f} deg (108.34), = 180 - arctan(es/|ec|)", close(f, 108.34, 0.005)
       and close(180 - np.degrees(np.arctan(es / abs(ec))), f, 1e-9))
    ok(f"r_p = {a*(1-e):.0f} km (4123), {RE - a*(1-e):.0f} km below the surface (2255)",
       close(a * (1 - e), 4123, 0.5) and close(RE - a * (1 - e), 2255, 0.5))


BLOCKS = [objective, note_exercises, tutorial, ellipse_and_hyperbola, assignment_one]


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