"""図1: 同じ核・同じ双極子の対（FAD4・Trp3）で、天然と 2H+15N の電波の遷移の強さを周波数ごとに並べる。
入力は pair_fast.py を HISTOUT 付きで回した npz（大きいので git に入れない）。出力は 1 MHz ごとの集計表と SVG/PNG。
使い方: python fig_spectrum.py spec_fad4trp3_nat.npz spec_fad4trp3_dn.npz
# no-test: 研究の図を描く使い捨て
"""
import sys
import numpy as np
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt

nat, dn = (np.load(f) for f in sys.argv[1:3])
edges = np.arange(0, 161, 1.0)


def binned(d):
    h, _ = np.histogram(d["fq"], bins=edges, weights=d["it"])
    return h / float(d["N"])          # 1状態あたり、1 MHz ごと


hn, hd = binned(nat), binned(dn)
mid = edges[:-1] + 0.5
np.savetxt("fig_spectrum_bins.csv", np.c_[mid, hn, hd], delimiter=",", fmt="%.6g",
           header="freq_MHz_center,natural_per_state_per_MHz,2H15N_per_state_per_MHz")
for name, h in (("natural", hn), ("2H+15N", hd)):
    print(name, "75–85 MHz:", f"{h[75:85].sum():.4e}", "140–150 MHz:", f"{h[140:150].sum():.4e}")

BLUE, VERM, INK, MUTED = "#0072B2", "#D55E00", "#222222", "#666666"
plt.rcParams.update({"font.size": 10, "axes.edgecolor": MUTED, "axes.labelcolor": INK,
                     "xtick.color": MUTED, "ytick.color": MUTED})
fig, ax = plt.subplots(figsize=(6.4, 3.6), dpi=150)
for lo, hi, lab in ((75, 85, "75–85 MHz\n(disorients)"), (140, 150, "140–150 MHz\n(does not)")):
    ax.axvspan(lo, hi, color="#000000", alpha=0.06, lw=0)
    ax.text((lo + hi) / 2, 2.5e-2, lab, ha="center", va="top", fontsize=8, color=MUTED)
floor = 1e-7
ax.step(mid, np.maximum(hn, floor), where="mid", color=BLUE, lw=1.6)
ax.step(mid, np.maximum(hd, floor), where="mid", color=VERM, lw=1.6)
ax.axvline(float(nat["spanA"]), color=BLUE, lw=0.8, ls=":")
ax.axvline(float(dn["spanA"]), color=VERM, lw=0.8, ls=":")
ax.text(float(nat["spanA"]) - 1, 5e-7, "FAD\u2022\u2212 span,\nnatural (FAD4)", color=INK, fontsize=8, ha="right", va="bottom")
ax.text(float(dn["spanA"]) - 1, 5e-7, "FAD\u2022\u2212 span,\n2H+15N (FAD4)", color=INK, fontsize=8, ha="right", va="bottom")
ax.text(118, 3.5e-4, "natural", color=INK, fontsize=9, fontweight="bold")
ax.text(58, 1.6e-3, "2H+15N", color=INK, fontsize=9, fontweight="bold")
ax.set_yscale("log")
ax.set_ylim(floor * 3, 3e-2)
ax.set_xlim(0, 160)
ax.set_xlabel("transition frequency (MHz)")
ax.set_ylabel("strength per state per MHz")
ax.spines[["top", "right"]].set_visible(False)
ax.grid(axis="y", color="#000000", alpha=0.06, lw=0.5)
fig.tight_layout()
fig.savefig("fig1_spectrum.svg")
fig.savefig("fig1_spectrum.png")
