"""Lecture 38: Hull's business jet. Left: elevator angle per g in a pull-up against CG position at 30,000 ft, for
three speeds; all cross zero at the same CG, the manoeuvre point. Right: the distance from the neutral point to the
manoeuvre point against altitude. Writes img/fig-38-per-g.png."""
import numpy as np
from _visual import plt, save, despine, MAROON, BLUE, GREEN, INK, AMBER
import _stab as S
from flight import stability as ST, atmosphere
from flight.constants import DEG, FT

XNP = ST.neutral_point(S.WING, S.TAIL)
KAPPA = ST.mass_parameter(S.RHO, S.AREA, S.MAC_M, S.MASS)
XMP = ST.manoeuvre_point(S.WING, S.TAIL, KAPPA)
H = np.linspace(0, 12000, 60)


def per_g(x_cg, speed):
    cw = S.WEIGHT / (0.5 * S.RHO * speed ** 2 * S.AREA)
    return ST.elevator_per_g(cw, KAPPA, S.WING, S.TAIL, x_cg)


def margin(h):
    rho = atmosphere.isa(h)[2]
    return ST.manoeuvre_point(S.WING, S.TAIL, ST.mass_parameter(rho, S.AREA, S.MAC_M, S.MASS)) - XNP


if __name__ == "__main__":
    fig, (a, b) = plt.subplots(1, 2, figsize=(10, 4.3))
    fig.subplots_adjust(wspace=0.32)
    x = np.linspace(0.15, 0.62, 100)
    for V, c in ((130.0, BLUE), (S.SPEED, INK), (230.0, GREEN)):
        a.plot(x, [per_g(v, V) / DEG for v in x], color=c, lw=2.4, label=f"{V:.0f} m/s")
    a.axhline(0, color=INK, lw=0.8); a.axvline(XMP, color=MAROON, lw=1.6, ls="--"); a.axvline(XNP, color=AMBER, lw=1.6, ls=":")
    a.text(XMP + 0.008, -11, "manoeuvre point", rotation=90, fontsize=11, color=MAROON, va="bottom")
    a.text(XNP - 0.035, -11, "neutral point", rotation=90, fontsize=11, color=AMBER, va="bottom")
    a.set_ylim(-12.5, 9); a.set_xlabel("CG position"); a.set_ylabel(r"elevator per g, $d\delta_e/dn$ (°)")
    a.legend(frameon=False, fontsize=11, loc="upper left")
    b.plot(H / 1000, [margin(h) * S.MAC_M * 100 for h in H], color=MAROON, lw=2.8)
    b.set_xlabel("altitude (km)"); b.set_ylabel("$(x_{mp}-x_{np})\\,\\bar c$ (cm)"); b.set_ylim(0, 7)
    despine(a); despine(b)
    save(fig, "fig-38-per-g")
