DDM, hands on · notebook for Moving tissues

A moving cell sheet 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: a moving cell sheet from a downloaded movie

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

The steps, as on the page: the structure function as recorded; the motion of the whole sheet from the phase of the widest patterns between consecutive frames (phase differential microscopy, Colin, Zhang and Wilson 2014); every frame moved back by that motion, and the structure function again, now relative to the sheet; the mean squared displacement from a band of q, inverted as a Gaussian (Giavazzi et al. 2018); the order of the sheet and its state; the rate of each q from a stretched exponential. The page adds the uncertainty of the sheet velocity, a choice of fit models and the network of nuclei.

Tested on the page's standard movie (a jammed sheet): sheet velocity 0.14 um/h, displacement relative to the sheet 0.63 um^2 in 1 h, order 0.16, jammed, as on the page. On the flocking liquid (choose it under "The cells" before downloading): 20.7 um/h, order 0.70, a flocking liquid, as on the page (21 um/h, 0.7).

1. What we know about the experiment

Times are in hours. The camera pixels are binned 4 x 4 on the page, so the read noise of one binned pixel is four times that of a camera pixel.

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

path = "ddm-tissues-jammed-128x128x256.tif"   # from "Download the movie (TIFF)"
cell_um = 15.0          # size of a cell (um): the square root of the area per cell
read_noise = 1.6 * 4    # read noise of a 4 x 4 binned pixel (electrons)

2. The movie and the structure function as recorded

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

dt_h = dt / 3600
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

QX, QY = 2 * np.pi * KX / (n * pixel_um), 2 * np.pi * KY / (n * pixel_um)
B = 2 * (frames.mean() + read_noise**2)
A = 2 * ring_average((np.abs(F) ** 2).mean(axis=0) / n**2) - B
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_h
d_lab = np.array([ring_average((np.abs(F[l:] - F[:-l]) ** 2).mean(axis=0) / n**2) for l in lags])
print(T, "frames, one every", round(dt / 60), "min; pixel", round(pixel_um, 2), "um; B =", round(B))

Output

256 frames, one every 5 min; pixel 2.6 um; B = 1678

3. The motion of the whole sheet

A sheet displaced by R turns the phase of pattern q by -q.R. Between consecutive frames the phase change of the widest patterns is fitted with a plane, weighted by the strength of each mode; the steps add up to R(t), and the sheet velocity is the slope of a straight line through R(t).

wide = (np.abs(KX) <= 4) & (np.abs(KY) <= 4) & ((KX > 0) | ((KX == 0) & (KY > 0)))
Mq = np.column_stack([QX[wide], QY[wide]])
steps = []
for t in range(T - 1):
    c = F[t + 1][wide] * np.conj(F[t][wide])
    w = np.abs(c)
    steps.append(-np.linalg.lstsq(Mq * np.sqrt(w)[:, None], np.angle(c) * np.sqrt(w), rcond=None)[0])
R = np.vstack([[0, 0], np.cumsum(steps, axis=0)])
t_h = np.arange(T) * dt_h
V = np.array([np.polyfit(t_h, R[:, c], 1)[0] for c in (0, 1)])
print(f"sheet velocity: {np.hypot(*V):.3g} um/h (vx = {V[0]:.3g}, vy = {V[1]:.3g})")

Output

sheet velocity: 0.14 um/h (vx = -0.13, vy = -0.0539)

4. Relative to the sheet

Every frame moved back by R(t), F(q, t) exp(i q.R(t)), and the structure function again: what is left is how the cells move relative to the sheet.

Fm = F * np.exp(1j * (QX[None] * R[:, 0, None, None] + QY[None] * R[:, 1, None, None]))
d_sheet = np.array([ring_average((np.abs(Fm[l:] - Fm[:-l]) ** 2).mean(axis=0) / n**2) for l in lags])

5. Mean squared displacement

The nuclei make A peak near the spacing of neighbours. A little above the peak (1.3 times its q), where the arrangement of neighbours no longer slows the patterns, a band of q starts and runs until A falls to three times B. In it, f = 1 - (d - B) / A gives <dr^2> = -4 ln f / q^2 for displacements that are Gaussian, where 0.1 < f < 0.95; the q are combined by the mean of the logarithms, with at least two per delay.

win = (q >= 2 * np.pi / (2 * cell_um)) & (q <= 2 * np.pi / (0.6 * cell_um))
win[:2] = False
jp = np.flatnonzero(win)[np.argmax(A[win])]
j0 = min(len(q) - 3, int(round(1.3 * (jp + 1))) - 1)
j1 = j0
while j1 + 1 < len(q) and A[j1 + 1] > 3 * B:
    j1 += 1
def msd_from(d):
    qb = q[j0:j1 + 1]
    fb = 1 - (d[:, j0:j1 + 1] - B) / A[j0:j1 + 1]
    m = np.where((fb > 0.1) & (fb < 0.95), -4 * np.log(np.clip(fb, 1e-12, 1)) / qb**2, np.nan)
    ok = np.isfinite(m).sum(axis=1) >= 2
    out = np.full(len(d), np.nan)
    out[ok] = np.exp(np.nanmean(np.log(m[ok]), axis=1))
    return out
