"""査読（12/1、論文の原稿）への応答(2): 淡い層から真っ黒までの入れ替わりを、光子を一つずつ追う計算で確かめる。

sumi_mc.py と同じ光子追跡（拡散光の入射、ヘニエイ–グリーンスタイン、吸収は重み、紙は Rg=0.85 の完全拡散面）。
光学的厚さは τ(λ) = c·Qext(λ)/d。c は面積あたりの煤の体積に比例するので、粒径をまたいで量を比べられる。
c0 は 30nm で 550nm の反射が紙の 0.53 倍になる量（KM の X0 に当たる）。各量で乱数の種を3つ変えて回し、b* の平均と幅を出す。
実行: uv run --no-project --with miepython==2.5.5 --with colour-science==0.4.6 --with numpy python sumi_mc_crossover.py
"""
import numpy as np, miepython, colour

nm = np.arange(400, 701, 10).astype(float)
Rg = 0.85
D65 = colour.SDS_ILLUMINANTS["D65"]


def mc(rng, tau, w, g, n):
    mu = np.sqrt(rng.random(n))
    z = np.zeros(n); wt = np.ones(n); alive = np.ones(n, bool); R = 0.0
    for _ in range(2000):
        if not alive.any():
            break
        idx = np.nonzero(alive)[0]
        s = -np.log(rng.random(idx.size))
        znew = z[idx] + s * mu[idx]
        up = znew < 0; down = znew > tau; inside = ~(up | down)
        R += wt[idx[up]].sum(); alive[idx[up]] = False
        di = idx[down]
        wt[di] *= Rg; z[di] = tau; mu[di] = -np.sqrt(rng.random(di.size))
        ii = idx[inside]; z[ii] = znew[inside]; wt[ii] *= w
        if g == 0:
            ct = 2 * rng.random(ii.size) - 1
        else:
            t = (1 - g * g) / (1 - g + 2 * g * rng.random(ii.size))
            ct = (1 + g * g - t * t) / (2 * g)
        phi = 2 * np.pi * rng.random(ii.size); m0 = mu[ii]
        st = np.sqrt(np.maximum(0, 1 - ct * ct)); s0 = np.sqrt(np.maximum(0, 1 - m0 * m0))
        mu[ii] = m0 * ct + s0 * st * np.cos(phi)
        # 重みが小さくなった光子はロシアンルーレット（偏りを作らない打ち切り）
        low = alive & (wt < 1e-3)
        if low.any():
            li = np.nonzero(low)[0]
            survive = rng.random(li.size) < 0.1
            wt[li[survive]] *= 10
            alive[li[~survive]] = False
    return R / n


def lab(R):
    return colour.XYZ_to_Lab(colour.sd_to_XYZ(colour.SpectralDistribution(dict(zip(nm, R))), illuminant=D65) / 100)


opt = {}
for d in (30.0, 400.0):
    qe, qs, qb, g = miepython.mie(1.95 - 0.79j, np.pi * d / nm)
    opt[d] = (qe / d, qs / qe, g)

ext, w, g = opt[30.0]
rng = np.random.default_rng(10)
lo, hi = 1e-4, 1e4
for _ in range(40):
    c = np.sqrt(lo * hi)
    lo, hi = (c, hi) if mc(rng, c * ext[15], w[15], g[15], 40000) > 0.53 * Rg else (lo, c)
c0 = np.sqrt(lo * hi)
print(f"c0 = {c0:.4g}（30nm で 550nm の反射が紙の 0.53 倍）")
print("X/X0    30nm: b*（種3つ: 平均 ± 幅/2）  L*        400nm: b*                 L*        30nm−400nm")
for f in (1, 4, 8, 10, 12, 16, 32, 1000):
    res = {}
    for d in (30.0, 400.0):
        ext, w, g = opt[d]
        bs, Ls = [], []
        for seed in (1, 2, 3):
            rng = np.random.default_rng(100 * seed + int(f))
            n = 60000 if f < 8 else 200000
            R = np.array([mc(rng, f * c0 * ext[i], w[i], g[i], n) for i in range(nm.size)])
            L, a, b = lab(R)
            bs.append(b); Ls.append(L)
        res[d] = (np.mean(bs), (max(bs) - min(bs)) / 2, np.mean(Ls))
    a, b_ = res[30.0], res[400.0]
    print(f"{f:<7} {a[0]:+7.2f} ± {a[1]:.2f}            {a[2]:6.2f}     {b_[0]:+7.2f} ± {b_[1]:.2f}          {b_[2]:6.2f}    {a[0]-b_[0]:+7.2f}", flush=True)
