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


def objective():
    """The 16 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

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

    num = Objective("hohmann-transfer-questions.qmd", 16).num

    r1, r2 = 6678.0, 42164.0
    vc1, vc2 = np.sqrt(mu / r1), np.sqrt(mu / r2)
    at = (r1 + r2) / 2
    vt1, vt2 = np.sqrt(mu * (2 / r1 - 1 / at)), np.sqrt(mu * (2 / r2 - 1 / at))
    num(3, vt1 - vc1 + vc2 - vt2, "3.89")
    num(4, np.pi * np.sqrt(at ** 3 / mu) / 3600, "5.3")
    num(8, np.sqrt(2 * mu * 14000 / (7000 * 21000)) - np.sqrt(mu / 7000), "1.17")

    roots = [x.real for x in np.roots([1, -15, -9, -1]) if abs(x.imag) < 1e-12 and x.real > 1]
    truth("Q12  single root of R^3-15R^2-9R-1 above 1 is 15.58", len(roots) == 1 and abs(roots[0] - 15.5817) < 1e-4)

    ra, rp = Re + 500, Re + 80
    num(16, (np.sqrt(mu / ra) - np.sqrt(2 * mu * rp / (ra * (ra + rp)))) * 1e3, "121")


def note_exercises():
    """Problems 1 and 4, going down from GEO, and the optimality proof."""
    import numpy as np

    from orbit.constants import MU_EARTH as mu
    r2 = 42164.0

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

    vc2 = np.sqrt(mu/r2)

    # exercises
    rP = 6378.137 + 100; at_ = (rP + r2)/2
    check("going down", vc2 - vis(r2, at_), 1.488, 5e-4)
    ag = (r2 + r2 + 300)/2
    gy = (vis(r2, ag) - vc2) + (np.sqrt(mu/(r2 + 300)) - vis(r2 + 300, ag))
    check("graveyard, m/s", 1e3*gy, 10.9, 0.05); check("ratio", (vc2 - vis(r2, at_))/gy, 137, 0.5)

    # worked solutions, Exercises 1 and 2
    rG, rpE = 42164.0, 6378.137 + 100
    vcG = np.sqrt(mu/rG); vaE = np.sqrt(2*mu*rpE/(rG*(rG + rpE)))
    check("P1: v_c GEO", vcG, 3.0747, 5e-5); check("P1: v_a", vaE, 1.5868, 5e-5); check("P1: burn", vcG - vaE, 1.488, 5e-4)
    atE = (rG + rpE)/2
    check("P1: fall time, h", np.pi*np.sqrt(atE**3/mu)/3600, 5.24, 5e-3); check("P1: perigee speed", np.sqrt(mu*(2/rpE - 1/atE)), 10.33, 5e-3)
    rg2 = rG + 300; ag = (rG + rg2)/2
    g1 = (np.sqrt(mu*(2/rG - 1/ag)) - vcG)*1e3; g2 = (np.sqrt(mu/rg2) - np.sqrt(mu*(2/rg2 - 1/ag)))*1e3
    check("P1: graveyard dv1, m/s", g1, 5.445, 5e-4); check("P1: graveyard dv2, m/s", g2, 5.435, 5e-4); check("P1: total", g1 + g2, 10.9, 0.05)
    check("P1: ratio", (vcG - vaE)/((g1 + g2)/1e3), 137, 0.5)
    import sympy as sp
    h_, m_, a1, a2 = sp.symbols("h mu r1 r2", positive=True)
    dv2sq = 2*(h_**2/(2*a1**2) - m_/a1) + 3*m_/a2 - 2*h_*sp.sqrt(m_)/a2**sp.Rational(3, 2)
    check("P4: d(dv2^2)/dh = 2h/r1^2 - 2 sqrt(mu)/r2^1.5", float(sp.simplify(sp.diff(dv2sq, h_) - (2*h_/a1**2 - 2*sp.sqrt(m_)/a2**sp.Rational(3, 2))) == 0), 1, 0)
    hH = sp.sqrt(2*m_*a1*a2/(a1 + a2))
    check("P4: h_H/r1^2 = sqrt(mu)/r1^1.5 sqrt(2 r2/(r1+r2))", float(sp.simplify(hH/a1**2 - sp.sqrt(m_)/a1**sp.Rational(3, 2)*sp.sqrt(2*a2/(a1 + a2))) == 0), 1, 0)
    rng = np.random.default_rng(7); worst = 1.0
    for _ in range(2000):
        R1_, R2_ = sorted(rng.uniform(1, 100, 2)); MU_ = 1.0
        HH = np.sqrt(2*MU_*R1_*R2_/(R1_ + R2_)); hh = HH*(1 + rng.uniform(1e-6, 2))
        worst = min(worst, hh/R1_**2 - np.sqrt(MU_)/R2_**1.5)
    check("P4: bracket positive for 2000 random cases with h > h_H", float(worst > 0), 1, 0)


def to_venus():
    """Problem 2, to Venus."""
    import numpy as np
    from numpy import sqrt, pi

    # ---------------------------------------------------------------- data table of the paper
    mu = 398600.0          # km^3/s^2
    Re = 6378.0            # km
    muS = 1.327e11         # km^3/s^2
    AU = 1.496e8           # km
    muV = 3.249e5          # km^3/s^2
    RV = 6052.0            # km
    g0 = 9.81e-3           # km/s^2

    print("\nQ7")
    r1 = AU; r2 = 0.723 * AU; at = (r1 + r2) / 2
    V1 = sqrt(muS / r1); V2 = sqrt(muS / r2)
    Va = sqrt(muS * (2 / r1 - 1 / at)); Vp = sqrt(muS * (2 / r2 - 1 / at))
    check("P2 Earth orbital speed [km/s]", V1, 29.783)
    check("P2 Venus orbital speed [km/s]", V2, 35.027)
    check("P2 transfer aphelion speed [km/s]", Va, 27.284)
    check("P2 transfer perihelion speed [km/s]", Vp, 37.737)
    vinf1 = V1 - Va; vinf2 = Vp - V2
    check("P2 v_inf at Earth [km/s]", vinf1, 2.499)
    check("P2 v_inf at Venus [km/s]", vinf2, 2.711)
    t12 = pi * sqrt(at**3 / muS)
    check("P2 transfer time [d]", t12 / 86400, 146.0)
    rpE = Re + 250; raE = Re + 23000; aE = (rpE + raE) / 2
    vpE = sqrt(mu * (2 / rpE - 1 / aE)); vhE = sqrt(vinf1**2 + 2 * mu / rpE); vcE = sqrt(mu / rpE)
    check("P2 parking perigee speed [km/s]", vpE, 9.906)
    check("P2 hyperbola perigee speed [km/s]", vhE, 11.248)
    check("P2 departure burn from ellipse [km/s]", vhE - vpE, 1.342)
    check("P2 departure burn from circle [km/s]", vhE - vcE, 3.493)
    rpV = RV + 500; raV = RV + 60000; aV = (rpV + raV) / 2
    vpV = sqrt(muV * (2 / rpV - 1 / aV)); vhV = sqrt(vinf2**2 + 2 * muV / rpV); vcV = sqrt(muV / rpV)
    check("P2 capture-orbit periapsis speed [km/s]", vpV, 9.499)
    check("P2 arrival hyperbola periapsis speed [km/s]", vhV, 10.321)
    check("P2 capture burn into ellipse [km/s]", vhV - vpV, 0.822)
    check("P2 capture burn into circle [km/s]", vhV - vcV, 3.279)
    check("P2 circular speed 500 km above Venus [km/s]", vcV, 7.042)
    m0 = 2500.0; Isp = 320.0
    mpe = m0 * (1 - np.exp(-(vhV - vpV) / (Isp * g0)))
    mpc = m0 * (1 - np.exp(-(vhV - vcV) / (Isp * g0)))
    check("P2 propellant ellipse capture [kg]", mpe, 576, 0.5)
    check("P2 propellant circle capture [kg]", mpc, 1620, 0.5)

    check("P2 Venus SOI [km]", r2 * (muV / muS)**0.4, 616000, 500)

    check("P2 parking r_p [km]", Re + 250, 6628); check("P2 parking r_a [km]", Re + 23000, 29378)
    check("P2 circular speed at 250 km [km/s]", sqrt(mu / (Re + 250)), 7.755)
    check("P2 exhaust speed [km/s]", 320 * g0, 3.139)
    check("P2 capture r_p [km]", RV + 500, 6552); check("P2 capture r_a [km]", RV + 60000, 66052)
    check("P2 ellipse/circle departure ratio", 1.342 / 3.493, 0.4, 0.03)
    check("P2 circle/ellipse capture ratio", 3.279 / 0.822, 4.0, 0.05)
    check("P2 propellant fraction circle capture", 1620 / 2500, 0.65, 0.005)


def three_bodies():
    """Problem 3, the same Hohmann transfer at three bodies."""
    import numpy as np

    # ---------------------------------------------------------------- constants (the handout's table)
    from orbit.constants import MU_EARTH as MU, R_EARTH as RE, MU_MOON as MU_M, R_MOON as R_M, MU_MARS as MU_MA, R_MARS as R_MA


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

    def hohmann(mu, r1, r2):
        at = (r1 + r2)/2
        v1, v2 = np.sqrt(mu/r1), np.sqrt(mu/r2)
        d1, d2 = vis(mu, r1, at) - v1, v2 - vis(mu, r2, at)
        return v1, v2, d1, d2, np.pi*np.sqrt(at**3/mu)

    # ================================================================ Problem 5: the same raise at three bodies
    print("\n--- Problem 3")
    for name, mu, Rb, qs in (("Earth", MU, RE, ("7.7843", "7.3501", "220.0", "213.8", "433.8", "48.34")),
                             ("Moon", MU_M, R_M, ("1.5908", "1.3383", "130.7", "119.9", "250.6", "84.50")),
                             ("Mars", MU_MA, R_MA, ("3.4510", "3.1212", "168.6", "160.3", "328.9", "63.92"))):
        v1, v2, d1, d2, tt = hohmann(mu, Rb + 200, Rb + 1000)
        check(f"P3 {name} v1", v1, qs[0]); check(f"P3 {name} v2", v2, qs[1])
        check(f"P3 {name} dv1 m/s", d1*1e3, qs[2]); check(f"P3 {name} dv2 m/s", d2*1e3, qs[3])
        check(f"P3 {name} total m/s", (d1 + d2)*1e3, qs[4]); check(f"P3 {name} tof min", tt/60, qs[5])
    check("P3 Moon r2/r1", (R_M + 1000)/(R_M + 200), "1.413")
    check("P3 Earth r2/r1", (RE + 1000)/(RE + 200), "1.122")


def analytic():
    """Problems 5, 6, 7 and 8, the larger burn, the dearest Hohmann transfer, coaxial ellipses and one-burn circularisation (labels 1 to 4 are the old problem numbers)."""
    import numpy as np
    import sympy as sp

    from orbit.constants import MU_EARTH as mu

    # ---------------------------------------------------------------- 1. Hohmann: which burn is larger
    r1, r2, m = sp.symbols("r1 r2 mu", positive=True)
    dv1 = sp.sqrt(m / r1) * (sp.sqrt(2 * r2 / (r1 + r2)) - 1)
    dv2 = sp.sqrt(m / r2) * (1 - sp.sqrt(2 * r1 / (r1 + r2)))
    claim = sp.sqrt(m) * (sp.sqrt(2 * (r1 + r2)) - sp.sqrt(r1) - sp.sqrt(r2)) / sp.sqrt(r1 * r2)
    diff = sp.simplify(sp.expand(dv1 - dv2 - claim))
    num_ok = all(abs(float((dv1 - dv2 - claim).subs({m: mu, r1: 7000.0, r2: x}))) < 1e-12
                 for x in [7000.0, 8000.0, 42164.0, 1e6])
    truth("1  dv1-dv2 = sqrt(mu)[sqrt(2(r1+r2)) - sqrt r1 - sqrt r2]/sqrt(r1 r2)", diff == 0 or num_ok)
    R = np.linspace(1.0001, 1e4, 200000)
    d1 = np.sqrt(2 * R / (1 + R)) - 1
    d2 = (1 - np.sqrt(2 / (1 + R))) / np.sqrt(R)
    truth("1  dv1 > dv2 for all R>1 (grid)", np.all(d1 > d2))
    truth("1  dv1/dv2 -> 1 as R->1", abs(d1[0] / d2[0] - 1) < 1e-3)
    # inward transfer: the burn at the inner circle is the same magnitude (time reversal)

    # ---------------------------------------------------------------- 2. Hohmann maximum
    Rs = sp.symbols("R", positive=True)
    g = sp.sqrt(2 * Rs / (1 + Rs)) - 1 + 1 / sp.sqrt(Rs) - sp.sqrt(2 / (Rs * (1 + Rs)))
    gp = sp.diff(g, Rs)
    # claim: 2 R^{3/2}(1+R)^{3/2} g'(R) = sqrt2 (1+3R) - (1+R)^{3/2}
    lhs = sp.simplify(2 * Rs**sp.Rational(3, 2) * (1 + Rs)**sp.Rational(3, 2) * gp)
    rhs = sp.sqrt(2) * (1 + 3 * Rs) - (1 + Rs)**sp.Rational(3, 2)
    truth("2  2R^{3/2}(1+R)^{3/2} g' = sqrt2(1+3R)-(1+R)^{3/2}",
          all(abs(float((lhs - rhs).subs(Rs, x))) < 1e-10 for x in [1.5, 3.0, 15.0, 200.0]))
    cubic = sp.Poly(sp.expand((1 + Rs)**3 - 2 * (1 + 3 * Rs)**2), Rs)
    truth("2  (1+R)^3 - 2(1+3R)^2 = R^3 - 15R^2 - 9R - 1", cubic.as_expr() == Rs**3 - 15 * Rs**2 - 9 * Rs - 1)
    roots = np.roots([1, -15, -9, -1])
    real = sorted(r.real for r in roots if abs(r.imag) < 1e-12)
    truth("2  cubic has exactly one root > 1, R=15.5817", len([x for x in real if x > 1]) == 1
          and abs(max(real) - 15.581719) < 1e-5)
    Rstar = max(real)
    gstar = float(g.subs(Rs, Rstar))
    truth("2  max g = 0.536258", abs(gstar - 0.536258) < 1e-6)
    # arrival burn alone
    h_arr = 1 / sp.sqrt(Rs) - sp.sqrt(2 / (Rs * (1 + Rs)))
    hp = sp.diff(h_arr, Rs)
    lhs = sp.simplify(2 * Rs**sp.Rational(3, 2) * (1 + Rs)**sp.Rational(3, 2) * hp)
    rhs = sp.sqrt(2) * (1 + 2 * Rs) - (1 + Rs)**sp.Rational(3, 2)
    truth("2  arrival: 2R^{3/2}(1+R)^{3/2} h' = sqrt2(1+2R)-(1+R)^{3/2}",
          all(abs(float((lhs - rhs).subs(Rs, x))) < 1e-10 for x in [1.5, 3.0, 15.0]))
    cub2 = sp.expand((1 + Rs)**3 - 2 * (1 + 2 * Rs)**2)
    truth("2  arrival cubic R^3 - 5R^2 - 5R - 1", cub2 == Rs**3 - 5 * Rs**2 - 5 * Rs - 1)
    r2roots = [r.real for r in np.roots([1, -5, -5, -1]) if abs(r.imag) < 1e-12]
    Rarr = max(r2roots)
    truth("2  arrival cubic has one root > 1, R = 5.8794", len([x for x in r2roots if x > 1]) == 1
          and abs(Rarr - 5.879362) < 1e-6)
    truth("2  arrival cubic has no rational root", sp.Poly(cub2, Rs).factor_list()[1][0][0].degree() == 3)

    # ---------------------------------------------------------------- 3. aligned coaxial ellipses: which route
    def H(x, y):  # angular momentum of the conic with apsides x, y
        return np.sqrt(2 * mu * x * y / (x + y))

    def Phi(s):
        return np.sqrt(2 * mu / s)

    def L(x, y):
        return (x - y) * Phi(x + y)

    rng = np.random.default_rng(1)
    ok_cyc = ok_sign = True
    n_cross = 0
    for _ in range(200000):
        rp1, ra1, rp2, ra2 = rng.uniform(6500, 4e5, 4)
        rp1, ra1 = min(rp1, ra1), max(rp1, ra1)
        rp2, ra2 = min(rp2, ra2), max(rp2, ra2)
        if not (rp1 < rp2 and ra1 < ra2):
            continue
        n_cross += ra1 > rp2
        h1, h2 = H(rp1, ra1), H(rp2, ra2)
        A1 = (H(rp1, ra2) - h1) / rp1 + (h2 - H(rp1, ra2)) / ra2      # p1 -> a2
        A2 = (H(ra1, rp2) - h1) / ra1 + (h2 - H(ra1, rp2)) / rp2      # a1 -> p2
        a, b, c, d = 1 / rp1, 1 / ra1, 1 / rp2, 1 / ra2
        cyc = L(a, b) + L(b, c) + L(c, d) + L(d, a)
        ok_cyc &= abs((A2 - A1) - cyc) < 1e-9
        ok_sign &= A2 > A1
    truth("3  A2 - A1 = cyclic sum L(a,b)+L(b,c)+L(c,d)+L(d,a)", ok_cyc)
    truth(f"3  A1 cheaper whenever rp1<rp2, ra1<ra2 ({n_cross} samples with ra1>rp2)", ok_sign)
    # anti-aligned: T1 - T2 is the cycle (a,b,d,c); its sign flips between the two circular limits
    def anti(rp1, ra1, rp2, ra2):
        h1, h2 = H(rp1, ra1), H(rp2, ra2)
        T2 = abs(H(rp1, rp2) - h1) / rp1 + abs(h2 - H(rp1, rp2)) / rp2    # peri -> peri
        T1 = abs(H(ra1, ra2) - h1) / ra1 + abs(h2 - H(ra1, ra2)) / ra2    # apo -> apo
        a, b, c, d = 1 / rp1, 1 / ra1, 1 / rp2, 1 / ra2
        return T1 - T2, L(a, b) + L(b, d) + L(d, c) + L(c, a)
    dA, cA = anti(8000, 8000, 21000, 63000)      # inner circular
    dB, cB = anti(8000, 15600, 30000, 30000)     # outer circular
    truth("3  anti-aligned: T1-T2 = cycle (a,b,d,c)", abs(dA - cA) < 1e-9 and abs(dB - cB) < 1e-9)
    truth("3  anti-aligned: T1 cheaper if inner circular, T2 cheaper if outer circular", dA < 0 < dB)
    d2, _ = anti(8400, 15600, 21000, 63000)
    print("     note Example 3: T1-T2 =", d2, "(T1 cheaper)")

    # ---------------------------------------------------------------- 4. one-burn circularisation
    e_, x_ = sp.symbols("e x", positive=True)
    F = 3 * x_**2 - 2 * x_**3 - (1 - e_**2)
    s_, t_ = sp.sqrt(1 - e_), sp.sqrt(1 + e_)
    truth("4  F(sqrt(1-e)) = (1-e)(1-sqrt(1-e))^2",
          sp.simplify(F.subs(x_, s_) - (1 - e_) * (1 - s_)**2) == 0)
    truth("4  F(sqrt(1+e)) = (1+e)(sqrt(1+e)-1)^2",
          sp.simplify(F.subs(x_, t_) - (1 + e_) * (t_ - 1)**2) == 0)
    truth("4  F(1) = e^2", sp.simplify(F.subs(x_, 1) - e_**2) == 0)
    # direct numerical check of the one-burn cost against the formula
    ok = True
    for a, e in [(10000, 0.3), (20000, 0.7), (8000, 0.05)]:
        p = a * (1 - e * e)
        for f in np.linspace(0, np.pi, 50):
            r = p / (1 + e * np.cos(f))
            vr = np.sqrt(mu / p) * e * np.sin(f)
            vt = np.sqrt(mu / p) * (1 + e * np.cos(f))
            dv = np.hypot(vr, vt - np.sqrt(mu / r))
            xx = np.sqrt(1 + e * np.cos(f))
            ok &= abs(dv - np.sqrt(mu / p) * np.sqrt(3 * xx**2 - 2 * xx**3 - (1 - e * e))) < 1e-10
    truth("4  dv(r)^2 = (mu/p)(3x^2-2x^3-(1-e^2)), x^2 = p/r... (here x^2 = 1+e cos f)", ok)
    ee = np.linspace(1e-4, 0.9999, 10000)
    truth("4  apoapsis cheaper than periapsis for all e",
          np.all(np.sqrt(1 - ee) * (1 - np.sqrt(1 - ee)) < np.sqrt(1 + ee) * (np.sqrt(1 + ee) - 1)))

    # 1: second proof via energy, dv1/dv2 = R (vt2+vc2)/(vc1+vt1), and vc1+vt1 < R(vc2+vt2)
    Rg = np.linspace(1.001, 1e3, 20000)
    vc1, vc2 = 1.0, 1 / np.sqrt(Rg)
    vt1, vt2 = np.sqrt(2 * Rg / (1 + Rg)), np.sqrt(2 / (Rg * (1 + Rg)))
    truth("1  dv1/dv2 = R (vt2+vc2)/(vc1+vt1)  (energy form)",
          np.allclose((vt1 - vc1) / (vc2 - vt2), Rg * (vt2 + vc2) / (vc1 + vt1), rtol=1e-10))
    truth("1  vc1+vt1 < R (vc2+vt2) for R>1", np.all(vc1 + vt1 < Rg * (vc2 + vt2)))
    # 4: B(x) = (x-1)^2 (2x+1) has B' = 6x(x-1)
    xb = sp.symbols("x")
    truth("4  B'(x) = 6x(x-1)", sp.expand(sp.diff((xb - 1)**2 * (2 * xb + 1), xb) - 6 * xb * (xb - 1)) == 0)


def chandrayaan():
    """Problem 9, Chandrayaan-3's five burns."""
    import sys
    import numpy as np
    sys.path.insert(0, "codes")
    from _mqburn import burn, MU, RE                                   # noqa: E402

    from orbit.constants import G0

    vis = lambda r, a: np.sqrt(MU * (2 / r - 1 / a))

    # ======================================================================= P9
    print("P9. Chandrayaan-3")
    rpc = RE + 200
    orb = lambda ra_alt: ((rpc + RE + ra_alt) / 2, (RE + ra_alt - rpc) / (RE + ra_alt + rpc))
    (aA, eA), (aB, eB), (aC, eC) = orb(36500), orb(127603), orb(369328)
    vA, vB, vC = vis(rpc, aA), vis(rpc, aB), vis(rpc, aC)
    check("dv A->B [m/s]", (vB - vA) * 1e3, 497.5, 0.05)
    check("dv B->C [m/s]", (vC - vB) * 1e3, 165.6, 0.05)
    check("from a 200 km circle [m/s]", (vC - np.sqrt(MU / rpc)) * 1e3, 3129, 0.5)
    ve = 310 * G0 * 1e-3
    m, a, e, vp, tot = 3900.0, aA, eA, vA, 0.0
    for k in range(5):
        vpt = vp + (vB - vA) / 5; at_ = 1 / (2 / rpc - vpt ** 2 / MU)
        tb = m * ve * 1e3 / 440 * (1 - np.exp(-(vB - vA) / 5 / ve))
        R = burn(a, e, m, 440, 310, tb, eps_target=-MU / (2 * at_))
        tot += R["dv"]; m, a, e, vp = R["m"], R["a"], R["e"], vpt
    check("five finite burns: extra dv [m/s]", (tot - (vB - vA)) * 1e3, 8.9, 0.05)
    check("  perigee after them [km]", R["rp"] - RE, 224, 0.5)
    check("burn 1 duration (formula) [s]", 3900 * ve * 1e3 / 440 * (1 - np.exp(-(vB - vA) / 5 / ve)), 868, 0.5)
    tb = 4068.0
    for _ in range(6):                                           # centre the single burn on its own duration
        R = burn(aA, eA, 3900, 440, 310, tb, eps_target=-MU / (2 * aB)); tb = R["t"]
    check("one burn A->B: duration [min]", R["t"] / 60, 86, 0.5)
    check("  dv [m/s]", R["dv"] * 1e3, 645, 0.5)
    check("  perigee [km]", R["rp"] - RE, 694, 0.5)
    tb = 1213.0
    for _ in range(6):
        R = burn(aB, eB, 3311, 440, 310, tb, eps_target=-MU / (2 * aC)); tb = R["t"]
    check("TLI finite burn: extra dv [m/s]", R["dv"] * 1e3 - (vC - vB) * 1e3, 6.5, 0.05)
    check("  as a fraction [%]", (R["dv"] / (vC - vB) - 1) * 100, 3.9, 0.05)
    check("TLI apogee gain [km per m/s]", 4 * aC ** 2 * vC / MU * 1e-3, 4000, 10)


