anharmonic_lattice_md_mc.py ダウンロード/コピー
anharmonic_lattice_md_mc.py をダウンロード
anharmonic_lattice_md_mc.py
anharmonic_lattice_md_mc.py
1#!/usr/bin/env python3
2"""
3概要:
4 2次元非調和格子のNVT分子動力学とメトロポリスモンテカルロ法を比較します。
5
6詳細説明:
7 L x Lの正方格子の各サイトはスカラー変位 u[i,j] を持ちます。
8 周期境界条件を使用し、換算単位系 (m=k_B=1) におけるポテンシャルは
9 V = K0/2 sum_i u_i^2 + sum_ij (K2/2 (u_i-u_j)^2 + K4/4 (u_i-u_j)^4)
10 で表されます。
11 K4=0 の場合は調和格子となり、基準振動モードは散乱しません。
12 K4>0 の場合は基準振動モードが結合し、本質的な非調和散乱が生じます。
13 弱いオンサイト項 K0 は、並進ゼロモードによる変位MSDの発散を防ぎます。
14 MDはLangevin (BAOAB) サーモスタットを使用し、MCは同じカノニカル座標分布から
15 サンプリングを行います。MCの運動量が有効な場合、それらは独立したマクスウェル
16 分布からの抽出であり、力学的軌道ではありません。
17"""
18
19from __future__ import annotations
20
21import argparse
22from dataclasses import dataclass
23
24import matplotlib.pyplot as plt
25import numpy as np
26
27
28@dataclass
29class Samples:
30 """
31 概要:
32 シミュレーションのサンプリング結果を保持するデータクラスです。
33
34 詳細説明:
35 時間やエネルギー、変位の統計量、およびスナップショットを格納します。
36
37 引数:
38 :param time: サンプリングされた時間の配列
39 :type time: numpy.ndarray
40 :param potential: ポテンシャルエネルギーの配列
41 :type potential: numpy.ndarray
42 :param kinetic: 運動エネルギーの配列
43 :type kinetic: numpy.ndarray
44 :param msd: 平均二乗変位の配列
45 :type msd: numpy.ndarray
46 :param v2: 速度の二乗平均の配列
47 :type v2: numpy.ndarray
48 :param u_snapshots: 変位のスナップショット配列
49 :type u_snapshots: numpy.ndarray
50 """
51 time: np.ndarray
52 potential: np.ndarray
53 kinetic: np.ndarray
54 msd: np.ndarray
55 v2: np.ndarray
56 u_snapshots: np.ndarray
57
58
59def bond_energy(delta: np.ndarray | float, k2: float, k4: float) -> np.ndarray | float:
60 """
61 概要:
62 隣接サイト間のボンドエネルギーを計算します。
63
64 引数:
65 :param delta: 変位の差
66 :type delta: numpy.ndarray | float
67 :param k2: 調和ボンド係数
68 :type k2: float
69 :param k4: 4次の非調和ボンド係数
70 :type k4: float
71
72 戻り値:
73 :returns: ボンドエネルギーの計算結果
74 :rtype: numpy.ndarray | float
75 """
76 return 0.5 * k2 * delta**2 + 0.25 * k4 * delta**4
77
78
79def potential_energy(u: np.ndarray, k0: float, k2: float, k4: float) -> float:
80 """
81 概要:
82 格子全体のポテンシャルエネルギーを計算します。
83
84 詳細説明:
85 各 +x 方向および +y 方向のボンドについてエネルギーを一度ずつカウントします。
86
87 引数:
88 :param u: 格子の変位配列
89 :type u: numpy.ndarray
90 :param k0: オンサイト調和ポテンシャル係数
91 :type k0: float
92 :param k2: 調和ボンド係数
93 :type k2: float
94 :param k4: 4次の非調和ボンド係数
95 :type k4: float
96
97 戻り値:
98 :returns: 計算された全ポテンシャルエネルギー
99 :rtype: float
100 """
101 dx = np.roll(u, -1, axis=0) - u
102 dy = np.roll(u, -1, axis=1) - u
103 return float(0.5 * k0 * np.sum(u**2)
104 + np.sum(bond_energy(dx, k2, k4))
105 + np.sum(bond_energy(dy, k2, k4)))
106
107
108def force(u: np.ndarray, k0: float, k2: float, k4: float) -> np.ndarray:
109 """
110 概要:
111 周期境界条件を持つ格子のポテンシャルの負の勾配を計算して力を返します。
112
113 引数:
114 :param u: 格子の変位配列
115 :type u: numpy.ndarray
116 :param k0: オンサイト調和ポテンシャル係数
117 :type k0: float
118 :param k2: 調和ボンド係数
119 :type k2: float
120 :param k4: 4次の非調和ボンド係数
121 :type k4: float
122
123 戻り値:
124 :returns: 各サイトに働く力の配列
125 :rtype: numpy.ndarray
126 """
127 f = -k0 * u
128 for axis in (0, 1):
129 forward = np.roll(u, -1, axis=axis) - u
130 backward = u - np.roll(u, 1, axis=axis)
131 f += k2 * forward + k4 * forward**3
132 f -= k2 * backward + k4 * backward**3
133 return f
134
135
136def langevin_baoab_step(u: np.ndarray, v: np.ndarray, dt: float, gamma: float,
137 temperature: float, k0: float, k2: float, k4: float,
138 rng: np.random.Generator) -> tuple[np.ndarray, np.ndarray]:
139 """
140 概要:
141 単位質量および k_B = 1 の条件でBAOAB法による1ステップの更新を行います。
142
143 引数:
144 :param u: 現在の変位配列
145 :type u: numpy.ndarray
146 :param v: 現在の速度配列
147 :type v: numpy.ndarray
148 :param dt: タイムステップ
149 :type dt: float
150 :param gamma: ランジュバン摩擦係数
151 :type gamma: float
152 :param temperature: 設定温度
153 :type temperature: float
154 :param k0: オンサイト調和ポテンシャル係数
155 :type k0: float
156 :param k2: 調和ボンド係数
157 :type k2: float
158 :param k4: 4次の非調和ボンド係数
159 :type k4: float
160 :param rng: 乱数生成器
161 :type rng: numpy.random.Generator
162
163 戻り値:
164 :returns: 更新後の変位配列と速度配列のタプル
165 :rtype: tuple[numpy.ndarray, numpy.ndarray]
166 """
167 v = v + 0.5 * dt * force(u, k0, k2, k4)
168 u = u + 0.5 * dt * v
169 damping = np.exp(-gamma * dt)
170 v = damping * v + np.sqrt((1.0 - damping**2) * temperature) * rng.normal(size=v.shape)
171 u = u + 0.5 * dt * v
172 v = v + 0.5 * dt * force(u, k0, k2, k4)
173 return u, v
174
175
176def run_md(args: argparse.Namespace, rng: np.random.Generator) -> Samples:
177 """
178 概要:
179 分子動力学法によるシミュレーションを実行します。
180
181 詳細説明:
182 バーンイン期間の後に一定の間隔でサンプリングを行い、サンプリング結果を返します。
183
184 引数:
185 :param args: コマンドライン引数を格納したオブジェクト
186 :type args: argparse.Namespace
187 :param rng: 乱数生成器
188 :type rng: numpy.random.Generator
189
190 戻り値:
191 :returns: サンプリング結果を格納したSamplesオブジェクト
192 :rtype: Samples
193
194 例外:
195 :raises ValueError: サンプルが生成されなかった場合に送出されます。
196 """
197 shape = (args.L, args.L)
198 u = np.zeros(shape)
199 v = rng.normal(scale=np.sqrt(args.temperature), size=shape)
200 records: list[tuple[float, float, float, float, float, np.ndarray]] = []
201
202 for step in range(args.md_steps):
203 u, v = langevin_baoab_step(u, v, args.dt, args.gamma, args.temperature,
204 args.k0, args.k2, args.k4, rng)
205 if step >= args.md_burn and (step - args.md_burn) % args.sample_stride == 0:
206 potential = potential_energy(u, args.k0, args.k2, args.k4)
207 kinetic = 0.5 * float(np.sum(v**2))
208 records.append((step * args.dt, potential, kinetic, float(np.mean(u**2)),
209 float(np.mean(v**2)), u.copy()))
210
211 if not records:
212 raise ValueError("MD produced no samples; reduce --md-burn or increase --md-steps")
213 array = np.asarray([(row[0], row[1], row[2], row[3], row[4]) for row in records])
214 return Samples(array[:, 0], array[:, 1], array[:, 2], array[:, 3], array[:, 4],
215 np.asarray([row[5] for row in records]))
216
217
218def metropolis_sweep(u: np.ndarray, temperature: float, proposal: float,
219 k0: float, k2: float, k4: float,
220 rng: np.random.Generator) -> tuple[int, int]:
221 """
222 概要:
223 局所的な変位提案によるメトロポリス更新を1スイープ実行します。
224
225 詳細説明:
226 サイトごとにランダムに変位を提案し、エネルギー変化に基づいて受容判定を行います。
227
228 引数:
229 :param u: 格子の変位配列
230 :type u: numpy.ndarray
231 :param temperature: 設定温度
232 :type temperature: float
233 :param proposal: 一様分布による提案変位の半値幅
234 :type proposal: float
235 :param k0: オンサイト調和ポテンシャル係数
236 :type k0: float
237 :param k2: 調和ボンド係数
238 :type k2: float
239 :param k4: 4次の非調和ボンド係数
240 :type k4: float
241 :param rng: 乱数生成器
242 :type rng: numpy.random.Generator
243
244 戻り値:
245 :returns: 受容された提案回数と試行回数のタプル
246 :rtype: tuple[int, int]
247 """
248 L = u.shape[0]
249 accepted = 0
250 attempted = L * L
251 for _ in range(attempted):
252 i = int(rng.integers(L))
253 j = int(rng.integers(L))
254 old = u[i, j]
255 new = old + rng.uniform(-proposal, proposal)
256 neighbors = (u[(i - 1) % L, j], u[(i + 1) % L, j],
257 u[i, (j - 1) % L], u[i, (j + 1) % L])
258 delta_e = 0.5 * k0 * (new**2 - old**2)
259 for neighbor in neighbors:
260 delta_e += bond_energy(new - neighbor, k2, k4) - bond_energy(old - neighbor, k2, k4)
261 if delta_e <= 0.0 or rng.random() < np.exp(-delta_e / temperature):
262 u[i, j] = new
263 accepted += 1
264 return accepted, attempted
265
266
267def run_mc(args: argparse.Namespace, rng: np.random.Generator) -> tuple[Samples, float]:
268 """
269 概要:
270 モンテカルロ法によるシミュレーションを実行します。
271
272 詳細説明:
273 バーンイン期間の後に一定の間隔でサンプリングを行い、サンプリング結果と受容確率を返します。
274
275 引数:
276 :param args: コマンドライン引数を格納したオブジェクト
277 :type args: argparse.Namespace
278 :param rng: 乱数生成器
279 :type rng: numpy.random.Generator
280
281 戻り値:
282 :returns: サンプリング結果のSamplesオブジェクトと受容確率のタプル
283 :rtype: tuple[Samples, float]
284
285 例外:
286 :raises ValueError: サンプルが生成されなかった場合に送出されます。
287 """
288 shape = (args.L, args.L)
289 u = np.zeros(shape)
290 records: list[tuple[float, float, float, float, float, np.ndarray]] = []
291 accepted_total = attempted_total = 0
292
293 for sweep in range(args.mc_sweeps):
294 accepted, attempted = metropolis_sweep(u, args.temperature, args.proposal,
295 args.k0, args.k2, args.k4, rng)
296 if sweep >= args.mc_burn:
297 accepted_total += accepted
298 attempted_total += attempted
299 if sweep >= args.mc_burn and (sweep - args.mc_burn) % args.sample_stride == 0:
300 potential = potential_energy(u, args.k0, args.k2, args.k4)
301 if args.mc_momenta:
302 v = rng.normal(scale=np.sqrt(args.temperature), size=shape)
303 kinetic = 0.5 * float(np.sum(v**2))
304 v2 = float(np.mean(v**2))
305 else:
306 kinetic = 0.5 * u.size * args.temperature # equipartition expectation
307 v2 = args.temperature
308 records.append((float(sweep), potential, kinetic, float(np.mean(u**2)), v2, u.copy()))
309
310 if not records:
311 raise ValueError("MC produced no samples; reduce --mc-burn or increase --mc-sweeps")
312 array = np.asarray([(row[0], row[1], row[2], row[3], row[4]) for row in records])
313 samples = Samples(array[:, 0], array[:, 1], array[:, 2], array[:, 3], array[:, 4],
314 np.asarray([row[5] for row in records]))
315 acceptance = accepted_total / max(attempted_total, 1)
316 return samples, acceptance
317
318
319def mean_and_error(values: np.ndarray) -> tuple[float, float]:
320 """
321 概要:
322 配列の平均値と標準誤差を計算します。
323
324 詳細説明:
325 時間相関を取り除くような処理は意図的に行っていません。
326
327 引数:
328 :param values: 計算対象の数値配列
329 :type values: numpy.ndarray
330
331 戻り値:
332 :returns: 平均値と標準誤差のタプル
333 :rtype: tuple[float, float]
334 """
335 mean = float(np.mean(values))
336 error = float(np.std(values, ddof=1) / np.sqrt(len(values))) if len(values) > 1 else 0.0
337 return mean, error
338
339
340def running_mean(values: np.ndarray) -> np.ndarray:
341 """
342 概要:
343 配列の累積平均を計算します。
344
345 引数:
346 :param values: 計算対象の数値配列
347 :type values: numpy.ndarray
348
349 戻り値:
350 :returns: 累積平均の配列
351 :rtype: numpy.ndarray
352 """
353 return np.cumsum(values) / np.arange(1, len(values) + 1)
354
355
356def print_summary(md: Samples, mc: Samples, acceptance: float, args: argparse.Namespace) -> None:
357 """
358 概要:
359 MDとMCのシミュレーション結果を比較してコンソールに出力します。
360
361 引数:
362 :param md: MDシミュレーションのサンプリング結果
363 :type md: Samples
364 :param mc: MCシミュレーションのサンプリング結果
365 :type mc: Samples
366 :param acceptance: MCシミュレーションの受容確率
367 :type acceptance: float
368 :param args: コマンドライン引数を格納したオブジェクト
369 :type args: argparse.Namespace
370
371 戻り値:
372 :returns: なし
373 :rtype: None
374 """
375 dof = args.L * args.L
376 print("\n=== 2D anharmonic lattice: NVT MD versus Metropolis MC ===")
377 print(f"L={args.L}, sites={dof}, T={args.temperature:g}, K0={args.k0:g}, "
378 f"K2={args.k2:g}, K4={args.k4:g}")
379 print("K4=0: harmonic normal modes; K4>0: anharmonic mode coupling.")
380 print(f"MC acceptance after burn-in: {acceptance:.3f}")
381 print(f"Equipartition reference: <K> = {0.5 * dof * args.temperature:.6g}, "
382 f"<v^2> = {args.temperature:.6g}\n")
383 print(f"{'observable':<16s} {'MD mean +/- SE':>24s} {'MC mean +/- SE':>24s}")
384 print("-" * 68)
385 for label, md_values, mc_values in (
386 ("potential U", md.potential, mc.potential),
387 ("kinetic K", md.kinetic, mc.kinetic),
388 ("MSD <u^2>", md.msd, mc.msd),
389 ("mean v^2", md.v2, mc.v2)):
390 md_mean, md_error = mean_and_error(md_values)
391 mc_mean, mc_error = mean_and_error(mc_values)
392 print(f"{label:<16s} {md_mean:11.6f} +/- {md_error:9.2e} "
393 f"{mc_mean:11.6f} +/- {mc_error:9.2e}")
394 print("\nNote: MC velocities are independent Maxwell draws, not MC dynamics.")
395 print(" Standard errors are naive; correlated samples need block analysis for precision work.")
396
397
398def plot_results(md: Samples, mc: Samples, args: argparse.Namespace) -> plt.Figure:
399 """
400 概要:
401 シミュレーション結果の各種グラフを描画します。
402
403 詳細説明:
404 エネルギー推移、ポテンシャルエネルギーの収束、平均二乗変位の収束、
405 変位分布のヒストグラムをプロットします。
406
407 引数:
408 :param md: MDシミュレーションのサンプリング結果
409 :type md: Samples
410 :param mc: MCシミュレーションのサンプリング結果
411 :type mc: Samples
412 :param args: コマンドライン引数を格納したオブジェクト
413 :type args: argparse.Namespace
414
415 戻り値:
416 :returns: 生成されたmatplotlibのFigureオブジェクト
417 :rtype: matplotlib.pyplot.Figure
418 """
419 fig, axes = plt.subplots(2, 2, figsize=(12.5, 8.5))
420 ax_energy, ax_potential, ax_msd, ax_hist = axes.flat
421
422 ax_energy.plot(md.time, md.potential, label="MD potential U", lw=1.0)
423 ax_energy.plot(md.time, md.kinetic, label="MD kinetic K", lw=1.0)
424 ax_energy.plot(md.time, md.potential + md.kinetic, label="MD total E", lw=1.0, alpha=0.8)
425 ax_energy.set(xlabel="MD time", ylabel="energy", title="Langevin-MD instantaneous energies")
426 ax_energy.legend(fontsize=8)
427 ax_energy.grid(alpha=0.25)
428
429 ax_potential.plot(np.arange(1, len(md.potential) + 1), running_mean(md.potential),
430 label="MD", color="tab:blue")
431 ax_potential.plot(np.arange(1, len(mc.potential) + 1), running_mean(mc.potential),
432 label="MC", color="tab:orange")
433 ax_potential.set(xlabel="stored sample", ylabel="running <U>",
434 title="Potential-energy convergence")
435 ax_potential.legend()
436 ax_potential.grid(alpha=0.25)
437
438 ax_msd.plot(np.arange(1, len(md.msd) + 1), running_mean(md.msd), label="MD", color="tab:blue")
439 ax_msd.plot(np.arange(1, len(mc.msd) + 1), running_mean(mc.msd), label="MC", color="tab:orange")
440 ax_msd.set(xlabel="stored sample", ylabel=r"running $\langle u^2\rangle$",
441 title="Mean-square displacement from lattice sites")
442 ax_msd.legend()
443 ax_msd.grid(alpha=0.25)
444
445 bins = np.linspace(min(float(np.min(md.u_snapshots)), float(np.min(mc.u_snapshots))),
446 max(float(np.max(md.u_snapshots)), float(np.max(mc.u_snapshots))), 45)
447 ax_hist.hist(md.u_snapshots.ravel(), bins=bins, density=True, histtype="step", lw=1.8,
448 label="MD", color="tab:blue")
449 ax_hist.hist(mc.u_snapshots.ravel(), bins=bins, density=True, histtype="step", lw=1.8,
450 label="MC", color="tab:orange")
451 ax_hist.set(xlabel="displacement u", ylabel="probability density",
452 title="Equilibrium displacement distribution")
453 ax_hist.legend()
454 ax_hist.grid(alpha=0.25)
455
456 fig.suptitle(f"2D lattice: K0={args.k0:g}, K2={args.k2:g}, K4={args.k4:g}, T={args.temperature:g}",
457 fontsize=14)
458 fig.tight_layout(rect=(0, 0, 1, 0.95))
459 return fig
460
461
462def parse_args() -> argparse.Namespace:
463 """
464 概要:
465 コマンドライン引数を解析します。
466
467 戻り値:
468 :returns: 解析されたコマンドライン引数を格納したオブジェクト
469 :rtype: argparse.Namespace
470 """
471 parser = argparse.ArgumentParser(description=__doc__)
472 parser.add_argument("--L", type=int, default=8, help="linear lattice size")
473 parser.add_argument("--temperature", type=float, default=1.0)
474 parser.add_argument("--k0", type=float, default=1.0,
475 help="on-site harmonic pinning; keeps the MSD finite and sampling fast")
476 parser.add_argument("--k2", type=float, default=1.0, help="harmonic bond coefficient")
477 parser.add_argument("--k4", type=float, default=0.20, help="quartic bond coefficient")
478 parser.add_argument("--dt", type=float, default=0.02)
479 parser.add_argument("--gamma", type=float, default=1.0, help="Langevin friction")
480 parser.add_argument("--md-steps", type=int, default=12000)
481 parser.add_argument("--md-burn", type=int, default=4000)
482 parser.add_argument("--mc-sweeps", type=int, default=7000)
483 parser.add_argument("--mc-burn", type=int, default=2000)
484 parser.add_argument("--proposal", type=float, default=0.8,
485 help="uniform MC displacement half-width")
486 parser.add_argument("--sample-stride", type=int, default=10)
487 parser.add_argument("--seed", type=int, default=12345)
488 parser.add_argument("--no-mc-momenta", dest="mc_momenta", action="store_false",
489 help="show equipartition expectation instead of Maxwell samples")
490 parser.set_defaults(mc_momenta=True)
491 parser.add_argument("--output", type=str, default=None, help="save summary figure")
492 parser.add_argument("--dpi", type=int, default=160)
493 parser.add_argument("--no-show", action="store_true")
494 return parser.parse_args()
495
496
497def validate_args(args: argparse.Namespace) -> None:
498 """
499 概要:
500 コマンドライン引数の値が妥当かどうかを検証します。
501
502 引数:
503 :param args: 検証対象のコマンドライン引数オブジェクト
504 :type args: argparse.Namespace
505
506 戻り値:
507 :returns: なし
508 :rtype: None
509
510 例外:
511 :raises ValueError: 引数の値が制約を満たさない場合に送出されます。
512 """
513 if args.L < 2:
514 raise ValueError("L must be at least 2")
515 if args.temperature <= 0.0 or args.k0 < 0.0 or args.k2 < 0.0 or args.k4 < 0.0:
516 raise ValueError("temperature must be positive and K0, K2, K4 must be non-negative")
517 if args.dt <= 0.0 or args.gamma < 0.0 or args.proposal <= 0.0 or args.sample_stride < 1:
518 raise ValueError("dt and proposal must be positive; gamma must be non-negative")
519 if args.md_burn >= args.md_steps or args.mc_burn >= args.mc_sweeps:
520 raise ValueError("burn-in must be shorter than the corresponding run")
521
522
523def main() -> None:
524 """
525 概要:
526 スクリプトのメインルーチンを実行します。
527
528 詳細説明:
529 引数を解析・検証し、MDおよびMCシミュレーションを実行し、結果の出力と描画を行います。
530
531 戻り値:
532 :returns: なし
533 :rtype: None
534
535 例外:
536 :raises SystemExit: 引数エラーが発生した場合に送出されます。
537 """
538 args = parse_args()
539 try:
540 validate_args(args)
541 seed_sequence = np.random.SeedSequence(args.seed)
542 md_rng, mc_rng = [np.random.default_rng(child) for child in seed_sequence.spawn(2)]
543 md = run_md(args, md_rng)
544 mc, acceptance = run_mc(args, mc_rng)
545 except ValueError as exc:
546 raise SystemExit(f"Input error: {exc}") from exc
547
548 print_summary(md, mc, acceptance, args)
549 fig = plot_results(md, mc, args)
550 if args.output:
551 fig.savefig(args.output, dpi=args.dpi, bbox_inches="tight")
552 print(f"\nSaved figure: {args.output}")
553 if args.no_show:
554 plt.close(fig)
555 else:
556 plt.show()
557
558
559if __name__ == "__main__":
560 main()