"""Lecture 36, the neutral point as the point where the extra lift of a disturbance acts. For Hull's business jet
(positions in chords aft of the leading edge of the mean chord): the wing-body's extra lift a_w d(alpha) at x_ac = 0.258
and the tail's a_t d(alpha) at x_ac,H = 2.93, arrow lengths in the ratio a_w : a_t, and their resultant
(a_w + a_t) d(alpha) at x_np, with the centre of gravity at 0.30 ahead of it and an unstable one at 0.80 behind it.
Writes img/fig-36-np-balance.png."""
import numpy as np
from matplotlib.patches import Ellipse
from _visual import plt, save, MAROON, BLUE, GREEN, INK, GREY, AMBER

AW, AH, EA, ETA, SH = 4.67, 4.03, 0.42, 0.9, 54 / 232
AT = AH * (1 - EA) * ETA * SH
X_AC, X_H = 0.258, 2.93
X_NP = (AW * X_AC + AT * X_H) / (AW + AT)
KW = dict(arrowstyle="-|>", lw=2.8, mutation_scale=18)

if __name__ == "__main__":
    fig, (a, b) = plt.subplots(2, 1, figsize=(10.5, 7.2), gridspec_kw=dict(hspace=0.12))
    SC = 1.0 / (AW + AT)                                    # arrow heights: the sum is 1 unit
    for ax in (a, b):
        ax.plot([0.0, 3.2], [0, 0], color=GREY, lw=6, solid_capstyle="round", zorder=1)
        ax.set_xlim(-0.75, 3.55); ax.set_ylim(-0.75, 1.3); ax.axis("off")
        for x in np.arange(0.0, 3.01, 0.5):
            ax.plot([x, x], [-0.04, 0.04], color=INK, lw=1, zorder=2)
            ax.text(x, -0.09, f"{x:g}", ha="center", va="top", fontsize=10, color=GREY)
    a.text(-0.7, 1.2, "the two extra lifts of a disturbance", fontsize=12.5, va="top")
    for x, k, c, lab, ha, dx in ((X_AC, AW, BLUE, "wing-body, $a_w\\Delta\\alpha$\nat 0.258", "left", 0.06),
                                 (X_H, AT, GREEN, "tail, $a_t\\Delta\\alpha$\nat 2.93", "center", 0.0)):
        a.annotate("", xy=(x, k * SC + 0.02), xytext=(x, 0.02), arrowprops=dict(color=c, **KW), zorder=4)
        a.text(x + dx, k * SC + (0.0 if ha == "left" else 0.07), lab, ha=ha, va="top" if ha == "left" else "bottom", fontsize=12, color=c)
    b.text(-0.7, 1.28, "their sum, acting at the neutral point", fontsize=12.5, va="top")
    b.annotate("", xy=(X_NP, 1.02), xytext=(X_NP, 0.02), arrowprops=dict(color=MAROON, **KW), zorder=4)
    b.text(X_NP + 0.07, 0.98, f"$(a_w+a_t)\\Delta\\alpha$\nat $x_{{np}}$ = {X_NP:.3f}", ha="left", va="top", fontsize=12.5, color=MAROON)
    for x, c, lab, tx in ((0.30, INK, "CG at 0.30, ahead of $x_{np}$:\nthe sum turns the nose down. Stable.", 0.0),
                          (0.80, AMBER, "CG at 0.80, behind $x_{np}$:\nthe sum turns the nose up. Unstable.", 2.45)):
        b.add_patch(Ellipse((x, 0), 0.07, 0.09, facecolor=c, edgecolor=INK, zorder=6))
        b.annotate(lab, xy=(x, -0.04), xytext=(tx, -0.35), fontsize=11.5, color=c, ha="center", va="top",
                   arrowprops=dict(arrowstyle="->", color=c))
    a.text(-0.12, 0.0, "nose", fontsize=11, color=GREY, ha="right", va="center")
    save(fig, "fig-36-np-balance")
