"""論文の図2: 面積あたりの煤の量 X/X0 を動かしたときの b*（媒質 1.0、表面の照り返しなし、sumi_crossover.py と同じ模型）。
あわせて、入れ替わる量の見積もり Rg·exp(-2KX) = S/(2K)（550nm）を粒径ごとに出して、計算の入れ替わりと比べる。
実行: uv run --no-project --with miepython==2.5.5 --with colour-science==0.4.6 --with numpy --with matplotlib python paper/fig_crossover.py
"""
import sys
from pathlib import Path
import numpy as np
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt

sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
import sumi_crossover as sc  # noqa: E402  （読み込むと表も出る）

n_med = 1.0
ks = {d: sc.KS(d, n_med) for d in (30, 80, 400, 600)}
X0 = sc.X_for(*ks[30], 0.53 * sc.Rg)
fs = np.geomspace(0.1, 100, 160)
print("\n見積もり: 紙から返る光 Rg·exp(-2KX) が層の跳ね返し S/(2K) と等しくなる X/X0（550nm）")
for d, (K, S) in ks.items():
    k, s = K[sc.i550], S[sc.i550]
    Xc = np.log(2 * k * sc.Rg / s) / (2 * k)
    print(f"  {d}nm: K/S = {k/s:.0f}, X/X0 = {Xc/X0:.1f}")

fig, ax = plt.subplots(figsize=(6.4, 4.0), dpi=200)
cols = {30: "#b5541c", 80: "#d08a3a", 400: "#1f3b73", 600: "#5b7fb8"}
for d, (K, S) in ks.items():
    ax.plot(fs, [sc.lab(sc.R_layer(K, S, f * X0))[2] for f in fs], color=cols[d], lw=1.6, label=f"{d} nm")
ax.axhline(0, color="#444", lw=0.6)
ax.axvline(1, color="#999", lw=0.5)
ax.text(1.08, -5.2, "X0: dilute ink\n(550 nm reflectance of the\n30 nm layer = 0.53 × paper)", fontsize=7, color="#555", va="top")
ax.set_xscale("log")
ax.set_xlim(0.1, 100); ax.set_ylim(-10, 16)
ax.set_xlabel("soot volume per unit area, relative to the dilute ink X0")
ax.set_ylabel("b*")
ax.legend(title="compact sphere diameter", fontsize=7, title_fontsize=7, frameon=False, loc="lower left")
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 / "fig2_crossover.png")
print("書いた:", out / "fig2_crossover.png")
