"""Checks every number in the answers and solutions of 18-supersonic-level-flight-questions.qmd,
including the guided derivations 4-7.
Run from anywhere:  python3 codes/18-supersonic-level-flight-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 scipy.optimize import minimize_scalar
import sympy as sp
from _verify import check, truth, sym_zero, Objective, run
from _scripts import load
import _fighter as F
from flight import performance as PF, atmosphere as A, aero as AE
from flight.constants import G0, FT

PAGE = os.path.join(HERE, "..", "18-supersonic-level-flight-questions.qmd")
V, MREF = F.TEJ, F.M_REF
AER = V.aero


def data():
    """The data box."""
    for h, pq in ((9000.0, 30742), (11000.0, 22632), (13000.0, 16510), (40000 * FT, 18754)):
        check(f"ISA p at {h:.0f} m", A.isa(h)[1], pq, tol=0.5)
    check("40,000 ft (km)", 40000 * FT / 1e3, 12.19)


def objective():
    """The 12 objective questions."""
    q = Objective(PAGE, 12)
    w4 = PF.dimensionless_force(10000 * G0, 22632, 40)
    q.num(4, w4, "0.155")
    check("Q4 A: W/(pS)", 10000 * G0 / (22632 * 40), 0.108)
    check("Q4 B: 2W/(pS)", 2 * 10000 * G0 / (22632 * 40), 0.217)
    check("Q4 C: W/(gamma p S)", 10000 * G0 / (1.4 * 22632 * 40), 0.0774)
    q.num(5, 0.2 / 4, "0.05")
    ws = PF.min_drag_wing_loading(1.2, 0.036, 0.22)
    q.num(6, ws, "0.583")
    check("Q6 sqrt 5 figures", np.sqrt(0.036 / 0.22), 0.40452)
    check("Q6 sqrt ratio", np.sqrt(0.036 / 0.22), 0.4045)
    check("Q6 A", 2 * np.sqrt(0.036 * 0.22), 0.178)
    check("Q6 C", np.sqrt(0.036 / 0.22), 0.405)
    check("Q6 D", 1.2 * np.sqrt(0.036 / 0.22), 0.485)
    t7 = PF.thrust_required_mach(1.5, 0.137, 0.0342, 0.295)
    q.num(7, t7, "0.0794")
    check("Q7 zero-lift part", 2.25 * 0.0342, 0.07695, tol=1e-6)
    check("Q7 induced part", 0.295 * 0.137**2 / 2.25, 0.00246)
    check("Q7 omega^2", 0.137**2, 0.01877)
    check("Q7 induced share (%)", 0.295 * 0.137**2 / 2.25 / t7 * 100, 3, tol=0.5)
    check("Q7 A", 2.25 * 0.0342, 0.0770)
    check("Q7 B", 0.0342 + 0.295 * 0.137**2, 0.0397)
    check("Q7 D", 2.25 * 0.0342 + 0.295 * 0.137**2 * 2.25, 0.0894)
    check("Q7 model value agrees", F.tau_r(V, 1.5, MREF, 11000.0), 0.0795, tol=0.0002)
    SB = load("fig-18-sound-barrier")
    truth("Q8 roots as stated", np.allclose(SB.ROOTS["72 % afterburner"], [0.41, 1.15, 1.38, 1.48], atol=0.005))
    truth("Q8 answer (A) is 1.15 and 1.48", "1.15" in q.right(8) and "1.48" in q.right(8))
    m9 = 8500 * A.isa(13000.0)[1] / A.isa(11000.0)[1]
    q.num(9, m9, "6201")
    check("Q9 A", 8500 * 22632 / 16510, 11650, tol=5)
    check("Q9 C", 8500 * 11 / 13, 7190, tol=5)
    lo, hi = PF.level_mach_squared(0.06, 0.15, 0.03, 0.3)
    q.num(10, np.sqrt(hi), "1.37")
    check("Q10 M^2", hi, 1.880)
    check("Q10 sqrt", np.sqrt(0.0036 - 4 * 0.03 * 0.3 * 0.0225), 0.0528)
    check("Q10 A", hi, 1.88)
    check("Q10 C", np.sqrt(lo), 0.35)
    check("Q10 D", np.sqrt(0.06 / 0.03), 1.41)
    TT = load("anim-18-throttle")
    up72 = TT.PATH[list(np.round(TT.LEVELS[:len(TT.UP)], 3)).index(0.72)]
    dn72 = TT.PATH[len(TT.UP) + list(np.round(TT.LEVELS[len(TT.UP):], 3)).index(0.72)]
    q.num(12, dn72, "1.48")
    check("Q12 A: on the way up", up72, 1.15)
    check("Q12 jump", TT.JUMP_UP[0][0] * 100, 73)


def drill_9km():
    """Drill 1: the Tejas-class model at 9 km."""
    h = 9000.0
    w = F.omega(V, MREF, h)
    check("P1 omega", w, 0.1009)
    check("P1 omega by hand", 2 * 8500 * 9.80665 / (1.4 * 30742 * 38.4), 0.1009)
    for M, cq, kq, mil, ab in ((1.0, 0.0265, 0.195, 0.0352, 0.0587), (1.5, "0.0342", 0.295, 0.0495, 0.0850)):
        check(f"P1 C_D0({M})", AER.cd0(M), cq)
        check(f"P1 K({M})", AER.k(M), kq)
        check(f"P1 tau mil({M})", F.tau_a(V, M, h, False), mil)
        check(f"P1 tau ab({M})", F.tau_a(V, M, h, True), ab)
    t1 = 0.0265 + 0.195 * 0.1009**2
    t15 = 2.25 * 0.0342 + 0.295 * 0.1009**2 / 2.25
    check("P1 induced at 1.0", 0.195 * 0.1009**2, 0.0020)
    check("P1 tau_r 1.0", t1, 0.0285)
    check("P1 zero-lift at 1.5", 2.25 * 0.0342, 0.0770)
    check("P1 induced at 1.5", 0.295 * 0.1009**2 / 2.25, 0.0013)
    check("P1 tau_r 1.5", t15, 0.0783)
    check("P1 tau_r 1.0, model", F.tau_r(V, 1.0, MREF, h), 0.0285)
    check("P1 tau_r 1.5, model", F.tau_r(V, 1.5, MREF, h), 0.0784, tol=0.00011)
    qS = 0.7 * 30742 * 38.4
    check("P1 gamma/2 p S (N)", qS, 826300, tol=60)
    check("P1 drag 1.0 (kN)", 0.0285 * qS / 1e3, 23.5, tol=0.06)
    check("P1 drag 1.5 (kN)", 0.0783 * qS / 1e3, 64.7)
    check("P1 military top Mach", max(F.level_machs(V, MREF, h, False)), 1.07)
    check("P1 afterburner top Mach", max(F.level_machs(V, MREF, h, True)), 1.55)
    check("P1 drag ratio", 64.7 / 23.5, 2.75, tol=0.01)
    check("P1 military thrust growth (%)", (0.0495 / 0.0352 - 1) * 100, 40, tol=1)


def drill_f16():
    """Drill 2: Sadraey's F-16 wave drag."""
    S, b, L, Vol = 27.8, 9.45, 15.3, 21.3
    p = A.isa(40000 * FT)[1]
    out = {}
    for M, bq, kq, cq, qq, dq in ((2.1, 1.847, 0.662, 0.00803, 57890, 12.9), (1.2, 0.663, 0.841, "0.0102", 18900, 5.4)):
        beta = np.sqrt(M**2 - 1)
        check(f"P2 beta {M}", beta, bq)
        check(f"P2 K_wv {M}", AE.sadraey_volume_factor(M, L, b), kq)
        cdw = AE.sadraey_wave_drag_volume(M, Vol, S, L, b)
        check(f"P2 C_Dwv {M}", cdw, cq)
        qd = 0.7 * p * M**2
        check(f"P2 q {M} (Pa)", qd, qq, tol=5 if M > 2 else 50)
        check(f"P2 wave drag {M} (kN)", qd * S * cdw / 1e3, dq)
        out[M] = (cdw, qd * S * cdw)
    check("P2 beta b/L at 2.1", 1.847 * b / L, 1.141)
    check("P2 numerator 1 + 0.75 x 1.141", 1 + 0.75 * 1.141, 1.856)
    check("P2 denominator 1 + 2 x 1.141", 1 + 2 * 1.141, 3.282, tol=0.0011)
    check("P2 coefficient 27 % larger at 1.2", (out[1.2][0] / out[2.1][0] - 1) * 100, 27)
    check("P2 force 2.4 times at 2.1", out[2.1][1] / out[1.2][1], 2.4)
    check("P2 q ratio", (2.1 / 1.2)**2, 3.06)
    check("P2 60 % of 0.017", out[1.2][0] / 0.017 * 100, 60)


