"""Checks every number and identity in the answers and solutions of further-questions.qmd
(Further 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/further-questions-verify.py
"""
from _verify import check, truth, 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

    num = Objective("further-questions.qmd", 4).num

    c = np.hypot(7000, 14000)
    num(4, (7000 + 14000 + c) / 4, "9163")


def moon_and_point_masses():
    """Problems 4 and 5, home from the Moon, and an Earth of point masses."""
    import json
    import os
    import numpy as np
    import sympy as sp

    HERE = os.path.dirname(os.path.abspath(__file__))

    # ---------------------------------------------------------------- constants (the handout's table)
    from orbit.constants import MU_EARTH as MU, R_EARTH as RE, MU_MOON, R_MOON, D_MOON as D, J2_EARTH as J2


    J4E, C22, S22 = -1.6196e-6, 1.5745e-6, -9.0387e-7
    M_EARTH, M_MOON = 5.9722e24, 7.342e22   # kg, for the "sixth of the Moon" remark only

    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)

    r1s, rps, res = sp.symbols("r_1 r_p r_e", positive=True)

    # ======================================================================== Problem 4
    print("\n== Problem 4: home from the Moon")
    Ds, rps, rLs, muM, vinf, c = sp.symbols("D r_p r_L mu_M v_inf c", positive=True)
    ve2m = 2*mu*(1/res - 1/(Ds + rps))
    truth("5b v_e^2 = v_esc^2 (1 - r_e/(D+r_p))", zero(ve2m - 2*mu/res*(1 - res/(Ds + rps))))
    rp_sol = sp.solve(sp.Eq(c*res*(Ds + rps - res), Ds*rps), rps)[0]
    truth("5b r_p = c r_e (D - r_e)/(D - c r_e)", zero(rp_sol - c*res*(Ds - res)/(Ds - c*res)))
    vas = sp.sqrt(2*mu*rps/(Ds*(Ds + rps)))
    dln = sp.diff(sp.log(vas), rps)
    truth("5d d ln v_a / d r_p = D/(2 r_p (D+r_p))", zero(dln - Ds/(2*rps*(Ds + rps))))

    REI = RE + 120.0
    VM = np.sqrt(MU/D)

    def rp_of(gdeg):
        cc = np.cos(np.radians(gdeg))**2
        return REI*cc*(D - REI)/(D - cc*REI)

    def va_of(rpv):
        return np.sqrt(2*MU*rpv/(D*(D + rpv)))

    for gq, rpq, altq, vaq in ((5.5, "6437.43", "59.29", "184.8205"), (6.5, "6413.45", "35.31", "184.4817"),
                               (7.5, "6385.56", "7.42", "184.0867")):
        rpv = rp_of(gq)
        check(f"5c r_p at {gq} deg", rpv, rpq)
        check(f"5c altitude at {gq} deg", rpv - RE, altq)
        check(f"5c v_a (m/s) at {gq} deg", va_of(rpv)*1e3, vaq)
        gback = deg(np.arccos(np.sqrt(D*rpv/(REI*(D + rpv - REI)))))
        check(f"5c round trip gamma at {gq} deg", gback, f"{gq}", tol=1e-9)
    check("5c corridor width (km)", rp_of(5.5) - rp_of(7.5), "52", tol=0.5)
    RPN = rp_of(6.5)
    VAN = va_of(RPN)
    VINF = VM - VAN
    RL = R_MOON + 100
    check("5c v_M", VM, "1.01830")
    check("5c v_a (km/s)", VAN, "0.18448")
    check("5c v_inf", VINF, "0.8338")
    check("5c lunar circular speed", np.sqrt(MU_MOON/RL), "1.6335")
    check("5c hyperbola periapsis speed", np.sqrt(VINF**2 + 2*MU_MOON/RL), "2.4560")
    TEI = np.sqrt(VINF**2 + 2*MU_MOON/RL) - np.sqrt(MU_MOON/RL)
    check("5c TEI", TEI, "0.8225")
    VEN = np.sqrt(2*MU*(1/REI - 1/(D + RPN)))
    VESCE = np.sqrt(2*MU/REI)
    check("5c entry speed", VEN, "10.984")
    check("5c escape speed at r_e", VESCE, "11.076")
    check("5c ratio", VEN/VESCE, "0.99165")
    check("5c approximation 1 - r_e/2D", 1 - REI/(2*D), "0.99155")
    check("5c r_e/(D+r_p) ~ 0.017", REI/(D + RPN), "0.017")
    check("5c flight time (days)", np.pi*np.sqrt(((D + RPN)/2)**3/MU)/86400, "4.975")
    check("5d D + r_p", D + RPN, "390813", tol=0.5)
    DRP = 2*RPN*(D + RPN)/D*(1e-3/VAN)
    check("5d shift per 1 m/s (km)", DRP, "70.69")
    W = (va_of(rp_of(5.5)) - va_of(rp_of(7.5)))*1e3
    check("5d corridor in v_a (m/s)", W, "0.734")
    check("5d half-width / v_a ~ 2e-3", W/2/(VAN*1e3), "0.002", tol=0.0005)
    RC = RE + 400
    VP400 = np.sqrt(2*MU*(1/RC - 1/(D + RC)))
    check("5e speed at 400 km perigee", VP400, "10.751")
    check("5e circular speed at 400 km", np.sqrt(MU/RC), "7.669")
    check("5e braking burn", VP400 - np.sqrt(MU/RC), "3.08")
    check("5e braking / TEI ~ 4", (VP400 - np.sqrt(MU/RC))/TEI, "3.7", tol=0.1)

    # ======================================================================== Problem 5
    print("\n== Problem 5: point-mass Earth")
    phi, lam, m, M, b, R = sp.symbols("varphi lambda m M b R", positive=True)
    P2 = lambda z: (3*z**2 - 1)/2
    P4 = lambda z: (35*z**4 - 30*z**2 + 3)/8
    # (a) polar pair
    truth("6a pair: P2(+-sin) sum = m P2(sin)",
       zero(m/2*P2(sp.sin(phi)) + m/2*P2(-sp.sin(phi)) - m*P2(sp.sin(phi))))
    # (b) rings: N = 3..6, average of P2 over the ring
    for N in (3, 4, 5, 6):
        s = sum(P2(sp.cos(phi)*sp.cos(lam - 2*sp.pi*k/N)) for k in range(N))/N
        truth(f"6b N={N}: ring average of P2 = -P2(sin)/2", zero(sp.expand_trig(sp.simplify(s + P2(sp.sin(phi))/2))))
    s2 = sum(P2(sp.cos(phi)*sp.cos(lam - sp.pi*k)) for k in range(2))/2
    extra = sp.simplify(s2 + P2(sp.sin(phi))/2)
    truth("6d N=2: extra part = (3/4) cos^2 phi cos 2 lambda", zero(sp.simplify(extra - sp.Rational(3, 4)*sp.cos(phi)**2*sp.cos(2*lam))))
    truth("6b 3/4 cos^2 - 1/2 = -P2(sin)/2", zero(sp.Rational(3, 4)*sp.cos(phi)**2 - sp.Rational(1, 2) + P2(sp.sin(phi))/2))
    # (c) continuous-ring average of P4 = P4(0) P4(sin phi); the m=0 part for N >= 5 equals it exactly
    al = sp.symbols("alpha")
    avg4 = sp.integrate(P4(sp.cos(phi)*sp.cos(al)), (al, 0, 2*sp.pi))/(2*sp.pi)
    truth("6c ring average of P4 = (3/8) P4(sin)", zero(sp.simplify(avg4 - sp.Rational(3, 8)*P4(sp.sin(phi)))))
    truth("6c P4(0) = 3/8", sp.nsimplify(P4(sp.Integer(0))) == sp.Rational(3, 8))
    J2m = m/(2*M)*(b/R)**2
    J4m = -m/M*sp.Rational(3, 8)*(b/R)**4
    truth("6c J4 = -(3/4) J2 (b/R)^2", zero(J4m + sp.Rational(3, 4)*J2m*(b/R)**2))
    truth("6c at m = M: J4 = -(3/2) J2^2", zero((J4m + sp.Rational(3, 2)*J2m**2).subs(b, R*sp.sqrt(2*J2m)).subs(m, M)))
    truth("6d C22 = J2/2 for N=2", zero(m/(4*M)*(b/R)**2 - J2m/2))
    # sign of the along-track acceleration -(1/r) dU/dlam for U = -K cos 2 lam
    K = sp.symbols("K", positive=True)
    at = -sp.diff(-K*sp.cos(2*lam), lam)
    truth("6d along-track accel = -2K sin 2 lam (westward for 0<lam<90)", zero(at + 2*K*sp.sin(2*lam)))

    check("6b m/M at b=R", 2*J2, "2.165e-3")
    check("6b ring mass (kg)", 2*J2*M_EARTH, "1.29e22")
    check("6b ring mass / Moon ~ 1/6", 2*J2*M_EARTH/M_MOON, "0.18", tol=0.02)
    check("6c J4 at b=R", -0.75*J2, "-8.12e-4")
    check("6c J4(b=R)/J4(Earth)", -0.75*J2/J4E, "500", tol=5)
    check("6c (R/r)^2 at 700 km", (RE/(RE + 700))**2, "0.81")
    BMIN = RE*np.sqrt(2*J2)
    check("6c b_min (km)", BMIN, "296.8")
    check("6c J4 at b_min", -1.5*J2**2, "-1.758e-6")
    check("6c within 9% of Earth's J4", (-1.5*J2**2)/J4E - 1, "0.09", tol=0.005)
    check("6d J2/C22 ~ 690", J2/C22, "690", tol=5)
    l22 = 0.5*deg(np.arctan2(S22, C22))
    check("6d long axis (deg)", l22, "-14.93")
    check("6d other end of long axis (deg E)", l22 + 180, "165.07")
    check("6d stable point east (deg E)", l22 + 90, "75.07")
    check("6d stable point west (deg W)", -(l22 - 90), "104.93")

    with open(os.path.join(HERE, "ring-rates.json")) as fh:
        rr = json.load(fh)
    BS = rr["b_over_R"]
    r3, r4, r2 = rr["rates"]["3"], rr["rates"]["4"], rr["rates"]["2"]
    check("6 fig: J2 model rate (deg/day)", rr["rate_j2"], "0.991")
    check("6 fig: N=3 at b=R", r3[BS.index(1.0)], "0.39")
    check("6 fig: N=4 at b=R", r4[BS.index(1.0)], "0.44")
    check("6 fig: N=3 at b=0.1R", r3[BS.index(0.1)], "0.981")
    check("6 fig: N=3 at b_min", r3[0], "0.989")
    check("6 fig: N=3 at b_min within 0.2%", 1 - r3[0]/rr["rate_j2"], "0.002", tol=0.0005)
    truth("6 fig: b_min used in the sweep", abs(BS[0] - np.sqrt(2*J2)) < 1e-12)
    truth("6 fig: drift at b=R exceeds half a degree per day", rr["rate_j2"] - max(r3[BS.index(1.0)], r4[BS.index(1.0)]) > 0.5)
    check("6 fig: N=2 a few per cent below N=3 at b_min", 1 - r2[0]/r3[0], "0.04", tol=0.01)
    check("6 fig: sun-synchronous rate 360/365.2422 (deg/day)", 360/365.2422, "0.9856")
    check("6 fig: J2 secular formula at 700 km, 98.19 deg", rr["rate_formula"], "0.9859")


