trajectories.py ダウンロード/コピー
trajectories.py
trajectories.py
1"""
2概要:
3 1次元N粒子分子動力学シミュレータスクリプトです。
4詳細説明:
5 コマンドライン引数を受け取り、指定されたモードで粒子の時間発展シミュレーションを行い、
6 その結果をアニメーションとして保存します。
7関連リンク:
8 trajectories_usage
9"""
10import argparse
11import numpy as np
12import matplotlib.pyplot as plt
13from matplotlib.animation import FuncAnimation, PillowWriter
14
15# 力の定義:調和振動子 + 相互作用項(デフォルトは0)
16'''
17def fij(xi, x_list):
18 f = 0.0
19 for x2 in x_list:
20 f += 5.0e-3 * (xi - x2)**2
21 return f
22'''
23
24def fij(xi, x_list):
25 """
26 概要:
27 粒子間の相互作用力を計算します。
28 詳細説明:
29 デフォルトでは相互作用がないため、常に0.0を返します。
30 引数:
31 :param xi: 対象粒子の位置
32 :type xi: float
33 :param x_list: 全粒子の位置のリストまたは配列
34 :type x_list: numpy.ndarray
35 戻り値:
36 :returns: 計算された相互作用力
37 :rtype: float
38 """
39 return 0.0 # デフォルトでは相互作用なし
40
41def force(xi, x_list):
42 """
43 概要:
44 粒子に働く全力を計算します。
45 詳細説明:
46 調和振動子の復元力に、相互作用力を加えて返します。
47 引数:
48 :param xi: 対象粒子の位置
49 :type xi: float
50 :param x_list: 全粒子の位置
51 :type x_list: numpy.ndarray
52 戻り値:
53 :returns: 全力
54 :rtype: float
55 """
56 return -0.2 * xi + fij(xi, x_list)
57# return -0.2 * xi - 0.03 * xi * xi + fij(xi, x_list)
58
59# Verlet法による時間発展
60def verlet(x, v, dt, f_func):
61 """
62 概要:
63 Verlet法により粒子の位置と速度を1時間ステップ進めます。
64 詳細説明:
65 現在の位置、速度、時間ステップ、および力計算関数を用いて次のステップの状態を計算します。
66 引数:
67 :param x: 現在の粒子の位置
68 :type x: float
69 :param v: 現在の粒子の速度
70 :type v: float
71 :param dt: 時間ステップ
72 :type dt: float
73 :param f_func: 力を計算する関数
74 :type f_func: callable
75 戻り値:
76 :returns: 更新された位置と速度のタプル
77 :rtype: tuple
78 """
79 x_new = x + v * dt + 0.5 * f_func(x, x) * dt**2
80 f_new = f_func(x_new, x)
81 v_new = v + 0.5 * (f_func(x, x) + f_new) * dt
82 return x_new, v_new
83
84# アニメーション生成(mode=md)
85def animate_md(x_hist, p_hist, dt, filename, nplotinterval, pause):
86 """
87 概要:
88 位置および運動量の時間変化アニメーションを生成して保存します。
89 詳細説明:
90 時間経過に伴う各粒子の位置xと運動量pの変化を描画し、GIF形式で保存します。
91 引数:
92 :param x_hist: 位置の履歴データ
93 :type x_hist: numpy.ndarray
94 :param p_hist: 運動量の履歴データ
95 :type p_hist: numpy.ndarray
96 :param dt: 時間ステップ
97 :type dt: float
98 :param filename: 保存するアニメーションのファイル名
99 :type filename: str
100 :param nplotinterval: 描画を更新するステップ間隔
101 :type nplotinterval: int
102 :param pause: 描画更新時のポーズ時間
103 :type pause: float
104 """
105 fig, ax = plt.subplots(2, 1, figsize=(6, 6))
106 lines_x = [ax[0].plot([], [], label=f'Particle {i}')[0] for i in range(x_hist.shape[1])]
107 lines_p = [ax[1].plot([], [], label=f'Particle {i}')[0] for i in range(p_hist.shape[1])]
108 ax[0].set_xlim(0, dt * x_hist.shape[0])
109 ax[1].set_xlim(0, dt * x_hist.shape[0])
110 ax[0].set_ylim(np.min(x_hist), np.max(x_hist))
111 ax[1].set_ylim(np.min(p_hist), np.max(p_hist))
112 ax[0].set_ylabel('x')
113 ax[1].set_ylabel('p')
114 ax[1].set_xlabel('t')
115 ax[0].legend()
116 ax[1].legend()
117
118 istep = 0
119 def update(frame):
120 nonlocal istep
121 t = np.arange(frame + 1) * dt
122 for i, line in enumerate(lines_x):
123 line.set_data(t, x_hist[:frame + 1, i])
124 for i, line in enumerate(lines_p):
125 line.set_data(t, p_hist[:frame + 1, i])
126 if istep % nplotinterval == 0:
127 print(f"[DEBUG] Frame {frame+1}/{x_hist.shape[0]}")
128 plt.pause(pause)
129 istep += 1
130 return lines_x + lines_p
131
132 ani = FuncAnimation(fig, update, frames=x_hist.shape[0], interval=50)
133 ani.save(filename, writer=PillowWriter(fps=20))
134 plt.close()
135
136# アニメーション生成(mode=trajectory)
137def animate_trajectory(x_hist, p_hist, filename, nplotinterval, pause):
138 """
139 概要:
140 位相空間における軌跡のアニメーションを生成して保存します。
141 詳細説明:
142 位置xと運動量pを軸とした位相空間上の粒子の軌跡を描画し、GIF形式で保存します。
143 引数:
144 :param x_hist: 位置の履歴データ
145 :type x_hist: numpy.ndarray
146 :param p_hist: 運動量の履歴データ
147 :type p_hist: numpy.ndarray
148 :param filename: 保存するアニメーションのファイル名
149 :type filename: str
150 :param nplotinterval: 描画を更新するステップ間隔
151 :type nplotinterval: int
152 :param pause: 描画更新時のポーズ時間
153 :type pause: float
154 """
155 print("[INFO] Trajectory animation started...")
156 fig, ax = plt.subplots(figsize=(6, 6))
157 ax.set_xlim(np.min(x_hist) - 1, np.max(x_hist) + 1)
158 ax.set_ylim(np.min(p_hist) - 1, np.max(p_hist) + 1)
159 ax.set_xlabel('x')
160 ax.set_ylabel('p')
161 ax.set_title('Phase Space Trajectory')
162
163 N = x_hist.shape[1]
164 scat = ax.scatter([], [], color='red') # 始点用
165 lines = [ax.plot([], [], lw=1)[0] for _ in range(N)] # 軌跡用
166
167 istep = 0
168 def update(frame):
169 nonlocal istep
170 # 始点を赤丸で表示
171 scat.set_offsets(np.c_[x_hist[0], p_hist[0]])
172 # 各粒子の軌跡を更新
173 for i in range(N):
174 lines[i].set_data(x_hist[:frame + 1, i], p_hist[:frame + 1, i])
175 if istep % nplotinterval == 0:
176 print(f"[DEBUG] Frame {frame+1}/{x_hist.shape[0]}")
177 plt.pause(pause)
178 istep += 1
179 return [scat] + lines
180
181 ani = FuncAnimation(fig, update, frames=x_hist.shape[0], interval=50)
182 print(f"[INFO] Saving animation to {filename}...")
183 ani.save(filename, writer=PillowWriter(fps=20))
184 print("[INFO] Animation saved successfully.")
185 plt.close()
186
187# メイン関数
188def main():
189 """
190 概要:
191 スクリプトのメインエントリーポイントです。
192 詳細説明:
193 コマンドライン引数を解析し、初期位置と速度をランダムに生成してシミュレーションを実行します。
194 その後、指定されたモードに応じてアニメーションを生成します。
195 """
196 parser = argparse.ArgumentParser(description='1D N-particle MD simulator')
197 parser.add_argument('--N', type=int, default=5, help='Number of particles')
198 parser.add_argument('--dt', type=float, default=0.05, help='Time step')
199 parser.add_argument('--nstep', type=int, default=200, help='Number of steps')
200 parser.add_argument('--nplotinterval', type=int, default=10, help='Number of steps to update graph')
201 parser.add_argument('--tpause', type=float, default=1.0e-3, help='time to sleep for update()')
202 parser.add_argument('--seed', type=int, default=42, help='Random seed')
203 parser.add_argument('--mode', type=str, default='md', choices=['md', 'trajectory'], help='Simulation mode')
204 args = parser.parse_args()
205
206 np.random.seed(args.seed)
207 x = np.random.randn(args.N)
208 v = np.random.randn(args.N)
209 x_hist = np.zeros((args.nstep, args.N))
210 p_hist = np.zeros((args.nstep, args.N))
211
212 for step in range(args.nstep):
213 x_hist[step] = x
214 p_hist[step] = v # 質量1なので運動量p = v
215 for i in range(args.N):
216 xi, vi = x[i], v[i]
217 x_new, v_new = verlet(xi, vi, args.dt, lambda xi_, x_: force(xi_, x))
218 x[i], v[i] = x_new, v_new
219
220 if args.mode == 'md':
221 animate_md(x_hist, p_hist, args.dt, 'md_simulation.gif', args.nplotinterval, args.tpause)
222 else:
223 animate_trajectory(x_hist, p_hist, 'trajectory.gif', args.nplotinterval, args.tpause)
224
225if __name__ == '__main__':
226 main()