"""層一枚ずつの厚さの不ぞろい（表2の 95% 区間＝1個体の中のばらつき）が主な指標をどう動かすか。
各層の厚さを独立に正規分布で揺らし（標準偏差 = (上限−下限)/3.92 × 倍率 k）、反射を多数の実現で平均してから重心を取る
（羽の上の広い範囲を測る実測は、場所ごとに違う積み重ねの反射の平均を見ているとみなす）。
表皮(cortex)は表2の cortex の区間、板の殻と内側のメラニンは melanin の区間、板の中の空気は air の区間、板の間のケラチンは keratin spacing の区間。
上の板の厚さ(top mel.)の区間で上の板の中の空気を揺らす。"""
import io, math, contextlib, numpy as np
import table2_model as m
from residual_map import EMP as EMP_MAX
with contextlib.redirect_stdout(io.StringIO()):
    import read_fig4_centroid as C
EMP_CEN = {k: v[1] for k, v in C.res.items()}
EMP_MIX = {k: (EMP_MAX[k] if v[3] else v[1]) for k, v in C.res.items()}
lams = np.arange(300, 1301, 2.0)
def refl_fast(layers):
    L = lams; nk = m.n_ker(L); nm = m.n_mel(L)
    a, b, c, d = (np.ones_like(L, complex), np.zeros_like(L, complex), np.zeros_like(L, complex), np.ones_like(L, complex))
    for kind, th, fa in layers:
        n = nk if kind == 'k' else (nm if kind == 'm' else fa*1 + (1-fa)*nm)
        dl = 2*np.pi*n*th/L; cs, sn = np.cos(dl), np.sin(dl)
        e, f, g, h = cs, 1j*sn/n, 1j*n*sn, cs
        a, b, c, d = a*e + b*g, a*f + b*h, c*e + d*g, c*f + d*h
    B = a + b*nk; C_ = c + d*nk
    return np.abs((B - C_)/(B + C_))**2
assert np.allclose(refl_fast(m.stack(*m.T2[('hybrid', 'gorget')])), m.refl(lams, m.stack(*m.T2[('hybrid', 'gorget')])))
def cen_vis(R):
    win = (lams >= 400) & (lams <= 800)
    i = int(np.flatnonzero(win)[np.argmax(R[win])]); h = R[i]/2; a = b = i
    while a > 0 and R[a-1] > h: a -= 1
    while b < len(R)-1 and R[b+1] > h: b += 1
    w = R[a:b+1]; return float((lams[a:b+1]*w).sum()/w.sum())
# 表2の 95% 区間（下限, 上限）: air, cortex, ker, mel, top
CI = {
 ('branickii','crown'): ((64,111),(106,153),(15,36),(28,46),(67,107)), ('hybrid','crown'): ((78,115),(95,126),(23,45),(34,53),(72,113)), ('gularis','crown'): ((76,126),(124,168),(24,44),(32,46),(100,152)),
 ('branickii','gorget'): ((93,151),(157,192),(25,66),(41,65),(141,190)), ('hybrid','gorget'): ((116,179),(111,164),(19,65),(39,61),(167,224)), ('gularis','gorget'): ((65,133),(129,199),(20,47),(40,60),(128,206)),
 ('branickii','tail'): ((67,112),(45,87),(6,37),(32,48),(132,207)), ('hybrid','tail'): ((65,110),(30,78),(12,22),(36,58),(147,197)), ('gularis','tail'): ((50,102),(31,77),(19,54),(43,68),(186,229)),
}
def disordered(sp, p, k, rng):
    air, cor, ker, lay, mel, ptt = m.T2[(sp, p)]
    sd = {n: (hi - lo)/3.92*k for n, (lo, hi) in zip(('air', 'cor', 'ker', 'mel', 'top'), CI[(sp, p)])}
    g = lambda mu, s: max(1.0, mu + s*rng.standard_normal())
    L = [('k', g(cor, sd['cor']), 0)]
    top = g(ptt, sd['top']); ms = min(g(mel, sd['mel']), top/2); inner = max(top - 2*ms, 0)
    L += [('m', ms, 0), ('a', inner, 0.8), ('m', ms, 0), ('k', g(ker, sd['ker']), 0)]
    for i in range(lay - 1):
        L += [('m', g(mel, sd['mel']), 0), ('a', g(air, sd['air']), 0.8), ('m', g(mel, sd['mel']), 0)]
        if i < lay - 2: L += [('k', g(ker, sd['ker']), 0)]
    return L
SP = ('branickii', 'hybrid', 'gularis'); P = ('gorget', 'crown', 'tail'); NR = 400
rng = np.random.default_rng(11)
for k in (0.0, 0.5, 1.0):
    cen = {}
    for sp in SP:
        for p in P:
            if k == 0: R = refl_fast(m.stack(*m.T2[(sp, p)]))
            else: R = np.mean([refl_fast(disordered(sp, p, k, rng)) for _ in range(NR)], axis=0)
            cen[(sp, p)] = cen_vis(R)
    line = f'倍率 k={k:.1f}  模型の重心 ' + ' '.join(f'{sp[:4]}{p[0]}={cen[(sp,p)]:.0f}' for sp in SP for p in P)
    print(line)
    for lab, emp in (('実測 最高点', EMP_MAX), ('実測 重心  ', EMP_CEN), ('切れだけ最高点', EMP_MIX)):
        out = []
        for sp in SP:
            q = {p: cen[(sp, p)]/emp[(sp, p)] for p in P}; out.append(q['gorget']/math.sqrt(q['crown']*q['tail']))
        print(f'   {lab}: ' + ' / '.join(f'{x:.3f}' for x in out), flush=True)
