"""Checks every number in the answers and solutions of 22-energy-climb-questions.qmd,
including the guided derivations 4-7.
Run from anywhere:  python3 codes/22-energy-climb-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 _scripts import load
import _energy as E
from flight import performance as PF, airspeed as AS, atmosphere as A
from flight.constants import G0, KT, FT

PAGE = os.path.join(HERE, "..", "22-energy-climb-questions.qmd")


def data():
    check("gamma R lambda / 2g", 1.4 * 287.053 * (-0.0065) / (2 * G0), -0.1332, tol=5e-5)
    check("a at 35,000 ft", A.speed_of_sound(A.isa(35000 * FT)[0]), 296.5)


def objective():
    q = Objective(PAGE, 12)
    q.num(4, PF.energy_height(10000.0, 300.0) / 1e3, "14.6")
    check("Q4 KE", 300**2 / (2 * G0), 4589, tol=0.5)
    check("Q4 B", (10000 + 300**2 / G0) / 1e3, 19.2)
    q.num(5, 5000 / 100, "50")
    q.num(6, PF.energy_share_constant_mach(0.8), "1.09")
    check("Q6 A: the bracket not inverted", 1 - 0.1332 * 0.64, 0.91)
    q.num(7, 50 / 1.25, "40")
    check("Q7 A", 50 * 1.25, 62.5)
    check("Q7 D", 50 * 0.75, 37.5)
    he = PF.energy_height(10000.0, 400.0)
    q.num(8, (he - 150**2 / (2 * G0)) / 1e3, "17.0")
    check("Q8 h_E (m)", he, 18158, tol=0.5)
    check("Q8 KE at top", 150**2 / (2 * G0), 1147, tol=0.5)
    check("Q8 A", he / 1e3, 18.2)
    a = A.speed_of_sound(A.isa(35000 * FT)[0])
    q.num(10, (0.9 * a)**2 / (2 * G0) / (35000 * FT), "0.34")
    check("Q10 KE (m)", (0.9 * a)**2 / (2 * G0), 3632, tol=1)
    check("Q10 PE (m)", 35000 * FT, 10668, tol=0.5)
    q.num(11, 1000 / 100 * 2, "20")


def airliner():
    for h, fq, rq, mq in ((3000.0, 0.882, 13.2, 0.504), (9000.0, 0.792, 11.9, 0.735)):
        f = PF.energy_share_factor(lambda hh: AS.mach_at_cas(280 * KT, hh) * E.a_of(hh), h)
        check(f"P1 factor at {h:.0f}", f, fq)
        check(f"P1 ROC at {h:.0f}", 15 * fq, rq)
        check(f"P1 Mach at {h:.0f}", AS.mach_at_cas(280 * KT, h), mq)


def by_hand():
    P = load("fig-22-ps-map")
    r = P.PATHS["minimum time"][0]
    hes = np.linspace(E.HE0, E.HE_F, 6)
    ps = np.interp(hes, r[0], r[3])
    for got, qv in zip(hes / 1e3, (1.48, 5.38, 9.28, 13.18, 17.09, 20.99)):
        check(f"P2 h_E {qv}", got, qv)
    for got, qv in zip(ps, (176.9, 247.4, 203.6, 111.1, 98.7, 90.0)):
        check(f"P2 P_s {qv}", got, qv)
    step = np.diff(hes)[0]
    check("P2 step (km)", step / 1e3, 3.90)
    tq = np.trapz(1 / np.array([176.9, 247.4, 203.6, 111.1, 98.7, 90.0]), dx=3900)
    check("P2 trapezoid (s)", tq, 142)
    check("P2 within 3 %", (tq / r[4][-1] - 1) * 100, 3, tol=0.5)


def constant_q():
    h, H, g, R, T, M, gam = sp.symbols("h H g R T M gamma", positive=True)
    V = sp.exp(h / (2 * H))
    expr = sp.simplify(V / g * sp.diff(V, h))
    sym_zero("P3 (V/g) dV/dh = V^2/(2 g H)", expr - V**2 / (2 * g * H))
    sym_zero("P3 = gamma M^2 / 2 with H = RT/g, V^2 = gamma R T M^2", (gam * R * T * M**2) / (2 * g * (R * T / g)) - gam * M**2 / 2)
    for M_, q in ((0.5, 0.851), (2.0, 0.263)):
        check(f"P3 factor at M {M_}", 1 / (1 + 0.7 * M_**2), q)
    # numerical cross-check with the engine at 14 km
    q0 = 0.5 * A.isa(14000.0)[2] * (2.0 * E.a_of(14000.0))**2
    check("P3 engine numerical factor at M 2, 14 km", PF.energy_share_factor(lambda hh: np.sqrt(2 * q0 / A.isa(hh)[2]), 14000.0), 0.263, tol=0.002)


def share_eas():
    """Guided derivation 4: the energy-share factor at constant EAS."""
    M, g, R, lam, T, gm = sp.symbols("M g R lambda T gamma", real=True)
    V2 = M**2 * gm * R * T
    sym_zero("P4a V^2/(2gH_rho) = (gamma M^2/2)(1 + R lambda/g)", V2 * (g + R * lam) / (2 * g * R * T) - gm * M**2 / 2 * (1 + R * lam / g))
    r = 287.053 * -0.0065 / G0
    check("P4b R lambda/g", r, -0.190)
    check("P4b coefficient", 0.7 * (1 + r), 0.567)
    check("P4c M^2", 0.606**2, 0.367)
    f = 1 / (1 + 0.7 * (1 + r) * 0.606**2)
    check("P4c factor", f, 0.828)
    # check against a numerical constant-EAS climb: V = Ve/sqrt(sigma) at 6 km
    h, dh = 6000.0, 1.0
    T6 = A.isa(h)[0]
    V = 0.606 * A.speed_of_sound(T6)
    sig = lambda z: A.isa(z)[2] / A.isa(0.0)[2]
    Ve = V * np.sqrt(sig(h))
    dV = (Ve / np.sqrt(sig(h + dh)) - Ve / np.sqrt(sig(h - dh))) / (2 * dh)
    check("P4c numerical constant-EAS factor at 6 km", 1 / (1 + V / G0 * dV), f, tol=0.002)
    check("P4d constant-Mach coefficient", 1.4 * 287.053 * 0.0065 / (2 * G0), 0.133)


def zoom_drag():
    """Guided derivation 5: the vertical zoom with drag."""
    h, k, g, V0 = sp.symbols("h k g V_0", positive=True)
    V2 = (V0**2 + 2 * g / k) * sp.exp(-k * h) - 2 * g / k
    sym_zero("P5a solves d(V^2)/dh = -2g - k V^2", sp.diff(V2, h) + 2 * g + k * V2)
    sym_zero("P5b V^2(0) = V0^2", V2.subs(h, 0) - V0**2)
    hm = sp.log(1 + k * V0**2 / (2 * g)) / k
    sym_zero("P5b V^2(h_max) = 0", sp.simplify(V2.subs(h, hm)))
    sym_zero("P5b small-k expansion", sp.series(hm, k, 0, 2).removeO() - V0**2 / (2 * g) * (1 - k * V0**2 / (4 * g)))
    rho = A.isa(11e3)[2]
    check("P5c rho", rho, 0.3639)
    V = 1.2 * A.speed_of_sound(216.65)
    check("P5c V0", V, 354.1)
    check("P5c drag-free (m)", V**2 / (2 * G0), 6392)
    kv = rho * 38.4 * 0.036 / 8500
    check("P5c k", kv, 5.92e-5)
    check("P5c kV0^2/2g", kv * V**2 / (2 * G0), 0.378)
    hz = np.log(1 + kv * V**2 / (2 * G0)) / kv
    check("P5c zoom (m)", hz, 5420, tol=5)
    check("P5c lost (m)", V**2 / (2 * G0) - hz, 970, tol=5)
    check("P5c lost (%)", (1 - hz / (V**2 / (2 * G0))) * 100, 15)
    check("P5d density ratio over 5.4 km", A.isa(16.4e3)[2] / rho, 0.43, tol=0.01)


def afterburner_energy():
    """Guided derivation 6: fuel per unit energy, dry against wet."""
    import _fighter as F
    v, h, m, M = F.TEJ, 11000.0, 8500.0, 0.9
    Td, Tw, D = F.thrust(v, M, h, ab=False), F.thrust(v, M, h, ab=True), F.drag(v, M, m, h)
    cd, cw = F.tsfc(v, M, h, False) * 3600, F.tsfc(v, M, h, True) * 3600
    check("P6c T_d (kN)", Td / 1e3, 19.15)
    check("P6c T_w (kN)", Tw / 1e3, 31.92)
    check("P6c D (kN)", D / 1e3, 11.49)
    check("P6c c_d (1/h)", cd, 1.145)
    check("P6c c_w (1/h)", cw, 2.459)
    Td, Tw, D, cd, cw = 19.15, 31.92, 11.49, 1.145, 2.459
    check("P6c wet term", cw * Tw / (Tw - D), 3.842)
    check("P6c dry term", cd * Td / (Td - D), 2.862)
    check("P6c ratio", (cw * Tw / (Tw - D)) / (cd * Td / (Td - D)), 1.34)
    check("P6c time ratio", (Td - D) / (Tw - D), 0.375)
    check("P6c faster by", (Tw - D) / (Td - D), 2.7, tol=0.05)
    truth("P6b the ratio is below the TSFC ratio", (cw * Tw / (Tw - D)) / (cd * Td / (Td - D)) < cw / cd)


def zoom_qmin():
    """Guided derivation 7: how high can a zoom go if the controls need air?"""
    from scipy.special import lambertw
    from scipy.optimize import brentq
    from flight import atmosphere as AT
    h, he, H, x, q, g, r11, h11 = sp.symbols("h h_e H x q g rho_11 h_11", positive=True)
    eq = h + q / (g * r11) * sp.exp((h - h11) / H) - he
    e2 = sp.expand(eq.subs(h, he - H * x))
    Aexp = q / (g * r11 * H) * sp.exp((he - h11) / H)
    sym_zero("P7b equivalent", sp.simplify(sp.expand(-(e2 / H) * sp.exp(x)) - (x * sp.exp(x) - Aexp)))
    T11, p11, rho11 = AT.isa(11000.0)
    Hn = 287.05287 * T11 / G0
    check("P7 rho11", rho11, 0.3639, tol=5e-5)
    check("P7 H", Hn, 6342, tol=0.5)
    hen = 24070.0
    check("P7d exponent", (hen - 11000) / Hn, 2.061, tol=5e-4)
    check("P7d g rho11 H", G0 * rho11 * Hn, 22630, tol=5)
    tops = {}
    for qm, a_, w_, hm, vt, mt in ((2000., 0.694, 0.445, 21.25, 235, 0.80), (5000., 1.735, 0.789, 19.07, 313, 1.06),
                                   (10000., 3.470, 1.126, 16.93, 374, 1.27)):
        An = qm / (G0 * rho11 * Hn) * np.exp((hen - 11000) / Hn)
        check(f"P7d A {qm}", An, a_, tol=5e-4)
        Wn = lambertw(An).real
        check(f"P7d W {qm}", Wn, w_, tol=5e-4)
        hx = hen - Hn * Wn
        check(f"P7d h_max {qm}", hx / 1e3, hm, tol=0.005)
        rho = rho11 * np.exp(-(hx - 11000) / Hn)
        V = np.sqrt(2 * qm / rho)
        check(f"P7d speed {qm}", V, vt, tol=0.5)
        check(f"P7d Mach {qm}", V / AT.speed_of_sound(T11), mt, tol=0.005)
        tops[qm] = hx
        hi = brentq(lambda z: z + qm / (AT.isa(z)[2] * G0) - hen, 11000, 24000)
        if qm == 2000.:
            check("P7d ISA difference (m)", abs(hi - hx), 10, tol=0.5)
    check("P7d 2 -> 10 kPa (km)", (tops[2000.] - tops[10000.]) / 1e3, 4.3, tol=0.05)
    qnote = lambda hh, M: 0.7 * AT.isa(hh)[1] * M**2
    check("P7d note's Mach 1 top q (kPa)", qnote(19630, 1.0) / 1e3, 4.1, tol=0.05)
    check("P7d note's Mach 0.6 top q (kPa)", qnote(22460, 0.6) / 1e3, 0.9, tol=0.05)
    truth("P7d 5 kPa top a little below 19.63 km", 0 < 19630 - tops[5000.] < 1000)
    truth("P7d 2 kPa top between the note's", 19630 < tops[2000.] < 22460)
    check("P7c e", np.e, 2.72, tol=0.005)



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
    gm = np.arctan(-1000 * FT / (10 * 1609.344)); ds = np.hypot(1000 * FT, 10 * 1609.344); acc = (185**2 - 195**2) / (2 * ds)
    rho = At.isa(12000 * FT)[2]; q = 0.5 * rho * 195**2; AR = 60.9**2 / 427.8; k = 1 / (np.pi * 0.87 * AR)
    cl = 200000 * g * np.cos(gm) / (q * 427.8); cd = 0.02 + k * cl**2; D = q * 427.8 * cd; Th = D + 200000 * (acc + g * np.sin(gm))
    check("E22 gamma", np.degrees(gm), -1.085, tol=5e-4); check("E22 ds", ds, 16096, tol=0.5); check("E22 accel", acc, -0.1180, tol=5e-5)
    check("E22 rho", rho, 0.8491, tol=5e-5); check("E22 q", q, 16144, tol=0.5); check("E22 CL", cl, 0.2839, tol=5e-5)
    check("E22 AR", AR, 8.67, tol=0.005); check("E22 K", k, 0.0422, tol=5e-5); check("E22 CD", cd, 0.02340, tol=5e-6)
    check("E22 drag kN", D / 1e3, 161.6, tol=0.05); check("E22 gravity and slowing kN", 200000 * (acc + g * np.sin(gm)) / 1e3, -60.7, tol=0.05)
    check("E22 thrust kN", Th / 1e3, 100.9, tol=0.05); check("E22 share SL %", 100 * Th / 684e3, 14.7, tol=0.05)
    check("E22 share lapsed %", 100 * Th / (684e3 * rho / At.isa(0.0)[2]), 21, tol=0.5)
    check("E22 height lost (m)", 1000 * FT, 304.8, tol=1e-9)
    check("E22 horizontal distance (m)", 10 * 1609.344, 16093, tol=0.5)


if __name__ == "__main__":
    run([data, objective, airliner, by_hand, constant_q, share_eas, zoom_drag, afterburner_energy, zoom_qmin, earlier_papers])
