Scherrer, Lynch et al. (2023), dandiset 000691: motion of the field of view¶

Paper. Scherrer JR, Lynch GF, Zhang JJ, Fee MS (2023). An optical design enabling lightweight and large field-of-view head-mounted microscopes. Nature Methods 20, 546-549. doi:10.1038/s41592-023-01806-1.

Claims. claims/000691/10.1038-s41592-023-01806-1.yaml, written from the full text of the version of record and the paper's code. It decides what is tested and how.

Dandiset. DANDI:000691, version 0.260827.1358, the only published version (the paper cites none); see the main notebook, reproduce_scherrer_2023.ipynb, for the reasons and the full data check. This notebook reads the whole imaging movie (15 GB compressed, 36 GB as 16-bit values) by HTTP range requests, in blocks of 1200 frames held in memory, and registers every frame.

Claim Data Status
ed7-motion-small dandiset tested
In [1]:
import time

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import scipy.fft as sfft
from scipy import ndimage

import kiloscope as ks

started = time.time()
urls = ks.asset_urls()
f = ks.open_nwb(urls)
reader = ks.MovieReader(urls[ks.NWB_PATH], f)
t_img = f["acquisition/TwoPhotonSeries/timestamps"][:]
print(f"chunk index of the movie read in {reader.index_seconds:.0f} s")
chunk index of the movie read in 103 s

Data check¶

In [2]:
print(f"movie {reader.shape}, chunks {reader.chunks}, {len(reader.index)} stored chunks in {len(reader.blocks)} blocks of frames; "
      f"{sum(s for _, _, s in reader.index) / 1e9:.2f} GB compressed; timestamps {len(t_img)}")
