"""図1: 選択した3個体の、喉・頭頂・尾の実測の反射スペクトル（Dryad）と、表2の寸法で組んだ補正なしの模型。
どちらも最大値で割って形だけを比べる。縦線は実測の山 P（420〜700nm の最大）と模型の山。
    python fig_spectra.py            # ../figs/fig1_spectra.{svg,png}
    python fig_spectra.py --ja       # 日本語の版 fig1_spectra_ja.*
"""
import io, contextlib, sys, numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
with contextlib.redirect_stdout(io.StringIO()):
    import unify_window as U
import table2_model as m
import dryad_emp as D

JA = '--ja' in sys.argv
MOB = '--mobile' in sys.argv   # 記事用: 縦長で文字を大きく（スマホの幅で読めるように）
FS = 1.35 if MOB else 1.0
if JA:
    plt.rcParams['font.family'] = 'Noto Sans CJK JP'
REF = {'branickii': 'FMNH_67693', 'hybrid': 'FMNH_511084', 'gularis': 'FMNH_286879'}
SPN = {'branickii': 'H. branickii', 'hybrid': 'hybrid', 'gularis': 'H. gularis'}
PN = {'gorget': ('Gorget', '喉'), 'crown': ('Crown', '頭頂'), 'tail': ('Tail', '尾')}
INK, MUTED, MODEL = '#1f2328', '#6e7781', '#c2410c'

fig, axes = plt.subplots(3, 3, figsize=((6.0, 7.6) if MOB else (9.2, 7.0)), sharex=True, sharey=True)
for c, sp in enumerate(U.SP):
    for r, p in enumerate(U.P):
        ax = axes[r, c]
        y = D.SPEC[(sp, p, REF[sp])]
        ax.plot(D.wl, y/np.max(y[(D.wl >= 420)]), color=INK, lw=1.6)
        L = m.stack(*m.T2[(sp, p)])
        R = U.R_of([(U.nk if kd == 'k' else (U.nm0 if kd == 'm' else f + (1-f)*U.nm0), th) for kd, th, f in L])
        sel = (U.lams >= 400) & (U.lams <= 1000)
        ax.plot(U.lams[sel], R[sel]/R[sel].max(), color=MODEL, lw=1.6, ls=(0, (4, 2)))
        Pe = D.P_W(y)[0]; Pm = U.defs(R, r)[0]
        ax.axvline(Pe, color=INK, lw=0.8, alpha=0.5); ax.axvline(Pm, color=MODEL, lw=0.8, alpha=0.6)
        ax.axvspan(700, 1000, color='#d0d7de', alpha=0.35, lw=0)
        ax.text(0.98, 0.95, (f'{Pe:.0f}/{Pm:.0f}' if MOB else f'{Pe:.0f} / {Pm:.0f} nm'), transform=ax.transAxes, ha='right', va='top', fontsize=8.5*FS, color=INK, bbox=dict(boxstyle='square,pad=0.15', fc='white', ec='none', alpha=0.7))
        ax.set_xlim(300, 1000); ax.set_ylim(0, 1.08)
        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*FS)
        if MOB: ax.set_xticks([400, 700, 1000]); ax.set_yticks([0, 0.5, 1.0])
        if r == 0: ax.set_title(('雑種' if (JA and sp == 'hybrid') else SPN[sp]), fontsize=10*FS, color=INK, style='italic' if sp != 'hybrid' else 'normal')
        if c == 0: ax.set_ylabel(PN[p][1 if JA else 0] + ('' if MOB else ('\n反射率（最大で割る）' if JA else '\nreflectance (scaled)')), fontsize=9*FS, color=INK, rotation=0 if MOB else 90, labelpad=14 if MOB else 4)
        if r == 2: ax.set_xlabel('波長 (nm)' if JA else 'wavelength (nm)', fontsize=9*FS, color=INK)
h1, = axes[0, 0].plot([], [], color=INK, lw=1.6); h2, = axes[0, 0].plot([], [], color=MODEL, lw=1.6, ls=(0, (4, 2)))
lab = ('実測（Dryad、選択した個体）', '計算（表2の寸法、補正なし）') if JA else ('measured (Dryad, selected individual)', 'model (Table 2 dimensions, uncorrected)')
fig.legend([h1, h2], (('実測', '計算（補正なし）') if (MOB and JA) else lab), loc='upper center', ncol=2, frameon=False, fontsize=9*FS, bbox_to_anchor=(0.5, 1.0))
note = '数字は 実測の山 / 計算の山。灰色の帯は実測の無い波長' if JA else 'numbers: measured peak / model peak. grey band: no measurement'
fig.text(0.5, 0.005, note if not MOB else ('数字は 実測の山 / 計算の山（nm）' if JA else note), ha='center', fontsize=8.5*FS, color=MUTED)
fig.tight_layout(rect=(0, 0.02, 1, 0.95))
out = '../figs/fig1_spectra' + ('_ja' if JA else '') + ('_mobile' if MOB else '')
fig.savefig(out + '.svg'); fig.savefig(out + '.png', dpi=160)
print(out)
