One energy, two derivatives
The slope of the first curve gives the second. The slope of the second gives the third.
We build the calculation in small parts and test each part before continuing. The Python notebook follows the same sequence.
We use the website’s dimensionless two-dimensional model, with periodic boundaries, unit mobility and unit gradient coefficient. Composition c is a conserved field. The bulk free-energy density is c²(1-c)². Its derivative contributes 2c(1-c)(1-2c) to chemical potential. The elastic coefficient B(k) is zero for the chemical example. The elastic example uses a homogeneous 2D constitutive model with zero mean stress; it is not a calibrated alloy or a plane-strain reduction of a 3D eigenstrain.
Python notebook · Python notebook collection
If you would like a similar tutorial in Julia or C, email me with the lesson title and your intended use. I can share a Google Colab notebook with step-by-step explanations and worked examples.
Email: saswata_at_msme.iith.ac.in (replace _at_ with @).
Run notebook cells in order. Use Python with NumPy, Matplotlib and Jupyter.
The download includes installation commands and the actual check report.
We set the mean composition, \(c_0\), to 0.5. The small initial perturbation breaks the spatial uniformity. Subtracting its mean preserves our chosen composition; the printed value checks this initialization.
We follow the same point through the energy, slope and curvature curves. Then we compare a uniform composition with two nearby compositions in equal amounts.
The slope of the first curve gives the second. The slope of the second gives the third.
The moving line marks the same composition on all three curves.
A flat tangent. Is this a minimum?
The simulation below uses \(c_0=0.5\). This control explores the energy curves.
The orange lines mark the inflection compositions. Between them the chemical free-energy curvature is negative.
At \(c_0=0.5\), the energy has a horizontal tangent, but it is a maximum: \(f'(0.5)=0\) and \(f''(0.5)=-1\).
Equal amounts keep the mean at \(c_0\). Here \(\delta c=0.04\).
The faint segments show amplitudes 0.01, 0.02 and 0.03; the strong segment uses 0.04. Each midpoint gives an average chemical energy. The orange segment joins two nearby compositions; its midpoint gives their average chemical energy. It is not the equilibrium common tangent.
We start with a tiny composition difference. As we lengthen the chord, we keep the mean composition fixed. Faint lines show earlier steps.
Amounts: . The lever rule keeps the mean fixed; equal amounts apply at \(c_0=0.5\).
Bulk-energy hill on this path: .
The red ladder shows the bulk-energy rise along this chosen composition path. A physical nucleation barrier also includes interfacial energy and depends on the nucleus geometry. This panel is a schematic construction; the phase-field movie calculates its own evolution.
With \(u=c-\tfrac12\), the same double well has the quadratic–quartic form \(f=u^4-\tfrac12u^2+\tfrac1{16}\). This simply shifts the composition coordinate.
For two equal amounts at \(c_0-a\) and \(c_0+a\), the mean remains \(c_0\). The terms odd in \(a\) cancel when we average their free energies. For this quartic potential the result is exact:
If \(f''(c_0)>0\), these small fluctuations increase the chemical energy. If \(f''(c_0)<0\), sufficiently small ones lower it. At an inflection composition, the quadratic term vanishes and the finite-amplitude quartic term is positive. The chemical spinodal extends from approximately 0.21 to 0.79. To decide whether a spatial fluctuation grows, we also need its wavelength and the interfacial and elastic terms.
A spatial fluctuation also creates gradients. Linearizing the conserved evolution about a uniform composition gives the growth rate of a nonzero Fourier mode. Its amplitude is proportional to \(e^{\omega t}\):
Here \(M\) is mobility, \(\kappa\) the gradient coefficient and \(B\) the elastic kernel; \(k=|\mathbf k|\) and \(\mathbf n=\mathbf k/k\) specifies its direction. A mode grows when \(\omega>0\). In the purely chemical case \(B=0\), negative curvature permits sufficiently long waves to grow, while the gradient term suppresses very short waves. The zero mode fixes the mean and does not grow.
The common tangent for \(f(c)=c^2(1-c)^2\) touches the minima at \(c_\alpha=0\) and \(c_\beta=1\). These are the bulk binodal compositions in this model. To illustrate a continuous path toward them, we use a progress parameter \(0
The orange point lies on the chord at the fixed mean \(c_0\). At \(s=1\), both endpoint slopes and the chord slope are zero: the common tangent has been reached. Inside the chemical spinodal, this chosen path starts downhill. Between a binodal composition and the neighboring spinodal composition it initially rises. That bulk-energy hill illustrates why a small fluctuation can decay even though separated bulk phases have lower energy.
All quantities are dimensionless. The purple point marks the uniform composition. Orange marks the two nearby compositions and their average energy. Panel 5 follows a chosen path to the common tangent. We compare the chemical bulk energy here; interfacial and elastic energy add further terms in the full calculation. Curvature describes the limit of very small fluctuations, while panel 4 evaluates a finite fluctuation directly.
For the chemical free energy in this lesson,
The inflection points, where this curvature changes sign, are \((3-\sqrt{3})/6\approx0.2113\) and \((3+\sqrt{3})/6\approx0.7887\). Between them the chemical free energy has negative curvature, so sufficiently long-wavelength composition fluctuations grow. We can choose another mean within this chemical spinodal to explore a different phase fraction. Elastic energy adds a penalty and can narrow the unstable range.
Outside this interval, small fluctuations decay. Phase separation by nucleation requires a sufficiently large fluctuation or a suitable seed. Sustained thermal fluctuations can generate such events, but a small initial perturbation alone need not do so.
The random field in this lesson is added only once. It is not sustained thermal noise. Sustained noise supplies new fluctuations as time advances, rather than only at the start.
In a thermal Cahn–Hilliard–Cook model, we would add the divergence of a random flux so that composition remains conserved. Ideal Gaussian white noise has no correlation between distinct positions or times; fluctuation–dissipation fixes its strength in relation to temperature and mobility. On a numerical grid, that strength also depends on the cell size and time step. It is not an arbitrary noise amplitude added to every composition value.
Elastic kernel: derivation and assumptions
We show the purpose of each notebook cell beside its code and recorded result. The controls move through those results; they do not execute Python in the browser. The notebook remains available for running or changing the calculation.
Loading the lesson…
We start with the chemical case. The grid spacing is one dimensionless length unit. We use NumPy’s random generator with seed 714. We remove the mean of the seeded random perturbation so that the mean composition remains at our chosen c0, to floating-point accuracy.
import numpy as np
n = 64
dt = 0.2
k = 2 * np.pi * np.fft.fftfreq(n)
kx, ky = np.meshgrid(k, k, indexing="ij")
k2 = kx**2 + ky**2
c0 = 0.5
seed = 714
rng = np.random.default_rng(seed)
noise = 0.02 * (rng.random((n, n)) - 0.5)
noise -= noise.mean()
initial = c0 + noise
assert abs(initial.mean() - c0) < 1e-12
assert k2[0, 0] == 0
print("Mean composition =", initial.mean())
The gradient and elastic terms are implicit; the nonlinear bulk derivative is explicit. The zero Fourier mode is unchanged because k² is zero there. We check the mean and finite values after one update. These checks do not prove energy stability.
chemical_kernel = np.zeros_like(k2)
bulk_derivative = 2 * initial * (1 - initial) * (1 - 2 * initial)
numerator = np.fft.fft2(initial) - dt * k2 * np.fft.fft2(bulk_derivative)
denominator = 1 + dt * k2 * (k2 + chemical_kernel)
one_step = np.fft.ifft2(numerator / denominator).real
assert np.isfinite(one_step).all()
assert abs(one_step.mean() - initial.mean()) < 1e-12
print("Mean change after one update:", one_step.mean() - initial.mean())
We use the homogeneous elastic-energy kernel derived here from mechanical equilibrium. \(C_{11}\), \(C_{12}\) and \(C_{44}\) are dimensionless elastic stiffnesses here. The dilatational eigenstrain is dimensionless. We check the isotropic limit, in which the nonzero-mode kernel has no angular dependence. We also check that zero misfit removes the elastic contribution.
A real composition field has Fourier coefficients at opposite wave vectors. For each wave vector \(\mathbf{k}\), the coefficient at \(-\mathbf{k}\) is its complex conjugate: the real parts are equal and the imaginary parts have opposite signs, \[\widehat c(-\mathbf{k})=\widehat c(\mathbf{k})^*.\] Here the star means complex conjugation. This conjugate symmetry is what allows the inverse Fourier transform to recover a real field.
The elastic kernel in this calculation is real. To preserve that conjugate symmetry during an update, it must have the same value at opposite wave vectors: \(B(-\mathbf{k})=B(\mathbf{k})\). This symmetry already holds analytically for the dilatational kernel used here. We make it explicit in the stored numerical array by replacing the coefficients at opposite wave vectors with their average.
For example, \(m=1\) and \(m=-1\) are stored at indices 1 and 7. The modulo operation finds this opposite index. In two dimensions we apply the same rule to both directions, so index (1, 2) maps to (7, 6). We average the two kernel values so they agree.
def kernel(kx, ky, c11=4.0, c12=2.0, c44=3.0, eigenstrain=0.2):
"""B = E:C:E - (sigma0.n).Q^-1.(sigma0.n), E=eigenstrain*I.
Q_ik=C_ijkl*n_j*n_l; Q11=C11*nx²+C44*ny² (not C12).
This is a 2D constitutive model, not a reduction with epsilon_zz eigenstrain.
"""
k2 = kx * kx + ky * ky
radius = np.sqrt(np.where(k2 == 0, 1.0, k2))
nx, ny = (kx / radius, ky / radius)
q11 = c11 * nx * nx + c44 * ny * ny
q22 = c44 * nx * nx + c11 * ny * ny
q12 = (c12 + c44) * nx * ny
det = q11 * q22 - q12 * q12
det = np.where(k2 == 0, 1.0, det)
stress = (c11 + c12) * eigenstrain
b = 2 * (c11 + c12) * eigenstrain ** 2 - stress ** 2 * (q22 * nx * nx - 2 * q12 * nx * ny + q11 * ny * ny) / det
return np.where(k2 == 0, 0.0, b)
angles = np.linspace(0, 2 * np.pi, 33)
isotropic = kernel(np.cos(angles), np.sin(angles), c11=4, c12=2, c44=1)
assert np.ptp(isotropic) < 1e-12
assert np.allclose(kernel(kx, ky, eigenstrain=0), 0)
elastic_kernel = kernel(kx, ky, c11=4, c12=2, c44=3, eigenstrain=0.2)
# Find the opposite Fourier index in each direction.
opposite_index = (-np.arange(n)) % n
# Give opposite wave vectors the same real kernel value.
elastic_kernel = 0.5 * (elastic_kernel + elastic_kernel[np.ix_(opposite_index, opposite_index)])
assert np.isfinite(elastic_kernel).all()
print("Isotropic angular variation:", np.ptp(isotropic))
We advance both cases from identical fields for 50 steps. This is a short execution and conservation check. The complete program supplies longer runs and free-energy records. Timestep and spatial refinement are separate questions and have not been established by this notebook.
chemical = initial.copy()
elastic = initial.copy()
for step in range(50):
chemical_bulk = 2 * chemical * (1 - chemical) * (1 - 2 * chemical)
chemical_spectrum = np.fft.fft2(chemical) - dt * k2 * np.fft.fft2(chemical_bulk)
chemical = np.fft.ifft2(chemical_spectrum / (1 + dt*k2*(k2 + chemical_kernel))).real
elastic_bulk = 2 * elastic * (1 - elastic) * (1 - 2 * elastic)
elastic_spectrum = np.fft.fft2(elastic) - dt * k2 * np.fft.fft2(elastic_bulk)
elastic = np.fft.ifft2(elastic_spectrum / (1 + dt*k2*(k2 + elastic_kernel))).real
for result in (chemical, elastic):
assert np.isfinite(result).all()
assert abs(result.mean() - initial.mean()) < 1e-10
assert np.linalg.norm(chemical - elastic) > 0
print("Final time:", 50 * dt)
print("Field RMS difference:", np.sqrt(np.mean((chemical - elastic)**2)))
import matplotlib.pyplot as plt
fig, axes = plt.subplots(1, 2, figsize=(9, 4))
for ax, field, name in zip(axes, [chemical, elastic], ["Chemical", "With elasticity"]):
image = ax.imshow(field, vmin=0, vmax=1, origin="lower")
ax.set_title(name)
ax.set_xlabel("y grid index")
ax.set_ylabel("x grid index")
fig.colorbar(image, ax=axes, label="Composition c (dimensionless)")
plt.show()

We now use a 256 × 256 grid and run to time 400. The spacing stays at one, so this is a larger periodic domain. We keep the same mean composition, seed 714, time step and energy model. Every 25 updates we save the time and copies of both fields. The copies matter: each saved frame must retain its own values while the calculation continues. The calculation runs once; the animation will only display these saved arrays.
# A larger periodic domain, using the same model and initial mean.
movie_n = 256
movie_steps = 2000
save_every = 25
movie_k = 2 * np.pi * np.fft.fftfreq(movie_n)
movie_kx, movie_ky = np.meshgrid(movie_k, movie_k, indexing="ij")
movie_k2 = movie_kx**2 + movie_ky**2
rng = np.random.default_rng(seed)
movie_noise = 0.02 * (rng.random((movie_n, movie_n)) - 0.5)
movie_noise -= movie_noise.mean()
movie_initial = c0 + movie_noise
chemical_movie = movie_initial.copy()
elastic_movie = movie_initial.copy()
movie_b = kernel(movie_kx, movie_ky)
movie_opposite_index = (-np.arange(movie_n)) % movie_n
movie_b = 0.5 * (movie_b + movie_b[np.ix_(movie_opposite_index, movie_opposite_index)])
chemical_denominator = 1 + dt * movie_k2 * movie_k2
elastic_denominator = 1 + dt * movie_k2 * (movie_k2 + movie_b)
times = [0.0]
chemical_frames = [chemical_movie.copy()]
elastic_frames = [elastic_movie.copy()]
for step in range(1, movie_steps + 1):
bulk = 2 * chemical_movie * (1 - chemical_movie) * (1 - 2 * chemical_movie)
spectrum = np.fft.fft2(chemical_movie) - dt * movie_k2 * np.fft.fft2(bulk)
chemical_movie = np.fft.ifft2(spectrum / chemical_denominator).real
bulk = 2 * elastic_movie * (1 - elastic_movie) * (1 - 2 * elastic_movie)
spectrum = np.fft.fft2(elastic_movie) - dt * movie_k2 * np.fft.fft2(bulk)
elastic_movie = np.fft.ifft2(spectrum / elastic_denominator).real
if step % save_every == 0 or step == movie_steps:
times.append(step * dt)
chemical_frames.append(chemical_movie.copy())
elastic_frames.append(elastic_movie.copy())
for field in chemical_frames + elastic_frames:
assert np.isfinite(field).all()
assert abs(field.mean() - c0) < 1e-10
print("Saved frames:", len(times))
print("Last dimensionless time:", times[-1])

We create two images with a fixed composition scale. The function draw_frame(index) replaces their displayed values with the saved arrays at that index and updates the time label. FuncAnimation calls this function once for each saved frame. The 125 millisecond interval gives eight frames per second. This controls playback speed, not the numerical time step. We retain the movie variable so the animation object remains available. Closing the static figure prevents an extra still plot from appearing in the notebook.
from matplotlib.animation import FuncAnimation
fig, axes = plt.subplots(1, 2, figsize=(10, 5), layout="constrained")
images = []
for ax, field, title in zip(axes, [chemical_frames[0], elastic_frames[0]],
["Chemical", "With elasticity"]):
image = ax.imshow(field, origin="lower", vmin=0, vmax=1,
cmap="viridis", interpolation="nearest",
extent=(0, movie_n, 0, movie_n))
images.append(image)
ax.set_title(title)
ax.set_xlabel("y (dimensionless)")
ax.set_ylabel("x (dimensionless)")
fig.colorbar(images[0], ax=axes, label="Composition c (dimensionless)", shrink=0.8)
time_label = fig.suptitle(f"Seed {seed} | time = 0")
def draw_frame(index):
images[0].set_data(chemical_frames[index])
images[1].set_data(elastic_frames[index])
time_label.set_text(f"Seed {seed} | time = {times[index]:g}")
return images[0], images[1], time_label
movie = FuncAnimation(fig, draw_frame, frames=len(times),
interval=125, repeat=True)
plt.close(fig)
We use Matplotlib’s FFMpegWriter to encode the frames as an MP4. This requires the separate FFmpeg program on the system PATH, in addition to NumPy, Matplotlib and IPython. If it is missing in a Colab/Linux environment, we can install it in a separate cell with !apt-get -qq install ffmpeg; on macOS with Homebrew, the terminal command is brew install ffmpeg. IPython’s Video displays the saved file inside Jupyter or Colab. Setting embed=True stores the movie in the notebook output, so the notebook can carry the result with it. The controls allow playback and pause; loop repeats playback, not the physical evolution.
from matplotlib.animation import FFMpegWriter
from IPython.display import Video, display
movie_path = "phase-field-comparison.mp4"
movie.save(movie_path, writer=FFMpegWriter(fps=8), dpi=120)
print("Saved movie:", movie_path)
display(Video(movie_path, embed=True,
html_attributes="controls loop muted playsinline"))
To display an animation directly as JavaScript without encoding an MP4, we can instead use the following after Step 6. This embeds all rendered frames and can make the notebook much larger.
from IPython.display import HTML, display
with plt.rc_context({"animation.embed_limit": 50}):
display(HTML(movie.to_jshtml()))
Further reading: Matplotlib animation and IPython Video display.
The calculation above uses the same seed 714 initial field for both calculations on a 256 × 256 periodic grid. The left field has chemical and interfacial energy; the right also includes elastic energy. The composition scale stays fixed from 0 to 1 throughout.
The movie advances to dimensionless time 400 in 2,000 steps, with Δt = 0.2 and Δx = 1. We save a frame every 25 steps. This larger grid gives the patterns more room to develop. It enlarges the periodic domain; it is not a test of mesh convergence at fixed domain size. We retain the notebook’s model, stiffnesses and misfit. The chemical field has a small overshoot beyond 0 and 1; those values use the end colors in this fixed display scale. The calculated field is not clipped, and the diagnostics record its actual range.
Press play to watch the evolution. Playback loops back to the initial field at the end; the simulation itself does not reverse or cycle.
Chemical diagnostics · Elastic diagnostics · Parameters and numerical checks
We executed all Python notebook cells in a clean kernel. We also ran the longer comparison and saved its movie. These checks do not establish grid convergence or equilibrium.