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

PAGE = os.path.join(HERE, "..", "15-level-flight-questions.qmd")
HSTRAT = 287.053 * 216.65 / G0


def objective():
    """The 12 objective questions."""
    q = Objective(PAGE, 12)
    check("Q2 parts equal at u = 1", 0.5 * 1**2 - 0.5 / 1**2, 0.0, tol=0)
    u1, u2 = PF.level_speed_ratios(1.25)
    check("Q5 sqrt(tau^2 - 1)", np.sqrt(1.25**2 - 1), 0.75, tol=1e-12)
    q.num(5, u2, "1.414")
    check("Q5 distractor u1", u1, 0.707)
    q.num(6, 100 * PF.U_MIN_POWER, "76.0")
    check("Q6 distractor 3^(1/4)", 100 * 3**0.25, 131.6)
    check("Q6 distractor sqrt 3", 100 / np.sqrt(3), 57.7)
    q.num(7, 50e3 / 16, "3125")
    q.num(8, 70 / np.sqrt(0.5), "99.0")
    q.num(9, PF.drag_ratio(2.0), "2.125")
    q.num(10, PF.power_ratio(2.0) / PF.power_ratio(1.0), "4.25")
    check("H in the stratosphere", HSTRAT, 6341.6)
    q.num(11, (11000 + HSTRAT * np.log(1.5)) / 1e3, "13.6")
    q.num(12, 40 / PF.U_MIN_POWER, "52.6")
    check("Q12 3^(1/4)", 3**0.25, 1.316)
    check("Q12 distractor A", 40 * PF.U_MIN_POWER, 30.4)
    check("Q12 distractor D", 40 * np.sqrt(3), 69.3)


def transport():
    """Drill 1: the jet transport at 11 km."""
    W, S, cd0, k = 270000 * G0, 476.0, 0.017, 0.04
    em = AE.max_lift_to_drag(cd0, k)[1]
    check("P1 E*", em, 19.17)
    ds = W / em
    check("P1 D* (kN)", ds / 1e3, 138.1)
    t, p, r = A.isa(11000.0)
    vs = PF.min_drag_speed(W, r, S, cd0, k)
    check("P1 V*", vs, 216.5)
    tau = 144.8e3 / ds
    check("P1 tau", tau, 1.049)
    check("P1 sqrt(tau^2 - 1)", np.sqrt(tau**2 - 1), 0.315)
    u1, u2 = PF.level_speed_ratios(tau)
    check("P1 u1", u1, 0.856)
    check("P1 u2", u2, 1.168)
    a = A.speed_of_sound(t)
    check("P1 V1", u1 * vs, 185, tol=0.5)
    check("P1 V2", u2 * vs, 253, tol=0.5)
    check("P1 M1", u1 * vs / a, 0.63)
    check("P1 M2", u2 * vs / a, 0.86)
    check("P1 5 % above 1", (tau - 1) * 100, 5, tol=0.5)


def trainer():
    """Drill 2: how long can the trainer stay up?"""
    H = load("fig-15-hansa-power")
    h = 4000.0
    r = A.isa(h)[2]
    check("P2 rho at 4 km", r, 0.8191)
    vs = PF.min_drag_speed(H.W, r, H.S, H.CD0, H.K)
    check("P2 V*", vs, 42.74)
    vmp = H.v_min_power(h)
    check("P2 V min power (m/s)", vmp, 32.5)
    check("P2 V min power (kt)", vmp / KT, 63.1)
    check("P2 stall (kt)", H.v_stall(h) / KT, 61.4)
    pr = H.p_required(vmp, h)
    check("P2 power required (kW)", pr / 1e3, 20.2)
    ps = pr / 0.78
    check("P2 shaft power (kW)", ps / 1e3, 25.9)
    md = 8.5e-8 * ps
    check("P2 fuel flow (kg/s)", md / 1e-3, 2.20)
    check("P2 fuel flow (kg/h)", md * 3600, 7.9)
    check("P2 endurance (h)", 61 / (md * 3600), 7.7)


