Reproducing Qi et al. (2026) from dandiset 001960¶
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 claims/001960/10.64898-2026.10.05.756595.yaml
was written from the full text of that preprint (main text, figure legends, Methods) and its
supplementary information PDF, and checked by a second reader.
Dataset. DANDI:001960, version 0.261013.2016 (doi:10.48324/dandi.001960/0.261013.2016), streamed from the archive. The paper's Data availability statement names the dandiset without a version, and this is the only published version (the draft has the same 7 assets and the same size, 505,494,176,572 bytes), so the most recent published version is pinned, as the protocol asks when no version is cited.
Code read for methods. The paper's code, https://github.com/adamcohenlab/Qi2026WideAreaL1 at
commit 181ad475520224c44d27903e7522d3e2aa76857d, which the claims file cites for many criteria.
Every method detail is cited in the helper l1opto.py or in the cell that uses it.
The attempt has three notebooks, so that each runs well inside the time limit: this one (data
check, intrinsic properties, connectivity, the effect of connections on spontaneous activity, and
the NPY subtype differences in excitability and connectivity), qi2026_spontaneous.ipynb (the
spontaneous sessions: SNR, Figure 4 and the Figure 6 behaviour claims) and
qi2026_excitability_spontaneous.ipynb (Figure 5A to C and Supplementary Figure 22).
| Claims | Notebook | Tested |
|---|---|---|
| adaptation-vadp-correlation, fig2c-three-bins, fig2gk-bin-profiles, two-mice-intrinsic-distributions | this one | tested |
| synaptic-connection-counts, ipsp-median-amplitude, gap-junction-connection-counts, hadamard-stimulation-rates, connection-distance-structure, fig3eg-amplitude-falls-with-distance, fig3h-conduction-speed, amplitudes-log-normal, interaction-kernel, fig3jk-presynaptic-sets-amplitude, fig3mn-postsynaptic-sets-decay, fig3lo-variance-components, gap-junction-no-identity-effect | this one | tested |
| fig5e-inhibition-in-spontaneous-voltage, fig5e-inhibition-in-spontaneous-rate, fig5g-gap-junction-synchrony | this one | tested |
| inhibition-gap-balance | this one | blocked, methods underspecified (all readings shown) |
| npy-intrinsic-differences, npy-classifier, npy-connection-probability, npy-ipsp-amplitude, npy-ipsp-duration, npy-gap-junction-no-difference | this one | tested |
| jf608-brighter, targeting-signal-to-background, fig1d-stimulation-fold-change, off-target-length-constants, l1-sampling-density, highmag-footprint | none | blocked, data missing |
| spikelet-not-scatter, lasso-off-target-correction | this one | tested (the scatter on a subset of the raw movie) |
| detection-limits | this one | blocked, too large (the per-pair nulls are not stored) |
| spike-snr-and-detection-errors, snr-decay-one-hour, subthreshold-correlation-length, subthreshold-low-dimensional, quiet-state-oscillations, spike-synchrony-localized, voltage-to-spike-sigmoid, fig4g-private-depolarizations, fig4hi-self-sta-diverges, npy-fraction-and-similarity, npy-subthreshold-similar, npy-umap-groups, npy-whisking-onset-rates, npy-state-dependent-excitability, traveling-waves | qi2026_spontaneous | tested |
| npy-oscillation-peak-rates | qi2026_spontaneous | blocked, methods underspecified (both readings shown) |
| fig5a-rheobase-predicts-spontaneous-excitability, supp22-rheobase-correlations, fig5b-adaptation-dvdt, fig5c-adp-bursting | qi2026_excitability_spontaneous | tested |
Of the 56 claims, 47 are tested and 9 blocked.
import os
os.environ.setdefault("OMP_NUM_THREADS", "4")
import time
import numpy as np
import pandas as pd
from scipy import stats
import matplotlib.pyplot as plt
import l1opto as L
T0 = time.time()
pd.set_option("display.width", 160)
print("dandiset", L.DANDISET, "version", L.VERSION)
assets = L.assets()
for p, a in sorted(assets.items()):
print(p, a)
dandiset 001960 version 0.261013.2016 sub-M-YQ0201-27/sub-M-YQ0201-27_ses-behavior_behavior+ophys.nwb f5d362e5-0f27-42af-8166-37835d4d62f6 sub-M-YQ0201-27/sub-M-YQ0201-27_ses-sparseOpto_behavior+ophys.nwb 95b0523b-3981-464d-8cc5-8d0789a12073 sub-M-YQ0201-27/sub-M-YQ0201-27_ses-sparsePulseHad_behavior+ophys.nwb 9ef53fc8-42a0-496b-ad43-15bebd9870b4 sub-M-YQ0201-29/sub-M-YQ0201-29_ses-behavior-rawexcerpt_behavior+ophys.nwb 20f36138-2e20-4823-b80d-418bad0c65c4 sub-M-YQ0201-29/sub-M-YQ0201-29_ses-behavior_behavior+ophys.nwb 175ad19c-e469-452d-a8dc-3c57c9f0c88f sub-M-YQ0201-29/sub-M-YQ0201-29_ses-sparseOpto_behavior+ophys.nwb 7a91354a-0ae7-4f97-b9b3-26000820a583 sub-M-YQ0201-29/sub-M-YQ0201-29_ses-sparsePulseHad_behavior+ophys.nwb d27cf030-acbe-476b-9026-6a8ef4cb0243
Data check¶
Every session file holds a units table of 320 cells (all detected cells, with a passed_qc
flag), the spike-height-normalized voltage, and stimulus and behaviour series. The checks below
print counts per mouse and session, the ranges and units of the variables used, the sampling
interval, the orientation of the pairwise arrays, whether unit ids refer to the same cells across
sessions, and the shared clock of stimulus and response.
rows = []
U = {}
for m in L.MICE:
for s in L.SESSIONS:
u = L.units(m, s)
U[m, s] = u
f = L.open_file(m, s)
ts = f["processing/optical_voltage/normalized_voltage/timestamps"]
tt = f["intervals/trials/trial_type"][:]
rows.append(dict(mouse=m, session=s, cells=len(u["id"]), qc=int(u["passed_qc"].sum()),
gfp=int(u["gfp_positive"].sum()), gfp_qc=int((u["gfp_positive"] & u["passed_qc"]).sum()),
frames=ts.shape[0], trials=len(tt), trial_types=", ".join(sorted(set(t.decode() for t in tt))),
spikes=sum(len(x) for x in u["spike_times"]),
genotype=f["general/subject/genotype"][()].decode(), sex=f["general/subject/sex"][()].decode()))
sanity = pd.DataFrame(rows)
print(sanity.to_string())
print("\nQC cells: sparsePulseHad", sanity.query("session=='sparsePulseHad'").qc.sum(),
"(paper n = 576); behavior", sanity.query("session=='behavior'").qc.sum(),
"(paper n = 505); sparseOpto", sanity.query("session=='sparseOpto'").qc.sum(), "(Supplementary Fig. 22 n = 543)")
mouse session cells qc gfp gfp_qc frames trials trial_types spikes genotype sex 0 M-YQ0201-27 behavior 320 247 156 131 2880000 10 spontaneous_activity 1096474 NDNF-cre::NPY-GFP F 1 M-YQ0201-27 sparseOpto 320 286 171 158 2400000 300 intrinsic_excitability_mapping 1823290 NDNF-cre::NPY-GFP F 2 M-YQ0201-27 sparsePulseHad 320 290 171 161 3174400 640 hadamard_gap_junction_mapping, sparse_pulse_synaptic_mapping 6345535 NDNF-cre::NPY-GFP F 3 M-YQ0201-29 behavior 320 258 135 117 2880000 10 spontaneous_activity 1314377 NDNF-cre::NPY-GFP M 4 M-YQ0201-29 sparseOpto 320 257 144 132 2400000 300 intrinsic_excitability_mapping 1680038 NDNF-cre::NPY-GFP M 5 M-YQ0201-29 sparsePulseHad 320 286 157 146 3174400 640 hadamard_gap_junction_mapping, sparse_pulse_synaptic_mapping 5194332 NDNF-cre::NPY-GFP M QC cells: sparsePulseHad 576 (paper n = 576); behavior 505 (paper n = 505); sparseOpto 543 (Supplementary Fig. 22 n = 543)
# Sampling interval, from the stored timestamps of every session
for m in L.MICE:
for s in L.SESSIONS:
ts = L.series_timestamps(m, s)
d = np.diff(ts)
print(f"{m} {s}: median frame interval {np.median(d)*1e3:.4f} ms, {np.sum(d > 2*L.DT)} gaps over 2 frames, "
f"duration {ts[-1]-ts[0]:.1f} s")
M-YQ0201-27 behavior: median frame interval 1.2700 ms, 0 gaps over 2 frames, duration 3657.6 s
M-YQ0201-27 sparseOpto: median frame interval 1.2700 ms, 0 gaps over 2 frames, duration 3047.6 s
M-YQ0201-27 sparsePulseHad: median frame interval 1.2700 ms, 639 gaps over 2 frames, duration 4193.0 s
M-YQ0201-29 behavior: median frame interval 1.2700 ms, 0 gaps over 2 frames, duration 3657.6 s
M-YQ0201-29 sparseOpto: median frame interval 1.2700 ms, 0 gaps over 2 frames, duration 3047.6 s
M-YQ0201-29 sparsePulseHad: median frame interval 1.2700 ms, 639 gaps over 2 frames, duration 4193.0 s
# Intrinsic properties (sparseOpto units table): ranges and units
for m in L.MICE:
P = L.intrinsic_properties(m)
print(m, "finite rows", np.isfinite(P).all(1).sum(), "of", len(P))
for j, p in enumerate(L.PROPERTIES):
print(f" {p:28s} min {np.nanmin(P[:, j]):9.4f} median {np.nanmedian(P[:, j]):9.4f} max {np.nanmax(P[:, j]):9.4f}"
f" zeros {np.sum(P[:, j] == 0)}")
M-YQ0201-27 finite rows 320 of 320 adp_blue_norm min 0.0089 median 0.1113 max 0.5213 zeros 0 optical_rheobase_norm min -0.1372 median 0.3463 max 1.1752 zeros 0 max_firing_rate_hz min 2.9687 median 30.8045 max 70.9211 zeros 0 pulse_adaptation min -1.0000 median 0.2740 max 2.5656 zeros 0 membrane_time_constant_ms min 0.0000 median 16.8114 max 38.5877 zeros 7 M-YQ0201-29 finite rows 320 of 320 adp_blue_norm min 0.0073 median 0.1135 max 0.5477 zeros 0 optical_rheobase_norm min -0.1322 median 0.2903 max 1.1937 zeros 0 max_firing_rate_hz min 1.7681 median 30.1759 max 59.7231 zeros 0 pulse_adaptation min -1.0000 median 0.2628 max 2.3675 zeros 0 membrane_time_constant_ms min 9.9865 median 16.0315 max 76.2000 zeros 0
# Pairwise metrics: table order, distances, and value ranges
PM = {}
for m in L.MICE:
M = L.pair_matrices(m)
PM[m] = M
u = U[m, "sparsePulseHad"]
k = np.arange(320 * 320)
print(m, "table rows run pre = k mod 320:", bool(np.all(M["table_pre"] == k % 320)),
"| distance_pixels x 6.5 equals the distance of x_um, y_um:",
bool(np.allclose(M["distance_um"], L.distance_matrix_um(u["x_um"], u["y_um"]))))
for c in L.PAIR_COLUMNS:
v = M[c].astype(float)
print(f" {c:45s} finite {np.isfinite(v).sum():6d} min {np.nanmin(v):8.4f} max {np.nanmax(v):8.4f}")
S, G = M["synaptic_connection"], M["gap_junction_connection"]
q = u["passed_qc"]
print(f" synaptic flags {S.sum()}, on the diagonal {np.trace(S)}, beyond 400 um {np.sum(S & (M['distance_um'] > 400))}, "
f"involving a non-QC cell {np.sum(S & ~(q[:, None] & q[None, :]))}; gap-junction flags {G.sum()}")
tau = M["ipsp_decay_source_units"]
print(f" ipsp_decay among synaptic pairs: median {np.median(tau[S]):.4f}, max {tau[S].max():.3f} "
f"(units not stored; values are consistent with seconds: tens of ms, capped at 0.4)")
M-YQ0201-27 table rows run pre = k mod 320: True | distance_pixels x 6.5 equals the distance of x_um, y_um: True synaptic_connection finite 102400 min 0.0000 max 1.0000 ipsp_amplitude_norm_per_presynaptic_spike finite 102398 min 0.0000 max 0.1742 ipsp_decay_source_units finite 102400 min 0.0000 max 0.4000 ipsp_decay_standard_error_source_units finite 955 min 0.0004 max 1.0018 distance_pixels finite 102400 min 0.0000 max 440.0928 gap_junction_connection finite 102400 min 0.0000 max 1.0000 spikelet_amplitude_normalized finite 102400 min -0.0831 max 0.3139 synaptic flags 955, on the diagonal 0, beyond 400 um 0, involving a non-QC cell 127; gap-junction flags 4516 ipsp_decay among synaptic pairs: median 0.0343, max 0.400 (units not stored; values are consistent with seconds: tens of ms, capped at 0.4)
M-YQ0201-29 table rows run pre = k mod 320: True | distance_pixels x 6.5 equals the distance of x_um, y_um: True synaptic_connection finite 102400 min 0.0000 max 1.0000 ipsp_amplitude_norm_per_presynaptic_spike finite 102400 min 0.0000 max 0.2901 ipsp_decay_source_units finite 102400 min 0.0000 max 0.4000 ipsp_decay_standard_error_source_units finite 800 min 0.0005 max 1.4896 distance_pixels finite 102400 min 0.0000 max 446.2638 gap_junction_connection finite 102400 min 0.0000 max 1.0000 spikelet_amplitude_normalized finite 102400 min -0.0969 max 0.3291 synaptic flags 800, on the diagonal 0, beyond 400 um 0, involving a non-QC cell 121; gap-junction flags 2927 ipsp_decay among synaptic pairs: median 0.0359, max 0.400 (units not stored; values are consistent with seconds: tens of ms, capped at 0.4)
# Orientation of the per-pair series: row k of the table holds the presynaptic spike times of pair
# (pre = k mod 320, post = k // 320); check that they are spikes of the presynaptic cell.
rng = np.random.default_rng(0)
for m in L.MICE:
f = L.open_file(m, "sparsePulseHad")
g = f["analysis/pairwise_connectivity_metrics"]
hi = g["hadamard_orthogonal_spike_times_index"][:].astype(int)
lo = np.concatenate([[0], hi[:-1]])
spk = U[m, "sparsePulseHad"]["spike_times"]
ks = [k for k in rng.choice(len(hi), 3000, replace=False) if hi[k] > lo[k]][:40]
frac_pre = [np.isin(np.round(g["hadamard_orthogonal_spike_times"][lo[k]:hi[k]], 5), np.round(spk[k % 320], 5)).mean() for k in ks]
frac_post = [np.isin(np.round(g["hadamard_orthogonal_spike_times"][lo[k]:hi[k]], 5), np.round(spk[k // 320], 5)).mean() for k in ks]
print(f"{m}: over {len(ks)} pairs, fraction of trigger times that are spikes of the presynaptic cell "
f"{np.mean(frac_pre):.3f}, of the postsynaptic cell {np.mean(frac_post):.3f}")
# 3-D series are stored lag x post x pre: the blue-pulse IPSP of connected pairs is negative after the pulse
W = L.pair_series(m, "blue_pulse_ipsp_waveform")
C = L.pair_series(m, "blue_light_crosstalk_estimate")
M = PM[m]
S = M["synaptic_connection"]
win = slice(140 + 16, 140 + 60)
resp = (W - C)[:, :, win].mean(2)
amp = M["ipsp_amplitude_norm_per_presynaptic_spike"]
ok = S & np.isfinite(amp)
print(f" mean IPSP waveform 20 to 76 ms after the pulse: connected {np.nanmean(resp[S]):.4f}, "
f"unconnected {np.nanmean(resp[~S]):.4f}; correlation with stored amplitude, as read "
f"{np.corrcoef(-resp[ok], amp[ok])[0,1]:.2f}, transposed {np.corrcoef(-resp.T[ok], amp[ok])[0,1]:.2f}")
del W, C
M-YQ0201-27: over 40 pairs, fraction of trigger times that are spikes of the presynaptic cell 1.000, of the postsynaptic cell 0.018
mean IPSP waveform 20 to 76 ms after the pulse: connected -0.0235, unconnected 0.0007; correlation with stored amplitude, as read 0.87, transposed -0.06
M-YQ0201-29: over 40 pairs, fraction of trigger times that are spikes of the presynaptic cell 1.000, of the postsynaptic cell 0.006
mean IPSP waveform 20 to 76 ms after the pulse: connected -0.0209, unconnected 0.0009; correlation with stored amplitude, as read 0.85, transposed -0.14
# Do unit ids refer to the same cells across the three sessions of a mouse?
from scipy.spatial import cKDTree
for m in L.MICE:
for a, b in [("behavior", "sparseOpto"), ("behavior", "sparsePulseHad"), ("sparseOpto", "sparsePulseHad")]:
ua, ub = U[m, a], U[m, b]
same_id = np.hypot(ua["x_um"] - ub["x_um"], ua["y_um"] - ub["y_um"])
d, _ = cKDTree(np.column_stack([ub["x_um"], ub["y_um"]])).query(np.column_stack([ua["x_um"], ua["y_um"]]))
print(f"{m} {a} vs {b}: same unit id, median distance {np.median(same_id):.0f} um; nearest cell of the other session "
f"median {np.median(d):.0f} um, within 10 um for {np.sum(d < 10)} of 320; gfp flags equal for the same id "
f"{np.sum(ua['gfp_positive'] == ub['gfp_positive'])} of 320")
print("Within-session nearest-neighbour distance (behavior):",
{m: round(float(np.median(cKDTree(np.column_stack([U[m, 'behavior']['x_um'], U[m, 'behavior']['y_um']])).query(
np.column_stack([U[m, 'behavior']['x_um'], U[m, 'behavior']['y_um']]), k=2)[0][:, 1])), 1) for m in L.MICE})
M-YQ0201-27 behavior vs sparseOpto: same unit id, median distance 1163 um; nearest cell of the other session median 58 um, within 10 um for 6 of 320; gfp flags equal for the same id 155 of 320
M-YQ0201-27 behavior vs sparsePulseHad: same unit id, median distance 1259 um; nearest cell of the other session median 29 um, within 10 um for 26 of 320; gfp flags equal for the same id 167 of 320
M-YQ0201-27 sparseOpto vs sparsePulseHad: same unit id, median distance 1067 um; nearest cell of the other session median 54 um, within 10 um for 6 of 320; gfp flags equal for the same id 152 of 320
M-YQ0201-29 behavior vs sparseOpto: same unit id, median distance 1163 um; nearest cell of the other session median 49 um, within 10 um for 9 of 320; gfp flags equal for the same id 167 of 320
M-YQ0201-29 behavior vs sparsePulseHad: same unit id, median distance 1122 um; nearest cell of the other session median 53 um, within 10 um for 8 of 320; gfp flags equal for the same id 162 of 320
M-YQ0201-29 sparseOpto vs sparsePulseHad: same unit id, median distance 1227 um; nearest cell of the other session median 51 um, within 10 um for 8 of 320; gfp flags equal for the same id 161 of 320
Within-session nearest-neighbour distance (behavior): {'M-YQ0201-27': 60.2, 'M-YQ0201-29': 63.5}
# Duplicate recordings: compare spike counts and the first 2000 frames of voltage between all sessions
sig = {}
for m in L.MICE:
for s in L.SESSIONS:
f = L.open_file(m, s)
v = f["processing/optical_voltage/normalized_voltage/data"][:2000]
sig[m, s] = (v, np.array([len(x) for x in U[m, s]["spike_times"]]))
keys = list(sig)
for i in range(len(keys)):
for j in range(i + 1, len(keys)):
a, b = sig[keys[i]], sig[keys[j]]
same_v = np.allclose(a[0], b[0]) if a[0].shape == b[0].shape else False
same_n = np.array_equal(a[1], b[1])
if same_v or same_n:
print("possible duplicate", keys[i], keys[j], same_v, same_n)
print("checked", len(keys) * (len(keys) - 1) // 2, "pairs of sessions; any duplicates are listed above")
checked 15 pairs of sessions; any duplicates are listed above
# Shared clock of stimulus and response (sparseOpto, M-YQ0201-29): spike rate of the stimulated
# cells around the onsets of their blue steps, with the true onsets and with onsets shifted 1 s earlier.
f = L.open_file("M-YQ0201-29", "sparseOpto")
blue = f["stimulus/presentation/blue_stimulation_per_cell/data"]
ts = L.series_timestamps("M-YQ0201-29", "sparseOpto")
u = U["M-YQ0201-29", "sparseOpto"]
sf = [L.spike_frames(x, ts) for x in u["spike_times"]]
true_r, shift_r = [], []
for trial in range(0, 300, 30):
a = trial * 8000
bl = blue[a:a + 8000]
for c in np.nonzero((bl > 0).any(0))[0][:5]:
on = np.nonzero(np.diff((bl[:, c] > 0).astype(int)) > 0)[0][:1]
if not len(on):
continue
o = a + on[0]
fr = sf[c]
for lst, oo in [(true_r, o), (shift_r, o - 787)]:
lst.append([np.sum((fr >= oo - 200) & (fr < oo)) / (200 * L.DT), np.sum((fr >= oo) & (fr < oo + 200)) / (200 * L.DT)])
true_r, shift_r = np.array(true_r), np.array(shift_r)
print(f"{len(true_r)} step onsets: rate before/after onset {true_r.mean(0).round(2)} Hz; "
f"with onsets shifted 1 s earlier {shift_r.mean(0).round(2)} Hz")
del blue
50 step onsets: rate before/after onset [ 1.26 10.24] Hz; with onsets shifted 1 s earlier [0.47 0.47] Hz
Figure 1 claims that need recordings not in the dandiset¶
The dandiset holds, per mouse, one spontaneous session, one intrinsic-excitability session and one connectivity session, plus a raw-movie excerpt of the M-YQ0201-29 spontaneous session (asset list above). It holds no JF585 against JF608 comparison (jf608-brighter), no wide-field against targeted images of one field (targeting-signal-to-background; the excerpt has a segmentation reference image and GFP and RFP maximum projections only), no 76-cell periodic stimulation session (fig1d-stimulation-fold-change), no lattice off-target experiment (off-target-length-constants), no spinning-disk z-stack (l1-sampling-density; only the 47-plane GFP maximum projection) and no 7.5x high-magnification recordings (highmag-footprint). These claims are blocked.
Figure 2: intrinsic excitability¶
adaptation-vadp-correlation¶
Spike-rate adaptation is weakly positively correlated with spike after-depolarization (R = 0.23, p = 1.9E-8, 564 neurons, 2 mice).
Per-cell pulse_adaptation and adp_blue_norm of the two sparseOpto sessions, pooled. Readings for
the cells: (a) QC cells with finite values, (b) all cells with finite values.
PROPS = {m: L.intrinsic_properties(m) for m in L.MICE}
QC_OPTO = {m: U[m, "sparseOpto"]["passed_qc"] for m in L.MICE}
GFP_OPTO = {m: U[m, "sparseOpto"]["gfp_positive"] for m in L.MICE}
A = np.vstack([PROPS[m] for m in L.MICE])
q = np.concatenate([QC_OPTO[m] for m in L.MICE])
mouse_of = np.concatenate([[m] * 320 for m in L.MICE])
iadp, irh, imax, iad, itau = range(5)
for name, sel in [("(a) QC cells", q), ("(b) all cells", np.ones(len(q), bool))]:
ok = sel & np.isfinite(A[:, iad]) & np.isfinite(A[:, iadp])
r, p = stats.pearsonr(A[ok, iad], A[ok, iadp])
print(f"{name}: n = {ok.sum()}, R = {r:.3f}, p = {p:.2g}")
for m in L.MICE:
okm = ok & (mouse_of == m)
r, p = stats.pearsonr(A[okm, iad], A[okm, iadp])
print(f" {m}: n = {okm.sum()}, R = {r:.3f}, p = {p:.2g}")
(a) QC cells: n = 543, R = 0.232, p = 4.5e-08
M-YQ0201-27: n = 286, R = 0.192, p = 0.0011
M-YQ0201-29: n = 257, R = 0.275, p = 7.7e-06
(b) all cells: n = 640, R = 0.186, p = 2e-06
M-YQ0201-27: n = 320, R = 0.160, p = 0.0042
M-YQ0201-29: n = 320, R = 0.216, p = 0.0001
Result: reproduced. With the 543 QC cells (reading (a)) R = 0.232 (p = 4.5e-8), within 0.023 of the paper's 0.23, with p < 0.05; all 640 cells give R = 0.186. Neither selection gives the paper's n = 564; per mouse R is printed above.
fig2c-three-bins¶
Ward hierarchical clustering of the five z-scored intrinsic properties of the 320 cells of one mouse gives three bins of 94, 116 and 110 cells.
As the code (reproduce_figure2_from_nwb.m): linkage(zscore(properties), 'ward') and
cluster(..., 'maxclust', 3) on all 320 cells of M-YQ0201-29. MATLAB's zscore uses the sample
s.d.; scipy's Ward linkage is the same algorithm.
from scipy.cluster.hierarchy import linkage, fcluster
P29 = PROPS["M-YQ0201-29"]
Z29 = (P29 - P29.mean(0)) / P29.std(0, ddof=1)
clus = fcluster(linkage(Z29, "ward"), 3, "maxclust")
sizes = np.bincount(clus)[1:]
print("cluster sizes (scipy labels 1, 2, 3):", sizes, "| as a set:", sorted(sizes), "| expected", sorted([94, 116, 110]))
P27 = PROPS["M-YQ0201-27"]
c27 = fcluster(linkage((P27 - P27.mean(0)) / P27.std(0, ddof=1), "ward"), 3, "maxclust")
print("M-YQ0201-27, for reference:", np.bincount(c27)[1:])
cluster sizes (scipy labels 1, 2, 3): [110 94 116] | as a set: [np.int64(94), np.int64(110), np.int64(116)] | expected [94, 110, 116] M-YQ0201-27, for reference: [ 57 143 120]
Result: reproduced. Ward clustering of the 320 cells of M-YQ0201-29 gives clusters of 110, 94 and 116 cells, the paper's 94, 116 and 110 as a set, exactly.
fig2gk-bin-profiles¶
Bin 1 has the highest firing rate and the highest optical rheobase; bin 2 the lowest firing rate, the lowest adaptation and the highest membrane time constant; bin 3 the highest after-depolarization and adaptation and the lowest optical rheobase.
Bins named by their sizes (94 = bin 1, 116 = bin 2, 110 = bin 3). Bin medians after the code's
outlier removal (values more than 6 s.d. from the mean). "Firing rate": reading (a) maximum rate;
reading (b) the cluster-average firing rate of Figure 2F, computed as the code's
trialAverageFiringRateFromMask: per cell, spikes per frame averaged over the trials in which the
cell received blue, then the mean over the trial and over cells.
name_of = {94: "bin1", 116: "bin2", 110: "bin3"}
lab = np.array([name_of[sizes[c - 1]] for c in clus])
med = {}
pvals = {}
for j, p in enumerate(L.PROPERTIES):
v = P29[:, j]
keep = np.abs(v - v.mean()) <= 6 * v.std(ddof=1)
med[p] = {b: np.median(v[keep & (lab == b)]) for b in ["bin1", "bin2", "bin3"]}
pvals[p] = {f"{a} vs {b}": stats.ranksums(v[keep & (lab == a)], v[keep & (lab == b)]).pvalue
for a, b in [("bin1", "bin2"), ("bin1", "bin3"), ("bin2", "bin3")]}
print(f"{p:28s} medians {', '.join(f'{b} {x:.4g}' for b, x in med[p].items())}; removed {np.sum(~keep)}; "
f"rank-sum p {', '.join(f'{k} {x:.2g}' for k, x in pvals[p].items())}")
# reading (b): trial-average firing rate during each cell's blue-stimulated trials (code, Figure 2F)
f = L.open_file("M-YQ0201-29", "sparseOpto")
blue = f["stimulus/presentation/blue_stimulation_per_cell/data"]
ts29o = L.series_timestamps("M-YQ0201-29", "sparseOpto")
stim_trials = np.zeros((320, 300), bool)
for a, x in L.iter_blocks(blue, 80_000):
for k in range(len(x) // 8000):
stim_trials[:, a // 8000 + k] = (x[k * 8000:(k + 1) * 8000] > 0).any(0)
rate_b = np.zeros(320)
for c in range(320):
fr = L.spike_frames(U["M-YQ0201-29", "sparseOpto"]["spike_times"][c], ts29o)
tr = fr // 8000
fr_u = np.unique(fr[stim_trials[c, tr]])
rate_b[c] = len(fr_u) / stim_trials[c].sum() / (8000 * L.DT)
print("stimulated trials per cell: median", np.median(stim_trials.sum(1)), "range", stim_trials.sum(1).min(), stim_trials.sum(1).max())
med_b = {b: rate_b[lab == b].mean() for b in ["bin1", "bin2", "bin3"]}
print("reading (b), cluster-average firing rate in stimulated trials (Hz):", {b: round(x, 2) for b, x in med_b.items()})
def order_checks(rate):
mx = lambda d: max(d, key=d.get)
mn = lambda d: min(d, key=d.get)
return {"bin1 highest firing rate": mx(rate) == "bin1",
"bin1 highest rheobase": mx(med["optical_rheobase_norm"]) == "bin1",
"bin2 lowest firing rate": mn(rate) == "bin2",
"bin2 lowest adaptation": mn(med["pulse_adaptation"]) == "bin2",
"bin2 highest membrane time constant": mx(med["membrane_time_constant_ms"]) == "bin2",
"bin3 highest after-depolarization": mx(med["adp_blue_norm"]) == "bin3",
"bin3 highest adaptation": mx(med["pulse_adaptation"]) == "bin3",
"bin3 lowest rheobase": mn(med["optical_rheobase_norm"]) == "bin3"}
for nm, rate in [("(a) maximum rate", med["max_firing_rate_hz"]), ("(b) cluster-average rate", med_b)]:
oc = order_checks(rate)
print(f"\nreading {nm}: {sum(oc.values())} of 8 orderings hold")
for k, v in oc.items():
print(f" {k}: {v}")
adp_blue_norm medians bin1 0.09475, bin2 0.09698, bin3 0.1748; removed 1; rank-sum p bin1 vs bin2 0.5, bin1 vs bin3 6.6e-26, bin2 vs bin3 1.2e-20 optical_rheobase_norm medians bin1 0.386, bin2 0.3256, bin3 0.1015; removed 0; rank-sum p bin1 vs bin2 0.00083, bin1 vs bin3 4.7e-29, bin2 vs bin3 1e-21 max_firing_rate_hz medians bin1 39, bin2 19.65, bin3 30.86; removed 0; rank-sum p bin1 vs bin2 4e-33, bin1 vs bin3 3.7e-16, bin2 vs bin3 2.7e-17 pulse_adaptation medians bin1 0.2777, bin2 -0.1667, bin3 0.4837; removed 0; rank-sum p bin1 vs bin2 4.2e-11, bin1 vs bin3 0.00021, bin2 vs bin3 5.2e-17 membrane_time_constant_ms medians bin1 15.31, bin2 18.89, bin3 14.93; removed 2; rank-sum p bin1 vs bin2 5.5e-13, bin1 vs bin3 0.27, bin2 vs bin3 1.5e-14
stimulated trials per cell: median 9.0 range 7 10
reading (b), cluster-average firing rate in stimulated trials (Hz): {'bin1': np.float64(23.06), 'bin2': np.float64(9.46), 'bin3': np.float64(16.28)}
reading (a) maximum rate: 8 of 8 orderings hold
bin1 highest firing rate: True
bin1 highest rheobase: True
bin2 lowest firing rate: True
bin2 lowest adaptation: True
bin2 highest membrane time constant: True
bin3 highest after-depolarization: True
bin3 highest adaptation: True
bin3 lowest rheobase: True
reading (b) cluster-average rate: 8 of 8 orderings hold
bin1 highest firing rate: True
bin1 highest rheobase: True
bin2 lowest firing rate: True
bin2 lowest adaptation: True
bin2 highest membrane time constant: True
bin3 highest after-depolarization: True
bin3 highest adaptation: True
bin3 lowest rheobase: True
Result: reproduced. All eight orderings hold under both readings of "firing rate": maximum rate (medians 39.0, 19.7 and 30.9 Hz for bins 1, 2, 3) and the Figure 2F trial-average rate (23.1, 9.5 and 16.3 Hz). Rheobase medians are 0.386, 0.326 and 0.102 SH; adaptation 0.278, -0.167 and 0.484; membrane time constant 15.3, 18.9 and 14.9 ms; the V_adp medians and every rank-sum p are printed above.
two-mice-intrinsic-distributions¶
The two mice show similar broad distributions of intrinsic properties; by two-sided rank-sum tests they differ in optical rheobase (p <= 0.001) and membrane time constant (0.01 < p <= 0.05), not in V_adp, maximum rate or adaptation.
# membrane_time_constant_ms is exactly 0 for 7 cells of M-YQ0201-27 (data check), a value no fitted
# exponential decay can take; the main variant treats it as a failed fit (missing), and keeping it is shown.
for zero_tau in ("as missing", "kept as a value"):
for nm, sel27, sel29 in [("(a) all cells", np.ones(320, bool), np.ones(320, bool)),
("(b) QC cells", QC_OPTO["M-YQ0201-27"], QC_OPTO["M-YQ0201-29"])]:
print(f"reading {nm}, membrane time constant of 0 {zero_tau}: n = {sel27.sum()} and {sel29.sum()}")
calls = {}
for j, p in enumerate(L.PROPERTIES):
a, b = PROPS["M-YQ0201-27"][sel27, j], PROPS["M-YQ0201-29"][sel29, j]
a, b = a[np.isfinite(a)], b[np.isfinite(b)]
if p == "membrane_time_constant_ms" and zero_tau == "as missing":
a, b = a[a != 0], b[b != 0]
pv = stats.ranksums(a, b).pvalue
calls[p] = pv <= 0.05
print(f" {p:28s} median {np.median(a):8.4f} vs {np.median(b):8.4f} n = {len(a)}, {len(b)} p = {pv:.3g}")
want = {"optical_rheobase_norm": True, "membrane_time_constant_ms": True, "adp_blue_norm": False,
"max_firing_rate_hz": False, "pulse_adaptation": False}
print(" calls matching the paper:", sum(calls[k] == v for k, v in want.items()), "of 5")
reading (a) all cells, membrane time constant of 0 as missing: n = 320 and 320 adp_blue_norm median 0.1113 vs 0.1135 n = 320, 320 p = 0.179 optical_rheobase_norm median 0.3463 vs 0.2903 n = 320, 320 p = 1.13e-05 max_firing_rate_hz median 30.8045 vs 30.1759 n = 320, 320 p = 0.197 pulse_adaptation median 0.2740 vs 0.2628 n = 320, 320 p = 0.24 membrane_time_constant_ms median 16.9067 vs 16.0315 n = 313, 320 p = 0.0313 calls matching the paper: 5 of 5 reading (b) QC cells, membrane time constant of 0 as missing: n = 286 and 257 adp_blue_norm median 0.1114 vs 0.1098 n = 286, 257 p = 0.835 optical_rheobase_norm median 0.3419 vs 0.2862 n = 286, 257 p = 0.000103 max_firing_rate_hz median 30.6823 vs 31.4332 n = 286, 257 p = 0.932 pulse_adaptation median 0.2754 vs 0.2628 n = 286, 257 p = 0.477 membrane_time_constant_ms median 16.9212 vs 16.1094 n = 284, 257 p = 0.0333 calls matching the paper: 5 of 5 reading (a) all cells, membrane time constant of 0 kept as a value: n = 320 and 320 adp_blue_norm median 0.1113 vs 0.1135 n = 320, 320 p = 0.179 optical_rheobase_norm median 0.3463 vs 0.2903 n = 320, 320 p = 1.13e-05 max_firing_rate_hz median 30.8045 vs 30.1759 n = 320, 320 p = 0.197 pulse_adaptation median 0.2740 vs 0.2628 n = 320, 320 p = 0.24 membrane_time_constant_ms median 16.8114 vs 16.0315 n = 320, 320 p = 0.101 calls matching the paper: 4 of 5 reading (b) QC cells, membrane time constant of 0 kept as a value: n = 286 and 257 adp_blue_norm median 0.1114 vs 0.1098 n = 286, 257 p = 0.835 optical_rheobase_norm median 0.3419 vs 0.2862 n = 286, 257 p = 0.000103 max_firing_rate_hz median 30.6823 vs 31.4332 n = 286, 257 p = 0.932 pulse_adaptation median 0.2754 vs 0.2628 n = 286, 257 p = 0.477 membrane_time_constant_ms median 16.9165 vs 16.1094 n = 286, 257 p = 0.0482 calls matching the paper: 5 of 5
Result: reproduced, resting on an assumption. With a membrane time constant of exactly 0 (7 cells of M-YQ0201-27) treated as a failed fit, both readings give the paper's five calls: rheobase differs (p = 1.1e-5 all cells, 1.0e-4 QC cells), membrane time constant differs (p = 0.031 and 0.033, n = 313 and 284 against 320 and 257), and V_adp, maximum rate and adaptation do not (p = 0.18 to 0.93). Kept as values, the zeros give four of five calls under reading (a) (time constant p = 0.101) and five under (b) (p = 0.048).
Figure 3: synaptic and gap-junction connectivity¶
All connectivity claims use the stored per-pair products of the two sparsePulseHad sessions:
synaptic_connection and gap_junction_connection (the paper's per-pair null distributions with
Benjamini-Hochberg correction, Methods), the IPSP amplitude per presynaptic spike, the IPSP decay,
the spikelet amplitude, and the pairwise waveforms. Cells are the QC cells of each session (290 and
286, the paper's n = 576). "Tested pairs" are ordered pairs of distinct QC cells within 400 um.
synaptic-connection-counts¶
Optogenetic mapping found 802 inhibitory connections among 7,280 tested pairs in one mouse and 667 among 7,032 in the other, about 3 +/- 3 outgoing and 3 +/- 3 incoming per cell of 25 +/- 9 tested, a pairwise probability of 11 +/- 9% within 400 um.
pair_sets = L.pair_sets
rows = []
percell = {}
for m in L.MICE:
M, q, QQ, D, sets = pair_sets(m)
S = M["synaptic_connection"]
measured = QQ & (M["ipsp_amplitude_norm_per_presynaptic_spike"] != 0) & np.isfinite(M["ipsp_amplitude_norm_per_presynaptic_spike"])
for band, T in sets.items():
rows.append(dict(mouse=m, band=band, connections=int((S & T).sum()), tested_a=int(T.sum()),
tested_b=int((T & measured).sum())))
out, inn, tested = (S & T).sum(1)[q], (S & T).sum(0)[q], T.sum(1)[q]
percell.setdefault(band, []).append(pd.DataFrame(dict(mouse=m, out=out, inn=inn, tested=tested,
prob=np.where(tested > 0, out / np.maximum(tested, 1), np.nan))))
print(pd.DataFrame(rows).to_string())
print("(a) ordered QC pairs in the band; (b) those with a stored, nonzero IPSP amplitude")
for band, dfs in percell.items():
d = pd.concat(dfs)
print(f"\n{band}, per cell (n = {len(d)} QC cells, 2 mice): outgoing {d.out.mean():.2f} +/- {d.out.std():.2f}, "
f"incoming {d.inn.mean():.2f} +/- {d.inn.std():.2f}, tested {d.tested.mean():.1f} +/- {d.tested.std():.1f}, "
f"probability {100*d.prob.mean():.1f} +/- {100*d.prob.std():.1f}% ({d.prob.isna().sum()} cells with no tested partner)")
for m, dm in d.groupby("mouse"):
print(f" {m}: outgoing {dm.out.mean():.2f} +/- {dm.out.std():.2f}, tested {dm.tested.mean():.1f}, probability {100*dm.prob.mean():.1f}%")
mouse band connections tested_a tested_b 0 M-YQ0201-27 within 400 um 828 7426 7424 1 M-YQ0201-27 60 to 400 um 802 7280 7278 2 M-YQ0201-29 within 400 um 679 7150 7150 3 M-YQ0201-29 60 to 400 um 667 7032 7032 (a) ordered QC pairs in the band; (b) those with a stored, nonzero IPSP amplitude within 400 um, per cell (n = 576 QC cells, 2 mice): outgoing 2.62 +/- 2.93, incoming 2.62 +/- 2.62, tested 25.3 +/- 8.6, probability 10.8 +/- 11.7% (0 cells with no tested partner) M-YQ0201-27: outgoing 2.86 +/- 3.02, tested 25.6, probability 11.7% M-YQ0201-29: outgoing 2.37 +/- 2.83, tested 25.0, probability 9.8% 60 to 400 um, per cell (n = 576 QC cells, 2 mice): outgoing 2.55 +/- 2.87, incoming 2.55 +/- 2.61, tested 24.8 +/- 8.5, probability 10.7 +/- 11.6% (0 cells with no tested partner) M-YQ0201-27: outgoing 2.77 +/- 2.95, tested 25.1, probability 11.6% M-YQ0201-29: outgoing 2.33 +/- 2.78, tested 24.6, probability 9.7%
Result: reproduced. In the 60 to 400 um band the dandiset gives 802 connections among 7,280 ordered QC pairs in M-YQ0201-27 and 667 among 7,032 in M-YQ0201-29, the paper's four numbers exactly (within 400 um: 828 of 7,426 and 679 of 7,150). Per cell (n = 576): 2.55 +/- 2.87 outgoing and 2.55 +/- 2.61 incoming connections, 24.8 +/- 8.5 tested partners, probability 10.7 +/- 11.6%, all within the paper's 3 +/- 3, 25 +/- 9 and 11 +/- 9%. Reading (b) of pairs tested (a stored IPSP amplitude) differs from (a) by two pairs.
ipsp-median-amplitude¶
The median unitary IPSP among connected pairs was -2.8% of a spike height per presynaptic spike, while correlated spontaneous fluctuations were about 20% of a spike height.
IPSP amplitude: stored ipsp_amplitude_norm_per_presynaptic_spike (stored positive; sign flipped)
of pairs with synaptic_connection set. Fluctuations: the reading chosen in the claims file, the
code's cross-STA depolarization (reproduce_figure4_from_nwb.m STATS: range of each pair's quiet
spike-triggered voltage over lags -100 to -2 frames, mean over pairs 60 to 400 um apart), from the
stored behavior-session arrays.
amps = {}
for m in L.MICE:
M, q, QQ, D, sets = pair_sets(m)
S = M["synaptic_connection"]
a = -M["ipsp_amplitude_norm_per_presynaptic_spike"]
amps[m] = a[S]
print(f"{m}: connected pairs {S.sum()} ({np.isnan(a[S]).sum()} without an amplitude); median IPSP {np.nanmedian(a[S]):.4f} SH; "
f"QC pairs 60 to 400 um {np.nanmedian(a[S & sets['60 to 400 um']]):.4f}")
pooled = np.concatenate(list(amps.values()))
print(f"pooled median {np.nanmedian(pooled):.4f} SH over {np.isfinite(pooled).sum()} pairs (expected -0.028 +/- 0.0028)")
ST4 = {}
for m in L.MICE:
ST4[m] = L.fig4_stage2(m)
print(f"{m}: cross-STA depolarization (quiet, 60 to 400 um) {ST4[m]['cross_sta_depolarization']:.3f} SH")
print(f"mean over the two mice {np.mean([ST4[m]['cross_sta_depolarization'] for m in L.MICE]):.3f} SH (expected 0.20 +/- 0.02)")
M-YQ0201-27: connected pairs 955 (2 without an amplitude); median IPSP -0.0303 SH; QC pairs 60 to 400 um -0.0284 M-YQ0201-29: connected pairs 800 (0 without an amplitude); median IPSP -0.0292 SH; QC pairs 60 to 400 um -0.0288 pooled median -0.0297 SH over 1753 pairs (expected -0.028 +/- 0.0028)
M-YQ0201-27: cross-STA depolarization (quiet, 60 to 400 um) 0.217 SH
M-YQ0201-29: cross-STA depolarization (quiet, 60 to 400 um) 0.250 SH mean over the two mice 0.234 SH (expected 0.20 +/- 0.02)
Result: partially reproduced. The median IPSP of connected pairs is -0.0297 SH pooled (-0.0303 and -0.0292 per mouse), within 0.0028 of -0.028. The cross-STA depolarization, the claims file's reading for the 20%, is computed per mouse and averaged, as the criterion says: 0.217 (M-YQ0201-27) and 0.250 SH (M-YQ0201-29), mean 0.234, outside 0.20 +/- 0.02; one mouse alone is inside.
gap-junction-connection-counts¶
Spikelet mapping found 3,553 directed electrical connections among 7,280 tested pairs in one mouse and 2,199 among 7,032 in the other, 10 +/- 6 outgoing and 10 +/- 5 incoming per cell, a pairwise probability of 41 +/- 15%; the median spikelet was 1.2% of a spike.
rows = []
gpc = {}
for m in L.MICE:
M, q, QQ, D, sets = pair_sets(m)
G = M["gap_junction_connection"]
sp = M["spikelet_amplitude_normalized"]
for band, T in sets.items():
out, inn, tested = (G & T).sum(1)[q], (G & T).sum(0)[q], T.sum(1)[q]
rows.append(dict(mouse=m, band=band, connections=int((G & T).sum()), tested=int(T.sum()),
median_spikelet=np.median(sp[G & T])))
gpc.setdefault(band, []).append(pd.DataFrame(dict(mouse=m, out=out, inn=inn,
prob=np.where(tested > 0, out / np.maximum(tested, 1), np.nan))))
print(f"{m}: all gap-junction flags {G.sum()}, involving a non-QC cell {np.sum(G & ~QQ)}")
print(pd.DataFrame(rows).to_string())
for band, dfs in gpc.items():
d = pd.concat(dfs)
print(f"{band}: outgoing {d.out.mean():.2f} +/- {d.out.std():.2f}, incoming {d.inn.mean():.2f} +/- {d.inn.std():.2f}, "
f"probability {100*d.prob.mean():.1f} +/- {100*d.prob.std():.1f}% (n = {len(d)} cells)")
for band in ["60 to 400 um", "within 400 um"]:
allsp = np.concatenate([PM[m]["spikelet_amplitude_normalized"][PM[m]["gap_junction_connection"] & pair_sets(m)[4][band]] for m in L.MICE])
print(f"pooled median spikelet, {band}: {np.median(allsp):.4f} SH (expected 0.012 +/- 0.0012)")
M-YQ0201-27: all gap-junction flags 4516, involving a non-QC cell 819
M-YQ0201-29: all gap-junction flags 2927, involving a non-QC cell 618
mouse band connections tested median_spikelet
0 M-YQ0201-27 within 400 um 3697 7426 0.011820
1 M-YQ0201-27 60 to 400 um 3553 7280 0.011384
2 M-YQ0201-29 within 400 um 2309 7150 0.013463
3 M-YQ0201-29 60 to 400 um 2199 7032 0.012866
within 400 um: outgoing 10.43 +/- 5.87, incoming 10.43 +/- 5.30, probability 41.9 +/- 19.0% (n = 576 cells)
60 to 400 um: outgoing 9.99 +/- 5.74, incoming 9.99 +/- 5.09, probability 40.9 +/- 19.1% (n = 576 cells)
pooled median spikelet, 60 to 400 um: 0.0120 SH (expected 0.012 +/- 0.0012)
pooled median spikelet, within 400 um: 0.0125 SH (expected 0.012 +/- 0.0012)
Result: reproduced. In the 60 to 400 um band the counts are 3,553 of 7,280 and 2,199 of 7,032, the paper's numbers exactly. Per cell, 9.99 +/- 5.74 outgoing and 9.99 +/- 5.09 incoming connections and a probability of 40.9 +/- 19.1% (paper 10 +/- 6, 10 +/- 5 and 41 +/- 15%); the pooled median spikelet is 0.0120 SH (0.012 +/- 0.0012). All pairs within 400 um give 3,697 and 2,309.
hadamard-stimulation-rates¶
During Hadamard-coded stimulation, stimulated cells fired at 25.4 +/- 16.6 Hz and non-stimulated cells at 3.9 +/- 4.5 Hz; each cell received about 640 stimuli and fired about 12,380 evoked spikes in total.
In the 160 Hadamard trials of each sparsePulseHad session (trial_type hadamard_gap_junction_mapping),
per QC cell: spike rate in the frames where the cell receives blue (its on blocks) and in the other
frames of those trials (off blocks); spikes in on blocks. "Stimuli" is read (a) as on blocks
(rising edges of the cell's blue waveform), or (b) as 750 ms code steps with blue on (on frames over
590.6 frames; the Methods give 750 ms steps of a 50% duty-cycle code, and consecutive on steps
merge into one block). Mean +/- s.d. over QC cells of both mice.
had = []
for m in L.MICE:
f = L.open_file(m, "sparsePulseHad")
tt = f["intervals/trials/trial_type"][:]
ts = L.series_timestamps(m, "sparsePulseHad")
starts = np.searchsorted(ts, f["intervals/trials/start_time"][:])
stops = np.searchsorted(ts, f["intervals/trials/stop_time"][:], side="right")
blue = f["stimulus/presentation/blue_stimulation_per_cell/data"]
u = U[m, "sparsePulseHad"]
sfr = [L.spike_frames(x, ts) for x in u["spike_times"]]
on_frames = np.zeros(320)
off_frames = np.zeros(320)
on_spk = np.zeros(320)
off_spk = np.zeros(320)
n_stim = np.zeros(320)
hidx = np.nonzero(tt == b"hadamard_gap_junction_mapping")[0]
spk_mat_idx = [np.sort(x) for x in sfr]
for t in hidx:
a, b = starts[t], stops[t]
x = blue[a:b] > 0
on_frames += x.sum(0)
off_frames += (~x).sum(0)
n_stim += (np.diff(x.astype(int), axis=0) > 0).sum(0) + x[0]
for c in range(320):
fr = spk_mat_idx[c]
fr = fr[(fr >= a) & (fr < b)] - a
on_spk[c] += x[fr, c].sum()
off_spk[c] += (~x[fr, c]).sum()
q = u["passed_qc"]
had.append(pd.DataFrame(dict(mouse=m, on_rate=on_spk[q] / (on_frames[q] * L.DT), off_rate=off_spk[q] / (off_frames[q] * L.DT),
stimuli=n_stim[q], code_bits=on_frames[q] / (0.75 / L.DT), evoked_spikes=on_spk[q],
on_fraction=on_frames[q] / (on_frames[q] + off_frames[q]))))
print(f"{m}: {len(hidx)} Hadamard trials, {stops[hidx].sum() - starts[hidx].sum()} frames")
had = pd.concat(had)
print(had.groupby("mouse")[["on_rate", "off_rate", "stimuli", "code_bits", "evoked_spikes", "on_fraction"]].agg(["mean", "std"]).round(2).to_string())
print(f"\npooled, n = {len(had)} QC cells: stimulated {had.on_rate.mean():.1f} +/- {had.on_rate.std():.1f} Hz, "
f"non-stimulated {had.off_rate.mean():.1f} +/- {had.off_rate.std():.1f} Hz, stimuli as (a) on blocks {had.stimuli.mean():.0f}, "
f"(b) 750 ms on steps {had.code_bits.mean():.0f}, "
f"evoked spikes {had.evoked_spikes.mean():.0f}")
M-YQ0201-27: 160 Hadamard trials, 793600 frames
M-YQ0201-29: 160 Hadamard trials, 793600 frames
on_rate off_rate stimuli code_bits evoked_spikes on_fraction
mean std mean std mean std mean std mean std mean std
mouse
M-YQ0201-27 29.53 17.34 3.61 4.37 360.12 17.80 650.60 35.49 14410.37 8512.32 0.48 0.03
M-YQ0201-29 23.42 15.18 3.55 3.97 360.29 18.43 650.23 35.17 11426.45 7456.89 0.48 0.03
pooled, n = 576 QC cells: stimulated 26.5 +/- 16.6 Hz, non-stimulated 3.6 +/- 4.2 Hz, stimuli as (a) on blocks 360, (b) 750 ms on steps 650, evoked spikes 12929
Result: reproduced, resting on an assumption. Over the 576 QC cells, stimulated cells fire at 26.5 +/- 16.6 Hz and non-stimulated at 3.6 +/- 4.2 Hz (paper 25.4 +/- 16.6 and 3.9 +/- 4.5); evoked spikes total 12,929 per cell (12,380 +/- 1,238); counted as 750 ms code steps with blue on (reading (b), assumed from the Methods' description of the codes) each cell receives 650 stimuli (640 +/- 64). Counted as on blocks (reading (a)) it receives 360, since consecutive on steps merge.
highmag-footprint, detection-limits (blocked)¶
highmag-footprint needs 7.5x recordings the dandiset does not hold. detection-limits needs each pair's connection statistic and its null distribution; the pairwise table holds only the calls, amplitudes, decays and distances (its full listing is printed below), and rebuilding the paper's statistic (the residual sums of squares of the IPSP model with and without its double exponential, Methods) for 10,000 null draws per tested pair is out of reach (see the timing below).
# Everything stored in the pairwise table, and the cost of the paper's connection statistic
from scipy.optimize import least_squares
for m in L.MICE:
g = L.open_file(m, "sparsePulseHad")["analysis/pairwise_connectivity_metrics"]
print(m, {k: g[k].shape for k in g.keys()})
lag_s = (np.arange(281) - 140) * L.DT
tpost = np.clip(lag_s, 0, None)
rng_fit = np.random.default_rng(5)
yy = -0.03 * (np.exp(-tpost / 0.035) - np.exp(-tpost / 0.005)) * (lag_s > 0) + rng_fit.normal(0, 0.01, 281)
h1 = lambda p: p[0] * (np.exp(-tpost / p[1]) - np.exp(-tpost / p[2])) * (lag_s > 0) + p[3] + p[4] * lag_s + p[5] * lag_s ** 2 - yy
tf = time.time()
for _ in range(50):
least_squares(h1, [-0.02, 0.03, 0.004, 0, 0, 0], bounds=([-1, 0.006, 0.001, -1, -10, -100], [1, 0.4, 0.05, 1, 10, 100]))
per_fit = (time.time() - tf) / 50
n_tested = sum(int(L.pair_sets(m)[4]["within 400 um"].sum()) for m in L.MICE)
print(f"one double-exponential IPSP fit: {per_fit*1e3:.1f} ms; {n_tested} tested pairs x 10,000 null draws x 1 fit = "
f"{n_tested * 1e4 * per_fit / 3600:.0f} h")
M-YQ0201-27 {'distance_pixels': (102400,), 'gap_junction_connection': (102400,), 'hadamard_orthogonal_spike_times': (39011337,), 'hadamard_orthogonal_spike_times_index': (102400,), 'id': (102400,), 'ipsp_amplitude_norm_per_presynaptic_spike': (102400,), 'ipsp_decay_source_units': (102400,), 'ipsp_decay_standard_error_source_units': (102400,), 'postsynaptic_unit_id': (102400,), 'presynaptic_unit_id': (102400,), 'spikelet_amplitude_normalized': (102400,), 'synaptic_connection': (102400,)}
M-YQ0201-29 {'distance_pixels': (102400,), 'gap_junction_connection': (102400,), 'hadamard_orthogonal_spike_times': (29865553,), 'hadamard_orthogonal_spike_times_index': (102400,), 'id': (102400,), 'ipsp_amplitude_norm_per_presynaptic_spike': (102400,), 'ipsp_decay_source_units': (102400,), 'ipsp_decay_standard_error_source_units': (102400,), 'postsynaptic_unit_id': (102400,), 'presynaptic_unit_id': (102400,), 'spikelet_amplitude_normalized': (102400,), 'synaptic_connection': (102400,)}
one double-exponential IPSP fit: 57.3 ms; 14576 tested pairs x 10,000 null draws x 1 fit = 2322 h
Result: blocked (too large). The pairwise table holds no per-pair statistic, p-value or null. One fit of the IPSP model takes several tens of milliseconds here (printed above), so the null statistics of the 14,576 tested pairs (10,000 draws each) would take thousands of hours (printed above), and the pairs "near detection cutoff" cannot be picked without them.
spikelet-not-scatter¶
Fluorescence scattered from a spiking cell decays over a much shorter distance than the spikelet amplitude (spikelet to scatter ratio above 2.5 at 60 um), so pairs under 60 um were excluded.
Only the raw-movie excerpt (M-YQ0201-29, behavior session, 1,152,000 frames) holds interstitial
pixels. Reading 40,000 frames takes a few minutes here (printed below), so the whole movie would take
hours; this is a partial test on its first 40,000 frames (51 s), with l1opto.scatter_sta (Methods, Analysis for mapping gap
junction connections, paragraph 4): cross-STA fluorescence of interstitial pixels (4 x 4 pixel bins,
26 um, holding no footprint pixel) within 400 um of each triggering cell, normalized by the
trigger's spike fluorescence (frame 0 minus frame -2 of its own STA), and extracted as a spikelet.
Trigger cells are the excerpt's QC cells with at least 20 spikes in the frames read. Spikelets are
the stored spikelet_amplitude_normalized of the M-YQ0201-29 connectivity session, QC pairs, all
pairs (as Supplementary Fig. 17B's "cell pairs") and connected pairs as a variant. 40 um bins
(Supplementary Fig. 17B); the bin holding 60 um is 40 to 80 um. Means as the criterion, medians as a
variant, since a few triggers with small spike fluorescence give large normalized values. The
trigger's spike fluorescence is negative for every trigger (printed below): Voltron1, the paper's
indicator, is negative-going (its fluorescence falls when the membrane depolarizes; this is known
of the indicator, the paper does not say it), so a spike lowers the raw counts. The interstitial STA falls with it, and dividing by the
negative spike fluorescence gives a positive scatter amplitude, on the same scale as the stored
spikelets.
tl = time.time()
SC = L.scatter_sta("M-YQ0201-29", n_frames=40_000)
use = SC["qc"] & (SC["n_spikes"] >= 20)
print(f"scatter STA over 40,000 frames in {time.time() - tl:.0f} s: {SC['n_bins']} interstitial bins; {use.sum()} QC trigger cells with >= 20 spikes "
f"(spikes per cell median {np.median(SC['n_spikes'][use]):.0f}); spike fluorescence median {np.median(SC['spike_f'][use]):.1f} counts, "
f"{np.sum(SC['spike_f'][use] <= 0)} triggers with spike fluorescence <= 0")
M29, q29, QQ29, D29, sets29 = pair_sets("M-YQ0201-29")
spk = M29["spikelet_amplitude_normalized"]
edges_s = np.arange(0, 401, 40)
rows_s = []
for a, b in zip(edges_s[:-1], edges_s[1:]):
s_ = (SC["dist"] >= a) & (SC["dist"] < b) & use[:, None]
v = SC["amp"][s_]
pr = QQ29 & (D29 >= a) & (D29 < b) & np.isfinite(spk)
rows_s.append(dict(bin=f"{a}-{b}", scatter_n=len(v), scatter_mean=np.mean(v), scatter_median=np.median(v),
spikelet_pairs=int(pr.sum()), spikelet_mean=spk[pr].mean(), spikelet_median=np.median(spk[pr]),
connected_mean=spk[pr & M29["gap_junction_connection"]].mean()))
SCT = pd.DataFrame(rows_s)
SCT["ratio_mean"] = SCT.spikelet_mean / SCT.scatter_mean
SCT["ratio_median"] = SCT.spikelet_median / SCT.scatter_median
SCT["ratio_connected"] = SCT.connected_mean / SCT.scatter_mean
print(SCT.round(4).to_string())
b1, b3 = SCT.iloc[1], SCT.iloc[3]
print(f"from the 40-80 to the 120-160 um bin: scatter mean falls to {b3.scatter_mean / b1.scatter_mean:.2f} of its value "
f"(median {b3.scatter_median / b1.scatter_median:.2f}), spikelet mean to {b3.spikelet_mean / b1.spikelet_mean:.2f} "
f"(median {b3.spikelet_median / b1.spikelet_median:.2f}; connected {b3.connected_mean / b1.connected_mean:.2f})")
# split-half check of the scatter: triggers split by unit id parity
for par in (0, 1):
s_ = (SC["dist"] >= 40) & (SC["dist"] < 80) & (use & (np.arange(len(use)) % 2 == par))[:, None]
print(f" triggers with {'even' if par == 0 else 'odd'} unit ids: 40-80 um scatter mean {SC['amp'][s_].mean():.4f}, median {np.median(SC['amp'][s_]):.4f}")
scatter STA over 40,000 frames in 278 s: 5971 interstitial bins; 189 QC trigger cells with >= 20 spikes (spikes per cell median 107); spike fluorescence median -441.0 counts, 189 triggers with spike fluorescence <= 0
bin scatter_n scatter_mean scatter_median spikelet_pairs spikelet_mean spikelet_median connected_mean ratio_mean ratio_median ratio_connected
0 0-40 136 0.0400 0.0363 32 0.1121 0.1009 0.1163 2.8048 2.7787 2.9102
1 40-80 1531 0.0150 0.0126 240 0.0456 0.0396 0.0507 3.0287 3.1437 3.3707
2 80-120 3470 0.0054 0.0047 398 0.0211 0.0182 0.0253 3.9197 3.9101 4.6917
3 120-160 5189 0.0035 0.0034 618 0.0126 0.0116 0.0179 3.6167 3.4625 5.1350
4 160-200 6790 0.0022 0.0022 680 0.0080 0.0080 0.0137 3.5810 3.5822 6.0919
5 200-240 8212 0.0025 0.0022 806 0.0055 0.0054 0.0124 2.2101 2.4025 4.9507
6 240-280 9663 0.0023 0.0019 918 0.0042 0.0041 0.0112 1.8179 2.1172 4.8078
7 280-320 11304 0.0019 0.0016 1122 0.0032 0.0032 0.0112 1.6782 2.0340 5.8625
8 320-360 12417 0.0016 0.0014 1104 0.0025 0.0023 0.0107 1.5433 1.6217 6.5409
9 360-400 13736 0.0020 0.0016 1232 0.0015 0.0017 0.0107 0.7478 1.0862 5.4386
from the 40-80 to the 120-160 um bin: scatter mean falls to 0.23 of its value (median 0.27), spikelet mean to 0.28 (median 0.29; connected 0.35)
triggers with even unit ids: 40-80 um scatter mean 0.0148, median 0.0127
triggers with odd unit ids: 40-80 um scatter mean 0.0153, median 0.0123
Result: reproduced, on a subset of the movie. Over the first 40,000 frames of the excerpt (189 QC trigger cells, 107 spikes each in median), the normalized scatter in the 40 to 80 um bin is 0.0150 (mean; median 0.0126; 0.0148 and 0.0153 for the two halves of the triggers) against a mean spikelet of 0.0456 over QC pairs of the same mouse, a ratio of 3.03 (median 3.14; connected pairs 3.37), above 2.25. Every trigger's spike fluorescence is negative (median -441 counts), as expected of the negative-going Voltron1, and the scatter is normalized by it. From the 40 to 80 um bin to the 120 to 160 um bin the scatter falls to 0.23 of its value and the spikelet to 0.28, so the scatter falls faster, as the criterion requires. The test covers 3.5% of one mouse's excerpt, the only movie deposited.
lasso-off-target-correction¶
Correcting the IPSP matrix for spikes evoked in non-targeted cells by lasso regression changes little; the corrected and raw matrices correlate with R = 0.82 and fewer than 20% of significant IPSPs differ by more than 20%.
The dandiset does not store the paper's matrices, so both are rebuilt from the sparsePulseHad
sessions with l1opto.pulse_responses and l1opto.lasso_correction, whose docstrings say where each
choice comes from. One row per 20 ms pulse (the Methods' 14,400 trials, each cell targeted 243 to
480 times): the response of every cell, its mean normalized voltage 20 to 60 ms after onset minus
the 25 ms before (assumption: a window around the IPSP peak of about 30 ms, since the paper's
per-trial response is not given), and the evoked spikes of every cell. The model is R = S W
(Supplementary Fig. 16A) with S the spikes per pulse of targeted cells (stored estimate) and of
non-targeted cells within 100 um of a target (detected), fitted per postsynaptic cell by lasso with
an intercept. Penalty readings (a) least cross-validated error, (b) the largest within one standard
error (claims file); least squares as a variant. The comparison is over the 1755 pairs, the stored
synaptic flags of both mice (955 and 800; the 2 without a stored amplitude are kept here since the
rebuilt matrices do not need it), and pairs 60 to 400 um as a variant: Pearson R of corrected
against raw, and the fraction of pairs whose corrected value differs from the raw by more than 20%
of the raw. The rebuilt raw matrix is compared with the stored amplitudes, to show how far it measures
the same IPSPs. Since the paper compares the corrected matrix with "the connectivity matrix", which
is the stored amplitudes, the corrected matrix is also compared with the stored amplitudes, as
they are and after scaling by the median ratio of stored to rebuilt raw amplitude (the two
response measures differ in scale).
tl = time.time()
LASSO = {}
for m in L.MICE:
onsets, T_p, Y_p, E_p = L.pulse_responses(m)
M, q, QQ, D, sets = pair_sets(m)
s_hat = U[m, "sparsePulseHad"]["estimated_spikes_per_blue_pulse"]
dmin = np.array([D[t_].min(0) for t_ in T_p]) # pulses x cells: distance to the nearest target
print(f"{m}: {len(onsets)} pulses, {T_p.sum(1).min()} to {T_p.sum(1).max()} targets per pulse, each cell targeted "
f"{T_p.sum(0).min()} to {T_p.sum(0).max()} times; evoked spikes per pulse in non-targeted cells within 60 um of a target "
f"{E_p[(dmin < 60) & ~T_p].mean():.3f}, 60 to 100 um {E_p[(dmin >= 60) & (dmin < 100) & ~T_p].mean():.3f}, "
f"beyond 400 um {E_p[dmin > 400].mean():.4f}; targeted cells, stored estimate {np.mean(s_hat):.2f}, detected {E_p[T_p].mean():.2f}")
LASSO[m] = L.lasso_correction(T_p, Y_p, E_p, D, s_hat)
del T_p, Y_p, E_p, dmin
print(f"pulses and fits in {time.time() - tl:.0f} s")
for selnm in ("all stored flags", "flags 60 to 400 um"):
acc = {k: [] for k in ("raw", "cv_min", "one_se", "ols", "stored")}
for m in L.MICE:
M, q, QQ, D, sets = pair_sets(m)
sel = M["synaptic_connection"] & ((D > 60) & (D < 400) if selnm != "all stored flags" else True)
for k in ("raw", "cv_min", "one_se", "ols"):
acc[k].append(LASSO[m][k][sel])
acc["stored"].append(-M["ipsp_amplitude_norm_per_presynaptic_spike"][sel])
acc = {k: np.concatenate(v) for k, v in acc.items()}
ok = np.isfinite(acc["stored"])
print(f"\n{selnm}: {len(acc['raw'])} pairs; rebuilt raw against stored amplitude R = {stats.pearsonr(acc['raw'][ok], acc['stored'][ok])[0]:.3f} "
f"({ok.sum()} with a stored amplitude); median rebuilt raw {np.median(acc['raw']):.4f}, stored {np.median(acc['stored'][ok]):.4f} SH per spike")
for k, nm in (("cv_min", "(a) least CV error"), ("one_se", "(b) one standard error"), ("ols", "least squares (variant)")):
w, r = acc[k], acc["raw"]
rr = stats.pearsonr(w, r) if np.ptp(w) > 0 else (np.nan, np.nan)
print(f" {nm}: corrected against raw R = {rr[0]:.3f} (p = {rr[1]:.2g}); differing by more than 20% of raw: "
f"{100*np.mean(np.abs(w - r) > 0.2 * np.abs(r)):.1f}%; set to zero {100*np.mean(w == 0):.1f}%; "
f"median ratio corrected / raw {np.median(w / r):.2f}")
# the paper compares the corrected matrix with the connectivity matrix, which is the stored amplitudes
st = acc["stored"][ok]
scale = np.median(st / acc["raw"][ok])
print(f" against the stored connectivity matrix ({ok.sum()} pairs; median ratio stored / rebuilt raw {scale:.2f}):")
for k, nm in (("raw", "rebuilt raw"), ("cv_min", "(a) least CV error"), ("one_se", "(b) one standard error"), ("ols", "least squares (variant)")):
w = acc[k][ok]
rr = stats.pearsonr(w, st) if np.ptp(w) > 0 else (np.nan, np.nan)
print(f" {nm}: R = {rr[0]:.3f} (p = {rr[1]:.2g}); differing from the stored by more than 20%: "
f"{100*np.mean(np.abs(w - st) > 0.2 * np.abs(st)):.1f}%, after scaling by the median ratio "
f"{100*np.mean(np.abs(scale * w - st) > 0.2 * np.abs(st)):.1f}%")
for m in L.MICE:
a = LASSO[m]["alphas"]
print(f"{m}: penalty (a) median {np.median(a[:, 0]):.2g}, (b) median {np.median(a[:, 1]):.2g}; off-target entries in S {LASSO[m]['offtarget'].sum()}")
M-YQ0201-27: 14400 pulses, 3 to 10 targets per pulse, each cell targeted 281 to 480 times; evoked spikes per pulse in non-targeted cells within 60 um of a target 0.375, 60 to 100 um 0.040, beyond 400 um 0.0038; targeted cells, stored estimate 2.38, detected 1.22
M-YQ0201-29: 14400 pulses, 4 to 10 targets per pulse, each cell targeted 243 to 480 times; evoked spikes per pulse in non-targeted cells within 60 um of a target 0.385, 60 to 100 um 0.041, beyond 400 um 0.0045; targeted cells, stored estimate 1.96, detected 0.93
pulses and fits in 474 s
all stored flags: 1755 pairs; rebuilt raw against stored amplitude R = 0.642 (1753 with a stored amplitude); median rebuilt raw -0.0183, stored -0.0297 SH per spike
(a) least CV error: corrected against raw R = 0.937 (p = 0); differing by more than 20% of raw: 71.9%; set to zero 18.9%; median ratio corrected / raw 0.65
(b) one standard error: corrected against raw R = 0.054 (p = 0.025); differing by more than 20% of raw: 100.0%; set to zero 99.9%; median ratio corrected / raw 0.00
least squares (variant): corrected against raw R = 0.970 (p = 0); differing by more than 20% of raw: 37.0%; set to zero 0.0%; median ratio corrected / raw 0.90
against the stored connectivity matrix (1753 pairs; median ratio stored / rebuilt raw 1.31):
rebuilt raw: R = 0.642 (p = 2.2e-204); differing from the stored by more than 20%: 69.5%, after scaling by the median ratio 59.3%
(a) least CV error: R = 0.609 (p = 1.6e-178); differing from the stored by more than 20%: 91.1%, after scaling by the median ratio 73.9%
(b) one standard error: R = 0.049 (p = 0.041); differing from the stored by more than 20%: 100.0%, after scaling by the median ratio 100.0%
least squares (variant): R = 0.618 (p = 7e-185); differing from the stored by more than 20%: 78.7%, after scaling by the median ratio 63.7%
flags 60 to 400 um: 1701 pairs; rebuilt raw against stored amplitude R = 0.807 (1699 with a stored amplitude); median rebuilt raw -0.0186, stored -0.0292 SH per spike
(a) least CV error: corrected against raw R = 0.912 (p = 0); differing by more than 20% of raw: 73.0%; set to zero 19.2%; median ratio corrected / raw 0.65
(b) one standard error: corrected against raw R = 0.062 (p = 0.011); differing by more than 20% of raw: 100.0%; set to zero 99.9%; median ratio corrected / raw 0.00
least squares (variant): corrected against raw R = 0.960 (p = 0); differing by more than 20% of raw: 37.4%; set to zero 0.0%; median ratio corrected / raw 0.90
against the stored connectivity matrix (1699 pairs; median ratio stored / rebuilt raw 1.31):
rebuilt raw: R = 0.807 (p = 0); differing from the stored by more than 20%: 68.6%, after scaling by the median ratio 58.4%
(a) least CV error: R = 0.779 (p = 0); differing from the stored by more than 20%: 90.9%, after scaling by the median ratio 72.9%
(b) one standard error: R = 0.051 (p = 0.037); differing from the stored by more than 20%: 100.0%, after scaling by the median ratio 100.0%
least squares (variant): R = 0.779 (p = 0); differing from the stored by more than 20%: 78.1%, after scaling by the median ratio 62.9%
M-YQ0201-27: penalty (a) median 0.00048, (b) median 0.0077; off-target entries in S 201535
M-YQ0201-29: penalty (a) median 0.0006, (b) median 0.0052; off-target entries in S 196125
Result: not reproduced, resting on assumptions. The rebuilt raw matrix only partly matches the stored IPSPs: R = 0.642 with the stored amplitudes over the 1,753 flagged pairs that have one (0.807 over those 60 to 400 um), and its median is -0.0183 SH per spike against the stored -0.0297. Against its own raw matrix, the corrected matrix of reading (a) correlates at R = 0.937 (0.912 for 60 to 400 um), above 0.82 +/- 0.082, and 71.9% of the pairs differ by more than 20% (18.9% are set to zero), not under 22%. Against the stored connectivity matrix, the paper's comparison, reading (a) gives R = 0.609 (0.779 for 60 to 400 um, inside the tolerance) and 91.1% of pairs differing by more than 20% (73.9% after scaling by the median ratio 1.31). Under reading (b) the penalty sets 99.9% of the coefficients to zero (R = 0.054 with the raw, 0.049 with the stored). Without a penalty the correction still moves 37.0% of the pairs by more than 20% of the raw (R = 0.970). The fraction of changed pairs is far above 22% under every reading and either comparison. The per-pulse response window and the treatment of off-target spikes are assumptions (the paper gives neither), and the rebuilt raw matrix differs from the stored one, so the failure may come from the reconstruction.
connection-distance-structure¶
Synaptic connectivity had an exponential degree distribution, a connection probability of 24% for cells under 150 um apart and a length constant of about 105 um; gap junction probability was 83% under 150 um with a 159 um length constant.
Probability = connected over tested ordered QC pairs, by distance, both mice pooled (per mouse shown). Probability under 150 um over pairs from 0 um (synaptic) or 60 um (gap junction) to 150 um. Length constant: readings (a) A exp(-r/lambda) by least squares on binned probability, (b) a line on log probability; bins of 30 or 60 um, from 60 um (gap) or 0 um (synaptic) to 400 um. Degree distribution: exponential when an exponential fits the in- and out-degree histograms better than a power law (lower residual on log counts).
def binned_prob(kind, lo, width, mice=L.MICE):
edges = np.arange(lo, 400 + 1e-9, width)
if edges[-1] < 400:
edges = np.append(edges, 400)
conn = np.zeros(len(edges) - 1)
tot = np.zeros(len(edges) - 1)
for m in mice:
M, q, QQ, D, sets = pair_sets(m)
C = M["synaptic_connection" if kind == "syn" else "gap_junction_connection"]
T = QQ & (D <= 400)
for i in range(len(edges) - 1):
b = T & (D >= edges[i]) & (D < edges[i + 1])
conn[i] += (C & b).sum()
tot[i] += b.sum()
return (edges[:-1] + edges[1:]) / 2, conn / np.maximum(tot, 1), tot
res = []
for kind, lo in [("syn", 0), ("gap", 60)]:
for mice, lab_ in [(L.MICE, "pooled"), (("M-YQ0201-27",), "M-YQ0201-27"), (("M-YQ0201-29",), "M-YQ0201-29")]:
_, p150, _ = binned_prob(kind, lo, 150 - lo, mice)
for width in (30, 60):
r, p, n = binned_prob(kind, lo, width, mice)
try:
lam_a = L.exp_fit_least_squares(r, p)[1]
except Exception:
lam_a = np.nan
lam_b = L.exp_length_constant_loglinear(r, p)
res.append(dict(kind=kind, mice=lab_, bin_um=width, p_under_150=100 * p150[0], lambda_a=lam_a, lambda_b=lam_b))
res = pd.DataFrame(res)
print(res.round(1).to_string())
r, p, n = binned_prob("syn", 0, 30)
print("\nsynaptic probability by 30 um bin (pooled):", dict(zip(r.round(0), (100 * p).round(1))))
r, p, n = binned_prob("gap", 60, 30)
print("gap junction probability by 30 um bin (pooled):", dict(zip(r.round(0), (100 * p).round(1))))
# degree distributions (synaptic, 60 to 400 um band is not imposed here: all tested pairs within 400 um)
def fit_compare(deg):
vals, cnt = np.unique(deg, return_counts=True)
ok = (vals > 0) & (cnt > 0)
x, y = vals[ok], np.log(cnt[ok])
e = np.polyfit(x, y, 1)
pw = np.polyfit(np.log(x), y, 1)
re_ = np.sum((y - np.polyval(e, x)) ** 2)
rp = np.sum((y - np.polyval(pw, np.log(x))) ** 2)
return re_, rp
for m in L.MICE:
M, q, QQ, D, sets = pair_sets(m)
S = M["synaptic_connection"] & sets["within 400 um"]
for nm, deg in [("out", S.sum(1)[q]), ("in", S.sum(0)[q])]:
re_, rp = fit_compare(deg)
print(f"{m} {nm}-degree: residual on log counts, exponential {re_:.2f}, power law {rp:.2f} -> "
f"{'exponential' if re_ < rp else 'power law'} fits better; {np.sum(deg == 0)} cells with degree 0 left out of both fits")
kind mice bin_um p_under_150 lambda_a lambda_b
0 syn pooled 30 23.5 285.4 175.8
1 syn pooled 60 23.5 288.2 180.1
2 syn M-YQ0201-27 30 26.7 270.1 157.0
3 syn M-YQ0201-27 60 26.7 254.5 151.1
4 syn M-YQ0201-29 30 20.0 313.2 204.2
5 syn M-YQ0201-29 60 20.0 362.1 235.6
6 gap pooled 30 83.0 184.7 156.2
7 gap pooled 60 83.0 183.6 160.9
8 gap M-YQ0201-27 30 91.8 213.2 171.3
9 gap M-YQ0201-27 60 91.8 209.9 175.0
10 gap M-YQ0201-29 30 73.8 151.9 138.2
11 gap M-YQ0201-29 60 73.8 152.9 143.9
synaptic probability by 30 um bin (pooled): {np.float64(15.0): np.float64(16.7), np.float64(45.0): np.float64(14.2), np.float64(75.0): np.float64(23.0), np.float64(105.0): np.float64(28.9), np.float64(135.0): np.float64(22.4), np.float64(165.0): np.float64(21.5), np.float64(195.0): np.float64(14.5), np.float64(225.0): np.float64(11.5), np.float64(255.0): np.float64(8.3), np.float64(285.0): np.float64(6.0), np.float64(315.0): np.float64(4.4), np.float64(345.0): np.float64(4.0), np.float64(375.0): np.float64(3.5), np.float64(395.0): np.float64(2.8)}
gap junction probability by 30 um bin (pooled): {np.float64(75.0): np.float64(92.5), np.float64(105.0): np.float64(85.4), np.float64(135.0): np.float64(75.8), np.float64(165.0): np.float64(65.9), np.float64(195.0): np.float64(57.9), np.float64(225.0): np.float64(44.8), np.float64(255.0): np.float64(39.0), np.float64(285.0): np.float64(30.6), np.float64(315.0): np.float64(24.7), np.float64(345.0): np.float64(20.6), np.float64(375.0): np.float64(15.7), np.float64(395.0): np.float64(11.3)}
M-YQ0201-27 out-degree: residual on log counts, exponential 1.46, power law 2.23 -> exponential fits better; 72 cells with degree 0 left out of both fits
M-YQ0201-27 in-degree: residual on log counts, exponential 3.84, power law 4.38 -> exponential fits better; 59 cells with degree 0 left out of both fits
M-YQ0201-29 out-degree: residual on log counts, exponential 4.42, power law 4.16 -> power law fits better; 83 cells with degree 0 left out of both fits
M-YQ0201-29 in-degree: residual on log counts, exponential 2.50, power law 4.17 -> exponential fits better; 62 cells with degree 0 left out of both fits
Result: partially reproduced. The probabilities under 150 um match: 23.5% for synaptic connections (24 +/- 2.4%) and 83.0% for gap junctions (83 +/- 8.3%). The gap-junction length constant matches under the log-linear reading (156 um with 30 um bins, 161 um with 60 um bins; expected 159 +/- 15.9); the least-squares exponential gives 184 um. The synaptic length constant does not match under any reading: 176 to 180 um log-linear and 285 to 288 um least squares, against 105 +/- 10.5 um (per mouse 151 to 362 um); the synaptic probability rises from 17% at 0 to 30 um to 29% at 90 to 120 um before it falls. The exponential degree fit is better for three of the four degree distributions (the out-degree of M-YQ0201-29 fits a power law better).
fig3eg-amplitude-falls-with-distance¶
IPSP and spikelet amplitudes both decay with the distance between the cells.
As the code (panels E and G): IPSP pairs with stored amplitude above 1e-3 (no significance gate), spikelet pairs all, QC cells, 60 to 400 um, six equal bins (linspace(60, 400, 7)), per mouse. Spearman correlation of amplitude with distance (test chosen in the claims file). The connected-only selection is a variant.
edges = np.linspace(60, 400, 7)
for variant in ["code selection", "connected pairs only"]:
print(variant)
for m in L.MICE:
M, q, QQ, D, sets = pair_sets(m)
for kind in ["ipsp", "spikelet"]:
if kind == "ipsp":
v = M["ipsp_amplitude_norm_per_presynaptic_spike"]
valid = (v > 1e-3) if variant == "code selection" else M["synaptic_connection"]
else:
v = M["spikelet_amplitude_normalized"]
valid = np.ones_like(v, bool) if variant == "code selection" else M["gap_junction_connection"]
# code: figure cells are the QC cells; pairs strictly between 60 and 400 um
valid = valid & QQ & (D > 60) & (D < 400) & np.isfinite(v)
meds = [np.median(v[valid & (D >= edges[i]) & (D < edges[i + 1])]) for i in range(6)]
rho, p = stats.spearmanr(D[valid], v[valid])
print(f" {m} {kind:8s} n = {valid.sum():5d}; bin medians {np.round(meds, 4)}; Spearman rho = {rho:.3f}, p = {p:.2g}")
code selection M-YQ0201-27 ipsp n = 6326; bin medians [0.0196 0.0127 0.0096 0.0088 0.0077 0.0068]; Spearman rho = -0.245, p = 3.1e-87 M-YQ0201-27 spikelet n = 7280; bin medians [0.0281 0.0138 0.0083 0.005 0.0032 0.0021]; Spearman rho = -0.579, p = 0 M-YQ0201-29 ipsp n = 6223; bin medians [0.0147 0.0129 0.0106 0.01 0.0094 0.0097]; Spearman rho = -0.116, p = 5.4e-20 M-YQ0201-29 spikelet n = 7032; bin medians [0.0217 0.0109 0.0063 0.0041 0.0027 0.0018]; Spearman rho = -0.454, p = 0 connected pairs only M-YQ0201-27 ipsp n = 800; bin medians [0.0386 0.0363 0.0265 0.0193 0.0205 0.0144]; Spearman rho = -0.450, p = 3.4e-41 M-YQ0201-27 spikelet n = 3553; bin medians [0.0289 0.0154 0.0111 0.0091 0.0077 0.0065]; Spearman rho = -0.608, p = 0 M-YQ0201-29 ipsp n = 667; bin medians [0.0389 0.0315 0.0279 0.0247 0.0225 0.0218]; Spearman rho = -0.341, p = 1.3e-19 M-YQ0201-29 spikelet n = 2199; bin medians [0.026 0.0149 0.0118 0.01 0.0096 0.0096]; Spearman rho = -0.553, p = 3.9e-176
Result: reproduced. In both mice and for both measures the median in the nearest bin exceeds that in the farthest (IPSP 0.0196 against 0.0068 and 0.0147 against 0.0097 SH; spikelet 0.0281 against 0.0021 and 0.0217 against 0.0018), and the Spearman correlation with distance is negative (rho -0.12 to -0.58, every p below 1e-19). Connected pairs alone give the same result (rho -0.34 to -0.61).
fig3h-conduction-speed¶
Spikelet peak times increase with distance, giving a conduction speed of 0.28 m/s, consistent across two mice.
As the code (panel H, legacySpeedFit and pooledSpeedFit): mean Hadamard cross-spike STA of all QC pairs in twelve 30 um bins from 60 to 420 um, each bin's time mean subtracted; coarse peak within 16 frames of lag 0; cubic fitted over frames -2 to +4 around it, its maximum on a fine grid; delay at 1.27 ms per frame; distance regressed on delay, pooling both mice. The caption's ten 30 um bins (60 to 360 um) are a variant.
def speed_fit(traces, centers):
nT = traces.shape[0]
c0 = nT // 2 # zero lag (MATLAB ceil(nT/2), 1-based)
tau = np.arange(nT) - c0
delays = np.full(traces.shape[1], np.nan)
for i in range(traces.shape[1]):
loc = np.zeros(nT)
w = slice(max(0, c0 - 16), min(nT, c0 + 17))
loc[w] = traces[w, i]
pk = int(np.argmax(loc))
ff = pk + np.arange(-2, 5)
if ff.min() < 0 or ff.max() >= nT:
continue
co = np.polyfit(tau[ff], traces[ff, i], 3)
grid = np.linspace(-2, 4, 10000)
delays[i] = grid[np.argmax(np.polyval(co, grid))] * L.DT
return delays
HSTA = {}
fits = {}
for m in L.MICE:
M, q, QQ, D, sets = pair_sets(m)
H = L.pair_series(m, "hadamard_cross_spike_sta")
HSTA[m] = H
QQd = q[:, None] & q[None, :] # the code's figure cells include the diagonal; it falls in no bin from 60 um
for nm, ed in [("code, 12 bins 60-420 um", np.arange(60, 421, 30)), ("caption, 10 bins 60-360 um", np.arange(60, 361, 30))]:
cen = (ed[:-1] + ed[1:]) / 2
tr = np.zeros((H.shape[2], len(cen)))
for i in range(len(cen)):
mk = QQd & (D >= ed[i]) & (D < ed[i + 1])
tr[:, i] = np.nanmean(H[mk], axis=0)
tr = tr - tr.mean(0)
dl = speed_fit(tr, cen)
fits[m, nm] = (dl, cen)
for nm in ["code, 12 bins 60-420 um", "caption, 10 bins 60-360 um"]:
dl = np.concatenate([fits[m, nm][0] for m in L.MICE])
cc = np.concatenate([fits[m, nm][1] for m in L.MICE])
ok = np.isfinite(dl)
sp = np.polyfit(dl[ok], cc[ok], 1)[0] / 1e6
per = []
for m in L.MICE:
d1, c1 = fits[m, nm]
o1 = np.isfinite(d1)
per.append(np.polyfit(d1[o1], c1[o1], 1)[0] / 1e6)
print(f"{nm}: pooled speed {sp:.3f} m/s; per mouse {np.round(per, 3)}; delays (ms) 27 {np.round(fits['M-YQ0201-27', nm][0]*1e3, 2)}, "
f"29 {np.round(fits['M-YQ0201-29', nm][0]*1e3, 2)}")
code, 12 bins 60-420 um: pooled speed 0.265 m/s; per mouse [0.255 0.291]; delays (ms) 27 [0.35 0.37 0.56 0.8 0.85 0.99 0.99 1.12 1.19 1.38 1.52 1.63], 29 [0.51 0.51 0.68 0.95 0.97 1.15 1.16 1.31 1.39 1.38 1.38 1.57] caption, 10 bins 60-360 um: pooled speed 0.248 m/s; per mouse [0.258 0.261]; delays (ms) 27 [0.35 0.37 0.56 0.8 0.85 0.99 0.99 1.12 1.19 1.38], 29 [0.51 0.51 0.68 0.95 0.97 1.15 1.16 1.31 1.39 1.38]
Result: reproduced. With the code's twelve 30 um bins from 60 to 420 um the pooled speed is 0.265 m/s, within 0.028 of 0.28 (0.255 and 0.291 m/s per mouse). The caption's ten bins give 0.248 m/s pooled (0.258 and 0.261 per mouse), outside the tolerance.
amplitudes-log-normal¶
IPSP and spikelet amplitudes both follow approximately log-normal distributions.
Amplitudes of connected pairs, both mice pooled. The selection is the claims file's shared method: QC cells, and pairs under 60 um left out of the gap-junction analyses (Results, Gap junction coupling, paragraph 4), so connected QC pairs 60 to 400 um, the pairs of Supplementary Figure 19's neighbouring panels (the code's band, 1,467 synaptic and 5,752 gap-junction pairs). All stored flags and QC pairs within 400 um are shown as variants. Reading chosen in the claims file: skewness of log amplitudes within -0.5 to 0.5 and skewness of raw amplitudes above 1.
for selnm in ("QC 60 to 400 um", "QC within 400 um", "all stored flags"):
print(selnm)
for kind, col, flag in [("IPSP", "ipsp_amplitude_norm_per_presynaptic_spike", "synaptic_connection"),
("spikelet", "spikelet_amplitude_normalized", "gap_junction_connection")]:
per = []
for m in L.MICE:
M, q, QQ, D, sets = pair_sets(m)
T = {"QC 60 to 400 um": sets["60 to 400 um"], "QC within 400 um": sets["within 400 um"],
"all stored flags": np.ones_like(QQ)}[selnm]
w = M[col][M[flag] & T]
per.append(w[np.isfinite(w)])
v = np.concatenate(per)
pos = v[v > 0]
print(f" {kind}: n = {len(v)} connected pairs, {len(v) - len(pos)} with amplitude <= 0 left out of the log; "
f"skewness raw {stats.skew(v):.2f}, log {stats.skew(np.log(pos)):.2f}")
for m, w in zip(L.MICE, per):
w = w[w > 0]
print(f" {m}: n = {len(w)}, skewness raw {stats.skew(w):.2f}, log {stats.skew(np.log(w)):.2f}")
QC 60 to 400 um
IPSP: n = 1467 connected pairs, 0 with amplitude <= 0 left out of the log; skewness raw 2.46, log 0.13
M-YQ0201-27: n = 800, skewness raw 1.50, log 0.00
M-YQ0201-29: n = 667, skewness raw 3.31, log 0.34
spikelet: n = 5752 connected pairs, 0 with amplitude <= 0 left out of the log; skewness raw 3.15, log 0.41
M-YQ0201-27: n = 3553, skewness raw 3.19, log 0.43
M-YQ0201-29: n = 2199, skewness raw 3.04, log 0.49
QC within 400 um
IPSP: n = 1505 connected pairs, 0 with amplitude <= 0 left out of the log; skewness raw 2.41, log 0.12
M-YQ0201-27: n = 826, skewness raw 1.56, log -0.00
M-YQ0201-29: n = 679, skewness raw 3.26, log 0.31
spikelet: n = 6006 connected pairs, 0 with amplitude <= 0 left out of the log; skewness raw 4.68, log 0.70
M-YQ0201-27: n = 3697, skewness raw 4.62, log 0.71
M-YQ0201-29: n = 2309, skewness raw 4.77, log 0.81
all stored flags
IPSP: n = 1753 connected pairs, 0 with amplitude <= 0 left out of the log; skewness raw 2.21, log 0.10
M-YQ0201-27: n = 953, skewness raw 1.53, log -0.03
M-YQ0201-29: n = 800, skewness raw 3.03, log 0.29
spikelet: n = 7443 connected pairs, 0 with amplitude <= 0 left out of the log; skewness raw 4.64, log 0.73
M-YQ0201-27: n = 4516, skewness raw 4.53, log 0.73
M-YQ0201-29: n = 2927, skewness raw 4.83, log 0.86
Result: reproduced. With the claims file's selection (QC pairs 60 to 400 um), IPSP amplitudes have skewness 2.46 raw and 0.13 on the log scale (1,467 pairs) and spikelet amplitudes 3.15 and 0.41 (5,752 pairs; 0.43 and 0.49 per mouse), both inside the chosen reading. Pairs under 60 um carry the lack of fit: with them, the spikelet log skewness is 0.70 (QC pairs within 400 um) and 0.73 (all stored flags), outside it.
interaction-kernel¶
The population-average effect of one L1 spike is a brief excitatory pulse of about 2 ms spreading at 0.28 m/s with a decay length of about 160 um, followed by inhibition that peaks around 30 ms and decays with a time constant of about 35 ms.
The claims file's reading (the paper gives no method for Supplementary Movie 3). Inhibition: the
population-average IPSP waveform per presynaptic spike, blue_pulse_ipsp_waveform minus
blue_light_crosstalk_estimate, with unconnected pairs counted as zero (code panel 3F), over QC
pairs 60 to 400 um, both mice. Peak time from (a) pulse onset or (b) pulse end (20 ms pulses,
Methods); decay from an exponential fitted from the peak to the end of the stored window
(+178 ms). Excitation: the population-average Hadamard cross-spike STA (code panel 3H, time mean
subtracted), full width at half maximum of the peak at lag 0, and the length constant of
connection probability times mean spikelet amplitude by 30 um bin, readings as in
connection-distance-structure. The 0.28 m/s is the claim fig3h-conduction-speed.
from scipy.optimize import curve_fit
lag_t = (np.arange(281) - 140) * L.DT
ipsp_tr = []
sp_tr = []
for m in L.MICE:
M, q, QQ, D, sets = pair_sets(m)
W = L.pair_series(m, "blue_pulse_ipsp_waveform") - L.pair_series(m, "blue_light_crosstalk_estimate")
band = sets["60 to 400 um"]
Wm = np.where(M["synaptic_connection"][:, :, None], W, 0.0)
ipsp_tr.append(np.nanmean(Wm[band], axis=0))
H = HSTA[m]
sp_tr.append(np.nanmean(H[band], axis=0))
del W, Wm
ipsp_pop = np.mean(ipsp_tr, axis=0)
sp_pop = np.mean(sp_tr, axis=0)
sp_pop = sp_pop - sp_pop.mean()
post = lag_t >= 0.02 # after the pulse (the blue pulse lasts 20 ms)
ipk = np.nonzero(post)[0][np.argmin(ipsp_pop[post])]
print(f"IPSP minimum {ipsp_pop[ipk]:.5f} SH at {lag_t[ipk]*1e3:.1f} ms after pulse onset, {lag_t[ipk]*1e3 - 20:.1f} ms after pulse end")
for m, tr in zip(L.MICE, ipsp_tr):
k = np.nonzero(post)[0][np.argmin(tr[post])]
print(f" {m}: minimum at {lag_t[k]*1e3:.1f} ms after onset")
tt = lag_t[ipk:] - lag_t[ipk]
yy = ipsp_pop[ipk:]
popt, _ = curve_fit(lambda t, a, tau, c: a * np.exp(-t / tau) + c, tt, yy, p0=[yy[0], 0.03, 0], maxfev=20000)
popt0, _ = curve_fit(lambda t, a, tau: a * np.exp(-t / tau), tt, yy, p0=[yy[0], 0.03], maxfev=20000)
print(f"decay time constant after the peak: {popt[1]*1e3:.1f} ms with an offset, {popt0[1]*1e3:.1f} ms without "
f"(fit over {tt[-1]*1e3:.0f} ms)")
# excitatory pulse: FWHM of the population spikelet around lag 0
c0 = 140
w = slice(c0 - 16, c0 + 17)
pk = c0 - 16 + int(np.argmax(sp_pop[w]))
def fwhm(base):
half = base + (sp_pop[pk] - base) / 2
lo_i = pk
while lo_i > 0 and sp_pop[lo_i] > half:
lo_i -= 1
hi_i = pk
while hi_i < 280 and sp_pop[hi_i] > half:
hi_i += 1
# linear interpolation of the two half crossings
x_lo = lo_i + (half - sp_pop[lo_i]) / (sp_pop[lo_i + 1] - sp_pop[lo_i])
x_hi = hi_i - 1 + (sp_pop[hi_i - 1] - half) / (sp_pop[hi_i - 1] - sp_pop[hi_i])
return x_hi - x_lo
print(f"spikelet population peak {sp_pop[pk]:.5f} SH at lag {pk - c0} frames")
# baselines: lags beyond +/-40 frames (main), and the flanks of the spikelet used for its amplitude
# (frames -4 to -2 and 4 to 6, Methods, Analysis for mapping gap junction connections), which sit on
# the slow hump of the waveform
for nm, base in [("median of lags beyond +/-40 frames", np.median(sp_pop[np.r_[0:100, 181:281]])),
("mean of frames -4 to -2 and 4 to 6", sp_pop[np.r_[c0 - 4:c0 - 1, c0 + 4:c0 + 7]].mean())]:
w_ = fwhm(base)
print(f" baseline {nm} ({base:.5f}): FWHM {w_ * L.DT * 1e3:.2f} ms ({w_:.2f} frames)")
# decay length of probability x mean spikelet amplitude
ed = np.arange(60, 401, 30)
cen = (ed[:-1] + ed[1:]) / 2
prod = np.zeros(len(cen))
for i in range(len(cen)):
c_, t_, s_ = 0, 0, 0.0
for m in L.MICE:
M, q, QQ, D, sets = pair_sets(m)
b = sets["within 400 um"] & (D >= ed[i]) & (D < ed[i + 1])
G = M["gap_junction_connection"] & b
c_ += G.sum(); t_ += b.sum(); s_ += M["spikelet_amplitude_normalized"][G].sum()
prod[i] = (c_ / t_) * (s_ / c_)
print("probability x mean spikelet amplitude by bin:", dict(zip(cen, prod.round(5))))
print(f"length constant: (a) least squares {L.exp_fit_least_squares(cen, prod)[1]:.0f} um, (b) log-linear {L.exp_length_constant_loglinear(cen, prod):.0f} um")
IPSP minimum -0.00314 SH at 33.0 ms after pulse onset, 13.0 ms after pulse end
M-YQ0201-27: minimum at 33.0 ms after onset
M-YQ0201-29: minimum at 30.5 ms after onset
decay time constant after the peak: 39.4 ms with an offset, 47.9 ms without (fit over 145 ms)
spikelet population peak 0.02595 SH at lag 1 frames
baseline median of lags beyond +/-40 frames (-0.00093): FWHM 22.73 ms (17.90 frames)
baseline mean of frames -4 to -2 and 4 to 6 (0.01421): FWHM 4.94 ms (3.89 frames)
probability x mean spikelet amplitude by bin: {np.float64(75.0): np.float64(0.03795), np.float64(105.0): np.float64(0.0221), np.float64(135.0): np.float64(0.01403), np.float64(165.0): np.float64(0.01008), np.float64(195.0): np.float64(0.00797), np.float64(225.0): np.float64(0.00511), np.float64(255.0): np.float64(0.00431), np.float64(285.0): np.float64(0.00308), np.float64(315.0): np.float64(0.00236), np.float64(345.0): np.float64(0.00189), np.float64(375.0): np.float64(0.00144)}
length constant: (a) least squares 72 um, (b) log-linear 96 um
Result: not reproduced. The inhibition peaks 33.0 ms after pulse onset (13.0 ms after its end; 33.0 and 30.5 ms per mouse), within 3 ms of 30 ms under reading (a), and decays with 39.4 ms (fit with an offset) or 47.9 ms (without) against 35 +/- 3.5 ms. The population spikelet waveform has a full width at half maximum of 22.7 ms with the far-lag baseline, and 4.94 ms with the spikelet's own flanking frames as baseline, not about 2 ms either way, and the length constant of probability times amplitude is 72 um (least squares) or 96 um (log-linear) against 160 +/- 16 um. Two of the four values are outside tolerance under every reading. The paper gives no method for this claim; the measures are the claims file's readings.
fig3jk-presynaptic-sets-amplitude and fig3mn-postsynaptic-sets-decay¶
IPSP amplitude of a pair is strongly correlated with the presynaptic cell's mean output to other cells (R = 0.61) and only weakly with the postsynaptic cell's mean input from other cells (R = 0.26).
IPSP decay time constant is correlated with the mean time constant of other inputs to the postsynaptic cell (R = 0.33) and not with that of the presynaptic cell's other outputs (R = 0.07, p = 0.06).
As the code (reproduce_figure3_from_nwb.m, calculatePrePostComparisons and plotLogComparison): QC cells; mask = synaptic_connection, 60 < d < 400 um, tauSE/tau below its 90th percentile over all pairs with a defined value (MATLAB prctile, which interpolates between midpoints), and tau inside [min(tau > 0) + 1e-3, max(tau) - 1e-3]; leave-one-out means over the masked pairs of the same presynaptic (J, M) or postsynaptic (K, N) cell; Pearson R on natural logs of pairs with both values positive and finite. Amplitude on M-YQ0201-29 and decay on M-YQ0201-27, as the code.
matlab_prctile = L.matlab_prctile
def prepost(m, kind, use_tau_mask=True):
M, q, QQ, D, sets = pair_sets(m)
qi = np.nonzero(q)[0]
sub = lambda X: X[np.ix_(qi, qi)]
S = sub(M["synaptic_connection"]); tau = sub(M["ipsp_decay_source_units"]); se = sub(M["ipsp_decay_standard_error_source_units"])
d = sub(D)
with np.errstate(invalid="ignore", divide="ignore"):
snr = se / tau
lim = (tau[tau > 0].min() + 1e-3, tau.max() - 1e-3)
mask = S & (d < 400) & (d > 60)
if use_tau_mask:
mask = mask & (snr < matlab_prctile(snr.ravel(), 90)) & (tau > lim[0]) & (tau < lim[1])
vals = sub(M["ipsp_amplitude_norm_per_presynaptic_spike"]) if kind == "amplitude" else tau
if kind == "spikelet":
G = sub(M["gap_junction_connection"])
mask = G & (d < 400) & (d > 60)
vals = sub(M["spikelet_amplitude_normalized"])
wv = np.where(mask, vals, np.nan)
n = len(qi)
pre_avg = np.full((n, n), np.nan); post_avg = np.full((n, n), np.nan)
with np.errstate(invalid="ignore"):
for c in range(n):
other = np.r_[0:c, c + 1:n]
pre_avg[:, c] = np.nanmean(wv[:, other], axis=1) # same presynaptic cell, other targets
post_avg[c, :] = np.nanmean(wv[other, :], axis=0) # same postsynaptic cell, other inputs
out = {}
for nm, avg in [("outgoing (presynaptic mean)", pre_avg), ("incoming (postsynaptic mean)", post_avg)]:
x, y = avg[mask], vals[mask]
ok = np.isfinite(x) & np.isfinite(y) & (x > 0) & (y > 0)
r, p = stats.pearsonr(np.log(x[ok]), np.log(y[ok]))
out[nm] = (r, p, int(mask.sum()), int(ok.sum()))
return out
import warnings
warnings.filterwarnings("ignore", category=RuntimeWarning)
for claim, m, kind in [("fig3jk (amplitude)", "M-YQ0201-29", "amplitude"), ("fig3mn (decay)", "M-YQ0201-27", "tau")]:
print(claim, m)
for nm, (r, p, nmask, nok) in prepost(m, kind).items():
print(f" {nm}: R = {r:.3f}, p = {p:.3g}, mask n = {nmask}, plotted n = {nok}")
other = "M-YQ0201-27" if m == "M-YQ0201-29" else "M-YQ0201-29"
for nm, (r, p, nmask, nok) in prepost(other, kind).items():
print(f" other mouse {other}, {nm}: R = {r:.3f}, p = {p:.3g}, n = {nok}")
fig3jk (amplitude) M-YQ0201-29 outgoing (presynaptic mean): R = 0.609, p = 1.05e-51, mask n = 561, plotted n = 497 incoming (postsynaptic mean): R = 0.263, p = 4.34e-09, mask n = 561, plotted n = 482
other mouse M-YQ0201-27, outgoing (presynaptic mean): R = 0.419, p = 3.55e-29, n = 653 other mouse M-YQ0201-27, incoming (postsynaptic mean): R = 0.360, p = 2.37e-21, n = 651 fig3mn (decay) M-YQ0201-27 outgoing (presynaptic mean): R = 0.075, p = 0.0562, mask n = 706, plotted n = 653 incoming (postsynaptic mean): R = 0.330, p = 4.71e-18, mask n = 706, plotted n = 651
other mouse M-YQ0201-29, outgoing (presynaptic mean): R = 0.118, p = 0.00841, n = 497 other mouse M-YQ0201-29, incoming (postsynaptic mean): R = 0.230, p = 3.17e-07, n = 482
Result: reproduced (both claims). On M-YQ0201-29 the amplitude correlations are R = 0.609 (p = 1.05e-51, 497 plotted pairs) with the presynaptic cell's mean output and R = 0.263 (p = 4.3e-9, 482 pairs) with the postsynaptic cell's mean input, the code's mask n = 561 and the paper's 0.61, 0.26 and n exactly. On M-YQ0201-27 the decay correlations are R = 0.330 (p = 4.7e-18, 651 pairs) with the postsynaptic mean and R = 0.075 (p = 0.056, 653 pairs) with the presynaptic mean, not significant, as the paper reports; mask n = 706. In the other mouse the orderings hold but the values differ (amplitude 0.42 against 0.36; decay outgoing R = 0.12, p = 0.008).
fig3lo-variance-components¶
A linear mixed-effects model attributes more variance of IPSP amplitude to presynaptic than to postsynaptic identity, and more variance of IPSP decay time constant to postsynaptic than to presynaptic identity, each ordering holding in all but under 0.1% of bootstrap simulations.
As the code's tutorial 5 (tutorial5a_amplitudeVariance.m, tutorial5b_decayVariance.m): connected
QC pairs of both mice at 60 um or more with positive response; log response ~ 1 + animal +
distance term + (1|pre) + (1|post); the distance term (distance minus, or log of distance over, the
median distance of all measured QC pairs) chosen by AIC of ML fits; REML; for decay, weights
1/(SE_log^2 + s0^2) normalized to mean 1, with SE_log = SE/tau (delta method) and s0^2 the
unweighted residual variance minus the median SE_log^2; 2000 parametric bootstrap refits with
seeds 12012 (amplitude) and 12014 (decay). The model is fitted with the helper's CrossedLMM
(fitlme is MATLAB-only); numpy's generator replaces MATLAB's.
def lme_table(col):
rows, dall = [], []
for m in L.MICE:
M, q, QQ, D, sets = pair_sets(m)
v = M[col].copy()
v[D < 60] = np.nan
meas = QQ & np.isfinite(v)
dall.append(D[meas & (D > 0)])
S = M["synaptic_connection"] & meas & (v > 0)
for a, b in zip(*np.nonzero(S)):
rows.append(dict(animal=m, pre=f"{m}_{a}", post=f"{m}_{b}", d=D[a, b], resp=v[a, b],
se=M["ipsp_decay_standard_error_source_units"][a, b]))
t = pd.DataFrame(rows)
return t, np.median(np.concatenate(dall))
LME = {}
for kind, col, seed in [("amplitude", "ipsp_amplitude_norm_per_presynaptic_spike", 12012), ("decay", "ipsp_decay_source_units", 12014)]:
t, dref = lme_table(col)
if kind == "decay":
t["selog"] = t.se / t.resp
t = t[np.isfinite(t.selog) & (t.selog > 0)].reset_index(drop=True)
y = np.log(t.resp.values)
an = (t.animal == L.MICE[1]).astype(float).values
Xs = {"linear distance": np.column_stack([np.ones(len(t)), an, t.d - dref]),
"log distance": np.column_stack([np.ones(len(t)), an, np.log(t.d / dref)])}
aic = {k: L.CrossedLMM(y, X, t.pre.values, t.post.values).fit(reml=False)["aic"] for k, X in Xs.items()}
form = min(aic, key=aic.get)
X = Xs[form]
w = None
if kind == "decay":
un = L.CrossedLMM(y, X, t.pre.values, t.post.values).fit()
mv = t.selog.values ** 2
s0 = max(0.0, un["s2_resid"] - np.median(mv))
w = 1 / (mv + s0)
w = w / w.mean()
print(f"decay weights: unweighted residual variance {un['s2_resid']:.3f}, median measurement variance {np.median(mv):.3f}, "
f"s0^2 = {s0:.3f}, effective n {w.sum()**2 / (w**2).sum():.0f} of {len(w)}")
model = L.CrossedLMM(y, X, t.pre.values, t.post.values, w)
fit = model.fit()
tb = time.time()
boot = L.bootstrap_variances(model, fit, 2000, seed)
LME[kind] = (fit, boot)
ok = boot[:, 3] == 1
print(f"{kind}: {len(t)} pairs ({t.groupby('animal').size().to_dict()}), {t.pre.nunique()} presynaptic and {t.post.nunique()} "
f"postsynaptic cells; AIC {({k: round(v, 1) for k, v in aic.items()})} -> {form}")
print(f" REML variances: pre {fit['s2_pre']:.4f}, post {fit['s2_post']:.4f}, residual {fit['s2_resid']:.4f}")
frac_pre = np.mean(boot[ok, 0] > boot[ok, 1])
print(f" bootstrap ({ok.sum()} of {len(boot)} refits converged, {time.time() - tb:.0f} s): pre > post in {100*frac_pre:.2f}%, "
f"post > pre in {100*(1-frac_pre):.2f}%; 95% interval of pre - post "
f"[{np.percentile(boot[ok,0]-boot[ok,1], 2.5):.4f}, {np.percentile(boot[ok,0]-boot[ok,1], 97.5):.4f}]")
# every refit, the non-converged ones included: as fitted, and refitted from the grid start
bad = ~ok
pre2 = np.where(bad, boot[:, 4], boot[:, 0]); post2 = np.where(bad, boot[:, 5], boot[:, 1])
adverse = (lambda a, b: a <= b) if kind == "amplitude" else (lambda a, b: a >= b)
print(f" all {len(boot)} refits as fitted: adverse ordering in {adverse(boot[:, 0], boot[:, 1]).sum()} "
f"({100*adverse(boot[:, 0], boot[:, 1]).mean():.2f}%), of which {adverse(boot[bad, 0], boot[bad, 1]).sum()} among the "
f"{bad.sum()} non-converged; non-converged pre - post ranges {np.min(boot[bad,0]-boot[bad,1]):.4f} to {np.max(boot[bad,0]-boot[bad,1]):.4f}")
print(f" non-converged refitted from the grid start ({int(np.nansum(boot[bad, 6]))} of {bad.sum()} converge): adverse ordering in "
f"{adverse(pre2, post2).sum()} of {len(boot)} ({100*adverse(pre2, post2).mean():.2f}%)")
amplitude: 1467 pairs ({'M-YQ0201-27': 800, 'M-YQ0201-29': 667}), 417 presynaptic and 446 postsynaptic cells; AIC {'linear distance': np.float64(2140.6), 'log distance': np.float64(2134.3)} -> log distance
REML variances: pre 0.1445, post 0.0579, residual 0.1374
bootstrap (1971 of 2000 refits converged, 156 s): pre > post in 100.00%, post > pre in 0.00%; 95% interval of pre - post [0.0545, 0.1216]
all 2000 refits as fitted: adverse ordering in 0 (0.00%), of which 0 among the 29 non-converged; non-converged pre - post ranges 0.0574 to 0.1213
non-converged refitted from the grid start (29 of 29 converge): adverse ordering in 0 of 2000 (0.00%)
decay weights: unweighted residual variance 0.718, median measurement variance 0.057, s0^2 = 0.661, effective n 1364 of 1469
decay: 1469 pairs ({'M-YQ0201-27': 802, 'M-YQ0201-29': 667}), 419 presynaptic and 447 postsynaptic cells; AIC {'linear distance': np.float64(4077.1), 'log distance': np.float64(4067.9)} -> log distance
REML variances: pre 0.0213, post 0.1111, residual 0.5929
bootstrap (1969 of 2000 refits converged, 279 s): pre > post in 0.05%, post > pre in 99.95%; 95% interval of pre - post [-0.1413, -0.0409]
all 2000 refits as fitted: adverse ordering in 1 (0.05%), of which 0 among the 31 non-converged; non-converged pre - post ranges -0.1329 to -0.0011
non-converged refitted from the grid start (31 of 31 converge): adverse ordering in 1 of 2000 (0.05%)
Result: reproduced. Log distance is chosen for both models (by 6.2 and 9.2 AIC units, the tutorial's published values). For amplitude (1,467 pairs) the presynaptic variance is 0.1445 and the postsynaptic 0.0579; no refit of 2,000 has postsynaptic at or above presynaptic, among the 1,971 converged refits, among all refits as fitted (the 29 non-converged have pre minus post 0.057 to 0.121), and with the non-converged refitted from the grid start. For decay (1,469 pairs; s0^2 = 0.661 and effective n 1,364, the tutorial's values) the postsynaptic variance is 0.1111 and the presynaptic 0.0213; 1 of the 2,000 refits as fitted has presynaptic at or above postsynaptic (0.05%), none of the 31 non-converged (pre minus post -0.133 to -0.001, the closest almost adverse), and still 1 of 2,000 after refitting them, under the 0.1% bound.
gap-junction-no-identity-effect¶
Gap-junction strength shows little association with pre- or post-junctional identity.
The analysis of fig3jk applied to spikelet_amplitude_normalized of QC pairs with
gap_junction_connection set, 60 to 400 um, each mouse (no tau mask). Reproduced when both R are
below 0.26 in both mice (the reading chosen in the claims file).
for m in L.MICE:
for nm, (r, p, nmask, nok) in prepost(m, "spikelet").items():
print(f"{m} {nm}: R = {r:.3f}, p = {p:.3g}, n = {nok} of {nmask}")
M-YQ0201-27 outgoing (presynaptic mean): R = 0.214, p = 5.74e-38, n = 3551 of 3553 M-YQ0201-27 incoming (postsynaptic mean): R = 0.298, p = 1.23e-73, n = 3551 of 3553
M-YQ0201-29 outgoing (presynaptic mean): R = 0.268, p = 2.12e-37, n = 2187 of 2199 M-YQ0201-29 incoming (postsynaptic mean): R = 0.314, p = 1.37e-51, n = 2196 of 2199
Result: not reproduced. The leave-one-out correlations of spikelet amplitude are R = 0.214 (outgoing) and 0.298 (incoming) in M-YQ0201-27 and 0.268 and 0.314 in M-YQ0201-29, every p below 1e-36. Three of the four are above 0.26, the bound the claims file chose for "little association".
fig5e-inhibition-in-spontaneous-voltage, fig5e-inhibition-in-spontaneous-rate, fig5g-gap-junction-synchrony¶
Relative to distance-matched unconnected controls, a presynaptic spike is followed 15 to 30 ms later by a postsynaptic hyperpolarization of -2.1% of a spike height for the strongest quintile of connections and -1% at median strength; unconnected control pairs instead rise by 1% of a spike height from -20 to -5 ms to 15 to 30 ms.
For the strongest quintile of synaptic connections, a presynaptic spike lowers the postsynaptic rate by 0.18 Hz 5 to 13 ms later, a loss of 7e-3 spikes over the IPSP; near median strength, by 0.083 Hz, a loss of 2.7e-3 spikes.
Gap-junction coupling raises spontaneous spike synchrony; for the strongest quintile, synchronous firing (lag <= 2.5 ms) exceeds near-synchronous firing by 0.86 Hz more than in unconnected neighbours, and by 0.32 Hz at median coupling.
Stored spontaneous_cross_spike_sta and spontaneous_spike_cross_correlogram of the sparsePulseHad
sessions (lag 0 at index 140). Connected QC pairs 60 to 400 um, quintiles of IPSP amplitude or
spikelet amplitude per mouse (code, quintileConnectivityAverages), pooled over mice. Controls for a
connected pair (i, j): pairs (i, k) with k within 400 um of both i and j and unconnected to i
(Methods, Estimating cross STAs), 60 to 400 um from i (code). Measures (Methods, Effect of
connections): voltage suppression = mean of frames 12 to 25 minus mean of frames -17 to -4; rate
suppression = frames 4 to 10 minus -10 to -4 (Hz); synchrony = maximum over frames -1 to 1 minus the
larger of the means of frames -4 to -2 and 2 to 4 (Hz). Readings: (a) median over connected pairs
minus median over their controls; (b) median over connected pairs of (pair minus the mean of its
own controls); (c) the measure of the quintile average after regressing out the control average
(code removeSharedDynamics, spike-count weights). "Median strength": all connected pairs or the third
quintile. Spikes lost or gained: the control-subtracted rate minus its pre-spike baseline (frames -10
to -4) integrated over 0 to 100 ms or to its first return to zero (synaptic), or over frames -1 to 1
or the contiguous lags around 0 where it is positive (gap junction).
Z = 140
fr = lambda a, b: np.arange(Z + a, Z + b + 1)
def vsupp(X):
return X[..., fr(12, 25)].mean(-1) - X[..., fr(-17, -4)].mean(-1)
def rsupp(X):
return (X[..., fr(4, 10)].mean(-1) - X[..., fr(-10, -4)].mean(-1)) / L.DT
def sync(X):
return (X[..., fr(-1, 1)].max(-1) - np.maximum(X[..., fr(-4, -2)].mean(-1), X[..., fr(2, 4)].mean(-1))) / L.DT
def integral_lost(tr):
"""Spikes lost from a control-subtracted rate waveform (per frame, spikes per trigger)."""
t = tr - tr[fr(-10, -4)].mean()
a = t[Z:Z + int(round(0.1 / L.DT)) + 1].sum()
after = t[Z:]
neg = np.nonzero(after >= 0)[0]
stop = neg[neg > 2][0] if np.any(neg > 2) else len(after)
b = after[:stop].sum()
return a, b
def integral_gained(tr):
t = tr - np.maximum(tr[fr(-4, -2)].mean(), tr[fr(2, 4)].mean())
a = t[fr(-1, 1)].sum()
lo_, hi_ = Z, Z
while lo_ > 0 and t[lo_ - 1] > 0:
lo_ -= 1
while hi_ < len(t) - 1 and t[hi_ + 1] > 0:
hi_ += 1
b = t[lo_:hi_ + 1].sum() if t[Z] > 0 else 0.0
return a, b
def regress_out(trace, ref, fit_idx=np.arange(0, 139)):
trace = trace - trace.mean(); ref = ref - ref.mean()
x, y = ref[fit_idx], trace[fit_idx]
k = (x @ y) / (x @ x) if np.any(x != 0) else 0.0
return trace - k * ref
CONN = {}
for kind in ("syn", "gap"):
recs = []
for m in L.MICE:
M, q, QQ, D, sets = pair_sets(m)
qi = np.nonzero(q)[0]
sub = lambda X: X[np.ix_(qi, qi)]
d = sub(D)
band = (d > 60) & (d < 400)
C = sub(M["synaptic_connection"] if kind == "syn" else M["gap_junction_connection"])
amp = sub(M["ipsp_amplitude_norm_per_presynaptic_spike"] if kind == "syn" else M["spikelet_amplitude_normalized"])
sel = C & band
ed = np.percentile(amp[sel & np.isfinite(amp)], np.linspace(0, 100, 6))
qn = np.clip(np.digitize(amp, ed[1:-1]) + 1, 1, 5)
SV = L.pair_series(m, "spontaneous_cross_spike_sta")[np.ix_(qi, qi)]
SR = L.pair_series(m, "spontaneous_spike_cross_correlogram")[np.ix_(qi, qi)]
wnb = np.array([len(x) for x in U[m, "sparsePulseHad"]["spike_times_no_blue"]])[qi]
near = d < 400
for i, j in zip(*np.nonzero(sel & np.isfinite(amp))):
ctrl = np.nonzero(near[i] & near[j] & ~C[i] & band[i])[0]
recs.append(dict(mouse=m, i=i, j=j, quint=qn[i, j], amp=amp[i, j], ctrl=ctrl,
sta_v=SV[i, j], sta_r=SR[i, j], ctrl_v=SV[i, ctrl], ctrl_r=SR[i, ctrl], w=wnb[i]))
del SV, SR
CONN[kind] = recs
print(f"{kind}: {len(recs)} connected pairs, per quintile {np.bincount([r['quint'] for r in recs])[1:]}, "
f"controls per pair median {np.median([len(r['ctrl']) for r in recs]):.0f}, pairs without a control {sum(len(r['ctrl']) == 0 for r in recs)}")
def readings(recs, measure, wave_key, ctrl_key, integ):
out = {}
for grp, sel in [("top quintile", [r for r in recs if r["quint"] == 5]),
("all connected", recs),
("third quintile", [r for r in recs if r["quint"] == 3])]:
sel = [r for r in sel if len(r["ctrl"]) > 0]
pv = np.array([measure(r[wave_key]) for r in sel])
cv_all = np.concatenate([measure(r[ctrl_key]) for r in sel])
own = np.array([measure(r[ctrl_key]).mean() for r in sel])
a = np.median(pv) - np.median(cv_all)
b = np.median(pv - own)
w = np.array([r["w"] for r in sel], float)
avg = (np.array([r[wave_key] for r in sel]) * w[:, None]).sum(0) / w.sum()
wc = np.concatenate([np.full(len(r["ctrl"]), r["w"]) for r in sel]).astype(float)
cavg = (np.concatenate([r[ctrl_key] for r in sel]) * wc[:, None]).sum(0) / wc.sum()
res = regress_out(avg, cavg)
c = measure(res)
p1 = stats.mannwhitneyu(pv, cv_all, alternative="less" if measure is not sync else "greater").pvalue
p2 = stats.mannwhitneyu(pv, cv_all).pvalue
extra = {}
if integ is not None:
ia = [integ(r[wave_key] - r[ctrl_key].mean(0)) for r in sel]
extra["integral_b_med"] = (np.median([x[0] for x in ia]), np.median([x[1] for x in ia]))
extra["integral_c"] = integ(avg - cavg)
ip = [integ(r[wave_key]) for r in sel]; ic = [integ(x) for x in r_ctrl_waves(sel, ctrl_key)]
extra["integral_a"] = (np.median([x[0] for x in ip]) - np.median([x[0] for x in ic]),
np.median([x[1] for x in ip]) - np.median([x[1] for x in ic]))
out[grp] = dict(n=len(sel), n_ctrl=len(cv_all), a=a, b=b, c=c, p_one=p1, p_two=p2,
ctrl_median=np.median(cv_all), ctrl_mean=np.mean(cv_all),
ctrl_avg=measure(cavg), pair_avg=measure(avg), **extra)
return out
def r_ctrl_waves(sel, key):
return [w for r in sel for w in r[key]]
FIG5 = {}
FIG5["voltage"] = readings(CONN["syn"], vsupp, "sta_v", "ctrl_v", None)
FIG5["rate"] = readings(CONN["syn"], rsupp, "sta_r", "ctrl_r", integral_lost)
FIG5["sync"] = readings(CONN["gap"], sync, "sta_r", "ctrl_r", integral_gained)
for k, res in FIG5.items():
print(f"\n{k}:")
for grp, r in res.items():
s = (f" {grp}: n = {r['n']} pairs, {r['n_ctrl']} control pairs; (a) {r['a']:.4f}, (b) {r['b']:.4f}, (c) {r['c']:.4f}; "
f"controls median {r['ctrl_median']:.4f}, mean {r['ctrl_mean']:.4f}, measure of the weighted control average "
f"{r['ctrl_avg']:.4f} (of the weighted pair average {r['pair_avg']:.4f}); rank-sum p one-sided {r['p_one']:.2g}, two-sided {r['p_two']:.2g}")
if "integral_a" in r:
s += (f"\n spikes (window 1, window 2): (a) {np.round(r['integral_a'], 5)}, (b) {np.round(r['integral_b_med'], 5)}, "
f"(c) {np.round(r['integral_c'], 5)}")
print(s)
syn: 1467 connected pairs, per quintile [294 293 293 293 294], controls per pair median 13, pairs without a control 0
gap: 5752 connected pairs, per quintile [1151 1150 1150 1150 1151], controls per pair median 8, pairs without a control 34
voltage:
top quintile: n = 294 pairs, 4747 control pairs; (a) -0.0189, (b) -0.0188, (c) -0.0213; controls median 0.0031, mean 0.0120, measure of the weighted control average 0.0049 (of the weighted pair average -0.0160); rank-sum p one-sided 2.4e-31, two-sided 4.8e-31
all connected: n = 1467 pairs, 20742 control pairs; (a) -0.0095, (b) -0.0099, (c) -0.0095; controls median 0.0073, mean 0.0191, measure of the weighted control average 0.0097 (of the weighted pair average -0.0000); rank-sum p one-sided 6.4e-39, two-sided 1.3e-38
third quintile: n = 293 pairs, 4074 control pairs; (a) -0.0096, (b) -0.0091, (c) -0.0087; controls median 0.0079, mean 0.0183, measure of the weighted control average 0.0090 (of the weighted pair average -0.0002); rank-sum p one-sided 2.3e-08, two-sided 4.5e-08
rate:
top quintile: n = 294 pairs, 4747 control pairs; (a) -0.1898, (b) -0.1569, (c) -0.3858; controls median 0.0000, mean -0.0527, measure of the weighted control average -0.0444 (of the weighted pair average -0.4326); rank-sum p one-sided 4.5e-09, two-sided 8.9e-09
spikes (window 1, window 2): (a) [-0.00289 0.0013 ], (b) [ 0.01634 -0.00038], (c) [-0.01451 -0.01591]
all connected: n = 1467 pairs, 20742 control pairs; (a) -0.0825, (b) -0.0962, (c) -0.1759; controls median 0.0000, mean 0.0244, measure of the weighted control average 0.0146 (of the weighted pair average -0.1602); rank-sum p one-sided 4.5e-16, two-sided 9e-16
spikes (window 1, window 2): (a) [-0.0049 0.00083], (b) [ 0.01305 -0.00089], (c) [-0.00905 -0.01339]
third quintile: n = 293 pairs, 4074 control pairs; (a) -0.0700, (b) -0.0859, (c) -0.1098; controls median 0.0000, mean 0.0251, measure of the weighted control average 0.0176 (of the weighted pair average -0.0931); rank-sum p one-sided 0.001, two-sided 0.002
spikes (window 1, window 2): (a) [-0.00206 0.00085], (b) [ 0.01983 -0.0007 ], (c) [-0.00289 -0.00119]
sync:
top quintile: n = 1147 pairs, 12297 control pairs; (a) 0.7994, (b) 0.3919, (c) 1.3042; controls median 0.8359, mean 1.3352, measure of the weighted control average 0.5308 (of the weighted pair average 1.6819); rank-sum p one-sided 0, two-sided 0
spikes (window 1, window 2): (a) [0.00223 0.00284], (b) [0.00052 0.00093], (c) [0.00332 0.00368]
all connected: n = 5718 pairs, 50574 control pairs; (a) 0.2923, (b) 0.0925, (c) 0.4375; controls median 0.7755, mean 1.2761, measure of the weighted control average 0.4951 (of the weighted pair average 0.9282); rank-sum p one-sided 0, two-sided 0
spikes (window 1, window 2): (a) [0.00093 0.00114], (b) [-0.00049 0. ], (c) [0.00121 0.0014 ]
third quintile: n = 1142 pairs, 10107 control pairs; (a) 0.1535, (b) 0.0240, (c) 0.3788; controls median 0.8139, mean 1.3032, measure of the weighted control average 0.5247 (of the weighted pair average 0.8685); rank-sum p one-sided 7.5e-09, two-sided 1.5e-08
spikes (window 1, window 2): (a) [0.0008 0.00086], (b) [-0.00064 0. ], (c) [0.00108 0.00124]
Result: fig5e-inhibition-in-spontaneous-voltage reproduced. For the top quintile (294 pairs) the voltage change relative to controls is -0.0189 (a), -0.0188 (b) and -0.0213 SH (c), against -0.021 +/- 0.0021 ((a) at the edge, (c) inside); for all 1,467 connected pairs it is -0.0095, -0.0099 and -0.0095 SH, within -0.01 +/- 0.001; rank-sum tests against the controls give p = 2.4e-31 and 6.4e-39 one-sided (4.8e-31 and 1.3e-38 two-sided). The controls' own change from -20 to -5 ms to 15 to 30 ms, measured on the spike-weighted control-average waveform as the paper's "STA waveform", is +0.0097 for the controls of all connected pairs, within 0.01 +/- 0.001, and +0.0049 for those of the top quintile; per control pair the mean is +0.019 (median +0.007) for the controls of all connected pairs and +0.012 (median +0.003) for those of the top quintile. The criterion does not test this value.
fig5e-inhibition-in-spontaneous-rate partially reproduced. The rate decreases match under reading (a): 0.190 Hz for the top quintile (0.18 +/- 0.018) and 0.083 Hz for all connected pairs (0.083 +/- 0.0083). The spikes lost do not match under any reading or window: 2.9e-3 (top) and 4.9e-3 (all) under (a) in the 0 to 100 ms window, against 7e-3 and 2.7e-3, and other readings give values of the wrong sign or size (printed above).
fig5g-gap-junction-synchrony partially reproduced. Under reading (a) the synchrony enhancement is 0.80 Hz for the top quintile (1,147 pairs with controls; 0.86 +/- 0.086) and 0.29 Hz for all 5,718 pairs (0.32 +/- 0.032), with rank-sum p below 1e-300 against the controls. The spikes gained, 2.2e-3 and 9.3e-4 over frames -1 to 1 under (a), are outside 1.7e-3 and 7e-4 +/- 10%.
inhibition-gap-balance¶
Scaled by connection probability, spikes lost to inhibition per connected pair and spikes gained from gap junctions are approximately balanced.
Product of the median spikes lost per synaptic pair and the synaptic connection probability, against the product of the median spikes gained per gap-junction pair and the gap-junction probability, from the values measured above (all connected pairs; reading (b), first window, and the per-cell mean probabilities of synaptic-connection-counts and gap-junction-connection-counts, 60 to 400 um).
p_syn = pd.concat(percell["60 to 400 um"]).prob.mean()
p_gap = pd.concat(gpc["60 to 400 um"]).prob.mean()
for rd in ("integral_b_med", "integral_a"):
for wi in (0, 1):
lost = -FIG5["rate"]["all connected"][rd][wi]
gained = FIG5["sync"]["all connected"][rd][wi]
print(f"reading {rd[9]}, window {wi + 1}: spikes lost {lost:.2e} x p {p_syn:.3f} = {lost * p_syn:.2e}; "
f"spikes gained {gained:.2e} x p {p_gap:.3f} = {gained * p_gap:.2e}; ratio {lost * p_syn / (gained * p_gap):.2f}")
reading b, window 1: spikes lost -1.31e-02 x p 0.107 = -1.39e-03; spikes gained -4.90e-04 x p 0.409 = -2.00e-04; ratio 6.96 reading b, window 2: spikes lost 8.94e-04 x p 0.107 = 9.55e-05; spikes gained 0.00e+00 x p 0.409 = 0.00e+00; ratio inf reading a, window 1: spikes lost 4.90e-03 x p 0.107 = 5.23e-04; spikes gained 9.30e-04 x p 0.409 = 3.81e-04; ratio 1.37 reading a, window 2: spikes lost -8.34e-04 x p 0.107 = -8.91e-05; spikes gained 1.14e-03 x p 0.409 = 4.67e-04; ratio -0.19
Result: blocked (methods underspecified). The ratio of the two products depends on the integration window, which the paper does not fix ("the entire IPSP duration"): under reading (a) over 0 to 100 ms and frames -1 to 1 it is 1.37, inside 0.5 to 2; under the other readings it is 6.96, -0.19 or undefined. The spikes lost and gained that enter it do not match the paper's values under any reading (claims fig5e-inhibition-in-spontaneous-rate and fig5g-gap-junction-synchrony).
Figure 6: NPY-positive and NPY-negative subtypes, excitability and connectivity¶
Cells are grouped by the gfp_positive flag of the session the measure comes from.
npy-intrinsic-differences¶
NPY-negative neurons have greater after-depolarization, lower optical rheobase, more spike-rate adaptation, slightly lower maximum firing rate and a shorter membrane time constant than NPY-positive neurons, each difference at p <= 0.001.
Reading (a): QC cells of both sparseOpto sessions grouped by that session's gfp_positive;
two-sided rank-sum per property. Reading (b), the behavior-session cells, cannot be formed: the
intrinsic properties are stored only for the sparseOpto cells, and unit ids do not refer to the
same cells across sessions (data check).
want = {"adp_blue_norm": "NPY- higher", "optical_rheobase_norm": "NPY- lower", "pulse_adaptation": "NPY- higher",
"max_firing_rate_hz": "NPY- lower", "membrane_time_constant_ms": "NPY- lower"}
P_all = np.vstack([PROPS[m][QC_OPTO[m]] for m in L.MICE])
g_all = np.concatenate([GFP_OPTO[m][QC_OPTO[m]] for m in L.MICE])
print(f"QC cells: NPY- {np.sum(~g_all)}, NPY+ {np.sum(g_all)}")
hold = 0
for j, p in enumerate(L.PROPERTIES):
a, b = P_all[~g_all, j], P_all[g_all, j]
pv = stats.ranksums(a, b).pvalue
direction = "NPY- higher" if np.median(a) > np.median(b) else "NPY- lower"
ok = (direction == want[p]) and pv <= 0.001
hold += ok
print(f"{p:28s} median NPY- {np.median(a):8.4f}, NPY+ {np.median(b):8.4f}; {direction} (paper: {want[p]}); p = {pv:.2g}; holds: {ok}")
for m in L.MICE:
qa = PROPS[m][QC_OPTO[m] & ~GFP_OPTO[m], j]; qb = PROPS[m][QC_OPTO[m] & GFP_OPTO[m], j]
print(f" {m}: medians {np.median(qa):.4f} vs {np.median(qb):.4f}, p = {stats.ranksums(qa, qb).pvalue:.2g}")
print("differences holding:", hold, "of 5")
QC cells: NPY- 253, NPY+ 290
adp_blue_norm median NPY- 0.1489, NPY+ 0.0924; NPY- higher (paper: NPY- higher); p = 1.8e-34; holds: True
M-YQ0201-27: medians 0.1486 vs 0.0922, p = 2.2e-20
M-YQ0201-29: medians 0.1526 vs 0.0926, p = 7.1e-16
optical_rheobase_norm median NPY- 0.2164, NPY+ 0.3619; NPY- lower (paper: NPY- lower); p = 3.5e-16; holds: True
M-YQ0201-27: medians 0.2334 vs 0.3861, p = 9.1e-10
M-YQ0201-29: medians 0.2031 vs 0.3303, p = 2.1e-07
max_firing_rate_hz median NPY- 28.2899, NPY+ 32.7604; NPY- lower (paper: NPY- lower); p = 0.0002; holds: True
M-YQ0201-27: medians 29.2329 vs 31.2477, p = 0.61
M-YQ0201-29: medians 27.1111 vs 35.2401, p = 8.8e-07
pulse_adaptation median NPY- 0.3776, NPY+ 0.1809; NPY- higher (paper: NPY- higher); p = 2.1e-08; holds: True
M-YQ0201-27: medians 0.4617 vs 0.1468, p = 3.1e-07
M-YQ0201-29: medians 0.3470 vs 0.2311, p = 0.0061
membrane_time_constant_ms median NPY- 15.4435, NPY+ 17.2942; NPY- lower (paper: NPY- lower); p = 2.6e-08; holds: True
M-YQ0201-27: medians 15.4257 vs 17.9747, p = 3.6e-09
M-YQ0201-29: medians 15.5808 vs 16.4748, p = 0.064
differences holding: 5 of 5
Result: reproduced. Over the 543 sparseOpto QC cells (253 NPY-, 290 NPY+), NPY- cells have higher V_adp (p = 1.8e-34), lower rheobase (3.5e-16), more adaptation (2.1e-8), lower maximum rate (2.0e-4) and a shorter membrane time constant (2.6e-8): five of five at p <= 0.001. Reading (b) could not be formed (see above).
npy-classifier¶
A logistic-regression classifier on the five intrinsic properties identifies NPY status with 78% cross-validated balanced accuracy (95% CI 74 to 81%) against 50% (46 to 55%) for shuffled labels; after-depolarization is the most informative feature.
Logistic regression on the five properties (Methods, Cell type classification): 80/20 splits, 10,000 resampled folds, balanced accuracy on the test cells, 2.5 and 97.5 percentiles; chance from 5-fold cross-validation with shuffled labels. Readings: cells pooled or per mouse; z-scored or raw features; most informative feature by the largest absolute coefficient (z-scored) or the largest drop in balanced accuracy when left out. Z-scoring is fitted on the training cells of each split. Stratified splits and the default L2 penalty of scikit-learn (C = 1) are standard choices.
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import balanced_accuracy_score
from sklearn.model_selection import StratifiedShuffleSplit, StratifiedKFold
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import make_pipeline
rng_cls = np.random.default_rng(20261106)
def model(scale):
"""Logistic regression; for z-scored features the scaler is fitted on the training cells of
each split only, so no test cell enters the scaling."""
lr = LogisticRegression(max_iter=1000)
return make_pipeline(StandardScaler(), lr) if scale == "z-scored" else lr
def split_scores(X, y, n_splits, seed, cols=None, scale="z-scored"):
cols = list(range(X.shape[1])) if cols is None else cols
sss = StratifiedShuffleSplit(n_splits=n_splits, test_size=0.2, random_state=seed)
out = []
for tr, te in sss.split(X, y):
clf = model(scale).fit(X[tr][:, cols], y[tr])
out.append(balanced_accuracy_score(y[te], clf.predict(X[te][:, cols])))
return np.array(out)
def shuffled_chance(X, y, n_rep, seed, scale="z-scored"):
r = np.random.default_rng(seed)
out = []
for k in range(n_rep):
ys = r.permutation(y)
for tr, te in StratifiedKFold(5, shuffle=True, random_state=k).split(X, ys):
clf = model(scale).fit(X[tr], ys[tr])
out.append(balanced_accuracy_score(ys[te], clf.predict(X[te])))
return np.array(out)
sets_cls = {"pooled": (P_all, g_all)}
for m in L.MICE:
sets_cls[m] = (PROPS[m][QC_OPTO[m]], GFP_OPTO[m][QC_OPTO[m]])
for nm, (X, y) in sets_cls.items():
for scale in ("z-scored", "raw"):
n_sp = 10000 if (nm == "pooled" and scale == "z-scored") else 1000
sc = split_scores(X, y, n_sp, 1, scale=scale)
ch = shuffled_chance(X, y, 200 if n_sp == 10000 else 50, 2, scale=scale)
print(f"{nm}, {scale}: balanced accuracy {100*sc.mean():.1f}% [{100*np.percentile(sc, 2.5):.1f}, {100*np.percentile(sc, 97.5):.1f}] "
f"over {n_sp} splits; shuffled {100*ch.mean():.1f}% [{100*np.percentile(ch, 2.5):.1f}, {100*np.percentile(ch, 97.5):.1f}] over {len(ch)} folds")
Xz = (P_all - P_all.mean(0)) / P_all.std(0, ddof=1)
coef = LogisticRegression(max_iter=1000).fit(Xz, g_all).coef_[0]
print("coefficients on z-scored features:", dict(zip(L.PROPERTIES, coef.round(3))), "-> largest:", L.PROPERTIES[int(np.argmax(np.abs(coef)))])
full = split_scores(P_all, g_all, 1000, 3).mean()
drops = {p: full - split_scores(P_all, g_all, 1000, 3, [k for k in range(5) if k != j]).mean() for j, p in enumerate(L.PROPERTIES)}
print("drop in balanced accuracy when left out:", {k: round(100 * v, 2) for k, v in drops.items()}, "-> largest:", max(drops, key=drops.get))
pooled, z-scored: balanced accuracy 76.8% [69.3, 83.9] over 10000 splits; shuffled 50.0% [42.2, 57.5] over 1000 folds
pooled, raw: balanced accuracy 73.1% [65.5, 79.7] over 1000 splits; shuffled 50.6% [43.2, 57.6] over 250 folds
M-YQ0201-27, z-scored: balanced accuracy 76.6% [66.7, 86.1] over 1000 splits; shuffled 50.1% [39.5, 60.8] over 250 folds
M-YQ0201-27, raw: balanced accuracy 72.0% [60.5, 82.2] over 1000 splits; shuffled 49.9% [40.9, 58.7] over 250 folds
M-YQ0201-29, z-scored: balanced accuracy 76.3% [66.6, 86.3] over 1000 splits; shuffled 50.5% [37.0, 66.0] over 250 folds
M-YQ0201-29, raw: balanced accuracy 73.8% [63.2, 84.4] over 1000 splits; shuffled 50.4% [38.9, 64.1] over 250 folds
coefficients on z-scored features: {'adp_blue_norm': np.float64(-1.327), 'optical_rheobase_norm': np.float64(0.217), 'max_firing_rate_hz': np.float64(0.398), 'pulse_adaptation': np.float64(-0.322), 'membrane_time_constant_ms': np.float64(0.423)} -> largest: adp_blue_norm
drop in balanced accuracy when left out: {'adp_blue_norm': np.float64(5.45), 'optical_rheobase_norm': np.float64(-0.68), 'max_firing_rate_hz': np.float64(2.14), 'pulse_adaptation': np.float64(0.04), 'membrane_time_constant_ms': np.float64(0.08)} -> largest: adp_blue_norm
Result: reproduced. With the z-scoring fitted on the training cells of each split, pooled features give 76.8% balanced accuracy (2.5 to 97.5 percentiles 69.3 to 83.9% over 10,000 splits) against 50.0% for shuffled labels, within 4 and 5 points of 78% and 50%. After-depolarization has the largest coefficient (-1.33) and the largest drop when left out (5.5 points). The intervals printed are wider than the paper's.
npy-connection-probability, npy-ipsp-amplitude, npy-ipsp-duration¶
NPY-positive cells are more likely to synapse onto other L1 interneurons (outgoing probability within 400 um 14 +/- 15%) than NPY-negative cells (7 +/- 11%).
IPSPs from NPY-positive presynaptic cells are larger (-3.7 +/- 2.7% of a spike height, 977 pairs) than from NPY-negative cells (-3.1 +/- 2.3%, 490 pairs).
IPSPs last longer in NPY-positive postsynaptic cells (58 +/- 63 ms, 699 pairs) than in NPY-negative cells (43 +/- 54 ms, 646 pairs).
sparsePulseHad QC cells grouped by that session's gfp_positive. Connection probability per cell:
outgoing connections over tested partners within 400 um (as synaptic-connection-counts), and the
60 to 400 um band as a variant. Amplitudes: connected QC pairs 60 to 400 um by presynaptic subtype.
Durations: ipsp_decay (taken as seconds, see the data check) of connected pairs with a finite
fit, by postsynaptic subtype; all connected pairs and the QC pairs 60 to 400 um. Two-sided rank-sum.
for band in ("within 400 um", "60 to 400 um"):
d = pd.concat(percell[band])
g = np.concatenate([U[m, "sparsePulseHad"]["gfp_positive"][U[m, "sparsePulseHad"]["passed_qc"]] for m in L.MICE])
a, b = d.prob.values[g], d.prob.values[~g]
print(f"connection probability, {band}: NPY+ {100*a.mean():.1f} +/- {100*a.std(ddof=1):.1f}% (n = {len(a)}), "
f"NPY- {100*b.mean():.1f} +/- {100*b.std(ddof=1):.1f}% (n = {len(b)}), rank-sum p = {stats.ranksums(a, b).pvalue:.2g}")
amp_rows = []
for m in L.MICE:
M, q, QQ, D, sets = pair_sets(m)
g = U[m, "sparsePulseHad"]["gfp_positive"]
for selnm, T in [("QC 60-400 um", sets["60 to 400 um"]), ("QC within 400 um", sets["within 400 um"]),
("all flags", np.ones_like(QQ))]:
S = M["synaptic_connection"] & T
ii, jj = np.nonzero(S)
amp_rows.append(pd.DataFrame(dict(mouse=m, sel=selnm, pre_pos=g[ii], post_pos=g[jj],
amp=-M["ipsp_amplitude_norm_per_presynaptic_spike"][ii, jj],
tau_ms=1e3 * M["ipsp_decay_source_units"][ii, jj])))
AMP = pd.concat(amp_rows)
for selnm, d in AMP[AMP.sel != "QC within 400 um"].groupby("sel"):
d = d[np.isfinite(d.amp)]
a, b = d.amp[d.pre_pos], d.amp[~d.pre_pos]
print(f"IPSP amplitude, {selnm}: NPY+ pre {a.mean():.4f} +/- {a.std():.4f} (n = {len(a)}), NPY- pre {b.mean():.4f} +/- {b.std():.4f} "
f"(n = {len(b)}); |NPY+| larger: {abs(a.mean()) > abs(b.mean())}; rank-sum p = {stats.ranksums(a, b).pvalue:.2g}")
# The code's IPSP fit bounds the decay at 0.4 s (data check); a fit that ends on the bound has not
# found a decay, so fits at the bound are shown left out as well as kept.
for selnm, d in AMP.groupby("sel", sort=False):
d = d[np.isfinite(d.tau_ms) & (d.tau_ms > 0)]
at_bound = d.tau_ms >= 399.5
for fits, e in [("all finite fits", d), ("fits at the 0.4 s bound left out", d[~at_bound])]:
a, b = e.tau_ms[e.post_pos], e.tau_ms[~e.post_pos]
print(f"IPSP decay, {selnm}, {fits} ({at_bound.sum()} at the bound): NPY+ post {a.mean():.1f} +/- {a.std():.1f} ms (n = {len(a)}), "
f"NPY- post {b.mean():.1f} +/- {b.std():.1f} ms (n = {len(b)}); rank-sum p = {stats.ranksums(a, b).pvalue:.2g}")
connection probability, within 400 um: NPY+ 13.7 +/- 12.9% (n = 307), NPY- 7.4 +/- 9.0% (n = 269), rank-sum p = 1.4e-09 connection probability, 60 to 400 um: NPY+ 13.5 +/- 12.9% (n = 307), NPY- 7.4 +/- 8.9% (n = 269), rank-sum p = 2.4e-09 IPSP amplitude, QC 60-400 um: NPY+ pre -0.0372 +/- 0.0266 (n = 977), NPY- pre -0.0311 +/- 0.0227 (n = 490); |NPY+| larger: True; rank-sum p = 8.2e-07 IPSP amplitude, all flags: NPY+ pre -0.0380 +/- 0.0265 (n = 1145), NPY- pre -0.0347 +/- 0.0262 (n = 608); |NPY+| larger: True; rank-sum p = 0.00016 IPSP decay, QC 60-400 um, all finite fits (91 at the bound): NPY+ post 77.4 +/- 101.2 ms (n = 760), NPY- post 65.2 +/- 102.3 ms (n = 709); rank-sum p = 3.1e-13 IPSP decay, QC 60-400 um, fits at the 0.4 s bound left out (91 at the bound): NPY+ post 57.1 +/- 62.6 ms (n = 715), NPY- post 41.9 +/- 53.4 ms (n = 663); rank-sum p = 1.8e-16 IPSP decay, QC within 400 um, all finite fits (104 at the bound): NPY+ post 80.5 +/- 105.1 ms (n = 784), NPY- post 67.2 +/- 105.1 ms (n = 723); rank-sum p = 8.5e-14 IPSP decay, QC within 400 um, fits at the 0.4 s bound left out (104 at the bound): NPY+ post 57.4 +/- 62.5 ms (n = 731), NPY- post 41.9 +/- 53.1 ms (n = 672); rank-sum p = 3.6e-17 IPSP decay, all flags, all finite fits (128 at the bound): NPY+ post 82.2 +/- 108.3 ms (n = 873), NPY- post 69.0 +/- 107.0 ms (n = 882); rank-sum p = 2.1e-14 IPSP decay, all flags, fits at the 0.4 s bound left out (128 at the bound): NPY+ post 57.0 +/- 63.5 ms (n = 809), NPY- post 43.1 +/- 55.5 ms (n = 818); rank-sum p = 1.6e-17
Result: npy-connection-probability reproduced. NPY+ cells connect to 13.7 +/- 12.9% of their tested partners within 400 um (n = 307) and NPY- cells to 7.4 +/- 9.0% (n = 269), the paper's cell counts exactly; rank-sum p = 1.4e-9.
npy-ipsp-amplitude reproduced. For connected QC pairs 60 to 400 um, IPSPs from NPY+ cells average -0.0372 +/- 0.0266 SH (977 pairs) and from NPY- cells -0.0311 +/- 0.0227 SH (490 pairs), the paper's means and pair counts; rank-sum p = 8.2e-7.
npy-ipsp-duration reproduced, resting on an assumption. With the fits that end on the code's 0.4 s bound left out (91 of 1,469 in the QC pairs 60 to 400 um), decay time constants in NPY+ postsynaptic cells average 57.1 +/- 62.6 ms (715 pairs) and in NPY- cells 41.9 +/- 53.4 ms (663), against the paper's 58 +/- 63 (699) and 43 +/- 54 (646); rank-sum p = 1.8e-16. QC pairs within 400 um give 57.4 and 41.9 ms (731 and 672 pairs), also within tolerance. With the fits at the bound kept, the means are 77.4 and 65.2 ms (760 and 709 pairs, inside tolerance) in the 60 to 400 um band and 80.5 and 67.2 ms (784 and 723 pairs) within 400 um, where the NPY- count is outside 646 +/- 65.
npy-gap-junction-no-difference¶
Outgoing and incoming gap-junction connectivity does not differ systematically between NPY-positive and NPY-negative cells.
The claims file's test: two-sided rank-sum among the four pre/post subtype groups of per-cell gap-junction connection probability (Supplementary Fig. 25D) and pair spikelet amplitude (25E), QC pairs 60 to 400 um, both mice. Per-cell probability for a group (pre type -> post type): a presynaptic cell's connections to partners of the post type over its tested partners of that type. Not reproduced when a subtype effect is significant (p <= 0.05) in the same direction in both matched comparisons, for outgoing or for incoming.
gp_rows, sp_rows = [], []
for m in L.MICE:
M, q, QQ, D, sets = pair_sets(m)
g = U[m, "sparsePulseHad"]["gfp_positive"]
T = sets["60 to 400 um"]
G = M["gap_junction_connection"] & T
for c in np.nonzero(q)[0]:
for post_t in (False, True):
tm = T[c] & (g == post_t)
if tm.sum():
gp_rows.append(dict(pre=g[c], post=post_t, prob=G[c, tm].sum() / tm.sum()))
ii, jj = np.nonzero(G)
sp_rows.append(pd.DataFrame(dict(pre=g[ii], post=g[jj], amp=M["spikelet_amplitude_normalized"][ii, jj])))
GP = pd.DataFrame(gp_rows)
SP = pd.concat(sp_rows)
lab = lambda a, b: f"({'+' if a else '-'})->({'+' if b else '-'})"
flags = []
for nm, df, col in [("probability", GP, "prob"), ("spikelet amplitude", SP, "amp")]:
grp = {lab(a, b): df[(df.pre == a) & (df.post == b)][col].values for a in (False, True) for b in (False, True)}
print(nm, {k: f"median {np.median(v):.4f}, n = {len(v)}" for k, v in grp.items()})
for kind, pairs in [("outgoing (pre subtype)", [("(-)->(-)", "(+)->(-)"), ("(-)->(+)", "(+)->(+)")]),
("incoming (post subtype)", [("(-)->(-)", "(-)->(+)"), ("(+)->(-)", "(+)->(+)")])]:
res = []
for a, b in pairs:
p = stats.ranksums(grp[a], grp[b]).pvalue
res.append((p, np.sign(np.median(grp[b]) - np.median(grp[a]))))
print(f" {kind}: {a} vs {b}: medians {np.median(grp[a]):.4f} vs {np.median(grp[b]):.4f}, p = {p:.2g}")
consistent = all(p <= 0.05 for p, _ in res) and res[0][1] == res[1][1]
flags.append(consistent)
print(f" -> significant in the same direction in both matched comparisons: {consistent}")
print("systematic subtype effect found:", any(flags))
probability {'(-)->(-)': 'median 0.3636, n = 269', '(-)->(+)': 'median 0.3571, n = 269', '(+)->(-)': 'median 0.4545, n = 307', '(+)->(+)': 'median 0.4167, n = 307'}
outgoing (pre subtype): (-)->(-) vs (+)->(-): medians 0.3636 vs 0.4545, p = 0.00091
outgoing (pre subtype): (-)->(+) vs (+)->(+): medians 0.3571 vs 0.4167, p = 0.03
-> significant in the same direction in both matched comparisons: True
incoming (post subtype): (-)->(-) vs (-)->(+): medians 0.3636 vs 0.3571, p = 0.71
incoming (post subtype): (+)->(-) vs (+)->(+): medians 0.4545 vs 0.4167, p = 0.059
-> significant in the same direction in both matched comparisons: False
spikelet amplitude {'(-)->(-)': 'median 0.0137, n = 1222', '(-)->(+)': 'median 0.0124, n = 1327', '(+)->(-)': 'median 0.0116, n = 1571', '(+)->(+)': 'median 0.0109, n = 1632'}
outgoing (pre subtype): (-)->(-) vs (+)->(-): medians 0.0137 vs 0.0116, p = 5e-08
outgoing (pre subtype): (-)->(+) vs (+)->(+): medians 0.0124 vs 0.0109, p = 1.7e-07
-> significant in the same direction in both matched comparisons: True
incoming (post subtype): (-)->(-) vs (-)->(+): medians 0.0137 vs 0.0124, p = 0.0012
incoming (post subtype): (+)->(-) vs (+)->(+): medians 0.0116 vs 0.0109, p = 0.00073
-> significant in the same direction in both matched comparisons: True
systematic subtype effect found: True
Result: not reproduced. On the paper's test the subtypes differ systematically: NPY+ presynaptic cells have a higher gap-junction probability onto both postsynaptic types (p = 9.1e-4 and 0.030), and spikelet amplitudes differ in the same direction in both matched comparisons for the presynaptic subtype (p = 5e-8 and 1.7e-7) and for the postsynaptic subtype (p = 0.0012 and 7.3e-4). The effects are small (medians 0.36 against 0.45 and 0.0137 against 0.0116 SH).
Summary¶
| Claim | Outcome |
|---|---|
| adaptation-vadp-correlation | reproduced |
| fig2c-three-bins | reproduced |
| fig2gk-bin-profiles | reproduced |
| two-mice-intrinsic-distributions | reproduced (assumption) |
| synaptic-connection-counts | reproduced |
| ipsp-median-amplitude | partially reproduced |
| gap-junction-connection-counts | reproduced |
| hadamard-stimulation-rates | reproduced (assumption) |
| connection-distance-structure | partially reproduced |
| fig3eg-amplitude-falls-with-distance | reproduced |
| fig3h-conduction-speed | reproduced |
| amplitudes-log-normal | reproduced |
| interaction-kernel | not reproduced |
| fig3jk-presynaptic-sets-amplitude | reproduced |
| fig3mn-postsynaptic-sets-decay | reproduced |
| fig3lo-variance-components | reproduced |
| gap-junction-no-identity-effect | not reproduced |
| fig5e-inhibition-in-spontaneous-voltage | reproduced (reading (c)) |
| fig5e-inhibition-in-spontaneous-rate | partially reproduced |
| fig5g-gap-junction-synchrony | partially reproduced |
| inhibition-gap-balance | blocked: methods underspecified |
| npy-intrinsic-differences | reproduced |
| npy-classifier | reproduced |
| npy-connection-probability | reproduced |
| npy-ipsp-amplitude | reproduced |
| npy-ipsp-duration | reproduced (assumption) |
| npy-gap-junction-no-difference | not reproduced |
| jf608-brighter, targeting-signal-to-background, fig1d-stimulation-fold-change, off-target-length-constants, l1-sampling-density, highmag-footprint | blocked: data missing |
| spikelet-not-scatter | reproduced (subset of the movie) |
| lasso-off-target-correction | not reproduced (assumption) |
| detection-limits | blocked: too large |
The outcomes of the other two notebooks are in their summaries and in the attempt record.
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. It starts from the stored products of the dandiset (connection calls, amplitudes, decay constants, trial-average and spike-triggered waveforms) and does not re-run the paper's detection and fitting, except where a claim needs what is not stored: the lasso correction rebuilds per-pulse responses and evoked spikes from the voltage and the stimulation (with an assumed response window), and the scatter control reads the first 40,000 frames of the raw-movie excerpt. The mixed model is fitted with a Python implementation of the same REML likelihood, and numpy's generator replaces MATLAB's in the bootstrap. Where the paper leaves a measure open (the interaction kernel, the integration windows of spikes lost and gained, the length-constant fits) the claims file's readings are run.
What was found about the dataset. Unit ids do not refer to the same cells across the three
sessions of a mouse (cells with the same id lie a median 1.1 to 1.3 mm apart, and only 6 to 26 of
320 cells have a cell of the other session within 10 um), and the gfp_positive flags of a mouse
differ between its sessions (156, 171 and 171 NPY+ cells in M-YQ0201-27; 135, 144 and 157 in
M-YQ0201-29); nothing in the files says so. ipsp_decay_source_units and its standard error carry
no unit (the values are consistent with seconds). The paper's connection counts and pair counts are
those of the 60 to 400 um band of QC pairs, which the files do not state. The x and y origin is
undocumented. Everything else checked (frame interval, pairwise table order and orientation,
distances, clock of stimulus and response) agrees with the description.
Time to run this notebook is printed below.
print(f"notebook run time {(time.time() - T0) / 60:.1f} min")
notebook run time 28.6 min