"""Checks every number in the answers and solutions of 13-aero-mach-questions.qmd,
including the guided derivations 4-7.
Run from anywhere:  python3 codes/13-aero-mach-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 scipy.optimize import minimize_scalar
from _verify import check, truth, sym_zero, Objective, run
from _scripts import load
from flight import aero as AE, gasdynamics as GD, atmosphere as A

PAGE = os.path.join(HERE, "..", "13-aero-mach-questions.qmd")


def objective():
    """The 12 objective questions."""
    q = Objective(PAGE, 12)
    H = load("fig-13-sbj-mach")
    truth("Q1 Hull K constant to 0.75", np.all(H.K[H.M <= 0.75] == 0.073))
    q.num(5, AE.compressible_lift_slope(2 * np.pi, 0.7), "8.80")
    check("Q5 sqrt(0.51)", np.sqrt(0.51), 0.714)
    check("Q5 distractor A", 2 * np.pi * np.sqrt(0.51), 4.49)
    check("Q5 distractor C", 2 * np.pi / 0.51, 12.32)
    a4 = np.radians(4.0)
    check("Q6 alpha (rad)", a4, 0.0698)
    q.num(6, AE.ackeret_flat_plate(a4, 2.0)[0], "0.161")
    check("Q6 small-angle C_L", 4 * a4 / np.sqrt(3), 0.161)
    check("Q6 distractor sqrt(M^2+1)", 4 * a4 / np.sqrt(5), 0.125)
    check("Q7 beta", np.sqrt(1.25), 1.118)
    q.num(7, AE.ackeret_thickness_drag(0.04, 1.5), "0.0057")
    check("Q7 distractor biconvex", AE.ackeret_thickness_drag(0.04, 1.5, "biconvex"), 0.0076)
    check("Q7 distractor unsquared", 4 * 0.04 / np.sqrt(1.25), 0.143)
    q.num(8, AE.newtonian_cone_cd(np.radians(15.0)), "0.134")
    check("Q8 sin^2 15", np.sin(np.radians(15))**2, 0.0670)
    check("Q8 distractor unsquared", 2 * np.sin(np.radians(15)), 0.518)
    es = load("fig-13-emax-supersonic")
    e3 = AE.max_lift_to_drag(0.006 + AE.ackeret_thickness_drag(0.03, 3.0), AE.supersonic_induced_factor(3.0))[1]
    q.num(9, e3, "7.0")
    check("Q9 beta C_f", np.sqrt(8) * 0.006, 0.01697)
    check("Q9 distractor no sqrt", 1 / (np.sqrt(8) * 0.006 + 0.0036), 48.6)
    check("Q9 distractor half", e3 / 2, 3.5)
    check("Q9 distractor M 1.2", es.emax(0.03, 1.2), 11.5)
    b = np.sqrt(3)
    cd = 0.005 + AE.ackeret_thickness_drag(0.04, 2.0) + AE.supersonic_induced_factor(2.0) * 0.01
    check("Q10 parts", AE.ackeret_thickness_drag(0.04, 2.0), 0.0037)
    check("Q10 lift part", AE.supersonic_induced_factor(2.0) * 0.01, 0.0043)
    check("Q10 C_D", cd, 0.0130)
    q.num(10, 0.1 / cd, "7.7")
    check("Q10 distractor friction only", 0.1 / 0.005, 20.0)
    check("Q11 pitot ratio at M 10", GD.rayleigh_pitot(10.0), 129.2)
    check("Q11 C_p,max", AE.modified_newtonian_cpmax(10.0), 1.832)
    q.num(11, AE.newtonian_sphere_cd(AE.modified_newtonian_cpmax(10.0)), "0.92")
    truth("Q12 answer names the upper surface", "upper surface" in q.right(12))


def wing():
    """Drill 1: a supersonic wing at 12 km."""
    M, tau, cf = 1.8, 0.035, 0.005
    b = np.sqrt(M**2 - 1)
    check("P1 beta", b, 1.497)
    cla = AE.compressible_lift_slope(2 * np.pi, M)
    check("P1 lift slope /rad", cla, 2.67)
    check("P1 lift slope /deg", np.radians(cla), 0.0466)
    cdw = AE.ackeret_thickness_drag(tau, M)
    check("P1 thickness drag", cdw, 0.00327)
    cd0 = cf + cdw
    check("P1 C_D0", cd0, 0.00827)
    K = AE.supersonic_induced_factor(M)
    check("P1 K", K, 0.374)
    cls, em = AE.max_lift_to_drag(cd0, K)
    check("P1 C_L*", cls, 0.149)
    check("P1 E_max", em, 9.0)
    t, p, r = A.isa(12000.0)
    check("P1 p at 12 km", p, 19330, tol=0.5)
    q_ = 0.5 * GD.G * p * M**2
    check("P1 q", q_, 43841, tol=0.5)
    cl = 3000 / q_
    check("P1 C_L", cl, 0.0684)
    check("P1 alpha (deg)", np.degrees(cl / cla), 1.47)
    cd = AE.parabolic_cd(cl, cd0, K)
    check("P1 C_D", cd, 0.0100)
    check("P1 E", cl / cd, 6.8)
    check("P1 E below best (%)", (1 - cl / cd / em) * 100, 24, tol=0.5)
    truth("P1 less than half of C_L*", cl < cls / 2)


def nose():
    """Drill 2: a pointed nose or a blunt one."""
    check("P2 pitot ratio at M 5", GD.rayleigh_pitot(5.0), 32.65)
    cpm = AE.modified_newtonian_cpmax(5.0)
    check("P2 C_p,max", cpm, 1.809)
    cc = AE.newtonian_cone_cd(np.radians(10.0), cpm)
    cs = AE.newtonian_sphere_cd(cpm)
    check("P2 cone C_D", cc, 0.0545)
    check("P2 hemisphere C_D", cs, 0.904)
    check("P2 ratio", cs / cc, 16.6)
    t, p, r = A.isa(20000.0)
    check("P2 rho at 20 km", r, 0.08803)
    a = A.speed_of_sound(t)
    V = 5 * a
    check("P2 V", V, 1475, tol=0.5)
    q_ = 0.5 * r * V**2
    check("P2 q", q_, 95810, tol=1)
    S = np.pi * 0.3**2
    check("P2 base area", S, 0.283)
    check("P2 cone drag (N)", q_ * S * cc, 1478, tol=1)
    check("P2 hemisphere drag (N)", q_ * S * cs, 24500, tol=10)


def wedge():
    """Extension 3: exact against linear for a double wedge."""
    e = np.radians(5.0)
    ob = GD.oblique_shock(2.0, e)
    check("P3 shock angle (deg)", np.degrees(ob["beta"]), 34.3)
    check("P3 M behind shock", ob["M2"], 1.821)
    check("P3 p2/p", ob["p"], 1.315)
    ex = GD.expansion(ob["M2"], 2 * e)
    check("P3 M on rear faces", ex["M2"], 2.185)
    p3 = ob["p"] * ex["p"]
    check("P3 p3/p", p3, 0.748)
    tc = np.tan(e)
    check("P3 t/c", tc, 0.0875)
    cdx = (ob["p"] - p3) / 2.8 * tc
    check("P3 exact C_Dw", cdx, 0.0177)
    check("P3 linear C_Dw", AE.ackeret_thickness_drag(tc, 2.0), 0.0177)
    check("P3 front C_p", (ob["p"] - 1) / 2.8, 0.113)
    check("P3 rear C_p", (p3 - 1) / 2.8, -0.090)
    check("P3 linear C_p", AE.ackeret_cp(e, 2.0), 0.101)
    truth("P3 linear errors about 10 %", 0.08 < abs((ob["p"] - 1) / 2.8 / AE.ackeret_cp(e, 2.0) - 1) < 0.15)


def least_wave_drag():
    """Guided derivation 4: the supersonic section of least wave drag."""
    x, c, t, a, b = sp.symbols("x c t a beta", positive=True)
    tau = t / c
    I = sp.integrate((t / (2 * a))**2, (x, 0, a)) + sp.integrate((t / (2 * (c - a)))**2, (x, a, c))
    cd = 4 / (b * c) * I
    sym_zero("P4b C_Dw = tau^2 c^2/(beta a (c-a))", cd - tau**2 * c**2 / (b * a * (c - a)))
    sym_zero("P4b mid-chord gives 4 tau^2/beta", cd.subs(a, c / 2) - 4 * tau**2 / b)
    truth("P4b a = c/2 is the minimum", sp.solve(sp.diff(cd, a), a) == [c / 2])
    check("P4b 30 % ridge costs", 1 / (4 * 0.3 * 0.7), 1.19)
    y = 2 * t * x * (c - x) / c**2
    sym_zero("P4c biconvex y'' constant", sp.diff(y, x, 2) + 4 * t / c**2)
    sym_zero("P4c biconvex C_Dw = 16/3 tau^2/beta", 4 / (b * c) * sp.integrate(sp.diff(y, x)**2, (x, 0, c)) - sp.Rational(16, 3) * tau**2 / b)
    sym_zero("P4d biconvex area = 2/3 t c", 2 * sp.integrate(y, (x, 0, c)) - sp.Rational(2, 3) * t * c)
    bv = np.sqrt(3.0)
    check("P4d beta at Mach 2", bv, 1.732)
    dw = AE.ackeret_thickness_drag(0.04, 2.0)
    bc = AE.ackeret_thickness_drag(0.04, 2.0, "biconvex")
    check("P4d double wedge", dw, 0.00370)
    check("P4d biconvex", bc, 0.00493)
    check("P4d double wedge of equal area", AE.ackeret_thickness_drag(0.04 * 4 / 3, 2.0), 0.00657)


def decomposition():
    """Guided derivation 5: lift, camber and thickness separately."""
    x, c, al, b, h, tt = sp.symbols("x c alpha beta h t", positive=True)
    yc = 4 * h * x * (c - x) / c**2
    yt = 2 * tt * x * (c - x) / c**2 * 0 + tt / 2 * sp.sin(sp.pi * x / c)
    yu = yc + yt - al * x
    yl = yc - yt - al * x
    th_u, th_l = sp.diff(yu, x), -sp.diff(yl, x)
    CL = sp.integrate(2 * th_l / b - 2 * th_u / b, (x, 0, c)) / c
    sym_zero("P5a C_L = 4 alpha/beta for a cambered, thick section", CL - 4 * al / b)
    CD = 2 / (b * c) * sp.integrate(th_u**2 + th_l**2, (x, 0, c))
    mean = lambda f: sp.integrate(f, (x, 0, c)) / c
    sym_zero("P5b C_D = (4/beta)[alpha^2 + mean(yc'^2) + mean(yt'^2)]",
             CD - 4 / b * (al**2 + mean(sp.diff(yc, x)**2) + mean(sp.diff(yt, x)**2)))
    m = float(sp.Rational(16, 3) * sp.Rational(2, 100)**2)
    check("P5d mean camber slope^2", m, 2.13e-3)
    check("P5d camber drag", 4 / np.sqrt(3) * m, 4.93e-3)
    check("P5d alpha for C_L = 0.1", 0.1 * np.sqrt(3) / 4, 0.0433)
    check("P5d drag due to lift", np.sqrt(3) / 4 * 0.01, 4.33e-3)


def hypersonic_emax():
    """Guided derivation 6: the best L/D in Newtonian flow."""
    a, c0 = sp.symbols("alpha C_D0", positive=True)
    E = 2 * a**2 / (2 * a**3 + c0)
    truth("P6b stationary at alpha^3 = C_D0", sp.simplify(sp.diff(E, a).subs(a, c0**sp.Rational(1, 3))) == 0)
    sym_zero("P6b E_max = 2/(3 alpha*)", E.subs(a, c0**sp.Rational(1, 3)) - 2 / (3 * c0**sp.Rational(1, 3)))
    k, m, CLs = sp.symbols("k m C_L", positive=True)
    num = sp.numer(sp.together(sp.diff(CLs / (c0 + k * CLs**m), CLs)))
    sym_zero("P6b general: dE/dC_L = 0 is C_D0 - (m-1) k C_L^m = 0", sp.expand(num - (c0 - (m - 1) * k * CLs**m)))
    for cv, aw, ew in ((0.01, 12.3, 3.09), (0.005, 9.8, 3.90), (0.001, 5.7, 6.67)):
        av = cv**(1 / 3)
        check(f"P6c alpha* for C_D0={cv} (deg)", np.degrees(av), aw)
        check(f"P6c E_max for C_D0={cv}", 2 / (3 * av), ew)
    check("P6c alpha* rad", 0.01**(1 / 3), 0.215)
    def neg(x):
        cl, cd = AE.newtonian_flat_plate(x)
        return -cl / (cd + 0.01)
    r = minimize_scalar(neg, bounds=(0.02, 1.0), method="bounded", options=dict(xatol=1e-12))
    check("P6c exact search angle (deg)", np.degrees(r.x), 12.2)
    check("P6c exact search E", -r.fun, 3.02)
    check("P6d 2^(1/3)", 2**(1 / 3), 1.26)


def capsule_dish():
    """Guided derivation 7: the drag of a spherical cap."""
    ph, th, R, cp = sp.symbols("phi theta_c R C_pmax", positive=True)
    D = 2 * sp.pi * R**2 * cp * sp.integrate(sp.cos(ph)**3 * sp.sin(ph), (ph, 0, th))
    CD = D / (sp.pi * R**2 * sp.sin(th)**2)
    sym_zero("P7a C_D = (1 + cos^2) C_pmax/2", sp.simplify(CD - (1 + sp.cos(th)**2) * cp / 2))
    sym_zero("P7b hemisphere", CD.subs(th, sp.pi / 2) - cp / 2)
    sym_zero("P7b flat limit", sp.limit(CD, th, 0) - cp)
    s_ = 1.955 / 4.69
    check("P7c sin theta_c", s_, 0.417)
    tc = np.arcsin(s_)
    check("P7c theta_c (deg)", np.degrees(tc), 24.6)
    check("P7c 1 + cos^2", 1 + np.cos(tc)**2, 1.826)
    cpm = AE.modified_newtonian_cpmax(30.0)
    check("P7c C_pmax", cpm, 1.839, tol=0.001)
    check("P7c modified Newtonian C_D", (1 + np.cos(tc)**2) * cpm / 2, 1.68)
    check("P7c hemisphere agrees with the engine's sphere", (1 + np.cos(np.pi / 2)**2) / 2 * 2, AE.newtonian_sphere_cd(), tol=1e-12)


if __name__ == "__main__":
    run([objective, wing, nose, wedge, least_wave_drag, decomposition, hypersonic_emax, capsule_dish])
