When an Alnico permanent-magnet alloy, Fe–Cr duplex stainless steel, or –– spinodal bronze is quenched inside its miscibility gap, thermal composition fluctuations amplify into either a bicontinuous, percolating labyrinth () or isolated nanoscale droplets (). Once phase separation saturates at the equilibrium compositions and , the microstructure does not freeze: driven by interfacial capillary energy, small precipitates dissolve and feed larger domains via Ostwald ripening / Lifshitz–Slyozov–Wagner (LSW) coarsening. In this lecture we simulate 2-D microstructure evolution with phase_field.cahn_hilliard_2d_spectral, show exact solute conservation and Ginzburg–Landau Lyapunov decay, contrast critical vs. off-critical morphologies, and measure domain coarsening via the 2-D structure factor phase_field.characteristic_domain_size_2d.
Learning objectives¶
Integrate 2-D periodic spinodal decomposition using the semi-implicit Fourier spectral scheme in
phase_field.cahn_hilliard_2d_spectral.Verify exact machine-precision solute conservation (protected by at the zero-wavenumber Fourier mode) and monotonic Lyapunov decay of
phase_field.ginzburg_landau_free_energy_2d.Explain why critical quenches () form interconnected bicontinuous networks whereas off-critical quenches () pinch off into minority-phase droplets satisfying the lever rule.
Quantify coarsening kinetics by extracting the characteristic domain wavelength from the 2-D scattering structure factor via
phase_field.characteristic_domain_size_2d.
Time: about 60 min
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))1. Principles and governing equations¶
On a doubly periodic 2-D domain discretized on an grid, the 2-D Cahn–Hilliard equation evolves down the conserved gradient flow of the 2-D Ginzburg–Landau functional (phase_field.ginzburg_landau_free_energy_2d):
1.1 Exact Mass Conservation & Monotonic Lyapunov Free-Energy Dissipation¶
Exact Mass Conservation: In 2-D Fourier space with wavevector and , the semi-implicit spectral update (
phase_field.cahn_hilliard_2d_spectral) reads:At , annihilates the chemical-potential update identically, so and the spatial mean is invariant to machine round-off.
Lyapunov Free-Energy Decay: Differentiating along periodic solutions of and integrating by parts gives:
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]
Demonstration 1: 2-D Spectral Spinodal Decomposition — Mass Conservation & Lyapunov Free-Energy Decay
=====================================================================================================
Time t | Mean <c(t)> | Free Energy F[c] | Domain Size L_d
----------------------------------------------------------------
0.0 | 0.500000000000 | 288.6296 | 2.659
7.5 | 0.500000000000 | 232.7102 | 7.096
15.0 | 0.500000000000 | 191.6310 | 8.197
22.5 | 0.500000000000 | 171.5184 | 9.042
30.0 | 0.500000000000 | 157.0049 | 9.780
37.5 | 0.500000000000 | 147.3801 | 10.372
45.0 | 0.500000000000 | 140.3642 | 10.861
52.5 | 0.500000000000 | 135.0552 | 11.264
60.0 | 0.500000000000 | 130.4349 | 11.619
Max conservation drift |<c(t)> - <c(0)>| = 1.110e-16 (< 1e-13)
Max free-energy change between snapshots = -4.6203 (strictly non-increasing)
What Demonstration 1 shows. Over 240 spectral time steps (), the mean composition drifts by only (rounding error), while the Ginzburg–Landau free energy falls monotonically from 288.6 (the bulk energy of the uniform solution, , plus the gradient energy of the initial noise) to 130.4 as solute partitions into and domains and coarsens from 7.10 to 11.62.
2. Morphology Selection: Interconnected Labyrinth () vs. Droplets ()¶
Why do symmetric critical quenches () form bicontinuous, percolating channels, whereas off-critical quenches (, still well inside the spinodal ) pinch off into circular precipitates? By the equilibrium lever rule between and , the equilibrium area fraction of the -rich phase () equals . In 2-D continuum percolation, an isotropic phase at sits right at the symmetric bicontinuous threshold, whereas at capillary surface tension minimizes interfacial perimeter by rounding the minority phase into isolated disks.
heading("Demonstration 2: Critical Bicontinuous Network (c0 = 0.50) vs Off-Critical Droplets (c0 = 0.35)")
c0_off = 0.35 + noise_zero_mean # identical initial spatial fluctuations, shifted mean
res_off = phase_field.cahn_hilliard_2d_spectral(
c0_off, Lx=Lx, Ly=Ly, dt=0.25, n_steps=240, M=M_2d, W=W_2d, kappa=kap_2d, record_every=40
)
frac_beta_crit = float(np.mean(res_crit["final"] > 0.5))
frac_beta_off = float(np.mean(res_off["final"] > 0.5))
print(f"Critical quench (c0=0.50): minority/beta area fraction (c > 0.5) = {frac_beta_crit:.4f}, L_d(60) = {res_crit['domain_sizes'][-1]:.2f}")
print(f"Off-critical (c0=0.35): minority/beta area fraction (c > 0.5) = {frac_beta_off:.4f}, L_d(60) = {res_off['domain_sizes'][-1]:.2f}")
print(f"Off-critical mass drift |<c(t)> - 0.35| = {np.max(np.abs(res_off['mean_compositions'] - 0.35)):.3e}")
assert abs(frac_beta_crit - 0.50) < 0.04
assert 0.25 < frac_beta_off < 0.40 # slightly below 0.35 due to Gibbs-Thomson capillary shift on curved droplets
assert np.max(np.abs(res_off["mean_compositions"] - 0.35)) < 1e-13
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10.5, 4.3))
im1 = ax1.imshow(res_crit["final"].T, origin="lower", extent=[0, Lx, 0, Ly], cmap="RdBu_r", vmin=0.0, vmax=1.0)
ax1.set_title(rf"Critical $c_0 = 0.50$ (Bicontinuous, $f_\beta = {frac_beta_crit:.2f}$)")
ax1.set_xlabel("$x$ [grid units]")
ax1.set_ylabel("$y$ [grid units]")
plt.colorbar(im1, ax=ax1, fraction=0.046, label="$c(x,y)$")
im2 = ax2.imshow(res_off["final"].T, origin="lower", extent=[0, Lx, 0, Ly], cmap="RdBu_r", vmin=0.0, vmax=1.0)
ax2.set_title(rf"Off-Critical $c_0 = 0.35$ (Droplets, $f_\beta = {frac_beta_off:.2f}$)")
ax2.set_xlabel("$x$ [grid units]")
ax2.set_ylabel("$y$ [grid units]")
plt.colorbar(im2, ax=ax2, fraction=0.046, label="$c(x,y)$")
label_panels(fig)
plt.show()
Demonstration 2: Critical Bicontinuous Network (c0 = 0.50) vs Off-Critical Droplets (c0 = 0.35)
===============================================================================================
Critical quench (c0=0.50): minority/beta area fraction (c > 0.5) = 0.5013, L_d(60) = 11.62
Off-critical (c0=0.35): minority/beta area fraction (c > 0.5) = 0.3138, L_d(60) = 10.39
Off-critical mass drift |<c(t)> - 0.35| = 5.551e-17

