"""Lecture 29, dynamic pressure on the reference PSLV ascent: q against height, and near its maximum the density scale
height of the standard atmosphere against the scale height V^2 sin(gamma)/(2 dV/dt) at which q would be stationary.
Writes img/fig-29-maxq.png."""
import numpy as np
from _visual import plt, save, despine, MAROON, BLUE, GREY
import _ascent as AS
from flight import rocket as R, atmosphere as A

_, TR, _ = AS.reference()
M = TR.t < 105.0
I = int(np.argmax(TR.q))
WIN = np.where((TR.h > 8e3) & (TR.h < 14e3) & (TR.t < 105.0))[0]
NEED = np.array([R.max_q_scale_height(TR.V[k], TR.gamma[k], (TR.V[k + 1] - TR.V[k - 1]) / (TR.t[k + 1] - TR.t[k - 1])) for k in WIN])
H_AIR = np.linspace(8e3, 14e3, 600)
H_RHO = np.array([R.density_scale_height(lambda z: A.isa(z)[2], z) for z in H_AIR])

if __name__ == "__main__":
    fig, (a, b) = plt.subplots(1, 2, figsize=(10, 4.4), gridspec_kw=dict(wspace=0.3))
    a.plot(TR.q[M] / 1e3, TR.h[M] / 1e3, color=MAROON, lw=2.4)
    a.plot(TR.q[I] / 1e3, TR.h[I] / 1e3, "o", color=MAROON, ms=8)
    a.annotate(f"{TR.q[I] / 1e3:.1f} kPa\n{TR.h[I] / 1e3:.1f} km, {TR.t[I]:.0f} s", (TR.q[I] / 1e3, TR.h[I] / 1e3),
               xytext=(21, 32), fontsize=11, arrowprops=dict(arrowstyle="-", color=GREY))
    a.set_xlabel("dynamic pressure (kPa)"); a.set_ylabel("height (km)"); a.set_xlim(0, 45); a.set_ylim(0, 40)
    b.plot(H_RHO / 1e3, H_AIR / 1e3, color=BLUE, lw=2.4, label="of the air")
    b.plot(NEED / 1e3, TR.h[WIN] / 1e3, color=MAROON, lw=2.4, label="needed for max $q$")
    b.axhline(11.0, color=GREY, ls=":", lw=1)
    b.set_xlabel("density scale height (km)"); b.set_ylabel("height (km)"); b.set_xlim(5, 10); b.set_ylim(8, 14)
    b.legend(frameon=False, fontsize=11, ncol=2, loc="upper center", bbox_to_anchor=(0.45, -0.17))
    despine(a); despine(b)
    save(fig, "fig-29-maxq")
