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

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


def objective():
    q = Objective(PAGE, 12)
    check("Q2 ratio", E.BALLISTIC_PEAK_SPEED_RATIO, 0.61, tol=0.005)
    a = E.ballistic_peak_deceleration(7500, np.radians(-6), 7100)
    check("Q4 a (m/s^2)", a, 152.3, tol=0.05)
    q.num(4, a / G0, "15.5")
    q.num(6, 7.1 * np.log(3), "7.8")
    flux = lambda B, R=1.0: E.ballistic_peak_heat_flux(7500, B, -0.1, 7100, R)
    check("Q7 ratio", flux(800) / flux(200), 2.0, rel=1e-12)
    check("Q11 doubled size: B x2, R x2", flux(400, 2.0) / flux(200, 1.0), 1.0, rel=1e-12)
    tr = X.sre(-2.0)
    check("Q9 angle at the peak (deg)", -np.degrees(tr.gamma[X.peaks(tr)["i"]]), 5.0, tol=0.05)
    q.num(10, np.sin(np.radians(5)) / 6 * 100, "1.5", tol=0.06)
    truth("Q8 signs", E.ballistic_peak_heat_flux(8000, 200, -0.2, 7100, 1) > E.ballistic_peak_heat_flux(8000, 200, -0.1, 7100, 1)
          and E.ballistic_heat_load(8000, 200, -0.2, 7100, 1, 1.0) < E.ballistic_heat_load(8000, 200, -0.1, 7100, 1, 1.0))


def drill1():
    s = np.sin(np.radians(5))
    for dw, want in ((4, 2.23), (6, 1.47), (8, 1.10)):
        check(f"D1 D/W {dw}", s / (dw - s) * 100, want, tol=0.005)


def drill2():
    V, B, g, H, Rn = 7800.0, 400.0, np.radians(-6), 7087.0, 2.0
    a = E.ballistic_peak_deceleration(V, g, H)
    check("D2 a", a, 165.1, tol=0.05)
    check("D2 g", a / G0, 16.8, tol=0.05)
    rs = E.ballistic_peak_density(B, g, H)
    check("D2 rho*", rs, 5.90e-3, tol=5e-6)
    h = E.ballistic_peak_altitude(B, g, H, RHO0_SL)
    check("D2 h (km)", h / 1e3, 37.8, tol=0.05)
    check("D2 rho_q", E.ballistic_heating_density(B, g, H), 1.97e-3, tol=5e-6)
    check("D2 V_q", V * E.BALLISTIC_HEATING_SPEED_RATIO, 6603, tol=0.5)
    check("D2 flux (MW)", E.ballistic_peak_heat_flux(V, B, g, H, Rn) / 1e6, 1.57, tol=0.005)
    check("D2 h_q (km)", E.altitude_of_density(E.ballistic_heating_density(B, g, H), RHO0_SL, H) / 1e3, 45.6, tol=0.05)
    full = E.ballistic_heat_load(V, B, g, H, Rn, 1e3)
    low = E.ballistic_heat_load(V, B, g, H, Rn, RHO0_SL * np.exp(-10e3 / H))
    check("D2 erf within 1e-4 of 1", low / full, 1.0, tol=1e-4)
    check("D2 load (MJ)", low / 1e6, 69.2, tol=0.05)


def extension():
    r, k, n = sp.symbols("rho k n", positive=True)
    A = r * sp.exp(-n * k * r)
    sym_zero("E3a stationary at 1/(n k)", sp.simplify(sp.diff(A, r).subs(r, 1 / (n * k))))
    truth("E3c order 3 > 3/2 > 1", 1 / 3 < 2 / 3 < 1)


def meteors():
    """Guided derivation 4: what reaches the ground fast."""
    H = 7087.0
    for g, w in ((45, 8860), (90, 6260)):
        check(f"P4b B for half speed at {g} deg", RHO0_SL * H / (2 * np.sin(np.radians(g)) * np.log(2)), w, tol=5)
    B = RHO0_SL * H / (2 * np.sin(np.radians(45)) * np.log(2))
    check("P4c iron radius (m)", 3 * B / (4 * 7800), 0.85)
    check("P4c stone radius (m)", 3 * B / (4 * 3300), 2.0)
    r, rm = sp.symbols("r rho_m", positive=True)
    sym_zero("P4c B = 4/3 r rho_m", (sp.Rational(4, 3) * sp.pi * r**3 * rm) / (sp.pi * r**2) - sp.Rational(4, 3) * r * rm)
    check("P4a engine speed ratio agrees", E.ballistic_speed_ratio(RHO0_SL, B, H, np.radians(-45)), 0.5, tol=1e-9)
    x = RHO0_SL * H / (2 * 177 * np.sin(np.radians(5)))
    check("P4d exponent (log10)", -x / np.log(10), -122, tol=1)


