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

PAGE = os.path.join(HERE, "..", "08-standard-atmosphere-questions.qmd")


def objective():
    """The 12 objective questions."""
    q = Objective(PAGE, 12)
    t10 = A.isa(10e3)[0]
    q.num(5, t10 - 273.15, "-50", x=-50.0)
    check("Q5 T (K)", t10, 223.15)
    th, de, si = A.ISA.ratios(A.geometric(11e3))
    q.num(6, si, "0.297")
    check("Q6 by the exponent 4.2559", (216.65 / 288.15) ** 4.2559, 0.297)
    check("Q6 distractor delta", de, 0.223)
    check("Q6 distractor theta", th, 0.752)
    check("Q6 delta = sigma theta", de, si * th, tol=1e-12)
    hL = A.geopotential(3256.0)
    check("Q7 h (km)", hL / 1e3, 3.254)
    check("Q7 T (K)", 288.15 - 0.0065 * hL, 267.0)
    check("Q7 p (Pa)", A.ISA.state(3256.0)[1], 67870, tol=1)
    q.num(7, A.ISA.state(3256.0)[1] / 100, "679")
    check("Q7 two thirds of sea level", A.ISA.state(3256.0)[1] / P0_SL, 0.67, tol=0.005)
    H = A.scale_height(216.65)
    check("Q8 H (m)", H, 6341.6)
    q.num(8, np.exp(-9000 / H), "0.242")
    check("Q8 engine ratio", A.isa(20e3)[1] / A.isa(11e3)[1], 0.242)
    check("Q8 distractor: p20/p0", A.isa(20e3)[1] / P0_SL, 0.0540)
    gap = 50e3 - A.geopotential(50e3)
    q.num(9, gap, "390", tol=0.5)
    check("Q9 z^2/(r0 + z) (km)", 50**2 / (R0_GEOPOTENTIAL / 1e3 + 50), 0.390)
    check("Q9 distractor: gap at 86 km (km)", (86e3 - A.geopotential(86e3)) / 1e3, 1.15, tol=0.005)
    t5 = A.isa(5e3)[0]
    check("Q10 T at 5 km", t5, 255.65)
    q.num(10, (np.sqrt(288.15 / t5) - 1) * 100, "6.2")
    check("Q10 ratio", np.sqrt(288.15 / t5), 1.062)
    check("Q10 distractor: without the root (%)", (288.15 / t5 - 1) * 100, 13, tol=0.3)
    q.num(11, A.isa(11e3)[1] / P0_SL * 100, "22.3")
    check("Q11 distractor sigma (%)", A.isa(11e3)[2] / RHO0_SL * 100, 29.7)
    check("Q12 a at 11 km = a at 20 km", A.ISA.state(A.geometric(20e3))[3] - A.ISA.state(A.geometric(11e3))[3], 0.0, tol=1e-9)
    nu11 = A.ISA.state(A.geometric(11e3))[4] / A.isa(11e3)[2]
    nu20 = A.ISA.state(A.geometric(20e3))[4] / A.isa(20e3)[2]
    check("Q12 nu rises by 1/0.242", nu20 / nu11, 4.1, tol=0.05)
    truth("Q12 the right option is the speed of sound", "speed of sound" in q.right(12))


def balloon():
    """Drill 1: a balloon at 25 km."""
    i = 2
    check("P1 layer base (km)", A.LAYERS[i][1] / 1e3, 20, tol=1e-12)
    check("P1 T_b", A.ISA.t_b[i], 216.65, tol=1e-9)
    check("P1 p_b", A.ISA.p_b[i], 5474.9)
    check("P1 gradient (K/km)", A.LAYERS[i][2] * 1e3, 1.0, tol=1e-12)
    T = 216.65 + 0.001 * 5000
    check("P1 T", T, 221.65)
    n = A.pressure_exponent(0.001)
    check("P1 exponent", n, -34.163)
    p = 5474.9 * (T / 216.65) ** n
    check("P1 p by hand", p, 2511)
    t_, p_, r_ = A.isa(25e3)
    check("P1 p engine", p_, 2511)
    check("P1 rho", r_, 0.03947)
    check("P1 rho by hand", 2511 / (287.053 * 221.65), 0.03947)
    check("P1 sigma (%)", r_ / RHO0_SL * 100, 3.2)
    check("P1 a", A.speed_of_sound(T), 298.5)
    check("P1 fraction above (%)", p_ / P0_SL * 100, 2.5)
    check("P1 above 97.5 % of the air", 100 - p_ / P0_SL * 100, 97.5)
    z = A.geometric(25e3)
    check("P1 geometric (km)", z / 1e3, 25.099)
    check("P1 z - h (m)", z - 25e3, 99)


