We start with a picture and a question. Each panel adds one idea before we turn to the equations, code and checks.
1
Start near the top of the double well
Can a small fluctuation lower the bulk energy?
In this notebook, \(c\) is a signed dimensionless field, with preferred values \(-1\) and \(+1\), rather than a mole fraction between 0 and 1. At \(c=0\), the bulk energy \(f=(c^2-1)^2/4\) has negative curvature.
2
Not every wavelength grows
Why does the curve fall below zero at large wave number?
The interfacial term penalizes rapid spatial changes. In a simple linearized example, the growth rate is proportional to \(k^2(1-k^2)\). This curve is schematic, not a fit to the calculation.
3
A wave gains amplitude
The mean stays fixed while rich and poor regions develop.
The mean stays at zero while the two field values separate. The curves illustrate early growth of one unstable mode. Later coarsening requires the nonlinear calculation below.
4
Compare with the notebook
Recorded notebook output.
Does the calculated result agree with the picture I had in mind?
Panels 1–3 are explanatory schematics. Their scales and illustrative fields do not replace the parameters or numerical results in the notebook. Panel 4 shows the notebook’s recorded result or checks.
The calculation, one step at a time
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 calculate a dimensionless Cahn–Hilliard model with bulk energy (c²−1)²/4. c is the conserved field, not an SI concentration. The mobility and gradient coefficient are both 1, the grid spacing is 1, dt=0.2 and the random seed is 42. The nonlinear bulk term is explicit. Energy decrease alone does not establish numerical convergence.
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.
Step 1: Prepare the Python environment
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 pillow matplotlibimportnumpyasnpassertnp.isfinite(np.array([0.0,1.0])).all()print("NumPy is ready:",np.__version__)
NumPy is ready: 2.1.3
Step 2: Input values
We retain the default values from the original calculation. The output name locates the files written by this notebook.
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.
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.
We define history, snapshots. 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.
history=[]snapshots={100:1,400:2,steps:3}
Step 6: Define diagnostics
We define this operation before calling it. We keep its arguments explicit so we can test it separately.
We define stops. 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.
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.
forstepinrange(steps+1):ifstep%10==0:mean,energy=diagnostics(c)history.append((step,step*dt,mean,energy))ifstepinsnapshots:v=np.clip((c+1)/2,0,1)rgb=np.stack([np.interp(v,[0,0.25,0.5,0.75,1],stops[:,j])forjinrange(3)],axis=-1)img=Image.fromarray(np.rint(rgb).astype('uint8'))img.resize((640,640),Image.Resampling.BICUBIC).save(output/f'spinodal-{snapshots[step]}.png')ifstep==steps:breakc_hat=np.fft.fft2(c)bulk_hat=np.fft.fft2(c*c*c-c)c=np.fft.ifft2((c_hat-dt*k2*bulk_hat)/(1+dt*k2*k2)).realifnotnp.isfinite(c).all():raiseRuntimeError('Non-finite solution; reduce the time step.')
Step 9: Prepare the next part of the calculation
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.
We define drift, max_energy_rise. 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.
np.save(output/'final_field.npy',c)drift=abs(c.mean()-initial_mean)max_energy_rise=max(np.diff([row[3]forrowinhistory]))print(f'Mean drift: {drift:.3e}')print(f'Initial/final energy: {history[0][3]:.6f} / {history[-1][3]:.6f}')print(f'Max energy change between sampled states: {max_energy_rise:.3e}')ifdrift>1e-10:raiseRuntimeError('Conservation diagnostic failed.')
Mean drift: 4.902e-17
Initial/final energy: 0.254339 / 0.102015
Max energy change between sampled states: -6.576e-05
Plot and interpret the result
We show the calculated final field and sampled energy. The composition scale follows this model, whose minima are −1 and 1. These values do not represent a mole fraction between 0 and 1.
importmatplotlib.pyplotaspltvalues=np.asarray(history)fig,axes=plt.subplots(1,2,figsize=(10,4))im=axes[0].imshow(c,origin="lower",cmap="turbo",vmin=-1,vmax=1)fig.colorbar(im,ax=axes[0],label="Dimensionless field c")axes[0].set_title("Final field")axes[0].set_xlabel("Grid index")axes[0].set_ylabel("Grid index")axes[1].plot(values[:,1],values[:,3])axes[1].set_xlabel("Dimensionless time")axes[1].set_ylabel("Mean energy density")plt.show()
Result from the executed notebook cell.
Step 11: Review and extend the calculation
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.
Technical details
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.