def extension():
    """Extension 3: least D/W at a fixed omega (Miele ch. 11, eq. 15)."""
    import sympy as sp
    M, w = sp.symbols("M omega", positive=True)
    cd0, k = sp.Function("C")(M), sp.Function("K")(M)
    Z, I = cd0 * M**2 / w, k * w / M**2
    cdm = sp.diff(cd0, M) * M / cd0
    km = sp.diff(k, M) * M / k
    from _verify import sym_zero
    sym_zero("P3 dZ/dM = (Z/M)(C_D0,M + 2)", sp.diff(Z, M) - Z / M * (cdm + 2))
    sym_zero("P3 dI/dM = (I/M)(K_M - 2)", sp.diff(I, M) - I / M * (km - 2))
    res = {}
    for wv in (0.137, 0.4):
        f = lambda x: PF.drag_per_weight_mach(x, wv, AER.cd0(x), AER.k(x))
        Mx = minimize_scalar(f, bounds=(0.4, 1.2), method="bounded", options=dict(xatol=1e-10)).x
        e = 1e-5
        dl = lambda g: (np.log(g(Mx + e)) - np.log(g(Mx - e))) / (np.log(Mx + e) - np.log(Mx - e))
        R = AER.k(Mx) * wv**2 / Mx**4 / AER.cd0(Mx)
        check(f"P3 R equals Miele's formula at omega {wv}", R, (2 + dl(AER.cd0)) / (2 - dl(AER.k)), rel=1e-5)
        res[wv] = (Mx, R, f(Mx), 1 / AE.max_lift_to_drag(AER.cd0(Mx), AER.k(Mx))[1], dl(AER.cd0), dl(AER.k))
    check("P3 omega 0.137 at 11 km", F.omega(V, MREF, 11000.0), 0.137)
    Mx, R, dw, emin, _, _ = res[0.137]
    check("P3 (b) Mach", Mx, 0.682)
    check("P3 (b) R", R, 1.0, tol=1e-6)
    check("P3 (b) D/W", dw, 0.1153)
    check("P3 (b) = 1/Emax", dw, emin, rel=1e-6)
    Mx, R, dw, emin, cdm4, km4 = res[0.4]
    check("P3 (c) Mach", Mx, 0.912)
    check("P3 (c) C_D0,M", cdm4, 2.92)
    check("P3 (c) K_M", km4, 0.0, tol=1e-6)
    check("P3 (c) R", R, 2.46)
    check("P3 (c) R by hand", (2 + 2.92) / 2, 2.46)
    check("P3 (c) D/W", dw, 0.132)
    check("P3 (c) 1/Emax", emin, 0.120)
    check("P3 (c) 10 % above", (dw / emin - 1) * 100, 10, tol=0.5)
    check("P3 drag rise starts at M_c", AE.critical_from_divergence(AER.mdd), 0.82, tol=0.0025)


