"""斜めの切片（全層の厚さ ×1/cosδ、垂直入射）と、斜め入射（厚さそのまま、入射角 θ）の山のずれを比べる。
Valencia-Palacios ほか 2026 は「模型が赤い」ずれを入射角で合わせ、C. orina で θ≈δ を得た。
原因が切片の側なら、ずれを打ち消すのに要る θ は δ より大きくなるはず。それがどれだけか。
偏光は TE と TM の平均。山は主なローブの重心（centroid_peak.py と同じ）。"""
import numpy as np
import table2_model as m
lams = np.arange(300, 1201, 2.0)

def refl_theta(L, th):
    s0 = np.sin(np.radians(th)); R = []
    for l in lams:
        out = 0
        for pol in ('TE', 'TM'):
            def eta(n):
                c = np.sqrt(1 - (s0/n)**2 + 0j)
                return (n*c if pol == 'TE' else n/c), c
            M = np.eye(2, dtype=complex)
            for kind, d, fa in L:
                n = m.n_ker(l) if kind == 'k' else (m.n_mel(l) if kind == 'm' else fa + (1-fa)*m.n_mel(l))
                e, c = eta(n); dl = 2*np.pi*n*c*d/l
                M = M @ np.array([[np.cos(dl), 1j*np.sin(dl)/e], [1j*e*np.sin(dl), np.cos(dl)]])
            es, _ = eta(m.n_ker(l)); e0, _ = eta(1.0+0j)
            B = M[0, 0] + M[0, 1]*es; C = M[1, 0] + M[1, 1]*es
            out += abs((e0*B - C)/(e0*B + C))**2 / 2
        R.append(out)
    return np.array(R)

def cen(R):
    i = int(np.argmax(R)); 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())

def scaled(v, s):
    air, cor, ker, lay, mel, ptt = v
    return m.stack(air*s, cor*s, ker*s, lay, mel*s, ptt*s)

if __name__ == '__main__':
    for sp in ('branickii', 'hybrid', 'gularis'):
        v = m.T2[(sp, 'gorget')]
        base = cen(refl_theta(m.stack(*v), 0))
        row = []
        for d in (14, 26, 33):
            stretched = cen(refl_theta(scaled(v, 1/np.cos(np.radians(d))), 0))
            tilt = cen(refl_theta(m.stack(*v), d))
            # 伸ばした模型を、どの入射角で元の山に戻せるか
            ths = np.arange(0, 71, 1.0)
            cs = [cen(refl_theta(scaled(v, 1/np.cos(np.radians(d))), t)) for t in ths]
            back = ths[int(np.argmin([abs(c-base) for c in cs]))]
            row.append(f'δ{d}: 切片で +{stretched-base:.0f}nm / 入射{d}°で {tilt-base:+.0f}nm / 打ち消す入射角 {back:.0f}°')
        print(f'{sp:9s} 基準 {base:.0f}nm  ' + '  '.join(row))
