"""Checks every number in the answers and solutions of 07-flat-earth-questions.qmd,
including the guided derivations 4-7.
Run from anywhere:  python3 codes/07-flat-earth-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.integrate import solve_ivp
from _verify import check, truth, sym_zero, Objective, run
from flight import vehicle, wind, atmosphere
from flight.constants import G0, DEG

PAGE = os.path.join(HERE, "..", "07-flat-earth-questions.qmd")


from flight.performance import climb_angle, climb_angle_small, level_turn, best_glide, speed_for_cl


def objective():
    """The 12 objective questions."""
    q = Objective(PAGE, 12)
    q.num(5, 30 * 1.5, "45")
    q.num(6, 1 / np.cos(60 * DEG), "2", tol=1e-9)
    w, _, _ = level_turn(150.0, 45 * DEG)
    q.num(7, np.degrees(w), "3.75")
    check("Q7 in rad/s", w, 0.065, tol=0.0005)
    g = climb_angle(0.30, 12)
    check("Q8 first guess (deg)", np.degrees(climb_angle_small(0.30, 12)), 12.51)
    check("Q8 exact (deg)", np.degrees(g), 12.63)
    q.num(8, 100 * np.sin(g), "21.9")
    check("Q8 small-angle distractor", 100 * (0.30 - 1 / 12), 21.7)
    check("Q10 speed ratio", np.sqrt(1.21), 1.10)
    q.num(12, (125 * (1 / 210 + 1 / 290) - 1) * 100, "2.6")
    check("Q12 ratio", 125 * (1 / 210 + 1 / 290), 1.026)


def kiran():
    """Drill 1: a Kiran climbs out."""
    v = vehicle.load("hjt-16-kiran")
    E = 1 / (2 * np.sqrt(v.aero.cd0(0.3) * v.aero.k(0.3)))
    check("P1 E_max of the dataset polar", E, 12.7)
    tw = 18400 / (4950 * G0)
    check("P1 T/W", tw, 0.379)
    check("P1 first sin(gamma)", tw - 1 / 12.7, 0.300)
    check("P1 first gamma (deg)", np.degrees(np.arcsin(tw - 1 / 12.7)), 17.5)
    g = climb_angle(tw, 12.7)
    check("P1 exact gamma (deg)", np.degrees(g), 17.7)
    check("P1 rate of climb (m/s)", 120 * np.sin(g), 36.5)
    check("P1 time to 3 km (s)", 3000 / (120 * np.sin(g)), 82)


def hansa():
    """Drill 2: a Hansa-3 loses its engine."""
    v = vehicle.load("hansa-3")
    cd0, k, S = v.aero.cd0(0.1), v.aero.k(0.1), v.aero.S
    check("P2 dataset S", S, 12.0)
    check("P2 dataset mass (kg)", v.gross_mass, 750)
    rho = atmosphere.ISA.state(0.0)[2]
    cl, E = best_glide(cd0, k)
    check("P2 C_L*", cl, 0.816)
    check("P2 C_D at C_L*", cd0 + k * cl**2, 0.060)
    check("P2 E_max", E, 13.6)
    V = speed_for_cl(750 * G0, rho, S, cl)
    check("P2 best glide speed (m/s)", V, 35.0)
    ga = np.arctan(1 / E)
    check("P2 glide angle (deg)", np.degrees(ga), 4.2)
    sink = V * np.sin(ga)
    check("P2 sink rate (m/s)", sink, 2.57)
    check("P2 distance (km)", E * 1.5, 20.4)
    check("P2 time (s)", 1500 / sink, 585, tol=1)
    gs = V * np.cos(ga) - 10
    check("P2 ground speed into the wind (m/s)", gs, 24.9)
    check("P2 distance into the wind (km)", 1500 / sink * gs / 1e3, 14.6)


def windshear():
    """Extension 3: a windshear on approach, with the simulator's Windshear model."""
    ws = wind.Windshear(20.0, 0.0, from_deg=0.0, h_top=300.0)       # wind from the north; aircraft heads north
    Wx = lambda h: ws.ned(0.0, h, 0.0, 0.0)[0]                       # north component = along the flight
    check("P3 W_x at 300 m (headwind is negative)", Wx(300.0), -20.0, tol=1e-9)
    check("P3 W_x at the ground", Wx(0.0), 0.0, tol=1e-9)
    dWdh = (Wx(200.0) - Wx(100.0)) / 100.0
    check("P3 dW_x/dh (1/s)", dWdh, -0.0667)
    hdot = 70 * np.sin(-3 * DEG)
    check("P3 h_dot (m/s)", hdot, -3.66)
    Wd = dWdh * hdot
    check("P3 W_x dot (m/s^2)", Wd, 0.244)
    gam = -3 * DEG
    check("P3 speed equation term", -Wd * np.cos(gam), -0.244)
    check("P3 path equation term", Wd * np.sin(gam), -0.0128)
    T = 300 / -hdot
    check("P3 descent time (s)", T, 82)
    check("P3 airspeed lost (m/s)", Wd * np.cos(gam) * T / np.cos(gam), 20.0)
    check("P3 lift ratio at 50 m/s", (50 / 70) ** 2, 0.51)
    check("P3 extra thrust (% of weight)", Wd * np.cos(gam) / G0 * 100, 2.5)