def sears_haack():
    """Guided derivation 4: the Sears-Haack body."""
    x, R, L, V = sp.symbols("xi R L V", positive=True)
    I = sp.integrate((4 * x * (1 - x))**sp.Rational(3, 2), (x, 0, 1))
    sym_zero("P4a integral = 3 pi/16", I - 3 * sp.pi / 16)
    vol = sp.pi * R**2 * L * I
    Dq = 9 * sp.pi**3 * R**4 / (2 * L**2)
    Rs = sp.sqrt(16 * V / (3 * sp.pi**2 * L))
    sym_zero("P4b D/q = 128 V^2/(pi L^4)", Dq.subs(R, Rs) - 128 * V**2 / (sp.pi * L**4))
    sym_zero("P4a volume", vol - sp.Rational(3, 16) * sp.pi**2 * R**2 * L)
    for f, w in ((5, 0.444), (10, 0.111), (15, 0.0493)):
        check(f"P4c C_D at fineness {f}", 9 * np.pi**2 / (8 * f**2), w)
    Vv, Lv, S = 25.7, 13.2, 38.4
    Rv = np.sqrt(16 * Vv / (3 * np.pi**2 * Lv))
    check("P4d R_max", Rv, 1.026)
    dq = 9 * np.pi**3 * Rv**4 / (2 * Lv**2)
    check("P4d D/q", dq, 0.886)
    check("P4d on the wing area", dq / S, 0.0231)
    kwv = AE.sadraey_volume_factor(1.2, Lv, 8.2)
    check("P4d K_wv at 1.2", kwv, 0.84)
    check("P4d K_wv times", kwv * dq / S, 0.0194)
    check("P4d engine formula agrees", AE.sadraey_wave_drag_volume(1.2, Vv, S, Lv, 8.2), kwv * dq / S, rel=1e-12)
    check("P4d model C_D0 at 1.2", F.TEJ.aero.cd0(1.2), 0.036, tol=0.0006)
    check("P4d stretch factor", 1.1**4, 1.46)


