#!/usr/bin/env python3
"""出图：零模型分布 vs 实测复制数；以及复制基因的两队列效应方向。英文标签（无中文字体）。"""
import json
import matplotlib; matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np

r = json.load(open("results.json"))
null = np.array(r["null_distribution"]); obs = r["n_replicated"]
fig, ax = plt.subplots(1, 2, figsize=(12, 5))

ax[0].hist(null, bins=np.arange(0, max(null.max(), obs) + 2) - 0.5,
           color="#95a5a6", edgecolor="white")
ax[0].axvline(obs, color="#c0392b", lw=2.5)
ax[0].text(obs, ax[0].get_ylim()[1]*0.6, f"  observed = {obs}", color="#c0392b", fontsize=11)
ax[0].set_xlabel("genes replicating (direction + FDR<0.10)")
ax[0].set_ylabel("permutations")
ax[0].set_title(f"Label-permutation null (n={len(null)}):\n"
                f"{(null==0).sum()}/{len(null)} give zero, none reach {obs}")

det = r["replicated"]
xa = [d["tcga_delta"] for d in det]; xb = [d["beataml_delta"] for d in det]
ax[1].axhline(0, c="k", lw=0.8); ax[1].axvline(0, c="k", lw=0.8)
ax[1].scatter(xa, xb, s=45, color="#2c6fbb", zorder=3)
for d in sorted(det, key=lambda x: -abs(x["beataml_delta"]))[:6]:
    ax[1].annotate(d["gene"], (d["tcga_delta"], d["beataml_delta"]),
                   fontsize=8, xytext=(4, 3), textcoords="offset points")
ax[1].set_xlabel("TCGA-LAML  median(resistant) - median(sensitive)")
ax[1].set_ylabel("BeatAML  median(refractory) - median(CR)")
ax[1].set_title("All replicated genes fall in the same-sign quadrants")
ax[1].grid(alpha=0.3)
plt.tight_layout(); plt.savefig("figs/replication.png", dpi=150)
print("figs/replication.png 已生成")
