Chapter: 10. Isothermal–isobaric (NPT-MC) and grand canonical (muVT-MC) ensembles
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)def run_ideal_gcmc(z_activity: float, V_box: float, n_steps: int, rng_gen: np.random.Generator) -> np.ndarray:
N = int(round(z_activity * V_box))
N_hist = np.zeros(n_steps, dtype=int)
for k in range(n_steps):
if rng_gen.random() < 0.5:
# Insertion attempt
if rng_gen.random() < min(1.0, z_activity * V_box / (N + 1)):
N += 1
else:
# Deletion attempt
if N > 0 and rng_gen.random() < min(1.0, N / (z_activity * V_box)):
N -= 1
N_hist[k] = N
return N_hist
N_traj = run_ideal_gcmc(z_activity=0.25, V_box=100.0, n_steps=15000, rng_gen=rng)mean_N = float(np.mean(N_traj[2000:]))
var_N = float(np.var(N_traj[2000:]))
print(f"Ideal-gas GCMC (z*V = 25.0): <N> = {mean_N:.2f}, Var(N) = {var_N:.2f} (exact Poisson = 25.0)")
assert np.isclose(mean_N, 25.0, rtol=0.06)
assert np.isclose(var_N, 25.0, rtol=0.12)
n_vals = np.arange(10, 42)
from math import factorial
poisson_exact = np.array([(25.0**int(n)) * np.exp(-25.0) / factorial(int(n)) for n in n_vals])
hist_n, _ = np.histogram(N_traj[2000:], bins=np.arange(9.5, 42.5, 1.0), density=True)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10.8, 4.1))
ax1.plot(np.arange(600), N_traj[:600], "b-", label="GCMC N(t)")
ax1.axhline(25.0, color="r")
ax1.set_xlabel("GCMC Attempt k [-]"); ax1.set_ylabel("Particle Count N [-]")
ax1.set_title("(a) Grand Canonical Particle Fluctuations"); panel_label(ax1, "(a)")
ax2.plot(n_vals, poisson_exact, "k-", label="Exact Poisson")
ax2.plot(n_vals, hist_n, "ro", label="GCMC Sample")
ax2.set_xlabel("Particle Count N [-]"); ax2.set_ylabel("Probability P(N)")
ax2.set_title("(b) Exact Poisson Limit (Var(N) = <N>)"); panel_label(ax2, "(b)")
plt.show()Ideal-gas GCMC (z*V = 25.0): <N> = 25.30, Var(N) = 25.67 (exact Poisson = 25.0)

Worked solutions to Exercises 1–3¶
# Worked Solutions Ch 10: Exact Langmuir site occupancy in GCMC
z_grid = np.linspace(0.1, 5.0, 12)
eps_ads = 1.0
theta_exact = (z_grid * np.exp(eps_ads)) / (1.0 + z_grid * np.exp(eps_ads))
assert np.all((theta_exact > 0.0) & (theta_exact < 1.0))
print(f"Ch 10 Exercises — Langmuir coverage at z=1.0, eps=1.0: theta = {float(np.exp(1)/(1+np.exp(1))):.4f}")Ch 10 Exercises — Langmuir coverage at z=1.0, eps=1.0: theta = 0.7311