def weight_height():
    """Guided derivation 5: in the stratosphere, weight is height."""
    from flight.propulsion import mattingly_lapse
    th = 216.65 / 288.15
    for M in (0.9, 1.5):
        r = [mattingly_lapse("turbofan_low", M, th, A.isa(h)[1] / 101325.0) / (A.isa(h)[1] / 101325.0) for h in (12e3, 15e3, 19e3)]
        check(f"P5a F/delta constant above 11 km at M={M}", max(r) - min(r), 0, tol=1e-12)
    H = A.scale_height(216.65)
    check("P5 H (km)", H / 1e3, 6.34)
    check("P5c 8500 -> 7000 kg (m)", H * np.log(8500 / 7000), 1231)
    check("P5c half weight (m)", H * np.log(2), 4396, tol=1)


def barrier_exponent():
    """Guided derivation 6: the sound barrier as an exponent."""
    for n, w in ((0, 5), (3, 2), (-0.5, 6.7)):
        check(f"P6b response for n={n} (%)", 10 / (2 + n), w)
    M, n, m, c = sp.symbols("M n m c", positive=True)
    sym_zero("P6c d ln c/d ln M = 2 + n - m", sp.diff(sp.log(M**(2 + n) / M**m), M) * M - (2 + n - m))


def hot_records():
    """Guided derivation 7: hot days and speed records."""
    a1 = A.speed_of_sound(288.15)
    a2 = A.speed_of_sound(313.15)
    check("P7c a at 15 C", a1, 340.29)
    check("P7c a at 40 C", a2, 354.75)
    check("P7c V standard", 0.95 * a1, 323.3)
    check("P7c V hot", 0.95 * a2, 337.0)
    check("P7c gain (%)", (a2 / a1 - 1) * 100, 4.2)
    check("P7c gain (km/h)", 0.95 * (a2 - a1) * 3.6, 50, tol=1)



def earlier_papers():
    """Problems moved from the 2016-2019 papers."""
    import numpy as np
    import sympy as sp
    from flight import atmosphere as At, performance as Pf, aero as Ae
    from flight.constants import FT, KT
    g = 9.80665
    M, cd0, k, om = 1.4, 0.03, 0.2, 0.3
    check("E18 tau form = engine", Pf.thrust_required_mach(M, om, cd0, k), M**2 * cd0 + k * om**2 / M**2, tol=1e-12)
    V = 2 * np.pi * (6357e3 + 11e3) / 86400
    T, p, rho = At.isa(At.geopotential(11000.0) if hasattr(At, "geopotential") else 6356766 * 11000 / (6356766 + 11000))
    sg = rho / At.isa(0.0)[2]
    check("E18 V", V, 463.1, tol=0.05); check("E18 sigma", sg, 0.2978, tol=5e-5); check("E18 EAS", V * np.sqrt(sg), 252.7, tol=0.05)
    def tw(v):
        cl = 1800 / (0.5 * rho * v * v)
        return cl, 0.023 / cl + 0.073 * cl
    c1, t1 = tw(V); c2, t2 = tw(V - 100)
    a = At.speed_of_sound(T)
    check("E18 CL", c1, 0.0460, tol=5e-5); check("E18 T/W", t1, 0.503, tol=5e-4)
    check("E18 jet TAS", V - 100, 363.1, tol=0.05); check("E18 jet EAS", (V - 100) * np.sqrt(sg), 198.1, tol=0.06)
    check("E18 jet CL", c2, 0.0749, tol=5e-5); check("E18 jet T/W", t2, 0.313, tol=5e-4)
    check("E18 a", a, 295.2, tol=0.05); check("E18 M", V / a, 1.57, tol=0.005); check("E18 M jet", (V - 100) / a, 1.23, tol=0.005)
    check("E18 saving %", 100 * (1 - t2 / t1), 38, tol=0.5)
    check("E18 curvature share eastward %", 100 * (2 * V)**2 / (9.77 * 6368e3), 1.4, tol=0.05)

if __name__ == "__main__":
    run([data, objective, drill_9km, drill_f16, extension, sears_haack, weight_height, barrier_exponent, hot_records, earlier_papers])
