"""Lecture 16: flying faster than the best-range speed of a jet (parabolic polar, constant TSFC). Specific range and
block time, each relative to the best-range speed u = 3^(1/4), against the speed excess in per cent.
Writes img/fig-16-overspeed.png."""
import numpy as np
from scipy.optimize import brentq
from _visual import plt, save, despine, MAROON, BLUE, INK, GREY
from flight import performance as PF

U_BR = PF.best_range_u_wind(0.0)


def specific_range_ratio(excess):
    u = U_BR * (1 + np.asarray(excess))
    return (u / PF.drag_ratio(u)) / (U_BR / PF.drag_ratio(U_BR))


def time_ratio(excess):
    return 1.0 / (1 + np.asarray(excess))


X99 = brentq(lambda x: specific_range_ratio(x) - 0.99, 0.01, 0.3)

if __name__ == "__main__":
    x = np.linspace(0, 0.30, 300)
    fig, ax = plt.subplots(figsize=(10, 4.8))
    ax.plot(100 * x, 100 * specific_range_ratio(x), color=MAROON, lw=2.8, label="distance per kg of fuel")
    ax.plot(100 * x, 100 * time_ratio(x), color=BLUE, lw=2.8, label="time for the trip")
    for xx in (0.05, 0.10):
        for fn, c, dy in ((specific_range_ratio, MAROON, 1.2), (time_ratio, BLUE, -3.8)):
            ax.plot(100 * xx, 100 * fn(xx), "o", color=c, ms=7)
            ax.text(100 * xx + 0.4, 100 * fn(xx) + dy, f"{100 * fn(xx):.1f} %", color=c, fontsize=11.5)
    ax.axvline(100 * X99, color=GREY, lw=1.2, ls="--")
    ax.text(100 * X99 + 0.4, 78.5, f"99 % of the best range:\n{100 * X99:.1f} % faster", fontsize=11.5, color=INK)
    ax.set_xlim(0, 30); ax.set_ylim(76, 105)
    ax.set_xlabel("speed above the best-range speed (%)"); ax.set_ylabel("per cent of the value\nat the best-range speed")
    ax.legend(frameon=False, fontsize=12, loc="upper right", bbox_to_anchor=(1.0, 1.06))
    despine(ax)
    save(fig, "fig-16-overspeed")