def thrust_tilt():
    """Guided derivation 4: the best thrust inclination."""
    T, W, eps, E, gm = sp.symbols("T W epsilon E gamma", positive=True)
    L = W * sp.cos(gm) - T * sp.sin(eps)
    sym_zero("P4a T(cos e + sin e/E) = W(sin g + cos g/E)",
             (T * sp.cos(eps) - L / E - W * sp.sin(gm)) - (T * (sp.cos(eps) + sp.sin(eps) / E) - W * (sp.sin(gm) + sp.cos(gm) / E)))
    f = sp.cos(eps) + sp.sin(eps) / E
    es = sp.atan(1 / E)
    sym_zero("P4b f'(atan(1/E)) = 0", sp.diff(f, eps).subs(eps, es))
    sym_zero("P4b f max = sqrt(1+1/E^2)", f.subs(eps, es) - sp.sqrt(1 + 1 / E**2))
    sym_zero("P4c f(2 eta) = 1", sp.simplify(f.subs(eps, 2 * es) - 1))
    x = sp.symbols("x", positive=True)
    sym_zero("P4c sqrt(1+x^2) = 1 + x^2/2 + O(x^4)", sp.series(sp.sqrt(1 + x**2), x, 0, 4).removeO() - 1 - x**2 / 2)
    Ev, tau = 12.7, 18400 / (4950 * G0)
    e_ = np.arctan(1 / Ev)
    check("P4d best tilt (deg)", np.degrees(e_), 4.50)
    check("P4d gain (%)", (np.sqrt(1 + 1 / Ev**2) - 1) * 100, 0.31)
    check("P4d T/W", tau, 0.3790)
    check("P4d effective T/W", tau * np.sqrt(1 + 1 / Ev**2), 0.3802)
    check("P4d climb, no tilt (deg)", np.degrees(climb_angle(tau, Ev)), 17.70)
    check("P4d climb, best tilt (deg)", np.degrees(climb_angle(tau * np.sqrt(1 + 1 / Ev**2), Ev)), 17.77)
    check("P4d E = 2: best tilt (deg)", np.degrees(np.arctan(0.5)), 26.6)
    check("P4d E = 2: gain (%)", (np.sqrt(1.25) - 1) * 100, 12, tol=0.5)


def closed_form():
    """Guided derivation 5: the climb angle in closed form."""
    def exact(tau, E):
        return np.arcsin(tau / np.sqrt(1 + 1 / E**2)) - np.arctan(1 / E)
    for tau, E, want in ((0.25, 16, 10.87), (18400 / (4950 * G0), 12.7, 17.70)):
        check(f"P5b closed form tau={tau:.3f}, E={E} (deg)", np.degrees(exact(tau, E)), want)
        check(f"P5b closed form agrees with the engine's root (tau={tau:.3f})", exact(tau, E), climb_angle(tau, E), tol=1e-10)
    check("P5b eta for E=16 (deg)", np.degrees(np.arctan(1 / 16)), 3.576)
    check("P5b tau cos eta", 0.25 / np.sqrt(1 + 1 / 256), 0.24951)
    check("P5b arcsin (deg)", np.degrees(np.arcsin(0.25 / np.sqrt(1 + 1 / 256))), 14.449)
    truth("P5c gamma = 0 exactly at tau = 1/E", abs(exact(1 / 12.7, 12.7)) < 1e-12)
    t, e, k = sp.symbols("tau epsilon k", positive=True)
    g = sp.asin(t / sp.sqrt(1 + e**2)) - sp.atan(e)
    ge = sp.series(g.subs({t: k * t, e: k * e}), k, 0, 4).removeO().subs(k, 1)
    sym_zero("P5d third-order expansion", ge - ((t - e) + (t - e)**3 / 6 + e / 2 * (t - e)**2))
    g1 = sp.series(sp.asin(k * (t - e)), k, 0, 4).removeO().subs(k, 1)
    sym_zero("P5d exact - first guess = eps (tau-eps)^2/2", ge - g1 - e / 2 * (t - e)**2)
    check("P5d the missing term for the trainer (rad)", 0.1875**2 / 32, 1.10e-3)
    check("P5d in degrees", np.degrees(0.1875**2 / 32), 0.063)
    check("P5d first guess (deg)", np.degrees(climb_angle_small(0.25, 16)), 10.81)


