"""Checks every number in the answers and solutions of 23-envelope-questions.qmd,
including the guided derivations 4-7.
Run from anywhere:  python3 codes/23-envelope-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 _scripts import load
import _climb as C
import _dc9 as D
from flight import performance as PF, atmosphere as A
from flight.constants import G0, FT

PAGE = os.path.join(HERE, "..", "23-envelope-questions.qmd")


def objective():
    q = Objective(PAGE, 12)
    s = PF.absolute_ceiling_density_ratio(50e3, 12.5, 20e3)
    q.num(4, s, "0.2")
    h = 11 + A.scale_height(216.65) / 1e3 * np.log(0.2971 / 0.2)
    q.num(5, h, "13.5")
    check("Q5 ln term (km)", h - 11, 2.51)
    check("Q5 exact ISA", A.density_altitude(0.2 * 1.225) / 1e3, 13.5, tol=0.05)
    cl = 1.3 * 440e3 / (12e3 * 93)
    q.num(6, cl, "0.51")
    check("Q6 A (1 g)", 440e3 / (12e3 * 93), 0.39)
    q.num(7, A.scale_height(216.65) * np.log(1 / 0.9), "670", x=670, tol=5)
    t = PF.time_to_climb_linear(30.0, 12000.0, 12000.0 * (1 - 0.5 / 30))
    q.num(8, t / 60, "27.3")
    check("Q8 s", t, 1638, tol=1)
    check("Q8 ln 60", np.log(60), 4.09)
    EN = load("fig-23-sbj-envelope")
    check("Q9 q-limit Mach SL", EN.q_mach(0.0), 0.450)
    check("Q9 thrust Mach SL", EN.thrust_machs(0.0)[1], 0.87, tol=0.006)
    tt = 216.65 * (1 + 0.2 * 4)
    check("Q10 K", tt, 390.0, tol=0.05)
    q.num(10, tt - 273.15, "117", tol=0.5)
    CE = load("fig-23-ceilings")
    check("Q11 98.5 %", CE.CEIL["SBJ"]["service"] / CE.CEIL["SBJ"]["absolute"] * 100, 98.5)
    q.num(12, 1.07 * (0.80 + 0.04), "0.90")
    check("Q12 M_MO", 0.84, 0.84)


def kiran_light():
    s = PF.absolute_ceiling_density_ratio(4500 * G0, 12.74, 18400.0)
    check("P1 sigma", s, 0.1883)
    h = 11000 + A.scale_height(216.65) * np.log(0.2971 / s)
    check("P1 ceiling (km)", h / 1e3, 13.89)
    sv = PF.ceiling(lambda hh: C.max_roc(C.KIRAN, 4500 * G0, hh), 100 * FT / 60, 0.0, 20000.0)
    check("P1 service (ft)", sv / FT, 44875, tol=0.5)
    check("P1 service (km)", sv / 1e3, 13.68)
    check("P1 gap (m)", h - sv, 215, tol=3)
    check("P1 rise from 4950 kg (m)", h - load("fig-23-ceilings").CEIL["Kiran"]["absolute"], 600, tol=6)


def coffin_weight():
    BF = load("fig-23-buffet")
    for m, n, q in ((50000, 1.3, 32518), (40000, 1.3, 37218), (40000, 1.0, 42676)):
        p, _ = PF.coffin_corner_pressure(n, m * G0, D.S, BF.cl_buffet)
        check(f"P2 corner {m} kg n {n} (ft)", A.pressure_altitude(p) / FT, q, tol=0.6)
    check("P2 1 g at 45 t (km)", BF.H_CORNER_1G / 1e3, 12.26)
    check("P2 scaling (km)", A.scale_height(216.65) / 1e3 * np.log(45 / 40), 0.75)
    p40, _ = PF.coffin_corner_pressure(1.0, 40000 * G0, D.S, BF.cl_buffet)
    check("P2 scaling exact in the stratosphere (km)", A.pressure_altitude(p40) / 1e3,
          (BF.H_CORNER_1G + A.scale_height(216.65) * np.log(45 / 40)) / 1e3, tol=0.002)


def tangent():
    BF = load("fig-23-buffet")
    f = lambda M: 0.7 * M**2 * BF.cl_buffet(M)
    Ms = np.linspace(0.2, 0.84, 2000)
    fm = max(f(m) for m in Ms)
    check("P3 corner pressure = nW/(S max f)", A.isa(BF.H_CORNER)[1], D.N_BUFFET * BF.W / (D.S * fm), rel=2e-4)
    truth("P3 f rises from zero and falls to zero", f(0.0) == 0.0 and f(0.845) == 0.0 and fm > 0)


def climb_near_ceiling():
    """Guided derivation 4: the rate of climb near the ceiling."""
    H = A.scale_height(216.65)
    h = 45543 * FT
    sig = A.isa(h)[2] / A.isa(0.0)[2]
    check("P4b ceiling (km)", h / 1e3, 13.88)
    check("P4b sigma", sig, 0.1886)
    V = 81.3 / np.sqrt(sig)
    check("P4b V*", V, 187.2)
    sl = V / (12.2 * H)
    check("P4b slope (m/s per km)", sl * 1e3, 2.42)
    check("P4b service gap (m)", 0.5 / sl, 207)
    check("P4c rule at 5 m/s", 1 - 0.5 / 5, 0.90, tol=1e-12)
    check("P4c at 20 m/s", 1 - 0.5 / 20, 0.975, tol=1e-12)
    check("P4c at 40 m/s", 1 - 0.5 / 40, 0.9875, tol=1e-12)
    check("P4d tau_c (s)", 12.2 * H / V, 413)
    hh, hac, tc = sp.symbols("h h_ac tau_c", positive=True)
    sym_zero("P4d time integral", sp.diff(-tc * sp.log(hac - hh), hh) - tc / (hac - hh))


def prop_ceiling():
    """Guided derivation 5: the ceiling of a propeller aircraft."""
    from flight import propulsion as PR
    s2 = A.isa(2000.0)[2] / A.isa(0.0)[2]
    check("P5c P_SL from the Lecture 15 example (kW)", 47.9 / PR.gagg_ferrar(s2), 60.0)
    x = 16.5 / (0.78 * 60.0)
    check("P5c ratio", x, 0.353)
    sc = x**(1 / 1.7)
    check("P5c sigma", sc, 0.542)
    hc = 288.15 / 0.0065 * (1 - sc**(1 / 4.2559))
    check("P5c ceiling (km)", hc / 1e3, 5.95)
    check("P5c the ISA has that density there", A.isa(hc)[2] / A.isa(0.0)[2], sc, tol=2e-4)
    check("P5d turbocharged sigma", x**2, 0.124)


def turn_ceiling():
    """Guided derivation 6: the ceiling in a sustained turn."""
    H = A.scale_height(216.65)
    n30 = 1 / np.cos(np.radians(30))
    check("P6c n at 30 deg", n30, 1.155)
    check("P6c drop at 30 deg (km)", H * np.log(n30) / 1e3, 0.91)
    check("P6c drop at 1.3 g (km)", H * np.log(1.3) / 1e3, 1.66)
    check("P6c Kiran in a 30 deg turn (km)", 13.29 - H * np.log(n30) / 1e3, 12.38)
    check("P6d the note's 5500 ft (km)", (40226 - 34759) * FT / 1e3, 1.66, tol=0.01)


def ram_ceiling():
    """Guided derivation 7: a thrust that grows with speed."""
    from scipy.optimize import fsolve
    u, t, k, e = sp.symbols("u tau k epsilon")
    D = (u**2 + u**-2) / 2
    sym_zero("P7a tangency", sp.diff(t * (1 + k * (u - 1)), u) - sp.diff(D, u) - (t * k - (u - u**-3)))
    # series solution: u = 1 + a1 k + ..., tau = 1 + b1 k + b2 k^2
    a1, a2, b1, b2 = sp.symbols("a1 a2 b1 b2")
    us, ts = 1 + a1 * k + a2 * k**2, 1 + b1 * k + b2 * k**2
    e1 = sp.series((ts * (1 + k * (us - 1)) - D.subs(u, us)), k, 0, 3).removeO()
    e2 = sp.series((ts * k - (us - us**-3)), k, 0, 3).removeO()
    sol = sp.solve([sp.Poly(e1, k).coeff_monomial(k), sp.Poly(e1, k).coeff_monomial(k**2),
                    sp.Poly(e2, k).coeff_monomial(k), sp.Poly(e2, k).coeff_monomial(k**2)], [a1, a2, b1, b2], dict=True)[0]
    sym_zero("P7b epsilon = k/4", sol[a1] - sp.Rational(1, 4))
    sym_zero("P7b tau = 1 - k^2/8", sol[b1])
    sym_zero("P7b k^2 term", sol[b2] + sp.Rational(1, 8))
    H = 6342.0
    for kk, ue, te, rise in ((0.1, 1.026, 0.99872, 8), (0.3, 1.083, 0.98814, 76)):
        f = lambda z: [z[1] * (1 + kk * (z[0] - 1)) - 0.5 * (z[0]**2 + z[0]**-2), z[1] * kk - (z[0] - z[0]**-3)]
        uu, tt = fsolve(f, [1 + kk / 4, 1.0], xtol=1e-13)
        check(f"P7c u exact {kk}", uu, ue, tol=5e-4)
        check(f"P7c tau exact {kk}", tt, te, tol=5e-6)
        check(f"P7c 1-k^2/8 {kk}", 1 - kk**2 / 8, {0.1: 0.99875, 0.3: 0.98875}[kk], tol=5e-6)
        check(f"P7c rise exact {kk}", -H * np.log(tt), rise, tol=0.5)
        check(f"P7c rise approx {kk}", H * kk**2 / 8, {0.1: 8, 0.3: 71}[kk], tol=0.5)
        if kk == 0.3:
            check("P7c speed rise (%)", 100 * (uu - 1), 8, tol=0.5)



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
    V, rho, S_, c0, K, W = sp.symbols("V rho S C_D0 K W", positive=True)
    D = rho * V**2 * S_ * c0 / 2 + 2 * K * W**2 / (rho * V**2 * S_)
    Vs = sp.sqrt(2 * W / (rho * S_) * sp.sqrt(K / c0))
    sym_zero("E23 min drag speed", sp.simplify(sp.diff(D, V).subs(V, Vs)))
    sym_zero("E23 E_max", sp.simplify(W / D.subs(V, Vs) - 1 / (2 * sp.sqrt(K * c0))))

if __name__ == "__main__":
    run([objective, kiran_light, coffin_weight, tangent, climb_near_ceiling, prop_ceiling, turn_ceiling, ram_ceiling, earlier_papers])