def reboost_and_deorbit():
    """Problems 10 and 11, keeping a station up, and bringing a satellite down."""
    import numpy as np
    import sympy as sp

    # ---------------------------------------------------------------- constants (the handout's table)
    from orbit.constants import MU_EARTH as MU, R_EARTH as RE
    G0 = 9.80665e-3           # km/s^2

    YEAR = 365.25*86400.0

    def deg(x):
        return np.degrees(x)

    mu, r, v, dr, aD, H, A, u, x, rho = sp.symbols("mu r v Delta_r a_D H A u x rho", positive=True)

    # ======================================================================== Problem 10
    print("\n== Problem 10: reboost")
    t = sp.symbols("t")
    R_ = sp.Function("R")(t)
    eps = -mu/(2*R_)
    drdt = sp.solve(sp.Eq(sp.diff(eps, t), -sp.sqrt(mu/R_)*aD), sp.diff(R_, t))[0]
    truth("1a dr/dt = -(2r/v) a_D", zero(drdt.subs(R_, r) + 2*r/sp.sqrt(mu/r)*aD))
    dvdt = sp.diff(sp.sqrt(mu/R_), t).subs(sp.diff(R_, t), drdt).subs(R_, r)
    truth("1a dv/dt = +a_D", zero(dvdt - aD))
    d_ = sp.symbols("delta", positive=True)
    r1 = r - dr
    dv1 = sp.sqrt(mu/r1)*(sp.sqrt(2*r/(r1 + r)) - 1)
    dv2 = sp.sqrt(mu/r)*(1 - sp.sqrt(2*r1/(r1 + r)))
    s1 = sp.series(dv1.subs(dr, d_*r), d_, 0, 2).removeO()
    s2 = sp.series(dv2.subs(dr, d_*r), d_, 0, 2).removeO()
    truth("1b first burn = v dr/(4r) to first order", zero(s1 - sp.sqrt(mu/r)*d_/4))
    truth("1b second burn = v dr/(4r) to first order", zero(s2 - sp.sqrt(mu/r)*d_/4))
    f = (A/H)/(sp.exp(A/H) - 1)
    truth("1d f ~ 1 - A/(2H)", zero(sp.series(f.subs(A, u*H), u, 0, 2).removeO() - (1 - u/2)))
    # the cycle algebra: (v A/2r) / [v H (e^{A/H}-1)/(2 r aD0)] = aD0 f
    aD0 = sp.symbols("a_D0", positive=True)
    tcyc = v/(2*r*aD0)*sp.integrate(sp.exp(sp.Symbol("x")/H), (sp.Symbol("x"), 0, A))
    truth("1d cost rate = a_D0 f(A)", zero((v*A/(2*r))/tcyc - aD0*f))

    R400 = RE + 400.0
    V400 = np.sqrt(MU/R400)
    rate = 2.0/(30*86400)                      # km/s
    aD_num = V400/(2*R400)*rate                # km/s^2
    dv_year = aD_num*YEAR
    check("1c v at 400 km", V400, "7.66856")
    check("1c a_D (m/s^2)", aD_num*1e3, "4.365e-7")
    check("1c a_D / g0 ~ 45e-9", aD_num/G0, "45e-9", tol=1e-9)
    check("1c decay per year (km)", rate*YEAR, "24.35")
    check("1c reboost dv per year (m/s)", dv_year*1e3, "13.77")
    check("1c same via v dr/2r", V400*rate*YEAR/(2*R400)*1e3, "13.77")
    check("1c propellant per year (kg)", 50000*(1 - np.exp(-dv_year/(300*G0))), "233.6")
    fA = lambda a: (a/60.0)/np.expm1(a/60.0)
    check("1d f(2 km)", fA(2.0), "0.9834")
    check("1d f(20 km)", fA(20.0), "0.8426")
    check("1d dv/yr A=2 (m/s)", fA(2.0)*dv_year*1e3, "13.55")
    check("1d dv/yr A=20 (m/s)", fA(20.0)*dv_year*1e3, "11.61")
    cyc = lambda a: 60.0*np.expm1(a/60.0)/(rate*86400)
    check("1d cycle A=2 (days)", cyc(2.0), "30.5")
    check("1d cycle A=20 (days)", cyc(20.0), "356", tol=0.5)

    # ======================================================================== Problem 11
    print("\n== Problem 11: de-orbit of Megha-Tropiques")
    r1s, rps, res = sp.symbols("r_1 r_p r_e", positive=True)
    va = sp.sqrt(mu*(2/r1s - 2/(r1s + rps)))
    truth("2a v_a = v_c1 sqrt(2 r_p/(r1+r_p))", zero(va**2 - mu/r1s*2*rps/(r1s + rps)))
    ve2 = 2*mu*(1/res - 1/(r1s + rps))
    cos2 = (r1s*va)**2/(res**2*ve2)
    target = r1s*rps/(res*(r1s + rps - res))
    truth("2a cos^2 gamma_e formula", zero(cos2 - target))
    truth("2a gamma_e = 0 at r_p = r_e", zero(target.subs(rps, res) - 1))
    dtarget = sp.simplify(sp.diff(target, rps))
    truth("2a d(cos^2)/dr_p = r1 (r1 - r_e)/(r_e (r1+r_p-r_e)^2)",
       zero(dtarget - r1s*(r1s - res)/(res*(r1s + rps - res)**2)))

    R1 = RE + 867.0
    REI = RE + 120.0
    VC1 = np.sqrt(MU/R1)
    T1 = 2*np.pi*np.sqrt(R1**3/MU)
    check("2b r_1", R1, "7245.137")
    check("2b v_c1", VC1, "7.41730")
    check("2b r_e", REI, "6498.137")
    check("2b period (min)", T1/60, "102.3")
    for hp, vaq, dvq, gq in ((80, "7.20115", "216.1", "1.448"), (0, "7.17739", "239.9", "2.522")):
        rp = RE + hp
        va_n = VC1*np.sqrt(2*rp/(R1 + rp))
        g = deg(np.arccos(np.sqrt(R1*rp/(REI*(R1 + rp - REI)))))
        check(f"2b v_a, perigee {hp} km", va_n, vaq)
        check(f"2b dv (m/s), perigee {hp} km", (VC1 - va_n)*1e3, dvq)
        check(f"2b gamma_e (deg), perigee {hp} km", g, gq)
    rp = RE + 80
    dv80 = VC1 - VC1*np.sqrt(2*rp/(R1 + rp))
    mp = 1000*(1 - np.exp(-dv80/(220*G0)))
    mdot = 44.0/(220*9.80665)
    check("2b propellant (kg)", mp, "95.33")
    check("2b mass flow (kg/s)", mdot, "0.0204")
    check("2b burn time (s)", mp/mdot, "4674")
    check("2b burn time (min)", mp/mdot/60, "77.9")
    check("2b burn/period (%)", 100*mp/mdot/T1, "76", tol=0.5)
    check("2d GEO down to 100 km (km/s), Hohmann Ex 1", np.sqrt(MU/42164)*(1 - np.sqrt(2*(RE+100)/(42164+RE+100))), "1.49")

    gy = (np.sqrt(MU/42164)*(np.sqrt(2*42464/(42164+42464)) - 1) + np.sqrt(MU/42464)*(1 - np.sqrt(2*42164/(42164+42464))))
    check("2d graveyard +300 km (m/s), Hohmann Ex 1", gy*1e3, "10.9")


