"""Checks every number in the answers and solutions of 16-range-endurance-questions.qmd,
including the guided derivations 4-7.
Run from anywhere:  python3 codes/16-range-endurance-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
import _isbj as J
from flight import performance as PF, aero as AE, atmosphere as A
from flight.constants import G0, FT

PAGE = os.path.join(HERE, "..", "16-range-endurance-questions.qmd")
H = 287.053 * 216.65 / G0


def objective():
    """The 12 objective questions."""
    q = Objective(PAGE, 12)
    check("data rho", J.RHO, 0.3798)
    check("data S", J.S, 21.55)
    check("Q5 VE/c (km)", 230 * 17 / (0.6 / 3600) / 1e3, 23460, tol=0.5)
    check("Q5 ln 1.25", np.log(1.25), 0.2231)
    q.num(5, PF.range_cruise_climb(230, 17, 0.6 / 3600, 1.25, 1.0) / 1e3, "5235")
    q.num(6, 3**0.25 * 180, "237")
    check("Q6 distractor min power", 180 * 3**-0.25, 137, tol=0.5)
    check("Q6 distractor sqrt 3", 180 * np.sqrt(3), 312, tol=0.5)
    q.num(7, PF.endurance_const_cl(16, 0.5 / 3600, 1.25, 1.0) / 3600, "7.1")
    check("Q7 distractor", 32 * 0.2, 6.4)
    q.num(8, H * np.log(1.25), "1415")
    check("Q8 distractor 0.2 H", 0.2 * H, 1268, tol=0.5)
    check("Q9 1/(1-0.167)", 1 / (1 - 1 / 6), 1.2, tol=1e-12)
    q.num(9, (1 - 1 / 1.44) * 100, "30.6")
    q.num(10, 18 * np.sqrt(3) / 2, "15.6")
    check("Q10 distractor", 18 * 2 / np.sqrt(3), 20.8)
    sr = PF.specific_range(230, 0.6 / 3600, 40000)
    check("Q11 specific range (m/N)", sr, 34.5)
    q.num(11, sr * 1000 * G0 / 1000, "338")
    q.num(12, PF.best_range_cl(0.018, 0.045), "0.365")
    check("Q12 distractor C_L*", np.sqrt(0.018 / 0.045), 0.632)
    check("Q12 distractor C_L*/3", np.sqrt(0.018 / 0.045) / 3, 0.211)


def programs():
    """Drill 1: three programs from 13,000 to 11,000 lb."""
    W0, Wf = 13000 * J.LB, 11000 * J.LB
    cl = PF.best_range_cl(J.CD0, J.K)
    cd = AE.parabolic_cd(cl, J.CD0, J.K)
    check("P1 C_L", cl, 0.324)
    check("P1 3K", 3 * J.K, 0.219, tol=1e-12)
    check("P1 C_L^2", cl**2, 0.105)
    check("P1 C_D", cd, 0.0307)
    check("P1 E", cl / cd, 10.57)
    v0 = PF.speed_for_cl(W0, J.RHO, J.S, cl)
    check("P1 V0 (m/s)", v0, 208.8)
    check("P1 V0 (ft/s)", v0 / FT, 685, tol=0.5)
    r1 = PF.range_const_alt_cl(J.RHO, J.S, cl, cd, J.C, W0, Wf) / J.MILE
    check("P1 constant h, C_L (mi)", r1, 668, tol=0.5)
    check("P1 final speed", PF.speed_for_cl(Wf, J.RHO, J.S, cl), 192.1)
    r2 = PF.range_cruise_climb(v0, cl / cd, J.C, W0, Wf) / J.MILE
    check("P1 cruise-climb (mi)", r2, 696, tol=0.5)
    check("P1 climb (m)", H * np.log(13 / 11), 1059, tol=0.5)
    r3 = PF.range_const_alt_speed(v0, J.RHO, J.S, J.CD0, J.K, J.C, W0, Wf) / J.MILE
    check("P1 constant h, V (mi)", r3, 666, tol=0.5)
    truth("P1 ranking", r2 > r1 > r3)


def sector():
    """Drill 2: fuel for a 4000 km sector."""
    W0 = 270000 * G0
    t, p, r = A.isa(11000.0)
    V = 0.8 * A.speed_of_sound(t)
    cl = W0 / (0.5 * r * V**2 * 476)
    E = cl / AE.parabolic_cd(cl, 0.017, 0.04)
    check("P2 E", E, 18.9)
    arg = 4e6 * (0.7 / 3600) / (V * E)
    check("P2 exponent", arg, 0.1744)
    frac = 1 - np.exp(-arg)
    check("P2 fuel fraction (%)", frac * 100, 16.0)
    check("P2 fuel (t)", frac * 270, 43.2)
    check("P2 time (s)", 4e6 / V, 16950, tol=5)
    check("P2 time (h)", 4e6 / V / 3600, 4.71)


def constant_speed():
    """Extension 3: constant height and speed."""
    v = 630 * FT
    check("P3 630 ft/s (m/s)", v, 192.0)
    qd = 0.5 * J.RHO * v**2
    check("P3 q (Pa)", qd, 7003, tol=0.5)
    a, b = np.sqrt(J.CD0 * qd * J.S), np.sqrt(J.K / (qd * J.S))
    check("P3 a", a, 58.92)
    check("P3 b (1e-4)", b / 1e-4, 6.954)
    check("P3 bW0/a", b * J.W0 / a, 0.6300)
    check("P3 bWf/a", b * J.WF / a, 0.5250)
    br = np.arctan(b * J.W0 / a) - np.arctan(b * J.WF / a)
    check("P3 bracket", br, 0.07874)
    check("P3 V/(cab) (1e7)", v / (J.C * a * b) / 1e7, 1.4244)
    R = PF.range_const_alt_speed(v, J.RHO, J.S, J.CD0, J.K, J.C, J.W0, J.WF)
    check("P3 range (1e6 m)", R / 1e6, 1.122)
    check("P3 range (mi)", R / J.MILE, 697, tol=0.5)


def tsfc_family():
    """Guided derivation 4: c = c1 u^n."""
    u, n = sp.symbols("u n", positive=True)
    sr = u**(3 - n) / (u**4 + 1)
    uo = ((3 - n) / (1 + n))**sp.Rational(1, 4)
    sym_zero("P4a best range at u^4 = (3-n)/(1+n)", sp.simplify(sp.diff(sr, u).subs(u, uo)))
    en = u**(2 - n) / (u**4 + 1)
    ue = ((2 - n) / (2 + n))**sp.Rational(1, 4)
    sym_zero("P4d best endurance at u^4 = (2-n)/(2+n)", sp.simplify(sp.diff(en, u).subs(u, ue)))
    check("P4b n = 0", 3**0.25, 1.316)
    uc = (5 / 3)**0.25
    check("P4c n = 0.5", uc, 1.136)
    check("P4c E/E*", 2 * uc**2 / (uc**4 + 1), 0.968)
    check("P4d n = 1 endurance speed", (1 / 3)**0.25, 0.760)
    xs = np.linspace(0.5, 2.0, 150001)
    check("P4c search agrees", xs[np.argmax(xs**2.5 / (xs**4 + 1))], uc, tol=2e-5)


def payload_range():
    """Guided derivation 5: the payload-range diagram."""
    R0 = 22940.0
    check("P5 range factor from the note's example (km)", 236.1 * 18.9 / (0.7 / 3600) / 1e3, R0, tol=10)
    check("P5c max payload range (km)", R0 * np.log(270 / 210), 5765)
    check("P5c full tanks at MTOW (km)", R0 * np.log(270 / 170), 10610, tol=5)
    check("P5c ferry (km)", R0 * np.log(250 / 150), 11720, tol=5)
    check("P5c first tonne (km/t)", R0 / 210, 109)
    W, Wf, R0s = sp.symbols("W_MTO W_f R_0", positive=True)
    sym_zero("P5b dR/dW_f", sp.diff(R0s * sp.log(W / (W - Wf)), Wf) - R0s / (W - Wf))


def fuel_for_fuel():
    """Guided derivation 6: the cost of carrying weight."""
    R0 = 22940.0
    check("P6c 4697 km: R/R0", 4697 / R0, 0.2048)
    check("P6c 4697 km: kg per kg", np.exp(4697 / R0) - 1, 0.227)
    check("P6c 12000 km: R/R0", 12000 / R0, 0.523)
    check("P6c 12000 km: kg per kg", np.exp(12000 / R0) - 1, 0.687)
    check("P6d price ratio for 1500 km", np.exp(1500 / R0), 1.068)
    x = sp.symbols("x", positive=True)
    sym_zero("P6b e^x - 1 = x + O(x^2)", sp.series(sp.exp(x) - 1, x, 0, 2).removeO() - x)


def climb_gain():
    """Guided derivation 7: the cruise-climb advantage."""
    z = sp.symbols("zeta", positive=True)
    w = 1 - z
    ser = sp.series(sp.log(1 / w) / (2 * (1 - sp.sqrt(w))), z, 0, 3).removeO()
    sym_zero("P7b series", ser - (1 + z / 4 + sp.Rational(7, 48) * z**2))
    wv = 10000 / 12000
    ex = np.log(1 / wv) / (2 * (1 - np.sqrt(wv)))
    check("P7c exact", ex, 1.0463)
    check("P7c sqrt w", np.sqrt(wv), 0.9129)
    zv = 1 - wv
    check("P7c two terms", 1 + zv / 4, 1.0417)
    check("P7c three terms", 1 + zv / 4 + 7 / 48 * zv**2, 1.0457)
    check("P7c the note's 730/698", 730 / 698, 1.046, tol=0.001)
    check("P7d w = 0.6", np.log(1 / 0.6) / (2 * (1 - np.sqrt(0.6))), 1.133)
    check("P7d sqrt 0.6", np.sqrt(0.6), 0.7746)



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
    W1s, rho, S_, cl, cd0, K, c, z, Em = sp.symbols("W rho S C_L C_D0 K c zeta E_m", positive=True)
    clr = sp.sqrt(cd0 / (3 * K))
    lhs = sp.sqrt(clr) / (cd0 + K * clr**2)
    for vals in ({cd0: 0.02, K: 0.05}, {cd0: 0.017, K: 0.04}):
        em = 1 / (2 * np.sqrt(vals[K] * vals[cd0]))
        check("E16 factor identity", float(lhs.subs(vals)), 3**0.75 * np.sqrt(2) / 4 * np.sqrt(em / vals[cd0]), tol=1e-9)
        # the quoted closed form against the engine's range
        rr, SS, cc, W0, zz = 0.6, 100.0, 2e-4, 1e6, 0.2
        closed = np.sqrt(3 * np.sqrt(3) / 2) * np.sqrt(2 * W0 / SS / rr) / cc * np.sqrt(em / vals[cd0]) * (1 - np.sqrt(1 - zz))
        cl_ = np.sqrt(vals[cd0] / (3 * vals[K]))
        check("E16 closed form = engine range", Pf.range_const_alt_cl(rr, SS, cl_, vals[cd0] + vals[K] * cl_**2, cc, W0, W0 * (1 - zz)), closed, tol=1e-6 * closed)
    E = 1 / (2 * np.sqrt(0.09 * 0.025))
    check("E16 patrol E", E, 10.54, tol=0.005)
    check("E16 endurance h", E / 0.84 * np.log(17 / 12), 4.37, tol=0.005)
    r10 = At.isa(10000 * FT)[2]
    check("E16 rho 10000 ft", r10, 0.9046, tol=5e-5)
    check("E16 V* heavy", Pf.min_drag_speed(17000 * g, r10, 41, 0.025, 0.09), 130.6, tol=0.05)
    check("E16 V* light", Pf.min_drag_speed(12000 * g, r10, 41, 0.025, 0.09), 109.7, tol=0.05)
    S_, cd0, K, cc = 476.0, 0.017, 0.04, 0.7 / 3600
    E = 1 / (2 * np.sqrt(K * cd0)); clr = np.sqrt(cd0 / (3 * K)); cdr = cd0 + K * clr**2
    W0, Wd = 270000 * g, 220000 * g
    r25, r20 = At.isa(25000 * FT)[2], At.isa(20000 * FT)[2]
    check("E16 E_max", E, 19.17, tol=0.005); check("E16 CL", clr, 0.3764, tol=5e-5); check("E16 CD", cdr, 0.02267, tol=5e-6)
    check("E16 rho25", r25, 0.5489, tol=5e-5)
    V0 = Pf.speed_for_cl(W0, r25, S_, clr)
    check("E16 V0", V0, 232.0, tol=0.05); check("E16 Mach", V0 / At.speed_of_sound(At.isa(25000 * FT)[0]), 0.75, tol=0.005)
    check("E16 V1", Pf.speed_for_cl(Wd, r25, S_, clr), 209.5, tol=0.06)
    check("E16 range a (km)", Pf.range_const_alt_cl(r25, S_, clr, cdr, cc, W0, Wd) / 1e3, 3857, tol=0.5)
    m_end = 220000 * np.exp(cc * 1200 / E)
    check("E16 reserve (kg)", m_end - 220000, 2694, tol=0.5)
    check("E16 end mass", m_end, 222694, tol=1)
    check("E16 range b (km)", Pf.range_const_alt_cl(r25, S_, clr, cdr, cc, 265000 * g, m_end * g) / 1e3, 3270, tol=0.5)
    from scipy.optimize import minimize_scalar
    ground = lambda V, w: Pf.range_const_alt_speed(V, r20, S_, cd0, K, cc, W0, Wd) * (1 - w / V)
    o = minimize_scalar(lambda V: -ground(V, 15.43), bounds=(150, 320), method="bounded")
    o0 = minimize_scalar(lambda V: -ground(V, 0.0), bounds=(150, 320), method="bounded")
    check("E16 best V into wind", o.x, 208.2, tol=0.05); check("E16 its Mach", o.x / At.speed_of_sound(At.isa(20000 * FT)[0]), 0.66, tol=0.005)
    check("E16 ground distance (km)", ground(o.x, 15.43) / 1e3, 3267, tol=0.6)
    check("E16 still-air best V", o0.x, 202.5, tol=0.05); check("E16 at still-air speed (km)", ground(o0.x, 15.43) / 1e3, 3264, tol=0.6)
    rf = r25 * 230 / 270
    check("E16 final density", rf, 0.4676, tol=5e-5)
    from scipy.optimize import brentq
    hf = brentq(lambda h: At.isa(h)[2] - rf, 0, 11000)
    check("E16 final height (m)", hf, 8977, tol=1); check("E16 final height (ft)", hf / FT, 29450, tol=10)

if __name__ == "__main__":
    run([objective, programs, sector, constant_speed, tsfc_family, payload_range, fuel_for_fuel, climb_gain, earlier_papers])
