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


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

    J2 = 1.08263e-3

    obj = Objective("orbital-elements-questions.qmd", 46)
    num, right = obj.num, obj.right

    num(16, np.degrees(np.arccos(0)), "90^\\circ", tol=1e-9)
    num(19, np.degrees(np.arccos(1 / 2)), "60^\\circ", tol=1e-9)
    num(20, np.degrees(np.arctan2(1, -1)), "135^\\circ", tol=1e-9)
    num(23, 180 - 98, "82^\\circ", tol=1e-9)
    nu = 7000 * 64 / mu
    num(27, nu - 1, "0.12")
    num(28, 7000 / (2 - nu), "7990", tol=5)
    h = np.cross([0, 7000, 0], [0, 0, 7.546])
    nv = np.cross([0, 0, 1], h)
    truth("Q31  h along +I, node along +J", h[0] > 0 and abs(h[1]) + abs(h[2]) < 1e-9 and nv[1] > 0 and abs(nv[0]) < 1e-9)
    num(32, np.degrees(np.arcsin(np.sin(np.radians(51.6)) * 0.5)), "23.1")
    num(33, 360 - 60, "300^\\circ", tol=1e-9)
    num(35, np.degrees(np.arccos(np.cos(np.radians(13.72)) * np.sin(np.radians(135)))), "46.6")
    num(38, np.degrees(1e-5 / 1e-4), "5.7")
    e = 0.74
    num(39, 100 * (1 - (np.arccos(e) - e * np.sqrt(1 - e * e)) / np.pi), "92")
    a = Re + 700
    n = np.sqrt(mu / a ** 3)
    Od = 2 * np.pi / (365.2422 * 86400)
    num(40, np.degrees(np.arccos(-2 * Od / (3 * n * J2 * (Re / a) ** 2))), "98.2")
    r, v = np.array([7000.0, 0, 0]), np.array([1.0, np.sqrt(mu / 7000), 0])
    hv = np.cross(r, v)
    ev = np.cross(v, hv) / mu - r / 7000
    f = np.degrees(np.arctan2(np.dot(np.cross(ev, r), hv) / np.linalg.norm(hv), np.dot(ev, r))) % 360
    truth(f"Q41  e = {np.linalg.norm(ev):.4f} (0.13), f = {f:.2f} deg (90)",
          abs(np.linalg.norm(ev) - 0.13) < 0.005 and abs(f - 90) < 0.01 and "0.13" in right(41) and "90" in right(41))
    num(46, 50.3 * 100 / 3600, "1.4")


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

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

    MU = 398600.0
    from orbit.constants import R_EARTH as RE, SIDEREAL_DAY as Tsd
    J2 = 1.08262668e-3
    K = np.array([0, 0, 1.0])

    def R1(t):
        c, s = np.cos(t), np.sin(t)
        return np.array([[1, 0, 0], [0, c, -s], [0, s, c]])

    def R3(t):
        c, s = np.cos(t), np.sin(t)
        return np.array([[c, -s, 0], [s, c, 0], [0, 0, 1]])

    def rv2el(r, v, mu=MU):
        rn, vn = np.linalg.norm(r), np.linalg.norm(v)
        vr = r @ v/rn
        h = np.cross(r, v); hn = np.linalg.norm(h)
        i = np.arccos(h[2]/hn)
        n = np.cross(K, h); nn = np.linalg.norm(n)
        O = np.arctan2(n[1], n[0]) % (2*np.pi)
        e = ((vn**2 - mu/rn)*r - (r @ v)*v)/mu; en = np.linalg.norm(e)
        w = np.arctan2(e[2]/np.sin(i), n @ e/nn) % (2*np.pi)
        f = np.arctan2(hn*vr/mu, e @ r/rn) % (2*np.pi)          # e sin f, e cos f
        a = 1/(2/rn - vn**2/mu)
        return dict(r=rn, v=vn, vr=vr, h=h, hn=hn, i=i, n=n, nn=nn, O=O, e=e, en=en, w=w, f=f, a=a,
                    cosO=n[0]/nn, cosw=n @ e/(nn*en), cosf=e @ r/(en*rn))

    def el2rv(h, e, i, O, w, f, mu=MU):
        p = h**2/mu
        rP = p/(1 + e*np.cos(f))*np.array([np.cos(f), np.sin(f), 0])
        vP = mu/h*np.array([-np.sin(f), e + np.cos(f), 0])
        Q = R3(O) @ R1(i) @ R3(w)
        return Q @ rP, Q @ vP, Q, rP, vP

    # ------------------------------------------------------------------ identities
    Rs1 = lambda t: sp.Matrix([[1, 0, 0], [0, sp.cos(t), -sp.sin(t)], [0, sp.sin(t), sp.cos(t)]])
    Rs3 = lambda t: sp.Matrix([[sp.cos(t), -sp.sin(t), 0], [sp.sin(t), sp.cos(t), 0], [0, 0, 1]])
    adot = 2*np.pi/(365.2422*86400)
    cosi = lambda a, e=0: -2*adot*(1 - e**2)**2*a**3.5/(3*np.sqrt(MU)*J2*RE**2)

    # ------------------------------------------------------------------ worked solutions of Exercises 1-7
    aG = (MU*Tsd**2/(4*np.pi**2))**(1/3)
    ok(f"P1: GEO a = {aG:.1f} km (42164), v = {np.sqrt(MU/aG):.4f} km/s (3.0747)", close(aG, 42164, 0.5) and close(np.sqrt(MU/aG), 3.0747, 5e-5))
    vI = np.sqrt(MU/6778.0); dvI = 2*vI*np.sin(np.radians(8.4/2))
    ok(f"P2: v_c(6778) = {vI:.3f} (7.669), plane change 8.4 deg = {dvI:.2f} km/s (1.12)", close(vI, 7.669, 5e-4) and close(dvI, 1.12, 0.005))
    el3 = rv2el(np.array([7000.0, 0, 0]), np.array([0, 5.0, 5.0]))
    ok(f"P3: h = {el3['h']}, |h| = {el3['hn']:.1f} (49497.5), i = {np.degrees(el3['i']):.3f} (45)",
       np.allclose(el3['h'], [0, -35000, 35000]) and close(el3['hn'], 49497.5, 0.05) and close(np.degrees(el3['i']), 45, 1e-9))
    ok(f"P3: n = {el3['n']}, cos O = {el3['cosO']}", np.allclose(el3['n'], [35000, 0, 0]) and close(el3['cosO'], 1, 1e-12))
    ok(f"P3: mu/r = {MU/7000:.4f} (56.9429), e = {el3['e']} (-0.12193), |e| {el3['en']:.5f}",
       close(MU/7000, 56.9429, 5e-5) and close(el3['e'][0], -0.12193, 5e-6) and close(el3['en'], 0.12193, 5e-6))
    ok(f"P3: v_c = {np.sqrt(MU/7000):.3f} (7.546)", close(np.sqrt(MU/7000), 7.546, 5e-4))
    ok("P3: cos omega = -1 and cos f = -1, e_K = 0, v_r = 0",
       close(el3['cosw'], -1, 1e-12) and close(el3['cosf'], -1, 1e-12) and el3['e'][2] == 0 and el3['vr'] == 0)
    p3 = el3['hn']**2/MU
    ok(f"P3: a = {el3['a']:.1f} (6239.3), p = {p3:.1f} (6146.5), r_a = {el3['a']*(1+el3['en']):.1f} (7000), r_p = {el3['a']*(1-el3['en']):.1f} (5478.5)",
       close(el3['a'], 6239.3, 0.05) and close(p3, 6146.5, 0.05) and close(el3['a']*(1 + el3['en']), 7000, 1e-6) and close(el3['a']*(1 - el3['en']), 5478.5, 0.05))
    ok(f"P3: arccos(1 - 1e-10) = {np.arccos(1 - 1e-10):.2e} ~ sqrt(2e-10) = 1.4e-5", close(np.arccos(1 - 1e-10), 1.4e-5, 0.05e-5))
    a4, e4 = 10000.0, 0.3
    p4 = a4*(1 - e4**2); h4 = np.sqrt(MU*p4)
    r4, v4, Q4, rP4, vP4 = el2rv(h4, e4, *np.radians([40, 250, 60, 250]))
    f4 = np.radians(250)
    ok(f"P4: p = {p4:.0f} (9100), h = {h4:.1f} (60226.7)", close(p4, 9100, 1e-9) and close(h4, 60226.7, 0.05))
    ok(f"P4: r = {p4/(1+e4*np.cos(f4)):.2f} (10140.47), v_r = {MU/h4*e4*np.sin(f4):.5f} (-1.86576), v_t = {MU/h4*(1+e4*np.cos(f4)):.5f} (5.93924)",
       close(p4/(1 + e4*np.cos(f4)), 10140.47, 0.005) and close(MU/h4*e4*np.sin(f4), -1.86576, 5e-6) and close(MU/h4*(1 + e4*np.cos(f4)), 5.93924, 5e-6))
    ok(f"P4: r = {np.round(r4, 3)}", np.allclose(r4, [-7821.151, -4089.827, -4993.209], atol=6e-4))
    ok(f"P4: v = {np.round(v4, 6)}", np.allclose(v4, [2.631062, -4.523091, 3.372658], atol=6e-7))
    el4 = rv2el(np.round(r4, 3), np.round(v4, 6))
    ok(f"P4: h = {np.round(el4['h'], 2)}", np.allclose(el4['h'], [-36378.32, 13240.63, 46136.36], atol=0.05))
    ok(f"P4: n = {np.round(el4['n'], 2)}, e = {np.round(el4['e'], 6)}, |e| = {el4['en']:.6f}",
       np.allclose(el4['n'], [-13240.63, -36378.32, 0], atol=0.05) and np.allclose(el4['e'], [0.135719, -0.209024, 0.167001], atol=6e-7) and close(el4['en'], 0.3, 5e-6))
    ok(f"P4: r.v = {np.round(r4, 3) @ np.round(v4, 6):.0f} (-18920)", close(np.round(r4, 3) @ np.round(v4, 6), -18920, 0.5))
    ok(f"P4: cosines {el4['cosO']:.6f}, {el4['cosw']:.6f}, {el4['cosf']:.6f}; raw arccos 110, 60, 110",
       close(el4['cosO'], -0.34202, 5e-6) and close(el4['cosw'], 0.5, 5e-6) and close(el4['cosf'], -0.34202, 5e-6)
       and np.allclose(np.degrees(np.arccos([el4['cosO'], el4['cosw'], el4['cosf']])), [110, 60, 110], atol=5e-4))
    ok(f"P4: corrected Omega, omega, f = {np.degrees([el4['O'], el4['w'], el4['f']]).round(3)}, i = {np.degrees(el4['i']):.3f}, a = {el4['a']:.3f}",
       np.allclose(np.degrees([el4['O'], el4['w'], el4['f'], el4['i']]), [250, 60, 250, 40], atol=5e-4) and close(el4['a'], 10000, 5e-3))
    ok("P4: tests n_J < 0, e_K > 0, v_r < 0", el4['n'][1] < 0 and el4['e'][2] > 0 and el4['vr'] < 0)
    a5 = RE + 700
    ok(f"P5: alpha_dot = {adot:.3e} rad/s (1.991e-7)", close(adot, 1.991e-7, 5e-11))
    ok(f"P5: cos i = {cosi(a5):.5f} (-0.14242), i = {np.degrees(np.arccos(cosi(a5))):.2f} (98.19)",
       close(cosi(a5), -0.14242, 5e-6) and close(np.degrees(np.arccos(cosi(a5))), 98.19, 0.005))
    T5 = 2*np.pi*np.sqrt(a5**3/MU)
    ok(f"P5: T = {T5:.1f} s (5926.4) = {T5/60:.2f} min (98.77), {86400/T5:.3f} rev/day (14.579)",
       close(T5, 5926.4, 0.05) and close(T5/60, 98.77, 0.005) and close(86400/T5, 14.579, 5e-4))
    ok(f"P5: node spacing {360*T5/86400:.2f} deg (24.69), day-to-day shift {15*360*T5/86400 - 360:.1f} deg (10.4)",
       close(360*T5/86400, 24.69, 0.005) and close(15*360*T5/86400 - 360, 10.4, 0.05))
    T6 = Tsd/2; a6 = (MU*T6**2/(4*np.pi**2))**(1/3); e6 = 0.74
    ok(f"P6: T = {T6:.2f} s (43082.05), a = {a6:.1f} (26561.8), r_p = {a6*(1-e6):.1f} (6906.1), r_a = {a6*(1+e6):.1f} (46217.4)",
       close(T6, 43082.05, 0.005) and close(a6, 26561.8, 0.05) and close(a6*(1 - e6), 6906.1, 0.05) and close(a6*(1 + e6), 46217.4, 0.05))
    ok(f"P6: altitudes {a6*(1-e6)-RE:.0f} (528), {a6*(1+e6)-RE:.0f} (39839)", close(a6*(1 - e6) - RE, 528, 0.5) and close(a6*(1 + e6) - RE, 39839, 0.5))
    n6 = 2*np.pi/T6; p6 = a6*(1 - e6**2)
    wd = lambda ideg: np.degrees(0.75*n6*J2*(RE/p6)**2*(5*np.cos(np.radians(ideg))**2 - 1))*86400
    ok(f"P6: omega-dot {wd(0):.2f} deg/day at i = 0 (0.66), {wd(50):.2f} at 50 deg (0.18)", close(wd(0), 0.66, 0.005) and close(wd(50), 0.18, 0.005))
    ok("P6: critical inclinations 63.43 and 116.57 deg",
       close(np.degrees(np.arccos(1/np.sqrt(5))), 63.43, 0.005) and close(np.degrees(np.arccos(-1/np.sqrt(5))), 116.57, 0.005))
    Om, ii, ww = sp.symbols("Omega i omega", real=True)
    Qs = Rs3(Om)*Rs1(ii)*Rs3(ww)
    hhat = sp.Matrix([sp.sin(ii)*sp.sin(Om), -sp.sin(ii)*sp.cos(Om), sp.cos(ii)])
    nhat = sp.Matrix([sp.cos(Om), sp.sin(Om), 0])
    mhat = hhat.cross(nhat)
    ok("P9: Q (0,0,1) = hhat", sp.simplify(Qs*sp.Matrix([0, 0, 1]) - hhat) == sp.zeros(3, 1))
    ok("P9: K x hhat is along (cos O, sin O, 0)", sp.simplify(sp.Matrix([0, 0, 1]).cross(hhat) - sp.sin(ii)*nhat) == sp.zeros(3, 1))
    ok("P9: hhat x nhat = (-sin O cos i, cos O cos i, sin i)", sp.simplify(mhat - sp.Matrix([-sp.sin(Om)*sp.cos(ii), sp.cos(Om)*sp.cos(ii), sp.sin(ii)])) == sp.zeros(3, 1))
    ok("P9: Q (1,0,0) = cos w nhat + sin w mhat", sp.simplify(Qs*sp.Matrix([1, 0, 0]) - (sp.cos(ww)*nhat + sp.sin(ww)*mhat)) == sp.zeros(3, 1))


