"""Lecture 28, PSLV-CA (course dataset, 1 t payload) stage by stage: the mass at ignition and burnout of each stage and
the velocity each adds by the rocket equation with its vacuum specific impulse, no losses. The fairing is counted up
to the end of the second stage. Writes img/fig-28-pslv-stages.png."""
import numpy as np
from _visual import plt, save, despine, MAROON, BLUE, GREEN, AMBER, GREY, INK
from flight import rocket as R, vehicle

PSLV = vehicle.load("pslv-ca")
ROWS = R.stage_table(PSLV)
TOTAL = sum(r["dv"] for r in ROWS)

if __name__ == "__main__":
    fig, (a, b) = plt.subplots(1, 2, figsize=(10, 4.4), gridspec_kw=dict(wspace=0.32))
    k = np.arange(4)
    names = ["PS1", "PS2", "PS3", "PS4"]
    cols = [MAROON, BLUE, GREEN, AMBER]
    a.bar(k - 0.2, [r["m0"] / 1e3 for r in ROWS], 0.4, color=cols, label="ignition")
    a.bar(k + 0.2, [r["m1"] / 1e3 for r in ROWS], 0.4, color=cols, alpha=0.45, label="burnout")
    a.set_yscale("log"); a.set_ylim(1, 400); a.set_xticks(k, names); a.set_ylabel("mass (t)")
    for i, r in enumerate(ROWS):
        a.text(i, r["m0"] / 1e3 * 1.12, f"{r['m0'] / r['m1']:.2f}", ha="center", fontsize=11, color=INK)
    a.set_title("mass ratio of each stage", fontsize=11)
    base = 0.0
    for i, r in enumerate(ROWS):
        b.bar(i, r["dv"] / 1e3, bottom=base / 1e3, color=cols[i])
        b.text(i, (base + r["dv"]) / 1e3 + 0.2, f"+{r['dv'] / 1e3:.2f}", ha="center", fontsize=11, color=INK)
        base += r["dv"]
    b.set_xticks(k, names); b.set_ylim(0, 12); b.set_ylabel("ideal velocity (km/s)")
    b.set_title(f"total {TOTAL / 1e3:.2f} km/s", fontsize=11)
    despine(a); despine(b)
    save(fig, "fig-28-pslv-stages")
