STEP-BY-STEP TEACHING CODE

Diffusion through Fourier modes.

We build the calculation in small parts and test each part before continuing. The Python notebook follows the same sequence.

We calculate diffusion on a periodic line. All quantities in this example are dimensionless: position x, time t, concentration c and diffusivity D. The domain length is 2π and D = 1. Fourier wave number k identifies a spatial mode. We use exact propagation of each mode rather than an approximate time-stepping scheme.

Python notebook · Python notebook collection

If you would like a similar tutorial in Julia or C, email me with the lesson title and your intended use. I can share a Google Colab notebook with step-by-step explanations and worked examples.

Email: saswata_at_msme.iith.ac.in (replace _at_ with @).

Run notebook cells in order. Extract the complete collection without changing its folder structure: the phase-field lesson imports the original kernel from its parent folder. Use Python with NumPy, Matplotlib and Jupyter,.

Technical details

The download includes installation commands and the actual check report.

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…

Step 1: Define the grid

We omit the repeated endpoint of the periodic interval. We check that the grid spacing times the number of points equals the domain length.

Python

import numpy as np
n = 128
length = 2 * np.pi
spacing = length / n
x = spacing * np.arange(n)
k = 2 * np.pi * np.fft.fftfreq(n, d=spacing)
diffusivity = 1.0
assert np.isclose(n * spacing, length)
assert k[0] == 0
print("Grid points:", n, "spacing:", spacing)

Step 2: The initial concentration

The constant term sets the mean. Two cosine terms give two spatial wavelengths. We check the mean and transform the field back before introducing evolution.

Python

initial = 1 + 0.4 * np.cos(x) + 0.2 * np.cos(4 * x)
spectrum = np.fft.fft(initial)
assert abs(initial.mean() - 1) < 1e-12
assert np.max(np.abs(np.fft.ifft(spectrum).real - initial)) < 1e-12
print("Initial mean:", initial.mean())

Step 3: Evolve one Fourier mode

Diffusion multiplies a Fourier mode by exp(-D k² t). Higher wave numbers decay faster. We check the known concentration profile at one time; this check would catch a missing square on k.

Python

time = 0.3
decay = np.exp(-diffusivity * k**2 * time)
field = np.fft.ifft(spectrum * decay).real
exact = 1 + 0.4 * np.exp(-time) * np.cos(x) + 0.2 * np.exp(-16 * time) * np.cos(4 * x)
assert np.max(np.abs(field - exact)) < 1e-12
assert abs(field.mean() - initial.mean()) < 1e-12
print("Maximum analytical error:", np.max(np.abs(field - exact)))

Step 4: Repeat at several times

We keep the same initial spectrum for every time, since each evaluation gives the solution from the initial state. We check mean conservation and the decreasing concentration variation. This is not a time-step convergence study.

Python

times = [0.0, 0.02, 0.1, 0.3, 1.0]
profiles = []
variation = []
for sample_time in times:
    decay = np.exp(-diffusivity * k**2 * sample_time)
    profile = np.fft.ifft(spectrum * decay).real
    profiles.append(profile)
    variation.append(np.mean((profile - profile.mean())**2))
assert all(abs(profile.mean() - 1) < 1e-12 for profile in profiles)
assert np.all(np.diff(variation) <= 0)
print("Concentration variances:", variation)

import matplotlib.pyplot as plt
fig, ax = plt.subplots()
for sample_time, profile in zip(times, profiles):
    ax.plot(x, profile, label=f"t = {sample_time}")
ax.set_xlabel("Position x (dimensionless)")
ax.set_ylabel("Concentration c (dimensionless)")
ax.legend()
plt.show()
Checked result: Step 4: Repeat at several times
Result from the executed Python notebook.
Technical details

What we checked

We executed all Python notebook cells in a clean kernel. The checks apply to the short examples shown here. They do not establish grid convergence or reproduce every long simulation.

Return to the code collection