def spent_stage():
    """Problem 7, a spent upper stage."""
    import numpy as np
    from numpy import sqrt, sin, cos, pi, arccos, arctan2, radians as rad, degrees as deg

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

    print("\nQ2")
    Rv = np.array([-799.0, 6769.9, -993.1])
    Vv = np.array([-9.4378, 0.4934, -3.1788])
    r = np.linalg.norm(Rv); v = np.linalg.norm(Vv)
    vr = Rv @ Vv / r
    Hv = np.cross(Rv, Vv); h = np.linalg.norm(Hv)
    check("P7 r [km]", r, 6888.8)
    check("P7 v [km/s]", v, 9.9710)
    check("P7 v_r [km/s]", vr, 2.0378)
    check("P7 h_x", Hv[0], -21030.2); check("P7 h_y", Hv[1], 6832.8); check("P7 h_z", Hv[2], 63498.7)
    check("P7 h [km^2/s]", h, 67238.7)
    eps = v**2 / 2 - mu / r
    a = -mu / (2 * eps)
    check("P7 energy [km^2/s^2]", eps, -8.1515)
    check("P7 a [km]", a, 24449, 1)
    Ev = ((v**2 - mu / r) * Rv - r * vr * Vv) / mu
    e = np.linalg.norm(Ev)
    check("P7 e_x", Ev[0], 0.24908); check("P7 e_y", Ev[1], 0.68846); check("P7 e_z", Ev[2], 0.00841)
    check("P7 e", e, 0.7322)
    p = h**2 / mu
    check("P7 p from h [km]", p, 11342.3)
    check("P7 a from p, e [km]", p / (1 - e**2), 24449, 1.5)
    check("P7 perigee altitude [km]", a * (1 - e) - Re, 170, 0.5)
    check("P7 apogee altitude [km]", a * (1 + e) - Re, 35973, 1)
    Tp = 2 * pi * sqrt(a**3 / mu)
    check("P7 period [h]", Tp / 3600, 10.568)
    i = deg(arccos(Hv[2] / h))
    check("P7 i [deg]", i, 19.20)
    Nv = np.cross([0, 0, 1], Hv); n = np.linalg.norm(Nv)
    check("P7 N_x", Nv[0], -6832.8); check("P7 N_y", Nv[1], -21030.2)
    O = 360 - deg(arccos(Nv[0] / n))            # N_y < 0
    check("P7 Omega [deg]", O, 252.00)
    wq = deg(arccos(Nv @ Ev / (n * e)))         # e_z > 0, first value kept
    check("P7 omega [deg]", wq, 178.00)
    fq = deg(arccos(Ev @ Rv / (e * r)))         # v_r > 0, first value kept
    check("P7 theta [deg]", fq, 28.00)
    f = rad(fq)
    E0 = 2 * arctan2(sqrt(1 - e) * sin(f / 2), sqrt(1 + e) * cos(f / 2))
    M0 = E0 - e * sin(E0)
    nmean = sqrt(mu / a**3)
    check("P7 E [deg]", deg(E0), 11.20)
    check("P7 M [rad]", M0, 0.05326)
    check("P7 mean motion [rad/s]", nmean * 1e4, 1.6514, 5e-5)      # quoted as 1.6514e-4
    check("P7 time since perigee [min]", M0 / nmean / 60, 5.37)
    check("P7 time to apogee [h]", (Tp / 2 - M0 / nmean) / 3600, 5.19)

    Rv = np.array([-799.0, 6769.9, -993.1]); Vv = np.array([-9.4378, 0.4934, -3.1788])
    r = np.linalg.norm(Rv); v = np.linalg.norm(Vv); Hv = np.cross(Rv, Vv); h = np.linalg.norm(Hv)
    eps = v**2 / 2 - mu / r; a = -mu / (2 * eps)
    vr = Rv @ Vv / r
    Ev = ((v**2 - mu / r) * Rv - r * vr * Vv) / mu; e = np.linalg.norm(Ev)
    Nv = np.cross([0, 0, 1], Hv); n = np.linalg.norm(Nv)
    check("P7 cos i", Hv[2] / h, 0.94438)
    check("P7 N", n, 22112.3)
    check("P7 cos Omega", Nv[0] / n, -0.30900)
    check("P7 r_p [km]", a * (1 - e), 6548, 0.5)
    check("P7 r_a [km]", a * (1 + e), 42351, 0.5)
    Tp = 2 * pi * sqrt(a**3 / mu); nmean = sqrt(mu / a**3)
    f = rad(28.0)
    E0 = 2 * arctan2(sqrt(1 - e) * sin(f / 2), sqrt(1 + e) * cos(f / 2)); M0 = E0 - e * sin(E0)
    check("P7 half period [h]", Tp / 2 / 3600, 5.284)
    check("P7 time since perigee [s]", M0 / nmean, 322, 0.6)
    check("P7 time since perigee [h]", M0 / nmean / 3600, 0.090)


