"""作用スペクトルのヒストグラム（Leberecht ほか 2023 の式1）を [FAD•− Z•] 対で計算する。Z は超微細結合を持たない相手。
重み(ν) = Σ_{ν_ij ∈ 帯} |<i|H⊥|j>|² · |<i|P_S|i> − <j|P_S|j>|。H0 = 地磁気のゼーマン（両電子）+ FAD の超微細。D=0。
H⊥ は地磁気に垂直な電波の磁場（両電子に ν_e·S⊥、振幅は相対値なので 1 にする）。地磁気は z, x, y の3方向、それぞれ垂直な2軸の電波を平均。
出力: 全体の重みのうち、帯ごとの割合。"""
import sys, numpy as np
import numax as X
import scenarios as SC

def pair_ops(nuclei):
    import scipy.sparse as sp
    dims = [2, 2] + [int(round(2 * I + 1)) for I, _ in nuclei]   # 電子A(FAD), 電子B(Z), 核…
    S = X.spin_ops(0.5)
    def emb(ops):
        M = sp.identity(1, dtype=complex, format="csr")
        for ax, d in enumerate(dims):
            M = sp.kron(M, sp.csr_matrix(ops[ax]) if ax in ops else sp.identity(d, dtype=complex, format="csr"), format="csr")
        return M
    SA = [emb({0: S[a]}) for a in range(3)]
    SB = [emb({1: S[a]}) for a in range(3)]
    N = int(np.prod(dims))
    Hhf = sp.csr_matrix((N, N), dtype=complex)
    for k, (I, A) in enumerate(nuclei):
        Ik = X.spin_ops(I)
        for b in range(3):
            Sb = sum(A[a, b] * S[a] for a in range(3))
            if np.abs(Sb).max() > 0:
                Hhf = Hhf + emb({0: Sb, k + 2: Ik[b]})
    PS = 0.25 * sp.identity(N, dtype=complex, format="csr") - sum(SA[a] @ SB[a] for a in range(3))
    return N, SA, SB, Hhf, PS

def histogram(nuclei, edges):
    N, SA, SB, Hhf, PS = pair_ops(nuclei)
    tot = np.zeros(len(edges) - 1)
    numax = 0
    for z in range(3):
        perp = [a for a in range(3) if a != z]
        H0 = (Hhf + X.NU_E * (SA[z] + SB[z])).toarray()
        E, V = np.linalg.eigh(H0)
        ps = np.real(np.einsum("ij,ij->j", V.conj(), PS @ V))
        numax = max(numax, E[-1] - E[0])
        Hps = [V.conj().T @ ((SA[p] + SB[p]) @ V) for p in perp]
        # N×N の一時配列を作らないよう、行を区切って上三角だけ足す（4608次元で 2GB 超になって止められたため）
        step = 256
        for r0 in range(0, N, step):
            r = slice(r0, min(N, r0 + step))
            nu = np.abs(E[r, None] - E[None, :])
            dps = np.abs(ps[r, None] - ps[None, :])
            w = sum(np.abs(Hp[r]) ** 2 for Hp in Hps) * dps / 2   # 垂直な2軸の平均
            mask = np.arange(r0, r.stop)[:, None] < np.arange(N)[None, :]
            h, _ = np.histogram(nu[mask], bins=edges, weights=w[mask])
            tot += h
        del V, H0
    return N, numax, tot / tot.sum(), tot.sum()

if __name__ == "__main__":
    args = sys.argv[1:]
    edges = np.array([0, 50, 100, 116, 140, 150, 200, 400])
    if args and args[0] == "--fine":
        edges = np.array([0, 25, 50, 75, 85, 100, 116, 140, 150, 200, 400]); args = args[1:]
    for name in args:
        N, nm, f, total = histogram(SC.S[name](), edges)
        cells = "  ".join(f"{edges[i]:.0f}–{edges[i+1]:.0f}: {f[i]*100:6.3f}%" for i in range(len(f)))
        print(f"{name:16s} 次元 {N:>6d}  対の準位の幅 {nm:6.1f} MHz  合計 {total:.4g}  {cells}", flush=True)
