Multivariate differentiation (Figure 5) from dandiset 000036¶

Part of the attempt on Mayner, Marshall, Billeh et al. (2022), eNeuro 9(1) ENEURO.0280-21.2021 (doi:10.1523/eneuro.0280-21.2021), on DANDI:000036 version 0.230515.1917. The header of reproduce_mayner_2022.ipynb says why this version and gives the table of all claims; the data check there applies here. This notebook tests the two claims that need UMAP (fig5-multivariate-layer and fig5-multivariate-area), which take too long to share a notebook with the rest. Sessions are the 44 the paper analysed, found through the link claim (session-link) of the main notebook.

In [1]:
import os

os.environ["OMP_NUM_THREADS"] = "1"
os.environ["NUMBA_NUM_THREADS"] = "1"

import multiprocessing as mp
import time
import warnings
from concurrent.futures import ProcessPoolExecutor
from importlib.metadata import version

import numpy as np
import pandas as pd

import openscope_nd as o

warnings.filterwarnings("ignore")
pd.set_option("display.width", 200)

started = time.time()
assets = o.list_assets()
meta = o.read_all_metadata(assets)
paper = pd.read_parquet(o.CODE_RESULTS + "main.parquet")
link = o.link_to_paper(meta, paper)
use = link[link.in_paper].reset_index(drop=True)
print(f"dandiset {o.DANDISET_ID} version {o.DANDISET_VERSION}; {len(use)} of {len(link)} sessions linked to the paper")
print("umap-learn", version("umap-learn"), "; numba", version("numba"), "; UMAP parameters:", o.UMAP_PARAMS)
dandiset 000036 version 0.230515.1917; 44 of 57 sessions linked to the paper
umap-learn 0.5.12 ; numba 0.68.0 ; UMAP parameters: {'n_neighbors': 50, 'min_dist': 0.5, 'n_components': 8, 'metric': 'euclidean', 'init': 'spectral', 'random_state': 42, 'transform_seed': 42, 'low_memory': False, 'spread': 1.0, 'learning_rate': 1.0, 'local_connectivity': 1.0, 'negative_sample_rate': 5, 'repulsion_strength': 1.0, 'set_op_mix_ratio': 1.0}

Data check¶

In [2]:
print("Linked sessions by layer and area:")
print(pd.crosstab(use.layer, use.area).reindex(index=o.LAYERS, columns=o.AREAS).to_string())
print("Paper's area and layer agree for every linked session:",
      bool((use.area == use.paper_area.astype(str)).all() and (use.layer == use.paper_layer.astype(str)).all()))
Linked sessions by layer and area:
area   V1  LM  AL  PM  AM
layer                    
L2/3    3   3   3   3   3
L4      3   3   3   3   3
L5      3   3   2   3   3
Paper's area and layer agree for every linked session: True
In [3]:
t0 = time.time()
with ProcessPoolExecutor(4, mp_context=mp.get_context("spawn")) as ex:
    out = list(ex.map(o.umap_session, use.url))
print(f"UMAP on {len(out)} sessions in {(time.time() - t0) / 60:.1f} min")
mcd = pd.concat([r["trials"].assign(session=s) for r, s in zip(out, use.identifier)])
mcd = mcd.merge(use[["identifier", "layer", "area", "mouse_id"]], left_on="session", right_on="identifier")
mcd = mcd.merge(o.STIMULI.reset_index()[["stimulus", "stimulus_type"]], on="stimulus")
mcd["y"] = np.log10(mcd.mcd)
UMAP on 44 sessions in 14.4 min
In [4]:
fr = pd.Series({s: r["n_frames"] for r, s in zip(out, use.identifier)})
print(f"Frames embedded per session: {fr.min()} to {fr.max()}; cells per session: "
      f"{min(r['ncells'] for r in out)} to {max(r['ncells'] for r in out)}")
print("Trials:", len(mcd), "; per session:", mcd.groupby("session").size().unique(),
      "; frames per trial:", mcd.n_frames.min(), "to", mcd.n_frames.max())
print(f"log10 mean centroid distance: {mcd.y.min():.3f} to {mcd.y.max():.3f}; non-finite: {int((~np.isfinite(mcd.y)).sum())}")
ref = pd.read_parquet(o.CODE_RESULTS + "mean_centroid_distance.parquet")
ref = ref[ref.stimulus_is_scrambled_pair].assign(stimulus=lambda d: d.stimulus.astype(str), trial=lambda d: d.trial.astype(int))
cmp = mcd.merge(use[["identifier", "paper_session"]], left_on="session", right_on="identifier").merge(
    ref[["session", "stimulus", "trial", "log(mean_centroid_distance)"]],
    left_on=["paper_session", "stimulus", "trial"], right_on=["session", "stimulus", "trial"])
