Reproducing Mayner, Marshall, Billeh et al. (2022) from dandiset 000036¶

Paper. Mayner WGP, Marshall W, Billeh YN, et al. (2022). Measuring stimulus-evoked neurophysiological differentiation in distinct populations of neurons in mouse visual cortex. eNeuro 9(1) ENEURO.0280-21.2021. doi:10.1523/eneuro.0280-21.2021. The claims file (claims/000036/10.1523-eneuro.0280-21.2021.yaml) was written from the version of record, full text from Europe PMC (PMC8856714), with the legends of the Extended Data figures, and from the paper's code at commit 2d959bd.

Dandiset. DANDI:000036, version 0.230515.1917. The paper cites no DANDI version (it names its code repository, whose README points to a Zenodo deposit). This is the only published version; the draft holds the same 57 files with the same sizes and differs only in metadata (contributors, ethics approval and other fields) that the analysis does not use.

What the dandiset holds. 57 two-photon sessions from 9 mice (dF/F per ROI, ROI masks, running velocity, and the 12 movies with their presentation times). The paper analysed 44 of them; 12 more are not in the paper, and one is the session it excluded. There are no L0 events and no eye tracking.

Outside inputs. The paper's code, GitHub wmayner/openscope-differentiation at commit 2d959bd71b47055d2a3fd306091fe9254ceb86fb: its results/main.parquet identifies the 44 analysed sessions (claim session-link) and, with other files of results/, gives reference values that are printed beside the results. The arousal notebook also streams the paper's Zenodo deposit (doi:10.5281/zenodo.5781567) for the running artifact parameters, the sync alignment and pupil area.

Notebooks. This one tests most claims. multivariate_mayner_2022.ipynb tests the two UMAP claims and arousal_mayner_2022.ipynb the running and pupil claims of Figure 4.

Claim Status Where
session-link (link claim added here) tested this notebook
design-sessions tested this notebook
ext1-2-cell-counts tested this notebook
ext1-3-kinetics-no-difference blocked: not runnable (L0 events)
fig3a-layer-specific tested this notebook
fig3b-area-specific tested this notebook
ext3-1-natural-artificial tested this notebook
ext3-2-sensitivity tested this notebook
ext3-5-arousal-covariates blocked: data missing (pupil diameter)
ext3-8-events-spectral blocked: not runnable (L0 events)
ext3-9-no-transients blocked: not runnable (L0 events)
mediation-event-magnitude blocked: not runnable (L0 events)
table1-permutation tested this notebook
fig4-locomotion-effect-size tested arousal notebook
fig4-pupil-effect-size blocked: data missing (code's variant shown) arousal notebook
discussion-session-effect-sizes tested this notebook
fig5-multivariate-layer tested multivariate notebook
fig5-multivariate-area tested multivariate notebook
ext5-1-events-multivariate blocked: not runnable (L0 events)
fig6-category-decoding tested this notebook
ext6-1-identity-decoding tested this notebook
fig7-stimulus-effect tested this notebook
fig7-snake-highest tested this notebook
ext7-1-arousal-mediation blocked: data missing (pupil diameter)
fig8-nd-sd-correlation tested this notebook
fig8-no-sd-relation-controlled tested this notebook
ext8-1-no-low-level-relation tested; blocked by its own rule (readings differ) this notebook

Five claims need L0 calcium events, which the dandiset does not hold. Their criteria name the detector of AllenInstitute/visual_coding_2p_analysis (l0_analysis.py) run on the dandiset's dF/F. That file is Python 2 code that imports allensdk and the compiled package FastLZeroSpikeInference, which is not on PyPI. The section "Blocked claims" at the end shows, from the published sources, why it cannot be installed as published: the package's setup.py does not find its C++ sources, its current Python API has no arfpop, the function l0_analysis.py calls, and the last version that has it is Python 2 code whose C++ lacks an include it needs. The paper's own events are in its Zenodo deposit, but the criteria do not name them. Three claims need the pupil diameter the Methods define (twice the semi-major axis of the fitted ellipse): the dandiset has no eye tracking (listing below), and the deposit holds only pupil area (listed in the arousal notebook).

In [1]:
import os

os.environ["OMP_NUM_THREADS"] = "1"
os.environ["OPENBLAS_NUM_THREADS"] = "1"
os.environ["MKL_NUM_THREADS"] = "1"

import multiprocessing as mp
import time
import warnings
from concurrent.futures import ProcessPoolExecutor

import numpy as np
import pandas as pd
import scipy.ndimage
import scipy.stats
import statsmodels.api as sm

import openscope_nd as o

warnings.filterwarnings("ignore")
pd.set_option("display.width", 220)
pd.set_option("display.max_columns", 40)
pd.set_option("display.max_rows", 200)

# The paper's own outputs, used to link sessions and as reference values (attempt `inputs`).
CODE_COMMIT = "2d959bd71b47055d2a3fd306091fe9254ceb86fb"
CODE_RESULTS = f"https://raw.githubusercontent.com/wmayner/openscope-differentiation/{CODE_COMMIT}/results/"

started = time.time()
assets = o.list_assets()
meta = o.read_all_metadata(assets)
print(f"dandiset {o.DANDISET_ID} version {o.DANDISET_VERSION}: {len(assets)} files, "
      f"{assets['size'].sum() / 1e9:.1f} GB; metadata read in {time.time() - started:.0f} s")
dandiset 000036 version 0.230515.1917: 57 files, 79.8 GB; metadata read in 86 s

Data check¶

What the files hold, against the paper's description (claims file, opening comment). Each check is stated under its output.

In [2]:
print("Fields of every file: subject has", sorted({"genotype", "subject_id"}),
      "only (no sex, age or date of birth); one imaging plane; DfOverF, ImageSegmentation (image_mask only),",
      "running_velocity, and per stimulus an IndexSeries with its movie.")
print("\nStimulus series present in every file:", meta.stimuli.map(tuple).nunique() == 1, meta.stimuli.iloc[0])
print("\nIndicator:", meta.indicator.unique(), " stated imaging rate (Hz):", meta.imaging_rate.unique(),
      " running unit:", meta.run_unit.unique())
print("\nSessions by Cre line and mouse:")
print(meta.groupby(["cre", "mouse_id"]).size().to_string())
print("\nSessions by layer (from Cre line) and area; depth (um) per Cre line:",
      meta.groupby("cre").depth.unique().to_dict())
print(pd.crosstab(meta.layer, meta.area).reindex(index=o.LAYERS, columns=o.AREAS).to_string())
Fields of every file: subject has ['genotype', 'subject_id'] only (no sex, age or date of birth); one imaging plane; DfOverF, ImageSegmentation (image_mask only), running_velocity, and per stimulus an IndexSeries with its movie.

Stimulus series present in every file: True ['conspecifics', 'crickets', 'dots', 'human_montage', 'man_writing', 'mouse_montage_1', 'mouse_montage_1_spatial_phase_scramble', 'mouse_montage_1_temporal_phase_scramble', 'mouse_montage_2', 'mousecam', 'mousecam_spatial_phase_scramble', 'noise', 'snake', 'spontaneous']

Indicator: <ArrowStringArray>
['GCaMP6f']
Length: 1, dtype: str  stated imaging rate (Hz): [30.]  running unit: <ArrowStringArray>
['cm/s']
Length: 1, dtype: str

Sessions by Cre line and mouse:
cre   mouse_id
Cux2  389014      10
      389020      10
      390958       5
Rbp4  402796       6
      405808       6
      406876       5
Rorb  392392       5
      395480       6
      395481       4

Sessions by layer (from Cre line) and area; depth (um) per Cre line: {'Cux2': array([175]), 'Rbp4': array([375]), 'Rorb': array([275])}
area   V1  LM  AL  PM  AM
layer                    
L2/3    5   5   5   5   5
L4      3   3   3   3   3
L5      3   3   3   5   3

The archive lists 57 files from 9 mice, three per Cre line, with the genotypes the paper names (Cux2-CreERT2, Rorb-IRES2-Cre, Rbp4-Cre_KL100, each with Camk2a-tTA and Ai93). Layer is not stated in the files; it follows from the Cre line and the depth (175, 275 and 375 um). The paper has 45 sessions, 15 per line; the files hold 25 Cux2, 15 Rorb and 17 Rbp4 sessions, so 12 more than the paper describes. The subject's sex is not in the files.

In [3]:
tree = o.nwb_tree(meta.url.iloc[0])
print(meta.path.iloc[0], "holds", len(tree), "groups and datasets. Top level and everything under /acquisition and /processing:")
shown = tree[(tree.path.str.count("/") == 1) | tree.path.str.startswith(("/acquisition", "/processing"))]
print(shown.to_string(index=False))
from concurrent.futures import ThreadPoolExecutor
with ThreadPoolExecutor(12) as ex:
    trees = list(ex.map(o.nwb_tree, meta.url))
hits = sorted({p for t in trees for p in t.path[t.path.str.contains("event|eye|pupil|ellipse|/sex$|/age$|birth", case=False)]})
print("\nPaths in any of the", len(trees), "files naming events, eye, pupil, ellipse, sex, age or birth:", hits if hits else "none")
print("Objects per file:", sorted({len(t) for t in trees}))
sub-389014/sub-389014_ses-20180705T152908_behavior+image+ophys.nwb holds 163 groups and datasets. Top level and everything under /acquisition and /processing:
                                                                  path    kind          shape       neurodata_type
                                                          /acquisition   group           None                     
                                                             /analysis   group           None                     
                                                     /file_create_date dataset           (1,)                     
                                                              /general   group           None                     
                                                           /identifier dataset             ()                     
                                                           /processing   group           None                     
                                                  /processing/behavior   group           None     ProcessingModule
                             /processing/behavior/BehavioralTimeSeries   group           None BehavioralTimeSeries
            /processing/behavior/BehavioralTimeSeries/running_velocity   group           None           TimeSeries
       /processing/behavior/BehavioralTimeSeries/running_velocity/data dataset      (252239,)                     
 /processing/behavior/BehavioralTimeSeries/running_velocity/timestamps dataset      (252238,)                     
                                                     /processing/ophys   group           None     ProcessingModule
                                             /processing/ophys/DfOverF   group           None              DfOverF
                             /processing/ophys/DfOverF/imaging_plane_1   group           None    RoiResponseSeries
                        /processing/ophys/DfOverF/imaging_plane_1/data dataset   (41, 127177)                     
                        /processing/ophys/DfOverF/imaging_plane_1/rois dataset          (41,)   DynamicTableRegion
                  /processing/ophys/DfOverF/imaging_plane_1/timestamps dataset      (127178,)                     
                                   /processing/ophys/ImageSegmentation   group           None    ImageSegmentation
                 /processing/ophys/ImageSegmentation/PlaneSegmentation   group           None    PlaneSegmentation
              /processing/ophys/ImageSegmentation/PlaneSegmentation/id dataset          (41,)   ElementIdentifiers
      /processing/ophys/ImageSegmentation/PlaneSegmentation/image_mask dataset (41, 512, 512)           VectorData
/processing/ophys/ImageSegmentation/PlaneSegmentation/reference_images   group           None                     
                                                  /session_description dataset             ()                     
                                                   /session_start_time dataset             ()                     
                                                       /specifications   group           None                     
                                                             /stimulus   group           None                     
                                            /timestamps_reference_time dataset             ()                     
Paths in any of the 57 files naming events, eye, pupil, ellipse, sex, age or birth: none
Objects per file: [163]

Every file holds the same few objects: under /processing only the DfOverF and ImageSegmentation of the ophys module and the running velocity of the behavior module, and nothing under /acquisition. No path names events, eye tracking, pupil or an ellipse, so the dandiset holds neither L0 events nor eye data.

In [4]:
paper = pd.read_parquet(CODE_RESULTS + "main.parquet")
paper_sessions = (paper.groupby("session").first()
                  [["mouse_id", "cre", "area", "layer", "depth", "ncells", "start_time", "sex"]]
                  .reset_index().rename(columns={"session": "paper_session"}))
paper_sessions["area"] = paper_sessions.area.astype(str)
paper_sessions["layer"] = paper_sessions.layer.astype(str)
meta["start_nwb"] = pd.to_datetime(meta.session_start_time.str[:23])
meta["start_minus_7h"] = meta.start_nwb - pd.Timedelta(hours=7)
link = meta.merge(paper_sessions.add_prefix("paper_").rename(columns={"paper_paper_session": "paper_session"}),
                  left_on=["mouse_id", "start_minus_7h"], right_on=["paper_mouse_id", "paper_start_time"],
                  how="left")
link["in_paper"] = link.paper_session.notna()
print("Paper's sessions (results/main.parquet):", len(paper_sessions))
print("Dandiset sessions matched on mouse id and start time minus 7 h, to the millisecond:",
      int(link.in_paper.sum()), "; paper sessions left unmatched:",
      len(set(paper_sessions.paper_session) - set(link.paper_session.dropna())))
for k in [0, 1, 2, 3, 4, 5, 6, 8]:
    n = meta.merge(paper_sessions, left_on=["mouse_id", meta.start_nwb - pd.Timedelta(hours=k)],
                   right_on=["mouse_id", "start_time"]).shape[0]
    print(f"  matches with an offset of {k} h: {n}")
print("NWB start times (hour of day, as labelled -07:00):", sorted(meta.start_nwb.dt.hour.unique()))
print("Paper start times (hour of day):", sorted(paper_sessions.start_time.dt.hour.unique()))
print("\nDandiset sessions not in the paper's table:")
print(link.loc[~link.in_paper, ["path", "identifier", "mouse_id", "cre", "area", "n_frames"]].to_string(index=False))
Paper's sessions (results/main.parquet): 44
Dandiset sessions matched on mouse id and start time minus 7 h, to the millisecond: 44 ; paper sessions left unmatched: 0
  matches with an offset of 0 h: 0
  matches with an offset of 1 h: 0
  matches with an offset of 2 h: 0
  matches with an offset of 3 h: 0
  matches with an offset of 4 h: 0
  matches with an offset of 5 h: 0
  matches with an offset of 6 h: 0
  matches with an offset of 8 h: 0
NWB start times (hour of day, as labelled -07:00): [np.int32(0), np.int32(15), np.int32(16), np.int32(17), np.int32(18), np.int32(19), np.int32(20), np.int32(21), np.int32(22), np.int32(23)]
Paper start times (hour of day): [np.int32(8), np.int32(9), np.int32(10), np.int32(11), np.int32(12), np.int32(13), np.int32(14), np.int32(15), np.int32(16), np.int32(17)]

Dandiset sessions not in the paper's table:
                                                              path  identifier  mouse_id  cre area  n_frames
sub-389014/sub-389014_ses-20180713T154058_behavior+image+ophys.nwb   719367954    389014 Cux2   V1    127161
sub-389014/sub-389014_ses-20180716T154015_behavior+image+ophys.nwb   720111521    389014 Cux2   AM    127178
sub-389014/sub-389014_ses-20180718T153707_behavior+image+ophys.nwb   720899058    389014 Cux2   PM    127177
sub-389014/sub-389014_ses-20180723T154111_behavior+image+ophys.nwb   723200965    389014 Cux2   AL    127177
sub-389014/sub-389014_ses-20180724T154216_behavior+image+ophys.nwb   723852203    389014 Cux2   LM    127163
sub-389020/sub-389020_ses-20180713T153905_behavior+image+ophys.nwb   719349571    389020 Cux2   V1    126860
sub-389020/sub-389020_ses-20180716T152622_behavior+image+ophys.nwb   720111510    389020 Cux2   AM    126868
sub-389020/sub-389020_ses-20180717T152348_behavior+image+ophys.nwb   720422545    389020 Cux2   PM    126868
sub-389020/sub-389020_ses-20180718T152401_behavior+image+ophys.nwb   720899054    389020 Cux2   AL    126859
sub-389020/sub-389020_ses-20180723T152916_behavior+image+ophys.nwb   723200952    389020 Cux2   LM    126865
sub-402796/sub-402796_ses-20180824T201109_behavior+image+ophys.nwb   741889312    402796 Rbp4   AL     63586
sub-402796/sub-402796_ses-20180831T004642_behavior+image+ophys.nwb   744530725    402796 Rbp4   PM    127150
sub-405808/sub-405808_ses-20180914T231328_behavior+image+ophys.nwb   753917323    405808 Rbp4   PM    126839

The NWB session_start_time of every session equals the paper's start time plus exactly 7 hours (44 of 44 at 7 h, none at other offsets). The NWB times are labelled -07:00 but run from 15:00 to 00:46, while the paper's run from 08:00 to 17:44; the NWB times look like UTC labelled as Pacific time. This is consistent with the data, not shown by it. The NWB identifier (for example 717235570) is not the paper's session id (717911143); it is the number the pupil files of the paper's Zenodo deposit are named by. Of the 13 sessions the paper's table lacks, one is the L5 AL session of mouse 402796 with half the frames (63586), which fits the session the paper excluded for "technical problems with the two-photon recording"; the other 12 are second recordings of the same areas in mice 389014 and 389020 (Cux2) and two more PM sessions in mice 402796 and 405808 (Rbp4). Nothing in the files marks which sessions the paper used.

In [5]:
paper_nd = {s: {(st, int(t)): v for st, t, v in zip(g.stimulus, g.trial, g.differentiation)}
            for s, g in paper.groupby("session")}
# Six of the 108 parameter sets, one per window and frequency spacing, at different state lengths
# and metrics, are checked against the paper's per-trial values (data check of ext3-2-sensitivity).
CHECK = {(0.5, "cityblock", False, None), (2, "chebyshev", True, None), (0.2, "euclidean", False, "tukey"),
         (5, "cityblock", True, "tukey"), (1, "chebyshev", False, "kaiser"), (10, "euclidean", True, "kaiser")}
check_sets = {k: ps for k, ps in enumerate(o.SENSITIVITY_SETS)
              if (ps["state_length"], ps["metric"], ps["log_frequency"], ps["window"]) in CHECK}
paper_sa = pd.read_parquet(CODE_RESULTS + "sensitivity_analysis.parquet")
paper_sa["window"] = paper_sa.window.where(paper_sa.window.notna(), None)
paper_sa["set"] = -1
for k, ps in enumerate(o.SENSITIVITY_SETS):
    m = ((paper_sa.state_length == ps["state_length"]) & (paper_sa.metric == ps["metric"])
         & (paper_sa.log_frequency == ps["log_frequency"])
         & ((paper_sa.window == ps["window"]) if ps["window"] else paper_sa.window.isna()))
    paper_sa.loc[m, "set"] = k
paper_sens = {}
for (s, k), g in paper_sa[paper_sa.set.isin(list(check_sets))].groupby(["session", "set"]):
    paper_sens.setdefault(s, {})[k] = {(st, int(t)): v for st, t, v in zip(g.stimulus, g.trial, g.differentiation)}
jobs = [(row.url, bool(row.in_paper), paper_nd.get(row.paper_session), paper_sens.get(row.paper_session))
        for row in link.itertuples()]
t0 = time.time()
with ProcessPoolExecutor(4, mp_context=mp.get_context("spawn")) as ex:
    futures = [ex.submit(o.process_session, *job) for job in jobs]
    results = [f.result() for f in futures]
print(f"processed {len(results)} sessions in {(time.time() - t0) / 60:.1f} min")

session_cols = ["identifier", "path", "mouse_id", "cre", "layer", "area", "depth", "in_paper",
                "paper_session", "paper_ncells"]
sessions = link[session_cols].copy()
sessions["session"] = sessions.identifier
for key in ["ncells", "n_rois", "nan_rois", "all_nan_rois", "n_frames", "locomotion_fraction_a"]:
    sessions[key] = [r[key] for r in results]
trials = pd.concat([r["trials"].assign(session=s) for r, s in zip(results, sessions.session)])
trials = trials.merge(sessions[["session", "layer", "area", "in_paper", "ncells", "mouse_id"]], on="session")
trials = trials.merge(o.STIMULI.reset_index()[["stimulus", "stimulus_type", "scrambled_pair", "continuous"]],
                      on="stimulus")
main = trials[trials.in_paper & trials.complete].copy()
contrast = main[main.scrambled_pair].copy()
print("trials in the 44 linked sessions:", len(main), "; contrast trials:", len(contrast))
processed 57 sessions in 16.0 min
trials in the 44 linked sessions: 5280 ; contrast trials: 2200
In [6]:
print("ROIs per session: all-NaN traces, and ROIs with any NaN")
print(sessions.groupby("in_paper")[["n_rois", "nan_rois", "all_nan_rois", "ncells"]].sum().to_string())
print("\nSessions with NaN ROIs:")
print(sessions.loc[sessions.nan_rois > 0, ["identifier", "paper_session", "layer", "area", "n_rois",
                                            "nan_rois", "ncells", "paper_ncells"]].to_string(index=False))
lp = sessions[sessions.in_paper]
print("\nLinked sessions whose non-NaN ROI count equals the paper's ncells:",
      int((lp.ncells == lp.paper_ncells).sum()), "of", len(lp))
print("Linked sessions whose total ROI count equals the paper's ncells:",
      int((lp.n_rois == lp.paper_ncells).sum()), "of", len(lp))
dff_lo = np.array([r["dff_range"][0] for r in results]); dff_hi = np.array([r["dff_range"][1] for r in results])
pct = np.array([r["dff_pct"] for r in results])
print(f"\ndF/F over all sessions: min {dff_lo.min():.2f}, max {dff_hi.max():.2f}; per session median "
      f"{np.median(pct[:, 1]):.3f} (range {pct[:, 1].min():.3f} to {pct[:, 1].max():.3f}); "
      f"1st percentile {pct[:, 0].min():.2f} to {pct[:, 0].max():.2f}; 99th {pct[:, 2].min():.2f} to {pct[:, 2].max():.2f}")
ROIs per session: all-NaN traces, and ROIs with any NaN
          n_rois  nan_rois  all_nan_rois  ncells
in_paper                                        
False        748         1             1     747
True        4032        14            14    4018

Sessions with NaN ROIs:
 identifier  paper_session layer area  n_rois  nan_rois  ncells  paper_ncells
  717026762    717210484.0  L2/3   V1     249         2     247         247.0
  718136405    718385159.0  L2/3   PM     132         2     130         130.0
  718922162    719334427.0    L4   V1     294         1     293         293.0
  723931645    724266725.0    L4   V1     101         3      98          98.0
  724284646    724827248.0    L4   PM      58         2      56          56.0
  726519001    729819090.0    L4   AL     287         3     284         284.0
  741889312            NaN    L5   AL      62         1      61           NaN
  742800930    742814901.0    L5   AM      33         1      32          32.0

Linked sessions whose non-NaN ROI count equals the paper's ncells: 44 of 44
Linked sessions whose total ROI count equals the paper's ncells: 37 of 44

dF/F over all sessions: min -128.09, max 123.61; per session median 0.009 (range 0.005 to 0.028); 1st percentile -0.50 to -0.10; 99th 0.23 to 2.95

Fourteen ROIs in seven of the paper's sessions (and one in the excluded session) have dF/F that is NaN at every frame. Without them, the number of ROIs equals the paper's ncells in all 44 sessions. The analyses below use the non-NaN ROIs; an all-NaN trace has no spectrum, and the paper's counts show it did not use them. The files carry no flag that marks them. The dF/F values are fractions (a median near 0, 99th percentiles of 0.2 to 3, with rare extreme values printed above), as the "Normalized fluorescence (A.U.)" unit implies.

In [7]:
dt = np.concatenate([r["frame_dt"] for r in results])
print(f"2p frame intervals over all sessions: median {np.median(dt) * 1000:.3f} ms "
      f"({1 / np.median(dt):.2f} Hz), min {dt.min() * 1000:.3f}, max {dt.max() * 1000:.3f} ms")
per = pd.Series([np.ptp(r["frame_dt"]) * 1e6 for r in results])
med = pd.Series({sid: np.median(r["frame_dt"]) for sid, r in zip(meta.identifier, results)})
print("Sessions whose median frame interval is over 50 ms:", {k: round(v * 1000, 2) for k, v in med[med > 0.05].items()})
print("Spread of frame intervals within a session (max minus min, us): largest",
      round(max(np.ptp(r["frame_dt"]) for r in results) * 1e6, 1))
print("Frames against timestamps (data, timestamps): equal in",
      int((meta.n_frames == meta.n_frame_timestamps).sum()), "files; one more timestamp in",
      int((meta.n_frame_timestamps == meta.n_frames + 1).sum()))
print("Running: samples against timestamps equal in", int((meta.n_run == meta.n_run_timestamps).sum()),
      "files; one more sample than timestamps in", int((meta.n_run == meta.n_run_timestamps + 1).sum()))
rr = pd.DataFrame([{"lo": r["run_range"][0], "hi": r["run_range"][1], "dt": r["run_dt"],
                    "run_start": r["run_span"][0], "frame_start": r["frame_span"][0],
                    "run_end": r["run_span"][1], "frame_end": r["frame_span"][1]} for r in results])
print(f"Running velocity (cm/s): min {rr.lo.min():.1f}, max {rr.hi.max():.1f}; per-session max from "
      f"{rr.hi.min():.1f} to {rr.hi.max():.1f}; sample interval {rr.dt.median() * 1000:.2f} ms")
print(f"Running starts {(rr.run_start - rr.frame_start).min():.1f} to {(rr.run_start - rr.frame_start).max():.1f} s "
      f"after the first frame and ends {(rr.frame_end - rr.run_end).min():.1f} to {(rr.frame_end - rr.run_end).max():.1f} s before the last")
print("Session length (frames): ", meta.n_frames.min(), "to", meta.n_frames.max(),
      f"({meta.n_frames.min() / 30.15 / 60:.0f} to {meta.n_frames.max() / 30.15 / 60:.0f} min)")
2p frame intervals over all sessions: median 33.170 ms (30.15 Hz), min 33.160, max 66.340 ms
Sessions whose median frame interval is over 50 ms: {741889312: 66.33}
Spread of frame intervals within a session (max minus min, us): largest 20.0
Frames against timestamps (data, timestamps): equal in 18 files; one more timestamp in 39
Running: samples against timestamps equal in 0 files; one more sample than timestamps in 57
Running velocity (cm/s): min -654.4, max 525.5; per-session max from 8.4 to 525.5; sample interval 16.68 ms
Running starts 4.4 to 4.8 s after the first frame and ends 5.4 to 5.5 s before the last
Session length (frames):  63586 to 127181 (35 to 70 min)

The stated imaging rate is 30.0 Hz; the frame timestamps step by about 33.17 ms (30.15 Hz), very regularly, except in the half-length L5 AL session of mouse 402796, whose every interval is 66.3 ms: it was imaged at half the frame rate, which fits the paper's "technical problems with the two-photon recording". The arousal notebook shows that the timestamps are the 2p vsync times of the paper's own sync files. The analysis uses the nominal 30 Hz, as the paper's code does. In 39 of 57 files the frame timestamps have one entry more than the dF/F has frames, and in every file the running velocity has one sample more than its timestamps; the extra entries are dropped (the arousal notebook uses every running sample for the deposit's alignment). Running is sampled at 60 Hz, in cm/s; its range (hundreds of cm/s in both directions, printed above) shows artifacts, which the paper removes with per-session parameters (claims file, detail (1)).

