"""Checks every number and identity in the answers and solutions of patched-conics-questions.qmd
(Patched Conics: 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/patched-conics-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."""

    num = Objective("patched-conics-questions.qmd", 3).num

    num(2, 0.5 * ((1 + 1.524) / 2) ** 1.5 * 365.25, "259")
    num(3, 1 / (1 / 365.25 - 1 / 686.98), "780")


def venus():
    """Problem 1, patched conics from the Earth to Venus."""
    import numpy as np

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

    MU_V, R_V = 324858.59, 6051.8
    A_V = 0.72333*AU

    DAY, YEAR = 86400.0, 365.25*86400.0
    deg = np.degrees

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

    # ================================================================ Problem 10: to Venus
    print("\n--- Problem 1")
    r1, r2 = AU, A_V
    at = (r1 + r2)/2
    t12 = np.pi*np.sqrt(at**3/MU_S)
    VE, VV = np.sqrt(MU_S/r1), np.sqrt(MU_S/r2)
    vt1, vt2 = vis(MU_S, r1, at), vis(MU_S, r2, at)
    check("P1 r2", r2, "1.08209e8", tol=5e3); check("P1 a_t", at, "1.28903e8", tol=5e2)
    check("P1 t12 days", t12/DAY, "146.08")
    check("P1 VE", VE, "29.785"); check("P1 VV", VV, "35.021")
    check("P1 vt1", vt1, "27.289"); check("P1 vt2", vt2, "37.727")
    check("P1 vinf1", VE - vt1, "2.4954"); check("P1 vinf2", vt2 - VV, "2.7066")
    TV = 2*np.pi*np.sqrt(r2**3/MU_S); TE = 2*np.pi*np.sqrt(r1**3/MU_S)
    check("P1 TV days", TV/DAY, "224.70"); check("P1 TE days", TE/DAY, "365.26")
    nV = 2*np.pi/TV
    check("P1 nV deg/day", deg(nV)*DAY, "1.6021")
    check("P1 nV t12", deg(nV*t12), "234.03"); check("P1 phi0", 180 - deg(nV*t12), "-54.03")
    S = 1/abs(1/TE - 1/TV)
    check("P1 synodic days", S/DAY, "583.9"); check("P1 synodic years", S/YEAR, "1.599")
    vinf1, vinf2 = VE - vt1, vt2 - VV
    rpk = RE + 300
    check("P1 vc parking", np.sqrt(MU/rpk), "7.7258")
    check("P1 vp departure", np.sqrt(vinf1**2 + 2*MU/rpk), "11.2072")
    dv1 = np.sqrt(vinf1**2 + 2*MU/rpk) - np.sqrt(MU/rpk)
    check("P1 dv departure", dv1, "3.4815")
    check("P1 C3", vinf1**2, "6.227")
    e1 = 1 + rpk*vinf1**2/MU
    check("P1 e departure", e1, "1.10433")
    finf = deg(np.arccos(-1/e1))
    check("P1 f_inf", finf, "154.89")
    th = -90 - finf + 360
    check("P1 theta burn", th, "115.11")
    check("P1 theta before wrapping", -90 - finf, "-244.89")
    check("P1 capture rp", R_V + 500, "6551.8")
    check("P1 capture ra", R_V + 60000, "66 051.8")
    check("P1 local time h", th/15, "7.67", tol=0.005)
    rp2, ra2 = R_V + 500, R_V + 60000
    a2c = (rp2 + ra2)/2
    check("P1 capture e", (ra2 - rp2)/(ra2 + rp2), "0.81952")
    vhyp = np.sqrt(vinf2**2 + 2*MU_V/rp2); vell = vis(MU_V, rp2, a2c)
    check("P1 vp hyperbola", vhyp, "10.3195"); check("P1 vp ellipse", vell, "9.4983")
    check("P1 dv capture", vhyp - vell, "0.8212")
    check("P1 capture period h", 2*np.pi*np.sqrt(a2c**3/MU_V)/3600, "21.18")
    check("P1 total", dv1 + vhyp - vell, "4.3027")
    soiV = r2*(MU_V/MU_S)**0.4
    check("P1 SOI Venus", soiV, "616 276", tol=0.5)
    check("P1 apoapsis / SOI %", 100*ra2/soiV, "10.7", tol=0.05)
    check("P1 SOI Earth", r1*(MU/MU_S)**0.4, "924 647", tol=0.5)
    check("P1 capture into circle 500 km", vhyp - np.sqrt(MU_V/rp2), "3.2780")
    check("P1 extra for a circle", vell - np.sqrt(MU_V/rp2), "2.457", tol=6e-4)


