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


def objective():
    """The 4 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
    Re = 6378.0

    obj = Objective("phasing-questions.qmd", 4)
    num, right = obj.num, obj.right

    num(2, 23.934 * (1 - 45 / 360), "20.94")
    p1, p2 = 2 * 7000 * (11 / 12) ** (2 / 3) - 7000, 2 * 7000 * (23 / 24) ** (2 / 3) - 7000
    truth(f"Q3   perigee k=1 {p1:.0f} < 6378 < k=2 {p2:.0f}", p1 < Re < p2 and right(3).strip() == "$2$")

    num(4, (2 / 3) * 7000 * np.radians(10) / 86400 * 1e3, "9.4")


def note_exercises():
    """Problems 1 and 2, phasing in GEO, and spacing three satellites."""
    import numpy as np

    from orbit.constants import MU_EARTH as mu, R_EARTH as Re
    vis = lambda r, a: np.sqrt(mu*(2/r - 1/a))
    period = lambda a: 2*np.pi*np.sqrt(a**3/mu)

    # the exercise
    Tg, rg = 86164.0989, 42164.0                   # one sidereal day, s
    # period set by 2 deg per revolution east over 5 revolutions
    check("sidereal day h", Tg/3600, 23.934, 5e-4)
    Tn = Tg*(1 - 2/360); an = (mu*(Tn/(2*np.pi))**2)**(1/3)     # Kepler III with the new period
    check("period h", Tn/3600, 23.80, 5e-3); check("a", an, 42008, 0.5); check("perigee radius", 2*an - rg, 41852, 0.5)
    d = np.sqrt(mu/rg) - vis(rg, an); check("each m/s", d*1e3, 5.72, 5e-3); check("total m/s", 2e3*d, 11.4, 0.05)
    # the worked solution of the exercise
    check("period shorter by, min", (Tg - Tn)/60, 8.0, 0.05); check("five revolutions, h", 5*Tn/3600, 119.0, 0.05)
    check("five revolutions under five days", 5*Tn < 5*86400, 1, 0)
    check("perigee inside GEO by, km", rg - (2*an - rg), 312, 0.5)
    check("v_c GEO", np.sqrt(mu/rg), 3.074666, 5e-7); check("v_a phasing", vis(rg, an), 3.068947, 5e-7)
    lin = np.sqrt(mu/rg)*np.radians(10)/(3*np.pi*5)
    check("small-gap law m/s", lin*1e3, 11.39, 5e-3); check("within 0.5 percent", 100*abs(1 - lin/(2*d)), 0.45, 0.05)
    T20 = Tg*(1 - np.radians(10)/(2*np.pi*20)); a20 = (mu*(T20/(2*np.pi))**2)**(1/3)
    d20 = 2e3*(np.sqrt(mu/rg) - vis(rg, a20)); check("k = 20 total m/s", d20, 2.84, 5e-3); check("a quarter", 2e3*d/d20, 4, 0.05)
    check("k = 20 days", 20*T20/86400, 20, 0.1)

    # exercise 3: spacing three satellites by phasing (moved here from Assignment 04, Problem 1)
    import sympy as sp
    r_s, mu_s, k_s, th_s = sp.symbols("r mu k theta", positive=True); x_s = sp.symbols("x")
    v_s = sp.sqrt(mu_s/r_s); vph_s = sp.sqrt(mu_s*(2/r_s - 1/(r_s*(1 - x_s)**sp.Rational(2, 3))))
    ser = sp.series(2*(v_s - vph_s), x_s, 0, 2).removeO()
    check("P2 first-order cost is v theta/(3 pi k)", sp.simplify(ser.subs(x_s, th_s/(2*sp.pi*k_s)) - v_s*th_s/(3*sp.pi*k_s)), 0, 0)
    D = np.pi/180
    r3 = Re + 550.0; T3 = period(r3); v3 = np.sqrt(mu/r3)
    check("P2 r", r3, 6928.137, 1e-9); check("P2 T s", T3, 5739.0, 0.05); check("P2 T min", T3/60, 95.65, 5e-3); check("P2 v", v3, 7.5851, 5e-5)

    def phase3(dth_, k_):
        """Period, semi-major axis, other apsis radius, speed at the burn point, total dv and time taken."""
        Tph = T3*(1 - dth_/(2*np.pi*k_)); a_ = r3*(Tph/T3)**(2/3); v_ = vis(r3, a_)
        return Tph, a_, 2*a_ - r3, v_, 2*abs(v_ - v3), k_*Tph

    def kmax3(dth_, limit=86400.0):
        """Largest whole k with k*T_ph within the limit."""
        k_ = 1
        while phase3(dth_, k_ + 1)[5] <= limit:
            k_ += 1
        return k_

    check("P2 k bound B", (86400 + T3/3)/T3, 15.39, 5e-3); check("P2 k bound C", (86400 - T3/3)/T3, 14.72, 5e-3)
    check("P2 k B", kmax3(120*D), 15, 0); check("P2 k C", kmax3(-120*D), 14, 0); check("P2 k C 240 ahead", kmax3(240*D), 15, 0)
    est = lambda dth_, k_: 1e3*v3*abs(dth_)/(3*np.pi*k_)
    dv3 = {}
    for nm, dth_, k_, q in (("B", 120*D, 15, (5611.5, 6825.1, 344.0, 7.5276, 114.9, 23.38)),
                            ("C", -120*D, 14, (5875.6, 7037.7, 769.1, 7.6439, 117.6, 22.85)),
                            ("C 240 ahead", 240*D, 15, (5483.9, 6721.3, 136.3, 7.4675, 235.2, None))):
        Tph, a_, o_, v_, d_, t_ = phase3(dth_, k_); dv3[nm] = d_*1e3
        check(f"P2 {nm} T_ph", Tph, q[0], 0.05); check(f"P2 {nm} a_ph", a_, q[1], 0.05); check(f"P2 {nm} other apsis alt", o_ - Re, q[2], 0.05)
        check(f"P2 {nm} v_ph", v_, q[3], 5e-5); check(f"P2 {nm} dv m/s", d_*1e3, q[4], 0.05)
        if q[5]:
            check(f"P2 {nm} time h", t_/3600, q[5], 5e-3); check(f"P2 {nm} within a day", t_ <= 86400, 1, 0)
    check("P2 B estimate", est(120*D, 15), 112.4, 0.05); check("P2 C estimate", est(120*D, 14), 120.4, 0.05)
    check("P2 B estimate low, percent", 100*(dv3["B"] - est(120*D, 15))/dv3["B"], 2.2, 0.05)
    check("P2 C estimate high, percent", 100*(est(120*D, 14) - dv3["C"])/dv3["C"], 2.4, 0.05)
    check("P2 both within 2.5 percent", max(abs(1 - est(120*D, 15)/dv3["B"]), abs(1 - est(120*D, 14)/dv3["C"])) < 0.025, 1, 0)
    check("P2 B + C", dv3["B"] + dv3["C"], 232.5, 0.05); check("P2 240 ahead is twice", dv3["C 240 ahead"]/dv3["C"], 2, 0.05)
    check("P2 240 ahead perigee below 200 km", phase3(240*D, 15)[2] - Re < 200, 1, 0)
    check("P2 week k B", kmax3(120*D, 7*86400), 105, 0); check("P2 week k C", kmax3(-120*D, 7*86400), 105, 0)
    w = [1e3*phase3(s_*120*D, 105)[4] for s_ in (1, -1)]
    check("P2 week B", w[0], 16.1, 0.05); check("P2 week C", w[1], 16.0, 0.05); check("P2 week total", sum(w), 32.1, 0.05)
    check("P2 about a seventh", 232.5/32.1, 7.2, 0.05)


def spadex():
    """Problem 4, a phasing orbit or a drift."""
    import sympy as sp
    from numpy import sqrt, pi, degrees as deg

    # ---------------------------------------------------------------- data table of the paper
    mu = 398600.0          # km^3/s^2
    Re = 6378.0            # km

    print("\nQ3")
    r = Re + 470; vc = sqrt(mu / r); Tc = 2 * pi * sqrt(r**3 / mu); s = 20.0; dth = s / r
    check("P4 v_c [km/s]", vc, 7.6293)
    check("P4 T [min]", Tc / 60, 94.00)
    check("P4 Delta theta [deg]", deg(dth), 0.1673)

    def phasing(k):
        Tph = Tc * (1 - dth / (2 * pi * k))
        aph = (mu * (Tph / (2 * pi))**2)**(1 / 3)
        va = sqrt(mu * (2 / r - 1 / aph))
        return Tph, aph, 2 * aph - r, va, 2 * (vc - va)

    Tph, aph, rp1, va1, dv1 = phasing(1)
    check("P4 k=1 T_ph - T [s]", Tph - Tc, -2.62)
    check("P4 k=1 a_ph [km]", aph, 6845.88)
    check("P4 k=1 perigee radius [km]", rp1, 6843.76)
    check("P4 k=1 total dv [m/s]", dv1 * 1000, 2.37)
    Tph5, aph5, rp5, va5, dv5 = phasing(5)
    check("P4 k=5 a_ph [km]", aph5, 6847.58)
    check("P4 k=5 total dv [m/s]", dv5 * 1000, 0.473)
    check("P4 approx k=1 [m/s]", vc * s / (3 * pi * 1 * r) * 1000, 2.36)
    check("P4 approx k=5 [m/s]", vc * s / (3 * pi * 5 * r) * 1000, 0.473)
    # first-order statements, symbolically
    dT, T0, a0, v0, dv_, rr, ss, kk, dh, NN = sp.symbols("dT T0 a0 v0 dv r s k dh N", positive=True)
    mu_s = sp.symbols("mu", positive=True)
    # T ~ a^(3/2): da/a = (2/3) dT/T ; tangential burn: v^2 = mu(2/r - 1/a) -> dv = (v/2)(da/a)
    a_of_T = (mu_s * (T0 / (2 * sp.pi))**2)**sp.Rational(1, 3)
    da_dT = sp.diff(a_of_T, T0) * T0 / a_of_T
    sym_zero("da/a = (2/3) dT/T", da_dT - sp.Rational(2, 3))
    aa = sp.symbols("a", positive=True)
    vv = sp.sqrt(mu_s * (2 / rr - 1 / aa))
    dv_da = sp.diff(vv, aa).subs(aa, rr)
    sym_zero("dv = (v_c/2) da/a on a circle", dv_da * rr - sp.sqrt(mu_s / rr) / 2)
    # drift: n = sqrt(mu/a^3), dn/n = -(3/2) da/a
    nn = sp.sqrt(mu_s / aa**3)
    sym_zero("dn/n = -(3/2) da/a", sp.diff(nn, aa) * aa / nn + sp.Rational(3, 2))
    # exact drift plan
    N = 4
    dhq = s / (3 * pi * (N + 0.5))
    check("P4 drift dh [km]", dhq, 0.472)
    r2 = r - dhq; at = (r + r2) / 2
    v1 = sqrt(mu * (2 / r - 1 / at)); v2 = sqrt(mu * (2 / r2 - 1 / at)); vc2 = sqrt(mu / r2)
    dvH = (vc - v1) + (v2 - vc2)
    check("P4 drift approx dv [m/s]", vc * dhq / r * 1000, 0.525)
    check("P4 drift exact dv [m/s]", 2 * dvH * 1000, 0.525)
    Tt = 2 * pi * sqrt(at**3 / mu); T2 = 2 * pi * sqrt(r2**3 / mu)
    ttot = Tt + N * T2
    gain = ((2 * pi) * (N + 1) - sqrt(mu / r**3) * ttot) * r
    check("P4 drift exact along-track gain [km]", gain, 20.00)
    check("P4 drift time [min]", ttot / 60, 469.9)
    check("P4 k=5 phasing time [min]", 5 * Tph5 / 60, 469.9)
    check("P4 ratio drift/phasing at equal time", (vc * dhq / r) / (vc * s / (3 * pi * 5 * r)), 1.11)

    r3 = Re + 470; r = r3          # phasing() reads the global r
    check("P4 phasing perigee drop k=1 [km]", r3 - phasing(1)[2], 4.2, 0.06)
    # =============================================================== rounding band of P4
    print("\nRounding")
    def sig(x, n=6):
        from math import log10, floor
        return round(x, -int(floor(log10(abs(x)))) + (n - 1))
    r = Re + 470
    for kq, quoted in ((1, 2.36),):
        vc6 = sig(sqrt(mu / r))
        Tph = Tc * (1 - dth / (2 * pi * kq))
        a6 = sig((mu * (Tph / (2 * pi))**2)**(1 / 3))
        va6 = sig(sqrt(mu * (2 / r - 1 / a6)))
        check(f"P4 k={kq} total dv with six-figure rounding [m/s]", 2 * (vc6 - va6) * 1000, quoted)


def geo_move():
    """Problem 3, moving a geostationary satellite."""
    import numpy as np

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

    SID = 86164.09            # s, sidereal day
    R_GEO = 42164.0
    DAY = 86400.0
    rad = np.radians

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

    # ================================================================ Problem 7: moving a geostationary satellite
    print("\n--- Problem 3")
    vc = np.sqrt(MU/R_GEO)
    check("P3 vc", vc, "3.07467")
    for k, qs in ((1, ("84 728.0", "23.5356", "41 694.4", "3.05730", "34.73", "0.981", "41 224.7")),
                  (3, ("85 685.4", "23.8015", "42 007.9", "3.06895", "11.44", "2.975", "41 851.7"))):
        Tph = SID*(1 - rad(6)/(2*np.pi*k))
        aph = (MU*(Tph/(2*np.pi))**2)**(1/3)
        vph = vis(MU, R_GEO, aph)
        check(f"P3 k={k} Tph s", Tph, qs[0]); check(f"P3 k={k} Tph h", Tph/3600, qs[1])
        check(f"P3 k={k} aph", aph, qs[2]); check(f"P3 k={k} v after burn", vph, qs[3])
        check(f"P3 k={k} total dv m/s", 2*(vc - vph)*1e3, qs[4]); check(f"P3 k={k} days", k*Tph/DAY, qs[5])
        check(f"P3 k={k} lowest radius", 2*aph - R_GEO, qs[6])
    check("P3 k=1 to k=3 ratio", 34.73/11.44, "3.04", tol=0.005)

    check("P3 k=1 below GEO", R_GEO - (2*(MU*(SID*(1 - rad(6)/(2*np.pi))/(2*np.pi))**2)**(1/3) - R_GEO), "939", tol=0.5)
    check("P3 k=3 below GEO", R_GEO - (2*(MU*(SID*(1 - rad(6)/(6*np.pi))/(2*np.pi))**2)**(1/3) - R_GEO), "312", tol=0.5)
    check("P3 6 deg in rad", rad(6), "0.104720")


def invariant():
    """Problem 5, an invariant and an asymmetry of phasing (label 6 is the old number)."""
    import numpy as np
    import sympy as sp

    from orbit.constants import MU_EARTH as mu

    # ---------------------------------------------------------------- 6. phasing
    X = sp.symbols("x", positive=True)
    lower = 1 - sp.sqrt(2 - (1 - X)**sp.Rational(-2, 3))       # each burn / v_c, chaser behind
    upper = sp.sqrt(2 - (1 + X)**sp.Rational(-2, 3)) - 1       # chaser ahead
    sl = sp.series(lower, X, 0, 4).removeO()
    su = sp.series(upper, X, 0, 4).removeO()
    print("     behind:", sp.expand(sl), "   ahead:", sp.expand(su))
    truth("6  behind: x/3 + x^2/3 + ...", sp.expand(sl).coeff(X, 1) == sp.Rational(1, 3)
          and sp.expand(sl).coeff(X, 2) == sp.Rational(1, 3))
    truth("6  ahead:  x/3 - x^2/3 + ...", sp.expand(su).coeff(X, 1) == sp.Rational(1, 3)
          and sp.expand(su).coeff(X, 2) == -sp.Rational(1, 3))
    # product dv_total * t / (r dtheta) with x = dtheta/(2 pi k):  dv_total = 2 v_c * lower, t = k T (1-x)
    # = 2 v_c * lower * k (2 pi r / v_c)(1-x) / (r * 2 pi k x) = 2 lower (1-x)/x
    prod = sp.series(2 * lower * (1 - X) / X, X, 0, 3).removeO()
    print("     dv*t/(r dtheta) =", sp.expand(prod))
    truth("6  dv*t = (2/3) r dtheta (1 + 0*x + O(x^2))", sp.expand(prod).coeff(X, 0) == sp.Rational(2, 3)
          and sp.expand(prod).coeff(X, 1) == 0)
    # Example 6 of the note
    r, dth = 6778.0, np.radians(10)
    T = 2 * np.pi * np.sqrt(r**3 / mu)
    aph = r * (1 - dth / (2 * np.pi))**(2 / 3)
    dv = 2 * (np.sqrt(mu / r) - np.sqrt(mu * (2 / r - 1 / aph)))
    truth("6  Example 6: dv*t vs (2/3) r dtheta within 0.05%",
          abs(dv * T * (1 - dth / (2 * np.pi)) / (2 / 3 * r * dth) - 1) < 5e-4)
    print("     Example 6:", dv * T * (1 - dth / (2 * np.pi)), (2 / 3) * r * dth)
    # minimum k for a perigee floor
    rmin = 6378.137 + 200
    xmax = 1 - ((r + rmin) / (2 * r))**1.5
    kmin = dth / (2 * np.pi * xmax)
    a_k = r * (1 - dth / (2 * np.pi * kmin))**(2 / 3)
    truth("6  k_min formula puts perigee exactly on the floor", abs(2 * a_k - r - rmin) < 1e-8)


def errors_and_iss():
    """Problems 6 and 7, phasing errors, and ISS rendezvous."""
    import sys
    import numpy as np
    sys.path.insert(0, "codes")
    from _mqburn import MU, RE                                   # noqa: E402

    from orbit.constants import G0

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

    # ======================================================================= P6, P7
    print("P6, P7. phasing")
    r = 6778.137; v = np.sqrt(MU / r); T = 2 * np.pi * np.sqrt(r ** 3 / MU); dth = np.radians(20)
    check("ISS speed [km/s]", v, 7.6686, 5e-5)
    check("ISS period [s]", T, 5553.6, 0.05)
    for k, Tph_s, aph_s, hp_s, dv_s in ((2, 5399.4, 6652.0, 148, 146.1), (3, 5450.8, 6694.2, 232, 96.5), (34, 5544.5, 6770.8, 385, 8.4)):
        Tph = T * (1 - dth / (2 * np.pi * k)); aph = (MU * (Tph / (2 * np.pi)) ** 2) ** (1 / 3)
        dvt = 2 * (v - vis(r, aph)) * 1e3
        check(f"k = {k}: T_ph [s]", Tph, Tph_s, 0.05)
        check(f"  a_ph [km]", aph, aph_s, 0.05)
        check(f"  perigee altitude [km]", 2 * aph - r - RE, hp_s, 0.5)
        check(f"  dv total [m/s]", dvt, dv_s, 0.05)
    check("P6(b) small-angle estimate [m/s]", v * dth / (3 * np.pi * 2) * 1e3, 142.0, 0.05)
    check("k* (Q3c)", 7669 * 0.005 * dth / (6 * np.pi * 0.1), 7.1, 0.05)
    check("k_min bound (Q3d)", 2 * 6778 * dth / (3 * np.pi * 200), 2.51, 0.005)
    for k, prop in ((3, 226), (34, 20)):
        Tph = T * (1 - dth / (2 * np.pi * k)); aph = (MU * (Tph / (2 * np.pi)) ** 2) ** (1 / 3)
        check(f"P7(b) propellant k = {k} [kg]", 7000 * (1 - np.exp(-2 * (v - vis(r, aph)) * 1e3 / (300 * G0))), prop, 0.5)
    for k, stated in ((3, 12.8), (34, 57.9)):
        rel = 0.005 * dth; ab = 6 * np.pi * k * 0.1 / (v * 1e3)
        check(f"P7(c) along-track RSS, k = {k} [km]", np.hypot(rel, ab) * r, stated, 0.05)


def debris():
    """Problem 8, dodging a piece of debris."""
    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

    # ======================================================================== Problem 8
    print("\n== Problem 8: collision avoidance")
    a3, dv3, T3s, k3, s0, ep, tt = sp.symbols("a dv T k s_0 epsilon t", positive=True)
    v3 = sp.symbols("v", positive=True)
    da = 2*a3*dv3/v3
    dT = sp.Rational(3, 2)*T3s*da/a3
    truth("3a along-track shift per k revs = 3 dv kT", zero(k3*v3*dT - 3*dv3*k3*T3s))
    truth("3a apogee rise 2 da = 4 a dv / v", zero(2*da - 4*a3*dv3/v3))
    truth("3a half-orbit lag v dT/2 = (3/2) T dv", zero(v3*dT/2 - sp.Rational(3, 2)*T3s*dv3))
    tp = sp.symbols("tp", positive=True)
    serr = sp.integrate(3*ep*tp, (tp, 0, tt))
    truth("3c drag error 3/2 eps t^2", zero(serr - sp.Rational(3, 2)*ep*tt**2))
    dvt = s0/(3*tt) + ep*tt/2
    tstar = sp.solve(sp.diff(dvt, tt), tt)
    truth("3c t* = sqrt(2 s0/(3 eps))", len(tstar) == 1 and zero(tstar[0] - sp.sqrt(2*s0/(3*ep))))
    truth("3c dv* = sqrt(2 s0 eps/3)", zero(dvt.subs(tt, tstar[0]) - sp.sqrt(2*s0*ep/3)))
    truth("3c terms equal at t*", zero((s0/(3*tt) - ep*tt/2).subs(tt, tstar[0])))
    truth("3c minimum (second derivative > 0)", sp.simplify(sp.diff(dvt, tt, 2).subs(tt, tstar[0])) > 0)

    A500 = RE + 500.0
    V500 = np.sqrt(MU/A500)
    T500 = 2*np.pi*np.sqrt(A500**3/MU)
    check("3b a", A500, "6878.137")
    check("3b v", V500, "7.61261")
    check("3b T (min)", T500/60, "94.62")
    KR, KT = 4*A500/V500, 1.5*T500           # s: radial and along-track displacement per unit dv, half an orbit on
    KTOT = np.hypot(KR, KT)
    dv_half = 1000.0/KTOT                    # m/s for a total displacement of 1 km
    dv_day = 1000.0/(3*86400)*1e3
    check("3b 4a/v (s)", KR, "3614", tol=0.5)
    check("3b 3T/2 (s)", KT, "8515", tol=0.5)
    check("3b total factor (s)", KTOT, "9251", tol=0.5)
    check("3b half-orbit dv (m/s)", dv_half, "0.1081")
    check("3b radial part (km)", KR*dv_half/1e3, "0.391")
    check("3b along-track part (km)", KT*dv_half/1e3, "0.921")
    check("3b one-day dv (mm/s)", dv_day, "3.858")
    check("3b ratio", dv_half/(dv_day*1e-3), "28", tol=0.5)
    EPS, S0 = 5e-8, 1000.0
    TS = np.sqrt(2*S0/(3*EPS))
    check("3d t* (s)", TS, "115470", tol=0.5)
    check("3d t* (h)", TS/3600, "32.08")
    check("3d dv* (mm/s)", np.sqrt(2*S0*EPS/3)*1e3, "5.774")
    check("3d revolutions in t*", TS/T500, "20", tol=0.5)
    t5 = 5*86400.0
    check("3d 5 days, first term (mm/s)", S0/(3*t5)*1e3, "0.772")
    check("3d 5 days, second term (mm/s)", EPS*t5/2*1e3, "10.80")
    check("3d 5 days, dv (mm/s)", (S0/(3*t5) + EPS*t5/2)*1e3, "11.57")
    check("3d 5 days, drag error (km)", 1.5*EPS*t5**2/1e3, "14.0")
    check("3d 5-day dv is twice dv*", (S0/(3*t5) + EPS*t5/2)/np.sqrt(2*S0*EPS/3), "2.0")


def computing_9():
    """Problem 9, rendezvous by fitting a transfer to a phase angle. 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_q9(1.6)
    check("Delta beta* [deg]", a["dbeta_star"], 273.18); check("Delta beta_s [deg]", a["dbeta_s"], 315)
    check("r_i/r_1", a["r_i"], 1.874); truth("outer branch, r_i > k", a["r_i"] > 1.6)
    T1 = 2 * np.pi * np.sqrt(6678.137**3 / 398600.0) / 60
    check("period of the initial orbit [min]", T1, 90.52)
    check("Hohmann with wait [periods]", a["t_hohmann_over_T1"], 2.471); check("  [min]", a["t_hohmann_over_T1"] * T1, 223.6)
    check("bi-elliptic [periods]", a["t_outer_over_T1"], 2.006); check("  [min]", a["t_outer_over_T1"] * T1, 181.6)
    check("time saved %", a["time_saved_pct"], 18.8)
    check("dv bi-elliptic", a["dv_outer"], 0.2643); check("dv Hohmann", a["dv_hohmann"], 0.2066); check("extra %", a["dv_extra_pct"], 27.9)
    truth(f"integrated miss {a['miss']:.1e} < 3e-12", a["miss"] < 3e-12)
    check("3^(2/3)", 3 ** (2 / 3), 2.080)
    check("Delta beta* = 3 pi (1 - k^-1.5)", np.degrees(3 * np.pi * (1 - 1.6**-1.5)), a["dbeta_star"], tol=1e-9)


BLOCKS = [objective, note_exercises, spadex, geo_move, invariant, errors_and_iss, debris, computing_9]


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