DDM, hands on · notebook for Crowded particles

A crowd of particles from two downloaded movies

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 crowd of particles from two downloaded movies

This notebook repeats the analysis of the Crowded particles page with numpy only (pip install numpy tifffile matplotlib). It needs three files from the page (step 2, Student level or above): "Download the movie (TIFF)", "Download the reference movie (TIFF)" and "Numbers for the notebook (JSON)".

The steps: the structure function of each movie, with frames at log-spaced times paired by their time apart; camera noise B from each movie's mean count; amplitude A from the mean power; the structure factor S(q) as the amplitude per dyed particle against that of the dilute reference; the short-time rate of each pattern from the first delays; the collective diffusion D(q)/D0 as that rate against the rate of the same pattern in the reference. These are the steps of the page; it adds a jackknife for the uncertainties, left out here.

Tested on the page's standard movie (spinning disk, 30 % hard spheres): the peak of S(q) comes out 1.46 at q = 6.3 1/um, as on the page; D(q)/D0 agrees with the page to about 10 %.

1. What we know about the experiment

These are inputs, not results. The JSON file holds what the page told its analysis: the pixel size, the times of the frames of each movie, the number of dyed particles in each, the diffusion coefficient of one particle alone and the camera's noise.

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

base = "ddm-crowded-spinning-128x128x512"        # the name of the downloaded files, without the endings
facts = json.load(open(base + "-numbers.json"))
mov = tifffile.imread(facts["movie"]).astype(np.float64)        # frames x rows x columns, photoelectrons
ref = tifffile.imread(facts["reference"]).astype(np.float64)    # the dilute reference movie
px = facts["pixel_um"]
rn = facts.get("read_noise_e", 1.6)               # camera read noise (electrons)
F_ex = facts.get("excess_noise", 1.0)             # excess-noise factor: 1, or 2 for an electron-multiplying camera
n = mov.shape[1]
def times(key, rate_key, T):
    t = facts.get(key)
    return np.array(t) if t else np.arange(T) / facts[rate_key]   # evenly spaced frames when the JSON gives no times
t = times("movie_times_s", "movie_frame_rate_hz", len(mov))
tr = times("reference_times_s", "reference_frame_rate_hz", len(ref))
print(mov.shape, "movie;", ref.shape, "reference; pixel", round(px, 4), "um; volume fraction", facts["volume_fraction"])

Output

(512, 128, 128) movie; (512, 128, 128) reference; pixel 0.1083 um; volume fraction 0.3

2. Structure function from pairs of frames

Every pair of frames up to half the movie apart, grouped by its delay: one group per whole number of shortest intervals up to 10, then 12 groups per decade; at most about T pairs per group, spread over the movie. For each group, the mean of |F(t2) - F(t1)|^2 over the pairs, with F the Fourier transform of a frame. The mean power of each Fourier mode is kept too: it gives the amplitude.

def structure_function(frames, t):
    T, n, _ = frames.shape
    F = np.fft.fft2(frames)
    dt = np.diff(t).min()
    i, j = np.triu_indices(T, 1)
    gap = t[j] - t[i]
    keep = gap <= (t[-1] - t[0]) / 2 * (1 + 1e-12)
    i, j, gap = i[keep], j[keep], gap[keep]
    u = np.round(gap / dt, 6)
    group = np.where(u < 10.5, np.round(u) - 1, 10 + np.floor(12 * np.log10(u / 10.5))).astype(int)
    taus, d2d = [], []
    for g in np.unique(group):
        sel = np.flatnonzero(group == g)
        sel = sel[:: int(np.ceil(len(sel) / T))]
        if len(sel) < 4:
            continue
        acc = np.zeros((n, n))
        for a, b in zip(i[sel], j[sel]):
            acc += np.abs(F[b] - F[a]) ** 2
        taus.append(gap[sel].mean()); d2d.append(acc / len(sel) / n**2)
    power = (np.abs(F) ** 2).mean(axis=0) / n**2
    return np.array(taus), np.array(d2d), power