def ceiling():
    """Extension 3: the ceiling of a jet in the stratosphere."""
    B = load("anim-15-sbj-altitude")
    check("P3 T_t (N)", B.ENGINE.T_t, 6316, tol=0.5)
    check("P3 E*", B.E_STAR, 12.20)
    check("P3 W (N)", B.W, 48930, tol=1)
    rc = 0.36392 * 48930 / (6316 * 12.20)
    check("P3 ceiling density", rc, 0.2310)
    hc = 11000 + HSTRAT * np.log(0.36392 / rc)
    check("P3 ceiling (km)", hc / 1e3, 13.88)
    check("P3 agrees with the note's simulation (km)", B.CEILING / 1e3, 13.88)
    check("P3 ln(11000/9000)", np.log(11000 / 9000), 0.2007)
    check("P3 rise (m)", HSTRAT * np.log(11000 / 9000), 1273, tol=0.5)


def thrust_family():
    """Guided derivation 4: thrust T = T1 u^-lambda."""
    u, lam, c = sp.symbols("u lambda c", positive=True)
    f = (u**2 + u**-2) / 2 * u**lam
    sym_zero("P4a level flight: u^(2+l) + u^(l-2) = 2c", sp.expand(2 * f - (u**(2 + lam) + u**(lam - 2))))
    uc = ((2 - lam) / (2 + lam))**sp.Rational(1, 4)
    sym_zero("P4b f'(u_c) = 0", sp.simplify(sp.diff(f, u).subs(u, uc)))
    for lv, ucw, cw in ((0, 1.0, 1.0), (1, 0.760, 0.877)):
        ucv = ((2 - lv) / (2 + lv))**0.25
        check(f"P4b u_c for lambda={lv}", ucv, ucw)
        check(f"P4b ceiling thrust ratio for lambda={lv}", 0.5 * (ucv**2 + ucv**-2) * ucv**lv, cw)
    check("P4b propeller ceiling ratio = engine power_ratio minimum", 0.5 * (3**-0.5 + 3**0.5) * 3**-0.25, PF.power_ratio(3**-0.25), tol=1e-12)
    check("P4c jet factor", 2**0.5, 1.41)
    check("P4c prop factor", 2**(1 / 3), 1.26)
    cv = 20.0
    r = brentq(lambda x: x**3 + x**-1 - 2 * cv, 1.0, 10.0)
    check("P4c propeller high root approx (within 1 % for c = 20)", (2 * cv)**(1 / 3), r, rel=0.01)


def speed_stability():
    """Guided derivation 5: the time constant of the speed."""
    Vs, E, tau = 146.3, 12.2, 1.66
    u1, u2 = PF.level_speed_ratios(tau)
    check("P5c u1", u1, 0.579)
    check("P5c u2", u2, 1.728)
    sc = Vs * E / G0
    check("P5c V*E*/g (s)", sc, 182.0)
    br = lambda x: x - x**-3
    check("P5c bracket at u2", br(u2), 1.534)
    check("P5c bracket at u1", br(u1), -4.58)
    check("P5c t_c at u2 (s)", sc / br(u2), 119)
    check("P5c divergence time at u1 (s)", abs(sc / br(u1)), 40)
    u, Ds, T = sp.symbols("u D_s T", positive=True)
    Teq = Ds / 2 * (u**2 + u**-2)
    dnet = -Teq / u - Ds * (u - u**-3)
    sym_zero("P5d constant power: d(T-D)/du = -(D*/2u)(3u^2 - u^-2)", sp.simplify(dnet + Ds / (2 * u) * (3 * u**2 - u**-2)))


