DDM, hands on · notebook for Liquid or solid

Microrheology 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: microrheology from a downloaded movie

This notebook repeats the analysis of the Liquid or solid page on a movie you download from it, with numpy and scipy only (pip install numpy scipy tifffile matplotlib). The page records frames at log-spaced times, which fastDDM's fd.ddm (lags in frames) does not handle, so the structure function is computed here directly, as the page does.

The steps: structure function from pairs of frames grouped by their time apart; camera noise B from the detector and amplitude A from the mean power; the mean squared displacement from each q, combined; the creep compliance; the moduli from a retardation spectrum, with Mason's formulas for comparison. The page adds the depth of field and a jackknife over parts of the movie, left out here.

Tested on the page's standard movie (0.5 um beads in wormlike micelles, a Maxwell fluid of 0.5 Pa and 0.5 s in water at 22 C): the moduli agree with the simulated material to about 3 % on average from 0.02 to 500 rad/s, they cross at 2.1 rad/s (2.0 for the material simulated) and the viscosity at long times comes out 0.25 Pa s (true 0.25). On the soft gel it finds no flow within the movie and G' = 0.059 Pa at 0.02 rad/s, as simulated.

1. What we know about the experiment

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

import numpy as np
import tifffile
import matplotlib.pyplot as plt
from scipy.optimize import nnls
from scipy.special import gamma as gamma_fn

path = "ddm-rheology-brightfield-128x128x512.tif"              # from "Download the movie (TIFF)"
times_path = "ddm-rheology-brightfield-128x128x512-times.csv"  # from "Frame times (CSV)"
radius_um = 0.25        # bead radius (um)
T_C = 22.0              # temperature (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 the frame times

The TIFF holds photoelectrons per pixel; its ImageJ metadata give the pixel size. The CSV gives the time of each frame.

with tifffile.TiffFile(path) as tif:
    frames = tif.asarray().astype(np.float64)       # frames x rows x columns
    xr = tif.pages[0].tags["XResolution"].value      # pixels per micrometre, as a fraction
    pixel_um = xr[1] / xr[0]
t = np.loadtxt(times_path, delimiter=",", skiprows=1)[:, 1]
T, n, _ = frames.shape
print(T, "frames over", round(t[-1], 1), "s, the closest", round(np.diff(t).min() * 1000, 3), "ms apart; pixel", round(pixel_um, 4), "um")

Output

512 frames over 107.6 s, the closest 2.0 ms apart; pixel 0.1625 um

3. 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 its pairs.

F = np.fft.fft2(frames)                              # one transform per frame
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)                            # delay in shortest intervals
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)
taus = np.array(taus)

