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

randomtrade_numpy.py をダウンロード

randomtrade_numpy.py
randomtrade_numpy.py
  1"""
  2概要:
  3    ランダムな取引による資産分布の統計的変化をシミュレーションします。
  4詳細説明:
  5    全員が同じ資産を持つ状態からスタートし、ランダムに選ばれた相手に一定額を渡すサイクルを繰り返します。
  6    取引の経過とともに資産の分布が指数分布に近づく様子や、エントロピーの推移を可視化します。
  7関連リンク:
  8    randomtrade_numpy_usage
  9"""
 10
 11import sys
 12import numpy as np
 13from math import exp
 14from matplotlib import pyplot as plt
 15import matplotlib
 16
 17# MS Gothic フォント設定(日本語表示対応)
 18matplotlib.rcParams['font.family'] = 'MS Gothic'
 19
 20"""
 21Statistical results of random trade:
 22Start from the uniform situation where everyone has the same money,
 23repeat the cycle to exchange a constant dollars with a randomly selected person.
 24"""
 25
 26#=============================
 27# 大域変数の定義
 28#=============================
 29npersons = 50
 30value    = 50
 31vtrade   = 1
 32niter    = 500
 33nplotinterval = 100
 34nfx = 21
 35
 36# Treat arguments
 37argv = sys.argv
 38if len(argv) == 1:
 39    print("Usage: python randomtrade_numpy.py npersons value vtrade niter nplotinterval nfx")
 40    print("   ex: python randomtrade_numpy.py 200 50 1 10000 100 21")
 41    exit()
 42
 43if len(argv) >= 2:
 44    npersons = int(argv[1])
 45if len(argv) >= 3:
 46    value = int(argv[2])
 47if len(argv) >= 4:
 48    vtrade = int(argv[3])
 49if len(argv) >= 5:
 50    niter = int(argv[4])
 51if len(argv) >= 6:
 52    nplotinterval = int(argv[5])
 53if len(argv) >= 7:
 54    nfx = int(argv[6])
 55
 56# エントロピー計算関数(NumPyベース)
 57def calc_entropy(fy):
 58    """
 59    概要:
 60        度数分布からエントロピーを計算します。
 61    詳細説明:
 62        入力された度数配列を確率分布に変換し、0より大きい要素についてエントロピーを計算します。
 63    引数:
 64        :param fy: 度数を格納した配列。
 65        :type fy: numpy.ndarray
 66    戻り値:
 67        :returns: 計算されたエントロピーの値。
 68        :rtype: float
 69    """
 70    p = fy / np.sum(fy)
 71    p = p[p > 0]
 72    return -np.sum(p * np.log(p))
 73
 74def main():
 75    """
 76    概要:
 77        ランダムトレードのシミュレーションを実行し結果をプロットします。
 78    詳細説明:
 79        コマンドライン引数から大域変数に設定されたシミュレーション条件を使用し、資産のランダムな交換を繰り返します。
 80        指定されたインターバルごとに、各人の資産、ソート済み資産、資産の度数分布、およびエントロピーの推移を描画します。
 81    戻り値:
 82        :returns: 戻り値はありません。
 83        :rtype: None
 84    """
 85    xindex = np.arange(npersons)
 86    v = np.full(npersons, value, dtype=float)
 87
 88    print("")
 89    print("Analyatical distribution:")
 90    xmax = value * 10.0
 91    nftx = 101
 92    xstep = xmax / (nftx - 1)
 93    b = 1.0 / value
 94    A = npersons * b
 95    print("  x range: 0 - %g" % (xmax))
 96    print("  x step: %g" % (xstep))
 97    print("  f(x) = %g * exp(-%g * x)" % (A, b))
 98    ftx = np.linspace(0, xmax, nftx+1)
 99    fty = A * np.exp(-b * ftx)
100
101    fig = plt.figure(figsize=(8, 10))
102    ax1 = fig.add_subplot(4, 1, 1)
103    ax2 = fig.add_subplot(4, 1, 2)
104    ax3 = fig.add_subplot(4, 1, 3)
105    ax4 = fig.add_subplot(4, 1, 4)
106    
107    entropy_history = []
108    step_history = []
109
110    for i in range(niter):
111        # 元のプログラムに合わせて、ipは全員を順番に処理し、渡す相手(itarget)のみランダムに決定する
112        itargets = np.random.randint(0, npersons, size=npersons)
113        for ip, itarget in enumerate(itargets):
114            if v[ip] >= vtrade:
115                v[ip] -= vtrade
116                v[itarget] += vtrade
117            else:
118                v[itarget] += v[ip]
119                v[ip] = 0
120
121        if i == 0 or (i+1) % nplotinterval == 0 or i == niter - 1:
122            vs = np.sort(v)
123            vmax = np.max(v)
124            
125            # density=Trueを使わず度数を取得し、ビン幅(vstep)で割ることで理論式とスケールを合わせる
126            counts, bin_edges = np.histogram(vs, bins=nfx, range=(0, vmax))
127            vstep = bin_edges[1] - bin_edges[0]
128            if vstep > 0:
129                fy = counts / vstep
130            else:
131                fy = counts.astype(float)
132            fx = bin_edges[:-1]
133
134            # エントロピーとステップ数を記録
135            entropy = calc_entropy(fy)
136            entropy_history.append(entropy)
137            step_history.append(i + 1)
138
139            ax1.cla()
140            ax2.cla()
141            ax3.cla()
142            ax4.cla()
143
144            ax1.bar(xindex, v, width = 1.5)
145            ax1.plot([0, npersons], [value, value], linestyle = 'dashed', color = 'red', linewidth = 0.5)
146            ax1.set_title('Random trade (i = %d/%d, n=%d, avg=%d)' % (i+1, niter, npersons, value))
147            ax1.set_xlabel("i")
148            ax1.set_ylabel("value")
149            ax1.set_xlim([0, npersons])
150
151            ax2.bar(xindex, vs, width = 1.5)
152            ax2.plot([0, npersons], [value, value], linestyle = 'dashed', color = 'red', linewidth = 0.5)
153            ax2.set_xlim([0, npersons])
154            ax2.set_xlabel("i")
155            ax2.set_ylabel("value (sorted)")
156
157            ax3.plot(fx, fy, label = 'distrib')
158            ax3.plot(ftx, fty, label = 'exponential', color = "red", linewidth = 0.5, linestyle = 'dashed')
159            ax3.set_xlim([0, vmax])
160            # 理論値の最大値(A)が実データより大きい場合でも見切れないように調整
161            ax3.set_ylim([0, max(np.max(fy), A) + 1])
162            ax3.set_xlabel("value")
163            ax3.set_ylabel("frequency / value")
164            ax3.legend()
165
166            # ステップ数をX軸として描画
167            ax4.plot(step_history, entropy_history, color='green')
168            ax4.set_title("エントロピーの推移 S = -ΣP log P")
169            ax4.set_xlabel("ステップ")
170            ax4.set_ylabel("エントロピー")
171            ax4.set_xlim([0, niter])
172            # エントロピーの下限上限を適正化
173            ax4.set_ylim([0, max(entropy_history) * 1.2 if entropy_history else 3.0])
174
175            plt.tight_layout()
176            plt.pause(0.1)
177
178    print("Press ENTER to exit>>", end = '')
179    input()
180
181if __name__ == '__main__':
182    main()