"""Lecture 16, the range integral (eq-range-integral) as an area: the specific range, distance per unit weight of fuel,
against the weight for the three cruise programs of anim-16-programs (Hull's business jet, 12,000 to 10,000 lb from
35,000 ft at the best-range speed; flight.performance through _isbj). The weight axis runs from heavy to light, so time
runs from left to right; the area under each curve is that program's range. Writes img/fig-16-range-area.png."""
import numpy as np
from _visual import plt, save, despine, GREY
import _isbj as J
from _scripts import load

P = load("anim-16-programs").PATHS
LB = 4.4482216152605
CURVES = {}
for lab, (x, dh, v, c) in P.items():
    W = np.linspace(J.W0, J.WF, len(x))
    sr = -np.gradient(x, W)                                  # m of distance per N of fuel burnt
    CURVES[lab] = dict(W=W, sr=sr, c=c, R=x[-1], area=float(np.trapz(sr, -W)))

if __name__ == "__main__":
    fig, ax = plt.subplots(figsize=(10, 5.2))
    ys = {lab: cv["sr"] * LB * 1000 / J.MILE for lab, cv in CURVES.items()}       # miles per 1000 lb of fuel
    for lab, cv in sorted(CURVES.items(), key=lambda it: it[1]["R"]):
        ax.plot(cv["W"] / LB, ys[lab], color=cv["c"], lw=2.6, label=f"{lab}: {cv['R'] / J.MILE:.0f} mi")
    x = next(iter(CURVES.values()))["W"] / LB
    low, top = ys["constant altitude and speed"], ys["cruise-climb (Breguet)"]
    ax.fill_between(x, 0, low, color=GREY, alpha=0.15)
    ax.fill_between(x, low, top, color=next(cv["c"] for l, cv in CURVES.items() if "Breguet" in l), alpha=0.25)
    ax.text(11850, 60, "area common to all three", ha="left", fontsize=12, color=GREY)
    ax.annotate("extra area of the cruise-climb", xy=(10300, 375), xytext=(10900, 430), fontsize=12,
                arrowprops=dict(arrowstyle="->", color=GREY))
    ax.set_xlim(12000, 10000)
    ax.set_ylim(0, 470)
    ax.set_xlabel("weight (lb), falling as fuel burns $\\rightarrow$"); ax.set_ylabel("specific range (mi per 1000 lb of fuel)")
    ax.legend(frameon=False, fontsize=12, loc="lower right", title="the area under each curve is its range", title_fontsize=11)
    despine(ax)
    save(fig, "fig-16-range-area")
