"""Checks every number and identity in challenge-problems.qmd (Challenge Problems).

Each function below checks one problem of the page. Closed forms are checked with sympy, and each
key result is also checked independently (direct integration of the equations of motion, a Kepler
solve, or a brute-force search). Run from the sfm-slides directory, or from anywhere:

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

MU = 398600.4418          # km^3/s^2
RE = 6378.137             # km
WE = 7.2921151e-5         # rad/s
J2 = 1.08263e-3
MUS = 1.32712440018e11    # km^3/s^2
AU = 1.495978707e8        # km
DAY = 86400.0


def kepler_E(M, e):
    import numpy as np
    E = M + e * np.sin(M)
    for _ in range(60):
        E = E - (E - e * np.sin(E) - M) / (1 - e * np.cos(E))
    return E


# ----------------------------------------------------------------------------------------------
def p1_mass_change():
    """Problem 1, when the attracting mass changes."""
    import numpy as np
    import sympy as sp
    from scipy.integrate import solve_ivp

    mu, r, b, e = sp.symbols("mu r beta e", positive=True)
    v = sp.sqrt(mu / r)
    mup = (1 - b) * mu
    h = r * v
    p = h**2 / mup
    sym_zero("(a) p'/r = 1/(1-beta)", p / r - 1 / (1 - b))
    ep = p / r - 1
    sym_zero("(a) e' = beta/(1-beta)", ep - b / (1 - b))
    eps = v**2 / 2 - mup / r
    a = -mup / (2 * eps)
    sym_zero("(a) a' = r(1-beta)/(1-2beta)", a - r * (1 - b) / (1 - 2 * b))
    sym_zero("(a) r_a' = r/(1-2beta)", 2 * a - r - r / (1 - 2 * b))
    # (b) escape thresholds from periapsis / apoapsis of an ellipse with eccentricity e
    Qp, Qa = 1 + e, 1 - e          # Q = v^2 r / mu at periapsis and apoapsis
    sym_zero("(b) threshold at periapsis (1-e)/2", (1 - Qp / 2) - (1 - e) / 2)
    sym_zero("(b) threshold at apoapsis (1+e)/2", (1 - Qa / 2) - (1 + e) / 2)
    # (c) slow loss vs sudden, first order in beta
    sym_zero("(c) sudden a' and slow r' agree to first order",
             sp.series(r * (1 - b) / (1 - 2 * b) - r / (1 - b), b, 0, 2).removeO())

    # numbers: sail at 1 AU to Mars's orbit
    rM = 1.5237
    beta = (1 - 1 / rM) / 2
    check("beta to reach 1.524 AU", beta, 0.172)
    check("e' for that beta", beta / (1 - beta), 0.208)
    a_au = (1 - beta) / (1 - 2 * beta)
    check("a' AU", a_au, 1.262)
    yr = 2 * np.pi * np.sqrt(AU**3 / MUS) / DAY
    t_sail = 0.5 * yr * a_au**1.5 / np.sqrt(1 - beta)
    t_hoh = 0.5 * yr * ((1 + rM) / 2) ** 1.5
    check("sail flight time days", t_sail, 284)
    check("Hohmann to Mars days", t_hoh, 259)
    # independent: integrate with mu' and check apoapsis and time
    mup_n = (1 - beta) * MUS

    def f(t, y):
        rr = np.hypot(y[0], y[1])
        return [y[2], y[3], -mup_n * y[0] / rr**3, -mup_n * y[1] / rr**3]
    ev = lambda t, y: y[0] * y[2] + y[1] * y[3]
    ev.direction = -1
    ev.terminal = True
    s = solve_ivp(f, [0, 1e9], [AU, 0, 0, np.sqrt(MUS / AU)], events=ev, rtol=1e-11, atol=1e-3)
    ra = np.hypot(*s.y_events[0][0][:2]) / AU
    check("integrated apoapsis AU", ra, rM, tol=1e-6)
    check("integrated flight time days", s.t_events[0][0] / DAY, t_sail, tol=1e-3)
    check("beta for 1% mass loss: e' ", 0.01 / 0.99, 0.0101)


# ----------------------------------------------------------------------------------------------
def p2_weak_engine():
    """Problem 2, a weak engine."""
    import numpy as np
    import sympy as sp
    from scipy.integrate import solve_ivp

    x = sp.symbols("x", positive=True)       # x = sqrt(r1/r2)
    R = 1 / x**2
    hoh = sp.sqrt(2 * R / (1 + R)) - 1 + x - x * sp.sqrt(2 / (1 + R))
    spiral = 1 - x
    fac = (1 - x) * (2 - (1 + x) * sp.sqrt(2 / (1 + x**2)))
    sym_zero("(b) spiral - Hohmann factorises", sp.simplify(spiral - hoh - fac))
    sym_zero("(b) 4(1+x^2) - 2(1+x)^2 = 2(1-x)^2", 4 * (1 + x**2) - 2 * (1 + x)**2 - 2 * (1 - x)**2)
    ep = sp.symbols("epsilon")
    ser = sp.series((spiral - hoh).subs(x, 1 / sp.sqrt(1 + ep)), ep, 0, 4).removeO()
    sym_zero("(b) difference = eps^3/32 + ...", ser - ep**3 / 32)
    truth("(b) spiral > Hohmann on a grid", all(float((spiral - hoh).subs(x, t)) > 0 for t in np.linspace(0.05, 0.95, 19)))

    r1 = RE + 300.0
    r2 = 42164.17
    v1, v2 = np.sqrt(MU / r1), np.sqrt(MU / r2)
    at = (r1 + r2) / 2
    H = np.sqrt(MU * (2 / r1 - 1 / at)) - v1 + v2 - np.sqrt(MU * (2 / r2 - 1 / at))
    check("v1", v1, 7.726)
    check("v2", v2, 3.075)
    check("spiral dv", v1 - v2, 4.651)
    check("Hohmann dv", H, 3.893)
    check("ratio %", (v1 - v2) / H * 100 - 100, 19.5)
    aT = 1e-7
    check("spiral time days", (v1 - v2) / aT / DAY, 538)
    c_ch, c_el = 320 * 9.80665e-3, 1600 * 9.80665e-3
    check("chemical propellant fraction", 1 - np.exp(-H / c_ch), 0.711)
    check("electric propellant fraction", 1 - np.exp(-(v1 - v2) / c_el), 0.257)
    check("Hohmann flight time h (about five hours)", np.pi * np.sqrt(at**3 / MU) / 3600, 5.3)
    check("exhaust speed ratio", c_el / c_ch, 5.0)
    check("propellant ratio (about a third)", (1 - np.exp(-(v1 - v2) / c_el)) / (1 - np.exp(-H / c_ch)), 0.36)

    # independent: integrate a weak tangential thrust and compare dv = aT t with v1 - v2
    a_th = 2e-6
    ra, rb = 7000.0, 8000.0

    def f(t, y):
        rr = np.hypot(y[0], y[1])
        vv = np.hypot(y[2], y[3])
        return [y[2], y[3], -MU * y[0] / rr**3 + a_th * y[2] / vv, -MU * y[1] / rr**3 + a_th * y[3] / vv]
    # stop when the orbital energy reaches that of the circle at rb
    ev = lambda t, y: (y[2]**2 + y[3]**2) / 2 - MU / np.hypot(y[0], y[1]) + MU / (2 * rb)
    ev.terminal = True
    s = solve_ivp(f, [0, 1e8], [ra, 0, 0, np.sqrt(MU / ra)], events=ev, rtol=1e-10, atol=1e-6, max_step=500)
    dv_int = a_th * s.t_events[0][0]
    check("integrated spiral dv equals vc1 - vc2", dv_int, np.sqrt(MU / ra) - np.sqrt(MU / rb), rel=2e-3)

    # drag: speed rises
    k = sp.symbols("kappa", positive=True)
    rr, mu_ = sp.symbols("r mu", positive=True)
    rdot = -2 * k * sp.sqrt(mu_ * rr)          # dr/dt with drag deceleration kappa v^2
    vdot = sp.diff(sp.sqrt(mu_ / rr), rr) * rdot
    sym_zero("(d) dv/dt = +kappa v^2", vdot - k * mu_ / rr)
    eps = -mu_ / (2 * rr)
    sym_zero("(d) d(eps)/dt = -D v", sp.diff(eps, rr) * rdot + k * (mu_ / rr) * sp.sqrt(mu_ / rr))


# ----------------------------------------------------------------------------------------------
def p3_toy_oblate():
    """Problem 3, a Hohmann transfer round a toy oblate planet."""
    import numpy as np
    import sympy as sp
    from scipy.integrate import solve_ivp

    mu, l, r1, r2 = sp.symbols("mu lambda r1 r2", positive=True)
    h2 = l + 2 * mu * r1 * r2 / (r1 + r2)
    # apsides at r1 and r2: radial energy vanishes at both
    eps1 = (h2 - l) / (2 * r1**2) - mu / r1
    eps2 = (h2 - l) / (2 * r2**2) - mu / r2
    sym_zero("(b) both apsides have the same energy", eps1 - eps2)
    dv = (sp.sqrt(h2) / r1 - sp.sqrt(mu / r1 + l / r1**2)) + (sp.sqrt(mu / r2 + l / r2**2) - sp.sqrt(h2) / r2)
    d = sp.diff(dv, l).subs(l, 0)
    h0 = sp.sqrt(2 * mu * r1 * r2 / (r1 + r2))
    hc1, hc2 = sp.sqrt(mu * r1), sp.sqrt(mu * r2)
    claim = sp.Rational(1, 2) * ((1 / r1) * (1 / h0 - 1 / hc1) + (1 / r2) * (1 / hc2 - 1 / h0))
    sym_zero("(d) d(dv)/d(lambda) at 0", sp.simplify(d - claim))

    R1, R2 = RE + 300.0, 42164.17
    pt = 2 * R1 * R2 / (R1 + R2)
    lam = 3 * J2 * MU * RE**2 / pt
    check("p_t", pt, 11530)
    check("lambda", lam / 1e6, 4.568)
    H2 = lam + 2 * MU * R1 * R2 / (R1 + R2)
    k = np.sqrt(1 - lam / H2)
    check("transfer angle deg", 180 / k, 180.089)
    check("first-order transfer angle deg", 180 * (1 + lam / (2 * H2)), 180.089)
    check("arc beyond 180 deg at GEO km", R2 * np.radians(180 / k - 180), 66)
    vals = {mu: MU, r1: R1, r2: R2, l: lam}
    check("dv total toy", float(dv.subs(vals)), 3.8906)
    check("dv total point mass", float(dv.subs({**vals, l: 0})), 3.8926)
    check("saving m/s", 1000 * float(dv.subs({**vals, l: 0}) - dv.subs(vals)), 1.96)
    check("linear saving m/s", -1000 * lam * float(claim.subs(vals)), 1.97)

    # independent: integrate the toy force, find the apoapsis and its angle
    def f(t, y):
        rr = np.hypot(y[0], y[1])
        acc = MU / rr**2 + lam / rr**3
        return [y[2], y[3], -acc * y[0] / rr, -acc * y[1] / rr]
    ev = lambda t, y: y[0] * y[2] + y[1] * y[3]
    ev.direction = -1
    ev.terminal = True
    s = solve_ivp(f, [0, 1e6], [R1, 0, 0, np.sqrt(H2) / R1], events=ev, rtol=1e-12, atol=1e-9)
    ye = s.y_events[0][0]
    check("integrated apoapsis radius", np.hypot(ye[0], ye[1]), R2, tol=1e-3)
    check("integrated apoapsis angle", np.degrees(np.arctan2(ye[1], ye[0])) % 360, 180 / k, tol=1e-6)
    # apse rate match: pi*lambda/h^2 per orbit = 3 pi J2 (R/p)^2 for the transfer ellipse
    check("toy apse advance per orbit = J2 equatorial", np.pi * lam / (MU * pt), 3 * np.pi * J2 * (RE / pt)**2, tol=1e-15)


# ----------------------------------------------------------------------------------------------
def p4_node_by_waiting():
    """Problem 4, moving the node by waiting."""
    import numpy as np
    import sympy as sp

    a, K, ci = sp.symbols("a K c", positive=True)
    Od = -K * ci / a**sp.Rational(7, 2)
    sym_zero("(a) dOmegadot/da = -(7/2) Omegadot / a", sp.diff(Od, a) + sp.Rational(7, 2) * Od / a)

    r = RE + 500.0
    inc = np.radians(97.4)
    v = np.sqrt(MU / r)
    n = np.sqrt(MU / r**3)
    Kn = 1.5 * J2 * RE**2 * np.sqrt(MU)
    Od_n = -Kn * np.cos(inc) / r**3.5
    check("K consistent with J2", Od_n, -1.5 * n * J2 * (RE / r)**2 * np.cos(inc), tol=1e-18)
    check("Omega dot deg/day", np.degrees(Od_n) * DAY, 0.985)
    check("v", v, 7.613)
    dO = np.radians(10)
    check("impulsive dv m/s", 1000 * 2 * v * np.sin(inc) * np.sin(dO / 2), 1316)
    prod = 2 / 7 * v * 1000 * dO / abs(Od_n) / DAY
    check("product dv*T (m/s day)", prod, 22070, tol=5)
    dr = 50.0
    dv_lin = v * dr / r * 1000
    T_lin = dO / (3.5 * abs(Od_n) * dr / r) / DAY
    check("linear dv m/s for 50 km", dv_lin, 55.3)
    check("linear T days for 50 km", T_lin, 399)
    # exact (two Hohmann transfers and exact rate difference)
    r2 = r + dr
    at = (r + r2) / 2
    dvh = (np.sqrt(MU * (2 / r - 1 / at)) - v) + (np.sqrt(MU / r2) - np.sqrt(MU * (2 / r2 - 1 / at)))
    Od2 = -Kn * np.cos(inc) / r2**3.5
    check("exact dv m/s for 50 km", 2 * dvh * 1000, 55.0)
    check("exact T days for 50 km", dO / abs(Od2 - Od_n) / DAY, 405)
    check("going down: rate magnitude grows", (abs(-Kn * np.cos(inc) / (r - dr)**3.5) > abs(Od_n)) * 1.0, 1.0)
    check("T for a 60-day deadline: dv m/s", prod / 60, 368)
    check("dr for 60 days km", prod / 60 / 1000 / v * r, 330, tol=5)
    check("saving factor (more than twenty)", 1316 / 55.0, 24)


# ----------------------------------------------------------------------------------------------
def p5_disorbit():
    """Problem 5, why the cheapest disorbit is a horizontal retro burn."""
    import numpy as np
    import sympy as sp
    from scipy.optimize import minimize_scalar

    m, c, s, u = sp.symbols("m c s u", positive=True)
    K = m**2 / c**2 - 1
    M = 2 * (m - 1)
    vertex_val = (K + 1) * (1 / (K + 1))**2 - 2 / (K + 1) + 1 - M
    sym_zero("(a) vertex value = 1 - 2(m-1) - c^2/m^2", vertex_val - (1 - 2 * (m - 1) - c**2 / m**2))
    dV = sp.diff(1 - 2 * (m - 1) - c**2 / m**2, m)
    sym_zero("(a) dV/dm = -2 + 2c^2/m^3", dV - (-2 + 2 * c**2 / m**3))
    # (b) at m = 1 + s, c^2 = 1 - s^2: K+1 = (1+s)/(1-s), M/K = 1 - s
    sub = {c: sp.sqrt(1 - s**2), m: 1 + s}
    sym_zero("(b) K+1 at best", sp.simplify((K + 1).subs(sub) - (1 + s) / (1 - s)))
    sym_zero("(b) M/K at best", sp.simplify((M / K).subs(sub) - (1 - s)))
    truth("(b) vertex infeasible at 1+s on a grid", all((1 - t) / (1 + t) < np.sqrt(1 - t) for t in np.linspace(0.01, 0.99, 50)))
    # (c) J* and J'' exact
    x = sp.symbols("x", positive=True)
    J = 1 - sp.sqrt(1 - s**2) * sp.sqrt(2 * x / (2 * x + x**2 + s**2))
    sym_zero("(c) J* = 1 - sqrt(1-s)", sp.simplify(J.subs(x, s) - (1 - sp.sqrt(1 - s))))
    Jpp = sp.diff(J, x, 2).subs(x, s)
    sym_zero("(c) J'' = sqrt(1-s^2)/(2 s (1+s)^(3/2))", sp.simplify(Jpp - sp.sqrt(1 - s**2) / (2 * s * (1 + s)**sp.Rational(3, 2))))
    shift = (1 - sp.sqrt(1 - s)) / (2 * (1 + s) * Jpp)
    truth("(c) shift = s(1-sqrt(1-s))/sqrt(1-s) (numerically, several s)",
          all(abs(float((shift - s * (1 - sp.sqrt(1 - s)) / sp.sqrt(1 - s)).subs(s, t))) < 1e-12 for t in (0.05, 0.2, 0.5, 0.9)))
    sym_zero("(c) shift = s^2/2 + ...", sp.series(shift, s, 0, 3).removeO() - s**2 / 2)

    # numbers, gamma2 = -6 deg, r2 = 6478.137 km
    g = np.radians(6.0)
    sn, cn = np.sin(g), np.cos(g)
    r2 = RE + 100.0
    check("m_best", 1 + sn, 1.10453)
    check("r1 best", r2 * (1 + sn), 7155.3)
    vc1 = np.sqrt(MU / (r2 * (1 + sn)))
    check("vc1", vc1, 7.4637)
    Jstar = 1 - np.sqrt(1 - sn)
    check("J* closed form = note's form", Jstar, 1 - cn / np.sqrt(1 + sn), tol=1e-14)
    check("dv at normalised optimum m/s", 1000 * vc1 * Jstar, 401)
    Hf = lambda mm: (1 - cn * np.sqrt(2 * (mm - 1) / (mm * mm - cn * cn))) / np.sqrt(mm)
    res = minimize_scalar(Hf, bounds=(1.0001, 2), method="bounded", options={"xatol": 1e-12})
    check("km/s optimum m (search)", res.x, 1.111)
    check("km/s optimum m (series)", 1 + sn + sn**2 / 2, 1.110)
    check("km/s optimum altitude km", r2 * res.x - RE, 819)
    vc2 = np.sqrt(MU / r2)
    check("dv at km/s optimum m/s", 1000 * vc2 * res.fun, 400.3)
    # independent check of the regime claim: brute-force (u, w) optimisation at several m
    for gd in (2.0, 6.0, 10.0, 30.0):
        gg = np.radians(gd)
        cc = np.cos(gg)
        best = []
        for mm in np.linspace(1.0005, 1.6, 400):
            KK = mm**2 / cc**2 - 1
            MM = 2 * (mm - 1)
            uu = np.linspace(np.sqrt(MM / KK), 1.0, 4001)
            ww = np.sqrt(np.maximum(KK * uu**2 - MM, 0))
            cost = np.sqrt(ww**2 + (uu - 1)**2)
            j = np.argmin(cost)
            best.append((cost[j], mm, ww[j]))
        cbest, mbest, wbest = min(best)
        truth(f"(a,b) brute force, gamma {gd}: global best is horizontal and at 1+|sin|",
              abs(wbest) < 1e-6 and abs(mbest - (1 + np.sin(gg))) < 2e-3)


# ----------------------------------------------------------------------------------------------
def p6_tisserand():
    """Problem 6, what a flyby cannot change."""
    import numpy as np
    import sympy as sp

    Vp, ap, vt, vr, mu = sp.symbols("V_p a_p v_t v_r mu", positive=True)
    w = Vp / ap
    eps = ((Vp + vt)**2 + vr**2) / 2 - mu / ap
    h = ap * (Vp + vt)
    vinf2 = vt**2 + vr**2
    C = eps - w * h
    sym_zero("(a) eps - omega h = vinf^2/2 - Vp^2/2 - mu/a_p", C - (vinf2 / 2 - Vp**2 / 2 - mu / ap))
    sym_zero("(a) ... = vinf^2/2 - 3Vp^2/2 with Vp^2 = mu/a_p", (C - (vinf2 / 2 - 3 * Vp**2 / 2)).subs(mu, Vp**2 * ap))
    a, e = sp.symbols("a e", positive=True)
    lhs = -mu / (2 * a) - (Vp / ap) * sp.sqrt(mu * a * (1 - e**2))
    T = ap / a + 2 * sp.sqrt(a * (1 - e**2) / ap)
    sym_zero("(b) Tisserand form", sp.simplify((lhs * (-2 * ap / mu) - T).subs(Vp, sp.sqrt(mu / ap))))

    aE, aJ = AU, 5.2026 * AU
    muJ, RJ = 1.26686534e8, 71492.0
    VJ = np.sqrt(MUS / aJ)
    at = (aE + aJ) / 2
    vinf = VJ - np.sqrt(MUS * (2 / aJ - 1 / at))
    check("V_J", VJ, 13.06)
    check("v_inf at Jupiter", vinf, 5.64)
    check("ratio", vinf / VJ, 0.432)
    check("Hohmann aphelion speed", np.sqrt(MUS * (2 / aJ - 1 / at)), 7.41)
    check("Hohmann Earth-Jupiter time years", np.pi * np.sqrt(at**3 / MUS) / (365.25 * DAY), 2.7)
    check("sqrt2 - 1", np.sqrt(2) - 1, 0.414)
    eH = (aJ - aE) / (aJ + aE)
    TH = aJ / at + 2 * np.sqrt(at * (1 - eH**2) / aJ)
    check("Tisserand of Hohmann orbit", TH, 2.813)
    check("3 - (vinf/VJ)^2", 3 - (vinf / VJ)**2, 2.813)
    cth = (VJ**2 - vinf**2) / (2 * VJ * vinf)
    th = np.degrees(np.arccos(cth))
    check("largest allowed angle to V_J", th, 19.8)
    check("turn needed", 180 - th, 160.2)
    eflyby = 1 + RJ * vinf**2 / muJ
    check("largest turn at a grazing pass", 2 * np.degrees(np.arcsin(1 / eflyby)), 158.4)
    dneed = np.radians(180 - th)
    rp = (1 / np.sin(dneed / 2) - 1) * muJ / vinf**2
    check("periapsis needed / R_J", rp / RJ, 0.84)
    # independent: rotate v_inf by the grazing turn, check the energy stays negative, and check that
    # eps - omega h is the same before and after for a random turn
    rng = np.random.default_rng(1)
    vin = np.array([-vinf, 0.0])                   # (transverse, radial) relative to Jupiter
    ok = True
    for _ in range(20):
        d = rng.uniform(-np.pi, np.pi)
        R = np.array([[np.cos(d), -np.sin(d)], [np.sin(d), np.cos(d)]])
        vo = R @ vin
        C0 = 0.5 * ((VJ + vin[0])**2 + vin[1]**2) - MUS / aJ - (VJ / aJ) * aJ * (VJ + vin[0])
        C1 = 0.5 * ((VJ + vo[0])**2 + vo[1]**2) - MUS / aJ - (VJ / aJ) * aJ * (VJ + vo[0])
        ok &= abs(C0 - C1) < 1e-9
    truth("(a) invariant unchanged by random turns", ok)
    dmax = 2 * np.arcsin(1 / eflyby)
    vo = np.array([-vinf * np.cos(dmax), vinf * np.sin(dmax)])
    epsmax = 0.5 * ((VJ + vo[0])**2 + vo[1]**2) - MUS / aJ
    truth("grazing flyby leaves the orbit bound", epsmax < 0)


# ----------------------------------------------------------------------------------------------
def p7_hill():
    """Problem 7, two radii for one sphere."""
    import numpy as np
    import sympy as sp

    x, a, G, M, m = sp.symbols("x a G M m", positive=True)
    n2 = G * M / a**3
    acc = -G * M / (a + x)**2 + n2 * (a + x)
    lin = sp.series(acc, x, 0, 2).removeO()
    sym_zero("(a) tidal + centrifugal = 3 n^2 x", sp.simplify(lin - 3 * n2 * x))
    rH = a * (m / (3 * M))**sp.Rational(1, 3)
    sym_zero("(a) balance at r_H", sp.simplify(-G * m / rH**2 + 3 * n2 * rH))
    q = sp.symbols("q", positive=True)
    sym_zero("(b) equal radii at m/M = 3^-5", sp.simplify((q / 3)**sp.Rational(1, 3) - q**sp.Rational(2, 5)).subs(q, sp.Rational(1, 243)))
    check("1/243", 1 / 243, 0.00412)

    for name, mr, aa, qH, qS in [("Earth", 1 / 332946.0487, AU, 1.497e6, 0.925e6),
                                 ("Moon", 1 / 81.30056, 384400.0, 61500, 66200),
                                 ("Jupiter", 1 / 1047.348644, 5.2026 * AU, 5.31e7, 4.82e7)]:
        check(f"{name} Hill radius", aa * (mr / 3)**(1 / 3), qH, rel=2e-3)
        check(f"{name} SOI", aa * mr**0.4, qS, rel=2e-3)
    check("Earth ratio", (1 / 332946.0487 / 3)**(1 / 3) / (1 / 332946.0487)**0.4, 1.62)
    check("Moon ratio", (1 / 81.30056 / 3)**(1 / 3) / (1 / 81.30056)**0.4, 0.93)

    # independent: exact collinear L1 of the CR3BP for the Sun-Earth system
    from scipy.optimize import brentq
    mr = 3.0034896e-6        # Earth + Moon / (Sun + Earth + Moon), for L1 near Earth
    f = lambda g: (1 - mr) / (1 - mr - g)**2 - mr / g**2 - (1 - mr - g)
    gam = brentq(f, 1e-4, 0.1)
    check("exact L1 distance from Earth (km)", gam * AU, 1.49e6, rel=1e-2)
    check("Hill approximation of L1 (km)", AU * (mr / 3)**(1 / 3), 1.50e6, rel=1e-2)


# ----------------------------------------------------------------------------------------------
def p8_vertical_shot():
    """Problem 8, fire straight up from the equator."""
    import numpy as np
    import sympy as sp

    mu, R, rr, ra = sp.symbols("mu R r r_a", positive=True)
    # integral of dr / (r^2 sqrt(2 mu (1/r - 1/r_a))) from R to r_a
    u = sp.symbols("u", positive=True)
    ua = 1 / ra
    I = sp.integrate(1 / sp.sqrt(2 * mu * (u - ua)), (u, ua, 1 / R))
    sym_zero("(c) one-way integral = sqrt(2(1/R - 1/r_a)/mu)", sp.simplify(I - sp.sqrt(2 * (1 / R - 1 / ra) / mu)))
    v, g = sp.symbols("v g", positive=True)
    q = v**2 * R / mu
    ra_expr = R / (1 - q / 2)
    twoway = 2 * sp.sqrt(2 * (1 / R - 1 / ra_expr) / mu)
    sym_zero("(c) R^2 * two-way integral = 2v R^2/mu = 2v/g", sp.simplify(R**2 * twoway - 2 * v * R**2 / mu))
    qq = sp.symbols("q", positive=True)
    ratio = (sp.acos(1 - qq) + sp.sqrt(qq * (2 - qq))) / ((2 - qq)**sp.Rational(3, 2) * sp.sqrt(qq))
    ser = sp.series(ratio, qq, 0, 3).removeO()
    sym_zero("(d) t_f/(2v/g) = 1 + 2q/3 + 2q^2/5 + ...", sp.expand(ser - (1 + 2 * qq / 3 + 2 * qq**2 / 5)))

    g0 = MU / RE**2

    def tf_radial(vv):
        qv = vv * vv * RE / MU
        a = RE / (2 - qv)
        return 2 * np.sqrt(a**3 / MU) * (np.arccos(1 - qv) + np.sqrt(qv * (2 - qv)))

    def exact(vv):
        vt = WE * RE
        h = RE * vt
        eps = (vv**2 + vt**2) / 2 - MU / RE
        a = -MU / (2 * eps)
        p = h * h / MU
        ec, es = p / RE - 1, vv * h / MU
        e = np.hypot(ec, es)
        f1 = np.arctan2(es, ec)
        psi = 2 * (np.pi - f1)
        E1 = 2 * np.arctan(np.sqrt((1 - e) / (1 + e)) * np.tan(f1 / 2))
        M1 = E1 - e * np.sin(E1)
        tf = 2 * (np.pi - M1) / np.sqrt(MU / a**3)
        return psi, tf

    check("g", g0 * 1000, 9.798)
    check("omega R", WE * RE, 0.4651)
    for vv, q_t, tf_t, d_t, cl_t, ex_t in [(2.0, 0.0640, 426.3, 8.42, 8.10, 8.48),
                                          (5.0, 0.400, 1377, 166, 127, 167)]:
        qv = vv * vv * RE / MU
        check(f"v={vv}: q", qv, q_t)
        check(f"v={vv}: t_f", tf_radial(vv), tf_t)
        check(f"v={vv}: 2v/g", 2 * vv / g0, {2.0: 408.2, 5.0: 1021}[vv])
        d = WE * RE * (tf_radial(vv) - 2 * vv / g0)
        check(f"v={vv}: west distance, first order", d, d_t)
        check(f"v={vv}: classical 4/3 w v^3/g^2", 4 / 3 * WE * vv**3 / g0**2, cl_t)
        psi, tf = exact(vv)
        check(f"v={vv}: exact conic, west distance", -(psi - WE * tf) * RE, ex_t)
        check(f"v={vv}: exact psi vs 2 v w / g", psi, 2 * vv * WE / g0, rel=4e-3)
    check("relative size of the neglected (wR)^2/(gR)", (WE * RE)**2 / (g0 * RE), 0.0035)
    check("cos 8.5 deg", np.cos(np.radians(8.5)), 0.989)
    check("textbook low at 2 km/s %", (1 - 4 / 3 * WE * 8 / g0**2 / (WE * RE * (tf_radial(2.0) - 4 / g0))) * 100, 4, tol=0.5)
    check("textbook low at 5 km/s %", (1 - 4 / 3 * WE * 125 / g0**2 / (WE * RE * (tf_radial(5.0) - 10 / g0))) * 100, 24, tol=0.6)
    check("1 + 3q/5 at v=2", 1 + 0.6 * 2.0**2 * RE / MU, 1.038)


# ----------------------------------------------------------------------------------------------
def p9_geo_wander():
    """Problem 9, how a geosynchronous satellite wanders."""
    import numpy as np
    import sympy as sp

    u, c = sp.symbols("u c", positive=True)
    lam = sp.atan(c * sp.tan(u)) - u
    dl = sp.simplify(sp.diff(lam, u))
    sym_zero("(a) dlambda/du", sp.simplify(dl - (c / (sp.cos(u)**2 + c**2 * sp.sin(u)**2) - 1)))
    i = sp.symbols("i", positive=True)
    truth("(a) (1-cos i)/(1+cos i) = tan^2(i/2)", all(abs(float(((1 - sp.cos(i)) / (1 + sp.cos(i)) - sp.tan(i / 2)**2).subs(i, t))) < 1e-14 for t in (0.1, 0.7, 1.3)))

    for ideg, w_t, p_t, sm_t in [(29.0, 3.835, 20.74, 3.670), (5.0, 0.1092, 3.537, 0.1091)]:
        ir = np.radians(ideg)
        uu = np.linspace(0, np.pi / 2, 400001)
        ll = np.arctan2(np.cos(ir) * np.sin(uu), np.cos(uu)) - uu
        k = np.argmin(ll)
        check(f"i={ideg}: brute-force width", -np.degrees(ll[k]), np.degrees(np.arcsin(np.tan(ir / 2)**2)), tol=1e-6)
        check(f"i={ideg}: exact half-width", np.degrees(np.arcsin(np.tan(ir / 2)**2)), w_t)
        check(f"i={ideg}: latitude there", np.degrees(np.arcsin(np.sqrt(2) * np.sin(ir / 2))), p_t)
        check(f"i={ideg}: brute-force latitude", np.degrees(np.arcsin(np.sin(ir) * np.sin(uu[k]))), p_t)
        check(f"i={ideg}: i^2/4", np.degrees(ir**2 / 4), sm_t)

    # (b) eccentric, equatorial
    e = sp.symbols("e", positive=True)
    cf = ((1 - e**2)**sp.Rational(3, 4) - 1) / e
    sym_zero("(b) cos f* = -3e/4 + ...", sp.series(cf, e, 0, 2).removeO() + sp.Rational(3, 4) * e)
    for ev, tol in [(0.0005, 1e-9), (0.1, 1e-9)]:
        Ms = np.linspace(0, np.pi, 200001)
        Es = kepler_E(Ms, ev)
        fs = 2 * np.arctan2(np.sqrt(1 + ev) * np.sin(Es / 2), np.sqrt(1 - ev) * np.cos(Es / 2))
        mx = np.max(fs - Ms)
        f = np.arccos(((1 - ev**2)**0.75 - 1) / ev)
        E = 2 * np.arctan(np.sqrt((1 - ev) / (1 + ev)) * np.tan(f / 2))
        check(f"e={ev}: max(f-M) brute force = closed form", mx, f - (E - ev * np.sin(E)), tol=tol)
    check("e = 0.1: 2e error %", (0.2 - 0.20023034) / 0.20023034 * 100, -0.12)
    check("e=0.0005: libration deg", np.degrees(2 * 0.0005), 0.0573)
    check("e allowed for +-0.05 deg", np.radians(0.05) / 2, 4.4e-4)
    check("radius change for e = 0.0005 km", 42164.17 * 0.0005, 21)
    check("figure-8 half-width for i = 0.05 deg (deg)", np.degrees(np.radians(0.05)**2 / 4), 1.1e-5)
    check("NavIC small-angle error %", (1 - 3.6695547523 / 3.8349795977) * 100, 4.3)
    # second-order term of f - M vanishes at M = pi/2
    M = sp.symbols("M")
    fm = 2 * e * sp.sin(M) + sp.Rational(5, 4) * e**2 * sp.sin(2 * M)
    sym_zero("(b) e^2 term vanishes at M = pi/2", fm.subs(M, sp.pi / 2) - 2 * e)

    # (c) small e and i: the ellipse. Exact track for e = 2e-4, i = 0.0229 deg (so i = 2e), w = 90 deg
    ev = 2e-4
    ir = 2 * ev
    w = np.pi / 2
    Ms = np.linspace(0, 2 * np.pi, 2001)
    Es = kepler_E(Ms, ev)
    fs = 2 * np.arctan2(np.sqrt(1 + ev) * np.sin(Es / 2), np.sqrt(1 - ev) * np.cos(Es / 2))
    us = w + fs
    alpha = np.arctan2(np.cos(ir) * np.sin(us), np.cos(us))
    lam_t = np.unwrap(alpha - (w + Ms))            # Omega cancels with the sidereal angle at t = 0
    lam_t -= lam_t.mean()
    phi = np.arcsin(np.sin(ir) * np.sin(us))
    rad = np.hypot(lam_t, phi)
    truth("(c) exact track is a circle of radius i (to 1%)", np.max(np.abs(rad / ir - 1)) < 0.01)
    k0 = 0
    truth("(c) at perigee the point is north and moving east (clockwise)", phi[k0] > 0 and lam_t[1] > lam_t[0])


# ----------------------------------------------------------------------------------------------
def p10_seasons():
    """Problem 10, unequal seasons."""
    import numpy as np
    import sympy as sp

    f, e = sp.symbols("f e")
    # M = f - 2e sin f + O(e^2)
    E = 2 * sp.atan(sp.sqrt((1 - e) / (1 + e)) * sp.tan(f / 2))
    Mf = E - e * sp.sin(E)
    ser = sp.series(Mf, e, 0, 2).removeO()
    truth("(a) M = f - 2 e sin f + O(e^2) (series checked at several f)",
          all(abs(float((ser - (f - 2 * e * sp.sin(f))).subs({f: t, e: 0.3}))) < 1e-12 for t in (0.4, 1.1, 2.5, -0.8)))
    a1, w = sp.symbols("lambda varpi")
    s = sp.sin(a1 + sp.pi / 2 - w) - sp.sin(a1 - w)
    sym_zero("(b) sin difference identity", sp.simplify(s - sp.sqrt(2) * sp.cos(a1 + sp.pi / 4 - w)))

    Y = 365.242189
    ev = 0.0167086
    vp = np.radians(282.9373)

    def Mof(lam):
        ff = lam - vp
        EE = 2 * np.arctan(np.sqrt((1 - ev) / (1 + ev)) * np.tan(ff / 2))
        return EE - ev * np.sin(EE)

    def dt(l1, l2):
        return ((Mof(np.radians(l2)) - Mof(np.radians(l1))) % (2 * np.pi)) / (2 * np.pi) * Y

    A = np.sqrt(2) * ev * Y / np.pi
    check("A days", A, 2.747)
    check("Y/4", Y / 4, 91.31)
    for k, (ex_t, fo_t) in enumerate([(92.76, 92.77), (93.65, 93.64), (89.84, 89.85), (88.99, 88.98)]):
        check(f"season {k} exact", dt(90 * k, 90 * k + 90), ex_t)
        check(f"season {k} first order", Y / 4 - A * np.cos(np.radians(90 * k + 45) - vp), fo_t)
    check("summer half", dt(0, 180), 186.41)
    check("winter half", dt(180, 360), 178.83)
    check("difference", dt(0, 180) - dt(180, 360), 7.57)
    check("first-order half difference", 4 * ev * Y / np.pi * np.sin(-vp), 7.57)
    check("Uttarayana", dt(270, 450), 181.75)
    check("Dakshinayana", dt(90, 270), 183.49)
    check("Uttarayana first order", Y / 2 + 2 * ev * Y / np.pi * np.sin(np.radians(270) - vp), 181.75)
    # Hipparchus
    Yh = 365.25
    d1, d2 = Yh / 4 - 94.5, Yh / 4 - 92.5
    check("d1", d1, -3.1875, tol=1e-12)
    check("d2", d2, -1.1875, tol=1e-12)
    Ah = np.hypot(d1, d2)
    check("A Hipparchus", Ah, 3.40)
    eh = np.pi * Ah / (np.sqrt(2) * Yh)
    check("e Hipparchus", eh, 0.0207)
    check("1/(2e) Hipparchus", 1 / (2 * eh), 24.2)
    ang = np.degrees(np.arctan2(-d2, d1))
    check("45 - varpi", ang, 159.6)
    check("perigee longitude", (45 - ang) % 360, 245.4)
    check("apogee longitude", (225 - ang) % 360, 65.4)
    # modern season lengths back to e and perigee (closes the loop)
    L = [dt(90 * k, 90 * k + 90) for k in range(4)]
    d = [Y / 4 - x for x in L]
    Am = 0.5 * np.hypot(d[0] - d[2], d[1] - d[3])
    check("modern e recovered", np.pi * Am / (np.sqrt(2) * Y), 0.0167)
    check("apogee shift deg", 102.9373 - 65.4, 37.5, tol=0.06)
    check("61.9 arcsec/yr over 2150 yr deg", 61.9 * 2150 / 3600, 37, tol=0.5)
    check("one day error in A -> de", np.pi * 1.0 / (np.sqrt(2) * Yh), 0.006)
    check("solstice offset from apse line deg", 282.9373 - 270, 13)
    check("equinox half difference rounded", dt(0, 180) - dt(180, 360), 7.6)
    check("solstice half difference", dt(90, 270) - dt(270, 450), 1.7)
    check("modern perigee recovered", (45 - np.degrees(np.arctan2(-(d[1] - d[3]), d[0] - d[2]))) % 360, 282.9)


BLOCKS = [p1_mass_change, p2_weak_engine, p3_toy_oblate, p4_node_by_waiting, p5_disorbit,
          p6_tisserand, p7_hill, p8_vertical_shot, p9_geo_wander, p10_seasons]


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