def two_points():
    """Guided derivation 6: the polar from two level-flight points."""
    rho, W, S = 0.3795, 48930.0, 21.55
    check("P6c rho at 35000 ft", A.isa(10.67e3)[2], rho)
    D1 = sum(PF.level_flight_drag(W, A.isa(10.67e3)[2], 180.0, S, 0.023, 0.073))
    D2 = sum(PF.level_flight_drag(W, A.isa(10.67e3)[2], 240.0, S, 0.023, 0.073))
    check("P6c D at 180 m/s", D1, 4366)
    check("P6c D at 240 m/s", D2, 6159)
    D1, D2 = 4366.0, 6159.0
    x1, x2 = 180.0**4, 240.0**4
    y1, y2 = D1 * 180**2, D2 * 240**2
    check("P6c D V^2 at 180", y1, "1.4146e8")
    check("P6c D V^2 at 240", y2, "3.5476e8")
    check("P6c V^4 at 180", x1, "1.0498e9")
    check("P6c V^4 at 240", x2, "3.3178e9")
    a = (y2 - y1) / (x2 - x1)
    b = y1 - a * x1
    check("P6c a", a, 0.09405)
    check("P6c b", b, "4.273e7")
    check("P6c V*", (b / a)**0.25, 146.0)
    check("P6c D*", 2 * np.sqrt(a * b), 4010, tol=1)
    check("P6c E*", W / (2 * np.sqrt(a * b)), 12.20)
    check("P6c C_D0", a / (0.5 * rho * S), 0.0230)
    check("P6c K", b * 0.5 * rho * S / W**2, 0.0730)


def approach():
    """Guided derivation 7: attitude for speed, power for the path."""
    u, E = sp.symbols("u E", positive=True)
    tw = sp.symbols("tw")
    g = tw - (u**2 + u**-2) / (2 * E)
    sym_zero("P7a dgamma/du", sp.diff(g, u) + (u - u**-3) / E)
    sym_zero("P7d dgamma/d(T/W) = 1", sp.diff(g, tw) - 1)
    r = np.sqrt(0.56 / 2.0)
    check("P7c V_s/V*", r, 0.529)
    uv = 1.3 * r
    check("P7c u", uv, 0.688)
    check("P7c bracket", uv - uv**-3, -2.38)
    check("P7c dgamma/du", -(uv - uv**-3) / 12.2, 0.195)
    check("P7d 0.01 rad in deg", np.degrees(0.01), 0.6, tol=0.03)



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
    E = 1 / (2 * np.sqrt(0.02 * 0.06))
    check("E15 E_max", E, 14.43, tol=0.005)
    check("E15 drag", 3000 * g / E, 2038, tol=0.5)
    cl = np.sqrt(0.02 / 0.06)
    check("E15 C_L", cl, 0.577, tol=5e-4)
    check("E15 area", 3000 * g / (0.5 * 1.225 * (300 / 3.6)**2 * cl), 12.0, tol=0.05)
    W = 11000 * g
    check("E15 W/S", W / 56, 1926, tol=0.5)
    q = max(np.roots([0.018, -27e3 / 56, 0.05 * (W / 56)**2]))
    check("E15 q", q, 26395, tol=1)
    for h, rho, vs, vm, M in ((0.0, 1.225, 43.0, 207.6, 0.61), (7000.0, 0.5895, 62.0, 299.3, 0.96)):
        r = At.isa(h)[2]
        check(f"E15 rho {h}", r, rho, tol=5e-4)
        check(f"E15 stall {h}", np.sqrt(2 * W / 56 / (r * 1.7)), vs, tol=0.05)
        check(f"E15 vmax {h}", np.sqrt(2 * q / r), vm, tol=0.06)
        check(f"E15 Mach {h}", np.sqrt(2 * q / r) / At.speed_of_sound(At.isa(h)[0]), M, tol=0.005)

if __name__ == "__main__":
    run([objective, transport, trainer, ceiling, thrust_family, speed_stability, two_points, approach, earlier_papers])
