"""Checks every number in the answers and solutions of 24-turns-questions.qmd,
including the guided derivations 6-9.
Run from anywhere:  python3 codes/24-turns-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
from flight import performance as PF, aero as AE
from flight.constants import KT, G0

PAGE = os.path.join(HERE, "..", "24-turns-questions.qmd")
d = np.degrees


def objective():
    q = Objective(PAGE, 12)
    q.num(1, PF.level_turn(100.0, np.radians(60))[2], "2", x=2)
    check("Q1 D", np.cos(np.radians(60)), 0.5)
    V = 300 * KT
    check("Q4 V", V, 154.3)
    check("Q4 V^2", V**2, 23815, tol=5)
    check("Q4 g tan60", G0 * np.tan(np.radians(60)), 16.99)
    q.num(4, PF.level_turn(V, np.radians(60))[1] / 1e3, "1.40")
    check("Q4 B", V**2 / G0 / 1e3, 2.43)
    q.num(5, 50 * np.sqrt(4), "100", x=100)
    check("Q5 B", 50 * np.sqrt(2), 70.7)
    V = 120 * KT
    check("Q6 V", V, 61.73)
    check("Q6 tan", V * np.radians(3) / G0, 0.330)
    q.num(6, d(PF.bank_for_turn_rate(V, np.radians(3))), "18.2^\\circ", x=18.2)
    check("Q6 rule", 120 / 10 + 7, 19)
    q.num(7, PF.sustained_load_factor(np.sqrt(3), 3.0), "3", x=3)
    check("Q7 A", PF.sustained_load_factor(1.0, 3.0), 2.24)
    check("Q7 B", PF.sustained_load_factor(PF.tightest_sustained_u(3.0), 3.0), 1.37)
    q.num(8, PF.turn_rate_radius(100.0, 4.0)[0] / PF.turn_rate_radius(100.0, 2.0)[0], "2.24")
    truth("Q9 tightest n below sqrt 2 for all tau", all(PF.sustained_load_factor(PF.tightest_sustained_u(t), t) < np.sqrt(2)
                                                     for t in np.linspace(1.01, 50, 200)))
    r10 = PF.turn_rate_radius(100.0, PF.sustained_load_factor(1.0, 5.0))[0]
    check("Q10 rad/s", r10, 0.277)
    check("Q10 sqrt 8", np.sqrt(8), 2.828)
    q.num(10, d(r10), "15.9^\\circ", x=15.9)
    check("Q10 n", PF.sustained_load_factor(1.0, 5.0), 3.0, tol=1e-12)
    check("Q10 C_L = n C_L*: lift W n at V*", PF.sustained_load_factor(1.0, 5.0), 3.0, tol=1e-12)
    vc1, vc2 = PF.corner_speed(PF.speed_for_cl(1.0, 1.0, 1.0, 1.2), 9), PF.corner_speed(PF.speed_for_cl(2.0, 1.0, 1.0, 1.2), 9)
    check("Q11 corner ratio", vc2 / vc1, np.sqrt(2), rel=1e-12)
    check("Q11 rate ratio", PF.turn_rate_radius(vc1, 9)[0] / PF.turn_rate_radius(vc2, 9)[0], np.sqrt(2), rel=1e-12)
    B = load("anim-24-bleed")
    check("Q12 from (m/s)", B.RUNS[1][1].V[0], 159)
    check("Q12 to (m/s)", B.RUNS[1][1].V[-1], 128)


def f16():
    W, T, b, e = 12000 * 9.81, 127000.0, 9.96, 0.85
    for S, vals in ((27.87, (3.56, 0.105, 9.30, 83.8, 341, 130.4, 4.93, 20.8, 359)),
                    (28.87, (None, None, 9.13, 83.7, 335, 125.9, 4.76, 20.8, 347))):
        A_ = b**2 / S
        K = 1 / (np.pi * e * A_)
        if vals[0]:
            check(f"P1 A (S={S})", A_, vals[0])
            check(f"P1 K (S={S})", K, vals[1])
        tau = T * AE.max_lift_to_drag(0.032, K)[1] / W
        check(f"P1 tau = T/(2W sqrt(K CD0)) (S={S})", tau, T / (2 * W * np.sqrt(K * 0.032)), rel=1e-12)
        check(f"P1 tau (S={S})", tau, vals[2])
        check(f"P1 bank (S={S})", d(PF.bank_for_load_factor(tau)), vals[3])
        Vn = PF.max_load_factor_u(tau) * PF.min_drag_speed(W, 1.225, S, 0.032, K)
        check(f"P1 speed (S={S})", Vn, vals[4])
        check(f"P1 = sqrt(T/(rho S CD0)) (S={S})", Vn, np.sqrt(T / (1.225 * S * 0.032)), rel=1e-12)
        vcs = PF.sustained_corner_speed(T, 1.225, S, 0.017, K, 2.0)
        check(f"P1 corner (S={S})", vcs, vals[5])
        n = PF.stall_load_factor(vcs, PF.speed_for_cl(W, 1.225, S, 2.0))
        check(f"P1 n (S={S})", n, vals[6])
        r, R = PF.turn_rate_radius(vcs, n, g=9.81)
        check(f"P1 rate (S={S})", d(r), vals[7])
        check(f"P1 radius (S={S})", R, vals[8])


def holding():
    V = 230 * KT
    check("P2 V", V, 118.3)
    check("P2 bank", d(PF.bank_for_turn_rate(V, np.radians(3))), 32.3)
    r, R, n = PF.level_turn(V, np.radians(25))
    check("P2 rate", d(r), 2.21)
    check("P2 180 deg (s)", np.pi / r, 81)
    check("P2 pattern (s)", 2 * np.pi / r + 120, 283)
    check("P2 radius (km)", R / 1e3, 3.06)
    check("P2 n", n, 1.10)


def corner():
    """P4."""
    x = np.linspace(1.001, 5, 500)
    rate = PF.turn_rate_radius(x, PF.stall_load_factor(x, 1.0), g=1.0)
    truth("P4 stall line: rate rises, radius falls", np.all(np.diff(rate[0]) > 0) and np.all(np.diff(rate[1]) < 0))
    check("P4 radius tends to V_s^2/g", rate[1][-1], 1 / np.sqrt(1 - 1 / 5**4), rel=1e-9)
    v = np.linspace(1, 5, 50)
    rr = PF.turn_rate_radius(v, 9.0)
    truth("P4 limit line: rate falls, radius grows", np.all(np.diff(rr[0]) < 0) and np.all(np.diff(rr[1]) > 0))
    from flight import atmosphere as A
    for h in (0.0, 6000.0, 11000.0):
        rho = A.isa(h)[2]
        check(f"P4 EAS corner independent of height ({h:.0f} m)", np.sqrt(rho / 1.225) * PF.corner_speed(PF.speed_for_cl(1e5, rho, 30.0, 1.2), 9.0),
              PF.corner_speed(PF.speed_for_cl(1e5, 1.225, 30.0, 1.2), 9.0), rel=1e-9)


def vinh():
    WS, rho, g = 95.0, 0.0023769, 32.2
    vs = PF.speed_for_cl(WS, rho, 1.0, 1.0)
    check("P3 V_s (ft/s)", vs, 282.7)
    vc = PF.corner_speed(vs, 5.0)
    check("P3 V_c", vc, 632)
    r, R = PF.turn_rate_radius(vc, 5.0, g=g)
    check("P3 rate", d(r), 14.3)
    check("P3 radius", R, 2530, tol=5)
    cls, E = AE.max_lift_to_drag(0.012, 0.208)
    check("P3 E_max", E, 10.0)
    tau = 0.3 * E
    check("P3 tau", tau, 3.00)
    check("P3 bank", d(PF.bank_for_load_factor(tau)), 70.5)
    check("P3 C_L*", cls, 0.240)
    vstar = PF.speed_for_cl(WS, rho, 1.0, cls)
    check("P3 V*", vstar, 577)
    check("P3 fastest", d(PF.turn_rate_radius(vstar, PF.sustained_load_factor(1.0, tau), g=g)[0]), 6.4)
    check("P3 n fastest = sqrt 5", PF.sustained_load_factor(1.0, tau), np.sqrt(2 * tau - 1), rel=1e-12)


def invariant():
    tau = 3.0
    check("P5 2 sqrt((tau-1)/(tau+1))", 2 * np.sqrt(2 / 4), 1.414)
    check("P5 bank", d(PF.bank_for_load_factor(tau)), 70.5)
    check("P5 2 tan(sigma/2)", 2 * np.tan(PF.bank_for_load_factor(tau) / 2), 1.414)
    V = 87.0
    rmin = PF.turn_rate_radius(PF.tightest_sustained_u(tau) * V, PF.sustained_load_factor(PF.tightest_sustained_u(tau), tau))[1]
    rate = PF.turn_rate_radius(V, PF.sustained_load_factor(1.0, tau))[0]
    check("P5 identity", rmin * rate**2 / G0, 2 * np.tan(PF.bank_for_load_factor(tau) / 2), rel=1e-12)


def prop_turn():
    """Guided derivation 6: the sustained turn of a propeller aircraft."""
    u, pi_, n = sp.symbols("u pi n", positive=True)
    sol = sp.solve(sp.Eq(2 * pi_ / u, u**2 + n**2 / u**2), n)
    truth("P6a n^2 = 2 pi u - u^4", any(sp.simplify(s_**2 - (2 * pi_ * u - u**4)) == 0 for s_ in sol))
    us = (pi_ / 2)**sp.Rational(1, 3)
    sym_zero("P6b stationary at u^3 = pi/2", sp.diff(2 * pi_ * u - u**4, u).subs(u, us))
    sym_zero("P6b n_max = sqrt3 (pi/2)^(2/3)", sp.sqrt(2 * pi_ * us - us**4) - sp.sqrt(3) * (pi_ / 2)**sp.Rational(2, 3))
    for pv, uw, nw in ((1.5, 0.909, 1.43), (2.5, 1.077, 2.01)):
        check(f"P6c u for pi={pv}", (pv / 2)**(1 / 3), uw)
        check(f"P6c n_max for pi={pv}", np.sqrt(3) * (pv / 2)**(2 / 3), nw)


def turn_point():
    """Guided derivation 7: a turn around a point in a wind."""
    g = G0
    for Vg, w in ((60.0, 50.7), (40.0, 28.5)):
        check(f"P7c bank at V_g={Vg} (deg)", np.degrees(np.arctan(Vg**2 / (g * 300))), w)
    check("P7c tan downwind", 60**2 / (g * 300), 1.224)
    check("P7b ratio", ((1 + 0.2) / (1 - 0.2))**2, 2.25)
    n = 1 / np.cos(np.arctan(60**2 / (g * 300)))
    check("P7d load factor", n, 1.58)
    check("P7d stall speed rise (%)", (np.sqrt(n) - 1) * 100, 26)


def bleed_rate():
    """Guided derivation 8: how fast a hard turn bleeds the speed."""
    from scipy.integrate import quad, solve_ivp
    import _climb as C, _turns as TU
    from flight.constants import FT
    from flight import atmosphere as A
    u, ta, n, r = sp.symbols("u tau n r", positive=True)
    f = ta - (u**2 + n**2 / u**2) / 2
    sym_zero("P8b roots solve the balance", sp.simplify(f.subs(u, sp.sqrt(ta + sp.sqrt(ta**2 - n**2)))))
    sym_zero("P8b other root", sp.simplify(f.subs(u, sp.sqrt(ta - sp.sqrt(ta**2 - n**2)))))
    fp = sp.diff(f, u)
    sym_zero("P8c f'", fp + (u**4 - n**2) / u**3)
    up = sp.sqrt(ta + r)
    sym_zero("P8c f'(u+) = -2r/u+", sp.simplify(fp.subs(u, up).subs(n, sp.sqrt(ta**2 - r**2)) + 2 * r / up))
    sym_zero("P8d sum of squares", sp.expand((u**2 - ta)**2 + (n**2 - ta**2) - (u**4 - 2 * ta * u**2 + n**2)))
    h = 30000 * FT
    tau, vs, es = C.scales(C.SBJ, C.W_SBJ, h)
    check("P8e tau", tau, 2.0774, tol=5e-5)
    check("P8e r from the quoted tau", np.sqrt(2.0774**2 - 4), 0.562, tol=5e-4)
    check("P8e V*", vs, 132.9, tol=0.05)
    check("P8e E*", es, 12.20, tol=0.005)
    v1 = TU.sbj_stall(h)
    check("P8e 1-g stall", v1, 89.4, tol=0.05)
    rr = np.sqrt(tau**2 - 4)
    check("P8e r", rr, 0.562, tol=5e-4)
    check("P8e u+^2", tau + rr, 2.639, tol=5e-4)
    upn = np.sqrt(tau + rr)
    check("P8e u+", upn, 1.625, tol=5e-4)
    check("P8e steady speed", upn * vs, 216, tol=0.5)
    check("P8e Mach", upn * vs / A.speed_of_sound(A.isa(h)[0]), 0.71, tol=0.005)
    check("P8e steady 2g is sustained", PF.sustained_load_factor(upn, tau), 2.0, tol=1e-9)
    sc = es * vs / G0
    check("P8e time scale", sc, 165, tol=0.5)
    check("P8e t_c", sc * upn / (2 * rr), 239, tol=0.5)
    us = v1 * np.sqrt(2.5) / vs
    check("P8e stall at 2.5g", v1 * np.sqrt(2.5), 141, tol=0.5)
    check("P8e u_s", us, 1.064, tol=5e-4)
    I, _ = quad(lambda x: 2 * x * x / (x**4 - 2 * tau * x * x + 6.25), us, upn)
    check("P8e integral", I, 0.970, tol=5e-4)
    check("P8e time", sc * I, 160, tol=0.5)
    ev = lambda S, y: y[0] - us; ev.terminal = True
    sol = solve_ivp(lambda S, y: [tau - 0.5 * (y[0]**2 + 6.25 / y[0]**2)], (0, 100), [upn], events=ev, rtol=1e-11)
    check("P8e time by integration", sol.t[-1] * sc, sc * I, tol=1e-4)
    check("P8e 20 % above", 2.5 / tau, 1.20, tol=0.005)
    check("P8e tau at 20,000 ft", C.scales(C.SBJ, C.W_SBJ, 20000 * FT)[0], 3.18, tol=0.005)
    check("P8e note's loss 159 -> 128", 159 - 128, 31, tol=0)


def rate_with_height():
    """Guided derivation 9: why dogfights come down."""
    import _climb as C
    from scipy.optimize import brentq
    from flight import atmosphere as A
    from flight.constants import FT
    s, t0, a, g, V0 = sp.symbols("sigma tau_0 a g V_0", positive=True)
    rate = g * sp.sqrt(s) / V0 * sp.sqrt(2 * (t0 * s**a - 1))
    sym_zero("P9a ratio (squared)", sp.simplify((rate / rate.subs(s, 1))**2 - s * (t0 * s**a - 1) / (t0 - 1)))
    tau0 = C.scales(C.SBJ, C.W_SBJ, 0.0)[0]
    check("P9 tau0", tau0, 6.759, tol=5e-4)
    for hf in (10000, 20000, 30000):
        h = hf * FT; tt = C.scales(C.SBJ, C.W_SBJ, h)[0]; sg = A.isa(h)[2] / A.isa(0.0)[2]
        check(f"P9 thrust law a=1.2 at {hf} ft", tt, tau0 * sg**1.2, tol=1e-6)
    r0 = lambda h: np.degrees(G0 / C.scales(C.SBJ, C.W_SBJ, h)[1] * np.sqrt(2 * (C.scales(C.SBJ, C.W_SBJ, h)[0] - 1)))
    check("P9 sea level rate", r0(0.0), 23.47, tol=0.005)
    ratio = lambda sg: np.sqrt(sg * (tau0 * sg**1.2 - 1) / (tau0 - 1))
    truth("P9b falls with height", np.all(np.diff([ratio(x) for x in np.linspace(0.25, 1, 50)]) > 0))
    check("P9b zero at tau = 1", tau0 * (tau0**(-1 / 1.2))**1.2 - 1, 0.0, tol=1e-12)
    sh = brentq(lambda x: x * (tau0 * x**1.2 - 1) - (tau0 - 1) / 4, 0.25, 1)
    check("P9c sigma half", sh, 0.577, tol=5e-4)
    hh = brentq(lambda h: A.isa(h)[2] / A.isa(0.0)[2] - sh, 0, 11000)
    check("P9c height (km)", hh / 1e3, 5.37, tol=0.005)
    check("P9c height (ft)", hh / FT, 17600, tol=50)
    for hf, sg, rq, rr in ((20000, 0.5328, 0.449, 10.53), (30000, 0.3741, 0.265, 6.21)):
        check(f"P9c sigma {hf}", A.isa(hf * FT)[2] / A.isa(0.0)[2], sg, tol=5e-5)
        check(f"P9c ratio {hf}", ratio(sg), rq, tol=5e-4)
        check(f"P9c simulator rate {hf}", r0(hf * FT), rr, 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
    from scipy.optimize import brentq
    for R_, vals in ((11000.0, (5.32, 100.2, 0.1116, 0.028, 100.0, 0.048)), (1100.0, (68.0, 163.3, None, 10.8, None, 18.5))):
        phi = np.arcsin(100**2 / (g * R_)); Vt = 100 / np.sqrt(np.cos(phi)); TW = 1 / (9 * np.cos(phi))
        gm = brentq(lambda x: np.sin(x) + np.cos(x) / 9 - TW, -0.1, 1.2); Vc = 100 * np.sqrt(np.cos(gm))
        check(f"E24 bank {R_}", np.degrees(phi), vals[0], tol=0.05 if R_ < 2000 else 0.005)
        check(f"E24 turn speed {R_}", Vt, vals[1], tol=0.05)
        check(f"E24 turn force balance {R_}", np.tan(phi), Vt**2 / (g * R_), tol=1e-12)
        if vals[2]:
            check("E24 T/W", TW, vals[2], tol=5e-5); check("E24 climb speed", Vc, vals[4], tol=0.05)
            check("E24 gamma", np.degrees(gm), vals[3], tol=5e-4); check("E24 ROC", Vc * np.sin(gm), vals[5], tol=5e-4)
        else:
            check("E24 gamma 1100", np.degrees(gm), vals[3], tol=0.05); check("E24 ROC 1100", Vc * np.sin(gm), vals[5], tol=0.06)

if __name__ == "__main__":
    run([objective, f16, holding, vinh, corner, invariant, prop_turn, turn_point, bleed_rate, rate_with_height, earlier_papers])
