One energy, two derivatives
The slope of the first curve gives the second. The slope of the second gives the third.
We write a small part, check it, and then add the next part.
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 evolve a conserved dimensionless composition c on a periodic grid. The bulk energy is c²(1−c)². The chemical potential contains its derivative, a gradient contribution and, in elastic mode, a homogeneous elastic contribution. n is the number of points per direction, dt is the time step, and steps is the number of updates. All model quantities are dimensionless.
We develop this calculation in small steps. We run a cell, inspect its result and test it before adding the next part. Run the cells in order in Jupyter. A code cell defines a part of the calculation or carries it out; defining a function does not run it.
I permit free noncommercial teaching, learning and demonstrations with acknowledgment. Research and commercial use require my written permission. Earlier licensed releases retain their permissions. Read the code-use terms.
Copyright (c) 2026 Saswata Bhattacharyya.
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.
We install the packages listed in the next cell once in the same environment as the notebook. In Jupyter or Colab, remove the comment marker from the installation line below if a package is missing. NumPy stores arrays and evaluates numerical operations. Matplotlib displays plots. Pillow reads and writes images. This installation does not change the model parameters.
# %pip install numpy matplotlib
import numpy as np
assert np.isfinite(np.array([0.0, 1.0])).all()
print("NumPy is ready:", np.__version__)
NumPy is ready: 2.1.3
We retain the default values from the original calculation. The output name locates the files written by this notebook.
mode = 'chemical'
c0 = 0.5
output = 'phase-field-results'
n = None
dt = 0.2
steps = 2000
We define the following operations. These are the same operations as in the original source, written on separate lines so their order is clear. Inspect their values before running the next cell.
import sys
from pathlib import Path
import numpy as np
We derive this kernel from mechanical equilibrium in the elastic-energy derivation.
We calculate B for each wave-vector direction from the stiffness constants and a dilatational misfit. \(C_{11}\), \(C_{12}\) and \(C_{44}\) are the stiffness constants, and eigenstrain is the prescribed stress-free strain. This example uses dimensionless stiffness and strain. The zero mode corresponds to the specified macroscopic condition; it is not a directional mode.
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)
We construct Fourier wave numbers from the grid spacing and domain size. A Laplacian multiplies each Fourier mode by minus its squared wave number. The zero Fourier mode represents the spatial mean.
out = Path(output)
out.mkdir(parents=True, exist_ok=True)
if n is None:
n = 256 if mode == 'elastic' else 64
if mode not in ('chemical', 'elastic'):
raise ValueError('Choose chemical or elastic')
k = 2 * np.pi * np.fft.fftfreq(n)
kx, ky = np.meshgrid(k, k, indexing='ij')
k2 = kx * kx + ky * ky
b = kernel(kx, ky) if mode == 'elastic' else np.zeros_like(k2)
opposite_index = -np.arange(n) % n
We use NumPy’s random generator with seed 714 and subtract the perturbation’s mean so the initial mean composition remains 0.5.
We construct Fourier wave numbers from the grid spacing and domain size. A Laplacian multiplies each Fourier mode by minus its squared wave number. The zero Fourier mode represents the spatial mean.
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.
# Give opposite wave vectors the same real kernel value.
b = 0.5 * (b + b[np.ix_(opposite_index, opposite_index)])
seed = 714
rng = np.random.default_rng(seed)
noise = 0.02 * (rng.random((n, n)) - 0.5)
noise -= noise.mean()
c = c0 + noise
initial_mean = c.mean()
print("Mean composition =", initial_mean)
records = []
denominator = 1 + dt * k2 * (k2 + b)
Mean composition = 0.5
We define this operation before calling it. We keep its arguments explicit so we can test it separately.
def record(step):
h = np.fft.fft2(c)
energy = np.mean(c * c * (1 - c) ** 2) + 0.5 * np.sum((k2 + b) * np.abs(h) ** 2) / n ** 4
records.append([step * dt, c.mean(), energy, c.min(), c.max()])
np.savetxt(out / f'field_{step:04d}.csv', c, delimiter=',')
We define the following operations. These are the same operations as in the original source, written on separate lines so their order is clear. Inspect their values before running the next cell.
record(0)
We apply the update in its original order. We record the mean, energy or other diagnostics at the specified intervals. We do not clip the numerical field. A saved picture is a display of the field, not a substitute for a conservation check.
for step in range(1, steps + 1):
h = (np.fft.fft2(c) - dt * k2 * np.fft.fft2(2 * c * (1 - c) * (1 - 2 * c))) / denominator
c = np.fft.ifft2(h).real
if step % 25 == 0 or step == steps:
record(step)
We check finite values, conservation or the known reference result as specified below. An assertion stops the notebook if the condition fails. Inspect the quantities and tolerance rather than suppressing a failure.
assert np.isfinite(c).all()
assert abs(c.mean() - initial_mean) < 1e-10
np.savetxt(out / 'diagnostics.csv', records, delimiter=',', header='time,mean,energy_density,min,max', comments='')
print(mode, 'mean drift', abs(c.mean() - initial_mean), 'energy', records[0][2], records[-1][2])
chemical mean drift 2.1094237467877974e-15 energy 0.06259409563917234 0.025080532883736018
We plot c without changing its stored values. The color scale is a display choice. The mean checks test conservation, while the sampled energy history helps assess this particular run. It does not prove stability for arbitrary time steps.
import matplotlib.pyplot as plt
values = np.asarray(records)
fig, axes = plt.subplots(1, 2, figsize=(10, 4))
image = axes[0].imshow(c, origin="lower")
fig.colorbar(image, ax=axes[0], label="Dimensionless composition c")
axes[0].set_title(mode + " phase separation")
axes[0].set_xlabel("Grid index")
axes[0].set_ylabel("Grid index")
axes[1].plot(values[:, 0], values[:, 2])
axes[1].set_xlabel("Dimensionless time")
axes[1].set_ylabel("Dimensionless mean energy density")
plt.show()

We read the CSV snapshots in simulation-time order. These are the fields already calculated above; making the movie does not rerun the evolution.
snapshot_steps = [0] + list(range(25, steps + 1, 25))
if snapshot_steps[-1] != steps:
snapshot_steps.append(steps)
times = [step * dt for step in snapshot_steps]
saved_fields = [np.loadtxt(out / f"field_{step:04d}.csv", delimiter=",")
for step in snapshot_steps]
print("Saved frames:", len(saved_fields))
We create one image with a fixed composition scale. The function draw_frame(index) replaces its displayed values with the saved array 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, ax = plt.subplots(figsize=(6, 5), layout="constrained")
image = ax.imshow(saved_fields[0], origin="lower", vmin=0, vmax=1,
cmap="viridis", interpolation="nearest")
fig.colorbar(image, ax=ax, label="Composition c (dimensionless)")
ax.set_xlabel("y grid index")
ax.set_ylabel("x grid index")
time_label = ax.set_title(f"{mode}: time = 0")
def draw_frame(index):
image.set_data(saved_fields[index])
time_label.set_text(f"{mode}: time = {times[index]:g}")
return image, 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 = str(out / "phase-field.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"))
Further reading: Matplotlib animation and IPython Video display.
This is the movie made by the notebook above with its default chemical case on a 64 × 64 grid. Changing the mode or grid input changes the movie that the notebook produces. The shorter lesson builds a matched 256 × 256 chemical and elastic comparison.
Then we change one input, predict its effect and compare the result with that prediction. A successful check establishes the tested property; it does not establish convergence or equilibrium.
We first restart the kernel and run all the required cells. The notebook embeds the calculation directly and does not need that script to run.