# tm_results.jsonl の凝集体を、ばらばらの一次粒子・同じ体積の詰まった球（Mie）と並べて紙の上の色にする
# 7波長（400–700nm、50nm刻み）の値を 10nm 刻みへ線形補間し、sumi_check.py と同じ KM・CIELAB の手順に通す
import json, numpy as np, miepython, colour
from collections import defaultdict
from sumi_check import dilute, lab, nm
L7 = np.arange(400, 701, 50.)
m = 1.95 - 0.79j
def mieKS(d):
    K = []; S = []
    for l in L7:
        qe, qs, qb, g = miepython.mie(m, np.pi * d / l); A = np.pi * d * d / 4; V = np.pi * d ** 3 / 6
        K.append(2 * (qe - qs) * A / V); S.append(0.75 * qs * (1 - g) * A / V)
    return np.array(K), np.array(S)
def color(K7, S7):
    K = np.interp(nm, L7, K7); S = np.interp(nm, L7, S7)
    L, A, B = lab(dilute(K, S))
    de = colour.delta_E(np.array([L, A, B]), np.array([L, 0, 0]), method='CIE 2000')
    return L, A, B, de
def main():
  rows = defaultdict(dict)
  for l in open("tm_results.jsonl"):
      d = json.loads(l); rows[(d["N"], d["Df"], d.get("lmax", 2))][d["lam"]] = d
  print("もの                         L*     a*     b*   ΔE00   Cabs/V比(550nm, 一次粒子=1)")
  K0, S0 = mieKS(30.)
  print(f"{'一次粒子 30nm（ばらばら）':26s}", " ".join(f"{v:+6.2f}" for v in color(K0, S0)), "  1.00")
  for (N, Df, lmax), r in sorted(rows.items()):
      need = L7 if (N <= 200 and lmax == 2) else np.array([400., 500, 600, 700])
      if not all(l in r for l in need.astype(int)): print(N, Df, "未完", sorted(r)); continue
      V = N * np.pi * 30 ** 3 / 6
      Ls = np.array(sorted(r))
      K = np.interp(L7, Ls, [2 * r[l]["Cabs"] / V for l in Ls]); S = np.interp(L7, Ls, [0.75 * r[l]["Csca"] * (1 - r[l]["g"]) / V for l in Ls])
      deq = 30 * N ** (1 / 3); Ke, Se = mieKS(deq)
      print(f"{f'凝集体 N={N} Df={Df} l{lmax}':26s}", " ".join(f"{v:+6.2f}" for v in color(K, S)), f"  {K[3]/K0[3]:.2f}")
      print(f"{f'  同体積の詰まった球 {deq:.0f}nm':26s}", " ".join(f"{v:+6.2f}" for v in color(Ke, Se)), f"  {Ke[3]/K0[3]:.2f}")

if __name__ == "__main__":
    main()
