"""Checks every number and formula in the answers and solutions of 30-orbit-ascent-questions.qmd,
including the guided derivations 4-7.
Run from anywhere:  python3 codes/30-orbit-ascent-questions-verify.py"""
import os, sys
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
import _paths  # noqa
import numpy as np
import sympy as sp
from _verify import check, truth, sym_zero, Objective, run
from flight import rocket as R, frames
from flight.constants import MU, R_EARTH, OMEGA_EARTH

PAGE = os.path.join(HERE, "..", "30-orbit-ascent-questions.qmd")
LAT = np.radians(13.72)
U = R.ground_speed_of_rotation(R_EARTH, LAT)
VI = np.sqrt(MU / (R_EARTH + 867e3))
WR = OMEGA_EARTH * R_EARTH
saving = lambda inc, lat=LAT: VI - R.relative_speed_for_orbit(VI, np.radians(inc), R_EARTH, lat)


def data():
    check("data omega r", WR, 465.1, tol=0.05)
    check("data u", U, 451.8, tol=0.05)
    check("data v_I", VI, 7417, tol=0.5)


def objective():
    q = Objective(PAGE, 12)
    truth("Q2: 5 deg is below the latitude", 5 < 13.72)
    q.num(4, R.ground_speed_of_rotation(R_EARTH, np.radians(28.5)), "409", x=409)
    check("Q4 value", R.ground_speed_of_rotation(R_EARTH, np.radians(28.5)), 408.7, tol=0.05)
    i = np.degrees(R.inclination_from_azimuth(LAT, np.radians(135)))
    q.num(5, i, "46.6^\\circ", x=46.6)
    q.num(6, WR * 0.5, "233", x=233)
    for h_ in (45.0,):
        ci = np.degrees(R.inertial_from_relative(1000.0, 0.3, np.radians(h_), R_EARTH, LAT)[2])
        truth("Q7 between 45 and 90", 45 < ci < 90)
    s5, s46 = saving(51.6, np.radians(5)), saving(51.6, np.radians(46))
    check("Q8 saving at 46 N", s46, 287, tol=0.5)
    check("Q8 saving at 5 N", s5, 280, tol=0.5)
    truth("Q8 less than 10 m/s apart", abs(s5 - s46) < 10)
    check("Q8 u^2/2v at most about 14", WR**2 * np.cos(np.radians(5))**2 / (2 * VI), 14, tol=0.5)
    rate = lambda c: R.inertial_energy_rate(1.0, 3000.0, 0.0, c, R_EARTH, LAT)
    q.num(9, rate(np.pi / 2) / rate(3 * np.pi / 2), "1.35", tol=0.006)
    check("Q9 value", rate(np.pi / 2) / rate(3 * np.pi / 2), 1.355, tol=5e-4)
    from orbit.propagate import integrate, radius_event
    MW, RW = 9.80665 * 6378000.0**2, 6378000.0
    r0 = RW + 4e5
    sol = integrate(np.array([r0, 0, 0.0]), np.array([0, np.sqrt(MW / r0) - 7.292e-5 * r0, 0.0]), (0, 3000.0), MW,
                    events=[radius_event(RW, -1, True)])
    check("Q10 impact (s)", sol.t[-1], 885, tol=0.5)
    rv = np.array([0.0, np.cos(0.4), np.sin(0.4)]) * 7e6                    # the most northerly point of an orbit with i = 0.4 rad
    vv = np.array([-7500.0, 0.0, 0.0])
    check("Q11 no change of i at the most northerly point", R.inclination_rate(rv, vv, np.cross(rv, vv) / np.linalg.norm(np.cross(rv, vv))), 0.0, tol=1e-15)
    chi = R.azimuth_for_inclination(np.radians(98.7), LAT, True)
    check("Q12 inertial heading", np.degrees(chi), 189, tol=0.5)
    check("Q12 ground heading", np.degrees(R.relative_from_inertial(VI, 0, chi, R_EARTH, LAT)[2]) % 360, 192.4, tol=0.05)


