"""Checks every number in the answers and solutions of 14-propulsion-model-questions.qmd,
including the guided derivations 4-7.
Run from anywhere:  python3 codes/14-propulsion-model-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 propulsion as PR, gasdynamics as GD, atmosphere as A, vehicle
from flight.constants import T0_SL, P0_SL, RHO0_SL, G0, KT

PAGE = os.path.join(HERE, "..", "14-propulsion-model-questions.qmd")
T11, P11, R11 = A.isa(11000.0)


def objective():
    """The 12 objective questions."""
    q = Objective(PAGE, 12)
    q.num(5, PR.propulsive_efficiency(200, 400), "0.67")
    check("Q5 distractor V/Ve", 200 / 400, 0.50)
    check("Q5 distractor flipped", 2 / (1 + 200 / 400), 1.33)
    q.num(6, PR.isp_from_tsfc(0.6 / 3600), "6000")
    check("Q6 distractor no conversion", 1 / 0.6, 1.67)
    check("Q6 distractor multiply", 0.6 * 3600, 2160)
    q.num(7, PR.lapse_power_law(0.6, 1.2), "0.54")
    check("Q7 exact", 0.6**1.2, 0.542)
    check("Q7 Gagg and Ferrar", PR.gagg_ferrar(0.6), 0.547)
    check("Q7 distractor 0.9", 0.6**0.9, 0.63)
    t8 = PR.jet_thrust(80, 200, 600, 1.6)
    check("Q8 thrust (N)", t8, 32960, tol=1e-9)
    q.num(8, t8 / 1e3, "33.0", tol=0.05)
    check("Q8 distractor no fuel (kN)", PR.jet_thrust(80, 200, 600) / 1e3, 32.0)
    check("Q8 fuel effect (%)", (t8 / PR.jet_thrust(80, 200, 600) - 1) * 100, 3, tol=0.5)
    check("Q8 distractor no intake (kN)", 81.6 * 600 / 1e3, 49.0)
    q.num(9, PR.overall_efficiency(1.0, 250.0, (0.7 / 3600) / G0), "0.30")
    th, de = T11 / T0_SL, P11 / P0_SL
    check("Q10 theta", th, 0.7519)
    check("Q10 delta", de, 0.2234)
    check("Q10 theta0", th * GD.stagnation_temperature_ratio(0.8), 0.848)
    d0 = de * GD.stagnation_pressure_ratio(0.8)
    check("Q10 delta0", d0, 0.340)
    f = PR.mattingly_lapse("turbofan_high", 0.8, th, de, 1.072)
    q.num(10, f, "0.19")
    check("Q10 three figures", f, 0.191)
    check("Q10 distractor sigma", R11 / RHO0_SL, 0.30)
    q.num(11, GD.stagnation_pressure_ratio(2.5), "17.1")
    check("Q11 distractor normal shock", GD.rayleigh_pitot(2.5), 8.5)
    check("Q11 distractor Mach 3", GD.stagnation_pressure_ratio(3.0), 36.7)
    jet = (0.5 / 3600) * 20000 / G0 * 3600
    rkt = 20000 / (G0 * 300) * 3600
    check("Q12 turbofan fuel (kg)", jet, 1020, tol=0.5)
    check("Q12 rocket flow (kg/s)", 20000 / (G0 * 300), 6.80)
    check("Q12 rocket propellant (kg)", rkt, 24470, tol=5)
    q.num(12, rkt / jet, "24", tol=1e-9)


def stages():
    """Drill 1: Vikas against CE-20."""
    v = vehicle.load("pslv-ca").stages[1].engine
    check("P1 Vikas thrust (kN)", v.T_vac / 1e3, 809.6)
    check("P1 Vikas Isp", v.isp_vac, 293, tol=0)
    out = {}
    for lab, T, isp, md_q, c_q, mr_q, f_q in (("Vikas", v.T_vac, 293.0, 281.8, 2873, 4.02, 75), ("CE-20", 186360.0, 442.0, 43.0, 4335, 2.52, 60)):
        md = T / (G0 * isp)
        c = G0 * isp
        check(f"P1 {lab} mdot", md, md_q)
        check(f"P1 {lab} exhaust speed", c, c_q, tol=0.5)
        mr = np.exp(4000 / c)
        check(f"P1 {lab} mass ratio", mr, mr_q)
        check(f"P1 {lab} propellant fraction (%)", (1 - 1 / mr) * 100, f_q, tol=0.5)


def hansa():
    """Drill 2: the HANSA-3 class at 2 km."""
    s2 = A.isa(2000.0)[2] / RHO0_SL
    check("P2 sigma", s2, 0.8216)
    check("P2 Sadraey ratio", PR.lapse_power_law(s2, 1.2), 0.790)
    P = 60e3 * PR.lapse_power_law(s2, 1.2)
    check("P2 power (kW)", P / 1e3, 47.4)
    check("P2 Gagg and Ferrar ratio", PR.gagg_ferrar(s2), 0.798)
    check("P2 Gagg and Ferrar power (kW)", 60 * PR.gagg_ferrar(s2), 47.9)
    V = 96 * KT
    check("P2 V", V, 49.39)
    T = 0.78 * 47400 / 49.39
    check("P2 thrust (N)", T, 749, tol=0.5)
    check("P2 throttle", 606 / 749, 0.81)
    s4 = A.isa(4000.0)[2] / RHO0_SL
    check("P2 sigma 4 km", s4, 0.6687)
    check("P2 power at 4 km (kW)", 60 * PR.lapse_power_law(s4, 1.2), 37.0)


def transport():
    """Extension 3: is the transport's engine big enough?"""
    f = PR.mattingly_lapse("turbofan_high", 0.8, T11 / T0_SL, P11 / P0_SL, 1.072)
    check("P3 available at 11 km (kN)", 757 * f, 144.8)
    check("P3 margin (kN)", 757 * f - 140.2, 4.6)
    check("P3 margin (%)", (757 * f / 140.2 - 1) * 100, 3, tol=0.5)
    t12, p12, _ = A.isa(12000.0)
    check("P3 available at 12 km (kN)", 757 * PR.mattingly_lapse("turbofan_high", 0.8, t12 / T0_SL, p12 / P0_SL, 1.072), 123.7)
    fto = PR.mattingly_lapse("turbofan_high", 0.2, 1.0, 1.0, 1.072)
    check("P3 take-off ratio", fto, 0.80)
    check("P3 take-off thrust (kN)", 757 * fto, 608, tol=0.5)
    truth("P3 more than four times cruise drag", 757 * fto > 4 * 140.2)