def pslv():
    """Drill 2: dynamic pressure on the way up, against the simulator."""
    from flight import missions
    tr = missions.fly(missions.pslv_c18_like())
    for zq, tq, vq in ((20.25e3, 80, 759), (50.38e3, 115, 1428)):
        j = int(np.argmax(tr.h > zq - 300))
        k = int(np.argmin(abs(tr.h - zq)))
        check(f"P2 simulator time at {zq / 1e3:.2f} km (s)", tr.t[k], tq, tol=1.0)
        check(f"P2 simulator V_a at {zq / 1e3:.2f} km (m/s)", tr.Va[k], vq, tol=5)
    h1, h2 = A.geopotential(20.25e3), A.geopotential(50.38e3)
    check("P2 h1 (km)", h1 / 1e3, 20.186)
    check("P2 h2 (km)", h2 / 1e3, 49.984)
    T1 = 216.65 + 0.001 * (h1 - 20e3)
    check("P2 T1", T1, 216.84)
    p1 = 5474.9 * (T1 / 216.65) ** A.pressure_exponent(0.001)
    check("P2 p1", p1, 5317)
    r1 = p1 / (287.053 * T1)
    check("P2 rho1", r1, 0.08542)
    check("P2 rho1 engine", A.ISA.state(20.25e3)[2], 0.08542)
    H2 = A.scale_height(270.65)
    check("P2 H2 (m)", H2, 7922)
    check("P2 h2 - 47 km (m)", h2 - 47e3, 2984, tol=1)
    p2 = 110.91 * np.exp(-(h2 - 47e3) / H2)
    check("P2 p2", p2, 76.10)
    r2 = p2 / (287.053 * 270.65)
    check("P2 rho2 (1e-4)", r2 / 1e-4, 9.80)
    check("P2 rho2 engine (1e-4)", A.ISA.state(50.38e3)[2] / 1e-4, 9.80)
    q1, q2 = 0.5 * r1 * 759**2, 0.5 * r2 * 1428**2
    check("P2 q1 (kPa)", q1 / 1e3, 24.6)
    check("P2 q1 fraction of max (%)", q1 / 40.2e3 * 100, 61)
    check("P2 q2 (Pa)", q2, 999)
    check("P2 q2 fraction of max (%)", q2 / 40.2e3 * 100, 2.5)
    check("P2 speed factor", 1428 / 759, 1.88)
    check("P2 speed factor (rounded in the question)", 1428 / 759, 1.9)
    check("P2 V^2 factor", (1428 / 759) ** 2, 3.5)
    check("P2 density factor", r1 / r2, 87, tol=0.5)
    check("P2 density factor as written", 0.08542 / 0.00098, 87, tol=0.5)


def thickness():
    """Extension 3: how thick is the atmosphere."""
    D = P0_SL / (RHO0_SL * G0)
    check("P3 uniform thickness (km)", D / 1e3, 8.43)
    check("P3 equals R T0/g0", D, A.scale_height(288.15), tol=1e-9)
    H0 = A.scale_height(288.15)
    check("P3 H0 (m)", H0, 8435, tol=0.5)
    check("P3 ln 2", np.log(2), 0.693)
    check("P3 half below, isothermal (km)", H0 * np.log(2) / 1e3, 5.85)
    check("P3 half below, ISA (km)", A.pressure_altitude(P0_SL / 2) / 1e3, 5.48)
    truth("P3 the cold ISA puts half the air lower", A.pressure_altitude(P0_SL / 2) < H0 * np.log(2))
    h, Hs = sp.symbols("h H", positive=True)
    hbar = sp.integrate(h * sp.exp(-h / Hs), (h, 0, sp.oo)) / sp.integrate(sp.exp(-h / Hs), (h, 0, sp.oo))
    sym_zero("P3 centre of mass at H", sp.simplify(hbar - Hs))


CP = 1.4 * R_AIR / 0.4


def polytrope():
    """Guided derivation 4: the polytropic layer and the adiabatic limit."""
    lam, g, R, T, Tb, rb, pb = sp.symbols("lambda g_0 R T T_b rho_b p_b", real=True)
    n = -g / (R * lam)
    k = n / (n - 1)
    sym_zero("P4a k = 1/(1 + R lambda/g0)", k - 1 / (1 + R * lam / g))
    check("P4a k in the troposphere", 1 / (1 + R_AIR * -0.0065 / G0), 1.235)
    check("P4a R lambda/g0", R_AIR * -0.0065 / G0, -0.1903)
    gm = sp.symbols("gamma", positive=True)
    lad = sp.solve(sp.Eq(1 / (1 + R * lam / g), gm), lam)[0]
    sym_zero("P4b lambda_ad = -g0 (gamma-1)/(gamma R)", lad + g * (gm - 1) / (gm * R))
    check("P4b c_p", CP, 1004.7)
    check("P4b adiabatic gradient (K/km)", -G0 / CP * 1e3, -9.761)
    check("P4c top (km)", 288.15 * CP / G0 / 1e3, 29.5)
    check("P4c pressure exponent at the adiabatic gradient", A.pressure_exponent(-G0 / CP), 3.5, tol=1e-9)
    check("P4d gain of c_p T + g h (J/(kg m))", G0 - CP * 0.0065, 3.28)


