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

    # data, as in the page's data box
    mu = 398600.0

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

    r1, r2 = 6678.0, 42164.0
    vc1, vc2 = np.sqrt(mu / r1), np.sqrt(mu / r2)
    at = (r1 + r2) / 2
    vt1, vt2 = np.sqrt(mu * (2 / r1 - 1 / at)), np.sqrt(mu * (2 / r2 - 1 / at))
    num(1, (np.sqrt(2) - 1) * vc1, "3.20")
    num(2, np.sqrt(9 + 2 * vc1 ** 2) - vc1, "3.60")

    vcg = np.sqrt(mu / 42164)
    num(4, vt1 - vc1 + vc2 - vt2 + np.sqrt(9 + 2 * vcg ** 2) - vcg, "6.10")


def two_ways():
    """Problem 1, two ways to escape."""
    import sympy as sp
    from numpy import sqrt, pi

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

    rGEO = 42164.0         # km

    print("\nQ6")
    r1 = rGEO; vc1 = sqrt(mu / r1); ri = Re + 300
    k = ri / r1
    check("P1 v_c1 [km/s]", vc1, 3.0747)
    check("P1 v_esc at r1 [km/s]", sqrt(2) * vc1, 4.348)
    check("P1 k", k, 0.1584)

    def one(x): return sqrt(x**2 + 2) - 1
    def two(x, k): return (1 - sqrt(2 * k / (1 + k))) + sqrt(x**2 + 2 / k) - sqrt(2 / (k * (1 + k)))

    xm = 2.94 / vc1; xj = 8.79 / vc1
    check("P1 xi Mars", xm, 0.956); check("P1 xi Jupiter", xj, 2.859)
    check("P1 Mars one-impulse [km/s]", one(xm) * vc1, 2.174)
    check("P1 Mars two-impulse [km/s]", two(xm, k) * vc1, 2.630)
    check("P1 two-impulse first burn [km/s]", (1 - sqrt(2 * k / (1 + k))) * vc1, 1.467)
    check("P1 Mars two-impulse second burn [km/s]", (sqrt(xm**2 + 2 / k) - sqrt(2 / (k * (1 + k)))) * vc1, 1.163)
    check("P1 Jupiter one-impulse [km/s]", one(xj) * vc1, 6.732)
    check("P1 Jupiter two-impulse [km/s]", two(xj, k) * vc1, 5.338)
    check("P1 Jupiter two-impulse second burn [km/s]", (sqrt(xj**2 + 2 / k) - sqrt(2 / (k * (1 + k)))) * vc1, 3.871)
    check("P1 Jupiter: dive saves [km/s]", (one(xj) - two(xj, k)) * vc1, 1.394)
    xs, ks = sp.symbols("xi k", positive=True)
    two_s = (1 - sp.sqrt(2 * ks / (1 + ks))) + sp.sqrt(xs**2 + 2 / ks) - sp.sqrt(2 / (ks * (1 + ks)))
    sym_zero("P1 two-impulse cost = 1 at xi = sqrt 2, all k", sp.simplify(two_s.subs(xs, sp.sqrt(2))) - 1)
    sym_zero("P1 one-impulse cost = 1 at xi = sqrt 2", sp.sqrt(2 + 2) - 1 - 1)
    ad = (r1 + ri) / 2
    check("P1 dive coast time [h]", pi * sqrt(ad**3 / mu) / 3600, 5.28)

    check("P1 two-impulse a [km]", (rGEO + Re + 300) / 2, 24421)


