Najafi et al. (2020) on DANDI:000016, part 1: data, behaviour, single neurons and correlations¶

Paper: Najafi, Elsayed, Cao, Pnevmatikakis, Latham, Cunningham and Churchland (2020), "Excitatory and Inhibitory Subnetworks Are Equally Selective during Decision-Making and Emerge Simultaneously during Learning", Neuron 105, 165-179, doi:10.1016/j.neuron.2019.09.045.

Dataset: DANDI:000016, version 0.260915.2309 (doi:10.48324/dandi.000016/0.260915.2309). The paper cites no dandiset version (it names the CSHL repository and the NWB conversion); this is the only published version, so it is pinned, and it holds 135 files from 4 mice, the paper's 135 sessions.

Claims file: claims/najafi-2020.yaml, written from the accepted author manuscript in PubMed Central (PMC6952547) with its supplement, and the paper's code at commit b7352acd.

This notebook tests the claims on the data description, behaviour, single-neuron selectivity and pairwise correlations. Decoders are in 02_decoders.ipynb.

Claim Here
data-composition tested
fig1b-psychometric tested
figs1b-trial-history blocked: the files give trial times relative to each trial, so no ITI
fig1gi-inferred-spiking-differs tested
fig2a-example-session tested
fig2bc-fraction-selective-similar tested
fig2bd-selectivity-time-course tested
fig2de-selectivity-magnitude-similar tested
figs3d-same-spiking-selectivity tested
figs3c-wider-window tested
figs3e-correct-error-correlation tested
fig6a-same-selectivity-correlations tested
fig6bc-inhibitory-correlations-higher tested
fig8f-correlations-decrease tested
fig8g-fraction-selective-triples tested
figs2-temporal-dynamics-similar blocked: not reached in the run's time
figs14-neuropil, figs15-labeling-specificity blocked: raw movies and histology not in the dandiset
decoders and models see 02_decoders.ipynb and the attempt record
In [1]:
import os, time, resource
import numpy as np
import pandas as pd
from scipy import stats
import statsmodels.api as sm
import najafi as nj

pd.set_option("display.width", 200)
T0 = time.time()
A = nj.assets()
print(len(A), "assets in version", nj.VERSION)
print(A.groupby("subject").size())
135 assets in version 0.260915.2309
subject
mouse1_fni16    45
mouse2_fni17    48
mouse3_fni18     7
mouse4_fni19    35
dtype: int64
In [2]:
# Streams every session: the choice-aligned traces (all 97 ms bins, and frames -7 to +10 around the
# choice) and the bins before the initiation tone.
S = nj.load_all(A, workers=6, alignments=(nj.CHOICE, nj.INIT))
print("loaded", len(S), "sessions in %.0f s, peak memory %.1f GB" % (time.time() - T0, resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1e6))
loaded 135 sessions in 1490 s, peak memory 5.6 GB
In [3]:
rows = []
for s in S:
    tr = s["trials"]; a = s["al"][nj.CHOICE]
    good = s["rois_all"].roi_status.eq("good")
    rows.append(dict(mouse=s["mouse"], subject=s["subject"], session=s["session_id"], recording=s["description"].split("_ch2")[0],
                     date=s["start"][:10], trials=len(tr), with_choice=int(tr.choice.notna().sum()), good_flag=int(tr.trial_is_good.sum()),
                     used=int(tr.use.sum()), rois=len(s["rois_all"]), good=int(good.sum()), traced=len(s["type"]),
                     exc=int((s["type"] == "excitatory").sum()), inh=int((s["type"] == "inhibitory").sum()), unk=int((s["type"] == "unknown").sum()),
                     ev=a["ev"], frames=a["nframes"], dt=a["dt"], rate=s["imaging_rate"], bins=f"{a['k'][0]}..{a['k'][-1]}",
                     maxval=float(np.nanmax(a["max"])), nanused=int((a["nan_trials"] & tr.use.to_numpy()).sum())))
D = pd.DataFrame(rows)
print("Sessions per mouse:", D.groupby("mouse").size().to_dict())
print("Subjects:", D.groupby("mouse").subject.first().to_dict())
print("Traced ROIs are the good ROIs in every session:", bool((D.traced == D.good).all()) and all((s["status"] == "good").all() for s in S))
print("Neuron types of the traced ROIs:", pd.Series(np.concatenate([s["type"] for s in S])).value_counts().to_dict())
print("Neuron types of the bad ROIs:", pd.Series(np.concatenate([s["rois_all"].neuron_type[s["rois_all"].roi_status.eq("bad")] for s in S])).value_counts().to_dict())
print("Duplicate recordings (same mouse and recording name or date):", int(D.duplicated(["mouse", "recording"]).sum()), int(D.duplicated(["mouse", "date"]).sum()))
print("Duplicate (mouse, trials, ROIs) signatures:", int(D.duplicated(["mouse", "trials", "rois", "good"]).sum()))
print("Imaging rate stated:", D.rate.unique(), "Hz; frame interval in the files (attribute named 'rate'):", np.unique(D.dt.round(6)), "s")
print("Frames per choice-aligned trial: %d to %d; choice frame index %d to %d" % (D.frames.min(), D.frames.max(), D.ev.min(), D.ev.max()))
print("Choice-aligned bins kept per session (k, bin -1 = 0-97 ms before choice):", D.bins.value_counts().head(5).to_dict())
print("Used trials with no choice-aligned trace (left out):", int(D.nanused.sum()), "of", int(D.used.sum()))
tr_all = pd.concat([s["trials"].assign(mouse=s["mouse"]) for s in S])
print("Trial responses:", tr_all.trial_response.value_counts().to_dict())
print("trial_is_good by response:"); print(pd.crosstab(tr_all.trial_response, tr_all.trial_is_good))
print("Trial table columns (every session the same: %s):" % all(s["trial_columns"] == S[0]["trial_columns"] for s in S), S[0]["trial_columns"])
print("  no column marks helped trials or the first trials of a session; trial_is_good is exactly 'response correct or incorrect' (table above)")
fu = pd.Series([int(np.flatnonzero(s["trials"].trial_is_good.to_numpy())[0]) for s in S if s["trials"].trial_is_good.any()])
print("  index of the first good trial in a session: median %d, range %d to %d" % (fu.median(), fu.min(), fu.max()))
print("processing/Ophys groups (union over sessions):", sorted(set().union(*[s["ophys_keys"] for s in S])))
print("processing/Behavior groups (union over sessions):", {k: v for s in S for k, v in s["behaviour_keys"].items()})
print("Pulse rates stored as integers in %d sessions; the others store non-integer rates" % sum(np.allclose(s["trials"].trial_pulse_rate.astype(float) % 1, 0) for s in S))
print("Pulse rates, rounded:", [int(x) for x in sorted(tr_all.trial_pulse_rate.astype(float).round().unique())], "trial types:", tr_all.trial_type.value_counts().to_dict())
print("16 Hz trials (rate within 0.005 Hz of 16) by trial type and response:"); t16 = tr_all[tr_all.at16]; print(pd.crosstab(t16.trial_type.to_numpy(), t16.trial_response.to_numpy(), rownames=["trial_type"], colnames=["trial_response"]))
print("  16 Hz trials are rewarded on a random side, so their choice is left unknown; with a correct or incorrect response:", int((tr_all.at16 & tr_all.trial_is_good).sum()))
for al in (nj.CHOICE, nj.INIT):
    print("largest difference of any trial's starting_time or frame interval from the first trial's, %s: %.2g s" % (al, max(s["al"][al]["start_dev"] for s in S)))
print("High-rate trial type vs rate > 16:"); print(pd.crosstab(tr_all.trial_type, np.sign(tr_all.trial_pulse_rate.astype(float).round(2) - 16)))
ev_t = tr_all[tr_all.use][["init_tone", "stim_onset", "stim_offset", "go_tone", "first_commit", "second_commit"]]
print("Event times within the trial, s (used trials):"); print(ev_t.describe().loc[["min", "50%", "max"]].round(3))
print("Stimulus duration, s:", (ev_t.stim_offset - ev_t.stim_onset).round(3).value_counts().head(3).to_dict())
print("Confirmation lick after first side lick, s: median %.3f, max %.3f" % ((ev_t.second_commit - ev_t.first_commit).median(), (ev_t.second_commit - ev_t.first_commit).max()))
print("start_time range over all trials: %.3f to %.3f s (trial times are relative to each trial, no session clock)" % (tr_all.start_time.min(), tr_all.start_time.max()))
allv = np.concatenate([s["al"][nj.CHOICE]["B"][:, nj.bin_index(s, -1)].ravel() for s in S[:20]])
allv = allv[~np.isnan(allv)]
print("Values of the traces (bin -1, 20 sessions): min %.2g, median %.2g, 99th pct %.3f, max %.3f, fraction below 1e-6: %.2f"
      % (allv.min(), np.median(allv), np.percentile(allv, 99), allv.max(), np.mean(allv < 1e-6)))
mx = np.concatenate([np.maximum(s["al"][nj.CHOICE]["max"], 0) for s in S])
print("Per-neuron maximum over the choice-aligned traces: median %.3f, max %.3f, fraction equal to 1: %.3f" % (np.nanmedian(mx), np.nanmax(mx), np.mean(np.isclose(mx, 1))))
print(D.groupby("mouse")[["trials", "used", "good", "exc", "inh", "unk"]].agg(["median", "mean"]).round(1))
Sessions per mouse: {1: 45, 2: 48, 3: 7, 4: 35}
Subjects: {1: 'mouse1_fni16', 2: 'mouse2_fni17', 3: 'mouse3_fni18', 4: 'mouse4_fni19'}
Traced ROIs are the good ROIs in every session: True
Neuron types of the traced ROIs: {'excitatory': 44546, 'unknown': 14376, 'inhibitory': 5530}
Neuron types of the bad ROIs: {'unknown': 20948}
Duplicate recordings (same mouse and recording name or date): 0 0
Duplicate (mouse, trials, ROIs) signatures: 0
Imaging rate stated: [30.] Hz; frame interval in the files (attribute named 'rate'): [0.032362] s
Frames per choice-aligned trial: 52 to 106; choice frame index 26 to 72
Choice-aligned bins kept per session (k, bin -1 = 0-97 ms before choice): {'-18..7': 18, '-19..7': 11, '-17..7': 11, '-20..7': 7, '-16..7': 7}
Used trials with no choice-aligned trace (left out): 1982 of 25883
Trial responses: {'correct': 18893, 'incorrect': 7128, 'no go-tone lick (-1)': 2197, 'no decision': 2173, 'no go-tone lick (-4)': 738, 'no center lick': 647, 'no second commit': 251, 'no first commit': 234}
trial_is_good by response:
trial_is_good         False  True 
trial_response                    
correct                   0  18893
incorrect                 0   7128
no center lick          647      0
no decision            2173      0
no first commit         234      0
no go-tone lick (-1)   2197      0
no go-tone lick (-4)    738      0
no second commit        251      0
Trial table columns (every session the same: True): ['start_time', 'stop_time', 'trial_type', 'trial_pulse_rate', 'trial_response', 'trial_is_good', 'init_tone', 'stim_onset', 'stim_offset', 'go_tone', 'first_commit', 'second_commit']
  no column marks helped trials or the first trials of a session; trial_is_good is exactly 'response correct or incorrect' (table above)
  index of the first good trial in a session: median 5, range 5 to 20
processing/Ophys groups (union over sessions): ['ImageSegmentation', 'dFoF_commitIncorrAl', 'dFoF_firstSideTryAl', 'dFoF_firstSideTryAl_COM', 'dFoF_goToneAl', 'dFoF_initToneAl', 'dFoF_rewardAl', 'dFoF_stimAl_allTrs', 'dFoF_stimAl_noEarlyDec', 'dFoF_stimOffAl']
processing/Behavior groups (union over sessions): {'Epoched_behavioral_series': ['firstSideTryAl_lick', 'firstSideTryAl_wheelRev']}
Pulse rates stored as integers in 128 sessions; the others store non-integer rates
Pulse rates, rounded: [5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27] trial types: {'High-rate': 17047, 'Low-rate': 15214}
16 Hz trials (rate within 0.005 Hz of 16) by trial type and response:
trial_response  correct  incorrect  no center lick  no decision  no go-tone lick (-1)  no go-tone lick (-4)  no second commit
trial_type                                                                                                                   
High-rate            79         59               1            2                     4                     3                 1
  16 Hz trials are rewarded on a random side, so their choice is left unknown; with a correct or incorrect response: 138
