Start from the same perturbed portrait
Does the equation alone decide whether the face returns?
We compare two conserved Cahn–Hilliard calculations from the same initial color field. This first picture identifies the reference portrait.
We write a small part, check it, and then add the next part.
We start with a picture and a question. Each panel adds one idea before we turn to the equations, code and checks.
Does the equation alone decide whether the face returns?
We compare two conserved Cahn–Hilliard calculations from the same initial color field. This first picture identifies the reference portrait.
The reference image is explicitly supplied here.
A quadratic fidelity penalty makes the portrait the preferred field, subject to the conserved channel means. This is the restoration calculation.
What if the energy has no reference portrait?
The second calculation uses a double-well and gradient energy. Its local preferred values are \(-1\) and \(+1\), not the features of a face. The two energies, rather than the name Cahn–Hilliard alone, explain the different outcomes.
Final diagnostics: [200.0, np.float64(1.1488722250515884e-06), np.float64(0.054203544067834036), np.float64(2.736699755701011e-14), np.float64(0.25635801596276664), np.float64(0.23499795751631475), np.float64(0.09989267141149472)]
Does the calculated result agree with the picture I had in mind?
Follow the logic, active code and recorded results. We can then run the notebook, change one choice and compare again.
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.
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 keep both panels under conserved Cahn–Hilliard dynamics and change the energy. r is the reference portrait and u the evolving RGB fields. The portrait energy is quadratic; the domain energy contains a double well and a gradient coefficient kappa=0.4. dt=0.1 and stabilization S=2. Channels are independent and all quantities are dimensionless. This reproduces the full movie source; the shorter introductory notebook remains available separately.
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 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>=10.1" 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 download my public portrait once, or replace this path with your own image. An RGB array has two position axes and one channel axis. The three channels are red, green and blue.
from pathlib import Path
from urllib.request import urlretrieve
work = Path("lesson-data")
work.mkdir(exist_ok=True)
def get_file(relative_path):
# We download a public example only when its local copy is missing.
destination = work / Path(relative_path).name
if not destination.exists():
urlretrieve("https://saswataiith.github.io/" + relative_path, destination)
return destination
portrait = get_file("assets/images/saswata-landscape.png")
output = "portrait-abstraction-results"
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.
from pathlib import Path
import sys
import numpy as np
from PIL import Image, ImageDraw, ImageFont
We try the original font, then DejaVu Sans, then Pillow's default font. The font changes labels on the image only; it does not change a numerical field.
def portrait_font(size):
fonts = [Path('/') / 'System' / 'Library' / 'Fonts' / 'Helvetica.ttc', 'DejaVuSans.ttf']
for font in fonts:
try:
return ImageFont.truetype(str(font), size)
except OSError:
pass
return ImageFont.load_default(size=size)
We name the input data and output directory explicitly. Re-running these cells replaces files in that lesson's output directory. We keep the original image or composition field separate from the evolving array.
out = Path(output)
out.mkdir(parents=True, exist_ok=True)
r = np.asarray(Image.open(portrait).convert('RGB').resize((256, 312)), float) / 127.5 - 1
noise = np.random.default_rng(19).normal(0, 0.12, r.shape)
noise -= noise.mean((0, 1), keepdims=True)
u0 = r + noise
u = u0.copy()
mean0 = u.mean((0, 1))
axes = (0, 1)
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.
kx = 2 * np.pi * np.fft.fftfreq(256)
ky = 2 * np.pi * np.fft.fftfreq(312)
k2 = (ky[:, None] ** 2 + kx[None, :] ** 2)[..., None]
fft = lambda x: np.fft.fft2(x, axes=axes)
ifft = lambda x: np.fft.ifft2(x, axes=axes).real
e0 = fft(noise)
N = 256 * 312
dt = 0.1
kap = 0.4
We define S, font, rows. 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.
S = 2
font = portrait_font(23)
rows = []
We calculate the bulk and gradient contributions in the same convention as the source program. Fourier normalization is part of this definition. We compare this quantity through time within one model; energies from different functionals need not have the same meaning.
def energy(a):
return np.mean((a * a - 1) ** 2 / 4) + kap / 2 * np.sum(k2 * abs(fft(a)) ** 2) / (3 * N * N)
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(2001):
if step % 25 == 0:
t = step * dt
left = r + ifft(e0 * np.exp(-k2 * t))
energies = [0.5 * np.mean((left - r) ** 2), energy(u)]
drift = np.max(abs(u.mean((0, 1)) - mean0))
rows.append([t, *energies, drift, *u.mean((0, 1))])
im = Image.new('RGB', (1120, 845), '#f5f7f2')
d = ImageDraw.Draw(im)
d.text((24, 16), 'CAHN-HILLIARD IN BOTH PANELS: THE ENERGY CHANGES', font=font, fill='#173d40')
for x, a, title, e in [(24, left, 'Portrait energy: restores the face', energies[0]), (584, u, 'Double-well energy: makes domains', energies[1])]:
d.text((x, 63), title, font=font, fill='#173d40')
im.paste(Image.fromarray(np.uint8(np.clip((a + 1) * 127.5, 0, 255))).resize((512, 624)), (x, 108))
d.text((x, 750), f'Mean energy density (dimensionless): {e:.6f}', font=font, fill='#173d40')
d.text((24, 790), f'Time {t:.1f} | each channel mean conserved', font=font, fill='#173d40')
im.save(out / f'frame-{step // 25:03d}.png')
if step == 2000:
break
u = ifft((fft(u) - dt * k2 * fft(u ** 3 - u - S * u)) / (1 + dt * k2 * (S + kap * k2)))
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(u).all() and drift < 1e-10
v = np.array(rows)
assert np.max(np.diff(v[:, 2])) < 1e-09
np.savetxt(out / 'diagnostics.csv', rows, delimiter=',', header='time,portrait_energy,double_well_energy,max_channel_mean_drift,mean_R,mean_G,mean_B', comments='')
print('Final diagnostics:', rows[-1])
Final diagnostics: [200.0, np.float64(1.1488722250515884e-06), np.float64(0.054203544067834036), np.float64(2.736699755701011e-14), np.float64(0.25635801596276664), np.float64(0.23499795751631475), np.float64(0.09989267141149472)]
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.