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


def objective():
    """The 3 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("apse-line-rotation-questions.qmd", 3).num

    num(2, 2 * np.sqrt(mu / 10000) * 0.3 * np.sin(np.radians(30)), "1.89")

    sm = np.sqrt(0.6)
    num(3, 2 * np.degrees(np.arcsin(sm / (1 + sm))), "51.8")


def crossover():
    """Problem 1, the crossover angle."""
    import numpy as np
    ok=lambda n,x,y,tol:print(('ok  ' if abs(x-y)<=tol else 'FAIL'),n,round(x,5),y)

    # Exercise 1, worked solution
    T2 = np.sqrt(0.8); ok('P1: t', T2, .89443, 5e-6); ok('P1: sin', T2/(1 + T2), .47214, 5e-6)
    ok('P1: half angle', np.degrees(np.arcsin(T2/(1 + T2))), 28.17, 5e-3)
    for E, tt, ss in ((.2, .8944, .4721), (.4, .7746, .4365), (.8, .4472, .3090)):
        T_ = np.sqrt(1 - E); ok(f'P1 table e={E} t', T_, tt, 5e-5); ok(f'P1 table e={E} sin', T_/(1 + T_), ss, 5e-5)
    ok('P1: e=0.8 is sin 18 deg exactly', 1/(1 + np.sqrt(5)) - np.sin(np.radians(18)), 0, 1e-15)
    ok('P1: e=0.8 gives (sqrt5-1)/4', 1/(1 + np.sqrt(5)), (np.sqrt(5) - 1)/4, 1e-15)
    ok('P1: monotone in e', float(np.all(np.diff([np.sqrt(1 - E)/(1 + np.sqrt(1 - E)) for E in np.linspace(0, .999, 500)]) < 0)), 1, 0)


def turning():
    """Problem 2, turning the apse line with one or two burns."""
    import sympy as sp
    from numpy import sqrt, sin, cos, arcsin, arctan2, radians as rad, degrees as deg

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

    print("\nQ5")
    rp = 7200.0; ra = 21600.0
    a = (rp + ra) / 2; e = (ra - rp) / (ra + rp); p = a * (1 - e**2); h = sqrt(mu * p)
    check("P2 a [km]", a, 14400); check("P2 e", e, 0.5); check("P2 p [km]", p, 10800)
    check("P2 h [km^2/s]", h, 65611.6)
    check("P2 mu/h [km/s]", mu / h, 6.0751)
    eta = rad(40)
    f1 = eta / 2
    vr = mu / h * e * sin(f1); vt = mu / h * (1 + e * cos(f1))
    check("P2 crossing radius [km]", p / (1 + e * cos(f1)), 7347.7)
    check("P2 v_r at crossing [km/s]", vr, 1.0389)
    check("P2 v_theta at crossing [km/s]", vt, 8.9295)
    check("P2 single impulse [km/s]", 2 * vr, 2.0778)
    check("P2 flight-path angle before [deg]", deg(arctan2(vr, vt)), 6.64)
    vaa = sqrt(mu * (2 / ra - 1 / a)); vca = sqrt(mu / ra)
    check("P2 apoapsis speed [km/s]", vaa, 3.0376)
    check("P2 circular speed at r_a [km/s]", vca, 4.2958)
    check("P2 route through the circle [km/s]", 2 * (vca - vaa), 2.5164)
    eta_eq = 2 * arcsin((vca - vaa) / (mu / h * e))
    check("P2 break-even eta [deg]", deg(eta_eq), 48.9)
    # symbolic: vaa = (mu/h)(1-e), vca^2 = mu/ra = (mu/h)^2 (1-e)
    ee, k_ = sp.symbols("e k", positive=True)   # k = mu/h
    sym_zero("P2 break-even sin(eta/2) = (sqrt(1-e)-(1-e))/e", (k_ * sp.sqrt(1 - ee) - k_ * (1 - ee)) / (k_ * ee)
        - (sp.sqrt(1 - ee) - (1 - ee)) / ee)
    check("P2 break-even from closed form [deg]", 2 * deg(arcsin((sqrt(1 - e) - (1 - e)) / e)), 48.9)

    rp5 = 7200.0; ra5 = 21600.0; a5 = (rp5 + ra5) / 2; e5 = 0.5; h5 = sqrt(mu * a5 * (1 - e5**2))
    check("P2 each burn of the circle route [km/s]", sqrt(mu / ra5) - mu / h5 * (1 - e5), 1.2582)
    check("P2 saving of the single impulse [km/s]", 2 * (sqrt(mu / ra5) - mu / h5 * (1 - e5)) - 2 * mu / h5 * e5 * sin(rad(20)), 0.44)
    s_ = sin(rad(20)) / (1 - sin(rad(20)))
    check("P2 s for a 40 deg break-even", s_, 0.51980)
    check("P2 e for a 40 deg break-even", 1 - s_**2, 0.7298)
    e_ = 1 - s_**2
    check("P2 check: break-even angle at that e [deg]", 2 * deg(arcsin((sqrt(1 - e_) - (1 - e_)) / e_)), 40.0)
    ss = sp.symbols("s", positive=True)
    sym_zero("P2 (s - s^2)/(1 - s^2) = s/(1+s)", (ss - ss**2) / (1 - ss**2) - ss / (1 + ss))


def numbers():
    """Problem 3, turning the apse line, with numbers."""
    import numpy as np

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

    deg, rad = np.degrees, np.radians

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

    # ================================================================ Problem 8: turning the apse line
    print("\n--- Problem 3")
    rp8, ra8 = RE + 600, RE + 20000
    a8 = (rp8 + ra8)/2; e8 = (ra8 - rp8)/(ra8 + rp8); p8 = a8*(1 - e8**2)
    check("P3 a", a8, "16 678.137"); check("P3 e", e8, "0.58160"); check("P3 p", p8, "11 036.62")
    check("P3 sqrt(mu/p)", np.sqrt(MU/p8), "6.0097")
    one = 2*np.sqrt(MU/p8)*e8*np.sin(rad(20))
    check("P3 one burn", one, "2.3909")
    r8 = p8/(1 + e8*np.cos(rad(20)))
    check("P3 r at f=20", r8, "7136.4", tol=0.05); check("P3 altitude at f=20", r8 - RE, "758.3")
    g8 = np.arctan(e8*np.sin(rad(20))/(1 + e8*np.cos(rad(20))))
    v8 = vis(MU, r8, a8)
    check("P3 gamma", deg(g8), "7.329"); check("P3 v", v8, "9.3707"); check("P3 2 v sin gamma", 2*v8*np.sin(g8), "2.3909")
    check("P3 v_r = v sin gamma", v8*np.sin(g8), "1.1954")
    check("P3 v_r = sqrt(mu/p) e sin f", np.sqrt(MU/p8)*e8*np.sin(np.radians(20)), "1.1954")
    va8, vca8 = vis(MU, ra8, a8), np.sqrt(MU/ra8)
    check("P3 va", va8, "2.5144"); check("P3 vc at apogee", vca8, "3.8873")
    two = 2*(vca8 - va8)
    check("P3 two burns", two, "2.7457")
    eta_b = 2*np.arcsin(two/(2*np.sqrt(MU/p8)*e8))
    check("P3 break-even eta", deg(eta_b), "46.25")
    check("P3 r=Re+20000", ra8, "26 378.137")

    check("P3 rp", RE + 600, "6978.137")
    check("P3 one burn cheaper by m/s", (two - one)*1e3, "355", tol=0.5)


def by_a_circle():
    """Problem 4, when to go round by a circle (label 5 is the old number)."""
    import numpy as np
    import sympy as sp

    from orbit.constants import MU_EARTH as mu
    ee = np.linspace(1e-4, 0.9999, 10000)

    # ---------------------------------------------------------------- 5. apse-line rotation crossover
    def eta_c(e):
        s = np.sqrt(1 - e)
        return 2 * np.degrees(np.arcsin(s / (1 + s)))

    def eta_c_direct(a, e):
        p = a * (1 - e * e)
        ra = a * (1 + e)
        alt = 2 * (np.sqrt(mu / ra) - np.sqrt(mu * (2 / ra - 1 / a)))
        return 2 * np.degrees(np.arcsin(alt / (2 * np.sqrt(mu / p) * e)))

    truth("5  eta_c(e=0.4) = 51.8 deg (note)", abs(eta_c(0.4) - 51.8) < 0.05)
    truth("5  closed form = direct crossover", all(abs(eta_c(e) - eta_c_direct(12000, e)) < 1e-9
                                                  for e in [0.01, 0.3, 0.4, 0.9]))
    truth("5  eta_c -> 60 deg as e -> 0", abs(eta_c(1e-9) - 60) < 1e-6)
    truth("5  eta_c monotone decreasing", np.all(np.diff(eta_c(ee)) < 0))

    # 5: small-e estimates, dv_C ~ e v and dv_S ~ 2 e v sin(eta/2)
    eb = sp.symbols("e", positive=True)
    dvC = 2 * sp.sqrt(1 - eb) * (1 - sp.sqrt(1 - eb))
    truth("5  dv_C / (e v) -> 1 as e -> 0", sp.limit(dvC / eb, eb, 0) == 1)


def fragile():
    """Problem 5, cheap but fragile."""
    import sys
    import numpy as np
    sys.path.insert(0, "codes")
    from _mqburn import MU                                   # noqa: E402

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

    # ======================================================================= P5
    print("P5. apse rotation")
    a4, e4 = 12000.0, 0.4; p4 = a4 * (1 - e4 ** 2); s = np.sqrt(MU / p4)
    dv4 = 2 * s * e4 * np.sin(np.radians(15)); vth = s * (1 + e4 * np.cos(np.radians(15)))
    check("dv [km/s]", dv4, 1.30204, 5e-6)
    check("v_theta at the crossing [km/s]", vth, 8.71802, 5e-6)
    de = vth * dv4 * np.radians(1); da = 2 * a4 ** 2 * de / MU; T4 = 2 * np.pi * np.sqrt(a4 ** 3 / MU)
    check("delta a for 1 deg [km]", da, 143, 0.5)
    check("delta T per revolution [s]", 1.5 * T4 * da / a4, 234, 0.5)
    check("pointing for |dT| < 10 s [deg]", np.degrees(MU * (2 / 3 * a4 * 10 / T4) / (2 * a4 ** 2) / (vth * dv4)), 0.043, 5e-4)
    vp4 = vis(a4 * (1 - e4), a4)
    check("trim at periapsis for 0.3 deg [m/s]", MU * (2 * a4 ** 2 * vth * dv4 * np.radians(0.3) / MU) / (2 * vp4 * a4 ** 2) * 1e3, 6.8, 0.05)


def in_steps():
    """Problem 6, rotating the apse line in steps."""
    import numpy as np
    import sympy as sp

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

    DEG = np.pi / 180

    # =================================================================== P1
    print("\n=== Problem 6: apse-line rotation in steps")
    y = sp.symbols("y", positive=True)
    # N sin(eta/2N) = (eta/2) sin(y)/y with y = eta/(2N); d/dy (sin y / y) < 0 on (0, pi)
    deriv = sp.diff(sp.sin(y) / y, y)
    sym_zero("P6 d/dy(sin y/y) = (y cos y - sin y)/y^2", deriv - (y * sp.cos(y) - sp.sin(y)) / y**2)
    yy = np.linspace(1e-4, np.pi - 1e-4, 2000)
    truth("P6 y cos y - sin y < 0 on (0, pi)", np.all(yy * np.cos(yy) - np.sin(yy) < 0))
    a_, b_ = sp.symbols("alpha beta", nonnegative=True)
    sym_zero("P6 sin(a+b) = sin a cos b + cos a sin b",
             sp.expand_trig(sp.sin(a_ + b_)) - (sp.sin(a_) * sp.cos(b_) + sp.cos(a_) * sp.sin(b_)))
    N = sp.symbols("N", positive=True)
    eta_s = sp.symbols("eta", positive=True)
    truth("P6 limit N sin(eta/2N) = eta/2",
               sp.limit(N * sp.sin(eta_s / (2 * N)), N, sp.oo) == eta_s / 2)

    # The eccentricity vector e = v x h / mu - r_hat, in the perifocal frame of the old orbit.
    # A radial impulse leaves r and h unchanged, so Delta e = Delta v x h / mu, of length |Delta v| h / mu,
    # perpendicular to r_hat. At f = eta/2 the impulse -2 v_r r_hat turns e through exactly eta.
    mu_s, p_s, e_s, f_s = sp.symbols("mu p e f", positive=True)
    h_s = sp.sqrt(mu_s * p_s)
    rhat = sp.Matrix([sp.cos(f_s), sp.sin(f_s), 0])
    that = sp.Matrix([-sp.sin(f_s), sp.cos(f_s), 0])
    khat = sp.Matrix([0, 0, 1])
    r_s = p_s / (1 + e_s * sp.cos(f_s))
    vr_s = sp.sqrt(mu_s / p_s) * e_s * sp.sin(f_s)
    vt_s = sp.sqrt(mu_s / p_s) * (1 + e_s * sp.cos(f_s))
    v_s = vr_s * rhat + vt_s * that
    hvec = (r_s * rhat).cross(v_s)
    sym_zero("P6 h = r x v = sqrt(mu p) k", sp.simplify(hvec - h_s * khat).norm())
    evec = v_s.cross(hvec) / mu_s - rhat
    sym_zero("P6 e-vector = (e, 0, 0) (points at perigee)", sp.simplify(evec - sp.Matrix([e_s, 0, 0])).norm())
    dv_s = sp.symbols("dv_r", real=True)
    dvec = dv_s * rhat
    sym_zero("P6 radial impulse leaves h unchanged", sp.simplify((r_s * rhat).cross(dvec)).norm())
    de = dvec.cross(hvec) / mu_s
    sym_zero("P6 |De|^2 = (h/mu)^2 dv^2", sp.simplify(de.dot(de) - (h_s / mu_s)**2 * dv_s**2))
    sym_zero("P6 De . r_hat = 0", sp.simplify(de.dot(rhat)))
    e_after = sp.simplify(evec + de.subs(dv_s, -2 * vr_s)).subs(f_s, eta_s / 2)
    sym_zero("P6 impulse at f=eta/2 turns e by eta",
             sp.simplify(e_after - e_s * sp.Matrix([sp.cos(eta_s), sp.sin(eta_s), 0])).norm())
    sym_zero("P6 cost = sqrt(mu/p) x chord 2 e sin(eta/2)",
             sp.simplify(2 * vr_s.subs(f_s, eta_s / 2) - sp.sqrt(mu_s / p_s) * 2 * e_s * sp.sin(eta_s / 2)))

    rp2, ra2 = RE + 500, RE + 20000
    a2 = (rp2 + ra2) / 2
    e2 = (ra2 - rp2) / (ra2 + rp2)
    p2 = a2 * (1 - e2**2)
    s2 = np.sqrt(MU / p2)
    eta = 30 * DEG
    check("P6 a [km]", a2, "16628.1")
    check("P6 e", e2, "0.5864")
    check("P6 p [km]", p2, "10911.2")
    check("P6 sqrt(mu/p) [km/s]", s2, "6.0441")
    cost = {Nn: 2 * Nn * s2 * e2 * np.sin(eta / (2 * Nn)) for Nn in (1, 2, 3, 6, 10)}
    check("P6 N=1 [km/s]", cost[1], "1.835")
    check("P6 N=2 [km/s]", cost[2], "1.850")
    check("P6 N=3 [km/s]", cost[3], "1.853")
    check("P6 N=6 [km/s]", cost[6], "1.855")
    check("P6 N=10 [km/s]", cost[10], "1.855")
    check("P6 N=10 short of the limit [m/s]", (s2 * e2 * eta - cost[10]) * 1e3, "0.2")
    check("P6 chord vs arc at 120 deg (figure) [%]", (120 * DEG / 2 / np.sin(60 * DEG) - 1) * 100, "20.9")
    check("P6 N=inf [km/s]", s2 * e2 * eta, "1.856")
    check("P6 N=2 penalty [m/s]", (cost[2] - cost[1]) * 1e3, "15.8")
    check("P6 N=3 penalty [m/s]", (cost[3] - cost[1]) * 1e3, "18.8")
    check("P6 N=inf penalty [%]", (s2 * e2 * eta / cost[1] - 1) * 100, "1.15")
    # unequal split 20 + 10
    check("P6 split 20+10 [km/s]", 2 * s2 * e2 * (np.sin(10 * DEG) + np.sin(5 * DEG)), "1.849")
    vc2 = np.sqrt(MU / ra2)
    va2 = np.sqrt(MU * (2 / ra2 - 1 / a2))
    check("P6 two-burn route [km/s]", 2 * (vc2 - va2), "2.774")
    t2 = np.sqrt(1 - e2)
    check("P6 eta_c [deg]", 2 * np.arcsin(t2 / (1 + t2)) / DEG, "46.1")
    # crossings for the single step: f = 15 deg and 195 deg
    for name, f, rq, vtq, rateq in (("near", 15 * DEG, "6965.9", "9.467", "4.67"),
                                    ("far", 195 * DEG, "25162.7", "2.621", "0.358")):
        rr = p2 / (1 + e2 * np.cos(f))
        vt = s2 * (1 + e2 * np.cos(f))
        check(f"P6 crossing {name} r [km]", rr, rq)
        check(f"P6 crossing {name} v_theta [km/s]", vt, vtq)
        check(f"P6 crossing {name} f-dot [deg/min]", vt / rr / DEG * 60, rateq)
    check("P6 |v_r| at crossing [km/s]", s2 * e2 * np.sin(15 * DEG), "0.917")
    P1 = 2 * np.pi * np.sqrt(a2**3 / MU)
    check("P6 period [h]", P1 / 3600, "5.93")
    # burn durations, m0 = 1500 kg, F = 440 N, Isp = 315 s
    ve = 315 * G0
    for Nn, q in ((1, "78.6"), (2, "45.4"), (3, "31.8")):
        dv1 = 2 * s2 * e2 * np.sin(eta / (2 * Nn))
        tb = 1500 * (1 - np.exp(-dv1 / ve)) * ve * 1e3 / 440
        check(f"P6 first burn N={Nn} [min]", tb / 60, q)
    # arc of true anomaly swept during a burn centred on the crossing (Kepler's equation)
    from scipy.optimize import brentq

    def f_of_M(Mv, e):
        Ev = brentq(lambda E: E - e * np.sin(E) - Mv, -20, 20)
        return 2 * np.arctan(np.sqrt((1 + e) / (1 - e)) * np.tan(Ev / 2))

    def arc(fc, tb_min):
        Ec = 2 * np.arctan(np.sqrt((1 - e2) / (1 + e2)) * np.tan(fc / 2))
        Mc = Ec - e2 * np.sin(Ec)
        dM = np.sqrt(MU / a2**3) * tb_min * 60 / 2
        return ((f_of_M(Mc + dM, e2) - f_of_M(Mc - dM, e2)) / DEG) % 360

    check("P6 arc N=1 near [deg]", arc(15 * DEG, 78.6), "219", tol=1)
    check("P6 arc N=1 far [deg]", arc(195 * DEG, 78.6), "29.2", tol=0.1)
    check("P6 arc N=3 near [deg]", arc(15 * DEG, 31.8), "128", tol=1)
    check("P6 arc N=3 far [deg]", arc(195 * DEG, 31.8), "11.4", tol=0.1)
    check("P6 mass left N=1 [%]", np.exp(-cost[1] / ve) * 100, "55.2")
    check("P6 mass left N=3 [%]", np.exp(-cost[3] / ve) * 100, "54.9")

    check("P6 rate ratio near/far", 4.672268 / 0.358066, "13.0")
    check("P6 half-arc of the far single burn [deg]", 29.15 / 2, "14.6")
    check("P6 v_c at apogee [km/s]", vc2, "3.8873")
    check("P6 v_a [km/s]", va2, "2.5001")
    check("P6 first burn N=3 [km/s]", 2 * s2 * e2 * np.sin(eta / 6), "0.618")
    check("v_e at Isp 315 s [km/s]", 315 * G0, "3.089")


def computing_7():
    """Problem 7, congruent ellipses. 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_q7(90)
    check("e*(90 deg)", a["e_star"], 0.6279); check("e_t", a["e_test"], 0.5779)
    check("symmetric cost", a["dv_sym"], 0.41198); check("through infinity", a["dv_inf"], 0.48659)
    check("saving %", a["saving_pct"], 15.3); check("burn true anomaly [deg]", a["nu_burn_deg"], 107.03); check("e_T", a["e_transfer"], 0.4133)
    f = lambda e: np.sqrt(1 - e) + 2 * e - np.sqrt(2 * (1 + e))
    check("root of sqrt(1-e) + 2e = sqrt(2(1+e))", brentq(f, 0.2, 0.9, xtol=1e-14), 0.535334)
    check("e*(180 deg) from the optimiser", K.e_star(np.pi), 0.535334, tol=2e-6)
    e1 = K.e_star(1 * DEG)
    check("(1 - e*)/(2 omega^2) at 1 deg", (1 - e1) / (2 * DEG**2), 1.0, tol=0.01)


BLOCKS = [objective, crossover, turning, numbers, by_a_circle, fragile, in_steps, computing_7]


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