Arousal and effect size (Figure 4) from dandiset 000036, with the paper's Zenodo deposit¶
Part of the attempt on Mayner, Marshall, Billeh et al. (2022), eNeuro 9(1)
ENEURO.0280-21.2021 (doi:10.1523/eneuro.0280-21.2021),
on DANDI:000036 version 0.230515.1917.
The header of reproduce_mayner_2022.ipynb says why this version and gives the table of all
claims.
fig4-locomotion-effect-size is judged under two readings of running artifact removal (claims
file, opening comment, detail (1)): (a) none beyond interpolation and the 1 Hz filter, from
the dandiset alone; (b) the per-session parameters the paper's code reads from its Zenodo
deposit (doi:10.5281/zenodo.5781567, data/run/preprocessing_params.yaml), applied to the
dandiset's running velocity aligned with the deposit's stimulus_alignment (vsync to 2p
frame), as the code does. The deposit is one gzip-compressed tar file of 4.5 GB, whose members
can only be reached in order; the running parameters come after 4 GB of dF/F. This notebook
streams it in the background, in memory, while it reads the dandiset, fetching byte ranges over
several connections at once and decompressing them in order. It stops at a deadline so that it
fits the time limit; if the deadline is reached first, reading (b) is not available and the
output says so.
The pupil claims are blocked (data_missing): the dandiset has no eye tracking, and the deposit holds only pupil area, not the fitted ellipse whose semi-major axis the Methods define as the diameter. The code's reading (2*sqrt(area/pi)) is shown below for fig4-pupil-effect-size as a variant; it does not decide the claim.
import os
os.environ["OMP_NUM_THREADS"] = "1"
import io
import multiprocessing as mp
import threading
import time
import warnings
from concurrent.futures import ProcessPoolExecutor
import h5py
import numpy as np
import pandas as pd
import yaml
import openscope_nd as o
warnings.filterwarnings("ignore")
pd.set_option("display.width", 200)
started = time.time()
DEADLINE = started + 26 * 60 # stop streaming the deposit 26 min after the start
assets = o.list_assets()
meta = o.read_all_metadata(assets)
paper = pd.read_parquet(o.CODE_RESULTS + "main.parquet")
link = o.link_to_paper(meta, paper)
use = link[link.in_paper].reset_index(drop=True)
use["paper_session"] = use.paper_session.astype(int)
print(f"dandiset {o.DANDISET_ID} version {o.DANDISET_VERSION}; {len(use)} sessions linked to the paper")
need = ({f"./data/sync/{s}_time_synchronization.h5" for s in use.paper_session}
| {f"./data/eye/{i}_area.npy" for i in use.identifier}
| {f"./data/run/run_speed{s}.npy" for s in use.paper_session}
| {"./data/eye/preprocessing_params.yaml", "./data/run/preprocessing_params.yaml"})
want = lambda name: name in need
zen, zen_log = {}, []
def zenodo_worker():
try:
got, seen = o.stream_zenodo((want, need), DEADLINE, zen_log)
zen.update(got=got, seen=seen)
except Exception as e: # noqa: BLE001 - report it below
zen_log.append(f"stream failed: {e!r}")
thread = threading.Thread(target=zenodo_worker, daemon=True)
thread.start()
dandiset 000036 version 0.230515.1917; 44 sessions linked to the paper
t0 = time.time()
with ProcessPoolExecutor(3, mp_context=mp.get_context("spawn")) as ex:
sess = list(ex.map(o.arousal_session, use.url))
print(f"read {len(sess)} sessions from the dandiset in {(time.time() - t0) / 60:.1f} min")
thread.join(timeout=max(0, DEADLINE - time.time()) + 120)
print("Zenodo stream:", zen_log, "; members read:", len(zen.get("got", {})), "of", len(need))
read 44 sessions from the dandiset in 1.0 min
Zenodo stream: ['all required members read after 198 s'] ; members read: 134 of 134
Data check¶
seen = pd.DataFrame(zen.get("seen", []), columns=["member", "bytes", "seconds"])
if len(seen):
seen["folder"] = seen.member.str.split("/").str[2]
print("Deposit members passed, by folder (in stream order):")
print(seen.groupby("folder", sort=False).agg(members=("member", "size"), MB=("bytes", lambda b: round(b.sum() / 1e6)),
first_s=("seconds", "min"), last_s=("seconds", "max")).to_string())
eye = seen[(seen.folder == "eye") & (seen.member.str.count("/") > 2)]
print(f"\ndata/eye/ holds {len(eye)} members; their names with the session number replaced by <id>:",
eye.member.str.split("/").str[-1].str.replace(r"\d{6,}", "<id>", regex=True).value_counts().to_dict())
got = zen.get("got", {})
missing = sorted(need - set(got))
print("Required members missing:", len(missing), missing[:5])
have_b = "./data/run/preprocessing_params.yaml" in got
print("Reading (b) available:", have_b)
print("\nSessions read:", len(sess), "; contrast trials per session:", sorted({len(s['trials']) for s in sess}))
print("Running velocity per session (cm/s): min", round(min(s["run_v"].min() for s in sess), 1),
"max", round(max(s["run_v"].max() for s in sess), 1))
Deposit members passed, by folder (in stream order):
members MB first_s last_s
folder
eye 47 46 2.491196 23.412769
events 4125 4117 23.418674 43.520209
pkl 46 2840 43.521801 51.332111
sync 46 227 51.501730 52.098556
dff 46 4115 52.126334 193.696179
run 47 45 197.488364 197.736584
data/eye/ holds 46 members; their names with the session number replaced by <id>: {'<id>_area.npy': 45, 'preprocessing_params.yaml': 1}
Required members missing: 0 []
Reading (b) available: True
Sessions read: 44 ; contrast trials per session: [50]
Running velocity per session (cm/s): min -631.2 max 525.5
sync = {}
for s in use.paper_session:
key = f"./data/sync/{s}_time_synchronization.h5"
if key in got:
with h5py.File(io.BytesIO(got[key]), "r") as f:
sync[s] = {k: np.array(f[k]).ravel() for k in f}
run_params = yaml.safe_load(got["./data/run/preprocessing_params.yaml"]) if have_b else None
eye_params = yaml.safe_load(got["./data/eye/preprocessing_params.yaml"]) if "./data/eye/preprocessing_params.yaml" in got else None
rows = []
for (_, u), s in zip(use.iterrows(), sess):
sy = sync.get(u.paper_session)
if sy is None:
continue
tv = sy["twop_vsync_fall"]
al = sy["stimulus_alignment"].astype(int)
n = min(len(tv), len(s["frame_t"]))
frame_nwb = np.searchsorted(s["frame_t"], s["run_t"], side="right") - 1
k = min(len(frame_nwb), len(al))
diff = frame_nwb[:k] - al[:k]
rs_key = f"./data/run/run_speed{u.paper_session}.npy"
rs = np.load(io.BytesIO(got[rs_key])) if rs_key in got else None
rows.append({"session": u.identifier, "frames_equal": bool(np.allclose(tv[:n], s["frame_t"][:n])),
"run_equal": None if rs is None else bool(len(rs) == len(s["run_v"]) + 1 and np.array_equal(rs[:-1], s["run_v"])),
"n_vsync_sync": len(al), "n_run_nwb": len(s["run_v"]),
"frame_shift_first_min": diff[: 60 * 60].mean(), "frame_shift_last_min": diff[-60 * 60:].mean()})
chk = pd.DataFrame(rows)
if len(chk):
print("NWB frame timestamps equal the deposit's 2p vsync times in", int(chk.frames_equal.sum()), "of", len(chk), "sessions")
print("NWB running velocity, first sample dropped, equals the deposit's run_speed without its last sample in",
int(chk.run_equal.fillna(False).sum()), "of", len(chk))
print("NWB running samples equal the deposit's vsync count in", int((chk.n_vsync_sync == chk.n_run_nwb).sum()), "of", len(chk),
"; differences (vsyncs minus NWB samples kept):", sorted((chk.n_vsync_sync - chk.n_run_nwb).unique().tolist()))
print("2p frame of each running sample by the NWB timestamps minus the deposit's stimulus_alignment, mean over the")
print(f" first minute: {chk.frame_shift_first_min.mean():+.2f} (range {chk.frame_shift_first_min.min():+.2f} to {chk.frame_shift_first_min.max():+.2f})")
print(f" last minute: {chk.frame_shift_last_min.mean():+.2f} (range {chk.frame_shift_last_min.min():+.2f} to {chk.frame_shift_last_min.max():+.2f})")
if run_params is not None:
print("\nRunning parameters of the deposit: ", {k: v for k, v in run_params.items() if k != "bad_samples"})
print("sessions with hand-marked bad samples:", sum(1 for s in use.paper_session if run_params["bad_samples"].get(s)))
NWB frame timestamps equal the deposit's 2p vsync times in 44 of 44 sessions
NWB running velocity, first sample dropped, equals the deposit's run_speed without its last sample in 44 of 44
NWB running samples equal the deposit's vsync count in 0 of 44 ; differences (vsyncs minus NWB samples kept): [1, 2]
2p frame of each running sample by the NWB timestamps minus the deposit's stimulus_alignment, mean over the
first minute: +0.13 (range -0.47 to +0.52)
last minute: +3.18 (range +1.25 to +4.39)
Running parameters of the deposit: {'clean_signal_params': {'prominence': 25, 'rel_height': 0.5, 'wlen': 15, 'n': 10}, 'butterworth_params': {'analog': False, 'btype': 'lowpass', 'cutoff': 1.0, 'fs': 30.0, 'order': 2, 'output': 'ba'}, 'locomotion_threshold': 2.5}
sessions with hand-marked bad samples: 1
The data check: the deposit's members arrive in the order printed above, and the running parameters only after the 4 GB of dF/F. Its data/eye/ folder holds one pupil area file per session and a parameter file, and no ellipse fit or axis lengths. The NWB frame timestamps are the deposit's 2p vsync times in every session. The NWB running velocity, without its first sample, equals the deposit's run_speed without its last, so the NWB file's first sample is an extra one; it is dropped (the helper module does so for every notebook). Mapped to 2p frames by the NWB timestamps, running samples fall 0.1 frames later than the deposit's stimulus_alignment in the first minute and 3.2 frames later in the last (1.3 to 4.4 by session): the NWB vsync times drift against the 2p frame times, compared with the alignment the paper used, by about 3 frames (105 ms) on average and up to 4.4 frames (146 ms) by the end of a session. This is the drift the main notebook finds in the stimulus times. Reading (b) here uses the deposit's alignment, as the code does. Only one session has hand-marked bad running samples; the other parameters are global (prominence 25, wlen 15, 10 passes; 1 Hz, second order, 30 Hz).
fig4-locomotion-effect-size¶
In L2/3 of AL and AM, the per-session effect size of unscrambled against scrambled ND is positively correlated with the fraction of time spent running (r = 0.896).
eff = pd.DataFrame({
"session": use.identifier, "paper_session": use.paper_session, "layer": use.layer, "area": use.area,
"mouse_id": use.mouse_id,
"d": [o.cohens_d(s["trials"].y, s["trials"].stimulus.map(o.STIMULI.set_index("stimulus").stimulus_type)) for s in sess],
"d_code_sd": [o.cohens_d(s["trials"].y, s["trials"].stimulus.map(o.STIMULI.set_index("stimulus").stimulus_type),
code_sd=True) for s in sess],
"loco_a": [s["loco_a"].mean() for s in sess],
})
loco_b = []
for (_, u), s in zip(use.iterrows(), sess):
if run_params is None or u.paper_session not in sync:
loco_b.append(np.nan)
continue
_, loco = o.running_code_reading(s["run_v"], sync[u.paper_session]["stimulus_alignment"], s["n_frames"],
run_params, u.paper_session)
loco_b.append(loco.mean())
eff["loco_b"] = loco_b
ref = pd.read_parquet(o.CODE_RESULTS + "behavior_by_session.parquet").reset_index()
ref_es = pd.read_parquet(o.CODE_RESULTS + "effect_size.parquet").reset_index()
eff = eff.merge(ref[["session", "locomotion", "normalized_pupil_diameter"]].rename(
columns={"session": "paper_session", "locomotion": "paper_loco", "normalized_pupil_diameter": "paper_pupil"}),
on="paper_session", how="left").merge(ref_es[["session", "Cohen's d"]].rename(
columns={"session": "paper_session", "Cohen's d": "paper_d"}), on="paper_session", how="left")
main6 = eff[(eff.layer == "L2/3") & eff.area.isin(["AL", "AM"])]
print(main6[["session", "area", "mouse_id", "d", "d_code_sd", "paper_d", "loco_a", "loco_b", "paper_loco"]].round(4).to_string(index=False))
for reading in ["loco_a", "loco_b"]:
if main6[reading].notna().all():
r = o.pearson(main6[reading], main6.d)
print(f"reading ({reading[-1]}): r = {r['r']:.3f}, t({r['df']}) = {r['t']:.3f}, two-sided p = {r['p']:.4f}, "
f"95% CI [{r['ci_low']:.3f}, {r['ci_high']:.3f}] (paper r = 0.896, p = 0.0157)")
r44 = o.pearson(eff[reading], eff.d)
print(f" all 44 sessions: r = {r44['r']:.3f}, p = {r44['p']:.3g}")
else:
print(f"reading ({reading[-1]}): not available")
ok = eff.loco_b.notna()
if ok.any():
print(f"\nLocomotion fraction, reading (b) against the code's printed values (behavior_by_session.parquet), "
f"{int(ok.sum())} sessions: max abs difference {float((eff.loco_b - eff.paper_loco)[ok].abs().max()):.4f}")
print(f"Locomotion fraction, reading (a) against the code's printed values: max abs difference "
f"{float((eff.loco_a - eff.paper_loco).abs().max()):.4f}")
for reading in ["loco_a", "loco_b"]:
if main6[reading].notna().all():
r = o.pearson(main6[reading], main6.d_code_sd)
print(f"Variant, d with the code's SD, reading ({reading[-1]}): r = {r['r']:.3f}, p = {r['p']:.4f}")
rp = o.pearson(main6.paper_loco, main6.paper_d)
print(f"The code's own printed values (effect_size and behavior_by_session): r = {rp['r']:.3f}, p = {rp['p']:.4f}")
session area mouse_id d d_code_sd paper_d loco_a loco_b paper_loco
717235570 AL 389014 0.5725 0.5836 0.6004 0.1091 0.1088 0.1088
718470715 AM 389014 0.6056 0.5900 0.5705 0.0721 0.0721 0.0721
717235520 AL 389020 0.8757 0.8756 0.8627 0.1267 0.1265 0.1265
718469817 AM 389020 0.8121 0.8098 0.7903 0.1280 0.1275 0.1275
718575398 AM 390958 0.7566 0.8182 0.8056 0.1472 0.1471 0.1471
719080059 AL 390958 1.1111 1.1939 1.2577 0.1756 0.1759 0.1759
reading (a): r = 0.842, t(4) = 3.126, two-sided p = 0.0353, 95% CI [0.097, 0.982] (paper r = 0.896, p = 0.0157)
all 44 sessions: r = -0.032, p = 0.836
reading (b): r = 0.844, t(4) = 3.146, two-sided p = 0.0347, 95% CI [0.103, 0.983] (paper r = 0.896, p = 0.0157)
all 44 sessions: r = -0.032, p = 0.836
Locomotion fraction, reading (b) against the code's printed values (behavior_by_session.parquet), 44 sessions: max abs difference 0.0001
Locomotion fraction, reading (a) against the code's printed values: max abs difference 0.0008
Variant, d with the code's SD, reading (a): r = 0.892, p = 0.0169
Variant, d with the code's SD, reading (b): r = 0.894, p = 0.0164
The code's own printed values (effect_size and behavior_by_session): r = 0.896, p = 0.0157
Result: reproduced. Across the six L2/3 AL and AM sessions, Cohen's d correlates with the locomotion fraction at r = 0.842 (two-sided p = 0.035) under reading (a) and r = 0.844 (p = 0.035) under reading (b), both within tolerance of 0.896 (0.792 to 1) and significant. Reading (b) gives the code's printed locomotion fractions to within 0.0001, and reading (a) to within 0.0008, so the difference from the paper's r comes from the effect sizes (d 1.111 against the code's stored 1.258 for one session), not from running. With d computed with the pooled SD as the paper's code computes it (variant; see discussion-session-effect-sizes in the main notebook), r = 0.892 (p = 0.017) under reading (a) and 0.894 (p = 0.016) under reading (b), next to the code's own 0.896. Over all 44 sessions there is no correlation (r = -0.03). The deposit stream reached the running parameters before its deadline (the output above gives the time), so both readings are shown.
fig4-pupil-effect-size (blocked; variant shown)¶
In L2/3 of AL and AM, the per-session effect size is positively but not significantly correlated with mean normalized pupil diameter (r = 0.716, p = 0.109).
Blocked as data_missing: the Methods' diameter (twice the semi-major axis of the fitted ellipse) is in no public file. The code's reading, 2*sqrt(area/pi) from the deposit's pupil area, is shown with both readings of artifact removal; it does not decide the claim.
pup = {"a": [], "b": []}
for (_, u), s in zip(use.iterrows(), sess):
key = f"./data/eye/{u.identifier}_area.npy"
sy = sync.get(u.paper_session)
if key not in got or sy is None:
pup["a"].append(np.nan); pup["b"].append(np.nan)
continue
area = np.load(io.BytesIO(got[key]))
pup["a"].append(np.nanmean(o.pupil_code_reading(area, sy["eye_tracking_alignment"], s["n_frames"], s["block"])))
pup["b"].append(np.nanmean(o.pupil_code_reading(area, sy["eye_tracking_alignment"], s["n_frames"], s["block"],
eye_params["pupil"], u.paper_session)) if eye_params else np.nan)
eff["pupil_a"], eff["pupil_b"] = pup["a"], pup["b"]
main6 = eff[(eff.layer == "L2/3") & eff.area.isin(["AL", "AM"])]
print(main6[["session", "d", "pupil_a", "pupil_b", "paper_pupil"]].round(4).to_string(index=False))
for reading in ["pupil_a", "pupil_b"]:
if main6[reading].notna().all():
r = o.pearson(main6[reading], main6.d)
print(f"code diameter, artifact reading ({reading[-1]}): r = {r['r']:.3f}, p = {r['p']:.3f} (paper r = 0.716, p = 0.109)")
print(f"\nnotebook ran in {(time.time() - started) / 60:.1f} min")
session d pupil_a pupil_b paper_pupil 717235570 0.5725 0.2303 0.4697 0.4697 718470715 0.6056 0.2729 0.3919 0.3919 717235520 0.8757 0.0391 0.4562 0.4562 718469817 0.8121 0.2367 0.4975 0.4975 718575398 0.7566 0.0469 0.5095 0.5095 719080059 1.1111 0.0750 0.5273 0.5273 code diameter, artifact reading (a): r = -0.647, p = 0.165 (paper r = 0.716, p = 0.109) code diameter, artifact reading (b): r = 0.651, p = 0.161 (paper r = 0.716, p = 0.109) notebook ran in 5.0 min
Result: blocked (data_missing). The criterion requires the result under every reading of pupil diameter, and the Methods' reading (twice the semi-major axis of the fitted ellipse) cannot be computed from any public file: the dandiset has no eye tracking and the deposit holds only pupil area. With the code's diameter, as a variant, reading (b) of artifact removal gives the code's printed per-session pupil values exactly and r = 0.651 (p = 0.16), positive and within tolerance of 0.716; reading (a), with no artifact removal, gives r = -0.647 (p = 0.17), because unremoved artifacts set the maximum the diameter is normalised by (session means 0.04 to 0.27 against 0.39 to 0.53). So even the code's reading alone would be blocked as methods_underspecified under the criterion, since its two artifact readings disagree.
Summary¶
| Claim | Outcome |
|---|---|
| fig4-locomotion-effect-size | reproduced |
| fig4-pupil-effect-size | blocked: data missing |
The table of all claims, the differences from the paper's method and what was found about the
dataset are in the summary of reproduce_mayner_2022.ipynb. In this notebook, the dandiset's
running velocity reproduces the paper's locomotion fractions under both readings; the pupil
data and the running artifact parameters come from the paper's Zenodo deposit, which the
dandiset does not replace.