The same starting image with two prescribed minima
I write a small part, check it, and then add the next part.
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 compare two explicitly chosen reference images under the same Allen–Cahn law. a is the portrait, b is an illustrated target, and u0 is their common starting field. Channel values range from 0 to 1. The energy is half the mean squared difference from each run's own reference. A different prescribed destination is not a solver error.
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-targets-results"
other_portrait = get_file("assets/images/saswata-cubist.png")
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: Prepare inputs and output locations
I name the input data and output directory explicitly. Re-running these cells replaces files in that lesson's output directory. I keep the original image or composition field separate from the evolving array.
out = Path(output)
out.mkdir(parents=True, exist_ok=True)
a = np.array(Image.open(portrait).convert('RGB').resize((256, 312)), float) / 255
b = np.array(Image.open(other_portrait).convert('RGB').resize((256, 312)), float) / 255
blocks = a.reshape(12, 26, 8, 32, 3).transpose(0, 2, 1, 3, 4).reshape(96, 26, 32, 3)
u0 = blocks[np.random.default_rng(19).permutation(96)].reshape(12, 8, 26, 32, 3).transpose(0, 2, 1, 3, 4).reshape(312, 256, 3)
font = portrait_font(24)
rows = []
Step 6: Repeat the operation and inspect each case
I repeat the operation over the specified cases. Read the loop variable first, then follow what changes on each pass. The assertions check the stated numerical or topological condition.
for i, t in enumerate(np.r_[0, np.geomspace(0.1, 240, 80)]):
im = Image.new('RGB', (1120, 820), '#f5f7f2')
d = ImageDraw.Draw(im)
d.text((24, 16), 'SAME START. SAME DYNAMICS. DIFFERENT ENERGY MINIMA.', font=font, fill='#173d40')
es = []
for x, r, title in [(24, a, 'Intended minimum: my portrait'), (584, b, 'Wrong target: cubist portrait')]:
u = r + (u0 - r) * np.exp(-0.03 * t)
e = 0.5 * np.mean((u - r) ** 2)
es.append(e)
d.text((x, 64), title, font=font, fill='#173d40')
im.paste(Image.fromarray(np.uint8(np.clip(u * 255, 0, 255))).resize((512, 624)), (x, 108))
d.text((x, 752), f'Own energy: {e:.7f}', font=font, fill='#173d40')
d.text((24, 786), f'Allen-Cahn forward relaxation | time {t:.2f} | targets explicitly prescribed', font=font, fill='#173d40')
im.save(out / f'frame-{i:03d}.png')
rows.append([t, *es])
Step 7: 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.
np.savetxt(out / 'diagnostics.csv', rows, delimiter=',', header='time,intended_target_energy,wrong_target_energy', comments='')
assert all((np.diff(np.array(rows)[:, i]).max() < 1e-12 for i in [1, 2]))
print('Both energies decrease. Final:', rows[-1])
Both energies decrease. Final: [np.float64(240.0), np.float64(2.9069139073647637e-08), np.float64(4.191449460185143e-08)]
Step 8: 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 →