largest difference of any trial's starting_time or frame interval from the first trial's, dFoF_firstSideTryAl: 0 s
largest difference of any trial's starting_time or frame interval from the first trial's, dFoF_initToneAl: 0 s
High-rate trial type vs rate > 16:
trial_pulse_rate   -1.0   0.0    1.0
trial_type                          
High-rate             0   149  16898
Low-rate          15214     0      0
Event times within the trial, s (used trials):
     init_tone  stim_onset  stim_offset  go_tone  first_commit  second_commit
min      0.287       0.329        1.026    0.643         0.857          0.990
50%      0.829       1.074        2.070    1.966         2.612          3.017
max     35.956      36.048       37.048   36.923        37.259         37.590
Stimulus duration, s: {1.0: 24493, 0.406: 26, 0.403: 23}
Confirmation lick after first side lick, s: median 0.361, max 10.799
start_time range over all trials: -0.484 to 0.207 s (trial times are relative to each trial, no session clock)
Values of the traces (bin -1, 20 sessions): min -2.8e-08, median 1.3e-10, 99th pct 0.117, max 0.643, fraction below 1e-6: 0.90
Per-neuron maximum over the choice-aligned traces: median 0.895, max 1.000, fraction equal to 1: 0.359
      trials          used          good           exc           inh          unk       
      median   mean median   mean median   mean median   mean median  mean median   mean
mouse                                                                                   
1      213.0  215.0  166.0  173.6  458.0  436.6  309.0  290.6   40.0  39.0  112.0  107.0
2      253.0  275.0  190.5  219.2  576.5  538.8  393.5  367.8   49.5  47.3  119.5  123.7
3      264.0  283.3  152.0  184.3  393.0  390.6  270.0  269.6   27.0  26.0   94.0   95.0
4      222.0  211.6  188.0  178.9  478.0  463.1  347.0  340.7   37.0  37.8   83.0   84.6

The traces under processing/Ophys/dFoF_* hold sparse values in 0 to 1 with each neuron's maximum at 1, as the paper's normalised inferred spiking activity (STAR Methods), not Delta F/F as their names say. The time axis of each trial series is stated by starting_time and an attribute named rate that holds the frame interval (0.0324 s), not a rate. The trial table's times are relative to each trial's start, so no inter-trial interval can be computed.

Clock check: the traces are aligned to the choice by the file's own segmentation, and the trial table gives event times within each trial only. The alignment is consistent with the data, not proven: single-neuron choice selectivity rises from the earliest choice-aligned bins to the bin before the choice in every mouse (fig2bd below), and the choice decoders rise from 59 to 70 percent in the earliest bins to 72 to 86 percent at the choice, against shuffles of about 50 percent (03_learning_decoders.ipynb, fig3b).

data-composition¶

The imaging dataset has 135 sessions from 4 mice (45, 48, 7 and 35 sessions), with on average 480 neurons per session, about 40 inhibitory, 330 excitatory and 100 unclassified; inhibitory neurons are 11% of the population.

In [4]:
g = D.groupby("mouse")
print("sessions:", len(D), "per mouse:", g.size().to_dict())
print("median trials per session, (a) all trials in the table:", g.trials.median().to_dict())
print("median trials per session, (b) trials with a correct or incorrect choice:", g.with_choice.median().to_dict())
print("neurons (good ROIs) per session, mean: %.1f; excitatory %.1f; inhibitory %.1f; unknown %.1f" % (D.good.mean(), D.exc.mean(), D.inh.mean(), D.unk.mean()))
print("inhibitory fraction (a) of all neurons: %.4f (pooled %.4f); (b) of excitatory plus inhibitory: %.4f (pooled %.4f)"
      % ((D.inh / D.good).mean(), D.inh.sum() / D.good.sum(), (D.inh / (D.inh + D.exc)).mean(), D.inh.sum() / (D.inh.sum() + D.exc.sum())))
exp = {"sessions": (135, 13.5), "m1": (213, 21.3), "m2": (253, 25.3), "m3": (264, 26.4), "m4": (222, 22.2), "neurons": (480, 48), "inh": (40, 4), "exc": (330, 33)}
meas = {"sessions": len(D), "m1": g.trials.median()[1], "m2": g.trials.median()[2], "m3": g.trials.median()[3], "m4": g.trials.median()[4],
        "neurons": D.good.mean(), "inh": D.inh.mean(), "exc": D.exc.mean()}
for k, (v, tol) in exp.items():
    print(f"{k}: measured {meas[k]:.1f}, expected {v} +/- {tol}: {'within' if abs(meas[k]-v) <= tol else 'outside'}")
for lab, fr in [("a", (D.inh / D.good).mean()), ("b", (D.inh / (D.inh + D.exc)).mean())]:
    print(f"inhibitory fraction reading ({lab}): {fr:.4f}, expected 0.11 +/- 0.011: {'within' if abs(fr-0.11) <= 0.011 else 'outside'}")
sessions: 135 per mouse: {1: 45, 2: 48, 3: 7, 4: 35}
median trials per session, (a) all trials in the table: {1: 213.0, 2: 253.0, 3: 264.0, 4: 222.0}
median trials per session, (b) trials with a correct or incorrect choice: {1: 166.0, 2: 190.5, 3: 152.0, 4: 188.0}
neurons (good ROIs) per session, mean: 477.4; excitatory 330.0; inhibitory 41.0; unknown 106.5
inhibitory fraction (a) of all neurons: 0.0854 (pooled 0.0858); (b) of excitatory plus inhibitory: 0.1104 (pooled 0.1104)
sessions: measured 135.0, expected 135 +/- 13.5: within
m1: measured 213.0, expected 213 +/- 21.3: within
m2: measured 253.0, expected 253 +/- 25.3: within
m3: measured 264.0, expected 264 +/- 26.4: within
m4: measured 222.0, expected 222 +/- 22.2: within
neurons: measured 477.4, expected 480 +/- 48: within
inh: measured 41.0, expected 40 +/- 4: within
exc: measured 330.0, expected 330 +/- 33: within
inhibitory fraction reading (a): 0.0854, expected 0.11 +/- 0.011: outside
inhibitory fraction reading (b): 0.1104, expected 0.11 +/- 0.011: within

