DDM, hands on · notebook for Sheared materials
Echo-DDM under oscillatory shear 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 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: echo-DDM under oscillatory shear from a downloaded movie
This notebook repeats the analysis of the Sheared materials page with numpy only (pip install numpy tifffile matplotlib), on the movie from "Download the movie (TIFF)" (step 2). The note in the TIFF says how many frames are taken per cycle; the first is at zero strain.
The steps: the structure function at the echoes, whole numbers of cycles apart, from pairs of frames that start at zero strain; averages in two sectors of +- 20 degrees, q along the flow and q along the vorticity; camera noise B from the mean count and amplitude A from the mean power of the frames at zero strain; the rate of each q from a weighted line through the origin of -ln f against the delay; D in each direction from the mean of ln D over q. These are the page's steps; the page adds a jackknife over eight parts of the movie for the uncertainty.
Tested on the page's standard movie (2 um beads in a microgel, 20 % strain at 1 Hz, four frames per cycle): D = 2.48 x 10^-4 um^2/s along the flow and 2.88 x 10^-4 along the vorticity, as on the page (simulated 2.26 and 2.64 x 10^-4).
1. What we know about the experiment
import numpy as np
import tifffile
import matplotlib.pyplot as plt
path = "ddm-shear-carbopol-20pct-128x128x512.tif" # from "Download the movie (TIFF)"
m = 4 # frames per cycle, as in the TIFF's note; the first frame at zero strain
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 echoes and the frames at zero strain
Two frames a whole number of cycles apart show the sample in the same macroscopic state: the shear has undone its affine displacement, and what is left is what it did not undo. The echoes used: whole numbers of cycles, log-spaced up to half the movie (40 steps, fewer distinct ones in a short movie). Only pairs that start at zero strain (the first frame, then every half cycle) are compared: there the shear has no effect on a bead that moved along the height in between.
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
T0 = m * dt # one cycle, s
F = np.fft.fft2(frames)
Kmax = (T - 1) // (2 * m)
ks = sorted(set(max(1, int(round(Kmax ** (i / 39)))) for i in range(40))) # echoes, in cycles
rest = np.arange(0, T, m // 2 if m % 2 == 0 else m) # frames at zero strain
print(T, "frames,", m, "per cycle of", T0, "s;", len(ks), "echoes from 1 to", ks[-1], "cycles;", len(rest), "frames at zero strain")
Output
512 frames, 4 per cycle of 1.0 s; 27 echoes from 1 to 63 cycles; 256 frames at zero strain
3. Two sectors of q
Sector 1: Fourier pixels within 20 degrees of the x axis, stripes across the flow, which show motion along the flow. Sector 2: within 20 degrees of the y axis, motion along the vorticity. In each, the average over rings of equal q, where the ring holds at least four pixels.
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
tan20 = np.tan(np.radians(20))
sector = np.where(np.abs(KY) <= tan20 * np.abs(KX), 1, np.where(np.abs(KX) <= tan20 * np.abs(KY), 2, 0))
sector[ring == 0] = 0
def sector_average(mp, s):
sel = sector == s
c = np.bincount(ring[sel], minlength=n // 2 + 1)
return np.where(c[1:] >= 4, np.bincount(ring[sel], mp[sel], n // 2 + 1)[1:] / np.maximum(c[1:], 1), np.nan)
q = 2 * np.pi * np.arange(1, n // 2 + 1) / (n * pixel_um)
4. Noise, amplitude and what is left at each echo
B = 2 (excess-noise factor x mean count + read noise squared). A = 2 <|F|^2> - B from the frames at zero strain: these are the frames the echoes compare, and the exposure blurs them most (the plate moves fastest at zero strain). Then f = 1 - (d - B) / A at each echo.
B = 2 * (excess * frames.mean() + read_noise**2)
powR = (np.abs(F[rest]) ** 2).mean(axis=0) / n**2
d_echo = []
for kk in ks:
l = kk * m
st = rest[rest + l < T]
d_echo.append((np.abs(F[st + l] - F[st]) ** 2).mean(axis=0) / n**2)
tk = np.array(ks) * T0
A, f = {}, {}
for s in (1, 2):
A[s] = 2 * sector_average(powR, s) - B
f[s] = np.array([1 - (sector_average(d, s) - B) / A[s] for d in d_echo]) # echoes x q
5. Rates and D in each direction
At each q, -ln f against the delay, over the echoes while f > 0.15, fitted with a line through the origin (weights f^2, so that a constant error of f counts the same everywhere): the rate Gamma, and D = Gamma / q^2. A q is left out when its signal is below the noise, when it fades within the first three echoes, or when it hardly fades within the movie (the last echo used above 0.9).
names = {1: "along the flow", 2: "along the vorticity"}
D_q, D = {}, {}
for s in (1, 2):
rows = []
for j in range(1, len(q)):
if not A[s][j] > B:
continue
fs = f[s][:, j]
nu = 0
while nu < len(ks) and fs[nu] > 0.15:
nu += 1
if nu < 3 or fs[nu - 1] > 0.9:
continue
fi, ti = np.minimum(1, fs[:nu]), tk[:nu]
G = (fi**2 * ti * -np.log(fi)).sum() / (fi**2 * ti**2).sum()
if G > 0:
rows.append((q[j], G / q[j] ** 2))
D_q[s] = np.array(rows)
D[s] = np.exp(np.log(D_q[s][:, 1]).mean())
print(f"{names[s]}: D = {D[s]:.3g} um^2/s from {len(rows)} q ({D_q[s][0, 0]:.2f} to {D_q[s][-1, 0]:.2f} 1/um)")
per_cycle = {s: 1000 * np.sqrt(2 * D[s] * T0) for s in (1, 2)}
print(f"per cycle a bead ends about {per_cycle[1]:.0f} nm from where it started along the flow, {per_cycle[2]:.0f} nm along the vorticity")
Output
along the flow: D = 0.000248 um^2/s from 42 q (2.42 to 8.76 1/um) along the vorticity: D = 0.000288 um^2/s from 42 q (2.11 to 8.91 1/um) per cycle a bead ends about 22 nm from where it started along the flow, 24 nm along the vorticity
6. Plots
Left: f at the echoes for a few q, in both directions, with the exponential of the rate fitted. Right: D at each q; for rearrangements that add up like diffusion it does not depend on q.
fig, ax = plt.subplots(1, 2, figsize=(10, 3.6))
for s, mk in ((1, "o"), (2, "s")):
for j in np.linspace(10, 50, 3).astype(int):
G = np.interp(q[j], D_q[s][:, 0], D_q[s][:, 1]) * q[j] ** 2
l, = ax[0].semilogx(tk, f[s][:, j], mk, ms=3, label=f"{names[s]}, q = {q[j]:.1f}")
ax[0].semilogx(tk, np.exp(-G * tk), "-", color=l.get_color(), lw=0.8)
ax[1].plot(D_q[s][:, 0], D_q[s][:, 1], mk, ms=3, label=names[s])
ax[0].set_xlabel("delay (s)"); ax[0].set_ylabel("f at the echoes"); ax[0].set_ylim(-0.1, 1.1); ax[0].legend(fontsize=6)
ax[1].set_yscale("log"); ax[1].set_xlabel("q (1/um)"); ax[1].set_ylabel("D (um^2/s)"); ax[1].legend(fontsize=7)
fig.tight_layout()