def actuator_disc():
    """Guided derivation 4: Rankine-Froude momentum theory."""
    V, v, w, rho, A_, T, P = sp.symbols("V v w rho A T P", positive=True)
    md = rho * A_ * (V + v)
    sol = sp.solve(sp.Eq(md * w * (V + v), md * w * (2 * V + w) / 2), v)
    truth("P4a v = w/2", sol == [w / 2])
    vv = (-V + sp.sqrt(V**2 + 2 * T / (rho * A_))) / 2
    sym_zero("P4b v solves T = 2 rho A (V+v) v", 2 * rho * A_ * (V + vv) * vv - T)
    eta = V / (V + vv)
    sym_zero("P4b eta_i formula", sp.simplify(eta - 2 / (1 + sp.sqrt(1 + T / (rho * V**2 * A_ / 2)))))
    Av = np.pi * 1.7**2 / 4
    check("P4c disc area", Av, 2.27)
    T0 = (2 * RHO0_SL * Av * 60e3**2)**(1 / 3)
    check("P4c static thrust (N)", T0, 2715)
    check("P4c in kgf", T0 / G0, 277)
    W = 5000 * G0
    Ar = np.pi * 13**2 / 4
    check("P4d W (N)", W, 49033)
    check("P4d rotor area", Ar, 132.7)
    check("P4d induced velocity (m/s)", np.sqrt(W / (2 * RHO0_SL * Ar)), 12.3)
    check("P4d hover power (kW)", W**1.5 / np.sqrt(2 * RHO0_SL * Ar) / 1e3, 602)
    check("P4d Leh factor", 1 / np.sqrt(0.647), 1.24)


