"""Lecture 36: the neutral point of Hull's business jet against the horizontal-tail area (as a fraction of the wing
area), the tail's position and shape unchanged, with the design centre of gravity. Writes img/fig-36-tail-size.png."""
import numpy as np
from scipy.optimize import brentq
from _visual import plt, save, despine, MAROON, BLUE, INK, GREY
import _stab as S
from flight import stability as ST

AREA = np.linspace(0.0, 0.35, 200)
NP = np.array([ST.neutral_point(S.WING, S.tail_with_area(a)) for a in AREA])
A_NEUTRAL = brentq(lambda a: ST.neutral_point(S.WING, S.tail_with_area(a)) - S.XCG, 0.0, 0.3)

if __name__ == "__main__":
    fig, ax = plt.subplots(figsize=(10, 4.4))
    ax.plot(AREA, NP, color=BLUE, lw=2.8, label="neutral point")
    ax.axhline(S.XCG, color=INK, lw=1.2, ls="--", label="design CG, 0.30")
    ax.fill_between(AREA, S.XCG, NP, where=NP >= S.XCG, color=BLUE, alpha=0.12, label="static margin")
    ax.plot(S.TAIL.area_ratio, ST.neutral_point(S.WING, S.TAIL), "o", color=MAROON, ms=10)
    ax.annotate("the aircraft as built", (S.TAIL.area_ratio, ST.neutral_point(S.WING, S.TAIL)), textcoords="offset points",
                xytext=(-12, 10), ha="right", fontsize=11, color=MAROON)
    ax.set_xlabel("horizontal-tail area / wing area"); ax.set_ylabel("position (fraction of the mean chord)")
    ax.set_xlim(0, 0.35); ax.set_ylim(0.2, 0.65)
    ax.legend(frameon=False, fontsize=11, loc="upper left")
    despine(ax)
    save(fig, "fig-36-tail-size")
