"""Checks every number in the answers and solutions of 12-aero-model-questions.qmd,
including the guided derivations 4-7.
Run from anywhere:  python3 codes/12-aero-model-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 flight import aero as AE, performance as PF, atmosphere as A
from flight.constants import KT, G0, A0_SL

PAGE = os.path.join(HERE, "..", "12-aero-model-questions.qmd")


def objective():
    """The 12 objective questions."""
    q = Objective(PAGE, 12)
    q.num(5, AE.finite_wing_slope(6.0), "4.71")
    check("Q5 distractor without pi", 2 * np.pi / (1 + 2 * np.pi / 6), 3.07)
    check("Q5 per degree", np.radians(AE.finite_wing_slope(6.0)), 0.082)
    cls, em = AE.max_lift_to_drag(0.02, 0.05)
    q.num(6, em, "15.8")
    check("Q6 sqrt(K CD0)", np.sqrt(0.05 * 0.02), 0.03162)
    check("Q6 distractor without 2", 2 * em, 31.6)
    q.num(7, cls, "0.632")
    check("Q7 distractor sqrt(K/CD0)", np.sqrt(0.05 / 0.02), 1.581)
    check("Q8 8^0.68", 8**0.68, 4.112)
    e8 = AE.oswald_straight(8.0)
    check("Q8 e", e8, 0.811)
    q.num(8, AE.induced_drag_factor(8.0, e8), "0.0491")
    check("Q8 distractor e = 1", AE.induced_drag_factor(8.0, 1.0), 0.0398)
    check("Q8 distractor times e", e8 / (np.pi * 8), 0.0323)
    cl9 = AE.max_lift_to_drag(0.025, 0.05)[0]
    check("Q9 C_L*", cl9, 0.707)
    q.num(9, PF.speed_for_cl(2000.0, 1.225, 1.0, cl9), "68.0")
    check("Q9 distractor C_L 1", PF.speed_for_cl(2000.0, 1.225, 1.0, 1.0), 57.1)
    check("Q9 distractor C_L 0.5", PF.speed_for_cl(2000.0, 1.225, 1.0, 0.5), 80.8)
    check("Q9 distractor no 2", np.sqrt(2000 / (1.225 * cl9)), 48.1)
    check("Q10 tunnel speed", 60 * 10, 600, tol=0)
    check("Q10 tunnel Mach", 600 / A0_SL, 1.76)
    check("Q10 aircraft Mach", 60 / A0_SL, 0.18)
    check("Q10 distractor sqrt(10)", 60 * np.sqrt(10), 190, tol=0.5)
    cl0, k0 = 0.03, 0.045
    clstar, emax = AE.max_lift_to_drag(cl0, k0)
    q.num(11, AE.lift_to_drag(2 * clstar, cl0, k0) / emax, "0.8", tol=1e-12)
    check("Q11 2x/(1+x^2) at 2", 4 / 5, 0.8, tol=0)
    em12 = AE.max_lift_to_drag(0.012, AE.induced_drag_factor(25.0, 0.85))[1]
    q.num(12, em12, "37.3")
    check("Q12 distractor without 1/2", 2 * em12, 74.6)
    check("Q12 distractor without e", AE.max_lift_to_drag(0.012, AE.induced_drag_factor(25.0, 1.0))[1], 40.5)


def transport():
    """Drill 1: Sadraey's jet transport."""
    W, S, cd0, k = 270000 * G0, 476.0, 0.017, 0.04
    cls, em = AE.max_lift_to_drag(cd0, k)
    check("P1 C_L*", cls, 0.652)
    check("P1 E_max", em, 19.2)
    check("P1 W (MN)", W / 1e6, 2.648)
    check("P1 minimum drag (kN)", W / em / 1e3, 138.1)
    t, p, r = A.isa(11000.0)
    a = A.speed_of_sound(t)
    check("P1 rho, a at 11 km", r, 0.36392, tol=5e-6)
    check("P1 a", a, 295.07)
    vmd = PF.speed_for_cl(W, r, S, cls)
    check("P1 min-drag speed (m/s)", vmd, 216.5)
    check("P1 its Mach", vmd / a, 0.734)
    V = 0.8 * a
    check("P1 V at M 0.8", V, 236.1)
    qd = 0.5 * r * V**2
    check("P1 q", qd, 10139, tol=0.5)
    cl = W / (qd * S)
    check("P1 C_L", cl, 0.549)
    cd = AE.parabolic_cd(cl, cd0, k)
    check("P1 C_D", cd, 0.0290)
    check("P1 E", cl / cd, 18.9)
    check("P1 drag (kN)", qd * S * cd / 1e3, 140.2)
    check("P1 extra drag (%)", (qd * S * cd / (W / em) - 1) * 100, 1.5)
    check("P1 faster (%)", (V / vmd - 1) * 100, 9, tol=0.5)


