"""Lecture 25, a loop of the HJT-16 Kiran model (partly estimated dataset, 4500 kg, full thrust 18.4 kN at sea level,
T proportional to density) on the course simulator (flat-Earth form, Lecture 7), flown at a constant lift coefficient
chosen to give 5 g at the entry, 165 m/s (594 km/h) at 1 km. The Surya Kiran team flew the Kiran Mk II from 1996 to
2011 between 150 and 600 km/h and +6 and -1.5 g (Wikipedia, "Surya Kiran", read 2026-11-28). Path (left), airspeed and
load factor against time (right). Writes img/anim-25-kiran-loop.gif."""
import numpy as np
from _visual import plt, save_anim, despine, MAROON, BLUE, INK, GREY
from flight import vehicle, guidance, simulate, eom, atmosphere as A, performance as PF
from flight.constants import G0

KIRAN = vehicle.load("hjt-16-kiran")
M, H0, V0, N0 = 4500.0, 1000.0, 165.0, 5.0
CL = PF.cl_for_load_factor(N0, M * G0, A.isa(H0)[2], V0, KIRAN.aero.S)


def back_to_level(t, y):
    return y[4] - 2 * np.pi


back_to_level.direction = 1
TR = simulate.simulate(KIRAN, dict(h=H0, V=V0, gamma_deg=0.0, chi_deg=0.0, m=M), guidance.ConstantCL(CL, throttle=1.0),
                       eom.Options(gravity="flat"), t_end=80.0, max_step=0.02, form="flat", stops=(back_to_level,))
I_TOP = int(np.argmax(TR.h))
N_END = TR.load_factor[-1]
TOP = dict(t=TR.t[I_TOP], h=TR.h[I_TOP], V=TR.V[I_TOP], n=TR.load_factor[I_TOP])
END = dict(t=TR.t[-1], h=TR.h[-1], V=TR.V[-1], x=TR.x[-1])

if __name__ == "__main__":
    fig = plt.figure(figsize=(11, 5.0))
    a1 = fig.add_axes([0.1, 0.14, 0.38, 0.8])
    a2 = fig.add_axes([0.58, 0.58, 0.38, 0.36])
    a3 = fig.add_axes([0.58, 0.14, 0.38, 0.36])
    N = 110
    times = np.linspace(0, TR.t[-1], N)

    def frame(k):
        for a in (a1, a2, a3):
            a.clear()
        m = TR.t <= times[k]
        a1.plot(TR.x[m] / 1e3, TR.h[m] / 1e3, color=MAROON, lw=2.4)
        a1.plot(TR.x[m][-1] / 1e3, TR.h[m][-1] / 1e3, "o", color=MAROON, ms=8)
        a1.set_aspect("equal"); a1.set_xlim(-0.35, 1.0); a1.set_ylim(0.8, 2.3)
        a1.set_xlabel("distance (km)"); a1.set_ylabel("height (km)")
        a2.plot(TR.t[m], TR.V[m], color=BLUE, lw=2.2)
        a2.set_xlim(0, TR.t[-1]); a2.set_ylim(80, 190); a2.set_ylabel("speed (m/s)")
        a2.set_xticklabels([])
        a3.plot(TR.t[m], TR.load_factor[m], color=INK, lw=2.2)
        a3.axhline(6, color=GREY, lw=1, ls=":"); a3.text(1, 6.15, "+6 g", fontsize=11, color=GREY)
        a3.set_xlim(0, TR.t[-1]); a3.set_ylim(0, 6.8); a3.set_ylabel("load factor"); a3.set_xlabel("time (s)")
        if k == N - 1:
            a1.text(TR.x[I_TOP] / 1e3, TOP["h"] / 1e3 + 0.06, f"top: {TOP['V']:.0f} m/s, {TOP['n']:.1f} g", ha="center", fontsize=11)
        for a in (a1, a2, a3):
            despine(a)
        return []

    save_anim(fig, frame, N, 12, "anim-25-kiran-loop", hold=2.5)