def crew_limit():
    """Guided derivation 5: the steepest crew entry."""
    H = 7087.0
    s = 2 * np.e * H * 10 * G0 / 8000**2
    check("P5b sin limit at 8 km/s", s, 0.0590)
    check("P5b angle (deg)", np.degrees(np.arcsin(s)), 3.38)
    s11 = s * (8 / 11)**2
    check("P5b sin at 11 km/s", s11, 0.0312)
    check("P5b angle at 11 km/s", np.degrees(np.arcsin(s11)), 1.79)
    check("P5b engine peak at that angle (g)", E.ballistic_peak_deceleration(8000.0, -np.arcsin(s), H) / G0, 10.0, tol=1e-6)
    check("P5c q_max SRE-1 (kPa)", 177 * 10 * G0 / 1e3, 17.4)


def end_of_fall():
    """Guided derivation 6: the end of the fall."""
    from scipy.optimize import brentq
    g, B, rho, H, eps, Vt, x, Vi, sg = sp.symbols("g B rho H epsilon V_t x V_i s", positive=True)
    sym_zero("P6a terminal speed", (rho * (2 * g * B / rho) / (2 * B)) - g)
    lhs = sp.series(g * (1 - (1 + eps)**2), eps, 0, 2).removeO()
    sym_zero("P6b left side", lhs + 2 * g * eps)
    e_sol = sp.solve(sp.Eq(-2 * g * eps, -Vt**2 / (2 * H)), eps)[0]
    sym_zero("P6b epsilon", e_sol - Vt**2 / (4 * g * H))
    sym_zero("P6b = B/(2 rho H)", e_sol.subs(Vt, sp.sqrt(2 * g * B / rho)) - B / (2 * rho * H))
    a = x * sg / H * B / (2 * B) * Vi**2 * sp.exp(-x)      # rho V^2/(2B) with rho = x B s/H
    sym_zero("P6d angle and B cancel", sp.simplify(sp.solve(sp.Eq(a, g * sg), sp.exp(-x))[0] - 2 * g * H / (x * Vi**2)))
    v = X.capsule("sre-1"); Bn = X.B_of(v); Hn = X.H
    check("P6 B", Bn, 176.7, tol=0.05)
    check("P6 H", Hn, 7087, tol=0.5)
    check("P6b 4gH", 4 * G0 * Hn, 277990, tol=5)
    trs = {gd: X.fly(v, 8000.0, 100e3, gd, h_stop=500.0) for gd in (-20.0, -5.0)}
    simV = lambda gd, hh: np.interp(hh, trs[gd].h[::-1], trs[gd].V[::-1])
    for hh, r, vt, ep, vc, vs in ((10e3, 0.2988, 107.7, 0.042, 112.2, 112.8), (5e3, 0.6050, 75.7, 0.021, 77.2, 77.3),
                                  (2e3, 0.9238, 61.2, 0.013, 62.1, 62.1)):
        rn = RHO0_SL * np.exp(-hh / Hn)
        check(f"P6a rho {hh}", rn, r, tol=5e-5)
        vtn = np.sqrt(2 * G0 * Bn / rn)
        check(f"P6a V_t {hh}", vtn, vt, tol=0.05)
        en = vtn**2 / (4 * G0 * Hn)
        check(f"P6b eps {hh}", en, ep, tol=5e-4)
        check(f"P6b corrected {hh}", vtn * (1 + en), vc, tol=0.05)
        check(f"P6c simulator 20 deg {hh}", simV(-20.0, hh), vs, tol=0.05)
        check(f"P6c same for 5 deg {hh}", simV(-5.0, hh), simV(-20.0, hh), tol=0.05)
        truth(f"P6c V_t alone 1-5 % low {hh}", 0.01 < 1 - vtn / simV(-20.0, hh) < 0.05)
        if hh == 10e3:
            check("P6c within 0.5 % at 10 km", 100 * (1 - vtn * (1 + en) / simV(-20.0, hh)), 0.5, tol=0.05)
        else:
            truth(f"P6c within 0.1 m/s {hh}", abs(vtn * (1 + en) - simV(-20.0, hh)) < 0.1)
    ee = 2 * G0 * Hn / 8000.0**2
    check("P6d 2gH/V^2", ee, 0.00217, tol=5e-6)
    L = np.log(1 / ee)
    check("P6d L", L, 6.13, tol=0.005)
    xr = brentq(lambda z: z * np.exp(-z) - ee, 2, 40)
    check("P6d root", xr, 8.24, tol=0.005)
    check("P6d speed", np.sqrt(2 * G0 * Hn / xr), 130, tol=0.5)
    check("P6d speed, other form", 8000 * np.exp(-xr / 2), np.sqrt(2 * G0 * Hn / xr), tol=1e-9)
    hd = Hn * np.log(RHO0_SL / (xr * Bn * np.sin(np.radians(20)) / Hn))
    check("P6d height (km)", hd / 1e3, 20.3, tol=0.05)
    tr = trs[-20.0]
    check("P6d simulator speed there", np.interp(hd, tr.h[::-1], tr.V[::-1]), 313, tol=0.5)
    check("P6d simulator angle there", -np.degrees(np.interp(hd, tr.h[::-1], tr.gamma[::-1])), 40, tol=0.5)