def flaps():
    """Drill 2: approach with flaps."""
    W, S, K = 750 * G0, 12.0, 0.0447
    check("P2 W", W, 7355, tol=0.5)
    vc = PF.speed_for_cl(W, 1.225, S, 1.5)
    vf = PF.speed_for_cl(W, 1.225, S, 2.4)
    check("P2 clean stall (m/s)", vc, 25.83)
    check("P2 clean stall (kt)", vc / KT, 50.2)
    check("P2 flap stall (m/s)", vf, 20.42)
    check("P2 flap stall (kt)", vf / KT, 39.7)
    check("P2 ratio", vf / vc, 0.791)
    va = 1.3 * vf
    check("P2 approach (m/s)", va, 26.55)
    check("P2 approach (kt)", va / KT, 51.6)
    cl = 2.4 / 1.69
    check("P2 C_L", cl, 1.420)
    cdf = AE.parabolic_cd(cl, 0.075, K)
    check("P2 C_D flap", cdf, 0.165)
    ef = cl / cdf
    check("P2 E flap", ef, 8.60)
    check("P2 glide angle flap (deg)", -np.degrees(PF.glide_angle(ef)), 6.6)
    ec = AE.lift_to_drag(cl, 0.030, K)
    check("P2 E clean at this C_L", ec, 11.8)
    check("P2 glide angle clean (deg)", -np.degrees(PF.glide_angle(ec)), 4.8)
    check("P2 margin clean (%)", (va / vc - 1) * 100, 3, tol=0.5)


def fit():
    """Extension 3: fit of a polar from flight-test data."""
    CL = np.array([0.2, 0.4, 0.6, 0.8, 1.0])
    CD = np.array([0.02642, 0.03448, 0.04958, 0.06942, 0.09640])
    truth("data = Hull polar + errors under 0.0005",
          np.all(abs(CD - AE.parabolic_cd(CL, 0.0231, 0.073)) <= 0.0005))
    x = CL**2
    check("P3 mean x", x.mean(), 0.44, tol=1e-12)
    check("P3 mean C_D", CD.mean(), 0.05526, tol=1e-9)
    check("P3 sum x^2", (x**2).sum(), 1.5664, tol=1e-12)
    sxx = ((x - x.mean())**2).sum()
    check("P3 Sxx", sxx, 0.5984, tol=1e-9)
    check("P3 sum x C_D", (x * CD).sum(), 0.16525)
    check("P3 5 xbar CDbar", 5 * x.mean() * CD.mean(), 0.12157)
    sxy = ((x - x.mean()) * (CD - CD.mean())).sum()
    check("P3 Sxy", sxy, 0.04368)
    K = sxy / sxx
    check("P3 K", K, 0.0730)
    cd0 = CD.mean() - K * x.mean()
    check("P3 C_D0", cd0, 0.0231)
    cls, em = AE.max_lift_to_drag(cd0, K)
    check("P3 C_L*", cls, 0.563)
    check("P3 E_max", em, 12.2)


