# 黄みのある紙の上の淡墨を、紙を白と見た目で（紙に順応して）見たときの色
# 仮説: 墨の層が散らした光は紙を通らないので紙の黄みを持たない。紙を白と見る目には、そのぶん青く見える
import numpy as np, miepython, colour
m = 1.95 - 0.79j
nm = np.arange(400, 701, 10).astype(float)
D65 = colour.SDS_ILLUMINANTS['D65']
W65 = colour.sd_to_XYZ(colour.SpectralDistribution(dict(zip(nm, np.ones_like(nm)))), illuminant=D65) / 100

def paper(y):
    # 白 0.85 から、青側ほど反射が下がる紙（y=0 で無彩色）
    return 0.85 * (1 - y * np.clip((560 - nm) / 160, 0, 1) ** 1.5)

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

def KS_agg(N, dp=30.0, Df=1.8, kf=1.3):
    lam = nm * 1e-9; a = dp * 1e-9 / 2; mm = (1.95 + 0.79j) ** 2
    E = ((mm - 1) / (mm + 2)).imag; F = abs((mm - 1) / (mm + 2)) ** 2
    k = 2 * np.pi / lam
    Rgyr = a * (N / kf) ** (1 / Df); q2 = (k * Rgyr) ** 2
    G = (1 + 4 * q2 / (3 * Df)) ** (-Df / 2)
    Cabs = N * 4 * np.pi * k * a ** 3 * E; Csca = N * N * 8 / 3 * np.pi * k ** 4 * a ** 6 * F * G
    V = N * 4 / 3 * np.pi * a ** 3
    return 2 * Cabs / V, 0.75 * Csca * G / V

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

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

def lab_abs(R):
    return colour.XYZ_to_Lab(XYZ(R), colour.XYZ_to_xy(W65))

def lab_rel(R, Rg):
    # 紙に順応: CAT02 で紙の色を D65 の白へ写し、紙を L*=100 にそろえて Lab
    Wp = XYZ(Rg)
    X2 = colour.adaptation.chromatic_adaptation_VonKries(XYZ(R), Wp, W65 * Wp[1] / W65[1], transform='CAT02')
    return colour.XYZ_to_Lab(X2 / Wp[1], colour.XYZ_to_xy(W65))

def dilute(K, S, Rg, frac=0.53):
    # 550nm で紙の frac 倍の反射になる量
    i = np.argmin(abs(nm - 550)); lo, hi = 1e-12, 1e12
    for _ in range(300):
        X = np.sqrt(lo * hi)
        if R_layer(K, S, X, Rg)[i] > frac * Rg[i]: lo = X
        else: hi = X
    return R_layer(K, S, X, Rg)

inks = [("詰まった粒 30nm", KS_sphere(30.)), ("詰まった粒 50nm", KS_sphere(50.)), ("詰まった粒 80nm", KS_sphere(80.)),
        ("詰まった粒 120nm", KS_sphere(120.)), ("詰まった粒 200nm", KS_sphere(200.)), ("詰まった粒 300nm", KS_sphere(300.)),
        ("詰まった粒 400nm", KS_sphere(400.)), ("疎な塊 30nm×100", KS_agg(100)), ("疎な塊 30nm×10000", KS_agg(10000)),
        ("疎な塊 50nm×1000", KS_agg(1000, dp=50.))]
for y in [0.0, 0.15, 0.3]:
    Rg = paper(y); Lp = lab_abs(Rg)
    print(f"\n紙 y={y}: 紙そのものの L*a*b* = {Lp[0]:.1f} {Lp[1]:+.2f} {Lp[2]:+.2f}")
    print("  墨                     絶対 b*   紙に順応した a*  b*")
    for name, (K, S) in inks:
        R = dilute(K, S, Rg)
        la = lab_abs(R); lr = lab_rel(R, Rg)
        print(f"  {name:18s}  {la[2]:+6.2f}      {lr[1]:+6.2f} {lr[2]:+6.2f}")
