"""査読（--note 1回目、11/17）の指摘: 読み取りの誤差と寸法の誤差を比へ同時に伝え、部位間で誤差が共通の場合と独立の場合を比べる。
寸法（表2の air・cortex・ker・mel・pttop）に相対 s の誤差。分け方は ρ（部位間の相関）で: 誤差 = s(√ρ·共通 + √(1-ρ)·部位ごと)。
実測の重心には σ=7nm の読み取り誤差（部位ごとに独立）。補正なしの模型（metric_ci_dims.py と同じ）。5%・10% は仮定ごとの感度分析。"""
import numpy as np
import table2_model as m
from residual_map import EMP
from ratio_gm_vis import cen_vis, lams
def refl_fast(layers):
    """table2_model.refl と同じ計算を、波長方向にまとめて解く（結果は一致を確かめてある）"""
    L = np.asarray(lams, float); 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
rng = np.random.default_rng(7)
SP = ('branickii', 'hybrid', 'gularis'); P = ('gorget', 'crown', 'tail'); DIMS = (0, 1, 2, 4, 5); N = 300
assert np.allclose(refl_fast(m.stack(*m.T2[('hybrid','gorget')])), m.refl(lams, m.stack(*m.T2[('hybrid','gorget')])))
for srel in (0.05, 0.10):
    for rho in (0.0, 0.5, 1.0):
        vals = {s: [] for s in SP}
        for _ in range(N):
            for s in SP:
                common = rng.standard_normal(len(DIMS)); q = {}
                for p in P:
                    d = list(m.T2[(s, p)]); own = rng.standard_normal(len(DIMS))
                    for k, i in enumerate(DIMS): d[i] *= 1 + srel*(np.sqrt(rho)*common[k] + np.sqrt(1-rho)*own[k])
                    q[p] = cen_vis(refl_fast(m.stack(*d)))/(EMP[(s, p)] + 7*rng.standard_normal())
                vals[s].append(q['gorget']/np.sqrt(q['crown']*q['tail']))
        out = '  '.join(f'{s} {np.median(v):.3f} [{np.percentile(v,2.5):.3f},{np.percentile(v,97.5):.3f}] ≤1.024 {np.mean(np.array(v)<=1.024):.1%}' for s, v in vals.items())
        pr = [np.mean(np.array(vals[s]) <= 1.024) for s in SP]
        two = pr[0]*pr[1]*(1-pr[2]) + pr[0]*(1-pr[1])*pr[2] + (1-pr[0])*pr[1]*pr[2] + pr[0]*pr[1]*pr[2]
        print(f's={srel:.0%} ρ={rho:.1f}  {out}  3羽中2羽以上が線の下（羽どうし独立とみなす） {two:.1%}', flush=True)