def mars_and_flybys():
    """Problems 2, 3 and 4, the cheapest capture at Mars, the largest flyby, and a round trip to Mars."""
    import numpy as np
    import sympy as sp

    # ---------------------------------------------------------------- constants
    from orbit.constants import MU_EARTH as MU, R_EARTH as RE, MU_SUN as MU_S, AU, MU_MARS as MU_M, R_MARS as R_M, MU_JUPITER as MU_J, R_JUPITER as R_J
    G0 = 9.80665e-3           # km/s^2
    MU_V, R_V = 324858.59, 6051.8         # Venus
    DEG = np.pi / 180

    # =================================================================== P5
    print("\n=== Problem 2: the cheapest capture orbit at Mars")
    X, vv, eps_e = sp.symbols("x v_inf e", positive=True)   # x = mu/r_p
    f6 = sp.sqrt(vv**2 + 2 * X) - sp.sqrt((1 + eps_e) * X)
    xs = sp.solve(sp.Eq(sp.diff(f6, X), 0), X)
    truth("P2 stationary x = (1+e) v^2 / (2(1-e))",
               any(sp.simplify(s - (1 + eps_e) * vv**2 / (2 * (1 - eps_e))) == 0 for s in xs))
    xst = (1 + eps_e) * vv**2 / (2 * (1 - eps_e))
    sym_zero("P2 optimal cost = v sqrt((1-e)/2)",
             sp.simplify(f6.subs(X, xst) - vv * sp.sqrt((1 - eps_e) / 2)).subs(eps_e, sp.Rational(1, 3)))
    for ev in (0, sp.Rational(1, 3), sp.Rational(9, 10)):
        val = sp.simplify(f6.subs(X, xst) - vv * sp.sqrt((1 - eps_e) / 2)).subs(eps_e, ev)
        truth(f"P2 optimal cost identity at e = {ev}", sp.simplify(val) == 0)
        d2 = sp.simplify(sp.diff(f6, X, 2).subs(X, xst).subs(eps_e, ev))
        truth(f"P2 second derivative > 0 at e = {ev}", bool(sp.simplify(d2 * vv**3) > 0))
    vinf6 = 2.649
    rs = 2 * MU_M / vinf6**2
    check("P2 r* [km]", rs, "12207")
    check("P2 r* altitude [km]", rs - R_M, "8810")
    check("P2 dv* [km/s]", vinf6 / np.sqrt(2), "1.873")
    circ = lambda rr: np.sqrt(vinf6**2 + 2 * MU_M / rr) - np.sqrt(MU_M / rr)
    check("P2 dv circle 300 km [km/s]", circ(R_M + 300), "2.091")
    check("P2 dv circle at r* [km/s]", circ(rs), "1.873")
    check("P2 penalty of 300 km circle [m/s]", (circ(R_M + 300) - vinf6 / np.sqrt(2)) * 1e3, "218")
    rp6, ra6 = R_M + 421.7, R_M + 76993.6
    e6 = (ra6 - rp6) / (ra6 + rp6)
    dv6 = np.sqrt(vinf6**2 + 2 * MU_M / rp6) - np.sqrt(MU_M * (1 + e6) / rp6)
    check("P2 ellipse e", e6, "0.9093")
    check("P2 ellipse dv [km/s]", dv6, "0.799")
    check("P2 ellipse period [h]", 2 * np.pi * np.sqrt(((rp6 + ra6) / 2) ** 3 / MU_M) / 3600, "72.86")
    check("P2 optimal r_p for e = 0.9093 [km]", 2 * MU_M * (1 - e6) / ((1 + e6) * vinf6**2), "580")
    check("P2 unreachable optimum cost [km/s]", vinf6 * np.sqrt((1 - e6) / 2), "0.564")
    # mass, Isp 315 s
    ve6 = 315 * G0
    check("P2 mass left circle 300 [%]", np.exp(-circ(R_M + 300) / ve6) * 100, "50.8")
    check("P2 mass left circle r* [%]", np.exp(-vinf6 / np.sqrt(2) / ve6) * 100, "54.5")
    check("P2 mass left ellipse [%]", np.exp(-dv6 / ve6) * 100, "77.2")

    # =================================================================== P6
    print("\n=== Problem 3: the largest velocity change a flyby can give")
    w, rpp, mu7 = sp.symbols("v_inf r_p mu", positive=True)
    g7 = 2 * w / (1 + rpp * w**2 / mu7)
    crit7 = sp.solve(sp.diff(g7, w), w)
    truth("P3 stationary at v_inf = sqrt(mu/r_p)", crit7 == [sp.sqrt(mu7 / rpp)])
    sym_zero("P3 maximum = sqrt(mu/r_p)", g7.subs(w, sp.sqrt(mu7 / rpp)) - sp.sqrt(mu7 / rpp))
    sym_zero("P3 e = 2 at the optimum", (1 + rpp * w**2 / mu7).subs(w, sp.sqrt(mu7 / rpp)) - 2)
    for nm, m, Rb, rpv, q in (("Venus", MU_V, R_V, R_V + 300, "7.15"),
                              ("Earth", MU, RE, RE + 300, "7.73"),
                              ("Mars", MU_M, R_M, R_M + 300, "3.40"),
                              ("Jupiter", MU_J, R_J, 3 * R_J, "24.3")):
        check(f"P3 {nm} max dV = optimal v_inf [km/s]", np.sqrt(m / rpv), q)
    check("P3 Jupiter at the cloud tops [km/s]", np.sqrt(MU_J / R_J), "42.1")
    v7 = 2.649
    e7 = 1 + (R_M + 300) * v7**2 / MU_M
    check("P3 Mars e", e7, "1.6056")
    check("P3 Mars turn [deg]", 2 * np.arcsin(1 / e7) / DEG, "77.0")
    check("P3 Mars dV [km/s]", 2 * v7 / e7, "3.300")
    check("P3 Mars fraction of max [%]", 2 * v7 / e7 / np.sqrt(MU_M / (R_M + 300)) * 100, "96.9")
    # Jupiter at v_inf = 5.643 (the note's example), r_p = 3 R_J
    v7j = 5.643
    e7j = 1 + 3 * R_J * v7j**2 / MU_J
    check("P3 Jupiter e at 5.643", e7j, "1.0539")
    check("P3 Jupiter dV at 5.643 [km/s]", 2 * v7j / e7j, "10.71")
    check("P3 Jupiter turn at 5.643 [deg]", 2 * np.arcsin(1 / e7j) / DEG, "143.2")

    # =================================================================== P7
    print("\n=== Problem 4: a round trip to Mars")
    r81, r82 = AU, 1.52368 * AU
    at8 = (r81 + r82) / 2
    t12 = np.pi * np.sqrt(at8**3 / MU_S) / 86400
    nE = np.sqrt(MU_S / r81**3) * 86400 / DEG
    nM = np.sqrt(MU_S / r82**3) * 86400 / DEG
    check("P4 t12 [d]", t12, "258.9")
    check("P4 T_E [d]", 360 / nE, "365.26")
    check("P4 T_M [d]", 360 / nM, "686.97")
    check("P4 n_E [deg/d]", nE, "0.98561")
    check("P4 n_M [deg/d]", nM, "0.52404")
    check("P4 phi0 [deg]", 180 - nM * t12, "44.3")
    check("P4 n_E t12 [deg]", nE * t12, "255.1")
    check("P4 Earth lead at arrival [deg]", nE * t12 - 180, "75.1")
    check("P4 lead needed for return [deg]", 180 - nE * t12, "-75.1")
    tw = ((180 - nE * t12) - (nE * t12 - 180)) % 360 / (nE - nM)
    check("P4 change of lead needed [deg]", ((180 - nE * t12) - (nE * t12 - 180)) % 360, "209.7")
    check("P4 wait [d]", tw, "454.4")
    check("P4 total [d]", 2 * t12 + tw, "972.1")
    check("P4 total [yr]", (2 * t12 + tw) / 365.25, "2.66")
    S = 360 / (nE - nM)
    check("P4 synodic [d]", S, "779.9")
    check("P4 synodic [months]", S / 30.44, "25.6")
    # wait-time formula: t_w = (2 pi N - 2 n_E t12)/(n_E - n_M), smallest whole N with t_w > 0
    check("P4 formula N=1", (360 - 2 * nE * t12) / (nE - nM), "-325.6")
    check("P4 formula N=2", (720 - 2 * nE * t12) / (nE - nM), "454.4")
    check("P4 2 n_E t12 [deg]", 2 * nE * t12, "510.3")
    check("P4 n_E - n_M [deg/d]", nE - nM, "0.46157")
    # MOM launch 5 Nov 2013 + S
    import datetime as _dt
    nxt = _dt.date(2013, 11, 5) + _dt.timedelta(days=S)
    truth(f"P4 5 Nov 2013 + S = {nxt} (late December 2015)", nxt == _dt.date(2015, 12, 24))

    check("P2 MOM r_p [km]", R_M + 421.7, "3817.9")
    check("P2 MOM r_a [km]", R_M + 76993.6, "80389.8")
    check("P3 3 R_J [km]", 3 * R_J, "214476")


BLOCKS = [objective, venus, mars_and_flybys]


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