"""
概要:
    閉じた資産交換模型のシミュレーションを実行します。
詳細説明:
    全体系を小さい部分系Aと大きい熱浴Bに分け、各人がもつ資産を
    1単位ずつランダムに交換します。資産は負にならず、全資産は保存されます。
    下段の H は一人を無作為に選んだときの資産値の経験分布
    H = - sum_m p(m) log p(m)
    の Shannon エントロピーです。整数の資産値をそのまま数えているため、
    時刻ごとにヒストグラムのビンを取り直すことによる見かけの変化はありません。
    これは熱力学的エントロピー k_B log W そのものではない点に注意します。
    第3段は、この離散模型の状態数
    Omega_N(M) = (M+N-1)! / (M! (N-1)!)
    から計算する小正準エントロピー S/k_B = log Omega です。
"""

from collections import Counter
import math
import random

import matplotlib as mpl
import numpy as np

# 日本語フォントは、環境内で実際に認識された名前を使う。
mpl.rcdefaults()
mpl.rcParams.update(
    {
        "font.family": "Yu Mincho",
        "font.size": 14,
        "axes.unicode_minus": False,
        "text.usetex": False,
    }
)

import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation


# ----- パラメータ -----
NA = 50          # グループ A の人数（小さい部分系）
NB = 500         # グループ B の人数（大きい熱浴）
MA0 = 100          # 各人の初期資産
MB0 = 50          # 各人の初期資産
VTRADE = 1       # 1 回の交換額（整数にする）
NITER = 10_000   # スイープ回数
RECORD_EVERY = 1 # 何スイープごとに記録するか
ANIMATION_EVERY = 100  # 分布アニメーションの記録間隔（スイープ数）
ANIMATION_INTERVAL_MS = 150
DISPLAY_BIN_WIDTH = 5  # アニメーション表示用の資産ビン幅
SEED = None      # 再現したいときは、例えば 1234 を指定する


def shannon_entropy(values):
    """
    概要:
        資産値の経験分布の Shannon エントロピーを計算します。
    詳細説明:
        リストなどの値の集合を受け取り、各値の出現確率から
        自然対数を底とする Shannon エントロピーを求めます。
    引数:
        :param values: 資産値のリストなどの反復可能オブジェクト。
        :type values: iterable
    戻り値:
        :returns: 計算された Shannon エントロピー。
        :rtype: float
    """
    n = len(values)
    counts = Counter(values).values()
    return -sum((count / n) * math.log(count / n) for count in counts)


def log_omega(n_people, total_money):
    """
    概要:
        状態数 Omega の自然対数を計算します。
    詳細説明:
        非負整数の総資産 total_money を n_people 人へ配る状態数の自然対数です。
        階乗の対数は Stirling 近似ではなく math.lgamma を使用して計算します。
    引数:
        :param n_people: 人数。
        :type n_people: int
        :param total_money: 分配する総資産。
        :type total_money: int
    戻り値:
        :returns: 状態数の自然対数。
        :rtype: float
    例外:
        :raises ValueError: 総資産が負の場合に発生します。
    """
    if total_money < 0:
        raise ValueError("総資産は非負でなければなりません。")
    return (
        math.lgamma(total_money + n_people)
        - math.lgamma(total_money + 1)
        - math.lgamma(n_people)
    )


