"""Checks every number in the answers and solutions of 19-supersonic-cruise-questions.qmd,
including the guided derivations 4-7.
Run from anywhere:  python3 codes/19-supersonic-cruise-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 _scripts import load
import _fighter as F
from flight import performance as PF, atmosphere as A, aero as AE
from flight.constants import G0

PAGE = os.path.join(HERE, "..", "19-supersonic-cruise-questions.qmd")
A11 = 295.1


def data():
    check("a at 11 km", F.speed_of_sound(11000.0), A11)
    check("stratospheric scale height (m)", A.scale_height(216.65), 6341.6)


def objective():
    q = Objective(PAGE, 12)
    c = 1.2 / 3600
    rf = PF.range_cruise_climb(A11 * 2, 7, c, np.e, 1.0) / 1e3
    q.num(4, rf, "12{,}390", x=12390, tol=5)
    check("Q4 c (1/s)", c, 3.33e-4, tol=5e-7)
    check("Q4 A forgets M", A11 * 7 / c / 1e3, 6197)
    check("Q4 B uses M^2", A11 * 4 * 7 / c / 1e3, 24790, tol=5)
    check("Q4 C per minute", A11 * 2 * 7 / (1.2 / 60) / 1e3, 207)
    r5 = PF.range_cruise_climb(A11 * 2, 7, c, 1.0, 0.7) / 1e3
    q.num(5, r5, "4421")
    check("Q5 ln 4 figures", np.log(1 / 0.7), 0.3567)
    check("Q5 ln", np.log(1 / 0.7), 0.357)
    check("Q5 B", 12394 * 0.3, 3718)
    check("Q5 C", 12394 * 0.7, 8676)
    acc = 10000 / (8500 * G0)
    q.num(6, acc, "0.120g", x=0.120)
    check("Q6 m/s^2", 10000 / 8500, 1.176)
    run_ = PF.accelerate_level(0.9, 1.0, A11, 8500.0, lambda M, m: 10000.0, lambda M, m: 0.0, lambda M: 0.0)
    q.num(7, run_["t"][-1], "25.1")
    q.num(8, (1 - 0.81 / 1.74) * 100, "53", x=53)
    check("Q8 ratio", 0.81 / 1.74, 0.466)
    h = A.scale_height(216.65)
    q.num(9, h * np.log(4) / 1e3, "8.8")
    check("Q9 B", h * np.log(2) / 1e3, 4.4)
    w1, w2 = PF.min_drag_wing_loading(1.0, 0.02, 0.2), PF.min_drag_wing_loading(2.0, 0.02, 0.2)
    check("Q9 omega* ratio", w2 / w1, 4.0, tol=1e-12)
    q.num(10, (2 / 0.105) / (2 / 0.75), "7.1")
    check("Q10 dash fuel per km (kg)", 2 / 0.105, 19.0, tol=0.05)
    check("Q10 radius fuel per km (kg)", 2 / 0.75, 2.67)
    check("Q10 B", (1 / 0.105) / (2 / 0.75), 3.6)
    check("Q10 C", (2 / 0.105) / (1 / 0.75), 14.3)
    B = load("fig-19-best-altitude")
    EN = load("fig-18-envelope")
    check("Q12 best height at Mach 2 (km)", B.H_20 / 1e3, 24.19)
    check("Q12 ceiling (km)", EN.H_SUPERSONIC_CEILING / 1e3, 19.28)


def concorde():
    rf = PF.range_cruise_climb(A11 * 2.04, 7.5, 1.2 / 3600, np.e, 1.0) / 1e3
    check("P1 range factor (km)", rf, 13545, tol=1)
    check("P1 ln(1/0.6)", np.log(1 / 0.6), 0.511)
    r = PF.range_cruise_climb(A11 * 2.04, 7.5, 1.2 / 3600, 1.0, 0.6) / 1e3
    check("P1 range (km)", r, 6919, tol=1)
    check("P1 5 % above 6580", (r / 6580 - 1) * 100, 5, tol=0.5)


def by_hand():
    v, h, m = F.TEJ, 11000.0, 8500.0
    Ms = [0.9, 1.0, 1.1, 1.2, 1.3]
    T = [round(F.thrust(v, x, h) / 1e3, 1) for x in Ms]
    D = [round(F.drag(v, x, m, h) / 1e3, 1) for x in Ms]
    truth("P2 table thrust", T == [31.9, 35.7, 40.3, 45.8, 52.3])
    truth("P2 table drag", D == [11.5, 18.3, 26.9, 33.6, 38.1])
    check("P2 m a", 8500 * 295.1 / 1e6, 2.508)
    f = [8500 * 295.1 / ((t - d) * 1e3) for t, d in zip(T, D)]
    for got, qv in zip(f, (123.0, 144.2, 187.2, 205.6, 176.6)):
        check(f"P2 integrand {qv}", got, qv)
    check("P2 trapezoid (s)", 0.1 * (0.5 * f[0] + f[1] + f[2] + f[3] + 0.5 * f[4]), 68.7)
    check("P2 model (s)", F.accelerate(v, 0.9, 1.3, m, h)["t"][-1], 68.1)
    check("P2 smallest excess (kN)", min(t - d for t, d in zip(T, D)), 12.2, tol=0.06)
    truth("P2 slowest at 1.2", int(np.argmax(f)) == 3)


def miele():
    u, tau, W, Es, Vs, g = sp.symbols("u tau W E_s V_s g", positive=True)
    D = W / (2 * Es) * (u**2 + u**-2)
    dt = (W / g) * Vs / (tau * W / Es - D)
    sym_zero("P3 dt/du", sp.simplify(dt - Vs * Es / g * 2 * u**2 / (2 * tau * u**2 - u**4 - 1)))
    Es_ = AE.max_lift_to_drag(0.023, 0.073)[1]
    check("P3 E*", Es_, 12.20)
    k = 146.3 * Es_ / G0
    check("P3 V*E*/g (s)", k, 182.0)
    u2 = PF.level_speed_ratios(1.66)[1]
    check("P3 u2", u2, 1.728)
    integ = lambda uf: quad(lambda x: 2 * x * x / (2 * 1.66 * x * x - x**4 - 1), 1.0, uf)[0]
    check("P3 integral to 1.6", integ(1.6), 1.387)
    check("P3 t to 1.6 (s)", k * integ(1.6), 253)
    check("P3 t to 1.72 (s)", k * integ(1.72), 592)
    check("P3 0.4 % short", (1 - 1.72 / u2) * 100, 0.4, tol=0.06)
    # cross-check against the engine's integrator in dimensional form (Hull's SBJ, W = 48.93 kN, S = 21.55 m^2)
    Wt, rho = 48930.0, None
    Ds = Wt / Es_
    run_ = PF.accelerate_level(1.0, 1.6, 146.3, Wt / G0, lambda M, m: 1.66 * Ds, lambda M, m: Ds / 2 * (M**2 + M**-2), lambda M: 0.0)
    check("P3 engine integrator agrees (s)", run_["t"][-1], k * integ(1.6), rel=1e-5)


def best_height():
    """Guided derivation 4: the best supersonic height."""
    M, c0 = sp.symbols("M C_D0", positive=True)
    b = sp.sqrt(M**2 - 1)
    sym_zero("P4a omega* = 2 M^2 sqrt(C_D0/beta)", M**2 * sp.sqrt(c0 / (b / 4)) - 2 * M**2 * sp.sqrt(c0 / b))
    H = A.scale_height(216.65)
    b1, b2 = np.sqrt(1.5**2 - 1), np.sqrt(2.0**2 - 1)
    check("P4b beta1", b1, 1.118)
    check("P4b beta2", b2, 1.732)
    r = (2 / 1.5)**2 * np.sqrt(b1 / b2)
    check("P4b bracket", r, 1.428)
    check("P4b rise (km)", H * np.log(r) / 1e3, 2.26)
    rm = (2 / 1.5)**2 * np.sqrt(F.TEJ.aero.cd0(2.0) / F.TEJ.aero.k(2.0)) / np.sqrt(F.TEJ.aero.cd0(1.5) / F.TEJ.aero.k(1.5))
    check("P4b model polar rise (km)", H * np.log(rm) / 1e3, 2.24)
    sv = np.exp(-(21.93 - 19.28) * 1e3 / H)
    check("P4d s", sv, 0.658)
    check("P4d E/Emax", 2 * sv / (1 + sv**2), 0.919)


def accel_fuel():
    """Guided derivation 5: the fuel to accelerate."""
    a = A.speed_of_sound(216.65)
    check("P5c a", a, 295.07)
    dV = 0.6 * a
    check("P5c dV", dV, 177.0)
    c = 3.09 / 3600
    check("P5c c", c, 8.58e-4)
    check("P5c lower bound (kg)", c / G0 * 8500 * dV, 132)
    m0 = 8500.0
    m1 = m0 * np.exp(-c * dV / G0)
    check("P5b rocket equation vs small-fraction form (kg)", m0 - m1, c / G0 * m0 * dV, rel=0.01)
    V1, V2 = 0.9 * a, 1.2 * a
    check("P5d V at 0.9", V1, 265.6)
    check("P5d V at 1.2", V2, 354.1)
    check("P5d height given up (km)", (V2**2 - V1**2) / (2 * G0) / 1e3, 2.80)


def cost_index():
    """Guided derivation 6: the cost index."""
    u, C = sp.symbols("u C", positive=True)
    f = u / 2 + u**-3 / 2 + C / u
    sym_zero("P6b f'(u) * 2u^4 = u^4 - 2C u^2 - 3", sp.expand(sp.diff(f, u) * 2 * u**4 - (u**4 - 2 * C * u**2 - 3)))
    us = sp.sqrt(C + sp.sqrt(C**2 + 3))
    sym_zero("P6b root", sp.simplify((us**4 - 2 * C * us**2 - 3)))
    c = 1.18 / 3600
    check("P6c c", c, 3.278e-4)
    pt = 40000 / 3600
    check("P6c p_t", pt, 11.1)
    Cv = pt * G0 / (100 * c * 4010)
    check("P6c C", Cv, 0.83)
    u2 = Cv + np.sqrt(Cv**2 + 3)
    check("P6c u^2", u2, 2.75)
    check("P6c u", np.sqrt(u2), 1.66)
    check("P6c speed (m/s)", np.sqrt(u2) * 146.3, 243)
    check("P6c best-range speed (m/s)", 3**0.25 * 146.3, 192.5)
    check("P6c faster by (%)", (np.sqrt(u2) / 3**0.25 - 1) * 100, 26)


def tsfc_growth():
    """Guided derivation 7: how fast may the fuel consumption rise?"""
    M, b = sp.symbols("M b", positive=True)
    lf = sp.log(M) - sp.log(M**2 - 1) / 4 - sp.log(1 + b * M)
    d0 = sp.diff(lf.subs(b, 0), M)
    check("P7a minimum at sqrt2", float(sp.nsolve(d0, M, 1.5)), np.sqrt(2), tol=1e-9)
    check("P7a f(sqrt2)", np.sqrt(2) / (2 - 1)**0.25, 1.414, tol=5e-4)
    bs = sp.solve(sp.diff(lf, M), b)[0]
    sym_zero("P7b condition", sp.simplify(bs - (M**2 - 2) / M**3))
    rhs = (M**2 - 2) / M**3
    sym_zero("P7c max at sqrt6", sp.diff(rhs, M).subs(M, sp.sqrt(6)))
    check("P7c b_crit", float(rhs.subs(M, sp.sqrt(6))), 0.272, tol=5e-4)
    check("P7c 4/6^1.5", 4 / 6**1.5, 0.272, tol=5e-4)
    f = lambda m_, bb: m_ / ((m_ * m_ - 1)**0.25 * (1 + bb * m_))
    Ms = np.linspace(1.01, 20, 4000)
    truth("P7c b=0.7: f falls throughout", np.all(np.diff(f(Ms, 0.7)) < 0))
    sym_zero("P7d M=2 is a root", sp.Rational(1, 4) * 8 - 4 + 2)
    sym_zero("P7d factor", sp.expand((M - 2) * (M**2 - 2 * M - 4) / 4 - (sp.Rational(1, 4) * M**3 - M**2 + 2)))
    check("P7d 1+sqrt5", 1 + np.sqrt(5), 3.236, tol=5e-4)
    check("P7d f(2)", f(2.0, 0.25), 1.0131, tol=5e-5)
    check("P7d f(3.236)", f(1 + np.sqrt(5), 0.25), 1.0197, tol=5e-5)
    check("P7d gain (%)", 100 * (f(1 + np.sqrt(5), 0.25) / f(2.0, 0.25) - 1), 0.65, tol=0.005)
    r = sorted(x.real for x in np.roots([0.15, -1, 0, 2]) if x.real > 1)
    check("P7d b=0.15 min", r[0], 1.63, tol=0.005)
    check("P7d b=0.15 max", r[1], 6.33, tol=0.005)
    check("P7d b=0.15 gain (%)", 100 * (f(r[1], 0.15) / f(r[0], 0.15) - 1), 12.5, tol=0.05)


if __name__ == "__main__":
    run([data, objective, concorde, by_hand, miele, best_height, accel_fuel, cost_index, tsfc_growth])
