"""Lecture 26, the take-off ground run itself: airspeed against distance for Hull's SBJ with average thrust (_takeoff:
net_force, lapse sigma^1.2) at sea level in the ISA, at Mumbai on a hot May afternoon and at Leh on a hot July
afternoon, from dx = m V dV / F, up to the lift-off speed 1.2 V_stall of each. Writes img/fig-26-speed-distance.png."""
import numpy as np
from scipy.integrate import cumulative_trapezoid
from _visual import plt, save, despine, MAROON, BLUE, GREEN, GREY
import _takeoff as T
from flight import atmosphere as A

CASES = []
for lab, rho, c in (("sea level, ISA", A.isa(0.0)[2], GREEN),
                    ("Mumbai, 33.7 °C", T.airfield_state(T.MUMBAI)[2], BLUE),
                    ("Leh, 28.5 °C", T.airfield_state(T.LEH)[2], MAROON)):
    lapse = (rho / T.RHO0_SL)**T.A_LAPSE
    vlo = 1.2 * T.stall(rho, T.TO["clmax"])
    V = np.linspace(0.0, vlo, 2001)
    F = np.array([T.net_force(v, rho, T.T_AVG * lapse, T.TO) for v in V])
    x = cumulative_trapezoid(T.M * V / F, V, initial=0.0)
    CASES.append(dict(label=lab, c=c, V=V, x=x, vlo=vlo, xg=x[-1]))


def speed_at_fraction(cs, f):
    """V/V_LO when the fraction f of the ground run has been used."""
    return float(np.interp(f * cs["xg"], cs["x"], cs["V"])) / cs["vlo"]


def distance_fraction_for_last(cs, f):
    """Fraction of the ground run used to gain the last fraction f of the lift-off speed."""
    return 1 - float(np.interp((1 - f) * cs["vlo"], cs["V"], cs["x"])) / cs["xg"]


if __name__ == "__main__":
    fig, ax = plt.subplots(figsize=(10, 5.2))
    for cs in CASES:
        ax.plot(cs["x"], cs["V"], color=cs["c"], lw=2.6, label=f"{cs['label']}: lift-off {cs['vlo']:.1f} m/s after {cs['xg']:.0f} m")
        ax.plot(cs["xg"], cs["vlo"], "o", color=cs["c"], ms=8)
    s0 = CASES[0]
    ax.plot([s0["xg"] / 2] * 2, [0, speed_at_fraction(s0, 0.5) * s0["vlo"]], color=GREY, lw=1, ls="--")
    ax.text(s0["xg"] / 2 + 15, 8, "half the run", fontsize=11, color=GREY)
    ax.set_xlim(0, 1750); ax.set_ylim(0, 95)
    ax.set_xlabel("distance along the runway (m)"); ax.set_ylabel("airspeed (m/s)")
    ax.legend(frameon=False, fontsize=11, loc="upper left")
    despine(ax)
    save(fig, "fig-26-speed-distance")