def main():
    """
    概要:
        資産交換のシミュレーションを実行しグラフとアニメーションを表示します。
    詳細説明:
        乱数シードや各種パラメータに基づいて初期状態を設定し、
        指定されたスイープ数だけランダムな資産交換を行います。
        定期的に平均資産、Shannon エントロピー、小正準エントロピーを記録し、
        最終的にそれらの推移グラフと分布の変化を示すアニメーションを描画します。
    """
    rng = random.Random(SEED)
    n_total = NA + NB
    money = [MA0] * n_total
    money[NA:n_total] = [MB0] * NB
    total_money = sum(money)

    steps = []
    mean_a_history = []
    mean_b_history = []
    entropy_a_history = []
    entropy_b_history = []
    entropy_all_history = []
    micro_entropy_a_history = []
    micro_entropy_b_history = []
    micro_entropy_total_history = []
    distribution_frames = []

    def record(step):
        money_a = money[:NA]
        money_b = money[NA:]

        steps.append(step)
        mean_a_history.append(sum(money_a) / NA)
        mean_b_history.append(sum(money_b) / NB)
        entropy_a_history.append(shannon_entropy(money_a))
        entropy_b_history.append(shannon_entropy(money_b))
        entropy_all_history.append(shannon_entropy(money))

        # これは資産ヒストグラムの Shannon エントロピーとは別物である。
        # A の全資産 M_A に対し、Omega_A(M_A) 個の微視的資産配置を数える。
        total_money_a = sum(money_a)
        total_money_b = total_money - total_money_a
        s_a = log_omega(NA, total_money_a)
        s_b = log_omega(NB, total_money_b)
        micro_entropy_a_history.append(s_a)
        micro_entropy_b_history.append(s_b)
        micro_entropy_total_history.append(s_a + s_b)

        if step % ANIMATION_EVERY == 0:
            # 後から状態が変わってもよいように、ここでコピーを保存する。
            distribution_frames.append((step, money_a.copy(), money_b.copy()))

    # t = 0 も記録する。全員が M0 なので、ここで H = 0 になる。
    record(0)

    # 1 スイープ = 全人数と同じ回数だけ交換相手を選ぶ。
    for step in range(1, NITER + 1):
        for _ in range(n_total):
            giver = rng.randrange(n_total)
            receiver = rng.randrange(n_total)

            if giver == receiver or money[giver] < VTRADE:
                continue

            money[giver] -= VTRADE
            money[receiver] += VTRADE

        if step % RECORD_EVERY == 0:
            record(step)

    assert sum(money) == total_money, "全資産が保存されていません。"

    fig, (ax_mean, ax_entropy, ax_micro) = plt.subplots(
        3, 1, figsize=(6, 8), sharex=True, constrained_layout=True
    )

    ax_mean.plot(steps, mean_a_history, label=r"$\langle M \rangle_A$")
    ax_mean.plot(steps, mean_b_history, label=r"$\langle M \rangle_B$")
    ax_mean.axhline(MA0, color="0.5", linestyle=":", linewidth=1.5, label="A初期平均")
    ax_mean.axhline(MB0, color="0.5", linestyle="--", linewidth=1.5, label="B初期平均")
    ax_mean.set_title("平均資産の推移")
    ax_mean.set_ylabel("平均資産")
    ax_mean.legend()
    ax_mean.grid(alpha=0.25)

    ax_entropy.plot(steps, entropy_all_history, color="0.25", label="全体系")
    ax_entropy.plot(steps, entropy_a_history, label=r"$H_A$")
    ax_entropy.plot(steps, entropy_b_history, label=r"$H_B$")
    ax_entropy.set_title("資産分布の Shannon エントロピー")
    ax_entropy.set_ylabel(r"$H=-\sum_m p(m)\log p(m)$")
    ax_entropy.legend()
    ax_entropy.grid(alpha=0.25)

    ax_micro.plot(steps, micro_entropy_a_history, label=r"$S_A/k_{\rm B}$")
    ax_micro.plot(steps, micro_entropy_b_history, label=r"$S_B/k_{\rm B}$")
    ax_micro.plot(
        steps,
        micro_entropy_total_history,
        color="0.2",
        linewidth=2,
        label=r"$(S_A+S_B)/k_{\rm B}$",
    )
    ax_micro.set_title("状態数から求めた小正準エントロピー")
    ax_micro.set_xlabel("スイープ数")
    ax_micro.set_ylabel(r"$S/k_{\rm B}=\log\Omega$")
    ax_micro.legend()
    ax_micro.grid(alpha=0.25)

    # ----- A, B の資産分布のアニメーション -----
    # 全フレームで同じ粗いビンを使う。縦軸は各フレームで A・B 共通に
    # 自動調整し、初期状態の高さ 1 によって平衡後の分布が潰れないようにする。
    largest_money = max(
        max(max(money_a), max(money_b))
        for _, money_a, money_b in distribution_frames
    )
    bins = list(range(0, largest_money + DISPLAY_BIN_WIDTH + 1, DISPLAY_BIN_WIDTH))
    if bins[-1] <= largest_money:
        bins.append(bins[-1] + DISPLAY_BIN_WIDTH)

    fig_dist, (ax_a, ax_b) = plt.subplots(
        2, 1, figsize=(8, 6), sharex=True, sharey=True, constrained_layout=True
    )

    def draw_distribution(frame_index):
        step, money_a, money_b = distribution_frames[frame_index]
        count_a, _ = np.histogram(money_a, bins=bins)
        count_b, _ = np.histogram(money_b, bins=bins)
        y_max = 1.10 * max(count_a.max() / NA, count_b.max() / NB, 0.02)

        ax_a.clear()
        ax_b.clear()
        ax_a.hist(
            money_a,
            bins=bins,
            weights=[1 / NA] * NA,
            color="tab:blue",
            edgecolor="white",
        )
        ax_b.hist(
            money_b,
            bins=bins,
            weights=[1 / NB] * NB,
            color="tab:orange",
            edgecolor="white",
        )

        ax_a.set_title(f"系 A の資産分布（sweep = {step}）")
        ax_b.set_title(f"系 B の資産分布（sweep = {step}）")
        ax_a.set_ylabel("確率")
        ax_b.set_ylabel("確率")
        ax_b.set_xlabel("一人あたりの資産 $m$")
        for ax in (ax_a, ax_b):
            ax.set_xlim(0, bins[-1])
            ax.set_ylim(0, y_max)
            ax.grid(alpha=0.25)

    animation = FuncAnimation(
        fig_dist,
        draw_distribution,
        frames=len(distribution_frames),
        interval=ANIMATION_INTERVAL_MS,
        repeat=True,
        blit=False,
    )
    # 参照を figure にも保持し、アニメーションが破棄されないようにする。
    fig_dist._distribution_animation = animation

    print(f"初期値: H_A = {entropy_a_history[0]:.6f}, "
          f"H_B = {entropy_b_history[0]:.6f}, "
          f"H_all = {entropy_all_history[0]:.6f}")
    print(f"最終値: H_A = {entropy_a_history[-1]:.6f}, "
          f"H_B = {entropy_b_history[-1]:.6f}, "
          f"H_all = {entropy_all_history[-1]:.6f}")
    print(
        f"分布アニメーション: 0 から {NITER} sweep まで、"
        f"{ANIMATION_EVERY} sweep 間隔で表示します。"
    )

    plt.show()


if __name__ == "__main__":
    main()