"""Lecture 21: the Kiran model's climb at full thrust (thrust proportional to density) at sea level in the standard
atmosphere and at Leh on a July afternoon (_takeoff.LEH, flight.atmosphere.density_altitude). Left: rate of climb
against true airspeed. Right: height gained per kilometre flown. Shallow-climb values (T - D)/W.
Writes img/fig-21-kiran-leh.png."""
import numpy as np
from _visual import plt, save, despine, MAROON, BLUE, INK, GREY
import _climb as C
import _takeoff as T
from flight import performance as PF, atmosphere as A
from flight.constants import G0

W = C.M_KIRAN * G0
CD0, K = C.polar(C.KIRAN)
RHO_LEH = T.airfield_state(T.LEH)[2]
H_DA = float(A.density_altitude(RHO_LEH))
PLACES = [("sea level, ISA", 0.0, BLUE), (f"Leh, July afternoon (density altitude {H_DA:.0f} m)", H_DA, MAROON)]
CLMAX = float(C.KIRAN.aero.clmax(0.0))


def curve(h, V):
    rho = A.isa(h)[2]
    D = np.add(*PF.level_flight_drag(W, rho, V, C.KIRAN.aero.S, CD0, K))
    sing = (C.thrust(C.KIRAN, h) - D) / W
    return V * sing, 1000 * sing / np.sqrt(1 - sing**2)       # rate of climb (m/s), metres up per km over the ground


def best(h):
    vs = PF.speed_for_cl(W, A.isa(h)[2], C.KIRAN.aero.S, CLMAX)
    V = np.linspace(1.2 * vs, 280.0, 4000)
    r, g = curve(h, V)
    i, j = int(np.argmax(r)), int(np.argmax(g))
    return dict(V=V, roc=r, grad=g, vroc=V[i], rmax=r[i], vgrad=V[j], gmax=g[j])


if __name__ == "__main__":
    fig, (a, b) = plt.subplots(1, 2, figsize=(10.5, 4.8))
    fig.subplots_adjust(wspace=0.26)
    for lab, h, c in PLACES:
        d = best(h)
        a.plot(d["V"], d["roc"], color=c, lw=2.7, label=lab); b.plot(d["V"], d["grad"], color=c, lw=2.7)
        a.plot(d["vroc"], d["rmax"], "o", color=c, ms=8); b.plot(d["vgrad"], d["gmax"], "o", color=c, ms=8)
        a.annotate(f"{d['rmax']:.1f} m/s", (d["vroc"], d["rmax"]), xytext=(0, 9), textcoords="offset points", ha="center", color=c, fontsize=11.5)
        b.annotate(f"{d['gmax']:.0f} m per km", (d["vgrad"], d["gmax"]), xytext=(34, 14), textcoords="offset points", color=c, fontsize=11.5)
    a.set_ylabel("rate of climb (m/s)"); b.set_ylabel("height gained per km (m)")
    for ax in (a, b):
        ax.set_xlabel("true airspeed (m/s)"); ax.set_xlim(40, 290); despine(ax)
    a.set_ylim(0, 45); b.set_ylim(0, 340)
    fig.legend(*a.get_legend_handles_labels(), frameon=False, fontsize=11.5, loc="upper center", ncol=2, bbox_to_anchor=(0.5, 0.0))
    save(fig, "fig-21-kiran-leh")