Figure 13.1. Composition field at . (a) : two interpenetrating domains. (b) : droplets of the minority phase.
What Demonstration 2 shows. The off-critical area fraction, frac_beta_off , is below the lever-rule value 0.35 for flat interfaces. One reason is the Gibbs–Thomson effect: a droplet of radius raises the chemical potential by , so the matrix around it holds more solute than . Meanwhile, smaller droplets have higher chemical potential than larger droplets, driving diffusive solute transport from small droplets to large droplets (Ostwald ripening).
3. Structure-Factor Coarsening & Scattering Length Scale ¶
In small-angle X-ray or neutron scattering (SAXS / SANS), experimentalists monitor spinodal decomposition via the static structure factor . phase_field.characteristic_domain_size_2d computes the first-moment mean wavenumber and converts it into the characteristic real-space domain wavelength :
We run a longer coarsening trajectory ( on our 48x48 grid) and decompose the total Ginzburg–Landau energy to watch spinodal amplification transition into capillary-driven coarsening.
heading("Demonstration 3: Two-Stage Spinodal Evolution — Bulk Separation Followed by Interfacial Coarsening")
res_long = phase_field.cahn_hilliard_2d_spectral(
c0_crit, Lx=Lx, Ly=Ly, dt=0.30, n_steps=400, M=M_2d, W=W_2d, kappa=kap_2d, record_every=40
)
dx_g, dy_g = Lx / nx, Ly / ny
f_bulk_hist = [
float(np.sum(phase_field.double_well_potential(snap, W=W_2d)["f"]) * dx_g * dy_g)
for snap in res_long["snapshots"]
]
f_grad_hist = res_long["free_energies"] - np.array(f_bulk_hist)
t_arr = res_long["times"]
ld_arr = res_long["domain_sizes"]
print(f"Early spinodal wavelength L_d(t=12) = {ld_arr[1]:.2f} vs Linear lambda_max = "
f"{phase_field.cahn_hilliard_dispersion(1.0, c0=0.5, W=W_2d, kappa=kap_2d)['lambda_max']:.2f}")
print(f"Late coarsened wavelength L_d(t=120)= {ld_arr[-1]:.2f} (grew by {ld_arr[-1]/ld_arr[1]:.2f}x)")
assert ld_arr[-1] > 1.6 * ld_arr[1]
assert np.all(np.diff(res_long["free_energies"]) <= 1e-12)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11, 4))
ax1.plot(t_arr, res_long["free_energies"], "o-", lw=2.0, label=r"Total $\mathcal{F}[c]$")
ax1.plot(t_arr, f_bulk_hist, "s--", lw=1.7, label=r"Bulk $\iint f(c)\,dx\,dy$")
ax1.plot(t_arr, f_grad_hist, "^-.", lw=1.7, label=r"Gradient $\iint \frac{\kappa}{2}|\nabla c|^2\,dx\,dy$")
ax1.set_xlabel("Time $t$ [arb. units]")
ax1.set_ylabel("Free energy [arb. units]")
ax1.set_title("Bulk Separation vs. Capillary Coarsening")
ax1.legend(fontsize=8)
ax2.plot(t_arr[1:], ld_arr[1:], "o-", color="tab:purple", lw=2.1, label=r"$L_d(t) = 2\pi / \langle k \rangle$")
ax2.axhline(
phase_field.cahn_hilliard_dispersion(1.0, c0=0.5, W=W_2d, kappa=kap_2d)["lambda_max"],
ls=":", color="k", label=r"Linear $\lambda_{\max} = 2\pi\sqrt{2}/k_c$"
)
ax2.set_xlabel("Time $t$ [arb. units]")
ax2.set_ylabel("Characteristic domain size $L_d$ [grid units]")
ax2.set_title("Structure-Factor Coarsening Trajectory")
ax2.legend(fontsize=8)
label_panels(fig)
plt.show()
Demonstration 3: Two-Stage Spinodal Evolution — Bulk Separation Followed by Interfacial Coarsening
==================================================================================================
Early spinodal wavelength L_d(t=12) = 7.78 vs Linear lambda_max = 6.28
Late coarsened wavelength L_d(t=120)= 14.92 (grew by 1.92x)