print(f"Against the paper's per-trial values (results/mean_centroid_distance.parquet): n = {len(cmp)}, "
      f"r = {np.corrcoef(cmp.y, cmp['log(mean_centroid_distance)'])[0, 1]:.3f}, "
      f"mean difference {(cmp.y - cmp['log(mean_centroid_distance)']).mean():+.4f}")
Frames embedded per session: 45150 to 45287; cells per session: 8 to 293
Trials: 2200 ; per session: [50] ; frames per trial: 902 to 923
log10 mean centroid distance: 0.084 to 0.933; non-finite: 0
Against the paper's per-trial values (results/mean_centroid_distance.parquet): n = 2200, r = 0.995, mean difference +0.0035

UMAP is stochastic and its result depends on the library version; the paper's per-trial values come from its own run (umap-learn version not pinned in the code's environment files beyond what they list). The comparison with the paper's values is a reference, not a test.

fig5-multivariate-layer¶

Multivariate ND (mean distance to the centroid in an 8-dimensional UMAP embedding) is higher for unscrambled than scrambled stimuli specifically in L2/3.

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


r5l = o.category_models(mcd, "layer")
show(r5l, "layer")
d_layer = mcd.groupby("layer").apply(lambda g: o.cohens_d(g.y, g.stimulus_type)).reindex(o.LAYERS)
print("Cohen's d per layer:", d_layer.round(3).to_dict(), "(paper L2/3 0.194, L4 0.0994, L5 -0.0651)")
print("Cohen's d per layer and mouse:")
print(mcd.groupby(["layer", "mouse_id"]).apply(lambda g: o.cohens_d(g.y, g.stimulus_type)).round(3).to_string())
layer: interaction chi2(2) = 18.535, p = 9.44e-05 (2200 trials, 44 sessions)
      estimate      se       z   p_adj  ci_low
L2/3    0.0310  0.0060  5.1225  0.0000  0.0181
L4      0.0107  0.0060  1.7647  0.1120 -0.0022
L5     -0.0065  0.0063 -1.0360  0.9966 -0.0198
Cohen's d per layer: {'L2/3': 0.192, 'L4': 0.1, 'L5': -0.072} (paper L2/3 0.194, L4 0.0994, L5 -0.0651)
Cohen's d per layer and mouse:
layer  mouse_id
L2/3   389014      0.042
       389020      0.787
       390958      0.253
L4     392392      0.203
       395480      0.073
       395481     -0.009
L5     402796     -0.140
       405808      0.214
       406876     -0.250

Result: reproduced. The layer by category interaction on log10 mean centroid distance is chi2(2) = 18.535, p = 9.4e-5 (paper 18.135, within tolerance). L2/3 is significant (z = 5.12, adjusted p < 0.0001, Cohen's d 0.192 against the paper's 0.194) and L4 (p = 0.112) and L5 (p = 0.997) are not. Within L2/3 the effect is positive in all three mice (d 0.04, 0.79 and 0.25).

fig5-multivariate-area¶

Multivariate ND is higher for unscrambled than scrambled stimuli specifically in AL and AM.

In [6]:
r5a = o.category_models(mcd, "area")
show(r5a, "area")
d_area = mcd.groupby("area").apply(lambda g: o.cohens_d(g.y, g.stimulus_type)).reindex(o.AREAS)
print("Cohen's d per area:", d_area.round(3).to_dict(), "(paper AL 0.184, AM 0.277)")
print(f"notebook ran in {(time.time() - started) / 60:.1f} min")
area: interaction chi2(4) = 16.142, p = 0.00283 (2200 trials, 44 sessions)
    estimate      se       z   p_adj  ci_low
V1    0.0012  0.0078  0.1594  0.9433 -0.0169
LM    0.0011  0.0078  0.1352  0.9479 -0.0170
AL    0.0240  0.0083  2.8967  0.0094  0.0048
PM    0.0012  0.0078  0.1485  0.9454 -0.0169
AM    0.0345  0.0078  4.4211  0.0000  0.0164
Cohen's d per area: {'V1': 0.011, 'LM': 0.008, 'AL': 0.181, 'PM': 0.011, 'AM': 0.274} (paper AL 0.184, AM 0.277)
notebook ran in 15.8 min

Result: reproduced. The area interaction is chi2(4) = 16.142, p = 0.0028 (paper 16.232); AL (adjusted p = 0.0094) and AM (p < 0.0001) are significant and V1, LM and PM are not (p >= 0.94). Cohen's d is 0.181 for AL and 0.274 for AM (paper 0.184 and 0.277), within tolerance.

Summary¶

Claim Outcome
fig5-multivariate-layer reproduced
fig5-multivariate-area reproduced

The table of all claims, the differences from the paper's method and what was found about the dataset are in the summary of reproduce_mayner_2022.ipynb. Here UMAP is run with umap-learn (version printed above), whose embeddings differ from the paper's run; the per-trial values correlate with the paper's at r = 0.995, and the conclusions do not depend on the difference.