"""Lecture 27, the landing ground run of Hull's SBJ at sea level (flaps 40 deg, 13,000 lb, touch-down at 1.2 V_stall, idle thrust
390 lb): airspeed against distance for braking coefficients 0.40, 0.35 (Hull's value), 0.30 and 0.20, spanning Filippone's
"good" to "poor" braking action (Table 11.5), and at 0.35 with reverse thrust of 40 % of the take-off thrust (Hull sec. 6.1).
Writes img/fig-27-ground-run.png."""
import numpy as np
from _visual import plt, save, despine, MAROON, BLUE, GREEN, AMBER, INK, GREY
import _takeoff as T
from flight import performance as PF, atmosphere as A

RHO = A.isa(0.0)[2]
VTD = 1.2 * T.stall(RHO, T.LAND["clmax"])
CASES = [(0.40, 0.0, GREEN, "$\\mu$ = 0.40"), (0.35, 0.0, BLUE, "$\\mu$ = 0.35 (Hull)"), (0.30, 0.0, AMBER, "$\\mu$ = 0.30"),
         (0.20, 0.0, MAROON, "$\\mu$ = 0.20, poor"), (0.35, 0.4 * T.T_AVG, INK, "$\\mu$ = 0.35, 40 % reverse thrust")]
RUNS = []
for mu, rev, c, lab in CASES:
    cfg = dict(T.LAND, mu=mu)
    f = lambda V, cfg=cfg, rev=rev: T.net_force(V, RHO, T.LAND["idle"] - rev, cfg)
    V = np.linspace(VTD, 0.5, 40)
    x = np.array([0.0] + [PF.ground_run_numeric(f, T.M, VTD, v, n=400)[0] for v in V[1:]])
    xs, ts = PF.ground_run_numeric(f, T.M, VTD, 1e-3)
    RUNS.append(dict(mu=mu, rev=rev, c=c, lab=lab, V=V, x=x, total=xs, time=ts))

if __name__ == "__main__":
    fig, ax = plt.subplots(figsize=(10, 4.6))
    for r in RUNS:
        ax.plot(r["x"], r["V"], color=r["c"], lw=2.4, ls="--" if r["rev"] else "-", label=f"{r['lab']}: {r['total']:.0f} m")
    ax.set_xlabel("distance from touch-down (m)"); ax.set_ylabel("airspeed (m/s)"); ax.set_xlim(0, 1400); ax.set_ylim(0, 70)
    fig.legend(frameon=False, fontsize=11, ncol=2, loc="upper center", bbox_to_anchor=(0.5, 0.0))
    despine(ax)
    save(fig, "fig-27-ground-run")
