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

PAGE = os.path.join(HERE, "..", "25-vertical-vn-questions.qmd")


def objective():
    q = Objective(PAGE, 12)
    check("Q1 bottom - top", PF.loop_load_factor(0.0, 50, 100) - PF.loop_load_factor(np.pi, 50, 100), 2.0, tol=1e-12)
    V = 150 * KT
    check("Q4 V", V, 77.2)
    check("Q4 V^2", V**2, 5955, tol=1)
    check("Q4 gR", 9.81 * 300, 2943, tol=0.5)
    q.num(4, 1 + V**2 / (9.81 * 300), "3.02")
    check("Q4 A", V**2 / (9.81 * 300), 2.02)
    V = 130 * KT
    check("Q5 V", V, 66.9)
    check("Q5 V^2", V**2, 4473, tol=1)
    q.num(5, PF.vertical_turn(V, 6.0, g=9.81)[1], "91", x=91)
    check("Q5 A", V**2 / (9.81 * 6), 76)
    check("Q5 D", PF.vertical_turn(V, 6.0, top=True, g=9.81)[1], 65)
    q.num(6, PF.corner_speed(50.0, 4.4), "105", x=105)
    check("Q6 C", 50 * np.sqrt(2.2), 74, tol=0.5)
    q.num(7, PF.far23_limit_load_factors("normal", 5000)[0], "3.7")
    x, h, Vz, g = PF.zero_g_arc(200.0, np.radians(30), 20.394)
    q.num(8, PF.zero_g_time(200.0, np.radians(30)), "20.4")
    check("Q8 back at the entry height", h, 0.0, tol=0.05)
    check("Q8 C", 2 * 200 * np.cos(np.radians(30)) / G0, 35.3)
    q.num(9, PF.loop_load_factor(0.0, np.sqrt(G0 * 100), 100), "2", x=2)
    truth("Q9 0 <= n <= 2 all round", np.all((PF.loop_load_factor(np.linspace(0, 2 * np.pi, 100), np.sqrt(G0 * 100), 100) > -1e-12)))
    k1, m1 = PF.gust_alleviation(2000, RHO0_SL, 2.0, 5.0)
    k2, m2 = PF.gust_alleviation(4000, RHO0_SL, 2.0, 5.0)
    r = (PF.gust_load_factor(100, 10, 4000, 5.0, k2) - 1) / (PF.gust_load_factor(100, 10, 2000, 5.0, k1) - 1)
    check("Q10 ratio a little more than half", r, 0.5 * k2 / k1, rel=1e-12)
    truth("Q10 more than a half", r > 0.5)
    dn = PF.gust_load_factor(100.0, 10.0, 2000.0, 5.0, 1.0) - 1
    check("Q11 increment", dn, 1.53)
    q.num(11, 1 + dn, "2.53")


def loop():
    R = (1525 - 1220) / 2
    check("P1 R", R, 152.5)
    check("P1 V", np.sqrt(G0 * R), 38.7)
    check("P1 n bottom", PF.loop_load_factor(0.0, np.sqrt(G0 * R), R), 2.0, tol=1e-12)


def gust10k():
    F = load("fig-25-vn")
    rho = A.isa(10000 * FT)[2]
    check("P2 rho", rho, 0.905)
    check("P2 span", F.SPAN, 11.63)
    check("P2 chord", F.CHORD, 1.66)
    check("P2 W/S", F.WS, 1167, tol=1)
    kg, mu, g = F.gust_lines(rho)
    check("P2 mu", mu, 25.1)
    check("P2 K_g", kg, 0.727)
    check("P2 U", 50 * FT, 15.24)
    check("P2 V_E", F.VC, 159.5)
    check("P2 n", g["C"][0], 6.84)
    check("P2 sea level", F.G_SL["C"][0], 6.50)
    check("P2 Sadraey 5.33", 1 + 0.02715 * 310 * 0.5144, 5.33)
    check("P2 his mu with rounded values", 2 * 2300 / (0.9 * 1.66 * 6.3 * 19.33), 25.3)