def what_the_elements_mean():
    """Problems 10, 11, 12, 13, 14, 15, 16, 17, 18 and 19, what the elements mean (each check is labelled with the old problem number, 1 to 10, in the order of the page)."""
    import numpy as np
    import sympy as sp
    from scipy.integrate import quad

    from orbit.constants import MU_EARTH as mu
    rng = np.random.default_rng(7)
    K = np.array([0.0, 0.0, 1.0])

    def wrap(x):
        return np.mod(x, 2 * np.pi)

    def angdiff(x, y):
        return abs((x - y + np.pi) % (2 * np.pi) - np.pi)

    def rv2coe(r, v):
        h = np.cross(r, v)
        n = np.cross(K, h)
        e = np.cross(v, h) / mu - r / np.linalg.norm(r)
        rn, hn, nn, en = map(np.linalg.norm, (r, h, n, e))
        eps = v @ v / 2 - mu / rn
        a = -mu / (2 * eps)
        i = np.arccos(h[2] / hn)
        Om = np.arccos(n[0] / nn)
        if n[1] < 0:
            Om = 2 * np.pi - Om
        w = np.arccos(np.clip(n @ e / (nn * en), -1, 1))
        if e[2] < 0:
            w = 2 * np.pi - w
        f = np.arccos(np.clip(e @ r / (en * rn), -1, 1))
        if r @ v < 0:
            f = 2 * np.pi - f
        return a, en, i, Om, w, f

    def coe2rv(a, e, i, Om, w, f):
        p = a * (1 - e * e)
        r_pf = p / (1 + e * np.cos(f)) * np.array([np.cos(f), np.sin(f), 0])
        v_pf = np.sqrt(mu / p) * np.array([-np.sin(f), e + np.cos(f), 0])
        cO, sO, ci, si, cw, sw = np.cos(Om), np.sin(Om), np.cos(i), np.sin(i), np.cos(w), np.sin(w)
        Q = np.array([[cO * cw - sO * sw * ci, -cO * sw - sO * cw * ci, sO * si],
                      [sO * cw + cO * sw * ci, -sO * sw + cO * cw * ci, -cO * si],
                      [sw * si, cw * si, ci]])
        return Q @ r_pf, Q @ v_pf

    def random_coe():
        return (rng.uniform(7000, 40000), rng.uniform(0.01, 0.9), rng.uniform(0.05, np.pi - 0.05),
                rng.uniform(0, 2 * np.pi), rng.uniform(0, 2 * np.pi), rng.uniform(0, 2 * np.pi))

    samples = [random_coe() for _ in range(3000)]

    # ---------------------------------------------------------------- 1. constants
    ok1 = ok2 = True
    for c in samples:
        r, v = coe2rv(*c)
        h = np.cross(r, v)
        e = np.cross(v, h) / mu - r / np.linalg.norm(r)
        eps = v @ v / 2 - mu / np.linalg.norm(r)
        ok1 &= abs(h @ e) / np.linalg.norm(h) < 1e-12
        ok2 &= abs(e @ e - (1 + 2 * eps * (h @ h) / mu**2)) < 1e-10
    truth("1  h . e = 0", ok1)
    truth("1  e^2 = 1 + 2 eps h^2 / mu^2", ok2)

    # ---------------------------------------------------------------- 2. the local state (nu, gamma)
    ok_a = ok_e = ok_f = ok_F = True
    for c in samples:
        r, v = coe2rv(*c)
        a, e, *_, f = rv2coe(r, v)
        rn, vn = np.linalg.norm(r), np.linalg.norm(v)
        nu = rn * vn**2 / mu
        gam = np.arcsin((r @ v) / (rn * vn))
        ok_a &= abs(a - rn / (2 - nu)) < 1e-6
        ok_e &= abs(e**2 - (1 - nu * (2 - nu) * np.cos(gam)**2)) < 1e-10
        f2 = np.arctan2(nu * np.sin(gam) * np.cos(gam), nu * np.cos(gam)**2 - 1)
        ok_f &= angdiff(f, f2) < 1e-8
        # empty focus: at -2 a e_vec from the attracting focus; claim: P + (2a - r)(2 (rhat.vhat) vhat - rhat)
        h = np.cross(r, v)
        evec = np.cross(v, h) / mu - r / rn
        Fstar = -2 * a * evec
        rh, vh = r / rn, v / vn
        ok_F &= np.linalg.norm(Fstar - (r + (2 * a - rn) * (2 * (rh @ vh) * vh - rh))) < 1e-6 * a
    truth("2  a = r/(2 - nu)", ok_a)
    truth("2  e^2 = 1 - nu(2 - nu) cos^2 gamma", ok_e)
    truth("2  tan f = nu sin g cos g / (nu cos^2 g - 1)", ok_f)
    truth("2  empty focus = P + (2a - r)(2(rhat.vhat)vhat - rhat): PF reflected in the normal", ok_F)

    # ---------------------------------------------------------------- 3. orbit averages
    ok = True
    for a, e in [(10000, 0.1), (20000, 0.6), (9000, 0.95)]:
        T = 2 * np.pi * np.sqrt(a**3 / mu)
        b = a * np.sqrt(1 - e * e)
        rE = lambda E: a * (1 - e * np.cos(E))
        # time average: dt = (rE/a) dE / n  ->  <g>_t = (1/2pi) int g(r(E)) (1 - e cos E) dE
        tav = lambda g: quad(lambda E: g(rE(E)) * (1 - e * np.cos(E)), 0, 2 * np.pi, limit=200)[0] / (2 * np.pi)
        fav = lambda g: quad(lambda f: g(a * (1 - e * e) / (1 + e * np.cos(f))), 0, 2 * np.pi, limit=200)[0] / (2 * np.pi)
        ok &= abs(tav(lambda r: 1 / r) * a - 1) < 1e-10
        ok &= abs(tav(lambda r: r) / (a * (1 + e * e / 2)) - 1) < 1e-10
        ok &= abs(tav(lambda r: r * r) / (a * a * (1 + 1.5 * e * e)) - 1) < 1e-10
        ok &= abs(tav(lambda r: 1 / r**2) * a * b - 1) < 1e-6
        ok &= abs(fav(lambda r: r) / b - 1) < 1e-10
        ok &= abs(fav(lambda r: 1 / r) * a * (1 - e * e) - 1) < 1e-10
        ok &= abs(tav(lambda r: mu * (2 / r - 1 / a)) * a / mu - 1) < 1e-10
        # fraction of time with r < a
        frac = quad(lambda E: (1 - e * np.cos(E)) * (rE(E) < a), 0, 2 * np.pi, points=[np.pi / 2, 3 * np.pi / 2], limit=200)[0] / (2 * np.pi)
        ok &= abs(frac - (0.5 - e / np.pi)) < 1e-9
    truth("3  <1/r>_t=1/a, <r>_t=a(1+e^2/2), <r^2>_t=a^2(1+3e^2/2), <1/r^2>_t=1/(ab), <r>_f=b, <1/r>_f=1/p, <v^2>_t=mu/a, P(r<a)=1/2-e/pi", ok)

    # ---------------------------------------------------------------- 4. symmetries
    okT = okM = True
    for c in samples[:1000]:
        r, v = coe2rv(*c)
        a, e, i, Om, w, f = rv2coe(r, v)
        a2, e2, i2, Om2, w2, f2 = rv2coe(r, -v)
        okT &= (abs(a2 - a) < 1e-6 and abs(e2 - e) < 1e-10 and abs(i2 - (np.pi - i)) < 1e-9
                and angdiff(Om2, Om + np.pi) < 1e-9 and angdiff(w2, np.pi - w) < 1e-8 and angdiff(f2, -f) < 1e-8)
        M = np.diag([1, 1, -1.0])
        a3, e3, i3, Om3, w3, f3 = rv2coe(M @ r, M @ v)
        okM &= (abs(i3 - i) < 1e-9 and angdiff(Om3, Om + np.pi) < 1e-9 and angdiff(w3, w + np.pi) < 1e-8
                and angdiff(f3, f) < 1e-8)
    truth("4  v -> -v : (a, e, pi-i, Om+pi, pi-w, -f)", okT)
    truth("4  z -> -z : (a, e, i, Om+pi, w+pi, f)", okM)

    # ---------------------------------------------------------------- 5. latitude, right ascension, azimuth
    okd = oka = okb = True
    for c in samples:
        r, v = coe2rv(*c)
        a, e, i, Om, w, f = rv2coe(r, v)
        u = w + f
        rn = np.linalg.norm(r)
        dec = np.arcsin(r[2] / rn)
        ra = np.arctan2(r[1], r[0])
        okd &= abs(np.sin(dec) - np.sin(i) * np.sin(u)) < 1e-12
        # tan(alpha - Omega) = cos i tan u, with the quadrant of (alpha - Omega) that of (cos u, cos i sin u)
        oka &= angdiff(ra - Om, np.arctan2(np.cos(i) * np.sin(u), np.cos(u))) < 1e-9
        # azimuth of the velocity, from north towards east
        east = np.cross(K, r)
        east /= np.linalg.norm(east)
        north = np.cross(r / rn, east)
        beta = np.arctan2(v @ east, v @ north)
        okb &= abs(np.cos(i) - np.cos(dec) * np.sin(beta)) < 1e-12
    truth("5  sin(dec) = sin i sin u", okd)
    truth("5  (alpha - Omega) = atan2(cos i sin u, cos u)", oka)
    truth("5  cos i = cos(dec) sin(azimuth)", okb)

    # ---------------------------------------------------------------- 6. quadrant-free formulas
    ok = True
    for c in samples:
        r, v = coe2rv(*c)
        a, e, i, Om, w, f = rv2coe(r, v)
        h = np.cross(r, v)
        hn = np.linalg.norm(h)
        ev = np.cross(v, h) / mu - r / np.linalg.norm(r)
        Om2 = wrap(np.arctan2(h[0], -h[1]))
        i2 = np.arctan2(np.hypot(h[0], h[1]), h[2])
        w2 = wrap(np.arctan2(hn * ev[2], h[0] * ev[1] - h[1] * ev[0]))
        u2 = wrap(np.arctan2(hn * r[2], h[0] * r[1] - h[1] * r[0]))
        rn = np.linalg.norm(r)
        f2 = wrap(np.arctan2(hn * (r @ v), hn**2 - mu * rn))
        ok &= (angdiff(Om, Om2) < 1e-9 and abs(i - i2) < 1e-12 and angdiff(w, w2) < 1e-8
               and angdiff(w + f, u2) < 1e-8 and angdiff(f, f2) < 1e-8)
    truth("6  Om=atan2(hI,-hJ), i=atan2(sqrt(hI^2+hJ^2),hK), w=atan2(h eK, hI eJ - hJ eI), u=..., f=atan2(h r.v, h^2 - mu r)", ok)

    # ---------------------------------------------------------------- 7. an out-of-plane impulse
    ok = True
    for c in samples[:500]:
        r, v = coe2rv(*c)
        a, e, i, Om, w, f = rv2coe(r, v)
        h = np.cross(r, v)
        hn = np.linalg.norm(h)
        W = h / hn
        dv = 1e-6
        a2, e2, i2, Om2, w2, f2 = rv2coe(r, v + dv * W)
        rn = np.linalg.norm(r)
        u = w + f
        di = rn * np.cos(u) / hn * dv
        dO = rn * np.sin(u) / (hn * np.sin(i)) * dv
        dw = -np.cos(i) * dO
        sc = rn / hn * dv / np.sin(i)
        ok &= (abs((i2 - i) - di) < 1e-4 * sc and abs(((Om2 - Om + np.pi) % (2 * np.pi) - np.pi) - dO) < 1e-4 * sc
               and abs(((w2 - w + np.pi) % (2 * np.pi) - np.pi) - dw) < 1e-4 * sc
               and abs(a2 - a) < 1e-6 * a and abs(e2 - e) < 1e-9 and angdiff(f2, f) < 1e-9)
    truth("7  di = r cos u dv/h, dOm = r sin u dv/(h sin i), dw = -cos i dOm, a, e, f unchanged (1st order)", ok)

    # ---------------------------------------------------------------- 8. near-circular orbits
    def kepler(M, e):
        E = M.copy()
        for _ in range(50):
            E = E - (E - e * np.sin(E) - M) / (1 - e * np.cos(E))
        return E

    ok = True
    M = np.linspace(0, 2 * np.pi, 721)
    for e in [1e-3, 1e-4]:
        for w in [0.3, 2.0, 4.5]:
            a = 10000.0
            E = kepler(M, e)
            f = 2 * np.arctan2(np.sqrt(1 + e) * np.sin(E / 2), np.sqrt(1 - e) * np.cos(E / 2))
            r = a * (1 - e * np.cos(E))
            lam = w + M
            xi, eta = e * np.cos(w), e * np.sin(w)
            ok &= np.max(np.abs(r - a * (1 - xi * np.cos(lam) - eta * np.sin(lam)))) < 2 * a * e * e
            ok &= np.max(np.abs((w + f - lam - 2 * (xi * np.sin(lam) - eta * np.cos(lam)) + np.pi) % (2 * np.pi) - np.pi)) < 3 * e * e
    truth("8  r = a(1 - xi cos lam - eta sin lam) + O(e^2), u = lam + 2(xi sin lam - eta cos lam) + O(e^2)", ok)
    # sensitivity of omega: d omega = (xi d eta - eta d xi)/e^2
    xi, eta = 1e-3, 2e-4
    d = 1e-9
    w0 = np.arctan2(eta, xi)
    w1 = np.arctan2(eta + d, xi - 0.5 * d)
    truth("8  d omega = (xi d eta - eta d xi)/e^2", abs((w1 - w0) - (xi * d - eta * (-0.5 * d)) / (xi**2 + eta**2)) < 1e-6 * abs(w1 - w0))

    # ---------------------------------------------------------------- 9. time north of the equator
    def frac_north(e, w):
        # u in (0, pi)  <=>  f in (-w, pi - w)
        # integrate dt/df = r^2/h  (normalised: dM/df = (1-e^2)^{3/2}/(1+e cos f)^2)
        g = lambda f: (1 - e * e)**1.5 / (1 + e * np.cos(f))**2
        return quad(g, -w, np.pi - w, limit=200, epsabs=1e-13)[0] / (2 * np.pi)

    ok = True
    for e in [0.1, 0.5, 0.74, 0.9]:
        near = (np.arccos(e) - e * np.sqrt(1 - e * e)) / np.pi
        ok &= abs(frac_north(e, 1.5 * np.pi) - (1 - near)) < 1e-8
        ok &= abs(frac_north(e, 0.5 * np.pi) - near) < 1e-8
        ok &= abs(frac_north(e, 0.0) - 0.5) < 1e-8
        ws = np.linspace(0, 2 * np.pi, 361)
        vals = np.array([frac_north(e, x) for x in ws])
        ok &= abs(ws[np.argmax(vals)] - 1.5 * np.pi) < 1e-9
    truth("9  fraction north: 1/2 (w=0), near-half (w=90), 1-near-half (w=270, the maximum)", ok)
    print("     Molniya e=0.74: fraction north =", 1 - (np.arccos(0.74) - 0.74 * np.sqrt(1 - 0.74**2)) / np.pi)

    # ---------------------------------------------------------------- 10. J2 secular rates
    ci = 1 / np.sqrt(5)
    truth("10 critical inclination: tan i = 2", abs(np.tan(np.arccos(ci)) - 2) < 1e-12)
    # Om_dot = -3/2 k cos i, w_dot = 3/4 k (5 cos^2 i - 1)
    Omd = lambda i: -1.5 * np.cos(i)
    wd = lambda i: 0.75 * (5 * np.cos(i)**2 - 1)
    truth("10 equatorial: Om_dot + w_dot = 3/2 k", abs(Omd(0) + wd(0) - 1.5) < 1e-15)
    truth("10 polar: Om_dot = 0, w_dot = -3/4 k", abs(Omd(np.pi / 2)) < 1e-15 and abs(wd(np.pi / 2) + 0.75) < 1e-15)
    # the non-singular form: d(xi)/dt, d(eta)/dt at i=0 -- the pair (xi, eta) rotates at Om_dot + w_dot

    # ---------------------------------------------------------------- steps added in the pedagogical rewrite
    es = sp.symbols("e", positive=True)
    truth("9  d/de (arccos e - e sqrt(1-e^2)) = -2 sqrt(1-e^2)",
          sp.simplify(sp.diff(sp.acos(es) - es * sp.sqrt(1 - es**2), es) + 2 * sp.sqrt(1 - es**2)) == 0)
    Eb = sp.symbols("E")
    truth("3  (1/2pi) int (1 - e cos E)^3 dE = 1 + 3e^2/2",
          sp.simplify(sp.integrate((1 - es * sp.cos(Eb))**3, (Eb, 0, 2 * sp.pi)) / (2 * sp.pi) - (1 + sp.Rational(3, 2) * es**2)) == 0)

    # figure of Problem 9: e = 0.6, omega = 90 and 270 deg
    import numpy as _np
    _tn = (_np.arccos(0.6) - 0.6 * _np.sqrt(1 - 0.36)) / _np.pi
    truth(f"9  figure: north fraction {100*_tn:.1f}% (omega 90) and {100*(1-_tn):.1f}% (omega 270)", abs(100*_tn - 14.2) < 0.05 and abs(100*(1-_tn) - 85.8) < 0.05)
    # the integral of Problem 3, via the eccentric anomaly
    from scipy.integrate import quad as _quad
    truth("3  oint df/(1 + e cos f) = 2 pi/sqrt(1 - e^2) at e = 0.6", abs(_quad(lambda f: 1/(1 + 0.6*_np.cos(f)), 0, 2*_np.pi)[0] - 2*_np.pi/0.8) < 1e-10)


