"""Lecture 11, the critical Mach number: the pressure coefficient at the lowest-pressure point of a thick and a thin
section, scaled with Mach number by Prandtl-Glauert, meets the sonic value C_p* (flight.gasdynamics). C_p0 = -0.43
for a thicker section, -0.25 for a thinner one. Writes img/fig-11-critical-mach.png."""
import numpy as np
from _visual import plt, save, despine, MAROON, BLUE, GREEN, INK, GREY
from flight import gasdynamics as GD

M = np.linspace(0.3, 0.97, 300)
SECTIONS = [(-0.43, MAROON, "thicker section, $C_{p0}=-0.43$"), (-0.25, GREEN, "thinner section, $C_{p0}=-0.25$")]
LABEL_AT = {-0.43: (0.31, -0.52, "bottom"), -0.25: (0.31, -0.20, "top")}
MCR = {cp0: GD.critical_mach(cp0) for cp0, _, _ in SECTIONS}

if __name__ == "__main__":
    fig, ax = plt.subplots(figsize=(10, 5.6))
    ax.plot(M, GD.cp_star(M), color=INK, lw=2.6)
    ax.text(0.615, -1.5, "$C_p^*$: the local flow\nis exactly sonic", fontsize=13, color=INK)
    for cp0, c, lab in SECTIONS:
        ax.plot(M, GD.prandtl_glauert(cp0, M), color=c, lw=2.4)
        x_, y_, va_ = LABEL_AT[cp0]
        ax.text(x_, y_, lab, fontsize=12, color=c, va=va_)
        mc = MCR[cp0]
        ax.plot(mc, GD.cp_star(mc), "o", color=c, ms=8, zorder=5)
        ax.annotate(f"$M_{{cr}}={mc:.2f}$", (mc, GD.cp_star(mc)), (mc + (-0.09 if cp0 < -0.3 else -0.14), GD.cp_star(mc) + (-0.5 if cp0 < -0.3 else 0.4)),
                    fontsize=13, color=c, arrowprops=dict(arrowstyle="->", color=c))
    ax.set_xlim(0.3, 1.0); ax.set_ylim(0.15, -1.8)
    ax.set_xlabel("free-stream Mach number")
    ax.set_ylabel("pressure coefficient (negative up)")
    despine(ax)
    save(fig, "fig-11-critical-mach")