def drill1():
    s = np.cos(np.radians(45)) / np.cos(LAT)
    check("D1 sin chi", s, 0.7279, tol=5e-5)
    chi = R.azimuth_for_inclination(np.radians(45), LAT, True)
    check("D1 chi_I", np.degrees(chi), 133.29, tol=0.005)
    check("D1 north", VI * np.cos(chi), -5086, tol=0.6)
    check("D1 east", VI * np.sin(chi), 5399, tol=0.6)
    check("D1 east relative", VI * np.sin(chi) - U, 4947, tol=0.6)
    V, _, c = R.relative_from_inertial(VI, 0.0, chi, R_EARTH, LAT)
    check("D1 V", V, 7095, tol=0.6)
    check("D1 heading", np.degrees(c) % 360, 135.8, tol=0.05)
    check("D1 saving", VI - V, 322, tol=0.6)


def drill2():
    dv = lambda i: np.linalg.norm(VI * np.array([np.cos(np.radians(i)) - 1.0, np.sin(np.radians(i))]))   # |v_after - v_before|
    check("D2 Sriharikota", dv(13.72), 1772, tol=0.6)
    check("D2 Kourou", dv(5.2), 673, tol=0.6)
    k = R.ground_speed_of_rotation(R_EARTH, np.radians(5.2))
    check("D2 Kourou pad", k, 463.2, tol=0.05)
    check("D2 pad difference", k - U, 11, tol=0.5)
    check("D2 plane change difference", dv(13.72) - dv(5.2), 1100, tol=5)


def extension():
    v, uu, k, e = sp.symbols("v u k e", positive=True)
    V = sp.sqrt(v**2 + (e * uu)**2 - 2 * v * e * k)
    ser = sp.series(V, e, 0, 3).removeO()
    sym_zero("E3a expansion", sp.simplify(ser - (v - e * k + e**2 * (uu**2 - k**2) / (2 * v))))
    kk = WR * np.cos(np.radians(51.6))
    check("E3b k", kk, 288.9, tol=0.05)
    corr = (U**2 - kk**2) / (2 * VI)
    check("E3b correction", corr, 8.1, tol=0.05)
    check("E3b approximate saving", kk - corr, 280.8, tol=0.05)
    check("E3b exact", saving(51.6), 280.4, tol=0.05)
    c = U**2 / (2 * VI * WR)
    check("E3c cos i", c, 0.0296, tol=5e-5)
    i0 = np.degrees(np.arccos(c))
    check("E3c inclination", i0, 88.3, tol=0.05)
    check("E3c neutral", saving(i0), 0.0, tol=1e-9)
    check("E3c polar cost", -saving(90.0), 13.7, tol=0.05)


def dogleg():
    """Guided derivation 4: turning the plane during the ascent."""
    i, ph, ch = sp.symbols("i phi chi", positive=True)
    # implicit differentiation of cos i = cos phi sin chi
    di = sp.diff(sp.cos(ph) * sp.sin(ch), ch) / sp.diff(sp.cos(i), i)
    sym_zero("P4b di/dchi", di + sp.cos(ph) * sp.cos(ch) / sp.sin(i))
    phi = np.radians(13.72)
    chi = np.arcsin(np.cos(np.radians(45)) / np.cos(phi))
    check("P4b chi_I (deg)", np.degrees(chi), 46.7)
    check("P4b consistent with the engine", np.degrees(R.azimuth_for_inclination(np.radians(45), phi)), np.degrees(chi), tol=1e-9)
    check("P4b factor", -np.cos(phi) * np.cos(chi) / np.sin(np.radians(45)), -0.94)
    for V, w in ((2000.0, 174), (7800.0, 680)):
        check(f"P4c 5 deg at {V} m/s", 2 * V * np.sin(np.radians(2.5)), w)


