"""体積分率の型 I・II・III で、メラノソームの層の屈折率の混ぜ方を Stavenga ほか 2018（カササギ、FDTD と多層膜模型の比較）の
一般化平均 n_eff = (fk nk^w + fm nm^w + fa na^w)^(1/w) に替える。w=1 が今までの線形の混ぜ方。
偏光なしは TE（w=-0.5）と TM（w=2.5）の反射率の平均（Stavenga 2018 が FDTD に合わせた値）。つまみは元の値（補正なし）。"""
import math, numpy as np
import table2_model as m
from residual_map import EMP
from joint_search import lobe, lams
from joint_search_types import stack, TYPES, P, HI
def refl(L, frac, w):
    fk, fm, fa = frac; R = []
    for l in lams:
        nk, nm = m.n_ker(l), m.n_mel(l)
        mix = (fk*nk**w + fm*nm**w + fa*1.0**w)**(1/w)
        M = np.eye(2, dtype=complex)
        for kind, d in L:
            n = nk if kind == 'k' else mix
            dl = 2*np.pi*n*d/l
            M = M @ np.array([[np.cos(dl), 1j*np.sin(dl)/n], [1j*n*np.sin(dl), np.cos(dl)]])
        B = M[0, 0] + M[0, 1]*nk; C = M[1, 0] + M[1, 1]*nk
        R.append(abs((B - C)/(B + C))**2)
    return np.array(R)
for t, frac in TYPES.items():
    for sp in ('branickii', 'hybrid', 'gularis'):
        out = []
        for name, ws in (('w=1', (1.0,)), ('TE w=-0.5', (-0.5,)), ('TM w=2.5', (2.5,)), ('偏光なし', (-0.5, 2.5))):
            q = {}
            for p in P:
                air, cor, ker, lay, mel, ptt = m.T2[(sp, p)]
                R = np.mean([refl(stack(air, cor, ker, lay, mel, ptt), frac, w) for w in ws], axis=0)
                c, o = lobe(R, hi=HI.get(p, 800)); q[p] = c/EMP[(sp, p)]
            out.append(f'{name} {q["gorget"]/math.sqrt(q["crown"]*q["tail"]):.3f}')
        print(f'型{t:3s} {sp:9s} ' + '  '.join(out), flush=True)
