"""Lecture 37: stick force of Hull's business jet per unit G S_E c_E at the CG 0.30, for three trim-tab settings that
give zero force at 120, 150 and 182 m/s (the data and function of fig-37-stick-force.py), with the slope at each trim
speed. Writes img/fig-37-trim-tab.png."""
import numpy as np
from _visual import plt, save, despine, MAROON, BLUE, GREEN, INK, GREY
from _scripts import load

F = load("fig-37-stick-force")
XCG = 0.30
TRIMS = [(120.0, BLUE), (150.0, GREEN), (182.0, MAROON)]
V = np.linspace(0.0, 220.0, 300)[1:]


def zero_speed_force(vt):
    return float(F.force(XCG, 1e-6, vt))


def slope(vt, h=0.01):
    return float((F.force(XCG, vt + h, vt) - F.force(XCG, vt - h, vt)) / (2 * h))


if __name__ == "__main__":
    fig, ax = plt.subplots(figsize=(10, 5.0))
    for vt, c in TRIMS:
        ax.plot(V, F.force(XCG, V, vt), color=c, lw=2.6, label=f"tab set to trim at {vt:.0f} m/s: slope there {slope(vt):.2f} Pa per m/s")
        vv = np.array([vt - 22, vt + 22]); ax.plot(vv, slope(vt) * (vv - vt), color=INK, lw=1.2, ls="--")
        ax.plot(vt, 0, "o", color=c, ms=9, zorder=5)
    ax.plot(0, zero_speed_force(150.0), "o", color=INK, ms=8, clip_on=False)
    ax.annotate("one value at zero speed", (0, zero_speed_force(150.0)), xytext=(12, 6), textcoords="offset points", fontsize=11.5)
    ax.axhline(0, color=INK, lw=0.9); ax.set_xlim(0, 220)
    ax.set_xlabel("true airspeed (m/s)"); ax.set_ylabel("$F_s/(G\\,S_E\\,\\bar c_E)$ (Pa), pull $+$")
    fig.legend(frameon=False, fontsize=11.5, loc="upper center", bbox_to_anchor=(0.5, 0.0))
    despine(ax)
    save(fig, "fig-37-trim-tab")
