"""Lecture 38: the pitch rate an aircraft needs against load factor, in a pull-up and in a level turn, in units of
g/V; and the elevator angle of Hull's business jet (CG 0.30, 30,000 ft, 182 m/s) in each. Writes
img/fig-38-turn-rate.png."""
import numpy as np
from _visual import plt, save, despine, MAROON, BLUE, INK
import _stab as S
from flight import stability as ST
from flight.constants import DEG, G0

N = np.linspace(1.0, 3.0, 100)
CW = S.WEIGHT / (0.5 * S.RHO * S.SPEED ** 2 * S.AREA)


def elevator(n, rate_function, speed=S.SPEED):
    cw = S.WEIGHT / (0.5 * S.RHO * speed ** 2 * S.AREA)
    qhat = ST.nondimensional_rate(rate_function(n, speed, G0), S.MAC_M, speed)
    return ST.manoeuvre_trim(n, cw, qhat, S.WING, S.TAIL, S.XCG, S.THRUST)[1]


if __name__ == "__main__":
    fig, (a, b) = plt.subplots(1, 2, figsize=(10, 4.2))
    fig.subplots_adjust(wspace=0.3)
    for fn, c, lab in ((ST.pull_up_rate, BLUE, "pull-up, $n-1$"), (ST.level_turn_pitch_rate, MAROON, "level turn, $n-1/n$")):
        a.plot(N, [fn(n, 1.0, 1.0) for n in N], color=c, lw=2.6, label=lab)
        b.plot(N, [elevator(n, fn) / DEG for n in N], color=c, lw=2.6, label=lab.split(",")[0])
    a.set_ylabel("pitch rate $qV/g$"); b.set_ylabel(r"elevator $\delta_e$ (°)")
    for ax in (a, b):
        ax.set_xlabel("load factor $n$"); ax.legend(frameon=False, fontsize=11); despine(ax)
    b.axhline(0, color=INK, lw=0.8)
    save(fig, "fig-38-turn-rate")
