Worked solutions to the three exercises of Lecture 13. 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: 2-D Spectral Spinodal Decomposition — Mass Conservation & Lyapunov Free-Energy Decay")
rng_2d = np.random.default_rng(1301)
nx, ny = 48, 48
Lx, Ly = 48.0, 48.0
W_2d, kap_2d, M_2d = 2.0, 1.0, 1.0
noise_zero_mean = rng_2d.uniform(-0.02, 0.02, size=(nx, ny))
noise_zero_mean -= np.mean(noise_zero_mean)
c0_crit = 0.50 + noise_zero_mean
res_crit = phase_field.cahn_hilliard_2d_spectral(
c0_crit, Lx=Lx, Ly=Ly, dt=0.25, n_steps=240, M=M_2d, W=W_2d, kappa=kap_2d, record_every=30
)
max_mass_drift = float(np.max(np.abs(res_crit["mean_compositions"] - res_crit["mean_compositions"][0])))
dF_steps = np.diff(res_crit["free_energies"])
print(f"{'Time t':>8s} | {'Mean <c(t)>':>14s} | {'Free Energy F[c]':>16s} | {'Domain Size L_d':>15s}")
print("-" * 64)
for t_v, m_v, f_v, ld_v in zip(res_crit["times"], res_crit["mean_compositions"], res_crit["free_energies"], res_crit["domain_sizes"]):
print(f"{t_v:8.1f} | {m_v:14.12f} | {f_v:16.4f} | {ld_v:15.3f}")
print(f"\nMax conservation drift |<c(t)> - <c(0)>| = {max_mass_drift:.3e} (< 1e-13)")
print(f"Max free-energy change between snapshots = {np.max(dF_steps):.4f} (strictly non-increasing)")
assert max_mass_drift < 1e-13
assert np.all(dF_steps <= 1e-12)
assert res_crit["domain_sizes"][-1] > 1.5 * res_crit["domain_sizes"][1]
_stdout.__exit__(None, None, None); plt.show = _show; plt.close("all")Exercise 1¶
Problem. On a box (), evaluate characteristic_domain_size_2d on for to verify to 10-13, and verify ginzburg_landau_free_energy_2d on a uniform field equals .
heading("Exercise 1: Analytical Verification of 2-D Structure-Factor Length Scale & Uniform Free Energy")
L_box = 48.0
xy = np.linspace(0.0, L_box, 48, endpoint=False)
X, Y = np.meshgrid(xy, xy, indexing="ij")
for m_mode in [2, 3, 6]:
field_m = 0.5 + 0.1 * np.cos(2.0 * np.pi * m_mode * X / L_box) * np.cos(2.0 * np.pi * m_mode * Y / L_box)
ld_num = phase_field.characteristic_domain_size_2d(field_m, Lx=L_box, Ly=L_box)
ld_th = L_box / (np.sqrt(2.0) * m_mode)
print(f"Mode m={m_mode} | computed L_d = {ld_num:.10f} | exact L/(sqrt(2)*m) = {ld_th:.10f}")
assert np.isclose(ld_num, ld_th, rtol=1e-13)
c_unif = np.full((48, 48), 0.30)
F_unif = phase_field.ginzburg_landau_free_energy_2d(c_unif, Lx=L_box, Ly=L_box, W=2.5, kappa=1.2)
F_exact = (L_box ** 2) * 2.5 * (0.30 ** 2) * (0.70 ** 2)
print(f"Uniform c=0.30: F_2d = {F_unif:.8f} vs exact Lx*Ly*f(c0) = {F_exact:.8f}")
assert np.isclose(F_unif, F_exact, rtol=1e-14)
Exercise 1: Analytical Verification of 2-D Structure-Factor Length Scale & Uniform Free Energy
==============================================================================================
Mode m=2 | computed L_d = 16.9705627485 | exact L/(sqrt(2)*m) = 16.9705627485
Mode m=3 | computed L_d = 11.3137084990 | exact L/(sqrt(2)*m) = 11.3137084990
Mode m=6 | computed L_d = 5.6568542495 | exact L/(sqrt(2)*m) = 5.6568542495
Uniform c=0.30: F_2d = 254.01600000 vs exact Lx*Ly*f(c0) = 254.01600000
Explanation. By trigonometric product-to-sum identities, concentrates 100% of its non-zero Fourier power at the four symmetric wavevectors , each of magnitude . Hence and identically.
Exercise 2¶
Problem. Verify that cahn_hilliard_2d_spectral raises ValueError on a 1-D input array, and demonstrate on a field () that an overly aggressive step violates Lyapunov monotonicity (), whereas maintains everywhere.
heading("Exercise 2: 2-D Shape Guard & Nonlinear Semi-Implicit Time-Step Overshoot Audit")
caught_1d = False
try:
phase_field.cahn_hilliard_2d_spectral(np.ones(16), Lx=16.0, Ly=16.0, dt=0.1, n_steps=5)
except ValueError:
caught_1d = True
assert caught_1d is True
xg_e2 = np.linspace(0.0, 32.0, 32, endpoint=False)
Xe2, _ = np.meshgrid(xg_e2, xg_e2, indexing="ij")
c0_32 = 0.05 + 0.02 * np.cos(2.0 * np.pi * 4.0 * Xe2 / 32.0)
res_bad_dt = phase_field.cahn_hilliard_2d_spectral(c0_32, Lx=32.0, Ly=32.0, dt=1.00, n_steps=1, M=1.0, W=8.0, kappa=0.05, record_every=1)
res_good_dt = phase_field.cahn_hilliard_2d_spectral(c0_32, Lx=32.0, Ly=32.0, dt=0.005, n_steps=40, M=1.0, W=8.0, kappa=0.05, record_every=10)
max_dF_bad = float(np.max(np.diff(res_bad_dt["free_energies"])))
max_dF_good = float(np.max(np.diff(res_good_dt["free_energies"])))
print(f"Oversize dt = 1.000: single-step delta F = {max_dF_bad:+.4e} (Lyapunov VIOLATED)")
print(f"Resolved dt = 0.005: max 10-step delta F = {max_dF_good:+.4e} (Strictly dissipative)")
assert np.isfinite(max_dF_bad) and max_dF_bad > 0.0 and max_dF_good <= 0.0
Exercise 2: 2-D Shape Guard & Nonlinear Semi-Implicit Time-Step Overshoot Audit
===============================================================================
Oversize dt = 1.000: single-step delta F = +3.9291e+01 (Lyapunov VIOLATED)
Resolved dt = 0.005: max 10-step delta F = -6.9567e-02 (Strictly dissipative)
Explanation. Although implicit treatment of removes the high- stiffness, the chemical driving force is still evaluated explicitly. When , composition overshoots the wells into the steep quartic walls ( or ), injecting spurious free energy (). Always monitor np.diff(res['free_energies']) <= 0 as a physics-based step-size diagnostic.
Exercise 3¶
Problem. Implement circularly_averaged_structure_factor(field, Lx, Ly, n_bins=14) to compute radially averaged SAXS intensity , and verify on a spinodal simulation ( vs ) that the scattering ring peak shifts to smaller as domains coarsen.
heading("Exercise 3: Implement It Yourself — Radially Averaged SAXS Structure Factor Peak Shift")
def circularly_averaged_structure_factor(field: np.ndarray, Lx: float, Ly: float, n_bins: int = 14) -> tuple[np.ndarray, np.ndarray]:
"""Compute circularly averaged 2-D scattering intensity S_rad(k) in radial wavenumber shells."""
u = np.asarray(field, dtype=float)
nx_f, ny_f = u.shape
kx = 2.0 * np.pi * np.fft.fftfreq(nx_f, d=float(Lx) / nx_f)
ky = 2.0 * np.pi * np.fft.fftfreq(ny_f, d=float(Ly) / ny_f)
kx2, ky2 = np.meshgrid(kx, ky, indexing="ij")
kmag = np.sqrt(kx2 ** 2 + ky2 ** 2).ravel()
sk = (np.abs(np.fft.fft2(u - np.mean(u))) ** 2).ravel()
k_max_ring = 0.5 * float(np.max(np.abs(kx)))
edges = np.linspace(1e-8, k_max_ring, n_bins + 1)
centers = 0.5 * (edges[:-1] + edges[1:])
s_rad = np.zeros(n_bins, dtype=float)
for b in range(n_bins):
mask = (kmag >= edges[b]) & (kmag < edges[b + 1])
if np.any(mask):
s_rad[b] = float(np.mean(sk[mask]))
return centers, s_rad
rng_e3 = np.random.default_rng(1303)
c0_saxs = 0.5 + rng_e3.uniform(-0.02, 0.02, size=(48, 48))
sim_saxs = phase_field.cahn_hilliard_2d_spectral(c0_saxs, Lx=48.0, Ly=48.0, dt=0.25, n_steps=360, M=1.0, W=2.0, kappa=1.0, record_every=40)
k_bins, S_t10 = circularly_averaged_structure_factor(sim_saxs["snapshots"][1], 48.0, 48.0, n_bins=14)
_, S_t90 = circularly_averaged_structure_factor(sim_saxs["snapshots"][-1], 48.0, 48.0, n_bins=14)
k_peak_early = float(k_bins[int(np.argmax(S_t10))])
k_peak_late = float(k_bins[int(np.argmax(S_t90))])
print(f"SAXS Guinier/spinodal ring peak: k_peak(t=10) = {k_peak_early:.3f} -> k_peak(t=90) = {k_peak_late:.3f} [1/grid]")
print(f"Peak scattering intensity : S_max(t=10) = {np.max(S_t10):.1f} -> S_max(t=90) = {np.max(S_t90):.1f}")
assert k_peak_late < k_peak_early and np.max(S_t90) > np.max(S_t10)
Exercise 3: Implement It Yourself — Radially Averaged SAXS Structure Factor Peak Shift
======================================================================================
SAXS Guinier/spinodal ring peak: k_peak(t=10) = 0.841 -> k_peak(t=90) = 0.393 [1/grid]
Peak scattering intensity : S_max(t=10) = 5653.3 -> S_max(t=90) = 15123.7
Summary. Just as observed in synchrotron time-resolved SAXS experiments on decomposing alloys, the spinodal scattering ring sharpens, intensifies, and migrates radially inward toward () as nanoscale domains coarsen.