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


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

    num = Objective("plane-changes-questions.qmd", 7).num

    r1, r2 = 6678.0, 42164.0
    vc2 = np.sqrt(mu / r2)
    at = (r1 + r2) / 2
    vt2 = np.sqrt(mu * (2 / r2 - 1 / at))
    num(2, 2 * 7.5 * np.sin(np.radians(30)), "7.50")
    truth("Q4   GEO speeds 1.608, 3.075", abs(vt2 - 1.608) < 5e-4 and abs(vc2 - 3.075) < 5e-4)
    num(4, np.sqrt(vt2 ** 2 + vc2 ** 2 - 2 * vt2 * vc2 * np.cos(np.radians(28.5))), "1.83")
    truth("Q4   separate burns 2.981", abs(vc2 - vt2 + 2 * vc2 * np.sin(np.radians(14.25)) - 2.981) < 5e-4)
    num(5, 2 * 7.5 * np.sin(np.radians(30)) * np.sin(np.radians(30)), "3.75")

    s = np.sin(np.radians(25))
    num(6, s / (1 - 2 * s), "2.73")
    truth("Q6   optimal 0.794 vc vs direct 0.845 vc",
          abs(2 * (2 * np.sqrt(2 * s * (1 - s)) - 1) - 0.794) < 5e-4 and abs(2 * s - 0.845) < 5e-4)


def launch_due_east():
    """Problem 1, the shared turn for a launch due east."""
    import numpy as np
    from scipy.optimize import minimize_scalar

    from orbit.constants import MU_EARTH as mu
    r1, r2 = 6678.137, 42164.0

    at = (r1 + r2)/2
    vc1, vc2 = np.sqrt(mu/r1), np.sqrt(mu/r2)
    vt1, vt2 = np.sqrt(mu*(2/r1 - 1/at)), np.sqrt(mu*(2/r2 - 1/at))

    d = np.radians

    tri = lambda u, w, a: np.sqrt(u*u + w*w - 2*u*w*np.cos(a))

    DI = d(19.2)
    H1 = vt1 - vc1
    def best(a):
        r = minimize_scalar(lambda x: tri(vc1, vt1, x) + tri(vt2, vc2, a - x), bounds=(0, a), method="bounded",
                            options={"xatol": 1e-10})
        return r.x, r.fun

    # the optimum split
    x, f = best(DI)

    # the exercise
    y, g = best(d(13.7))
    check("Sriharikota delta*", np.degrees(y), 1.23, 5e-3); check("total", g, 3.977, 5e-4)
    check("whole turn at GEO", H1 + tri(vt2, vc2, d(13.7)), 3.985, 5e-4); check("saved m/s", (H1 + tri(vt2, vc2, d(13.7)) - g)*1e3, 8.0, 0.05)
    check("the dog-leg, m/s", (f - g)*1e3, 78, 0.5); check("19.2 total, 3 places", f, 4.055, 5e-4)
    # Exercise 1, worked solution: the shared turn for Delta i = 13.7 deg
    from scipy.optimize import minimize_scalar
    D13 = d(13.7)
    tot13 = lambda x: tri(vc1, vt1, x) + tri(vt2, vc2, D13 - x)
    xs = minimize_scalar(tot13, bounds=(0, D13), method="bounded", options={"xatol": 1e-12}).x
    check("P1: small-turn estimate, deg", 0.0944*13.7, 1.29, 5e-3)
    check("P1: delta*", np.degrees(xs), 1.23, 5e-3); check("P1: GEO share", 13.7 - np.degrees(xs), 12.47, 5e-3)
    check("P1: dv1", tri(vc1, vt1, xs), 2.43315, 5e-6); check("P1: dv2", tri(vt2, vc2, D13 - xs), 1.54430, 5e-6)
    check("P1: both sides", vc1*vt1*np.sin(xs)/tri(vc1, vt1, xs), 0.69129, 5e-6)
    check("P1: both sides agree", vt2*vc2*np.sin(D13 - xs)/tri(vt2, vc2, D13 - xs), 0.69129, 5e-6)
    check("P1: total", tot13(xs), 3.97745, 5e-6); check("P1: estimate 5% high, %", 100*(1.29/np.degrees(xs) - 1), 5, 0.5)
    check("P1: all at GEO burn", tri(vt2, vc2, D13), 1.55977, 5e-6); check("P1: total, all at GEO", tot13(0), 3.98550, 5e-6)
    check("P1: saving, m/s", 1e3*(tot13(0) - tot13(xs)), 8.0, 0.05)
    x19 = minimize_scalar(lambda x: tri(vc1, vt1, x) + tri(vt2, vc2, DI - x), bounds=(0, DI), method="bounded", options={"xatol": 1e-12}).x
    t19 = tri(vc1, vt1, x19) + tri(vt2, vc2, DI - x19)
    check("P1: 19.2 total", t19, 4.055, 5e-4); check("P1: extra turn, m/s", 1e3*(t19 - tot13(xs)), 78, 0.5)
    Hplan = vt1 - vc1 + vc2 - vt2
    check("P1: planar Hohmann", Hplan, 3.893, 5e-4); check("P1: turn cost from due east, m/s", 1e3*(tot13(xs) - Hplan), 85, 0.5)
    check("P1: turn cost at 19.2, m/s", 1e3*(t19 - Hplan), 163, 0.5)
    v315 = 315*9.80665e-3
    check("P1: 78 m/s as mass, %", 100*(1 - np.exp(-(t19 - tot13(xs))/v315)), 2.5, 0.05)