def lifting_line():
    """Guided derivation 4: the elliptic wing."""
    y, b, G0_, V, S, rho, a0, al, al0 = sp.symbols("y b Gamma_0 V S rho a_0 alpha alpha_0", positive=True)
    L = rho * V * sp.integrate(G0_ * sp.sqrt(1 - (2 * y / b)**2), (y, -b / 2, b / 2))
    sym_zero("P4a L = rho V Gamma0 pi b/4", L - rho * V * G0_ * sp.pi * b / 4)
    CL = L / (rho * V**2 * S / 2)
    sym_zero("P4a C_L = pi b Gamma0/(2 V S)", CL - sp.pi * b * G0_ / (2 * V * S))
    ai = G0_ / (2 * b) / V
    AR = b**2 / S
    sym_zero("P4b alpha_i = C_L/(pi AR)", ai - CL / (sp.pi * AR))
    c = sp.symbols("C_L")
    sol = sp.solve(sp.Eq(c, a0 * (al - al0 - c / (sp.pi * AR))), c)[0]
    sym_zero("P4c slope a0/(1 + a0/(pi AR))", sp.diff(sol, al) - a0 / (1 + a0 / (sp.pi * AR)))
    ARv = 10.47**2 / 12
    check("P4e AR", ARv, 9.135)
    ai_ = 0.8 / (np.pi * ARv)
    check("P4e alpha_i (rad)", ai_, 0.0279)
    check("P4e alpha_i (deg)", np.degrees(ai_), 1.60)
    check("P4e C_Di ideal", 0.8 * ai_, 0.0223)
    Kv = AE.induced_drag_factor(ARv, 0.779)
    check("P4e K", Kv, 0.0447)
    check("P4e K C_L^2", Kv * 0.64, 0.0286)
    check("P4e total C_D", 0.030 + Kv * 0.64, 0.0586)
    check("P4e induced share (%)", Kv * 0.64 / (0.030 + Kv * 0.64) * 100, 49)
    check("P4e C_L*", np.sqrt(0.030 / Kv), 0.82)
    check("P4e engine finite-wing slope matches", AE.finite_wing_slope(ARv), 2 * np.pi / (1 + 2 / ARv), tol=1e-12)


def offset_polar():
    """Guided derivation 5: the shifted polar."""
    c, cd, K, m = sp.symbols("C_L C_Dmin K C_Lm", positive=True)
    CD = cd + K * (c - m)**2
    sols = sp.solve(sp.diff(c / CD, c), c)
    cls = sp.sqrt(cd / K + m**2)
    truth("P5a stationary point at sqrt(C_Dmin/K + C_Lm^2)", any(sp.simplify(s_ - cls) == 0 for s_ in sols))
    sym_zero("P5a C_D at the optimum = 2K C_L*(C_L* - C_Lm)", CD.subs(c, cls) - 2 * K * cls * (cls - m))
    for mv, clw, ew in ((0.0, 0.523, 13.1), (0.15, 0.544, 17.4)):
        clv = np.sqrt(0.020 / 0.073 + mv**2)
        check(f"P5d C_L* for C_Lm={mv}", clv, clw)
        check(f"P5d E_max for C_Lm={mv}", 1 / (2 * 0.073 * (clv - mv)), ew)
        cg = np.linspace(0.05, 1.5, 200001)
        check(f"P5d E_max by search for C_Lm={mv}", np.max(cg / (0.020 + 0.073 * (cg - mv)**2)), ew)
    check("P5d C_Dmin/K", 0.020 / 0.073, 0.2740)
    check("P5d C_L* - C_Lm", np.sqrt(0.020 / 0.073 + 0.0225) - 0.15, 0.394)


