"""Checks every number in the answers and solutions of 04-forces-questions.qmd.
Run from anywhere:  python3 codes/04-forces-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
from _verify import check, truth, Objective, run
from flight import atmosphere as A, gravity, frames, vehicle
from flight.constants import G0, A_EARTH as R, B_EARTH, MU, J2, DEG, OMEGA_EARTH as W, P0_SL
from flight import rocket as RK

PAGE = os.path.join(HERE, "..", "04-forces-questions.qmd")
PSLV = vehicle.load("pslv-ca")


def data():
    """The data box, from the engine's standard atmosphere."""
    check("p at 10 km (Pa)", A.ISA.state(10e3)[1], 26500, tol=5)
    check("p at 30 km (Pa)", A.ISA.state(30e3)[1], 1197)
    check("rho at 11 km", A.ISA.state(11e3)[2], 0.3648)
    check("J2", J2, 1.08263e-3, tol=5e-9)


def objective():
    """The 12 objective questions."""
    q = Objective(PAGE, 12)
    q.num(5, (R / (R + 400e3)) ** 2 * 100, "88.5")
    check("Q5 distractor R/(R+h) (%)", R / (R + 400e3) * 100, 94.1)
    check("Q5 distractor squared twice (%)", (R / (R + 400e3)) ** 4 * 100, 78.4)
    Va = np.array([230.0, 0, 0]) - np.array([-30.0, 0, 0])      # NED; wind from the north blows south
    q.num(6, np.linalg.norm(Va), "260")
    rho = A.ISA.state(11e3)[2]
    q.num(7, 0.5 * rho * 230**2 / 1e3, "9.6")
    check("Q7 at sea level (kPa)", 0.5 * A.ISA.state(0)[2] * 230**2 / 1e3, 32, tol=0.5)
    check("Q7 distractor without 1/2 (kPa)", rho * 230**2 / 1e3, 19, tol=0.5)
    eng = PSLV.stages[1].engine
    check("Q8 dataset T_vac (kN)", eng.T_vac / 1e3, 809.6)
    check("Q8 dataset A_e (m^2)", eng.A_e, 0.845)
    q.num(8, (eng.T_vac - P0_SL * eng.A_e) / 1e3, "724")
    check("Q8 distractor (kN)", (eng.T_vac + P0_SL * eng.A_e) / 1e3, 895)
    a = 4 * DEG
    q.num(9, 0.20 * np.cos(a) - 0.30 * np.sin(a), "0.179")
    check("Q9 C_N cos a", 0.20 * np.cos(a), 0.1995)
    check("Q9 C_A sin a", 0.30 * np.sin(a), 0.0209)
    check("Q9 C_D", 0.20 * np.sin(a) + 0.30 * np.cos(a), 0.313)
    lat = np.radians(np.linspace(1, 89, 89))
    gN = np.array([gravity.spherical_components(R, p)[1] for p in lat])
    truth("Q11 g_N < 0 (southwards) at every northern latitude", np.all(gN < 0))
    truth("Q11 g_N = 0 at the equator and the pole",
          abs(gravity.spherical_components(R, 0.0)[1]) < 1e-15 and abs(gravity.spherical_components(R, np.pi / 2)[1]) < 1e-12)
    geq = np.linalg.norm(gravity.effective(frames.ecef_from_geodetic(0.0, 0.0, 0.0)))
    gpo = np.linalg.norm(gravity.effective(frames.ecef_from_geodetic(np.pi / 2, 0.0, 0.0)))
    check("Q12 equator (m/s^2)", geq, 9.780)
    check("Q12 pole (m/s^2)", gpo, 9.832)
    check("Q12 difference", gpo - geq, 0.052)
    check("Q12 centrifugal at the equator", W**2 * R, 0.0339)
    check("Q12 share (%)", W**2 * R / (gpo - geq) * 100, 65)
    check("Q12 poles closer (km)", (R - B_EARTH) / 1e3, 21)


def vikas():
    """Drill 1: the Vikas engine as it climbs."""
    eng, st = PSLV.stages[1].engine, PSLV.stages[1]
    md = eng.T_vac / (G0 * eng.isp_vac)
    check("P1 mdot (kg/s)", md, 281.8)
    for h, want in ((0, 724.0), (10e3, 787.2), (30e3, 808.6)):
        check(f"P1 thrust at {h / 1e3:.0f} km (kN)", eng.thrust(1.0, A.ISA.state(h)[1], 0, 0, 0, 0, 0) / 1e3, want)
    T0 = eng.T_vac - P0_SL * eng.A_e
    check("P1 sea-level Isp (s)", T0 / (md * G0), 262)
    check("P1 thrust lost at sea level (%)", (1 - T0 / eng.T_vac) * 100, 11, tol=0.5)
    check("P1 dataset propellant (t)", st.m_prop / 1e3, 41.7)
    check("P1 burn time (s)", st.m_prop / md, 148)


def sriharikota():
    """Drill 2: gravity over Sriharikota."""
    phi = 13.61 * DEG
    check("P2 3 sin^2 - 1", 3 * np.sin(phi) ** 2 - 1, -0.834)
    for h, gp, gr_, d in ((0, 9.798, 9.812, 0.0133), (100e3, 9.498, 9.511, 0.0125), (400e3, 8.676, 8.686, 0.0104)):
        g_r, g_n = gravity.spherical_components(R + h, phi)
        check(f"P2 point mass at {h / 1e3:.0f} km", MU / (R + h) ** 2, gp)
        check(f"P2 g_r with J2 at {h / 1e3:.0f} km", g_r, gr_)
        check(f"P2 J2 change at {h / 1e3:.0f} km", g_r - MU / (R + h) ** 2, d)
    g_r, g_n = gravity.spherical_components(R, phi)
    check("P2 J2 change at the surface (%)", (g_r / (MU / R**2) - 1) * 100, 0.14)
    check("P2 g_N at the surface", g_n, -0.0073)
    truth("P2 |g_N| is smaller than the Coriolis term on an airliner at 250 m/s", abs(g_n) < 2 * W * 250)


def fourth_stage():
    """Extension 3: the fourth stage."""
    import sympy as sp
    st = PSLV.stages[3]
    eng = st.engine
    check("P3 dataset thrust (kN)", eng.T_vac / 1e3, 14.66)
    check("P3 dataset Isp (s)", eng.isp_vac, 308)
    check("P3 dataset dry mass (kg)", st.m_dry, 920)
    m, ve, m0, m1 = sp.symbols("m v_e m_0 m_1", positive=True)
    truth("P3 integral of -v_e dm/m from m0 to m1 = v_e ln(m0/m1)",
          sp.simplify(sp.integrate(-ve / m, (m, m0, m1)) - ve * sp.log(m0 / m1)) == 0)
    m0_, m1_ = PSLV.payload + st.m_dry + st.m_prop, PSLV.payload + st.m_dry
    check("P3 m0 (kg)", m0_, 4420)
    check("P3 m1 (kg)", m1_, 1920)
    check("P3 delta v (m/s)", RK.delta_v(RK.exhaust_velocity(eng.isp_vac), m0_, m1_), 2518)
    check("P3 T/W", eng.T_vac / (m0_ * G0), 0.34)
    md = eng.T_vac / (G0 * eng.isp_vac)
    check("P3 mdot (kg/s)", md, 4.85)
    check("P3 burn time (s)", st.m_prop / md, 515)
    check("P3 g0 t_b (m/s)", G0 * st.m_prop / md, 5050, tol=1)


if __name__ == "__main__":
    run([data, objective, vikas, sriharikota, fourth_stage])
