Reproducing Qi et al. (2026) from dandiset 001960: spontaneous sessions¶

Paper. Qi, Parot, Wang, Pomeroy, Lavis and Cohen, "Large-scale all-optical electrophysiology links excitability and connectivity to circuit dynamics in vivo", bioRxiv preprint doi:10.64898/2026.10.05.756595 (version 1); the claims file was written from its full text and supplement. Dataset. DANDI:001960 version 0.261013.2016, the only published version (see the first notebook, qi2026_excitability_connectivity.ipynb, for the choice and the full data check).

This notebook tests the claims that use the two spontaneous (behavior) sessions:

Claim Tested here
spike-snr-and-detection-errors, snr-decay-one-hour tested
subthreshold-correlation-length, subthreshold-low-dimensional, quiet-state-oscillations, spike-synchrony-localized, fig4g-private-depolarizations, fig4hi-self-sta-diverges tested
traveling-waves tested
npy-fraction-and-similarity, npy-subthreshold-similar, npy-umap-groups, npy-whisking-onset-rates, npy-state-dependent-excitability tested
voltage-to-spike-sigmoid, npy-oscillation-peak-rates blocked, methods underspecified (every reading shown)
In [1]:
import os
os.environ.setdefault("OMP_NUM_THREADS", "4")
import time
import warnings
import numpy as np
import pandas as pd
from scipy import stats
import matplotlib.pyplot as plt
import l1opto as L

warnings.filterwarnings("ignore", category=RuntimeWarning)
T0 = time.time()
print("dandiset", L.DANDISET, "version", L.VERSION)
U = {(m, s): L.units(m, s) for m in L.MICE for s in L.SESSIONS}
ST4 = {m: L.fig4_stage2(m) for m in L.MICE}  # stored state-dependent correlation arrays, binned by distance
dandiset 001960 version 0.261013.2016

Spontaneous sessions: one pass per mouse¶