In [8]:
trial_check = trials.groupby(["in_paper", "stimulus"]).agg(
    presentations=("trial", "size"), display_frames=("n_display", "unique"),
    first_movie_frame=("movie_first", "unique"), last_movie_frame=("movie_last", "unique"),
    frames_min=("n_frames", "min"), frames_max=("n_frames", "max"), complete=("complete", "sum"))
print(trial_check.to_string())
print("\nPresentations per session and stimulus:", trials.groupby(["session", "stimulus"]).size().unique())
print("Incomplete trials (fewer than 900 frames or past the end of the dF/F):")
print(trials.loc[~trials.complete].groupby("session").size().to_string())
order = trials[trials.in_paper].sort_values(["session", "start_t"])
blocks = order.groupby("session").apply(lambda g: [set(g.stimulus.iloc[i:i + 12]) == set(o.STIMULI.stimulus)
                                                   for i in range(0, 120, 12)])
print("Sessions whose presentations form 10 blocks of the 12 stimuli:", int(blocks.map(all).sum()), "of", len(blocks))
gaps = order.groupby("session").apply(lambda g: np.diff(g.start_t.to_numpy()) - 30.0)
g = np.concatenate(gaps.to_numpy())
print(f"Gap between consecutive movies (s): median {np.median(g):.2f}; within blocks "
      f"{np.percentile(g, 5):.2f} to {np.percentile(g, 85):.2f}; largest {g.max():.1f}")
                                                   presentations display_frames first_movie_frame last_movie_frame  frames_min  frames_max  complete
in_paper stimulus                                                                                                                                   
False    conspecifics                                        130         [1800]               [0]            [899]         452         916       120
         crickets (prey)                                     130         [1800]               [0]            [899]         452         907       120
         human montage                                       130         [1800]               [0]            [899]         452         912       120
         man writing                                         130         [1800]               [0]            [899]         452         907       120
         mouse montage 1                                     130         [1800]               [0]            [899]         452         915       120
         mouse montage 1, spatial phase scramble             130         [1800]               [0]            [899]         452         908       120
         mouse montage 1, temporal phase scramble            130         [1800]               [0]            [899]         452         922       120
         mouse montage 2                                     130         [1800]               [0]            [899]         452         906       120
         mousecam                                            130         [1800]               [0]            [899]         452         906       120
         mousecam, spatial phase scramble                    130         [1800]               [0]            [899]         452         921       120
         noise                                               130         [1800]               [0]            [899]         452         907       120
         snake (predator)                                    130         [1800]               [0]            [899]         452         907       120
