""" 概要: 1次元N粒子分子動力学シミュレータスクリプトです。 詳細説明: コマンドライン引数を受け取り、指定されたモードで粒子の時間発展シミュレーションを行い、 その結果をアニメーションとして保存します。 関連リンク: trajectories_usage """ import argparse import numpy as np import matplotlib.pyplot as plt from matplotlib.animation import FuncAnimation, PillowWriter # 力の定義:調和振動子 + 相互作用項(デフォルトは0) ''' def fij(xi, x_list): f = 0.0 for x2 in x_list: f += 5.0e-3 * (xi - x2)**2 return f ''' def fij(xi, x_list): """ 概要: 粒子間の相互作用力を計算します。 詳細説明: デフォルトでは相互作用がないため、常に0.0を返します。 引数: :param xi: 対象粒子の位置 :type xi: float :param x_list: 全粒子の位置のリストまたは配列 :type x_list: numpy.ndarray 戻り値: :returns: 計算された相互作用力 :rtype: float """ return 0.0 # デフォルトでは相互作用なし def force(xi, x_list): """ 概要: 粒子に働く全力を計算します。 詳細説明: 調和振動子の復元力に、相互作用力を加えて返します。 引数: :param xi: 対象粒子の位置 :type xi: float :param x_list: 全粒子の位置 :type x_list: numpy.ndarray 戻り値: :returns: 全力 :rtype: float """ return -0.2 * xi + fij(xi, x_list) # return -0.2 * xi - 0.03 * xi * xi + fij(xi, x_list) # Verlet法による時間発展 def verlet(x, v, dt, f_func): """ 概要: Verlet法により粒子の位置と速度を1時間ステップ進めます。 詳細説明: 現在の位置、速度、時間ステップ、および力計算関数を用いて次のステップの状態を計算します。 引数: :param x: 現在の粒子の位置 :type x: float :param v: 現在の粒子の速度 :type v: float :param dt: 時間ステップ :type dt: float :param f_func: 力を計算する関数 :type f_func: callable 戻り値: :returns: 更新された位置と速度のタプル :rtype: tuple """ x_new = x + v * dt + 0.5 * f_func(x, x) * dt**2 f_new = f_func(x_new, x) v_new = v + 0.5 * (f_func(x, x) + f_new) * dt return x_new, v_new # アニメーション生成(mode=md) def animate_md(x_hist, p_hist, dt, filename, nplotinterval, pause): """ 概要: 位置および運動量の時間変化アニメーションを生成して保存します。 詳細説明: 時間経過に伴う各粒子の位置xと運動量pの変化を描画し、GIF形式で保存します。 引数: :param x_hist: 位置の履歴データ :type x_hist: numpy.ndarray :param p_hist: 運動量の履歴データ :type p_hist: numpy.ndarray :param dt: 時間ステップ :type dt: float :param filename: 保存するアニメーションのファイル名 :type filename: str :param nplotinterval: 描画を更新するステップ間隔 :type nplotinterval: int :param pause: 描画更新時のポーズ時間 :type pause: float """ fig, ax = plt.subplots(2, 1, figsize=(6, 6)) lines_x = [ax[0].plot([], [], label=f'Particle {i}')[0] for i in range(x_hist.shape[1])] lines_p = [ax[1].plot([], [], label=f'Particle {i}')[0] for i in range(p_hist.shape[1])] ax[0].set_xlim(0, dt * x_hist.shape[0]) ax[1].set_xlim(0, dt * x_hist.shape[0]) ax[0].set_ylim(np.min(x_hist), np.max(x_hist)) ax[1].set_ylim(np.min(p_hist), np.max(p_hist)) ax[0].set_ylabel('x') ax[1].set_ylabel('p') ax[1].set_xlabel('t') ax[0].legend() ax[1].legend() istep = 0 def update(frame): nonlocal istep t = np.arange(frame + 1) * dt for i, line in enumerate(lines_x): line.set_data(t, x_hist[:frame + 1, i]) for i, line in enumerate(lines_p): line.set_data(t, p_hist[:frame + 1, i]) if istep % nplotinterval == 0: print(f"[DEBUG] Frame {frame+1}/{x_hist.shape[0]}") plt.pause(pause) istep += 1 return lines_x + lines_p ani = FuncAnimation(fig, update, frames=x_hist.shape[0], interval=50) ani.save(filename, writer=PillowWriter(fps=20)) plt.close() # アニメーション生成(mode=trajectory) def animate_trajectory(x_hist, p_hist, filename, nplotinterval, pause): """ 概要: 位相空間における軌跡のアニメーションを生成して保存します。 詳細説明: 位置xと運動量pを軸とした位相空間上の粒子の軌跡を描画し、GIF形式で保存します。 引数: :param x_hist: 位置の履歴データ :type x_hist: numpy.ndarray :param p_hist: 運動量の履歴データ :type p_hist: numpy.ndarray :param filename: 保存するアニメーションのファイル名 :type filename: str :param nplotinterval: 描画を更新するステップ間隔 :type nplotinterval: int :param pause: 描画更新時のポーズ時間 :type pause: float """ print("[INFO] Trajectory animation started...") fig, ax = plt.subplots(figsize=(6, 6)) ax.set_xlim(np.min(x_hist) - 1, np.max(x_hist) + 1) ax.set_ylim(np.min(p_hist) - 1, np.max(p_hist) + 1) ax.set_xlabel('x') ax.set_ylabel('p') ax.set_title('Phase Space Trajectory') N = x_hist.shape[1] scat = ax.scatter([], [], color='red') # 始点用 lines = [ax.plot([], [], lw=1)[0] for _ in range(N)] # 軌跡用 istep = 0 def update(frame): nonlocal istep # 始点を赤丸で表示 scat.set_offsets(np.c_[x_hist[0], p_hist[0]]) # 各粒子の軌跡を更新 for i in range(N): lines[i].set_data(x_hist[:frame + 1, i], p_hist[:frame + 1, i]) if istep % nplotinterval == 0: print(f"[DEBUG] Frame {frame+1}/{x_hist.shape[0]}") plt.pause(pause) istep += 1 return [scat] + lines ani = FuncAnimation(fig, update, frames=x_hist.shape[0], interval=50) print(f"[INFO] Saving animation to {filename}...") ani.save(filename, writer=PillowWriter(fps=20)) print("[INFO] Animation saved successfully.") plt.close() # メイン関数 def main(): """ 概要: スクリプトのメインエントリーポイントです。 詳細説明: コマンドライン引数を解析し、初期位置と速度をランダムに生成してシミュレーションを実行します。 その後、指定されたモードに応じてアニメーションを生成します。 """ parser = argparse.ArgumentParser(description='1D N-particle MD simulator') parser.add_argument('--N', type=int, default=5, help='Number of particles') parser.add_argument('--dt', type=float, default=0.05, help='Time step') parser.add_argument('--nstep', type=int, default=200, help='Number of steps') parser.add_argument('--nplotinterval', type=int, default=10, help='Number of steps to update graph') parser.add_argument('--tpause', type=float, default=1.0e-3, help='time to sleep for update()') parser.add_argument('--seed', type=int, default=42, help='Random seed') parser.add_argument('--mode', type=str, default='md', choices=['md', 'trajectory'], help='Simulation mode') args = parser.parse_args() np.random.seed(args.seed) x = np.random.randn(args.N) v = np.random.randn(args.N) x_hist = np.zeros((args.nstep, args.N)) p_hist = np.zeros((args.nstep, args.N)) for step in range(args.nstep): x_hist[step] = x p_hist[step] = v # 質量1なので運動量p = v for i in range(args.N): xi, vi = x[i], v[i] x_new, v_new = verlet(xi, vi, args.dt, lambda xi_, x_: force(xi_, x)) x[i], v[i] = x_new, v_new if args.mode == 'md': animate_md(x_hist, p_hist, args.dt, 'md_simulation.gif', args.nplotinterval, args.tpause) else: animate_trajectory(x_hist, p_hist, 'trajectory.gif', args.nplotinterval, args.tpause) if __name__ == '__main__': main()