print("chunks per block:", sorted({sum(1 for o, _, _ in reader.index if o[0] == b) for b in reader.blocks}))
t0 = time.time()
first = reader.block(0)
print(f"block 0 read in {time.time() - t0:.1f} s: {first.shape} {first.dtype}, values {first.min()} to {first.max()}, mean {first.mean():.1f}")
print("block 0 equals the same frames read through h5py (first 5 frames):", bool(np.array_equal(first[:5], f[ks.MOVIE][:5])))
print("values above 1023 (the sensor's 10 bits):", int((first > 1023).sum()), "; values not integers: none (uint16)")
edge = np.concatenate([first[:, :3].ravel(), first[:, -3:].ravel(), first[:, :, :3].ravel(), first[:, :, -3:].ravel()])
print(f"mean of the 3-pixel border {edge.mean():.1f} against the whole frame {first.mean():.1f}")
# The registration on frames with known shifts: a smoothed frame of block 0 moved by Fourier shifts.
base = ndimage.gaussian_filter(first[:100].astype(np.float32).mean(0), 1)
true = np.array([[0.13, -0.07], [1.3, 0.7], [-0.42, 2.26], [0.0, 0.0]])
moved = np.array([np.real(sfft.ifft2(ndimage.fourier_shift(sfft.fft2(base), s))) for s in true]).astype(np.float32)
est, _ = ks.register_frames(moved, sfft.fft2(base))
print("known shifts (row, column):", true.tolist())
print("estimated correction      :", np.round(est, 3).tolist(), "(the correction is minus the shift)")
movie (36596, 808, 608), chunks (1200, 20, 20), 39401 stored chunks in 31 blocks of frames; 15.08 GB compressed; timestamps 36596
chunks per block: [1271]
block 0 read in 4.8 s: (1200, 808, 608) uint16, values 0 to 908, mean 129.1
block 0 equals the same frames read through h5py (first 5 frames): True
values above 1023 (the sensor's 10 bits): 0 ; values not integers: none (uint16)
mean of the 3-pixel border 28.3 against the whole frame 129.1
known shifts (row, column): [[0.13, -0.07], [1.3, 0.7], [-0.42, 2.26], [0.0, 0.0]]
estimated correction      : [[-0.14, 0.06], [-1.3, -0.7], [0.42, -2.26], [0.0, 0.0]] (the correction is minus the shift)

The movie's frames and timestamps agree in number, the blocks read by range requests equal the frames read through h5py, and the values are 10-bit sensor counts in 16-bit integers. The registration recovers known shifts to 1/50 pixel (printed above), with the opposite sign: it returns the correction.

In [3]:
# Is the movie the raw video? Nothing in the file says (printed below); these are the checks the values allow.
ts = f["acquisition/TwoPhotonSeries"]
print("series attributes:", {k: str(v) for k, v in ts.attrs.items() if k not in ("object_id", "namespace")})
print("data attributes:", {k: str(v) for k, v in ts["data"].attrs.items()})
print("processing modules:", list(f["processing"]), "; ophys holds:", list(f["processing/ophys"]))
zeros = (first == 0).sum((1, 2))
zr, zc = np.nonzero((first == 0).any(0))
print(f"block 0: frames with a zero-valued pixel {int((zeros > 0).sum())} of {len(first)}, at most {zeros.max()} per frame; "
      f"{len(zr)} pixels ever zero, at rows {sorted(set(zr.tolist()))} and columns {sorted(set(zc.tolist()))}")
# Sub-pixel shifting mixes neighbouring pixels and smooths the histogram of the 10-bit counts. 200 frames of block 0
# as deposited, and the same frames moved by random shifts of known size and written back as integers, as a
# sub-pixel motion correction would leave them. Roughness: the mean relative difference of each value's count from
# the mean of its two neighbours' (a check chosen here).
rng_raw = np.random.default_rng(691_71)
sample = first[:200]
rows = []
for rms in [0, 0.02, 0.05, 0.13, 0.3]:
    moved_ = sample if rms == 0 else ks.fourier_shift_frames(sample, rng_raw.normal(0, rms / np.sqrt(2), (len(sample), 2)))
    h = np.bincount(moved_.ravel(), minlength=1024)
    rows.append({"shift_rms_px": rms, "histogram_roughness": round(ks.histogram_roughness(h), 4),
                 "odd_over_even_counts": round(h[1::2].sum() / h[0::2].sum(), 4), "values_changed": round(float((moved_ != sample).mean()), 3)})
print(pd.DataFrame(rows).to_string(index=False))
del first, sample, moved_
series attributes: {'comments': 'no comments', 'description': 'Calcium imaging data at ~30 fps in grayscale format', 'neurodata_type': 'TwoPhotonSeries'}
data attributes: {'conversion': '1.0', 'offset': '0.0', 'resolution': '-1.0', 'unit': 'Frames'}
processing modules: ['ophys'] ; ophys holds: ['DfOverF', 'ImageSegmentation', 'SegmentationImages']
block 0: frames with a zero-valued pixel 22 of 1200, at most 1 per frame; 7 pixels ever zero, at rows [0, 1, 5, 11, 15, 99, 260] and columns [1, 81, 227, 432, 533, 549, 576]
 shift_rms_px  histogram_roughness  odd_over_even_counts  values_changed
         0.00               0.7451                1.2233           0.000
         0.02               0.4688                1.2331           0.061
         0.05               0.1453                1.1867           0.301
         0.13               0.0515                1.0627           0.580
         0.30               0.0094                1.0091           0.799

The file gives no description beyond "Calcium imaging data at ~30 fps in grayscale format" and no comments, and holds no motion-correction module (printed above). The values say more. The histogram of the deposited counts is rough, with odd values more frequent than even ones, as raw converter counts are; moving the same frames by sub-pixel shifts of the size the paper reports and writing them back as integers smooths it (the table above, rows with a shift). The roughness of the whole movie is printed with the registration below. The zero values of block 0 are single pixels scattered over the frame in a few frames, not the strips at the edges a shift would leave.

ed7-motion-small¶

Lateral shifts of the image due to the mouse's movement are small, with a root-mean-square displacement of 0.13 pixels (0.7 um).

Criterion: displacements NoRMCorre estimates on the raw imaging video; rigid registration with NoRMCorre's defaults is a standard choice. Readings of the root mean square: (a) of the 2D shift's length about the mean shift, (b) the same about zero shift, (c) over both axes' shifts about their means. Microns use the pixel sizes of abstract-kiloscope-fov (5.94 and 5.35 um). Reproduced when the value in pixels is within 0.13 +/- 0.013 under a reading.

The registration is written here after NoRMCorre's rigid algorithm (see the helper module); it is not MATLAB's NoRMCorre.

In [4]:
reg = ks.normcorre_rigid(reader, block_stats=lambda a: ((a == 0).sum((1, 2)), np.bincount(a[::10].ravel(), minlength=1024)))
sh = reg["shifts"]
print(f"registered {len(sh)} frames in {reg['seconds']:.0f} s")
dev = sh - sh.mean(0)
readings = {
    "(a) 2D length about the mean": np.sqrt(np.mean((dev ** 2).sum(1))),
    "(b) 2D length about zero": np.sqrt(np.mean((sh ** 2).sum(1))),
    "(c) both axes about their means": np.sqrt(np.mean(dev ** 2)),
}
rows = [{"reading": k, "rms_px": round(v, 4), "within_0.13+/-0.013": abs(v - 0.13) <= 0.013,
         "um_at_5.94": round(v * 5.94, 3), "um_at_5.35": round(v * 5.35, 3)} for k, v in readings.items()]
print(pd.DataFrame(rows).to_string(index=False))
print(f"mean shift (row, column) {np.round(sh.mean(0), 3).tolist()} px; per axis RMS about the mean {np.round(np.sqrt((dev ** 2).mean(0)), 4).tolist()} px")
print(f"largest |shift| per axis {np.round(np.abs(sh).max(0), 2).tolist()} px; frames with a 2D shift above 1 px: {(np.hypot(*sh.T) > 1).sum()}")
  block 1 of 31 registered, 41 s
  block 6 of 31 registered, 221 s
  block 11 of 31 registered, 400 s
  block 16 of 31 registered, 581 s
  block 21 of 31 registered, 762 s
  block 26 of 31 registered, 943 s
  block 31 of 31 registered, 1100 s
registered 36596 frames in 1100 s
                        reading  rms_px  within_0.13+/-0.013  um_at_5.94  um_at_5.35
   (a) 2D length about the mean  0.0367                False       0.218       0.196
       (b) 2D length about zero  0.0381                False       0.226       0.204
(c) both axes about their means  0.0260                False       0.154       0.139
mean shift (row, column) [-0.001, -0.01] px; per axis RMS about the mean [0.0202, 0.0306] px
largest |shift| per axis [0.1, 0.16] px; frames with a 2D shift above 1 px: 0
In [5]:
# Over time: RMS of the 2D shift about the session mean in 100 s windows, and the shifts themselves.
edges = np.arange(0, t_img[-1] + 100, 100)
win = np.digitize(t_img, edges) - 1
per = pd.DataFrame({"from_s": edges[:-1], "frames": np.bincount(win, minlength=len(edges) - 1),
                    "rms_px": [np.sqrt(np.mean((dev[win == k] ** 2).sum(1))) if (win == k).any() else np.nan for k in range(len(edges) - 1)]})
print(per.round(4).to_string(index=False))
fig, ax = plt.subplots(2, 1, figsize=(11, 4), sharex=True)
ax[0].plot(t_img, sh[:, 1], lw=0.3); ax[0].set_ylabel("horizontal (px)")
ax[1].plot(t_img, sh[:, 0], lw=0.3); ax[1].set_ylabel("vertical (px)"); ax[1].set_xlabel("time (s)")
plt.tight_layout(); plt.show()
print(f"plotted shifts: horizontal {sh[:, 1].min():.2f} to {sh[:, 1].max():.2f}, vertical {sh[:, 0].min():.2f} to {sh[:, 0].max():.2f} px, all inside the axes")
 from_s  frames  rms_px
    0.0    2965  0.0406
  100.0    2964  0.0512
  200.0    2965  0.0409
  300.0    2964  0.0310
  400.0    2964  0.0354
  500.0    2964  0.0346
  600.0    2965  0.0334
  700.0    2964  0.0370
  800.0    2964  0.0377
  900.0    2965  0.0350
 1000.0    2964  0.0312
 1100.0    2964  0.0304
 1200.0    1024  0.0275
No description has been provided for this image
plotted shifts: horizontal -0.16 to 0.10, vertical -0.10 to 0.08 px, all inside the axes
In [6]:
# The whole movie as read for the registration: zero-valued pixels per frame, and the histogram roughness of every
# tenth frame of each block (as in the data check).
zeros_all = np.concatenate([z for z, _ in reg["stats"]])
rough = [ks.histogram_roughness(h) for _, h in reg["stats"]]
h_all = np.sum([h for _, h in reg["stats"]], 0)
print(f"frames with a zero-valued pixel: {int((zeros_all > 0).sum())} of {len(zeros_all)}; zero pixels per frame at most {zeros_all.max()}")
print(f"histogram roughness per block of 1200 frames: {min(rough):.3f} to {max(rough):.3f}; whole movie {ks.histogram_roughness(h_all):.3f}; "
      f"odd over even counts {h_all[1::2].sum() / h_all[0::2].sum():.3f}")
frames with a zero-valued pixel: 243 of 36596; zero pixels per frame at most 2
histogram roughness per block of 1200 frames: 0.740 to 0.745; whole movie 0.742; odd over even counts 1.220
In [7]:
# The registration on the movie with a known jitter added: the frames of the first block moved by random shifts with
# a 2D RMS of 0.13 px about zero (the paper's value) and written back as integers, then registered as in the main run.
class Jittered:
    def __init__(self, reader, shifts):
        self.reader, self.shifts = reader, shifts
        self.blocks, self.chunks, self.shape = reader.blocks, reader.chunks, reader.shape

    def block(self, start):
        a = self.reader.block(start)
        return ks.fourier_shift_frames(a, self.shifts[start:start + len(a)])

rng_jit = np.random.default_rng(691_72)
jitter = rng_jit.normal(0, 0.13 / np.sqrt(2), (reader.shape[0], 2))
jr = ks.normcorre_rigid(Jittered(reader, jitter), blocks=reader.blocks[:1], log=None)
fr_, est = jr["frames"], jr["shifts"]
def rms_a(s_):
    d_ = s_ - s_.mean(0)
    return np.sqrt(np.mean((d_ ** 2).sum(1)))
change = est - sh[fr_]                 # what the jitter changed in the estimate
resid = change + jitter[fr_]           # zero (up to a constant) if the registration recovers the jitter exactly
print(f"frames {fr_[0]} to {fr_[-1]}, registered in {jr['seconds']:.0f} s")
print(f"RMS (a) of the added jitter {rms_a(jitter[fr_]):.4f} px; of the main run's shifts on these frames {rms_a(sh[fr_]):.4f} px; "
      f"of the shifts estimated on the jittered frames {rms_a(est):.4f} px")
print(f"correlation of the change in the estimate with minus the jitter: rows {np.corrcoef(change[:, 0], -jitter[fr_, 0])[0, 1]:.3f}, "
      f"columns {np.corrcoef(change[:, 1], -jitter[fr_, 1])[0, 1]:.3f}; RMS (a) of what is left {rms_a(resid):.4f} px")
frames 0 to 1199, registered in 60 s
RMS (a) of the added jitter 0.1322 px; of the main run's shifts on these frames 0.0334 px; of the shifts estimated on the jittered frames 0.1363 px
correlation of the change in the estimate with minus the jitter: rows 0.996, columns 0.996; RMS (a) of what is left 0.0119 px
In [8]:
# Variant chosen here, not part of the criterion: one-photon frames carry a static illumination pattern that does not
# move with the brain and can pull rigid shifts toward zero. The first two blocks (2400 frames) are registered again
# after removing each frame's Gaussian blur of 10 pixels, and compared with the main run on the same frames.
var = ks.normcorre_rigid(reader, blocks=reader.blocks[:2], prefilter=ks.highpass, log=None)
rows = []
for label, s_ in [("main run (no filter), same frames", sh[var["frames"]]), ("high-pass filtered", var["shifts"])]:
    d_ = s_ - s_.mean(0)
    rows.append({"registration": label, "(a)_px": round(np.sqrt(np.mean((d_ ** 2).sum(1))), 4),
                 "(b)_px": round(np.sqrt(np.mean((s_ ** 2).sum(1))), 4), "(c)_px": round(np.sqrt(np.mean(d_ ** 2)), 4),
                 "largest_px": round(np.abs(s_).max(), 3)})
print(f"frames {var['frames'][0]} to {var['frames'][-1]} ({t_img[var['frames'][-1]]:.0f} s), registered in {var['seconds']:.0f} s")
print(pd.DataFrame(rows).to_string(index=False))
print(f"correlation of the two runs' shifts: rows {np.corrcoef(sh[var['frames'], 0], var['shifts'][:, 0])[0, 1]:.2f}, "
      f"columns {np.corrcoef(sh[var['frames'], 1], var['shifts'][:, 1])[0, 1]:.2f}")
print(f"total run time {(time.time() - started) / 60:.1f} min")
frames 0 to 2399 (81 s), registered in 129 s
                     registration  (a)_px  (b)_px  (c)_px  largest_px
main run (no filter), same frames  0.0328  0.0467  0.0232        0.12
               high-pass filtered  0.0188  0.0220  0.0133        0.08
correlation of the two runs' shifts: rows 0.52, columns 0.68
total run time 24.9 min

Result: not reproduced. The RMS displacement is 0.0367 px under reading (a), 0.0381 px under (b) and 0.0260 px under (c), against 0.13 +/- 0.013 px; under (a) and (b) that is 0.20 to 0.23 um at the two pixel sizes, against the paper's 0.7 um. No frame moves more than 0.16 px along an axis, and the RMS in each 100 s window lies between 0.028 and 0.051 px. The registration finds motion of the paper's size when it is there: with a jitter of 0.132 px RMS added to the first block, the estimated shifts follow it (correlation 0.996 on each axis) and their RMS rises from 0.033 to 0.136 px. The movie is consistent with the raw video, not a motion-corrected one: the file holds no motion correction, the histogram of its counts keeps a roughness of 0.740 to 0.745 in every block, where moving frames by sub-pixel shifts of 0.13 px RMS and writing them back as integers lowers it from 0.745 to 0.052, and its zero values are at most 2 single pixels in 243 of 36596 frames, not strips at the edges. Registering high-pass filtered frames (a variant chosen here, on the first 2400 frames) gives a smaller value still, 0.0188 px under (a) against 0.0328 px for the main run on the same frames, so a static background pulling the estimate toward zero does not explain the difference. The registration is written here after NoRMCorre's rigid algorithm with its defaults, not MATLAB's NoRMCorre.

Summary¶

A failure to reproduce here may be a failure of this attempt, not of the paper: see the reasoning and the differences from the paper's method.

Claim Outcome (this attempt) Outcome of -01
ed7-motion-small not reproduced (new)

How the analysis differs from the paper's. The paper ran NoRMCorre in MATLAB with settings it does not give; here a rigid registration written after NoRMCorre's algorithm and defaults runs on the movie the dandiset holds, whose values are consistent with the raw video the paper registered.

What was found about the dandiset. The TwoPhotonSeries is described only as "Calcium imaging data at ~30 fps in grayscale format": nothing says whether it is raw or motion-corrected. Its values are consistent with the raw video, and its rigid shifts against a template are about a quarter of those the paper reports for the raw video.