"""記事の図: 回る楕円の芯の脇の空き。
左: w=0.08、t=100〜300 の 101 枚を各時刻の長軸の向きでそろえて重ねた平均の ω/γ0。破線は Pakter–Levin 2018 の式(12)(14)で、測った芯の形（a=0.430, b=0.347, Z=10.5）から出した「空になる領域」（内側の枝で ψ̃<ε_sep、芯の外）の輪郭。
右: 3つの幅で、短軸の方向（±35°）と長軸の方向（±35°）の ω/γ0 を r/R ごとに平均（radial_sectors.py と同じ）。

    uv run python fig_moat.py ../../../docs/articles/images/shear-final-moat.png
"""
import math, subprocess, sys
import numpy as np
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from matplotlib import font_manager
for _f in ("/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc",):
    try:
        font_manager.fontManager.addfont(_f)
    except OSError:
        pass
plt.rcParams["font.family"] = ["Noto Sans CJK JP", "sans-serif"]
out = sys.argv[1]
NTH = NZ = 64; ZW = 4.0
dth = 2 * math.pi / NTH; dz = 2 * ZW / NZ
TH = (np.arange(NTH) + 0.5) * dth; Zg = -ZW + np.arange(NZ + 1) * dz
j = np.arange(1, NZ)
S = np.sin(math.pi * j[:, None] * j[None, :] / NZ) * math.sqrt(2.0 / NZ)
lam_z = (2 * np.cos(math.pi * j / NZ) - 2) / dz**2
k = np.fft.fftfreq(NTH, d=1.0 / NTH)
lam_t = (2 * np.cos(2 * math.pi * k / NTH) - 2) / dth**2
den = lam_t[:, None] + lam_z[None, :]


def tval(k):
    try:
        return float(k[1:].replace("p", "."))
    except ValueError:
        return None


def frames(fn, w, t0, t1):
    d = np.load(fn + ".npz")
    for t, key in sorted((tval(k), k) for k in d.files if k.startswith("t") and tval(k) is not None and t0 <= tval(k) <= t1):
        th, zz = d[key]; th = th % (2 * math.pi); n = len(th)
        H, _, _ = np.histogram2d(th, zz, bins=[NTH, NZ + 1], range=[[0, 2 * math.pi], [-ZW - dz / 2, ZW + dz / 2]])
        G = H / (H.sum() * dth * dz) * 4 * math.pi
        psi = np.zeros_like(G)
        psi[:, 1:-1] = np.fft.ifft((-(np.fft.fft(G[:, 1:-1], axis=0) @ S) / den) @ S, axis=0).real
        top = psi >= np.quantile(psi, 0.99); wts = np.where(top, psi, 0)
        tc = np.angle((wts * np.exp(1j * TH)[:, None]).sum()) % (2 * math.pi); zc = (wts * Zg[None, :]).sum() / wts.sum()
        x = ((th - tc + math.pi) % (2 * math.pi)) - math.pi; y = zz - zc
        ii = np.clip((th / dth).astype(int), 0, NTH - 1); jj = np.clip(((zz + ZW) / dz + 0.5).astype(int), 0, NZ)
        core = (G[ii, jj] * w > 0.5) & (np.abs(x) < 1.5) & (np.abs(y) < 1.5)
        ev, evec = np.linalg.eigh(np.cov(np.vstack([x[core], y[core]])))
        ang = math.atan2(evec[1, 1], evec[0, 1])
        Rc = math.sqrt(((G * w) > 0.5).sum() * dth * dz / math.pi)
        yield x, y, ang, Rc, n


# 左の図
L = 1.2; NB = 96; acc = np.zeros((NB, NB)); cnt = 0
for x, y, ang, Rc, n in frames("trackf_w008", 0.08, 100, 300):
    c, s = math.cos(-ang), math.sin(-ang)
    h, _, _ = np.histogram2d(c * x - s * y, s * x + c * y, bins=NB, range=[[-L, L], [-L, L]])
    acc += h / (n * (2 * L / NB) ** 2) * 4 * math.pi * 0.08; cnt += 1