Result: reproduced. The dandiset holds 135 sessions (45, 48, 7, 35 per mouse, matching the paper's mice 1 to 4 by count). Median trials per session over all trials in the table are 213, 253, 264 and 222, the paper's values exactly; with a correct or incorrect choice they are 166, 190.5, 152 and 188. Means per session are 477.4 neurons, 330.0 excitatory and 41.0 inhibitory, all within tolerance. The inhibitory fraction is 0.1104 of excitatory plus inhibitory neurons, reading (b), within tolerance, and 0.0854 of all neurons, reading (a), outside.

fig1b-psychometric¶

Choices depend strongly on stimulus rate, at chance at the 16 Hz boundary and more accurate for rates further from it.

In [5]:
for m in range(1, 5):
    t = tr_all[(tr_all.mouse == m) & tr_all.use]
    rate_r = t.trial_pulse_rate.astype(float).round().astype(int)
    pc = t.groupby(rate_r).choice.agg(["mean", "size"])
    X = sm.add_constant(t.trial_pulse_rate.astype(float).to_numpy())
    fit = sm.Logit(t.choice.to_numpy(), X).fit(disp=0)
    n16 = int((tr_all.mouse.eq(m) & tr_all.at16 & tr_all.trial_is_good).sum())
    print(f"mouse {m}: {len(t)} trials; slope {fit.params[1]:.3f} per Hz (SE {fit.bse[1]:.3f}), p = {fit.pvalues[1]:.2g}; "
          f"16 Hz trials with a response: {n16} (choice side unknown, not in the fit)")
    print("   fraction high-rate choices by rate rounded to 1 Hz (trials):", {int(r): f"{v:.2f} ({n})" for r, v, n in zip(pc.index, pc["mean"], pc["size"])})
mouse 1: 7812 trials; slope 0.082 per Hz (SE 0.003), p = 1.4e-224; 16 Hz trials with a response: 10 (choice side unknown, not in the fit)
   fraction high-rate choices by rate rounded to 1 Hz (trials): {6: '0.28 (1572)', 7: '0.30 (1521)', 8: '0.18 (157)', 9: '0.28 (186)', 10: '0.20 (49)', 11: '0.18 (33)', 12: '0.27 (41)', 13: '0.17 (6)', 14: '0.38 (8)', 15: '0.25 (8)', 17: '0.36 (11)', 18: '0.50 (6)', 19: '0.40 (5)', 20: '0.00 (4)', 21: '0.41 (63)', 22: '0.47 (64)', 23: '0.58 (50)', 24: '0.66 (218)', 25: '0.61 (226)', 26: '0.66 (1717)', 27: '0.67 (1867)'}
mouse 2: 10520 trials; slope 0.139 per Hz (SE 0.003), p = 0; 16 Hz trials with a response: 122 (choice side unknown, not in the fit)
   fraction high-rate choices by rate rounded to 1 Hz (trials): {6: '0.14 (1647)', 7: '0.17 (1657)', 8: '0.14 (351)', 9: '0.18 (368)', 10: '0.17 (200)', 11: '0.26 (225)', 12: '0.24 (208)', 13: '0.26 (95)', 14: '0.29 (99)', 15: '0.33 (110)', 17: '0.41 (118)', 18: '0.58 (142)', 19: '0.55 (99)', 20: '0.61 (126)', 21: '0.66 (214)', 22: '0.68 (197)', 23: '0.74 (227)', 24: '0.73 (338)', 25: '0.77 (386)', 26: '0.68 (1842)', 27: '0.75 (1871)'}
mouse 3: 1290 trials; slope 0.210 per Hz (SE 0.010), p = 9.2e-99; 16 Hz trials with a response: 0 (choice side unknown, not in the fit)
   fraction high-rate choices by rate rounded to 1 Hz (trials): {5: '0.17 (36)', 6: '0.10 (113)', 7: '0.17 (190)', 8: '0.23 (56)', 9: '0.24 (87)', 10: '0.24 (54)', 11: '0.28 (43)', 12: '0.33 (15)', 13: '0.50 (12)', 14: '0.75 (8)', 15: '0.25 (8)', 16: '0.55 (11)', 17: '0.83 (6)', 18: '0.70 (20)', 19: '0.67 (9)', 20: '0.80 (10)', 21: '0.86 (22)', 22: '0.84 (68)', 23: '0.87 (60)', 24: '0.84 (89)', 25: '0.92 (153)', 26: '0.85 (130)', 27: '0.94 (90)'}
mouse 4: 6261 trials; slope 0.092 per Hz (SE 0.003), p = 2.2e-216; 16 Hz trials with a response: 6 (choice side unknown, not in the fit)
   fraction high-rate choices by rate rounded to 1 Hz (trials): {6: '0.24 (1277)', 7: '0.28 (1248)', 8: '0.30 (167)', 9: '0.28 (181)', 10: '0.37 (59)', 11: '0.36 (61)', 12: '0.51 (53)', 13: '0.67 (6)', 14: '0.22 (9)', 15: '0.50 (4)', 17: '0.50 (4)', 18: '0.71 (7)', 19: '0.75 (4)', 20: '0.60 (5)', 21: '0.58 (55)', 22: '0.57 (54)', 23: '0.67 (55)', 24: '0.65 (190)', 25: '0.71 (158)', 26: '0.67 (1348)', 27: '0.70 (1316)'}

Result: reproduced. The logistic slope of high-rate choice on stimulus rate is positive in every mouse (0.082, 0.139, 0.210 and 0.092 per Hz, all p below 1e-98). The 16 Hz trials (10, 122, 0 and 6 with a response) are rewarded on a random side, so their choice side is unknown and the fraction of high choices at 16 Hz that the criterion asks to report cannot be given; they are left out of the fit. The per-rate table is grouped on rates rounded to 1 Hz.

fig1gi-inferred-spiking-differs¶

Inferred spiking activity differs significantly between inhibitory and excitatory neurons throughout the trial, and in the bin just before the choice in every mouse.

In [6]:
act = []  # per session, per type: mean over correct trials, per neuron, per bin
for s in S:
    m = nj.trial_mask(s, (1,))
    a = s["al"][nj.CHOICE]
    mu = np.nanmean(a["B"][m], 0)  # bins x neurons
    act.append({"mouse": s["mouse"], "k": a["k"], "E": mu[:, s["type"] == "excitatory"], "I": mu[:, s["type"] == "inhibitory"]})
nE = sum(x["E"].shape[1] for x in act); nI = sum(x["I"].shape[1] for x in act)
print(f"neurons pooled over sessions: excitatory {nE} (expected 41723 +/- 4172), inhibitory {nI} (expected 5142 +/- 514)")
for m in range(1, 5):
    xs = [x for x in act if x["mouse"] == m]
    i = [int(np.flatnonzero(x["k"] == -1)[0]) for x in xs]
    dE = np.array([x["E"][j].mean() for x, j in zip(xs, i)]); dI = np.array([x["I"][j].mean() for x, j in zip(xs, i)])
    pa = stats.ttest_ind(dI, dE).pvalue
    pE = np.concatenate([x["E"][j] for x, j in zip(xs, i)]); pI = np.concatenate([x["I"][j] for x, j in zip(xs, i)])
    pb = stats.ttest_ind(pI, pE).pvalue
    print(f"mouse {m}, bin -1: day means inh {dI.mean():.4f} exc {dE.mean():.4f} (ratio {dI.mean()/dE.mean():.2f}), (a) p = {pa:.2g} ({len(xs)} days); "
          f"(b) pooled neurons inh {pI.mean():.4f} exc {pE.mean():.4f}, p = {pb:.2g} ({len(pI)} I, {len(pE)} E)")
    # time course: every bin present in all sessions of the mouse
    kcommon = sorted(set.intersection(*[set(x["k"]) for x in xs]))
    ps = []
    for k in kcommon:
        dE = np.array([x["E"][np.flatnonzero(x["k"] == k)[0]].mean() for x in xs]); dI = np.array([x["I"][np.flatnonzero(x["k"] == k)[0]].mean() for x in xs])
        ps.append((k, stats.ttest_ind(dI, dE).pvalue, np.sign(dI.mean() - dE.mean())))
    nsig = sum(p < 0.001 for _, p, _ in ps)
    print(f"   time course (a): {nsig} of {len(ps)} choice-aligned bins (k {kcommon[0]} to {kcommon[-1]}) at p < 0.001; largest p {max(p for _, p, _ in ps):.2g}; "
          f"inh higher in {sum(d > 0 for *_, d in ps)} bins")
neurons pooled over sessions: excitatory 44546 (expected 41723 +/- 4172), inhibitory 5530 (expected 5142 +/- 514)
mouse 1, bin -1: day means inh 0.0042 exc 0.0038 (ratio 1.11), (a) p = 0.05 (45 days); (b) pooled neurons inh 0.0042 exc 0.0038, p = 0.0013 (1753 I, 13079 E)
   time course (a): 0 of 15 choice-aligned bins (k -8 to 6) at p < 0.001; largest p 0.98; inh higher in 15 bins
mouse 2, bin -1: day means inh 0.0047 exc 0.0030 (ratio 1.54), (a) p = 8.7e-10 (48 days); (b) pooled neurons inh 0.0048 exc 0.0031, p = 0 (2271 I, 17655 E)
   time course (a): 14 of 15 choice-aligned bins (k -8 to 6) at p < 0.001; largest p 0.067; inh higher in 15 bins
mouse 3, bin -1: day means inh 0.0041 exc 0.0023 (ratio 1.79), (a) p = 0.1 (7 days); (b) pooled neurons inh 0.0043 exc 0.0023, p = 8.2e-10 (182 I, 1887 E)
   time course (a): 0 of 18 choice-aligned bins (k -11 to 6) at p < 0.001; largest p 0.33; inh higher in 18 bins
mouse 4, bin -1: day means inh 0.0036 exc 0.0031 (ratio 1.17), (a) p = 0.03 (35 days); (b) pooled neurons inh 0.0037 exc 0.0031, p = 3.5e-05 (1324 I, 11925 E)
   time course (a): 0 of 18 choice-aligned bins (k -10 to 7) at p < 0.001; largest p 0.8; inh higher in 14 bins

Result: not reproduced. Inhibitory activity is higher than excitatory activity in the bin before the choice in every mouse (ratios of day means 1.11 to 1.79). By the t-test across days, reading (a), p is 0.05, 8.7e-10, 0.1 and 0.03; on pooled neurons, reading (b), it is 0.0013, below 1e-300 (printed as 0), 8.2e-10 and 3.5e-05. So p < 0.001 holds in no reading for every mouse, mouse 1 missing at 0.0013 under (b). Under reading (a), p < 0.001 holds in 14 of 15 bins of mouse 2 and no bin of the other mice, so no mouse has it in every bin. The criterion has no partial band. The pooled counts (44546 E, 5530 I) are within the expected 41723 +/- 4172 and 5142 +/- 514.

Single-neuron ROC, every session¶

AUC of high-rate against low-rate choices on correct trials without 16 Hz trials, at every choice-aligned bin, with 50 label shuffles (claims file, opening comment). Error-trial AUCs for figs3e and the wider window of figs3c are computed in the same pass.

In [7]:
rng_roc = np.random.default_rng(2020)
R = []
for s in S:
    r = nj.roc_session(s, rng_roc, (1,))
    if r is None:
        R.append(None); continue
    a = s["al"][nj.CHOICE]; m = nj.trial_mask(s, (1,), no16=True)
    fr, ft = a["frames"], a["frames_t"]
    win_a = np.nanmean(a["B"][:, [int(np.flatnonzero(a["k"] == k)[0]) for k in (-2, -1, 0, 1, 2) if k in a["k"]]], 1)
    win_b = np.nanmean(fr[:, (ft >= -0.2) & (ft < 0.3)], 1)
    r["win_a"] = nj.roc_session(s, rng_roc, (1,), X=win_a)
    r["win_b"] = nj.roc_session(s, rng_roc, (1,), X=win_b)
    r["win_a_bins"] = [k for k in (-2, -1, 0, 1, 2) if k in a["k"]]
    r["err"] = nj.roc_session(s, rng_roc, (0,), bins=[-1])
    R.append(r)
print("sessions with at least 10 correct trials of each choice:", sum(r is not None for r in R), "of", len(R))
print("dropped:", [(s["mouse"], s["session_id"]) for s, r in zip(S, R) if r is None])

def per_session(k=-1, key="sig", src=None, mask=None):
    out = []
    for s, r in zip(S, R):
        if r is None:
            continue
        rr = r if src is None else r[src]
        if rr is None:
            continue
        j = int(np.flatnonzero(rr["k"] == k)[0]) if k in rr["k"] else None
        if j is None:
            continue
        v = rr[key][j]
        row = {"mouse": s["mouse"], "session": s["session_id"]}
        for t, lab in (("excitatory", "E"), ("inhibitory", "I")):
            sel = s["type"] == t
            if mask is not None:
                sel = sel & mask(s)
            row[lab] = np.nanmean(v[sel]) if sel.sum() else np.nan
            row["n" + lab] = int(np.nansum(v[sel])) if key in ("sig", "emp_sig") else int(sel.sum())
            row["N" + lab] = int(sel.sum())
        out.append(row)
    return pd.DataFrame(out)

for r in R:
    if r is not None:
        r["emp_sig"] = r["emp"] < 0.05
/tmp/ipykernel_2643/1118373972.py:9: RuntimeWarning: Mean of empty slice
  win_a = np.nanmean(a["B"][:, [int(np.flatnonzero(a["k"] == k)[0]) for k in (-2, -1, 0, 1, 2) if k in a["k"]]], 1)
/tmp/ipykernel_2643/1118373972.py:10: RuntimeWarning: Mean of empty slice
  win_b = np.nanmean(fr[:, (ft >= -0.2) & (ft < 0.3)], 1)
sessions with at least 10 correct trials of each choice: 127 of 135
dropped: [(1, '170808180842'), (1, '170808190057'), (1, '170814191401'), (1, '170815163235'), (2, '170724051215'), (2, '170822014200'), (2, '170822144835'), (4, '170821173730')]

fig2a-example-session¶

In an example session (285 excitatory and 29 inhibitory neurons), 24 excitatory (8%) and 5 inhibitory (17%) neurons were significantly choice selective just before the choice.

In [8]:
ex = [i for i, s in enumerate(S) if (s["type"] == "excitatory").sum() == 285 and (s["type"] == "inhibitory").sum() == 29]
print("sessions with 285 excitatory and 29 inhibitory neurons:", [(S[i]["mouse"], S[i]["session_id"]) for i in ex])
if len(ex) == 1:
    s = S[ex[0]]
    rng_ex = np.random.default_rng(1)
    cE, cI = [], []
    for rep in range(20):
        r = nj.roc_session(s, rng_ex, (1,), bins=[-1])
        cE.append(int(r["sig"][0][s["type"] == "excitatory"].sum())); cI.append(int(r["sig"][0][s["type"] == "inhibitory"].sum()))
    print("trials (low, high choice):", r["n"])
    print("selective excitatory over 20 repetitions:", cE, "median", np.median(cE), "(expected 24 +/- 2.4)")
    print("selective inhibitory over 20 repetitions:", cI, "median", np.median(cI), "(expected 5 +/- 0.5)")
    e = r["emp"][0] < 0.05
    print("variant, empirical p < 0.05 (last repetition): excitatory", int(e[s["type"] == "excitatory"].sum()), "inhibitory", int(e[s["type"] == "inhibitory"].sum()))
sessions with 285 excitatory and 29 inhibitory neurons: [(4, '170625231642')]
trials (low, high choice): (31, 37)
selective excitatory over 20 repetitions: [10, 12, 13, 8, 11, 12, 10, 8, 10, 14, 12, 12, 8, 16, 12, 15, 10, 9, 10, 12] median 11.5 (expected 24 +/- 2.4)
selective inhibitory over 20 repetitions: [1, 1, 2, 1, 1, 1, 2, 1, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2] median 1.0 (expected 5 +/- 0.5)
variant, empirical p < 0.05 (last repetition): excitatory 28 inhibitory 2

Result: not reproduced. One session (mouse 4, 170625231642) has 285 excitatory and 29 inhibitory neurons. Over 20 repetitions of the 50-shuffle rule, the median number of selective neurons is 11.5 excitatory and 1 inhibitory, against the expected 24 and 5. The empirical-p variant gives 28 and 2.

fig2bc-fraction-selective-similar¶

Excitatory and inhibitory neurons have a similar fraction of significantly choice-selective neurons just before the choice (median across mice 13% and 16%, about 43 excitatory and 6 inhibitory neurons per session); the difference is significant in mouse 4.

In [9]:
def frac_table(P, label):
    g = P.groupby("mouse")
    t = pd.DataFrame({"sessions": g.size(), "E": g.E.mean(), "I": g.I.mean(), "nE": g.nE.mean(), "nI": g.nI.mean()})
    t["p"] = [stats.ttest_ind(P[P.mouse == m].E, P[P.mouse == m].I, nan_policy="omit").pvalue for m in t.index]
    print(label); print(t.round(4).to_string())
    print("   p per mouse:", {m: f"{v:.4g}" for m, v in t.p.items()})
    print("median across mice: E %.4f, I %.4f; selective per session E %.1f, I %.1f" % (t.E.median(), t.I.median(), t.nE.median(), t.nI.median()))
    return t
F = per_session(-1, "sig")
tF = frac_table(F, "normal-fit rule (code)")
print("expected: E 0.13 +/- 0.013, I 0.16 +/- 0.016, 43 +/- 4.3 and 6 +/- 0.6 per session; mice with p < 0.05:", list(tF.index[tF.p < 0.05]))
Fe = per_session(-1, "emp_sig")
tFe = frac_table(Fe, "variant, empirical p < 0.05 from the 50 shuffles")
normal-fit rule (code)
       sessions       E       I       nE      nI       p
mouse                                                   
1            41  0.1439  0.1766  40.5122  6.6341  0.1761
2            45  0.1283  0.1673  47.3111  7.8000  0.0402
3             7  0.0775  0.0931  20.7143  2.4286  0.5468
4            34  0.1292  0.1858  43.9706  6.9706  0.0133
   p per mouse: {1: '0.1761', 2: '0.04023', 3: '0.5468', 4: '0.01335'}
median across mice: E 0.1288, I 0.1719; selective per session E 42.2, I 6.8
expected: E 0.13 +/- 0.013, I 0.16 +/- 0.016, 43 +/- 4.3 and 6 +/- 0.6 per session; mice with p < 0.05: [2, 4]
variant, empirical p < 0.05 from the 50 shuffles
       sessions       E       I       nE       nI       p
mouse                                                    
1            41  0.2264  0.2565  63.9756   9.6829  0.2589
2            45  0.2131  0.2491  78.8889  11.8222  0.1000
3             7  0.1417  0.1410  38.1429   3.5714  0.9870
4            34  0.2108  0.2683  71.5000  10.0000  0.0310
   p per mouse: {1: '0.2589', 2: '0.1', 3: '0.987', 4: '0.03105'}
median across mice: E 0.2120, I 0.2528; selective per session E 67.7, I 9.8

fig2bc and figs3c: repetition over seeds of the shuffles¶

The significance rule rests on 50 label shuffles per neuron, one draw per session above. The round-2 verifier noted that two outcomes lie near a bound on that one draw (fig2bc, mouse 2 p = 0.040; figs3c, reading (b) 9.883 inhibitory neurons per session against the lower bound 9.9), as fig2a did, where 20 repetitions are shown. Here the ROC at bin -1 and over both windows of figs3c is repeated with 10 further seeds (seed [seed, session index], a standard choice); the trials and the rule are those above.

In [10]:
# Seed repetitions of the ROC shuffles: bin -1 (fig2bc) and the two windows of figs3c, 10 seeds.
from joblib import Parallel, delayed
os.environ.setdefault("OMP_NUM_THREADS", "1")
NSEED = 10
def _rep_sig(D, y, i):
    out = []
    for seed in range(NSEED):
        _, _, sig, _ = nj.roc_selective(D, y, np.random.default_rng([seed, i]), 50)
        out.append(sig)
    return np.array(out)
jobs, meta = [], []
for i, (s, r) in enumerate(zip(S, R)):
    if r is None:
        continue
    a = s["al"][nj.CHOICE]; m = nj.trial_mask(s, (1,), no16=True)
    fr, ft = a["frames"], a["frames_t"]
    j = int(np.flatnonzero(a["k"] == -1)[0])
    win_a = np.nanmean(a["B"][:, [int(np.flatnonzero(a["k"] == k)[0]) for k in (-2, -1, 0, 1, 2) if k in a["k"]]], 1)
    win_b = np.nanmean(fr[:, (ft >= -0.2) & (ft < 0.3)], 1)
    D = np.concatenate([a["B"][m][:, j, :], win_a[m], win_b[m]], 1)
    jobs.append(delayed(_rep_sig)(D, s["trials"].choice.to_numpy()[m].astype(int), i)); meta.append(i)
t1 = time.time()
SIG = Parallel(n_jobs=4)(jobs)
rows = []
for i, sg in zip(meta, SIG):
    s = S[i]; nn = len(s["type"])
    for seed in range(NSEED):
        for c, col in enumerate(("bin-1", "a", "b")):
            v = sg[seed, c * nn:(c + 1) * nn]
            row = {"seed": seed, "col": col, "mouse": s["mouse"], "session": s["session_id"]}
            for t, lab in (("excitatory", "E"), ("inhibitory", "I")):
                sel = s["type"] == t
                row[lab] = np.nanmean(v[sel]) if sel.sum() else np.nan; row["n" + lab] = int(np.nansum(v[sel]))
            rows.append(row)
REP = pd.DataFrame(rows)
print("seed repetitions: %d sessions x %d seeds in %.1f min" % (len(meta), NSEED, (time.time() - t1) / 60))
/tmp/ipykernel_2643/3005725542.py:18: RuntimeWarning: Mean of empty slice
  win_a = np.nanmean(a["B"][:, [int(np.flatnonzero(a["k"] == k)[0]) for k in (-2, -1, 0, 1, 2) if k in a["k"]]], 1)
/tmp/ipykernel_2643/3005725542.py:19: RuntimeWarning: Mean of empty slice
  win_b = np.nanmean(fr[:, (ft >= -0.2) & (ft < 0.3)], 1)
seed repetitions: 127 sessions x 10 seeds in 5.0 min
In [11]:
out = []
for seed, P in REP[REP.col == "bin-1"].groupby("seed"):
    g = P.groupby("mouse")
    p = {m: stats.ttest_ind(P[P.mouse == m].E, P[P.mouse == m].I, nan_policy="omit").pvalue for m in g.groups}
    mE, mI = g.E.mean().median(), g.I.mean().median()
    inE, inI = abs(mE - 0.13) <= 0.013, abs(mI - 0.16) <= 0.016
    tests = all(p[m] >= 0.05 for m in (1, 2, 3) if m in p)
    band = "reproduced" if inE and inI and tests else ("partially reproduced" if tests else "not reproduced")
    out.append({"seed": seed, **{f"p{m}": round(v, 4) for m, v in p.items()}, "median E": round(mE, 4), "median I": round(mI, 4),
                "per session E": round(g.nE.mean().median(), 1), "per session I": round(g.nI.mean().median(), 1), "band": band})
O = pd.DataFrame(out)
print("fig2bc over %d seeds of the 50 shuffles (seed repetitions; the main result above is a separate draw):" % NSEED)
print(O.to_string(index=False))
print("seeds with p < 0.05 per mouse:", {m: int((O[f"p{m}"] < 0.05).sum()) for m in range(1, 5) if f"p{m}" in O})
print("mouse 2 p from %.4f to %.4f, median %.4f" % (O.p2.min(), O.p2.max(), O.p2.median()))
print("band per seed:", O.band.value_counts().to_dict())
fig2bc over 10 seeds of the 50 shuffles (seed repetitions; the main result above is a separate draw):
 seed     p1     p2     p3     p4  median E  median I  per session E  per session I           band
    0 0.2779 0.0797 0.6971 0.0225    0.1297    0.1609           42.0            6.5     reproduced
    1 0.3008 0.0857 0.5781 0.0149    0.1297    0.1617           42.0            6.5     reproduced
    2 0.4029 0.0427 0.7529 0.0344    0.1284    0.1613           41.6            6.3 not reproduced
    3 0.2761 0.0525 0.4809 0.0218    0.1287    0.1649           42.6            6.6     reproduced
    4 0.3218 0.0266 0.4016 0.0179    0.1287    0.1650           42.0            6.5 not reproduced
    5 0.2461 0.0508 0.5869 0.0273    0.1289    0.1653           42.5            6.7     reproduced
    6 0.1890 0.0593 0.4750 0.0211    0.1289    0.1648           41.9            6.5     reproduced
    7 0.2720 0.0385 0.5113 0.0091    0.1302    0.1659           42.6            6.6 not reproduced
    8 0.3113 0.0913 0.6579 0.0138    0.1317    0.1608           42.2            6.6     reproduced
    9 0.1966 0.0178 0.5112 0.0188    0.1286    0.1700           41.7            6.6 not reproduced
seeds with p < 0.05 per mouse: {1: 0, 2: 4, 3: 0, 4: 10}
mouse 2 p from 0.0178 to 0.0913, median 0.0517
band per seed: {'reproduced': 6, 'not reproduced': 4}

Result: not reproduced. The medians across mice of the fractions selective are E 0.1288 and I 0.1719, both within tolerance, and 42.2 excitatory neurons per session is within tolerance; 6.8 inhibitory is above 6 +/- 0.6. The unpaired t-test across sessions finds a difference in mouse 4 (p = 0.01335), as the paper reports, but also in mouse 2 (p = 0.04023), where the criterion requires none; in both, inhibitory neurons are more often selective. Neither the reproduced band nor the partial band (t-tests only) holds. With the empirical-p variant only mouse 4 differs (p = 0.03105), but the medians (0.2120, 0.2528) are then outside tolerance. Over 10 further seeds of the 50 shuffles the outcome is not stable: mouse 2 has p < 0.05 in 4 of 10 seeds (p 0.0178 to 0.0913, median 0.0517), mouse 4 in all 10, and the medians stay within tolerance (E 0.1284 to 0.1317, I 0.1608 to 0.1700), so the criterion's band is reproduced in 6 seeds and not reproduced in 4. The outcome kept is that of the main draw, which lies on the not-reproduced side.

fig2bd-selectivity-time-course¶

The fraction of choice-selective neurons and the magnitude of choice selectivity increase gradually over the trial and peak just after the choice.

In [12]:
ks_all = sorted(set().union(*[set(r["k"]) for r in R if r is not None]))
TC = []
for k in ks_all:
    for key in ("sig", "sel"):
        P = per_session(k, key)
        for m, g in P.groupby("mouse"):
            TC.append({"k": k, "key": key, "mouse": m, "E": g.E.mean(), "I": g.I.mean(), "n": len(g)})
TC = pd.DataFrame(TC)
for m in range(1, 5):
    nmax = TC[TC.mouse == m].n.max()
    for key in ("sig", "sel"):
        t = TC[(TC.mouse == m) & (TC.key == key) & (TC.n >= 0.5 * nmax)].set_index("k")
        for lab in ("E", "I"):
            v = t[lab]
            kpk = int(v.idxmax()); first = int(v.index.min())
            print(f"mouse {m} {'fraction' if key=='sig' else 'magnitude'} {lab}: bins {first}..{int(v.index.max())} (bins in at least half the sessions); "
                  f"earliest {v.loc[first]:.3f}, bin -1 {v.loc[-1]:.3f}, peak {v.max():.3f} at bin {kpk} "
                  f"({kpk*97}-{(kpk+1)*97} ms); (a) peak in bin 0: {kpk == 0}; (b) peak within 300 ms after: {0 <= kpk <= 2}; earliest below bin -1: {v.loc[first] < v.loc[-1]}")
print("number of sessions per bin, mouse 1:", TC[(TC.mouse == 1) & (TC.key == "sig")].set_index("k").n.to_dict())
sh_level = np.mean([np.mean(r["sel"][0]) for r in R if r is not None])
print("mean selectivity in the earliest bin of each session, all neurons: %.3f" % sh_level)
mouse 1 fraction E: bins -17..10 (bins in at least half the sessions); earliest 0.108, bin -1 0.144, peak 0.182 at bin 2 (194-291 ms); (a) peak in bin 0: False; (b) peak within 300 ms after: True; earliest below bin -1: True
mouse 1 fraction I: bins -17..10 (bins in at least half the sessions); earliest 0.117, bin -1 0.177, peak 0.201 at bin 1 (97-194 ms); (a) peak in bin 0: False; (b) peak within 300 ms after: True; earliest below bin -1: True
mouse 1 magnitude E: bins -17..10 (bins in at least half the sessions); earliest 0.117, bin -1 0.149, peak 0.164 at bin 2 (194-291 ms); (a) peak in bin 0: False; (b) peak within 300 ms after: True; earliest below bin -1: True
mouse 1 magnitude I: bins -17..10 (bins in at least half the sessions); earliest 0.121, bin -1 0.157, peak 0.172 at bin 1 (97-194 ms); (a) peak in bin 0: False; (b) peak within 300 ms after: True; earliest below bin -1: True
mouse 2 fraction E: bins -17..7 (bins in at least half the sessions); earliest 0.047, bin -1 0.128, peak 0.152 at bin 2 (194-291 ms); (a) peak in bin 0: False; (b) peak within 300 ms after: True; earliest below bin -1: True
mouse 2 fraction I: bins -17..7 (bins in at least half the sessions); earliest 0.049, bin -1 0.167, peak 0.200 at bin 3 (291-388 ms); (a) peak in bin 0: False; (b) peak within 300 ms after: False; earliest below bin -1: True
mouse 2 magnitude E: bins -17..7 (bins in at least half the sessions); earliest 0.084, bin -1 0.121, peak 0.130 at bin 2 (194-291 ms); (a) peak in bin 0: False; (b) peak within 300 ms after: True; earliest below bin -1: True
mouse 2 magnitude I: bins -17..7 (bins in at least half the sessions); earliest 0.087, bin -1 0.132, peak 0.145 at bin 3 (291-388 ms); (a) peak in bin 0: False; (b) peak within 300 ms after: False; earliest below bin -1: True
mouse 3 fraction E: bins -11..6 (bins in at least half the sessions); earliest 0.073, bin -1 0.077, peak 0.087 at bin 1 (97-194 ms); (a) peak in bin 0: False; (b) peak within 300 ms after: True; earliest below bin -1: True
mouse 3 fraction I: bins -11..6 (bins in at least half the sessions); earliest 0.075, bin -1 0.093, peak 0.154 at bin -9 (-873--776 ms); (a) peak in bin 0: False; (b) peak within 300 ms after: False; earliest below bin -1: True
mouse 3 magnitude E: bins -11..6 (bins in at least half the sessions); earliest 0.108, bin -1 0.110, peak 0.116 at bin 1 (97-194 ms); (a) peak in bin 0: False; (b) peak within 300 ms after: True; earliest below bin -1: True
mouse 3 magnitude I: bins -11..6 (bins in at least half the sessions); earliest 0.113, bin -1 0.110, peak 0.127 at bin -10 (-970--873 ms); (a) peak in bin 0: False; (b) peak within 300 ms after: False; earliest below bin -1: False
mouse 4 fraction E: bins -17..7 (bins in at least half the sessions); earliest 0.075, bin -1 0.129, peak 0.129 at bin -1 (-97-0 ms); (a) peak in bin 0: False; (b) peak within 300 ms after: False; earliest below bin -1: True
mouse 4 fraction I: bins -17..7 (bins in at least half the sessions); earliest 0.082, bin -1 0.186, peak 0.186 at bin -1 (-97-0 ms); (a) peak in bin 0: False; (b) peak within 300 ms after: False; earliest below bin -1: True
mouse 4 magnitude E: bins -17..7 (bins in at least half the sessions); earliest 0.104, bin -1 0.144, peak 0.144 at bin -1 (-97-0 ms); (a) peak in bin 0: False; (b) peak within 300 ms after: False; earliest below bin -1: True
mouse 4 magnitude I: bins -17..7 (bins in at least half the sessions); earliest 0.104, bin -1 0.163, peak 0.164 at bin 2 (194-291 ms); (a) peak in bin 0: False; (b) peak within 300 ms after: True; earliest below bin -1: True
number of sessions per bin, mouse 1: {-23: 1, -22: 2, -21: 2, -20: 5, -19: 7, -18: 19, -17: 22, -16: 25, -15: 30, -14: 32, -13: 35, -12: 37, -11: 38, -10: 41, -9: 41, -8: 41, -7: 41, -6: 41, -5: 41, -4: 41, -3: 41, -2: 41, -1: 41, 0: 41, 1: 41, 2: 41, 3: 41, 4: 41, 5: 41, 6: 41, 7: 40, 8: 23, 9: 22, 10: 21, 11: 18, 12: 13, 13: 8, 14: 6, 15: 5, 16: 3}
mean selectivity in the earliest bin of each session, all neurons: 0.109

Result: blocked, methods underspecified. In the example mouse (mouse 1, 41 sessions) the fraction selective and the magnitude rise from the earliest bin to the bin before the choice for both types. Their peaks fall at bin 2 for excitatory (0.182, 0.164) and bin 1 for inhibitory (0.201, 0.172), 97 to 291 ms after the choice. Under reading (b), within 300 ms after the choice, the claim is reproduced; under reading (a), the first bin after the choice, it is not reproduced. The readings give different outcomes, so the claim is blocked. In mouse 2 inhibitory peaks fall at bin 3 (291 to 388 ms), in mouse 4 three of four peaks fall at bin -1, and in mouse 3 inhibitory selectivity peaks at bin -9 or -10 (7 sessions). The question of the window is for the paper's authors (finding).

fig2de-selectivity-magnitude-similar¶

The magnitude and time course of choice selectivity are similar for excitatory and inhibitory neurons.

In [13]:
M = per_session(-1, "sel")
for m, g in M.groupby("mouse"):
    t = stats.ttest_ind(g.E, g.I, nan_policy="omit")
    print(f"mouse {m}: {len(g)} sessions, selectivity E {g.E.mean():.4f}, I {g.I.mean():.4f}, I - E {g.I.mean()-g.E.mean():+.4f}, t = {t.statistic:.2f}, p = {t.pvalue:.3g}")
print("time course, per bin (bins in at least half of a mouse's sessions): number of bins with p < 0.05")
for m in range(1, 5):
    res = []
    for k in ks_all:
        P = per_session(k, "sel"); g = P[P.mouse == m]
        if len(g) >= 0.5 * (M.mouse == m).sum() and len(g) > 2:
            res.append((k, stats.ttest_ind(g.E, g.I, nan_policy="omit").pvalue, g.I.mean() - g.E.mean()))
    print(f"mouse {m}: {sum(p < 0.05 for _, p, _ in res)} of {len(res)} bins; bins with p < 0.05: {[(k, round(p, 3), round(d, 4)) for k, p, d in res if p < 0.05]}")
mouse 1: 41 sessions, selectivity E 0.1490, I 0.1565, I - E +0.0076, t = -1.47, p = 0.144
mouse 2: 45 sessions, selectivity E 0.1213, I 0.1321, I - E +0.0107, t = -1.83, p = 0.0714
mouse 3: 7 sessions, selectivity E 0.1096, I 0.1099, I - E +0.0003, t = -0.02, p = 0.982
mouse 4: 34 sessions, selectivity E 0.1443, I 0.1629, I - E +0.0186, t = -2.36, p = 0.0212
time course, per bin (bins in at least half of a mouse's sessions): number of bins with p < 0.05
mouse 1: 0 of 28 bins; bins with p < 0.05: []
mouse 2: 5 of 25 bins; bins with p < 0.05: [(np.int64(2), np.float64(0.032), np.float64(0.0146)), (np.int64(3), np.float64(0.021), np.float64(0.0155)), (np.int64(4), np.float64(0.009), np.float64(0.0172)), (np.int64(5), np.float64(0.005), np.float64(0.0197)), (np.int64(6), np.float64(0.013), np.float64(0.0181))]
mouse 3: 0 of 18 bins; bins with p < 0.05: []
mouse 4: 9 of 25 bins; bins with p < 0.05: [(np.int64(-2), np.float64(0.042), np.float64(0.0149)), (np.int64(-1), np.float64(0.021), np.float64(0.0186)), (np.int64(0), np.float64(0.016), np.float64(0.0191)), (np.int64(1), np.float64(0.013), np.float64(0.0206)), (np.int64(2), np.float64(0.008), np.float64(0.023)), (np.int64(3), np.float64(0.01), np.float64(0.0222)), (np.int64(4), np.float64(0.009), np.float64(0.0229)), (np.int64(5), np.float64(0.007), np.float64(0.0241)), (np.int64(6), np.float64(0.028), np.float64(0.0208))]

Result: partially reproduced. At 0-97 ms before the choice, mean selectivity does not differ between the types in mice 1, 2 and 3 (p = 0.144, 0.071, 0.98) and differs in mouse 4 (I - E = +0.0186, p = 0.021). The criterion's partial band is one mouse. In the time course, 0, 5, 0 and 9 bins of mice 1 to 4 differ at p < 0.05.

figs3d-same-spiking-selectivity¶

Restricted to excitatory and inhibitory neurons with the same spiking activity, choice selectivity is still similar, and the difference in mouse 4 of Figure 2C disappears.

In [14]:
def matched_mask(s, stat=np.nanmedian):
    m = nj.trial_mask(s, (1,), no16=True)
    med = stat(s["al"][nj.CHOICE]["B"][m][:, nj.bin_index(s, -1)], 0)
    return nj.max_bin_match(med, s["type"])
def mean_matched_mask(s):
    return matched_mask(s, np.nanmean)
for key, lab, mk in (("sel", "selectivity", matched_mask), ("sig", "fraction selective", matched_mask),
                     ("sel", "variant, matched on mean activity: selectivity", mean_matched_mask),
                     ("sig", "variant, matched on mean activity: fraction selective", mean_matched_mask)):
    P = per_session(-1, key, mask=mk)
    print(f"{lab}, matched neurons: median per session E {P.NE.median():.0f}, I {P.NI.median():.0f}; sessions with both types {int(((P.NE>0)&(P.NI>0)).sum())}")
    for m, g in P.groupby("mouse"):
        t = stats.ttest_ind(g.E, g.I, nan_policy="omit")
        print(f"   mouse {m}: E {np.nanmean(g.E):.4f}, I {np.nanmean(g.I):.4f}, I - E {np.nanmean(g.I)-np.nanmean(g.E):+.4f}, p = {t.pvalue:.3g}")
# what the matching keeps: mean bin -1 activity (correct trials) of the kept and of all neurons, per type
rows = []
for s in S:
    if not (s["type"] == "inhibitory").any():
        continue
    mk = matched_mask(s); mk2 = mean_matched_mask(s); m = nj.trial_mask(s, (1,), no16=True)
    mu = np.nanmean(s["al"][nj.CHOICE]["B"][m][:, nj.bin_index(s, -1)], 0)
    med = np.nanmedian(s["al"][nj.CHOICE]["B"][m][:, nj.bin_index(s, -1)], 0)
    E, I = s["type"] == "excitatory", s["type"] == "inhibitory"
    rows.append({"mouse": s["mouse"], "kept_E": np.nanmean(mu[E & mk]), "kept_I": np.nanmean(mu[I & mk]), "all_E": np.nanmean(mu[E]), "all_I": np.nanmean(mu[I]),
                 "meanmatched_E": np.nanmean(mu[E & mk2]), "meanmatched_I": np.nanmean(mu[I & mk2]), "n_meanmatched_E": (E & mk2).sum(), "n_meanmatched_I": (I & mk2).sum(),
                 "frac_E_kept": (E & mk).sum() / E.sum(), "frac_I_kept": (I & mk).sum() / I.sum(), "median_zero_E": np.mean(med[E] < 1e-6), "median_zero_I": np.mean(med[I] < 1e-6)})
MA = pd.DataFrame(rows)
print("mean activity at bin -1 of kept (matched) and of all neurons, and the fraction kept, mean over sessions:")
print(MA.groupby("mouse").mean().round(4).to_string())
for mo, g in MA.groupby("mouse"):
    print(f"   mouse {mo}: kept I - E {np.nanmean(g.kept_I - g.kept_E):+.4f} (paired t across sessions p = {stats.ttest_rel(g.kept_I, g.kept_E, nan_policy='omit').pvalue:.2g}); "
          f"all I - E {np.nanmean(g.all_I - g.all_E):+.4f}; matched on means: I - E {np.nanmean(g.meanmatched_I - g.meanmatched_E):+.4f} "
          f"(p = {stats.ttest_rel(g.meanmatched_I, g.meanmatched_E, nan_policy='omit').pvalue:.2g})")
selectivity, matched neurons: median per session E 265, I 22; sessions with both types 127
   mouse 1: E 0.1437, I 0.1528, I - E +0.0091, p = 0.175
   mouse 2: E 0.1192, I 0.1214, I - E +0.0022, p = 0.748
   mouse 3: E 0.1063, I 0.1043, I - E -0.0020, p = 0.882
   mouse 4: E 0.1349, I 0.1388, I - E +0.0038, p = 0.551
fraction selective, matched neurons: median per session E 265, I 22; sessions with both types 127
   mouse 1: E 0.1344, I 0.1751, I - E +0.0407, p = 0.134
   mouse 2: E 0.1215, I 0.1380, I - E +0.0165, p = 0.454
   mouse 3: E 0.0669, I 0.0853, I - E +0.0184, p = 0.514
   mouse 4: E 0.1064, I 0.1336, I - E +0.0273, p = 0.202
variant, matched on mean activity: selectivity, matched neurons: median per session E 81, I 8; sessions with both types 127
   mouse 1: E 0.1314, I 0.1354, I - E +0.0040, p = 0.678
   mouse 2: E 0.1084, I 0.1085, I - E +0.0002, p = 0.985
   mouse 3: E 0.1057, I 0.0878, I - E -0.0178, p = 0.135
   mouse 4: E 0.1185, I 0.1150, I - E -0.0035, p = 0.657
variant, matched on mean activity: fraction selective, matched neurons: median per session E 81, I 8; sessions with both types 127
   mouse 1: E 0.0990, I 0.1251, I - E +0.0261, p = 0.322
   mouse 2: E 0.0894, I 0.1008, I - E +0.0114, p = 0.623
   mouse 3: E 0.0477, I 0.0298, I - E -0.0179, p = 0.513
   mouse 4: E 0.0649, I 0.0687, I - E +0.0038, p = 0.836
mean activity at bin -1 of kept (matched) and of all neurons, and the fraction kept, mean over sessions:
       kept_E  kept_I   all_E   all_I  meanmatched_E  meanmatched_I  n_meanmatched_E  n_meanmatched_I  frac_E_kept  frac_I_kept  median_zero_E  median_zero_I
mouse                                                                                                                                                        
1      0.0028  0.0027  0.0038  0.0042         0.0005         0.0004          66.2889           9.5778       0.7052       0.6246         0.9995         1.0000
2      0.0025  0.0028  0.0030  0.0047         0.0010         0.0010          63.0625           7.2292       0.6987       0.4692         1.0000         0.9996
3      0.0020  0.0031  0.0023  0.0041         0.0003         0.0003          95.0000           8.2857       0.8916       0.8275         0.9971         0.9945
4      0.0025  0.0023  0.0031  0.0036         0.0003         0.0003         117.1143          11.5714       0.8378       0.6593         0.9998         1.0000
   mouse 1: kept I - E -0.0001 (paired t across sessions p = 0.71); all I - E +0.0004; matched on means: I - E -0.0000 (p = 0.19)
   mouse 2: kept I - E +0.0003 (paired t across sessions p = 0.016); all I - E +0.0016; matched on means: I - E +0.0000 (p = 0.5)
   mouse 3: kept I - E +0.0011 (paired t across sessions p = 0.22); all I - E +0.0018; matched on means: I - E -0.0000 (p = 0.59)
   mouse 4: kept I - E -0.0002 (paired t across sessions p = 0.12); all I - E +0.0005; matched on means: I - E +0.0000 (p = 0.78)

Result: reproduced. Among neurons in the activity bin holding the most inhibitory neurons (median 265 E and 22 I per session) no mouse shows a difference in mean selectivity (p = 0.18, 0.75, 0.88, 0.55) or in the fraction selective (p = 0.13, 0.45, 0.51, 0.20), so the mouse 4 difference of fig2de is gone. The median activity is zero for 99.45 to 100 percent of neurons, so this match keeps the bin at zero, and in mouse 2 the kept inhibitory neurons stay more active than the kept excitatory ones (I - E +0.0003, p = 0.016). Matched on mean activity instead (median 81 E and 8 I per session, I - E activity p = 0.19 to 0.78), no mouse differs either (selectivity p = 0.68, 0.98, 0.14, 0.66; fraction p = 0.32, 0.62, 0.51, 0.84).

figs3c-wider-window¶

ROC on the window from 200 ms before to 300 ms after the choice gives a larger fraction of selective neurons, 21% of excitatory and 27% of inhibitory (median across mice), about 69 excitatory and 11 inhibitory neurons per session.

In [15]:
print("bins averaged in reading (a):", pd.Series([str(r["win_a_bins"]) for r in R if r is not None]).value_counts().to_dict())
for src, lab in (("win_a", "(a) bins -2 to 2 (194 ms before to 291 ms after)"), ("win_b", "(b) frames from 200 ms before to 300 ms after")):
    P = per_session(0, "sig", src=src)
    g = P.groupby("mouse")
    print(lab, "fraction E", g.E.mean().round(4).to_dict(), "I", g.I.mean().round(4).to_dict())
    print(f"   median across mice: E {g.E.mean().median():.4f} (0.21 +/- 0.021), I {g.I.mean().median():.4f} (0.27 +/- 0.027); "
          f"per session E {g.nE.mean().median():.3f} (69 +/- 6.9), I {g.nI.mean().median():.3f} (11 +/- 1.1)")
bins averaged in reading (a): {'[-2, -1, 0, 1, 2]': 127}
(a) bins -2 to 2 (194 ms before to 291 ms after) fraction E {1: 0.2308, 2: 0.2138, 3: 0.1213, 4: 0.1802} I {1: 0.2652, 2: 0.2699, 3: 0.1075, 4: 0.2551}
   median across mice: E 0.1970 (0.21 +/- 0.021), I 0.2602 (0.27 +/- 0.027); per session E 63.357 (69 +/- 6.9), I 9.819 (11 +/- 1.1)
(b) frames from 200 ms before to 300 ms after fraction E {1: 0.2382, 2: 0.2223, 3: 0.1218, 4: 0.1856} I {1: 0.2596, 2: 0.272, 3: 0.078, 4: 0.2638}
   median across mice: E 0.2039 (0.21 +/- 0.021), I 0.2617 (0.27 +/- 0.027); per session E 65.322 (69 +/- 6.9), I 9.883 (11 +/- 1.1)
In [16]:
out = []
for (seed, col), P in REP[REP.col.isin(["a", "b"])].groupby(["seed", "col"]):
    g = P.groupby("mouse")
    v = (g.E.mean().median(), g.I.mean().median(), g.nE.mean().median(), g.nI.mean().median())
    ok = [abs(x - e) <= t + 1e-12 for x, e, t in zip(v, (0.21, 0.27, 69, 11), (0.021, 0.027, 6.9, 1.1))]
    out.append({"seed": seed, "reading": col, "E": round(v[0], 4), "I": round(v[1], 4), "nE": round(v[2], 3), "nI": round(v[3], 3),
                "all four within": all(ok)})
O3 = pd.DataFrame(out)
print("figs3c over %d seeds of the 50 shuffles (seed repetitions; the main result above is a separate draw):" % NSEED)
print(O3.to_string(index=False))
for col, g in O3.groupby("reading"):
    print(f"reading ({col}): inhibitory per session {g.nI.min():.3f} to {g.nI.max():.3f} (11 +/- 1.1, lower bound 9.9), "
          f"seeds with all four within tolerance {int(g['all four within'].sum())} of {len(g)}")
figs3c over 10 seeds of the 50 shuffles (seed repetitions; the main result above is a separate draw):
 seed reading      E      I     nE     nI  all four within
    0       a 0.1978 0.2520 63.155  9.699            False
    0       b 0.2026 0.2576 64.489  9.875            False
    1       a 0.1986 0.2641 63.607 10.157             True
    1       b 0.2030 0.2693 65.029 10.191             True
    2       a 0.1987 0.2505 63.254  9.489            False
    2       b 0.2032 0.2592 64.539  9.814            False
    3       a 0.1991 0.2597 63.690  9.805            False
    3       b 0.2036 0.2662 64.812 10.059             True
    4       a 0.1981 0.2595 63.585  9.840            False
    4       b 0.2028 0.2647 64.821 10.012             True
    5       a 0.1986 0.2562 64.135  9.828            False
    5       b 0.2035 0.2632 65.552  9.936             True
    6       a 0.1969 0.2507 63.916  9.471            False
    6       b 0.2017 0.2576 65.025  9.733            False
    7       a 0.1988 0.2624 63.934  9.904             True
    7       b 0.2032 0.2649 65.297  9.975             True
    8       a 0.1990 0.2527 63.885  9.531            False
    8       b 0.2038 0.2560 65.314  9.668            False
    9       a 0.1976 0.2574 63.144  9.855            False
    9       b 0.2025 0.2610 64.456  9.904             True
reading (a): inhibitory per session 9.471 to 10.157 (11 +/- 1.1, lower bound 9.9), seeds with all four within tolerance 2 of 10
reading (b): inhibitory per session 9.668 to 10.191 (11 +/- 1.1, lower bound 9.9), seeds with all four within tolerance 6 of 10

Result: not reproduced. The median fractions across mice are E 0.197 and I 0.260 under reading (a) and E 0.204 and I 0.262 under reading (b), all within tolerance. Excitatory neurons per session are 63.357 and 65.322, within 69 +/- 6.9. Inhibitory neurons per session are 9.819 under (a) and 9.883 under (b), both below the lower bound 9.9. Both readings fail on the same value, and the criterion has no partial band. Over 10 further seeds of the 50 shuffles the inhibitory count per session is 9.471 to 10.157 under (a) and 9.668 to 10.191 under (b), so all four values are within tolerance in 2 of 10 seeds under (a) and 6 of 10 under (b): the result sits on the bound, and in 4 seeds the readings disagree. The outcome kept is that of the main draw, where both readings fail.

figs3e-correct-error-correlation¶

Choice selectivity on correct and on error trials is positively correlated across neurons, so most neurons reflect the choice more than the stimulus, and within each mouse this correlation is very similar for excitatory and inhibitory neurons; it is weaker in mouse 4.

In [17]:
rows = []
for s, r in zip(S, R):
    if r is None or r["err"] is None:
        continue
    j = int(np.flatnonzero(r["k"] == -1)[0])
    row = {"mouse": s["mouse"], "session": s["session_id"]}
    for t, lab in (("excitatory", "E"), ("inhibitory", "I")):
        sel = s["type"] == t
        row[lab] = stats.pearsonr(r["auc"][j][sel], r["err"]["auc"][0][sel])[0]
    rows.append(row)
CE = pd.DataFrame(rows)
print("sessions with at least 10 error trials of each choice:", len(CE), "of", sum(r is not None for r in R), CE.groupby("mouse").size().to_dict())
for m, g in CE.groupby("mouse"):
    t = stats.ttest_ind(g.E, g.I, nan_policy="omit")
    print(f"mouse {m}: mean r E {g.E.mean():.3f}, I {g.I.mean():.3f}, difference {g.E.mean()-g.I.mean():+.3f}, p = {t.pvalue:.3g}")
gm = CE.groupby("mouse")[["E", "I"]].mean()
print("lowest mean r: E in mouse", int(gm.E.idxmin()), ", I in mouse", int(gm.I.idxmin()))
sessions with at least 10 error trials of each choice: 94 of 127 {1: 34, 2: 31, 3: 3, 4: 26}
mouse 1: mean r E 0.419, I 0.494, difference -0.074, p = 0.136
mouse 2: mean r E 0.392, I 0.430, difference -0.039, p = 0.316
mouse 3: mean r E 0.285, I 0.275, difference +0.010, p = 0.965
mouse 4: mean r E 0.041, I -0.027, difference +0.068, p = 0.35
lowest mean r: E in mouse 4 , I in mouse 4

Result: not reproduced. In 94 sessions with at least 10 error trials of each choice the mean correct-to-error AUC correlation is positive for both types in mice 1 to 3 (0.275 to 0.494). Mouse 4 has the lowest r for both types (E 0.041, I -0.027), so its inhibitory mean is not positive. No mouse shows a difference between the types (p = 0.14, 0.32, 0.97, 0.35). One part fails and the criterion has no partial band.

Noise and spontaneous correlations, every session¶

Noise correlations at bin -1 on trials with a choice after subtracting each choice's mean; spontaneous correlations at 0-97 ms before the initiation tone without subtraction (Methods, Noise correlations). Preference by the sign of AUC - 0.5 at bin -1 (correct-trial AUC).

In [18]:
NC = []
for s, r in zip(S, R):
    if r is None:
        continue
    pref = r["auc"][int(np.flatnonzero(r["k"] == -1)[0])] > 0.5
    E = s["type"] == "excitatory"; I = s["type"] == "inhibitory"
    m = nj.trial_mask(s, (1,), no16=True)
    med = np.nanmedian(s["al"][nj.CHOICE]["B"][m][:, nj.bin_index(s, -1)], 0)
    match = nj.max_bin_match(med, s["type"])
    match2 = nj.max_bin_match(np.nanmean(s["al"][nj.CHOICE]["B"][m][:, nj.bin_index(s, -1)], 0), s["type"])  # variant: matched on means
    for kind, C in (("noise", nj.corr_session(s, nj.CHOICE, -1, True)), ("spont", nj.corr_session(s, nj.INIT, -1, False))):
        row = {"mouse": s["mouse"], "session": s["session_id"], "kind": kind}
        # same vs opposite preference
        for lab, a, b in (("EI", E, I), ("IE", I, E), ("EE", E, E), ("II", I, I)):
            same = np.concatenate([nj.mean_partner_r(C, a & (pref == p), b & (pref == p)) for p in (True, False)])
            opp = np.concatenate([nj.mean_partner_r(C, a & (pref == p), b & (pref != p)) for p in (True, False)])
            row["same_" + lab] = same; row["opp_" + lab] = opp
            row[lab] = nj.mean_partner_r(C, a, b)
            row["m_" + lab] = nj.mean_partner_r(C, a & match, b & match)
            row["mm_" + lab] = nj.mean_partner_r(C, a & match2, b & match2)
        NC.append(row)
NC = pd.DataFrame(NC)
print("sessions:", NC[NC.kind == "noise"].groupby("mouse").size().to_dict())
sessions: {1: 41, 2: 45, 3: 7, 4: 34}

fig6a-same-selectivity-correlations¶

Noise correlations are stronger between neurons with the same choice selectivity than between neurons with opposite selectivity, for excitatory-inhibitory, excitatory-excitatory and inhibitory-inhibitory pairs, significant in every mouse except mouse 3 for EE and II pairs; the same holds in the spontaneous pre-trial period.

In [19]:
def cat(x):
    x = np.concatenate(list(x)); return x[~np.isnan(x)]
for kind in ("noise", "spont"):
    print(kind)
    for m in range(1, 5):
        g = NC[(NC.kind == kind) & (NC.mouse == m)]
        out = []
        for lab in ("EI", "EE", "II"):
            if lab == "EI":
                same = np.concatenate([cat(g.same_EI), cat(g.same_IE)]); opp = np.concatenate([cat(g.opp_EI), cat(g.opp_IE)])
                ss = np.array([np.nanmean(np.concatenate([a, b])) for a, b in zip(g.same_EI, g.same_IE)]); so = np.array([np.nanmean(np.concatenate([a, b])) for a, b in zip(g.opp_EI, g.opp_IE)])
            else:
                same, opp = cat(g["same_" + lab]), cat(g["opp_" + lab])
                ss = np.array([np.nanmean(a) for a in g["same_" + lab]]); so = np.array([np.nanmean(a) for a in g["opp_" + lab]])
            p = stats.ttest_ind(same, opp).pvalue
            pv = stats.ttest_ind(ss, so, nan_policy="omit").pvalue
            out.append(f"{lab}: same {same.mean():.4f} opp {opp.mean():.4f} p = {p:.2g} [sessions p = {pv:.4f}]")
        print(f"  mouse {m}: " + "; ".join(out))
noise
  mouse 1: EI: same 0.0142 opp 0.0093 p = 3.8e-43 [sessions p = 0.0000]; EE: same 0.0123 opp 0.0079 p = 3.3e-87 [sessions p = 0.0000]; II: same 0.0196 opp 0.0125 p = 2.5e-09 [sessions p = 0.0006]
  mouse 2: EI: same 0.0125 opp 0.0092 p = 1.1e-26 [sessions p = 0.0498]; EE: same 0.0106 opp 0.0074 p = 7e-79 [sessions p = 0.0007]; II: same 0.0245 opp 0.0174 p = 7.2e-10 [sessions p = 0.0394]
  mouse 3: EI: same 0.0136 opp 0.0087 p = 4.7e-05 [sessions p = 0.2353]; EE: same 0.0081 opp 0.0058 p = 1.9e-06 [sessions p = 0.1474]; II: same 0.0315 opp 0.0110 p = 0.00017 [sessions p = 0.1878]
  mouse 4: EI: same 0.0114 opp 0.0070 p = 8e-23 [sessions p = 0.0227]; EE: same 0.0098 opp 0.0057 p = 2.6e-70 [sessions p = 0.0014]; II: same 0.0349 opp 0.0187 p = 2.4e-13 [sessions p = 0.0010]
spont
  mouse 1: EI: same 0.0152 opp 0.0120 p = 1.7e-18 [sessions p = 0.0252]; EE: same 0.0131 opp 0.0097 p = 7.2e-47 [sessions p = 0.0025]; II: same 0.0209 opp 0.0146 p = 2e-07 [sessions p = 0.0133]
  mouse 2: EI: same 0.0138 opp 0.0116 p = 1.7e-13 [sessions p = 0.1959]; EE: same 0.0102 opp 0.0082 p = 7.8e-33 [sessions p = 0.0868]; II: same 0.0285 opp 0.0228 p = 8.7e-07 [sessions p = 0.1225]
  mouse 3: EI: same 0.0114 opp 0.0075 p = 0.00071 [sessions p = 0.2874]; EE: same 0.0082 opp 0.0069 p = 0.012 [sessions p = 0.5822]; II: same 0.0238 opp 0.0072 p = 0.0002 [sessions p = 0.1361]
  mouse 4: EI: same 0.0089 opp 0.0075 p = 9.9e-05 [sessions p = 0.3241]; EE: same 0.0078 opp 0.0065 p = 7.2e-13 [sessions p = 0.2354]; II: same 0.0233 opp 0.0191 p = 0.0046 [sessions p = 0.2246]

Result: reproduced. By the code's t-test on pooled neurons, noise correlations are higher between neurons of the same preference than of opposite preference for EI, EE and II pairs in every mouse (largest p 0.00017). Spontaneous correlations before the initiation tone show the same pattern in every mouse and pair type (largest p 0.012). Mouse 3 is significant for EE and II too, where the paper reports it is not; the criterion does not require that. Across sessions, the variant, the noise effect holds in mice 1, 2 and 4 (mouse 2 EI p = 0.0498) and not in mouse 3 (p 0.15 to 0.24).

fig6bc-inhibitory-correlations-higher¶

Inhibitory pairs have significantly higher noise correlations than excitatory pairs, with intermediate values for excitatory-inhibitory pairs, also for spontaneous correlations and for neurons matched in spiking activity.

In [20]:
for kind, pre, lab in (("noise", "", "noise"), ("spont", "", "spontaneous"), ("noise", "m_", "noise, matched activity"), ("noise", "mm_", "variant: noise, matched on mean activity")):
    print(lab)
    for m in range(1, 5):
        g = NC[(NC.kind == kind) & (NC.mouse == m)]
        EE, II = cat(g[pre + "EE"]), cat(g[pre + "II"]); EI = np.concatenate([cat(g[pre + "EI"]), cat(g[pre + "IE"])])
        sEE = np.array([np.nanmean(a) if len(a) and not np.all(np.isnan(a)) else np.nan for a in g[pre + "EE"]])
        sII = np.array([np.nanmean(a) if len(a) and not np.all(np.isnan(a)) else np.nan for a in g[pre + "II"]])
        pa = stats.ttest_ind(sII, sEE, nan_policy="omit").pvalue; pb = stats.ttest_ind(II, EE).pvalue
        print(f"  mouse {m}: EE {EE.mean():.4f} ({len(EE)} neurons), EI {EI.mean():.4f}, II {II.mean():.4f} ({len(II)} neurons); "
              f"II > EE (a) sessions p = {pa:.2g} (b) neurons p = {pb:.2g}; EI between: {min(EE.mean(), II.mean()) < EI.mean() < max(EE.mean(), II.mean())}")
print("expected example-mouse counts: 11867 excitatory, 1583 inhibitory neurons")
noise
  mouse 1: EE 0.0101 (11867 neurons), EI 0.0119, II 0.0161 (1583 neurons); II > EE (a) sessions p = 4.8e-05 (b) neurons p = 5e-42; EI between: True
  mouse 2: EE 0.0091 (16758 neurons), EI 0.0112, II 0.0214 (2127 neurons); II > EE (a) sessions p = 2e-06 (b) neurons p = 4.6e-210; EI between: True
  mouse 3: EE 0.0071 (1887 neurons), EI 0.0117, II 0.0225 (182 neurons); II > EE (a) sessions p = 0.025 (b) neurons p = 2.1e-31; EI between: True
  mouse 4: EE 0.0078 (11507 neurons), EI 0.0094, II 0.0281 (1280 neurons); II > EE (a) sessions p = 5e-09 (b) neurons p = 4.4e-234; EI between: True
spontaneous
  mouse 1: EE 0.0115 (11867 neurons), EI 0.0138, II 0.0180 (1583 neurons); II > EE (a) sessions p = 0.0034 (b) neurons p = 9.4e-42; EI between: True
  mouse 2: EE 0.0093 (16758 neurons), EI 0.0129, II 0.0264 (2127 neurons); II > EE (a) sessions p = 1.7e-08 (b) neurons p = 0; EI between: True
  mouse 3: EE 0.0078 (1887 neurons), EI 0.0098, II 0.0162 (182 neurons); II > EE (a) sessions p = 0.15 (b) neurons p = 5.8e-10; EI between: True
  mouse 4: EE 0.0072 (11507 neurons), EI 0.0083, II 0.0220 (1280 neurons); II > EE (a) sessions p = 1.1e-08 (b) neurons p = 7.9e-217; EI between: True
noise, matched activity
  mouse 1: EE 0.0084 (8541 neurons), EI 0.0095, II 0.0135 (998 neurons); II > EE (a) sessions p = 0.092 (b) neurons p = 3.6e-21; EI between: True
  mouse 2: EE 0.0076 (11848 neurons), EI 0.0104, II 0.0237 (1029 neurons); II > EE (a) sessions p = 2.6e-06 (b) neurons p = 3e-187; EI between: True
  mouse 3: EE 0.0067 (1678 neurons), EI 0.0114, II 0.0207 (151 neurons); II > EE (a) sessions p = 0.094 (b) neurons p = 1.2e-22; EI between: True
  mouse 4: EE 0.0070 (9616 neurons), EI 0.0087, II 0.0264 (847 neurons); II > EE (a) sessions p = 1.5e-06 (b) neurons p = 1.6e-168; EI between: True
variant: noise, matched on mean activity
  mouse 1: EE 0.0100 (2381 neurons), EI 0.0102, II 0.0140 (332 neurons); II > EE (a) sessions p = 0.83 (b) neurons p = 0.01; EI between: True
  mouse 2: EE 0.0079 (2790 neurons), EI 0.0097, II 0.0177 (313 neurons); II > EE (a) sessions p = 0.15 (b) neurons p = 3.3e-11; EI between: True
  mouse 3: EE 0.0048 (665 neurons), EI 0.0089, II 0.0006 (58 neurons); II > EE (a) sessions p = 0.33 (b) neurons p = 0.058; EI between: False
  mouse 4: EE 0.0074 (3886 neurons), EI 0.0072, II 0.0199 (392 neurons); II > EE (a) sessions p = 0.028 (b) neurons p = 9.2e-23; EI between: False
expected example-mouse counts: 11867 excitatory, 1583 inhibitory neurons

Result: blocked, methods underspecified. On pooled neurons, reading (b), II noise correlations exceed EE in every mouse for noise, spontaneous and activity-matched correlations (largest p 5.8e-10), with EI between them in every case, so (b) gives reproduced. Across sessions, reading (a), II exceeds EE in every mouse for noise correlations (largest p 0.025), but not for spontaneous correlations in mouse 3 (p = 0.15) or matched correlations in mice 1 and 3 (p = 0.092, 0.094), so (a) gives not reproduced. The readings differ, so the claim is blocked. With neurons matched on mean activity (a variant), II exceeds EE across sessions only in mouse 4 (p = 0.028), on pooled neurons not in mouse 3 (p = 0.058, II 0.0006 below EE 0.0048), and EI is not between in mice 3 and 4. Mouse 1 has exactly 11867 excitatory and 1583 inhibitory neurons, the expected counts, so it is the example mouse. The matching keeps the lowest activity bin, as the median activity is zero for nearly every neuron (01, figs3d).

Learning: performance, early and late days¶

Performance is the fraction correct on easy trials (code's rule, in the helper). Sessions are ordered by the recording date in the file (session_start_time); early and late days by the 20th and 80th percentiles of performance (Methods, Learning analysis), with readings (a) all such days and (b) only the run at the start or end of training.

In [21]:
L = pd.DataFrame([{"i": i, "mouse": s["mouse"], "date": s["start"][:10], "perf": nj.easy_performance(s["trials"])[0], "n_easy": nj.easy_performance(s["trials"])[1]}
                  for i, s in enumerate(S) if s["mouse"] in nj.LEARNING_MICE])
L["day"] = L.groupby("mouse").date.rank(method="first").astype(int)
for m, g in L.groupby("mouse"):
    el = nj.early_late(g.perf.to_numpy(), g.day.to_numpy())
    for rd in ("a", "b"):
        L.loc[g.index, "early_" + rd] = el[rd][0]; L.loc[g.index, "late_" + rd] = el[rd][1]
    print(f"mouse {m}: {len(g)} days, {g.date.min()} to {g.date.max()}, performance {g.perf.min():.2f} to {g.perf.max():.2f}; "
          f"Pearson r of performance with day {stats.pearsonr(g.day, g.perf)[0]:.2f}; early (a) {int(L.loc[g.index,'early_a'].sum())} days {sorted(g.day[L.loc[g.index,'early_a'].astype(bool)])}, "
          f"late (a) {int(L.loc[g.index,'late_a'].sum())} days {sorted(g.day[L.loc[g.index,'late_a'].astype(bool)])}; early (b) {int(L.loc[g.index,'early_b'].sum())}, late (b) {int(L.loc[g.index,'late_b'].sum())}")
print("easy trials per session: median", L.n_easy.median(), "min", L.n_easy.min())
mouse 1: 45 days, 2015-08-17 to 2015-10-29, performance 0.44 to 0.88; Pearson r of performance with day 0.53; early (a) 9 days [1, 3, 5, 6, 7, 8, 10, 11, 16], late (a) 9 days [23, 24, 25, 26, 27, 28, 31, 34, 35]; early (b) 1, late (b) 0
mouse 2: 48 days, 2015-08-14 to 2015-11-02, performance 0.45 to 0.89; Pearson r of performance with day 0.59; early (a) 10 days [1, 2, 3, 4, 5, 6, 7, 8, 19, 23], late (a) 10 days [13, 15, 16, 30, 32, 35, 36, 37, 45, 48]; early (b) 8, late (b) 1
mouse 4: 35 days, 2015-09-03 to 2015-11-01, performance 0.51 to 0.85; Pearson r of performance with day 0.24; early (a) 7 days [2, 3, 5, 7, 8, 32, 33], late (a) 7 days [12, 13, 14, 15, 16, 17, 20]; early (b) 0, late (b) 0
easy trials per session: median 160.0 min 28

fig8f-correlations-decrease¶

Pairwise noise correlations are higher early in training than late, for all combinations of neuron types.

In [22]:
sid2i = {s["session_id"]: i for i, s in enumerate(S)}
Nn = NC[NC.kind == "noise"].copy()
Nn["i"] = Nn.session.map(sid2i)
Nn = Nn.merge(L[["i", "early_a", "late_a", "early_b", "late_b"]], on="i")
for rd in ("a", "b"):
    print("reading", rd)
    for m in nj.LEARNING_MICE:
        g = Nn[Nn.mouse == m]; out = []
        for lab in ("EE", "II", "EI"):
            v = np.array([np.nanmean(np.concatenate([a, b])) if lab == "EI" else np.nanmean(a) for a, b in zip(g[lab], g["IE"])])
            e, l = v[g["early_" + rd].astype(bool).to_numpy()], v[g["late_" + rd].astype(bool).to_numpy()]
            p = stats.ttest_ind(e, l, nan_policy="omit").pvalue if len(e) > 1 and len(l) > 1 else np.nan
            out.append(f"{lab} early {np.nanmean(e):.4f} late {np.nanmean(l):.4f} p = {p:.2g}")
        print(f"  mouse {m} ({int(g['early_'+rd].sum())} early, {int(g['late_'+rd].sum())} late): " + "; ".join(out))
reading a
  mouse 1 (6 early, 9 late): EE early 0.0108 late 0.0095 p = 0.43; II early 0.0172 late 0.0129 p = 0.26; EI early 0.0124 late 0.0107 p = 0.32
  mouse 2 (7 early, 10 late): EE early 0.0138 late 0.0079 p = 0.032; II early 0.0363 late 0.0158 p = 0.014; EI early 0.0192 late 0.0089 p = 0.031
  mouse 4 (6 early, 7 late): EE early 0.0093 late 0.0059 p = 0.16; II early 0.0318 late 0.0237 p = 0.41; EI early 0.0092 late 0.0065 p = 0.22
reading b
  mouse 1 (0 early, 0 late): EE early nan late nan p = nan; II early nan late nan p = nan; EI early nan late nan p = nan
  mouse 2 (5 early, 1 late): EE early 0.0167 late 0.0049 p = nan; II early 0.0429 late -0.0019 p = nan; EI early 0.0236 late 0.0033 p = nan
  mouse 4 (0 early, 0 late): EE early nan late nan p = nan; II early nan late nan p = nan; EI early nan late nan p = nan
/tmp/ipykernel_2643/3165453070.py:13: RuntimeWarning: Mean of empty slice
  out.append(f"{lab} early {np.nanmean(e):.4f} late {np.nanmean(l):.4f} p = {p:.2g}")
/tmp/ipykernel_2643/3165453070.py:13: RuntimeWarning: Mean of empty slice
  out.append(f"{lab} early {np.nanmean(e):.4f} late {np.nanmean(l):.4f} p = {p:.2g}")
/tmp/ipykernel_2643/3165453070.py:13: RuntimeWarning: Mean of empty slice
  out.append(f"{lab} early {np.nanmean(e):.4f} late {np.nanmean(l):.4f} p = {p:.2g}")
/tmp/ipykernel_2643/3165453070.py:13: RuntimeWarning: Mean of empty slice
  out.append(f"{lab} early {np.nanmean(e):.4f} late {np.nanmean(l):.4f} p = {p:.2g}")
/tmp/ipykernel_2643/3165453070.py:13: RuntimeWarning: Mean of empty slice
  out.append(f"{lab} early {np.nanmean(e):.4f} late {np.nanmean(l):.4f} p = {p:.2g}")
/tmp/ipykernel_2643/3165453070.py:13: RuntimeWarning: Mean of empty slice
  out.append(f"{lab} early {np.nanmean(e):.4f} late {np.nanmean(l):.4f} p = {p:.2g}")

Result: partially reproduced. With early and late days by reading (a), noise correlations are higher early than late for EE, II and EI in every learning mouse in the mean. The difference is significant only in mouse 2 (p = 0.032, 0.014, 0.031), not in mice 1 and 4 (p 0.16 to 0.43). Reading (b) of early and late days gives no days in mice 1 and 4 and 1 late day in mouse 2, so it cannot be tested.

fig8g-fraction-selective-triples¶

The fraction of choice-selective neurons increases about threefold from early to late training, in both excitatory and inhibitory neurons.

In [23]:
F2 = F.copy(); F2["i"] = F2.session.map(sid2i); F2 = F2.merge(L[["i", "early_a", "late_a", "early_b", "late_b"]], on="i")
for rd in ("a", "b"):
    print("reading", rd, "of early and late days")
    ratios = {"E": [], "I": []}; pooled = {}
    for lab in ("E", "I"):
        e_all, l_all = [], []
        for m in nj.LEARNING_MICE:
            g = F2[F2.mouse == m]
            e = g[lab][g["early_" + rd].astype(bool)]; l = g[lab][g["late_" + rd].astype(bool)]
            p = stats.ttest_ind(l, e, nan_policy="omit").pvalue if len(e) > 1 and len(l) > 1 else np.nan
            ratios[lab].append(l.mean() / e.mean()); e_all.append(e.mean()); l_all.append(l.mean())
            print(f"  {lab} mouse {m}: early {e.mean():.4f} ({len(e)} days), late {l.mean():.4f} ({len(l)} days), ratio {l.mean()/e.mean():.2f}, late > early p = {p:.2g}")
        print(f"  {lab}: (a) mean of per-mouse ratios {np.mean(ratios[lab]):.2f}; (b) ratio of fractions pooled over mice {np.mean(l_all)/np.mean(e_all):.2f} (expected 3 +/- 0.3)")
reading a of early and late days
  E mouse 1: early 0.0339 (6 days), late 0.2484 (9 days), ratio 7.34, late > early p = 2.8e-06
  E mouse 2: early 0.0685 (7 days), late 0.1333 (10 days), ratio 1.95, late > early p = 0.12
  E mouse 4: early 0.0775 (6 days), late 0.1667 (7 days), ratio 2.15, late > early p = 0.0061
  E: (a) mean of per-mouse ratios 3.81; (b) ratio of fractions pooled over mice 3.05 (expected 3 +/- 0.3)
  I mouse 1: early 0.0286 (6 days), late 0.2982 (9 days), ratio 10.44, late > early p = 2.6e-05
  I mouse 2: early 0.0752 (7 days), late 0.1594 (10 days), ratio 2.12, late > early p = 0.063
  I mouse 4: early 0.1476 (6 days), late 0.2103 (7 days), ratio 1.43, late > early p = 0.4
  I: (a) mean of per-mouse ratios 4.66; (b) ratio of fractions pooled over mice 2.66 (expected 3 +/- 0.3)
reading b of early and late days
  E mouse 1: early nan (0 days), late nan (0 days), ratio nan, late > early p = nan
  E mouse 2: early 0.0674 (5 days), late 0.0930 (1 days), ratio 1.38, late > early p = nan
  E mouse 4: early nan (0 days), late nan (0 days), ratio nan, late > early p = nan
  E: (a) mean of per-mouse ratios nan; (b) ratio of fractions pooled over mice nan (expected 3 +/- 0.3)
  I mouse 1: early nan (0 days), late nan (0 days), ratio nan, late > early p = nan
  I mouse 2: early 0.0661 (5 days), late 0.2105 (1 days), ratio 3.18, late > early p = nan
  I mouse 4: early nan (0 days), late nan (0 days), ratio nan, late > early p = nan
  I: (a) mean of per-mouse ratios nan; (b) ratio of fractions pooled over mice nan (expected 3 +/- 0.3)

Result: not reproduced. With early and late days by reading (a), the fraction selective rises from early to late in every mouse and type (per-mouse ratios 1.43 to 10.44). The ratio is E 3.81 and I 4.66 as the mean of per-mouse ratios, and E 3.05 (within tolerance) and I 2.66 (outside 3 +/- 0.3) on pooled fractions. Late exceeds early significantly in mice 1 and 4 for E and only mouse 1 for I (p = 0.12 E and 0.063 I in mouse 2, 0.4 I in mouse 4). The reproduced and partial bands both need the increase significant in every learning mouse.

Summary¶

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.

Claim Outcome
data-composition reproduced
fig1b-psychometric reproduced
figs1b-trial-history blocked, data missing
fig1gi-inferred-spiking-differs not reproduced
fig2a-example-session not reproduced
fig2bc-fraction-selective-similar not reproduced
fig2bd-selectivity-time-course blocked, methods underspecified
fig2de-selectivity-magnitude-similar partially reproduced
figs3d-same-spiking-selectivity reproduced
figs3c-wider-window not reproduced
figs3e-correct-error-correlation not reproduced
fig3bc-decoding-similar reproduced
fig3b-decoding-time-course not reproduced
fig3df-weights-similar partially reproduced
fig3hi-mixed-no-advantage reproduced
figs5-fluorescence-decoding blocked, data missing
figs6ab-previous-choice-stimulus blocked, other
figs6c-outcome-decoding blocked, other
figs6de-incorrect-trials not reproduced
fig4bd-stability-similar reproduced
figs7c-angle-stability blocked, too large
fig5a-nonselective-model, fig5bc-selective-models-match, figs9-signal-selective-best blocked, not reached in the run's time (simulations)
fig6a-same-selectivity-correlations reproduced
fig6bc-inhibitory-correlations-higher blocked, methods underspecified
fig7-noise-correlations-limit-decoding blocked, methods underspecified
fig8ab-learning-accuracy not reproduced
fig8ce-choice-signal-onset not reproduced
fig8de-learning-parallel not reproduced
figs13c-equal-trials not reproduced
figs12-licking-running not reproduced
fig8f-correlations-decrease partially reproduced
figs13ab-pseudo-learning not reproduced
fig8g-fraction-selective-triples not reproduced
figs2-temporal-dynamics-similar blocked, other
figs14-neuropil, figs15-labeling-specificity blocked, data missing (raw movies, histology)

How the analysis differs from the paper's: the SVM regularisation is chosen from a grid with steps of 1 in log10 (the paper 0.2; the check in 02_decoders.ipynb shows differences of at most 0.44 points); excitatory, mixed and 2n-excitatory populations use 5 subsamples (3 in the learning analysis) where the paper uses 50; the time courses use 25 splits per bin and one C per session chosen at the bin before the choice; choices are matched once per session; and side labels are "high-rate" and "low-rate" choices, as the files do not name the side. 16 Hz trials are left out everywhere, as their choice side is unknown; the trial table has no flag for helped trials or the first trials of a session, so those exclusions of the code are not applied; notebook 04 repeats the fig3b time course and the per-bin fig3df weights for mice 1, 2 and 3 with C chosen at every bin and 50 splits.

What was found about the dataset: the session counts, trials per session and neuron counts match the paper; the traces named dFoF_* hold the normalised inferred spiking activity, not Delta F/F, and no fluorescence trace is in the files; the attribute named rate of each trial series holds the frame interval; trial times are relative to each trial, so inter-trial intervals cannot be computed; the lick trace does not say which spout was licked; some files store non-integer pulse rates; and the NWB session identifiers are the CNMF run timestamps, while the recording date is in session_start_time and session_description. The trial table has no helped-trial or first-trial flag (trial_is_good equals a correct or incorrect response), and the side licked on 16 Hz trials cannot be recovered.

In [24]:
print("runtime %.1f min, peak memory %.1f GB" % ((time.time() - T0) / 60, resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1e6))
runtime 41.7 min, peak memory 6.0 GB