def buoyancy():
    """Guided derivation 5: the buoyancy frequency."""
    for T, lam, N2, N, P in ((288.15, -0.0065, 1.11e-4, 0.0105, 596), (216.65, 0.0, 4.42e-4, 0.0210, 299)):
        n2 = G0 / T * (lam + G0 / CP)
        check(f"P5c N^2 at {T} K", n2, N2)
        check(f"P5c N at {T} K", np.sqrt(n2), N)
        check(f"P5c period at {T} K (s)", 2 * np.pi / np.sqrt(n2), P)
    check("P5d ratio of N^2", G0 / 216.65 * G0 / CP / (G0 / 288.15 * (-0.0065 + G0 / CP)), 4, tol=0.05)
    z, lam, lad, g, T = sp.symbols("zeta lambda lambda_ad g T", real=True)
    acc = g * ((T + lad * z) - (T + lam * z)) / (T + lam * z)
    sym_zero("P5b first-order acceleration", sp.series(acc, z, 0, 2).removeO() - g / T * (lad - lam) * z)


def max_q():
    """Guided derivation 6: maximum dynamic pressure at about one scale height."""
    for T, want in ((288.15, 10.42), (216.68, 7.83)):
        check(f"P6a density scale height at {T} K (km)", A.local_scale_height(T, -0.0065) / 1e3, want)
    check("P6a pressure scale height at 288.15 K (km)", A.scale_height(288.15) / 1e3, 8.43)
    check("P6a pressure scale height at 216.65 K (km)", A.scale_height(216.65) / 1e3, 6.34)
    lam, g, R, T = sp.symbols("lambda g_0 R T", positive=True)
    h = sp.symbols("h", positive=True)
    rho = (1 + lam * h / T) ** (-g / (R * lam) - 1)
    sym_zero("P6a -dln(rho)/dh at h=0 = (g0 + R lambda)/(R T)", -sp.diff(sp.log(rho), h).subs(h, 0) - (g + R * lam) / (R * T))
    r0, a, H, m, C = sp.symbols("rho_0 a H m C", positive=True)
    q = r0 * a * h * sp.exp(-h / H)
    truth("P6b dq/dh = 0 at h = H", sp.simplify(sp.diff(q, h).subs(h, H)) == 0)
    sym_zero("P6b q* = rho0 a H/e", q.subs(h, H) - r0 * a * H / sp.E)
    qm = r0 / 2 * C * h**m * sp.exp(-h / H)
    sym_zero("P6c dq/dh = 0 at h = m H", sp.simplify(sp.diff(qm, h).subs(h, m * H)))
    # numerical: constant acceleration in the real ISA gives a maximum near H_rho
    hs = np.linspace(100.0, 30e3, 30001)
    qs = np.array([A.isa(x)[2] for x in hs]) * hs
    check("P6b in the ISA, constant acceleration: q max (km), between 7.8 and 10.4", hs[np.argmax(qs)] / 1e3, 9.1, tol=1.3)


def weigh():
    """Guided derivation 7: the mass of the atmosphere."""
    M0 = 4 * np.pi * A_EARTH**2 * P0_SL / G0
    check("P7a flat estimate (kg)", M0, 5.28e18)
    H = A.scale_height(288.15)
    check("P7c correction (%)", 4 * H / A_EARTH * 100, 0.53)
    check("P7c corrected (kg)", M0 * (1 + 4 * H / A_EARTH), 5.31e18)
    h, Hs, p0 = sp.symbols("h H p_0", positive=True)
    sym_zero("P7c pressure-weighted mean height = H",
             sp.integrate(h * (p0 / Hs) * sp.exp(-h / Hs), (h, 0, sp.oo)) / p0 - Hs)
    check("P7d excess over the measured mass (%)", (M0 * (1 + 4 * H / A_EARTH) / 5.15e18 - 1) * 100, 3, tol=0.5)
    check("P7d excess / correction", (M0 * (1 + 4 * H / A_EARTH) / 5.15e18 - 1) / (4 * H / A_EARTH), 6, tol=0.5)
    check("P7d implied mean surface pressure (kPa)", 5.15e18 * G0 / (4 * np.pi * A_EARTH**2 * (1 + 4 * H / A_EARTH)) / 1e3, 98.3)



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
    r = 8000e3; h = r * 1500 / (r + 1500)
    P = lambda z: 0.9e5 * (1 - 0.0015 * z / 273.15)**(10.1 / (0.0015 * 300))
    check("E8 geopotential", h, 1499.72, tol=0.005)
    check("E8 error %", 100 * (1400 - h) / h, -6.65, tol=0.005)
    check("E8 exponent", 10.1 / (0.0015 * 300), 22.44, tol=0.005)
    check("E8 p(1400)", P(1400), 75686, tol=0.7)
    check("E8 p(h)", P(h), 74754, tol=0.7)
    check("E8 difference", P(1400) - P(h), 932, tol=0.5)
    check("E8 10 K as height (km)", 10 / 6.5, 1.5, tol=0.05)

if __name__ == "__main__":
    run([objective, balloon, pslv, thickness, polytrope, buoyancy, max_q, weigh, earlier_papers])
