DDM, hands on · notebook for Sizing particles

Sizing particles 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 fastddm tifffile matplotlib. In Google Colab (a Google account is needed; the movie goes to Google's servers), add a first cell with !pip install fastddm tifffile matplotlib, upload the movie with the folder icon on the left, then choose Runtime, Run all.

DDM, hands on: sizing particles from a downloaded movie

This notebook repeats the analysis of the Sizing particles page on a movie you download from it, with fastDDM (pip install fastddm tifffile matplotlib). It follows the page's standard method: camera noise known from the detector, a simple exponential fitted at each wave vector, and the size from the Stokes-Einstein relation. The page adds a few corrections that this notebook leaves out (depth of field, exposure time, outlier rejection); see "What this page adds" on the page.

Tested on the page's standard movie (200 nm polystyrene beads in water at 22 C, bright field, 20x): it gives 198 nm.

1. What we know about the experiment

These are inputs, not results: the analysis is told them. Change them to match your movie (the page lists them under the movie, step 2, and under the bench).

import numpy as np
import tifffile
import matplotlib.pyplot as plt
import fastddm as fd
from fastddm.fit import fit_multik
from fastddm.fit_models import simple_exponential_model as model

path = "ddm-sizing-brightfield-128x128x256.tif"   # the file from "Download the movie (TIFF)"
T_C = 22.0                                         # temperature of the sample (C)
eta = 0.955e-3                                     # viscosity of the liquid at that temperature (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

The TIFF holds photoelectrons per pixel. Its ImageJ metadata give the pixel size in the sample and the time between frames.

with tifffile.TiffFile(path) as tif:
    img_seq = tif.asarray().astype(np.float64)    # frames x rows x columns
    xr = tif.pages[0].tags["XResolution"].value    # pixels per micrometre, as a fraction
    pixel_size = xr[1] / xr[0]                     # micrometres per pixel
    dt = tif.imagej_metadata["finterval"]          # seconds between frames
print(img_seq.shape, "frames; pixel", round(pixel_size, 4), "um; one frame every", dt, "s")

Output

(256, 128, 128) frames; pixel 0.325 um; one frame every 0.01 s

3. Structure function and its azimuthal average

fd.ddm subtracts frames a delay apart and Fourier-transforms the differences. Its lags count frames: this works for evenly spaced frames, as on the sizing page. The average along rings of equal wave vector q leaves out the central cross, where the edges of the image add artefacts.

lags = range(1, len(img_seq) // 2)                 # delays up to half the movie, in frames
dqt = fd.ddm(img_seq, lags, core="py", mode="fft")
dqt.pixel_size = pixel_size
dqt.set_frame_rate(1 / dt)

mask = fd.mask.central_cross_mask(dqt.shape[1:])
aa = fd.azimuthal_average(dqt, bins=len(dqt.ky) // 2, range=(0, dqt.ky[-1]), mask=mask)
k, tau = aa.k, aa.tau                              # q in 1/um, delays in s

4. Noise B and amplitude A

The camera noise is white, so B is the same at every q, and the camera gives it: B = 2 (excess-noise factor x mean count + read noise squared). The amplitude follows from the temporal variance of each mode, A = 2 var - B. (fd.noise_est.estimate_camera_noise estimates B from the curves instead; on this movie it comes out about 10 % higher.)

B_cam = 2 * (excess * img_seq.mean() + read_noise**2)
B = np.full(len(k), B_cam)
A = 2 * aa.var - B
print("B =", round(B_cam), "; signal above noise for", int(np.sum(A > B)), "of", len(k), "q")

Output

B = 29910 ; signal above noise for 36 of 64 q

5. Fit at each q

The model is d(q, dt) = A [1 - exp(-Gamma dt)] + B with B fixed. fit_multik starts at a reference q and uses each result as the first guess for the next q.

k_ref = int(np.argmin(np.abs(k - 2.0)))            # start near q = 2 / um
f_ref = 1 - (aa.data[k_ref] - B[k_ref]) / A[k_ref]
Gamma0 = 1 / tau[np.argmin(np.abs(f_ref - np.exp(-1)))]
model.set_param_hint("A", value=A[k_ref], min=0)
model.set_param_hint("B", value=B_cam, vary=False)
model.set_param_hint("Gamma", value=Gamma0, min=0)
fit, _ = fit_multik(aa, model, k_ref, use_err=True, return_model_results=True)
Gamma = fit["Gamma"].to_numpy()

6. From the rates to the size

Keep the q where the signal is above the noise and the rate is within what the movie can measure: slower than one frame, and fast enough to change within half the movie. For diffusion, Gamma = D q^2. The size follows from the Stokes-Einstein relation, d = kB T / (3 pi eta D): the viscosity and the temperature are inputs, so a wrong viscosity gives a wrong size from a fit that looks just as good.

good = fit["success"].to_numpy() & (A > B) & (Gamma > 2 / tau[-1]) & (Gamma < 1 / tau[0]) & (k > 0)
D = np.exp(np.median(np.log(Gamma[good] / k[good] ** 2)))      # um^2/s
kB = 1.380649e-23
diameter_nm = kB * (T_C + 273.15) / (3 * np.pi * eta * D * 1e-12) * 1e9
print(f"{good.sum()} q from {k[good].min():.2f} to {k[good].max():.2f} 1/um; D = {D:.3g} um^2/s; diameter {diameter_nm:.0f} nm")

fig, ax = plt.subplots(1, 2, figsize=(9, 3.5))
ax[0].loglog(k[good], Gamma[good], "o"); ax[0].loglog(k[good], D * k[good] ** 2, "-")
ax[0].set_xlabel("q (1/um)"); ax[0].set_ylabel("Gamma (1/s)"); ax[0].set_title("slope 2: diffusion")
ax[1].semilogx(k[good], Gamma[good] / k[good] ** 2, "o"); ax[1].axhline(D)
ax[1].set_xlabel("q (1/um)"); ax[1].set_ylabel("Gamma / q^2 (um^2/s)"); ax[1].set_title("flat: one diffusion coefficient")
fig.tight_layout()

Output

35 q from 0.96 to 6.11 1/um; D = 2.29 um^2/s; diameter 198 nm
Plot: 6. From the rates to the size