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

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


def objective():
    q = Objective(PAGE, 12)
    g = 0.3 - 1 / 12
    check("Q4 rad", g, 0.217)
    q.num(4, np.degrees(g), "12.4^\\circ", x=12.4)
    check("Q4 A", np.degrees(0.3), 17.2)
    u = PF.fastest_climb_u(3.0)
    q.num(5, u, "1.47")
    check("Q5 u^2", u**2, 2.155)
    check("Q5 C", np.sqrt(3), 1.73)
    check("Q5 D", u**2, 2.15, tol=0.006)
    r = PF.climb_rate_ideal(u, 3.0, 100.0, 10.0)
    q.num(6, r, "24.8")
    check("Q6 tau u", 3 * u, 4.404)
    check("Q6 drag term", (u**3 + 1 / u) / 2, 1.922)
    check("Q6 A", PF.climb_rate_ideal(1.0, 3.0, 100.0, 10.0), 20.0)
    q.num(7, 3000 / 15 / 60, "3.3")
    q.num(8, PF.U_MIN_POWER, "0.76", x=0.76)
    check("Q9 u at tau 1", PF.fastest_climb_u(1.0), 1.0, tol=1e-12)
    t = PF.time_to_climb_linear(30.0, 12000.0, 9000.0)
    q.num(10, t / 60, "9.2")
    check("Q10 ln 4", np.log(4), 1.386)
    check("Q10 s", t, 554, tol=1)
    check("Q10 A", 9000 / 30 / 60, 5.0)
    g2 = 0.15 - 1 / 12
    check("Q11 rad", g2, 0.067, tol=0.0005)
    check("Q11 deg", np.degrees(g2), 3.8)
    truth("Q11 answer text", "3.8" in q.right(11))
    EA = load("fig-21-eas")
    check("Q12 5 %", (EA.T_BEST / EA.MIN_TIME[1][-1] - 1) * 100, 5, tol=0.5)


def kiran6():
    W = C.M_KIRAN * G0
    tau, vs, es = C.scales(C.KIRAN, W, 6000.0)
    check("P1 tau", tau, 2.60)
    check("P1 V*", vs, 117.5)
    check("P1 E*", es, 12.74)
    g = PF.climb_angle_ideal(1.0, tau, es)
    check("P1 gamma rad", g, 0.126)
    check("P1 gamma deg", np.degrees(g), 7.20)
    check("P1 hdot", vs * g, 14.8)
    u = PF.fastest_climb_u(tau)
    check("P1 u^2", u**2, 1.909)
    check("P1 u", u, 1.381)
    check("P1 V", u * vs, 162.4)
    check("P1 hdot fastest", PF.climb_rate_ideal(u, tau, vs, es), 17.6)
    check("P1 gamma fastest", np.degrees(PF.climb_angle_ideal(u, tau, es)), 6.23)
    check("P1 19 % more rate", (PF.climb_rate_ideal(u, tau, vs, es) / (vs * g) - 1) * 100, 19, tol=0.5)
    check("P1 38 % more speed", (u - 1) * 100, 38, tol=0.5)


def time_to_climb():
    K = load("fig-21-kiran")
    check("P2 ROC0", K.ROC_SL, 37.2)
    check("P2 H", K.H_ABS / 1e3, 13.29)
    check("P2 linear to 9 km (min)", PF.time_to_climb_linear(37.2, 13290.0, 9000.0) / 60, 6.7)
    hs = np.linspace(0, 9000, 901)
    x, t, f = PF.climb_integrals(hs, C.climb_state(C.KIRAN, C.M_KIRAN * G0, C.FASTEST))
    check("P2 numerical (min)", t[-1] / 60, 7.6)
    check("P2 linear to service ceiling (min)", PF.time_to_climb_linear(37.2, 13290.0, 13070.0) / 60, 24.4)
    r = np.array([C.max_roc(C.KIRAN, C.M_KIRAN * G0, h) for h in np.linspace(0, 9000, 10)])
    lin = 37.2 * (1 - np.linspace(0, 9000, 10) / 13290.0)
    truth("P2 the model rate lies below the linear law in the middle of the climb", np.all(r[2:-1] < lin[2:-1]))


def eas():
    vs0 = C.scales(C.SBJ, C.W_SBJ, 0.0)[1] / KT
    check("P3 V*_SL (kt)", vs0, 158)
    check("P3 u", 210 / 158, 1.33)
    S = load("fig-21-schedule")
    check("P3 fastest u at SL", S.TABLE[0, 2] / S.TABLE[0, 0], 2.14)
    check("P3 fastest u at 35,000 ft (Hull)", 557 / 479, 1.16)
    check("P3 ours at 35,000 ft", S.TABLE[7, 2] / S.TABLE[7, 0], 1.16)


def prop_climb():
    """Guided derivation 4: how a propeller aircraft climbs."""
    u, pi_, E = sp.symbols("u pi E", positive=True)
    g = (pi_ / u - (u**2 + u**-2) / 2) / E
    hd = u * g
    sym_zero("P4a rate of climb", sp.expand(hd - (pi_ - (u**3 + 1 / u) / 2) / E))
    truth("P4b fastest at u^4 = 1/3, independent of pi", sp.solve(sp.diff(hd, u), u) == [3**sp.Rational(-1, 4)])
    sym_zero("P4c steepest condition", sp.expand(-u**3 * sp.diff(g, u) * E - (u**4 + pi_ * u - 1)))
    for pv, w in ((1.5, 0.587), (3.0, 0.329)):
        check(f"P4c steepest u for pi={pv}", brentq(lambda x: x**4 + pv * x - 1, 0.01, 1.0), w)
    check("P4b 3^(-1/4)", 3**-0.25, 0.760)


