"""Lecture 37: how flight test finds the neutral point. Left: the elevator angle to trim against lift coefficient for
several CG positions of Hull's business jet. Right: the slope of each of those lines against CG position; it
vanishes at the neutral point. Writes img/fig-37-flight-test.png."""
import numpy as np
from _visual import plt, save, despine, MAROON, BLUE, GREEN, AMBER, INK
import _stab as S
from flight import stability as ST
from flight.constants import DEG

CL = np.linspace(0.2, 1.2, 6)
CGS = (0.15, 0.25, 0.35, 0.45)
XNP = ST.neutral_point(S.WING, S.TAIL)


def slope_deg(x_cg):
    cm0, cma, cmd = ST.moment_coefficients(x_cg, S.WING, S.TAIL, S.THRUST)
    _, cla, cld = ST.lift_coefficients(S.WING, S.TAIL)
    return ST.trim_slopes(cla, cld, cma, cmd)[1] / 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 zip(CGS, (BLUE, GREEN, AMBER, MAROON)):
        a.plot(CL, [ST.trim_at_cg(cl, x, S.WING, S.TAIL, S.THRUST)[1] / DEG for cl in CL], "o-", color=c, lw=2, ms=5, label=f"CG at {x:.2f}")
        b.plot(x, slope_deg(x), "o", color=c, ms=10)
    a.set_xlabel("lift coefficient in level flight"); a.set_ylabel(r"$\delta_e$ to trim (°)")
    a.legend(frameon=False, fontsize=11, loc="lower left"); a.set_ylim(-30, 7)
    x = np.linspace(0.12, XNP, 50)
    b.plot(x, [slope_deg(v) for v in x], color=INK, lw=1.4, ls="--", zorder=1)
    b.axhline(0, color=INK, lw=0.9)
    b.plot(XNP, 0, "X", color=INK, ms=12)
    b.annotate("neutral point", (XNP, 0), textcoords="offset points", xytext=(-22, -4), ha="right", va="top", fontsize=11)
    b.set_xlabel("CG position"); b.set_ylabel(r"slope $d\delta_e/dC_L$ (°)")
    despine(a); despine(b)
    save(fig, "fig-37-flight-test")