def flux_load_product():
    """Guided derivation 7: a product that the angle cannot change."""
    k, V, B, H, R, s = sp.symbols("k V_i B H R_n s", positive=True)
    q = k * sp.sqrt(B * s / H / (3 * R)) * (V * sp.exp(-sp.Rational(1, 6)))**3
    Q = k * V**2 * sp.sqrt(sp.pi * B * H / (R * s))
    sym_zero("P7a peak", sp.simplify(q - k * V**3 * sp.exp(-sp.Rational(1, 2)) * sp.sqrt(B * s / (3 * H * R))))
    sym_zero("P7a product", sp.simplify(q * Q - sp.sqrt(sp.pi / 3) * sp.exp(-sp.Rational(1, 2)) * k**2 * V**5 * B / R))
    sym_zero("P7b tau", sp.simplify(Q / q - sp.sqrt(3 * sp.pi * sp.E) * H / (V * s)))
    check("P7b sqrt(3 pi e)", np.sqrt(3 * np.pi * np.e), 5.06, tol=0.005)
    v = X.capsule("sre-1"); Bn = X.B_of(v); Rn = v.nose_radius; Hn = X.H; kk = E.SUTTON_GRAVES_K
    check("P7c R_n", Rn, 0.5, tol=0)
    prod = np.sqrt(np.pi / 3) * np.exp(-0.5) * kk**2 * 8000.0**5 * Bn / Rn
    check("P7c product", prod, "2.18e14")
    for g, qs, Qs, rq in ((-5., 2.10, 104.4, 1.003), (-8., 2.66, 83.4, 1.017), (-12., 3.25, 68.6, 1.025), (-20., 4.18, 53.8, 1.032), (-40., 5.75, 39.4, 1.039)):
        p = X.peaks(X.sre(g))
        check(f"P7c q {g}", p["q"] / 1e6, qs, tol=0.005)
        check(f"P7c Q {g}", p["Q"] / 1e6, Qs, tol=0.05)
        check(f"P7c ratio {g}", p["q"] * p["Q"] / prod, rq, tol=5e-4)
        tf = np.sqrt(3 * np.pi * np.e) * Hn / (8000.0 * np.sin(np.radians(-g)))
        if g == -5.:
            check("P7c tau formula 5", tf, 51.4, tol=0.05); check("P7c tau sim 5", p["Q"] / p["q"], 49.8, tol=0.05)
        if g == -40.:
            check("P7c tau formula 40", tf, 7.0, tol=0.05); check("P7c tau sim 40", p["Q"] / p["q"], 6.9, tol=0.05)
    check("P7c flux nearly triples", X.peaks(X.sre(-40.))["q"] / X.peaks(X.sre(-5.))["q"], 2.7, tol=0.05)
    check("P7d 10 % slower", 100 * (1 - 0.9**5), 41, tol=0.5)


if __name__ == "__main__":
    run([objective, drill1, drill2, extension, meteors, crew_limit, end_of_fall, flux_load_product])
