DDM, hands on · notebook for Swimming cells

Swimming speed 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 scipy 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 scipy tifffile matplotlib, upload the movie with the folder icon on the left, then choose Runtime, Run all.

DDM, hands on: swimming speed from a downloaded movie

This notebook repeats the analysis of the Swimming cells page with numpy and scipy (pip install numpy scipy tifffile matplotlib), on the movie from "Download the movie (TIFF)" (step 2).

The steps: the structure function; camera noise B from the mean count; amplitude A from the mean power; the model of Wilson et al. (2011) for cells that swim straight in random 3D directions with a Schulz distribution of speeds, plus cells that only diffuse, fitted to all q at once: mean speed v, share of swimmers alpha, relative spread of speeds and D. This is the published model alone, the page's baseline. The page adds the shape of the cells (rods turn and their image changes), the depth of field, the turning of the swimmers and a jackknife; see "What this page adds".

Tested on the page's standard movie (rod-shaped bacteria, phase contrast, 61 % swimmers at 20 um/s): v = 19.6 um/s and alpha = 64 %, against 20.2 um/s and 67 % as the microscope sees the simulated cells (the page: 20.9 um/s and 69 %). The spread comes out 0.40 against 0.27: the model of straight swimmers attributes to the speeds what the rods' turning and the depth of field do.

1. What we know about the experiment

These are inputs, not results. The TIFF carries the pixel size and the time between frames; the camera noise must be given.

import math
import numpy as np
import tifffile
import matplotlib.pyplot as plt
from scipy.optimize import least_squares

path = "ddm-swimmers-phase-128x128x256.tif"   # from "Download the movie (TIFF)"
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
q_max_bin = 40          # index of the finest ring used: the page stops where the microscope no longer resolves the cells (step 4)

2. The movie

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

print(T, "frames,", round(1 / dt), "per second; pixel", round(pixel_um, 4), "um")

Output

256 frames, 50 per second; pixel 0.65 um

3. Structure function

d(q, dt) = <|F(t + dt) - F(t)|^2>, averaged over every starting frame and over rings of equal q, with F the Fourier transform of a frame.

F = np.fft.fft2(frames)

# 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

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
dq = np.array([ring_average((np.abs(F[l:] - F[:-l]) ** 2).mean(axis=0) / n**2) for l in lags])   # delays x q
print(len(taus), "delays from", taus[0], "to", round(taus[-1], 2), "s")

Output

34 delays from 0.02 to 2.56 s

4. Noise B and amplitude A

B is the camera noise, the same at every q: B = 2 (excess-noise factor x mean count + read noise squared). The amplitude from the mean power, A = 2 <|F|^2> - B, decides which q carry signal; in the fit below each q gets its own A by least squares, as the page does, so that a pattern that has not fully faded within the movie does not need a separate value.

B = 2 * (excess * frames.mean() + read_noise**2)
A = 2 * ring_average((np.abs(F) ** 2).mean(axis=0) / n**2) - B
use = (A > 3 * B) & (np.arange(len(q)) >= 1) & (np.arange(len(q)) <= q_max_bin)   # the widest ring is as large as the image
print("B =", round(B), "; q used:", use.sum(), "from", round(q[use][0], 2), "to", round(q[use][-1], 2), "1/um")

Output

B = 30976 ; q used: 40 from 0.15 to 3.1 1/um

5. The model of Wilson et al. (2011)

f(q, dt) = exp(-D q^2 dt) [(1 - alpha) + alpha S(q v dt)], with S the average of sin(q u dt) / (q u dt) over a Schulz distribution of speeds u of mean v and shape Z = 1 / spread^2 - 1:

S(X) = ((Z + 1) / (Z X)) sin(Z arctan(X / (Z + 1))) / (1 + (X / (Z + 1))^2)^(Z / 2).

d(q, dt) = A (1 - f) + B, fitted to every q and delay at once; at each trial of v, alpha, spread and D the amplitude of each q follows by linear least squares. Each point counts relative to the amplitude of its q.

def S_swim(X, Z):
    X = np.maximum(X, 1e-9)
    L = X / (Z + 1)
    return (Z + 1) / X * np.sin(Z * np.arctan(L)) / Z / (1 + L * L) ** (Z / 2)

def f_model(qq, t, v, alpha, spread, D):
    return np.exp(-D * qq**2 * t) * ((1 - alpha) + alpha * S_swim(qq * v * t, 1 / spread**2 - 1))

qs, Y = q[use], dq[:, use] - B
def residuals(p):
    v, alpha, spread, D = np.exp(p[0]), p[1], p[2], np.exp(p[3])
    g = 1 - f_model(qs[None, :], taus[:, None], v, alpha, spread, D)
    Aq = (g * Y).sum(0) / (g * g).sum(0)
    return ((Aq * g - Y) / Aq).ravel()

fit = least_squares(residuals, [np.log(15), 0.5, 0.4, np.log(0.3)],
                    bounds=([np.log(0.5), 0, 0.05, np.log(1e-3)], [np.log(200), 1, 0.95, np.log(10)]))
v, alpha, spread, D = np.exp(fit.x[0]), fit.x[1], fit.x[2], np.exp(fit.x[3])
print(f"mean speed v = {v:.1f} um/s, swimmers alpha = {100 * alpha:.0f} %, spread of speeds = {spread:.2f}, D of the others = {D:.3f} um^2/s")

Output

mean speed v = 19.6 um/s, swimmers alpha = 64 %, spread of speeds = 0.40, D of the others = 0.311 um^2/s

6. Plots

Left: what is left of each pattern after the delay, f = 1 - (d - B) / A, with the model. The swimmers make the patterns fade at a rate proportional to q (they cross a stripe in a time 1 / (q v)); the cells that only diffuse leave a shoulder that fades at D q^2. The model fits worst at the widest patterns: there the rods turning and the depth of field matter most, and these are what the page adds to the model. Right: the speeds of the swimmers according to the fit.

g = 1 - f_model(qs[None, :], taus[:, None], v, alpha, spread, D)
Aq = (g * Y).sum(0) / (g * g).sum(0)
fig, ax = plt.subplots(1, 2, figsize=(10, 3.6))
for j in np.linspace(0, len(qs) - 1, 6).astype(int):
    l, = ax[0].semilogx(taus, 1 - Y[:, j] / Aq[j], "o", ms=3, label=f"q = {qs[j]:.2f}")
    ax[0].semilogx(taus, 1 - g[:, j], "-", color=l.get_color())
ax[0].set_xlabel("delay (s)"); ax[0].set_ylabel("f(q, dt)"); ax[0].legend(fontsize=7)
Z = 1 / spread**2 - 1
u = np.linspace(0, 3 * v, 300)
p = (Z + 1) ** (Z + 1) / np.exp(math.lgamma(Z + 1)) * (u / v) ** Z * np.exp(-(Z + 1) * u / v) / v
ax[1].plot(u, p); ax[1].set_xlabel("swimming speed (um/s)"); ax[1].set_ylabel("share per um/s")
fig.tight_layout()
Plot: 6. Plots