"""Checks every number and formula in the answers and solutions of 39-lateral-stability-questions.qmd,
including the guided derivations 4-7.
Run from anywhere:  python3 codes/39-lateral-stability-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 _stab as S
import _lat as L
from flight import lateral as LA
from flight.constants import DEG

PAGE = os.path.join(HERE, "..", "39-lateral-stability-questions.qmd")


def objective():
    q = Objective(PAGE, 12)
    q.num(6, LA.dihedral_alpha_change(10 * DEG, 4 * DEG) / DEG, "0.7^\\circ", x=0.7)
    check("Q6 beta", 10 * DEG, 0.1745, tol=5e-5)
    check("Q6 gamma", 4 * DEG, 0.0698, tol=5e-5)
    check("Q6 rad", 10 * DEG * 4 * DEG, 0.0122, tol=5e-5)
    q.num(8, np.sqrt(2), "\\sqrt2", x=1.4142)
    q.num(9, LA.cn_beta_vertical_tail(0.06, 0.9, 3.0, 0.1), "0.178")
    q.num(11, 30 * 0.08 / 0.2, "12")
    q.num(12, LA.crosswind_sideslip(10, 60) / DEG, "9.6^\\circ", x=9.6)


def drill1():
    v = LA.minimum_control_speed(25e3, 4.5, 1.225, 60, 27, -0.080, 25 * DEG)
    check("D1 delta max (rad)", 25 * DEG, 0.4363, tol=5e-5)
    check("D1 V^2", v ** 2, 3248, tol=0.6)
    check("D1 V", v, 57.0, tol=0.05)
    check("D1b", LA.minimum_control_speed(30e3, 4.5, 1.225, 60, 27, -0.080, 25 * DEG), 62.4, tol=0.05)
    check("D1c", LA.minimum_control_speed(25e3, 4.5, 1.225, 60, 27, -0.096, 25 * DEG), 52.0, tol=0.05)


def drill2():
    b, da, dr, phi = L.crosswind(S.NAVION, 10.0)
    check("D2 V", L.condition(S.NAVION)[0], 53.8, tol=0.05)
    check("D2 beta deg", b / DEG, 10.7, tol=0.05)
    check("D2 beta rad", b, 0.1871, tol=5e-5)
    check("D2 rhs roll", 0.074 * b, 0.01384, tol=5e-6)
    check("D2 rhs yaw", -0.071 * b, -0.01328, tol=5e-6)
    check("D2 rudder", dr / DEG, 10.5, tol=0.05)
    check("D2 rudder rad", dr, 0.1824, tol=1e-4)
    check("D2 aileron", da / DEG, 2.4, tol=0.05)
    check("D2 C_Y", -0.564 * b + 0.157 * dr, -0.0769, tol=5e-5)
    check("D2 bank", phi / DEG, 11.0, tol=0.05)
    check("D2b", L.crosswind(L.NAVION_ALT, 10.0)[1] / DEG, -5.1, tol=0.05)


def extension():
    cr, b, lam, y, a, G = sp.symbols("c_r b lambda y a G", positive=True)
    c = cr * (1 - (1 - lam) * 2 * y / b)
    I = sp.integrate(c * y, (y, 0, b / 2))
    sym_zero("E3a integral", sp.simplify(I - cr * b ** 2 * (1 + 2 * lam) / 24))
    area = 2 * sp.integrate(c, (y, 0, b / 2))
    sym_zero("E3a area", sp.simplify(area - cr * b * (1 + lam) / 2))
    clb = -2 * a * G * I / (area * b)
    sym_zero("E3a result", sp.simplify(clb + a * G * (1 + 2 * lam) / (6 * (1 + lam))))
    sym_zero("E3b untapered", sp.simplify(clb.subs(lam, 1) + a * G / 4))
    check("E3c", float(clb.subs({a: 4.67, G: 2.5 * DEG, lam: 0.5})), -0.045, tol=5e-4)
    check("E3d", 4 * 0.1 / 4.5, 0.089, tol=5e-4)
    check("E3d deg", 4 * 0.1 / 4.5 / DEG, 5.1, tol=0.05)


def roll_rate():
    """Guided derivation 4: roll damping and the helix angle."""
    y, b, c, a, p, V, q, tau, y1, y2 = sp.symbols("y b c a p V q tau y_1 y_2", positive=True)
    Lr = -sp.integrate(q * c * a * p * y / V * y, (y, -b / 2, b / 2))
    sym_zero("P4a rolling moment", Lr + q * a * p * c * b**3 / (12 * V))
    Cl = Lr / (q * c * b * b)
    sym_zero("P4a C_lp = -a/6", sp.diff(Cl, p) * 2 * V / b + a / 6)
    cld = 2 * a * tau / (c * b * b) * sp.integrate(c * y, (y, y1, y2))
    sym_zero("P4b C_l_da", cld - a * tau * (y2**2 - y1**2) / b**2)
    hel = 1.5 * 0.5 * (1 - 0.36) * np.radians(15)
    check("P4c helix angle", hel, 0.126)
    check("P4c engine aileron derivative consistent", LA.aileron_cl_rectangular(5.0, 0.5, 1.0, 0.6 * 5.0, 5.0, 10.0, 10.0) / (5.0 / 6) * np.radians(15), hel, rel=1e-9)
    pr = hel * 2 * 50 / 10.47
    check("P4c roll rate (rad/s)", pr, 1.20)
    check("P4c roll rate (deg/s)", np.degrees(pr), 69)


def weathercock():
    """Guided derivation 5: the weathercock swing."""
    q = 0.5 * 1.225 * 55**2
    check("P5c q", q, 1853, tol=0.5)
    w = np.sqrt(q * 17 * 10.2 * 0.07 / 2700)
    check("P5c omega", w, 2.89)
    check("P5c period", 2 * np.pi / w, 2.18)
    check("P5c omega at 100 m/s", w * 100 / 55, 5.25)
    check("P5c period at 100 m/s", 2 * np.pi / (w * 100 / 55), 1.20)


def bank_for_vmc():
    """Guided derivation 6: why the pilot banks towards the live engine."""
    b_, cyb, cnb, cydr, cndr, CW, ph, Tye, q, S_, W, dm = sp.symbols("b c_yb c_nb c_ydr c_ndr C_W phi Tye q S W d_m", positive=True)
    beta, dr = sp.symbols("beta delta_r", real=True)
    # magnitudes: C_yb = -cyb, C_ndr = -cndr; delta_r = -d_m at the stop
    sol = sp.solve([-cyb * beta + cydr * (-dm) + W / (q * S_) * sp.sin(ph),
                    cnb * beta - cndr * (-dm) - Tye / (q * S_ * b_)], [beta, q], dict=True)[0]
    Ne = cndr - cnb * cydr / cyb
    sym_zero("P6b q_mc", sp.simplify(sol[q] - (Tye - b_ * cnb * W * sp.sin(ph) / cyb) / (S_ * b_ * dm * Ne)))
    Sn, bn, ye, T, cn_dr, dmax, rho = 60.0, 27.0, 4.5, 25e3, 0.080, np.radians(25), 1.225
    c_yb, c_nb, c_ydr, Wn = 0.60, 0.06, 0.20, 150e3
    ne = cn_dr - c_nb * c_ydr / c_yb
    qmc = lambda p_: (T * ye - bn * c_nb * Wn * np.sin(p_) / c_yb) / (Sn * bn * dmax * ne)
    V = lambda qq: np.sqrt(2 * qq / rho)
    check("P6c N_e", ne, 0.0600, tol=5e-5)
    check("P6c shown chain", 25000 * 4.5 / (60 * 27 * 0.4363 * 0.0600), 2653, tol=0.5)
    check("P6c delta_max (rad)", dmax, 0.4363, tol=5e-5)
    check("P6c q wings level", qmc(0.0), 2653, tol=0.5)
    check("P6c V wings level", V(qmc(0.0)), 65.8, tol=0.05)
    truth("P6c beta < 0 wings level", -c_ydr * dmax / c_yb < 0)
    q0 = T * ye / (Sn * bn * dmax * cn_dr)
    check("P6c note's V_mc", V(q0), 57.0, tol=0.05)
    check("P6c 15 % more", 100 * (V(qmc(0.0)) / V(q0) - 1), 15, tol=0.5)
    check("P6d q at 57.0", q0, 1989, tol=0.5)
    cw0 = Wn / (q0 * Sn)
    check("P6d C_W", cw0, 1.257, tol=5e-4)
    check("P6d C_ydr dmax", c_ydr * dmax, 0.0873, tol=5e-5)
    p0 = np.arcsin(c_ydr * dmax / cw0)
    check("P6d zero-sideslip bank", np.degrees(p0), 3.98, tol=0.005)
    check("P6d gives the note's q back", qmc(p0), q0, tol=1e-6)
    q5 = qmc(np.radians(5))
    check("P6d q at 5 deg", q5, 1820, tol=0.5)
    check("P6d V at 5 deg", V(q5), 54.5, tol=0.05)
    cw5 = Wn / (q5 * Sn)
    check("P6d C_W at 5 deg", cw5, 1.373, tol=5e-4)
    check("P6d beta at 5 deg", np.degrees((cw5 * np.sin(np.radians(5)) - c_ydr * dmax) / c_yb), 3.1, tol=0.05)


def fin_sizing():
    """Guided derivation 7: what sizes the fin?"""
    T, ye, rho, S_, b, dm, V, eta, cla, tau = sp.symbols("T y_e rho S b d_m V eta C_La tau", positive=True)
    Vv = 2 * T * ye / (rho * S_ * b * dm * V**2 * eta * cla * tau)
    cndr = 2 * T * ye / (rho * S_ * b * V**2 * dm)
    sym_zero("P7a fin volume", sp.simplify(eta * Vv * cla * tau - cndr))
    Tn, yn, rn, Sn, bn, dmn = 25e3, 4.5, 1.225, 60.0, 27.0, np.radians(25)
    e_, c_, t_, sb = 0.95, 3.0, 0.5, 0.1
    vv = lambda Vm, y=yn: 2 * Tn * y / (rn * Sn * bn * dmn * Vm**2) / (e_ * c_ * t_)
    check("P7a |C_ndr|", 2 * Tn * yn / (rn * Sn * bn * dmn * 57.0**2), 0.0800, tol=5e-5)
    check("P7a factor", e_ * c_ * t_, 1.425, tol=5e-4)
    check("P7a V_v", vv(57.0), 0.0561, tol=5e-5)
    vs = (0.06 + 0.10) / (e_ * c_ * (1 + sb))
    check("P7b V_v stability", vs, 0.0510, tol=5e-5)
    v50 = vv(50.0)
    check("P7c V_v", v50, 0.0729, tol=5e-5)
    check("P7c scaling", 0.0561 * (57.0 / 50)**2, 0.0729, tol=5e-5)
    check("P7c +30 %", 100 * (v50 / vv(57.0) - 1), 30, tol=0.5)
    check("P7c +43 %", 100 * (v50 / vs - 1), 43, tol=0.5)
    check("P7c total C_nbeta", e_ * v50 * c_ * (1 + sb) - 0.10, 0.129, tol=5e-4)
    check("P7d inboard", vv(50.0, 3.5), 0.0567, tol=5e-5)
    check("P7d scaling", 0.0729 * 3.5 / 4.5, 0.0567, tol=5e-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
    L_, b_ = sp.symbols("Lambda beta")
    expr = -(sp.cos(L_ - b_)**2 - sp.cos(L_ + b_)**2) / (8 * sp.cos(L_)**2)
    sym_zero("E39 exact sweep form", sp.simplify(sp.expand_trig(expr + sp.sin(2 * L_) * sp.sin(2 * b_) / (8 * sp.cos(L_)**2))))
    sym_zero("E39 linearised", sp.simplify(sp.series(expr, b_, 0, 2).removeO() + b_ * sp.tan(L_) / 2))
    yaw = (sp.cos(L_) + b_ * sp.sin(L_))**2 - (sp.cos(L_) - b_ * sp.sin(L_))**2
    sym_zero("E39 yaw difference", sp.simplify(yaw / 2 - b_ * sp.sin(2 * L_)))
    check("E39 aileron over rudder", 2 * 0.5 / (np.pi * 0.8 * 8), 0.05, tol=5e-3)
    AR = 1 / 0.12
    dCD = 4 * 25 * np.radians(10) * np.radians(5) / (np.pi * 0.7 * AR)            # per unit tau
    y = sp.symbols("y")
    check("E39 integral", float(sp.integrate(y, (y, sp.Rational(1, 4), sp.Rational(3, 8)))), 5 / 128, tol=1e-12)
    check("E39 AR", AR, 8.33, tol=0.005)
    check("E39 Cn_a/tau", dCD * 5 / 128, 0.00325, tol=5e-6)
    check("E39 rudder (rad)", dCD * 5 / 128 / 0.03, 0.108, tol=5e-4)
    check("E39 rudder (deg)", np.degrees(dCD * 5 / 128 / 0.03), 6.2, tol=0.05)

if __name__ == "__main__":
    run([objective, drill1, drill2, extension, roll_rate, weathercock, bank_for_vmc, fin_sizing, earlier_papers])
