Worked solutions to the three exercises of Lecture 7. Each solution is computed here and checked with assert statements against an exact identity or an independent calculation. The first code cell sets up the notebook and runs Demonstration 1 of the lecture without showing its output, because some of the solutions use its variables.
try: # use the installed package, or the copy in this repository
import engmaterials
except ImportError:
import pathlib, subprocess, sys
for _root in [pathlib.Path.cwd(), *pathlib.Path.cwd().parents]:
if (_root / "engmaterials" / "__init__.py").exists():
sys.path.insert(0, str(_root))
break
else: # on Google Colab: install from GitHub
subprocess.run([sys.executable, "-m", "pip", "install", "-q",
"git+https://github.com/ktwyw/engmaterials.git"], check=True)
import engmaterials
import inspect
import numpy as np
import matplotlib.pyplot as plt
from engmaterials import (atomistics, constants, diffraction, elasticity, kinetics_selection,
lattices, phase_field, phase_thermodynamics)
from engmaterials.plotting import label_panels, panel_label, use_style
use_style()
def show_source(obj):
"""Return the source code of a library function or class."""
return inspect.getsource(obj)
def heading(text):
print(f"\n{text}\n" + "=" * len(text))
# Demonstration 1 of the lecture, run without output: the solutions use its variables.
import contextlib, io
_show, plt.show = plt.show, lambda *args, **kwargs: None
_stdout = contextlib.redirect_stdout(io.StringIO()); _stdout.__enter__()
heading("Demonstration 1: Lennard-Jones Exact Stationary Point, Harmonic-Matched Morse & C^1 Shifted-Force LJ")
r_min = 2.0 ** (1.0 / 6.0)
k_harm_exact = 72.0 / (2.0 ** (1.0 / 3.0))
lj_eq = atomistics.lennard_jones_potential(r_min, epsilon=1.0, sigma=1.0)
alpha_match = np.sqrt(k_harm_exact / 2.0)
morse_eq = atomistics.morse_potential(r_min, D_e=1.0, alpha=alpha_match, r_0=r_min)
sf_at_cut = atomistics.shifted_force_lj(2.5 - 1e-12, epsilon=1.0, sigma=1.0, r_cut=2.5)
print(f"LJ at r_min = {r_min:.6f} sigma : V = {lj_eq['energy']:.6f}, F = {lj_eq['force']:.2e}, d2V/dr2 = {lj_eq['d2V_dr2']:.6f}")
print(f"Matched Morse (alpha={alpha_match:.4f}): V = {morse_eq['energy']:.6f}, F = {morse_eq['force']:.2e}, d2V/dr2 = {morse_eq['d2V_dr2']:.6f}")
print(f"Shifted-Force LJ at r_cut^- : V_SF = {sf_at_cut['energy']:.2e}, F_SF = {sf_at_cut['force']:.2e}")
assert np.isclose(lj_eq["energy"], -1.0, atol=1e-15) and np.isclose(lj_eq["force"], 0.0, atol=1e-14)
assert np.isclose(lj_eq["d2V_dr2"], k_harm_exact, rtol=1e-14)
assert np.isclose(morse_eq["d2V_dr2"], k_harm_exact, rtol=1e-14)
assert abs(sf_at_cut["energy"]) < 1e-11 and abs(sf_at_cut["force"]) < 1e-10
r_grid = np.linspace(0.96, 2.75, 300)
lj_c = atomistics.lennard_jones_potential(r_grid)
sf_c = atomistics.shifted_force_lj(r_grid, r_cut=2.5)
mo_c = atomistics.morse_potential(r_grid, D_e=1.0, alpha=alpha_match, r_0=r_min)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(9.2, 3.8))
ax1.plot(r_grid, lj_c["energy"], lw=2.0, label="Raw 12-6 LJ")
ax1.plot(r_grid, sf_c["energy"], "--", lw=1.8, label=r"Shifted-Force LJ ($r_c = 2.5\sigma$)")
ax1.plot(r_grid, mo_c["energy"], ":", lw=1.8, label="Curvature-Matched Morse")
ax1.set_ylim(-1.15, 0.8)
ax1.set_xlabel(r"Reduced Separation $r / \sigma$ [-]")
ax1.set_ylabel(r"Pair Energy $V(r) / \varepsilon$ [-]")
ax1.set_title("Pair Potential Energy Curves")
ax1.legend(fontsize=8)
ax2.plot(r_grid, lj_c["force"], lw=2.0, label="Raw LJ Force")
ax2.plot(r_grid, sf_c["force"], "--", lw=1.8, label=r"$C^1$ Shifted-Force ($F \to 0$ at $2.5\sigma$)")
ax2.axvline(2.5, color="gray", ls=":", lw=1.2)
ax2.set_ylim(-3.0, 2.0)
ax2.set_xlabel(r"Reduced Separation $r / \sigma$ [-]")
ax2.set_ylabel(r"Pair Force $F(r)\,\sigma / \varepsilon$ [-]")
ax2.set_title("Smooth Force Cutoff at $r_c = 2.5\\sigma$")
ax2.legend(fontsize=8)
label_panels(fig)
plt.show()
_stdout.__exit__(None, None, None); plt.show = _show; plt.close("all")Exercise 1¶
Problem. Verify analytically and numerically that the 12-6 Lennard-Jones inflection point occurs at , where d2V_dr2 == 0 and the attractive restoring tension reaches its strict extremum .
heading("Exercise 1: Lennard-Jones Bond Inflection Point & Peak Attractive Rupture Tension")
r_infl = (26.0 / 7.0) ** (1.0 / 6.0)
lj_inf = atomistics.lennard_jones_potential(r_infl, epsilon=1.0, sigma=1.0)
sr6_inf = 7.0 / 26.0
f_exact = (24.0 / r_infl) * (2.0 * (sr6_inf ** 2) - sr6_inf)
r_scan = np.linspace(1.13, 1.60, 5000)
f_scan = atomistics.lennard_jones_potential(r_scan, epsilon=1.0, sigma=1.0)["force"]
print(f"r_infl / sigma = {r_infl:.8f}")
print(f"d2V/dr2(r_infl) = {lj_inf['d2V_dr2']:.3e}")
print(f"F(r_infl) [analytic] = {f_exact:.8f} eps/sigma (min on scan = {np.min(f_scan):.8f})")
assert abs(lj_inf["d2V_dr2"]) < 1e-13
assert np.isclose(lj_inf["force"], f_exact, rtol=1e-15, atol=1e-15)
assert lj_inf["force"] <= float(np.min(f_scan)) + 1e-9
Exercise 1: Lennard-Jones Bond Inflection Point & Peak Attractive Rupture Tension
=================================================================================
r_infl / sigma = 1.24445506
d2V/dr2(r_infl) = -1.032e-14
F(r_infl) [analytic] = -2.39642926 eps/sigma (min on scan = -2.39642918)
Explanation. Setting yields ( bond stretch beyond ). Stretching a crystal uniformly past makes the tangent bond stiffness , triggering spinodal cavitation/cleavage at peak tension .
Exercise 2¶
Problem. Compare the cutoff boundary jump at between raw shifted-potential-only truncation and atomistics.shifted_force_lj, and verify that across .
heading("Exercise 2: Diagnostic Audit — Shifted-Potential Force Discontinuity vs Shifted-Force C^1 Consistency")
r_c = 2.5
lj_cut = atomistics.lennard_jones_potential(r_c)
sf_just_in = atomistics.shifted_force_lj(r_c - 1e-10, r_cut=r_c)
print(f"Shifted-potential-only force jump at r_c = 2.5 sigma : |F_LJ(r_c)| = {abs(lj_cut['force']):.6f} eps/sigma")
print(f"Shifted-force residual at r_c - 1e-10 : |F_SF| = {abs(sf_just_in['force']):.3e} eps/sigma")
r_pts = np.linspace(1.10, 2.45, 40)
dr = 1e-6
sf_mid = atomistics.shifted_force_lj(r_pts, r_cut=r_c)
v_plus = atomistics.shifted_force_lj(r_pts + dr, r_cut=r_c)["energy"]
v_minus = atomistics.shifted_force_lj(r_pts - dr, r_cut=r_c)["energy"]
f_from_dv = -(v_plus - v_minus) / (2.0 * dr)
# Buggy combination: shifting F without adding +(r - r_c)*F_LJ(r_c) to V creates a constant force mismatch equal to |F_LJ(r_c)|
v_sp_only_p = atomistics.lennard_jones_potential(r_pts + dr)["energy"] - lj_cut["energy"]
v_sp_only_m = atomistics.lennard_jones_potential(r_pts - dr)["energy"] - lj_cut["energy"]
f_sp_mismatch = np.max(np.abs(-(v_sp_only_p - v_sp_only_m) / (2.0 * dr) - sf_mid["force"]))
print(f"Max |-dV_SF/dr - F_SF| = {np.max(np.abs(f_from_dv - sf_mid['force'])):.2e} | Mismatch if linear ramp omitted = {f_sp_mismatch:.6f}")
assert np.allclose(f_from_dv, sf_mid["force"], rtol=1e-9, atol=1e-9)
assert np.isclose(f_sp_mismatch, abs(lj_cut["force"]), rtol=1e-7)
Exercise 2: Diagnostic Audit — Shifted-Potential Force Discontinuity vs Shifted-Force C^1 Consistency
=====================================================================================================
Shifted-potential-only force jump at r_c = 2.5 sigma : |F_LJ(r_c)| = 0.038999 eps/sigma
Shifted-force residual at r_c - 1e-10 : |F_SF| = 1.084e-11 eps/sigma
Max |-dV_SF/dr - F_SF| = 3.46e-10 | Mismatch if linear ramp omitted = 0.038999
Explanation. Shifting the force by shifts by a constant across the entire sphere . Integrating backward from therefore requires the linear energy tilt ; omitting that tilt makes forces non-conservative () and injects artificial heating during MD integration.
Exercise 3¶
Problem. Implement argon_fcc_eos_pressure_GPa(a_A, r_cut_sigma=5.5) for solid Argon (, ) using central finite differences (1 eV/A^3 = 160.2176634 GPa), and verify agreement with virial_pressure from cauchy_born_elastic_constants_lj_cubic across to < 1e-4 GPa.
heading("Exercise 3: Implement It Yourself — Solid Argon Thermodynamic EOS vs Virial Pressure [GPa]")
EPS_AR_EV = (119.8 * constants.K_B) / constants.EV_TO_J
SIG_AR_A = 3.405
EV_A3_TO_GPA = constants.EV_TO_J * 1e21 # 1 eV / A^3 = 160.2176634 GPa
def argon_fcc_eos_pressure_GPa(a_A: float, r_cut_sigma: float = 5.5) -> dict:
"""Compute thermodynamic pressure -dE/dV and Cauchy-Born virial pressure [GPa] for solid FCC Argon."""
da = 1e-5
e_p = atomistics.cubic_lattice_cohesive_energy_lj(a_A + da, "fcc", epsilon=EPS_AR_EV, sigma=SIG_AR_A, r_cut_sigma=r_cut_sigma)
e_m = atomistics.cubic_lattice_cohesive_energy_lj(a_A - da, "fcc", epsilon=EPS_AR_EV, sigma=SIG_AR_A, r_cut_sigma=r_cut_sigma)
v_p = ((a_A + da) ** 3) / 4.0
v_m = ((a_A - da) ** 3) / 4.0
p_thermo_gpa = -((e_p - e_m) / (v_p - v_m)) * EV_A3_TO_GPA
cb = atomistics.cauchy_born_elastic_constants_lj_cubic(a_A, "fcc", epsilon=EPS_AR_EV, sigma=SIG_AR_A, r_cut_sigma=r_cut_sigma)
p_virial_gpa = cb["virial_pressure"] * EV_A3_TO_GPA
return {"P_thermo_GPa": float(p_thermo_gpa), "P_virial_GPa": float(p_virial_gpa)}
a_ar_eq = atomistics.equilibrium_lattice_constant_lj("fcc", epsilon=EPS_AR_EV, sigma=SIG_AR_A, r_cut_sigma=5.5)["a_eq"]
print(f"Predicted 0 K Argon FCC lattice constant a_eq = {a_ar_eq:.4f} A (Experimental 4 K Ar: ~5.31 A)\n")
print(f"{'a [A]':>8s} | {'P_thermo [GPa]':>15s} | {'P_virial [GPa]':>15s} | {'|Diff| [GPa]':>14s}")
print("-" * 62)
for a_val in [5.05, 5.18, a_ar_eq, 5.40, 5.55]:
res = argon_fcc_eos_pressure_GPa(a_val)
diff = abs(res["P_thermo_GPa"] - res["P_virial_GPa"])
print(f"{a_val:8.4f} | {res['P_thermo_GPa']:+15.6f} | {res['P_virial_GPa']:+15.6f} | {diff:14.2e}")
assert diff < 1e-4
assert abs(argon_fcc_eos_pressure_GPa(a_ar_eq)["P_virial_GPa"]) < 1e-6
Exercise 3: Implement It Yourself — Solid Argon Thermodynamic EOS vs Virial Pressure [GPa]
==========================================================================================
Predicted 0 K Argon FCC lattice constant a_eq = 5.2524 A (Experimental 4 K Ar: ~5.31 A)
a [A] | P_thermo [GPa] | P_virial [GPa] | |Diff| [GPa]
--------------------------------------------------------------
5.0500 | +0.590792 | +0.590792 | 2.49e-10
5.1800 | +0.153585 | +0.153585 | 1.55e-10
5.2524 | -0.000000 | -0.000000 | 1.11e-10
5.4000 | -0.186082 | -0.186082 | 6.51e-11
5.5500 | -0.267263 | -0.267263 | 3.65e-11
Summary. Because atomic volume scales as and every neighbor distance scales affinely as , the Clausius virial formula is the exact analytical volume derivative , and gives for solid argon at zero pressure, below the measured value of about at ; the static lattice sum leaves out the zero-point motion, which expands the real crystal.