"""論文の図1: 詰まった煤の球の直径と、白い紙の上の淡墨の b*（sumi_km.py と同じ模型を細かい直径で回す）。
凝集体の点は研究ノートの結果13（T 行列、tm_color.py / tm_extra_color.py の出力）の値を書き写したもの。
実行: uv run --with miepython==2.5.5 --with colour-science==0.4.6 --with matplotlib python paper/fig_bstar.py
"""
import numpy as np, miepython, colour
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from pathlib import Path

lam = np.arange(400, 701, 10).astype(float)
Rg = 0.85
i550 = int(np.argmin(abs(lam - 550)))


def KS(m, d):
    x = np.pi * d / lam
    qe, qs, qb, g = miepython.mie(m, x)
    return 2 * (qe - qs) / d, 0.75 * qs * (1 - g) / d


def R_layer(K, S, X):
    S = np.maximum(S, 1e-12)
    a = 1 + K / S; b = np.sqrt(a * a - 1)
    sh, ch = np.sinh(b * S * X), np.cosh(b * S * X)
    return (1 - Rg * (a - b * ch / sh)) / (a - Rg + b * ch / sh)


def bstar(m, d):
    K, S = KS(m, d)
    lo, hi = 1e-6, 1e6
    for _ in range(200):
        X = np.sqrt(lo * hi)
        if R_layer(K, S, X)[i550] > 0.45:
            lo = X
        else:
            hi = X
    sd = colour.SpectralDistribution(dict(zip(lam, R_layer(K, S, X))))
    return colour.XYZ_to_Lab(colour.sd_to_XYZ(sd, illuminant=colour.SDS_ILLUMINANTS["D65"]) / 100)[2]


ds = np.geomspace(10, 1000, 120)
curves = {"1.95 − 0.79i": 1.95 - 0.79j, "1.75 − 0.63i": 1.75 - 0.63j, "1.95 − 0.96i": 1.95 - 0.96j}
fig, ax = plt.subplots(figsize=(6.4, 4.0), dpi=200)
for (lab, m), c, ls in zip(curves.items(), ["#1f3b73", "#7a7a7a", "#7a7a7a"], ["-", "--", ":"]):
    ax.plot(ds, [bstar(m, d) for d in ds], color=c, ls=ls, lw=1.6 if ls == "-" else 1.1, label=f"compact sphere, m = {lab}")
# 結果13: T 行列の凝集体（一次粒子 30nm、体積で等しい球の直径に置く）。N=1000 は向き3つの平均
agg = [(176, 6.02, "s", "N=200, Df=2.8", (-8, -11), "right"), (176, 7.32, "^", "N=200, Df=1.8", (-8, 4), "right"),
       (300, 3.57, "s", "N=1000, Df=2.8", (8, -3), "left"), (300, 6.60, "^", "N=1000, Df=1.8", (8, -3), "left")]
for d, b, mk, lab, off, ha in agg:
    ax.plot(d, b, mk, ms=6, mfc="white", mec="#b5541c", mew=1.4)
    ax.annotate(lab, (d, b), xytext=off, textcoords="offset points", fontsize=7, color="#b5541c", ha=ha)
ax.plot([], [], "s", mfc="white", mec="#b5541c", label="aggregate of 30 nm spheres, Df = 2.8 (T-matrix)")
ax.plot([], [], "^", mfc="white", mec="#b5541c", label="aggregate of 30 nm spheres, Df = 1.8 (T-matrix)")
ax.axhline(0, color="#444", lw=0.6)
for d in (30, 50):
    ax.axvline(d, color="#999", lw=0.5, ls="-")
ax.text(30, 11.6, "30", ha="center", fontsize=7, color="#666")
ax.text(50, 11.6, "50 nm", ha="left", fontsize=7, color="#666")
ax.set_xscale("log")
ax.set_xlim(10, 1000); ax.set_ylim(-3, 12)
ax.set_xlabel("diameter of the compact sphere, or of a sphere of equal soot volume (nm)")
ax.set_ylabel("b* of the dilute ink on white paper")
ax.text(12, -2.4, "bluish", fontsize=8, color="#1f3b73"); ax.text(12, 10.6, "brownish", fontsize=8, color="#b5541c")
ax.legend(fontsize=7, frameon=False, loc="upper right")
for s in ("top", "right"):
    ax.spines[s].set_visible(False)
fig.tight_layout()
out = Path(__file__).with_name("figs"); out.mkdir(exist_ok=True)
fig.savefig(out / "fig1_bstar.png")
print("書いた:", out / "fig1_bstar.png")
for d in (30, 50, 80, 300, 400, 600):
    print(d, round(bstar(1.95 - 0.79j, d), 2))