def computing_1():
    """Problem 1, one impulse to a point. 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
    DEG = np.pi / 180

    a = K.ans_q1(40)
    check("rho* at 40 deg", a["rho_star"], 9.658); check("dv at rho*", a["dv"], 1.2768)
    check("gamma+ [deg]", a["gamma_plus"], 61.03); check("Hohmann first burn", a["dv_hohmann"], 0.3462)
    check("ratio", a["ratio"], 3.688)
    for th, q in ((30, 19.70), (60, 4.18), (90, 4.43), (120, 8.25)):
        check(f"rho* at {th} deg", K.rho_star(th * DEG), q)
    ths = np.arange(60, 81, 1.0); rs = [K.rho_star(t * DEG) for t in ths]; j = int(np.argmin(rs))
    check("smallest rho*", rs[j], 3.85); check("near theta [deg]", ths[j], 71, tol=1)
    for th in (40, 100, 150):
        al, be, s = np.cos(th * DEG) - 1 / 3, 1 - np.cos(th * DEG), np.sin(th * DEG)
        r = np.roots([al * al + s * s, -s * s, 0, 0, -be * be])
        truth(f"quartic has exactly one positive real root (theta {th})", sum(1 for z in r if abs(z.imag) < 1e-9 and z.real > 0) == 1)
    check("theta -> 0 limit sqrt(3 - 2/rho) at rho = 3", K.intercept(3.0, 1e-6)["dv"], np.sqrt(3 - 2 / 3), tol=1e-4)
    check("Delta V(70) = Delta V(290) at rho = 4", K.intercept(4, 70 * DEG)["dv"] - K.intercept(4, 290 * DEG)["dv"], 0, tol=1e-12)


def computing_2():
    """Problem 2, deorbit to a prescribed entry. 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
    DEG = np.pi / 180

    a = K.ans_q2(-9); s9 = np.sin(9 * DEG); c9 = np.cos(9 * DEG)
    check("n_best", a["n_best"], 1.1564); check("n_best = 1 + |sin gamma|", a["n_best"], 1 + s9, tol=1e-12)
    check("dv_min", a["dv_min"], 0.08154); check("dv_min closed form", 1 - c9 / np.sqrt(1 + s9), a["dv_min"], tol=1e-12)
    check("dv_min by brute force", K.disorbit_brute(a["n_best"], -9 * DEG), a["dv_min"], tol=3e-5)
    check("n_b", a["n_boundary"], 1.0527); check("n_s", a["n_s"], 1.0263)
    truth("regime at n_s is tilted", a["regime_ns"] == "tilted")
    check("phi at n_s [deg]", a["phi_ns"], 59.52); check("dv at n_s", a["dv_ns"], 0.14568); check("penalty %", a["penalty_pct"], 78.7)
    gs = np.linspace(-89, -1, 177)
    nb = np.array([K.n_boundary(g * DEG) for g in gs])
    check("max n_b", nb.max(), 1.125, tol=5e-4); check("at gamma [deg]", gs[int(np.argmax(nb))], -37.3, tol=0.6)
    truth("n_best = 1+|sin gamma| lies above n_b for every gamma", np.all(1 + np.abs(np.sin(gs * DEG)) > nb))
    truth("n -> 1 in both limits", K.n_boundary(-0.5 * DEG) < 1.01 and K.n_boundary(-89.5 * DEG) < 1.01)


def computing_8():
    """Problem 3, the useful 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
    DEG = np.pi / 180

    a = K.ans_q8(0.35, 40)
    check("gamma [deg]", a["gamma"], 10.060); check("phi_i [deg]", a["phi_i"], 3.970); check("phi_s [deg]", a["phi_s"], 5.260)
    check("width [deg]", a["width"], 1.290); check("partner of phi_i [deg]", a["nu2_i"], 205.4); check("partner of phi_s [deg]", a["nu2_s"], 152.9)
    check("widest at nu [deg]", a["nu_widest"], 120, tol=2.5); check("widest width [deg]", a["width_max"], 3.377)
    check("tan gamma formula", np.degrees(np.arctan2(0.35 * np.sin(40 * DEG), 1 + 0.35 * np.cos(40 * DEG))), a["gamma"], tol=1e-9)
    W = K.window(0.01); pl, pu, g = W.edges(90 * DEG)
    check("e = 0.01: phi_i/gamma -> 1/3", pl / g, 1 / 3, tol=2e-3); check("e = 0.01: phi_s/gamma -> 1/2", pu / g, 1 / 2, tol=2e-3)


BLOCKS = [objective, moon_and_point_masses, computing_1, computing_2, computing_8]


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