def where_to_burn():
    """Problem 2, where to burn."""
    import numpy as np

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


    rad = np.radians

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

    # ================================================================ Problem 9: where to burn
    print("\n--- Problem 2")
    rp9, ra9 = R_MA + 421.7, R_MA + 76993.6
    a9 = (rp9 + ra9)/2; e9 = (ra9 - rp9)/(ra9 + rp9)
    vp9, va9 = vis(MU_MA, rp9, a9), vis(MU_MA, ra9, a9)
    check("P2 rp", rp9, "3817.9"); check("P2 ra", ra9, "80 389.8"); check("P2 a", a9, "42 103.85"); check("P2 e", e9, "0.90932")
    check("P2 T, h", 2*np.pi*np.sqrt(a9**3/MU_MA)/3600, "72.86")
    check("P2 vp", vp9, "4.6280"); check("P2 va", va9, "0.21979")
    check("P2 dv at periapsis m/s", 2*vp9*np.sin(rad(2.5))*1e3, "403.7")
    check("P2 dv at apoapsis m/s", 2*va9*np.sin(rad(2.5))*1e3, "19.17")
    check("P2 ratio", vp9/va9, "21.06"); check("P2 ra/rp", ra9/rp9, "21.06")
    rp10, ra10 = RE + 256, RE + 121973
    a10 = (rp10 + ra10)/2; e10 = (ra10 - rp10)/(ra10 + rp10)
    vp10, va10 = vis(MU, rp10, a10), vis(MU, ra10, a10)
    check("P2 Aditya rp", rp10, "6634.137"); check("P2 Aditya ra", ra10, "128 351.137")
    check("P2 Aditya a", a10, "67 492.637"); check("P2 Aditya e", e10, "0.90171")
    check("P2 Aditya vp", vp10, "10.6893"); check("P2 Aditya va", va10, "0.55250")
    up = np.sqrt(1 + 2*MU/rp10); ua = np.sqrt(1 + 2*MU/ra10)
    check("P2 needed at perigee", up, "11.0076"); check("P2 needed at apogee", ua, "2.6853")
    check("P2 burn at perigee", up - vp10, "0.3183"); check("P2 burn at apogee", ua - va10, "2.1328")
    check("P2 apogee/perigee", (ua - va10)/(up - vp10), "6.70", tol=0.005)
    check("P2 wait apogee->perigee h", np.pi*np.sqrt(a10**3/MU)/3600, "24.24")
    r0 = RE + 300
    check("P2 from 300 km circle", np.sqrt(1 + 2*MU/r0) - np.sqrt(MU/r0), "3.2458")


def oberth_dive():
    """Problem 3, an Oberth dive before escape (label 10 is the old number)."""
    import numpy as np
    import sympy as sp

    # ---------------------------------------------------------------- 10. Oberth dive before escape
    def dive(rho, V):
        return (1 - np.sqrt(2 * rho / (1 + rho))) + np.sqrt(V**2 + 2 / rho) - np.sqrt(2 / (rho * (1 + rho)))

    rho = np.logspace(-6, 0, 200001)
    ok = True
    for V in np.linspace(0.0, 4.0, 401):
        c = dive(rho, V)
        direct = np.sqrt(V**2 + 2) - 1
        if V < np.sqrt(2) - 1e-9:
            ok &= c.min() >= direct - 1e-12          # never better than not diving
        elif V > np.sqrt(2) + 1e-9:
            ok &= np.all(np.diff(c) > -1e-15)        # cost rises with rho: deeper is cheaper
    truth("10 dive pays iff v_inf > sqrt2 v_c; then deeper is always cheaper", ok)
    rr, VV = sp.symbols("rho V", positive=True)
    Cd = (1 - sp.sqrt(2 * rr / (1 + rr))) + sp.sqrt(VV**2 + 2 / rr) - sp.sqrt(2 / (rr * (1 + rr)))
    slope1 = sp.simplify(sp.diff(Cd, rr).subs(rr, 1))
    truth("10 dC/drho at rho=1 = 1/2 - 1/sqrt(V^2+2)",
          sp.simplify(slope1 - (sp.Rational(1, 2) - 1 / sp.sqrt(VV**2 + 2))) == 0)
    truth("10 limit rho->0 cost = v_c", abs(dive(1e-12, 2.0) - 1) < 1e-5)


