"""Checks every number and identity in the answers and solutions of bielliptic-transfer-questions.qmd
(The Bi-elliptic Transfer: 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/bielliptic-transfer-questions-verify.py
"""
from _verify import check, truth, 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

    obj = Objective("bielliptic-transfer-questions.qmd", 3)
    num, right = obj.num, obj.right

    R = 20.0
    g = np.sqrt(2 * R / (1 + R)) - 1 + 1 / np.sqrt(R) - np.sqrt(2 / (R * (1 + R)))
    bp = (np.sqrt(2) - 1) * (1 + 1 / np.sqrt(R))
    truth(f"Q3   Hohmann {g:.3f}, bi-parabolic {bp:.3f}, saving {(g - bp) / g:.1%}",
          abs(g - 0.535) < 5e-4 and bp < g and abs((g - bp) / g - 0.05) < 0.005 and "bi-parabolic" in right(3))


def moon_transfer():
    """Problem 1, a transfer to the Moon's distance."""
    import numpy as np

    from orbit.constants import MU_EARTH as mu
    r1 = 6678.137
    vc1 = np.sqrt(mu/r1)

    vis = lambda r, a: np.sqrt(mu*(2/r - 1/a))
    half = lambda a: np.pi*np.sqrt(a**3/mu)
    g = lambda R: np.sqrt(2*R/(1 + R)) - 1 + (1 - np.sqrt(2/(1 + R)))/np.sqrt(R)

    def bi(R, S):
        """The three burns in units of v_c1, positive sizes, from the formulas of the note; S = r_b/r_1 > R."""
        return (np.sqrt(2*S/(1 + S)) - 1, np.sqrt(2/S)*(np.sqrt(R/(R + S)) - np.sqrt(1/(1 + S))), np.sqrt(2*S/(R*(R + S))) - 1/np.sqrt(R))

    # the speed formula on an ellipse with apsides r and r'
    for r, rr in ((7000., 50000.), (42000., 9000.)):
        check("v from apsides", np.sqrt(2*mu*rr/(r*(r + rr))), vis(r, (r + rr)/2), 1e-10)
    check("R* = R is Hohmann", sum(bi(15, 15)), g(15), 1e-12); check("no third burn", bi(15, 15)[2], 0, 1e-12)
    check("second burn vanishes as r_b grows", bi(15, 1e12)[1], 0, 1e-4)

    # the example
    binf = lambda R: (np.sqrt(2) - 1)*(1 + 1/np.sqrt(R))

    # the exercise
    rm = 384400.0; am = (r1 + rm)/2; R = rm/r1
    d1_, d2_ = vis(r1, am) - vc1, np.sqrt(mu/rm) - vis(rm, am)
    check("burn 1", d1_, 3.106, 5e-4); check("burn 2", d2_, 0.830, 5e-4); check("total", d1_ + d2_, 3.937, 6e-4); check("days", half(am)/86400, 4.98, 5e-3); check("R", R, 57.6, 0.05)
    S = 2*R; check("saving at 2 r_2, m/s", 1e3*(g(R) - sum(bi(R, S)))*vc1, 133, 0.5)
    check("time at 2 r_2, days", (half((r1 + 2*rm)/2) + half((rm + 2*rm)/2))/86400, 39, 0.5); check("limit saving, m/s", 1e3*(g(R) - binf(R))*vc1, 315, 0.5)

    # the exercise, worked solution
    check("a_t", am, 195539, 0.5); check("perigee speed", vis(r1, am), 10.8322, 5e-5); check("v_c1", vc1, 7.7258, 5e-5)
    check("apogee speed", vis(rm, am), 0.1882, 5e-5); check("circular at r_2", np.sqrt(mu/rm), 1.0183, 5e-5)
    rbx = 2*rm; ax1, ax2 = (r1 + rbx)/2, (rm + rbx)/2
    rows = [(vc1, vis(r1, ax1)), (vis(rbx, ax1), vis(rbx, ax2)), (vis(rm, ax2), np.sqrt(mu/rm))]
    for k, (q1, q2, dq) in enumerate(((7.7258, 10.8787, 3.1530), (0.0945, 0.5879, 0.4934), (1.1758, 1.0183, 0.1575))):
        check(f"table row {k+1}", rows[k][0], q1, 5e-5); check(f"table row {k+1} after", rows[k][1], q2, 5e-5); check(f"table row {k+1} dv", abs(rows[k][1] - rows[k][0]), dq, 5e-5)
    tot2 = sum(abs(b - a_) for a_, b in rows); check("total at 2 r_2", tot2, 3.804, 5e-4); check("eight times as long", 39.12/4.98, 8, 0.2)
    check("limit cost", (np.sqrt(2) - 1)*(1 + 1/np.sqrt(R))*vc1, 3.622, 5e-4); check("saving at 2 r_2, %", 100*(1 - tot2/(d1_ + d2_)), 3, 0.5)


