"""Lecture 18: the zero-lift and lift-dependent parts of the required thrust coefficient, M^2 C_D0 and K omega^2/M^2,
for the Tejas-class model at 8500 kg and 11 km (_fighter, flight.performance.thrust_required_mach).
Writes img/fig-18-drag-split.png."""
import numpy as np
from _visual import plt, save, despine, MAROON, BLUE, INK, GREY
import _fighter as F
from flight import performance as PF

H = 11000.0
OM = F.omega(F.TEJ, F.M_REF, H)
M = np.linspace(0.4, 1.9, 400)


def parts(m):
    """(zero-lift, lift-dependent) parts of tau_r at Mach m."""
    a = F.TEJ.aero
    return (float(PF.thrust_required_mach(m, 0.0, a.cd0(m), a.k(m))),
            float(PF.thrust_required_mach(m, OM, a.cd0(m), a.k(m)) - PF.thrust_required_mach(m, 0.0, a.cd0(m), a.k(m))))


P = np.array([parts(m) for m in M])
_d = P[:, 0] - P[:, 1]
M_EQUAL = [float(M[i]) for i in np.where(np.diff(np.sign(_d)) != 0)[0]]


def share(m):
    z, i = parts(m)
    return z / (z + i)


if __name__ == "__main__":
    fig, ax = plt.subplots(figsize=(10, 4.9))
    ax.stackplot(M, P[:, 0], P[:, 1], colors=[MAROON, BLUE], alpha=0.7, labels=["zero-lift part $M^2C_{D_0}$", "lift-dependent part $K\\omega^2/M^2$"])
    for m in M_EQUAL:
        ax.axvline(m, color=INK, lw=1.4, ls="--"); ax.text(m + 0.015, 0.45 * P.sum(1).max(), f"equal parts\nMach {m:.2f}", fontsize=11.5)
    for m in (1.2, 1.6):
        ax.text(m, 0.5 * parts(m)[0], f"{100 * share(m):.0f} % zero-lift", ha="center", color="white", fontsize=12.5)
    ax.set_xlim(0.4, 1.9); ax.set_ylim(0, None); ax.set_xlabel("Mach number"); ax.set_ylabel("required thrust coefficient $\\tau_r$")
    ax.legend(frameon=False, fontsize=11.5, loc="upper left")
    despine(ax)
    save(fig, "fig-18-drag-split")