# azimuthal average: rings of whole wave numbers, central cross left out
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:]
dq = np.array([ring_average(m) for m in d2d])      # delays x q
q = 2 * np.pi * np.arange(1, n // 2 + 1) / (n * pixel_um)
print(len(taus), "delays from", round(taus[0], 4), "to", round(taus[-1], 1), "s;", len(q), "q")

Output

51 delays from 0.002 to 48.9 s; 64 q

4. Noise B, amplitude A, and what is left of each pattern

B is the camera noise, the same at every q. A comes from the mean power of each mode, which holds the whole amplitude even when part of the pattern never changes during the movie (beads caged in a gel). It also holds dust or uneven light, which this simulated movie does not have; in a real one, subtract the power of a movie taken without beads. Then f = 1 - (d - B) / A is what is left of each pattern after the delay.

B = 2 * (excess * frames.mean() + read_noise**2)
power = ring_average(np.mean(np.abs(F) ** 2, axis=0) / n**2)
A = 2 * power - B
f = 1 - (dq - B) / A

5. Mean squared displacement

For beads with Gaussian displacements, f = exp(-q^2 <dr^2> / 4), with <dr^2> in the image plane. Each q gives <dr^2> = -(4 / q^2) ln f where f is clearly below 1 and above 0.15; the q are combined by the median of the logarithms, with at least three per delay. Fine q give the short delays, wide q the long ones.

use_q = (A > 3 * B) & (np.arange(len(q)) >= 3)
msd_q = np.where((f > 0.15) & (f < 0.95) & use_q[None, :], -4 / q[None, :] ** 2 * np.log(np.clip(f, 1e-12, None)), np.nan)
nq = np.sum(np.isfinite(msd_q), axis=1)
msd = np.where(nq >= 3, np.exp(np.nanmedian(np.log(msd_q), axis=1)), np.nan)
ok = np.isfinite(msd)
tt, mm = taus[ok], msd[ok]

fig, ax = plt.subplots(figsize=(5, 3.5))
ax.loglog(taus, msd_q, ".", color="0.7", ms=2)
ax.loglog(tt, mm, "ko-", ms=3)
ax.set_xlabel("delay (s)"); ax.set_ylabel("<dr^2> in the image plane (um^2)")
Plot: 5. Mean squared displacement

6. Creep compliance and moduli

The generalised Stokes-Einstein relation turns the displacement into the creep compliance, J(t) = pi a <dr^2>_3D / kB T, with <dr^2>_3D = 1.5 <dr^2> in the image plane. J(t) is fitted with Kelvin-Voigt elements (retardation times four per decade, all weights positive) plus a free flow t / eta; the complex modulus of that sum follows exactly, G*(omega) = 1 / [sum c_k / (1 + i omega lambda_k) + 1 / (i omega eta)]. The fit weighs every point by its relative size.

kT = 1.380649e-23 * (T_C + 273.15)
J = np.pi * radius_um * 1e-6 * 1.5 * mm * 1e-12 / kT          # 1/Pa

decades = np.log10(tt[-1]) - np.log10(tt[0])
lam = np.logspace(np.log10(tt[0]) - 1, np.log10(tt[-1]) + 0.5, int(4 * (decades + 1.5)) + 1)
Mx = np.column_stack([1 - np.exp(-tt[:, None] / lam[None, :]), tt])
c, _ = nnls(Mx / J[:, None], np.ones_like(J))
ck, inv_eta = c[:-1], c[-1]

w = np.logspace(np.log10(1 / tt[-1]), np.log10(1 / tt[0]), 60)   # angular frequency, rad/s
Gstar = 1 / ((ck[None, :] / (1 + 1j * w[:, None] * lam[None, :])).sum(axis=1) + inv_eta / (1j * w))
Gp, Gpp = Gstar.real, Gstar.imag

# Mason's local power-law formulas on the same displacement, for comparison
alpha = np.gradient(np.log(mm), np.log(tt))
Gabs = kT / (np.pi * radius_um * 1e-6 * 1.5 * mm * 1e-12 * gamma_fn(1 + alpha))
w_m, Gp_m, Gpp_m = 1 / tt, Gabs * np.cos(np.pi * alpha / 2), Gabs * np.sin(np.pi * alpha / 2)

fig, ax = plt.subplots(figsize=(5, 3.5))
ax.loglog(w, Gp, "C0-", label="G' (retardation spectrum)"); ax.loglog(w, Gpp, "C3-", label="G''")
ax.loglog(w_m, Gp_m, "C0o", ms=3, mfc="none", label="G' (Mason)"); ax.loglog(w_m, Gpp_m, "C3s", ms=3, mfc="none", label="G'' (Mason)")
ax.set_xlabel("angular frequency (rad/s)"); ax.set_ylabel("modulus (Pa)"); ax.legend(fontsize=7)
Plot: 6. Creep compliance and moduli

7. What the moduli say

Where G' and G'' cross, the material changes character: a viscoelastic liquid is viscous at low frequencies and elastic at high ones, and the inverse of the crossing frequency is its relaxation time. At the lowest frequencies a liquid has G'' = eta omega, which gives its viscosity; a solid keeps G' above G'' there.

d = np.log(Gp / Gpp)
for m in np.flatnonzero(np.diff(np.sign(d)) != 0):
    wc = np.exp(np.log(w[m]) + (np.log(w[m + 1]) - np.log(w[m])) * d[m] / (d[m] - d[m + 1]))
    above = "more elastic above, more viscous below" if d[m + 1] > 0 else "more viscous above, more elastic below"
    print(f"G' and G'' cross at {wc:.3g} rad/s ({above}): a time of about {1 / wc:.3g} s")
if Gp[0] < 0.3 * Gpp[0]:
    print(f"a liquid at long times: viscosity G''/omega at {w[0]:.2g} rad/s = {Gpp[0] / w[0]:.3g} Pa s")
else:
    print(f"not flowing within the movie: at {w[0]:.2g} rad/s G' = {Gp[0]:.3g} Pa and G'' = {Gpp[0]:.3g} Pa")

Output

G' and G'' cross at 2.11 rad/s (more elastic above, more viscous below): a time of about 0.473 s
a liquid at long times: viscosity G''/omega at 0.02 rad/s = 0.246 Pa s