def navic():
    """Problem 2, from a sub-GTO to an inclined geosynchronous orbit."""
    import numpy as np
    from numpy import sqrt, sin, cos, radians as rad

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

    g0 = 9.81e-3           # km/s^2
    rGEO = 42164.0         # km

    print("\nQ4")
    rp = Re + 280; ra = Re + 20650
    di = rad(29 - 19.2)
    a0 = (rp + ra) / 2
    vp0 = sqrt(mu * (2 / rp - 1 / a0)); va0 = sqrt(mu * (2 / ra - 1 / a0))
    a1 = (rp + rGEO) / 2
    vp1 = sqrt(mu * (2 / rp - 1 / a1)); va1 = sqrt(mu * (2 / rGEO - 1 / a1)); vcG = sqrt(mu / rGEO)
    check("P2 sub-GTO perigee speed [km/s]", vp0, 9.8015)
    check("P2 sub-GTO apogee speed [km/s]", va0, 2.4145)
    check("P2 new ellipse perigee speed [km/s]", vp1, 10.1689)
    check("P2 new ellipse apogee speed [km/s]", va1, 1.6057)
    check("P2 circular speed at 42164 km [km/s]", vcG, 3.0747)
    d1 = vp1 - vp0
    d2 = sqrt(va1**2 + vcG**2 - 2 * va1 * vcG * cos(di))
    check("P2 plan 1 burn 1 [km/s]", d1, 0.3674)
    check("P2 plan 1 burn 2 [km/s]", d2, 1.5172)
    check("P2 plan 1 total [km/s]", d1 + d2, 1.8846)
    check("P2 coplanar circularisation [km/s]", vcG - va1, 1.4689)
    check("P2 plane-change share of burn 2 [km/s]", d2 - (vcG - va1), 0.0483)
    dpc = 2 * va0 * sin(di / 2)
    check("P2 plan 2 plane change at sub-GTO apogee [km/s]", dpc, 0.4125)
    check("P2 plan 2 total [km/s]", dpc + d1 + vcG - va1, 2.2488)
    check("P2 plan 2 minus plan 1 [km/s]", dpc + d1 + vcG - va1 - (d1 + d2), 0.3642)
    Isp = 310.0; m0 = 1425.0
    check("P2 exhaust speed [km/s]", Isp * g0, 3.0411)
    mp1 = m0 * (1 - np.exp(-(d1 + d2) / (Isp * g0)))
    mp2 = m0 * (1 - np.exp(-(dpc + d1 + vcG - va1) / (Isp * g0)))
    check("P2 propellant plan 1 [kg]", mp1, 658, 0.5)
    check("P2 propellant plan 2 [kg]", mp2, 745, 0.5)
    check("P2 extra propellant plan 2 [kg]", mp2 - mp1, 87, 0.6)

    rp = Re + 280; ra = Re + 20650
    check("P2 a sub-GTO [km]", (rp + ra) / 2, 16843)
    check("P2 a raised [km]", (rp + rGEO) / 2, 24411)
    a1 = (rp + rGEO) / 2; va1 = sqrt(mu * (2 / rGEO - 1 / a1)); vcG = sqrt(mu / rGEO); di = rad(9.8)
    check("P2 first-order extra cost of the turn [km/s]", va1 * vcG * di**2 / (2 * (vcG - va1)), 0.049, 0.0006)