def east_west():
    """Guided derivation 5: where the east-west difference comes from."""
    import _orbit30 as O
    from flight.constants import MU as MU_
    Vx, Vy, uu = sp.symbols("V_x V_y u", real=True)            # x east
    sym_zero("P5a kinetic energy gained", ((Vx + uu)**2 + Vy**2) / 2 - uu**2 / 2 - ((Vx**2 + Vy**2) / 2 + uu * Vx))
    t = sp.symbols("t", positive=True); A = sp.symbols("A", positive=True)   # constant eastward a: same result by work
    vI = uu + A * t
    sym_zero("P5a work integral", sp.integrate(A * vI, (t, 0, 1)) - ((A**2) / 2 + uu * A))
    out = {}
    for h in (90.0, 270.0):
        b = O.boost(h); tr = b["tr"]; k = slice(0, b["j"] + 1)
        a = (tr.thrust[k] * np.cos(tr.alpha[k]) - tr.drag[k]) / tr.m[k]
        rad = np.linalg.norm(tr.r[k], axis=1)
        u_ = R.ground_speed_of_rotation(rad, tr.lat[k])
        out[h] = dict(I1=np.trapz(a * tr.V[k], tr.t[k]), I2=np.trapz(a * u_ * np.sin(tr.chi[k]) * np.cos(tr.gamma[k]), tr.t[k]),
                      Ih=np.trapz(a * np.cos(tr.gamma[k]), tr.t[k]), E=b["energy"], V=tr.V[k][-1],
                      g=np.degrees(tr.gamma[k][-1]), h=b["h"])
    e, w = out[90.0], out[270.0]
    check("P5 east - west (MJ/kg)", (e["E"] - w["E"]) / 1e6, 5.2, tol=0.05)
    check("P5c horizontal impulse (m/s)", e["Ih"], 6206, tol=0.5)
    est = 2 * U * e["Ih"] / 1e6
    check("P5c estimate (MJ/kg)", est, 5.61, tol=0.005)
    check("P5c 8 % high", 100 * (est / ((e["E"] - w["E"]) / 1e6) - 1), 8, tol=0.5)
    check("P5d rotation terms (MJ/kg)", (e["I2"] - w["I2"]) / 1e6, 5.88, tol=0.005)
    check("P5d first terms (MJ/kg)", (e["I1"] - w["I1"]) / 1e6, -0.68, tol=0.005)
    check("P5d sum = simulator (MJ/kg)", (e["I1"] - w["I1"] + e["I2"] - w["I2"]) / 1e6, 5.20, tol=0.01)
    check("P5d gamma east", e["g"], 15.0, tol=0.05)
    check("P5d gamma west", w["g"], 6.8, tol=0.05)
    check("P5d height difference (km)", (e["h"] - w["h"]) / 1e3, 92, tol=0.5)
    check("P5d V east", e["V"], 6204, tol=0.5)
    check("P5d V west", w["V"], 6441, tol=0.5)
    check("P5d share (%)", 100 * 0.68 / 5.88, 12, tol=0.5)