True     conspecifics                                        440         [1800]               [0]            [899]         902         922       440
         crickets (prey)                                     440         [1800]               [0]            [899]         903         913       440
         human montage                                       440         [1800]               [0]            [899]         902         922       440
         man writing                                         440         [1800]               [0]            [899]         902         922       440
         mouse montage 1                                     440         [1800]               [0]            [899]         902         914       440
         mouse montage 1, spatial phase scramble             440         [1800]               [0]            [899]         903         907       440
         mouse montage 1, temporal phase scramble            440         [1800]               [0]            [899]         903         923       440
         mouse montage 2                                     440         [1800]               [0]            [899]         903         923       440
         mousecam                                            440         [1800]               [0]            [899]         903         909       440
         mousecam, spatial phase scramble                    440         [1800]               [0]            [899]         903         922       440
         noise                                               440         [1800]               [0]            [899]         903         914       440
         snake (predator)                                    440         [1800]               [0]            [899]         902         922       440

Presentations per session and stimulus: [10]
Incomplete trials (fewer than 900 frames or past the end of the dF/F):
session
741889312    120
Sessions whose presentations form 10 blocks of the 12 stimuli: 44 of 44
Gap between consecutive movies (s): median 4.03; within blocks 4.03 to 4.03; largest 4.6

Every session has 10 presentations of each of the 12 movies, each of 1800 display frames (30 s at 60 Hz, each of the 900 movie frames shown twice), in 10 randomised blocks of the 12, with about 4 s between movies, as the paper describes. A trial spans 905 to 912 2p frames and is cut to 900 (30 one-second states) for the ND. In the excluded half-length session the trials after its last frame are incomplete; no trial of the 44 linked sessions is.

In [9]:
movies_a = {n: o.read_movie(meta.url.iloc[0], n) for n in o.STIMULI.index}
movies_b = {n: o.read_movie(meta.url.iloc[-1], n) for n in o.STIMULI.index}
print("Movie templates identical in the first and last file:",
      all(np.array_equal(movies_a[n], movies_b[n]) for n in o.STIMULI.index))
print(pd.DataFrame({n: {"shape": m.shape, "dtype": str(m.dtype), "min": int(m.min()), "max": int(m.max()),
                        "mean": round(float(m.mean()), 1)} for n, m in movies_a.items()}).T.to_string())
Movie templates identical in the first and last file: True
                                                   shape  dtype min  max   mean
mouse_montage_1                          (900, 120, 192)  uint8   0  255  117.3
mouse_montage_2                          (900, 120, 192)  uint8   1  255  128.5
mousecam                                 (900, 120, 192)  uint8   0  255   86.2
conspecifics                             (900, 120, 192)  uint8   3  250  141.2
crickets                                 (900, 120, 192)  uint8  28  249  171.2
snake                                    (900, 120, 192)  uint8   1  255  115.5
human_montage                            (900, 120, 192)  uint8   0  255  105.6
man_writing                              (900, 120, 192)  uint8   0  253  140.0
mouse_montage_1_temporal_phase_scramble  (900, 120, 192)  uint8   0  255  117.7
mouse_montage_1_spatial_phase_scramble   (900, 120, 192)  uint8   0  255  117.6
mousecam_spatial_phase_scramble          (900, 120, 192)  uint8   0  255  127.9
noise                                    (900, 120, 192)  uint8   0  255  127.5
In [10]:
sig = [r["signature"] for r in results]
pairs = [(sessions.identifier.iloc[i], sessions.identifier.iloc[j]) for i in range(len(sig)) for j in range(i + 1, len(sig))
         if sig[i] is not None and sig[j] is not None and np.allclose(sig[i], sig[j])]
print("Pairs of sessions with an identical first trace:", pairs if pairs else "none")
same = sessions.groupby(["n_frames", "n_rois"]).size()
print("Pairs sharing both frame count and ROI count:", int((same > 1).sum()))
tr_ = [r["mean_trace"] for r in results]
mx = 0.0
for i in range(len(tr_)):
    for j in range(i + 1, len(tr_)):
        n = min(len(tr_[i]), len(tr_[j]))
        mx = max(mx, np.corrcoef(tr_[i][:n], tr_[j][:n])[0, 1])
print(f"Largest correlation between the mean dF/F of two sessions (1 s steps): {mx:.3f}")
Pairs of sessions with an identical first trace: none
Pairs sharing both frame count and ROI count: 0
Largest correlation between the mean dF/F of two sessions (1 s steps): 0.216

No recording is deposited twice: no two sessions share a first trace, no two share both frame and ROI counts, and the population traces of different sessions are not alike.

Do the stimulus times share the clock of the dF/F?¶

