"""Lecture 34: stagnation heat flux along the simulated equilibrium glides of the representative capsule re-massed to
B = 300 kg/m^2 (_entry33.glide) at L/D = 0.5, 1 and 2, against u = V^2/(g r), and the heat taken up to each time.
Writes img/fig-34-glide-heat.png."""
import numpy as np
from scipy.integrate import cumulative_trapezoid
from _visual import plt, save, despine, MAROON, BLUE, GREEN, INK, GREY
import _entry33 as C

CASES = []
for ld, c in ((0.5, MAROON), (1.0, BLUE), (2.0, GREEN)):
    tr = C.glide(ld)
    u, q = C.u_of(tr), tr.heat_flux
    Q = np.concatenate([[0], cumulative_trapezoid(q, tr.t)])
    i = int(np.argmax(q))
    CASES.append(dict(ld=ld, c=c, t=tr.t, u=u, q=q / 1e6, Q=Q / 1e6, u_peak=float(u[i]), q_peak=float(q[i] / 1e6), Q_end=float(Q[-1] / 1e6)))

if __name__ == "__main__":
    fig, (a, b) = plt.subplots(1, 2, figsize=(10.5, 4.8), gridspec_kw=dict(wspace=0.28))
    uu = np.linspace(0.05, 0.95, 200)
    shape = lambda u: u * np.sqrt(1 - u)
    for r in CASES:
        a.plot(r["u"], r["q"], color=r["c"], lw=2.8, label=f"$L/D$ = {r['ld']:g}")
        a.plot(uu, r["q_peak"] * shape(uu) / shape(2 / 3), color=INK, lw=1, ls="--")
        b.plot(r["t"], r["Q"], color=r["c"], lw=2.8)
        b.plot(r["t"][-1], r["Q_end"], "o", color=r["c"], ms=7)
        b.annotate(f"{r['Q_end']:.0f}", (r["t"][-1], r["Q_end"]), xytext=(-4, 8), textcoords="offset points", ha="right", color=r["c"], fontsize=12)
    a.axvline(2 / 3, color=GREY, lw=1.2, ls=":"); a.text(0.665, 0.005, "$u=2/3$", fontsize=12, ha="right", rotation=90, va="bottom")
    a.set_xlim(0.95, 0.0); a.set_ylim(0, 0.42); a.set_xlabel("$u=V^2/(gr)$, falling during the flight"); a.set_ylabel("heat flux (MW/m²)")
    b.set_xlabel("time (s)"); b.set_ylabel("heat taken up (MJ/m²)"); b.set_xlim(0, None); b.set_ylim(0, 500)
    a.legend(frameon=False, fontsize=11.5, loc="upper right")
    despine(a); despine(b)
    save(fig, "fig-34-glide-heat")
