"""Checks every number and formula in the answers and solutions of 34-lifting-entry-questions.qmd,
including the guided derivations 4-7.
Run from anywhere:  python3 codes/34-lifting-entry-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 entry as E
from flight.constants import G0, RHO0_SL

PAGE = os.path.join(HERE, "..", "34-lifting-entry-questions.qmd")


def objective():
    q = Objective(PAGE, 12)
    check("Q2 range doubles", E.glide_range_angle(0.2, 0.9, 2.0) / E.glide_range_angle(0.2, 0.9, 1.0), 2.0, rel=1e-12)
    q.num(4, E.glide_deceleration(0.4, 1.5) / G0, "0.40")
    check("Q5 speed ratio", np.sqrt(E.GLIDE_HEATING_U), 0.82, tol=0.005)
    check("Q5 D", np.sqrt(1 / 3), 0.58, tol=0.005)
    q.num(6, E.skip_exit_speed_ratio(np.radians(-4), 2.0), "0.93")
    check("Q7", 0.3 * np.cos(np.radians(70)), 0.103, tol=5e-4)
    check("Q9 Z", 30 * (1 - np.cos(np.radians(5))), 0.114, tol=5e-4)


def drill1():
    g, r, H = 9.5, 6438e3, 7087.0
    th = E.glide_range_angle(0.1, 0.9, 1.5)
    check("D1 angle", th, 1.648, tol=5e-4)
    check("D1 distance (km)", th * r / 1e3, 10610, tol=5)
    check("D1 time", E.glide_time(0.1, 0.9, 1.5, r, g), 1841, tol=0.5)
    rho = E.glide_density(2 / 3, 300.0, 1.5, r)
    check("D1 rho", rho, 3.11e-5, tol=5e-8)
    check("D1 h (km)", E.altitude_of_density(rho, RHO0_SL, H) / 1e3, 75.0, tol=0.05)
    d = E.glide_deceleration(2 / 3, 1.5, g)
    check("D1 decel", d, 2.11, tol=0.005)
    check("D1 in g0", d / G0, 0.22, tol=0.005)


def drill2():
    gi = np.radians(-3)
    q = E.skip_exit_speed_ratio(gi, 2.0)
    check("D2 factor", q, 0.949, tol=5e-4)
    for n, want in ((1, 7.212), (2, 6.844), (3, 6.495)):
        check(f"D2 after {n}", 7.6 * q**n, want, tol=6e-4)
    check("D2 bottom of third", 7.6 * q**2 * E.skip_speed_ratio(0.0, gi, 2.0), 6.668, tol=6e-4)


def extension():
    for gi, ld in ((-0.1, 1.0), (-0.3, 2.5)):
        vb, vf = E.skip_speed_ratio(0.0, gi, ld), E.skip_exit_speed_ratio(gi, ld)
        check("E3a V_b^2 = V_i V_f", vb**2, vf, rel=1e-12)
        check("E3b loss ratio", (vb**2 - vf**2) / (1 - vb**2), vf, rel=1e-12)
    gi = np.radians(-8)
    check("E3c V_b", E.skip_speed_ratio(0.0, gi, 1.0), 0.870, tol=5e-4)
    check("E3c V_f", E.skip_exit_speed_ratio(gi, 1.0), 0.756, tol=5e-4)


def glide_oscillation():
    """Guided derivation 4: the oscillation about the equilibrium glide."""
    from scipy.integrate import solve_ivp
    from flight.constants import MU, R_EARTH
    H, B, Ev = 7087.0, 300.0, 1.0
    for u, w in ((0.95, 760), (0.74, 333), (0.56, 256)):
        check(f"P4c period at u={u} (s)", 2 * np.pi * np.sqrt(H / (9.7 * (1 - u))), w)
    def rhs(t, y):
        h, V, g = y
        r = R_EARTH + h
        gg = MU / r**2
        Dm = RHO0_SL * np.exp(-h / H) * V * V / (2 * B)
        return [V * np.sin(g), -Dm - gg * np.sin(g), (Ev * Dm - (gg - V * V / r) * np.cos(g)) / V]
    u0 = 0.95
    r = R_EARTH + 65e3
    rho = E.glide_density(u0, B, Ev, r)
    h0 = -H * np.log(rho / RHO0_SL)
    V0 = np.sqrt(u0 * MU / (R_EARTH + h0))
    sol = solve_ivp(rhs, (0, 1500), [h0, V0, 0.0], max_step=0.5, rtol=1e-9, atol=1e-9, dense_output=True)
    t = np.linspace(0, 1500, 30001)
    y = sol.sol(t)
    gm = y[2]
    pk = [i for i in range(1, len(t) - 1) if gm[i] > gm[i - 1] and gm[i] >= gm[i + 1]]
    us = [y[1][i]**2 / (MU / (R_EARTH + y[0][i])) for i in pk]
    per = np.diff(t[pk])
    for k, w in zip(range(3), (565, 343, 251)):
        check(f"P4c simulated period {k + 1} (s)", per[k], w, tol=2)
        um = 0.5 * (us[k] + us[k + 1])
        gk = MU / (R_EARTH + y[0][pk[k]])**2
        check(f"P4c formula at the mean u within 12 % (period {k + 1})", 2 * np.pi * np.sqrt(H / (gk * (1 - um))), per[k], rel=0.12)
    check("P4c u at the peaks", us[1], 0.83)
    check("P4c u at the peaks (3)", us[2], 0.66)
    check("P4c u at the peaks (4)", us[3], 0.46)


def banked_glide():
    """Guided derivation 5: turning on the glide."""
    u, E_, s_, g, r = sp.symbols("u E sigma g r", positive=True)
    V = sp.sqrt(u * g * r)
    Lm = g * (1 - u) / sp.cos(s_)
    udot = -2 * (Lm / E_) * V / (g * r)
    chidot = Lm * sp.sin(s_) / V
    sym_zero("P5b dchi/du = -E sin(sigma)/(2u)", sp.simplify(chidot / udot + E_ * sp.sin(s_) / (2 * u)))
    thdot = V / r
    sym_zero("P5c dtheta/du = -E cos(sigma)/(2(1-u))", sp.simplify(thdot / udot + E_ * sp.cos(s_) / (2 * (1 - u))))
    d1 = 1.0 * np.sin(np.radians(45)) / 2 * np.log(0.95 / 0.4)
    check("P5d heading change (rad)", d1, 0.306)
    check("P5d heading change (deg)", np.degrees(d1), 17.5)
    check("P5d L/D = 2 (deg)", 2 * np.degrees(d1), 35.0)


def glider_temperature():
    """Guided derivation 6: how hot does a glider get?"""
    import _entry33 as XX
    from flight import entry as EN
    from flight.constants import MU as MU_, R_EARTH as RE_
    u, g, r, B, E_, Rn, k = sp.symbols("u g r B E R_n k", positive=True)
    rho = 2 * B * (1 - u) / (r * E_ * u)
    q = k * sp.sqrt(rho / Rn) * (u * g * r)**sp.Rational(3, 2)
    sym_zero("P6a flux on the glide", sp.simplify(q - k * (g * r)**sp.Rational(3, 2) * sp.sqrt(2 * B / (r * E_ * Rn)) * u * sp.sqrt(1 - u)))
    f = u * sp.sqrt(1 - u)
    sym_zero("P6a peak at 2/3", sp.diff(f, u).subs(u, sp.Rational(2, 3)))
    sym_zero("P6a value", f.subs(u, sp.Rational(2, 3)) - 2 / (3 * sp.sqrt(3)))
    check("P6a 0.385", 2 / (3 * np.sqrt(3)), 0.385, tol=5e-4)
    kk, R_n, Bn, sig, em = EN.SUTTON_GRAVES_K, 1.5, 300.0, 5.670e-8, 0.85
    check("P6 k", kk, 1.7415e-4, tol=5e-9)
    rr = RE_ + 70e3
    check("P6 r (km)", rr / 1e3, 6448, tol=0.5)
    gg = MU_ / rr**2
    check("P6 g", gg, 9.587, tol=5e-4)
    check("P6a (gr)^1.5", (gg * rr)**1.5, "4.860e11")
    check("P6 glider nose radius", XX.glider(1.0).nose_radius, R_n, tol=0)
    check("P6 glider B", XX.B_of(XX.glider(1.0)), Bn, tol=1e-6)
    for E, qf, qs, T in ((0.5, 0.363, 0.359, 1656), (1.0, 0.257, 0.256, 1519), (2.0, 0.181, 0.181, 1393)):
        qn = 2 / (3 * np.sqrt(3)) * kk * (gg * rr)**1.5 * np.sqrt(2 * Bn / (rr * E * R_n))
        check(f"P6a formula E={E}", qn / 1e6, qf, tol=5e-4)
        tr = XX.glide(E)
        check(f"P6a simulator E={E}", tr.heat_flux.max() / 1e6, qs, tol=5e-4)
        truth(f"P6a within 1.1 % E={E}", abs(qn / tr.heat_flux.max() - 1) < 0.011)
        check(f"P6b T_w E={E}", (qn / (em * sig))**0.25, T, tol=0.5)
    check("P6b shown chain", (256600 / (0.85 * 5.670e-8))**0.25, 1519, tol=0.5)
    check("P6c 2^-1/8", 2**-0.125, 0.917, tol=5e-4)
    check("P6c 8 %", 100 * (1 - 2**-0.125), 8, tol=0.5)
    check("P6c 2^8", 2**8, 256, tol=0)
    check("P6c 2^3/8", 2**0.375, 1.30, tol=0.005)
    Tc = (1.11e6 / (0.85 * 5.670e-8))**0.25
    check("P6d capsule", Tc, 2191, tol=0.5)
    check("P6d capsule flux in the note (MW/m^2)", XX.peaks(XX.lifting(0.0))["q"] / 1e6, 1.11, tol=0.005)
    truth("P6d several hundred K cooler", 500 < Tc - 1656 and Tc - 1393 < 900)


def glide_heat_load():
    """Guided derivation 7: the heat load of a glide."""
    import _entry33 as XX
    from flight import entry as EN
    from flight.constants import MU as MU_, R_EARTH as RE_
    from scipy.integrate import trapezoid
    u, ui, E_, g, r = sp.symbols("u u_i E g r", positive=True)
    t = sp.sqrt(r / g) * E_ / 2 * sp.log((1 + sp.sqrt(ui)) / (1 - sp.sqrt(ui)) * (1 - sp.sqrt(u)) / (1 + sp.sqrt(u)))
    sym_zero("P7 clock", sp.simplify(sp.diff(t, u) + E_ / 2 * sp.sqrt(r / g) / ((1 - u) * sp.sqrt(u))))
    F = sp.asin(sp.sqrt(u)) - sp.sqrt(u * (1 - u))
    wv = sp.symbols("w", positive=True)                       # u = 1/(1+w) keeps 0 < u < 1
    sym_zero("P7b antiderivative", sp.simplify((sp.diff(F, u) - sp.sqrt(u / (1 - u))).subs(u, 1 / (1 + wv))))
    Fn = lambda x: np.arcsin(np.sqrt(x)) - np.sqrt(x * (1 - x))
    check("P7b arcsin", np.arcsin(np.sqrt(0.95)), 1.3453, tol=5e-5)
    check("P7b root", np.sqrt(0.95 * 0.05), 0.2179, tol=5e-5)
    check("P7b F(0.95)", Fn(0.95), 1.127, tol=5e-4)
    check("P7b F(1)", Fn(1.0), np.pi / 2, tol=1e-12)
    kk, Bn, Rn = EN.SUTTON_GRAVES_K, 300.0, 1.5
    rr = RE_ + 70e3; gg = MU_ / rr**2
    C = kk * gg * rr**1.5 / 2 * np.sqrt(2 * Bn / Rn)
    check("P7c constant (MJ/m^2)", C / 1e6, 273.4, tol=0.05)
    for E, qf, qs in ((0.5, 217.9, 223.7), (1.0, 308.2, 312.9), (2.0, 435.8, 440.9)):
        check(f"P7c formula {E}", C * np.sqrt(E) * Fn(0.95) / 1e6, qf, tol=0.05)
        tr = XX.glide(E)
        Qs = trapezoid(tr.heat_flux, tr.t) / 1e6
        check(f"P7c simulator {E}", Qs, qs, tol=0.05)
        truth(f"P7c within 3 % {E}", abs(C * np.sqrt(E) * Fn(0.95) / 1e6 / Qs - 1) < 0.03)
        check(f"P7c simulator starts at u=0.95 {E}", XX.u_of(tr)[0], 0.95, tol=1e-6)
    check("P7d ratio", (np.pi / 2) / Fn(0.95), 1.39, tol=0.005)


if __name__ == "__main__":
    run([objective, drill1, drill2, extension, glide_oscillation, banked_glide, glider_temperature, glide_heat_load])
