"""Lecture 29, Miele's sounding rocket (sec. 17-3): vertical flight with constant mass flow, constant C_D and an
exponential atmosphere; propellant fraction 0.5, V_E/sqrt(g lambda) = 11.8. Peak height (in scale heights) against the
initial thrust-to-weight ratio for drag factors 0, 0.1 and 0.4, with the best ratios marked. Writes img/fig-29-sounding.png."""
import numpy as np
from _visual import plt, save, despine, MAROON, BLUE, GREEN
from flight import rocket as R

ZETA = 0.5
TAU = np.geomspace(1.15, 40.0, 90)
CASES = []
for kd, c, lab in ((0.0, GREEN, "no drag"), (0.1, BLUE, "$K_D$ = 0.1 (large rocket)"), (0.4, MAROON, "$K_D$ = 0.4 (small rocket)")):
    peak = np.array([R.sounding_rocket(ZETA, t, kd)["eta_f"] for t in TAU])
    best = R.best_thrust_to_weight(ZETA, kd) if kd else None
    CASES.append(dict(kd=kd, c=c, lab=lab, peak=peak, best=best))

if __name__ == "__main__":
    fig, ax = plt.subplots(figsize=(10, 4.8))
    for cs in CASES:
        ax.semilogx(TAU, cs["peak"], color=cs["c"], lw=2.4, label=cs["lab"])
        if cs["best"]:
            ax.plot(*cs["best"], "o", color=cs["c"], ms=8)
            ax.annotate(f"best T/W {cs['best'][0]:.1f}", cs["best"], textcoords="offset points", xytext=(0, 9), ha="center", fontsize=11, color=cs["c"])
    ax.set_xticks([1.5, 2, 4, 8, 16, 32], ["1.5", "2", "4", "8", "16", "32"]); ax.minorticks_off()
    ax.set_xlabel("initial thrust / weight"); ax.set_ylabel("peak height / scale height"); ax.set_ylim(0, 40)
    fig.legend(frameon=False, fontsize=11, ncol=3, loc="upper center", bbox_to_anchor=(0.5, 0.0))
    despine(ax)
    save(fig, "fig-29-sounding")