def range_bound():
    """Guided derivation 5: an upper bound on range."""
    h, g = 42e6, G0
    check("P5b h/g0 (km)", h / g / 1e3, 4283)
    check("P5d range factor (km)", 0.40 * h / g * 18 / 1e3, 30840, tol=5)
    check("P5d ln(1/0.7)", np.log(1 / 0.7), 0.357)
    check("P5d range (km)", 0.40 * h / g * 18 * np.log(1 / 0.7) / 1e3, 11000, tol=50)
    check("P5d ideal bound (km)", h / g * 25 * np.log(2) / 1e3, 74200, tol=50)
    c = 0.5 / 3600
    V = 236.0
    eo = PR.overall_efficiency(1.0, V, c / G0, h)
    check("P5c eta_o h/g0 = V/c", eo * h / G0, V / c, rel=1e-12)


def ramjet():
    """Guided derivation 6: the ideal ramjet."""
    T, p, rho = A.isa(20e3)
    a = A.speed_of_sound(T)
    cp = 1.4 * 287.053 / 0.4
    def spec(M, Tt4=2400.0):
        Tt0 = T * GD.stagnation_temperature_ratio(M)
        return M * a * (np.sqrt(Tt4 / Tt0) - 1), cp * (Tt4 - Tt0) / 42e6, Tt0
    check("P6c T at 20 km", T, 216.65)
    check("P6c a", a, 295.07)
    st, f, Tt0 = spec(3.0)
    check("P6c V", 3 * a, 885.2)
    check("P6c T_t0", Tt0, 606.6)
    check("P6c sqrt ratio", np.sqrt(2400 / Tt0), 1.989)
    check("P6c specific thrust", st, 875.5)
    check("P6c f", f, 0.0429)
    check("P6c Isp", st / (f * G0), 2080, tol=5)
    check("P6c eta_p", PR.propulsive_efficiency(3 * a, 3 * a * np.sqrt(2400 / Tt0)), 0.67)
    check("P6d zero-thrust Mach", np.sqrt(5 * (2400 / T - 1)), 7.10)
    Ms = np.linspace(0.5, 7.0, 6501)
    sts = np.array([spec(m)[0] for m in Ms])
    Mb = Ms[np.argmax(sts)]
    truth(f"P6d best specific thrust between Mach 2 and 3 (found {Mb:.2f})", 2 <= Mb <= 3)
    check("P6d fall by Mach 5 (%)", (1 - spec(5.0)[0] / sts.max()) * 100, 40, tol=2)


def nozzle():
    """Guided derivation 7: the optimum expansion."""
    md, Ae, pe, pa, dVe, dpe, dAe = sp.symbols("mdot A_e p_e p_a dV_e dp_e dA_e", real=True)
    dT = md * dVe + Ae * dpe + (pe - pa) * dAe
    sym_zero("P7b dT = (p_e - p_a) dA_e", dT.subs(dVe, -Ae * dpe / md) - (pe - pa) * dAe)
    check("P7c Isp difference (s)", P0_SL * 1.0 / (275 * G0), 37.6)
    check("P7c an eighth of 300 s", P0_SL * 1.0 / (275 * G0) / 300, 0.125, tol=0.005)



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, Ve, md = sp.symbols("V V_e mdot", positive=True)
    sym_zero("E14 efficiency", sp.simplify(md * (Ve - V) * V / (md * (Ve**2 - V**2) / 2) - 2 / (1 + Ve / V)))

if __name__ == "__main__":
    run([objective, stages, hansa, transport, actuator_disc, range_bound, ramjet, nozzle, earlier_papers])
