"""Checks every number and formula in the answers and solutions of 29-ascent-questions.qmd,
including the guided derivations 4-7.
Run from anywhere:  python3 codes/29-ascent-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 rocket as R, vehicle, performance as PF
from flight.constants import G0, RHO0_SL, P0_SL

PAGE = os.path.join(HERE, "..", "29-ascent-questions.qmd")


def objective():
    q = Objective(PAGE, 12)
    H = R.max_q_scale_height(300.0, np.radians(80), 10.0)
    check("Q5 H (m)", H, 4432, tol=0.5)
    q.num(5, H / 1e3, "4.43")
    ae = vehicle.load("pslv-ca").stages[0].engine.A_e
    check("Q6 area", ae, 4.077, tol=5e-4)
    q.num(6, P0_SL * ae / 1e3, "413", x=413)
    check("Q7 K_D halves", R.drag_factor(1, 4, 1, 1, 8) / R.drag_factor(1, 1, 1, 1, 1), 0.5, tol=1e-12)
    truth("Q8 draggier rocket, lower best ratio", R.best_thrust_to_weight(0.5, 0.4)[0] < R.best_thrust_to_weight(0.5, 0.1)[0])
    rate = G0 * np.sin(np.radians(1)) / 100.0
    check("Q9 rad/s", rate, 0.00171, tol=5e-6)
    q.num(9, np.degrees(rate), "0.098")
    check("Q10", 6208 - 5595, 613, tol=1e-9)
    check("Q11", 9000 - 1800 - 80 - 120 - 40, 6960, tol=1e-9)
    truth("Q11 key", "6960" in q.right(11))
    truth("Q12 signs", 7.8 > 7.35 > 6.3)


def sounding():
    kd = R.drag_factor(RHO0_SL, 0.10, 0.40, 7200.0, 441.0)
    check("D1 K_D", kd, 0.400, tol=5e-4)
    ve = 11.8 * np.sqrt(G0 * 7200)
    check("D1 V_E", ve, 3136, tol=0.5)
    best = R.best_thrust_to_weight(0.5, 0.4)
    check("D1 best tau", best[0], 3.96, tol=0.005)
    check("D1 peak / lambda", best[1], 18.0, tol=0.05)
    nodrag = R.sounding_rocket(0.5, 3.96, 0.0)["eta_f"]
    check("D1 no drag / lambda", nodrag, 26.7, tol=0.05)
    check("D1 peak (km)", best[1] * 7.2, 130, tol=0.5)
    check("D1 no drag (km)", nodrag * 7.2, 192, tol=0.5)
    check("D1 share lost", 1 - best[1] / nodrag, 0.33, tol=0.015)
    check("D1 thrust (kN)", 3.96 * 441 * G0 / 1e3, 17.1, tol=0.05)
    check("D1 burn (s)", 0.5 * ve / (3.96 * G0), 40, tol=0.5)


def turn():
    d = np.radians
    a = (np.tan(d(10)) / np.tan(d(1)))**2
    b = np.sin(d(2)) / np.sin(d(20))
    check("D2 first factor", a, 102.0, tol=0.05)
    check("D2 second factor", b, 0.1020, tol=5e-5)
    V = R.gravity_turn_speed(d(70), 100.0, d(88), 2.0)
    check("D2 V", V, 1041, tol=0.5)
    check("D2 product", a * b, 10.41, tol=0.005)
    from scipy.optimize import brentq
    state = lambda t: R.gravity_turn(100.0, d(88), 2.0, t)
    T = brentq(lambda t: state(t)[2][-1] - d(70), 50.0, 150.0, xtol=1e-9)
    t, v, g, x, h = R.gravity_turn(100.0, d(88), 2.0, T, t_eval=np.linspace(0, T, 100001))
    s = np.sum(np.hypot(np.diff(x), np.diff(h)))
    check("D2 climb (km)", h[-1] / 1e3, 51.47, tol=0.005)
    check("D2 energy-height gain (km)", (PF.energy_height(h[-1], v[-1]) - PF.energy_height(0.0, 100.0)) / 1e3, 106.24, tol=0.01)
    check("D2 path (km)", s / 1e3, 53.1, tol=0.05)
    check("E3c h_e - n s", PF.energy_height(h[-1], v[-1]) - PF.energy_height(0.0, 100.0), 2 * s, rel=1e-7)


def energy():
    V, gam, n, al, g = sp.symbols("V gamma n alpha g", positive=True)
    he_dot = V * sp.sin(gam) + V / g * (g * (n * sp.cos(al) - sp.sin(gam)))
    sym_zero("E3a dh_e/dt = n V cos(alpha)", sp.simplify(he_dot - n * V * sp.cos(al)))
    check("E3d gain (km)", 2 * 30, 60, tol=1e-9)


def turn_clock():
    """Guided derivation 4: the time along a gravity turn."""
    x, n, C, g, d = sp.symbols("x n C g delta", positive=True)
    integrand = (C / g) * sp.tan(d / 2)**n / sp.sin(d)**2
    sub = integrand.subs(d, 2 * sp.atan(x)) * 2 / (1 + x**2)
    sym_zero("P4b integrand in x", sp.simplify(sub - C / (2 * g) * x**(n - 2) * (1 + x**2)))
    t = C / (2 * g) * (x**(n - 1) / (n - 1) + x**(n + 1) / (n + 1))
    sym_zero("P4b antiderivative", sp.simplify(sp.diff(t, x) - C / (2 * g) * x**(n - 2) * (1 + x**2)))
    # numerical check against the engine's speed formula and a direct integration
    from scipy.integrate import quad
    Cv, nv = 400.0, 2.0
    d1, d2 = 0.2, 0.8
    tn = quad(lambda dd: R.gravity_turn_from_rest_speed(dd, nv, Cv) / (G0 * np.sin(dd)), d1, d2)[0]
    tf = lambda dd: Cv / (2 * G0) * (np.tan(dd / 2)**(nv - 1) / (nv - 1) + np.tan(dd / 2)**(nv + 1) / (nv + 1))
    check("P4b closed form = numerical time", tf(d2) - tf(d1), tn, rel=1e-9)
    check("P4c n = 2: error growth from 50 to 500 m/s", 0.5 * (500 / 50)**(1 / (2 - 1)), 5.0, tol=1e-12)
    dd = 1e-3
    check("P4c small-angle V", R.gravity_turn_from_rest_speed(dd, 3.0, 1.0), dd**2 / 8, rel=1e-5)


def gravity_drag():
    """Guided derivation 5: gravity against drag."""
    h, H, a, K, gv, Vc = sp.symbols("h H a K_D g V_c", positive=True)
    sym_zero("P5a integral", sp.integrate(sp.sqrt(h) * sp.exp(-h / H), (h, 0, sp.oo)) - sp.sqrt(sp.pi) / 2 * H**sp.Rational(3, 2))
    loss = gv * Vc / a + K * sp.sqrt(sp.pi * a * H / 2)
    ast = (2 * gv * Vc / (K * sp.sqrt(sp.pi * H / 2)))**sp.Rational(2, 3)
    sym_zero("P5b stationary at a*", sp.simplify(sp.diff(loss, a).subs(a, ast)))
    check("P5c ratio from the note", (9.0 - 1) / (4.0 - 1), 2.67)
    check("P5c scaling law", 4**(2 / 3), 2.52)
    check("P5c drag loss (m/s)", 0.4 * np.sqrt(np.pi * 3 * G0 * 7200 / 2), 231)


def nozzle_pressure():
    """Guided derivation 6: the price of a large nozzle at sea level."""
    from flight import vehicle, missions
    from flight.atmosphere import isa
    from flight.constants import G0 as G0_
    h, H, a, KD, P = sp.symbols("h H a K_D P", positive=True)
    sym_zero("P6a integral", sp.integrate(h**sp.Rational(-1, 2) * sp.exp(-h / H), (h, 0, sp.oo)) - sp.sqrt(sp.pi * H))
    dVp = P / sp.sqrt(2 * a) * sp.sqrt(sp.pi * H)
    sym_zero("P6a result", dVp - P * sp.sqrt(sp.pi * H / (2 * a)))
    dVD = KD * sp.sqrt(sp.pi * a * H / 2)
    sym_zero("P6d product", sp.simplify(dVD * dVp - sp.pi * H / 2 * KD * P))
    p0, p11 = isa(0.0)[1], isa(11000.0)[1]
    check("P6b p(11 km) kPa", p11 / 1e3, 22.63, tol=0.005)
    Hp = 11000 / np.log(p0 / p11)
    check("P6b H_p (km)", Hp / 1e3, 7.34, tol=0.005)
    m = missions.pslv_c18_like(); tr = missions.fly(m)
    v = m.vehicle
    check("P6c m0 (t)", tr.m[0] / 1e3, 229.7, tol=0.05)
    check("P6c A_e", v.stages[0].engine.A_e, 4.077, tol=5e-4)
    check("P6c sea-level thrust (kN)", tr.thrust[0] / 1e3, 3060, tol=0.5)
    a0 = tr.thrust[0] / tr.m[0] - G0_
    check("P6c a", a0, 3.52, tol=0.005)
    check("P6c p0 A_e (kN)", p0 * v.stages[0].engine.A_e / 1e3, 413, tol=0.5)
    PA = p0 * v.stages[0].engine.A_e / tr.m[0]
    check("P6c p0A_e/m", PA, 1.80, tol=0.005)
    check("P6c estimate", PA * np.sqrt(np.pi * Hp / (2 * a0)), 103, tol=0.5)
    Tv = np.array([v.stages[int(k)].engine.T_vac for k in tr.stage])
    on = (tr.thrust > 0) & (tr.stage == 0)
    check("P6c simulator PS1", np.trapz(np.where(on, (Tv - tr.thrust) / tr.m, 0.0), tr.t), 102.8, tol=0.05)


def steering_turn():
    """Guided derivation 7: turning the path while the engine burns."""
    from scipy.integrate import solve_ivp
    V, V0, V1, al, dg = sp.symbols("V V_0 V_1 alpha Delta_gamma", positive=True)
    sym_zero("P7a integral", sp.integrate(sp.tan(al) / V, (V, V0, V1)) - sp.tan(al) * sp.log(V1 / V0))
    loss = (V1 - V0) * (1 / sp.cos(al) - 1)
    sym_zero("P7b small angle", sp.series(1 / sp.cos(al) - 1, al, 0, 3).removeO() - al**2 / 2)
    v0, v1, d = 2000.0, 4000.0, np.radians(5)
    check("P7c ln2", np.log(2), 0.693, tol=5e-4)
    check("P7c 5 deg rad", d, 0.0873, tol=5e-5)
    a_ = np.arctan(d / np.log(v1 / v0))
    check("P7c alpha", np.degrees(a_), 7.18, tol=0.005)
    L = (v1 - v0) * (1 / np.cos(a_) - 1)
    check("P7c loss", L, 15.8, tol=0.05)
    check("P7c small-angle", (v1 - v0) * d**2 / (2 * np.log(2)**2), 15.9, tol=0.05)
    sol = solve_ivp(lambda t, y: [16 * np.cos(a_), 16 * np.sin(a_) / y[0], 16.0], (0, (v1 - v0) / (16 * np.cos(a_))), [v0, 0, 0], rtol=1e-11)
    check("P7c ODE turn", sol.y[1, -1], d, tol=1e-6)
    check("P7c ODE loss", sol.y[2, -1] - (sol.y[0, -1] - v0), L, tol=1e-4)
    i0, i1 = 2 * v0 * np.sin(d / 2), 2 * v1 * np.sin(d / 2)
    check("P7c impulse 2 km/s", i0, 174, tol=0.5)
    check("P7c impulse 4 km/s", i1, 349, tol=0.5)
    check("P7c ten times", i0 / L, 11, tol=0.5)
    check("P7c twenty times", i1 / L, 22, tol=0.5)


if __name__ == "__main__":
    run([objective, sounding, turn, energy, turn_clock, gravity_drag, nozzle_pressure, steering_turn])
