"""Lecture 37, stick fixed against stick free for Hull's business jet (_stab; free tail slope f times the fixed one,
flight.stability.free_tail). Left: C_m against the angle of attack at x_cg = 0.30, both lines drawn through the same
trim point (the cruise angle of attack, with the elevator or the tab set for C_m = 0 there). Right: the slope
C_malpha against the CG position for both, crossing zero at the two neutral points; Hull's CG range shaded.
Writes img/fig-37-stick-free.png."""
import numpy as np
from _visual import plt, save, despine, MAROON, BLUE, GREY, INK
import _stab as S
from flight import stability as ST

FREE = ST.free_tail(S.TAIL, S.HINGE)
XCG = 0.30


def cma(x, tail):
    return ST.moment_coefficients(x, S.WING, tail, S.THRUST)[1]


SLOPE_FIXED, SLOPE_FREE = cma(XCG, S.TAIL), cma(XCG, FREE)
X_NP, X_NP_FREE = ST.neutral_point(S.WING, S.TAIL), ST.neutral_point(S.WING, FREE)
ALPHA_TRIM = ST.trim(S.CL_CRUISE, *ST.lift_coefficients(S.WING, S.TAIL), *ST.moment_coefficients(XCG, S.WING, S.TAIL, S.THRUST))[0]

if __name__ == "__main__":
    fig, (a1, a2) = plt.subplots(1, 2, figsize=(10.5, 4.9))
    fig.subplots_adjust(wspace=0.3)
    al = np.radians(np.linspace(-2, 8, 100))
    for slope, c, lab in ((SLOPE_FIXED, BLUE, "stick fixed"), (SLOPE_FREE, MAROON, "stick free")):
        a1.plot(np.degrees(al), slope * (al - ALPHA_TRIM), color=c, lw=2.6, label=f"{lab}: slope {slope:.2f} per rad")
    a1.plot(np.degrees(ALPHA_TRIM), 0, "o", color=INK, ms=8, zorder=5)
    a1.axhline(0, color=GREY, lw=0.8)
    a1.set_xlabel("angle of attack (deg)"); a1.set_ylabel("$C_m$ about the CG at 0.30")
    a1.set_ylim(-0.12, 0.135)
    a1.legend(frameon=False, fontsize=11, loc="upper right")
    x = np.linspace(0.1, 0.6, 100)
    a2.axvspan(*S.CG_RANGE, color=BLUE, alpha=0.12)
    a2.text(np.mean(S.CG_RANGE), 0.45, "Hull's CG range", ha="center", fontsize=11, color=BLUE)
    for tail, c, xn, lab, dy in ((S.TAIL, BLUE, X_NP, "fixed", -0.55), (FREE, MAROON, X_NP_FREE, "free", 0.28)):
        a2.plot(x, [cma(xx, tail) for xx in x], color=c, lw=2.6)
        a2.plot(xn, 0, "o", color=c, ms=9)
        a2.annotate(f"$x_{{np}}$ {lab}: {xn:.3f}", xy=(xn, 0), xytext=(xn - (0.19 if lab == "free" else 0.04), dy), fontsize=11, color=c,
                    arrowprops=dict(arrowstyle="->", color=c))
    a2.axhline(0, color=GREY, lw=0.8)
    a2.set_xlim(0.1, 0.6); a2.set_ylim(-2.2, 0.7)
    a2.set_xlabel("CG position (chords)"); a2.set_ylabel("slope $C_{m_\\alpha}$ (per rad)")
    despine(a1); despine(a2)
    save(fig, "fig-37-stick-free")