acc /= cnt
# 2018 年の模型の ψ̃（pl2018_regions.py と同じ作り方）
a, b, Zc = 0.430, 0.347, 10.51
Lm = 6.0; N = 1024; h = 2 * Lm / N
xm = -Lm + (np.arange(N) + 0.5) * h; X, Y = np.meshgrid(xm, xm, indexing="ij")
wv = np.where((X / a) ** 2 + (Y / b) ** 2 <= 1, Zc, 0.0)
M = 2 * N; kk = (np.arange(M) - M // 2) * h; KX, KY = np.meshgrid(kk, kk, indexing="ij")
Gk = -np.log(np.hypot(KX, KY) + 1e-300) / (2 * math.pi); Gk[M // 2, M // 2] = -(math.log(h / 2) - 1.5) / (2 * math.pi); Gk = np.fft.ifftshift(Gk)
W = np.zeros((M, M)); W[:N, :N] = wv
psi = np.fft.irfft2(np.fft.rfft2(W) * np.fft.rfft2(Gk), s=(M, M))[:N, :N] * h * h
Om = Zc * a * b / (a + b) ** 2; pt = psi + Om * (X**2 + Y**2) / 2; i0 = N // 2
px = pt[i0:, i0]; xs = xm[i0:]; eps_sep = px[np.argmin(px[xs > a]) + np.sum(xs <= a)]
sel = (np.abs(xm) <= L)
fig, ax = plt.subplots(1, 2, figsize=(11.5, 5.0), gridspec_kw={"width_ratios": [1, 1.15]})
im = ax[0].imshow(acc.T, origin="lower", extent=[-L, L, -L, L], cmap="magma", vmin=0, vmax=0.1)
cb = fig.colorbar(im, ax=ax[0], fraction=0.046, pad=0.03); cb.set_label("渦度 / γ0（0.1 で頭打ち）")
gx, gy = np.gradient(pt, h, h)
inner = (X * gx + Y * gy) < 0  # 内側の枝: 外へ行くほど ψ̃ が下がる（各方向の極小より内側）
empty = inner & (pt < eps_sep) & ((X / a) ** 2 + (Y / b) ** 2 > 1)
ax[0].contour(xm[sel], xm[sel], empty[np.ix_(sel, sel)].T.astype(float), levels=[0.5], colors="cyan", linewidths=1.2, linestyles="--")
ax[0].set_title("w=0.08R：芯の向きをそろえた平均（t=100〜300）", fontsize=11)
ax[0].set_xlabel("長軸の向き（円筒の半径 R が単位）"); ax[0].set_ylabel("短軸の向き")
# 右の図
edges = np.arange(0.0, 3.01, 0.1); cen = 0.5 * (edges[1:] + edges[:-1]); hw = math.radians(35)
cols = {"0.08": "#c0392b", "0.13": "#7d3c98", "0.20": "#2471a3"}
for wl, fn, w in (("0.08", "trackf_w008", 0.08), ("0.13", "trackf_w013", 0.13), ("0.20", "trackf_w020", 0.20)):
    cs = {"短": np.zeros(len(cen)), "長": np.zeros(len(cen))}; ar = {"短": np.zeros(len(cen)), "長": np.zeros(len(cen))}
    for x, y, ang, Rc, n in frames(fn, w, 100, 300):
        rr = np.hypot(x, y) / Rc; ph = (np.arctan2(y, x) - ang) % math.pi
        for nm, m in (("長", (ph < hw) | (ph > math.pi - hw)), ("短", np.abs(ph - math.pi / 2) < hw)):
            hh, _ = np.histogram(rr[m], bins=edges); cs[nm] += hh * 4 * math.pi * w / n
            ar[nm] += 2 * hw * (edges[1:] ** 2 - edges[:-1] ** 2) * Rc**2
    ax[1].plot(cen, cs["短"] / ar["短"], "-", color=cols[wl], lw=1.8, label=f"w={wl}R 短軸の向き")
    ax[1].plot(cen, cs["長"] / ar["長"], ":", color=cols[wl], lw=1.4, label=f"w={wl}R 長軸の向き")
ax[1].set_xlim(0.9, 2.6); ax[1].set_ylim(0, 0.14)
ax[1].set_xlabel("芯の中心からの距離 ÷ 芯の等価半径"); ax[1].set_ylabel("渦度 / γ0")
ax[1].set_title("短軸の向きだけに谷ができる", fontsize=11); ax[1].legend(fontsize=8, ncol=2, frameon=False)
fig.tight_layout(); fig.savefig(out, dpi=120)
print(f"→ {out}  ε_sep={eps_sep:.4f}")
