"""Lecture 15: required thrust and required power of any parabolic-polar aircraft in level flight, in the units of the
note, each split into its zero-lift and lift-dependent parts, with values of C_L/C_L* marked along the thrust curve
(C_L/C_L* = 1/u^2). Writes img/fig-15-power-parts.png."""
import numpy as np
from _visual import plt, save, despine, MAROON, BLUE, GREEN, INK, GREY
from flight import performance as PF

U = np.linspace(0.45, 2.0, 300)
CL_MARKS = [3.0, 2.0, 1.0, 0.5, 0.333]


def power_parts(u):
    """(zero-lift, lift-dependent) parts of the power in units D* V*: the drag parts times u."""
    return u * (0.5 * u**2), u * (0.5 / u**2)


if __name__ == "__main__":
    fig, (a, b) = plt.subplots(1, 2, figsize=(10.5, 4.8), gridspec_kw=dict(wspace=0.22))
    a.plot(U, PF.drag_ratio(U), color=INK, lw=3, label="total")
    a.plot(U, 0.5 * U**2, color=BLUE, lw=2, ls="--", label="zero-lift part")
    a.plot(U, 0.5 / U**2, color=GREEN, lw=2, ls="--", label="lift-dependent part")
    for r in CL_MARKS:
        u = r**-0.5; a.plot(u, PF.drag_ratio(u), "o", color=MAROON, ms=7, zorder=5)
        a.annotate(f"{r:.2g}" if r > 0.34 else "1/3", (u, PF.drag_ratio(u)), xytext=(0, 8), textcoords="offset points", ha="center", fontsize=11, color=MAROON)
    a.text(1.62, 2.75, "dots: $C_L/C_L^*$", color=MAROON, fontsize=11.5, ha="center")
    z, i = power_parts(U)
    b.plot(U, PF.power_ratio(U), color=INK, lw=3); b.plot(U, z, color=BLUE, lw=2, ls="--"); b.plot(U, i, color=GREEN, lw=2, ls="--")
    um = PF.U_MIN_POWER; b.plot(um, PF.power_ratio(um), "o", color=MAROON, ms=8)
    b.annotate(f"least power\n$u$ = {um:.2f}", (um, PF.power_ratio(um)), xytext=(-4, 32), textcoords="offset points", ha="center", fontsize=11.5)
    a.set_ylim(0, 3.1); b.set_ylim(0, 4.2); a.set_ylabel("$D/D^*$"); b.set_ylabel("$P/(D^*V^*)$")
    for ax in (a, b):
        ax.set_xlim(0.45, 2.0); ax.set_xlabel("$u=V/V^*$"); despine(ax)
    a.legend(frameon=False, fontsize=11, loc="upper left")
    save(fig, "fig-15-power-parts")