def gto_elements():
    """Problem 8, a GTO from Sriharikota, to elements and back."""
    import numpy as np

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

    deg = np.degrees

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

    # ================================================================ Problem 4: a GTO from Sriharikota
    print("\n--- Problem 8")
    rv = np.array([12806.3, -16065.0, 6104.1])
    vv = np.array([0.3344, 4.5392, -0.4312])
    R = np.linalg.norm(rv); V = np.linalg.norm(vv); vr = rv @ vv/R
    check("P8 r", R, "21 432.35"); check("P8 v", V, "4.57188"); check("P8 r.v", rv @ vv, "-71 271.9")
    check("P8 vr", vr, "-3.32544")
    hv = np.cross(rv, vv); H = np.linalg.norm(hv)
    for k, qs in zip(range(3), ("-20 780.50", "7563.29", "63 502.49")):
        check(f"P8 h[{k}]", hv[k], qs)
    check("P8 h", H, "67 242.84")
    i4 = np.arccos(hv[2]/H)
    check("P8 cos i", hv[2]/H, "0.94438"); check("P8 i", deg(i4), "19.200")
    Nv = np.cross([0, 0, 1], hv); N = np.linalg.norm(Nv)
    check("P8 N_x", Nv[0], "-7563.29"); check("P8 N_y", Nv[1], "-20 780.50"); check("P8 N", N, "22 114.08")
    O0 = np.arccos(Nv[0]/N)
    check("P8 arccos(Nx/N)", deg(O0), "110.000"); check("P8 Omega", 360 - deg(O0), "250.000")
    ev = ((V**2 - MU/R)*rv - R*vr*vv)/MU; e4 = np.linalg.norm(ev)
    check("P8 v^2 - mu/r", V**2 - MU/R, "2.30402")
    check("P8 r vr", R*vr, "-71 271.9")
    for k, qs in zip(range(3), ("0.133816", "0.718773", "-0.041818")):
        check(f"P8 e[{k}]", ev[k], qs)
    check("P8 e", e4, "0.73232")
    w0 = np.arccos(Nv @ ev/(N*e4))
    check("P8 arccos for omega", deg(w0), "170.00"); check("P8 omega", 360 - deg(w0), "190.00")
    f0 = np.arccos(ev @ rv/(e4*R))
    check("P8 arccos for f", deg(f0), "130.00"); check("P8 f", 360 - deg(f0), "230.00")
    a4 = 1/(2/R - V**2/MU); p4 = H**2/MU
    check("P8 a", a4, "24 462.9"); check("P8 p", p4, "11 343.69")
    check("P8 a from p/(1-e^2)", p4/(1 - e4**2), "24 462.9")
    check("P8 perigee altitude", p4/(1 + e4) - RE, "170.1"); check("P8 apogee altitude", p4/(1 - e4) - RE, "35 999.5")
    check("P8 T, h", 2*np.pi*np.sqrt(a4**3/MU)/3600, "10.577")
    # (b) the state at apogee, built from p-hat and q-hat
    phat = ev/e4; what = hv/H; qhat = np.cross(what, phat)
    for k, qs in zip(range(3), ("0.18273", "0.98150", "-0.05710")):
        check(f"P8 p-hat[{k}]", phat[k], qs)
    for k, qs in zip(range(3), ("-0.30904", "0.11248", "0.94438")):
        check(f"P8 w-hat[{k}]", what[k], qs)
    for k, qs in zip(range(3), ("-0.93333", "0.15492", "-0.32387")):
        check(f"P8 q-hat[{k}]", qhat[k], qs)
    # the same unit vectors from the rotation matrix R3(Omega) R1(i) R3(omega)
    Om, w4 = 2*np.pi - O0, 2*np.pi - w0

    def R3(t):
        c, s = np.cos(t), np.sin(t)
        return np.array([[c, -s, 0], [s, c, 0], [0, 0, 1]])

    def R1(t):
        c, s = np.cos(t), np.sin(t)
        return np.array([[1, 0, 0], [0, c, -s], [0, s, c]])

    Qm = R3(Om) @ R1(i4) @ R3(w4)
    check("P8 matrix column 1 = p-hat", np.abs(Qm[:, 0] - phat).max(), "0", tol=1e-9)
    check("P8 matrix column 2 = q-hat", np.abs(Qm[:, 1] - qhat).max(), "0", tol=1e-9)
    r_apo = p4/(1 - e4); v_apo = np.sqrt(MU/p4)*(1 - e4)
    check("P8 r at apogee", r_apo, "42 377.6"); check("P8 v at apogee", v_apo, "1.58675")
    check("P8 sqrt(mu/p)", np.sqrt(MU/p4), "5.92778")
    check("P8 v at apogee by vis-viva", vis(MU, r_apo, a4), "1.58675")
    ra_vec, va_vec = -r_apo*phat, -v_apo*qhat
    for k, qs in zip(range(3), ("-7743.6", "-41 593.8", "2419.9")):
        check(f"P8 r_apo[{k}]", ra_vec[k], qs)
    for k, qs in zip(range(3), ("1.4810", "-0.2458", "0.5139")):
        check(f"P8 v_apo[{k}]", va_vec[k], qs)
    check("P8 apogee declination", deg(np.arcsin(ra_vec[2]/r_apo)), "3.27")
    check("P8 r_apo . v_apo", ra_vec @ va_vec, "0", tol=1e-6)


BLOCKS = [objective, note_exercises, spent_stage, what_the_elements_mean, gto_elements]


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