"""Lecture 39, the rudder needed to hold a failed engine against speed, without units: from eq-oei at zero sideslip with
a thrust that does not change with speed, |delta_r| / delta_r,max = (V_mc / V)^2. A bigger rudder or fin that raises
|C_ndr| by 30 % lowers V_mc by 1/sqrt(1.3). Writes img/fig-39-vmc.png."""
import numpy as np
from _visual import plt, save, despine, MAROON, BLUE, INK, GREY

U = np.linspace(0.68, 2.5, 400)                 # V / V_mc of the basic aircraft
GAIN = 1.3


def rudder(u, gain=1.0):
    """Fraction of the full rudder travel needed at speed u V_mc."""
    return 1.0 / (gain * u**2)


V_MC_BIG = 1 / np.sqrt(GAIN)

if __name__ == "__main__":
    fig, ax = plt.subplots(figsize=(10, 5.2))
    ax.axhspan(1.0, 2.0, color=MAROON, alpha=0.10)
    ax.axhline(1.0, color=MAROON, lw=1.6)
    ax.text(2.45, 1.05, "the rudder is at its stop", ha="right", fontsize=12, color=MAROON)
    ax.plot(U, rudder(U), color=INK, lw=2.8, label="the aircraft")
    ax.plot(U, rudder(U, GAIN), color=BLUE, lw=2.4, label="30 % more rudder power")
    for x, c, lab, ha in ((1.0, INK, "$V_{mc}$", "left"), (V_MC_BIG, BLUE, f"{V_MC_BIG:.2f} $V_{{mc}}$", "right")):
        ax.plot(x, 1.0, "o", color=c, ms=9, zorder=5)
        ax.plot([x, x], [0, 1.0], color=c, lw=1, ls="--")
        ax.text(x + (0.02 if ha == "left" else -0.02), 0.05, lab, ha=ha, fontsize=12, color=c)
    ax.set_xlim(0.68, 2.5); ax.set_ylim(0, 1.6)
    ax.set_xlabel("speed, $V/V_{mc}$"); ax.set_ylabel("rudder needed / full travel")
    ax.legend(frameon=False, fontsize=12, loc="upper right", bbox_to_anchor=(1.0, 0.6))
    despine(ax)
    save(fig, "fig-39-vmc")
