PYTHON · STEP-BY-STEP LESSON

The same starting image with two prescribed minima

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

Download the notebook Open in Colab

All Python notebook lessons

Same start, different destinations

We start with a picture and a question. Each panel adds one idea before we turn to the equations, code and checks.

1

Keep the starting portrait

Keep the starting portrait: schematic panel 1

Does the starting image determine the final image?

We hold the starting field fixed and change the prescribed target.

2

Choose the first minimum

Choose the first minimum: schematic panel 2

The energy now prefers this target.

The parabola represents one prescribed minimum in an illustrative field coordinate.

3

Choose a different minimum

Choose a different minimum: schematic panel 3

A different energy can tell a different story.

This second parabola illustrates changing the target, not discovering an unknown face. The notebook contains the actual image-based construction.

4

Compare with the notebook

Calculation details
Both energies decrease. Final: [np.float64(240.0), np.float64(2.9069139073647637e-08), np.float64(4.191449460185143e-08)]

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.

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 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.

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>=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

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-targets-results"
other_portrait = get_file("assets/images/saswata-cubist.png")

Step 3: 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.

import sys
from pathlib import Path
import numpy as np
from PIL import Image, ImageDraw, ImageFont

Step 4: A portable display font

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)

Step 5: Prepare inputs and output locations

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

We 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: Our check of this result

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.

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

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.

Technical details

Read the notebook execution checks

More step-by-step Python lessons