def cl_power_family():
    """Guided derivation 6: the family C_L^n/C_D."""
    c, cd, K, n = sp.symbols("C_L C_D0 K n", positive=True)
    d = sp.diff(n * sp.log(c) - sp.log(cd + K * c**2), c)
    sym_zero("P6a stationary at C_L^2 = n C_D0/((2-n) K)", sp.simplify(d.subs(c, sp.sqrt(n * cd / ((2 - n) * K)))))
    s_ = sp.symbols("s", positive=True)
    for sv in (sp.sqrt(3), 1 / sp.sqrt(3)):
        sym_zero(f"P6d E/E_max = sqrt3/2 at s = {sv}", 2 * sv / (1 + sv**2) - sp.sqrt(3) / 2)
    check("P6c V ratio n=1/2", 3**0.25, 1.316)
    check("P6c V ratio n=3/2", 3**-0.25, 0.760)
    check("P6b 1/sqrt3", 1 / np.sqrt(3), 0.577)
    check("P6b sqrt3", np.sqrt(3), 1.732)
    cd0, k = 0.023, 0.073
    em = AE.max_lift_to_drag(cd0, k)[1]
    check("P6d E_max Hull", em, 12.2)
    check("P6d E at the other optima", em * np.sqrt(3) / 2, 10.6)
    for nv, clw, vw in ((0.5, 0.324, 18.6), (1.0, 0.561, 12.2), (1.5, 0.972, 10.4)):
        clv = np.sqrt(nv * cd0 / ((2 - nv) * k))
        check(f"P6d C_L at n={nv}", clv, clw)
        check(f"P6d C_L^n/C_D at n={nv}", clv**nv / (cd0 + k * clv**2), vw)


def scale_effect():
    """Guided derivation 7: the Reynolds-number scale effect on C_D0."""
    Re = sp.symbols("Re", positive=True)
    cf = sp.Rational(455, 1000) / (sp.log(Re) / sp.log(10))**sp.Rational(258, 100)
    sym_zero("P7b dln Cf/dln Re = -2.58/ln Re", sp.simplify(sp.diff(sp.log(cf), Re) * Re + sp.Rational(258, 100) / sp.log(Re)))
    check("P7b slope at Re = 1e7", -2.58 / np.log(1e7), -0.160)
    T, p, rho = A.isa(6e3)
    mu = A.sutherland(T)
    check("P7c T at 6 km (K)", T, 249.15)
    check("P7c rho at 6 km", rho, 0.6597)
    check("P7c mu at 6 km", mu, 1.595e-5)
    R1 = AE.reynolds_number(rho, 150.0, 2.0, mu)
    R2 = AE.reynolds_number(1.225, 50.0, 0.25, A.sutherland(288.15))
    check("P7c Re aircraft", R1, "1.24e7")
    check("P7c Re model", R2, "8.6e5")
    f = lambda r: 0.455 / np.log10(r)**2.58
    check("P7c Cf aircraft", f(R1), 0.00290)
    check("P7c Cf model", f(R2), 0.00460)
    check("P7c ratio", f(R2) / f(R1), 1.59)
    check("P7c E ratio", np.sqrt(f(R1) / f(R2)), 0.79)
    check("P7c mu at sea level", A.sutherland(288.15), 1.789e-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
    y, b, cr, lam = sp.symbols("y b c_r lambda", positive=True)
    c = cr * (1 - (1 - lam) * 2 * y / b)
    Sw = 2 * sp.integrate(c, (y, 0, b / 2))
    sym_zero("E12 S", Sw - b / 2 * cr * (1 + lam))
    sym_zero("E12 AR", b**2 / Sw - 2 * b / (cr * (1 + lam)))
    sym_zero("E12 MAC", 2 / Sw * sp.integrate(c**2, (y, 0, b / 2)) - sp.Rational(2, 3) * cr * (1 + lam + lam**2) / (1 + lam))
    sym_zero("E12 y_mac", 2 / Sw * sp.integrate(c * y, (y, 0, b / 2)) - b / 6 * (1 + 2 * lam) / (1 + lam))
    fg = __import__("_scripts").load("fig-12-wing-geometry")
    check("E12 figure MAC position", fg.chord(fg.Y_MAC), fg.MAC, tol=1e-9)

if __name__ == "__main__":
    run([objective, transport, flaps, fit, lifting_line, offset_polar, cl_power_family, scale_effect, earlier_papers])
