mc_alloy のソースコード

import argparse
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from numba import njit

# ==========================================
# 物理定数と基本関数の定義
# ==========================================
kB = 8.6173e-5  # ボルツマン定数 (eV/K)

[ドキュメント] def calc_omega(H_AA, H_BB, H_AB, z=4): return z * (H_AB - (H_AA + H_BB) / 2.0)
[ドキュメント] def G_x(x, T, H_AA, H_BB, Omega, z=4): """Bragg-Williams (regular-solution) free energy per lattice site. H_AA, H_BB, and H_AB are bond energies. The first term therefore has z/2 bonds per site. Keeping this linear reference term makes the energetic asymmetry between the A and B end members visible in G(x). """ x_safe = np.clip(x, 1e-10, 1 - 1e-10) H_mix = 0.5 * z * ((1 - x) * H_AA + x * H_BB) + Omega * x * (1 - x) S_mix = -kB * T * (x_safe * np.log(x_safe) + (1 - x_safe) * np.log(1 - x_safe)) return H_mix - S_mix
# ========================================== # Numbaによる超高速MC・解析コア # ========================================== @njit def count_diff_bonds_except(grid, i, j, L, atom_type, exclude_i, exclude_j): """Number of unlike 1NN bonds from (i,j), except one specified neighbor.""" count = 0 ni, nj = (i + 1) % L, j if not (ni == exclude_i and nj == exclude_j) and grid[ni, nj] != atom_type: count += 1 ni, nj = (i - 1) % L, j if not (ni == exclude_i and nj == exclude_j) and grid[ni, nj] != atom_type: count += 1 ni, nj = i, (j + 1) % L if not (ni == exclude_i and nj == exclude_j) and grid[ni, nj] != atom_type: count += 1 ni, nj = i, (j - 1) % L if not (ni == exclude_i and nj == exclude_j) and grid[ni, nj] != atom_type: count += 1 return count @njit def kawasaki_steps(grid, L, Omega_z, kT, n_steps): for _ in range(n_steps): i1 = np.random.randint(L) j1 = np.random.randint(L) direction = np.random.randint(4) if direction == 0: i2, j2 = (i1 + 1) % L, j1 elif direction == 1: i2, j2 = (i1 - 1) % L, j1 elif direction == 2: i2, j2 = i1, (j1 + 1) % L else: i2, j2 = i1, (j1 - 1) % L c1 = grid[i1, j1] c2 = grid[i2, j2] if c1 == c2: continue # The bond between the two exchanged sites remains an A-B bond. It # must not enter dE; count only the other three neighbors of each site. old_bonds = (count_diff_bonds_except(grid, i1, j1, L, c1, i2, j2) + count_diff_bonds_except(grid, i2, j2, L, c2, i1, j1)) new_bonds = (count_diff_bonds_except(grid, i1, j1, L, c2, i2, j2) + count_diff_bonds_except(grid, i2, j2, L, c1, i1, j1)) d_bonds = new_bonds - old_bonds dE = d_bonds * Omega_z if dE <= 0.0 or np.random.rand() < np.exp(-dE / kT): grid[i1, j1] = c2 grid[i2, j2] = c1 @njit def calc_sro(grid, L, x_B): """Warren-Cowley SRO パラメータ (1NN, 2NN) の計算""" N_A = 0 N_AB_1nn = 0 N_AB_2nn = 0 for i in range(L): for j in range(L): if grid[i, j] == 1: # A原子の場合 N_A += 1 if grid[(i+1)%L, j] == -1: N_AB_1nn += 1 if grid[(i-1)%L, j] == -1: N_AB_1nn += 1 if grid[i, (j+1)%L] == -1: N_AB_1nn += 1 if grid[i, (j-1)%L] == -1: N_AB_1nn += 1 if grid[(i+1)%L, (j+1)%L] == -1: N_AB_2nn += 1 if grid[(i-1)%L, (j+1)%L] == -1: N_AB_2nn += 1 if grid[(i+1)%L, (j-1)%L] == -1: N_AB_2nn += 1 if grid[(i-1)%L, (j-1)%L] == -1: N_AB_2nn += 1 if N_A == 0 or x_B == 0.0 or x_B == 1.0: return 0.0, 0.0 P_BA_1 = N_AB_1nn / (4.0 * N_A) P_BA_2 = N_AB_2nn / (4.0 * N_A) alpha_1 = 1.0 - (P_BA_1 / x_B) alpha_2 = 1.0 - (P_BA_2 / x_B) return alpha_1, alpha_2 @njit def count_unlike_bonds(grid, L): """Count every 1NN bond once (right and up directions only).""" n_ab = 0 for i in range(L): for j in range(L): if grid[i, j] != grid[(i + 1) % L, j]: n_ab += 1 if grid[i, j] != grid[i, (j + 1) % L]: n_ab += 1 return n_ab @njit def seed_numba_rng(seed): np.random.seed(seed) # ========================================== # メイン実行部 # ==========================================
[ドキュメント] def main(): parser = argparse.ArgumentParser( description="Regular-solution mean field and 2D lattice-gas (Ising) Kawasaki MC" ) parser.add_argument("--mode", type=str, default="sim", choices=["Gx", "Gx3c", "Gx3d", "sim"], help="実行モード") parser.add_argument("--HAA", type=float, default=0.0, help="A-A結合エネルギー (eV/bond)") parser.add_argument("--HBB", type=float, default=0.04, help="B-B結合エネルギー (eV/bond)") parser.add_argument("--HAB", type=float, default=0.06, help="A-B結合エネルギー (eV/bond)") parser.add_argument("--xb", type=float, default=0.5, help="B原子の組成比 (0.0~1.0)") parser.add_argument("--T", type=float, default=850, help="シミュレーション温度 (K)") parser.add_argument("--Tmin", type=float, default=100, help="プロット用最小温度 (K)") parser.add_argument("--Tmax", type=float, default=1000, help="プロット用最大温度 (K)") parser.add_argument("--n-composition", type=int, default=200, help="G(x) の組成分割数") parser.add_argument("--n-temperature", type=int, default=100, help="G(x,T) の温度分割数") parser.add_argument("--n-gx-curves", type=int, default=10, help="Gx モードで重ね描きする温度曲線数") parser.add_argument("--gx-offset", type=float, default=0.02, help="Gx モードの曲線ごとの縦方向オフセット (eV/site)") parser.add_argument("--L", type=int, default=200, help="MCグリッドサイズ") parser.add_argument("--init", type=str, default="random", choices=["random", "separated"], help="MC初期状態") parser.add_argument("--sweeps-per-frame", type=int, default=1, help="アニメーション1フレーム当たりのMC sweep数") parser.add_argument("--n-frames", type=int, default=5000, help="アニメーション総フレーム数") parser.add_argument("--interval-ms", type=int, default=30, help="アニメーションのフレーム間隔 (ms)") parser.add_argument("--output-interval", type=int, default=10, help="コンソール出力のフレーム間隔") parser.add_argument("--seed", type=int, default=None, help="乱数seed(指定しない場合はランダム)") args = parser.parse_args() z = 4 # square lattice coordination number Omega = calc_omega(args.HAA, args.HBB, args.HAB, z=z) Tc_MF = Omega / (2 * kB) Tc_2D = 2.269 * (Omega / 8) / kB print("--- 入力パラメータ ---") for name, value in vars(args).items(): print(f"{name} = {value}") print("-" * 20) print(f"--- 物理パラメータ ---") print(f"Omega = {Omega:.4f} eV") print(f"T_c (平均場) = {Tc_MF:.1f} K") print(f"T_c (2D厳密解) = {Tc_2D:.1f} K") print("Random-alloy limit: alpha1 = 0.0000, alpha2 = 0.0000") print("-" * 20) if args.mode in ['Gx', 'Gx3c', 'Gx3d']: x_array = np.linspace(0.001, 0.999, args.n_composition) T_array = np.linspace(args.Tmin, args.Tmax, args.n_temperature) if args.mode == 'Gx': plt.figure(figsize=(8, 6)) T_steps = np.linspace(args.Tmin, args.Tmax, args.n_gx_curves) for i, temp in enumerate(T_steps): G = G_x(x_array, temp, args.HAA, args.HBB, Omega, z) plt.plot(x_array, G + i * args.gx_offset, label=f"T={int(temp)} K") plt.title("Bragg-Williams free energy G(x) (with offset)") plt.xlabel("Composition x (B fraction)") plt.ylabel("Gibbs free energy G (eV/site) + offset") plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left') plt.tight_layout() plt.show() elif args.mode == 'Gx3c': X, Y = np.meshgrid(x_array, T_array) Z = G_x(X, Y, args.HAA, args.HBB, Omega, z) plt.figure(figsize=(8, 6)) cp = plt.contourf(X, Y, Z, levels=50, cmap='viridis') plt.colorbar(cp, label="Gibbs Free Energy (eV)") plt.axhline(Tc_MF, color='w', linestyle='--', label=f"Tc (mean field) = {Tc_MF:.0f} K") plt.axhline(Tc_2D, color='r', linestyle=':', label=f"Tc (2D Ising) = {Tc_2D:.0f} K") plt.title("Mean-field G(x, T) contour") plt.xlabel("Composition x") plt.ylabel("Temperature T (K)") plt.legend() plt.show() elif args.mode == 'Gx3d': fig = plt.figure(figsize=(10, 8)) ax = fig.add_subplot(111, projection='3d') X, Y = np.meshgrid(x_array, T_array) Z = G_x(X, Y, args.HAA, args.HBB, Omega, z) surf = ax.plot_surface(X, Y, Z, cmap='coolwarm', edgecolor='none') fig.colorbar(surf, shrink=0.5, aspect=5) ax.set_title("G(x, T) 3D Surface") plt.show() elif args.mode == 'sim': N_total = args.L * args.L N_B = int(N_total * args.xb) N_A = N_total - N_B x_B_actual = N_B / N_total if args.seed is not None: np.random.seed(args.seed) seed_numba_rng(args.seed) if args.init == 'random': flat = np.array([1]*N_A + [-1]*N_B, dtype=np.int8) np.random.shuffle(flat) grid = flat.reshape((args.L, args.L)) else: grid = np.ones((args.L, args.L), dtype=np.int8) cols_B = N_B // args.L if cols_B > 0: grid[:, -cols_B:] = -1 rem_B = N_B % args.L if rem_B > 0: grid[:rem_B, -(cols_B + 1)] = -1 fig, ax = plt.subplots(figsize=(7, 7)) cmap = plt.colormaps['bwr'].resampled(2) im = ax.imshow(grid, cmap=cmap, vmin=-1, vmax=1, animated=True, interpolation='nearest') ax.axis('off') # 解決策1: 枠外のタイトルを廃止し、枠内にテキストボックスを配置 title_text = ax.text(0.5, 0.98, "", transform=ax.transAxes, ha="center", va="top", fontsize=12, bbox=dict(facecolor='white', alpha=0.85, edgecolor='none')) steps_per_frame = args.sweeps_per_frame * args.L * args.L Omega_z = Omega / 4.0 kT = kB * args.T def update(frame): kawasaki_steps(grid, args.L, Omega_z, kT, steps_per_frame) alpha_1, alpha_2 = calc_sro(grid, args.L, x_B_actual) n_ab = count_unlike_bonds(grid, args.L) e_mix_per_site = n_ab * Omega_z / N_total # 画像上のテキスト更新 title_text.set_text( f"T={args.T:g} K, x_B={x_B_actual:.4f} (Frame {frame})\n" f"SRO 1NN (alpha1): {alpha_1:.4f} | 2NN (alpha2): {alpha_2:.4f}\n" "Random-alloy limit: alpha1 = alpha2 = 0.0000\n" f"N_AB={n_ab} | E_mix/N={e_mix_per_site:.5f} eV" ) # コンソールへの定期出力 if frame % args.output_interval == 0: print( f"Frame {frame:4d} | N_AB: {n_ab:6d} | E_mix/N: {e_mix_per_site:9.5f} eV" f" | 1NN(alpha1): {alpha_1:8.4f} | 2NN(alpha2): {alpha_2:8.4f}" ) im.set_data(grid) return im, title_text ani = FuncAnimation(fig, update, frames=args.n_frames, interval=args.interval_ms, blit=True) plt.show()
if __name__ == "__main__": main()