def neptune():
    """Problem 2, Hohmann or bi-elliptic to Neptune's orbit."""
    import numpy as np

    # ---------------------------------------------------------------- constants (the handout's table)

    from orbit.constants import MU_SUN as MU_S, AU
    A_N = 30.07*AU

    YEAR = 365.25*86400.0

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

    def hohmann(mu, r1, r2):
        at = (r1 + r2)/2
        v1, v2 = np.sqrt(mu/r1), np.sqrt(mu/r2)
        d1, d2 = vis(mu, r1, at) - v1, v2 - vis(mu, r2, at)
        return v1, v2, d1, d2, np.pi*np.sqrt(at**3/mu)

    # ================================================================ Problem 6: to Neptune's orbit
    print("\n--- Problem 2")
    r1, r2, rb = AU, A_N, 60*AU
    v1, v2, d1, d2, tt = hohmann(MU_S, r1, r2)
    check("P2 V Earth", v1, "29.785"); check("P2 V Neptune", v2, "5.432")
    check("P2 Hohmann dv1", d1, "11.654"); check("P2 Hohmann dv2", d2, "4.054"); check("P2 Hohmann total", d1 + d2, "15.707")
    check("P2 Hohmann time, yr", tt/YEAR, "30.6", tol=0.05)
    a1, a2 = (r1 + rb)/2, (r2 + rb)/2
    b1 = vis(MU_S, r1, a1) - v1
    b2 = vis(MU_S, rb, a2) - vis(MU_S, rb, a1)
    b3 = vis(MU_S, r2, a2) - v2
    check("P2 a1/AU", a1/AU, "30.5", tol=0.05); check("P2 a2/AU", a2/AU, "45.035")
    check("P2 bi dv1", b1, "11.991"); check("P2 bi dv2", b2, "2.446"); check("P2 bi dv3", b3, "0.838")
    check("P2 speed at rb on ellipse 1", vis(MU_S, rb, a1), "0.696"); check("P2 speed at rb on ellipse 2", vis(MU_S, rb, a2), "3.142")
    check("P2 bi total", b1 + b2 + b3, "15.274")
    check("P2 saving m/s", (d1 + d2 - b1 - b2 - b3)*1e3, "433", tol=0.5)
    tb = (np.pi*np.sqrt(a1**3/MU_S) + np.pi*np.sqrt(a2**3/MU_S))/YEAR
    check("P2 bi time, yr", tb, "235.3")
    check("P2 first half, yr", np.pi*np.sqrt(a1**3/MU_S)/YEAR, "84.2", tol=0.05)
    check("P2 second half, yr", np.pi*np.sqrt(a2**3/MU_S)/YEAR, "151.1", tol=0.05)
    check("P2 r2/r1", r2/r1, "30.07")

    check("P2 Hohmann a/AU", (1 + 30.07)/2, "15.535")


