"""部位ごとに、寸法の一律倍率 s と空気の割合 fa を振り、山の位置と幅の割合の両方が実測に合う点を探す。実測は種の平均（EMP_SOURCE=dryad_mean）。"""
import numpy as np
import unify_window as U, dryad_emp as D
def fw(x,y):
    i=int(np.argmax(y)); h=y[i]/2; l=i
    while l>0 and y[l]>h: l-=1
    r=i
    while r<len(y)-1 and y[r]>h: r+=1
    return x[i], x[r]-x[l], (l==0 or r==len(y)-1)
mm=(U.lams>=400)&(U.lams<=900)
def model(sp,p,s,fa):
    air,cortex,ker,layers,mel,pttop=U.m.T2[(sp,p)]
    L=U.m.stack(air*s,cortex*s,ker*s,int(layers),mel*s,pttop*s,fa=fa,fa_top=fa)
    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])
    return fw(U.lams[mm],R[mm])
S=np.arange(0.70,1.21,0.05); FA=np.arange(0.35,0.96,0.05)
for sp in U.SP:
    for p in ('gorget','crown'):
        y=np.mean([v for k,v in D.SPEC.items() if k[0]==sp and k[1]==p],axis=0); e=(D.wl>=400)&(D.wl<=700)
        pe,we,cut=fw(D.wl[e],y[e])
        if cut: print(sp,p,'実測の半値が端にかかるので幅は使えない'); continue
        best=None
        for s in S:
            for fa in FA:
                pm,wm,c=model(sp,p,s,fa)
                if c: continue
                cost=(pm/pe-1)**2+((wm/pm)/(we/pe)-1)**2
                if best is None or cost<best[0]: best=(cost,s,fa,pm,wm/pm)
        print(f'{sp:9s}{p:7s} 実測 山{pe:.0f} 割合{we/pe:.2f} → 最良 s={best[1]:.2f} fa={best[2]:.2f} 山{best[3]:.0f} 割合{best[4]:.2f} 誤差{best[0]**.5:.3f}')
