randomtrade_canonical_entropy.py ダウンロード/コピー

randomtrade_canonical_entropy.py をダウンロード

randomtrade_canonical_entropy.py
randomtrade_canonical_entropy.py
  1"""
  2概要:
  3    閉じた資産交換模型のシミュレーションを実行します。
  4詳細説明:
  5    全体系を小さい部分系Aと大きい熱浴Bに分け、各人がもつ資産を
  6    1単位ずつランダムに交換します。資産は負にならず、全資産は保存されます。
  7    下段の H は一人を無作為に選んだときの資産値の経験分布
  8    H = - sum_m p(m) log p(m)
  9    の Shannon エントロピーです。整数の資産値をそのまま数えているため、
 10    時刻ごとにヒストグラムのビンを取り直すことによる見かけの変化はありません。
 11    これは熱力学的エントロピー k_B log W そのものではない点に注意します。
 12    第3段は、この離散模型の状態数
 13    Omega_N(M) = (M+N-1)! / (M! (N-1)!)
 14    から計算する小正準エントロピー S/k_B = log Omega です。
 15"""
 16
 17from collections import Counter
 18import math
 19import random
 20
 21import matplotlib as mpl
 22import numpy as np
 23
 24# 日本語フォントは、環境内で実際に認識された名前を使う。
 25mpl.rcdefaults()
 26mpl.rcParams.update(
 27    {
 28        "font.family": "Yu Mincho",
 29        "font.size": 14,
 30        "axes.unicode_minus": False,
 31        "text.usetex": False,
 32    }
 33)
 34
 35import matplotlib.pyplot as plt
 36from matplotlib.animation import FuncAnimation
 37
 38
 39# ----- パラメータ -----
 40NA = 50          # グループ A の人数(小さい部分系)
 41NB = 500         # グループ B の人数(大きい熱浴)
 42MA0 = 100          # 各人の初期資産
 43MB0 = 50          # 各人の初期資産
 44VTRADE = 1       # 1 回の交換額(整数にする)
 45NITER = 10_000   # スイープ回数
 46RECORD_EVERY = 1 # 何スイープごとに記録するか
 47ANIMATION_EVERY = 100  # 分布アニメーションの記録間隔(スイープ数)
 48ANIMATION_INTERVAL_MS = 150
 49DISPLAY_BIN_WIDTH = 5  # アニメーション表示用の資産ビン幅
 50SEED = None      # 再現したいときは、例えば 1234 を指定する
 51
 52
 53def shannon_entropy(values):
 54    """
 55    概要:
 56        資産値の経験分布の Shannon エントロピーを計算します。
 57    詳細説明:
 58        リストなどの値の集合を受け取り、各値の出現確率から
 59        自然対数を底とする Shannon エントロピーを求めます。
 60    引数:
 61        :param values: 資産値のリストなどの反復可能オブジェクト。
 62        :type values: iterable
 63    戻り値:
 64        :returns: 計算された Shannon エントロピー。
 65        :rtype: float
 66    """
 67    n = len(values)
 68    counts = Counter(values).values()
 69    return -sum((count / n) * math.log(count / n) for count in counts)
 70
 71
 72def log_omega(n_people, total_money):
 73    """
 74    概要:
 75        状態数 Omega の自然対数を計算します。
 76    詳細説明:
 77        非負整数の総資産 total_money を n_people 人へ配る状態数の自然対数です。
 78        階乗の対数は Stirling 近似ではなく math.lgamma を使用して計算します。
 79    引数:
 80        :param n_people: 人数。
 81        :type n_people: int
 82        :param total_money: 分配する総資産。
 83        :type total_money: int
 84    戻り値:
 85        :returns: 状態数の自然対数。
 86        :rtype: float
 87    例外:
 88        :raises ValueError: 総資産が負の場合に発生します。
 89    """
 90    if total_money < 0:
 91        raise ValueError("総資産は非負でなければなりません。")
 92    return (
 93        math.lgamma(total_money + n_people)
 94        - math.lgamma(total_money + 1)
 95        - math.lgamma(n_people)
 96    )
 97
 98
 99def main():
