"""Checks every number in the answers and solutions of 09-real-atmosphere-questions.qmd,
including the guided derivations 4-7.
Run from anywhere:  python3 codes/09-real-atmosphere-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.integrate import quad
from _verify import check, truth, sym_zero, Objective, run
from flight import atmosphere as A
from flight.constants import R_AIR, P0_SL, RHO0_SL, FT, G0

PAGE = os.path.join(HERE, "..", "09-real-atmosphere-questions.qmd")
HL = A.geopotential(3256.0)


def objective():
    """The 12 objective questions."""
    q = Objective(PAGE, 12)
    truth("Q5 answer is ISA +25", "+25" in q.right(5))
    q.num(6, 288.15 / 313.15, "0.920")
    check("Q6 distractor 1/sigma", 313.15 / 288.15, 1.087)
    q.num(7, 900 + 20 * A.density_altitude_rule(), "1620", tol=5)
    check("Q7 rule (m)", 900 + 20 * A.density_altitude_rule(), 1623)
    hd7 = A.density_altitude_from(900.0, A.isa(900.0)[0] + 20)
    check("Q7 exact (m)", hd7, 1593)
    check("Q7 rule within 2 %", (1623 - hd7) / hd7 * 100, 2, tol=0.5)
    q.num(8, A.local_scale_height(288.15, -0.0065) / 1e3, "10.4")
    check("Q8 by hand (km)", 287.053 * 288.15 / (9.80665 - 287.053 * 0.0065) / 1e3, 10.42)
    check("Q8 distractor RT0/g0 (km)", A.scale_height(288.15) / 1e3, 8.43)
    hp500 = A.pressure_altitude(50000.0)
    check("Q9 500 hPa standard height (m)", hp500, 5574)
    dh = A.thickness(0.0, hp500, 10.0) - hp500
    q.num(9, dh, "210", tol=5)
    check("Q9 by the formula (m)", 10 / 0.0065 * np.log(288.15 / (288.15 - 0.0065 * 5574)), 207)
    check("Q9 relative (%)", dh / hp500 * 100, 3.7)
    Tm = np.mean([A.isa(h)[0] for h in np.linspace(0, hp500, 200)])
    check("Q9 mean warming (%)", 10 / Tm * 100, 3.7, tol=0.1)
    es = A.saturation_vapour_pressure(303.15)
    check("Q10 e_s (Pa)", es, 4237)
    q.num(10, 100 * (1 - A.moist_density(P0_SL, 303.15, es) / (P0_SL / (R_AIR * 303.15))), "1.6")
    check("Q10 distractor e/p (%)", es / P0_SL * 100, 4.2)
    q.num(11, 70 / np.sqrt(0.647), "87")
    check("Q11 distractor 70/sigma", 70 / 0.647, 108)
    q.num(12, 7.2 * np.log(1.27), "1.7")
    check("Q12 ln 1.27", np.log(1.27), 0.239)
    check("Q12 distractor 0.27 H", 0.27 * 7.2, 1.9)


def leh():
    """Drill 1: Leh at dawn and in the afternoon."""
    check("P1 T_std (K)", A.isa(HL)[0], 267.0)
    out = {}
    for oat, dT_q, rho_q, sig_q, hd_q, f_q in ((5, 11.2, 0.8500, 0.694, 3647, 1.200), (30, 36.2, 0.7799, 0.637, 4462, 1.253)):
        T = oat + 273.15
        dT = T - A.isa(HL)[0]
        check(f"P1 {oat} C: dT", dT, dT_q)
        t, p, r = A.at_pressure_altitude(HL, dT)
        check(f"P1 {oat} C: p (Pa)", p, 67870, tol=1)
        check(f"P1 {oat} C: rho", r, rho_q)
        check(f"P1 {oat} C: sigma", r / RHO0_SL, sig_q)
        hd = A.density_altitude_from(HL, T)
        check(f"P1 {oat} C: density altitude (m)", hd, hd_q)
        check(f"P1 {oat} C: speed factor", 1 / np.sqrt(r / RHO0_SL), f_q)
        out[oat] = (hd, r)
    d = out[30][0] - out[5][0]
    check("P1 change (m)", d, 815, tol=1)
    check("P1 change from the rounded values (m)", 4462 - 3647, 815, tol=0)
    check("P1 per kelvin", d / 25, 32.6)
    check("P1 rule over 25 K (m)", A.density_altitude_rule() * 25, 904)
    check("P1 lift-off speed 4 % higher", (np.sqrt(out[5][1] / out[30][1]) - 1) * 100, 4, tol=0.5)


def chennai():
    """Drill 2: a humid afternoon at Chennai."""
    T = 305.15
    es = A.saturation_vapour_pressure(T)
    check("P2 e_s (Pa)", es, 4749)
    e = 0.75 * es
    check("P2 e (Pa)", e, 3561)
    rd = P0_SL / (R_AIR * T)
    check("P2 dry rho", rd, 1.1568)
    rm = A.moist_density(P0_SL, T, e)
    check("P2 moist rho", rm, 1.1414)
    check("P2 moist by the factor", 1.1568 * (1 - 0.378 * 3561 / 101325), 1.1414)
    check("P2 drop (%)", 100 * (1 - rm / rd), 1.33)
    check("P2 dry density altitude (m)", A.density_altitude(rd), 593)
    check("P2 moist density altitude (m)", A.density_altitude(rm), 730)
    check("P2 humidity adds (m)", A.density_altitude(rm) - A.density_altitude(rd), 140, tol=5)
    check("P2 equivalent kelvin", (A.density_altitude(rm) - A.density_altitude(rd)) / A.density_altitude_rule(), 4, tol=0.3)
    check("P2 dT", T - 288.15, 17)
    check("P2 temperature effect four times", A.density_altitude(rd) / (A.density_altitude(rm) - A.density_altitude(rd)), 4, tol=0.35)


def fl370():
    """Extension 3: an airliner at FL370 on an ISA+10 day."""
    hp = 37000 * FT
    check("P3 FL370 (m)", hp, 11278)
    t, p, r = A.at_pressure_altitude(hp, 10.0)
    check("P3 T (K)", t, 226.65)
    check("P3 T (C)", t - 273.15, -46.5)
    check("P3 p (Pa)", p, 21663)
    check("P3 p by hand", 22632 * np.exp(-277.6 / 6341.6), 21663)
    check("P3 rho", r, 0.3330)
    check("P3 sigma", r / RHO0_SL, 0.272)
    a = A.speed_of_sound(t)
    check("P3 a (m/s)", a, 301.8)
    h11 = 11000 + 10 / 0.0065 * np.log(288.15 / 216.65)
    check("P3 true height of the 11 km level (m)", h11, 11439)
    check("P3 isothermal factor", 1 + 10 / 216.65, 1.0462)
    check("P3 277.6 m become (m)", 277.6 * (1 + 10 / 216.65), 290)
    ht = A.thickness(0.0, hp, 10.0)
    check("P3 true height (m)", ht, 11729)
    check("P3 above the flight level (m)", ht - hp, 452)
    check("P3 Mach on the warm day", 240 / a, 0.795)
    check("P3 standard a", A.speed_of_sound(216.65), 295.1)
    check("P3 Mach on a standard day", 240 / A.speed_of_sound(216.65), 0.813)


LAM, T0 = 0.0065, 288.15


def cold_correction():
    """Guided derivation 4: the cold-temperature correction above an airfield."""
    dT, L, ha, hi, Tb, x = sp.symbols("Delta_T Lambda h_a h_i Tbar x", positive=True)
    sym_zero("P4b ln((1+x)/(1-x)) = 2x + 2x^3/3 + O(x^5)",
             sp.series(sp.log((1 + x) / (1 - x)), x, 0, 5).removeO() - 2 * x - sp.Rational(2, 3) * x**3)
    Ts = lambda h: T0 - LAM * h
    check("P4d geopotential elevation (m)", HL, 3254, tol=0.5)
    check("P4d standard temperature at the airfield (K)", Ts(HL), 267.0)
    d = 248.15 - Ts(HL)
    check("P4d deviation (K)", d, -18.8, tol=0.06)
    hi_ = HL + 600
    check("P4d T_std at h_i (K)", Ts(hi_), 263.10)
    tr = 600 + d / LAM * np.log(Ts(HL) / Ts(hi_))
    check("P4d true height above the runway by (a) (m)", tr, 557)
    check("P4d mid-point temperature (K)", Ts(HL + 300), 265.05)
    check("P4d true height by (b) (m)", 600 * (1 + d / Ts(HL + 300)), 557)
    check("P4d (a) and (b) agree to the neglected term", abs(tr - 600 * (1 + d / Ts(HL + 300))), 0, tol=600 * abs(d) / 265 * (LAM * 600)**2 / (12 * 265**2) * 1.01)
    check("P4d lower by (m)", 600 - tr, 43)
    check("P4d rule (m)", abs(d) / 10 * 0.04 * 600, 45)
    check("P4c rule exact at (K)", 10 / 0.04, 250)
    check("P4c correction per 10 K at 288 K (%)", 10 / 288.15 * 100, 3.5)


def virtual():
    """Guided derivation 5: the virtual temperature."""
    eps = R_AIR / 461.5
    check("P5a epsilon", eps, 0.622)
    check("P5b (1-eps)/eps", (1 - eps) / eps, 0.608)
    e, p, T = 3932.0, 101325.0, 308.15
    rho = A.moist_density(p, T, e)
    Tv = T / (1 - (1 - eps) * e / p)
    check("P5a p/(R T_v) = moist density", p / (R_AIR * Tv), rho, tol=1e-12)
    q = eps * e / (p - (1 - eps) * e)
    check("P5d q", q, 0.0245)
    check("P5d T_v (K)", Tv, 312.74)
    check("P5d T_v - T (K)", Tv - T, 4.59)
    check("P5b first-order T_v (K)", T * (1 + (1 - eps) / eps * q), Tv, tol=0.01)
    rule = 0.0065 * (A.pressure_exponent(-0.0065) - 1)
    check("P5d rule 36.1 m/K", 1 / rule, 36.1)
    check("P5d rule (m)", (20 + Tv - T) * 36.1, 888)
    check("P5d exact density altitude (m)", A.density_altitude(rho), 845)
    check("P5d moist scale height (km)", R_AIR * Tv / G0 / 1e3, 9.15)
    check("P5d dry scale height (km)", R_AIR * T / G0 / 1e3, 9.02)
    check("P5d taller by (%)", (Tv / T - 1) * 100, 1.5)


def one_scale_height():
    """Guided derivation 6: choosing one scale height."""
    check("P6a column-mass H (km)", P0_SL / (RHO0_SL * G0) / 1e3, 8.43)
    s1 = A.isa(11e3)[2] / RHO0_SL
    check("P6b sigma at 11 km", s1, 0.2971)
    check("P6b H (km)", 11 / np.log(1 / s1), 9.06)
    hs = np.linspace(0, 20e3, 4001)
    ls = np.array([np.log(A.isa(h)[2] / RHO0_SL) for h in hs])
    check("P6c least-squares H (km)", -np.trapz(hs * hs, hs) / np.trapz(hs * ls, hs) / 1e3, 8.20)
    check("P6c Hull's H (km)", 26600 * FT / 1e3, 8.11)
    lam, g, R, T, D = sp.symbols("lambda g_0 R T Delta", real=True)
    rho = (1 + lam * D / T) ** (-g / (R * lam) - 1)
    quad = sp.series(sp.log(rho), D, 0, 3).removeO().coeff(D, 2)
    Hr = R * T / (g + R * lam)
    sym_zero("P6d quadratic term of ln(rho) = (1/2)(R lam/(g+R lam))/H_rho^2", quad - sp.Rational(1, 2) * R * lam / (g + R * lam) / Hr**2)
    c = R_AIR * -LAM / (G0 + R_AIR * -LAM)
    check("P6d R lam/(g + R lam)", c, -0.235)
    Hs = A.local_scale_height(T0, -LAM)
    check("P6d H_rho at sea level (km)", Hs / 1e3, 10.42)
    check("P6d error at 5 km (%)", -0.5 * c * (5e3 / Hs)**2 * 100, 2.7)
    true5 = A.isa(5e3)[2]
    fit5 = RHO0_SL * np.exp(-5e3 / Hs)
    check("P6d actual error 5 km above sea level (%)", (fit5 / true5 - 1) * 100, 3.0)


def round_trip():
    """Guided derivation 7: the wind never pays back."""
    w, th = sp.symbols("w theta", positive=True)
    f = 1 / (w * sp.cos(th) + sp.sqrt(1 - w**2 * sp.sin(th)**2))
    ser = sp.series(f, w, 0, 3).removeO()
    sym_zero("P7c 1/V_g to second order", ser - (1 - w * sp.cos(th) + w**2 * sp.cos(th)**2 + w**2 * sp.sin(th)**2 / 2))
    sym_zero("P7c average = 1 + 3w^2/4", sp.integrate(ser, (th, 0, 2 * sp.pi)) / (2 * sp.pi) - 1 - sp.Rational(3, 4) * w**2)
    V, W, sdist = 250.0, 60.0, 2000e3
    wv = W / V
    check("P7d w", wv, 0.24)
    check("P7d still-air round trip (h)", 2 * sdist / V / 3600, 4.44)
    check("P7d with wind (h)", 2 * sdist / V / (1 - wv**2) / 3600, 4.72)
    check("P7d extra (min)", 2 * sdist / V * (1 / (1 - wv**2) - 1) / 60, 16.3)
    check("P7d westward leg (h)", sdist / (V - W) / 3600, 2.92)
    check("P7d eastward leg (h)", sdist / (V + W) / 3600, 1.79)
    avg = quad(lambda t: 1 / (wv * np.cos(t) + np.sqrt(1 - wv**2 * np.sin(t)**2)), 0, 2 * np.pi)[0] / (2 * np.pi)
    check("P7d circle exact factor", avg, 1.0457)
    check("P7d circle approx factor", 1 + 0.75 * wv**2, 1.0432)
    check("P7d circle extra (%)", (avg - 1) * 100, 4.6)
    check("P7b crosswind factor > 1", 1 / np.sqrt(1 - wv**2), 1.030)



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
    a10 = At.speed_of_sound(At.isa(10000.0)[0]); V = 0.7 * a10; w = 100 * 0.5144
    check("E9 a", a10, 299.46, tol=0.005)
    check("E9 V", V, 209.6, tol=0.05)
    check("E9 with wind (s)", 6000e3 / (V + w), 22983, tol=1)
    check("E9 against (s)", 6000e3 / (V - w), 37930, tol=1)
    check("E9 hours with", 6000e3 / (V + w) / 3600, 6.38, tol=0.005)
    check("E9 hours against", 6000e3 / (V - w) / 3600, 10.54, tol=0.005)
    check("E9 round trip", (6000e3 / (V + w) + 6000e3 / (V - w)) / 3600, 16.92, tol=0.005)
    check("E9 still air", 12000e3 / V / 3600, 15.90, tol=0.005)
    check("E9 T actual", 288.15 - 0.0065 * 9150, 228.675, tol=5e-4)
    check("E9 T standard", 288.15 - 0.0065 * 9000, 229.65, tol=5e-3)
    check("E9 Td", -0.0065 * 150, -0.975, tol=5e-4)
    check("E9 ground speed with the wind", V + w, 261.1, tol=0.06)
    check("E9 ground speed against the wind", V - w, 158.2, tol=0.06)


if __name__ == "__main__":
    run([objective, leh, chennai, fl370, cold_correction, virtual, one_scale_height, round_trip, earlier_papers])
