PYTHON · STEP-BY-STEP LESSON

One portrait and two double-well evolution laws

I write a small part, check it, and then add the next part.

Download the notebook ↓ Open in Colab ↗

All Python notebook lessons →

The calculation, one step at a time

I 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…

I use the same double-well and gradient energy for Allen–Cahn and Cahn–Hilliard evolution. The portrait supplies the initial field only. u is a dimensionless grayscale intensity between approximately −1 and 1; kappa=0.4 is the gradient coefficient, dt=0.1 is the step size and S=2 is numerical stabilization. These dynamics are not a reverse inference of the original image.

I develop this calculation in small steps. I 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

I 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

Step 2: Read the image and check its dimensions

I download my public portrait once, or replace this path with my 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):
    # I 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-dynamics-results"

Step 3: Prepare the next part of the calculation

I 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
from PIL import Image, ImageDraw, ImageFont

Step 4: A portable display font

I 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)

Step 5: Set up the Fourier grid

I 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)
u = np.array(Image.open(portrait).convert('L').resize((256, 256)), float) / 127.5 - 1
ac = u.copy()
ch = u.copy()
mean0 = u.mean()
del u
k = 2 * np.pi * np.fft.fftfreq(256)
k2 = k[:, None] ** 2 + k[None, :] ** 2

Step 6: Prepare the next part of the calculation

I define dt, kap, S, font, small, records. 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.

dt = 0.1
kap = 0.4
S = 2
font = portrait_font(27)
small = portrait_font(23)
records = []

Step 7: Define the energy diagnostic

I calculate the bulk and gradient contributions in the same convention as the source program. Fourier normalization is part of this definition. I 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(np.fft.fft2(a)) ** 2) / 256 ** 4

Step 8: Advance the field and record the result

I apply the update in its original order. I record the mean, energy or other diagnostics at the specified intervals. I 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:
        i = step // 25
        im = Image.new('RGB', (1160, 730), '#f5f7f2')
        d = ImageDraw.Draw(im)
        d.text((24, 15), 'ONE FACE, TWO EVOLUTION LAWS', font=font, fill='#173d40')
        d.text((24, 52), f'Forward simulation | time {step * dt:.1f} | no target image or fidelity term', font=small, fill='#173d40')
        for x, a, title in [(24, ac, 'Allen-Cahn: nonconserved'), (604, ch, 'Cahn-Hilliard: conserved')]:
            d.text((x, 99), title, font=small, fill='#173d40')
            im.paste(Image.fromarray(np.uint8(np.clip((a + 1) * 127.5, 0, 255))).resize((528, 528)), (x, 139))
            d.text((x, 685), f'Mean field: {a.mean():+.5f} | change: {a.mean() - mean0:+.5f}', font=small, fill='#173d40')
        im.save(out / f'frame-{i:03d}.png')
        records.append([step * dt, ac.mean(), ch.mean(), energy(ac), energy(ch)])
    if step == 2000:
        break
    ac = np.fft.ifft2((np.fft.fft2(ac) - dt * np.fft.fft2(ac ** 3 - ac - S * ac)) / (1 + dt * (S + kap * k2))).real
    ch = np.fft.ifft2((np.fft.fft2(ch) - dt * k2 * np.fft.fft2(ch ** 3 - ch - S * ch)) / (1 + dt * k2 * (S + kap * k2))).real

Step 9: My check of this result

I 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(ac).all() and np.isfinite(ch).all()
assert abs(ch.mean() - mean0) < 1e-10
np.savetxt(out / 'diagnostics.csv', records, delimiter=',', header='time,AC_mean,CH_mean,AC_energy,CH_energy', comments='')
print('Initial/final mean:', mean0, ac.mean(), ch.mean())
Initial/final mean: 0.22601545745251223 0.5506254461057442 0.22601545745251247

Step 10: Review and extend the calculation

I first restart the kernel and run all the required cells. Then I 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. I retain the complete script for command-line use. The notebook embeds the calculation directly and does not need that script to run.

Read the notebook execution checks → · More Python, Julia and C lessons →