def analytic():
    """Problems 3, 4 and 5, plane changes from far away, folded into a Hohmann transfer, and moving the node (labels 7 to 9 are the old numbers)."""
    import numpy as np
    import sympy as sp
    from scipy.optimize import brentq

    from orbit.constants import MU_EARTH as mu

    # ---------------------------------------------------------------- 7. plane change via a high apoapsis
    K, S = sp.symbols("K s", positive=True)
    C = 2 * (sp.sqrt(2 * K / (1 + K)) - 1) + 2 * S * sp.sqrt(2 / (K * (1 + K)))
    dC = sp.diff(C, K)
    claim = 2 / (sp.sqrt(2) * K**sp.Rational(3, 2) * (1 + K)**sp.Rational(3, 2)) * (K - S * (1 + 2 * K))
    truth("7  dC/dK = sqrt2 [K - s(1+2K)] / (K(1+K))^{3/2}",
          all(abs(float((dC - claim).subs({K: k, S: s}))) < 1e-12 for k in [1.0, 2.5, 30.0] for s in [0.2, 0.4, 0.7]))
    Kopt = S / (1 - 2 * S)
    Copt = sp.simplify(C.subs(K, Kopt))
    truth("7  C(K*) = 4 sqrt(2 s(1-s)) - 2",
          all(abs(float((Copt - (4 * sp.sqrt(2 * S * (1 - S)) - 2)).subs(S, s))) < 1e-12 for s in [0.34, 0.4, 0.45, 0.49]))
    Cn = sp.lambdify((K, S), C, "numpy")
    ok = True
    for th in np.radians(np.linspace(1, 179, 357)):
        s = np.sin(th / 2)
        Kg = np.logspace(0, 6, 20001)
        best = Kg[np.argmin(Cn(Kg, s))]
        if s <= 1 / 3:
            ok &= best == 1.0
        elif s < 0.5 - 1e-9:
            ok &= abs(best / (s / (1 - 2 * s)) - 1) < 2e-3
        else:
            ok &= best == Kg[-1]
    truth("7  optimum: K=1 (s<=1/3), K=s/(1-2s) (1/3<s<1/2), K->inf (s>=1/2)", ok)
    truth("7  thresholds 38.94, 48.94, 60 deg",
          abs(2 * np.degrees(np.arcsin(1 / 3)) - 38.942) < 1e-3
          and abs(2 * np.degrees(np.arcsin(np.sqrt(2) - 1)) - 48.94) < 1e-2)

    # ---------------------------------------------------------------- 8. folding the plane change in
    vc1, vt1, vt2, vc2, d, D = sp.symbols("v_c1 v_t1 v_t2 v_c2 delta Di", positive=True)
    dv2exp = sp.sqrt(vt2**2 + vc2**2 - 2 * vt2 * vc2 * sp.cos(D))
    ser = sp.series(dv2exp.subs({vt2: 1.6, vc2: 3.1}), D, 0, 3).removeO()
    truth("8  dv2 = (vc2-vt2) + vt2 vc2 Di^2 / (2(vc2-vt2)) + O(Di^4)",
          abs(float(ser.coeff(D, 2)) - 1.6 * 3.1 / (2 * 1.5)) < 1e-12 and abs(float(ser.coeff(D, 0)) - 1.5) < 1e-12)

    def split_opt(Rr, Di):
        v_c1, v_c2 = 1.0, 1 / np.sqrt(Rr)
        v_t1 = np.sqrt(2 * Rr / (1 + Rr))
        v_t2 = v_t1 / Rr
        d1 = lambda dd: np.sqrt(v_c1**2 + v_t1**2 - 2 * v_c1 * v_t1 * np.cos(dd))
        d2 = lambda dd: np.sqrt(v_t2**2 + v_c2**2 - 2 * v_t2 * v_c2 * np.cos(Di - dd))
        der = lambda dd: v_c1 * v_t1 * np.sin(dd) / d1(dd) - v_t2 * v_c2 * np.sin(Di - dd) / d2(dd)
        x = brentq(der, 1e-15 * Di, Di * (1 - 1e-12), xtol=1e-18)
        D1, D2 = v_t1 - v_c1, v_c2 - v_t2
        return x / Di, 1 / (1 + Rr**1.5 * D2 / D1)

    ok = True
    for Rr in [1.05, 2.0, 6.3136, 20.0]:
        got, pred = split_opt(Rr, np.radians(0.01))
        ok &= abs(got / pred - 1) < 1e-5
    truth("8  small-angle split delta/Di = 1/(1+R^{3/2} dv2/dv1)", ok)
    print("     LEO-GEO fraction (small angle, 28.5 deg):", split_opt(42164 / 6678.137, np.radians(0.01)),
          split_opt(42164 / 6678.137, np.radians(28.5)))

    # ---------------------------------------------------------------- 9. node change
    def hhat(i, O):
        return np.array([np.sin(i) * np.sin(O), -np.sin(i) * np.cos(O), np.cos(i)])

    ok1 = ok2 = True
    for i in np.radians([5, 30, 51.6, 89, 120, 170]):
        for dO in np.radians([1, 10, 90, 170]):
            h1, h2 = hhat(i, -dO / 2), hhat(i, dO / 2)
            alpha = np.arccos(np.clip(h1 @ h2, -1, 1))
            ok1 &= abs(np.sin(alpha / 2) - np.sin(i) * np.sin(dO / 2)) < 1e-12
            x = np.cross(h1, h2)
            x /= np.linalg.norm(x)          # northern intersection (x_K >= 0 for 0<i<pi)
            n1 = np.array([np.cos(-dO / 2), np.sin(-dO / 2), 0])
            n2 = np.array([np.cos(dO / 2), np.sin(dO / 2), 0])
            u1 = np.arctan2(x @ np.cross(h1, n1), x @ n1)   # angle from n1 to x about h1
            u2 = np.arctan2(x @ np.cross(h2, n2), x @ n2)
            ok2 &= abs(u1 - (np.pi / 2 + np.arctan(np.cos(i) * np.tan(dO / 2)))) < 1e-10
            ok2 &= abs(u2 - (np.pi / 2 - np.arctan(np.cos(i) * np.tan(dO / 2)))) < 1e-10
    truth("9  sin(alpha/2) = sin i sin(dOmega/2)", ok1)
    truth("9  burn at u1 = 90+arctan(cos i tan(dO/2)), u2 = 90-arctan(...)", ok2)

    # 8: LEO-GEO, the expansion parameter at the second burn is about 0.5 (not small)
    r1g, r2g = 6678.137, 42164.0
    vc2g = np.sqrt(mu / r2g)
    vt2g = np.sqrt(2 * mu * r1g / (r2g * (r1g + r2g)))
    epsg = 4 * vt2g * vc2g * np.sin(np.radians(28.5) / 2)**2 / (vc2g - vt2g)**2
    print("     LEO-GEO epsilon at the second burn:", epsg)
    truth("8  LEO-GEO: epsilon at second burn ~ 0.5", 0.45 < epsg < 0.6)