def rings(maps, n):
    # average over rings of equal q, leaving out the central cross, where the edges of the image add artefacts
    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
    cnt = np.bincount(ring.ravel(), minlength=n // 2 + 1)
    maps = np.asarray(maps).reshape(-1, n, n)
    return np.array([np.bincount(ring.ravel(), m.ravel(), n // 2 + 1) / np.maximum(cnt, 1) for m in maps])[:, 1:]

taus, d2d, pw = structure_function(mov, t)
taus_r, d2d_r, pw_r = structure_function(ref, tr)
q = 2 * np.pi * np.arange(1, n // 2 + 1) / (n * px)      # 1/um
dq, dq_r = rings(d2d, n), rings(d2d_r, n)
print(len(taus), "delays from", round(taus[0], 4), "to", round(taus[-1], 2), "s")

Output

36 delays from 0.01 to 12.8 s

3. Noise B and amplitude A, for each movie

The camera noise is white, so B is the same at every q; the camera gives it from the mean count, B = 2 (excess-noise factor x mean count + read noise squared). The reference has fewer dyed particles, so a lower count and a lower B: each movie needs its own. The amplitude is A = 2 x mean power - B.

The reference amplitude changes smoothly with q, so it is smoothed with a local quadratic through ln A over seven neighbouring q: A falls steeply with q, and a plain running mean would bias it.

B = 2 * (F_ex * mov.mean() + rn**2)
B_r = 2 * (F_ex * ref.mean() + rn**2)
A = 2 * rings(pw, n)[0] - B
A_r = 2 * rings(pw_r, n)[0] - B_r

def smooth(y, half=3):
    out = np.full(len(y), np.nan); x = np.arange(len(y))
    for k in range(len(y)):
        s = slice(max(0, k - half), min(len(y), k + half + 1)); xs, ys = x[s], y[s]; ok = ys > 0
        if ok.sum() >= 3:
            out[k] = np.exp(np.polyval(np.polyfit(xs[ok] - k, np.log(ys[ok]), 2), 0))
    return out

A_rs = smooth(A_r)
use = (A > B) & (A_r > B_r) & (q > 2 * q[0])     # where both movies carry more signal than the camera noise
print("B =", round(B, 1), "(movie),", round(B_r, 1), "(reference); q used:", int(use.sum()), "of", len(q))

Output

B = 47.7 (movie), 16.5 (reference); q used: 14 of 64

4. The structure factor

S(q) = (A / N) / (A_ref / N_ref), with N the number of dyed particles in each movie. The optics, the dye and the camera are the same for both movies, so they cancel: what remains is how the order of the crowd strengthens or weakens each pattern. It peaks at the spacing of neighbours, about 2 pi / q.

S = (A / facts["n_labelled"]) / (A_rs / facts["n_reference"])
kp = np.nanargmax(np.where(use, S, np.nan))
print("peak of S(q):", round(S[kp], 3), "at q =", round(q[kp], 2), "1/um, a spacing of", round(2 * np.pi / q[kp], 2), "um")

Output

peak of S(q): 1.464 at q = 6.34 1/um, a spacing of 0.99 um

5. Short-time rates and the collective diffusion

f(q, dt) = 1 - (d - B) / A goes from 1 to 0 as each pattern fades. Its rate over the first delays is read from a straight line through ln f with a free intercept: delays from the first on, while f > 0.6 and at least three (never below f = 0.3), each weighted by f squared, so that a constant error of f counts the same everywhere.

D(q) / D0 = Gamma / Gamma_ref, with the rate of the same pattern in the dilute reference, smoothed over q like its amplitude. Dividing by the reference instead of by q^2 cancels most of what the depth in focus adds. This simulation has no hydrodynamic interactions, so D(q)/D0 = 1/S(q) at short times.

def first_rate(f, taus):
    xs, ys, ws = [], [], []
    for ti, fi in zip(taus, f):
        if not fi > 0 or fi < 0.3 or (fi < 0.6 and len(xs) >= 3):
            break
        xs.append(ti); ys.append(np.log(fi)); ws.append(fi * fi)
    if len(xs) < 3:
        return np.nan
    return -np.polyfit(xs, ys, 1, w=np.sqrt(ws))[0]

f = 1 - (dq - B) / A
f_r = 1 - (dq_r - B_r) / A_r
G = np.array([first_rate(f[:, k], taus) if use[k] else np.nan for k in range(len(q))])
G_r = np.array([first_rate(f_r[:, k], taus_r) if A_r[k] > 0 else np.nan for k in range(len(q))])
G_rs = smooth(np.where(np.isfinite(G_r), G_r, -1))
D_rel = G / G_rs
print("at the peak: D(q)/D0 =", round(D_rel[kp], 2), "(1/S =", round(1 / S[kp], 2), ")")
print("D(q) there:", round(D_rel[kp] * facts["D0_um2_s"], 4), "um^2/s; one particle alone:", round(facts["D0_um2_s"], 4), "um^2/s")

Output

at the peak: D(q)/D0 = 0.51 (1/S = 0.68 )
D(q) there: 0.0397 um^2/s; one particle alone: 0.0776 um^2/s

6. Plots

fig, ax = plt.subplots(1, 2, figsize=(9.5, 3.6))
ax[0].plot(q[use], S[use], "o", ms=4); ax[0].axhline(1, color="0.6", lw=0.8)
ax[0].set_xlabel("q (1/um)"); ax[0].set_ylabel("S(q)"); ax[0].set_title("order of the crowd")
ax[1].plot(q[use], D_rel[use], "o", ms=4, label="D(q)/D0"); ax[1].plot(q[use], 1 / S[use], "-", label="1/S(q)")
ax[1].axhline(1, color="0.6", lw=0.8); ax[1].set_ylim(0, 3); ax[1].legend()
ax[1].set_xlabel("q (1/um)"); ax[1].set_title("collective diffusion: slowest at the peak")
fig.tight_layout()
Plot: 6. Plots