"""Checks every number and formula in the answers and solutions of 38-manoeuvre-point-questions.qmd,
including the guided derivations 4-7.
Run from anywhere:  python3 codes/38-manoeuvre-point-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
from flight import stability as ST, vehicle
from flight.constants import DEG, G0

PAGE = os.path.join(HERE, "..", "38-manoeuvre-point-questions.qmd")


def objective():
    q = Objective(PAGE, 12)
    q.num(8, ST.manoeuvre_point_from_derivatives(0.45, 4, -10, 0.005), "0.501")
    q.num(9, ST.level_turn_pitch_rate(2.0, 1.0, 1.0), "1.5", x=1.5)
    check("Q6: halving density about halves the margin", ST.manoeuvre_point_from_derivatives(0.0, 4, -10, 0.0025) /
          ST.manoeuvre_point_from_derivatives(0.0, 4, -10, 0.005), 0.5, tol=0.01)


def drill1():
    t = ST.Tail(3.5, 0.2, 3.2, tau=0.5, eta=0.9)
    kap = ST.mass_parameter(1.225, 17, 1.6, 1500)
    check("D1 kappa", kap, 0.00555, tol=5e-6)
    check("D1 V_H", ST.tail_volume(t, 0.30), 0.580, tol=5e-4)
    clq, cmq = ST.pitch_rate_derivatives(t, 0.30)
    check("D1 CLq", clq, 3.65, tol=5e-3)
    check("D1 Cmq", cmq, -10.6, tol=0.05)
    xm = ST.manoeuvre_point_from_derivatives(0.457, clq, cmq, kap)
    check("D1 mp", xm, 0.517, tol=5e-4)
    check("D1 shift", xm - 0.457, 0.060, tol=5e-4)
    check("D1 cm", (xm - 0.457) * 160, 9.6, tol=0.06)
    qh = ST.nondimensional_rate(ST.pull_up_rate(3, 70, G0), 1.6, 70)
    check("D1 qhat", qh, 0.00320, tol=5e-6)
    term = 2 * 2.9 * qh / 0.5
    check("D1 term rad", term, 0.0371, tol=5e-5)
    check("D1 term deg", term / DEG, 2.13, tol=5e-3)


def drill2():
    check("D2 n", 1 + (1.96 + 20) / 3.68, 6.97, tol=5e-3)
    check("D2 lift coefficient", 7 * 0.299, 2.1, tol=0.05)
    lim = vehicle.load("sbj-hull").info["limits"]
    check("D2 structural limit", lim["n_lim"], 4.5, tol=1e-12)
    check("D2 C_Lmax", vehicle.load("sbj-hull").aero.clmax(0.6), 1.24, tol=1e-12)


def extension():
    # a pitch-rate feedback k_q adds C_mde k_q to C_mq and moves the manoeuvre point aft
    t = S.TAIL
    clq, cmq = ST.pitch_rate_derivatives(t, 0.30)
    cld = ST.lift_coefficients(S.WING, t)[2]
    cmd = ST.tail_moment(t, 0.30)[2]
    base = ST.manoeuvre_point_from_derivatives(0.512, clq, cmq, 0.001)
    fed = ST.manoeuvre_point_from_derivatives(0.512, clq + cld * 5, cmq + cmd * 5, 0.001)
    truth("E3 positive k_q adds damping and moves the manoeuvre point aft", cmq + cmd * 5 < cmq and fed > base)


def short_period():
    """Guided derivation 4: the short period and the manoeuvre margin."""
    import sympy as sp
    s, a, Ma, Mq = sp.symbols("s a M_alpha M_q", real=True)
    A = sp.Matrix([[-a, 1], [Ma, Mq]])
    cp = sp.expand((s * sp.eye(2) - A).det())
    truth("P4a characteristic polynomial", sp.simplify(cp - (s**2 + (a - Mq) * s - (Ma + a * Mq))) == 0)
    m, S_, c, I, V, rho = 1250.0, 17.0, 1.7, 4000.0, 55.0, 1.225
    CLa, Cma, Cmq = 4.4, -0.68, -10.0
    qb = 0.5 * rho * V * V
    av = qb * S_ * CLa / (m * V)
    Mav = qb * S_ * c * Cma / I
    Mqv = qb * S_ * c * c * Cmq / (2 * V * I)
    kap = ST.mass_parameter(rho, S_, c, m)
    check("P4c kappa", kap, 0.00708)
    check("P4c static margin", -Cma / CLa, 0.155)
    check("P4c mp - np", -kap * Cmq, 0.071)
    check("P4c manoeuvre margin", -Cma / CLa - kap * Cmq, 0.225)
    check("P4c manoeuvre point from the engine (C_Lq = 0)", ST.manoeuvre_point_from_derivatives(0.0, 0.0, Cmq, kap), -kap * Cmq, tol=1e-12)
    check("P4c a", av, 2.02)
    check("P4c M_alpha", Mav, -9.10)
    check("P4c M_q", Mqv, -2.07)
    w2 = -(Mav + av * Mqv)
    check("P4c omega^2", w2, 13.27)
    check("P4b omega^2 from the margin", qb * S_ * c * CLa / I * (-Cma / CLa - kap * Cmq), w2, rel=1e-12)
    w = np.sqrt(w2)
    check("P4c omega", w, 3.64)
    check("P4c period", 2 * np.pi / w, 1.72)
    check("P4c zeta", (av - Mqv) / (2 * w), 0.56)


def turn_mp():
    """Guided derivation 5: the manoeuvre point in a turn."""
    import sympy as sp
    n, k = sp.symbols("n k", positive=True)
    truth("P5a dqhat/dn in a turn", sp.simplify(sp.diff(k * (n - 1 / n), n) - k * (1 + 1 / n**2)) == 0)
    kap, cmq = 0.00708, -10.0
    check("P5c pull-up", ST.manoeuvre_point_from_derivatives(0.0, 0.0, cmq, kap), 0.071)
    check("P5c turn near 1 g", ST.manoeuvre_point_from_derivatives(0.0, 0.0, cmq, 2 * kap), 0.142)
    check("P5c turn at 2 g", ST.manoeuvre_point_from_derivatives(0.0, 0.0, cmq, 1.25 * kap), 0.089)


def downwash_lag():
    """Guided derivation 6: the downwash that arrives late."""
    t, l, V, ea, xH, xc, cb = sp.symbols("t l V epsilon_alpha x_H x_cg cbar", positive=True)
    al = sp.Function("alpha")
    tay = sp.series(sp.Function("alpha")(t - sp.Symbol("h")), sp.Symbol("h"), 0, 2).removeO().doit()
    sym_zero("P6a first-order delay", sp.simplify(tay.subs(sp.Symbol("h"), l / V) - (al(t) - l / V * sp.diff(al(t), t))))
    ad = sp.symbols("alphadot")
    sym_zero("P6a nondimensional form", ea * ad * (xH - xc) * cb / V - 2 * (xH - xc) * ea * (ad * cb / (2 * V)))
    a, Ma, Mq, Mad, s_ = sp.symbols("a M_alpha M_q M_alphadot s")
    A = sp.Matrix([[-a, 1], [Ma - a * Mad, Mq + Mad]])
    sym_zero("P6c characteristic equation", sp.expand(A.charpoly(s_).as_expr() - (s_**2 + (a - Mq - Mad) * s_ - (Ma + a * Mq))))
    check("P6a C_L_alphadot", 0.42 * 4.44, 1.86, tol=0.005)
    check("P6a C_m_alphadot", 0.42 * -11.68, -4.91, tol=0.005)
    m, S, c, Iy, CLa, Cma, Cmq, V0, rho = 1250, 17, 1.7, 4000, 4.4, -0.68, -10.0, 55.0, 1.225
    Q = 0.5 * rho * V0**2
    an = Q * S * CLa / (m * V0); Man = Q * S * c * Cma / Iy; Mqn = Q * S * c**2 * Cmq / (2 * V0 * Iy)
    Madn = Q * S * c**2 * (0.40 * Cmq) / (2 * V0 * Iy)
    check("P6d C_m_alphadot", 0.40 * Cmq, -4, tol=0)
    check("P6d M_alphadot", Madn, -0.83, tol=0.005)
    check("P6d = 0.4 M_q", Madn, 0.4 * Mqn, tol=1e-12)
    check("P6d a", an, 2.016, tol=5e-4)
    check("P6d M_q", -Mqn, 2.069, tol=5e-4)
    check("P6d M_alphadot 3 d.p.", -Madn, 0.828, tol=5e-4)
    w = np.sqrt(-(Man + an * Mqn))
    check("P6d omega", w, 3.643, tol=5e-4)
    z1 = (an - Mqn - Madn) / (2 * w)
    check("P6d zeta", z1, 0.67, tol=0.005)
    check("P6d shown chain", (2.016 + 2.069 + 0.828) / (2 * 3.643), 0.67, tol=0.005)
    check("P6d zeta before", (an - Mqn) / (2 * w), 0.56, tol=0.005)
    ev = np.linalg.eigvals(np.array([[-an, 1], [Man - an * Madn, Mqn + Madn]]))
    check("P6d frequency unchanged", abs(ev[0]), w, tol=1e-9)
    check("P6d share of damping", -Madn / (an - Mqn - Madn), 1 / 6, tol=0.01)


def free_manoeuvre_point():
    """Guided derivation 7: the manoeuvre point with the stick free."""
    da, cha, chd, tau, cla = sp.symbols("Delta_alpha C_ha C_hd tau C_LaH")
    dde = -cha / chd * da
    sym_zero("P7a factor f", sp.expand(cla * (da + tau * dde) - cla * (1 - tau * cha / chd) * da))
    f = ST.free_elevator_factor(S.TAIL, S.HINGE)
    check("P7 f", f, 0.783, tol=5e-4)
    ft = ST.free_tail(S.TAIL, S.HINGE)
    xnpf = ST.neutral_point(S.WING, ft)
    check("P7 stick-free np", xnpf, 0.461, tol=5e-4)
    clq, cmq = ST.pitch_rate_derivatives(S.TAIL, 0.30)
    check("P7 C_Lq", clq, 4.44, tol=0.005)
    check("P7 C_mq", cmq, -11.68, tol=0.005)
    res = {}
    for k, ap, ex, fx in ((0.00106, 0.471, 0.469, 0.522), (0.00282, 0.487, 0.483, 0.539)):
        check(f"P7b approx {k}", 0.461 - f * cmq * k / (1 - f * clq * k), ap, tol=5e-4)
        e = ST.manoeuvre_point(S.WING, ft, k)
        check(f"P7b exact {k}", e, ex, tol=5e-4)
        fxx = ST.manoeuvre_point(S.WING, S.TAIL, k)
        check(f"P7c fixed {k}", fxx, fx, tol=5e-4)
        res[k] = (e, fxx)
    for k, mf, mx in ((0.00106, 0.119, 0.172), (0.00282, 0.133, 0.189)):
        check(f"P7c free margin {k}", res[k][0] - 0.35, mf, tol=5e-4)
        check(f"P7c fixed margin {k}", res[k][1] - 0.35, mx, tol=5e-4)
        check(f"P7c 30 % smaller {k}", 100 * (1 - (res[k][0] - 0.35) / (res[k][1] - 0.35)), 30, tol=1.5)
    check("P7d np shift", ST.neutral_point(S.WING, S.TAIL) - xnpf, 0.051, tol=5e-4)
    check("P7d fixed gap", res[0.00106][1] - ST.neutral_point(S.WING, S.TAIL), 0.010, tol=5e-4)
    check("P7d free gap", res[0.00106][0] - xnpf, 0.009, tol=5e-4)
    check("P7d mp shift", res[0.00106][1] - res[0.00106][0], 0.053, tol=5e-4)


if __name__ == "__main__":
    run([objective, drill1, drill2, extension, short_period, turn_mp, downwash_lag, free_manoeuvre_point])