Two checks. (1) Decoding which of the 12 movies was shown from each trial's dF/F (the decoder of ext6-1-identity-decoding), with the trial windows where the NWB times put them and moved by -34 s (one presentation earlier, so each window holds the previous movie while keeping its label), -1 s and +1 s. (2) Against the paper's own per-trial ND (results/main.parquet, which was computed from the same dF/F with the paper's stimulus table), the shift of the trial start, in frames from -8 to +3, at which this dF/F gives the paper's value to a relative 1e-6.

In [11]:
timing = pd.DataFrame({s: r["timing_decode"] for s, r in zip(sessions.session, results) if "timing_decode" in r}).T
print("Identity decoding (balanced accuracy, chance 1/12 = 0.083) by window shift (s), 44 sessions:")
print(timing.describe().loc[["mean", "min", "max"]].round(3).to_string())
offs = pd.concat([r["paper_offsets"].assign(session=s) for s, r in zip(sessions.session, results) if "paper_offsets" in r])
print("\nTrials whose ND matches the paper's at exactly one shift:", int(offs.offset.notna().sum()), "of", len(offs),
      "; at more than one:", int((offs.n_hits > 1).sum()), "; at none:", int((offs.n_hits == 0).sum()))
print("Shift (frames; negative = the paper's trial starts earlier):")
print(offs.offset.value_counts().sort_index().to_string())
offs["minute"] = (offs.start_t - offs.groupby("session").start_t.transform("min")) / 60
offs["part"] = pd.cut(offs.minute, [-1, 17, 34, 51, 70], labels=["0-17 min", "17-34", "34-51", "51-70"])
print("\nMean shift by time in the session:")
print(offs.groupby("part").offset.mean().round(2).to_string())
nomatch = offs.groupby("session").offset.apply(lambda x: x.notna().mean())
print("\nSessions where every trial matches at one shift:", int((nomatch == 1).sum()), "of", len(nomatch),
      "; sessions with no match:", list(nomatch[nomatch == 0].index))
lag = pd.Series({s: r["run_xcorr"].idxmax() for s, r in zip(sessions.session, results)})
peak = pd.Series({s: r["run_xcorr"].max() for s, r in zip(sessions.session, results)})
print(f"\nCross-correlation of mean dF/F with running speed: peak at {lag.median():+.1f} s (median; "
      f"IQR {lag.quantile(.25):+.1f} to {lag.quantile(.75):+.1f}), peak r median {peak.median():.2f}; "
      f"sessions with peak r > 0.1: {int((peak > 0.1).sum())} of {len(peak)}")
Identity decoding (balanced accuracy, chance 1/12 = 0.083) by window shift (s), 44 sessions:
      -34.0  -1.0    0.0    1.0 
mean  0.085  0.897  0.900  0.898
min   0.017  0.342  0.333  0.367
max   0.175  1.000  1.000  1.000

Trials whose ND matches the paper's at exactly one shift: 5279 of 5280 ; at more than one: 1 ; at none: 0
Shift (frames; negative = the paper's trial starts earlier):
offset
-6.0       5
-5.0     258
-4.0     915
-3.0    1426
-2.0    1633
-1.0     907
 0.0     135

Mean shift by time in the session:
part
0-17 min   -1.41
17-34      -2.16
34-51      -2.93
51-70      -3.68

Sessions where every trial matches at one shift: 43 of 44 ; sessions with no match: []

Cross-correlation of mean dF/F with running speed: peak at -0.6 s (median; IQR -2.9 to +0.2), peak r median 0.13; sessions with peak r > 0.1: 36 of 57

Identity decoding is far above chance with the NWB times and falls to chance (mean 0.085, chance 0.083) when the windows are moved one presentation back, so the stimulus times and the dF/F share a clock, to within a second at least. The finer check against the paper is more telling. The dF/F is the paper's: with the trial start moved by a few frames, it gives the paper's ND to within 1e-6 for every trial. But the shift is not zero: the paper's trials start 0 to 6 frames (up to 200 ms) before the NWB stimulus times would put them, and the shift grows through the session, from -1.4 frames on average in the first 17 minutes to -3.7 in the last. So, against the 2p frames, the NWB stimulus times run late by an amount that drifts by about 2 to 3 frames over 70 minutes. The arousal notebook shows the same drift between the NWB running timestamps and the vsync-to-frame alignment of the paper's sync files. The analyses use the NWB times, as the dataset gives them; a trial still holds 30 s of the same movie, so the effect on ND is small (next cell). Running speed and mean dF/F are only weakly correlated (median peak r 0.13) and the peak lag varies between sessions, so that check is consistent with one clock but cannot resolve offsets of this size.

session-link: the dandiset's sessions are the paper's¶

Link claim added by this attempt. The dandiset's sessions can be matched to the paper's 44 analysed sessions (the code's results/main.parquet), and matched sessions agree on mouse, Cre line, area, depth and number of cells, and give the paper's per-trial ND.

In [12]:
cmp = link[link.in_paper].copy()
cmp["ncells"] = sessions.loc[sessions.in_paper, "ncells"].to_numpy()
agree = pd.Series({
    "Cre line": (cmp.cre == cmp.paper_cre).mean(),
    "area": (cmp.area == cmp.paper_area).mean(),
    "layer": (cmp.layer == cmp.paper_layer).mean(),
    "depth": (cmp.depth == cmp.paper_depth).mean(),
    "cells (non-NaN ROIs)": (cmp.ncells == cmp.paper_ncells).mean(),
})
print("Matched:", int(link.in_paper.sum()), "of 44 paper sessions; dandiset sessions unmatched:",
      int((~link.in_paper).sum()))
print("Fraction of matched sessions that agree:\n" + agree.to_string())
print(f"\nTrials whose ND equals the paper's at one start shift in -8..+3 frames: "
      f"{offs.offset.notna().mean():.3f} ({int(offs.offset.notna().sum())} of {len(offs)})")
by = offs.groupby("session").offset.apply(lambda x: x.notna().mean())
print("Sessions by fraction of trials matched:", by.round(2).value_counts().sort_index().to_dict())
excluded = link[(~link.in_paper) & (link.cre == "Rbp4") & (link.area == "AL")]
print("\nCandidate for the excluded L5 AL session:", excluded[["identifier", "path", "n_frames"]].to_dict("records"))
y_mine = main.set_index(["session", "stimulus", "trial"]).y
pp = paper.assign(stimulus=paper.stimulus.astype(str), trial=paper.trial.astype(int))
pp = pp.merge(link[["paper_session", "identifier"]].dropna(), left_on="session", right_on="paper_session")
y_paper = pp.set_index(["identifier", "stimulus", "trial"])["log(normalized differentiation)"]
y_paper.index.names = ["session", "stimulus", "trial"]
both = pd.concat([y_mine, y_paper], axis=1, keys=["dandiset", "paper"]).dropna()
d = both.dandiset - both.paper
print(f"\nPer-trial log10 ND, trials as the NWB times give them, against the paper's: n = {len(both)}, "
      f"r = {np.corrcoef(both.dandiset, both.paper)[0, 1]:.4f}, difference mean {d.mean():+.4f}, "
      f"SD {d.std():.4f}, 1st to 99th percentile {d.quantile(.01):+.3f} to {d.quantile(.99):+.3f}")
Matched: 44 of 44 paper sessions; dandiset sessions unmatched: 13
Fraction of matched sessions that agree:
Cre line                1.0
area                    1.0
layer                   1.0
depth                   1.0
cells (non-NaN ROIs)    1.0

Trials whose ND equals the paper's at one start shift in -8..+3 frames: 1.000 (5279 of 5280)
Sessions by fraction of trials matched: {0.99: 1, 1.0: 43}

Candidate for the excluded L5 AL session: [{'identifier': 741889312, 'path': 'sub-402796/sub-402796_ses-20180824T201109_behavior+image+ophys.nwb', 'n_frames': 63586}]

Per-trial log10 ND, trials as the NWB times give them, against the paper's: n = 5280, r = 0.9974, difference mean +0.0009, SD 0.0465, 1st to 99th percentile -0.133 to +0.141

Result: reproduced. All 44 of the paper's sessions match one dandiset session each on mouse and start time (minus 7 hours, to the millisecond), and all 44 agree on Cre line, layer, area, depth and number of cells, once the ROIs whose dF/F is NaN at every frame are left out. The dandiset's dF/F gives the paper's per-trial ND to a relative 1e-6 in all 5280 trials when the trial start is moved by 0 to -6 frames (one trial matches at two shifts), so the dF/F is the paper's; the shift is the drift of the NWB stimulus times described above. With the trial windows the NWB times give, per-trial log10 ND correlates with the paper's at r = 0.997 (difference SD 0.047). The dandiset session the paper lacks in L5 AL is the half-length, half-rate one, which fits the excluded session. Nothing in the dandiset marks which sessions the paper used; the link rests on the code's output.

Check of the statistics code against the paper's printed output¶

The LME, likelihood ratio and post hoc tests are implemented here in Python (statsmodels and scipy), not R. Run on the paper's own per-trial values (results/main.parquet), they should give the paper's printed results (chi2(2) = 13.379 for layer, chi2(4) = 15.203 for area, and the post hoc z values and interval bounds of results/stats).

In [13]:
pv = paper.rename(columns={"log(normalized differentiation)": "y"}).assign(
    layer=paper.layer.astype(str), area=paper.area.astype(str), stimulus=paper.stimulus.astype(str))
for factor in ["layer", "area"]:
    r = o.category_models(pv[pv.stimulus_is_scrambled_pair], factor)
    print(f"{factor}: chi2({r['df']}) = {r['chi2']:.3f}, p = {r['p']:.3g}, n = {r['n']}")
    print(r["posthoc"].round(6).to_string())
levels7 = ["snake (predator)", "conspecifics", "crickets (prey)", "man writing", "mousecam"]
p7 = pv[pv.stimulus.isin(o.CONTINUOUS_NATURAL)].copy()
p7["stimulus"] = pd.Categorical(p7.stimulus, categories=levels7)
pf7 = o.fit_lme(p7, "y ~ C(stimulus)")
pchi7, pdf7, pp7 = o.lrt(pf7, o.fit_lme(p7, "y ~ 1"))
print(f"\nFigure 7 on the paper's data: chi2({pdf7}) = {pchi7:.3f}, p = {pp7:.4g}, n = {len(p7)} (paper chi2(4) = 32.115, p = 1.812e-6)")
ppw = o.emmeans_pairwise_tukey(pf7, levels7, "stimulus")
print(ppw.round(6).to_string(index=False))
print("Paper's printed Tukey tests: snake - conspecifics z = 3.229, p = 0.011, CI [0.015, 0.180]; snake - crickets "
      "z = 3.928, p = 0.0008149, [0.036, 0.201]; snake - man writing z = 5.249, p = 1.522e-06, [0.076, 0.241]; "
      "mousecam - man writing z = 3.396, p = 0.00615, [0.020, 0.185]")
layer: chi2(2) = 13.379, p = 0.00124, n = 2200
      estimate        se         z     p_adj    ci_low
L2/3  0.113259  0.029300  3.865547  0.000166  0.051109
L4    0.005594  0.029300  0.190915  0.809191 -0.056557
L5   -0.035425  0.030328 -1.168059  0.998211 -0.099757
area: chi2(4) = 15.202, p = 0.0043, n = 2200
    estimate        se         z     p_adj    ci_low
V1  0.026602  0.037810  0.703583  0.747856 -0.061066
LM -0.008836  0.037810 -0.233684  0.988747 -0.096504
AL  0.115221  0.040103  2.873116  0.010120  0.022235
PM -0.069673  0.037810 -1.842723  1.000000 -0.157341
AM  0.092470  0.037810  2.445667  0.035627  0.004801

Figure 7 on the paper's data: chi2(4) = 32.115, p = 1.812e-06, n = 2200 (paper chi2(4) = 32.115, p = 1.812e-6)
                          contrast  estimate       se         z  p_tukey    ci_low   ci_high
   snake (predator) - conspecifics  0.097520 0.030205  3.228643 0.010909  0.015129  0.179911
snake (predator) - crickets (prey)  0.118645 0.030205  3.928035 0.000815  0.036253  0.201036
    snake (predator) - man writing  0.158540 0.030205  5.248857 0.000002  0.076148  0.240931
       snake (predator) - mousecam  0.055952 0.030205  1.852434 0.343409 -0.026439  0.138343
    conspecifics - crickets (prey)  0.021125 0.030205  0.699392 0.956678 -0.061266  0.103516
        conspecifics - man writing  0.061020 0.030205  2.020214 0.256157 -0.021372  0.143411
           conspecifics - mousecam -0.041568 0.030205 -1.376208 0.642998 -0.123959  0.040824
     crickets (prey) - man writing  0.039895 0.030205  1.320822 0.678214 -0.042496  0.122286
        crickets (prey) - mousecam -0.062693 0.030205 -2.075600 0.230646 -0.145084  0.019699
            man writing - mousecam -0.102588 0.030205 -3.396423 0.006146 -0.184979 -0.020196
Paper's printed Tukey tests: snake - conspecifics z = 3.229, p = 0.011, CI [0.015, 0.180]; snake - crickets z = 3.928, p = 0.0008149, [0.036, 0.201]; snake - man writing z = 5.249, p = 1.522e-06, [0.076, 0.241]; mousecam - man writing z = 3.396, p = 0.00615, [0.020, 0.185]

The implementation gives the paper's printed values from the paper's data to the printed precision (chi2 13.379 and 15.202 against 15.203; z, adjusted p and interval bounds within 1e-5), so differences below come from the data, not the statistics code. The same holds for Figure 7: on the paper's data the stimulus model gives chi2(4) = 32.115, p = 1.812e-6, and the emmeans-style Tukey tests give the paper's printed z values (3.229, 3.928, 5.249 and 3.396 for the four named pairs), adjusted p (0.0109, 0.00082, 2e-6 and 0.0061) and interval bounds, with the other six pairs not significant.

design-sessions¶

Data come from 45 two-photon sessions in nine mice (three per Cre line for L2/3, L4 and L5), 15 sessions per line and 9 per area over V1, LM, AL, PM and AM, with one L5 AL session excluded for recording problems.

In [14]:
def counts(df, label):
    print(f"--- {label}: {len(df)} sessions, {df.mouse_id.nunique()} mice")
    print("mice per Cre line:", df.groupby("cre").mouse_id.nunique().to_dict())
    print("sessions per Cre line:", df.groupby("cre").size().to_dict())
    print("sessions per area:", df.groupby("area").size().reindex(o.AREAS).to_dict())
    print("sessions per mouse:", df.groupby("mouse_id").size().to_dict())
    print(pd.crosstab(df.layer, df.area).reindex(index=o.LAYERS, columns=o.AREAS).to_string())

counts(link, "dandiset, all files")
paper45 = link[link.in_paper | link.identifier.isin(excluded.identifier)]
counts(paper45, "the 44 linked sessions and the excluded L5 AL session")
print("\nSex per mouse (not in the files; from the paper's table):",
      paper_sessions.groupby("mouse_id").sex.first().to_dict())
--- dandiset, all files: 57 sessions, 9 mice
mice per Cre line: {'Cux2': 3, 'Rbp4': 3, 'Rorb': 3}
sessions per Cre line: {'Cux2': 25, 'Rbp4': 17, 'Rorb': 15}
sessions per area: {'V1': 11, 'LM': 11, 'AL': 11, 'PM': 13, 'AM': 11}
sessions per mouse: {389014: 10, 389020: 10, 390958: 5, 392392: 5, 395480: 6, 395481: 4, 402796: 6, 405808: 6, 406876: 5}
area   V1  LM  AL  PM  AM
layer                    
L2/3    5   5   5   5   5
L4      3   3   3   3   3
L5      3   3   3   5   3
--- the 44 linked sessions and the excluded L5 AL session: 45 sessions, 9 mice
mice per Cre line: {'Cux2': 3, 'Rbp4': 3, 'Rorb': 3}
sessions per Cre line: {'Cux2': 15, 'Rbp4': 15, 'Rorb': 15}
sessions per area: {'V1': 9, 'LM': 9, 'AL': 9, 'PM': 9, 'AM': 9}
sessions per mouse: {389014: 5, 389020: 5, 390958: 5, 392392: 5, 395480: 6, 395481: 4, 402796: 5, 405808: 5, 406876: 5}
area   V1  LM  AL  PM  AM
layer                    
L2/3    3   3   3   3   3
L4      3   3   3   3   3
L5      3   3   3   3   3

Sex per mouse (not in the files; from the paper's table): {389014: 'M', 389020: 'F', 390958: 'M', 392392: 'M', 395480: 'M', 395481: 'M', 402796: 'M', 405808: 'F', 406876: 'F'}

Result: reproduced. The paper's 45 sessions are all in the dandiset: the 44 linked sessions and the half-length L5 AL session give 45 sessions from 9 mice, 3 mice and 15 sessions per Cre line, 9 per area, 3 per layer and area pair, and 4 to 6 sessions per mouse (the paper's 5 +/- 1). The excluded session is identified by its absence from main.parquet and by its half frame rate. The dandiset holds 12 more (10 Cux2, 2 Rbp4 PM), 57 sessions in all, with 25 Cux2, 15 Rorb and 17 Rbp4 sessions and 11 to 13 per area; these are not described in the paper and not marked in the files, so identifying the paper's sessions needs the code's output (a finding about the dataset, not a failure of the claim). The files do not give the sex of the mice; the paper's table gives 2, 3 and 1 males for the three lines, as the paper states.

ext1-2-cell-counts¶

4018 cells were recorded over the 44 analysed sessions, 1683 in L2/3, 1781 in L4 and 554 in L5, with per layer and area totals from 62 (L4 AM) to 649 (L4 V1).

In [15]:
lp = sessions[sessions.in_paper]
table_s1 = pd.read_csv(CODE_RESULTS + "table-s1.csv").set_index(["layer", "area"]).ncells
cells = lp.groupby(["layer", "area"])[["n_rois", "ncells"]].sum().reindex(table_s1.index)
cells["paper"] = table_s1
cells["within_10pct"] = (cells.ncells - cells.paper).abs() <= 0.1 * cells.paper
print(cells.to_string())
print("\nPer layer:", lp.groupby("layer")[["n_rois", "ncells"]].sum().to_dict())
print("All 44 sessions: ROIs", int(lp.n_rois.sum()), "; non-NaN ROIs", int(lp.ncells.sum()), "; paper 4018")
print("Layer and area totals within 10% of table-s1.csv:", int(cells.within_10pct.sum()), "of 15")
print("All 57 files: ROIs", int(sessions.n_rois.sum()), "; non-NaN", int(sessions.ncells.sum()))
            n_rois  ncells  paper  within_10pct
layer area                                     
L2/3  V1       453     451    451          True
      LM       353     353    353          True
      AL       336     336    336          True
      PM       261     259    259          True
      AM       284     284    284          True
L4    V1       653     649    649          True
      LM       456     456    456          True
      AL       482     479    479          True
      PM       137     135    135          True
      AM        62      62     62          True
L5    V1       126     126    126          True
      LM       185     185    185          True
      AL        86      86     86          True
      PM        76      76     76          True
      AM        82      81     81          True

Per layer: {'n_rois': {'L2/3': 1687, 'L4': 1790, 'L5': 555}, 'ncells': {'L2/3': 1683, 'L4': 1781, 'L5': 554}}
All 44 sessions: ROIs 4032 ; non-NaN ROIs 4018 ; paper 4018
Layer and area totals within 10% of table-s1.csv: 15 of 15
All 57 files: ROIs 4780 ; non-NaN 4765

Result: reproduced. Over the 44 linked sessions the files hold 4032 ROIs, 14 of them NaN at every frame; the other 4018 are 1683 in L2/3, 1781 in L4 and 554 in L5, the paper's counts, and all 15 layer and area totals equal table-s1.csv. Counting the NaN ROIs, the totals (4032; 1687, 1790, 555) are still within 10%. The files have no validity flag; the NaN traces are the only mark of the ROIs the paper did not count.

fig3a-layer-specific¶

Unscrambled stimuli evoke higher ND than their phase-scrambled versions in L2/3 but not in L4 or L5, with a significant layer by stimulus category interaction.

ND as in the claims file's opening comment, on the 5 contrast stimuli of the 44 linked sessions (2200 trials). Model log10 ND ~ layer * category + (1 | session) against the additive model, by maximum likelihood; one-sided single-step post hoc tests of unscrambled minus scrambled per layer. Cohen's d per layer over pooled trials. As a variant, the same on every complete trial of all 57 files, which is what the dandiset alone would give.

In [16]:
def describe_models(r, label):
    print(f"{label}: interaction chi2({r['df']}) = {r['chi2']:.3f}, p = {r['p']:.3g} "
          f"({r['n']} trials, {r['sessions']} sessions)")
    print(r["posthoc"].round(4).to_string())


def d_by(data, factor):
    return data.groupby(factor).apply(lambda g: o.cohens_d(g.y, g.stimulus_type)).reindex(
        o.LAYERS if factor == "layer" else o.AREAS)


all_complete = trials[trials.complete & trials.scrambled_pair]
print("contrast trials per layer (44 sessions):", contrast.groupby("layer").size().to_dict(),
      "; log10 ND range", round(contrast.y.min(), 2), "to", round(contrast.y.max(), 2))
contrast trials per layer (44 sessions):
 {'L2/3': 750, 'L4': 750, 'L5': 700} ; log10 ND range 0.07 to 3.41
In [17]:
r3a = o.category_models(contrast, "layer")
describe_models(r3a, "44 linked sessions")
print("Cohen's d per layer:", d_by(contrast, "layer").round(3).to_dict(), " (paper L2/3 0.164, L4 0.011, L5 -0.067)")
print("Cohen's d per session, by layer (median, min, max):")
sd = contrast.groupby(["session", "layer"]).apply(lambda g: o.cohens_d(g.y, g.stimulus_type)).reset_index(name="d")
print(sd.groupby("layer").d.agg(["median", "min", "max", "size"]).round(3).to_string())
print("Cohen's d per layer by mouse:")
print(contrast.groupby(["layer", "mouse_id"]).apply(lambda g: o.cohens_d(g.y, g.stimulus_type)).round(3).to_string())
rv = o.category_models(all_complete, "layer")
describe_models(rv, "\nVariant, all complete trials of all 57 files")
44 linked sessions: interaction chi2(2) = 14.090, p = 0.000872 (2200 trials, 44 sessions)
      estimate      se       z   p_adj  ci_low
L2/3    0.1122  0.0293  3.8286  0.0002  0.0500
L4      0.0029  0.0293  0.0994  0.8429 -0.0593
L5     -0.0409  0.0303 -1.3483  0.9993 -0.1053
Cohen's d per layer: {'L2/3': 0.163, 'L4': 0.006, 'L5': -0.079}  (paper L2/3 0.164, L4 0.011, L5 -0.067)
Cohen's d per session, by layer (median, min, max):
       median    min    max  size
layer                            
L2/3    0.553 -0.728  1.111    15
L4     -0.046 -0.729  0.508    15
L5      0.032 -0.935  0.287    14
Cohen's d per layer by mouse:
layer  mouse_id
L2/3   389014      0.149
       389020      0.429
       390958      0.293
L4     392392      0.088
       395480     -0.022
       395481     -0.060
L5     402796     -0.044
       405808      0.010
       406876     -0.168
Variant, all complete trials of all 57 files: interaction chi2(2) = 8.735, p = 0.0127 (2800 trials, 56 sessions)
      estimate      se       z   p_adj  ci_low
L2/3    0.0777  0.0227  3.4263  0.0009  0.0296
L4      0.0029  0.0293  0.0996  0.8428 -0.0592
L5     -0.0228  0.0283 -0.8055  0.9907 -0.0829

Result: reproduced. On the 2200 contrast trials of the 44 linked sessions the layer by category interaction is chi2(2) = 14.09, p = 0.00087 (paper 13.379, within tolerance). Unscrambled exceeds scrambled in L2/3 (z = 3.83, adjusted p = 0.0002; Cohen's d 0.163 against 0.164) and not in L4 (adjusted p = 0.84) or L5 (p = 0.999). The L2/3 effect is positive in each of the three Cux2 mice (d 0.15, 0.43 and 0.29). The paper's p-values and z values are matched closely (3.83 against 3.866). On all complete trials of all files, including the 12 sessions the paper did not use, the interaction is weaker (chi2(2) = 8.74, p = 0.013) and L2/3 is still the only significant layer.

fig3b-area-specific¶

The higher ND for unscrambled than scrambled stimuli is specific to areas AL and AM, with a significant area by stimulus category interaction.

In [18]:
r3b = o.category_models(contrast, "area")
describe_models(r3b, "44 linked sessions")
print("Cohen's d per area:", d_by(contrast, "area").round(3).to_dict(), " (paper AL 0.200, AM 0.268)")
print("Cohen's d per area and layer:")
print(contrast.groupby(["layer", "area"]).apply(lambda g: o.cohens_d(g.y, g.stimulus_type)).unstack()
      .reindex(index=o.LAYERS, columns=o.AREAS).round(3).to_string())
print("Cohen's d per area from the paper's own per-trial values (main.parquet):",
      pv[pv.stimulus_is_scrambled_pair].groupby("area").apply(lambda g: o.cohens_d(g.y, g.stimulus_type))
      .reindex(o.AREAS).round(3).to_dict())
print("Variant, the pooled SD as the code computes it (each group's SD weighted by the other group's n - 1): this "
      "dataset", contrast.groupby("area").apply(lambda g: o.cohens_d(g.y, g.stimulus_type, code_sd=True)).reindex(o.AREAS)
      .round(3).to_dict(), "; the paper's per-trial values", pv[pv.stimulus_is_scrambled_pair].groupby("area")
      .apply(lambda g: o.cohens_d(g.y, g.stimulus_type, code_sd=True)).reindex(o.AREAS).round(3).to_dict())
rv = o.category_models(all_complete, "area")
describe_models(rv, "\nVariant, all complete trials of all 57 files")
44 linked sessions: interaction chi2(4) = 15.576, p = 0.00364 (2200 trials, 44 sessions)
    estimate      se       z   p_adj  ci_low
V1    0.0221  0.0378  0.5843  0.8058 -0.0656
LM   -0.0076  0.0378 -0.2013  0.9869 -0.0953
AL    0.1065  0.0401  2.6534  0.0198  0.0134
PM   -0.0768  0.0378 -2.0310  1.0000 -0.1645
AM    0.0960  0.0378  2.5369  0.0277  0.0083
Cohen's d per area: {'V1': 0.045, 'LM': -0.013, 'AL': 0.181, 'PM': -0.137, 'AM': 0.132}  (paper AL 0.200, AM 0.268)
Cohen's d per area and layer:
area      V1     LM     AL     PM     AM
layer                                   
L2/3   0.093  0.075  0.325 -0.070  0.357
L4    -0.092  0.086 -0.056 -0.157  0.105
L5     0.069 -0.176  0.167 -0.302 -0.069
Cohen's d per area from the paper's own per-trial values (main.parquet): {'V1': 0.054, 'LM': -0.016, 'AL': 0.197, 'PM': -0.124, 'AM': 0.127}
Variant, the pooled SD as the code computes it (each group's SD weighted by the other group's n - 1): this dataset {'V1': 0.045, 'LM': -0.013, 'AL': 0.184, 'PM': -0.135, 'AM': 0.133} ; the paper's per-trial values {'V1': 0.054, 'LM': -0.016, 'AL': 0.2, 'PM': -0.122, 'AM': 0.128}
Variant, all complete trials of all 57 files: interaction chi2(4) = 14.393, p = 0.00614 (2800 trials, 56 sessions)
    estimate      se       z   p_adj  ci_low
V1   -0.0204  0.0341 -0.5977  0.9984 -0.0996
LM    0.0112  0.0341  0.3287  0.9017 -0.0679
AL    0.0780  0.0358  2.1772  0.0715 -0.0051
PM   -0.0280  0.0314 -0.8913  0.9998 -0.1008
AM    0.1187  0.0341  3.4767  0.0013  0.0395

Result: reproduced. The area by category interaction is chi2(4) = 15.58, p = 0.0036 (paper 15.203, within tolerance). AL (z = 2.65, adjusted p = 0.020) and AM (z = 2.54, p = 0.028) are significant, and V1, LM and PM are not (adjusted p 0.81 to 1.0). Cohen's d is 0.181 in AL (paper 0.200, within tolerance) and 0.132 in AM, outside the tolerance of the paper's 0.268. The paper's own per-trial values give AM d = 0.127, and 0.128 with the pooled SD as the code computes it (below); the paper's text prints "Cohen's d = 0.268, 95% CI [0.128, inf)" for AM, which looks like a transcription slip (0.128 is the code's d). So the dataset agrees with the paper's computation, not with that printed number. With the pooled SD as the code computes it (each group's SD weighted by the other group's n - 1, see discussion-session-effect-sizes), the paper's per-trial values give AL 0.200 and AM 0.128, the paper's AL value and the code's printed AM value; this dataset gives 0.184 and 0.133. On all files the area result changes: AM stays significant but AL does not (adjusted p = 0.072).

ext3-1-natural-artificial¶

Over all 12 stimuli, naturalistic stimuli evoke higher ND than artificial ones in L2/3 and L5 (not L4) and in AL and AM (not V1, LM or PM), with significant interactions with layer and with area.

In [19]:
print("trials:", len(main), "in", main.session.nunique(), "sessions")
r31l = o.category_models(main, "layer")
describe_models(r31l, "layer")
r31a = o.category_models(main, "area")
describe_models(r31a, "area")
print("area chi2 against the code's printed 22.213")
print("Cohen's d per layer:", d_by(main, "layer").round(3).to_dict(), " (paper L2/3 0.153, L5 0.144)")
print("Cohen's d per area:", d_by(main, "area").round(3).to_dict(), " (paper AL 0.222, AM 0.156)")
trials: 5280 in 44 sessions
layer: interaction chi2(2) = 16.093, p = 0.00032 (5280 trials, 44 sessions)
      estimate      se       z   p_adj  ci_low
L2/3    0.1065  0.0223  4.7782  0.0000  0.0592
L4     -0.0130  0.0223 -0.5821  0.9780 -0.0603
L5      0.0837  0.0231  3.6295  0.0004  0.0348
area: interaction chi2(4) = 21.839, p = 0.000216 (5280 trials, 44 sessions)
    estimate      se       z   p_adj  ci_low
V1    0.0290  0.0288  1.0078  0.5737 -0.0377
LM    0.0440  0.0288  1.5310  0.2773 -0.0227
AL    0.1366  0.0305  4.4771  0.0000  0.0658
PM   -0.0292  0.0288 -1.0170  0.9999 -0.0959
AM    0.1210  0.0288  4.2065  0.0001  0.0543
area chi2 against the code's printed 22.213
Cohen's d per layer: {'L2/3': 0.147, 'L4': -0.025, 'L5': 0.14}  (paper L2/3 0.153, L5 0.144)
Cohen's d per area: {'V1': 0.054, 'LM': 0.075, 'AL': 0.216, 'PM': -0.046, 'AM': 0.156}  (paper AL 0.222, AM 0.156)

Result: reproduced. Over all 12 stimuli (5280 trials) the layer interaction is chi2(2) = 16.09, p = 0.0003 (paper 16.343, within tolerance) and the area interaction chi2(4) = 21.84, p = 0.0002 (the code prints 22.213). Natural exceeds artificial in L2/3 (adjusted p < 0.0001) and L5 (p = 0.0004) but not L4 (p = 0.98), and in AL and AM (both p <= 0.0001) but not V1, LM or PM (p 0.28 to 1.0). Cohen's d is 0.147 for L2/3, 0.140 for L5, 0.216 for AL and 0.156 for AM, all within tolerance.

ext3-2-sensitivity¶

The L2/3, AL and AM specificity of the unscrambled against scrambled ND difference holds for nearly all choices of distance metric, state length, frequency spacing and spectral window.

The 108 parameter sets of the code; for each, the layer and area models and post hoc tests of fig3a and fig3b. A set agrees when both interactions have p < 0.05, L2/3 is the only significant layer, and AL and AM are the only significant areas. Readings of "nearly all": at least 90% and at least 80% of sets.

In [20]:
sens = pd.concat([r["sensitivity"].assign(session=s) for s, r in zip(sessions.session, results) if "sensitivity" in r])
sens = sens.merge(sessions[["session", "layer", "area", "ncells"]], on="session").merge(
    o.STIMULI.reset_index()[["stimulus", "stimulus_type"]], on="stimulus")
sens["y"] = o.log_normalized(sens.nd, sens.ncells)
print("rows:", len(sens), "; sets:", sens.set.nunique(), "; trials per set:", sens.groupby("set").size().unique(),
      "; non-finite log ND:", int((~np.isfinite(sens.y)).sum()))
t0 = time.time()
rows = []
for k, g in sens.groupby("set"):
    rl, ra = o.category_models(g, "layer"), o.category_models(g, "area")
    sig_l = rl["posthoc"].p_adj < 0.05
    sig_a = ra["posthoc"].p_adj < 0.05
    rows.append({**o.SENSITIVITY_SETS[k], "set": k, "chi2_layer": rl["chi2"], "p_layer": rl["p"],
                 "chi2_area": ra["chi2"], "p_area": ra["p"],
                 "sig_layers": ",".join(sig_l[sig_l].index), "sig_areas": ",".join(sig_a[sig_a].index),
                 "agree": rl["p"] < 0.05 and ra["p"] < 0.05 and list(sig_l[sig_l].index) == ["L2/3"]
                 and sorted(sig_a[sig_a].index) == ["AL", "AM"],
                 "loose": bool(sig_l["L2/3"] and sig_a["AL"] and sig_a["AM"])})
sens_stats = pd.DataFrame(rows)
sens_stats["window"] = sens_stats.window.fillna("rectangular")
print(f"models fitted in {(time.time() - t0) / 60:.1f} min")
rows: 237600 ; sets: 108 ; trials per set: [2200] ; non-finite log ND: 0
models fitted in 0.9 min
In [21]:
share = sens_stats.agree.mean()
print(f"Sets that agree: {int(sens_stats.agree.sum())} of {len(sens_stats)} ({share:.1%}); "
      f"looser rule (L2/3, AL and AM each significant): {int(sens_stats.loose.sum())} ({sens_stats.loose.mean():.1%})")
print("Reading 90%:", share >= 0.9, "; reading 80%:", share >= 0.8)
print("\nBy window:")
print(sens_stats.groupby("window")[["agree", "loose"]].mean().round(3).to_string())
print("\nBy state length:")
print(sens_stats.groupby("state_length")[["agree", "loose"]].mean().round(3).to_string())
print("\nBy metric:")
print(sens_stats.groupby("metric")[["agree", "loose"]].mean().round(3).to_string())
print("\nSignificant layers and areas, counts of sets:")
print(sens_stats.sig_layers.value_counts().to_string())
print(sens_stats.sig_areas.value_counts().to_string())
print("\nSets with p < 0.05 for the layer interaction:", int((sens_stats.p_layer < .05).sum()),
      "; for the area interaction:", int((sens_stats.p_area < .05).sum()))
paper_stats = pd.read_parquet(CODE_RESULTS + "stats.parquet").reset_index()
keys = ["state_length", "metric", "window", "window_param", "overlap", "log_frequency"]
ref_rows = []
for _, g in paper_stats.groupby(keys, dropna=False):
    lr = g[g.test_type == "likelihood_ratio"].dropna(subset=["p.value"])
    ph = g[g.test_type == "posthoc"]
    sl = sorted(ph[(ph.interaction == "layer") & (ph["p.value"] < 0.05)].layer.astype(str))
    sa = sorted(ph[(ph.interaction == "area") & (ph["p.value"] < 0.05)].area.astype(str))
    pl = lr.loc[lr.interaction == "layer", "p.value"].iloc[0]
    pa = lr.loc[lr.interaction == "area", "p.value"].iloc[0]
    ref_rows.append({"agree": pl < 0.05 and pa < 0.05 and sl == ["L2/3"] and sa == ["AL", "AM"],
                     "loose": "L2/3" in sl and "AL" in sa and "AM" in sa,
                     "sig_layers": ",".join(sl), "sig_areas": ",".join(sa)})
ref_rows = pd.DataFrame(ref_rows)
print(f"\nReference, the same rule on the paper's own results (stats.parquet): {int(ref_rows.agree.sum())} of "
      f"{len(ref_rows)} sets agree ({ref_rows.agree.mean():.1%}); looser rule {int(ref_rows.loose.sum())}")
print("Paper's results, significant layers and areas, counts of sets:")
print(ref_rows.sig_layers.value_counts().to_string())
print(ref_rows.sig_areas.value_counts().to_string())
main_row = sens_stats[(sens_stats.state_length == 1) & (sens_stats.metric == "euclidean") &
                      (~sens_stats.log_frequency) & (sens_stats.window == "rectangular")]
print("\nMain set:", main_row[["chi2_layer", "p_layer", "chi2_area", "p_area", "sig_layers", "sig_areas", "agree"]]
      .round(4).to_dict("records"))
Sets that agree: 36 of 108 (33.3%); looser rule (L2/3, AL and AM each significant): 36 (33.3%)
Reading 90%: False ; reading 80%: False

By window:
             agree  loose
window                   
kaiser       0.333  0.333
rectangular  0.389  0.389
tukey        0.278  0.278

By state length:
              agree  loose
state_length              
0.2           0.444  0.444
0.5           0.222  0.222
1.0           0.278  0.278
2.0           0.722  0.722
5.0           0.333  0.333
10.0          0.000  0.000

By metric:
           agree  loose
metric                 
chebyshev  0.389  0.389
cityblock  0.167  0.167
euclidean  0.444  0.444

Significant layers and areas, counts of sets:
sig_layers
L2/3    108
sig_areas
AL       41
AL,AM    36
AM       24
          7

Sets with p < 0.05 for the layer interaction: 108 ; for the area interaction: 102
Reference, the same rule on the paper's own results (stats.parquet): 28 of 108 sets agree (25.9%); looser rule 28
Paper's results, significant layers and areas, counts of sets:
sig_layers
L2/3    108
sig_areas
AL       50
AL,AM    28
AM       24
          6

Main set: [{'chi2_layer': 14.09, 'p_layer': 0.0009, 'chi2_area': 15.5755, 'p_area': 0.0036, 'sig_layers': 'L2/3', 'sig_areas': 'AL,AM', 'agree': True}]
In [22]:
chk = pd.concat([r["sensitivity_check"].assign(session=s) for s, r in zip(sessions.session, results)
                 if "sensitivity_check" in r])
summ = chk.groupby("set").rel_diff.agg(trials="size", matched=lambda x: int((x <= 1e-6).sum()), max_rel_diff="max")
summ.index = [", ".join(f"{k} {v}" for k, v in o.SENSITIVITY_SETS[s].items() if k in ("state_length", "metric", "log_frequency", "window"))
              for s in summ.index]
print("Six other parameter sets: this dF/F at the start shift found for the main set (the trial's own length -2 to +2")
print("frames, or 900, until one matches) against the paper's per-trial ND (results/sensitivity_analysis.parquet):")
print(summ.to_string())
lk = link[["paper_session", "identifier"]].dropna().astype(int)
ps_ = paper_sa[paper_sa.stimulus_is_scrambled_pair].merge(lk, left_on="session", right_on="paper_session")
ps_ = ps_.assign(trial=ps_.trial.astype(int), stimulus=ps_.stimulus.astype(str))[
    ["identifier", "set", "stimulus", "trial", "log(normalized differentiation)"]]
both_s = sens.merge(ps_, left_on=["session", "set", "stimulus", "trial"], right_on=["identifier", "set", "stimulus", "trial"])
per_set = both_s.groupby("set").apply(lambda g: pd.Series({
    "n": len(g), "r": np.corrcoef(g.y, g["log(normalized differentiation)"])[0, 1],
    "diff_sd": (g.y - g["log(normalized differentiation)"]).std()}))
print(f"\nAll {len(per_set)} sets, per-trial log10 ND with the NWB trial windows against the paper's: trials per set "
      f"{sorted(per_set.n.astype(int).unique())}; r {per_set.r.min():.4f} to {per_set.r.max():.4f} (median "
      f"{per_set.r.median():.4f}); difference SD {per_set.diff_sd.min():.4f} to {per_set.diff_sd.max():.4f}")
per_set = per_set.join(sens_stats.set_index("set")[["window", "state_length"]])
print("Lowest r by window:", per_set.groupby("window").r.min().round(4).to_dict(),
      "; by state length:", per_set.groupby("state_length").r.min().round(4).to_dict())
Six other parameter sets: this dF/F at the start shift found for the main set (the trial's own length -2 to +2
frames, or 900, until one matches) against the paper's per-trial ND (results/sensitivity_analysis.parquet):
                                                                       trials  matched  max_rel_diff
state_length 0.2, metric euclidean, log_frequency False, window tukey    2199     2199  1.317575e-15
state_length 0.5, metric cityblock, log_frequency False, window None     2199     2199  2.463221e-15
state_length 1, metric chebyshev, log_frequency False, window kaiser     2199     2199  1.290946e-16
state_length 2, metric chebyshev, log_frequency True, window None        2199     2199  3.790453e-16
state_length 5, metric cityblock, log_frequency True, window tukey       2199     2199  1.036004e-14
state_length 10, metric euclidean, log_frequency True, window kaiser     2199     2199  9.286763e-15
All 108 sets, per-trial log10 ND with the NWB trial windows against the paper's: trials per set [np.int64(2200)]; r 0.9934 to 0.9999 (median 0.9985); difference SD 0.0085 to 0.0705
Lowest r by window: {'kaiser': 0.9934, 'rectangular': 0.9955, 'tukey': 0.9954} ; by state length: {0.2: 0.998, 0.5: 0.9958, 1.0: 0.9953, 2.0: 0.9934, 5.0: 0.996, 10.0: 0.9986}

Result: not reproduced. Under the claims file's rule (both interactions significant, L2/3 the only significant layer, AL and AM the only significant areas) 36 of the 108 parameter sets agree (33%), below both readings of "nearly all" (90% and 80%). The layer result is robust: both interactions are significant in 108 and 102 sets, and L2/3 is the only significant layer in all 108. What varies is the area result: AL and AM are both significant in 36 sets, AL alone in 41, AM alone in 24 and neither in 7. Agreement is 39% for the rectangular window, 33% for Kaiser and 28% for Tukey, and 0% at the 10 s state length. The same rule applied to the paper's own sensitivity statistics (results/stats.parquet) gives 28 of 108 (26%); there too L2/3 is the only significant layer in all 108 sets, and AL and AM are both significant in 28, AL alone in 50, AM alone in 24 and neither in 6. So the dataset gives what the paper's code gave; it is the claims file's reading of "nearly all" that the paper's own outputs do not meet. The parameter sets are computed as the paper's code computes them: for six sets, one per window and frequency spacing, this dF/F at the start shift found for the main set gives the paper's per-trial ND (results/sensitivity_analysis.parquet) to a relative 1.1e-14 or less in all 2199 contrast trials that have a single matching shift, and over all 108 sets the per-trial log10 ND with the NWB trial windows correlates with the paper's at r = 0.993 to 0.9999.

table1-permutation¶

Per-session permutation tests find ND greater for unscrambled than scrambled stimuli in all 6 sessions of L2/3 AL and AM, in 8 of 15 L2/3 sessions, 1 of 15 L4 and 0 of 14 L5 sessions.

In [23]:
rng = np.random.default_rng(20220101)
N_PERM = 20_000
perm_rows = []
for s, g in contrast.groupby("session"):
    lab = (g.stimulus_type == "natural").to_numpy()
    perms = np.array([rng.permutation(lab) for _ in range(N_PERM)])
    for scale, vals in (("log10", g.y.to_numpy()), ("untransformed", 10 ** g.y.to_numpy())):
        obs = vals[lab].mean() - vals[~lab].mean()
        null = (perms * vals).sum(1) / lab.sum() - ((~perms) * vals).sum(1) / (~lab).sum()
        perm_rows.append({"session": s, "scale": scale, "observed": obs,
                          "p_greater": float(np.mean(null > obs)), "p_greater_equal": float(np.mean(null >= obs))})
perm = pd.DataFrame(perm_rows).merge(sessions[["session", "layer", "area", "mouse_id"]], on="session")
perm["sig_methods"] = perm.p_greater < 0.05
perm["sig_code"] = perm.p_greater_equal <= 0.05


def table(df, col):
    t = df.groupby(["layer", "area"])[col].agg(lambda x: f"{int(x.sum())} / {len(x)}").unstack().reindex(
        index=o.LAYERS, columns=o.AREAS)
    t["All areas"] = df.groupby("layer")[col].agg(lambda x: f"{int(x.sum())} / {len(x)}")
    return t


for scale in ["log10", "untransformed"]:
    p = perm[perm.scale == scale]
    print(f"--- {scale} ND, Methods rule (p = fraction greater, p < 0.05)")
    print(table(p, "sig_methods").to_string())
    print(f"--- {scale} ND, code rule (greater or equal, p <= 0.05)")
    print(table(p, "sig_code").to_string())
p = perm[perm.scale == "log10"]
print("\nL2/3 AL and AM sessions:")
print(p[(p.layer == "L2/3") & p.area.isin(["AL", "AM"])][["session", "area", "mouse_id", "observed", "p_greater"]]
      .round(5).to_string(index=False))
paper_perm = pd.read_csv(CODE_RESULTS + "permutation_tests_summary.csv")
print("\nThe code's printed table:\n", paper_perm.to_string(index=False))
--- log10 ND, Methods rule (p = fraction greater, p < 0.05)
area      V1     LM     AL     PM     AM All areas
layer                                             
L2/3   1 / 3  1 / 3  3 / 3  0 / 3  3 / 3    8 / 15
L4     0 / 3  1 / 3  0 / 3  0 / 3  0 / 3    1 / 15
L5     0 / 3  0 / 3  0 / 2  0 / 3  0 / 3    0 / 14
--- log10 ND, code rule (greater or equal, p <= 0.05)
area      V1     LM     AL     PM     AM All areas
layer                                             
L2/3   1 / 3  1 / 3  3 / 3  0 / 3  3 / 3    8 / 15
L4     0 / 3  1 / 3  0 / 3  0 / 3  0 / 3    1 / 15
L5     0 / 3  0 / 3  0 / 2  0 / 3  0 / 3    0 / 14
--- untransformed ND, Methods rule (p = fraction greater, p < 0.05)
area      V1     LM     AL     PM     AM All areas
layer                                             
L2/3   1 / 3  0 / 3  2 / 3  0 / 3  2 / 3    5 / 15
L4     0 / 3  1 / 3  0 / 3  0 / 3  0 / 3    1 / 15
L5     0 / 3  0 / 3  0 / 2  0 / 3  0 / 3    0 / 14
--- untransformed ND, code rule (greater or equal, p <= 0.05)
area      V1     LM     AL     PM     AM All areas
layer                                             
L2/3   1 / 3  0 / 3  2 / 3  0 / 3  2 / 3    5 / 15
L4     0 / 3  1 / 3  0 / 3  0 / 3  0 / 3    1 / 15
L5     0 / 3  0 / 3  0 / 2  0 / 3  0 / 3    0 / 14

L2/3 AL and AM sessions:
  session area  mouse_id  observed  p_greater
717235520   AL    389020   0.22414    0.00200
717235570   AL    389014   0.30222    0.02850
718469817   AM    389020   0.31302    0.00455
718470715   AM    389014   0.24829    0.02205
718575398   AM    390958   0.15945    0.00590
719080059   AL    390958   0.20064    0.00005

The code's printed table:
      layer    V1    LM    AL    PM    AM All areas
      L2/3 1 / 3 1 / 3 3 / 3 0 / 3 3 / 3    8 / 15
        L4 0 / 3 1 / 3 0 / 3 0 / 3 0 / 3    1 / 15
        L5 0 / 3 0 / 3 0 / 2 0 / 3 0 / 3    0 / 14
All layers 1 / 9 2 / 9 3 / 8 0 / 9 3 / 9       NaN

Result: reproduced. Under the Methods rule the five counts match: 3 of 3 L2/3 AL sessions, 3 of 3 L2/3 AM, 8 of 15 L2/3, 1 of 15 L4 and 0 of 14 L5. The whole table equals the code's printed table cell by cell, and the code's rule (greater or equal, p <= 0.05) gives the same table. The six L2/3 AL and AM sessions have p from 0.00005 to 0.029. On untransformed ND (variant) only 5 of 15 L2/3 sessions are significant (2 of 3 in AL and in AM).

discussion-session-effect-sizes¶

Within single L2/3 AL and AM sessions effect sizes are medium to very large (Cohen's d 0.57 to 1.25), while the effect over these sessions pooled is 0.34.

In [24]:
sel = contrast[(contrast.layer == "L2/3") & contrast.area.isin(["AL", "AM"])]
per_session = sel.groupby(["session", "area", "mouse_id"]).apply(lambda g: o.cohens_d(g.y, g.stimulus_type))
per_session_code = sel.groupby(["session", "area", "mouse_id"]).apply(lambda g: o.cohens_d(g.y, g.stimulus_type, code_sd=True))
print("Per-session Cohen's d, L2/3 AL and AM (Methods' pooled SD, and the variant with the code's SD):")
print(pd.DataFrame({"d": per_session, "d, code's SD": per_session_code}).round(3).to_string())


def check_d(ps_, pooled, label):
    lo, hi = ps_.min(), ps_.max()
    print(f"{label}: smallest {lo:.3f}, within 0.57 +/- 0.057: {abs(lo - 0.57) <= 0.057}; largest {hi:.3f}, within "
          f"1.25 +/- 0.125: {abs(hi - 1.25) <= 0.125}; all six within 0.513 to 1.375: {bool(ps_.between(0.513, 1.375).all())}; "
          f"pooled over {len(sel)} trials {pooled:.3f}, within 0.34 +/- 0.034: {abs(pooled - 0.34) <= 0.034}")


check_d(per_session, o.cohens_d(sel.y, sel.stimulus_type), "Methods' pooled SD")
check_d(per_session_code, o.cohens_d(sel.y, sel.stimulus_type, code_sd=True), "Variant, code's SD")
ps = pv[pv.stimulus_is_scrambled_pair & (pv.layer == "L2/3") & pv.area.isin(["AL", "AM"])]
from_main = ps.groupby("session").apply(lambda g: o.cohens_d(g.y, g.stimulus_type))
from_main_code = ps.groupby("session").apply(lambda g: o.cohens_d(g.y, g.stimulus_type, code_sd=True))
es_all = pd.read_parquet(CODE_RESULTS + "effect_size.parquet")["Cohen's d"]
print("\nReference, by the paper's session id: d from the paper's per-trial values (main.parquet) with each SD, and "
      "as the code's effect_size.parquet stores it")
print(pd.DataFrame({"main.parquet": from_main, "main.parquet, code's SD": from_main_code,
                    "effect_size.parquet": es_all.reindex(from_main.index)}).round(4).to_string())
pall = pv[pv.stimulus_is_scrambled_pair]
for label, flag in (("Methods' pooled SD", False), ("code's SD", True)):
    dd = pall.groupby("session").apply(lambda g: o.cohens_d(g.y, g.stimulus_type, code_sd=flag))
    print(f"effect_size.parquet against main.parquet, all {len(dd)} sessions, {label}: max abs difference "
          f"{float((dd - es_all.reindex(dd.index)).abs().max()):.2e}")
Per-session Cohen's d, L2/3 AL and AM (Methods' pooled SD, and the variant with the code's SD):
                             d  d, code's SD
session   area mouse_id                     
717235520 AL   389020    0.876         0.876
717235570 AL   389014    0.572         0.584
718469817 AM   389020    0.812         0.810
718470715 AM   389014    0.606         0.590
718575398 AM   390958    0.757         0.818
719080059 AL   390958    1.111         1.194
Methods' pooled SD: smallest 0.572, within 0.57 +/- 0.057: True; largest 1.111, within 1.25 +/- 0.125: False; all six within 0.513 to 1.375: True; pooled over 300 trials 0.340, within 0.34 +/- 0.034: True
Variant, code's SD: smallest 0.584, within 0.57 +/- 0.057: True; largest 1.194, within 1.25 +/- 0.125: True; all six within 0.513 to 1.375: True; pooled over 300 trials 0.343, within 0.34 +/- 0.034: True
Reference, by the paper's session id: d from the paper's per-trial values (main.parquet) with each SD, and as the code's effect_size.parquet stores it
           main.parquet  main.parquet, code's SD  effect_size.parquet
session                                                              
717911123        0.8863                   0.8627               0.8627
717911143        0.5923                   0.6004               0.6004
718673378        0.7934                   0.7903               0.7903
718673398        0.5983                   0.5705               0.5705
718674510        0.7439                   0.8056               0.8056
719334668        1.1547                   1.2577               1.2577
effect_size.parquet against main.parquet, all 44 sessions, Methods' pooled SD: max abs difference 1.03e-01
effect_size.parquet against main.parquet, all 44 sessions, code's SD: max abs difference 4.02e-15

Result: partially reproduced. With the Methods' pooled SD, the six L2/3 AL and AM sessions have Cohen's d from 0.572 to 1.111, all inside 0.513 to 1.375; the smallest is within tolerance of 0.57 and the pooled d over 300 trials is 0.340 (paper 0.34), but the largest, 1.111, is below the tolerance of 1.25 (1.125 to 1.375), so one of the criterion's conditions fails. The paper's 1.25 is not the Methods' formula applied to its own per-trial values (main.parquet gives 1.155 for that session). It is the code's effect_size.parquet (1.258), which equals, to 4e-15 in all 44 sessions, Cohen's d with the pooled SD as the code's analysis.pooled_std_dev computes it: each group's SD weighted by the other group's n - 1 (its groupby sorts "artificial" before "natural" while n1 counts "natural"). With that SD, as a variant, this dataset gives 0.584 to 1.194 and a pooled d of 0.343, all within tolerance. The claims file and the Methods give the standard formula, so the outcome rests on it; the variant is recorded, and a reader is asked which the criterion means.

fig6-category-decoding¶

Stimulus category (unscrambled or scrambled) can be decoded accurately from most layers and areas, well above chance, without the layer and area specificity of ND.

In [25]:
dec = sessions[sessions.in_paper].copy()
dec["category"] = [r["decode_category"] for r, ip in zip(results, sessions.in_paper) if ip]
dec["identity"] = [r["decode_identity"] for r, ip in zip(results, sessions.in_paper) if ip]
paper_dec = pd.read_parquet(CODE_RESULTS + "decoding__stimuli-unscrambled_scrambled__decode-category__scoring-balanced_accuracy.parquet")


def decoding_summary(col, chance):
    pop = dec.groupby(["layer", "area"])[col].mean().unstack().reindex(index=o.LAYERS, columns=o.AREAS)
    print(f"Mean balanced accuracy per population (chance {chance:.3f}):")
    print(pop.round(3).to_string())
    flat = pop.stack()
    for thr in (0.75, 0.9):
        print(f"  populations with mean >= {thr}: {int((flat >= thr).sum())} of 15 (most = 8 or more)")
    print("  per layer:", dec.groupby("layer")[col].mean().round(3).to_dict())
    print("  per area:", dec.groupby("area")[col].mean().reindex(o.AREAS).round(3).to_dict())
    print(f"  per session: min {dec[col].min():.3f}, median {dec[col].median():.3f}, max {dec[col].max():.3f}; "
          f"sessions at or below chance: {int((dec[col] <= chance).sum())}")
    print("  per mouse:", dec.groupby("mouse_id")[col].mean().round(3).to_dict())
    return flat


flat = decoding_summary("category", 0.5)
cmpd = dec.merge(paper_dec[["session", "balanced_accuracy"]], left_on="paper_session", right_on="session")
print(f"\nAgainst the paper's per-session scores: r = {np.corrcoef(cmpd.category, cmpd.balanced_accuracy)[0, 1]:.3f}, "
      f"mean difference {(cmpd.category - cmpd.balanced_accuracy).mean():+.3f}")
Mean balanced accuracy per population (chance 0.500):
area      V1     LM     AL     PM     AM
layer                                   
L2/3   0.958  0.975  0.928  0.950  0.925
L4     0.983  0.958  0.936  0.750  0.664
L5     0.917  0.944  0.925  0.889  0.900
  populations with mean >= 0.75: 14 of 15 (most = 8 or more)
  populations with mean >= 0.9: 12 of 15 (most = 8 or more)
  per layer: {'L2/3': 0.947, 'L4': 0.858, 'L5': 0.914}
  per area: {'V1': 0.953, 'LM': 0.959, 'AL': 0.93, 'PM': 0.863, 'AM': 0.83}
  per session: min 0.575, median 0.950, max 1.000; sessions at or below chance: 0
  per mouse: {389014: 0.907, 389020: 0.955, 390958: 0.98, 392392: 0.847, 395480: 0.797, 395481: 0.965, 402796: 0.931, 405808: 0.935, 406876: 0.88}

Against the paper's per-session scores: r = 0.990, mean difference -0.005

Result: reproduced. Mean balanced accuracy is at least 0.75 in 14 of the 15 layer and area populations and at least 0.9 in 12, so most populations are high under both readings. Every layer (0.86 to 0.95) and every area (0.83 to 0.96) is far above chance (0.5); the lowest session scores 0.575. The lowest populations are L4 AM (0.66) and L4 PM (0.75), and the populations with the ND effect are not the best decoded (L2/3 AL 0.93 and AM 0.93, against L2/3 V1 0.96 and LM 0.98). Per-session accuracies correlate with the paper's at r = 0.990.

ext6-1-identity-decoding¶

Stimulus identity among all 12 stimuli can be decoded accurately from most layers and areas (chance 1/12).

In [26]:
flat_id = decoding_summary("identity", 1 / 12)
paper_id = pd.read_parquet(CODE_RESULTS + "decoding__stimuli-all__decode-identity__scoring-balanced_accuracy.parquet")
cmpi = dec.merge(paper_id[["session", "balanced_accuracy"]], left_on="paper_session", right_on="session")
print(f"\nAgainst the paper's per-session scores: r = {np.corrcoef(cmpi.identity, cmpi.balanced_accuracy)[0, 1]:.3f}, "
      f"mean difference {(cmpi.identity - cmpi.balanced_accuracy).mean():+.3f}")
Mean balanced accuracy per population (chance 0.083):
area      V1     LM     AL     PM     AM
layer                                   
L2/3   0.969  0.972  0.936  0.986  0.967
L4     0.961  0.969  0.942  0.786  0.506
L5     0.931  0.914  0.896  0.861  0.897
  populations with mean >= 0.75: 14 of 15 (most = 8 or more)
  populations with mean >= 0.9: 10 of 15 (most = 8 or more)
  per layer: {'L2/3': 0.966, 'L4': 0.833, 'L5': 0.9}
  per area: {'V1': 0.954, 'LM': 0.952, 'AL': 0.928, 'PM': 0.878, 'AM': 0.79}
  per session: min 0.333, median 0.946, max 1.000; sessions at or below chance: 0
  per mouse: {389014: 0.942, 389020: 0.977, 390958: 0.98, 392392: 0.802, 395480: 0.765, 395481: 0.973, 402796: 0.948, 405808: 0.913, 406876: 0.848}

Against the paper's per-session scores: r = 0.998, mean difference -0.001

Result: reproduced. Identity among the 12 movies is decoded with mean balanced accuracy at least 0.75 in 14 of 15 populations and at least 0.9 in 10, and every layer (0.83 to 0.97) and area (0.79 to 0.95) is far above chance (0.083). L4 AM is the lowest population (0.51). Per-session accuracies correlate with the paper's at r = 0.998.

fig7-stimulus-effect¶

ND differs among the five continuous naturalistic clips, over all layers and areas.

In [27]:
LEVELS7 = ["snake (predator)", "conspecifics", "crickets (prey)", "man writing", "mousecam"]
c7 = main[main.stimulus.isin(o.CONTINUOUS_NATURAL)].copy()
c7["stimulus"] = pd.Categorical(c7.stimulus, categories=LEVELS7)
full7 = o.fit_lme(c7, "y ~ C(stimulus)")
red7 = o.fit_lme(c7, "y ~ 1")
chi7, df7, p7 = o.lrt(full7, red7)
print(f"{len(c7)} trials, {c7.session.nunique()} sessions; stimulus effect chi2({df7}) = {chi7:.3f}, p = {p7:.3g} "
      "(paper 32.115, p = 1.812e-6)")
print("mean log10 ND per clip:", c7.groupby("stimulus").y.mean().round(3).to_dict())
2200 trials, 44 sessions; stimulus effect chi2(4) = 31.545, p = 2.37e-06 (paper 32.115, p = 1.812e-6)
mean log10 ND per clip: {'snake (predator)': 2.069, 'conspecifics': 1.973, 'crickets (prey)': 1.951, 'man writing': 1.915, 'mousecam': 2.017}

Result: reproduced. Over the 2200 trials of the five continuous natural clips, stimulus has a significant effect: chi2(4) = 31.55, p = 2.4e-6 (paper 32.115, p = 1.812e-6, within tolerance).

fig7-snake-highest¶

The snake (predator) clip evokes higher ND than the conspecifics, crickets and man writing clips, and the mousecam clip higher ND than man writing.

In [28]:
pw = o.emmeans_pairwise_tukey(full7, LEVELS7, "stimulus")


def pair_d(a, b):
    g = c7[c7.stimulus.isin([a, b])]
    return o.cohens_d(g.y, g.stimulus.astype(str), a, b)


pw["cohens_d"] = [pair_d(*c.split(" - ")) for c in pw.contrast]
print(pw.round(4).to_string(index=False))
named = {"snake (predator) - conspecifics": (0.015, 0.180, 0.156), "snake (predator) - crickets (prey)": (0.036, 0.201, 0.181),
         "snake (predator) - man writing": (0.076, 0.241, 0.232), "man writing - mousecam": (-0.185, -0.020, -0.154)}
print("\nThe four named pairs (man writing - mousecam is the reverse of mousecam - man writing):")
for c, (lo, hi, dp) in named.items():
    row = pw.set_index("contrast").loc[c]
    print(f"  {c}: estimate {row.estimate:+.3f} (paper CI {lo} to {hi}), adjusted p {row.p_tukey:.3g}, "
          f"d {row.cohens_d:+.3f} (paper {dp:+.3f})")
others = pw[~pw.contrast.isin(named)]
print("Other six pairs with adjusted p < 0.05:", others.loc[others.p_tukey < 0.05, "contrast"].tolist())
                          contrast  estimate     se       z  p_tukey  ci_low  ci_high  cohens_d
   snake (predator) - conspecifics    0.0963 0.0301  3.2020   0.0119  0.0143   0.1784    0.1544
snake (predator) - crickets (prey)    0.1183 0.0301  3.9327   0.0008  0.0363   0.2004    0.1805
    snake (predator) - man writing    0.1545 0.0301  5.1345   0.0000  0.0724   0.2365    0.2268
       snake (predator) - mousecam    0.0519 0.0301  1.7260   0.4178 -0.0301   0.1340    0.0834
    conspecifics - crickets (prey)    0.0220 0.0301  0.7307   0.9494 -0.0601   0.1040    0.0344
        conspecifics - man writing    0.0581 0.0301  1.9325   0.2999 -0.0239   0.1402    0.0873
           conspecifics - mousecam   -0.0444 0.0301 -1.4760   0.5782 -0.1265   0.0377   -0.0733
     crickets (prey) - man writing    0.0362 0.0301  1.2018   0.7504 -0.0459   0.1182    0.0520
        crickets (prey) - mousecam   -0.0664 0.0301 -2.2067   0.1771 -0.1485   0.0157   -0.1040
            man writing - mousecam   -0.1025 0.0301 -3.4085   0.0059 -0.1846  -0.0205   -0.1542

The four named pairs (man writing - mousecam is the reverse of mousecam - man writing):
  snake (predator) - conspecifics: estimate +0.096 (paper CI 0.015 to 0.18), adjusted p 0.0119, d +0.154 (paper +0.156)
  snake (predator) - crickets (prey): estimate +0.118 (paper CI 0.036 to 0.201), adjusted p 0.000799, d +0.181 (paper +0.181)
  snake (predator) - man writing: estimate +0.154 (paper CI 0.076 to 0.241), adjusted p 2.81e-06, d +0.227 (paper +0.232)
  man writing - mousecam: estimate -0.103 (paper CI -0.185 to -0.02), adjusted p 0.00589, d -0.154 (paper -0.154)
Other six pairs with adjusted p < 0.05: []

Result: reproduced. The four named pairs are significant in the stated direction: snake over conspecifics (Tukey-adjusted p = 0.012), over crickets (p = 0.0008) and over man writing (p = 2.8e-6), and mousecam over man writing (p = 0.006). None of the other six pairs is (smallest adjusted p = 0.18, crickets against mousecam). Cohen's d is 0.154, 0.181, 0.227 and 0.154 (paper 0.156, 0.181, 0.232 and 0.154), all within tolerance, and each estimated difference lies inside the paper's interval.

fig8-nd-sd-correlation¶

Within L2/3 of AL and AM, mean ND per stimulus is positively correlated with stimulus differentiation across the 12 stimuli, but the noise stimulus is highly influential (Cook's D 2.318).

Stimulus differentiation (SD) is the ND of the blurred movie with each pixel a cell (no division by pixel count), from the movies in the files. Blur: a Gaussian whose half width at half maximum is the 8.92-degree RF radius (sqrt(250/pi)), on a 120 x 95 degree screen of 192 x 120 pixels, reflect mode, truncate 4 (claims file; code stimulus_properties.ipynb).

In [29]:
RF_RADIUS = np.sqrt(250 / np.pi)
RF_PIXELS = {"x": RF_RADIUS * 192 / 120, "y": RF_RADIUS * 120 / 95}
SIGMA = {k: v / np.sqrt(2 * np.log(2)) for k, v in RF_PIXELS.items()}
print("RF radius (deg):", round(RF_RADIUS, 3), "; sigma (pixels):", {k: round(v, 3) for k, v in SIGMA.items()})
props = []
for name in o.STIMULI.index:
    movie = movies_a[name].astype(np.float64)
    blurred = np.array([scipy.ndimage.gaussian_filter(f, sigma=(SIGMA["y"], SIGMA["x"]), mode="reflect", truncate=4.0)
                        for f in movie])
    pixels = blurred.reshape(blurred.shape[0], -1).T                  # pixel x sample
    sd = o.nd_trial(pixels, state_length=1.0, metric="euclidean")
    energy_global = (np.abs(np.fft.rfft(blurred - blurred.mean(), axis=0)) ** 2).sum()
    energy_pixel = (np.abs(np.fft.rfft(blurred - blurred.mean(axis=0, keepdims=True), axis=0)) ** 2).sum()
    props.append({"stimulus": o.STIMULI.loc[name, "stimulus"], "log_sd": np.log10(sd),
                  "luminance": movie.mean(), "contrast": movie.std(),
                  "energy_pixel_dc": energy_pixel, "energy_global_dc": energy_global})
props = pd.DataFrame(props).set_index("stimulus")
paper_props = pd.read_parquet(CODE_RESULTS + "stimulus_properties.parquet").set_index("stimulus")
props["paper_log_sd"] = paper_props["log(stimulus differentiation)"]
props["paper_energy"] = paper_props["spectral energy"]
sel_all = main[(main.layer == "L2/3") & main.area.isin(["AL", "AM"])]
props["mean_nd"] = sel_all.groupby("stimulus").y.mean()
print(props.round(4).to_string())
print("Sessions:", sel_all.session.nunique(), "; trials:", len(sel_all))
RF radius (deg): 8.921 ; sigma (pixels): {'x': np.float64(12.122), 'y': np.float64(9.57)}
                                          log_sd  luminance  contrast  energy_pixel_dc  energy_global_dc  paper_log_sd  paper_energy  mean_nd
stimulus                                                                                                                                     
mouse montage 1                           9.3402   117.3460   63.8470     2.436700e+13      2.561027e+13        9.3402  2.561027e+13   2.2030
mouse montage 2                           9.3099   128.5031   60.1189     1.643259e+13      2.061243e+13        9.3099  2.061243e+13   2.3215
mousecam                                  9.3100    86.1768   66.9151     2.025315e+13      3.309864e+13        9.3100  3.309864e+13   2.1458
conspecifics                              9.0584   141.2330   62.0554     1.029484e+13      3.803484e+13        9.0584  3.803484e+13   1.9152
crickets (prey)                           8.4104   171.1548   18.6709     1.676491e+11      3.032619e+12        8.4104  3.032619e+12   1.8808
snake (predator)                          9.0600   115.4868   57.7804     7.470758e+12      2.077056e+13        9.0600  2.077056e+13   1.9414
human montage                             9.2030   105.6101   58.5558     1.406521e+13      1.921339e+13        9.2030  1.921339e+13   1.9609
man writing                               8.2327   140.0203   45.0949     1.154705e+11      1.343467e+13        8.2327  1.343467e+13   2.0310
mouse montage 1, temporal phase scramble  9.3411   117.6553   62.7180     2.239213e+13      2.359774e+13        9.3411  2.359774e+13   1.9562
mouse montage 1, spatial phase scramble   9.3051   117.6134   58.8471     2.181990e+13      2.236193e+13        9.3051  2.236193e+13   1.9961
mousecam, spatial phase scramble          9.3566   127.8626   69.3726     2.224693e+13      2.308270e+13        9.3566  2.308270e+13   1.8472
noise                                     6.9226   127.4843   51.2653     2.732770e+09      2.733406e+09        6.9226  2.733406e+09   1.4410
Sessions: 6 ; trials: 720
In [30]:
r8 = o.pearson(props.log_sd, props.mean_nd, "greater")
print(f"12 stimuli: r = {r8['r']:.3f}, t({r8['df']}) = {r8['t']:.3f}, one-sided p = {r8['p']:.4g}, "
      f"95% CI [{r8['ci_low']:.3f}, 1] (paper r = 0.746, p = 0.00267)")
fit8 = sm.OLS(props.mean_nd, sm.add_constant(props.log_sd)).fit()
cooks = pd.Series(fit8.get_influence().cooks_distance[0], index=props.index).sort_values(ascending=False)
print("Cook's distance:\n" + cooks.round(3).to_string())
print("SD from the files' movies against the code's printed log SD: max abs difference",
      round(float((props.log_sd - props.paper_log_sd).abs().max()), 6))
by_area = sel_all.groupby(["area", "stimulus"]).y.mean().unstack(0)
for a in ["AL", "AM"]:
    ra = o.pearson(props.log_sd, by_area.loc[props.index, a], "greater")
    print(f"  {a} sessions only: r = {ra['r']:.3f}, p = {ra['p']:.3g}")
12 stimuli: r = 0.746, t(10) = 3.546, one-sided p = 0.002653, 95% CI [0.394, 1] (paper r = 0.746, p = 0.00267)
Cook's distance:
stimulus
noise                                       2.113
man writing                                 0.219
mouse montage 2                             0.209
mousecam, spatial phase scramble            0.165
mouse montage 1                             0.059
mouse montage 1, temporal phase scramble    0.040
mousecam                                    0.022
conspecifics                                0.018
human montage                               0.015
mouse montage 1, spatial phase scramble     0.012
snake (predator)                            0.009
crickets (prey)                             0.002
SD from the files' movies against the code's printed log SD: max abs difference 0.0
  AL sessions only: r = 0.878, p = 8.59e-05
  AM sessions only: r = 0.392, p = 0.103

Result: reproduced. Across the 12 stimuli, mean log10 ND in the six L2/3 AL and AM sessions correlates with log10 stimulus differentiation at r = 0.746, one-sided p = 0.0027 (paper 0.746, 0.00267), and noise has the largest Cook's distance, 2.11 (paper 2.318, within tolerance; the next largest is 0.22). The stimulus differentiation computed from the files' movies equals the code's printed values, so the movies in the dandiset are the ones the paper used.

fig8-no-sd-relation-controlled¶

Without the noise stimulus the ND and SD correlation is weak and not significant (r = 0.258), and among the scrambled stimuli and their unscrambled counterparts there is no evidence of a relation (r = -0.378); so ND is not inherited from SD.

In [31]:
no_noise = props.drop(index="noise")
r11 = o.pearson(no_noise.log_sd, no_noise.mean_nd, "greater")
print(f"11 stimuli without noise: r = {r11['r']:.3f}, t({r11['df']}) = {r11['t']:.3f}, one-sided p = {r11['p']:.3g} "
      "(paper r = 0.258, p = 0.222)")
pairs5 = props.loc[o.CONTRAST]
r5 = o.pearson(pairs5.log_sd, pairs5.mean_nd, "two-sided")
print(f"5 contrast stimuli: r = {r5['r']:.3f}, t({r5['df']}) = {r5['t']:.3f}, two-sided p = {r5['p']:.3g}, "
      f"95% CI [{r5['ci_low']:.3f}, {r5['ci_high']:.3f}] (paper r = -0.378, p = 0.530)")
11 stimuli without noise: r = 0.271, t(9) = 0.845, one-sided p = 0.21 (paper r = 0.258, p = 0.222)
5 contrast stimuli: r = -0.423, t(3) = -0.809, two-sided p = 0.478, 95% CI [-0.951, 0.733] (paper r = -0.378, p = 0.530)

Result: reproduced. Without noise, r = 0.271 with one-sided p = 0.21 (paper 0.258, p = 0.222); over the five contrast stimuli, r = -0.423 with two-sided p = 0.48 (paper -0.378, p = 0.530). Neither test finds a relation.

ext8-1-no-low-level-relation¶

ND in L2/3 of AL and AM is not explained by stimulus luminance, contrast or spectral energy.

In [32]:
low = []
for prop in ["luminance", "contrast", "energy_pixel_dc", "energy_global_dc"]:
    for alt in ["two-sided", "greater"]:
        r = o.pearson(props[prop], props.mean_nd, alt)
        low.append({"property": prop, "alternative": alt, "r": r["r"], "p": r["p"]})
low = pd.DataFrame(low)
print(low.round(4).to_string(index=False))
print("Spectral energy, global-mean DC removal, against the code's printed values: max relative difference",
      f"{float(((props.energy_global_dc - props.paper_energy) / props.paper_energy).abs().max()):.2e}")
print("Any p < 0.05:", low.loc[low.p < 0.05, ["property", "alternative"]].to_dict("records"))
        property alternative       r      p
       luminance   two-sided -0.2561 0.4217
       luminance     greater -0.2561 0.7892
        contrast   two-sided  0.2566 0.4207
        contrast     greater  0.2566 0.2103
 energy_pixel_dc   two-sided  0.5143 0.0872
 energy_pixel_dc     greater  0.5143 0.0436
energy_global_dc   two-sided  0.5465 0.0660
energy_global_dc     greater  0.5465 0.0330
Spectral energy, global-mean DC removal, against the code's printed values: max relative difference 1.89e-15
Any p < 0.05: [{'property': 'energy_pixel_dc', 'alternative': 'greater'}, {'property': 'energy_global_dc', 'alternative': 'greater'}]

Result: blocked (methods_underspecified). The criterion blocks the claim when its readings differ, and they do. Under the two-sided reading no property correlates with mean ND (luminance r = -0.26, contrast r = 0.26, spectral energy r = 0.51 and 0.55 for the two DC readings; smallest p = 0.066). Under the one-sided reading, spectral energy does (p = 0.044 with per-pixel DC removal, 0.033 with the code's global mean) while luminance and contrast do not. The code's spectral energy values are reproduced from the files' movies.

Blocked claims: the L0 event detector¶

ext1-3-kinetics-no-difference, ext3-8-events-spectral, ext3-9-no-transients, ext5-1-events-multivariate and mediation-event-magnitude need L0 events, which the dandiset does not hold (data check above). Their criteria name l0_analysis.py of AllenInstitute/visual_coding_2p_analysis, which calls arfpop of FastLZeroSpikeInference. The cell below reads the published sources (nothing is built or installed) and prints what stands in the way of installing them.

In [33]:
import re
import requests

FL = "https://raw.githubusercontent.com/jewellsean/FastLZeroSpikeInference/"
L0 = ("https://raw.githubusercontent.com/AllenInstitute/visual_coding_2p_analysis/"
      "3ceca10/visual_coding_2p_analysis/l0_analysis.py")


def get(url):
    r = requests.get(url, timeout=60)
    return r.text if r.status_code == 200 else None


def py3(source):
    try:
        compile(source, "<source>", "exec")
        return "compiles under Python 3"
    except SyntaxError as e:
        return f"SyntaxError under Python 3 at line {e.lineno}: {e.text.strip()}"


l0 = get(L0)
print("l0_analysis.py (visual_coding_2p_analysis, commit 3ceca10):")
print("  imports:", [ln.strip() for ln in l0.splitlines() if re.match(r"(import|from) ", ln)])
print("  calls fast.arfpop:", "fast.arfpop" in l0, "; reads corrected fluorescence:", "get_corrected_fluorescence_traces" in l0)
print("FastLZeroSpikeInference on PyPI:", requests.get("https://pypi.org/pypi/FastLZeroSpikeInference/json", timeout=60).status_code)
for commit, label in [("cdfaade68ceb6aa15ec5003c460de4e0575f1d5f", "cdfaade, the latest commit"),
                      ("7b80ccd8ea5e05354c4c73775b3faf645b87f37f", "7b80ccd, the latest commit that defines arfpop")]:
    fast = get(FL + commit + "/python/FastLZeroSpikeInference/fast.py")
    setup = get(FL + commit + "/python/setup.py")
    sources = re.findall(r"'(src/[^']+)'", setup)
    print(f"\nFastLZeroSpikeInference {label}:")
    print("  fast.py defines arfpop:", "def arfpop" in fast, ";", py3(fast))
    print("  setup.py (in python/) compiles", sources, "; found under python/:",
          [s for s in sources if get(FL + commit + "/python/" + s) is not None],
          "; found under the repository root:", [s for s in sources if get(FL + commit + "/" + s) is not None])
    print("  python/make.sh:", " ; ".join((get(FL + commit + "/python/make.sh") or "").split("\n")[1:4]))
    cpp = get(FL + commit + "/src/FitSegmentModel.cpp") or ""
    hdr = get(FL + commit + "/src/FitSegmentModel.h") or ""
    print("  src/FitSegmentModel.cpp uses std::numeric_limits:", "numeric_limits" in cpp,
          "; it or its header includes <limits>:", "<limits>" in cpp + hdr)
l0_analysis.py (visual_coding_2p_analysis, commit 3ceca10):
  imports: ['from __future__ import print_function', 'import numpy as np', 'from scipy.ndimage.filters import median_filter', 'import sys', 'from allensdk.core.brain_observatory_cache import BrainObservatoryCache', 'import cPickle as pickle', 'import warnings', 'import os', 'import pandas as pd', 'import core']
  calls fast.arfpop: True ; reads corrected fluorescence: True
FastLZeroSpikeInference on PyPI: 404
FastLZeroSpikeInference cdfaade, the latest commit:
  fast.py defines arfpop: False ; compiles under Python 3
  setup.py (in python/) compiles ['src/funPieceListLog.cpp', 'src/ARFPOP.cpp', 'src/FitSegmentModel.cpp', 'src/python_interface.cpp'] ; found under python/: [] ; found under the repository root: ['src/funPieceListLog.cpp', 'src/ARFPOP.cpp', 'src/FitSegmentModel.cpp', 'src/python_interface.cpp']
  python/make.sh: cp -r ../src ./ ; python setup.py install ; rm -r src  
  src/FitSegmentModel.cpp uses std::numeric_limits: False ; it or its header includes <limits>: False
FastLZeroSpikeInference 7b80ccd, the latest commit that defines arfpop:
  fast.py defines arfpop: True ; SyntaxError under Python 3 at line 89: print "gam must be in interval (0, 1]"
  setup.py (in python/) compiles ['src/funPieceListLog.cpp', 'src/ARFPOP.cpp', 'src/FitSegmentModel.cpp', 'src/interface.cpp'] ; found under python/: [] ; found under the repository root: ['src/funPieceListLog.cpp', 'src/ARFPOP.cpp', 'src/FitSegmentModel.cpp', 'src/interface.cpp']
  python/make.sh: cp -r ../src ./ ; python setup.py install ; rm -r src  
  src/FitSegmentModel.cpp uses std::numeric_limits: True ; it or its header includes <limits>: False

The detector cannot be installed as published, so these claims are blocked as not_runnable. l0_analysis.py is Python 2 code (cPickle, the Allen SDK's BrainObservatoryCache and a local core module) and calls fast.arfpop. FastLZeroSpikeInference is not on PyPI. Its latest version defines no arfpop, and its setup.py, run from python/, names C++ sources that exist only at the repository root (make.sh copies them in before installing), so pip cannot install it from the repository. The latest version that defines arfpop is Python 2 code, and its FitSegmentModel.cpp uses std::numeric_limits without including . Running the detector would mean patching the package's C++ and Python and porting l0_analysis.py to Python 3, which is no longer the paper's software. While preparing the previous revision, outside the notebook and not run here, the 7b80ccd sources were built that way: g++ (C++11) stopped at std::numeric_limits until was added, the Python 2 print statements of fast.py were rewritten for Python 3, and arfpop then ran on a synthetic trace. l0_analysis.py was not ported and no events were computed from this dataset, so the patched build decides nothing.

In [34]:
print(f"notebook ran in {(time.time() - started) / 60:.1f} min")
notebook ran in 23.3 min

Summary¶

Claim Outcome Notebook
session-link reproduced this one
design-sessions reproduced this one
ext1-2-cell-counts reproduced this one
ext1-3-kinetics-no-difference blocked: not runnable
fig3a-layer-specific reproduced this one
fig3b-area-specific reproduced this one
ext3-1-natural-artificial reproduced this one
ext3-2-sensitivity not reproduced this one
ext3-5-arousal-covariates blocked: data missing
ext3-8-events-spectral blocked: not runnable
ext3-9-no-transients blocked: not runnable
mediation-event-magnitude blocked: not runnable
table1-permutation reproduced this one
fig4-locomotion-effect-size reproduced arousal
fig4-pupil-effect-size blocked: data missing arousal
discussion-session-effect-sizes partially reproduced this one
fig5-multivariate-layer reproduced multivariate
fig5-multivariate-area reproduced multivariate
ext5-1-events-multivariate blocked: not runnable
fig6-category-decoding reproduced this one
ext6-1-identity-decoding reproduced this one
fig7-stimulus-effect reproduced this one
fig7-snake-highest reproduced this one
ext7-1-arousal-mediation blocked: data missing
fig8-nd-sd-correlation reproduced this one
fig8-no-sd-relation-controlled reproduced this one
ext8-1-no-low-level-relation blocked: methods underspecified this one

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.

  • Trials are cut where the NWB stimulus times put them. The paper's stimulus table (from its sync files) starts each trial 0 to 6 frames earlier, a shift that grows through the session; per-trial log10 ND differs from the paper's by an SD of 0.047.
  • ROIs whose dF/F is NaN at every frame (14 in the analysed sessions) are left out; without them the cell counts equal the paper's.
  • The statistics are run in Python (statsmodels and scipy), not R (lme4, multcomp, emmeans). On the paper's own per-trial values they give the paper's printed results.
  • Sessions are the 44 of the paper's results table, found through the link. The dandiset alone would give 56 complete sessions; that variant is shown for fig3a and fig3b.
  • The permutation tests use their own random numbers (seeded), not the paper's.
  • Cohen's d uses the Methods' pooled SD. The paper's code weights each group's SD by the other group's n - 1, which moves per-session values by up to 0.1; that variant is shown for discussion-session-effect-sizes and fig4-locomotion-effect-size.
  • Claims that need L0 events or the Methods' pupil diameter are not tested (header, and the section on the L0 detector).

What was found about the dataset.

  • It holds 57 sessions, not the paper's 45: 12 more (10 Cux2, 2 Rbp4 PM) that the paper does not describe, and the excluded L5 AL session, which was imaged at half the frame rate. Nothing in the files marks which sessions the paper analysed or why one was excluded.
  • session_start_time is 7 hours later than the paper's start times while labelled -07:00; it looks like UTC labelled as Pacific time.
  • The NWB identifier is not the session id the paper and its code use; it is the ophys session id that names the pupil files of the deposit.
  • 15 ROIs have dF/F that is NaN at every frame, with no flag.
  • The stimulus presentation 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.
  • The dF/F timestamps have one entry more than the data in 39 files; the running velocity has one sample more than its timestamps in every file (the extra one is the first).
  • The stated imaging rate is 30.0 Hz; the frames are 30.15 Hz apart (15.08 Hz in the excluded session).
  • There are no L0 events, no eye tracking and no pupil data, and the subject's sex, age and date of birth are absent, all of which the paper reports or uses.