def oei():
    """Guided derivation 5: one engine inoperative."""
    E = 12.0
    check("P5b 1/E", 1 / E, 0.0833)
    for N, gm, w in ((2, 0.024, 0.215), (3, 0.027, 0.165), (4, 0.030, 0.151)):
        check(f"P5b T/W for N={N}", N / (N - 1) * (gm + 1 / E), w)
    check("P5c ratio twin/quad", (2 * (0.024 + 1 / E)) / (4 / 3 * (0.030 + 1 / E)), 1.42)
    t2 = 2 * (0.024 + 1.05 / E)
    check("P5d with 5 % extra drag", t2, 0.223)
    check("P5d increase (%)", (t2 / (2 * (0.024 + 1 / E)) - 1) * 100, 4, tol=0.2)


def climb_fuel():
    """Guided derivation 6: minimum fuel to climb."""
    c, D, W, V, gm = sp.symbols("c D W V gamma", positive=True)
    f = c * (D + W * sp.sin(gm)) / (V * sp.sin(gm))
    sym_zero("P6a fuel per height", f - c * (D / (V * sp.sin(gm)) + W / V))
    truth("P6b d/dgamma < 0 for 0 < gamma < pi/2", sp.simplify(sp.diff(f, gm) + c * D * sp.cos(gm) / (V * sp.sin(gm)**2)) == 0)


def climb_in_wind():
    """Guided derivation 7: the steepest climb over the ground in a wind."""
    from scipy.optimize import minimize_scalar
    u, w, ta, Es, a = sp.symbols("u omega tau E a", positive=True)
    hd = (ta * u - (u**3 + 1 / u) / 2) / Es               # hdot / V*
    Gm = hd / (u - w)
    sym_zero("P7a gradient", sp.simplify(Gm - u * (2 * ta - u**2 - u**-2) / (2 * Es * (u - w))))
    sym_zero("P7a still air", sp.simplify(Gm.subs(w, 0).subs(u, 1) - (ta - 1) / Es))
    dl = sp.diff(sp.log(u) + sp.log(2 * ta - u**2 - u**-2) - sp.log(u - w), u)
    lin = sp.series(dl.subs(u, 1 + a * w), w, 0, 2).removeO()
    sym_zero("P7b shift", sp.solve(lin, a)[0] + (ta - 1) / 4)
    W = C.M_KIRAN * G0
    tau, vs, es = C.scales(C.KIRAN, W, 0.0)
    check("P7 mass", C.M_KIRAN, 4950, tol=0)
    check("P7 tau", tau, 4.83, tol=0.005)
    check("P7 V*", vs, 86.26, tol=0.005)
    check("P7 E*", es, 12.74, tol=0.005)
    g0 = (tau - 1) / es
    check("P7c still air", g0, 0.301, tol=5e-4)
    for wv, ue, ur, gb, g1 in ((10.0, 0.866, 0.889, 0.343, 0.340), (-10.0, 1.095, 1.111, 0.271, 0.269)):
        om = wv / vs
        G = lambda x: x * (2 * tau - x * x - x**-2) / (2 * es * (x - om))
        r = minimize_scalar(lambda x: -G(x), bounds=(0.5, 1.5), method="bounded", options=dict(xatol=1e-10))
        check(f"P7c best u {wv}", r.x, ue, tol=5e-4)
        check(f"P7c rule {wv}", 1 - (tau - 1) * om / 4, ur, tol=5e-4)
        check(f"P7c best gradient {wv}", G(r.x), gb, tol=5e-4)
        check(f"P7c at u=1 {wv}", G(1.0), g1, tol=5e-4)
        if wv > 0:
            check("P7c extra from best speed, share of still air (%)", 100 * (G(r.x) - G(1.0)) / g0, 1, tol=0.5)
            check("P7c four-fifths", ((tau - 1) * abs(om) / 4) / abs(r.x - 1), 0.8, tol=0.05)
        else:
            truth("P7c tailwind: less extra, rule overshoots", (G(r.x) - G(1.0)) / g0 < 0.01 and (tau - 1) * abs(om) / 4 > abs(r.x - 1))
        if wv > 0:
            check("P7c headwind +14 %", 100 * (G(r.x) / g0 - 1), 14, tol=0.5)
            check("P7c (tau-1) omega", (tau - 1) * om, 0.44, tol=0.005)
        else:
            check("P7c tailwind -10 %", 100 * (1 - G(r.x) / g0), 10, tol=0.5)
    check("P7 omega", 10 / vs, 0.116, tol=5e-4)
    check("P7d climb angle (deg)", np.degrees(np.arcsin(g0)), 17, tol=0.5)
    check("P7d cos", np.cos(np.arcsin(g0)), 0.95, 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
    for tw_, Em in ((0.3, 15.0), (0.8, 8.0)):
        ws, rho, cd0 = 3000.0, 0.9, 0.02
        K = 1 / (4 * Em**2 * cd0); tau = tw_ * Em
        Vs = Pf.min_drag_speed(ws * 10.0, rho, 10.0, cd0, K)
        V2 = Vs**2 * (tau + np.sqrt(tau**2 + 3)) / 3
        check("E21 design form", tw_ * ws / (3 * rho * cd0) * (1 + np.sqrt(1 + 3 / (Em**2 * tw_**2))), V2, tol=1e-6 * V2)

if __name__ == "__main__":
    run([objective, kiran6, time_to_climb, eas, prop_climb, oei, climb_fuel, climb_in_wind, earlier_papers])
