"""記事の図3枚。出力: docs/articles/images/shear-final-*.png

    cd ayumu-lab/research/euler-final-state && uv run python figs.py
"""
import glob
import math

import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import font_manager as fm

fp = glob.glob('/usr/share/fonts/**/NotoSansCJK*Regular*', recursive=True) + \
    glob.glob('/usr/share/fonts/**/NotoSerifCJK*Regular*', recursive=True)
fm.fontManager.addfont(fp[0])
plt.rcParams.update({'font.family': fm.FontProperties(fname=fp[0]).get_name(),
                     'figure.facecolor': '#0a0a0a', 'axes.facecolor': '#0a0a0a', 'savefig.facecolor': '#0a0a0a',
                     'text.color': '#ddd', 'axes.labelcolor': '#ddd', 'xtick.color': '#aaa',
                     'ytick.color': '#aaa', 'axes.edgecolor': '#555'})
OUT = '../../../docs/articles/images/'
TAGS = [("w008", 0.08, 5), ("w013", 0.13, 3), ("w02", 0.2, 2)]
GOLD, BLUE, RED = '#d4a937', '#6fa8dc', '#e06666'


from coremeas import disk, disk_field, disk_split


def core_vorticity(th, z, w):
    return disk(th, z, w, 0.1)


# 図1: w=0.08 の時間変化
md = np.load("run_w008.npz")
ts = [0, 18, 48, 900]
fig, axs = plt.subplots(len(ts), 1, figsize=(7, 8.4), sharex=True)
for ax, t in zip(axs, ts):
    th, z = md[f"t{t}"]
    ax.scatter((th + math.pi) % (2 * math.pi) - math.pi, z, s=0.15, c=GOLD, alpha=0.35, lw=0)
    ax.set_ylim(-2.5, 2.5); ax.set_xlim(-math.pi, math.pi)
    ax.text(0.01, 0.85, f"t = {t}", transform=ax.transAxes, fontsize=11)
    ax.set_ylabel("z / R")
axs[-1].set_xlabel("θ（円筒を一周する向き）")
plt.tight_layout(); plt.savefig(OUT + "shear-final-snapshots.png", dpi=110); plt.close()

# 図2: n(z)
fig, axs = plt.subplots(1, 3, figsize=(12, 4.3), sharey=True)
for ax, (tag, w, n) in zip(axs, TAGS):
    md = np.load(f"run_{tag}.npz"); e = md["edges"]; zc = 0.5 * (e[1:] + e[:-1])
    ax.plot(zc, md["nz"], ".", color='#ddd', ms=3, label="シミュレーション（渦50万本）")
    for k, col, lab, ls in (("ch", RED, "コアハロー（論文の理論）", "-"), ("mrs", BLUE, "最大エントロピー（MRS）", "--")):
        d = np.load(f"{k}_{tag}.npz")
        ax.plot(d["Z"], d["nz"], ls, color=col, lw=1.6, label=lab)
    ax.set_xlim(-3, 3); ax.set_title(f"層の半幅 w = {w}R（最初の渦 {n} 個）", fontsize=11)
    ax.set_xlabel("z / R")
axs[0].set_ylabel("その高さにある渦の割合 n(z)")
h, l = axs[0].get_legend_handles_labels()
fig.legend(h, l, loc="lower center", ncol=3, fontsize=9, frameon=False)
plt.tight_layout(rect=(0, 0.07, 1, 1)); plt.savefig(OUT + "shear-final-profiles.png", dpi=110); plt.close()

# 図3: 芯の渦度の時間変化
fig, ax = plt.subplots(figsize=(7, 4))
cols = [GOLD, '#93c47d', '#c27ba0']
for (tag, w, n), col in zip(TAGS, cols):
    md = np.load(f"run_{tag}.npz")
    times = sorted(int(k[1:]) for k in md.files if k.startswith("t") and k[1:].isdigit())
    v = [disk_split(*md[f"t{t}"], w, 0.1, n=100) for t in times]
    ax.errorbar(times, [a for a, _ in v], yerr=[s for _, s in v], fmt="o-", color=col, ms=4, capsize=2,
                lw=1.2, label=f"w = {w}R")
    m = np.load(f"mrs_{tag}.npz")
    ax.axhline(disk_field(m["G"], m["Z"], w, 0.1, m["psi"]), color=col, ls=":", lw=1)
ax.axhline(1.0, color=RED, lw=1)
ax.text(450, 1.22, "実線 1.0 がコアハローの予言", color=RED, ha="center", fontsize=9)
ax.set_xlabel("時刻 t（単位 R/u0）"); ax.set_ylabel("芯の渦度 / 最初の渦度")
ax.set_ylim(0, 1.35); ax.legend(fontsize=9, frameon=False)
ax.set_title("芯（半径0.1Rの円）の平均。中心を決める点と測る点を分けた100回の平均±標準偏差。点線は MRS の予言", fontsize=9)
plt.tight_layout(); plt.savefig(OUT + "shear-final-core.png", dpi=110); plt.close()
print("ok")
