Chapter: 8. Constant-pressure simulation (NPT): Berendsen and isotropic barostats
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_8, L_8 = es.make_fcc_lattice(3, rho=0.60) # Start deliberately under-dense
vel_8 = es.init_velocities(len(pos_8), 1.0, rng=rng)
f_fn = lambda p, L: es.lj_forces_all_pairs(p, L, rc=2.5, shifted=True)
f_8, _, vir_8 = f_fn(pos_8, L_8)
rho_hist, P_hist = [], []
P_target = 1.5
for step in range(220):
pos_8, vel_8, f_8, _, vir_8, _ = es.velocity_verlet_step(pos_8, vel_8, f_8, 0.005, L_8, f_fn)
vel_8 = es.bussi_csvr_thermostat(vel_8, 1.0, 0.005, 0.05, rng)
_, T_c = es.kinetic_energy_and_temp(vel_8)
rho_c = len(pos_8) / (L_8**3)
P_c = rho_c * T_c + vir_8 / (3.0 * L_8**3)
pos_8, L_8 = es.berendsen_barostat_scale(pos_8, L_8, P_c, P_target, 0.005, tau_P=0.2, kappa_T=0.08)
rho_hist.append(len(pos_8) / (L_8**3))
P_hist.append(P_c)rho_eq = float(np.mean(rho_hist[120:]))
P_eq = float(np.mean(P_hist[120:]))
print(f"NPT equilibration (T*=1.0, P*=1.5): <rho*> = {rho_eq:.3f}, <P*> = {P_eq:.3f}")
assert 0.65 < rho_eq < 0.90
assert np.isclose(P_eq, P_target, atol=0.45)
t_8 = np.arange(len(rho_hist)) * 0.005
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10.8, 4.1))
ax1.plot(t_8, rho_hist, "b-", label="Density rho(t)")
ax1.set_xlabel("Time t [tau]"); ax1.set_ylabel("Number Density rho* [-]")
ax1.set_title("(a) NPT Liquid Density Equilibration"); panel_label(ax1, "(a)")
ax2.plot(t_8, P_hist, "r-", label="Instantaneous P(t)")
ax2.axhline(P_target, color="k")
ax2.set_xlabel("Time t [tau]"); ax2.set_ylabel("Pressure P* [eps/sigma^3]")
ax2.set_title("(b) Virial Pressure Relaxation to P* = 1.5"); panel_label(ax2, "(b)")
plt.show()NPT equilibration (T*=1.0, P*=1.5): <rho*> = 0.785, <P*> = 1.398

Worked solutions to Exercises 1–3¶
# Worked Solutions Ch 8
L_ig = 8.0; p_ig = rng.uniform(0.0, L_ig, size=(64, 3)); v_ig = es.init_velocities(64, 1.0, rng=rng)
for _ in range(350):
v_ig = es.bussi_csvr_thermostat(v_ig, 1.0, 0.01, 0.05, rng)
_, T_i = es.kinetic_energy_and_temp(v_ig)
P_i = (64.0 / L_ig**3) * T_i
p_ig, L_ig = es.berendsen_barostat_scale(p_ig, L_ig, P_i, 0.25, 0.01, tau_P=0.05, kappa_T=1.2)
rho_ig_final = 64.0 / (L_ig**3)
print(f"Ch 8 Exercises — Ideal-gas NPT density = {rho_ig_final:.3f} (exact P/T = 0.250)")
assert np.isclose(rho_ig_final, 0.25, rtol=0.12)Ch 8 Exercises — Ideal-gas NPT density = 0.258 (exact P/T = 0.250)