msd, msd_lab = msd_from(d_sheet), msd_from(d_lab)
print(f"peak of A at q = {q[jp]:.2f} 1/um; band {q[j0]:.2f} to {q[j1]:.2f} 1/um")
i1 = np.argmin(np.abs(taus - 1))
print(f"relative to the sheet: <dr^2> = {msd[i1]:.3g} um^2 in {taus[i1]:.2g} h")

Output

peak of A at q = 0.47 1/um; band 0.60 to 1.15 1/um
relative to the sheet: <dr^2> = 0.629 um^2 in 1 h

6. Order and state

Order: the share of a cell's displacement over the shortest delay measured that the sheet's motion explains, psi = |V| dt / sqrt(<dr^2>_recorded) (1 for a sheet that moves as one block). A flock when psi > 0.5. Solid-like when the displacement relative to the sheet stays below a tenth of the area of a cell over the movie (and the patterns could still follow it); fluid-like otherwise. This is a classification for this model and this movie, as on the page.

ok = np.flatnonzero(np.isfinite(msd))
beyond = len(ok) > 0 and ok[-1] < len(taus) - 1          # the band can no longer follow the cells: they moved further
solid = len(ok) == 0 or (not beyond and msd[ok[-1]] < 0.1 * cell_um**2)
il = np.flatnonzero(np.isfinite(msd_lab))[0]
psi = min(1.0, np.hypot(*V) * taus[il] / np.sqrt(msd_lab[il]))
flock = psi > 0.5
state = ("flocking " if flock else "") + ("solid" if solid else "liquid") if flock else ("jammed" if solid else "fluid")
print(f"order psi = {psi:.2f}; state: {state}")
if len(ok):
    print(f"last displacement measured: {msd[ok[-1]]:.3g} um^2 after {taus[ok[-1]]:.2g} h" + (" (beyond, the band cannot follow)" if beyond else ""))

Output

order psi = 0.16; state: jammed
last displacement measured: 5.65 um^2 after 11 h

7. The rate of each pattern

At each q with A > 3 B, f relative to the sheet is fitted with a stretched (or compressed) exponential, exp(-(Gamma dt)^beta), the page's default model. A rate counts as measured when the fitted curve has fallen below 0.8 by the end of the movie and is still above 0.2 at the first delay. Read the slope of the rate against q together with the shape of the curves and the length of the movie, as the page explains: a slope near 1 with beta near 2 suggests directed motion, near 2 with beta near 1 diffusion, and a plateau of f caging.

f_sheet = 1 - (d_sheet - B) / A
rates = []
for j in range(1, len(q)):
    if not A[j] > 3 * B:
        continue
    fj = f_sheet[:, j]
    try:
        (G, beta), _ = curve_fit(lambda t, G, b: np.exp(-(G * t) ** b), taus, fj, p0=[1 / taus[len(taus) // 2], 1.0],
                                 bounds=([1e-4, 0.2], [1e3, 2.5]))
    except RuntimeError:
        continue
    fm = np.exp(-(G * taus) ** beta)
    if fm[-1] < 0.8 and fm[0] > 0.2:
        rates.append((q[j], G, beta))
rates = np.array(rates)
if len(rates) >= 3:
    slope = np.polyfit(np.log(rates[:, 0]), np.log(rates[:, 1]), 1)[0]
    print(f"{len(rates)} rates measured; slope of ln rate against ln q: {slope:.2f}; median beta: {np.median(rates[:, 2]):.2f}")

Output

50 rates measured; slope of ln rate against ln q: 1.47; median beta: 0.89

8. Plots

Left: the path of the sheet. Middle: the mean squared displacement, relative to the sheet and as recorded, with a tenth of a cell area. Right: the rate of each pattern against q.

fig, ax = plt.subplots(1, 3, figsize=(12, 3.5))
ax[0].plot(R[:, 0], R[:, 1]); ax[0].set_xlabel("x (um)"); ax[0].set_ylabel("y (um)"); ax[0].set_title("path of the sheet"); ax[0].axis("equal")
ax[1].loglog(taus, msd, "o-", ms=3, label="relative to the sheet"); ax[1].loglog(taus, msd_lab, "s", ms=3, mfc="none", label="as recorded")
ax[1].axhline(0.1 * cell_um**2, color="0.6", lw=0.8); ax[1].set_xlabel("delay (h)"); ax[1].set_ylabel("<dr^2> (um^2)"); ax[1].legend(fontsize=7)
if len(rates):
    ax[2].loglog(rates[:, 0], rates[:, 1], "o", ms=3)
ax[2].set_xlabel("q (1/um)"); ax[2].set_ylabel("rate (1/h)")
fig.tight_layout()
Plot: 8. Plots