randommoney2.py ダウンロード/コピー
randommoney2.py
randommoney2.py
1#!/usr/bin/env python3
2"""
3概要:
4 外部からのランダムな増減を受ける資産モデルのシミュレーションを行います。
5詳細説明:
6 各個人の資産が独立して外部からのランダムな変動を受ける様子を計算し、可視化します。
7 シミュレーション結果は画面表示のほか、PNG画像やGIFアニメーションとして保存できます。
8関連リンク:
9 randommoney2_usage
10"""
11
12import argparse
13import random
14from math import log
15from pathlib import Path
16
17import matplotlib as mpl
18from matplotlib import pyplot as plt
19from matplotlib.animation import FuncAnimation, PillowWriter
20
21
22mpl.rcParams.update({
23 "font.family": ["Yu Mincho", "MS Mincho", "serif"],
24 "axes.unicode_minus": False,
25 "text.usetex": False,
26})
27
28
29def parse_args():
30 """
31 概要:
32 比較用プログラムと共通のコマンドライン引数を解析します。
33 詳細説明:
34 argparseを使用して、人数や初期資産、外部変動の最大値、スイープ数などのパラメータを設定します。
35 戻り値:
36 :returns: 解析されたコマンドライン引数を格納した名前空間オブジェクト。
37 :rtype: argparse.Namespace
38 """
39 parser = argparse.ArgumentParser(description="外部ランダム変動を受ける資産分布を可視化します。")
40 parser.add_argument("--npersons", type=int, default=200, help="人数(既定値: 200)")
41 parser.add_argument("--value", type=float, default=100, help="一人当たりの初期資産(既定値: 10)")
42 parser.add_argument(
43 "--vtrade", type=float, default=1,
44 help="一回の外部変動の最大絶対値。Δm は [-vtrade, +vtrade](既定値: 1)",
45 )
46 parser.add_argument("--niter", type=int, default=100000, help="スイープ数(既定値: 100000)")
47 parser.add_argument("--record-every", type=int, default=100, help="状態を記録する間隔(既定値: 100)")
48 parser.add_argument("--nbins", type=int, default=21, help="資産分布のビン数(既定値: 21)")
49 parser.add_argument("--interval", type=int, default=200, help="GIF のフレーム間隔 [ms](既定値: 200)")
50 parser.add_argument("--gif-fps", type=int, default=5, help="GIF の毎秒フレーム数(既定値: 5)")
51 parser.add_argument("--seed", type=int, default=None, help="乱数シード")
52 parser.add_argument("--save-png", type=Path, metavar="FILE", help="最終状態を PNG 保存")
53 parser.add_argument("--save-gif", type=Path, metavar="FILE", help="時間発展を GIF 保存")
54 parser.add_argument("--dpi", type=int, default=150, help="保存画像の dpi(既定値: 150)")
55 parser.add_argument("--no-show", action="store_true", help="画面にグラフを表示しない")
56 args = parser.parse_args()
57 if args.npersons <= 0 or args.value < 0 or args.vtrade <= 0:
58 parser.error("--npersons は正、--value は非負、--vtrade は正にしてください。")
59 if args.niter < 0 or args.record_every <= 0 or args.nbins < 2:
60 parser.error("--niter は非負、--record-every は正、--nbins は 2 以上にしてください。")
61 return args
62
63
64def fluctuate_one_sweep(money, amplitude, rng):
65 """
66 概要:
67 全員の資産へ独立な一様乱数の増減を加えます。
68 詳細説明:
69 各個人の資産に対して、指定された振幅の範囲内でランダムな増減を行います。
70 資産は負にならないように0.0で下限が設定されます。
71 引数:
72 :param money: 各個人の資産を格納したリスト。
73 :type money: list
74 :param amplitude: 一回の変動の最大絶対値。
75 :type amplitude: float
76 :param rng: 乱数生成器オブジェクト。
77 :type rng: random.Random
78 戻り値:
79 :returns: 戻り値はありません。
80 :rtype: None
81 """
82 for index in range(len(money)):
83 money[index] = max(0.0, money[index] + rng.uniform(-amplitude, amplitude))
84
85
86def shannon_entropy(money, nbins, hist_max):
87 """
88 概要:
89 固定ビンの資産分布からシャノンエントロピーを計算します。
90 詳細説明:
91 ヒストグラムの最大値とビン数からビン幅を求め、各ビンに含まれる資産の割合を確率として計算します。
92 H = -Σp log(p) の式を用いてエントロピーを算出します。
93 引数:
94 :param money: 各個人の資産を格納したリスト。
95 :type money: list
96 :param nbins: ヒストグラムのビン数。
97 :type nbins: int
98 :param hist_max: ヒストグラムの最大値。
99 :type hist_max: float
100 戻り値:
101 :returns: 計算されたシャノンエントロピーの値。
102 :rtype: float
103 """
104 counts = [0] * nbins
105 bin_width = hist_max / nbins
106 for amount in money:
107 index = min(int(amount / bin_width), nbins - 1)
108 counts[index] += 1
109 probabilities = [count / len(money) for count in counts if count > 0]
110 return -sum(p * log(p) for p in probabilities)
111
112
113def draw_state(axes, frame_index, frames, entropy_history, args, hist_max):
114 """
115 概要:
116 指定されたフレームのシミュレーション状態をグラフに描画します。
117 詳細説明:
118 4つのサブプロットに対し、現在の資産分布、昇順に並べた資産、ヒストグラム、およびシャノンエントロピーの時間発展を描画します。
119 引数:
120 :param axes: 描画先のAxesオブジェクトのリスト。
121 :type axes: list
122 :param frame_index: 描画対象のフレームインデックス。
123 :type frame_index: int
124 :param frames: 記録されたスイープ数と資産リストのタプルを格納したリスト。
125 :type frames: list
126 :param entropy_history: 各フレームにおけるエントロピーの履歴リスト。
127 :type entropy_history: list
128 :param args: コマンドライン引数を格納した名前空間オブジェクト。
129 :type args: argparse.Namespace
130 :param hist_max: ヒストグラムの最大値。
131 :type hist_max: float
132 戻り値:
133 :returns: 戻り値はありません。
134 :rtype: None
135 """
136 ax1, ax2, ax3, ax4 = axes
137 for ax in axes:
138 ax.clear()
139
140 sweep, money = frames[frame_index]
141 n = args.npersons
142 sorted_money = sorted(money)
143 average = sum(money) / n
144
145 ax1.bar(range(n), money, width=1.0)
146 ax1.axhline(average, linestyle="--", color="red", linewidth=0.8, label="現在の平均")
147 ax1.set_title(f"外部ランダム変動(sweep = {sweep}/{args.niter}, N = {n})")
148 ax1.set_xlabel("個人 i")
149 ax1.set_ylabel("資産")
150 ax1.set_xlim(-0.5, n - 0.5)
151 ax1.legend(loc="upper right")
152
153 ax2.bar(range(n), sorted_money, width=1.0)
154 ax2.axhline(average, linestyle="--", color="red", linewidth=0.8, label="現在の平均")
155 ax2.set_xlabel("順位 i")
156 ax2.set_ylabel("資産(昇順)")
157 ax2.set_xlim(-0.5, n - 0.5)
158 ax2.legend(loc="upper right")
159
160 counts, _, _ = ax3.hist(money, bins=args.nbins, range=(0, hist_max), density=True,
161 histtype="stepfilled", alpha=0.45, label="シミュレーション")
162 ax3.set_xlabel("一人あたりの資産 m")
163 ax3.set_ylabel("確率密度")
164 ax3.set_xlim(0, hist_max)
165 ymax = max(max(counts, default=0), 1e-12)
166 ax3.set_ylim(0, 1.15 * ymax)
167 ax3.legend(loc="upper right")
168
169 sweeps = [item[0] for item in frames[:frame_index + 1]]
170 ax4.plot(sweeps, entropy_history[:frame_index + 1], color="green")
171 ax4.set_title(r"資産分布の Shannon エントロピー $H=-\sum_j p_j\log p_j$")
172 ax4.set_xlabel("スイープ数")
173 ax4.set_ylabel("H")
174 ax4.set_xlim(0, max(args.niter, 1))
175 ax4.set_ylim(0, max(log(args.nbins) * 1.05, max(entropy_history, default=0) * 1.05, 1))
176
177
178def prepare_output(path):
179 """
180 概要:
181 出力先ファイルの親ディレクトリを作成します。
182 詳細説明:
183 指定されたパスの親ディレクトリが存在しない場合は新しく作成します。
184 引数:
185 :param path: 出力先ファイルのパスオブジェクト。
186 :type path: pathlib.Path
187 戻り値:
188 :returns: 戻り値はありません。
189 :rtype: None
190 """
191 path.parent.mkdir(parents=True, exist_ok=True)
192
193
194def main():
195 """
196 概要:
197 プログラムのメイン処理を実行します。
198 詳細説明:
199 引数の解析、シミュレーションの実行、データの記録を行い、最終的にグラフの描画やファイル保存を処理します。
200 戻り値:
201 :returns: 戻り値はありません。
202 :rtype: None
203 例外:
204 :raises RuntimeError: GIF保存時にPillowがインストールされていない場合に発生します。
205 """
206 args = parse_args()
207 rng = random.Random(args.seed)
208 money = [args.value] * args.npersons
209 frames = [(0, money.copy())]
210
211 for sweep in range(1, args.niter + 1):
212 fluctuate_one_sweep(money, args.vtrade, rng)
213 if sweep % args.record_every == 0 or sweep == args.niter:
214 frames.append((sweep, money.copy()))
215
216 # 全記録時刻の最大資産を共通上限にするので、ビン範囲は全フレームで固定される。
217 hist_max = max(max(values) for _, values in frames)
218 hist_max = max(float(hist_max), 1.0)
219 entropy_history = [shannon_entropy(values, args.nbins, hist_max) for _, values in frames]
220
221 fig, axes = plt.subplots(4, 1, figsize=(6, 8), constrained_layout=True)
222 draw_state(axes, len(frames) - 1, frames, entropy_history, args, hist_max)
223
224 if args.save_png:
225 prepare_output(args.save_png)
226 fig.savefig(args.save_png, dpi=args.dpi, bbox_inches="tight")
227 print(f"PNG を保存しました: {args.save_png}")
228
229 if args.save_gif:
230 prepare_output(args.save_gif)
231
232 def update(frame_index):
233 draw_state(axes, frame_index, frames, entropy_history, args, hist_max)
234 return axes
235
236 animation = FuncAnimation(fig, update, frames=len(frames), interval=args.interval, repeat=True)
237 try:
238 animation.save(args.save_gif, writer=PillowWriter(fps=args.gif_fps), dpi=args.dpi)
239 except (ImportError, ModuleNotFoundError) as exc:
240 raise RuntimeError("GIF 保存には Pillow が必要です: python -m pip install pillow") from exc
241 print(f"GIF を保存しました: {args.save_gif}")
242
243 if not args.no_show:
244 plt.show()
245
246
247if __name__ == "__main__":
248 main()