"""Checks every number in the answers and solutions of 11-mach-regimes-questions.qmd,
including the guided derivations 4-7.
Run from anywhere:  python3 codes/11-mach-regimes-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 gasdynamics as GD, atmosphere as A, aero as AE

PAGE = os.path.join(HERE, "..", "11-mach-regimes-questions.qmd")
A_STRAT = A.speed_of_sound(216.65)


def objective():
    """The 12 objective questions."""
    q = Objective(PAGE, 12)
    q.num(2, np.degrees(GD.mach_angle(2.0)), "30", tol=1e-9)
    check("Q2 distractor arctan(1/2)", np.degrees(np.arctan(0.5)), 26.6)
    truth("Q3 subsonic behind", GD.normal_shock(2.0)["M2"] < 1)
    q.num(5, (GD.stagnation_density_ratio(0.5) - 1) * 100, "13.0")
    check("Q5 1.05^2.5", 1.05**2.5, 1.130)
    check("Q5 distractor temperature (%)", (GD.stagnation_temperature_ratio(0.5) - 1) * 100, 5.0)
    check("Q5 distractor pressure (%)", (GD.stagnation_pressure_ratio(0.5) - 1) * 100, 18.6)
    T15 = A.isa(15000.0)[0]
    check("Q6 T at 15 km", T15, 216.65, tol=1e-9)
    tt = T15 * GD.stagnation_temperature_ratio(3.0)
    check("Q6 Tt (K)", tt, 606.6)
    q.num(6, tt - 273.15, "333")
    check("Q6 distractor 0.2M (C)", T15 * 1.6 - 273.15, 73, tol=0.5)
    q.num(7, AE.critical_from_divergence(0.78), "0.672")
    q.num(8, GD.normal_mach(0.85, np.radians(30.0)), "0.736")
    check("Q8 distractor sine", 0.85 * np.sin(np.radians(30)), 0.425)
    check("Q8 distractor divide", 0.85 / np.cos(np.radians(30)), 0.981)
    V = 1.4 * A_STRAT
    x = GD.cone_ground_distance(15000.0, 1.4)
    check("Q9 V (m/s)", V, 413.1)
    check("Q9 mu (deg)", np.degrees(GD.mach_angle(1.4)), 45.6)
    check("Q9 x (km)", x / 1e3, 14.70)
    q.num(9, x / V, "35.6")
    check("Q9 distractor h/V", 15000 / V, 36.3)
    check("Q9 distractor h tan mu / V", 15000 * np.tan(GD.mach_angle(1.4)) / V, 37.1)
    ns = GD.normal_shock(3.0)
    check("Q10 p2/p1", ns["p"], 10.33)
    check("Q10 rho2/rho1", ns["rho"], 3.857)
    check("Q10 M2", ns["M2"], 0.475)
    check("Q10 p0 ratio", ns["p0"], 0.328)
    q.num(10, ns["p0"], "0.33")
    check("Q10 distractor M1 = 2", GD.normal_shock(2.0)["p0"], 0.72)
    q.num(11, GD.critical_mach(-0.6), "0.69")
    check("Q11 note's section", GD.critical_mach(-0.43), 0.74)
    truth("Q12 answer names dissociation", "broken apart" in q.right(12))


def concorde():
    """Drill 1: Concorde at Mach 2.2 at 16 km."""
    t = A.isa(16000.0)[0]
    a = A.speed_of_sound(t)
    check("P1 T, a", t, 216.65, tol=1e-9)
    check("P1 a (m/s)", a, 295.07)
    V = 2.2 * a
    check("P1 V (m/s)", V, 649.2)
    check("P1 mu (deg)", np.degrees(GD.mach_angle(2.2)), 27.0)
    x = GD.cone_ground_distance(16000.0, 2.2)
    check("P1 x (km)", x / 1e3, 31.35)
    check("P1 delay (s)", x / V, 48.3)
    check("P1 31350/649.2", 31350 / 649.2, 48.3)
    tt = t * GD.stagnation_temperature_ratio(2.2)
    check("P1 Tt (K)", tt, 426.4)
    check("P1 Tt (C)", tt - 273.15, 153, tol=0.5)
    ns = GD.normal_shock(2.2)
    check("P1 M2", ns["M2"], 0.547)
    check("P1 p0 ratio", ns["p0"], 0.628)
    check("P1 loss (%)", (1 - ns["p0"]) * 100, 37, tol=0.5)
    check("P1 p2/p1", ns["p"], 5.48, tol=1e-9)
    check("P1 pitot p_t/p", GD.rayleigh_pitot(2.2), 6.72)
    check("P1 by hand", 5.48 * (1 + 0.2 * 0.547**2) ** 3.5, 6.72)
    check("P1 isentropic", GD.stagnation_pressure_ratio(2.2), 10.69)


def sweep():
    """Drill 2: sweep against the drag rise."""
    mc = AE.critical_from_divergence(0.74)
    check("P2 Mcr", mc, 0.632)
    cdw = AE.transonic_wave_drag(0.82, 0.74)
    check("P2 CDw unswept", cdw, 0.0248)
    check("P2 ratio to CD0", cdw / 0.018, 1.38)
    check("P2 cos", 0.74 / 0.82, 0.902)
    lam = np.arccos(0.74 / 0.82)
    check("P2 sweep (deg)", np.degrees(lam), 25.5)
    cdw_s = AE.transonic_wave_drag(GD.normal_mach(0.82, lam), 0.74)
    check("P2 CDw swept", cdw_s, 0.0027)
    truth("P2 less than a ninth", cdw_s < cdw / 9)


def scramjet():
    """Extension 3: Mach 6 at 30 km."""
    t = A.isa(30000.0)[0]
    check("P3 T at 30 km", t, 226.65, tol=1e-9)
    ns = GD.normal_shock(6.0)
    check("P3 M2", ns["M2"], 0.404)
    check("P3 T2/T1", ns["T"], 7.94)
    check("P3 p0 ratio", ns["p0"], 0.0297)
    check("P3 T2 (K)", t * ns["T"], 1800, tol=0.5)
    tt = t * GD.stagnation_temperature_ratio(6.0)
    check("P3 Tt (K)", tt, 1858.5)
    t2 = tt / GD.stagnation_temperature_ratio(2.0)
    check("P3 T at Mach 2 (K)", t2, 1032.5)
    v2 = 2.0 * A.speed_of_sound(t2)
    check("P3 speed at Mach 2 (km/s)", v2 / 1e3, 1.3, tol=0.05)
    check("P3 time per metre (ms)", 1e3 / v2, 0.78, tol=0.01)


def shock_derivation():
    """Guided derivation 4: the normal shock from the conservation laws."""
    g, ast, u = sp.symbols("gamma a_star u", positive=True)
    a2 = (g + 1) / 2 * ast**2 - (g - 1) / 2 * u**2
    sym_zero("P4b a^2/(g-1) + u^2/2 = (g+1)/(2(g-1)) a*^2", a2 / (g - 1) + u**2 / 2 - (g + 1) / (2 * (g - 1)) * ast**2)
    u1 = sp.symbols("u_1", positive=True)
    u2 = ast**2 / u1
    lhs = a2.subs(u, u1) / (g * u1) - a2.subs(u, u2) / (g * u2)
    sym_zero("P4c Prandtl's relation satisfies the momentum/mass equation", lhs - (u2 - u1))
    M = sp.symbols("M_1", positive=True)
    ratio = sp.solve(sp.Eq(1 / M**2, (g + 1) / 2 / sp.Symbol("X") - (g - 1) / 2), sp.Symbol("X"))[0]
    sym_zero("P4d (u1/a*)^2 = (g+1)M^2/(2+(g-1)M^2)", ratio - (g + 1) * M**2 / (2 + (g - 1) * M**2))
    r21 = (g + 1) * M**2 / (2 + (g - 1) * M**2)
    sym_zero("P4d p2/p1 = 1 + g M^2 (1 - rho1/rho2) = 1 + 2g/(g+1)(M^2-1)", 1 + g * M**2 * (1 - 1 / r21) - (1 + 2 * g / (g + 1) * (M**2 - 1)))
    for Mv in (1.3, 1.8, 2.5):
        r = GD.normal_shock(Mv)
        check(f"P4d engine density ratio at M={Mv}", r["rho"], float(r21.subs({g: 1.4, M: Mv})), tol=1e-12)
    m = sp.symbols("m", positive=True)
    G7 = sp.Rational(7, 5)
    p21 = 1 + 2 * G7 / (G7 + 1) * m
    rr = (G7 + 1) * (1 + m) / (2 + (G7 - 1) * (1 + m))
    sR = (sp.log(p21) - G7 * sp.log(rr)) / (G7 - 1)
    ser = sp.series(sR, m, 0, 4).removeO()
    sym_zero("P4e Delta s/R = 2g m^3/(3(g+1)^2) to third order", ser - 2 * G7 / (3 * (G7 + 1)**2) * m**3)
    check("P4e coefficient for air", 2 * 1.4 / (3 * 2.4**2), 0.162)
    check("P4e loss at m = 0.1 (%)", (1 - np.exp(-0.162 * 0.001)) * 100, 0.02, tol=0.005)
    r = GD.normal_shock(1.1)
    check("P4e exact loss at M = 1.1 (%)", (1 - r["p0"]) * 100, 0.11)
    check("P4e cube law at M = 1.1 (%)", (1 - np.exp(-2 * 1.4 / (3 * 2.4**2) * 0.21**3)) * 100, 0.15)
    check("P4e p02/p01 = exp(-Delta s/R) at M=2", np.exp(-float(sR.subs(m, 3))), GD.normal_shock(2.0)["p0"], tol=1e-12)


def transonic_similarity():
    """Guided derivation 5: the critical Mach number of a thin section."""
    Mv = sp.symbols("M", positive=True)
    G7 = sp.Rational(7, 5)
    cps = 2 / (G7 * Mv**2) * (((2 + (G7 - 1) * Mv**2) / (G7 + 1))**(G7 / (G7 - 1)) - 1)
    sym_zero("P5a C_p*(1) = 0", cps.subs(Mv, 1))
    sym_zero("P5a dC_p*/dM at 1 = 4/(g+1)", sp.diff(cps, Mv).subs(Mv, 1) - 4 / (G7 + 1))
    for cp0, approx, full in ((-0.25, 0.776, 0.805), (-0.43, 0.678, 0.737)):
        e = (2.4 * abs(cp0) / (4 * np.sqrt(2)))**(2 / 3)
        check(f"P5d 1 - M_cr by the law, C_p0={cp0}", e, 1 - approx, tol=6e-4)
        check(f"P5d M_cr by the law, C_p0={cp0}", 1 - e, approx)
        check(f"P5d M_cr by the construction, C_p0={cp0}", GD.critical_mach(cp0), full)
        truth(f"P5d the law is below the construction for C_p0={cp0}", 1 - e < GD.critical_mach(cp0))
    check("P5c 2^(-2/3)", 2**(-2 / 3), 0.63)


def mach_cutoff():
    """Guided derivation 6: the cutoff Mach number."""
    check("P6c cutoff, standard day", np.sqrt(288.15 / 216.65), 1.153)
    check("P6d cutoff, 40 C at the ground", np.sqrt(313.15 / 216.65), 1.202)
    a_f = A.speed_of_sound(216.65)
    a_g = A.speed_of_sound(288.15)
    check("P6c the same from speeds of sound", a_g / a_f, 1.153)
    # the wavefront turns vertical where a(h) = V: below the aircraft at M = 1.1 in the ISA
    V = 1.1 * a_f
    hs = np.linspace(0, 11e3, 11001)
    aa = np.array([A.speed_of_sound(A.isa(h)[0]) for h in hs])
    truth("P6c at M = 1.1 the front turns vertical above the ground (a(h) = V somewhere)", aa.max() > V > aa.min())


def hypersonic_limit():
    """Guided derivation 7: the hypersonic limit of the normal shock."""
    g, M = sp.symbols("gamma M", positive=True)
    p21 = 1 + 2 * g / (g + 1) * (M**2 - 1)
    r21 = (g + 1) * M**2 / (2 + (g - 1) * M**2)
    M22 = (1 + (g - 1) / 2 * M**2) / (g * M**2 - (g - 1) / 2)
    sym_zero("P7a rho ratio limit", sp.limit(r21, M, sp.oo) - (g + 1) / (g - 1))
    sym_zero("P7a p ratio ~ 2g M^2/(g+1)", sp.limit(p21 / M**2, M, sp.oo) - 2 * g / (g + 1))
    sym_zero("P7a T ratio ~ 2g(g-1)M^2/(g+1)^2", sp.limit(p21 / r21 / M**2, M, sp.oo) - 2 * g * (g - 1) / (g + 1)**2)
    sym_zero("P7a M2^2 limit", sp.limit(M22, M, sp.oo) - (g - 1) / (2 * g))
    check("P7a M2 limit for air", np.sqrt(0.4 / 2.8), 0.378)
    check("P7a engine M2 at M=50", GD.normal_shock(50.0)["M2"], 0.378)
    sym_zero("P7b T2/Tt limit", sp.limit(p21 / r21 / (1 + (g - 1) / 2 * M**2), M, sp.oo) - 4 * g / (g + 1)**2)
    check("P7b for air", 4 * 1.4 / 2.4**2, 0.972)
    cpm = ((2.4**2 / 5.6)**3.5) * (4 / 2.4)
    check("P7c C_p,max limit", cpm, 1.839)
    Mb = 200.0
    check("P7c engine Rayleigh pitot at M=200 gives the same", (GD.rayleigh_pitot(Mb) - 1) * 2 / (1.4 * Mb**2), 1.839)
    cp = 1.4 * 287.053 / 0.4
    check("P7d T_t - T at 7.8 km/s (K)", 7800**2 / (2 * cp), 30280, tol=10)
    check("P7d T_t (K)", 200 + 7800**2 / (2 * cp), 30500, tol=50)


if __name__ == "__main__":
    run([objective, concorde, sweep, scramjet, shock_derivation, transonic_similarity, mach_cutoff, hypersonic_limit])
