"""Checks every number in the answers and solutions of 10-airspeed-questions.qmd,
including the guided derivations 4-7.
Run from anywhere:  python3 codes/10-airspeed-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 airspeed as AS, atmosphere as A
from flight.constants import KT, P0_SL, A0_SL, RHO0_SL, R_AIR

PAGE = os.path.join(HERE, "..", "10-airspeed-questions.qmd")


def checks(name, values, quoted, tol=None):
    """check() for several numbers quoted together; tol is one value or one per number."""
    tols = tol if isinstance(tol, tuple) else (tol,) * len(values)
    for k, (v, q, t) in enumerate(zip(values, quoted, tols)):
        check(f"{name} [{k + 1}]", v, q, **({} if t is None else dict(tol=t)))


def objective():
    """The 12 objective questions."""
    q = Objective(PAGE, 12)
    truth("Q1 answer is the impact pressure", "q_c=p_t-p" in q.right(1))
    truth("Q2 answer is the dynamic-pressure definition", "rho_0V_e^2" in q.right(2))
    s3 = A.isa(3000.0)[2] / RHO0_SL
    check("Q5 sigma(3000 m)", s3, 0.7421)
    q.num(5, 80 / np.sqrt(s3), "92.9")
    check("Q5 sqrt(sigma)", np.sqrt(s3), 0.8615)
    check("Q5 distractor A", 80 * np.sqrt(s3), 68.9)
    check("Q5 distractor B", 80 / s3, 107.8)
    q.num(6, (AS.compressibility_ratio(0.5) - 1) * 100, "6.4")
    check("Q6 series", 1 + 0.25 / 4 + 0.0625 / 40, 1.064)
    check("Q6 exact ratio", AS.compressibility_ratio(0.5), 1.0641)
    checks("Q6 terms", (0.25 / 4, 0.0625 / 40), (0.0625, 0.0016), tol=5e-5)
    check("Q7 Bernoulli with rho0 (m/s)", np.sqrt(2 * 5000 / RHO0_SL), 90.4)
    check("Q7 qc/p0", 5000 / P0_SL, 0.04935)
    check("Q7 Mach", AS.mach_from_impact_ratio(5000 / P0_SL), 0.2632)
    q.num(7, AS.cas_from_impact(5000.0), "89.6")
    check("Q7 distractor B (no factor 2)", np.sqrt(5000 / RHO0_SL), 63.9)
    truth("Q8 Mach rises at constant CAS, also in the stratosphere",
          np.all(np.diff([AS.mach_at_cas(280 * KT, h) for h in np.linspace(0, 15000, 31)]) > 0))
    # Q9
    t6, p6, r6 = A.isa(6000.0)
    a6 = A.speed_of_sound(t6)
    check("Q9 p(6 km)", p6, 47181, tol=0.5)
    check("Q9 a(6 km)", a6, 316.43)
    check("Q9 Vc/a0", 250 * KT / A0_SL, 0.3779)
    check("Q9 Vc (m/s)", 250 * KT, 128.61)
    qc9 = AS.impact_from_cas(250 * KT)
    check("Q9 qc (Pa)", qc9, 10500, tol=5)
    check("Q9 qc/p", qc9 / p6, 0.2225)
    M9 = AS.mach_at_cas(250 * KT, 6000.0)
    q.num(9, M9, "0.544")
    check("Q9 distractor C (EAS treatment)", 250 * KT / np.sqrt(r6 / RHO0_SL) / a6, 0.554)
    check("Q9 distractor B", 250 * KT / a6, 0.406)
    check("Q9 distractor D", 250 * KT / A0_SL, 0.378)
    # Q10: trapped static pressure in a climb
    p_trap = P0_SL
    for h, M in ((1000.0, 0.15), (2000.0, 0.15)):
        p = A.isa(h)[1]
        qc = p * AS.impact_ratio(M)
        truth(f"Q10 indicated difference below the real qc at {h:.0f} m", (p + qc) - p_trap < qc)
    # Q11
    q.num(11, AS.mach_from_impact_ratio(2.0), "1.386")
    check("Q11 subsonic formula", np.sqrt(5 * (3.0 ** (2 / 7) - 1)), 1.358)
    truth("Q11 3.0 exceeds the sonic value", 3.0 > 1 + AS.R_SONIC)
    check("Q11 sonic value", 1 + AS.R_SONIC, 1.893)
    # Q12
    hx = AS.crossover_altitude(300 * KT, 0.80)
    q.num(12, hx / 1e3, "9.3")
    check("Q12 qc/p at M 0.80", AS.impact_ratio(0.8), 0.5243)
    d = (300 * KT / (A0_SL * 0.8)) ** 2
    check("Q12 distractor C, low-speed link (km)", A.pressure_altitude(d * P0_SL) / 1e3, 8.6)


def saras():
    """Drill 1: SARAS at 550 km/h at 6000 m."""
    V = 550 / 3.6
    t, p, r = A.isa(6000.0)
    a = A.speed_of_sound(t)
    check("P1 V (m/s)", V, 152.78)
    checks("P1 T, p, rho, a", (t, p, r, a), (249.15, 47181, 0.6597, 316.43), tol=(0.005, 0.5, 5e-5, 0.005))
    M = V / a
    check("P1 Mach", M, 0.483)
    q = 0.5 * r * V**2
    qc = p * AS.impact_ratio(M)
    check("P1 q (Pa)", q, 7699)
    check("P1 qc (Pa)", qc, 8158)
    check("P1 qc/q - 1 (%)", (qc / q - 1) * 100, 6.0)
    check("P1 sigma", r / RHO0_SL, 0.5385)
    ve = AS.eas_from_tas(V, r)
    checks("P1 EAS (m/s, kt)", (ve, ve / KT), (112.1, 217.9))
    check("P1 qc/p0", qc / P0_SL, 0.08052, tol=1.5e-5)
    vc = AS.cas_from_impact(qc)
    checks("P1 CAS (m/s, kt)", (vc, vc / KT), (113.8, 221.2))
    check("P1 TAS (kt)", V / KT, 297.0)
    vb = AS.incompressible_speed(qc, r)
    check("P1 Bernoulli (m/s)", vb, 157.3)
    check("P1 Bernoulli error (%)", (vb / V - 1) * 100, 2.9)


def deccan():
    """Drill 2: IAS 120 kt, position error +3 kt, pressure altitude 3000 m, ISA +15."""
    vc = 123 * KT
    check("P2 Vc (m/s)", vc, 63.28)
    qc = AS.impact_from_cas(vc)
    check("P2 qc (Pa)", qc, 2474, tol=0.5)
    t, p, r = A.at_pressure_altitude(3000.0, 15.0)
    check("P2 p (Pa)", p, 70109, tol=0.5)
    checks("P2 T_std, T (K)", (t - 15, t), (268.65, 283.65), tol=1e-6)
    check("P2 rho", r, 0.8610)
    check("P2 sigma", r / RHO0_SL, 0.7029)
    check("P2 qc/p", qc / p, 0.03528, tol=1e-5)
    M = AS.mach_from_impact_ratio(qc / p)
    check("P2 Mach", M, 0.2231)
    a = A.speed_of_sound(t)
    check("P2 a (m/s)", a, 337.63)
    V = M * a
    checks("P2 TAS (m/s, kt)", (V, V / KT), (75.33, 146.4))
    a_std = A.speed_of_sound(t - 15)
    check("P2 standard a (m/s)", a_std, 328.6)
    Vn = M * a_std
    check("P2 navigator TAS (kt)", Vn / KT, 142.5)
    check("P2 navigator error (%)", (1 - Vn / V) * 100, 2.7)
    check("P2 an hour's error (nmi)", (V - Vn) / KT, 4, tol=0.1)


def tejas():
    """Extension 3: a supersonic Mach meter by hand at 11 km, p_t/p = 4.0."""
    check("P3 a(11 km)", A.speed_of_sound(A.isa(11000.0)[0]), 295.07)
    checks("P3 both formulas at Mach 1", (1 + AS.impact_ratio_subsonic(1.0), 1 + AS.impact_ratio_supersonic(1.0)), (1.893, 1.893))
    checks("P3 Rayleigh pieces at Mach 1", (2.4**2 / (5.6 - 0.8), (1 - 1.4 + 2.8) / 2.4), (1.2, 1.0), tol=1e-12)
    f = lambda m: 1 + AS.impact_ratio_supersonic(m)
    lo, hi = 1.0, 2.0
    quoted = [(1.5, 3.413), (1.75, 4.443), (1.625, 3.907), (1.6875, 4.170), (1.65625, 4.037), (1.640625, 3.972)]
    for k, (mid_q, f_q) in enumerate(quoted, 1):
        mid = 0.5 * (lo + hi)
        checks(f"P3 step {k}: midpoint and f", (mid, f(mid)), (mid_q, f_q), tol=(1e-12, 5e-4))
        if f(mid) > 4.0:
            hi = mid
        else:
            lo = mid
    M = AS.mach_from_impact_ratio(3.0)
    check("P3 Mach", M, 1.647)
    V = M * A.speed_of_sound(A.isa(11000.0)[0])
    check("P3 TAS (m/s)", V, 486.1)
    check("P3 TAS (kt)", V / KT, 945, tol=1)
    Ms = np.sqrt(5 * (4.0 ** (2 / 7) - 1))
    check("P3 subsonic formula", Ms, 1.559)
    check("P3 error (%)", (1 - Ms / M) * 100, 5.4)


def crossover():
    """Guided derivation 4: the crossover altitude in closed form."""
    def dx(vc, M):
        return ((1 + 0.2 * (vc / A0_SL)**2)**3.5 - 1) / ((1 + 0.2 * M**2)**3.5 - 1)
    vc = 280 * KT
    check("P4b 280 kt (m/s)", vc, 144.04)
    check("P4b a0 (m/s)", A0_SL, 340.29)
    d = dx(vc, 0.78)
    check("P4b delta_x", d, 0.2651)
    truth("P4b above the tropopause ratio 0.2234", d > A.isa(11e3)[1] / P0_SL and abs(A.isa(11e3)[1] / P0_SL - 0.2234) < 5e-5)
    hx = 288.15 / 0.0065 * (1 - d**(1 / A.pressure_exponent(-0.0065)))
    check("P4b crossover (km)", hx / 1e3, 9.90)
    check("P4b agrees with the engine's root (m)", hx, AS.crossover_altitude(vc, 0.78), tol=0.5)
    d3 = dx(300 * KT, 0.78)
    check("P4d 300 kt delta_x", d3, 0.3064)
    check("P4d 300 kt crossover (km)", 288.15 / 0.0065 * (1 - d3**(1 / 5.2559)) / 1e3, 8.93)
    check("P4d 300 kt (m/s)", 300 * KT, 154.3)
    check("P4d a0 M (m/s)", A0_SL * 0.78, 265.4)
    check("P4d small-Mach estimate", (300 * KT / (A0_SL * 0.78))**2, 0.338)
    check("P4d too high by (%)", ((300 * KT / (A0_SL * 0.78))**2 / d3 - 1) * 100, 10, tol=1)


def air_data():
    """Guided derivation 5: the air-data computer."""
    T, p, rho = A.isa(11e3)
    a = A.speed_of_sound(T)
    M = 0.78
    V = M * a
    check("P5c T (K)", T, 216.65)
    check("P5c a (m/s)", a, 295.07)
    check("P5c V (m/s)", V, 230.15)
    cp = 1.4 * R_AIR / 0.4
    check("P5a rise = V^2/(2cp) = T(gamma-1)M^2/2", V**2 / (2 * cp), T * 0.2 * M**2, tol=1e-9)
    check("P5c ram rise (K)", T * 0.2 * M**2, 26.4)
    check("P5c T_t (K)", T * (1 + 0.2 * M**2), 243.0)
    Tm = T * (1 + 0.95 * 0.2 * M**2)
    check("P5c probe reading (K)", Tm, 241.7)
    check("P5c 1 + 0.2 M^2", 1 + 0.2 * M**2, 1.1217)
    Tw = Tm / (1 + 0.2 * M**2)
    check("P5c computed T with r = 1 (K)", Tw, 215.5)
    check("P5c too cold by (K)", T - Tw, 1.2)
    Vw = M * np.sqrt(1.4 * R_AIR * Tw)
    check("P5c TAS too low by (m/s)", V - Vw, 0.63)
    check("P5c in per cent", (V - Vw) / V * 100, 0.27)
    check("P5b formula with the right r gives V", M * np.sqrt(1.4 * R_AIR * Tm / (1 + 0.95 * 0.2 * M**2)), V, tol=1e-9)
    check("P5d Concorde nose (K)", 217 * (1 + 0.2 * 4), 391, tol=0.5)
    check("P5d in deg C", 217 * 1.8 - 273.15, 117, tol=0.5)
    check("P5d growth of a 60 m airframe (m)", 23e-6 * 100 * 60, 0.14)


def static_error():
    """Guided derivation 6: the static-port error."""
    C, x = sp.symbols("C x", real=True)
    sym_zero("P6a sqrt(1-C) = 1 - C/2 + O(C^2)", sp.series(sp.sqrt(1 - C), C, 0, 2).removeO() - (1 - C / 2))
    g = 9.80665
    for V, dV, dh in ((50, 0.5, 2.5), (150, 1.5, 22.9)):
        check(f"P6d speed error at {V} m/s (first order)", 0.01 * V, dV)
        check(f"P6d height error at {V} m/s (m)", 0.02 * V**2 / (2 * g), dh)
        check(f"P6c dh g/V^2 = dV/V at {V} m/s", 0.02 * V**2 / (2 * g) * g / V**2, 0.01, tol=1e-12)
    check("P6d jet at 250 m/s (m)", 0.02 * 250**2 / (2 * g), 64)
    check("P6d a fifth of 300 m", 0.02 * 250**2 / (2 * g) / 300, 0.2, tol=0.02)
    # at sea level the exact pressure-altitude error matches the hydrostatic estimate
    q = 0.5 * RHO0_SL * 150**2
    check("P6b exact altimeter error at sea level, 150 m/s (m)", A.pressure_altitude(P0_SL - 0.02 * q), 22.9, tol=0.2)


def cas_series():
    """Guided derivation 7: CAS minus EAS as a series."""
    Ve, a0, d, e = sp.symbols("V_e a_0 delta epsilon", positive=True)
    Vc2 = Ve**2 * (1 + Ve**2 / (a0**2 * d) / 4) / (1 + Ve**2 / a0**2 / 4)
    ser = sp.series(sp.sqrt(Vc2.subs(Ve, e * Ve)) / (e * Ve), e, 0, 3).removeO()
    sym_zero("P7b V_c/V_e = 1 + (V_e^2/8a0^2)(1/delta - 1) + O(4)", ser - (1 + e**2 * Ve**2 / (8 * a0**2) * (1 / d - 1)))
    T, p, rho = A.isa(9e3)
    V = 0.75 * A.speed_of_sound(T)
    ve = AS.eas_from_tas(V, rho)
    vcx = AS.cas_from_impact(p * AS.impact_ratio(0.75))
    dl = p / P0_SL
    check("P7c delta at 9 km", dl, 0.3034)
    check("P7c 1/delta - 1", 1 / dl - 1, 2.296)
    check("P7c V_e (m/s)", ve, 140.58)
    check("P7c series (m/s)", ve**3 * (1 / dl - 1) / (8 * A0_SL**2), 6.9)
    check("P7c exact (m/s)", vcx - ve, 6.6)
    check("P7c series good to (%)", ((ve**3 * (1 / dl - 1) / (8 * A0_SL**2)) / (vcx - ve) - 1) * 100, 4, tol=0.5)
    check("P7c half pressure at (km)", A.pressure_altitude(P0_SL / 2) / 1e3, 5.5, tol=0.05)
    v1 = A0_SL * np.sqrt(0.08 / (1 / dl - 1))
    check("P7d 1 % at (m/s)", v1, 63.5)
    check("P7d in kt", v1 / KT, 123)



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
    sg = At.isa(1000.0)[2] / At.isa(0.0)[2]
    check("E10 sigma", sg, 0.9075, tol=5e-5)
    check("E10 TAS", 100 / np.sqrt(0.9075), 104.97, tol=0.005)
    check("E10 ground speed", 100 / np.sqrt(0.9075) - 10.29, 94.68, tol=0.006)
    check("E10 distance km", (100 / np.sqrt(0.9075) - 10.29) * 0.9, 85.2, tol=0.05)
    check("E10 Mach at 200 m/s, 1 km", 200 / At.speed_of_sound(At.isa(1000.0)[0]), 0.6, tol=0.01)

if __name__ == "__main__":
    run([objective, saras, deccan, tejas, crossover, air_data, static_error, cas_series, earlier_papers])