def from_an_ellipse():
    """Problem 4, leaving the Earth from an elliptic orbit."""
    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

    # =================================================================== P4
    print("\n=== Problem 4: leaving the Earth from an elliptic orbit")
    vi, rp_s, mu_e, ee = sp.symbols("v_inf r_p mu e", positive=True)
    dv5 = sp.sqrt(vi**2 + 2 * mu_e / rp_s) - sp.sqrt(mu_e * (1 + ee) / rp_s)
    truth("P4 d(dv)/de < 0", sp.simplify(sp.diff(dv5, ee) + sp.sqrt(mu_e / rp_s) / (2 * sp.sqrt(1 + ee))) == 0)
    ve_s = sp.symbols("v_e", positive=True)   # local escape speed
    lim = sp.sqrt(vi**2 + ve_s**2) - ve_s
    sym_zero("P4 e->1 limit rationalised", sp.simplify(lim - vi**2 / (sp.sqrt(vi**2 + ve_s**2) + ve_s)))
    ser5 = sp.series(lim.subs(vi, sp.Symbol("eps") * ve_s), sp.Symbol("eps"), 0, 3).removeO()
    sym_zero("P4 small v_inf: limit ~ v_inf^2/(2 v_e)", sp.simplify(ser5 - (sp.Symbol("eps") * ve_s) ** 2 / (2 * ve_s)))

    rp5 = RE + 250
    vinf5 = 2.945
    vesc5 = np.sqrt(2 * MU / rp5)
    vp5 = np.sqrt(vinf5**2 + vesc5**2)
    eh5 = 1 + rp5 * vinf5**2 / MU
    check("P4 v_esc [km/s]", vesc5, "10.967")
    check("P4 v_p hyperbola [km/s]", vp5, "11.356")
    check("P4 e_h", eh5, "1.1442")
    check("P4 f_inf [deg]", np.arccos(-1 / eh5) / DEG, "150.9")
    check("P4 e->1 limit [km/s]", vp5 - vesc5, "0.389")
    check("P4 small-v_inf estimate [km/s]", vinf5**2 / (2 * vesc5), "0.395")
    for ha, q_e, q_v0, q_dv, q_m in ((250, "0", "7.755", "3.601", "31.2"),
                                     (23000, "0.632", "9.906", "1.449", "62.6"),
                                     (35786, "0.728", "10.195", "1.161", "68.7"),
                                     (200000, "0.938", "10.795", "0.561", "83.4")):
        ra5 = RE + ha
        a5 = (rp5 + ra5) / 2
        e5 = (ra5 - rp5) / (ra5 + rp5)
        v0 = np.sqrt(MU * (2 / rp5 - 1 / a5))
        dv = vp5 - v0
        check(f"P4 h_a={ha} e", e5, q_e)
        check(f"P4 h_a={ha} v0 [km/s]", v0, q_v0)
        check(f"P4 h_a={ha} dv [km/s]", dv, q_dv)
        check(f"P4 h_a={ha} mass left [%]", np.exp(-dv / (315 * G0)) * 100, q_m)
    check("P4 period of 250 x 200000 orbit [h]",
          2 * np.pi * np.sqrt(((rp5 + RE + 200000) / 2) ** 3 / MU) / 3600, "96.1")

    check("P4 circle to 200000 km orbit [km/s]", 10.795029 - 7.754845, "3.040")


def computing_3():
    """Problem 5, escape, and why it pays to dive. 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

    a = K.ans_q3(3, 4, 2.2)
    check("dv1", a["dv1"], 1.6153); check("dv2", a["dv2"], 1.4640); check("dv3", a["dv3"], 1.3240)
    truth("three impulses cheapest", a["best"] == "three impulses")
    check("saving of three impulses %", a["saving3_pct"], 18.0); check("saving of two impulses %", a["saving2_pct"], 9.4)
    check("crossing x", a["x_cross_3v1"], 0.707); check("sqrt(2/K)", np.sqrt(0.5), 0.70711)
    truth("dv2(sqrt2, k) = 1 for k = 0.9, 0.5, 0.1, 0.01", all(abs(K.dv2(np.sqrt(2), k) - 1) < 1e-12 for k in (0.9, 0.5, 0.1, 0.01)))
    truth("dv3 = dv1 at x = sqrt(2/K) for several depths",
          all(abs(K.dv3(np.sqrt(2 / Kk), Kk, kii) - K.dv1(np.sqrt(2 / Kk))) < 1e-12 for Kk in (4.0, 10.0) for kii in (0.5, 0.1, 0.02)))
    check("K = 1e6, kii = 1e-6, x = 6: tends to sqrt2 - 1", K.dv3(6.0, 1e6, 1e-6), np.sqrt(2) - 1, tol=0.02)


BLOCKS = [objective, two_ways, where_to_burn, oberth_dive, from_an_ellipse, computing_3]


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