"""Lecture 26: ground-run distance against the lift coefficient held on the runway, relative to the least distance, for
Hull's SBJ on concrete (mu = .02, take-off flaps, Hull's ground polar _takeoff.ground_cd_to) and for the HANSA-3 model
on grass (mu = .05 and .10, dataset polar and propeller thrust, sea level, lift-off at 1.2 V_stall). Writes img/fig-26-runway-cl.png."""
import numpy as np
from _visual import plt, save, despine, MAROON, BLUE, GREEN, INK, GREY
import _takeoff as T
from flight import performance as PF, atmosphere as A, aero as AE, vehicle
from flight.constants import G0, RHO0_SL

RHO = A.isa(0.0)[2]
H = vehicle.load("hansa-3")
H_M, H_S = H.gross_mass, H.aero.S
H_CD0, H_K, H_CLMAX = float(H.aero.cd0(0.0)), float(H.aero.k(0.0)), float(H.aero.clmax(0.0))
ENG = H.stages[0].engine


def run_sbj(cl):
    cfg = dict(T.TO, cl=cl, cd=T.ground_cd_to(cl))
    vlo = 1.2 * T.stall(RHO, T.TO["clmax"])
    return PF.ground_run_numeric(lambda V: T.net_force(V, RHO, T.T_AVG, cfg), T.M, 0.0, vlo, n=800)[0]


def run_hansa(cl, mu):
    cfg = dict(cl=cl, cd=AE.parabolic_cd(cl, H_CD0, H_K), mu=mu)
    vlo = 1.2 * PF.speed_for_cl(H_M * G0, RHO, H_S, H_CLMAX)
    thrust = lambda V: ENG.thrust(1.0, 101325.0, RHO, RHO / RHO0_SL, 1.0, max(V, 1.0), max(V, 1.0) / 340.3)
    return PF.ground_run_numeric(lambda V: T.net_force(V, RHO, thrust(V), cfg, weight=H_M * G0, S=H_S), H_M, 0.0, vlo, n=800)[0]


CL = np.linspace(0.0, 1.35, 136)
CASES = [("Hull's jet, concrete, $\\mu$ = 0.02", run_sbj, PF.best_ground_run_cl(0.02, T.KM_TO, T.CLM_TO), BLUE),
         ("HANSA-3 model, short grass, $\\mu$ = 0.05", lambda c: run_hansa(c, 0.05), PF.best_ground_run_cl(0.05, H_K), GREEN),
         ("HANSA-3 model, long grass, $\\mu$ = 0.10", lambda c: run_hansa(c, 0.10), PF.best_ground_run_cl(0.10, H_K), MAROON)]
DATA = [dict(label=l, run=f, best=b, c=c, d=np.array([f(x) for x in CL])) for l, f, b, c in CASES]

if __name__ == "__main__":
    fig, ax = plt.subplots(figsize=(10, 5.2))
    for r in DATA:
        ref = r["run"](r["best"])
        ax.plot(CL, 100 * (r["d"] / ref - 1), color=r["c"], lw=2.8, label=f"{r['label']}: least run {ref:.0f} m at $C_L$ = {r['best']:.2f}")
        ax.plot(r["best"], 0, "o", color=r["c"], ms=9, clip_on=False)
    ax.set_xlim(0, 1.35); ax.set_ylim(0, None); ax.set_xlabel("lift coefficient held on the runway"); ax.set_ylabel("extra ground run (%)")
    fig.legend(frameon=False, fontsize=11.5, loc="upper center", bbox_to_anchor=(0.5, 0.0))
    despine(ax)
    save(fig, "fig-26-runway-cl")
