"""Lecture 39: along the half-span of a rectangular wing, the lift change of each strip from dihedral in a sideslip (the
same for every strip), the rolling moment of each strip (grows with y), and the running total from the root
(flight.lateral strip results). Writes img/fig-39-strip-roll.png."""
import numpy as np
from _visual import plt, save, despine, MAROON, BLUE, GREEN, AMBER, INK, GREY
from flight import lateral as L

ETA = np.linspace(0, 1, 401)                    # y / (b/2)
AIL = (0.6, 0.95)                               # an illustrative aileron span


def moment_fraction(e0, e1):
    """Share of the whole dihedral rolling moment made between e0 and e1 of the half-span (the moment of equal strips
    is proportional to y)."""
    whole = L.aileron_cl_rectangular(1.0, 1.0, 1.0, 0.0, 1.0, 2.0, 2.0)
    return float(L.aileron_cl_rectangular(1.0, 1.0, 1.0, e0, e1, 2.0, 2.0) / whole)


if __name__ == "__main__":
    fig, (a, b) = plt.subplots(2, 1, figsize=(10, 5.8), sharex=True, gridspec_kw=dict(hspace=0.12))
    a.plot(ETA, np.ones_like(ETA), color=BLUE, lw=2.8, label="lift change of a strip: the same everywhere")
    a.plot(ETA, ETA, color=MAROON, lw=2.8, label="its rolling moment: grows with distance")
    a.set_ylim(0, 2.2); a.set_ylabel("each strip\n(relative)"); a.legend(frameon=False, fontsize=11.5, loc="upper left")
    b.plot(ETA, [moment_fraction(0, e) if e > 0 else 0.0 for e in ETA], color=INK, lw=2.8)
    b.set_ylim(0, 1.08); b.set_ylabel("share of the moment\nfrom the root out to here")
    for ax in (a, b):
        ax.axvspan(0.7, 1.0, color=AMBER, alpha=0.18, zorder=0); despine(ax)
    a.text(0.85, 1.65, f"outer 30 % of the span:\n{100 * moment_fraction(0.7, 1.0):.0f} % of the moment", ha="center", fontsize=12)
    for ax in (b,):
        ax.plot(AIL, [0.06, 0.06], color=GREEN, lw=7, solid_capstyle="butt")
        ax.text(sum(AIL) / 2, 0.14, "a typical outboard aileron position", ha="center", fontsize=11, color=GREEN)
    b.set_xlim(0, 1); b.set_xlabel("distance from the centre line, as a fraction of the half-span")
    save(fig, "fig-39-strip-roll")
