Worked solutions to the three exercises of Lecture 14. 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: Conserved Cahn-Hilliard vs Non-Conserved Allen-Cahn on an Identical Circular Island")
nx_ac, ny_ac = 64, 64
Lx_ac, Ly_ac = 64.0, 64.0
W_ac, kap_ac, L_mob = 1.0, 2.0, 1.0 # diffuse width l_w = sqrt(2*2/1) = 2.0 grid spacings (well-resolved)
lw_ac = np.sqrt(2.0 * kap_ac / W_ac)
xg_ac = np.linspace(0.0, Lx_ac, nx_ac, endpoint=False)
X_ac, Y_ac = np.meshgrid(xg_ac, xg_ac, indexing="ij")
R0 = 18.0
r_dist = np.sqrt((X_ac - 0.5 * Lx_ac) ** 2 + (Y_ac - 0.5 * Ly_ac) ** 2)
circle_init = 0.5 * (1.0 - np.tanh((r_dist - R0) / lw_ac))
ac_circle = phase_field.allen_cahn_2d_spectral(
circle_init, Lx=Lx_ac, Ly=Ly_ac, dt=0.025, n_steps=600, L_mob=L_mob, W=W_ac, kappa=kap_ac, record_every=75
)
ch_circle = phase_field.cahn_hilliard_2d_spectral(
circle_init, Lx=Lx_ac, Ly=Ly_ac, dt=0.025, n_steps=600, M=1.0, W=W_ac, kappa=kap_ac, record_every=75
)
area_ac = (Lx_ac * Ly_ac) * ac_circle["phase_fractions"]
area_ch = (Lx_ac * Ly_ac) * ch_circle["mean_compositions"]
area_exact = area_ac[0] - 2.0 * np.pi * L_mob * kap_ac * ac_circle["times"]
print(f"Initial island area A(0) = {area_ac[0]:.2f} (pi*R0^2 = {np.pi * R0**2:.2f})")
print(f"At t = 15.0: Allen-Cahn area = {area_ac[-1]:.2f} vs analytical A0 - 2*pi*L*kappa*t = {area_exact[-1]:.2f}")
print(f"At t = 15.0: Cahn-Hilliard conserved integral = {area_ch[-1]:.6f} (drift = {abs(area_ch[-1] - area_ch[0]):.2e})")
assert np.isclose(area_ac[-1], area_exact[-1], rtol=0.015)
assert abs(area_ch[-1] - area_ch[0]) < 1e-11
_stdout.__exit__(None, None, None); plt.show = _show; plt.close("all")Exercise 1¶
Problem. Simulate a circular domain ( on , , ) for via allen_cahn_2d_spectral () and verify that the fitted area rate agrees with within .
heading("Exercise 1: Parametric Verification of dA/dt = -2*pi*L_mob*kappa Across (L_mob, kappa)")
xg = np.linspace(0.0, 64.0, 64, endpoint=False)
X, Y = np.meshgrid(xg, xg, indexing="ij")
rad = np.sqrt((X - 32.0) ** 2 + (Y - 32.0) ** 2)
for L_m, kap in [(0.5, 2.0), (1.0, 2.0), (1.5, 1.5)]:
lw = np.sqrt(2.0 * kap / 1.0)
eta0 = 0.5 * (1.0 - np.tanh((rad - 17.0) / lw))
sim = phase_field.allen_cahn_2d_spectral(eta0, Lx=64.0, Ly=64.0, dt=0.025, n_steps=400, L_mob=L_m, W=1.0, kappa=kap, record_every=50)
area_t = (64.0 ** 2) * sim["phase_fractions"]
dA_dt_num = float(np.polyfit(sim["times"], area_t, 1)[0])
dA_dt_ex = -2.0 * np.pi * L_m * kap
print(f"L_mob={L_m:.1f}, kappa={kap:.1f} | dA/dt measured = {dA_dt_num:9.4f} | exact = {dA_dt_ex:9.4f} | rel err = {abs(dA_dt_num - dA_dt_ex)/abs(dA_dt_ex):.3%}")
assert np.isclose(dA_dt_num, dA_dt_ex, rtol=0.02)
Exercise 1: Parametric Verification of dA/dt = -2*pi*L_mob*kappa Across (L_mob, kappa)
======================================================================================
L_mob=0.5, kappa=2.0 | dA/dt measured = -6.2779 | exact = -6.2832 | rel err = 0.085%
L_mob=1.0, kappa=2.0 | dA/dt measured = -12.5016 | exact = -12.5664 | rel err = 0.516%
L_mob=1.5, kappa=1.5 | dA/dt measured = -13.9812 | exact = -14.1372 | rel err = 1.103%
Explanation. Whenever the diffuse width and , the normal gradient profile remains locked to , making the integrated area rate quantitatively exact across parameter combinations.
Exercise 2¶
Problem. Verify allen_cahn_2d_spectral raises ValueError on 1-D input, and demonstrate the grid-pinning failure mode on (): compare a resolved interface () against an under-resolved interface () and show that the under-resolved circle becomes artificially trapped on the grid.
heading("Exercise 2: Grid-Pinning (Lattice Trapping) Audit When Interface Width l_w << dx")
caught_dim = False
try:
phase_field.allen_cahn_2d_spectral(np.zeros(32), Lx=32.0, Ly=32.0, dt=0.1, n_steps=5)
except ValueError:
caught_dim = True
assert caught_dim is True
xg = np.linspace(0.0, 64.0, 64, endpoint=False)
X, Y = np.meshgrid(xg, xg, indexing="ij")
rad = np.sqrt((X - 32.0) ** 2 + (Y - 32.0) ** 2)
# Under-resolved interface: l_w = sqrt(2*0.05/10) = 0.10 << dx = 1.0
eta_pinned = 0.5 * (1.0 - np.tanh((rad - 14.0) / 0.10))
sim_pinned = phase_field.allen_cahn_2d_spectral(eta_pinned, Lx=64.0, Ly=64.0, dt=0.05, n_steps=400, L_mob=1.0, W=10.0, kappa=0.05, record_every=100)
# Measure steady post-relaxation shrinkage rate over t in [5, 20] after initial 1-grid-cell sharpening:
rate_pinned = float((64.0 ** 2) * (sim_pinned["phase_fractions"][-1] - sim_pinned["phase_fractions"][1]) / (sim_pinned["times"][-1] - sim_pinned["times"][1]))
rate_continuum = -2.0 * np.pi * 1.0 * 0.05 # expected -0.31416 grid^2 / time
print(f"Under-resolved (l_w = 0.10*dx): post-snap dA/dt = {rate_pinned:.6f} vs continuum -2*pi*L*kappa = {rate_continuum:.5f} (FROZEN ON MESH)")
assert abs(rate_pinned) < 0.02 * abs(rate_continuum)
Exercise 2: Grid-Pinning (Lattice Trapping) Audit When Interface Width l_w << dx
================================================================================
Under-resolved (l_w = 0.10*dx): post-snap dA/dt = -0.000000 vs continuum -2*pi*L*kappa = -0.31416 (FROZEN ON MESH)
Explanation. When , every grid node sits at or where , creating an artificial discrete Peierls-like energy barrier between grid points. In computational materials engineering, always enforce so interfaces translate smoothly across mesh cells.
Exercise 3¶
Problem. Implement track_circular_grain_extinction(R0=8.0, L_mob=1.0, kappa=2.0, W=1.0) on a domain to verify the analytical extinction time : confirm linearity () for and complete grain disappearance () by .
heading("Exercise 3: Implement It Yourself — Parabolic Radius Law R^2(t) & Grain Extinction Time")
def track_circular_grain_extinction(R0: float = 8.0, L_mob: float = 1.0, kappa: float = 2.0, W: float = 1.0) -> dict:
"""Simulate circular grain collapse through extinction and verify R^2(t) = R0^2 - 2*L_mob*kappa*t."""
L_dom, N_dom = 48.0, 48
xg = np.linspace(0.0, L_dom, N_dom, endpoint=False)
X, Y = np.meshgrid(xg, xg, indexing="ij")
rad = np.sqrt((X - 0.5 * L_dom) ** 2 + (Y - 0.5 * L_dom) ** 2)
lw = np.sqrt(2.0 * kappa / W)
eta0 = 0.5 * (1.0 - np.tanh((rad - R0) / lw))
t_ext = (R0 ** 2) / (2.0 * L_mob * kappa)
dt = 0.04
n_steps = int(np.ceil(1.25 * t_ext / dt))
sim = phase_field.allen_cahn_2d_spectral(eta0, Lx=L_dom, Ly=L_dom, dt=dt, n_steps=n_steps, L_mob=L_mob, W=W, kappa=kappa, record_every=20)
r2_sim = (L_dom ** 2) * sim["phase_fractions"] / np.pi
pre_mask = sim["times"] <= 0.625 * t_ext
t_pre, r2_pre = sim["times"][pre_mask], r2_sim[pre_mask]
slope, intercept = np.polyfit(t_pre, r2_pre, 1)
r2_pred = slope * t_pre + intercept
r2_gof = float(1.0 - np.sum((r2_pre - r2_pred) ** 2) / np.sum((r2_pre - np.mean(r2_pre)) ** 2))
t_ext_fit = float(-intercept / slope)
return {
"t_ext_exact": t_ext,
"t_ext_fit": t_ext_fit,
"r2_gof": r2_gof,
"final_max_eta": float(np.max(sim["final"])),
}
ext = track_circular_grain_extinction(R0=8.0, L_mob=1.0, kappa=2.0, W=1.0)
print(f"Exact t_ext = {ext['t_ext_exact']:.2f} | Extrapolated t_ext = {ext['t_ext_fit']:.2f} | R^2 linearity = {ext['r2_gof']:.6f} | max(eta_final) = {ext['final_max_eta']:.2e}")
assert ext["r2_gof"] > 0.9995
assert np.isclose(ext["t_ext_fit"], ext["t_ext_exact"], rtol=0.06)
assert ext["final_max_eta"] < 1e-3
Exercise 3: Implement It Yourself — Parabolic Radius Law R^2(t) & Grain Extinction Time
=======================================================================================
Exact t_ext = 16.00 | Extrapolated t_ext = 16.61 | R^2 linearity = 0.999973 | max(eta_final) = 5.32e-06
Summary. Plotting vs. yields a straight line with whose horizontal intercept is 16.6, against the sharp-interface extinction time (shifted slightly by the finite diffuse-interface excess area ), after which the grain vanishes into the matrix.