def lunar_distance():
    """Problem 3, bi-elliptic to lunar distance."""
    import sys
    import numpy as np
    sys.path.insert(0, "codes")
    from _mqburn import MU                                   # noqa: E402

    from orbit.constants import MU_SUN as MUS, AU, D_MOON as r2

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

    # ======================================================================= P3
    print("P3. bi-elliptic to lunar distance")
    r1, rb = 6678.137, 1e6
    aH = (r1 + r2) / 2
    dvH = (vis(r1, aH) - np.sqrt(MU / r1)) + (np.sqrt(MU / r2) - vis(r2, aH))
    check("Hohmann [km/s]", dvH, 3.9365, 5e-5)
    a1, a2 = (r1 + rb) / 2, (rb + r2) / 2
    dvB = (vis(r1, a1) - np.sqrt(MU / r1)) + (vis(rb, a2) - vis(rb, a1)) + (vis(r2, a2) - np.sqrt(MU / r2))
    check("bi-elliptic [km/s]", dvB, 3.7672, 5e-5)
    check("saving [m/s]", (dvH - dvB) * 1e3, 169, 0.5)
    check("flight time [d]", (np.pi * np.sqrt(a1 ** 3 / MU) + np.pi * np.sqrt(a2 ** 3 / MU)) / 86400, 53.7, 0.05)
    check("Hill radius of the Earth [km]", AU * (MU / (3 * MUS)) ** (1 / 3), 1.50e6, 0.01e6)


def to_the_sun():
    """Problem 4, reaching the Sun the long way round."""
    import numpy as np
    import sympy as sp

    # ---------------------------------------------------------------- constants (the handout's table)
    from orbit.constants import MU_EARTH as MU, R_EARTH as RE, MU_SUN as MU_S, AU, R_SUN
    G0 = 9.80665e-3           # km/s^2

    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)

    # ======================================================================== Problem 4
    print("\n== Problem 4: to the Sun")
    vE = sp.symbols("v_E", positive=True)
    dv1s = vE*(sp.sqrt(2*x/(1 + x)) - 1)
    dv2s = vE*(sp.sqrt(2/(x*(1 + x))) - sp.sqrt(2*rho/(x*(x + rho))))
    # vis-viva in AU units (mu = vE^2): aphelion speed of the (1, x) ellipse and of the (rho, x) ellipse
    truth("4a aphelion speed of first ellipse", zero(vE**2*(2/x - 2/(1 + x)) - vE**2*2/(x*(1 + x))))
    truth("4a aphelion speed of second ellipse", zero(vE**2*(2/x - 2/(x + rho)) - vE**2*2*rho/(x*(x + rho))))
    lim0 = sp.limit(dv1s + dv2s, rho, 0)
    truth("4b rho->0 total", zero(lim0 - vE*(sp.sqrt(2*x/(1 + x)) - 1 + sp.sqrt(2/(x*(1 + x))))))
    truth("4b factor: sqrt(2/(x(1+x)))(x+1) = sqrt(2(1+x)/x)",
       zero(sp.sqrt(2/(x*(1 + x)))*(x + 1) - sp.sqrt(2*(1 + x)/x)))
    # cheaper than v_E iff x > 1: check sign of v_E - total at sample points on both sides and equality at x=1
    g = lambda X: float((vE - lim0).subs({vE: 1, x: X}))
    truth("4b equal at x = 1", abs(g(1.0)) < 1e-12)
    truth("4b cheaper for x > 1 (samples)", all(g(X) > 0 for X in (1.01, 2, 5.2, 30, 1e4)))
    truth("4b dearer for x < 1 (samples)", all(g(X) < 0 for X in (0.2, 0.5, 0.99)))
    truth("4b limit x->inf = (sqrt2 - 1) v_E", zero(sp.limit(lim0, x, sp.oo) - (sp.sqrt(2) - 1)*vE))

    VE = np.sqrt(MU_S/AU)
    RHO = 10*R_SUN/AU
    X = 5.2026
    check("4c v_E", VE, "29.7847")
    check("4c rho", RHO, "0.04650")
    direct = VE*(1 - np.sqrt(2*RHO/(1 + RHO)))
    check("4c direct (km/s)", direct, "20.905")
    check("4b escape (sqrt2-1) v_E", (np.sqrt(2) - 1)*VE, "12.34")
    D1 = VE*(np.sqrt(2*X/(1 + X)) - 1)
    V1B = VE*np.sqrt(2/(X*(1 + X)))
    V2B = VE*np.sqrt(2*RHO/(X*(X + RHO)))
    check("4c dv1", D1, "8.793")
    check("4c aphelion speed, first ellipse", V1B, "7.4150")
    check("4c aphelion speed, second ellipse", V2B, "1.7382")
    check("4c dv2", V1B - V2B, "5.677")
    check("4c total", D1 + V1B - V2B, "14.469")
    check("4c saving vs direct", direct - (D1 + V1B - V2B), "6.44")
    check("4c a of first half", (1 + X)/2, "3.101")
    check("4c time of first half (yr)", 0.5*((1 + X)/2)**1.5, "2.731")
    check("4c a of second half", (X + RHO)/2, "2.625")
    check("4c time of second half (yr)", 0.5*((X + RHO)/2)**1.5, "2.126")
    check("4c total time (yr)", 0.5*((1 + X)/2)**1.5 + 0.5*((X + RHO)/2)**1.5, "4.857")
    check("4c direct time (days)", 0.5*((1 + RHO)/2)**1.5*365.25, "69", tol=0.5)
    RP = RE + 300
    VCP, VESC = np.sqrt(MU/RP), np.sqrt(2*MU/RP)
    check("4d v_c at 300 km", VCP, "7.7258")
    check("4d v_esc at 300 km", VESC, "10.9259")
    check("4d departure, direct", np.sqrt(direct**2 + VESC**2) - VCP, "15.862")
    check("4d departure, bi-elliptic", np.sqrt(D1**2 + VESC**2) - VCP, "6.299")
    frac = np.exp(-(V1B - V2B)/(320*G0))
    check("4d mass left after dv2", frac, "0.164")
    check("4d propellant fraction ~ 5/6", 1 - frac, "0.83", tol=0.01)


