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

PAGE = os.path.join(HERE, "..", "36-static-stability-questions.qmd")


def objective():
    q = Objective(PAGE, 12)
    q.num(4, ST.trim_angle(0.08, -1.1) / DEG, "4.2^\\circ", x=4.2)
    check("Q4 rad", 0.08 / 1.1, 0.0727, tol=5e-5)
    q.num(7, (1 - 0.4) * 2, "1.2^\\circ", x=1.2)
    q.num(9, -5.0 * ST.static_margin(0.28, 0.45), "-0.85", x=-0.85)
    w = ST.Wing(4.5, 0.25, 0.0)
    t = ST.Tail(0.5, 1.0, 3.0)                       # adds exactly 0.5 per radian at x = 3
    q.num(11, ST.neutral_point(w, t), "0.525")
    check("Q11 B", (0.25 + 3.0) / 2, 1.625, tol=1e-9)


def drill1():
    w = ST.Wing(4.6, 0.25, -0.05, 3 * DEG, 0.0)
    t = ST.Tail(3.5, 0.20, 3.2, -2 * DEG, 1.4 * DEG, 0.45, 0.9)
    w0, wa = ST.wing_moment(w, 0.30)
    check("D1 wing slope", wa, 0.230, tol=5e-4)
    check("D1 wing Cm0", w0, -0.038, tol=5e-4)
    check("D1 V_H", ST.tail_volume(t, 0.30), 0.580, tol=5e-4)
    t0, ta, _ = ST.tail_moment(t, 0.30)
    check("D1 tail slope", ta, -1.005, tol=5e-4)
    check("D1 tail Cm0", t0, 0.108, tol=5e-4)
    c0, ca, _ = ST.moment_coefficients(0.30, w, t)
    check("D1 Cm0", c0, 0.070, tol=6e-4)
    check("D1 Cma", ca, -0.775, tol=5e-4)
    check("D1 a_t", 3.5 * 0.55 * 0.9 * 0.20, 0.3465, tol=1e-9)
    xn = ST.neutral_point(w, t)
    check("D1 x_np", xn, 0.457, tol=5e-4)
    check("D1 margin", xn - 0.30, 0.157, tol=5e-4)
    check("D1 check of the slope", -(4.6 + 0.3465) * (xn - 0.30), ca, rel=1e-9)
    check("D1 trim (deg)", ST.trim_angle(c0, ca) / DEG, 5.2, tol=0.05)


def drill2():
    xn = ST.neutral_point(S.WING, S.TAIL)
    cla = ST.lift_coefficients(S.WING, S.TAIL)[1]
    check("D2 x_np", xn, 0.512, tol=6e-4)
    check("D2 aft limit", 0.512 - 0.10, 0.412, tol=1e-9)
    check("D2 slope at limit", -5.16 * 0.10, -0.516, tol=1e-9)
    check("D2 slope at 0.20", -cla * (xn - 0.20), -1.61, tol=0.006)
    check("D2 metres", (0.412 - 0.30) * S.MAC_M, 0.24, tol=0.005)


def canard():
    aw, ac, xw, xc = sp.symbols("a_w a_c x_w x_c")
    sym_zero("E3a shift", sp.simplify((aw * xw + ac * xc) / (aw + ac) - xw - ac * (xc - xw) / (aw + ac)))
    check("E3d", ST.neutral_point(ST.Wing(4.5, 0.25, 0.0), ST.Tail(0.6, 1.0, -2.0)), -0.015, tol=5e-4)


def downwash_factor():
    """Guided derivation 4: why the downwash at the tail is twice that at the wing."""
    check("P4a semi-infinite bracket", np.cos(np.pi / 2) - np.cos(np.pi), 1.0, tol=1e-12)
    check("P4a infinite bracket", np.cos(0.0) - np.cos(np.pi), 2.0, tol=1e-12)
    AR, cla = 9.135, 5.15
    check("P4b engine downwash = 2 alpha_i", ST.downwash_from_lift(0.8, AR), 2 * 0.8 / (np.pi * AR), tol=1e-12)
    ea = 2 * cla / (np.pi * AR)
    check("P4c eps_alpha", ea, 0.359)
    check("P4c 1 - eps_alpha", 1 - ea, 0.641)


def trim_drag():
    """Guided derivation 5: the trim drag of a forward CG."""
    LH, W, d, cmac, CL, lh = sp.symbols("L_H W d C_mac C_L l_H", real=True)
    sol = sp.solve(sp.Eq((1 - LH / W) * d + cmac / CL - (LH / W) * lh, 0), LH)[0]
    sym_zero("P5a L_H/W", sp.simplify(sol / W - (d + cmac / CL) / (lh + d)))
    for dv, lw, fw in ((-0.10, -0.0513, 1.105), (0.05, -0.0123, 1.025)):
        r = (dv + (-0.05) / 0.5) / (4 + dv)
        check(f"P5c tail load at d={dv}", r, lw)
        check(f"P5c induced factor at d={dv}", (1 - r)**2, fw)


