"""ratio_their_exact.py の可視版: 主なローブを 400〜800nm の最大の山に固定（全体の最大が紫外の高次の山に飛ぶ種があった: helianthea 339nm など）。
前の版はケラチンの分をメラニンに数えていた。比（斜めの切片の伸びを打ち消す入射角 ÷ δ）が 1 を超えるかを見直す。"""
import numpy as np
import table2_model as m
from incidence_vs_section import lams
def cen(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())
FILL = {'I': (0.05, 0.40, 0.55), 'II': (0.05, 0.30, 0.65), 'III': (0.025, 0.025, 0.95)}
def n_of(kind, l):
    if kind == 'k': return m.n_ker(l)
    fk, fm, fa = FILL[kind]; return fk*m.n_ker(l) + fm*m.n_mel(l) + fa
def refl(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 in L:
                n = n_of(kind, 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 build(c, b2, d, N, fill, s=1.0):
    return [('k', c*s)] + sum(([(fill, b2*s)] + ([('k', d*s)] if i < N-1 else []) for i in range(N)), [])
rows = [l.split('\t') for l in open('../src/scirep2026_table2.tsv').read().splitlines()[1:]]
for r in rows:
    if len(r) < 10 or not r[1].replace('.', '').isdigit(): continue
    sp, c, b1, d, a, b2, N, fill, cm, dl = r[:10]
    c, d, b2, N = float(c), float(d), float(b2), int(N); delta = float(dl.rstrip('°'))
    if delta == 0: continue
    base = cen(refl(build(c, b2, d, N, fill), 0))
    st = build(c, b2, d, N, fill, 1/np.cos(np.radians(delta)))
    ths = np.arange(0, 80, 2.0); cs = [cen(refl(st, t)) for t in ths]
    back = ths[int(np.argmin([abs(x-base) for x in cs]))]
    print(f'{sp:16s} 型{fill:3s} δ{delta:3.0f}°  山 {base:4.0f}nm  打ち消す入射角 {back:3.0f}°  比 {back/delta:.2f}', flush=True)
