PYTHON · STEP-BY-STEP LESSON

Fourier diffusion: reproduce the full example

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

Download the notebook Open in Colab

All Python notebook lessons

Why does the fine detail disappear first?

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

1

Start with a bumpy concentration profile

Start with a bumpy concentration profile: schematic panel 1

Which bumps will disappear first?

We combine a constant mean with one long and one short cosine wave.

2

Separate the wavelengths

Separate the wavelengths: schematic panel 2

The same profile contains more than one length scale.

The two curves are contributions to the profile, not two separate substances.

3

Watch the amplitudes decay

Watch the amplitudes decay: schematic panel 3

The shorter wave fades faster.

For diffusion, each Fourier amplitude is multiplied by \(e^{-Dk^2t}\). Larger \(k\) means faster decay; the zero mode preserves the mean.

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 diffusion of two cosine modes on a periodic line. c is a dimensionless concentration field, x is position on a dimensionless line of length 2π, t is dimensionless time, and D=1 is the dimensionless diffusivity. The mode with wave number 4 decays sixteen times faster than the mode with wave number 1.

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 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: Input values

We retain the default values from the original calculation. The output name locates the files written by this notebook.

output = 'diffusion-results'

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

Step 4: Set up the Fourier grid

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.

out = Path(output)
out.mkdir(parents=True, exist_ok=True)
n = 128
x = 2 * np.pi * np.arange(n) / n
k = 2 * np.pi * np.fft.fftfreq(n, d=2 * np.pi / n)
c0 = 1 + 0.4 * np.cos(x) + 0.2 * np.cos(4 * x)
rows = []

Step 5: 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 t in [0, 0.02, 0.1, 0.3, 1.0]:
    c = np.fft.ifft(np.fft.fft(c0) * np.exp(-k * k * t)).real
    exact = 1 + 0.4 * np.exp(-t) * np.cos(x) + 0.2 * np.exp(-16 * t) * np.cos(4 * x)
    rows.append([t, c.mean(), np.max(np.abs(c - exact))])
    np.savetxt(out / f'profile_{t:.2f}.csv', np.column_stack([x, c]), delimiter=',')

Step 6: 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,mean,max_exact_error', comments='')
assert max((r[2] for r in rows)) < 1e-12
print('Fourier diffusion: max exact error', max((r[2] for r in rows)))
Fourier diffusion: max exact error 4.440892098500626e-16

Plot and interpret the result

We compare the profiles at the saved times. The rapidly varying mode fades first, while the mean remains 1. The horizontal coordinate and concentration are dimensionless.

import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(8, 4))
for t in (0, .02, .1, .3, 1.):
    profile = np.loadtxt(out / f"profile_{t:.2f}.csv", delimiter=",")
    ax.plot(profile[:, 0], profile[:, 1], label=f"t={t}")
ax.set_xlabel("Dimensionless position x")
ax.set_ylabel("Dimensionless concentration c")
ax.legend()
plt.show()
Computed result from the Fourier diffusion: reproduce the full example notebook
Result from the executed notebook cell.

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