def climbing_turn():
    """Guided derivation 6: the helix."""
    V, gm, sg, gg = 120.0, 10 * DEG, 30 * DEG, G0
    w = gg * np.tan(sg) / V
    check("P6d turn rate (rad/s)", w, 0.0472)
    check("P6d turn rate (deg/s)", np.degrees(w), 2.70)
    check("P6d radius (m)", V * np.cos(gm) / w, 2505, tol=1)
    check("P6d time per turn (s)", 2 * np.pi / w, 133)
    check("P6d height per turn (m)", 2 * np.pi * V**2 * np.sin(gm) / (gg * np.tan(sg)), 2775, tol=1)
    check("P6d load factor", np.cos(gm) / np.cos(sg), 1.14)
    tau = 18400 / (4950 * G0)
    check("P6d effective E", 12.7 * np.cos(sg), 11.0)
    gb = climb_angle(tau, 12.7 * np.cos(sg))
    check("P6d steepest climb in the turn (deg)", np.degrees(gb), 17.0)
    check("P6d check: sin g = tau - cos g/(E cos s)", np.sin(gb), tau - np.cos(gb) / (12.7 * np.cos(sg)), tol=1e-12)
    L, W, s_, g_, m, chid, Vs, gs_ = sp.symbols("L W sigma gamma m chidot V g", positive=True)
    sol = sp.solve([L * sp.cos(s_) - W * sp.cos(g_), (W / gs_) * Vs * sp.cos(g_) * chid - L * sp.sin(s_)], [L, chid], dict=True)[0]
    sym_zero("P6a chidot = g tan(sigma)/V", sol[chid] - gs_ * sp.tan(s_) / Vs)


def phugoid():
    """Guided derivation 7: Lanchester's phugoid, linear and nonlinear."""
    s, g, V0, E = sp.symbols("s g V_0 E", positive=True)
    # state (u, gamma): udot = -(2g/(E V0)) u - g gamma, gammadot = 2 g u / V0^2
    A = sp.Matrix([[-2 * g / (E * V0), -g], [2 * g / V0**2, 0]])
    cp = sp.expand((s * sp.eye(2) - A).det())
    sym_zero("P7c characteristic polynomial", cp - (s**2 + 2 * g / (E * V0) * s + 2 * g**2 / V0**2))
    om = sp.sqrt(2) * g / V0
    sym_zero("P7c zeta = 1/(sqrt2 E)", (2 * g / (E * V0)) / (2 * om) - 1 / (sp.sqrt(2) * E))
    for V, Ev, P, z, cyc in ((120.0, 12.7, 54.4, 0.056, 2.0), (230.0, 17.0, 104, 0.042, 2.7)):
        Pl = np.pi * np.sqrt(2) * V / G0
        zl = 1 / (np.sqrt(2) * Ev)
        check(f"P7d period at {V:.0f} m/s (s)", Pl, P)
        check(f"P7d zeta for E={Ev}", zl, z)
        check(f"P7d cycles to halve", np.log(2) / (2 * np.pi * zl), cyc)

        def rhs(t, y):
            u, gm_, h = y
            Vv = V + u
            q = (Vv / V)**2
            return [G0 / Ev * (1 - q) - G0 * np.sin(gm_), G0 / Vv * (q - np.cos(gm_)), Vv * np.sin(gm_)]
        sol = solve_ivp(rhs, (0, 8 * Pl), [2.0, 0.0, 0.0], max_step=0.05, rtol=1e-10, atol=1e-10, dense_output=True)
        tt = np.linspace(0, 8 * Pl, 40001)
        u = sol.sol(tt)[0]
        pk = [i for i in range(1, len(u) - 1) if u[i] > u[i - 1] and u[i] >= u[i + 1]]
        Pn = np.mean(np.diff(tt[pk]))
        check(f"P7 nonlinear period agrees with pi sqrt2 V/g at {V:.0f} m/s (s)", Pn, Pl, rel=0.01)
        dec = np.log(u[pk[0]] / u[pk[-1]]) / (tt[pk[-1]] - tt[pk[0]])
        check(f"P7 nonlinear decay rate agrees with zeta*omega at {V:.0f} m/s", dec, zl * np.sqrt(2) * G0 / V, rel=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
    cl, a, k, c0 = sp.symbols("C_L a k C_D0", positive=True)
    st = sp.sqrt(c0 / k)
    sym_zero("E7 dE/dCL = 0 at sqrt(CD0/k)", sp.simplify(sp.diff(cl / (c0 + a * cl + k * cl**2), cl).subs(cl, st)))
    sym_zero("E7 E_m", sp.simplify((cl / (c0 + a * cl + k * cl**2)).subs(cl, st) - 1 / (a + 2 * sp.sqrt(k * c0))))
    L, D, T, W, al = sp.symbols("L D T W alpha")
    sol = sp.solve([T + L * sp.sin(al) - D * sp.cos(al) - W * sp.sin(al), L * sp.cos(al) + D * sp.sin(al) - W * sp.cos(al)], [L, T], dict=True)[0]
    sym_zero("E7 L = W - D tan(alpha)", sp.simplify(sol[L] - (W - D * sp.tan(al))))

if __name__ == "__main__":
    run([objective, kiran, hansa, windshear, thrust_tilt, closed_form, climbing_turn, phugoid, earlier_papers])
