DDM, hands on · notebook for Drifting particles

A drift and its direction from a downloaded movie

What you see here is the notebook as it ran on the page's standard movie: the text, the code, the numbers it printed and its plots.

To run it yourself, download the movie from step 2 of the page (the files are named in the first code cell), put it next to the notebook and run all cells; it needs numpy tifffile matplotlib. In Google Colab (a Google account is needed; the movie goes to Google's servers), add a first cell with !pip install numpy tifffile matplotlib, upload the movie with the folder icon on the left, then choose Runtime, Run all.

DDM, hands on: a drift and its direction from a downloaded movie

This notebook repeats the analysis of the Drifting particles page with numpy only (pip install numpy tifffile matplotlib), on the movie from "Download the movie (TIFF)" (step 2).

The steps: a first guess of the velocity from the phase steps of the widest patterns between consecutive frames (phase differential microscopy, Colin, Zhang and Wilson 2014); the velocity refined from the phase of the cross spectrum <F(t + dt) F*(t)> at several delays; every frame moved back by the drift, so that only the diffusion is left in the structure function; the rate of each q from a straight line through ln f; D and the size. The page fits the cross spectrum at all delays, takes the depth of field into account and adds two jackknifes for the uncertainty.

Tested on the page's standard movie (1 um polystyrene beads in water carried by a flow of 10 um/s to the right): v = 10.00 um/s at -0.1 degrees (the page: 10.01 um/s at -0.05 degrees), D = 0.468 um^2/s (the page 0.461, simulated 0.452) and a diameter of 970 nm (true 1.00 um; the depth of field, left out here, explains most of the difference).

1. What we know about the experiment

import numpy as np
import tifffile
import matplotlib.pyplot as plt

path = "ddm-drift-brightfield-128x128x256.tif"   # from "Download the movie (TIFF)"
T_C, eta = 22.0, 0.955e-3   # temperature (C) and viscosity of the liquid (Pa s): water at 22 C
read_noise = 1.6            # camera read noise (electrons); ORCA-Flash4.0, standard scan
excess = 1.0                # excess-noise factor: 1, or 2 for an electron-multiplying camera

2. The movie and its Fourier transforms

Each frame first loses its own mean brightness, so that a flicker of the lamp does not enter the phases.

with tifffile.TiffFile(path) as tif:
    frames = tif.asarray().astype(np.float64)      # frames x rows x columns, photoelectrons
    xr = tif.pages[0].tags["XResolution"].value     # pixels per micrometre, as a fraction
    desc = tif.pages[0].tags["ImageDescription"].value
pixel_um = xr[1] / xr[0]
dt = float([l for l in desc.splitlines() if l.startswith("finterval=")][0].split("=")[1])   # seconds between frames
T, n, _ = frames.shape

F = np.fft.fft2(frames - frames.mean(axis=(1, 2), keepdims=True))

# azimuthal average: rings of whole wave numbers, central cross left out (the edges of the image add artefacts there)
k = np.fft.fftfreq(n) * n
KX, KY = np.meshgrid(k, k)
ring = np.rint(np.hypot(KX, KY)).astype(int)
ring[(KX == 0) | (KY == 0) | (ring > n // 2)] = 0
count = np.bincount(ring.ravel(), minlength=n // 2 + 1)
def ring_average(m):
    return (np.bincount(ring.ravel(), m.ravel(), n // 2 + 1) / np.maximum(count, 1))[1:]
q = 2 * np.pi * np.arange(1, n // 2 + 1) / (n * pixel_um)    # 1/um, one value per ring

QX, QY = 2 * np.pi * KX / (n * pixel_um), 2 * np.pi * KY / (n * pixel_um)   # wave vector of each Fourier pixel, 1/um
B = 2 * (excess * frames.mean() + read_noise**2)
A2d = 2 * (np.abs(F) ** 2).mean(axis=0) / n**2 - B      # amplitude of each Fourier pixel
A = ring_average(A2d)
print(T, "frames,", round(1 / dt), "per second; pixel", round(pixel_um, 4), "um; B =", round(B))

Output

256 frames, 20 per second; pixel 0.65 um; B = 24971

3. A first guess of the velocity

A uniform drift R(t) turns the phase of each Fourier mode by -q.R. Between consecutive frames the phase change of the widest patterns (|kx|, |ky| <= 4, where it stays below pi) is fitted with a plane, weighted by the strength of each mode: that gives the step of R in one frame interval.

wide = (np.abs(KX) <= 4) & (np.abs(KY) <= 4) & ((KX > 0) | ((KX == 0) & (KY > 0)))
C1 = (F[1:] * np.conj(F[:-1])).mean(axis=0)
w = np.abs(C1[wide])
Mq = np.column_stack([QX[wide], QY[wide]])
v = -np.linalg.lstsq(Mq * np.sqrt(w)[:, None], np.angle(C1[wide]) * np.sqrt(w), rcond=None)[0] / dt
print("first guess: v =", v.round(3), "um/s")

Output

first guess: v = [10.124  0.013] um/s

4. The velocity from the cross spectrum

C(q, dt) = <F(q, t + dt) F*(q, t)> = (A / 2) exp(-D q^2 dt) exp(-i q.v dt). Turned by the current guess, C exp(i q.v dt) keeps only the phase of the correction, -q.dv dt; a weighted least-squares fit over all Fourier pixels with signal, at several delays and while each pattern is still there (|C| above a fifth of A / 2), gives dv. Two or three rounds converge.

good = (A2d > 3 * B) & (ring > 0)
for it in range(3):
    rows, rhs, wts = [], [], []
    for l in [1, 2, 3, 4, 6, 8, 12, 16]:
        z = (F[l:] * np.conj(F[:-l])).mean(axis=0) / n**2 * np.exp(1j * (QX * v[0] + QY * v[1]) * l * dt)
        keep = good & (np.abs(z) > 0.2 * A2d / 2)
        rows.append(np.column_stack([QX[keep], QY[keep]]) * l * dt); rhs.append(-np.angle(z[keep])); wts.append(np.abs(z[keep]) ** 2)
    Mx, y, wt = np.vstack(rows), np.concatenate(rhs), np.concatenate(wts)
    v = v + np.linalg.lstsq(Mx * np.sqrt(wt)[:, None], y * np.sqrt(wt), rcond=None)[0]
speed, direction = np.hypot(*v), np.degrees(np.arctan2(v[1], v[0]))
print(f"drift: {speed:.3f} um/s towards {direction:.2f} degrees (0 = to the right, 90 = down the image, as on the page)")

Output

drift: 10.005 um/s towards -0.12 degrees (0 = to the right, 90 = down the image, as on the page)

5. Diffusion, with the drift taken out

Each frame is moved back by the drift, F(q, t) exp(i q.v t): the patterns then no longer swing, and the structure function of these frames holds only the diffusion, d = A (1 - exp(-D q^2 dt)) + B. The rate of each q comes from a straight line through ln f, f = 1 - (d - B) / A, where 0.15 < f < 0.95 (weights f).

lags = sorted(set(list(range(1, 11)) + [int(round(x)) for x in np.logspace(1, np.log10(T // 2), 25)]))   # every frame up to 10, then about 12 per decade
taus = np.array(lags) * dt
Fm = F * np.exp(1j * (QX * v[0] + QY * v[1]) * (np.arange(T) * dt)[:, None, None])
dq = np.array([ring_average((np.abs(Fm[l:] - Fm[:-l]) ** 2).mean(axis=0) / n**2) for l in lags])
f = 1 - (dq - B) / A
G = np.full(len(q), np.nan)
for j in range(1, len(q)):
    sel = (f[:, j] > 0.15) & (f[:, j] < 0.95)
    if A[j] > 3 * B and sel.sum() >= 3:
        G[j] = -np.polyfit(taus[sel], np.log(f[sel, j]), 1, w=f[sel, j])[0]
D = np.exp(np.nanmean(np.log(G / q**2)))
kT = 1.380649e-23 * (T_C + 273.15)
d_nm = 2 * kT / (6 * np.pi * eta * D * 1e-12) * 1e9
print(f"{np.isfinite(G).sum()} q used; D = {D:.3f} um^2/s, a diameter of {d_nm:.0f} nm (Stokes-Einstein)")

Output

62 q used; D = 0.468 um^2/s, a diameter of 967 nm (Stokes-Einstein)

6. Plots

Left: the phase of the cross spectrum at one delay against q.v dt, for every Fourier pixel used: a drift puts the points on the line of slope -1. Right: the fading rate against q, on log scales, with D q^2.

l = 4
z = (F[l:] * np.conj(F[:-l])).mean(axis=0)
keep = good & (np.abs(z) / n**2 > 0.2 * A2d / 2)
x = ((QX * v[0] + QY * v[1]) * l * dt)[keep]
fig, ax = plt.subplots(1, 2, figsize=(10, 3.6))
ax[0].plot(x, np.angle(z[keep]), ".", ms=2); ax[0].plot([-np.pi, np.pi], [np.pi, -np.pi], "k-", lw=0.8)
ax[0].set_xlabel("q.v dt (rad)"); ax[0].set_ylabel("phase of C (rad)"); ax[0].set_title(f"delay {l * dt:.2f} s")
ax[1].loglog(q, G, "o", ms=3); ax[1].loglog(q, D * q**2, "k-", lw=0.8)
ax[1].set_xlabel("q (1/um)"); ax[1].set_ylabel("fading rate (1/s)")
fig.tight_layout()
Plot: 6. Plots