def wing_loading():
    G = load("fig-25-gust")
    h3, tp = G.CASES
    check("P3 HANSA chord", h3["chord"], 1.146)
    check("P3 transport chord", tp["chord"], 7.44)
    check("P3 HANSA mu", h3["mu"], 17.8)
    check("P3 HANSA K_g", h3["kg"], 0.678)
    check("P3 transport mu", tp["mu"], 24.9)
    check("P3 transport K_g", tp["kg"], 0.726)
    U, V = 50 * FT, 100 * KT
    d1 = PF.gust_load_factor(V, U, h3["ws"], h3["a"], h3["kg"]) - 1
    d2 = PF.gust_load_factor(V, U, tp["ws"], tp["a"], tp["kg"]) - 1
    check("P3 HANSA increment", d1, 2.66)
    check("P3 transport increment", d2, 0.31)
    check("P3 ratio", d1 / d2, 8.5)
    check("P3 ratio formula", d1 / d2, (h3["kg"] / tp["kg"]) * tp["ws"] / h3["ws"], rel=1e-12)
    check("P3 wing-loading ratio", tp["ws"] / h3["ws"], 9.1)


def energy_loop():
    """Guided derivation 4: a circular loop at constant energy."""
    th, Vb, g, R = sp.symbols("theta V_b g R", positive=True)
    V2 = Vb**2 - 2 * g * R * (1 - sp.cos(th))
    n = sp.cos(th) + V2 / (g * R)
    sym_zero("P4a n(theta)", n - (3 * sp.cos(th) - 2 + Vb**2 / (g * R)))
    sym_zero("P4b bottom minus top = 6", n.subs(th, 0) - n.subs(th, sp.pi) - 6)
    sym_zero("P4b n_b = 6 when n_t = 0", n.subs(th, 0).subs(Vb, sp.sqrt(5 * g * R)) - 6)
    v = np.sqrt(5 * G0 * 500)
    check("P4c least entry speed (m/s)", v, 156.6)
    check("P4c in km/h", v * 3.6, 564)


def parabola():
    """Guided derivation 5: the longest weightless parabola."""
    Vmax, Vmin = 180.0, 110.0
    t = 2 / G0 * np.sqrt(Vmax**2 - Vmin**2)
    check("P5c t_max (s)", t, 29.1)
    gm = np.arccos(Vmin / Vmax)
    check("P5c entry angle (deg)", np.degrees(gm), 52.3)
    check("P5c vertical speed", Vmax * np.sin(gm), 142.5)
    check("P5c climb (km)", (Vmax * np.sin(gm))**2 / (2 * G0) / 1e3, 1.04)
    gs = np.linspace(0.01, gm, 20001)
    check("P5b the limit gives the longest time", np.max(2 * Vmax * np.sin(gs) / G0), t, tol=1e-6)


def pull_out():
    """Guided derivation 6: how much height a pull-out costs."""
    from scipy.integrate import solve_ivp
    d, d0, n, V, Q, z = sp.symbols("delta delta_0 n V Q z", positive=True)
    gs = sp.symbols("g", positive=True)
    sym_zero("P6a antiderivative", sp.diff(sp.log(n - sp.cos(d)), d) - sp.sin(d) / (n - sp.cos(d)))
    ser = sp.series(sp.log(1 + z), z, 0, 2).removeO()
    sym_zero("P6b first term", ser - z)
    sym_zero("P6c (Q^2-1)/2 - ln Q has derivative Q - 1/Q", sp.diff((Q**2 - 1) / 2 - sp.log(Q), Q) - (Q - 1 / Q))
    G = 9.80665
    check("P6d V0^2/g", 150**2 / G, 2294, tol=0.5)

    def ode(V0, nn, dd, energy):
        def f(t, y):
            Vn = np.sqrt(V0**2 + 2 * G * y[1]) if energy else V0
            return [-(G / Vn) * (nn - np.cos(y[0])), Vn * np.sin(y[0])]
        ev = lambda t, y: y[0]; ev.terminal = True
        sol = solve_ivp(f, (0, 100), [np.radians(dd), 0.0], events=ev, rtol=1e-11, atol=1e-9)
        return sol.y_events[0][0][1]
    for dd, q, sc, circ, se, vf in ((60, 1.125, 270, 287, 305, 169), (90, 1.25, 512, 574, 645, 188)):
        Qn = (5 - np.cos(np.radians(dd))) / 4
        check(f"P6d Q {dd}", Qn, q, tol=5e-4)
        a = 150**2 / G * np.log(Qn)
        check(f"P6d constant speed {dd}", a, sc, tol=0.5)
        check(f"P6d constant speed ODE {dd}", ode(150, 5, dd, False), a, tol=1e-4)
        check(f"P6d bottom circle {dd}", 150**2 / (G * 4) * (1 - np.cos(np.radians(dd))), circ, tol=0.5)
        b = 150**2 / (2 * G) * (Qn**2 - 1)
        check(f"P6d constant energy {dd}", b, se, tol=0.5)
        check(f"P6d constant energy ODE {dd}", ode(150, 5, dd, True), b, tol=1e-4)
        check(f"P6d final speed {dd}", 150 * Qn, vf, tol=0.5)
    r = np.log(5.5 / 5) / np.log(4.5 / 4)
    check("P6d 6g saves about a fifth (60 deg)", 1 - r, 0.2, tol=0.015)


