"""Checks every number in the answers and solutions of 26-takeoff-questions.qmd,
including the guided derivations 4-7.
Run from anywhere:  python3 codes/26-takeoff-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
import _takeoff as T
from flight import performance as PF, atmosphere as A
from flight.constants import KT, FT, G0

PAGE = os.path.join(HERE, "..", "26-takeoff-questions.qmd")
R0 = A.isa(0.0)[2]
BASE = T.takeoff(R0)


def objective():
    q = Objective(PAGE, 12)
    V = 94 * KT
    check("Q4 V", V, 48.4)
    check("Q4 V^2", V**2, 2338, tol=1)
    q.num(4, V**2 / 3400, "0.69")
    check("Q4 B", V**2 / 1700, 1.38)
    q.num(5, 60 / np.sqrt(0.64), "75", x=75)
    check("Q5 C", 60 / 0.64, 94, tol=0.5)
    q.num(6, (1 - 0.1)**2, "0.81")
    check("Q7 V", 1.8 * 43, 77.4)
    q.num(7, 0.5 * 1.8 * 43**2, "1664", x=1664)
    x, t, g = PF.takeoff_transition(70.0, 1.2, 10.7)
    check("Q8 t", t, 3.30)
    q.num(8, x, "231", x=231)
    W = 1.0
    truth("Q10 x_g ~ W^2 when drag and friction are small", abs(PF.ground_run(4.0, 100.0, 0.0, 1.0, 1.0, 1e-9, 0.0, np.sqrt(2.0))
          / PF.ground_run(2.0, 100.0, 0.0, 1.0, 1.0, 1e-9, 0.0, 1.0) - 4.0) < 1e-6)
    L = 120e3 * 10 / 35
    check("Q11 fin force (kN)", L / 1e3, 34.3)
    q.num(11, np.sqrt(2 * L / (1.225 * 30 * 1.0)), "43", x=43)
    q.num(12, PF.best_ground_run_cl(0.02, 0.05), "0.2")


def fuel():
    check("P1 time", BASE["t_ground"], 16.6)
    f = 1.05 / 3600 * T.T_AVG / T.LB * BASE["t_ground"]
    check("P1 fuel (lb)", f, 28)
    check("P1 fraction of the weight (%)", f / 13000 * 100, 0.2)


def vinh():
    vs = 134.96
    check("P2 V_LO", 1.1 * vs, 148.46)
    check("P2 V2", 1.2 * vs, 161.95)
    check("P2 x1", 2 * (1.1 + 1.2) / 2 * vs, 310)
    R, x2, hr, x3, t2, t3 = PF.arc_transition(1.2 * vs, 1.15, np.radians(8), 50.0, g=32.2)
    check("P2 R", R, 5430)
    check("P2 x2", x2, 756)
    check("P2 t2", t2, 4.68)
    check("P2 h_r", hr, 52.8)
    truth("P2 obstacle passed during the arc", hr > 50)


def wind():
    Vw = 20 * KT
    check("P3 V_w", Vw, 10.29)
    check("P3 V_w/V_LO", Vw / BASE["vlo"], 0.156)
    check("P3 rule", (1 - Vw / BASE["vlo"])**2, 0.712)
    full = T.takeoff(R0, headwind=Vw)["ground"] / BASE["ground"]
    check("P3 full", full, 0.718)
    check("P3 within 1 %", (full / (1 - Vw / BASE["vlo"])**2 - 1) * 100, 0.7, tol=0.3)


def run_scaling():
    """Guided derivation 4: what the ground run depends on."""
    WS, rho, g, CL, tw, mu = sp.symbols("W_S rho g C_Lmax tw mu", positive=True)
    VLO2 = 1.44 * 2 * WS / (rho * CL)
    sym_zero("P4a constant-acceleration run", VLO2 / (2 * g * (tw - mu)) - 1.44 * WS / (rho * g * CL * (tw - mu)))
    check("P4b 10 % heavier (%)", (1.1**2 - 1) * 100, 21)
    check("P4c Leh factor", 0.640**-2.2, 2.67)
    check("P4c wing part", 0.640**-1, 1.56)
    check("P4c engine part", 0.640**-1.2, 1.71)
    check("P4c product", 0.640**-1 * 0.640**-1.2, 0.640**-2.2, tol=1e-12)


def bfl():
    """Guided derivation 5: the balanced field length in closed form."""
    V1, a, ae, d, VLO, xa = sp.symbols("V_1 a a_e d V_LO x_a", positive=True)
    go = V1**2 / (2 * a) + (VLO**2 - V1**2) / (2 * ae) + xa
    stop = V1**2 / (2 * a) + V1**2 / (2 * d)
    sol = sp.solve(sp.Eq(go, stop), V1)
    truth("P5b V1^2 = (V_LO^2 + 2 a_e x_a) d/(d + a_e)", any(sp.simplify(s_**2 - (VLO**2 + 2 * ae * xa) * d / (d + ae)) == 0 for s_ in sol))
    av, aev, dv, Vv, xav = 2.5, 1.0, 3.0, 70.0, 300.0
    v1 = np.sqrt((Vv**2 + 2 * aev * xav) * dv / (dv + aev))
    check("P5c V1^2", v1**2, 4125)
    check("P5c V1", v1, 64.2)
    check("P5c V1/V_LO", v1 / Vv, 0.92)
    check("P5c BFL (m)", v1**2 / (2 * av) + v1**2 / (2 * dv), 1513, tol=0.6)
    check("P5c AEO run (m)", Vv**2 / (2 * av), 980)
    A_ = 1 / (2 * aev) + 1 / (2 * dv)
    C_ = -(Vv**2 / (2 * aev) + xav)
    v1r = (-2.0 + np.sqrt(4.0 - 4 * A_ * C_)) / (2 * A_)
    check("P5d V1 with reaction time", v1r, 62.7)
    check("P5d BFL with reaction time (m)", v1r**2 / (2 * av) + 2 * v1r + v1r**2 / (2 * dv), 1569)
    g_ = v1r**2 / (2 * av) + (Vv**2 - v1r**2) / (2 * aev) + xav
    f = lambda ae_, d_: np.sqrt((Vv**2 + 2 * ae_ * xav) * d_ / (d_ + ae_))
    truth("P5d better brakes raise V1", f(aev, 3.5) > f(aev, 3.0))
    truth("P5d a weaker remaining engine raises V1 here (2 d x_a < V_LO^2)", f(0.8, dv) > f(1.0, dv) and 2 * dv * xav < Vv**2)
    check("P5d go = stop at that V1", g_, v1r**2 / (2 * av) + 2 * v1r + v1r**2 / (2 * dv), tol=1e-6)


def seven_tenths():
    """Guided derivation 6: why the books use the acceleration at 0.7 V_LO."""
    F0, F1, c, m, sv, V, d, Fb = sp.symbols("F_0 F_1 c m s V delta Fbar", positive=True)
    anti = -sp.log(F0 - c * sv) / c                                    # antiderivative of 1/(F0 - c s)
    sym_zero("P6a antiderivative", sp.diff(anti, sv) - 1 / (F0 - c * sv))
    sym_zero("P6a distance", sp.expand_log(m / 2 * (anti.subs(sv, V**2) - anti.subs(sv, 0))
                                           - m / (2 * c) * sp.log(F0 / (F0 - c * V**2)), force=True))
    sym_zero("P6b force at V/sqrt2", (F0 - c * V**2 / 2).subs(c, (F0 - F1) / V**2) - (F0 + F1) / 2)
    LM = 2 * Fb * d / sp.log((1 + d) / (1 - d))
    sym_zero("P6c expansion", sp.series(LM / Fb, d, 0, 3).removeO() - (1 - d**2 / 3))
    sym_zero("P6e mean over V", sp.integrate(F0 - c * sv**2, (sv, 0, V)) / V - (F0 - c * V**2 / 3))
    Vlo = BASE["vlo"]
    f0, f1 = T.net_force(0.0, R0, T.T_AVG, T.TO), T.net_force(Vlo, R0, T.T_AVG, T.TO)
    check("P6d F0", f0, 24421, tol=0.5)
    check("P6d F1", f1, 21338, tol=0.5)
    check("P6d F(V/sqrt2) is the mean", T.net_force(Vlo / np.sqrt(2), R0, T.T_AVG, T.TO), (f0 + f1) / 2, tol=1e-6)
    dl = (f0 - f1) / (f0 + f1)
    check("P6d delta", dl, 0.067, tol=5e-4)
    check("P6d error (%)", 100 * dl**2 / 3, 0.15, tol=0.005)
    lm = (f0 - f1) / np.log(f0 / f1)
    check("P6d exact = Hull closed form (ft)", T.M * Vlo**2 / (2 * lm) / FT, BASE["ground"] / FT, tol=1e-6)
    check("P6d exact (ft)", BASE["ground"] / FT, 1841, tol=0.5)
    check("P6d rule (ft)", T.M * Vlo**2 / (f0 + f1) / FT, 1838, tol=0.5)
    check("P6d half: estimate (%)", 100 * (1 / 3)**2 / 3, 3.7, tol=0.05)
    r = 0.5
    check("P6d half: LM", (1 - r) / np.log(1 / r), 0.7213, tol=5e-5)
    check("P6d half: shown ratio", 0.7213 / 0.75, 0.962, tol=5e-4)
    check("P6d half: ratio", (1 - r) / np.log(1 / r) / 0.75, 0.962, tol=5e-4)
    check("P6d half: error (%)", 100 * (1 - (1 - r) / np.log(1 / r) / 0.75), 3.8, tol=0.05)
    fv = T.net_force(Vlo / np.sqrt(3), R0, T.T_AVG, T.TO)
    check("P6e force at V/sqrt3", fv, 23393, tol=0.5)
    check("P6e V_LO", Vlo, 65.93, tol=0.005)
    check("P6e m", T.M, 5897, tol=0.5)
    check("P6e exact time", BASE["t_ground"], 16.65, tol=0.005)
    check("P6e rule time", T.M * Vlo / fv, 16.62, tol=0.005)


def slope_or_wind():
    """Guided derivation 7: uphill into the wind, or downhill with it?"""
    from scipy.optimize import brentq
    om, s_, Vl, w = sp.symbols("omega s V w", positive=True)
    lhs = sp.series(2 * (sp.log(1 + om) - sp.log(1 - om)), om, 0, 2).removeO()
    rhs = sp.series(sp.log(1 + s_) - sp.log(1 - s_), s_, 0, 2).removeO()
    sym_zero("P7b ln left", lhs - 4 * om)
    sym_zero("P7b ln right", rhs - 2 * s_)
    sym_zero("P7b kinetic saving", sp.series(Vl**2 / 2 - (Vl - w)**2 / 2, w, 0, 2).removeO() - Vl * w)
    x0, Vlo = BASE["ground"], BASE["vlo"]
    check("P7c x0", x0, 561.0, tol=0.05)
    check("P7c V_LO", Vlo, 65.93, tol=0.005)
    bal = lambda th: brentq(lambda ww: T.takeoff(R0, headwind=ww, slope=th)["ground"] - T.takeoff(R0, headwind=-ww, slope=-th)["ground"], 0.01, 30)
    th2 = np.arctan(0.02)
    check("P7c sin", np.sin(th2), 0.0200, tol=5e-5)
    ws = G0 * x0 * np.sin(th2) / Vlo
    check("P7c w*", ws, 1.67, tol=0.005)
    check("P7c full balance", bal(th2), 1.71, tol=0.005)
    sv = 2 * G0 * x0 * np.sin(th2) / Vlo**2
    check("P7c s", sv, 0.0506, tol=5e-5)
    check("P7c omega", 5 / Vlo, 0.0758, tol=5e-5)
    up = x0 * (1 - 5 / Vlo)**2 / (1 - sv); dn = x0 * (1 + 5 / Vlo)**2 / (1 + sv)
    check("P7c rule up", up, 505, tol=0.5)
    check("P7c rule down", dn, 618, tol=0.5)
    check("P7c full up", T.takeoff(R0, headwind=5.0, slope=th2)["ground"], 507, tol=0.5)
    check("P7c full down", T.takeoff(R0, headwind=-5.0, slope=-th2)["ground"], 616, tol=0.5)
    check("P7c difference", dn - up, 110, tol=5)
    th12 = np.arctan(0.12)
    check("P7d sin", np.sin(th12), 0.1191, tol=5e-5)
    check("P7d w*", G0 * x0 * np.sin(th12) / Vlo, 9.9, tol=0.05)
    check("P7d full balance", bal(th12), 10.4, tol=0.05)



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
    F0_, c_, m_, Vl = sp.symbols("F_0 c m V", positive=True)
    v = sp.symbols("v", positive=True)
    tg = m_ / sp.sqrt(F0_ * c_) * sp.atanh(v * sp.sqrt(c_ / F0_))
    sym_zero("E26 time antiderivative", sp.simplify(sp.diff(tg, v) - m_ / (F0_ - c_ * v**2)))
    f0, f1, Vlo = T.net_force(0.0, R0, T.T_AVG, T.TO), T.net_force(BASE["vlo"], R0, T.T_AVG, T.TO), BASE["vlo"]
    cc = (f0 - f1) / Vlo**2
    check("E26 time for Hull's jet", T.M / np.sqrt(f0 * cc) * np.arctanh(Vlo * np.sqrt(cc / f0)), 16.65, tol=0.005)

if __name__ == "__main__":
    run([objective, fuel, vinh, wind, run_scaling, bfl, seven_tenths, slope_or_wind, earlier_papers])