def gto_geo():
    """Problem 6, GTO to GEO from three launch sites."""
    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
    print("P6. GTO to GEO")
    rpg, rag = RE + 185, RE + 35786; ag = (rpg + rag) / 2; va = vis(rag, ag); vg = np.sqrt(MU / rag)
    vex = 315 * G0 * 1e-3
    for site, i_d, dvs, tbs, arcs, losss in (("Kourou", 7, 1503, 8116, 25.1, 12.0), ("Sriharikota", 19.2, 1653, 8728, 26.7, 14.9),
                                             ("Cape", 28.5, 1837, 9443, 28.5, 18.9)):
        ir = np.radians(i_d); V0 = np.array([va, 0]); V1 = vg * np.array([np.cos(ir), np.sin(ir)])
        d = np.linalg.norm(V1 - V0); u = (V1 - V0) / d
        tb = 3000 * vex * 1e3 / 440 * (1 - np.exp(-d / vex))
        t = np.linspace(0, tb, 20001); mm = 3000 - 440 / (vex * 1e3) * t; sv = vex * np.log(3000 / mm)
        sp = np.linalg.norm(V0[None, :] + sv[:, None] * u[None, :], axis=1)
        arc = np.trapz(sp, t) / rag
        check(f"{site}: dv [m/s]", d * 1e3, dvs, 0.5)
        check(f"  burn time [s]", tb, tbs, 0.5)
        check(f"  arc [deg]", np.degrees(arc), arcs, 0.05)
        check(f"  loss theta^2/6 [m/s]", (arc / 2) ** 2 / 6 * d * 1e3, losss, 0.05)
    ir = np.radians(28.5); d = np.sqrt(va ** 2 + vg ** 2 - 2 * va * vg * np.cos(ir))
    beta = np.arctan2(vg * np.sin(ir), vg * np.cos(ir) - va)
    dvf = -va * d * np.sin(beta) / vg                             # d|v_f|/d beta
    check("P6(c) speed change per degree of yaw (Cape) [m/s]", abs(dvf) * np.radians(1) * 1e3, 13.3, 0.05)
    gain = 2 * rag ** 2 * vg / MU * 1e-3
    check("  semi-major axis error [km]", gain * abs(dvf) * np.radians(1) * 1e3, 364, 1)
    check("  drift [deg/day]", 360 * 1.5 * gain * abs(dvf) * np.radians(1) * 1e3 / rag, 4.7, 0.05)
    check("GEO gain [km per m/s]", gain, 27.4, 0.05)
    check("angle between dv and v_GEO (cos) (Q8d)", np.cos(np.arcsin(va * np.sin(ir) / d)), 0.91, 0.005)