def computing_4():
    """Problem 5, Hohmann against bi-elliptic. 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_q4(12.0)
    check("Hohmann R = 12", a["dv_H"], 0.53418); check("bi-parabolic R = 12", a["dv_inf"], 0.53379)
    check("k_min", a["k_min"], 816, tol=0.5); check("r_i/r_2", a["ratio_min"], 68.0)
    check("saving at 10 R %", a["saving_10R_pct"], -0.36); check("saving at infinity %", a["saving_inf_pct"], 0.074)
    check("R where Hohmann = bi-parabolic", K.R_inf(), 11.939); check("R where the slope at R+ is zero", K.R_touch(), 15.582)
    roots = [z.real for z in np.roots([1, -15, -9, -1]) if abs(z.imag) < 1e-12 and z.real > 1]
    check("root of R^3 - 15R^2 - 9R - 1", roots[0], K.R_touch(), tol=1e-4)
    for R in (2.0, 12.0, 20.0):
        k = 1e5
        check(f"k(dV - dV_inf) at k = 1e5, R = {R}", k * (K.dv_bi(R, k) - K.dv_inf(R)), np.sqrt(2) / 2 * (np.sqrt(R) - 3), tol=3e-3)
    ks = np.linspace(1.001, 1.999, 4000); vals = [K.dv_bi(2.0, k) for k in ks]; j = int(np.argmax(vals))
    check("interior crest R = 2", vals[j], 0.2907); check("at k", ks[j], 1.40, tol=0.02); check("Hohmann R = 2", K.dv_H(2.0), 0.28446)


BLOCKS = [objective, moon_transfer, neptune, lunar_distance, to_the_sun, computing_4]


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