"""Checks every number in the answers and solutions of 20-glide-questions.qmd,
including the guided derivations 4-7.
Run from anywhere:  python3 codes/20-glide-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 _ojha as O
from flight import performance as PF, aero as AE, atmosphere as A
from flight.constants import FT, NMI

PAGE = os.path.join(HERE, "..", "20-glide-questions.qmd")


def data():
    check("sigma at 5 km", A.isa(5000.0)[2] / 1.225, 0.6009)


def objective():
    q = Objective(PAGE, 12)
    q.num(4, 15 * 3, "45")
    check("Q4 C", np.sqrt(3) / 2 * 45, 39, tol=0.05)
    g = np.degrees(np.arctan(2 * np.sqrt(0.02 * 0.05)))
    q.num(5, g, "3.62^\\circ", x=3.62)
    check("Q5 tangent", 2 * np.sqrt(0.001), 0.0632)
    check("Q5 B", g / 2, 1.81)
    check("Q5 C", 2 * g, 7.24)
    q.num(6, 30 * PF.U_MIN_POWER, "22.8")
    check("Q6 A", 30 * 3**0.25, 39.5)
    check("Q6 B", 30 / np.sqrt(3), 17.3)
    q.num(7, (25 - 5) / 1.0, "20")
    s = A.isa(5000.0)[2] / 1.225
    q.num(8, 1.2 / np.sqrt(s), "1.55")
    check("Q8 A", 1.2 * s, 0.72)
    check("Q8 B", 1.2 * np.sqrt(s), 0.93)
    check("Q8 C", 1.2 / s, 2.00)
    q.num(9, 27.1 * np.sqrt(1.44), "32.5")
    check("Q9 A", 27.1 * 1.44, 39.0)
    check("Q9 D", 27.1 / 1.2, 22.6)
    q.num(10, 1.15 * 2 / 3**0.75, "1.01")
    check("Q10 12 % saving", (1 - 2 / 3**0.75) * 100, 12, tol=0.5)
    b = O.OJHA_SCALE
    r = 2 * b * (1 - np.exp(-4000 / (2 * b))) / 4000
    check("Q11 ratio", r, 0.900)
    q.num(11, (1 - r) * 100, "10", tol=0.5)
    AL = load("anim-20-airliner")
    check("Q12 gain (km)", (AL.RESULT["speed to fly, 50 kt headwind"][0] - AL.RESULT["flattest-glide speed, 50 kt headwind"][0]) / 1e3, 1)
    check("Q12 wind costs (%)", (1 - AL.RESULT["flattest-glide speed, 50 kt headwind"][0] / AL.RESULT["flattest glide, still air"][0]) * 100, 18)


def ojha2():
    g = O.UNPOWERED
    cls, E = AE.max_lift_to_drag(g["CD0"], g["K"])
    cd = AE.parabolic_cd(cls, g["CD0"], g["K"])
    check("P1 C_L*", cls, 0.582)
    truth("P1 below C_Lmax", cls < g["CLmax"])
    check("P1 E", E, 14.56)
    check("P1 angle (deg)", np.degrees(np.arctan(1 / E)), 3.93)
    check("P1 distance (km)", E * 5, 72.8)
    s5 = PF.glide_state(g["W"], A.isa(5000.0)[2], g["S"], cls, cd)
    s0 = PF.glide_state(g["W"], A.isa(0.0)[2], g["S"], cls, cd)
    check("P1 V at 5 km", s5[0], 59.9)
    check("P1 sink at 5 km", s5[2], 4.10)
    check("P1 V at SL", s0[0], 46.4)
    check("P1 sink at SL", s0[2], 3.18)
    check("P1 ratio 1/sqrt(sigma)", s5[0] / s0[0], 1.29)
    check("P1 time (min)", PF.glide_time_exponential(g["W"], g["S"], cls, cd, 5000.0, 0.0) / 60, 22.9)
    check("P1 least-sink C_L", PF.min_sink_cl(g["CD0"], g["K"]), 1.01)
    truth("P1 least-sink C_L below C_Lmax", PF.min_sink_cl(g["CD0"], g["K"]) < g["CLmax"])


def gimli():
    r = 10 * NMI / (5000 * FT)
    check("P2 ratio", r, 12.2)
    h = 35000 * FT / 1e3
    check("P2 height (km)", h, 10.67)
    check("P2 at 12", 12 * h, 128)
    check("P2 at 20", 20 * h, 213)
    AL = load("anim-20-airliner")
    check("P2 transport E_max", AL.E_MAX, 19.2)
    for vb, uq, lq in ((240.0, 0.92, 1.5), (230.0, 0.96, 0.4)):
        u = 220.0 / vb
        check(f"P2 u at best {vb:.0f} kt", u, uq, tol=0.005)
        check(f"P2 drag above least at best {vb:.0f} kt (%)", (PF.drag_ratio(u) - 1) * 100, lq, tol=0.06)


def speed_to_fly():
    V, w, s = sp.symbols("V V_w s")
    h = sp.Function("h")(V)
    cond = sp.numer(sp.together(sp.diff((V - w) / (h + s), V)))
    sym_zero("P3 condition: (h + s) - (V - w) h' = 0", sp.expand(cond - ((h + s) - (V - w) * sp.diff(h, V))))
    G = O.GLIDER
    rho = A.isa(2000.0)[2]
    sink = lambda v: PF.sink_rate_small_angle(v, G["W"], rho, G["S"], G["CD0"], G["K"])
    MA = load("fig-20-moving-air")
    vb = MA.BEST["air sinking 1.5 m/s"]
    check("P3 speed (m/s)", vb, 34.6)
    a, b = 27.1 / (sink(27.1) + 1.5), vb / (sink(vb) + 1.5)
    check("P3 ratio at 27.1", a, 10.2)
    check("P3 ratio at 34.6", b, 11.0)
    check("P3 8 % better", (b / a - 1) * 100, 8, tol=0.5)
    check("P3 still-air ratio", AE.max_lift_to_drag(G["CD0"], G["K"])[1], 23.6)
    check("P3 still air: the flattest glide", MA.BEST["still air"], PF.min_drag_speed(G["W"], rho, G["S"], G["CD0"], G["K"]), tol=0.01)


def steep_glide():
    """Guided derivation 4: the exact sink rate of a steep glide."""
    E, CL, W, rho, S = sp.symbols("E C_L W rho S", positive=True)
    cg = E / sp.sqrt(1 + E**2)
    sg = 1 / sp.sqrt(1 + E**2)
    hs = sp.sqrt(2 * W * cg / (rho * S * CL)) * sg
    CD = CL / E
    sym_zero("P4a exact sink rate", sp.simplify(hs / (sp.sqrt(2 * W / (rho * S)) * CD / CL**sp.Rational(3, 2) * (1 + E**-2)**sp.Rational(-3, 4))) - 1)
    for Ev, w in ((23.6, 0.999), (10, 0.993), (4, 0.956)):
        check(f"P4c factor at E={Ev}", (1 + Ev**-2)**-0.75, w)
    Es = 1 / np.tan(np.radians(20))
    check("P4c Shuttle E", Es, 2.75)
    check("P4c Shuttle factor", (1 + Es**-2)**-0.75, 0.911)


def thermal():
    """Guided derivation 5: circling in a thermal."""
    W, S, rho, g = 3920.0, 15.0, 1.0065, 9.80665
    check("P5 rho at 2 km", A.isa(2000.0)[2], rho)
    sn = 2 * W / (rho * S * 1.1 * g * 100)
    check("P5c sin(sigma)", sn, 0.481)
    sig = np.arcsin(sn)
    check("P5c bank (deg)", np.degrees(sig), 28.8)
    n = 1 / np.cos(sig)
    check("P5c n", n, 1.141)
    V = PF.speed_for_cl(W, rho, S, 1.1)
    check("P5c V straight", V, 21.73)
    cd = AE.parabolic_cd(1.1, 0.015, 0.03)
    check("P5c C_D", cd, 0.0513)
    check("P5c E", 1.1 / cd, 21.4)
    hs = V * cd / 1.1
    check("P5c straight sink", hs, 1.013)
    check("P5c turn V", V * np.sqrt(n), 23.2)
    check("P5c turn sink", hs * n**1.5, 1.235)
    check("P5c increase (%)", (n**1.5 - 1) * 100, 22)
    check("P5b radius agrees with V^2/(g tan sigma)", (V * np.sqrt(n))**2 / (g * np.tan(sig)), 100, tol=1e-6)
    s6 = 2 * W / (rho * S * 1.2 * g * 60)
    check("P5d sin(sigma) for 60 m", s6, 0.735)
    check("P5d bank (deg)", np.degrees(np.arcsin(s6)), 47, tol=0.5)
    n6 = 1 / np.cos(np.arcsin(s6))
    check("P5d n", n6, 1.48)
    check("P5d sink factor", n6**1.5, 1.80)


def glide_drag():
    """Guided derivation 6: the price of drag in a glide."""
    check("P6c distance factor", 1.3**-0.5, 0.877)
    check("P6c speed factor", 1.3**-0.25, 0.937)
    check("P6c clean (km)", 17 * 10, 170)
    check("P6c gear down (km)", 170 * 1.3**-0.5, 149)
    check("P6c cost (km)", 170 * (1 - 1.3**-0.5), 21)
    c0, K = sp.symbols("C_D0 K", positive=True)
    sym_zero("P6b V* ~ C_L*^(-1/2) = (K/C_D0)^(1/4)", (sp.sqrt(c0 / K))**sp.Rational(-1, 2) - (K / c0)**sp.Rational(1, 4))


def speed_to_fly_closed():
    """Guided derivation 7: the speed to fly, in closed form."""
    import _ojha as OJ
    from scipy.optimize import brentq
    u, w, s, a = sp.symbols("u omega sigma a")
    Fh = (u - w) / (u**3 + 1 / u)
    sym_zero("P7a quintic", sp.factor(sp.numer(sp.together(sp.diff(Fh, u)))) + (2 * u**5 - 3 * w * u**4 - 2 * u + w))
    lin = sp.series((2 * u**5 - 3 * w * u**4 - 2 * u + w).subs(u, 1 + a * w), w, 0, 2).removeO()
    sym_zero("P7a a = 1/4", sp.solve(lin, a)[0] - sp.Rational(1, 4))
    Fs = u / (u**3 + 1 / u + s)
    truth("P7b quartic (numerator proportional)", sp.simplify(sp.numer(sp.together(sp.diff(Fs, u))) / (2 * u**4 - s * u - 2)).free_symbols <= {u} and sp.simplify(sp.diff(sp.numer(sp.together(sp.diff(Fs, u))) / (2 * u**4 - s * u - 2), s)) == 0)
    lin = sp.series((2 * u**4 - s * u - 2).subs(u, 1 + a * s), s, 0, 2).removeO()
    sym_zero("P7b a = 1/8", sp.solve(lin, a)[0] - sp.Rational(1, 8))
    G = OJ.GLIDER; rho = A.isa(2000.0)[2]
    cls, Es = AE.max_lift_to_drag(G["CD0"], G["K"])
    Vs = PF.speed_for_cl(G["W"], rho, G["S"], cls)
    check("P7 V*", Vs, 27.10, tol=0.005)
    check("P7 E*", Es, 23.57, tol=0.005)
    check("P7 sink model", PF.sink_rate_small_angle(1.3 * Vs, G["W"], rho, G["S"], G["CD0"], G["K"]), Vs / (2 * Es) * (1.3**3 + 1 / 1.3), tol=1e-9)
    om = 8 / Vs
    check("P7c omega", om, 0.295, tol=5e-4)
    uh = brentq(lambda x: 2 * x**5 - 3 * om * x**4 - 2 * x + om, 0.8, 2)
    check("P7c u headwind", uh, 1.0975, tol=5e-5)
    check("P7c V headwind", uh * Vs, 29.74, tol=0.005)
    check("P7c = engine", PF.speed_to_fly(G["W"], rho, G["S"], G["CD0"], G["K"], 8.0, 0.0), uh * Vs, tol=1e-4)
    check("P7c rule factor", 1 + om / 4, 1.074, tol=5e-4)
    check("P7c rule V", (1 + om / 4) * Vs, 29.10, tol=0.005)
    check("P7c 2 % low", 100 * (1 - (1 + om / 4) / uh), 2, tol=0.5)
    sg = 2 * Es * 1.5 / Vs
    check("P7c sigma", sg, 2.61, tol=0.005)
    us = brentq(lambda x: 2 * x**4 - sg * x - 2, 0.8, 2)
    check("P7c V sink", us * Vs, 34.63, tol=0.005)
    check("P7c = engine (sink)", PF.speed_to_fly(G["W"], rho, G["S"], G["CD0"], G["K"], 0.0, 1.5), us * Vs, tol=1e-4)
    check("P7c rule V sink", (1 + sg / 8) * Vs, 35.94, tol=0.005)
    check("P7c 4 % high", 100 * ((1 + sg / 8) / us - 1), 4, tol=0.5)
    check("P7c own sink", Vs / Es, 1.15, tol=0.005)
    Eg = lambda x: (x - om) * 2 * Es / (x**3 + 1 / x)
    check("P7d at V*", Eg(1.0), Es * (1 - om), tol=1e-12)
    check("P7d 1 - omega", 1 - om, 0.705, tol=5e-4)
    check("P7d at V*", Eg(1.0), 16.61, tol=0.005)
    check("P7d best", Eg(uh), 16.94, tol=0.005)
    check("P7d gain (%)", 100 * (Eg(uh) / Eg(1.0) - 1), 2, tol=0.5)
    check("P7d cost of headwind (%)", 100 * (1 - Eg(uh) / Es), 28, tol=0.5)



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
    k = 1 / (np.pi * 0.75 * 6.2); E = 1 / (2 * np.sqrt(k * 0.056)); W = 116 * g
    check("E20 K", k, 0.0685, tol=5e-5); check("E20 E", E, 8.08, tol=0.005); check("E20 gamma", np.degrees(np.arctan(1 / E)), 7.06, tol=0.005)
    check("E20 V*", Pf.min_drag_speed(W, 1.225, 15.8, 0.056, k), 11.40, tol=0.005)
    cl = np.sqrt(3 * 0.056 / k); gm = np.arctan(4 * 0.056 / cl); V = np.sqrt(2 * W * np.cos(gm) / (1.225 * 15.8 * cl))
    check("E20 CL min sink", cl, 1.567, tol=5e-4); check("E20 V min sink", V, 8.62, tol=0.005)
    check("E20 sink", V * np.sin(gm), 1.220, tol=5e-4); check("E20 height", V * np.sin(gm) * 600, 732, tol=0.5)
    truth("E20 below C_Lmax", cl < 2.27)
    c, c0, K = sp.symbols("C_L C_D0 K", positive=True)
    f = c0 * c**sp.Rational(-3, 2) + K * c**sp.Rational(1, 2)
    sym_zero("E20 min sink C_L", sp.simplify(sp.diff(f, c).subs(c, sp.sqrt(3 * c0 / K))))
    h, A_, beta = sp.symbols("h A beta", positive=True)
    F = beta / sp.sqrt(K * c0) * sp.atan(A_ * sp.sqrt(K / c0) * sp.exp(h / beta))
    sym_zero("E20 range antiderivative", sp.simplify(sp.diff(F, h) - A_ * sp.exp(h / beta) / (c0 + K * A_**2 * sp.exp(2 * h / beta))))
    check("E20 density change over 732 m (%)", 100 * (1 - At.isa(732.0)[2] / At.isa(0.0)[2]), 7, tol=0.5)


if __name__ == "__main__":
    run([data, objective, ojha2, gimli, speed_to_fly, steep_glide, thermal, glide_drag, speed_to_fly_closed, earlier_papers])