def tail_for_cg_range():
    """Guided derivation 6: how much tail does a CG range need?"""
    aw, at, l, d, k, sh, xac, xh = sp.symbols("a_w a_t l d k s x_ac x_H", positive=True)
    xnp = (aw * xac + at * xh) / (aw + at)
    sym_zero("P6a d", sp.simplify(xnp - xac - (xh - xac) * at / (aw + at)))
    sym_zero("P6a inverse", sp.simplify((l * at / (aw + at)).subs(at, aw * d / (l - d)) - d))
    dd = l * k * sh / (aw + k * sh)
    sym_zero("P6b slope at 0", sp.diff(dd, sh).subs(sh, 0) - l * k / aw)
    sym_zero("P6b below the line", sp.simplify(dd - (l * k * sh / aw) / (1 + k * sh / aw)))
    sym_zero("P6b limit", sp.limit(dd, sh, sp.oo) - l)
    AW, AH, EA, ETA, XAC, XH = 4.67, 4.03, 0.42, 0.9, 0.258, 2.93
    L, K = XH - XAC, AH * (1 - EA) * ETA
    need = lambda x: AW * (x - XAC) / (L - (x - XAC)) / K
    check("P6b k", K, 2.104, tol=5e-4)
    check("P6b l", L, 2.672, tol=5e-4)
    check("P6b slope", K * L / AW, 1.204, tol=5e-4)
    check("P6c shown chain", 0.242 / 1.204, 0.201, tol=5e-4)
    check("P6c d", 0.50 - XAC, 0.242, tol=5e-4)
    s1 = need(0.50)
    check("P6c S_H/S", s1, 0.221, tol=5e-4)
    check("P6c ft^2", s1 * 232, 51.3, tol=0.05)
    check("P6c fraction of fitted", s1 / (54 / 232), 0.95, tol=0.005)
    xn = (AW * XAC + K * s1 * XH) / (AW + K * s1)
    check("P6c neutral point back at 0.50", xn, 0.50, tol=1e-12)
    lin = 0.242 / (K * L / AW)
    check("P6c straight line", lin, 0.201, tol=5e-4)
    check("P6c straight line short by (%)", 100 * (1 - lin / s1), 9, tol=0.5)
    s2 = need(0.40)
    check("P6d l - d", L - (0.40 - XAC), 2.530, tol=5e-4)
    check("P6d S_H/S", s2, 0.125, tol=5e-4)
    check("P6d ft^2", s2 * 232, 28.9, tol=0.05)
    check("P6d fraction", s2 / (54 / 232), 0.54, tol=0.005)


def supersonic_ac():
    """Guided derivation 7: why the aircraft grows stiffer through Mach 1."""
    a, b, tl, tu, x = sp.symbols("alpha beta theta_l theta_u x", positive=True)
    dcp = 2 * (tl + a) / b - 2 * (tu - a) / b
    sym_zero("P7a jump", sp.expand(dcp - (4 * a / b + 2 * (tl - tu) / b)))
    dda = sp.diff(dcp, a)
    xc = sp.integrate(x * dda, (x, 0, 1)) / sp.integrate(dda, (x, 0, 1))
    sym_zero("P7a mid-chord", xc - sp.Rational(1, 2))
    aw, at, xac, xh = 4.67, 0.490, 0.258, 2.93
    np0 = (aw * xac + at * xh) / (aw + at); np1 = (aw * 0.5 + at * xh) / (aw + at)
    check("P7b shift", np1 - np0, 0.219, tol=5e-4)
    check("P7b formula", aw * 0.242 / (aw + at), np1 - np0, tol=1e-12)
    check("P7b a_w + a_t", aw + at, 5.16, tol=0.005)
    check("P7b old np", np0, 0.512, tol=5e-4)
    check("P7b new np", np1, 0.731, tol=5e-4)
    check("P7b old margin", np0 - 0.30, 0.212, tol=5e-4)
    check("P7b new margin", np1 - 0.30, 0.431, tol=5e-4)
    check("P7b about twice", (np1 - 0.30) / (np0 - 0.30), 2.0, tol=0.05)
    for k in (0.5, 2.0):                      # the same factor on both slopes leaves the shift unchanged
        check(f"P7b scaling {k}", (k * aw * 0.5 + k * at * xh) / (k * aw + k * at), np1, tol=1e-12)



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
    eta, VH, a, ea, e0, iH, al = sp.symbols("eta V_H a eps_a eps_0 i_H alpha")
    cm = -eta * VH * a * (al + iH - (e0 + ea * al))
    sym_zero("E36 tail slope", sp.diff(cm, al) + eta * VH * a * (1 - ea))
    sym_zero("E36 tail Cm0", cm.subs(al, 0) + eta * VH * a * (iH - e0))
    check("E36 service-ceiling rate (m/s)", 100 * 0.3048 / 60, 0.508, tol=5e-4)

if __name__ == "__main__":
    run([objective, drill1, drill2, canard, downwash_factor, trim_drag, tail_for_cg_range, supersonic_ac, earlier_papers])