Figure 13.2. (a) Total, bulk and gradient free energy against time. (b) Domain size against time; the dotted line is the wavelength of fastest growth in the linear theory.
What Demonstration 3 shows. The split of the energy into bulk and gradient parts shows two regimes.
Spinodal Amplification (): Bulk free energy falls rapidly as rolls off the hilltop into the 0 and 1 wells, while gradient energy rises from as interfaces form; at the domain size is , already above the linear value .
Capillary Coarsening (): Once bulk phase separation is complete, both and equal half of the total interfacial energy ( by equipartition) and decay in lockstep as interfaces merge and grows steadily.
4. Sensitivity to the parameters¶
How does solute mobility (controlled exponentially by aging temperature via Arrhenius diffusion) affect the microstructure? We sweep at fixed annealing time , and also verify kinetic time-rescaling collapse: does produce the same microstructure as when is matched?
heading("Demonstration 4: Mobility Sensitivity M & Exact dimensionless (M * t) Scaling Collapse")
print(f"{'Mobility M':>10s} | {'Fixed t_end':>11s} | {'Scaled M*t':>10s} | {'Free Energy F':>14s} | {'Domain Size L_d':>15s}")
print("-" * 72)
ld_by_M = []
for m_val in [0.25, 0.50, 1.00, 2.00]:
r_m = phase_field.cahn_hilliard_2d_spectral(
c0_crit, Lx=Lx, Ly=Ly, dt=0.20, n_steps=200, M=m_val, W=W_2d, kappa=kap_2d, record_every=200
)
ld_by_M.append(r_m["domain_sizes"][-1])
print(f"{m_val:10.2f} | {40.0:11.1f} | {m_val * 40.0:10.1f} | {r_m['free_energies'][-1]:14.4f} | {r_m['domain_sizes'][-1]:15.3f}")
# Exact dimensionless time M * t = 30.0 test (with matched M * dt = 0.25):
r_slow = phase_field.cahn_hilliard_2d_spectral(c0_crit, Lx=Lx, Ly=Ly, dt=0.50, n_steps=120, M=0.5, W=W_2d, kappa=kap_2d, record_every=120)
r_fast = phase_field.cahn_hilliard_2d_spectral(c0_crit, Lx=Lx, Ly=Ly, dt=0.125, n_steps=120, M=2.0, W=W_2d, kappa=kap_2d, record_every=120)
collapse_diff = float(np.max(np.abs(r_slow["final"] - r_fast["final"])))
print(f"\nExact M*t=30 collapse max |c(M=0.5, t=60) - c(M=2.0, t=15)| = {collapse_diff:.3e}")
assert np.all(np.diff(ld_by_M) > 0.0)
assert collapse_diff < 1e-14
Demonstration 4: Mobility Sensitivity M & Exact dimensionless (M * t) Scaling Collapse
======================================================================================
Mobility M | Fixed t_end | Scaled M*t | Free Energy F | Domain Size L_d
------------------------------------------------------------------------
0.25 | 40.0 | 10.0 | 212.8428 | 7.454
0.50 | 40.0 | 20.0 | 175.1738 | 8.868
1.00 | 40.0 | 40.0 | 144.3765 | 10.580
2.00 | 40.0 | 80.0 | 114.2146 | 12.947
Exact M*t=30 collapse max |c(M=0.5, t=60) - c(M=2.0, t=15)| = 0.000e+00
Inside the algorithm¶
What Demonstration 4 shows. Constant mobility enters purely as a clock-rate multiplier : higher aging mobility accelerates coarsening ( increases monotonically with at fixed ), and matching collapses onto to 10-15.
Below we inspect phase_field.characteristic_domain_size_2d and phase_field.cahn_hilliard_2d_spectral, and verify our NumPy 2-D structure-factor calculation against the library implementation.
Check against the library¶
heading("Inside the Algorithm: phase_field.characteristic_domain_size_2d")
print(show_source(phase_field.characteristic_domain_size_2d))
u_test = res_crit["final"]
kx = 2.0 * np.pi * np.fft.fftfreq(nx, d=Lx / nx)
ky = 2.0 * np.pi * np.fft.fftfreq(ny, d=Ly / ny)
kx2d, ky2d = np.meshgrid(kx, ky, indexing="ij")
kmag = np.sqrt(kx2d ** 2 + ky2d ** 2)
sk = np.abs(np.fft.fft2(u_test - np.mean(u_test))) ** 2
sk[0, 0] = 0.0
ld_hand = float(2.0 * np.pi / (np.sum(kmag * sk) / np.sum(sk)))
ld_lib = phase_field.characteristic_domain_size_2d(u_test, Lx=Lx, Ly=Ly)
print(f"L_d by hand = {ld_hand:.10f} | L_d library = {ld_lib:.10f} | diff = {abs(ld_hand - ld_lib):.3e}")
assert np.isclose(ld_hand, ld_lib, rtol=1e-15, atol=1e-15)
Inside the Algorithm: phase_field.characteristic_domain_size_2d
===============================================================
def characteristic_domain_size_2d(field: np.ndarray, Lx: float, Ly: float) -> float:
"""Compute characteristic domain wavelength L_d = 2*pi / <k> from the first moment of structure factor S(k)."""
u = np.asarray(field, dtype=float)
nx, ny = u.shape
dx, dy = float(Lx) / nx, float(Ly) / ny
kx = 2.0 * np.pi * np.fft.fftfreq(nx, d=dx)
ky = 2.0 * np.pi * np.fft.fftfreq(ny, d=dy)
kx_2d, ky_2d = np.meshgrid(kx, ky, indexing="ij")
k_mag = np.sqrt(kx_2d**2 + ky_2d**2)
s_k = np.abs(np.fft.fft2(u - np.mean(u))) ** 2
s_k[0, 0] = 0.0
denom = float(np.sum(s_k))
if denom <= 1e-30:
return 0.0
k_mean = float(np.sum(k_mag * s_k) / denom)
return float(2.0 * np.pi / k_mean) if k_mean > 0.0 else 0.0
L_d by hand = 11.6194984323 | L_d library = 11.6194984323 | diff = 0.000e+00
Exercises¶
Worked solutions are in 13_solutions.ipynb. The cell below the list is a short self-check to start from.
Verify a result. On a box (), evaluate
characteristic_domain_size_2don for to verify to 10-13, and verifyginzburg_landau_free_energy_2don a uniform field equals .Find how it fails. Verify that
cahn_hilliard_2d_spectralraisesValueErroron a 1-D input array, and demonstrate on a field () that an overly aggressive step violates Lyapunov monotonicity (), whereas maintains everywhere.Implement it yourself. 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("Self-check for the exercises")
xg = np.linspace(0.0, 48.0, 48, endpoint=False)
X2, Y2 = np.meshgrid(xg, xg, indexing="ij")
m_chk = 3
c_chk = 0.5 + 0.1 * np.cos(2.0 * np.pi * m_chk * X2 / 48.0) * np.cos(2.0 * np.pi * m_chk * Y2 / 48.0)
ld_chk = phase_field.characteristic_domain_size_2d(c_chk, Lx=48.0, Ly=48.0)
ld_exact = 48.0 / (np.sqrt(2.0) * m_chk)
print(f"Checkerboard m=3: L_d computed = {ld_chk:.8f} vs exact L/(sqrt(2)*m) = {ld_exact:.8f}")
assert np.isclose(ld_chk, ld_exact, rtol=1e-13)
print("All checks passed.")
Self-check for the exercises
============================
Checkerboard m=3: L_d computed = 11.31370850 vs exact L/(sqrt(2)*m) = 11.31370850
All checks passed.