"""Lecture 16, why the best range is faster than the minimum drag: the fuel per unit distance is proportional to
D/V, the slope of a line from the origin to the drag curve, smallest where that line touches the curve, at
u = 3^(1/4); the minimum drag itself is at u = 1 (flight.performance.drag_ratio). Writes img/fig-16-tangent.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.3, 2.4, 300)
UR = 3**0.25

if __name__ == "__main__":
    fig, ax = plt.subplots(figsize=(10, 5.4))
    ax.plot(U, PF.drag_ratio(U), color=MAROON, lw=2.7, label="drag $D/D^*$")
    ax.plot([0, 2.3], [0, 2.3 * PF.drag_ratio(UR) / UR], color=BLUE, lw=2, ls="--", label="tangent from the origin")
    ax.plot(UR, PF.drag_ratio(UR), "o", color=BLUE, ms=9)
    ax.text(UR + 0.05, PF.drag_ratio(UR) - 0.28, f"best range\n$u=3^{{1/4}}={UR:.3f}$", color=BLUE, fontsize=12)
    ax.plot(1, 1, "o", color=MAROON, ms=8)
    ax.text(0.62, 0.3, "minimum drag,\nbest endurance\n$u=1$", color=MAROON, fontsize=12, ha="center")
    ax.set_xlim(0, 2.4); ax.set_ylim(0, 3)
    ax.set_xlabel("$u=V/V^*$"); ax.set_ylabel("$D/D^*$")
    ax.legend(frameon=False, fontsize=12, loc="upper left")
    despine(ax)
    save(fig, "fig-16-tangent")
