"""Lecture 10, the compressibility correction: calibrated minus equivalent airspeed against the calibrated airspeed,
at five ISA altitudes, from flight.airspeed. It replaces the textbook chart of the old note. Writes img/fig-10-cas-eas.png."""
import numpy as np
from _visual import plt, save, despine, MAROON, BLUE, GREEN, AMBER, PURPLE, INK
from flight import airspeed as AS, atmosphere as A
from flight.constants import KT, RHO0_SL

ALTS = [(0.0, INK), (3000.0, GREEN), (6000.0, BLUE), (9000.0, AMBER), (12000.0, MAROON)]
VC_KT = np.linspace(50.0, 450.0, 161)


def correction_kt(vc_kt, h):
    """CAS - EAS (kt) at geopotential altitude h for a calibrated airspeed vc_kt (kt)."""
    t, p, rho = A.isa(h)
    M = AS.mach_from_impact_ratio(AS.impact_from_cas(vc_kt * KT) / p)
    V = M * A.speed_of_sound(t)
    return vc_kt - AS.eas_from_tas(V, rho) / KT, M


if __name__ == "__main__":
    fig, ax = plt.subplots(figsize=(10, 5.6))
    for h, c in ALTS:
        ys, ms = zip(*[correction_kt(v, h) for v in VC_KT])
        ok = np.array(ms) <= 1.0
        ax.plot(VC_KT[ok], np.array(ys)[ok], color=c, lw=2.3, label=f"{h / 1e3:.0f} km")
    ax.set_xlabel("calibrated airspeed (kt)")
    ax.set_ylabel("CAS $-$ EAS (kt)")
    ax.legend(title="ISA altitude", frameon=False, fontsize=11, title_fontsize=11, loc="upper left")
    ax.text(445, 0.6, "curves end at Mach 1", fontsize=11, ha="right", color=INK)
    despine(ax)
    save(fig, "fig-10-cas-eas")
