"""図2: 表1の割合（100試行のうち、3個体中2個体以上が線 1.024 以下と確かめられた試行の数）を、実測の種類ごとに並べる。
数は unify_joint の出力の写し（../unify_joint_dryad_{ref,mean,boot}_{strict,crown}_sd*_20261124.txt）から読む。
    python fig_fractions.py [--ja]   # ../figs/fig2_fractions{_ja}.{svg,png}
"""
import re, sys
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

JA = '--ja' in sys.argv
MOB = '--mobile' in sys.argv   # 記事用: 縦に3枚並べる
if JA: plt.rcParams['font.family'] = 'Noto Sans CJK JP'
SDS = (0.02, 0.05, 0.07)
def count(src, kind, sd):
    t = open(f'../unify_joint_dryad_{src}_{kind}_sd{sd}_20261124.txt').read()
    return int(re.findall(r'100試行.*?2羽以上 (\d+)件', t)[-1])
SRC = (('ref', 'selected individuals', '選択した個体'), ('mean', 'species mean', '種の平均'), ('boot', 'resampled individuals', '個体の再標本化'))
KIND = (('crown', 'crown only', '頭頂だけ', '#1d4ed8'), ('strict', 'crown–tail\n(edge tails undecided)', '頭頂と尾\n（端の尾は保留）', '#c2410c'))
INK, MUTED = '#1f2328', '#6e7781'
fig, axes = plt.subplots(3, 1, figsize=(5.4, 8.6), sharex=True) if MOB else plt.subplots(1, 3, figsize=(9.2, 3.4), sharey=True)
for ax, (src, en, ja) in zip(axes, SRC):
    for kind, ken, kja, col in KIND:
        y = [count(src, kind, sd) for sd in SDS]
        x = [100*s for s in SDS]
        ax.plot(x, y, color=col, lw=2, marker='o', ms=6)
        for xi, yi in zip(x, y):
            ax.annotate(f'{yi}', (xi, yi), textcoords='offset points', xytext=(0, 7), ha='center', fontsize=8.5, color=INK)
        if src == 'ref':
            ax.annotate(kja if JA else ken, (x[-1], y[-1]), textcoords='offset points', xytext=(-22, -26 if kind == 'crown' else 16),
                        ha='right', fontsize=8.5, color=col)
    ax.set_title(ja if JA else en, fontsize=12 if MOB else 10, color=INK)
    ax.set_xticks([2, 5, 7]); ax.set_xlim(1, 8); ax.set_ylim(-5, 110)
    if not MOB or ax is axes[-1]: ax.set_xlabel('寸法の誤差 σ (%)' if JA else 'dimension error σ (%)', fontsize=11 if MOB else 9, color=INK)
    if MOB: ax.set_ylabel('条件を満たした試行 (%)' if JA else 'draws meeting the condition (%)', fontsize=10, color=INK)
    ax.spines[['top', 'right']].set_visible(False)
    for s in ('left', 'bottom'): ax.spines[s].set_color(MUTED)
    ax.tick_params(colors=MUTED, labelsize=8.5)
    ax.grid(axis='y', color='#d0d7de', lw=0.6)
if not MOB: axes[0].set_ylabel('条件を満たした試行 (%)' if JA else 'draws meeting the condition (%)', fontsize=9, color=INK)
fig.tight_layout()
out = '../figs/fig2_fractions' + ('_ja' if JA else '') + ('_mobile' if MOB else '')
fig.savefig(out + '.svg'); fig.savefig(out + '.png', dpi=160)
print(out)
