"""図4 d–f（実測スペクトル）と a–c（模型）から、色ごとに曲線の画素を拾い、山の波長を読む。
x の目盛り: 実測の曲線は 300〜700nm に描かれているので、曲線の左端=300、右端=700 として合わせる（パネルごと）。
色: 緑 branickii、橙 雑種、紫 gularis。"""
import numpy as np
from PIL import Image
im = np.asarray(Image.open('../src/rsos221603f04.jpg').convert('RGB')).astype(int)
H, W, _ = im.shape
def mask(p, kind):
    r, g, b = p[..., 0], p[..., 1], p[..., 2]
    if kind == 'green':  return (g > r + 50) & (g > b + 10)
    if kind == 'orange': return (r > g + 50) & (g > b + 10)
    if kind == 'purple': return (b > r + 25) & (b > g + 25) & (abs(r - g) < 30)
cols = [(0.07, 0.36), (0.39, 0.68), (0.71, 1.0)]
for (name, y0, y1) in (('実測', 0.52, 0.93),):
    for k, (x0, x1) in zip('def', cols):
        p = im[int(H*y0):int(H*y1), int(W*x0):int(W*x1)]
        allm = mask(p, 'green') | mask(p, 'orange') | mask(p, 'purple')
        xs = np.nonzero(allm.any(axis=0))[0]
        xa, xb = xs.min(), xs.max()
        nm = lambda x: 300 + (x - xa) * 400 / (xb - xa)
        out = []
        for c, lab in (('green', 'branickii'), ('orange', '雑種'), ('purple', 'gularis')):
            m = mask(p, c)
            top = np.full(p.shape[1], 10**6)
            for x in range(p.shape[1]):
                ys = np.nonzero(m[:, x])[0]
                if len(ys): top[x] = ys.min()
            # 400nm より長い側で一番高い点（短波長端の立ち上がりを除く）
            valid = [x for x in range(p.shape[1]) if top[x] < 10**6 and nm(x) > 420]
            xbest = min(valid, key=lambda x: top[x])
            out.append(f'{lab} {nm(xbest):.0f}')
        print(f'{name} {k}（{"頭頂" if k=="d" else "喉" if k=="e" else "尾"}）: ' + '  '.join(out) + f'   (目盛り {xb-xa}px/400nm)')

# 模型（上の段 a–c）: 曲線は 300〜1000nm。色ごとに複数の曲線があるので、各列で一番上の点を取り、
# 400nm より長い側の最大を「その色の最も高い山」とする（個々の曲線の山の平均ではない点に注意）
for k, (x0, x1) in zip('abc', cols):
    p = im[int(H*0.03):int(H*0.47), int(W*x0):int(W*x1)]
    allm = mask(p, 'green') | mask(p, 'orange') | mask(p, 'purple')
    xs = np.nonzero(allm.any(axis=0))[0]
    xa, xb = xs.min(), xs.max()
    nm = lambda x: 300 + (x - xa) * 700 / (xb - xa)
    out = []
    for c, lab in (('green', 'branickii'), ('orange', '雑種'), ('purple', 'gularis')):
        m = mask(p, c)
        top = np.full(p.shape[1], 10**6)
        for x in range(p.shape[1]):
            ys = np.nonzero(m[:, x])[0]
            if len(ys): top[x] = ys.min()
        valid = [x for x in range(p.shape[1]) if top[x] < 10**6 and nm(x) > (480 if k == 'a' else 450)]
        xbest = min(valid, key=lambda x: top[x])
        out.append(f'{lab} {nm(xbest):.0f}')
    print(f'模型 {k}（{"頭頂" if k=="a" else "喉" if k=="b" else "尾"}）: ' + '  '.join(out) + f'   (目盛り {xb-xa}px/700nm)')