def half_loop():
    """Guided derivation 7: turning round over the top or on the level."""
    from scipy.integrate import quad
    th, n, s = sp.symbols("theta n s", positive=True)
    mm = sp.symbols("m", positive=True)                    # n = 1 + m > 1
    n = 1 + mm
    anti = 2 / sp.sqrt((n - 1) * (n + 1)) * sp.atan(s * sp.sqrt((n + 1) / (n - 1)))
    sym_zero("P7a antiderivative", sp.simplify(sp.diff(anti, s) - 2 / ((n - 1) + (n + 1) * s**2)))
    sym_zero("P7a integral", sp.simplify(sp.limit(anti, s, sp.oo) - sp.pi / sp.sqrt(n**2 - 1)))
    n = sp.symbols("n", positive=True)
    sym_zero("P7a substitution", sp.simplify((1 / (n - sp.cos(th))).subs(th, 2 * sp.atan(s)) * sp.diff(2 * sp.atan(s), s) - 2 / ((n - 1) + (n + 1) * s**2)))
    sym_zero("P7c height antiderivative", sp.diff(sp.log(n - sp.cos(th)), th) - sp.sin(th) / (n - sp.cos(th)))
    sym_zero("P7c cos identity", sp.cos(th) / (n - sp.cos(th)) - (-1 + n / (n - sp.cos(th))))
    lim1 = sp.limit(n * sp.log((n + 1) / (n - 1)), n, sp.oo); lim2 = sp.limit(n * 2 / sp.sqrt(n**2 - 1), n, sp.oo)
    sym_zero("P7c large n", lim1 - lim2)
    g, V, nn = 9.80665, 150.0, 4.0
    for k in (2.0, 4.0, 7.0):
        check(f"P7a quad n={k}", quad(lambda a: 1 / (k - np.cos(a)), 0, np.pi)[0], np.pi / np.sqrt(k * k - 1), tol=1e-10)
    check("P7d V^2/g", V**2 / g, 2294, tol=0.5)
    check("P7d time", np.pi * V / (g * np.sqrt(15)), 12.4, tol=0.05)
    check("P7d height", V**2 / g * np.log(5 / 3), 1172, tol=0.5)
    check("P7d forward", V**2 / g * np.pi * (4 / np.sqrt(15) - 1), 236, tol=0.5)
    check("P7d diameter", 2 * V**2 / (g * np.sqrt(15)), 1185, tol=0.5)
    xq = quad(lambda a: V * np.cos(a) * V / (g * (nn - np.cos(a))), 0, np.pi)[0]
    check("P7c forward by quadrature", xq, V**2 / g * np.pi * (4 / np.sqrt(15) - 1), tol=1e-6)


if __name__ == "__main__":
    run([objective, loop, gust10k, wing_loading, energy_loop, parabola, pull_out, half_loop])