def small_and_eccentric():
    """Problems 7 and 8, a small plane change folded into a raise, and a plane change on an eccentric orbit."""
    import numpy as np
    import sympy as sp
    from scipy.optimize import minimize_scalar

    # ---------------------------------------------------------------- constants
    from orbit.constants import MU_EARTH as MU, R_EARTH as RE
    G0 = 9.80665e-3           # km/s^2

    DEG = np.pi / 180

    def kepler_time(a, e, f1, f2, mu=MU):
        """Time from true anomaly f1 forward to f2 on an ellipse."""
        def M(f):
            E = 2 * np.arctan(np.sqrt((1 - e) / (1 + e)) * np.tan(f / 2))
            return E - e * np.sin(E)
        n = np.sqrt(mu / a**3)
        return ((M(f2) - M(f1)) % (2 * np.pi)) / n

    # =================================================================== P2
    print("\n=== Problem 7: folding a small plane change into an orbit raise")
    v, vp_, dl = sp.symbols("v v' delta", positive=True)
    lhs = v**2 + vp_**2 - 2 * v * vp_ * sp.cos(dl)
    rhs = (vp_ - v) ** 2 + 4 * v * vp_ * sp.sin(dl / 2) ** 2
    sym_zero("P7 law of cosines split", sp.expand(sp.expand_trig(lhs - rhs).rewrite(sp.cos)))

    # saving fraction 1 - sqrt(A^2+B^2)/(A+B), maximum at A = B
    rho = sp.symbols("rho", positive=True)
    fr = 1 - sp.sqrt(1 + rho**2) / (1 + rho)
    crit = sp.solve(sp.diff(fr, rho), rho)
    truth("P7 saving fraction stationary only at rho = 1", crit == [1])
    sym_zero("P7 max saving = 1 - 1/sqrt 2", fr.subs(rho, 1) - (1 - 1 / sp.sqrt(2)))
    # equal split of a small raise and small turn: 2 sqrt((H/2)^2 + (v di/2)^2) = sqrt(H^2 + (v di)^2)
    H_, di_ = sp.symbols("H Delta_i", positive=True)
    sym_zero("P7 equal split gives Pythagorean sum",
             2 * sp.sqrt((H_ / 2) ** 2 + (v * di_ / 2) ** 2) - sp.sqrt(H_**2 + (v * di_) ** 2))

    r31, r32 = RE + 500, RE + 520

    def hoh(di1=0.0, di2=0.0):
        at = (r31 + r32) / 2
        c1, c2 = np.sqrt(MU / r31), np.sqrt(MU / r32)
        t1, t2_ = np.sqrt(MU * (2 / r31 - 1 / at)), np.sqrt(MU * (2 / r32 - 1 / at))
        b1 = np.sqrt(c1**2 + t1**2 - 2 * c1 * t1 * np.cos(di1))
        b2 = np.sqrt(t2_**2 + c2**2 - 2 * t2_ * c2 * np.cos(di2))
        return b1, b2, c1, c2, t1, t2_

    b1, b2, c1, c2, t1, t2_ = hoh()
    H = b1 + b2
    check("P7 v_c1 [km/s]", c1, "7.6126")
    check("P7 v_c2 [km/s]", c2, "7.6016")
    check("P7 dv1 Hohmann [m/s]", b1 * 1e3, "5.52")
    check("P7 dv2 Hohmann [m/s]", b2 * 1e3, "5.52")
    check("P7 Hohmann total [m/s]", H * 1e3, "11.04")
    check("P7 v_t1 [km/s]", t1, "7.6181")
    check("P7 v_t2 [km/s]", t2_, "7.5960")
    res = {}
    for diD in (0.01, 0.1, 1.0):
        di = diD * DEG
        sep = H + 2 * c2 * np.sin(di / 2)
        all1 = sum(hoh(di, 0)[:2])
        all2 = sum(hoh(0, di)[:2])
        half = sum(hoh(di / 2, di / 2)[:2])
        opt = minimize_scalar(lambda z: sum(hoh(z, di - z)[:2]), bounds=(0, di),
                              method="bounded", options={"xatol": 1e-15})
        pyth = np.sqrt(H**2 + (c1 * di) ** 2)
        res[diD] = dict(plane=2 * c2 * np.sin(di / 2), sep=sep, all1=all1, all2=all2,
                        half=half, opt=opt.fun, dstar=opt.x / di, pyth=pyth)
    R = res[0.1]
    check("P7 0.1 plane alone [m/s]", R["plane"] * 1e3, "13.27")
    check("P7 0.1 separate [m/s]", R["sep"] * 1e3, "24.31")
    check("P7 0.1 all in burn 1 [m/s]", R["all1"] * 1e3, "19.91")
    check("P7 0.1 all in burn 2 [m/s]", R["all2"] * 1e3, "19.89")
    check("P7 0.1 equal split [m/s]", R["half"] * 1e3, "17.27")
    check("P7 0.1 optimum [m/s]", R["opt"] * 1e3, "17.27")
    check("P7 0.1 optimum share", R["dstar"], "0.498")
    check("P7 0.1 Pythagorean [m/s]", R["pyth"] * 1e3, "17.28")
    check("P7 0.1 saving vs separate [%]", (1 - R["half"] / R["sep"]) * 100, "29.0")
    check("P7 0.1 v_c1 * di [m/s]", c1 * 0.1 * DEG * 1e3, "13.29")
    for diD, q_sep, q_half, q_sav in ((0.01, "12.37", "11.12", "10.1"),
                                      (1.0, "143.71", "133.23", "7.3")):
        R = res[diD]
        check(f"P7 {diD} separate [m/s]", R["sep"] * 1e3, q_sep)
        check(f"P7 {diD} equal split [m/s]", R["half"] * 1e3, q_half)
        check(f"P7 {diD} saving [%]", (1 - R["half"] / R["sep"]) * 100, q_sav)
    check("P7 1.0 optimum [m/s]", res[1.0]["opt"] * 1e3, "133.22")
    check("P7 1.0 Pythagorean [m/s]", res[1.0]["pyth"] * 1e3, "133.32")
    check("P7 1.0 plane alone [m/s]", res[1.0]["plane"] * 1e3, "132.67")
    check("P7 1.0 raise hidden in the turn [m/s]", (res[1.0]["opt"] - res[1.0]["plane"]) * 1e3, "0.54")
    check("P7 1.0 optimum share", res[1.0]["dstar"], "0.42")
    # ratio of the two jobs
    check("P7 ratio b/a at 0.1 deg", c1 * 0.1 * DEG / H, "1.20")
    check("P7 0.1 deg in-plane/out-of-plane equal at di [deg]", H / c1 / DEG, "0.083")
    # propellant, 700 kg, Isp 220 s
    ve3 = 220 * G0
    mp = lambda dv: 700 * (1 - np.exp(-dv / ve3))
    check("P7 propellant separate [kg]", mp(res[0.1]["sep"]), "7.84")
    check("P7 propellant combined [kg]", mp(res[0.1]["half"]), "5.58")

    # =================================================================== P3
    print("\n=== Problem 8: a plane change on an eccentric orbit")
    e_, om_, p_ = sp.symbols("e omega p", positive=True)
    r_an = p_ / (1 + e_ * sp.cos(om_))
    r_dn = p_ / (1 - e_ * sp.cos(om_))
    sym_zero("P8 cost ratio AN/DN = r_DN/r_AN", (r_dn / r_an) - (1 + e_ * sp.cos(om_)) / (1 - e_ * sp.cos(om_)))
    rp4, ra4 = 7000.0, 21000.0
    a4 = (rp4 + ra4) / 2
    e4 = (ra4 - rp4) / (ra4 + rp4)
    p4 = a4 * (1 - e4**2)
    s4 = np.sqrt(MU / p4)
    om4 = 50 * DEG
    di4 = 6 * DEG
    check("P8 e", e4, "0.5")
    check("P8 p [km]", p4, "10500")
    check("P8 sqrt(mu/p) [km/s]", s4, "6.1613")
    vals = {}
    for nm, f in (("AN", -om4), ("DN", np.pi - om4)):
        rr = p4 / (1 + e4 * np.cos(f))
        vt = s4 * (1 + e4 * np.cos(f))
        vr = s4 * e4 * np.sin(f)
        vals[nm] = dict(r=rr, vt=vt, vr=vr, v=np.hypot(vr, vt), dv=2 * vt * np.sin(di4 / 2),
                        wrong=2 * np.hypot(vr, vt) * np.sin(di4 / 2))
    check("P8 AN r [km]", vals["AN"]["r"], "7946.2")
    check("P8 DN r [km]", vals["DN"]["r"], "15472.9")
    check("P8 AN v_theta [km/s]", vals["AN"]["vt"], "8.1415")
    check("P8 DN v_theta [km/s]", vals["DN"]["vt"], "4.1811")
    check("P8 |v_r| [km/s]", abs(vals["AN"]["vr"]), "2.3599")
    check("P8 AN v [km/s]", vals["AN"]["v"], "8.4767")
    check("P8 DN v [km/s]", vals["DN"]["v"], "4.8011")
    check("P8 AN dv [km/s]", vals["AN"]["dv"], "0.852")
    check("P8 DN dv [km/s]", vals["DN"]["dv"], "0.438")
    check("P8 ratio", vals["AN"]["dv"] / vals["DN"]["dv"], "1.947")
    check("P8 ratio formula", (1 + e4 * np.cos(om4)) / (1 - e4 * np.cos(om4)), "1.947")
    check("P8 DN wrong (full v) [km/s]", vals["DN"]["wrong"], "0.503")
    check("P8 DN wrong overestimate [%]", (vals["DN"]["wrong"] / vals["DN"]["dv"] - 1) * 100, "14.8")
    va4 = np.sqrt(MU * (2 / ra4 - 1 / a4))
    check("P8 v_a [km/s]", va4, "3.0807")
    check("P8 node at apoapsis dv [km/s]", 2 * va4 * np.sin(di4 / 2), "0.322")
    ve4 = 315 * G0
    check("P8 mass left AN [%]", np.exp(-vals["AN"]["dv"] / ve4) * 100, "75.9")
    check("P8 mass left DN [%]", np.exp(-vals["DN"]["dv"] / ve4) * 100, "86.8")
    # time from AN to DN (f = 310 deg -> 130 deg)
    check("P8 time AN -> DN [min]", kepler_time(a4, e4, -om4, np.pi - om4) / 60, "68.6")
    check("P8 period [min]", 2 * np.pi * np.sqrt(a4**3 / MU) / 60, "274.8")
    # radial component unchanged -> same r, same speed, so same a; same h -> same p, e
    truth("P8 v_theta at DN equals h/r", abs(vals["DN"]["vt"] - np.sqrt(MU * p4) / vals["DN"]["r"]) < 1e-12)

    check("P7 LEO-GEO transfer speeds [km/s]", np.sqrt(MU * (2 / (RE + 300) - 2 / (RE + 300 + 42164))), "10.2")
    check("P7 max saving", 1 - 1 / np.sqrt(2), "0.293")