The Figure 1 SNR claims, the Figure 4 voltage claims and the Figure 6 behaviour claims use the two spontaneous (behavior) sessions. Each is read once: the subthreshold voltage of the QC cells is held in memory (about 3 GB), reduced to what the claims need, and freed; the normalized voltage is streamed in 3 min chunks for the SNR measures. Masks follow the code (see l1opto.load_behavior). Cells are the QC cells of each session (247 and 258, the paper's n = 505).

In [2]:
from scipy.signal import butter, filtfilt, find_peaks, welch, hilbert
from scipy.optimize import curve_fit

VEDGES_F4 = np.linspace(-2, 2, 101)  # code, Figure 4E-G: 100 bins from -2 to 2 SH
CHUNK3 = int(round(180 / L.DT))       # 3 min chunks (Supplementary Fig. 8A)
BEH = {}
for m in L.MICE:
    tl = time.time()
    B = L.load_behavior(m)
    V, n = B["V"], B["n_frames"]
    nc = V.shape[1]
    R = {"gfp": B["gfp"], "x": B["x_um"], "y": B["y_um"], "cells": B["cells"], "n_frames": n}
    sf = B["spike_frames"]
    R["spike_counts"] = np.array([len(x) for x in sf])
    R["duration_s"] = B["ts"][-1] - B["ts"][0] + L.DT
    print(f"{m}: {nc} QC cells, {n} frames ({R['duration_s']:.0f} s); quiet {B['quiet'].mean():.3f}, whisking {B['whisk'].mean():.3f}, "
          f"running guard {B['run_guard'].mean():.3f} of frames; running speed {B['speed'].min():.3f} to {B['speed'].max():.3f} m/s; "
          f"subthreshold 0.1 to 99.9 percentile {np.percentile(V[::97], [0.1, 99.9]).round(2)} SH")
    analysisEF = B["base"] & ~B["chunk_guard_1000"] & ~B["run_guard"] & B["quiet"]
    analysisG = B["base"] & ~L.chunk_guard(n, B["frames_per_chunk"], 5000) & ~B["run_guard"] & B["quiet"]
    quiet_nr = B["quiet"] & ~B["run_guard"]
    whisk_nr = B["whisk"] & ~B["run_guard"]
    R["n_frames_states"] = dict(analysisEF=int(analysisEF.sum()), analysisG=int(analysisG.sum()),
                                quiet_nr=int(quiet_nr.sum()), whisk_nr=int(whisk_nr.sum()))

    # --- dimensionality (stored subthreshold, diagonal kept): covariance per state, in blocks
    for st, mk in [("quiet", quiet_nr), ("whisk", whisk_nr)]:
        s1 = np.zeros(nc); s2 = np.zeros((nc, nc)); cnt = 0
        for a in range(0, n, 200_000):
            X = V[a:a + 200_000][mk[a:a + 200_000]].astype(np.float64)
            s1 += X.sum(0); s2 += X.T @ X; cnt += len(X)
        C = (s2 - np.outer(s1, s1) / cnt) / (cnt - 1)
        ev = np.sort(np.linalg.eigvalsh(C))[::-1]
        R[f"pca_sub_{st}"] = ev / ev.sum()
    # --- Welch spectra per cell and state, 2 s segments inside the state (standard choice)
    seg = int(round(2 / L.DT))
    for st, mk in [("quiet", quiet_nr), ("whisk", whisk_nr)]:
        starts = [s for s in range(0, n - seg, seg // 2) if mk[s:s + seg].all()]
        psd = None
        for s in starts:
            fq, p = welch(V[s:s + seg], fs=1 / L.DT, nperseg=seg, axis=0)
            psd = p if psd is None else psd + p
        R[f"psd_{st}"] = (fq, psd / len(starts), len(starts))
    # --- P(spk|V), quiet, code masks (analysisEF), at the spike frame and 8 frames (10 ms) before,
    #     and with V the mean of the 8 frames (10.2 ms) before each frame
    for off in (0, 8):
        rate, allc, spkc = L.p_spk_given_v(V, sf, analysisEF, VEDGES_F4, offset=off)
        R[f"pspkv_off{off}"] = (rate, allc, spkc)
    R["pspkv_win8"] = L.p_spk_given_v(V, sf, analysisEF, VEDGES_F4, window=8)
    # --- joint distribution of neighbour voltages (code panel G), 60 to 200 um, analysisG frames,
    #     every 4th frame (the subthreshold is smoothed over 17 frames; a computational choice)
    Dn = L.distance_matrix_um(B["x_um"], B["y_um"])
    pi_, pj_ = np.nonzero((Dn > 60) & (Dn < 200))
    fr = np.nonzero(analysisG)[0][::4]
    bins = np.digitize(V[fr], VEDGES_F4) - 1
    bins[(bins < 0) | (bins >= 100)] = -1
    N = np.zeros(100 * 100)
    for a, b in zip(pi_, pj_):
        ok = (bins[:, a] >= 0) & (bins[:, b] >= 0)
        N += np.bincount(bins[ok, a] * 100 + bins[ok, b], minlength=10000)
    R["joint"] = N.reshape(100, 100)  # [own bin, neighbour bin]
    R["joint_pairs"] = len(pi_)
    del bins
    # --- population averages
    R["pop_all"] = V.mean(1)
    R["pop_npy_pos"] = V[:, B["gfp"]].mean(1)
    R["pop_npy_neg"] = V[:, ~B["gfp"]].mean(1)
    R["quiet"], R["whisk"], R["run_guard"] = B["quiet"], B["whisk"], B["run_guard"]
    # --- wave propagation events (Methods, Wave propagation analysis; l1opto.wave_events): quiet and
    #     whisking frames without running and outside +/-1000 frames of a chunk edge, whole session
    tw = time.time()
    wq = quiet_nr & ~B["chunk_guard_1000"]
    ww = whisk_nr & ~B["chunk_guard_1000"]
    R["waves"] = {}
    for seg, step in (("extrema", 1), ("window", 4)):
        thr, ev = L.wave_events(V, B["x_um"], B["y_um"], wq, ww, segment=seg)
        spans = sorted(set((lo, hi) for _, lo, hi in ev))
        rows = []
        for lo, hi in spans[::step]:  # every 4th span for the longer "window" spans (run time)
            if hi - lo + 1 < 5:
                continue
            lag = L.event_lags(V[lo:hi + 1].astype(np.float64))
            sp_ = L.wave_speed(lag, B["x_um"], B["y_um"])
            a0, b0 = max(0, lo - 300), min(n, hi + 301)
            Zs = hilbert(V[a0:b0] - V[a0:b0].mean(0), axis=0)[lo - a0:hi - a0 + 1].mean(0)
            sp_["dir"] = L.phase_direction(Zs, B["x_um"], B["y_um"])
            sp_["lo"], sp_["hi"] = lo, hi
            rows.append(sp_)
        R["waves"][seg] = dict(thr=thr, peaks=np.array([e[0] for e in ev]), spans=spans, step=step,
                               quiet_s=wq.sum() * L.DT, table=pd.DataFrame(rows))
    print(f"   wave events in {time.time() - tw:.0f} s")
    R["chunk_guard_140"] = L.chunk_guard(n, B["frames_per_chunk"], 140)
    # --- oscillation peaks (code, Figure 6I) and per-cell peak-triggered averages (Supplementary Fig. 26A)
    bb, aa = butter(4, np.array([1.5, 10]) * 2 * L.DT, btype="bandpass")
    filt = filtfilt(bb, aa, R["pop_all"].astype(np.float64))
    pk, _ = find_peaks(filt, height=0)
    pk = pk[B["quiet"][pk]]
    pk = pk[pk + 1 <= 1.3e6]  # code: peakFrames > 1.3e6 removed (1-based)
    pk = pk[(pk >= 300) & (pk < n - 300)]
    R["osc_peaks"] = pk
    Sm = L.spike_train_matrix(sf, n)
    win = np.arange(-300, 301)
    vsum = np.zeros((len(win), nc)); rsum = np.zeros((len(win), nc))
    for k0 in range(0, len(pk), 500):
        idx = pk[k0:k0 + 500, None] + win[None, :]
        vsum += V[idx].sum(0)
        rsum += Sm[idx].sum(0)
    R["osc_V"] = vsum / len(pk)
    R["osc_rate"] = rsum / len(pk) / L.DT
    # --- whisking onsets (code, selectWhiskingOnsets) and onset-triggered rates (Supplementary Fig. 26B)
    on, lam, sds = L.whisking_onsets(B)
    R["onsets"], R["onset_lambda"] = on, lam
    w640 = int(round(0.64 / L.DT))
    on_ok = on[(on >= w640) & (on < n - w640)]
    R["rate_before"] = np.array([np.mean(np.searchsorted(x, on_ok) - np.searchsorted(x, on_ok - w640)) for x in sf]) / 0.64
    R["rate_after"] = np.array([np.mean(np.searchsorted(x, on_ok + w640) - np.searchsorted(x, on_ok)) for x in sf]) / 0.64
    R["n_onsets_used"] = len(on_ok)
    sh = on_ok - int(round(3 / L.DT))  # clock check: onsets moved 3 s earlier
    sh = sh[sh >= w640]
    R["shift_before"] = np.array([np.mean(np.searchsorted(x, sh) - np.searchsorted(x, sh - w640)) for x in sf]) / 0.64
    R["shift_after"] = np.array([np.mean(np.searchsorted(x, sh + w640) - np.searchsorted(x, sh)) for x in sf]) / 0.64
    # --- state-dependent P(spk|V) (code, Figure 6K): first 2000 s, chunk guard +/-140 frames;
    #     quiet = stored quiet mask; whisking = 0 to 500 frames after an onset, without running
    tmask = np.zeros(n, bool); tmask[:int(round(2000 / L.DT))] = True
    tmask &= ~R["chunk_guard_140"]
    onset_win = np.zeros(n, bool)
    for o in on:
        onset_win[o:min(n, o + 501)] = True
    st_masks = {"quiet": tmask & B["quiet"], "whisk": tmask & onset_win & ~B["run_guard"]}
    R["k_frames"] = {k: int(v.sum()) for k, v in st_masks.items()}
    for st, mk in st_masks.items():
        num = np.zeros(nc); den = np.zeros(nc)
        for c in range(nc):
            inb = mk & (V[:, c] >= 0.4) & (V[:, c] < 0.6)
            den[c] = inb.sum()
            num[c] = inb[sf[c]].sum()
        R[f"pv46_{st}"] = (num, den)
    # --- UMAP input (code, Figure 6E-G umapGrouping): spikes with frames where more than 15 cells
    #     spike zeroed, 500 ms bins over the session; bins used are those more than 80% inside the
    #     first 2000 s and outside +/-5000 frames of a chunk boundary
    Sm_r = Sm.copy()
    Sm_r[Sm.sum(1) > 15] = False
    binf = int(round(0.5 / L.DT))
    nb_ = n // binf
    R["umap_counts"] = Sm_r[:nb_ * binf].reshape(nb_, binf, nc).sum(1) / (binf * L.DT)
    tm = np.zeros(n, bool); tm[:int(round(2000 / L.DT))] = True
    tm &= ~L.chunk_guard(n, B["frames_per_chunk"], 5000)
    R["umap_binmask"] = tm[:nb_ * binf].reshape(nb_, binf).mean(1) > 0.8
    R["n_sync_frames"] = int((Sm.sum(1) > 15).sum())
    del Sm, Sm_r
    del V
    # --- normalized voltage, all 320 cells, in 3 min chunks: shot noise (1.4826 x MAD of the
    #     1-frame difference, Methods) and spike height (normalized voltage at the spike frame minus
    #     the mean of frames -6 to -3, a standard choice); plus the covariance of the QC cells' normalized
    #     voltage per state with lag-1 products, for the dimensionality reading (b)
    f = L.open_file(m, "behavior")
    dn = f["processing/optical_voltage/normalized_voltage/data"]
    u_all = U[m, "behavior"]
    sf_all = [L.spike_frames(x, B["ts"]) for x in u_all["spike_times"]]
    nch = n // CHUNK3
    noise = np.full((nch, 320), np.nan); height = np.full((nch, 320), np.nan)
    acc = {st: [np.zeros(nc), np.zeros((nc, nc)), 0, np.zeros(nc)] for st in ("quiet", "whisk")}
    for k in range(nch):
        a = k * CHUNK3
        X = dn[a:a + CHUNK3]
        dX = np.diff(X, axis=0)
        noise[k] = 1.4826 * np.median(np.abs(dX - np.median(dX, 0)), 0)
        for c in range(320):
            s_ = sf_all[c]
            s_ = s_[(s_ >= a + 6) & (s_ < a + CHUNK3)] - a
            if len(s_) >= 5:
                height[k, c] = np.median(X[s_, c] - X[s_[:, None] + np.arange(-6, -2)[None, :], c].mean(1))
        Xq = X[:, B["cells"]].astype(np.float64)
        for st, mk in [("quiet", quiet_nr), ("whisk", whisk_nr)]:
            mm_ = mk[a:a + CHUNK3]
            Y = Xq[mm_]
            acc[st][0] += Y.sum(0); acc[st][1] += Y.T @ Y; acc[st][2] += len(Y)
            both = mm_[:-1] & mm_[1:]
            acc[st][3] += (Xq[:-1][both] * Xq[1:][both]).sum(0)
    R["snr_noise"], R["snr_height"] = noise, height
    R["snr_qc"] = u_all["passed_qc"]
    for st in ("quiet", "whisk"):
        s1, s2, cnt, lag1 = acc[st]
        mu = s1 / cnt
        C = (s2 - np.outer(s1, s1) / cnt) / (cnt - 1)
        C[np.diag_indices(nc)] = lag1 / cnt - mu ** 2  # lag-1 covariance on the diagonal (Methods)
        ev = np.sort(np.linalg.eigvalsh(C))[::-1]
        R[f"pca_norm_{st}"] = ev / ev.sum()
    del B
    BEH[m] = R
    print(f"   reduced in {time.time() - tl:.0f} s; {len(pk)} oscillation peaks, {len(on)} whisking onsets "
          f"(reconstruction {lam + 1} of 15), {R['n_sync_frames']} frames with more than 15 cells spiking")
M-YQ0201-27: 247 QC cells, 2880000 frames (3658 s); quiet 0.472, whisking 0.365, running guard 0.108 of frames; running speed -0.134 to 0.034 m/s; subthreshold 0.1 to 99.9 percentile [-1.99  1.54] SH
   wave events in 164 s
   reduced in 439 s; 4279 oscillation peaks, 688 whisking onsets (reconstruction 14 of 15), 60 frames with more than 15 cells spiking
M-YQ0201-29: 258 QC cells, 2880000 frames (3658 s); quiet 0.547, whisking 0.297, running guard 0.098 of frames; running speed -0.054 to 0.019 m/s; subthreshold 0.1 to 99.9 percentile [-2.43  1.46] SH
   wave events in 187 s
   reduced in 473 s; 5886 oscillation peaks, 551 whisking onsets (reconstruction 9 of 15), 11 frames with more than 15 cells spiking
In [3]:
# Shared clock of the face-camera whisking trace and the voltage: population spike rate in the
# 640 ms before and after whisking onsets, at the true onsets and with onsets moved 3 s earlier.
for m in L.MICE:
    R = BEH[m]
    print(f"{m}: mean rate over QC cells before / after onset {R['rate_before'].mean():.2f} / {R['rate_after'].mean():.2f} Hz; "
          f"onsets moved 3 s earlier {R['shift_before'].mean():.2f} / {R['shift_after'].mean():.2f} Hz")
M-YQ0201-27: mean rate over QC cells before / after onset 1.06 / 1.74 Hz; onsets moved 3 s earlier 1.18 / 1.19 Hz
M-YQ0201-29: mean rate over QC cells before / after onset 1.27 / 1.94 Hz; onsets moved 3 s earlier 1.32 / 1.38 Hz

spike-snr-and-detection-errors¶

Single-spike SNR (spike height over baseline shot noise) was 4.5 +/- 0.7; the estimated false-discovery proportion of spike detection was 17 +/- 13% and the false-negative rate 28 +/- 19%.

The stored voltage is normalized by each cell's spike height (the mean of the spike Gaussian, Methods), so the SNR is 1 over the shot noise of the normalized trace, taken as 1.4826 x the median absolute deviation of the 1-frame difference (Methods). The noise is the median over the session's 3 min chunks; the SNR measured with the spike height found in the data (normalized voltage at the spike frame minus the mean of frames -6 to -3) is shown too. Readings: (a) behavior sessions, (b) every session; QC cells or all cells. The false-discovery and false-negative rates need the matched-filter output and its fitted mixture, which the dandiset does not store; they are not computed here.

In [4]:
snr_rows = []
for m in L.MICE:
    R = BEH[m]
    noise = np.nanmedian(R["snr_noise"], 0)
    h = np.nanmedian(R["snr_height"], 0)
    for cells, sel in [("QC", R["snr_qc"]), ("all", np.ones(320, bool))]:
        snr_rows.append(dict(mouse=m, session="behavior", cells=cells, n=int(sel.sum()),
                             snr_norm_mean=np.mean(1 / noise[sel]), snr_norm_sd=np.std(1 / noise[sel], ddof=1),
                             snr_meas_mean=np.nanmean(h[sel] / noise[sel]), snr_meas_sd=np.nanstd(h[sel] / noise[sel], ddof=1),
                             spike_height_median=np.nanmedian(h[sel])))
SNR_OTHER = {}
for m in L.MICE:
    for s in ("sparseOpto", "sparsePulseHad"):
        f = L.open_file(m, s)
        d = f["processing/optical_voltage/normalized_voltage/data"]
        nz = []
        for a in range(0, d.shape[0] - CHUNK3 + 1, 4 * CHUNK3):  # every fourth 3 min chunk, to save time
            dX = np.diff(d[a:a + 20000], axis=0)  # 25 s from the start of the chunk
            nz.append(1.4826 * np.median(np.abs(dX - np.median(dX, 0)), 0))
        noise = np.median(nz, 0)
        SNR_OTHER[m, s] = noise
        for cells, sel in [("QC", U[m, s]["passed_qc"]), ("all", np.ones(320, bool))]:
            snr_rows.append(dict(mouse=m, session=s, cells=cells, n=int(sel.sum()), snr_norm_mean=np.mean(1 / noise[sel]),
                                 snr_norm_sd=np.std(1 / noise[sel], ddof=1)))
snr_df = pd.DataFrame(snr_rows)
print(snr_df.round(3).to_string())
for nm, q_ in [("(a) behavior sessions", snr_df.session == "behavior"), ("(b) every session", snr_df.session.notna())]:
    for cells in ("QC", "all"):
        d = snr_df[q_ & (snr_df.cells == cells)]
        print(f"{nm}, {cells} cells (n = {d.n.sum()}): mean SNR (1/noise) weighted by cells {np.average(d.snr_norm_mean, weights=d.n):.2f}")
          mouse         session cells    n  snr_norm_mean  snr_norm_sd  snr_meas_mean  snr_meas_sd  spike_height_median
0   M-YQ0201-27        behavior    QC  247          3.504        0.961          2.961        0.508                0.881
1   M-YQ0201-27        behavior   all  320          3.334        0.984          2.864        0.492                0.893
2   M-YQ0201-29        behavior    QC  258          3.156        0.826          2.897        0.500                0.931
3   M-YQ0201-29        behavior   all  320          3.028        0.829          2.826        0.483                0.960
4   M-YQ0201-27      sparseOpto    QC  286          3.523        0.881            NaN          NaN                  NaN
5   M-YQ0201-27      sparseOpto   all  320          3.463        0.877            NaN          NaN                  NaN
6   M-YQ0201-27  sparsePulseHad    QC  290          3.942        1.009            NaN          NaN                  NaN
7   M-YQ0201-27  sparsePulseHad   all  320          3.851        1.027            NaN          NaN                  NaN
8   M-YQ0201-29      sparseOpto    QC  257          3.239        0.719            NaN          NaN                  NaN
9   M-YQ0201-29      sparseOpto   all  320          3.150        0.723            NaN          NaN                  NaN
10  M-YQ0201-29  sparsePulseHad    QC  286          3.269        0.734            NaN          NaN                  NaN
11  M-YQ0201-29  sparsePulseHad   all  320          3.204        0.743            NaN          NaN                  NaN
(a) behavior sessions, QC cells (n = 505): mean SNR (1/noise) weighted by cells 3.33
(a) behavior sessions, all cells (n = 640): mean SNR (1/noise) weighted by cells 3.18
(b) every session, QC cells (n = 1624): mean SNR (1/noise) weighted by cells 3.45
(b) every session, all cells (n = 1920): mean SNR (1/noise) weighted by cells 3.34
In [5]:
# What the raw-movie excerpt holds (its DANDI metadata mentions "the demixing and spike-finding
# products"): every dataset outside the NWB specifications, to see whether a matched-filter
# output or a fitted spike mixture is stored
import h5py
fx = L.open_file("M-YQ0201-29", "behavior-rawexcerpt")
listing = []
fx.visititems(lambda name, obj: listing.append((name, obj.shape, str(obj.dtype)))
              if isinstance(obj, h5py.Dataset) and not name.startswith("specifications") else None)
for name, shape, dt in listing:
    print(f"   {name} {shape} {dt}")
print("datasets named like a filter, template, threshold or mixture:",
      [n for n, _, _ in listing if any(k in n.lower() for k in ("filter", "template", "thresh", "mixture", "gauss", "snr"))])
   acquisition/images/segmentation_reference_image (328, 448) float32
   acquisition/images/structural_gfp (328, 448) float32
   acquisition/images/structural_rfp (328, 448) float32
   acquisition/raw_voltage_movie/data (1152000, 328, 448) uint16
   acquisition/raw_voltage_movie/format () object
   acquisition/raw_voltage_movie/timestamps (1152000,) float64
   file_create_date (1,) object
   general/experiment_description () object
   general/optophysiology/imaging_plane/description () object
   general/optophysiology/imaging_plane/excitation_lambda () float64
   general/optophysiology/imaging_plane/grid_spacing (2,) float64
   general/optophysiology/imaging_plane/imaging_rate () float64
   general/optophysiology/imaging_plane/indicator () object
   general/optophysiology/imaging_plane/location () object
   general/optophysiology/imaging_plane/opticalchannel/description () object
   general/optophysiology/imaging_plane/opticalchannel/emission_lambda () float64
   general/session_id () object
   general/subject/date_of_birth (1,) object
   general/subject/description () object
   general/subject/genotype () object
   general/subject/sex () object
   general/subject/species () object
   general/subject/subject_id () object
   general/was_generated_by (1, 2) object
   identifier () object
   intervals/recording_chunks/chunk_id (4,) int32
   intervals/recording_chunks/id (4,) int64
   intervals/recording_chunks/source_folder (4,) object
   intervals/recording_chunks/start_time (4,) float64
   intervals/recording_chunks/stop_time (4,) float64
   processing/behavior/behavioral_time_series/running_speed/data (1152000, 1) float64
   processing/behavior/behavioral_time_series/running_speed/timestamps (1152000,) float64
   processing/ophys/Fluorescence/roi_response_series/data (1152000, 320) float32
   processing/ophys/Fluorescence/roi_response_series/rois (320,) int64
   processing/ophys/Fluorescence/roi_response_series/timestamps (1152000,) float64
   processing/ophys/ImageSegmentation/plane_segmentation/id (320,) int64
   processing/ophys/ImageSegmentation/plane_segmentation/image_mask (320, 328, 448) float32
   processing/ophys/ImageSegmentation/plane_segmentation/initial_image_mask (320, 328, 448) float32
   processing/ophys/mc_pixel_map/id (5712,) int64
   processing/ophys/mc_pixel_map/mov_mask_column (5712,) int32
   processing/ophys/mc_pixel_map/pixel_column (5712,) int32
   processing/ophys/mc_pixel_map/pixel_row (5712,) int32
   processing/ophys/mc_pixel_map/unit_id (5712,) int32
   processing/ophys/mc_pixel_subset/data (1152000, 5712) uint16
   processing/ophys/mc_pixel_subset/timestamps (1152000,) float64
   processing/ophys/motion_trace_x/data (1152000, 320) float32
   processing/ophys/motion_trace_x/timestamps (1152000,) float64
   processing/ophys/motion_trace_y/data (1152000, 320) float32
   processing/ophys/motion_trace_y/timestamps (1152000,) float64
   scratch/matlab_variable_lookup/id (16,) int64
   scratch/matlab_variable_lookup/mapping_notes (16,) object
   scratch/matlab_variable_lookup/matlab_variable (16,) object
   scratch/matlab_variable_lookup/nwb_path (16,) object
   session_description () object
   session_start_time (1,) object
   timestamps_reference_time (1,) object
   units/edge_distance_pixels (320,) float64
   units/gfp_positive (320,) uint8
   units/id (320,) int64
   units/passed_qc (320,) uint8
   units/spike_times (738722,) float64
   units/spike_times_index (320,) uint64
   units/tutorial_cell (320,) uint8
   units/x_pixel (320,) float64
   units/x_um (320,) float64
   units/y_pixel (320,) float64
   units/y_um (320,) float64
datasets named like a filter, template, threshold or mixture: []

Result: not reproduced. The single-spike SNR of the stored normalized voltage is 3.33 (mean over the 505 QC cells of the behavior sessions; 3.18 over all 640 cells), and 3.0 to 3.9 per mouse and session under every reading, below 4.5 +/- 0.7. Measured with the spike heights found in the data (median 0.88 to 0.96 SH) it is lower (2.8 to 3.0). The false-discovery and false-negative rates were not tested: no matched-filter output or fitted mixture is stored, in the session files or in the raw-movie excerpt, whose datasets (listed above) are the movie, fluorescence traces, footprints, motion traces, a pixel subset and spike times.

snr-decay-one-hour¶

After 1 h of continuous imaging at 16 mW/mm2, spike SNR fell to 76 +/- 13% of its initial value.

The behavior sessions are 61 min of continuous imaging (10 chunks of 365.8 s, adjacent in time). Per cell and 3 min chunk, SNR = spike height / shot noise as above; the ratio of the chunk ending at 60 min (the 20th) to the first. Mean of per-cell ratios and ratio of mean SNRs; QC cells and all cells. Cells with fewer than 5 spikes in a chunk have no height there and are left out.

In [6]:
for cells in ("QC", "all"):
    ratios, first, last = [], [], []
    for m in L.MICE:
        R = BEH[m]
        sel = R["snr_qc"] if cells == "QC" else np.ones(320, bool)
        snr = R["snr_height"] / R["snr_noise"]
        r_ = snr[19, sel] / snr[0, sel]
        ratios.append(r_); first.append(snr[0, sel]); last.append(snr[19, sel])
        print(f"{cells} cells, {m}: {np.isfinite(r_).sum()} cells; SNR first chunk {np.nanmean(snr[0, sel]):.2f}, chunk 20 "
              f"{np.nanmean(snr[19, sel]):.2f}; noise ratio {np.nanmean(R['snr_noise'][19, sel] / R['snr_noise'][0, sel]):.3f}, "
              f"height ratio {np.nanmean(R['snr_height'][19, sel] / R['snr_height'][0, sel]):.3f}")
    r_ = np.concatenate(ratios)
    fi, la = np.concatenate(first), np.concatenate(last)
    ok = np.isfinite(r_)
    print(f"{cells} cells pooled (n = {ok.sum()}): mean of ratios {100*np.mean(r_[ok]):.1f} +/- {100*np.std(r_[ok], ddof=1):.1f}%, "
          f"ratio of means {100*np.mean(la[ok])/np.mean(fi[ok]):.1f}%")
snr_q = np.concatenate([(BEH[m]["snr_height"] / BEH[m]["snr_noise"])[:, BEH[m]["snr_qc"]] for m in L.MICE], axis=1)
print("mean SNR by 3 min chunk, QC cells:", np.round(np.nanmean(snr_q, 1), 2))
QC cells, M-YQ0201-27: 247 cells; SNR first chunk 3.91, chunk 20 2.64; noise ratio 0.955, height ratio 0.675
QC cells, M-YQ0201-29: 258 cells; SNR first chunk 3.56, chunk 20 2.57; noise ratio 1.019, height ratio 0.765
QC cells pooled (n = 505): mean of ratios 72.9 +/- 15.6%, ratio of means 69.8%
all cells, M-YQ0201-27: 320 cells; SNR first chunk 3.67, chunk 20 2.61; noise ratio 0.955, height ratio 0.721
all cells, M-YQ0201-29: 320 cells; SNR first chunk 3.37, chunk 20 2.55; noise ratio 1.022, height ratio 0.809
all cells pooled (n = 640): mean of ratios 77.3 +/- 17.7%, ratio of means 73.4%
mean SNR by 3 min chunk, QC cells: [3.73 3.6  3.36 3.3  3.22 3.16 3.05 3.04 2.98 2.96 2.92 2.88 2.83 2.79
 2.78 2.75 2.69 2.66 2.66 2.6 ]

Result: reproduced. The SNR of the 20th 3 min chunk (57 to 60 min) is 72.9 +/- 15.6% of the first chunk's for the 505 QC cells (mean of ratios; ratio of means 69.8%) and 77.3 +/- 17.7% for all 640 cells (ratio of means 73.4%), within 76 +/- 13%. The decline comes from the spike height (ratio 0.68 and 0.77 for QC cells), not the noise (0.96 and 1.02).

Figure 4: spontaneous dynamics¶

subthreshold-correlation-length¶

In the quiet state subthreshold voltages of nearby cells (60 to 120 um) correlate at 0.6 and the correlation decays with a 2.4 mm length constant; in the whisking state the values are 0.5 and 4.0 mm.

As the code's STATS block (l1opto.fig4_statistics), from the stored state-dependent voltage cross-correlations; per mouse, then averaged. The code reports 1/slope, negative for a decay; the length constant is its magnitude.

In [7]:
F4 = {m: L.fig4_statistics(ST4[m]) for m in L.MICE}
for m in L.MICE:
    print(f"{m}: short-range correlation quiet {F4[m]['short_range'][0]:.3f}, whisking {F4[m]['short_range'][1]:.3f}; "
          f"length constant quiet {abs(F4[m]['lambda_V'][0])/1e3:.2f} mm, whisking {abs(F4[m]['lambda_V'][1])/1e3:.2f} mm")
sr = np.mean([F4[m]["short_range"] for m in L.MICE], 0)
lv = np.mean([np.abs(F4[m]["lambda_V"]) for m in L.MICE], 0) / 1e3
print(f"mean of the two mice: short-range {sr.round(3)} (quiet, whisking; expected 0.6, 0.5), length constant {lv.round(2)} mm (expected 2.4, 4.0)")
c = ST4["M-YQ0201-27"]["centers_um"]
print("zero-lag correlation by distance bin, quiet, M-YQ0201-27 (first 8 bins):", dict(zip(c[2:10].round(0), ST4["M-YQ0201-27"]["summary"]["xcorrV0"][0, 2:10].round(3))))
M-YQ0201-27: short-range correlation quiet 0.645, whisking 0.497; length constant quiet 2.22 mm, whisking 3.71 mm
M-YQ0201-29: short-range correlation quiet 0.630, whisking 0.539; length constant quiet 2.63 mm, whisking 4.35 mm
mean of the two mice: short-range [0.638 0.518] (quiet, whisking; expected 0.6, 0.5), length constant [2.42 4.03] mm (expected 2.4, 4.0)
zero-lag correlation by distance bin, quiet, M-YQ0201-27 (first 8 bins): {np.float64(90.0): np.float64(0.645), np.float64(150.0): np.float64(0.61), np.float64(210.0): np.float64(0.592), np.float64(270.0): np.float64(0.576), np.float64(330.0): np.float64(0.553), np.float64(390.0): np.float64(0.539), np.float64(450.0): np.float64(0.526), np.float64(510.0): np.float64(0.507)}

Result: reproduced. Averaged over the two mice, the 60 to 120 um zero-lag correlation is 0.638 quiet and 0.518 whisking (expected 0.6 +/- 0.06 and 0.5 +/- 0.05), and the length constants are 2.42 and 4.03 mm (2.4 +/- 0.24 and 4.0 +/- 0.4).

subthreshold-low-dimensional¶

Subthreshold dynamics are low dimensional; the first 10 principal components explain 72% of the variance in the quiet state and 62% in the whisking state.

Covariance of the QC cells' voltage per state (stored quiet or whisking mask, running frames excluded as in the code's Figures 4 to 6), eigenvalues over total variance (Methods). Readings: (a) the stored subthreshold voltage, diagonal kept; (b) the normalized voltage with the lag-1 variance on the diagonal; per mouse and averaged.

In [8]:
pca_rows = []
for m in L.MICE:
    for rd, key in [("(a) subthreshold", "pca_sub"), ("(b) normalized, lag-1 diagonal", "pca_norm")]:
        pca_rows.append(dict(mouse=m, reading=rd, quiet=100 * BEH[m][f"{key}_quiet"][:10].sum(), whisk=100 * BEH[m][f"{key}_whisk"][:10].sum(),
                             quiet_pc1=100 * BEH[m][f"{key}_quiet"][0], whisk_pc1=100 * BEH[m][f"{key}_whisk"][0]))
pca_df = pd.DataFrame(pca_rows)
print(pca_df.round(1).to_string())
print(pca_df.groupby("reading")[["quiet", "whisk"]].mean().round(1).to_string())
for m in L.MICE:
    print(m, "frames per state (no running):", {k: v for k, v in BEH[m]["n_frames_states"].items() if k.endswith("_nr")})
         mouse                         reading  quiet  whisk  quiet_pc1  whisk_pc1
0  M-YQ0201-27                (a) subthreshold   70.8   63.0       41.7       37.8
1  M-YQ0201-27  (b) normalized, lag-1 diagonal   72.8   64.2       43.2       38.4
2  M-YQ0201-29                (a) subthreshold   70.6   72.0       49.9       57.1
3  M-YQ0201-29  (b) normalized, lag-1 diagonal   77.6   74.0       56.1       58.6
                                quiet  whisk
reading                                     
(a) subthreshold                 70.7   67.5
(b) normalized, lag-1 diagonal   75.2   69.1
M-YQ0201-27 frames per state (no running): {'quiet_nr': 1347832, 'whisk_nr': 1051907}
M-YQ0201-29 frames per state (no running): {'quiet_nr': 1569405, 'whisk_nr': 855947}

Result: reproduced. Under reading (a), the stored subthreshold voltage averaged over the two mice, the first 10 components explain 70.7% of the variance in quiet and 67.5% in whisking (72 +/- 7.2 and 62 +/- 6.2), quiet above whisking. Per mouse the ordering holds in M-YQ0201-27 (70.8 and 63.0%) but not in M-YQ0201-29 (70.6 and 72.0%). Reading (b) gives 75.2 and 69.1%, the whisking value outside tolerance.

quiet-state-oscillations¶

In the quiet state, but not the whisking state, subthreshold dynamics often show global oscillations between 1 and 10 Hz.

Welch power spectrum of each QC cell's subthreshold voltage, 2 s segments wholly inside the state (no running), averaged over cells (Methods, Frequency spectrum). Reproduced when in both mice the power integrated over 1 to 10 Hz is higher in quiet than in whisking (the claims file's reading).

In [9]:
for m in L.MICE:
    out = {}
    for st in ("quiet", "whisk"):
        fq, psd, nseg = BEH[m][f"psd_{st}"]
        pop = psd.mean(1)
        band = (fq >= 1) & (fq <= 10)
        out[st] = (np.trapezoid(pop[band], fq[band]), nseg, fq[band][np.argmax(pop[band])])
    print(f"{m}: 1 to 10 Hz power quiet {out['quiet'][0]:.4g} ({out['quiet'][1]} segments, peak {out['quiet'][2]:.1f} Hz), "
          f"whisking {out['whisk'][0]:.4g} ({out['whisk'][1]} segments, peak {out['whisk'][2]:.1f} Hz); ratio {out['quiet'][0]/out['whisk'][0]:.2f}")
fq, pq, _ = BEH["M-YQ0201-27"]["psd_quiet"]
_, pw, _ = BEH["M-YQ0201-27"]["psd_whisk"]
plt.figure(figsize=(5, 3))
plt.semilogy(fq[fq <= 30], pq.mean(1)[fq <= 30], label="quiet")
plt.semilogy(fq[fq <= 30], pw.mean(1)[fq <= 30], label="whisking")
plt.xlabel("Frequency (Hz)"); plt.ylabel("PSD (SH^2/Hz)"); plt.legend(); plt.title("M-YQ0201-27, mean over QC cells, 0 to 30 Hz")
plt.show()
M-YQ0201-27: 1 to 10 Hz power quiet 0.08323 (436 segments, peak 2.5 Hz), whisking 0.01685 (243 segments, peak 1.5 Hz); ratio 4.94
M-YQ0201-29: 1 to 10 Hz power quiet 0.04879 (531 segments, peak 4.5 Hz), whisking 0.01671 (107 segments, peak 1.5 Hz); ratio 2.92
No description has been provided for this image

Result: reproduced. The population-average power from 1 to 10 Hz is 4.9 times higher in quiet than in whisking in M-YQ0201-27 and 2.9 times in M-YQ0201-29; the quiet spectra peak at 2.5 and 4.5 Hz.

traveling-waves¶

Quiet-state oscillations are traveling waves with various directions, a slight bias toward medial-posterior, and a mean speed of 18.2 +/- 8.3 mm/s (3,858 events, 2 mice); a 5 Hz oscillation has a wavelength of about 4 mm.

Methods, Wave propagation analysis, with no code: events are peaks of the derivative of the population-average subthreshold voltage (QC cells) above 3.5 times its s.d. during whisking, in quiet epochs; each event spans the voltage minimum to maximum flanking the peak; its speed is the slope of the line relating the lag of the peak cross-correlation of every cell pair to their separation; its direction is that of the flow field of the Hilbert phase (325 um Gaussian, 160 um grid). Quiet and whisking frames are the stored masks without running and outside +/-1000 frames of a chunk edge (the code's Figure 4 masks), over the whole session. The Methods leave open the parts that set the count and the speed, so each is run (l1opto.wave_events): the span as the adjacent turning points of the average ("extrema") or the minimum and maximum within 250 ms ("window"); events counted per derivative peak or per distinct span; the speed (a) distance regressed on absolute lag, (b) absolute lag on distance, inverted (the claims file's readings), and (c) a plane-wave fit of signed lag on displacement (a variant). The "window" spans are long, so every fourth span is used for their speeds. The first 2000 s (the code's Figure 4 window) are shown as a variant for the count. The files do not give the orientation of the x and y axes relative to the brain (data check), so directions are in the image frame and the medial-posterior bias cannot be tested.

In [10]:
for seg in ("extrema", "window"):
    print(f"span reading '{seg}':")
    tot_p = tot_s = 0
    allsp = []
    for m in L.MICE:
        W = BEH[m]["waves"][seg]
        pk_ = W["peaks"]; sp_ = W["spans"]
        early = np.sum((pk_ >= 5000) & (pk_ < round(2000 / L.DT)))
        early_s = sum(1 for lo, hi in sp_ if 5000 <= lo < round(2000 / L.DT))
        tot_p += len(pk_); tot_s += len(sp_)
        t = W["table"]; allsp.append(t)
        ln = np.array([hi - lo + 1 for lo, hi in sp_]) * L.DT * 1e3
        print(f"   {m}: threshold {W['thr']:.4f} SH/frame; {W['quiet_s']:.0f} s quiet; {len(pk_)} derivative peaks, {len(sp_)} distinct spans "
              f"(first 2000 s: {early} and {early_s}); span {np.median(ln):.0f} ms median ({np.percentile(ln, 5):.0f} to {np.percentile(ln, 95):.0f}); "
              f"speeds from {len(t)} spans")
        for k in ("a", "b", "c"):
            v = t[k].values; v = v[np.isfinite(v)]
            print(f"      speed ({k}): mean {v.mean():.1f} +/- {v.std(ddof=1):.1f} mm/s, median {np.median(v):.1f} (n = {len(v)})")
    t = pd.concat(allsp)
    print(f"   both mice: {tot_p} derivative peaks, {tot_s} distinct spans")
    for k in ("a", "b", "c"):
        v = t[k].values; v = v[np.isfinite(v)]
        print(f"      speed ({k}): mean {v.mean():.1f} +/- {v.std(ddof=1):.1f} mm/s, median {np.median(v):.1f}, "
              f"5 to 95 percentile {np.percentile(v, 5):.1f} to {np.percentile(v, 95):.1f} (n = {len(v)} of {len(t)})")
    for m, tm in zip(L.MICE, allsp):
        for nm, col in (("phase gradient", "dir"), ("plane-wave fit", "c_dir")):
            z = np.exp(1j * tm[col].values)
            print(f"      {m} {nm} direction (image frame, 0 = +x, 90 = +y): circular mean {np.degrees(np.angle(z.mean())):.0f} deg, "
                  f"resultant length {abs(z.mean()):.2f}")
span reading 'extrema':
   M-YQ0201-27: threshold 0.0272 SH/frame; 1705 s quiet; 3254 derivative peaks, 2155 distinct spans (first 2000 s: 718 and 398); span 33 ms median (10 to 70); speeds from 2155 spans
      speed (a): mean 8.6 +/- 9.8 mm/s, median 7.9 (n = 2155)
      speed (b): mean 6091.7 +/- 28845.2 mm/s, median 921.6 (n = 1887)
      speed (c): mean 2797.5 +/- 4879.9 mm/s, median 1205.5 (n = 2155)
   M-YQ0201-29: threshold 0.0260 SH/frame; 1985 s quiet; 3655 derivative peaks, 2291 distinct spans (first 2000 s: 2548 and 1566); span 41 ms median (23 to 69); speeds from 2291 spans
      speed (a): mean 11.5 +/- 8.5 mm/s, median 10.5 (n = 2291)
      speed (b): mean 1693.4 +/- 18180.9 mm/s, median 505.1 (n = 2229)
      speed (c): mean 1123.9 +/- 2429.1 mm/s, median 608.4 (n = 2291)
   both mice: 6909 derivative peaks, 4446 distinct spans
      speed (a): mean 10.1 +/- 9.3 mm/s, median 9.5, 5 to 95 percentile -1.4 to 22.5 (n = 4446 of 4446)
      speed (b): mean 3709.8 +/- 23772.2 mm/s, median 632.3, 5 to 95 percentile 167.8 to 10518.2 (n = 4116 of 4446)
      speed (c): mean 1935.1 +/- 3908.9 mm/s, median 765.9, 5 to 95 percentile 173.5 to 6684.6 (n = 4446 of 4446)
      M-YQ0201-27 phase gradient direction (image frame, 0 = +x, 90 = +y): circular mean 79 deg, resultant length 0.13
      M-YQ0201-27 plane-wave fit direction (image frame, 0 = +x, 90 = +y): circular mean 65 deg, resultant length 0.10
      M-YQ0201-29 phase gradient direction (image frame, 0 = +x, 90 = +y): circular mean 94 deg, resultant length 0.16
      M-YQ0201-29 plane-wave fit direction (image frame, 0 = +x, 90 = +y): circular mean 41 deg, resultant length 0.17
span reading 'window':
   M-YQ0201-27: threshold 0.0272 SH/frame; 1705 s quiet; 2935 derivative peaks, 1777 distinct spans (first 2000 s: 627 and 355); span 189 ms median (48 to 394); speeds from 445 spans
      speed (a): mean 5.9 +/- 7.1 mm/s, median 3.6 (n = 445)
      speed (b): mean 618.8 +/- 4360.0 mm/s, median 88.3 (n = 433)
      speed (c): mean 388.1 +/- 1250.0 mm/s, median 91.9 (n = 445)
   M-YQ0201-29: threshold 0.0260 SH/frame; 1985 s quiet; 3263 derivative peaks, 1998 distinct spans (first 2000 s: 2283 and 1359); span 184 ms median (41 to 404); speeds from 500 spans
      speed (a): mean 6.5 +/- 8.5 mm/s, median 4.2 (n = 500)
      speed (b): mean 356.7 +/- 2019.8 mm/s, median 61.2 (n = 499)
      speed (c): mean 324.2 +/- 833.2 mm/s, median 79.6 (n = 500)
   both mice: 6198 derivative peaks, 3775 distinct spans
      speed (a): mean 6.2 +/- 7.8 mm/s, median 4.0, 5 to 95 percentile 1.3 to 18.1 (n = 945 of 945)
      speed (b): mean 478.4 +/- 3319.7 mm/s, median 69.6, 5 to 95 percentile 18.2 to 1278.3 (n = 932 of 945)
      speed (c): mean 354.3 +/- 1050.2 mm/s, median 87.0, 5 to 95 percentile 19.3 to 1446.4 (n = 945 of 945)
      M-YQ0201-27 phase gradient direction (image frame, 0 = +x, 90 = +y): circular mean 113 deg, resultant length 0.10
      M-YQ0201-27 plane-wave fit direction (image frame, 0 = +x, 90 = +y): circular mean 124 deg, resultant length 0.12
      M-YQ0201-29 phase gradient direction (image frame, 0 = +x, 90 = +y): circular mean 112 deg, resultant length 0.17
      M-YQ0201-29 plane-wave fit direction (image frame, 0 = +x, 90 = +y): circular mean 131 deg, resultant length 0.09

Result: not reproduced, resting on assumptions. No reading gives both the count and the speed. With the span between the adjacent turning points, the 4,446 distinct spans (6,909 derivative peaks) are outside 3,858 +/- 386, and the mean speed under reading (a) is 10.1 +/- 9.3 mm/s (8.6 and 11.5 per mouse), just inside 18.2 +/- 8.3. With the span between the extremes within 250 ms, the 3,775 spans are inside the tolerance (6,198 peaks are not), but the speed under (a) is 6.2 +/- 7.8 mm/s, outside it. Reading (b) and the plane-wave variant give speeds far above reading (a) in every case (per-mouse medians 61 to 1,206 mm/s; 61 to 92 mm/s for the spans within 250 ms and 505 to 1,206 mm/s for the spans between turning points), since most pairs peak at near-zero lag within these short spans. The directions are broad (resultant lengths 0.09 to 0.17), and the files do not orient the image axes on the brain, so the medial-posterior bias could not be tested. The span, the counting and the analysed frames are the Methods' open details, run as readings.

spike-synchrony-localized¶

Spike-rate cross-correlograms peak sharply in space (length constants of 277 um quiet and 270 um whisking) and time (50% decay by 2.5 ms lag), unlike subthreshold correlations (2.4 mm, full width at half maximum 80 ms).

As the code's STATS: synchrony length constants by log-linear fit restricted to r < 800 um (reading (a)) or the 2.5 ms-lag correlogram over all bins (reading (b)), per mouse, averaged; quiet voltage FWHM, the median over bins; spike half-width in the 60 to 120 um bin, whisking (code) and quiet (variant).

In [11]:
for m in L.MICE:
    s = F4[m]
    print(f"{m}: synchrony length constant (a) quiet {abs(s['lambda_sync'][0]):.0f}, whisking {abs(s['lambda_sync'][1]):.0f} um; "
          f"(b) 2.5 ms-lag fit quiet {abs(s['lambda_lag2'][0]):.0f}, whisking {abs(s['lambda_lag2'][1]):.0f} um; "
          f"voltage FWHM quiet {s['fwhm_V_quiet_ms']:.1f} ms; spike half-width whisking {s['spike_halfwidth_whisk_ms']:.2f}, quiet {s['spike_halfwidth_quiet_ms']:.2f} ms")
for k, nm in [("lambda_sync", "(a) synchrony, r < 800 um"), ("lambda_lag2", "(b) 2.5 ms lag")]:
    print(f"{nm}: mean of mice {np.mean([np.abs(F4[m][k]) for m in L.MICE], 0).round(1)} um (quiet, whisking; expected 277, 270)")
print(f"voltage FWHM quiet, mean of mice {np.mean([F4[m]['fwhm_V_quiet_ms'] for m in L.MICE]):.1f} ms (expected 80 +/- 8)")
print(f"spike half-width, mean of mice: whisking {np.mean([F4[m]['spike_halfwidth_whisk_ms'] for m in L.MICE]):.2f}, "
      f"quiet {np.mean([F4[m]['spike_halfwidth_quiet_ms'] for m in L.MICE]):.2f} ms (expected 2.5 +/- 0.25)")
M-YQ0201-27: synchrony length constant (a) quiet 263, whisking 265 um; (b) 2.5 ms-lag fit quiet 2498, whisking 6021 um; voltage FWHM quiet 78.7 ms; spike half-width whisking 2.54, quiet 2.54 ms
M-YQ0201-29: synchrony length constant (a) quiet 291, whisking 277 um; (b) 2.5 ms-lag fit quiet 2032, whisking 5402 um; voltage FWHM quiet 63.5 ms; spike half-width whisking 2.54, quiet 2.54 ms
(a) synchrony, r < 800 um: mean of mice [277.1 270.7] um (quiet, whisking; expected 277, 270)
(b) 2.5 ms lag: mean of mice [2265.2 5711.3] um (quiet, whisking; expected 277, 270)
voltage FWHM quiet, mean of mice 71.1 ms (expected 80 +/- 8)
spike half-width, mean of mice: whisking 2.54, quiet 2.54 ms (expected 2.5 +/- 0.25)

Result: partially reproduced. Three of the four values match: the synchrony length constants (reading (a)) are 277 um quiet and 271 um whisking (277 +/- 27.7 and 270 +/- 27), and the spike correlogram's half-width is 2.54 ms (2.5 +/- 0.25) in both states. The quiet voltage FWHM is 71.1 ms averaged over the mice (78.7 and 63.5 ms), outside 80 +/- 8 ms; only M-YQ0201-27 alone is within. Reading (b) gives length constants of 2.3 and 5.7 mm.

voltage-to-spike-sigmoid¶

Each cell's spontaneous voltage-to-spike relationship is sigmoidal, with substantial cell-to-cell variation in threshold and maximum rate.

P(spk|V) per QC cell in the code's quiet analysis frames (code, Figure 4E-F), V bins of 0.04 SH from -2 to 2. V is read three ways: at the spike frame (the code, and the Methods' V(t_s), "the subthreshold voltage at spike times"); as the sample 8 frames (10.2 ms) before it; and as the mean over the 8 frames (10.2 ms) before each frame, for spike frames and all frames alike (the Results' and the Figure 4E legend's "10 ms interval"). A four-parameter logistic fitted over bins holding at least 100 frames (the claims file's reading). Since a logistic fitted to a curve that has not saturated can put its top far beyond the data, the spread of maxima is also given for the largest observed rate of each cell and for fits whose top lies within twice that rate.

In [12]:
vc = (VEDGES_F4[:-1] + VEDGES_F4[1:]) / 2
logistic = lambda v, b, top, v0, k: b + (top - b) / (1 + np.exp(-(v - v0) / k))
for off in ("off0", "off8", "win8"):
    label = {"off0": "V at the spike frame", "off8": "V 8 frames before the spike", "win8": "V the mean of the 8 frames before"}[off]
    rows = []
    for m in L.MICE:
        rate, allc, spkc = BEH[m][f"pspkv_{off}"]
        for c in range(rate.shape[0]):
            ok = allc[c] >= 100
            x, y = vc[ok], rate[c, ok]
            if ok.sum() < 6 or np.nanmax(y) <= 0:
                rows.append(dict(mouse=m, r2=np.nan, v0=np.nan, top=np.nan, ymax=np.nan)); continue
            try:
                p, _ = curve_fit(logistic, x, y, p0=[0, y.max(), x[np.argmax(y > y.max() / 2)], 0.1], maxfev=20000)
                r2 = 1 - np.sum((y - logistic(x, *p)) ** 2) / np.sum((y - y.mean()) ** 2)
                rows.append(dict(mouse=m, r2=r2, v0=p[2], top=p[1], ymax=np.nanmax(y)))
            except Exception:
                rows.append(dict(mouse=m, r2=np.nan, v0=np.nan, top=np.nan, ymax=np.nanmax(y)))
    d = pd.DataFrame(rows)
    good = d.r2 >= 0.9
    cv = lambda x: np.std(x, ddof=1) / abs(np.mean(x))
    print(f"{label}: {len(d)} cells, fits failed {d.r2.isna().sum()}; R^2 >= 0.9 in {good.sum()} "
          f"({100*good.mean():.0f}%); among those, midpoint {d.v0[good].mean():.3f} +/- {d.v0[good].std():.3f} SH (CV {cv(d.v0[good]):.2f}), "
          f"maximum {d.top[good].median():.1f} Hz median (CV {cv(d.top[good]):.2f})")
    inside = good & (d.top <= 2 * d.ymax)
    print(f"   largest observed rate among the R^2 >= 0.9 cells: median {d.ymax[good].median():.1f} Hz, CV {cv(d.ymax[good]):.2f}; "
          f"fits with the top within twice the largest observed rate: {inside.sum()} of {good.sum()}, top CV {cv(d.top[inside]):.2f}, "
          f"midpoint CV {cv(d.v0[inside]):.2f}")
    for m in L.MICE:
        dm = d[d.mouse == m]
        print(f"   {m}: R^2 >= 0.9 in {(dm.r2 >= 0.9).sum()} of {len(dm)}")
/tmp/ipykernel_2957/282043745.py:14: OptimizeWarning: Covariance of the parameters could not be estimated
  p, _ = curve_fit(logistic, x, y, p0=[0, y.max(), x[np.argmax(y > y.max() / 2)], 0.1], maxfev=20000)
V at the spike frame: 505 cells, fits failed 0; R^2 >= 0.9 in 262 (52%); among those, midpoint 1.013 +/- 0.826 SH (CV 0.82), maximum 63.6 Hz median (CV 4.54)
   largest observed rate among the R^2 >= 0.9 cells: median 57.3 Hz, CV 0.59; fits with the top within twice the largest observed rate: 221 of 262, top CV 0.64, midpoint CV 0.29
   M-YQ0201-27: R^2 >= 0.9 in 133 of 247
   M-YQ0201-29: R^2 >= 0.9 in 129 of 258
/tmp/ipykernel_2957/282043745.py:14: OptimizeWarning: Covariance of the parameters could not be estimated
  p, _ = curve_fit(logistic, x, y, p0=[0, y.max(), x[np.argmax(y > y.max() / 2)], 0.1], maxfev=20000)
V 8 frames before the spike: 505 cells, fits failed 0; R^2 >= 0.9 in 121 (24%); among those, midpoint 0.840 +/- 0.745 SH (CV 0.89), maximum 26.4 Hz median (CV 3.96)
   largest observed rate among the R^2 >= 0.9 cells: median 29.6 Hz, CV 0.47; fits with the top within twice the largest observed rate: 105 of 121, top CV 0.57, midpoint CV 0.38
   M-YQ0201-27: R^2 >= 0.9 in 62 of 247
   M-YQ0201-29: R^2 >= 0.9 in 59 of 258
/tmp/ipykernel_2957/282043745.py:14: OptimizeWarning: Covariance of the parameters could not be estimated
  p, _ = curve_fit(logistic, x, y, p0=[0, y.max(), x[np.argmax(y > y.max() / 2)], 0.1], maxfev=20000)
V the mean of the 8 frames before: 505 cells, fits failed 0; R^2 >= 0.9 in 214 (42%); among those, midpoint 1.037 +/- 0.917 SH (CV 0.89), maximum 52.1 Hz median (CV 4.14)
   largest observed rate among the R^2 >= 0.9 cells: median 45.2 Hz, CV 0.46; fits with the top within twice the largest observed rate: 181 of 214, top CV 0.48, midpoint CV 0.31
   M-YQ0201-27: R^2 >= 0.9 in 108 of 247
   M-YQ0201-29: R^2 >= 0.9 in 106 of 258

Result: blocked, methods underspecified. The readings named in the criterion give different outcomes, and the claims file's header says that such a claim is blocked as methods_underspecified. With V at the spike frame (the code, and the Methods' V(t_s)) the logistic explains at least 90% of the variance for 262 of 505 cells (52%; 133 of 247 and 129 of 258), and their midpoints (CV 0.82) and maxima (CV about 4.5) vary across cells, which passes. The fitted maxima are partly unconstrained extrapolations, but the spread holds without them: the largest observed rate has CV 0.59, and the 221 fits whose top lies within twice that rate have top CV 0.64 and midpoint CV 0.29. With V the mean over the 10 ms before (the Results' and the legend's interval) 214 cells (42%) pass, and with the single sample 10 ms before 121 (24%); both fail. Which V enters P(spk|V) is asked of the paper's authors; that the claims file attributes the 10 ms to the Methods is asked of a reader.

fig4g-private-depolarizations¶

Voltages of neighbouring cells (under 200 um) are most correlated near rest and during hyperpolarizing fluctuations, and much less as voltage approaches spike threshold.

As the code (panel G): pairs 60 to 200 um, both orderings, quiet frames without running and with the +/-5000 frame chunk guard, 100 bins from -2 to 2 SH, counts pooled over both mice; every fourth frame is used (the voltage is smoothed over 17 frames). Reproduced when the slope of the conditional mean of V_j on V_i over -0.5 to 0.2 SH is at least twice that over 0.5 to 1 SH.

In [13]:
def slopes(N):
    cnt = N.sum(1)
    cm = (N * vc[None, :]).sum(1) / np.maximum(cnt, 1)
    out = {}
    for nm, (a, b) in [("-0.5 to 0.2", (-0.5, 0.2)), ("0.5 to 1", (0.5, 1.0))]:
        ok = (vc >= a) & (vc <= b) & (cnt > 0)
        out[nm] = np.polyfit(vc[ok], cm[ok], 1, w=np.sqrt(cnt[ok]))[0]
    return out, cm, cnt


Ntot = sum(BEH[m]["joint"] for m in L.MICE)
for nm, N in [("pooled", Ntot)] + [(m, BEH[m]["joint"]) for m in L.MICE]:
    s_, cm, cnt = slopes(N)
    print(f"{nm}: slope of E[V_j | V_i] over V_i -0.5 to 0.2 SH {s_['-0.5 to 0.2']:.3f}, over 0.5 to 1 SH {s_['0.5 to 1']:.3f}, "
          f"ratio {s_['-0.5 to 0.2'] / s_['0.5 to 1']:.2f}; frames x pairs in 0.5 to 1 SH: {cnt[(vc >= 0.5) & (vc <= 1)].sum():.0f}")
print("pairs (ordered) per mouse:", {m: BEH[m]["joint_pairs"] for m in L.MICE})
s_, cm, cnt = slopes(Ntot)
print("conditional mean by V_i (pooled), V_i from -1 to 1.2 SH:", dict(zip(vc[(vc > -1) & (vc < 1.2)][::3].round(2), cm[(vc > -1) & (vc < 1.2)][::3].round(3))))
# the same slopes with unweighted fits
for nm, (a, b) in [("-0.5 to 0.2", (-0.5, 0.2)), ("0.5 to 1", (0.5, 1.0))]:
    ok = (vc >= a) & (vc <= b) & (cnt > 0)
    print(f"   unweighted slope over {nm}: {np.polyfit(vc[ok], cm[ok], 1)[0]:.3f}")
pooled: slope of E[V_j | V_i] over V_i -0.5 to 0.2 SH 0.612, over 0.5 to 1 SH 0.212, ratio 2.89; frames x pairs in 0.5 to 1 SH: 31761610
M-YQ0201-27: slope of E[V_j | V_i] over V_i -0.5 to 0.2 SH 0.616, over 0.5 to 1 SH 0.172, ratio 3.57; frames x pairs in 0.5 to 1 SH: 11173664
M-YQ0201-29: slope of E[V_j | V_i] over V_i -0.5 to 0.2 SH 0.609, over 0.5 to 1 SH 0.233, ratio 2.62; frames x pairs in 0.5 to 1 SH: 20587946
pairs (ordered) per mouse: {'M-YQ0201-27': 1346, 'M-YQ0201-29': 1758}
conditional mean by V_i (pooled), V_i from -1 to 1.2 SH: {np.float64(-0.98): np.float64(-0.682), np.float64(-0.86): np.float64(-0.606), np.float64(-0.74): np.float64(-0.518), np.float64(-0.62): np.float64(-0.424), np.float64(-0.5): np.float64(-0.329), np.float64(-0.38): np.float64(-0.238), np.float64(-0.26): np.float64(-0.153), np.float64(-0.14): np.float64(-0.076), np.float64(-0.02): np.float64(-0.005), np.float64(0.1): np.float64(0.058), np.float64(0.22): np.float64(0.113), np.float64(0.34): np.float64(0.159), np.float64(0.46): np.float64(0.196), np.float64(0.58): np.float64(0.227), np.float64(0.7): np.float64(0.254), np.float64(0.82): np.float64(0.278), np.float64(0.94): np.float64(0.298), np.float64(1.06): np.float64(0.312), np.float64(1.18): np.float64(0.327)}
   unweighted slope over -0.5 to 0.2: 0.626
   unweighted slope over 0.5 to 1: 0.202

Result: reproduced. Pooled over both mice (3,104 ordered pairs 60 to 200 um), the conditional mean of the neighbour's voltage rises with slope 0.61 over V_i from -0.5 to 0.2 SH and 0.21 over 0.5 to 1 SH, a ratio of 2.89 (3.57 and 2.62 per mouse; unweighted fits 0.63 and 0.20).

fig4hi-self-sta-diverges¶

For cells under 200 um apart, self- and cross-STAs of membrane voltage track each other at lags beyond 30 ms, but the spiking cell has a higher baseline and an upward divergence in the 30 ms before its spike.

Stored quiet spike-triggered voltage; self-STA on the diagonal (the trigger cell's own entry, as the code's panel H uses it); pairs 60 to 200 um, per mouse. Per pair, self minus cross; -5 ms is lag -4 frames, -30 ms lag -24 frames, the reference spread over lags -110 to -24 frames.

In [14]:
lag_f = np.arange(-140, 141)
for m in L.MICE:
    X = ST4[m]["staV_quiet"]  # trigger x target x lag
    Dp = ST4[m]["D_pix"] * L.PIXEL_UM
    ii, jj = np.nonzero((Dp > 60) & (Dp < 200))
    selfsta = X[ii, ii]
    cross = X[ii, jj]
    diff = (selfsta - cross).mean(0)
    i5, i30 = 140 - 4, 140 - 24
    ref = diff[140 - 110:i30 + 1]
    print(f"{m}: {len(ii)} pairs; self minus cross at -5 ms {diff[i5]:.4f}, at -30 ms {diff[i30]:.4f}, "
          f"increase {diff[i5] - diff[i30]:.4f} against s.d. over -140 to -30 ms {ref.std(ddof=1):.4f}; "
          f"mean self {selfsta.mean(0)[i30]:.4f} vs cross {cross.mean(0)[i30]:.4f} at -30 ms; "
          f"difference at -100 ms {diff[140 - 79]:.4f}")
M-YQ0201-27: 1346 pairs; self minus cross at -5 ms 0.3128, at -30 ms 0.1370, increase 0.1758 against s.d. over -140 to -30 ms 0.0149; mean self 0.1018 vs cross -0.0353 at -30 ms; difference at -100 ms 0.0836
M-YQ0201-29: 1758 pairs; self minus cross at -5 ms 0.2967, at -30 ms 0.1146, increase 0.1821 against s.d. over -140 to -30 ms 0.0073; mean self 0.0472 vs cross -0.0673 at -30 ms; difference at -100 ms 0.0866

Result: reproduced. In both mice the self-STA exceeds the mean cross-STA (pairs 60 to 200 um) at -30 ms (0.102 against -0.035 and 0.047 against -0.067 SH), and the difference grows from -30 to -5 ms by 0.176 and 0.182 SH, against a spread of 0.015 and 0.007 over -140 to -30 ms. The self-STA is also higher at -100 ms (difference 0.084 and 0.087), the "higher baseline".

Figure 6: NPY-positive and NPY-negative subtypes¶

npy-fraction-and-similarity¶

About 49% of recorded neurons are NPY-positive (166 of 320 and 145 of 320); the two subtypes are intermixed and have similar spike SNR and mean spike rate.

gfp_positive over all 320 cells; the file does not say which session the paper counted, and the flags differ between the sessions of a mouse (the data check), so every session is shown. SNR and rate of the behavior-session QC cells (Supplementary Fig. 24B, D: 257 NPY- and 248 NPY+); similar when the two-sided rank-sum p >= 0.05 or the medians differ by less than 10%. Intermixed: two-sided Kolmogorov-Smirnov tests of x and y between subtypes with p >= 0.05 in each mouse.

In [15]:
for m in L.MICE:
    print(m, "NPY+ of 320:", {s: int(U[m, s]["gfp_positive"].sum()) for s in L.SESSIONS})
snr_c, rate_c, g_c = [], [], []
for m in L.MICE:
    R = BEH[m]
    noise = np.nanmedian(R["snr_noise"], 0)[R["cells"]]
    snr_c.append(1 / noise); rate_c.append(R["spike_counts"] / R["duration_s"]); g_c.append(R["gfp"])
snr_c, rate_c, g_c = map(np.concatenate, (snr_c, rate_c, g_c))
print(f"behavior QC cells: NPY- {np.sum(~g_c)}, NPY+ {np.sum(g_c)}")
for nm, v in [("spike SNR", snr_c), ("mean spike rate (Hz)", rate_c)]:
    a, b = v[~g_c], v[g_c]
    p = stats.ranksums(a, b).pvalue
    dm = abs(np.median(b) - np.median(a)) / np.median(a)
    print(f"{nm}: median NPY- {np.median(a):.3f}, NPY+ {np.median(b):.3f} (difference {100*dm:.1f}%), rank-sum p = {p:.3g} -> "
          f"{'similar' if (p >= 0.05 or dm < 0.1) else 'different'}")
for m in L.MICE:
    for s in L.SESSIONS:
        u = U[m, s]
        g = u["gfp_positive"]
        px = stats.ks_2samp(u["x_um"][g], u["x_um"][~g]).pvalue
        py = stats.ks_2samp(u["y_um"][g], u["y_um"][~g]).pvalue
        print(f"{m} {s}: KS p for x {px:.3f}, y {py:.3f}")
M-YQ0201-27 NPY+ of 320: {'behavior': 156, 'sparseOpto': 171, 'sparsePulseHad': 171}
M-YQ0201-29 NPY+ of 320: {'behavior': 135, 'sparseOpto': 144, 'sparsePulseHad': 157}
behavior QC cells: NPY- 257, NPY+ 248
spike SNR: median NPY- 3.130, NPY+ 3.302 (difference 5.5%), rank-sum p = 0.011 -> similar
mean spike rate (Hz): median NPY- 0.709, NPY+ 0.707 (difference 0.3%), rank-sum p = 0.799 -> similar
M-YQ0201-27 behavior: KS p for x 0.745, y 0.168
M-YQ0201-27 sparseOpto: KS p for x 0.623, y 0.800
M-YQ0201-27 sparsePulseHad: KS p for x 0.467, y 0.648
M-YQ0201-29 behavior: KS p for x 0.081, y 0.964
M-YQ0201-29 sparseOpto: KS p for x 0.231, y 0.149
M-YQ0201-29 sparsePulseHad: KS p for x 0.239, y 0.161

Result: reproduced. NPY+ cells number 156, 171 and 171 of 320 in the three sessions of M-YQ0201-27 and 135, 144 and 157 in M-YQ0201-29, all within tolerance of 166 and 145 matched in that order. Over the 505 behavior QC cells (257 NPY-, 248 NPY+, the legend's counts) the SNR medians differ by 5.5% (p = 0.011) and the rate medians by 0.3% (p = 0.80), both similar under the chosen rule; the Kolmogorov-Smirnov p values for x and y are 0.08 to 0.96 in every session.

npy-subthreshold-similar¶

Population-average subthreshold voltages of NPY-positive and NPY-negative cells are almost indistinguishable (R = 0.97, slope 0.96).

Mean subthreshold voltage over the NPY+ and over the NPY- QC cells of the M-YQ0201-29 behavior session (117 and 141 cells), frame by frame; frames (a) the first 2000 s, (b) non-running frames; slope (a) NPY+ on NPY-, (b) the reverse.

In [16]:
for m in L.MICE:
    R = BEH[m]
    pos, neg = R["pop_npy_pos"], R["pop_npy_neg"]
    print(f"{m}: NPY+ {R['gfp'].sum()} and NPY- {(~R['gfp']).sum()} QC cells")
    for nm, mk in [("(a) first 2000 s", np.arange(R["n_frames"]) < int(round(2000 / L.DT))), ("(b) non-running", ~R["run_guard"])]:
        r = np.corrcoef(pos[mk], neg[mk])[0, 1]
        s1 = np.polyfit(neg[mk], pos[mk], 1)[0]
        s2 = np.polyfit(pos[mk], neg[mk], 1)[0]
        print(f"   {nm}: R = {r:.3f}, slope NPY+ on NPY- {s1:.3f}, NPY- on NPY+ {s2:.3f}")
M-YQ0201-27: NPY+ 131 and NPY- 116 QC cells
   (a) first 2000 s: R = 0.979, slope NPY+ on NPY- 0.996, NPY- on NPY+ 0.963
   (b) non-running: R = 0.983, slope NPY+ on NPY- 0.987, NPY- on NPY+ 0.979
M-YQ0201-29: NPY+ 117 and NPY- 141 QC cells
   (a) first 2000 s: R = 0.973, slope NPY+ on NPY- 0.933, NPY- on NPY+ 1.015
   (b) non-running: R = 0.979, slope NPY+ on NPY- 0.920, NPY- on NPY+ 1.041

Result: reproduced. In M-YQ0201-29 over the first 2000 s the NPY+ and NPY- averages correlate with R = 0.973 and the slope of NPY+ on NPY- is 0.933 (the reverse 1.015), within 0.03 and 0.096 of 0.97 and 0.96. Non-running frames give R = 0.979, slope 0.920; M-YQ0201-27 gives R = 0.98.

npy-umap-groups¶

Clustering spontaneous firing patterns alone gives two groups that co-assort with NPY status; 157 of 203 group 1 cells are NPY-negative and 202 of 302 group 2 cells are NPY-positive.

As the code (umapGrouping): 500 ms bins of the spike trains with frames where more than 15 cells spike zeroed; bins more than 80% inside the first 2000 s and outside +/-5000 frames of a chunk boundary; z-scored per cell; projected by the SVD (u*s, all components) as the UMAP input; UMAP with 20 neighbours and 2 components (umap-learn in place of MATLAB's UMAP); k-means with k = 2; groups labelled by matching the group-mean binned rate to the subtype means; each behavior session separately, counts pooled. UMAP and k-means are unseeded in the code; 10 seeds here.

In [17]:
import umap
from sklearn.cluster import KMeans
counts = []
for seed in range(10):
    tot = np.zeros((2, 2), int)  # rows group 1, 2; columns NPY-, NPY+
    for m in L.MICE:
        R = BEH[m]
        Xb = R["umap_counts"][R["umap_binmask"]].T  # cells x bins
        Zb = (Xb - Xb.mean(1, keepdims=True)) / Xb.std(1, ddof=1, keepdims=True)
        Zb = np.nan_to_num(Zb)
        uu, ss, _ = np.linalg.svd(Zb, full_matrices=False)
        emb = umap.UMAP(n_neighbors=20, n_components=2, random_state=seed).fit_transform(uu * ss)
        grp = KMeans(2, n_init=1, random_state=seed).fit_predict(emb) + 1
        rates = R["umap_counts"].T
        gm = np.vstack([rates[grp == 1].mean(0), rates[grp == 2].mean(0)])
        tm = np.vstack([rates[~R["gfp"]].mean(0), rates[R["gfp"]].mean(0)])
        cc = np.corrcoef(np.vstack([gm, tm]))[:2, 2:]
        if cc[0, 1] + cc[1, 0] > cc[0, 0] + cc[1, 1]:
            grp = 3 - grp
        for gi in (1, 2):
            tot[gi - 1, 0] += np.sum((grp == gi) & ~R["gfp"])
            tot[gi - 1, 1] += np.sum((grp == gi) & R["gfp"])
    counts.append(dict(seed=seed, g1_neg=tot[0, 0], g1=tot[0].sum(), g2_pos=tot[1, 1], g2=tot[1].sum(),
                       fisher_p=stats.fisher_exact(tot)[1]))
cdf = pd.DataFrame(counts)
print(cdf.to_string())
print("median over seeds:", cdf[["g1_neg", "g1", "g2_pos", "g2", "fisher_p"]].median().round(4).to_dict(),
      "(expected 157, 203, 202, 302)")
/home/runner/work/_temp/executed/.venv/lib/python3.13/site-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html
  from .autonotebook import tqdm as notebook_tqdm
/home/runner/work/_temp/executed/.venv/lib/python3.13/site-packages/umap/umap_.py:1952: UserWarning: n_jobs value 1 overridden to 1 by setting random_state. Use no seed for parallelism.
  warn(
/home/runner/work/_temp/executed/.venv/lib/python3.13/site-packages/umap/umap_.py:1952: UserWarning: n_jobs value 1 overridden to 1 by setting random_state. Use no seed for parallelism.
  warn(
/home/runner/work/_temp/executed/.venv/lib/python3.13/site-packages/umap/umap_.py:1952: UserWarning: n_jobs value 1 overridden to 1 by setting random_state. Use no seed for parallelism.
  warn(
/home/runner/work/_temp/executed/.venv/lib/python3.13/site-packages/umap/umap_.py:1952: UserWarning: n_jobs value 1 overridden to 1 by setting random_state. Use no seed for parallelism.
  warn(
/home/runner/work/_temp/executed/.venv/lib/python3.13/site-packages/umap/umap_.py:1952: UserWarning: n_jobs value 1 overridden to 1 by setting random_state. Use no seed for parallelism.
  warn(
/home/runner/work/_temp/executed/.venv/lib/python3.13/site-packages/umap/umap_.py:1952: UserWarning: n_jobs value 1 overridden to 1 by setting random_state. Use no seed for parallelism.
  warn(
/home/runner/work/_temp/executed/.venv/lib/python3.13/site-packages/umap/umap_.py:1952: UserWarning: n_jobs value 1 overridden to 1 by setting random_state. Use no seed for parallelism.
  warn(
/home/runner/work/_temp/executed/.venv/lib/python3.13/site-packages/umap/umap_.py:1952: UserWarning: n_jobs value 1 overridden to 1 by setting random_state. Use no seed for parallelism.
  warn(
/home/runner/work/_temp/executed/.venv/lib/python3.13/site-packages/umap/umap_.py:1952: UserWarning: n_jobs value 1 overridden to 1 by setting random_state. Use no seed for parallelism.
  warn(
/home/runner/work/_temp/executed/.venv/lib/python3.13/site-packages/umap/umap_.py:1952: UserWarning: n_jobs value 1 overridden to 1 by setting random_state. Use no seed for parallelism.
  warn(
/home/runner/work/_temp/executed/.venv/lib/python3.13/site-packages/umap/umap_.py:1952: UserWarning: n_jobs value 1 overridden to 1 by setting random_state. Use no seed for parallelism.
  warn(
/home/runner/work/_temp/executed/.venv/lib/python3.13/site-packages/umap/umap_.py:1952: UserWarning: n_jobs value 1 overridden to 1 by setting random_state. Use no seed for parallelism.
  warn(
/home/runner/work/_temp/executed/.venv/lib/python3.13/site-packages/umap/umap_.py:1952: UserWarning: n_jobs value 1 overridden to 1 by setting random_state. Use no seed for parallelism.
  warn(
/home/runner/work/_temp/executed/.venv/lib/python3.13/site-packages/umap/umap_.py:1952: UserWarning: n_jobs value 1 overridden to 1 by setting random_state. Use no seed for parallelism.
  warn(
/home/runner/work/_temp/executed/.venv/lib/python3.13/site-packages/umap/umap_.py:1952: UserWarning: n_jobs value 1 overridden to 1 by setting random_state. Use no seed for parallelism.
  warn(
/home/runner/work/_temp/executed/.venv/lib/python3.13/site-packages/umap/umap_.py:1952: UserWarning: n_jobs value 1 overridden to 1 by setting random_state. Use no seed for parallelism.
  warn(
/home/runner/work/_temp/executed/.venv/lib/python3.13/site-packages/umap/umap_.py:1952: UserWarning: n_jobs value 1 overridden to 1 by setting random_state. Use no seed for parallelism.
  warn(
/home/runner/work/_temp/executed/.venv/lib/python3.13/site-packages/umap/umap_.py:1952: UserWarning: n_jobs value 1 overridden to 1 by setting random_state. Use no seed for parallelism.
  warn(
/home/runner/work/_temp/executed/.venv/lib/python3.13/site-packages/umap/umap_.py:1952: UserWarning: n_jobs value 1 overridden to 1 by setting random_state. Use no seed for parallelism.
  warn(
/home/runner/work/_temp/executed/.venv/lib/python3.13/site-packages/umap/umap_.py:1952: UserWarning: n_jobs value 1 overridden to 1 by setting random_state. Use no seed for parallelism.
  warn(
   seed  g1_neg   g1  g2_pos   g2      fisher_p
0     0     158  205     201  300  5.441525e-23
1     1     155  200     203  305  8.431310e-23
2     2     159  206     201  299  2.293894e-23
3     3     157  204     201  301  1.280588e-22
4     4     159  207     200  298  6.625607e-23
5     5     159  206     201  299  2.293894e-23
6     6     158  204     202  301  1.867390e-23
7     7     159  206     201  299  2.293894e-23
8     8     158  204     202  301  1.867390e-23
9     9     159  205     202  300  7.806260e-24
median over seeds: {'g1_neg': 158.5, 'g1': 205.0, 'g2_pos': 201.0, 'g2': 300.0, 'fisher_p': 0.0} (expected 157, 203, 202, 302)

Result: reproduced. Over 10 seeds the median counts are 158.5 NPY- of 205 group 1 cells and 201 NPY+ of 300 group 2 cells (expected 157 of 203 and 202 of 302); every seed gives counts within tolerance, and Fisher's exact test gives p below 1e-21.

npy-whisking-onset-rates¶

At whisking onset NPY-positive cells raise their spike rate from 1.4 +/- 1.7 Hz to 2.8 +/- 4.3 Hz, while NPY-negative cells show no significant change (1.8 +/- 2.1 Hz to 2.0 +/- 2.6 Hz).

Onsets as the code (l1opto.whisking_onsets); per cell, mean rate in the 640 ms before and after each onset, averaged over onsets (Supplementary Fig. 26B); both behavior sessions, QC cells. Two-sided rank-sum before against after per subtype (the paper's test), and the signed-rank test as a variant.

In [18]:
bef = np.concatenate([BEH[m]["rate_before"] for m in L.MICE]); aft = np.concatenate([BEH[m]["rate_after"] for m in L.MICE])
gg = np.concatenate([BEH[m]["gfp"] for m in L.MICE])
print("onsets used per mouse:", {m: BEH[m]["n_onsets_used"] for m in L.MICE})
for nm, sel in [("NPY+", gg), ("NPY-", ~gg)]:
    a, b = bef[sel], aft[sel]
    print(f"{nm} (n = {sel.sum()}): before {a.mean():.2f} +/- {a.std(ddof=1):.2f} Hz, after {b.mean():.2f} +/- {b.std(ddof=1):.2f} Hz; "
          f"rank-sum p = {stats.ranksums(a, b).pvalue:.3g}; signed-rank p = {stats.wilcoxon(a, b).pvalue:.3g}")
    for m in L.MICE:
        g_ = BEH[m]["gfp"] if nm == "NPY+" else ~BEH[m]["gfp"]
        print(f"   {m}: before {BEH[m]['rate_before'][g_].mean():.2f}, after {BEH[m]['rate_after'][g_].mean():.2f} Hz")
onsets used per mouse: {'M-YQ0201-27': 687, 'M-YQ0201-29': 551}
NPY+ (n = 248): before 1.06 +/- 1.26 Hz, after 2.20 +/- 3.36 Hz; rank-sum p = 5.88e-08; signed-rank p = 5.84e-30
   M-YQ0201-27: before 0.89, after 1.76 Hz
   M-YQ0201-29: before 1.25, after 2.69 Hz
NPY- (n = 257): before 1.27 +/- 1.47 Hz, after 1.50 +/- 1.94 Hz; rank-sum p = 0.758; signed-rank p = 0.35
   M-YQ0201-27: before 1.26, after 1.73 Hz
   M-YQ0201-29: before 1.29, after 1.32 Hz

Result: reproduced. Around 1,238 onsets, NPY+ cells (n = 248) rise from 1.06 +/- 1.26 to 2.20 +/- 3.36 Hz (rank-sum p = 5.9e-8) and NPY- cells (n = 257) from 1.27 +/- 1.47 to 1.50 +/- 1.94 Hz (p = 0.76, no change), all four rates within tolerance.

npy-oscillation-peak-rates¶

At the peaks of quiet-state subthreshold oscillations, NPY-negative cells spike at a higher rate than NPY-positive cells, while their mean subthreshold voltages do not differ.

Peaks of the QC-cell population-average subthreshold voltage band-passed 1.5 to 10 Hz (4th-order Butterworth, filtfilt), above zero, in quiet frames and before frame 1.3e6 (code, Figure 6I); per cell, the peak-triggered average voltage and rate; a cell's value is (a) the mean over +/-300 frames, (b) the value at the peak frame. Both behavior sessions; two-sided rank-sum NPY- against NPY+.

In [19]:
print("peaks per mouse:", {m: len(BEH[m]["osc_peaks"]) for m in L.MICE}, "(code README: 5888 for M-YQ0201-29)")
for nm, fn in [("(a) mean over +/-300 frames", lambda X: X.mean(0)), ("(b) at the peak", lambda X: X[300])]:
    v = np.concatenate([fn(BEH[m]["osc_V"]) for m in L.MICE]); r = np.concatenate([fn(BEH[m]["osc_rate"]) for m in L.MICE])
    pr = stats.ranksums(r[~gg], r[gg]).pvalue; pv = stats.ranksums(v[~gg], v[gg]).pvalue
    print(f"{nm}: rate NPY- median {np.median(r[~gg]):.2f}, NPY+ {np.median(r[gg]):.2f} Hz, p = {pr:.3g}; "
          f"voltage NPY- median {np.median(v[~gg]):.4f}, NPY+ {np.median(v[gg]):.4f}, p = {pv:.3g}")
peaks per mouse: {'M-YQ0201-27': 4279, 'M-YQ0201-29': 5886} (code README: 5888 for M-YQ0201-29)
(a) mean over +/-300 frames: rate NPY- median 0.87, NPY+ 0.60 Hz, p = 0.000147; voltage NPY- median -0.0379, NPY+ -0.0448, p = 0.0223
(b) at the peak: rate NPY- median 1.10, NPY+ 0.74 Hz, p = 7.48e-06; voltage NPY- median 0.0701, NPY+ 0.0581, p = 0.219

Result: blocked (methods underspecified). The criterion's two readings give different outcomes, and the claims file blocks such a claim. At the peak frame (reading (b)) NPY- cells fire at a median 1.10 Hz and NPY+ cells at 0.74 Hz (p = 7.5e-6), while the voltages do not differ (p = 0.22), as the claim says. Over +/-300 frames (reading (a)) the rate difference holds (p = 1.5e-4) but the voltages differ at p = 0.022.

npy-state-dependent-excitability¶

Whisking decreases the excitability of NPY-negative cells and increases that of NPY-positive cells; in the quiet state NPY-negative cells spike faster at a given voltage, in the whisking state NPY-positive cells do.

Per QC cell, P(spk|V) for V in [0.4, 0.6) SH (Supplementary Fig. 26C): spikes over frames in that voltage range, over 1.27 ms, in quiet frames and in the 0 to 500 frames (635 ms) after a whisking onset without running, both within the first 2000 s and outside +/-140 frames of a chunk boundary (code, Figure 6K). Two-sided rank-sum tests; cells with no frame in the range are left out of that comparison.

In [20]:
def pv46(st):
    num = np.concatenate([BEH[m][f"pv46_{st}"][0] for m in L.MICE]); den = np.concatenate([BEH[m][f"pv46_{st}"][1] for m in L.MICE])
    with np.errstate(invalid="ignore", divide="ignore"):
        return num / den / L.DT, den


rq, dq = pv46("quiet"); rw, dw = pv46("whisk")
print("frames per state:", {m: BEH[m]["k_frames"] for m in L.MICE})
print(f"cells with frames in range: quiet {np.sum(dq > 0)}, whisking {np.sum(dw > 0)} of {len(dq)}")
tests = [("NPY- quiet above whisking", rq[~gg], rw[~gg], "greater"), ("NPY+ whisking above quiet", rw[gg], rq[gg], "greater"),
         ("NPY- above NPY+ in quiet", rq[~gg], rq[gg], "greater"), ("NPY+ above NPY- in whisking", rw[gg], rw[~gg], "greater")]
for nm, a, b, _ in tests:
    a, b = a[np.isfinite(a)], b[np.isfinite(b)]
    p = stats.ranksums(a, b).pvalue
    print(f"{nm}: medians {np.median(a):.2f} vs {np.median(b):.2f} Hz, means {a.mean():.2f} vs {b.mean():.2f}; two-sided p = {p:.3g}; "
          f"holds: {np.median(a) > np.median(b) and p <= 0.05}")
frames per state: {'M-YQ0201-27': {'quiet': 693113, 'whisk': 182722}, 'M-YQ0201-29': {'quiet': 882863, 'whisk': 128305}}
cells with frames in range: quiet 505, whisking 505 of 505
NPY- quiet above whisking: medians 3.75 vs 2.28 Hz, means 7.44 vs 5.96; two-sided p = 0.0182; holds: True
NPY+ whisking above quiet: medians 3.51 vs 2.37 Hz, means 7.53 vs 5.15; two-sided p = 0.0102; holds: True
NPY- above NPY+ in quiet: medians 3.75 vs 2.37 Hz, means 7.44 vs 5.15; two-sided p = 0.0321; holds: True
NPY+ above NPY- in whisking: medians 3.51 vs 2.28 Hz, means 7.53 vs 5.96; two-sided p = 0.00642; holds: True

Result: reproduced. For V in [0.4, 0.6) SH, NPY- cells fire faster in quiet than after whisking onset (medians 3.75 against 2.28 Hz, p = 0.018), NPY+ cells faster after onset (3.51 against 2.37 Hz, p = 0.010); NPY- above NPY+ in quiet (p = 0.032) and NPY+ above NPY- after onset (p = 0.0064): all four comparisons hold at p <= 0.05.

Summary¶

Claim Outcome
spike-snr-and-detection-errors not reproduced
snr-decay-one-hour reproduced
subthreshold-correlation-length reproduced
subthreshold-low-dimensional reproduced
quiet-state-oscillations reproduced
traveling-waves not reproduced (assumptions)
spike-synchrony-localized partially reproduced
voltage-to-spike-sigmoid blocked: methods underspecified
fig4g-private-depolarizations reproduced
fig4hi-self-sta-diverges reproduced
npy-fraction-and-similarity reproduced
npy-subthreshold-similar reproduced
npy-umap-groups reproduced
npy-whisking-onset-rates reproduced
npy-oscillation-peak-rates blocked: methods underspecified
npy-state-dependent-excitability reproduced

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.

How the analysis differs from the paper's. The SNR is computed from the stored normalized voltage, not from the raw fluorescence and the matched filter; the detection error rates are not computed. The wave analysis has no code; its open details are run as readings. UMAP is umap-learn, not the MATLAB package. The neighbour-voltage joint distribution uses every fourth analysis frame. Whisking onsets are placed on the voltage clock by timestamp lookup, not the code's bilinear resize (551 onsets in M-YQ0201-29, against the code's 547).

What was found about the dataset. The stored quiet mask is a fresh fit (the code says so), and the masks, correlation arrays and voltages agree with the code's published numbers wherever those can be compared (the Figure 4 length constants, the 5,886 oscillation peaks against the code's 5,888, the chosen whisking reconstructions 14 and 9). The x and y axes of the cell positions are not oriented on the brain in the files, so directions can be given only in the image frame.

In [21]:
print(f"notebook run time {(time.time() - T0) / 60:.1f} min")
notebook run time 20.1 min