def launch_window():
    """Guided derivation 6: why the launch window to a given plane is short."""
    from scipy.optimize import brentq
    ph, ch = sp.symbols("phi chi", positive=True)
    sym_zero("P6a second form", sp.expand(sp.cos(ph)**2 * sp.cos(ch)**2 - (sp.cos(ph)**2 - (sp.cos(ph) * sp.sin(ch))**2)))
    phi, inc = np.radians(13.72), np.radians(51.6)
    check("P6b cos^2 phi", np.cos(phi)**2, 0.9437, tol=5e-5)
    check("P6b cos^2 i", np.cos(inc)**2, 0.3858, tol=5e-5)
    check("P6b difference", np.cos(phi)**2 - np.cos(inc)**2, 0.5579, tol=5e-5)
    rate = OMEGA_EARTH * np.sqrt(np.cos(phi)**2 - np.cos(inc)**2)
    check("P6b rate", rate, 5.45e-5, tol=5e-8)
    chi = R.azimuth_for_inclination(inc, phi)
    check("P6a = omega cos phi |cos chi|", OMEGA_EARTH * np.cos(phi) * abs(np.cos(chi)), rate, tol=1e-15)
    hvec = np.array([0, -np.sin(inc), np.cos(inc)])
    beta = lambda L: np.arcsin(np.array([np.cos(phi) * np.cos(L), np.cos(phi) * np.sin(L), np.sin(phi)]) @ hvec)
    L0 = brentq(beta, 0, np.pi / 2); dL = 1e-6
    check("P6a numerical rate", abs(beta(L0 + dL) - beta(L0 - dL)) / (2 * dL) * OMEGA_EARTH, rate, tol=1e-12)
    check("P6b deg per minute", np.degrees(rate) * 60, 0.187, tol=5e-4)
    check("P6b beta per minute", rate * 60, 3.27e-3, tol=5e-6)
    v = np.sqrt(MU / (R_EARTH + 400e3))
    check("P6 v", v, 7669, tol=0.5)
    check("P6b per minute", 7669 * 3.27e-3, 25, tol=0.5)
    check("P6b five minutes", v * rate * 300, 125, tol=0.5)
    check("P6b saving at 51.6", saving(51.6), 280, tol=0.5)
    # (c): at i = phi the crossing is tangential: beta grows as the square of the delay
    hv2 = np.array([0, -np.sin(phi), np.cos(phi)])
    b2 = lambda L: np.arcsin(np.array([np.cos(phi) * np.cos(L), np.cos(phi) * np.sin(L), np.sin(phi)]) @ hv2)
    Lt = np.pi / 2   # the most northerly point of the plane's track
    check("P6c tangent: beta zero at the touching point", b2(Lt), 0.0, tol=1e-12)
    r1, r2 = b2(Lt + 0.01), b2(Lt + 0.02)
    check("P6c quadratic growth", r2 / r1, 4.0, tol=0.01)
    a_ = np.arctan(np.radians(0.5) / np.log(7.6 / 2))
    check("P6d tilt", np.degrees(a_), 0.37, tol=0.005)
    check("P6d loss", 5600 * (1 / np.cos(a_) - 1), 0.1, tol=0.05)


def along_across():
    """Guided derivation 7: along the orbit and across it."""
    v, u, c = sp.symbols("v u chi", positive=True)
    Vpar, Vper = v - u * sp.sin(c), -u * sp.cos(c)
    sym_zero("P7a V^2", sp.expand(Vpar**2 + Vper**2 - (v**2 - 2 * v * u * sp.sin(c) + u**2)).subs(sp.sin(c)**2, 1 - sp.cos(c)**2).expand())
    check("P7b u/v", U / VI, 0.0609, tol=5e-5)
    check("P7b polar deg", np.degrees(U / VI), 3.49, tol=0.005)
    for inc, south, ci, de, d1 in ((45, True, 133.29, 2.50, 2.39), (98.7, True, 188.96, 3.41, 3.45), (90, True, 180.0, 3.49, 3.49),
                                   (20, False, 75.31, -0.94, -0.89)):
        chi = R.azimuth_for_inclination(np.radians(inc), LAT, south)
        check(f"P7c chi_I {inc}", np.degrees(chi) % 360, ci, tol=0.005)
        V, _, cg = R.relative_from_inertial(VI, 0.0, chi, R_EARTH, LAT)
        dex = (np.degrees(cg) - np.degrees(chi) + 180) % 360 - 180
        check(f"P7c delta exact (engine) {inc}", dex, de, tol=0.005)
        check(f"P7c delta exact (formula) {inc}", np.degrees(np.arctan2(-U * np.cos(chi), VI - U * np.sin(chi))), dex, tol=1e-9)
        check(f"P7c first order {inc}", np.degrees(-(U / VI) * np.cos(chi)), d1, tol=0.005)
        truth(f"P7c within about 0.1 deg {inc}", abs(dex - np.degrees(-(U / VI) * np.cos(chi))) < 0.12)
    check("P7d cos phi", np.cos(LAT), 0.97, tol=0.005)
    check("P7d error", np.cos(LAT) * 3.49, 3.4, tol=0.05)
    check("P7d cost to correct (m/s)", 2 * VI * np.sin(np.radians(3.39) / 2), 440, tol=5)


if __name__ == "__main__":
    run([data, objective, drill1, drill2, extension, dogleg, east_west, launch_window, along_across])