def computing_5():
    """Problem 9, a transfer with a plane change. 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
    from scipy.optimize import brentq
    warnings.filterwarnings("ignore")
    sys.path.insert(0, os.path.join("..", "assignments", "_assignment-03-key"))   # the reference implementation
    import key as K                                                                 # noqa: E402
    DEG = np.pi / 180

    a = K.ans_q5(44)
    check("three-impulse cost", a["dv_3"], 0.62143); check("r_i/r_1", a["k_opt"], 2.40)
    for n, q in zip(("alpha1", "alpha2", "alpha3"), (5.05, 36.60, 2.36)):
        check(f"{n} [deg]", a["split"][("alpha1", "alpha2", "alpha3").index(n)], q, tol=0.01)
    h, (h1, h2) = K.split2(2.0, 44)
    check("generalised Hohmann", h, 0.62671); check("its turn 1 [deg]", h1, 5.25); check("its turn 2 [deg]", h2, 38.75)
    check("through infinity", a["dv_inf"], 0.70711)
    check("saving vs Hohmann %", a["saving_vs_H_pct"], 0.84); check("saving vs infinity %", a["saving_vs_inf_pct"], 12.1)
    gH = lambda i: K.split2(2.0, i)[0] - K.best_finite(2.0, i)[0]
    gI = lambda i: K.dv_inf_pc(2.0) - K.best_finite(2.0, i)[0]
    check("crossover Hohmann / three-impulse [deg]", brentq(gH, 35, 38, xtol=1e-3), 36.0)
    check("crossover three-impulse / infinity [deg]", brentq(gI, 57, 58, xtol=1e-3), 57.4)
    cc = lambda R, i: np.sqrt(2) * (np.sqrt(1 + R - 2 * np.sqrt(R) * np.cos(i * DEG)) - (1 + np.sqrt(R)) / 2)
    for (R, i), q in (((1, 50), -0.21887), ((4, 30), -0.36867), ((4, 50), 0.08270), ((12, 10), 0.35824)):
        check(f"c(R, i) of T5 at ({R}, {i})", cc(R, i), q, tol=2e-5)
    check("i_s(1/2) from the cos i condition [deg]", K.i_s(0.5), 56.94, tol=0.02)


BLOCKS = [objective, launch_due_east, navic, analytic, gto_geo, small_and_eccentric, computing_5]


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