100    """
101    概要:
102        資産交換のシミュレーションを実行しグラフとアニメーションを表示します。
103    詳細説明:
104        乱数シードや各種パラメータに基づいて初期状態を設定し、
105        指定されたスイープ数だけランダムな資産交換を行います。
106        定期的に平均資産、Shannon エントロピー、小正準エントロピーを記録し、
107        最終的にそれらの推移グラフと分布の変化を示すアニメーションを描画します。
108    """
109    rng = random.Random(SEED)
110    n_total = NA + NB
111    money = [MA0] * n_total
112    money[NA:n_total] = [MB0] * NB
113    total_money = sum(money)
114
115    steps = []
116    mean_a_history = []
117    mean_b_history = []
118    entropy_a_history = []
119    entropy_b_history = []
120    entropy_all_history = []
121    micro_entropy_a_history = []
122    micro_entropy_b_history = []
123    micro_entropy_total_history = []
124    distribution_frames = []
125
126    def record(step):
127        money_a = money[:NA]
128        money_b = money[NA:]
129
130        steps.append(step)
131        mean_a_history.append(sum(money_a) / NA)
132        mean_b_history.append(sum(money_b) / NB)
133        entropy_a_history.append(shannon_entropy(money_a))
134        entropy_b_history.append(shannon_entropy(money_b))
135        entropy_all_history.append(shannon_entropy(money))
136
137        # これは資産ヒストグラムの Shannon エントロピーとは別物である。
138        # A の全資産 M_A に対し、Omega_A(M_A) 個の微視的資産配置を数える。
139        total_money_a = sum(money_a)
140        total_money_b = total_money - total_money_a
141        s_a = log_omega(NA, total_money_a)
142        s_b = log_omega(NB, total_money_b)
143        micro_entropy_a_history.append(s_a)
144        micro_entropy_b_history.append(s_b)
145        micro_entropy_total_history.append(s_a + s_b)
146
147        if step % ANIMATION_EVERY == 0:
148            # 後から状態が変わってもよいように、ここでコピーを保存する。
149            distribution_frames.append((step, money_a.copy(), money_b.copy()))
150
151    # t = 0 も記録する。全員が M0 なので、ここで H = 0 になる。
152    record(0)
153
154    # 1 スイープ = 全人数と同じ回数だけ交換相手を選ぶ。
155    for step in range(1, NITER + 1):
156        for _ in range(n_total):
157            giver = rng.randrange(n_total)
158            receiver = rng.randrange(n_total)
159
160            if giver == receiver or money[giver] < VTRADE:
161                continue
162
163            money[giver] -= VTRADE
164            money[receiver] += VTRADE
165
166        if step % RECORD_EVERY == 0:
167            record(step)
168
169    assert sum(money) == total_money, "全資産が保存されていません。"
170
171    fig, (ax_mean, ax_entropy, ax_micro) = plt.subplots(
172        3, 1, figsize=(6, 8), sharex=True, constrained_layout=True
173    )
174
175    ax_mean.plot(steps, mean_a_history, label=r"$\langle M \rangle_A$")
176    ax_mean.plot(steps, mean_b_history, label=r"$\langle M \rangle_B$")
177    ax_mean.axhline(MA0, color="0.5", linestyle=":", linewidth=1.5, label="A初期平均")
178    ax_mean.axhline(MB0, color="0.5", linestyle="--", linewidth=1.5, label="B初期平均")
179    ax_mean.set_title("平均資産の推移")
180    ax_mean.set_ylabel("平均資産")
181    ax_mean.legend()
182    ax_mean.grid(alpha=0.25)
183
184    ax_entropy.plot(steps, entropy_all_history, color="0.25", label="全体系")
185    ax_entropy.plot(steps, entropy_a_history, label=r"$H_A$")
186    ax_entropy.plot(steps, entropy_b_history, label=r"$H_B$")
187    ax_entropy.set_title("資産分布の Shannon エントロピー")
188    ax_entropy.set_ylabel(r"$H=-\sum_m p(m)\log p(m)$")
189    ax_entropy.legend()
190    ax_entropy.grid(alpha=0.25)
191
192    ax_micro.plot(steps, micro_entropy_a_history, label=r"$S_A/k_{\rm B}$")
193    ax_micro.plot(steps, micro_entropy_b_history, label=r"$S_B/k_{\rm B}$")
194    ax_micro.plot(
195        steps,
196        micro_entropy_total_history,
197        color="0.2",
198        linewidth=2,
199        label=r"$(S_A+S_B)/k_{\rm B}$",
200    )
201    ax_micro.set_title("状態数から求めた小正準エントロピー")
202    ax_micro.set_xlabel("スイープ数")
203    ax_micro.set_ylabel(r"$S/k_{\rm B}=\log\Omega$")
204    ax_micro.legend()
205    ax_micro.grid(alpha=0.25)
206
207    # ----- A, B の資産分布のアニメーション -----
208    # 全フレームで同じ粗いビンを使う。縦軸は各フレームで A・B 共通に
209    # 自動調整し、初期状態の高さ 1 によって平衡後の分布が潰れないようにする。
210    largest_money = max(
211        max(max(money_a), max(money_b))
212        for _, money_a, money_b in distribution_frames
213    )
214    bins = list(range(0, largest_money + DISPLAY_BIN_WIDTH + 1, DISPLAY_BIN_WIDTH))
215    if bins[-1] <= largest_money:
216        bins.append(bins[-1] + DISPLAY_BIN_WIDTH)
217
218    fig_dist, (ax_a, ax_b) = plt.subplots(
219        2, 1, figsize=(8, 6), sharex=True, sharey=True, constrained_layout=True
220    )
221
222    def draw_distribution(frame_index):
223        step, money_a, money_b = distribution_frames[frame_index]
224        count_a, _ = np.histogram(money_a, bins=bins)
225        count_b, _ = np.histogram(money_b, bins=bins)
226        y_max = 1.10 * max(count_a.max() / NA, count_b.max() / NB, 0.02)
227
228        ax_a.clear()
229        ax_b.clear()
230        ax_a.hist(
231            money_a,
232            bins=bins,
233            weights=[1 / NA] * NA,
234            color="tab:blue",
235            edgecolor="white",
236        )
237        ax_b.hist(
238            money_b,
239            bins=bins,
240            weights=[1 / NB] * NB,
241            color="tab:orange",
242            edgecolor="white",
243        )
244
245        ax_a.set_title(f"系 A の資産分布(sweep = {step})")
246        ax_b.set_title(f"系 B の資産分布(sweep = {step})")
247        ax_a.set_ylabel("確率")
248        ax_b.set_ylabel("確率")
249        ax_b.set_xlabel("一人あたりの資産 $m$")
250        for ax in (ax_a, ax_b):
251            ax.set_xlim(0, bins[-1])
252            ax.set_ylim(0, y_max)
253            ax.grid(alpha=0.25)
254
255    animation = FuncAnimation(
256        fig_dist,
257        draw_distribution,
258        frames=len(distribution_frames),
259        interval=ANIMATION_INTERVAL_MS,
260        repeat=True,
261        blit=False,
262    )
263    # 参照を figure にも保持し、アニメーションが破棄されないようにする。
264    fig_dist._distribution_animation = animation
265
266    print(f"初期値: H_A = {entropy_a_history[0]:.6f}, "
267          f"H_B = {entropy_b_history[0]:.6f}, "
268          f"H_all = {entropy_all_history[0]:.6f}")
269    print(f"最終値: H_A = {entropy_a_history[-1]:.6f}, "
270          f"H_B = {entropy_b_history[-1]:.6f}, "
271          f"H_all = {entropy_all_history[-1]:.6f}")
272    print(
273        f"分布アニメーション: 0 から {NITER} sweep まで、"
274        f"{ANIMATION_EVERY} sweep 間隔で表示します。"
275    )
276
277    plt.show()
278
279
280if __name__ == "__main__":
281    main()