Chapter: 9. Metropolis Monte Carlo in the canonical ensemble (NVT-MC)
Each solution below reproduces the chapter state and verifies the exercise targets with explicit assert checks.
import sys
from pathlib import Path
import numpy as np
import matplotlib.pyplot as plt
REPO_ROOT = Path(__file__).resolve().parents[2] if "__file__" in globals() else Path("../..").resolve()
if str(REPO_ROOT) not in sys.path:
sys.path.insert(0, str(REPO_ROOT))
import engsim as es
from engsim.plotting import panel_label, use_style
use_style()
rng = np.random.default_rng(2026)pos_9, L_9 = es.make_fcc_lattice(3, rho=0.75) # N = 108
mc_res = es.run_nvt_mc(pos_9, L_9, T=1.2, n_sweeps=80, max_disp=0.18, rc=2.5, shifted=True, rng=rng)
# Independent NVT-MD (Bussi CSVR) at identical state (rho=0.75, T=1.2)
p_md, v_md = pos_9.copy(), es.init_velocities(len(pos_9), 1.2, rng=rng)
f_fn = lambda p, L: es.lj_forces_all_pairs(p, L, rc=2.5, shifted=True)
f_md, u_md, _ = f_fn(p_md, L_9)
u_md_hist = []
for st in range(160):
p_md, v_md, f_md, u_md, _, _ = es.velocity_verlet_step(p_md, v_md, f_md, 0.005, L_9, f_fn)
v_md = es.bussi_csvr_thermostat(v_md, 1.2, 0.005, 0.05, rng)
u_md_hist.append(u_md / len(pos_9))u_mc_mean = float(np.mean(mc_res["u_per_atom"][30:]))
u_md_mean = float(np.mean(u_md_hist[60:]))
print(f"NVT-MC (acc={mc_res['acceptance']*100:.1f}%): <U/N> = {u_mc_mean:.3f} vs. NVT-MD: <U/N> = {u_md_mean:.3f}")
assert 0.25 < mc_res["acceptance"] < 0.70
assert abs(u_mc_mean - u_md_mean) < 0.25
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10.8, 4.1))
ax1.plot(np.arange(len(mc_res["u_per_atom"])), mc_res["u_per_atom"], "b-", label="NVT-MC Sweeps")
ax1.axhline(u_md_mean, color="r")
ax1.set_xlabel("MC Sweep [-]"); ax1.set_ylabel("Potential Energy U/N [eps]")
ax1.set_title("(a) NVT-MC Equilibration vs NVT-MD Mean"); panel_label(ax1, "(a)")
r_mc, g_mc = es.compute_rdf(mc_res["pos"], L_9, n_bins=35)
r_md, g_md = es.compute_rdf(p_md, L_9, n_bins=35)
ax2.plot(r_mc, g_mc, "b-", label="NVT-MC Snapshot g(r)")
ax2.plot(r_md, g_md, "r--", label="NVT-MD Snapshot g(r)")
ax2.set_xlabel("Pair distance r [sigma]"); ax2.set_ylabel("g(r) [-]")
ax2.set_title("(b) Structural Equivalence of MC & MD"); panel_label(ax2, "(b)")
plt.show()NVT-MC (acc=37.6%): <U/N> = -4.432 vs. NVT-MD: <U/N> = -4.356

Worked solutions to Exercises 1–3¶
# Worked Solutions Ch 9
r_small = es.run_nvt_mc(pos_9, L_9, T=1.2, n_sweeps=10, max_disp=0.05, rng=rng)["acceptance"]
r_large = es.run_nvt_mc(pos_9, L_9, T=1.2, n_sweeps=10, max_disp=0.50, rng=rng)["acceptance"]
print(f"Ch 9 Exercises — Acceptance: dr=0.05 -> {r_small*100:.1f}%, dr=0.50 -> {r_large*100:.1f}%")
assert r_small > r_largeCh 9 Exercises — Acceptance: dr=0.05 -> 93.1%, dr=0.50 -> 5.0%