"""Checks every number and formula in the answers and solutions of 37-longitudinal-control-questions.qmd,
including the guided derivations 4-7.
Run from anywhere:  python3 codes/37-longitudinal-control-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, "..", "37-longitudinal-control-questions.qmd")


def objective():
    q = Objective(PAGE, 12)
    q.num(5, 0.35 + 6 * 0.15 / 6, "0.50")
    q.num(8, ST.free_elevator_factor(ST.Tail(4.0, 0.2, 3.0, tau=0.5), ST.Hinge(-0.3, -0.6)), "0.75")
    q.num(9, 4, "4")
    q.num(11, np.sqrt(300 / 0.012), "158")
    q.num(12, 2 * -0.012 * np.sqrt(300 / 0.012), "-3.8", x=-3.8)
    check("Q12 equivalent", -2 * 300 / np.sqrt(300 / 0.012), 2 * -0.012 * np.sqrt(300 / 0.012), rel=1e-12)


def drill1():
    c0, ca, cd = ST.moment_coefficients(0.20, S.WING, S.TAIL, S.THRUST)
    cl0, cla, cld = ST.lift_coefficients(S.WING, S.TAIL)
    check("D1 Cm0", c0, 0.0728, tol=5e-5)
    check("D1 Cma", ca, -1.608, tol=5e-4)
    check("D1 Cmd", cd, -1.173, tol=5e-4)
    check("D1 Delta", ST.trim_determinant(cla, cld, ca, cd), -5.36, tol=5e-3)
    a, d = ST.trim(1.0, cl0, cla, cld, c0, ca, cd)
    check("D1 alpha rad", a, 0.195, tol=5e-4)
    check("D1 alpha deg", a / DEG, 11.2, tol=0.05)
    check("D1 elevator rad", d, -0.205, tol=5e-4)
    check("D1 elevator deg", d / DEG, -11.7, tol=0.05)
    check("D1 left", 20 + d / DEG, 8.3, tol=0.05)
    check("D1 same Delta at 0.30", ST.trim_determinant(cla, cld, *ST.moment_coefficients(0.30, S.WING, S.TAIL)[1:]),
          ST.trim_determinant(cla, cld, ca, cd), rel=1e-12)


def drill2():
    f = ST.free_elevator_factor(ST.Tail(0.08, 0.2, 3.0, tau=0.55), ST.Hinge(-0.003, -0.005))
    check("D2 f", f, 0.67, tol=1e-9)
    check("D2 shift", (1 - f) * 0.4 * 1.0 * (0.08 / 0.09) * 0.6, 0.070, tol=5e-4)


def extension():
    a, d = ST.trim_at_cg(0.299, 0.30, S.WING, S.TAIL, S.THRUST)
    ih = S.TAIL.incidence + S.TAIL.tau * d
    check("E3b tail angle", ih / DEG, -1.00, tol=5e-3)
    t2 = ST.Tail(S.TAIL.cl_alpha, S.TAIL.area_ratio, S.TAIL.x_ac, ih, S.TAIL.eps0, S.TAIL.eps_alpha, S.TAIL.eta, S.TAIL.tau)
    a2, d2 = ST.trim_at_cg(0.299, 0.30, S.WING, t2, S.THRUST)
    check("E3b elevator zero", d2, 0.0, tol=1e-12)
    check("E3b same alpha", a2, a, rel=1e-12)
    check("E3b alpha", a2 / DEG, 2.23, tol=5e-3)


def power_effect():
    """Guided derivation 4: power moves the neutral point."""
    CL, K, c0, z = sp.symbols("C_L K C_D0 z", positive=True)
    cmT = (c0 + K * CL**2) * z
    sym_zero("P4a dC_mT/dC_L", sp.diff(cmT, CL) - 2 * K * CL * z)
    check("P4c cruise shift", 2 * 0.073 * 0.5 * 0.3, 0.022)
    check("P4c approach shift", 2 * 0.073 * 1.2 * 0.3, 0.053)
    check("P4c a 10 % margin halved", 0.10 - 2 * 0.073 * 1.2 * 0.3, 0.047, tol=0.001)


def feel():
    """Guided derivation 5: stick feel at height and weight."""
    check("P5c true speed at 11 km", 150 / np.sqrt(0.297), 275)
    check("P5c gradient ratio", np.sqrt(0.297), 0.545)
    check("P5c sigma at 11 km from the ISA", __import__("flight").atmosphere.isa(11e3)[2] / 1.225, 0.297)


def bigger_elevator():
    """Guided derivation 6: how much a bigger elevator buys."""
    import dataclasses
    import _stab as SB
    from flight import stability as STB
    xnp, cm0, eta, VH, cla, tau, dmin, CL, CL0 = sp.symbols("x_np C_m0 eta V_H C_LaH tau d_min C_L C_L0")
    xf = xnp - (cm0 - eta * VH * cla * tau * dmin) / (CL - CL0)
    sym_zero("P6a derivative", sp.diff(xf, tau) - eta * VH * cla * dmin / (CL - CL0))
    cl0 = STB.lift_coefficients(SB.WING, SB.TAIL)[0]
    check("P6 C_L0", cl0, 0.0835, tol=5e-5)
    check("P6 tau", SB.TAIL.tau, 0.509, tol=0)
    f = lambda t: STB.forward_cg_limit(1.2, SB.DE_MIN, SB.WING, dataclasses.replace(SB.TAIL, tau=t), SB.THRUST)
    check("P6 exact limit", f(0.509), 0.127, tol=5e-4)
    check("P6b V_H at 0.127", STB.tail_volume(SB.TAIL, 0.127), 0.652, tol=5e-4)
    check("P6b approx slope", 0.9 * 0.652 * 4.03 * np.radians(-20) / (1.2 - 0.0835), -0.74, tol=0.005)
    check("P6b limit tau 0.407", f(0.407), 0.187, tol=5e-4)
    check("P6b limit tau 0.611", f(0.611), 0.066, tol=5e-4)
    check("P6b exact slope", (f(0.509 + 1e-4) - f(0.509 - 1e-4)) / 2e-4, -0.59, tol=0.005)
    check("P6b chord slope", (f(0.611) - f(0.407)) / 0.204, -0.59, tol=0.005)
    check("P6b deg -> rad", np.radians(-20), -0.349, tol=5e-4)
    from scipy.optimize import brentq
    t77 = brentq(lambda t: f(t) - 0.077, 0.5, 0.8)
    check("P6c exact tau", t77, 0.593, tol=5e-4)
    check("P6c estimate", 0.509 + 0.05 / 0.59, 0.594, tol=5e-4)
    check("P6c 17 %", 100 * (t77 / 0.509 - 1), 17, tol=0.5)


def down_spring():
    """Guided derivation 7: a spring that hides an aft CG."""
    import _stab as SB
    from flight import stability as STB
    from scipy.optimize import brentq
    WS, eta = SB.WEIGHT / SB.AREA, SB.TAIL.eta
    A = lambda x: eta * STB.hinge_trim_line(SB.WING, SB.TAIL, SB.HINGE, x, SB.THRUST)[1] * WS
    check("P7 A at 0.30 (Pa)", A(0.30), 278, tol=0.5)
    sl = (A(0.40) - A(0.30)) / 0.1
    check("P7 slope (Pa per chord)", sl, -1731, tol=0.5)
    truth("P7 A linear in the CG", abs((A(0.20) - A(0.30)) / -0.1 - sl) < 1e-6)
    xnp = brentq(A, 0.2, 0.7)
    check("P7 stick-free np", xnp, 0.461, tol=5e-4)
    fsp = 0.5 * A(0.30)
    check("P7b spring", fsp, 139, tol=0.5)
    check("P7b shift", fsp / -sl, 0.080, tol=5e-4)
    xa = brentq(lambda x: A(x) + fsp, 0.2, 0.8)
    check("P7b apparent np", xa, 0.541, tol=5e-4)
    Vt, a_, f_ = sp.symbols("V_t A f", positive=True)
    B = -(a_ + f_) / Vt**2
    sym_zero("P7a slope", 2 * B * Vt + 2 * (a_ + f_) / Vt)



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
    cla, cld, cm0, cma, cmd, CL, al, de = sp.symbols("CLa CLd Cm0 Cma Cmd CL alpha de")
    sol = sp.solve([cm0 + cma * al + cmd * de, cla * al + cld * de - CL], [al, de], dict=True)[0]
    sym_zero("E37 trim elevator", sp.simplify(sol[de] + (cla * cm0 + cma * CL) / (cla * cmd - cma * cld)))

if __name__ == "__main__":
    run([objective, drill1, drill2, extension, power_effect, feel, bigger_elevator, down_spring, earlier_papers])
