"""Lecture 37: the angle of attack and elevator angle of Hull's business jet in level flight against speed, at
30,000 ft, for three CG positions, with the Mach 0.6 aerodynamics used at every speed (an idealisation).
Writes img/fig-37-trim-speed.png."""
import numpy as np
from _visual import plt, save, despine, MAROON, BLUE, GREEN, INK
import _stab as S
from flight import stability as ST
from flight.constants import DEG

V = np.linspace(95, 230, 200)
CL = S.WEIGHT / (0.5 * S.RHO * V ** 2 * S.AREA)
CGS = ((0.15, BLUE), (0.30, INK), (0.45, MAROON))


def trim_curve(x_cg):
    return np.array([ST.trim_at_cg(c, x_cg, S.WING, S.TAIL, S.THRUST) for c in CL]).T / DEG


if __name__ == "__main__":
    fig, (a, b) = plt.subplots(1, 2, figsize=(10, 4.2))
    fig.subplots_adjust(wspace=0.3)
    for x, c in CGS:
        al, de = trim_curve(x)
        a.plot(V, al, color=c, lw=2.4, label=f"CG at {x:.2f}")
        b.plot(V, de, color=c, lw=2.4, label=f"CG at {x:.2f}")
    a.set_ylabel("angle of attack to trim (°)"); b.set_ylabel(r"elevator to trim, $\delta_e$ (°)")
    for ax in (a, b):
        ax.set_xlabel("true airspeed (m/s)"); ax.axhline(0, color=INK, lw=0.8); despine(ax)
    b.legend(frameon=False, fontsize=11, loc="lower right")
    save(fig, "fig-37-trim-speed")
