"""SI 図S1（Eliason 2023、TEM 9枚、目盛り 500nm）から板の周期を測る。
各パネルで白い目盛りの横の長さ（px）を探し、縦方向の明るさの断面を横に平均して自己相関の最初の山から周期（px）を出す。"""
import numpy as np
from PIL import Image
im = np.asarray(Image.open('../src/si_figS1_0.png').convert('L')).astype(float)
H, W = im.shape
# パネルの境目（白い隙間）を探す
colw = (im > 250).mean(axis=0) > 0.97; roww = (im > 250).mean(axis=1) > 0.97
def spans(mask):
    out=[]; i=0
    while i < len(mask):
        if not mask[i]:
            j=i
            while j < len(mask) and not mask[j]: j+=1
            if j-i > 100: out.append((i,j))
            i=j
        else: i+=1
    return out
cols, rows = spans(colw), spans(roww)
names = 'ABCDEFGHI'; label = {'A':'喉 branickii','B':'喉 雑種','C':'喉 gularis','D':'頭頂 branickii','E':'頭頂 雑種','F':'頭頂 gularis','G':'尾 branickii','H':'尾 雑種','I':'尾 gularis'}
k=0
for (r0,r1) in rows:
    for (c0,c1) in cols:
        p = im[r0:r1, c0:c1]; h,w = p.shape
        # 目盛り: 下の 25% にある、ほぼ白(>245)の横長の塊。行ごとの最長の白の連続
        best=0
        for y in range(int(h*0.75), h):
            run=m=0
            for v in p[y]:
                run = run+1 if v>245 else 0; m=max(m,run)
            best=max(best,m)
        # 周期: 目盛りの上側（下の 25% と上の 15% を除く）の縦断面
        sub = p[int(h*0.15):int(h*0.72), :]
        prof = sub.mean(axis=1); prof = prof - prof.mean()
        ac = np.correlate(prof, prof, 'full')[len(prof)-1:]; ac /= ac[0]
        # 最初の谷の後の最初の山
        i=1
        while i < len(ac)-1 and not (ac[i] < ac[i-1] and ac[i] <= ac[i+1]): i+=1
        j=i
        while j < len(ac)-1 and not (ac[j] > ac[j-1] and ac[j] >= ac[j+1]): j+=1
        nmpp = 500/best
        print(f'{names[k]} {label[names[k]]:14s} 目盛り {best:3d}px  周期 {j:3d}px = {j*nmpp:5.0f} nm  (自己相関の山 {ac[j]:.2f})')
        k+=1
