"""Lecture 15: four very different aircraft in level flight. Left: drag against true airspeed on log axes. Right: the
same points as D/D* against u = V/V*, all on one curve. Masses and heights as listed in AIRCRAFT; polars from the
course data. Writes img/fig-15-drag-collapse.png."""
import numpy as np
from _visual import plt, save, despine, MAROON, BLUE, GREEN, AMBER, INK
from _scripts import load
from flight import performance as PF, atmosphere as A, vehicle
from flight.constants import G0, FT, LBF
import _transport as TR

P12 = load("fig-12-polar")
kiran = vehicle.load("hjt-16-kiran").aero
sbj = vehicle.load("sbj-hull").aero
AIRCRAFT = [("HANSA-3, sea level", 750.0 * G0, P12.S_H, P12.CD0_H, P12.K_H, 0.0, GREEN, "o"),
            ("Kiran, 6 km", 4950.0 * G0, kiran.S, float(kiran.cd0(0.0)), float(kiran.k(0.0)), 6000.0, BLUE, "s"),
            ("Hull's jet, 35,000 ft", 11000.0 * LBF, sbj.S, 0.023, 0.073, 35000 * FT, AMBER, "^"),
            ("transport, 11 km", TR.W0, TR.S, TR.CD0, TR.K, 11000.0, MAROON, "D")]
U = np.linspace(0.7, 1.9, 13)


def curve(i, u):
    name, W, S, cd0, k, h, c, m = AIRCRAFT[i]
    rho = A.isa(h)[2]
    vs = PF.min_drag_speed(W, rho, S, cd0, k)
    V = u * vs
    D = np.add(*PF.level_flight_drag(W, rho, V, S, cd0, k))
    D_star = np.add(*PF.level_flight_drag(W, rho, vs, S, cd0, k))
    return V, D, D / D_star


if __name__ == "__main__":
    fig, (a, b) = plt.subplots(1, 2, figsize=(10.5, 4.8))
    fig.subplots_adjust(wspace=0.28)
    uu = np.linspace(0.65, 2.0, 200)
    b.plot(uu, PF.drag_ratio(uu), color=INK, lw=1.4)
    for i, row in enumerate(AIRCRAFT):
        V, D, _ = curve(i, uu)
        a.plot(V, D / 1e3, color=row[6], lw=2.4, label=row[0])
        V, D, r = curve(i, U[i::4])
        a.plot(V, D / 1e3, row[7], color=row[6], ms=7)
        b.plot(U[i::4], r, row[7], color=row[6], ms=8, ls="none")
    a.set_xscale("log"); a.set_yscale("log"); a.set_xlabel("true airspeed (m/s)"); a.set_ylabel("drag (kN)")
    a.set_xticks([30, 100, 300], ["30", "100", "300"]); a.set_ylim(0.4, 9000)
    a.legend(frameon=False, fontsize=10, loc="upper left")
    b.set_xlabel("$u=V/V^*$"); b.set_ylabel("$D/D^*$"); b.set_ylim(0.8, 2.1); b.set_xlim(0.65, 2.0)
    despine(a); despine(b)
    save(fig, "fig-15-drag-collapse")
