Worked solutions to the three exercises of Lecture 12. 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: Landau Double-Well Spinodal Region & Exact Planar tanh Interface")
c_grid = np.linspace(0.0, 1.0, 401)
W_val, kappa_val = 2.0, 0.5
dw = phase_field.double_well_potential(c_grid, W=W_val)
cs_minus = 0.5 * (1.0 - 1.0 / np.sqrt(3.0))
cs_plus = 0.5 * (1.0 + 1.0 / np.sqrt(3.0))
assert np.isclose(phase_field.double_well_potential(cs_minus, W=W_val)["d2f_dc2"], 0.0, atol=1e-14)
assert np.isclose(phase_field.double_well_potential(0.5, W=W_val)["d2f_dc2"], -1.0 * W_val, atol=1e-14)
x_dom = np.linspace(-10.0, 10.0, 2001)
prof = phase_field.equilibrium_interface_profile_1d(x_dom, W=W_val, kappa=kappa_val, x0=0.0)
f_prof = phase_field.double_well_potential(prof["c"], W=W_val)["f"]
grad_e = 0.5 * kappa_val * (prof["dc_dx"] ** 2)
integrand = f_prof + grad_e
sigma_num = float(np.sum(0.5 * (integrand[:-1] + integrand[1:]) * np.diff(x_dom)))
print(f"Spinodal interval where f''(c) < 0 : [{cs_minus:.6f}, {cs_plus:.6f}]")
print(f"Diffuse interface width l_w : {prof['interface_width']:.6f} (exact sqrt(2*kappa/W) = {np.sqrt(2*kappa_val/W_val):.6f})")
print(f"Pointwise equipartition max |f - 0.5*kappa*(dc/dx)^2| : {np.max(np.abs(f_prof - grad_e)):.2e}")
print(f"Surface tension sigma: quadrature = {sigma_num:.8f} vs exact sqrt(kappa*W/18) = {prof['interfacial_energy_exact']:.8f}")
assert np.allclose(f_prof, grad_e, atol=1e-14)
assert np.isclose(sigma_num, prof["interfacial_energy_exact"], rtol=1e-6)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11, 4))
ax1.plot(c_grid, dw["f"], lw=2.2, label=r"$f(c) = W c^2(1-c)^2$")
ax1.plot(c_grid, 0.1 * dw["d2f_dc2"], "--", lw=1.8, label=r"$0.1\,f''(c)$")
ax1.axhline(0.0, color="k", lw=0.8)
ax1.axvspan(cs_minus, cs_plus, alpha=0.18, color="tab:red", label=r"Spinodal ($f''(c) \leq 0$)")
ax1.set_xlabel("Composition $c$ [-]")
ax1.set_ylabel("Free-energy density [arb. units]")
ax1.set_title("Landau Double-Well & Chemical Spinodal")
ax1.legend(fontsize=8)
ax2.plot(x_dom, prof["c"], lw=2.2, label=r"$c_{\mathrm{eq}}(x)$")
ax2.plot(x_dom, f_prof / np.max(f_prof), "--", lw=1.8, label=r"Normalized $f(c) = \frac{\kappa}{2}(dc/dx)^2$")
ax2.set_xlim(-4.0, 4.0)
ax2.set_xlabel("Position $x$ [arb. length]")
ax2.set_ylabel("Composition / Normalized Energy [-]")
ax2.set_title(rf"Diffuse Planar Interface ($\ell_w = {prof['interface_width']:.2f}$, $\sigma = {prof['interfacial_energy_exact']:.4f}$)")
ax2.legend(fontsize=8)
label_panels(fig)
plt.show()
_stdout.__exit__(None, None, None); plt.show = _show; plt.close("all")Exercise 1¶
Problem. On a periodic domain (), construct a smooth two-interface slab for , evaluate phase_field.ginzburg_landau_free_energy_1d, and verify across three pairs that to within 10-5.
heading("Exercise 1: Periodic Two-Interface Slab Free Energy F[c] == 2 * sqrt(kappa * W / 18)")
L_box, N_pts = 40.0, 256
x_g = np.linspace(0.0, L_box, N_pts, endpoint=False)
for W_t, kap_t in [(4.0, 0.5), (2.0, 0.5), (4.0, 1.0)]:
pr = phase_field.equilibrium_interface_profile_1d(x_g, W=W_t, kappa=kap_t)
lw = pr["interface_width"]
c_slab = 0.5 * (np.tanh((x_g - 10.0) / lw) - np.tanh((x_g - 30.0) / lw))
F_num = phase_field.ginzburg_landau_free_energy_1d(c_slab, L=L_box, W=W_t, kappa=kap_t)
F_exact = 2.0 * pr["interfacial_energy_exact"]
print(f"W={W_t:.1f}, kappa={kap_t:.1f} (l_w={lw:.3f}) | F_1d = {F_num:.8f} | 2*sigma = {F_exact:.8f} | rel err = {abs(F_num - F_exact)/F_exact:.2e}")
assert np.isclose(F_num, F_exact, rtol=1e-5)
Exercise 1: Periodic Two-Interface Slab Free Energy F[c] == 2 * sqrt(kappa * W / 18)
====================================================================================
W=4.0, kappa=0.5 (l_w=0.500) | F_1d = 0.66666667 | 2*sigma = 0.66666667 | rel err = 6.22e-11
W=2.0, kappa=0.5 (l_w=0.707) | F_1d = 0.47140452 | 2*sigma = 0.47140452 | rel err = 2.36e-16
W=4.0, kappa=1.0 (l_w=0.707) | F_1d = 0.94280904 | 2*sigma = 0.94280904 | rel err = 2.36e-16
Explanation. On a periodic ring , a precipitate domain ( on , elsewhere) is bounded by two planar interfaces at and . Because in the bulk plateaus and , the entire Ginzburg–Landau integral concentrates inside the two transition zones, yielding .
Exercise 2¶
Problem. Verify that equilibrium_interface_profile_1d raises ValueError when W <= 0 or kappa <= 0, and check numerically on cahn_hilliard_1d_fd () that is stable at () yet blows up at () due to the biharmonic CFL penalty.
heading("Exercise 2: Parameter Positivity Guard & 16x Biharmonic CFL Collapse Under 2x Grid Refinement")
for bad_W, bad_kap in [(0.0, 1.0), (-2.0, 1.0), (1.0, 0.0), (1.0, -0.5)]:
caught = False
try:
phase_field.equilibrium_interface_profile_1d(np.linspace(-2.0, 2.0, 11), W=bad_W, kappa=bad_kap)
except ValueError:
caught = True
assert caught, f"Expected ValueError for W={bad_W}, kappa={bad_kap}"
L_test, dt_test = 32.0, 0.05
x32 = np.linspace(0.0, L_test, 32, endpoint=False)
x64 = np.linspace(0.0, L_test, 64, endpoint=False)
c32_0 = 0.5 + 0.01 * np.cos(4.0 * 2.0 * np.pi * x32 / L_test)
c64_0 = 0.5 + 0.01 * np.cos(4.0 * 2.0 * np.pi * x64 / L_test)
res_32 = phase_field.cahn_hilliard_1d_fd(c32_0, L=L_test, dt=dt_test, n_steps=200, M=1.0, W=2.0, kappa=0.5)
with np.errstate(over="ignore", invalid="ignore"):
res_64 = phase_field.cahn_hilliard_1d_fd(c64_0, L=L_test, dt=dt_test, n_steps=200, M=1.0, W=2.0, kappa=0.5)
stable_32 = bool(np.all(np.isfinite(res_32["final"])) and np.max(np.abs(res_32["final"])) <= 1.1)
blew_64 = bool((not np.all(np.isfinite(res_64["final"]))) or np.max(np.abs(res_64["final"])) > 1e6)
print(f"N=32 (dx=1.0, dt_crit ~ 0.2500): dt=0.05 stable = {stable_32}, F_end = {res_32['free_energies'][-1]:.4f}")
print(f"N=64 (dx=0.5, dt_crit ~ 0.0156): dt=0.05 blew up = {blew_64}")
assert stable_32 is True and blew_64 is True
Exercise 2: Parameter Positivity Guard & 16x Biharmonic CFL Collapse Under 2x Grid Refinement
=============================================================================================
N=32 (dx=1.0, dt_crit ~ 0.2500): dt=0.05 stable = True, F_end = 1.9652
N=64 (dx=0.5, dt_crit ~ 0.0156): dt=0.05 blew up = True
Explanation. Whereas second-order Fickian diffusion has ( smaller when is halved), the fourth-order Cahn–Hilliard operator scales as , shrinking by (from 0.25 down to 0.0156) and motivating semi-implicit spectral time stepping.
Exercise 3¶
Problem. Implement my_cahn_hilliard_1d_spectral(c_init, L, dt, n_steps, M=1.0, W=1.0, kappa=1.0) in pure NumPy using np.fft.fft and np.fft.ifft, verify its final composition profile matches phase_field.cahn_hilliard_1d_spectral to < 1e-13, and verify .
heading("Exercise 3: Implement It Yourself — 1-D Semi-Implicit Fourier Spectral Cahn-Hilliard Solver")
def my_cahn_hilliard_1d_spectral(
c_init: np.ndarray, L: float, dt: float, n_steps: int, M: float = 1.0, W: float = 1.0, kappa: float = 1.0
) -> np.ndarray:
"""NumPy semi-implicit Fourier spectral integrator for 1-D periodic Cahn-Hilliard dynamics."""
c = np.asarray(c_init, dtype=float).ravel().copy()
n = c.size
k = 2.0 * np.pi * np.fft.fftfreq(n, d=float(L) / n)
k2 = k ** 2
denom = 1.0 + dt * M * kappa * (k2 ** 2)
c_hat = np.fft.fft(c)
for _ in range(n_steps):
df_dc = 2.0 * W * c * (1.0 - c) * (1.0 - 2.0 * c)
c_hat = (c_hat - dt * M * k2 * np.fft.fft(df_dc)) / denom
c = np.real(np.fft.ifft(c_hat))
return c
rng_ex3 = np.random.default_rng(1203)
c0_ex3 = 0.42 + 0.03 * rng_ex3.standard_normal(64)
c_mine = my_cahn_hilliard_1d_spectral(c0_ex3, L=32.0, dt=0.05, n_steps=300, M=1.0, W=2.0, kappa=0.5)
c_lib = phase_field.cahn_hilliard_1d_spectral(c0_ex3, L=32.0, dt=0.05, n_steps=300, M=1.0, W=2.0, kappa=0.5)["final"]
max_err = float(np.max(np.abs(c_mine - c_lib)))
mass_drift = abs(float(np.mean(c_mine) - np.mean(c0_ex3)))
print(f"Max |c_mine - c_lib| = {max_err:.3e} | Conservation drift |<c(T)> - <c(0)>| = {mass_drift:.3e}")
assert max_err < 1e-13 and mass_drift < 1e-14
Exercise 3: Implement It Yourself — 1-D Semi-Implicit Fourier Spectral Cahn-Hilliard Solver
===========================================================================================
Max |c_mine - c_lib| = 0.000e+00 | Conservation drift |<c(T)> - <c(0)>| = 5.551e-17
Summary. Diagonalizing the fourth-order operator via FFT reduces each semi-implicit Cahn–Hilliard step to two 1-D FFTs and pointwise division by , guaranteeing exact solute conservation and handling of biharmonic stiffness.