def computing_6():
    """Problem 12, circle to ellipse. The numbers come from the reference implementation of the assignment this problem was set in (assignments/_assignment-03-key/key.py)."""
    import os
    import sys
    import warnings
    import numpy as np

    warnings.filterwarnings("ignore")
    sys.path.insert(0, os.path.join("..", "assignments", "_assignment-03-key"))   # the reference implementation
    import key as K                                                                 # noqa: E402

    a = K.ans_q6(30)
    truth("A-first is the cheapest", a["best"] == "A-first")
    check("A-first", a["dv_Afirst"], 0.47394); check("through infinity", a["dv_inf"], 0.47413); check("P-first", a["dv_Pfirst"], 0.60086)
    check("P*(30)", a["P_star"], 10.062); truth("through infinity does not win at P = 10", not a["inf_wins"])
    for y in (0.2, 0.5):
        rb = K.rho_boundary(y)
        dev = max(abs(K.coax_boundary(A1, y) - rb) for A1 in (1.0, 1.5, 3.0, 8.0))
        truth(f"boundary from initial ellipses = circle curve at y = {y} (max deviation {dev:.1e})", dev < 1e-10)
    P, A = 3.0, 7.0
    s_other = lambda r, w: r * r * w * w / (2 - r * w * w)
    check("lemma: other apse after a tangential burn", s_other(P, K.v(P, A)), A, tol=1e-9)
    u, w = np.sqrt(P / (A + P)), np.sqrt(A / (A + P))
    truth("u + w >= 1 when u^2 + w^2 = 1", u + w >= 1 and abs(u * u + w * w - 1) < 1e-12)
    check("diagonal P = A = R gives the bi-parabolic cost", K.inf_ce(12.0, 12.0), K.dv_inf(12.0), tol=1e-12)


BLOCKS = [objective, note_exercises, to_venus, three_bodies, analytic, chandrayaan, reboost_and_deorbit, computing_6]


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