The International Brain Laboratory (2021) on DANDI:000045¶
Paper: The International Brain Laboratory, "Standardized and reproducible measurement of decision-making in mice", eLife 10:e63711 (2021), doi:10.7554/eLife.63711.
Dataset: DANDI:000045, "IBL behavioral data", version 0.211209.1413 (doi:10.48324/dandi.000045/0.211209.1413). The paper cites no version of the dandiset (its data statement points to data.internationalbrainlab.org, and the dandiset names the bioRxiv preprint). There are two published versions, 0.211209.1412 and 0.211209.1413, made a minute apart; they hold the same files (checked below), so the most recent is pinned.
Claims: claims/000045/10.7554-elife.63711.yaml, written from the version of record (eLife,
PMC8137147) with its Methods, figure legends and Appendix 1, and the paper's code
(github.com/int-brain-lab/paper-behavior at commit edc4531). The claims file decides what is tested
and how; this notebook does not change it.
How claims are judged. The questions this attempt asked were answered on 2026-10-22
(questions/000045.yaml), and the claims file now names a main reading and variants for basic
proficiency (P1), the first full-task session (P1b), 50:50 sessions and the classifier's subsample
size. The main reading decides each outcome; the variants are shown, and the attempt record says
where one gives a different outcome. Where a claim's criterion lists readings of its own (sessions,
filters, accuracy measures, the 50% weight of the GLM), a claim matches when it matches under any of
them, unless the criterion says otherwise. Where the expected values are not all met but
some are, or the effect holds without the reported strength, the outcome is
partially_reproduced.
| Claim | Tested here |
|---|---|
| cohort-counts | tested |
| fig2g-days-to-proficiency | tested |
| fig2g-days-differ-across-labs | tested |
| fig2s1-trials-to-proficiency | tested |
| fig2h-proportion-learned-40-days | tested |
| fig2bc-threshold-bias-iqr | tested |
| fig2-abs-bias-threshold-during-training | tested |
| fig2s2-variability-decreases | tested |
| early-sessions-predict-slow-learners | tested; blocked, the criterion's readings disagree |
| fig3c-easy-errors-basic | tested |
| fig3de-threshold-bias-basic | tested |
| fig3cde-no-lab-difference-medians | tested |
| fig3cde-no-lab-difference-variances | tested |
| fig3s2a-trial-duration | tested |
| fig3s2b-trials-per-session | tested |
| fig3f-classifier-chance-basic | tested |
| fig3f-positive-control | tested |
| fig3s3-other-classifiers | tested; the Random Forest on 50 of the 2000 subsamples, as 2000 do not fit the time limit |
| lab-link (added: the labs and their time zones) | tested |
| fig3s1a-choice-consistency-basic | tested |
| fig3s1bc-choice-consistency-full | tested |
| fig3s4-looser-criterion | tested |
| fig3s5-first-full-sessions | tested |
| fig3s5a-prior-used-from-first-sessions | tested |
| full-task-training-time | tested |
| fig4cd-biasshift-largest-at-zero | tested |
| fig4de-biasshift-no-lab-difference | tested |
| fig4f-threshold-unchanged-by-block | tested |
| fig4gh-lapses-change-with-block | tested |
| fig4i-bias-shifts-with-block | tested |
| fig4fi-no-lab-difference | tested |
| fig4j-classifier-chance-full | tested |
| fig5cf-glm-weights | tested |
| fig5dg-history-weights-higher-full | tested |
| fig5s2-glm-accuracy | tested |
| fig5s2-weights-similar-across-labs | tested |
| fig5s1b-win-stay-lose-switch | tested |
| fig5s1c-updating-by-contrast | tested |
| session-end-criteria | tested |
The notebook streams every file (three to four minutes) and runs in about twenty-seven minutes in all.
import os
for v in ("OMP_NUM_THREADS", "OPENBLAS_NUM_THREADS", "MKL_NUM_THREADS"):
os.environ.setdefault(v, "1")
import time
import warnings
import numpy as np
import pandas as pd
from scipy import stats
import ibl_behavior as ib
warnings.filterwarnings("ignore", category=RuntimeWarning)
pd.set_option("display.width", 220)
pd.set_option("display.max_columns", 40)
T0 = time.time()
print("dandiset", ib.DANDISET_ID, "version", ib.DANDISET_VERSION)
dandiset 000045 version 0.211209.1413
Loading¶
Every file of the pinned version is streamed; only the trials table, the session metadata and the rig settings are read. This takes three to four minutes.
#LOAD
meta = ib.version_metadata()
assets = ib.list_assets()
other = ib.list_assets("0.211209.1412")
print(meta["doi"], "| assets", len(assets), "| subjects (archive summary)",
meta["assetsSummary"]["numberOfSubjects"])
print("the two published versions hold the same files:",
sorted(assets.blob) == sorted(other.blob) and sorted(assets.path) == sorted(other.path))
sessions = ib.read_all(assets.asset_id.tolist())
errors = [s for s in sessions if "error" in s]
print("files read", len(sessions), "| failed", len(errors))
sessions = [s for s in sessions if "error" not in s]
S = ib.session_table(sessions)
T = ib.trials_frame(sessions)
print(f"loaded in {(time.time() - T0) / 60:.1f} min")
10.48324/dandi.000045/0.211209.1413 | assets 6615 | subjects (archive summary) 178 the two published versions hold the same files: True
files read 6615 | failed 0
loaded in 4.3 min
Data check¶
What was loaded, and each check of the description against the data.
import hashlib
print("sessions", len(S), "| with trials", (S.n_trials > 0).sum(), "| trials", len(T))
print("subjects", S.subject_id.nunique(), "| nicknames", S.nickname.nunique(),
"| subject folder = subject_id in file:", (assets.set_index("asset_id").subject_dir
.reindex(S.asset_id).to_numpy() == S.subject_id).all())
print("dates", S.date.min(), "to", S.date.max())
print("\nsessions by institution and lab number (code numbering by institution)")
print(S.groupby(["institution", "lab_number"]).agg(sessions=("session_id", "size"),
mice=("subject_id", "nunique")))
print("\nsessions by task protocol")
print(S.protocol.str.replace(r"[\d.]+$", "", regex=True).value_counts())
print("\nsessions by task as used here:", S.task.value_counts().to_dict())
print("sex of mice:", S.groupby("subject_id").sex.first().value_counts().to_dict())
# duplicated recordings: identical choices, contrasts and stimulus times
key = {}
for s in sessions:
if s.get("choice") is None or len(s["choice"]) < 20:
continue
h = hashlib.md5(np.ascontiguousarray(s["choice"]).tobytes()
+ np.ascontiguousarray(s["contrastLeft"]).tobytes()
+ np.ascontiguousarray(s["stimOn_times"]).tobytes()).hexdigest()
key.setdefault(h, []).append(s["session_id"])
dups = [v for v in key.values() if len(v) > 1]
print("\nrecordings deposited more than once:", len(dups))
for v in dups:
print(S.set_index("session_id").loc[v, ["nickname", "start", "n_trials", "protocol"]])
dup_ids = {x for v in dups for x in v}
print("excluded session of the code present:", (S.session_id == ib.EXCLUDED_SESSION).any())
sessions 6615 | with trials 6614 | trials 4260440
subjects 178 | nicknames 178 | subject folder = subject_id in file: True
dates 2019-06-11 to 2020-03-23
sessions by institution and lab number (code numbering by institution)
sessions mice
institution lab_number
Champalimaud Centre for the Unknown Lab 2 747 22
Cold Spring Harbor Laboratory Lab 3 1636 46
New York University / Center for Neural Science Lab 4 769 20
Princeton Lab 5 701 18
Sainsbury Wellcome Centre Lab 6 1470 37
University College London Lab 1 800 21
University of California Berkeley Lab 7 492 14
sessions by task protocol
protocol
_iblrig_tasks_trainingChoiceWorld 3502
_iblrig_tasks_biasedChoiceWorld 2871
_iblrig_tasks_ephysChoiceWorld 188
_iblrig_tasks_biasedChoiceWorldRPE 44
_iblrig_tasks_prestim_opto 9
_iblrig_tasks_optoFloraChW 1
Name: count, dtype: int64
sessions by task as used here: {'training': 3502, 'biased': 2871, 'ephys': 188, 'other': 54}
sex of mice: {'M': 98, 'F': 80}
recordings deposited more than once: 1
nickname start n_trials protocol
session_id
0ea61fbc-f1c2-41ab-bff3-7eef9e45ecb9 CSHL_015 2019-07-15T16:59:43+00:00 562 _iblrig_tasks_biasedChoiceWorld5.1.0
5e45deab-73d7-4b00-a196-1b394b9855d1 CSHL_013 2019-07-15T16:59:43+00:00 562 _iblrig_tasks_biasedChoiceWorld5.1.0
excluded session of the code present: False
# Trial variables: values, ranges and units, against the column descriptions
print("contrastLeft/Right values (fraction):", sorted(set(np.unique(T.contrastLeft.dropna()))
| set(np.unique(T.contrastRight.dropna()))))
print("trials with both or neither contrast set:",
int((T.contrastLeft.notna() == T.contrastRight.notna()).sum()))
print("signed contrast (%) values:", sorted(T.signed_contrast.unique()))
odd = T[T.abs_contrast.isin([4.0, 8.0])].session_id.unique()
print("sessions with 4% or 8% contrasts:", S[S.session_id.isin(odd)][["nickname", "date", "protocol"]].to_dict("records"))
print("probabilityLeft values:", T.probabilityLeft.round(3).value_counts().to_dict())
tt = T.merge(S[["session_id", "task"]], on="session_id")
tb = tt[tt.task == "training"]
print("basic-task sessions with probabilityLeft other than 0.5 on some trial: %d of %d; trials %.1f%%"
% ((tb.probabilityLeft != 0.5).groupby(tb.session_id).any().sum(), tb.session_id.nunique(),
100 * (tb.probabilityLeft != 0.5).mean()))
print("basic task, fraction of left stimuli by probabilityLeft:",
tb.groupby(tb.probabilityLeft.round(1)).contrastLeft.apply(lambda x: round(x.notna().mean(), 3)).to_dict())
del tt, tb
print("choice values:", T.choice.value_counts().to_dict(), "| feedbackType:", T.feedbackType.value_counts().to_dict())
print("no-response trials (choice 0): %.2f%%" % (100 * (T.choice == 0).mean()))
# choice convention: on trials with a stimulus on one side, which choice is rewarded
t = T[(T.choice != 0) & (T.abs_contrast > 0)]
print("\nrewarded fraction by stimulus side and choice:")
print(t.groupby([np.where(t.signed_contrast > 0, "right stim", "left stim"), "choice"]).correct.mean().round(4))
print("-> choice -1 (CCW) is the rightward choice, as coded in trials_frame")
q = T.rt.quantile([0, 0.01, 0.5, 0.99, 1]).round(3).to_dict()
print("\ntrial duration, response - stimOn (s), quantiles:", q)
print("negative trial durations:", int((T.rt < 0).sum()), "| missing stimOn:", int(T.stimOn_times.isna().sum()),
"| missing response time:", int(T.response_times.isna().sum()))
miss = T.stimOn_times.isna().groupby(T.session_id).mean()
print("sessions with some trials lacking stimOn: %d; with none: %d" % ((miss > 0).sum(), (miss == 1).sum()))
print("sessions with a negative trial duration: %d" % (T.rt < 0).groupby(T.session_id).any().sum())
print("trials per session: median", S.n_trials.median(), "range", S.n_trials.min(), "-", S.n_trials.max())
print("session duration (min, end - start): median %.1f, range %.1f - %.1f, missing end %d"
% (S.duration_min.median(), S.duration_min.min(), S.duration_min.max(), S.duration_min.isna().sum()))
# session_start_time is stated in UTC (+00:00); start hours by lab
hour = pd.to_datetime(S.start.str[:19]).dt.hour
print("\nsession_start_time offsets:", S.start.str[19:].value_counts().to_dict())
print("start hour by lab (5th, 50th, 95th percentile):")
print(S.assign(hour=hour).groupby("lab_number").hour.quantile([0.05, 0.5, 0.95]).unstack())
contrastLeft/Right values (fraction): [np.float64(0.0), np.float64(0.04), np.float64(0.0625), np.float64(0.08), np.float64(0.125), np.float64(0.25), np.float64(0.5), np.float64(1.0)]
trials with both or neither contrast set: 0
signed contrast (%) values: [np.float64(-100.0), np.float64(-50.0), np.float64(-25.0), np.float64(-12.5), np.float64(-8.0), np.float64(-6.25), np.float64(-4.0), np.float64(0.0), np.float64(4.0), np.float64(6.25), np.float64(8.0), np.float64(12.5), np.float64(25.0), np.float64(50.0), np.float64(100.0)]
sessions with 4% or 8% contrasts: [{'nickname': 'ZM_1367', 'date': '2019-06-11', 'protocol': '_iblrig_tasks_biasedChoiceWorld'}]
probabilityLeft values: {0.5: 1786985, 0.2: 1047060, 0.8: 1046256, 0.4: 54619, 0.3: 53519, 0.6: 52878, 0.7: 51624, 0.0: 44494, 0.1: 44077, 0.9: 40859, 1.0: 38069}
basic-task sessions with probabilityLeft other than 0.5 on some trial: 3502 of 3502; trials 24.1%
basic task, fraction of left stimuli by probabilityLeft: {0.0: 0.158, 0.1: 0.214, 0.2: 0.272, 0.3: 0.341, 0.4: 0.42, 0.5: 0.499, 0.6: 0.578, 0.7: 0.654, 0.8: 0.723, 0.9: 0.789, 1.0: 0.841}
choice values: {1: 2136791, -1: 2104784, 0: 18865} | feedbackType: {1: 3082820, -1: 1177620}
no-response trials (choice 0): 0.44%
rewarded fraction by stimulus side and choice:
choice
left stim -1 0.0
1 1.0
right stim -1 1.0
1 0.0
Name: correct, dtype: float64
-> choice -1 (CCW) is the rightward choice, as coded in trials_frame
trial duration, response - stimOn (s), quantiles: {0.0: -5637.64, 0.01: 0.116, 0.5: 0.423, 0.99: 23.219, 1.0: 60.778}
negative trial durations: 1541 | missing stimOn: 257021 | missing response time: 2925
sessions with some trials lacking stimOn: 2858; with none: 185
sessions with a negative trial duration: 220
trials per session: median 628.0 range 0 - 1594
session duration (min, end - start): median 60.0, range 2.7 - 157.4, missing end 6
session_start_time offsets: {'+00:00': 6615}
start hour by lab (5th, 50th, 95th percentile):
0.05 0.50 0.95 lab_number Lab 1 9.0 11.0 16.0 Lab 2 10.0 14.0 17.0 Lab 3 9.0 12.0 18.0 Lab 4 9.0 11.0 15.0 Lab 5 9.0 11.0 17.0 Lab 6 9.0 13.0 15.0 Lab 7 9.0 11.0 14.0
# Session-end status in the rig settings: SUBJECT_DISENGAGED_TRIGGERED and _TRIALNUM
print("end status (SUBJECT_DISENGAGED_TRIGGERED):", S.disengaged.astype(str).value_counts().to_dict())
x = S[S.disengaged_trial.notna()]
print("sessions with a trigger trial:", len(x), "| trigger trial after the last trial:",
int((x.disengaged_trial > x.n_trials).sum()))
# Wheel series: data and timestamps should have the same length
wm = S[S.wheel_n.notna() & (S.wheel_n != S.wheel_ts_n)]
print("files without a wheel series:", int(S.wheel_n.isna().sum()), "| wheel data and timestamps of different length:",
len(wm), "files;", wm.lab_number.value_counts().sort_index().to_dict())
# Clock check: wheel position against the trial table, in 16 sessions drawn at random.
# The wheel displacement from stimulus onset to response should follow the choice when
# the trial times are taken as they are, and not when they are shifted by 30 s.
rng_check = np.random.default_rng(1)
pick = S[(S.n_trials > 300)].sample(16, random_state=1)
res = ib.wheel_many(pick.asset_id.tolist(), [0.0, 30.0, -30.0])
rows = []
for (sid, nick, lab), (disp, ch) in zip(pick[["session_id", "nickname", "lab_number"]].to_numpy(), res):
if disp is None:
rows.append(dict(session=sid[:8], mouse=nick, lab=lab, ok=False, reason=ch))
continue
m = ch != 0
r = {f"agree_{int(s):+d}s": np.nanmean(np.sign(disp[s][m]) == -ch[m]) for s in disp}
rows.append(dict(session=sid[:8], mouse=nick, lab=lab, ok=True, **r))
wheel_check = pd.DataFrame(rows)
print(wheel_check.round(3).to_string())
print("agreement is the fraction of trials whose wheel displacement has the sign of -choice; 0 means the opposite sign")
print("median agreement, true times %.3f; shifted +30 s %.3f; -30 s %.3f"
% tuple(wheel_check[c].median() for c in ["agree_+0s", "agree_+30s", "agree_-30s"]))
end status (SUBJECT_DISENGAGED_TRIGGERED): {'2': 3330, '1': 1522, 'False': 727, '3': 550, 'None': 486}
sessions with a trigger trial: 5402 | trigger trial after the last trial: 16
files without a wheel series: 16 | wheel data and timestamps of different length: 807 files; {'Lab 1': 307, 'Lab 2': 5, 'Lab 3': 2, 'Lab 4': 123, 'Lab 5': 120, 'Lab 6': 250}
session mouse lab ok agree_+0s agree_+30s agree_-30s reason 0 e3367b7c ibl_witten_20 Lab 5 True 0.996 0.452 0.431 NaN 1 a69af56b KS018 Lab 1 False NaN NaN NaN wheel data 181623 samples, timestamps 340799 2 4af6c7a3 SWC_029 Lab 6 True 0.984 0.771 0.742 NaN 3 5b3decf1 CSH_ZAD_007 Lab 3 True 1.000 0.423 0.426 NaN 4 92c93923 DY_012 Lab 7 True 0.998 0.502 0.460 NaN 5 d9da32e7 ibl_witten_14 Lab 5 True 0.998 0.506 0.510 NaN 6 4a810266 CSH_ZAD_023 Lab 3 True 1.000 0.445 0.467 NaN 7 e19dadc9 NYU-02 Lab 4 True 1.000 0.518 0.486 NaN 8 6b5e3738 ibl_witten_13 Lab 5 True 1.000 0.545 0.561 NaN 9 343b6a92 ibl_witten_12 Lab 5 True 1.000 0.539 0.514 NaN 10 0fcf6c04 CSHL055 Lab 3 True 0.999 0.493 0.507 NaN 11 a3d9d5ce ibl_witten_06 Lab 5 True 1.000 0.451 0.426 NaN 12 78fef9d2 CSH_ZAD_004 Lab 3 True 1.000 0.473 0.428 NaN 13 7e2c31e4 CSHL047 Lab 3 True 0.999 0.624 0.621 NaN 14 fa8c9e16 ibl_witten_07 Lab 5 True 0.000 0.363 0.337 NaN 15 c54701cb KS016 Lab 1 False NaN NaN NaN wheel data 290254 samples, timestamps 497932 agreement is the fraction of trials whose wheel displacement has the sign of -choice; 0 means the opposite sign median agreement, true times 0.999; shifted +30 s 0.497; -30 s 0.477
Selection and proficiency¶
The paper's mice are those of project ibl_neuropixel_brainwide_01 (claims file header). The
dataset begins on 2019-06-11, while the paper's mice began training in January 2019 (Methods), so
only mice whose first session in the dataset is a first-stage session (50% and 100% contrasts
only) have their whole training in the dataset; the training-time claims need that. The files
carry no training status, so basic (P1) and full (P2) task proficiency are recomputed from the
trials with the criteria of Appendix 1, table 1d, as the claims file header gives them (answers
of 2026-10-22). P1 follows the pipeline's SessionTrainingStatus: at each session, that session and
the two before it (any protocol); trials completed are all trials, no-response trials included;
percent correct is over contrasts of 50% or more; the 1b criteria are tested and then the 1a
criteria, at any date. The main reading requires "all contrasts introduced" (100, 25, 12.5, 6.25
and 0%) in each of the three sessions. Variants: the pipeline's check of the current session only
(0% and a contrast between 0.1 and 6.5%), and 1b replacing 1a from 2019-09-12. P2 is computed as
before, over three consecutive full-task training days.
S = S[~S.session_id.isin(dup_ids) & (S.n_trials > 0)].copy()
T = T[T.session_id.isin(S.session_id)].copy()
mice = ib.project_mice(S)
lab = S.groupby("subject_id").lab_number.first()
nick = S.groupby("subject_id").nickname.first()
print("mice in the dataset", S.subject_id.nunique(), "| of the project", len(mice))
print("not in the project:", list(nick[~nick.index.isin(mice)]))
Dall = ib.daily(T, S)
first = Dall.groupby("subject_id").head(1).set_index("subject_id")
first_stage = first.contrasts.apply(lambda c: c == frozenset([50.0, 100.0]))
complete = first_stage[first_stage].index.intersection(mice)
print("project mice whose first session is a first-stage session:", len(complete),
"| others:", len(mice) - len(complete))
print("first session of the others: task", S[S.subject_id.isin(mice.difference(complete))]
.sort_values("start").groupby("subject_id").task.first().value_counts().to_dict(),
"| date", S[S.subject_id.isin(mice.difference(complete))].groupby("subject_id").date.min()
.value_counts().head(3).to_dict())
print("complete-history mice by lab:", lab[complete].value_counts().sort_index().to_dict())
# A mouse that began its first stage before the dataset's first date would also pass this test:
# the first-session dates of the whole-training mice
fd = pd.to_datetime(S[S.subject_id.isin(complete)].groupby("subject_id").date.min())
d0 = pd.to_datetime(S.date.min())
early_start = fd.index[(fd - d0).dt.days < 7]
print(f"whole-training mice whose first session is on the dataset's first date ({d0.date()}): {int((fd == d0).sum())}"
f" | within its first 7 days: {len(early_start)} | first session by month:",
fd.dt.strftime("%Y-%m").value_counts().sort_index().to_dict())
Sc = S[S.subject_id.isin(complete)]
Tc = T[T.session_id.isin(Sc.session_id)]
Dc = Dall[Dall.subject_id.isin(complete)]
Dfull = ib.daily(Tc, Sc, ["biased"])
Tm = ib.trials_with_days(Tc, Sc, Dc)
print("days with more than one session:", int((Sc.groupby(["subject_id", "date"]).size() > 1).sum()))
mice in the dataset 178 | of the project 177 not in the project: ['SWC_029']
project mice whose first session is a first-stage session: 136 | others: 41
first session of the others: task {'biased': 31, 'training': 10} | date {'2019-06-11': 32, '2019-07-01': 4, '2019-11-21': 1}
complete-history mice by lab: {'Lab 1': 18, 'Lab 2': 14, 'Lab 3': 39, 'Lab 4': 11, 'Lab 5': 14, 'Lab 6': 33, 'Lab 7': 7}
whole-training mice whose first session is on the dataset's first date (2019-06-11): 5 | within its first 7 days: 6 | first session by month: {'2019-06': 12, '2019-07': 4, '2019-08': 30, '2019-09': 8, '2019-10': 9, '2019-11': 18, '2020-01': 16, '2020-02': 27, '2020-03': 12}
days with more than one session: 73
# P1 readings (claims file header, answers of 2026-10-22). Main: a mouse is proficient at the first
# session meeting the 1a or the 1b criteria, at any date, with "all contrasts introduced" in each of
# the three sessions. Variants: the pipeline's contrast check on the current session only ("last"),
# and 1b replacing 1a from 2019-09-12 ("1b-replace").
READINGS = [("either", "each"), ("either", "last"), ("replace", "each"), ("replace", "last")]
MAIN = READINGS[0]
RN = {MAIN: "main", ("either", "last"): "contrasts:last", ("replace", "each"): "1b-replace",
("replace", "last"): "1b-replace,contrasts:last"}
SS = ib.session_summary(Tc, Sc)
tday = Dc.set_index(["subject_id", "date"]).tday0
def p1_frame(st):
st = st[st.p1_session.notna()].copy()
st["p1_tday0"] = [int(tday[(s, d)]) for s, d in zip(st.index, st.p1_date)]
return st
STATUS = {r: ib.training_status(SS, Tc, r[1], ib.DATE_1B if r[0] == "replace" else None) for r in READINGS}
P1 = {r: p1_frame(STATUS[r]) for r in READINGS}
P2 = ib.full_proficiency(Dfull, Tc, Sc)
print("sessions of the whole-training mice:", len(SS), "| three-session windows fitted:", len(ib._WINDOW_FITS))
print("sessions with no trial at 50% or more:", int(SS.perf_easy.isna().sum()))
first_biased = Dc[Dc.tasks.apply(lambda t: "biased" in t)].groupby("subject_id").tday0.min()
rows = []
for r in READINGS:
p = P1[r].p1_tday0
gap = (first_biased - p).dropna()
rows.append(dict(reading=RN[r], P1=len(p), **{f"P1 {l}": int((lab[p.index] == l).sum()) for l in ib.LABS},
P1_status_1a=int((P1[r].p1_status == "1a").sum()), P1_status_1b=int((P1[r].p1_status == "1b").sum()),
reach_1b=int(P1[r].b1_session.notna().sum()),
P1_protocol_basic=int(P1[r].p1_session.map(Sc.set_index("session_id").task).eq("training").sum()),
first_full_day_minus_P1_median=gap.median(),
within_1_to_3_days=f"{int(gap.between(1, 3).sum())}/{len(gap)}",
full_task_without_P1=int(len(first_biased.index.difference(p.index)))))
prof = pd.DataFrame(rows).set_index("reading")
print(prof.T.to_string())
print("\nP2 (full task proficiency):", len(P2), "mice;", lab[P2.index].value_counts().sort_index().to_dict())
print("P2 mice without P1 under each reading:", {RN[r]: len(P2.index.difference(P1[r].index)) for r in READINGS})
# Sensitivity that decides nothing: percent correct on 100% contrast only, the wording of Appendix 1, table 1d
alt = p1_frame(ib.training_status(SS, Tc, "each", None, perf="100"))
j = P1[MAIN][["p1_tday0"]].join(alt[["p1_tday0"]], rsuffix="_100", how="outer")
print(f"main reading with percent correct on 100% contrast: {len(alt)} mice reach P1 (against {len(P1[MAIN])}); "
f"P1 differs for {int((j.p1_tday0 != j.p1_tday0_100).sum())} mice")
sessions of the whole-training mice: 5347 | three-session windows fitted: 1679
sessions with no trial at 50% or more: 1
reading main contrasts:last 1b-replace 1b-replace,contrasts:last
P1 83 85 70 71
P1 Lab 1 12 12 11 11
P1 Lab 2 12 13 8 8
P1 Lab 3 26 26 25 25
P1 Lab 4 7 7 6 7
P1 Lab 5 8 8 7 7
P1 Lab 6 12 13 8 8
P1 Lab 7 6 6 5 5
P1_status_1a 61 74 19 20
P1_status_1b 22 11 51 51
reach_1b 67 67 65 65
P1_protocol_basic 77 84 56 61
first_full_day_minus_P1_median 3.0 4.0 2.0 2.0
within_1_to_3_days 31/73 30/74 41/69 43/70
full_task_without_P1 4 3 8 7
P2 (full task proficiency): 60 mice; {'Lab 1': 9, 'Lab 2': 7, 'Lab 3': 21, 'Lab 4': 5, 'Lab 5': 7, 'Lab 6': 6, 'Lab 7': 5}
P2 mice without P1 under each reading: {'main': 0, 'contrasts:last': 0, '1b-replace': 0, '1b-replace,contrasts:last': 0}
main reading with percent correct on 100% contrast: 84 mice reach P1 (against 83); P1 differs for 2 mice
cohort-counts¶
Of 206 mice that started training, 140 reached proficiency in the basic task and 98 in the full task.
Counts of distinct mice under the paper's selection; proficiency as P1 (four readings) and P2.
print("project mice in the dataset:", len(mice), "| with their whole training in the dataset:", len(complete))
print("P1 by reading:", {RN[r]: len(P1[r]) for r in READINGS})
print("P2:", len(P2))
exp = [(206, 20.6), (140, 14), (98, 9.8)]
for name, n in [("started training, whole training in the dataset", len(complete)),
("project mice with any session", len(mice))]:
print(f"{name}: {n}, within 206 +- 20.6: {abs(n - 206) <= 20.6}")
for r in READINGS:
print(f"P1 {RN[r]}: {len(P1[r])}, within 140 +- 14: {abs(len(P1[r]) - 140) <= 14}")
print(f"P2: {len(P2)}, within 98 +- 9.8: {abs(len(P2) - 98) <= 9.8}")
# Missing stimulus onset times leave the median reaction time at 0% undefined, which fails the
# 1b and P2 criterion of < 2 s. The windows evaluated that fail only for that (none would change a count)
# and, where there are any, the counts if they passed.
for r in READINGS:
n_nan = STATUS[r].attrs["rt_nan_windows"]
msg = ""
if n_nan:
p1n = p1_frame(ib.training_status(SS, Tc, r[1], ib.DATE_1B if r[0] == "replace" else None, nan_rt_passes=True))
msg = f" | if they passed: P1 {len(p1n)}, 1b reached by {int(p1n.b1_session.notna().sum())}"
print(f"{RN[r]}: windows meeting every 1b criterion but an undefined reaction time: {n_nan}{msg}")
n_nan = P2.attrs["rt_nan_windows"]
msg = f" | if they passed: P2 {len(ib.full_proficiency(Dfull, Tc, Sc, nan_rt_passes=True))}" if n_nan else ""
print(f"P2: windows meeting every criterion but an undefined reaction time: {n_nan}{msg}")
# P2 slides over full-task days, not sessions; the two differ only where a day holds more than one full-task session
multi = Sc[Sc.task == "biased"].groupby(["subject_id", "date"]).size()
multi = multi[multi > 1]
upto = Dfull.subject_id.map(P2.p2_tday0).fillna(np.inf)
dm = Dfull[Dfull.tday0 <= upto].set_index(["subject_id", "date"])
hit = dm.index.intersection(multi.index)
print(f"full-task days with more than one full-task session: {len(multi)}; at or before a mouse's P2 day (or any day for"
f" mice without P2): {len(hit)}, in {hit.get_level_values(0).nunique()} mice")
project mice in the dataset: 177 | with their whole training in the dataset: 136
P1 by reading: {'main': 83, 'contrasts:last': 85, '1b-replace': 70, '1b-replace,contrasts:last': 71}
P2: 60
started training, whole training in the dataset: 136, within 206 +- 20.6: False
project mice with any session: 177, within 206 +- 20.6: False
P1 main: 83, within 140 +- 14: False
P1 contrasts:last: 85, within 140 +- 14: False
P1 1b-replace: 70, within 140 +- 14: False
P1 1b-replace,contrasts:last: 71, within 140 +- 14: False
P2: 60, within 98 +- 9.8: False
main: windows meeting every 1b criterion but an undefined reaction time: 0
contrasts:last: windows meeting every 1b criterion but an undefined reaction time: 0
1b-replace: windows meeting every 1b criterion but an undefined reaction time: 0
1b-replace,contrasts:last: windows meeting every 1b criterion but an undefined reaction time: 0
P2: windows meeting every criterion but an undefined reaction time: 0
full-task days with more than one full-task session: 20; at or before a mouse's P2 day (or any day for mice without P2): 10, in 7 mice
Result: not reproduced. The dataset holds 177 mice of the paper's project, and 136 of them have their whole training in it, against 206 that started training. Under the main reading 83 of these reach basic task proficiency (85, 70 and 71 under the variants), against 140, and 60 reach full task proficiency, against 98. No count is within tolerance under any reading. The dataset holds only sessions from 2019-06-11 on, while training began in January 2019. No three-session window fails the 1b or the P2 criteria only because missing stimulus onsets leave its reaction time undefined (0 windows under every reading), so the missing onsets do not lower these counts. P2 slides over full-task days; 10 days with more than one full-task session fall at or before a mouse's P2 day (or on any day of a mouse without P2), in 7 mice, so a count over sessions could differ for at most 7 mice.
fig2g-days-to-proficiency¶
Basic task training took 18.4 +- 13.0 days (s.d., n = 140 mice), from 3 days for the fastest mouse to 59 days for the slowest.
Training days up to P1, counting the P1 day (code query branch) or not (CSV branch).
def check(vals, exp):
return all(abs(v - e) <= tol for v, (e, tol) in zip(vals, exp))
EXP_DAYS = [(18.4, 1.84), (13.0, 1.3), (3, 0.3), (59, 5.9)]
rows = []
days = {}
for r in READINGS:
for cnt in ("incl", "excl"):
d = P1[r].p1_tday0 + (1 if cnt == "incl" else 0)
days[(r, cnt)] = d
v = [d.mean(), d.std(), d.min(), d.max()]
rows.append(dict(reading=RN[r], count=cnt, n=len(d), mean=v[0], sd=v[1], min=v[2], max=v[3],
n_in_tol=sum(abs(x - e) <= t for x, (e, t) in zip(v, EXP_DAYS)),
all_in_tol=check(v, EXP_DAYS)))
fig2g = pd.DataFrame(rows)
print(fig2g.round(2).to_string())
# Variant: leaving out the mice whose first session falls in the dataset's first 7 days (they may have begun earlier)
for cnt in ("incl", "excl"):
d = days[(MAIN, cnt)]
d = d[~d.index.isin(early_start)]
v = [d.mean(), d.std(), d.min(), d.max()]
print(f"main, {cnt}, without the {int(days[(MAIN, cnt)].index.isin(early_start).sum())} mice starting in the first week:"
f" n {len(d)}, mean {v[0]:.2f}, s.d. {v[1]:.2f}, min {v[2]}, max {v[3]},"
f" in tolerance {sum(abs(x - e) <= t for x, (e, t) in zip(v, EXP_DAYS))} of 4")
d = days[(MAIN, "incl")]
print("fastest mice (main, incl):", d.nsmallest(5).to_dict(), "| their first session:",
fd.reindex(d.nsmallest(5).index).dt.strftime("%Y-%m-%d").to_dict())
d = days[(READINGS[0], "incl")]
print("\nby lab (main, incl):")
print(d.groupby(lab[d.index]).describe()[["count", "mean", "50%", "min", "max"]].round(1))
reading count n mean sd min max n_in_tol all_in_tol
0 main incl 83 19.87 11.39 5 58 2 False
1 main excl 83 18.87 11.39 4 57 2 False
2 contrasts:last incl 85 18.73 10.91 4 54 2 False
3 contrasts:last excl 85 17.73 10.91 3 53 2 False
4 1b-replace incl 70 23.16 13.94 5 58 2 False
5 1b-replace excl 70 22.16 13.94 4 57 2 False
6 1b-replace,contrasts:last incl 71 23.17 14.42 4 58 1 False
7 1b-replace,contrasts:last excl 71 22.17 14.42 3 57 2 False
main, incl, without the 2 mice starting in the first week: n 81, mean 19.40, s.d. 10.98, min 5, max 58, in tolerance 2 of 4
main, excl, without the 2 mice starting in the first week: n 81, mean 18.40, s.d. 10.98, min 4, max 57, in tolerance 2 of 4
fastest mice (main, incl): {'0932d382-3fd4-4688-88d1-a0156cadd488': 5, '0fbb1324-1ac7-445a-8831-8fc2225338ca': 5, '9a46fcfa-81cf-4742-87c0-bb95f90d5913': 6, 'c6e8125f-b6c7-4349-b74d-32e8bd606f63': 6, 'fdfa9a26-75fd-49c4-a4ed-1768cfd861ca': 6} | their first session: {'0932d382-3fd4-4688-88d1-a0156cadd488': '2019-08-19', '0fbb1324-1ac7-445a-8831-8fc2225338ca': '2019-08-19', '9a46fcfa-81cf-4742-87c0-bb95f90d5913': '2019-08-06', 'c6e8125f-b6c7-4349-b74d-32e8bd606f63': '2019-10-01', 'fdfa9a26-75fd-49c4-a4ed-1768cfd861ca': '2019-11-21'}
by lab (main, incl):
count mean 50% min max
lab_number
Lab 1 12.0 18.4 19.0 6.0 38.0
Lab 2 12.0 16.4 13.5 9.0 34.0
Lab 3 26.0 20.9 17.0 5.0 58.0
Lab 4 7.0 25.3 19.0 11.0 50.0
Lab 5 8.0 13.4 11.5 7.0 23.0
Lab 6 12.0 26.4 24.5 12.0 54.0
Lab 7 6.0 14.3 13.0 6.0 31.0
Result: partially reproduced. Under the main reading (83 mice) the mean is 19.87 days counting the P1 day and 18.87 without, both within 18.4 +- 1.84, and the slowest mouse takes 58 and 57 days, within 59 +- 5.9. The s.d. is 11.39 days, against 13.0 +- 1.3, and the fastest mouse takes 5 or 4 days, against 3 +- 0.3: two of the four values are within tolerance. The variants give means of 17.73 to 23.17 days, s.d.s of 10.91 to 14.42, and at most two values within tolerance. Only 6 of the 136 whole-training mice have their first session in the dataset's first 7 days, where an earlier start would go unseen; leaving out the 2 of them that reach P1 gives a mean of 19.40 days (s.d. 10.98, fastest 5, slowest 58), again two of four within tolerance. The five fastest mice start between 2019-08-06 and 2019-11-21, so the fastest mouse's 5 days is not cut short by the start of the dataset.
fig2g-days-differ-across-labs¶
The number of days to basic task proficiency differed across laboratories; within-lab interquartile ranges ranged from 8 days (Lab 2) to 22 days (Lab 6).
rows = []
for (r, cnt), d in days.items():
l = lab[d.index]
iqr = d.groupby(l).quantile(0.75) - d.groupby(l).quantile(0.25)
p_kw = ib.lab_test(d, l, "kruskal")
p_code = ib.lab_test(d, l, "code")
rows.append(dict(reading=RN[r], count=cnt, n=len(d), p_kruskal=p_kw, p_code_switch=p_code,
iqr_lab2=iqr.get("Lab 2"), iqr_lab6=iqr.get("Lab 6"),
iqr_range=f"{iqr.min():.1f}-{iqr.max():.1f}",
p_below_0001=p_kw < 0.001,
iqr_in_tol=abs(iqr.get("Lab 2", np.nan) - 8) <= 0.8 and abs(iqr.get("Lab 6", np.nan) - 22) <= 2.2))
print(pd.DataFrame(rows).to_string(float_format=lambda x: f"{x:.4g}"))
print("mice per lab (main):", lab[days[(READINGS[0], 'incl')].index].value_counts().sort_index().to_dict())
reading count n p_kruskal p_code_switch iqr_lab2 iqr_lab6 iqr_range p_below_0001 iqr_in_tol
0 main incl 83 0.02906 0.02906 7.75 5.75 5.8-12.5 False False
1 main excl 83 0.02906 0.02906 7.75 5.75 5.8-12.5 False False
2 contrasts:last incl 85 0.02338 0.02338 8 5 5.0-14.0 False False
3 contrasts:last excl 85 0.02338 0.02338 8 5 5.0-14.0 False False
4 1b-replace incl 70 0.08847 0.08847 6 10 5.0-46.0 False False
5 1b-replace excl 70 0.08847 0.08847 6 10 5.0-46.0 False False
6 1b-replace,contrasts:last incl 71 0.0484 0.0484 6 10 5.0-46.0 False False
7 1b-replace,contrasts:last excl 71 0.0484 0.0484 6 10 5.0-46.0 False False
mice per lab (main): {'Lab 1': 12, 'Lab 2': 12, 'Lab 3': 26, 'Lab 4': 7, 'Lab 5': 8, 'Lab 6': 12, 'Lab 7': 6}
Result: partially reproduced. Under the main reading the Kruskal-Wallis p across labs is 0.029: the labs differ at p < 0.05 but not at the paper's p < 0.001, which the criterion requires (0.023 to 0.088 under the variants). The Lab 2 interquartile range is 7.75 days, within 8 +- 0.8, and the Lab 6 range 5.75 days, against 22 +- 2.2; the within-lab ranges run from 5.8 to 12.5 days. The difference across labs is present but weaker, and one of the two ranges matches.
fig2s1-trials-to-proficiency¶
Measured in trials, basic task training took 10.8 +- 8.6 thousand trials (s.d., n = 140), from one thousand for the fastest mouse to 43 thousand for the slowest; reaching 80% correct on easy trials took on average about 7.4 thousand trials.
EXP_TR = [(10800, 1080), (8600, 860), (1000, 100), (43000, 4300)]
rows = []
for (r, cnt), d in days.items():
dd = Dc[Dc.subject_id.isin(d.index)]
lim = dd.subject_id.map(d)
# days counted: tday0 < days (excl) or <= p1 day (incl); d is the count, so tday0 < d
tr = dd[dd.tday0 < lim].groupby("subject_id").n_trials.sum()
v = [tr.mean(), tr.std(), tr.min(), tr.max()]
rows.append(dict(reading=RN[r], count=cnt, n=len(tr), mean=v[0], sd=v[1], min=v[2], max=v[3],
n_in_tol=sum(abs(x - e) <= t for x, (e, t) in zip(v, EXP_TR)), all_in_tol=check(v, EXP_TR)))
print(pd.DataFrame(rows).round(0).to_string())
def trials_to_80(mice_idx, variant=False):
dd = Dc[Dc.subject_id.isin(mice_idx) & (Dc.n_trials > 100)].sort_values(["subject_id", "tday0"]).copy()
dd["perf_f"] = dd.groupby("subject_id").perf_easy.transform(
lambda x: x.rolling(3, center=True, min_periods=1).median())
dd["day"] = dd.groupby("subject_id").cumcount()
dd["cum"] = dd.groupby("subject_id").n_trials.cumsum()
if variant:
f = dd[dd.perf_f > 80].groupby("subject_id").cum.first()
return f.mean(), len(f)
g = dd.groupby("day").agg(perf=("perf_f", "mean"), cum=("cum", "mean"), n=("subject_id", "size"))
hit = g[g.perf > 80]
return (hit.cum.min() if len(hit) else np.nan), int(hit.index.min()) if len(hit) else None
for r in READINGS:
v, day = trials_to_80(P1[r].index)
vv, nn = trials_to_80(P1[r].index, variant=True)
print(f"{RN[r]}: trials to a mean of 80% on easy trials {v:.0f} (first at training day {day}); "
f"within 7400 +- 740: {abs(v - 7400) <= 740} | variant, mean of each mouse's first: {vv:.0f} (n={nn})")
reading count n mean sd min max n_in_tol all_in_tol 0 main incl 83 11839.0 7515.0 2357 34998 1 False 1 main excl 83 11104.0 7472.0 1687 34265 1 False 2 contrasts:last incl 85 11019.0 7260.0 1687 32999 1 False 3 contrasts:last excl 85 10304.0 7192.0 1195 32235 1 False 4 1b-replace incl 70 14199.0 8429.0 2438 34998 1 False 5 1b-replace excl 70 13422.0 8371.0 1687 34265 1 False 6 1b-replace,contrasts:last incl 71 14125.0 8715.0 1687 34998 1 False 7 1b-replace,contrasts:last excl 71 13377.0 8630.0 1195 34265 1 False main: trials to a mean of 80% on easy trials 7329 (first at training day 12); within 7400 +- 740: True | variant, mean of each mouse's first: 6465 (n=83) contrasts:last: trials to a mean of 80% on easy trials 7306 (first at training day 12); within 7400 +- 740: True | variant, mean of each mouse's first: 6443 (n=85) 1b-replace: trials to a mean of 80% on easy trials 6659 (first at training day 11); within 7400 +- 740: False | variant, mean of each mouse's first: 5856 (n=70) 1b-replace,contrasts:last: trials to a mean of 80% on easy trials 6689 (first at training day 11); within 7400 +- 740: True | variant, mean of each mouse's first: 6019 (n=71)
Result: partially reproduced. Under the main reading the mean number of trials to P1 is 11,839 counting the P1 day and 11,104 without, within 10,800 +- 1,080. The s.d. (7,515 and 7,472), the fastest mouse (2,357 and 1,687 trials) and the slowest (34,998 and 34,265) are outside tolerance. The trial count at which the mean easy-trial performance first exceeds 80% is 7,329, within 7,400 +- 740 (6,659 to 7,306 under the variants).
fig2h-proportion-learned-40-days¶
About 80% of mice that started training would learn the basic task within the 40 days usually allotted (Kaplan-Meier estimate over all 206 mice).
from lifelines import KaplanMeierFitter
total_days = Dc.groupby("subject_id").tday0.max() + 1
last_date = Dc.groupby("subject_id").date.max()
rows = []
for r in READINGS:
for cnt in ("incl", "excl"):
for variant in ("main", "drop_in_training"):
idx = complete
p = days[(r, cnt)]
# censored at the mouse's last training day, counted the same way as the events
cens = total_days.reindex(idx) - (0 if cnt == "incl" else 1)
dur = pd.Series(np.where(idx.isin(p.index), p.reindex(idx), cens), index=idx)
ev = pd.Series(idx.isin(p.index), index=idx)
if variant == "drop_in_training":
# still in training at the cutoff: no P1 and a session in the last 7 days before it
still = (~ev) & (last_date.reindex(idx) >= "2020-03-16")
dur, ev = dur[~still], ev[~still]
km = KaplanMeierFitter().fit(dur, ev)
at40 = 1 - km.predict(40)
atlast = 1 - km.predict(dur.max())
rows.append(dict(reading=RN[r], count=cnt, variant=variant, n=len(dur), events=int(ev.sum()),
p40=at40, p_last=atlast, last_day=dur.max(),
ok=abs(at40 - 0.8) <= 0.08 and atlast > at40))
print(pd.DataFrame(rows).round(3).to_string())
reading count variant n events p40 p_last last_day ok 0 main incl main 136 83 0.749 1.000 58.0 True 1 main incl drop_in_training 112 83 0.815 1.000 58.0 True 2 main excl main 136 83 0.749 1.000 57.0 True 3 main excl drop_in_training 112 83 0.815 1.000 57.0 True 4 contrasts:last incl main 136 85 0.768 1.000 54.0 True 5 contrasts:last incl drop_in_training 113 85 0.833 1.000 54.0 True 6 contrasts:last excl main 136 85 0.768 1.000 53.0 True 7 contrasts:last excl drop_in_training 113 85 0.833 1.000 53.0 True 8 1b-replace incl main 136 70 0.602 0.883 84.0 False 9 1b-replace incl drop_in_training 107 70 0.681 0.934 84.0 False 10 1b-replace excl main 136 70 0.602 0.883 83.0 False 11 1b-replace excl drop_in_training 107 70 0.681 0.934 83.0 False 12 1b-replace,contrasts:last incl main 136 71 0.600 0.892 84.0 False 13 1b-replace,contrasts:last incl drop_in_training 107 71 0.680 0.941 84.0 False 14 1b-replace,contrasts:last excl main 136 71 0.600 0.892 83.0 False 15 1b-replace,contrasts:last excl drop_in_training 107 71 0.680 0.941 83.0 False
Result: reproduced. Under the main reading ("all contrasts introduced" in each of the three sessions), over the 136 mice that started training, mice without P1 censored, the Kaplan-Meier proportion at day 40 is 0.749 with the days counted either way (mice without P1 censored at their last training day, counted the same way), within 0.8 +- 0.08, and 1.000 at the last day. The pipeline's contrast check, a variant, gives 0.768. With 1b replacing 1a from 2019-09-12 the proportion is 0.600 to 0.602, outside tolerance. The code's variant, leaving out mice still in training at the cutoff (taken as a session in the dataset's last 7 days), gives 0.815 under the main reading.
fig2bc-threshold-bias-iqr¶
Contrast threshold and bias varied little during training; the threshold interquartile range slightly decreased from 12-29% in the first 10 training days to 11-23% thereafter, and the bias interquartile range went from -5.2 to 7.1% to -5.6 to 6.5%.
Per training day (all sessions of the day pooled), 50:50 days with more than 100 trials and six or more signed contrasts are fitted. Training day counted from 0 at the mouse's first session. 50:50 sessions are the basic-task sessions with all their trials, repeat trials included (claims file header, answer of 2026-10-22), so 50:50 days are days with basic-task sessions only.
keep = Dc[(Dc.n_trials > 100) & Dc.basic_only & (Dc.n_signed >= 6)]
tk = Tm.merge(keep[["subject_id", "date"]], on=["subject_id", "date"])
day_fits = ib.mouse_fits(tk, by=("subject_id", "tday0")).reset_index()
day_fits = day_fits.sort_values(["subject_id", "tday0"])
for v in ("threshold", "bias"):
day_fits[v + "_f"] = day_fits.groupby("subject_id")[v].transform(
lambda x: x.rolling(3, center=True, min_periods=1).median())
print("day fits:", len(day_fits), "of", len(keep), "days;", day_fits.threshold.isna().sum(), "without a fit")
print("threshold range %.1f-%.1f, bias range %.1f-%.1f" % (day_fits.threshold.min(), day_fits.threshold.max(),
day_fits.bias.min(), day_fits.bias.max()))
EXP_BC = [(12, 1.2), (29, 2.9), (11, 1.1), (23, 2.3), (-5.2, 0.52), (7.1, 0.71), (-5.6, 0.56), (6.5, 0.65)]
rows = []
for r in READINGS:
f = day_fits[day_fits.subject_id.isin(P1[r].index)]
for filt in ("filtered", "unfiltered"):
sfx = "_f" if filt == "filtered" else ""
early = f[f.tday0 <= 9]
for after in ("10-39", "10+"):
late = f[(f.tday0 >= 10) & ((f.tday0 <= 39) if after == "10-39" else True)]
v = [early["threshold" + sfx].quantile(.25), early["threshold" + sfx].quantile(.75),
late["threshold" + sfx].quantile(.25), late["threshold" + sfx].quantile(.75),
early["bias" + sfx].quantile(.25), early["bias" + sfx].quantile(.75),
late["bias" + sfx].quantile(.25), late["bias" + sfx].quantile(.75)]
narrower = (v[3] - v[2]) < (v[1] - v[0])
rows.append(dict(reading=RN[r], filt=filt, after=after, n_early=len(early), n_late=len(late),
thr_early=f"{v[0]:.1f}-{v[1]:.1f}", thr_late=f"{v[2]:.1f}-{v[3]:.1f}",
bias_early=f"{v[4]:.1f}-{v[5]:.1f}", bias_late=f"{v[6]:.1f}-{v[7]:.1f}",
n_in_tol=sum(abs(x - e) <= t for x, (e, t) in zip(v, EXP_BC)),
narrower=narrower, ok=check(v, EXP_BC) and narrower))
fig2bc = pd.DataFrame(rows)
print(fig2bc.to_string())
day fits: 1427 of 1427 days; 0 without a fit
threshold range 5.0-40.0, bias range -81.4-98.1
reading filt after n_early n_late thr_early thr_late bias_early bias_late n_in_tol narrower ok
0 main filtered 10-39 174 907 11.1-24.3 11.5-23.7 -8.4-6.1 -8.8-7.5 3 True False
1 main filtered 10+ 174 1100 11.1-24.3 11.5-23.0 -8.4-6.1 -8.6-7.1 4 True False
2 main unfiltered 10-39 174 907 10.0-24.7 10.8-24.5 -9.3-6.8 -9.1-7.8 3 True False
3 main unfiltered 10+ 174 1100 10.0-24.7 10.8-23.7 -9.3-6.8 -8.9-7.1 4 True False
4 contrasts:last filtered 10-39 176 923 11.1-24.6 11.5-24.4 -8.3-6.5 -8.7-7.6 4 True False
5 contrasts:last filtered 10+ 176 1116 11.1-24.6 11.5-23.4 -8.3-6.5 -8.5-7.2 4 True False
6 contrasts:last unfiltered 10-39 176 923 10.0-25.0 10.9-24.9 -9.2-7.9 -9.0-7.9 2 True False
7 contrasts:last unfiltered 10+ 176 1116 10.0-25.0 10.8-24.1 -9.2-7.9 -8.8-7.3 2 True False
8 1b-replace filtered 10-39 159 703 11.0-24.6 11.6-24.7 -7.7-5.5 -7.0-8.0 3 True False
9 1b-replace filtered 10+ 159 801 11.0-24.6 12.2-23.9 -7.7-5.5 -6.3-7.3 2 True False
10 1b-replace unfiltered 10-39 159 703 9.9-24.9 11.4-25.0 -8.4-5.5 -7.1-8.3 2 True False
11 1b-replace unfiltered 10+ 159 801 9.9-24.9 11.7-24.8 -8.4-5.5 -6.7-7.4 2 True False
12 1b-replace,contrasts:last filtered 10-39 159 713 11.0-24.6 11.7-24.7 -7.7-5.5 -7.0-8.1 3 True False
13 1b-replace,contrasts:last filtered 10+ 159 820 11.0-24.6 12.3-24.3 -7.7-5.5 -6.4-7.3 2 True False
14 1b-replace,contrasts:last unfiltered 10-39 159 713 9.9-24.9 11.4-25.1 -8.4-5.5 -7.1-8.3 2 True False
15 1b-replace,contrasts:last unfiltered 10+ 159 820 9.9-24.9 11.7-24.9 -8.4-5.5 -6.7-7.4 2 True False
Result: partially reproduced. Under every reading the threshold interquartile range after day 10 is narrower than in the first 10 days (main, filtered, days 10 to 39: 11.5-23.7% against 11.1-24.3%). No reading puts all eight bounds within tolerance; the main reading puts at most four (filtered, days 10 on: threshold 11.1-24.3% then 11.5-23.0%, bias -8.4 to 6.1% then -8.6 to 7.1%). The early threshold range is narrower than the paper's 12-29%. The early bias range is shifted to the left of the paper's -5.2 to 7.1%; the later bias range is wider than the paper's -5.6 to 6.5%, with its upper bound above the paper's.
fig2-abs-bias-threshold-during-training¶
During training mice were not systematically biased to one side; absolute bias averaged 9.8 +- 12.1 (s.d.), and contrast threshold, which stabilized after about 10 sessions, averaged 17.8 +- 11.7%.
EXP_AB = [(9.8, 0.98), (12.1, 1.21), (17.8, 1.78), (11.7, 1.17)]
rows = []
for r in READINGS:
f = day_fits[day_fits.subject_id.isin(P1[r].index)].copy()
f["lab"] = lab[f.subject_id].to_numpy()
for filt in ("filtered", "unfiltered"):
sfx = "_f" if filt == "filtered" else ""
ab = f["bias" + sfx].abs()
for after in ("10-39", "10+"):
late = f[(f.tday0 >= 10) & ((f.tday0 <= 39) if after == "10-39" else True)]
th = late["threshold" + sfx]
for avg in ("pooled", "lab means"):
if avg == "pooled":
m_ab, m_th = ab.mean(), th.mean()
else:
m_ab = ab.groupby(f.lab).mean().mean()
m_th = th.groupby(late.lab).mean().mean()
v = [m_ab, ab.std(), m_th, th.std()]
rows.append(dict(reading=RN[r], filt=filt, after=after, avg=avg, abs_bias=v[0], abs_bias_sd=v[1],
thr=v[2], thr_sd=v[3],
means_ok=abs(v[0] - 9.8) <= 0.98 and abs(v[2] - 17.8) <= 1.78,
sds_ok=abs(v[1] - 12.1) <= 1.21 and abs(v[3] - 11.7) <= 1.17))
print(pd.DataFrame(rows).round(3).to_string())
f = day_fits[day_fits.subject_id.isin(P1[READINGS[0]].index)]
print("\nsigned bias over all days (main, filtered): mean %.2f, median %.2f; per lab mean:"
% (f.bias_f.mean(), f.bias_f.median()),
f.bias_f.groupby(lab[f.subject_id].to_numpy()).mean().round(2).to_dict())
reading filt after avg abs_bias abs_bias_sd thr thr_sd means_ok sds_ok
0 main filtered 10-39 pooled 8.821 6.392 18.392 8.849 True False
1 main filtered 10-39 lab means 8.487 6.392 18.368 8.849 False False
2 main filtered 10+ pooled 8.821 6.392 18.160 8.605 True False
3 main filtered 10+ lab means 8.487 6.392 18.207 8.605 False False
4 main unfiltered 10-39 pooled 9.759 8.492 18.560 9.839 True False
5 main unfiltered 10-39 lab means 9.477 8.492 18.609 9.839 True False
6 main unfiltered 10+ pooled 9.759 8.492 18.303 9.596 True False
7 main unfiltered 10+ lab means 9.477 8.492 18.399 9.596 True False
8 contrasts:last filtered 10-39 pooled 8.831 6.417 18.564 8.900 True False
9 contrasts:last filtered 10-39 lab means 8.472 6.417 18.523 8.900 False False
10 contrasts:last filtered 10+ pooled 8.831 6.417 18.305 8.656 True False
11 contrasts:last filtered 10+ lab means 8.472 6.417 18.355 8.656 False False
12 contrasts:last unfiltered 10-39 pooled 9.779 8.521 18.712 9.888 True False
13 contrasts:last unfiltered 10-39 lab means 9.478 8.521 18.748 9.888 True False
14 contrasts:last unfiltered 10+ pooled 9.779 8.521 18.432 9.644 True False
15 contrasts:last unfiltered 10+ lab means 9.478 8.521 18.531 9.644 True False
16 1b-replace filtered 10-39 pooled 7.959 6.300 18.796 8.936 False False
17 1b-replace filtered 10-39 lab means 7.553 6.300 18.892 8.936 False False
18 1b-replace filtered 10+ pooled 7.959 6.300 18.886 8.552 False False
19 1b-replace filtered 10+ lab means 7.553 6.300 18.979 8.552 False False
20 1b-replace unfiltered 10-39 pooled 8.961 8.722 18.971 9.830 True False
21 1b-replace unfiltered 10-39 lab means 8.587 8.722 19.113 9.830 False False
22 1b-replace unfiltered 10+ pooled 8.961 8.722 19.071 9.483 True False
23 1b-replace unfiltered 10+ lab means 8.587 8.722 19.200 9.483 False False
24 1b-replace,contrasts:last filtered 10-39 pooled 7.976 6.307 18.873 8.930 False False
25 1b-replace,contrasts:last filtered 10-39 lab means 7.603 6.307 19.000 8.930 False False
26 1b-replace,contrasts:last filtered 10+ pooled 7.976 6.307 19.026 8.620 False False
27 1b-replace,contrasts:last filtered 10+ lab means 7.603 6.307 19.185 8.620 False False
28 1b-replace,contrasts:last unfiltered 10-39 pooled 8.991 8.721 19.013 9.854 True False
29 1b-replace,contrasts:last unfiltered 10-39 lab means 8.620 8.721 19.176 9.854 False False
30 1b-replace,contrasts:last unfiltered 10+ pooled 8.991 8.721 19.140 9.578 True False
31 1b-replace,contrasts:last unfiltered 10+ lab means 8.620 8.721 19.310 9.578 False False
signed bias over all days (main, filtered): mean -0.99, median -1.35; per lab mean: {'Lab 1': -2.75, 'Lab 2': -5.11, 'Lab 3': 2.55, 'Lab 4': -4.78, 'Lab 5': 1.94, 'Lab 6': 0.99, 'Lab 7': -4.14}
Result: reproduced. Under the main reading, without the median filter, the mean absolute bias over all days is 9.759 and the mean threshold after day 10 is 18.56% (days 10 to 39) and 18.30% (days 10 on), within tolerance of 9.8 and 17.8; with the filter the absolute bias is 8.821, at the lower edge of 9.8 +- 0.98. The s.d.s are smaller than the paper's under every reading (absolute bias 6.30 to 8.72 against 12.1; threshold 8.55 to 9.89 against 11.7). The mean signed bias is -0.99 (main, filtered), with lab means from -5.11 to 2.55; the paper's "similar across laboratories" is not tested by the criterion.
fig2s2-variability-decreases¶
Variability in performance across mice decreased with training but did not disappear; between training days 15 and 40, mean easy-trial performance rose from 80.7% to 91.1% while its s.d. across mice fell from 19.1% to 10.1%.
EXP_V = [(80.7, 8.07), (91.1, 9.11), (19.1, 1.91), (10.1, 1.01)]
def perf_by_day(mice_idx, only_5050):
dd = Dc[Dc.subject_id.isin(mice_idx) & (Dc.n_trials > 100)]
if only_5050:
dd = dd[dd.basic_only]
dd = dd.sort_values(["subject_id", "tday0"]).copy()
dd["perf_f"] = dd.groupby("subject_id").perf_easy.transform(
lambda x: x.rolling(3, center=True, min_periods=1).median())
dd["day"] = dd.groupby("subject_id").cumcount()
return dd.groupby("day").perf_f.agg(["mean", "std", "size"])
rows = []
for r in READINGS:
idx = P1[r].index
for name, g in (("(1) all sessions", perf_by_day(idx, False)), ("(2) basic-task days only", perf_by_day(idx, True))):
for a, b in ((15, 40), (14, 39)):
if b not in g.index:
continue
v = [g.loc[a, "mean"], g.loc[b, "mean"], g.loc[a, "std"], g.loc[b, "std"]]
rows.append(dict(reading=RN[r], data=name, days=f"{a},{b}", n=f"{g.loc[a, 'size']},{g.loc[b, 'size']}",
mean_a=v[0], mean_b=v[1], sd_a=v[2], sd_b=v[3],
n_in_tol=sum(abs(x - e) <= t for x, (e, t) in zip(v, EXP_V)),
ok=check(v, EXP_V) and v[1] > v[0] and v[3] < v[2]))
# (3) unfiltered per-day performance, days strictly within 2 of the bin centre; mean per mouse in the bin
dd = Dc[Dc.subject_id.isin(idx)]
vals = []
for c in (15, 39):
b = dd[(dd.tday0 - c).abs() < 2].groupby("subject_id").perf_easy.mean()
vals.append(b)
v = [vals[0].mean(), vals[1].mean(), vals[0].std(), vals[1].std()]
rows.append(dict(reading=RN[r], data="(3) binned", days="15,39", n=f"{len(vals[0])},{len(vals[1])}",
mean_a=v[0], mean_b=v[1], sd_a=v[2], sd_b=v[3],
n_in_tol=sum(abs(x - e) <= t for x, (e, t) in zip(v, EXP_V)),
ok=check(v, EXP_V) and v[1] > v[0] and v[3] < v[2]))
print(pd.DataFrame(rows).round(2).to_string())
reading data days n mean_a mean_b sd_a sd_b n_in_tol ok 0 main (1) all sessions 15,40 83,53 86.13 91.11 15.17 7.98 2 False 1 main (1) all sessions 14,39 83,55 85.01 91.62 16.31 8.07 2 False 2 main (2) basic-task days only 15,40 60,13 81.57 86.72 15.87 8.09 2 False 3 main (2) basic-task days only 14,39 66,13 81.40 85.62 16.70 10.73 3 False 4 main (3) binned 15,39 83,57 85.46 91.38 16.01 8.04 2 False 5 contrasts:last (1) all sessions 15,40 85,53 86.29 91.11 15.03 7.98 2 False 6 contrasts:last (1) all sessions 14,39 85,55 85.17 91.62 16.16 8.07 2 False 7 contrasts:last (2) basic-task days only 15,40 62,13 81.94 86.72 15.75 8.09 2 False 8 contrasts:last (2) basic-task days only 14,39 68,13 81.70 85.62 16.55 10.73 3 False 9 contrasts:last (3) binned 15,39 85,57 85.66 91.38 15.87 8.04 2 False 10 1b-replace (1) all sessions 15,40 70,48 87.76 92.23 15.13 6.86 2 False 11 1b-replace (1) all sessions 14,39 70,50 86.80 92.44 16.22 7.62 2 False 12 1b-replace (2) basic-task days only 15,40 47,8 82.92 87.89 16.38 7.67 2 False 13 1b-replace (2) basic-task days only 14,39 53,8 83.03 85.73 16.95 12.19 2 False 14 1b-replace (3) binned 15,39 70,52 87.00 92.00 16.22 7.82 2 False 15 1b-replace,contrasts:last (1) all sessions 15,40 71,49 87.47 91.75 15.22 7.57 2 False 16 1b-replace,contrasts:last (1) all sessions 14,39 71,51 86.52 92.22 16.27 7.70 2 False 17 1b-replace,contrasts:last (2) basic-task days only 15,40 48,9 82.41 88.26 16.59 7.26 2 False 18 1b-replace,contrasts:last (2) basic-task days only 14,39 54,9 82.58 86.34 17.12 11.55 2 False 19 1b-replace,contrasts:last (3) binned 15,39 71,53 86.69 91.91 16.32 7.77 2 False
Result: partially reproduced. Under every reading the mean easy-trial performance rises and its s.d. across mice falls between days 15 and 40 (main, all sessions: 86.13 to 91.11%, s.d. 15.17 to 7.98%). The two means are within tolerance under every reading, but no reading has both s.d.s within tolerance (15.03 to 17.12% at day 15 against 19.1%; 6.86 to 12.19% at day 40 against 10.1%).
early-sessions-predict-slow-learners¶
A Random Forests decoder applied to the change in easy-trial performance over the first five sessions predicted whether a mouse would be in the bottom quartile of learning speed with 53% accuracy (chance 25%), and misclassified a top-quartile mouse as bottom-quartile only 7% of the time.
The readings of the criterion: features (a) four differences, (b) five performances; labels (A) four quartiles, (B) bottom quartile against the rest; quartiles from days to P1 or trials to P1; accuracy (i) recall of the bottom quartile, (ii) four-class accuracy under (A), (iii) precision of the bottom quartile. scikit-learn RandomForestClassifier with default settings, leave-one-out; its seed is a standard choice (0). The criterion's readings are run under the main reading of P1 only, to keep the notebook within its time limit.
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import LeaveOneOut, cross_val_predict
first5 = Dc[Dc.tday0 <= 4].pivot(index="subject_id", columns="tday0", values="perf_easy")
rows = []
for r in [MAIN]:
for qsrc in ("days", "trials"):
d = days[(r, "incl")]
if qsrc == "trials":
dd = Dc[Dc.subject_id.isin(d.index)]
d = dd[dd.tday0 < dd.subject_id.map(d)].groupby("subject_id").n_trials.sum()
idx = d.index.intersection(first5.dropna().index)
q = pd.qcut(d[idx].rank(method="first"), 4, labels=[1, 2, 3, 4]).astype(int) # 4 = slowest
F = {"a": np.diff(first5.loc[idx].to_numpy(), axis=1), "b": first5.loc[idx].to_numpy()}
for feat, X in F.items():
for lab_kind in ("A", "B"):
y = q.to_numpy() if lab_kind == "A" else (q.to_numpy() == 4).astype(int)
pred = cross_val_predict(RandomForestClassifier(random_state=0, n_jobs=4), X, y, cv=LeaveOneOut())
bottom = 4 if lab_kind == "A" else 1
recall = np.mean(pred[y == bottom] == bottom)
precision = np.mean(y[pred == bottom] == bottom) if (pred == bottom).any() else np.nan
acc4 = np.mean(pred == y) if lab_kind == "A" else np.nan
top_as_bottom = np.mean(pred[q.to_numpy() == 1] == bottom)
rows.append(dict(reading=RN[r], quartiles=qsrc, features=feat, labels=lab_kind, n=len(idx),
recall=recall, four_class=acc4, precision=precision, top_as_bottom=top_as_bottom,
base_rate=np.mean(y == bottom)))
es = pd.DataFrame(rows)
print(es.round(3).to_string())
acc = pd.concat([es.recall, es.four_class.dropna(), es.precision])
print("\naccuracy readings within 0.53 +- 0.053: %d of %d; range %.3f-%.3f"
% (int(((acc - 0.53).abs() <= 0.053).sum()), len(acc), acc.min(), acc.max()))
print("top quartile classed as bottom, range %.3f-%.3f; within 0.07 +- 0.007: %d of %d"
% (es.top_as_bottom.min(), es.top_as_bottom.max(), int(((es.top_as_bottom - 0.07).abs() <= 0.007).sum()), len(es)))
reading quartiles features labels n recall four_class precision top_as_bottom base_rate 0 main days a A 83 0.381 0.313 0.421 0.048 0.253 1 main days a B 83 0.286 NaN 0.400 0.048 0.253 2 main days b A 83 0.571 0.518 0.571 0.048 0.253 3 main days b B 83 0.381 NaN 0.667 0.000 0.253 4 main trials a A 83 0.333 0.265 0.250 0.143 0.253 5 main trials a B 83 0.143 NaN 0.200 0.000 0.253 6 main trials b A 83 0.429 0.434 0.321 0.143 0.253 7 main trials b B 83 0.190 NaN 0.364 0.048 0.253 accuracy readings within 0.53 +- 0.053: 3 of 20; range 0.143-0.667 top quartile classed as bottom, range 0.000-0.143; within 0.07 +- 0.007: 0 of 8
Result: blocked (methods_underspecified). Under the main reading of P1 the criterion's readings disagree on whether the accuracy is near 53%: 3 of 20 accuracy values are within 0.53 +- 0.053 (features (b), four quartiles from days: recall 0.571, four-class accuracy 0.518, precision 0.571), and the others run from 0.143 to 0.667. The share of top-quartile mice classed as bottom quartile ranges from 0.000 to 0.143 (within 0.07 +- 0.007 in none of 8). The repository holds no code for this analysis.
Sessions at basic task proficiency (S1)¶
The basic (training protocol) sessions of the P1 day and the two training days before it, per reading of P1. One value per mouse from the pooled trials.
def s1_values(r):
t = ib.window(Tm, P1[r].p1_tday0, -2, 0, ["training"])
fits = ib.mouse_fits(t)
g = t.groupby("subject_id")
ses = Sc[Sc.session_id.isin(t.session_id)]
v = pd.DataFrame({
"perf_easy": g.apply(ib.perf_easy, include_groups=False),
"rt": g.rt.median(),
"n_trials": ses.groupby("subject_id").n_trials.mean(),
"threshold": fits.threshold, "bias": fits.bias,
"trials_per_min": (ses.n_trials / ses.duration_min).groupby(ses.subject_id).mean(),
})
v["lab"] = lab[v.index]
return v, t
S1 = {}
S1_trials = {}
for r in READINGS:
S1[r], S1_trials[r] = s1_values(r)
print(RN[r], "mice", len(S1[r]), "| sessions per mouse", S1_trials[r].groupby("subject_id").session_id.nunique()
.value_counts().to_dict(), "| no valid trial duration", int(S1[r].rt.isna().sum()))
main mice 81 | sessions per mouse {3: 75, 2: 3, 4: 2, 1: 1} | no valid trial duration 0
contrasts:last mice 85 | sessions per mouse {3: 83, 2: 1, 4: 1} | no valid trial duration 0
1b-replace mice 62 | sessions per mouse {3: 52, 1: 4, 4: 3, 2: 3} | no valid trial duration 0
1b-replace,contrasts:last mice 64 | sessions per mouse {3: 57, 4: 3, 1: 2, 2: 2} | no valid trial duration 0
fig3c-easy-errors-basic¶
At basic task proficiency, errors on easy (50% and 100%) contrasts were low, 9.5 +- 3.6%, with no significant difference across laboratories.
rows = []
for r in READINGS:
v = S1[r][S1[r].rt.notna()]
e = 100 - v.perf_easy
rows.append(dict(reading=RN[r], n=len(e), mean=e.mean(), sd=e.std(), min=e.min(), max=e.max(),
mean_ok=abs(e.mean() - 9.5) <= 0.95, sd_ok=abs(e.std() - 3.6) <= 0.36))
print(pd.DataFrame(rows).round(2).to_string())
v = S1[READINGS[0]]
print("by lab (main):", (100 - v.perf_easy).groupby(v.lab).mean().round(2).to_dict())
reading n mean sd min max mean_ok sd_ok
0 main 81 8.41 3.79 1.02 15.21 False True
1 contrasts:last 85 9.66 3.69 2.64 17.25 True True
2 1b-replace 62 5.26 3.26 0.94 15.21 False True
3 1b-replace,contrasts:last 64 5.84 3.64 0.94 17.25 False True
by lab (main): {'Lab 1': 8.53, 'Lab 2': 7.92, 'Lab 3': 7.03, 'Lab 4': 9.96, 'Lab 5': 10.06, 'Lab 6': 10.0, 'Lab 7': 8.01}
Result: partially reproduced. Under the main reading the error rate on easy trials at proficiency is 8.41 +- 3.79% (81 mice): the s.d. is within tolerance of 3.6 +- 0.36, the mean just outside 9.5 +- 0.95. The pipeline's contrast check, a variant, gives 9.66 +- 3.69% (85 mice), both within tolerance; with 1b replacing 1a it is 5.26 and 5.84%, as the 1b criteria require more than 90% correct. Two of the 83 mice with P1 have no basic-task session in S1. The lab comparison is the next claim.
fig3de-threshold-bias-basic¶
At basic task proficiency the contrast threshold was similar across laboratories at 14.3 +- 3.8 (s.d., n = 7 laboratories) and the response bias was small at 0.3 +- 8.4.
EXP_DE = [(14.3, 1.43), (0.3, 3.2), (3.8, 0.38), (8.4, 0.84)]
rows = []
for r in READINGS:
v = S1[r]
for how in ("over mice", "over lab means"):
if how == "over mice":
th, bi = v.threshold.dropna(), v.bias.dropna()
else:
th, bi = v.threshold.groupby(v.lab).mean(), v.bias.groupby(v.lab).mean()
x = [th.mean(), bi.mean(), th.std(), bi.std()]
rows.append(dict(reading=RN[r], how=how, n=len(th), thr=x[0], bias=x[1], thr_sd=x[2], bias_sd=x[3],
n_in_tol=sum(abs(a - e) <= t for a, (e, t) in zip(x, EXP_DE)),
means_ok=abs(x[0] - 14.3) <= 1.43 and abs(x[1] - 0.3) <= 3.2, all_ok=check(x, EXP_DE)))
print(pd.DataFrame(rows).round(2).to_string())
print("fits without a value:", {RN[r]: int(S1[r].threshold.isna().sum()) for r in READINGS})
reading how n thr bias thr_sd bias_sd n_in_tol means_ok all_ok
0 main over mice 81 14.09 -0.46 3.80 8.09 4 True True
1 main over lab means 7 14.06 -0.89 1.43 1.73 2 True False
2 contrasts:last over mice 85 13.89 0.16 3.92 9.05 4 True True
3 contrasts:last over lab means 7 13.81 -0.32 1.24 1.61 2 True False
4 1b-replace over mice 62 14.78 0.49 3.86 6.16 3 True False
5 1b-replace over lab means 7 14.55 0.32 2.01 1.14 2 True False
6 1b-replace,contrasts:last over mice 64 14.74 0.57 3.83 6.72 3 True False
7 1b-replace,contrasts:last over lab means 7 14.41 0.44 2.24 1.15 2 True False
fits without a value: {'main': 0, 'contrasts:last': 0, '1b-replace': 0, '1b-replace,contrasts:last': 0}
Result: reproduced. Over mice, under the main reading, the threshold is 14.09 +- 3.80 and the bias -0.46 +- 8.09 (81 mice): all four values within tolerance, and also under the pipeline's contrast check (13.89 +- 3.92 and 0.16 +- 9.05). Over the seven lab means the means match (13.81 to 14.55) but the s.d.s are 1.14 to 2.24, far below 3.8 and 8.4, so the paper's s.d.s are over mice.
fig3cde-no-lab-difference-medians and fig3cde-no-lab-difference-variances¶
At basic task proficiency, easy-trial performance, contrast threshold and bias did not differ in median across laboratories.
At basic task proficiency, easy-trial performance, contrast threshold and bias did not differ in variance across laboratories.
Kruskal-Wallis (and Levene) across labs on six variables, Benjamini-Hochberg over the six.
VARS = ["perf_easy", "rt", "n_trials", "threshold", "bias", "trials_per_min"]
labtests = {}
for r in READINGS:
v = S1[r][S1[r].rt.notna()]
out = {}
for test in ("kruskal", "levene", "code"):
p = np.array([ib.lab_test(v[x], v.lab, test) for x in VARS])
out[test] = pd.Series(p, index=VARS)
out[test + "_fdr"] = pd.Series(ib.fdr(p), index=VARS)
labtests[r] = pd.DataFrame(out)
print(RN[r], "n =", len(v), "| mice per lab", v.lab.value_counts().sort_index().to_dict())
print(labtests[r].round(4).to_string(), "\n")
main n = 81 | mice per lab {'Lab 1': 12, 'Lab 2': 12, 'Lab 3': 25, 'Lab 4': 7, 'Lab 5': 8, 'Lab 6': 11, 'Lab 7': 6}
kruskal kruskal_fdr levene levene_fdr code code_fdr
perf_easy 0.1913 0.2870 0.1388 0.2679 0.1913 0.2870
rt 0.0609 0.1217 0.0811 0.2434 0.0609 0.1217
n_trials 0.0005 0.0028 0.4236 0.4236 0.0001 0.0007
threshold 0.3655 0.4386 0.1786 0.2679 0.3408 0.4090
bias 0.7299 0.7299 0.2495 0.2994 0.6579 0.6579
trials_per_min 0.0009 0.0028 0.0102 0.0612 0.0009 0.0028
contrasts:last n = 85 | mice per lab {'Lab 1': 12, 'Lab 2': 13, 'Lab 3': 26, 'Lab 4': 7, 'Lab 5': 8, 'Lab 6': 13, 'Lab 7': 6}
kruskal kruskal_fdr levene levene_fdr code code_fdr
perf_easy 0.2634 0.3951 0.0379 0.2131 0.2250 0.3376
rt 0.0681 0.1362 0.1085 0.2169 0.0681 0.1362
n_trials 0.0003 0.0016 0.4849 0.5441 0.0001 0.0006
threshold 0.4167 0.5000 0.5441 0.5441 0.4167 0.5000
bias 0.8135 0.8135 0.2865 0.4298 0.8135 0.8135
trials_per_min 0.0018 0.0053 0.0710 0.2131 0.0018 0.0053
1b-replace n = 62 | mice per lab {'Lab 1': 10, 'Lab 2': 8, 'Lab 3': 23, 'Lab 4': 3, 'Lab 5': 7, 'Lab 6': 6, 'Lab 7': 5}
kruskal kruskal_fdr levene levene_fdr code code_fdr
perf_easy 0.0126 0.0377 0.0366 0.2120 0.0126 0.0377
rt 0.3954 0.4745 0.8337 0.8337 0.3954 0.4745
n_trials 0.0035 0.0211 0.3968 0.5953 0.0035 0.0211
threshold 0.1723 0.3447 0.1037 0.2120 0.1212 0.2424
bias 0.9751 0.9751 0.5765 0.6918 0.9679 0.9679
trials_per_min 0.2927 0.4390 0.1060 0.2120 0.1737 0.2605
1b-replace,contrasts:last n = 64 | mice per lab {'Lab 1': 11, 'Lab 2': 8, 'Lab 3': 23, 'Lab 4': 4, 'Lab 5': 7, 'Lab 6': 6, 'Lab 7': 5}
kruskal kruskal_fdr levene levene_fdr code code_fdr
perf_easy 0.0087 0.0261 0.0976 0.2927 0.0087 0.0261
rt 0.1873 0.2810 0.7172 0.7172 0.1873 0.2810
n_trials 0.0027 0.0160 0.3985 0.5977 0.0027 0.0160
threshold 0.0312 0.0625 0.2966 0.5931 0.0312 0.0625
bias 0.9716 0.9716 0.5418 0.6501 0.9771 0.9771
trials_per_min 0.3562 0.4275 0.0892 0.2927 0.2820 0.3385
for r in READINGS:
lt = labtests[r]
m = lt.loc[["perf_easy", "threshold", "bias"]]
print(f"{RN[r]}: medians, all three FDR p >= 0.05: {bool((m.kruskal_fdr >= 0.05).all())} "
f"(min {m.kruskal_fdr.min():.3f}); code switch: {bool((m.code_fdr >= 0.05).all())} | "
f"variances, all three FDR p >= 0.05: {bool((m.levene_fdr >= 0.05).all())} (min {m.levene_fdr.min():.3f})")
v = S1[r]
eff = {x: f"{v[x].groupby(v.lab).median().min():.2f}..{v[x].groupby(v.lab).median().max():.2f}"
for x in ["perf_easy", "threshold", "bias"]}
sds = {x: f"{v[x].groupby(v.lab).std().min():.2f}..{v[x].groupby(v.lab).std().max():.2f}"
for x in ["perf_easy", "threshold", "bias"]}
print(" lab medians:", eff, "| lab s.d.:", sds)
main: medians, all three FDR p >= 0.05: True (min 0.287); code switch: True | variances, all three FDR p >= 0.05: True (min 0.268)
lab medians: {'perf_easy': '89.04..93.13', 'threshold': '12.29..17.11', 'bias': '-6.14..1.78'} | lab s.d.: {'perf_easy': '1.48..4.35', 'threshold': '2.35..4.75', 'bias': '4.66..10.57'}
contrasts:last: medians, all three FDR p >= 0.05: True (min 0.395); code switch: True | variances, all three FDR p >= 0.05: True (min 0.213)
lab medians: {'perf_easy': '87.98..91.57', 'threshold': '11.89..16.61', 'bias': '-6.75..3.77'} | lab s.d.: {'perf_easy': '0.95..4.33', 'threshold': '2.80..4.45', 'bias': '4.52..11.08'}
1b-replace: medians, all three FDR p >= 0.05: False (min 0.038); code switch: False | variances, all three FDR p >= 0.05: True (min 0.212)
lab medians: {'perf_easy': '92.36..97.44', 'threshold': '11.70..17.75', 'bias': '-1.32..1.78'} | lab s.d.: {'perf_easy': '0.92..4.08', 'threshold': '2.01..6.66', 'bias': '5.03..8.32'}
1b-replace,contrasts:last: medians, all three FDR p >= 0.05: False (min 0.026); code switch: False | variances, all three FDR p >= 0.05: True (min 0.293)
lab medians: {'perf_easy': '91.14..97.44', 'threshold': '11.10..17.75', 'bias': '-1.32..2.97'} | lab s.d.: {'perf_easy': '0.92..4.50', 'threshold': '2.01..5.58', 'bias': '4.14..9.78'}
Result: reproduced. Under the main reading the corrected Kruskal-Wallis p values are 0.287 for performance, 0.439 for threshold and 0.730 for bias, all above 0.05 (lab medians: performance 89.0 to 93.1%, threshold 12.3 to 17.1, bias -6.1 to 1.8); the paper's are 0.63, 0.81 and 0.81. The code's switch to ANOVA gives the same. The pipeline's contrast check gives the same outcome (smallest 0.395); with 1b replacing 1a, a variant, performance differs across labs (corrected p = 0.038 and 0.026).
Result: reproduced. The corrected Levene p values for performance, threshold and bias are all above 0.05 under the main reading (0.268, 0.268 and 0.299) and under every variant (smallest 0.212).
fig3s2a-trial-duration¶
At basic task proficiency the median trial duration (stimulus onset to feedback) was 468 +- 221 ms, with some differences across laboratories.
rows = []
for r in READINGS:
v = S1[r][S1[r].rt.notna()]
rt = 1000 * v.rt
pk = labtests[r].loc["rt", "kruskal"]
pf = labtests[r].loc["rt", "kruskal_fdr"]
rows.append(dict(reading=RN[r], n=len(rt), median=rt.median(), sd=rt.std(), mean=rt.mean(),
p_kw=pk, p_kw_fdr=pf,
ok_uncorr=abs(rt.median() - 468) <= 46.8 and abs(rt.std() - 221) <= 22.1 and pk < 0.05,
ok_fdr=abs(rt.median() - 468) <= 46.8 and abs(rt.std() - 221) <= 22.1 and pf < 0.05))
print(pd.DataFrame(rows).round(4).to_string())
v = S1[READINGS[0]]
print("lab medians (ms, main):", (1000 * v.rt).groupby(v.lab).median().round(0).to_dict())
reading n median sd mean p_kw p_kw_fdr ok_uncorr ok_fdr
0 main 81 420.450 219.4180 472.0056 0.0609 0.1217 False False
1 contrasts:last 85 438.400 225.7105 483.5200 0.0681 0.1362 False False
2 1b-replace 62 382.625 161.2229 412.2710 0.3954 0.4745 False False
3 1b-replace,contrasts:last 64 385.800 187.1870 426.7062 0.1873 0.2810 False False
lab medians (ms, main): {'Lab 1': 407.0, 'Lab 2': 419.0, 'Lab 3': 391.0, 'Lab 4': 702.0, 'Lab 5': 370.0, 'Lab 6': 455.0, 'Lab 7': 428.0}
Result: partially reproduced. Under the main reading the median over mice of the median trial duration is 420.45 ms, just below 468 +- 46.8, with s.d. 219 ms (within 221 +- 22.1), and the Kruskal-Wallis test does not find a difference across labs (p = 0.061 uncorrected, 0.122 corrected), which the criterion requires (p < 0.05). The pipeline's contrast check gives 438.4 +- 225.7 ms, within tolerance, with p = 0.068. Lab 4 is slower than the others (median 702 ms against 370 to 455 ms). One of the two values is within tolerance and the other just outside it, and the difference across labs is not significant.
fig3s2b-trials-per-session¶
At basic task proficiency mice performed 719 +- 223 trials per session; the difference across laboratories was significant but only in one laboratory relative to the rest.
from statsmodels.stats.multicomp import pairwise_tukeyhsd
rows = []
for r in READINGS:
v = S1[r][S1[r].rt.notna()]
p = ib.lab_test(v.n_trials, v.lab, "anova")
tk = pairwise_tukeyhsd(v.n_trials, v.lab)
tab = pd.DataFrame(tk._results_table.data[1:], columns=tk._results_table.data[0])
sig = tab[tab.reject]
labs_inv = pd.concat([sig.group1, sig.group2]).value_counts()
common = [l for l in labs_inv.index if all((sig.group1 == l) | (sig.group2 == l))] if len(sig) else []
rows.append(dict(reading=RN[r], n=len(v), mean=v.n_trials.mean(), sd=v.n_trials.std(), p_anova=p,
p_kw_fdr=labtests[r].loc["n_trials", "kruskal_fdr"],
sig_pairs=", ".join(f"{a}-{b}" for a, b in zip(sig.group1, sig.group2)),
one_lab=common[0] if common else "",
values_ok=abs(v.n_trials.mean() - 719) <= 71.9 and abs(v.n_trials.std() - 223) <= 22.3))
print(pd.DataFrame(rows).to_string(float_format=lambda x: f"{x:.4g}"))
v = S1[READINGS[0]]
print("lab means (main):", v.n_trials.groupby(v.lab).mean().round(0).to_dict())
reading n mean sd p_anova p_kw_fdr sig_pairs one_lab values_ok
0 main 81 706.8 196.9 0.0001225 0.002755 Lab 2-Lab 7, Lab 3-Lab 7, Lab 4-Lab 7, Lab 5-Lab 7, Lab 6-Lab 7 Lab 7 False
1 contrasts:last 85 691.8 194.2 9.198e-05 0.001647 Lab 2-Lab 7, Lab 3-Lab 7, Lab 4-Lab 7, Lab 5-Lab 7, Lab 6-Lab 7 Lab 7 False
2 1b-replace 62 730.8 188 0.00255 0.02109 Lab 2-Lab 7, Lab 4-Lab 7, Lab 5-Lab 7 Lab 7 False
3 1b-replace,contrasts:last 64 718.2 191.9 0.002021 0.01599 Lab 2-Lab 7, Lab 4-Lab 7, Lab 5-Lab 7 Lab 7 False
lab means (main): {'Lab 1': 635.0, 'Lab 2': 823.0, 'Lab 3': 690.0, 'Lab 4': 797.0, 'Lab 5': 836.0, 'Lab 6': 706.0, 'Lab 7': 412.0}
Result: partially reproduced. Under the main reading mice performed 706.8 +- 196.9 trials per session (81 mice): the mean is within 719 +- 71.9, the s.d. below 223 +- 22.3. The one-way ANOVA across labs gives p = 1.2e-04, below 0.05 but not below 1e-6, and the five significant Tukey pairs all involve Lab 7 (412 trials per session against 635 to 836). The variants give the same pattern (p = 9.2e-05 to 0.0026, every pair with Lab 7).
lab-link¶
The lab numbers (Lab 1 to 7) and, for the positive control, the labs' time zones come from the paper's code by institution (claims file header). The dataset names each session's institution.
inst = S.groupby("institution").agg(lab_number=("lab_number", "first"), mice=("subject_id", "nunique"),
labs_in_files=("lab", lambda x: sorted(set(x))))
inst["time_zone"] = inst.lab_number.map(ib.TIME_ZONE)
print(inst.to_string())
print("institutions matched to a lab number:", int(inst.lab_number.notna().sum()), "of", len(inst),
"| distinct lab numbers:", inst.lab_number.nunique())
h = pd.to_datetime(S.start.str[:19]).dt.hour + pd.to_datetime(S.start.str[:19]).dt.minute / 60
med = h.groupby(S.lab_number).median()
print("median start hour by lab (stated as UTC):", med.round(1).to_dict())
print("spread of lab medians %.1f h; if the times were UTC, Lab 7 (UTC-7) would start about 7 h later than Lab 1"
% (med.max() - med.min()))
lab_number mice labs_in_files time_zone
institution
Champalimaud Centre for the Unknown Lab 2 22 [mainenlab] 0
Cold Spring Harbor Laboratory Lab 3 46 [churchlandlab, zadorlab] -5
New York University / Center for Neural Science Lab 4 20 [angelakilab] -5
Princeton Lab 5 18 [wittenlab] -5
Sainsbury Wellcome Centre Lab 6 37 [hoferlab, mrsicflogellab] 0
University College London Lab 1 21 [cortexlab] 0
University of California Berkeley Lab 7 14 [danlab] -7
institutions matched to a lab number: 7 of 7 | distinct lab numbers: 7
median start hour by lab (stated as UTC): {'Lab 1': 11.0, 'Lab 2': 14.4, 'Lab 3': 12.9, 'Lab 4': 11.7, 'Lab 5': 11.7, 'Lab 6': 13.0, 'Lab 7': 11.0}
spread of lab medians 3.4 h; if the times were UTC, Lab 7 (UTC-7) would start about 7 h later than Lab 1
Result: reproduced. The seven institutions in the files match the code's seven labs one to
one (7 of 7), with CSHL holding two lab groups (churchlandlab and zadorlab) and SWC two (hoferlab
and mrsicflogellab). The time zones cannot be confirmed from the data: session_start_time is
stated in UTC, but the median start hours of all labs fall between 11.0 and 14.4 h, Lab 7 at 11.0
h like Lab 1, so the times are local clock times labelled UTC.
fig3s1a-choice-consistency-basic¶
In the basic task, mouse choices were no more consistent within laboratories than across laboratories.
Fraction of rightward choices per signed contrast (50% contrast trials dropped), per mouse; 10,000 shuffles of lab labels. Main: S1 sessions; variant (code): the P1 day and the two days after.
def choice_matrix(t, by_block=False):
t = t[(t.abs_contrast != 50) & t.choice_right.notna()]
cols = ["signed_contrast"] + (["probabilityLeft"] if by_block else [])
return t.groupby(["subject_id"] + cols).choice_right.mean().unstack(cols)
rows = []
for r in READINGS:
for win in ("S1", "code [0, 2]"):
t = S1_trials[r] if win == "S1" else ib.window(Tm, P1[r].p1_tday0, 0, 2, ["training", "biased"])
if win != "S1": # basic-task trials, and the 50:50 trials of full-task sessions
t = t[(t.task == "training") | np.isclose(t.probabilityLeft, 0.5)]
M = choice_matrix(t)
obs, null, p = ib.consistency_test(M, lab[M.index], 10000, seed=11)
rows.append(dict(reading=RN[r], sessions=win, mice=len(M), consistency=obs,
null_mean=null.mean(), p=p, ok=p >= 0.05))
print(pd.DataFrame(rows).round(4).to_string())
reading sessions mice consistency null_mean p ok 0 main S1 81 54.5310 55.0971 0.4584 True 1 main code [0, 2] 83 52.0144 53.2711 0.5346 True 2 contrasts:last S1 85 46.9108 48.6018 0.5719 True 3 contrasts:last code [0, 2] 85 49.6093 51.0743 0.5577 True 4 1b-replace S1 62 67.5559 83.6826 0.8609 True 5 1b-replace code [0, 2] 70 81.2070 81.5806 0.4496 True 6 1b-replace,contrasts:last S1 64 67.9048 73.9860 0.6605 True 7 1b-replace,contrasts:last code [0, 2] 71 75.3786 75.7613 0.4405 True
Result: reproduced. Choices are not more consistent within labs than in shuffles: p = 0.458 on S1 and 0.535 on the code's sessions under the main reading, and 0.440 to 0.861 under the variants.
Sessions at full task proficiency (S2)¶
The full task (biased protocol) sessions of the P2 day and the two training days before it.
S2t = ib.window(Tm, P2.p2_tday0, -2, 0, ["biased"])
print("P2 mice", len(P2), "| sessions per mouse", S2t.groupby("subject_id").session_id.nunique().value_counts().to_dict(),
"| trials", len(S2t), "| block values", S2t.probabilityLeft.round(2).value_counts().to_dict())
blk = {"2080": 0.2, "8020": 0.8}
S2fits = ib.mouse_fits(S2t.assign(block=np.select([np.isclose(S2t.probabilityLeft, 0.2),
np.isclose(S2t.probabilityLeft, 0.8)],
["2080", "8020"], "5050")),
by=("subject_id", "block")).unstack("block")
print("fits without a value:", int(S2fits.isna().any(axis=1).sum()))
P2 mice 60 | sessions per mouse {3: 58, 4: 2} | trials 152255 | block values {0.8: 68465, 0.2: 67410, 0.5: 16380}
fits without a value: 0
fig3s1bc-choice-consistency-full¶
In the full task, neither choice fractions nor the bias shift between blocks were more consistent within laboratories than expected by chance.
Mb = choice_matrix(S2t, by_block=True)
obs_b, null_b, p_b = ib.consistency_test(Mb, lab[Mb.index], 10000, seed=12)
Mfrac = choice_matrix(S2t, by_block=True)
shift = Mfrac.xs(0.2, axis=1, level="probabilityLeft") - Mfrac.xs(0.8, axis=1, level="probabilityLeft")
obs_c, null_c, p_c = ib.consistency_test(shift, lab[shift.index], 10000, seed=13)
print(f"(b) choices per contrast and block: mice {len(Mb)}, consistency {obs_b:.3f}, null mean {null_b.mean():.3f}, p = {p_b:.4f}")
print(f"(c) bias shift per contrast: mice {len(shift)}, consistency {obs_c:.3f}, null mean {null_c.mean():.3f}, p = {p_c:.4f}")
print("both p >= 0.05:", p_b >= 0.05 and p_c >= 0.05)
(b) choices per contrast and block: mice 60, consistency 98.204, null mean 82.496, p = 0.0168 (c) bias shift per contrast: mice 60, consistency 173.681, null mean 158.797, p = 0.1539 both p >= 0.05: False
Result: not reproduced. In the full task, choices per contrast and block are more consistent within labs than in shuffles (consistency 98.2 against a null mean of 82.5, p = 0.017, 60 mice). The bias shift is not (p = 0.154), as in the paper.
fig3s4-looser-criterion¶
With a looser proficiency criterion (80% correct on easy trials over three sessions, n = 150 mice), behavior was again consistent across laboratories; only the number of trials per session differed slightly, and a classifier failed to identify a mouse's laboratory.
For each mouse, basic-task sessions with five or more signed contrasts; the first three consecutive such sessions each above 80% correct on easy trials.
ses_tr = Sc[Sc.task == "training"].sort_values("start")
st = Tm[Tm.task == "training"].groupby("session_id").agg(perf=("correct", lambda x: np.nan), n_signed=("signed_contrast", "nunique"))
st["perf"] = Tm[Tm.task == "training"].groupby("session_id").apply(ib.perf_easy, include_groups=False)
ses_tr = ses_tr.join(st, on="session_id")
ses_tr = ses_tr[ses_tr.n_signed >= 5]
loose = {}
for sid, d in ses_tr.groupby("subject_id"):
ok = (d.perf > 80).to_numpy()
for j in range(2, len(d)):
if ok[j - 2: j + 1].all():
loose[sid] = d.session_id.iloc[j - 2: j + 1].tolist()
break
print("mice meeting the looser criterion:", len(loose), "| within 150 +- 15:", abs(len(loose) - 150) <= 15)
print("by lab:", lab[list(loose)].value_counts().sort_index().to_dict())
tl = Tm[Tm.session_id.isin({x for v in loose.values() for x in v})]
fl = ib.mouse_fits(tl)
g = tl.groupby("subject_id")
sl = Sc[Sc.session_id.isin(tl.session_id)]
vl = pd.DataFrame({"perf_easy": g.apply(ib.perf_easy, include_groups=False), "rt": g.rt.median(),
"n_trials": sl.groupby("subject_id").n_trials.mean(), "threshold": fl.threshold, "bias": fl.bias,
"trials_per_min": (sl.n_trials / sl.duration_min).groupby(sl.subject_id).mean()})
vl["lab"] = lab[vl.index]
p = np.array([ib.lab_test(vl[x], vl.lab, "kruskal") for x in VARS])
pc = np.array([ib.lab_test(vl[x], vl.lab, "code") for x in VARS])
print(pd.DataFrame({"kruskal": p, "kruskal_fdr": ib.fdr(p), "code_switch_fdr": ib.fdr(pc)}, index=VARS).round(4))
pf = pd.Series(ib.fdr(p), index=VARS)
print("trials per session corrected p < 0.05:", pf["n_trials"] < 0.05,
"| other five >= 0.05:", bool((pf.drop("n_trials") >= 0.05).all()))
mice meeting the looser criterion: 91 | within 150 +- 15: False
by lab: {'Lab 1': 12, 'Lab 2': 13, 'Lab 3': 29, 'Lab 4': 7, 'Lab 5': 8, 'Lab 6': 15, 'Lab 7': 7}
kruskal kruskal_fdr code_switch_fdr perf_easy 0.2664 0.3197 0.3197 rt 0.0398 0.0775 0.0775 n_trials 0.0004 0.0022 0.0019 threshold 0.0517 0.0775 0.0775 bias 0.9153 0.9153 0.9463 trials_per_min 0.0007 0.0022 0.0022 trials per session corrected p < 0.05: True | other five >= 0.05: False
The classifier part of this claim runs in the section on the lab classifiers below, which gives its conclusion.
First full-task sessions (P1b)¶
Claims file header, answer of 2026-10-22. Main reading: P1b is the first full-task (biased protocol) session starting at or after the P1 session. Variant, the code's: the first full-task session at or after the first session meeting the 1b criteria (the pipeline gives a biased session status trained_1b when the mouse had it before or its last three sessions meet the 1b criteria); a mouse that never meets them has no P1b. The variant is run under the main reading of P1.
def p1b_day(r, kind):
"""Training day of the first full-task (biased protocol) session starting at or after P1
(legend, main) or at or after the first session meeting the 1b criteria (code, variant)."""
p = P1[r]
ref = p.p1_session if kind == "legend" else p.b1_session.dropna()
start = Sc.set_index("session_id").start
s0 = pd.Series(start.reindex(ref.to_numpy()).to_numpy(), index=ref.index)
ses = Sc[(Sc.task == "biased") & Sc.subject_id.isin(s0.index)]
ses = ses[ses.start >= ses.subject_id.map(s0)].sort_values("start").groupby("subject_id").first()
return pd.Series([int(tday[(s, d)]) for s, d in zip(ses.index, ses.date)], index=ses.index, dtype=int)
PB = [(MAIN, "legend"), (MAIN, "code")] + [(r, "legend") for r in READINGS[1:]]
for r in READINGS:
RN[(r, "legend")] = RN[r]
RN[(MAIN, "code")] = "main, code P1b"
P1b = {k: p1b_day(*k) for k in PB}
print("mice with a P1b:", {RN[k]: len(P1b[k]) for k in PB})
for k in PB[:2]:
print(f"days from P1 to P1b ({RN[k]}):", (P1b[k] - P1[MAIN].p1_tday0.reindex(P1b[k].index))
.describe()[["min", "50%", "max"]].to_dict())
print("main-reading mice with P1 but no 1b status (no code P1b possible):",
int(P1[MAIN].b1_session.isna().sum()), "| with 1b but no biased session after it:",
int(P1[MAIN].b1_session.notna().sum() - len(P1b[(MAIN, "code")])))
mice with a P1b: {'main': 72, 'main, code P1b': 66, 'contrasts:last': 73, '1b-replace': 69, '1b-replace,contrasts:last': 69}
days from P1 to P1b (main): {'min': 0.0, '50%': 3.0, 'max': 53.0}
days from P1 to P1b (main, code P1b): {'min': 0.0, '50%': 4.0, 'max': 53.0}
main-reading mice with P1 but no 1b status (no code P1b possible): 16 | with 1b but no biased session after it: 1
fig3s5-first-full-sessions¶
In the first three sessions of the full task, bias in each block, contrast threshold in each block and performance on 100% contrast trials did not vary significantly across laboratories, and a classifier could not predict lab membership.
def first_full(r, how):
if how == "legend: first three biased days":
t = Tm[Tm.subject_id.isin(P1b[r].index) & (Tm.task == "biased")]
t = t[t.tday0 >= t.subject_id.map(P1b[r])]
firstdays = t.groupby("subject_id").tday0.apply(lambda x: sorted(x.unique())[:3])
return t[[d in firstdays[s] for s, d in zip(t.subject_id, t.tday0)]]
return ib.window(Tm, P1b[r], 1, 3, ["biased"])
ff = {}
rows = []
for r in PB:
# the code's sessions, a variant, for the main reading of P1 only
for how in ("legend: first three biased days", "code: days P1b+1 to P1b+3")[: 2 if r in PB[:2] else 1]:
t = first_full(r, how)
t = t.assign(block=np.select([np.isclose(t.probabilityLeft, 0.2), np.isclose(t.probabilityLeft, 0.8)],
["2080", "8020"], "5050"))
fits = ib.mouse_fits(t, by=("subject_id", "block")).unstack("block")
v = pd.DataFrame({f"{p}_{b}": fits[(p, b)] for p in ("bias", "threshold") for b in ("2080", "5050", "8020")})
v["perf_100"] = t[t.abs_contrast == 100].groupby("subject_id").correct.mean() * 100
v["perf_easy_code"] = t[t.abs_contrast >= 50].groupby("subject_id").correct.mean() * 100
v["lab"] = lab[v.index]
ff[(r, how)] = v
ps = {c: ib.lab_test(v[c], v.lab, "kruskal") for c in v.columns if c not in ("lab", "perf_easy_code")}
from statsmodels.stats.multitest import multipletests
holm = multipletests(list(ps.values()), method="holm-sidak")[1]
rows.append(dict(reading=RN[r], sessions=how, mice=len(v), **{k: round(x, 3) for k, x in ps.items()},
p_perf_easy_code=round(ib.lab_test(v.perf_easy_code, v.lab, "kruskal"), 3),
min_p=min(ps.values()), min_p_holm=holm.min(), all_ns=min(ps.values()) >= 0.05))
print(pd.DataFrame(rows).to_string())
reading sessions mice bias_2080 bias_5050 bias_8020 threshold_2080 threshold_5050 threshold_8020 perf_100 p_perf_easy_code min_p min_p_holm all_ns 0 main legend: first three biased days 72 0.896 0.983 0.434 0.022 0.038 0.053 0.022 0.022 0.021550 0.141443 False 1 main code: days P1b+1 to P1b+3 70 0.658 0.772 0.217 0.007 0.011 0.004 0.001 0.001 0.001396 0.009730 False 2 main, code P1b legend: first three biased days 66 0.960 0.680 0.612 0.007 0.041 0.012 0.155 0.155 0.006621 0.045436 False 3 main, code P1b code: days P1b+1 to P1b+3 66 0.425 0.474 0.099 0.022 0.029 0.007 0.091 0.091 0.007036 0.048227 False 4 contrasts:last legend: first three biased days 73 0.938 0.957 0.425 0.012 0.073 0.062 0.011 0.011 0.010733 0.072752 False 5 1b-replace legend: first three biased days 69 0.955 0.592 0.558 0.023 0.028 0.046 0.129 0.129 0.023340 0.152375 False 6 1b-replace,contrasts:last legend: first three biased days 69 0.938 0.620 0.546 0.025 0.031 0.047 0.143 0.143 0.024842 0.161458 False
The classifier part of this claim runs in the section on the lab classifiers below, which gives its conclusion.
fig3s5a-prior-used-from-first-sessions¶
Mice incorporated the block priors into their choices from the first sessions of the full task.
rows = []
for (r, how), v in ff.items():
d = (v.bias_8020 - v.bias_2080).dropna()
w = stats.wilcoxon(v.bias_8020, v.bias_2080, nan_policy="omit")
rows.append(dict(reading=RN[r], sessions=how, n=len(d), median_diff=d.median(), positive=f"{int((d > 0).sum())}/{len(d)}",
p=w.pvalue, above_5=f"{int((d > 5).sum())}/{len(d)}", ok=d.median() > 0 and w.pvalue < 0.05))
print(pd.DataFrame(rows).to_string(float_format=lambda x: f"{x:.4g}"))
reading sessions n median_diff positive p above_5 ok 0 main legend: first three biased days 72 4.453 69/72 2.134e-13 31/72 True 1 main code: days P1b+1 to P1b+3 70 4.712 68/70 1.961e-12 33/70 True 2 main, code P1b legend: first three biased days 66 5.834 65/66 1.718e-12 36/66 True 3 main, code P1b code: days P1b+1 to P1b+3 66 6.398 65/66 1.799e-12 39/66 True 4 contrasts:last legend: first three biased days 73 4.348 70/73 1.452e-13 30/73 True 5 1b-replace legend: first three biased days 69 4.988 67/69 5.949e-13 34/69 True 6 1b-replace,contrasts:last legend: first three biased days 69 4.988 67/69 5.949e-13 34/69 True
Result: reproduced. In the first full-task sessions bias is higher in 80:20 than in 20:80 blocks under every reading (main, legend sessions: median difference 4.45, 69 of 72 mice, Wilcoxon p = 2.1e-13; over all readings the median difference is 4.35 to 6.40 and p is 2.0e-12 or smaller). Between 30 of 73 and 39 of 66 mice exceed the proficiency threshold of 5, a variant.
full-task-training-time¶
Mice that reached full task proficiency took 31.5 +- 16.1 days, or 20,494 +- 10,980 trials (s.d., n = 98), from the start of training; the fastest took 8 days (4691 trials), the slowest 81 days (61,316 trials).
nd = P2.p2_tday0 + 1
dd = Dc[Dc.subject_id.isin(nd.index)]
ntr = dd[dd.tday0 < dd.subject_id.map(nd)].groupby("subject_id").n_trials.sum()
EXP_FT = [(31.5, 3.15), (16.1, 1.61), (20494, 2049), (10980, 1098), (8, 0.8), (81, 8.1), (4691, 469), (61316, 6132)]
v = [nd.mean(), nd.std(), ntr.mean(), ntr.std(), nd.min(), nd.max(), ntr.min(), ntr.max()]
for (e, t), x, name in zip(EXP_FT, v, ["mean days", "sd days", "mean trials", "sd trials", "min days", "max days",
"min trials", "max trials"]):
print(f"{name}: {x:.1f} (paper {e}, within tolerance: {abs(x - e) <= t})")
print("mice:", len(nd), "| by lab:", lab[nd.index].value_counts().sort_index().to_dict())
active = Dc.groupby("subject_id").date.max() >= "2020-03-16"
print("last date of the dataset", Dc.date.max(), "| whole-training mice without P2 with a session in its last week:",
int((active & ~active.index.isin(P2.index)).sum()))
mean days: 29.4 (paper 31.5, within tolerance: True)
sd days: 14.1 (paper 16.1, within tolerance: False)
mean trials: 19637.3 (paper 20494, within tolerance: True)
sd trials: 9173.4 (paper 10980, within tolerance: False)
min days: 10.0 (paper 8, within tolerance: False)
max days: 64.0 (paper 81, within tolerance: False)
min trials: 5592.0 (paper 4691, within tolerance: False)
max trials: 43500.0 (paper 61316, within tolerance: False)
mice: 60 | by lab: {'Lab 1': 9, 'Lab 2': 7, 'Lab 3': 21, 'Lab 4': 5, 'Lab 5': 7, 'Lab 6': 6, 'Lab 7': 5}
last date of the dataset 2020-03-23 | whole-training mice without P2 with a session in its last week: 30
Result: partially reproduced. The 60 mice that reach full task proficiency take 29.4 +- 14.1 days and 19,637 +- 9,173 trials: the means are within tolerance, the s.d.s are not (16.1 and 10,980 in the paper). The fastest takes 10 days (5,592 trials) and the slowest 64 days (43,500 trials), against 8 (4,691) and 81 (61,316). 30 mice without P2 were still training in the dataset's last week, which cuts off slow learners.
fig4cd-biasshift-largest-at-zero¶
Block structure had the greatest effect on choices when sensory evidence was absent; the shift in rightward choices between 20:80 and 80:20 blocks was highest at 0% contrast in every laboratory, averaging 28.5%.
CON = sorted(S2t.signed_contrast.unique())
def curve(row, b, c):
p = {k: row[(k, b)] for k in ("bias", "threshold", "lapselow", "lapsehigh")}
return 100 * ib.gamma_curve(p, c)
sh = pd.DataFrame({c: [curve(S2fits.loc[m], "2080", c) - curve(S2fits.loc[m], "8020", c) for m in S2fits.index]
for c in CON}, index=S2fits.index)
print("signed contrasts:", CON)
print("mean shift over mice by contrast:", sh.mean().round(2).to_dict())
by_lab = sh.groupby(lab[sh.index]).mean()
print(by_lab.round(1).to_string())
at0 = sh[0.0]
print(f"mean shift at 0%: {at0.mean():.2f} (n = {at0.notna().sum()}), within 28.5 +- 2.85: {abs(at0.mean() - 28.5) <= 2.85}")
print("labs whose mean shift is highest at 0%:", int((by_lab.idxmax(axis=1) == 0.0).sum()), "of", len(by_lab),
"| argmax per lab:", by_lab.idxmax(axis=1).to_dict())
signed contrasts: [np.float64(-100.0), np.float64(-25.0), np.float64(-12.5), np.float64(-6.25), np.float64(0.0), np.float64(6.25), np.float64(12.5), np.float64(25.0), np.float64(100.0)]
mean shift over mice by contrast: {-100.0: 1.72, -25.0: 5.33, -12.5: 15.64, -6.25: 23.53, 0.0: 28.0, 6.25: 24.58, 12.5: 16.75, 25.0: 6.31, 100.0: 1.88}
-100.00 -25.00 -12.50 -6.25 0.00 6.25 12.50 25.00 100.00
lab_number
Lab 1 2.2 3.8 11.5 20.4 29.9 26.9 17.2 6.1 0.1
Lab 2 1.7 7.9 18.1 22.9 24.8 22.8 17.6 6.4 1.3
Lab 3 1.7 6.0 16.9 24.3 27.4 23.7 16.6 6.5 2.6
Lab 4 2.2 2.8 11.8 22.4 26.0 17.4 7.6 1.1 0.5
Lab 5 0.8 3.9 14.5 23.7 28.6 26.2 17.5 9.5 4.2
Lab 6 2.3 7.6 21.9 31.4 36.2 32.3 22.9 8.6 3.2
Lab 7 1.2 3.4 12.1 18.4 23.0 22.2 16.1 3.8 -0.7
mean shift at 0%: 28.00 (n = 60), within 28.5 +- 2.85: True
labs whose mean shift is highest at 0%: 7 of 7 | argmax per lab: {'Lab 1': 0.0, 'Lab 2': 0.0, 'Lab 3': 0.0, 'Lab 4': 0.0, 'Lab 5': 0.0, 'Lab 6': 0.0, 'Lab 7': 0.0}
Result: reproduced. The mean shift in fitted rightward choices between 20:80 and 80:20 blocks is 28.00% at 0% contrast (60 mice; within 28.5 +- 2.85), and in each of the 7 labs the lab mean is highest at 0%.
fig4de-biasshift-no-lab-difference¶
The bias shift at 0% contrast did not differ across laboratories more than within them.
import statsmodels.formula.api as smf
import statsmodels.api as sm
dfa = pd.DataFrame({"shift": at0, "lab": lab[at0.index]}).dropna()
aov = sm.stats.anova_lm(smf.ols("shift ~ C(lab)", data=dfa).fit(), typ=2)
print(aov)
print("p >= 0.05:", aov["PR(>F)"].iloc[0] >= 0.05, "| lab means:", dfa.groupby("lab")["shift"].mean().round(1).to_dict())
sum_sq df F PR(>F)
C(lab) 660.716909 6.0 2.069664 0.072399
Residual 2819.942660 53.0 NaN NaN
p >= 0.05: True | lab means: {'Lab 1': 29.9, 'Lab 2': 24.8, 'Lab 3': 27.4, 'Lab 4': 26.0, 'Lab 5': 28.6, 'Lab 6': 36.2, 'Lab 7': 23.0}
Result: reproduced. The one-way ANOVA of the shift at 0% across labs gives F = 2.07, p = 0.072 (paper F = 1.345, p = 0.2455), with lab means from 23.0 to 36.2%.
fig4f, fig4gh, fig4i: block effects on the psychometric parameters¶
Block type did not significantly affect the contrast threshold.
Block type changed lapse rates, which were higher on the left in 20:80 blocks and higher on the right in 80:20 blocks.
Block type changed the overall bias consistently, with curves shifting left in 20:80 blocks and right in 80:20 blocks.
def wil(a, b):
d = (a - b).dropna()
return d.median(), stats.wilcoxon(a, b, nan_policy="omit").pvalue, int((d > 0).sum()), len(d)
md_, p, npos, n = wil(S2fits[("threshold", "2080")], S2fits[("threshold", "8020")])
print(f"threshold 20:80 - 80:20: median {md_:.2f}, {npos}/{n} positive, Wilcoxon p = {p:.4g}; p >= 0.05: {p >= 0.05}")
threshold 20:80 - 80:20: median 0.08, 31/60 positive, Wilcoxon p = 0.7967; p >= 0.05: True
Result: reproduced. The threshold does not differ between 20:80 and 80:20 blocks (median difference 0.08, 31 of 60 positive, Wilcoxon p = 0.80; paper p = 0.85).
m1, p1, n1, n = wil(S2fits[("lapselow", "2080")], S2fits[("lapselow", "8020")])
m2, p2, n2, _ = wil(S2fits[("lapsehigh", "8020")], S2fits[("lapsehigh", "2080")])
print(f"left lapse, 20:80 - 80:20: median {m1:.4f}, {n1}/{n} positive, p = {p1:.3g}")
print(f"right lapse, 80:20 - 20:80: median {m2:.4f}, {n2}/{n} positive, p = {p2:.3g}")
print("directions hold:", m1 > 0 and m2 > 0, "| p < 1e-6 and < 1e-7:", p1 < 1e-6 and p2 < 1e-7,
"| both p < 0.05:", p1 < 0.05 and p2 < 0.05)
print("smallest p a Wilcoxon test can give with n = %d (normal approximation, all differences one sign): %.2g"
% (n, stats.wilcoxon(np.arange(1, n + 1)).pvalue))
left lapse, 20:80 - 80:20: median 0.0150, 46/60 positive, p = 2.29e-06 right lapse, 80:20 - 20:80: median 0.0181, 45/60 positive, p = 2.23e-05 directions hold: True | p < 1e-6 and < 1e-7: False | both p < 0.05: True smallest p a Wilcoxon test can give with n = 60 (normal approximation, all differences one sign): 1.6e-11
Result: partially reproduced. The left lapse is higher in 20:80 blocks (median difference 0.015, 46 of 60 mice, p = 2.3e-06) and the right lapse higher in 80:20 blocks (0.018, 45 of 60, p = 2.2e-05). The directions hold with p < 0.05, but not with p < 1e-6 and < 1e-7.
m3, p3, n3, n = wil(S2fits[("bias", "8020")], S2fits[("bias", "2080")])
print(f"bias 80:20 - 20:80: median {m3:.2f}, {n3}/{n} positive, p = {p3:.3g}")
print("direction holds:", m3 > 0, "| p < 1e-16:", p3 < 1e-16, "| p < 0.05:", p3 < 0.05)
bias 80:20 - 20:80: median 7.11, 60/60 positive, p = 1.63e-11 direction holds: True | p < 1e-16: False | p < 0.05: True
Result: partially reproduced. Bias is higher in 80:20 than in 20:80 blocks in all 60 mice (median difference 7.11, p = 1.6e-11). This is the smallest p the test gives with 60 mice, so the paper's p < 1e-16 (98 mice) cannot be reached, and the criterion gives partial.
fig4fi-no-lab-difference¶
Threshold, lapses and bias in each block type showed no significant differences across laboratories.
v8 = pd.DataFrame({f"{p}_{b}": S2fits[(p, b)] for p in ("threshold", "lapselow", "lapsehigh", "bias")
for b in ("8020", "2080")})
pv = np.array([ib.lab_test(v8[c], lab[v8.index], "code") for c in v8.columns])
pk = np.array([ib.lab_test(v8[c], lab[v8.index], "kruskal") for c in v8.columns])
print(pd.DataFrame({"code_switch": pv, "code_switch_fdr": ib.fdr(pv), "kruskal_fdr": ib.fdr(pk)}, index=v8.columns).round(4))
print("all eight corrected p >= 0.05:", bool((ib.fdr(pv) >= 0.05).all()))
code_switch code_switch_fdr kruskal_fdr threshold_8020 0.0630 0.1892 0.1878 threshold_2080 0.0946 0.1892 0.1878 lapselow_8020 0.0898 0.1892 0.1878 lapselow_2080 0.5039 0.6719 0.6719 lapsehigh_8020 0.0371 0.1892 0.1878 lapsehigh_2080 0.2758 0.4412 0.4412 bias_8020 0.8292 0.8803 0.8958 bias_2080 0.8803 0.8803 0.9017 all eight corrected p >= 0.05: True
Result: reproduced. None of the eight per-block parameters differs across labs after correction (corrected p 0.19 to 0.88).
Lab classifiers (fig3f-classifier-chance-basic, fig3f-positive-control, fig3s3-other-classifiers, fig4j-classifier-chance-full, and the classifier parts of fig3s4-looser-criterion and fig3s5-first-full-sessions)¶
A Naive Bayes classifier could not identify a mouse's laboratory from its basic-task performance, threshold and bias; its accuracy was 0.12 +- 0.051 against a chance level of 0.11, and the 95% range of its distribution included chance.
With the laboratory's time zone added as a feature, the classifier performed above chance and confused labs in the same time zone.
Random Forest and Logistic Regression classifiers also failed to predict laboratory membership from basic-task behavior.
A classifier trained on the full-task psychometric parameters could not predict the laboratory of individual mice above chance.
The classifier draws the same number of mice from each lab, 2000 times, with leave-one-out cross-validation and a null from shuffled lab labels (claims file header, Lab classifier). The subsample size follows the Methods' rule (answer of 2026-10-22): the lowest number of mice per lab over all the datasets classified, one size for every classifier claim. The datasets are those of the main reading: S1 (fig3f, fig3s3), S2 (fig4j), the looser criterion (fig3s4) and the first full-task sessions (fig3s5). The code's 8 mice per lab is a variant. A classifier is above chance when the 2.5th percentile of its accuracies is above the mean shuffled accuracy.
from sklearn.naive_bayes import GaussianNB
from sklearn.linear_model import LogisticRegression
from sklearn.multiclass import OneVsRestClassifier
from sklearn.model_selection import LeaveOneOut, cross_val_predict
F_S1 = ["perf_easy", "threshold", "bias"]
F_FF = ["bias_2080", "bias_5050", "bias_8020", "threshold_2080", "threshold_5050", "threshold_8020", "perf_100"]
LEGEND = "legend: first three biased days"
CLF_DATA = {
"S1": S1[MAIN][S1[MAIN].rt.notna()].dropna(subset=F_S1),
"S2": v8.dropna().assign(lab=lab[v8.dropna().index].to_numpy()),
"looser criterion": vl.dropna(subset=F_S1),
"first full-task sessions": ff[((MAIN, "legend"), LEGEND)].dropna(subset=F_FF),
}
clf_counts = pd.DataFrame({k: v.lab.value_counts() for k, v in CLF_DATA.items()}).reindex(ib.LABS).fillna(0).astype(int)
print(clf_counts.to_string())
K = int(clf_counts.min().min())
print("mice per lab drawn (lowest count over the datasets):", K,
"| datasets with a lab under 8 (the code's size cannot run):", list(clf_counts.columns[clf_counts.min() < 8]))
# The direct leave-one-out classifiers against scikit-learn, on subsamples of S1 with true and shuffled labels
rng_chk = np.random.default_rng(5)
d = CLF_DATA["S1"]
X1, y1 = d[F_S1].to_numpy(), d.lab.to_numpy()
agree_nb, agree_lr = [], []
for k in range(20):
idx = np.concatenate([rng_chk.choice(np.flatnonzero(y1 == l), K, replace=False) for l in ib.LABS])
ys = y1[idx] if k % 2 else rng_chk.permutation(y1[idx])
agree_nb.append(np.mean(ib.loo_gaussian_nb(X1[idx], ys) == cross_val_predict(GaussianNB(), X1[idx], ys, cv=LeaveOneOut())))
agree_lr.append(np.mean(ib.loo_ovr_logistic(X1[idx], ys) == cross_val_predict(
OneVsRestClassifier(LogisticRegression(solver="liblinear")), X1[idx], ys, cv=LeaveOneOut())))
print(f"agreement with scikit-learn over 20 subsamples: GaussianNB {np.mean(agree_nb):.4f}, "
f"one-vs-rest liblinear LogisticRegression {np.mean(agree_lr):.4f}")
def run_clf(name, X, labs, kind="nb", n_iter=2000, **kw):
out = ib.classify_labs(X, labs, kind, n_iter=n_iter, per_lab=K, **kw)
acc, null = out[0], out[1]
row = dict(classifier=name, mice=len(labs), per_lab=K, n_iter=n_iter, acc_mean=acc.mean(), acc_sd=acc.std(),
acc_p2_5=np.percentile(acc, 2.5), acc_p97_5=np.percentile(acc, 97.5), null_mean=null.mean(),
above_chance=np.percentile(acc, 2.5) > null.mean())
return row, out
CLF = {}
rows = []
for name, data, feats, kind in (("fig3f: Naive Bayes, S1", "S1", F_S1, "nb"),
("fig3s3: Logistic Regression, S1", "S1", F_S1, "lr"),
("fig4j: Naive Bayes, S2", "S2", list(v8.columns), "nb"),
("fig3s4: Naive Bayes, looser criterion", "looser criterion", F_S1, "nb"),
("fig3s5: Naive Bayes, first full-task sessions", "first full-task sessions", F_FF, "nb")):
d = CLF_DATA[data]
row, CLF[name] = run_clf(name, d[feats].to_numpy(), d.lab.to_numpy(), kind)
rows.append(row)
d = CLF_DATA["S1"]
Xtz = np.column_stack([d[F_S1].to_numpy(), d.lab.map(ib.TIME_ZONE).to_numpy()])
row, CLF["fig3f-positive-control"] = run_clf("fig3f-positive-control: Naive Bayes, S1 + time zone", Xtz, d.lab.to_numpy(),
"nb", return_confusion=True)
rows.append(row)
clf_tab = pd.DataFrame(rows).set_index("classifier")
print(clf_tab.round(3).to_string())
S1 S2 looser criterion first full-task sessions lab Lab 1 12 9 12 12 Lab 2 12 7 13 7 Lab 3 25 21 29 25 Lab 4 7 5 7 6 Lab 5 8 7 8 7 Lab 6 11 6 15 10 Lab 7 6 5 7 5 mice per lab drawn (lowest count over the datasets): 5 | datasets with a lab under 8 (the code's size cannot run): ['S1', 'S2', 'looser criterion', 'first full-task sessions']
agreement with scikit-learn over 20 subsamples: GaussianNB 1.0000, one-vs-rest liblinear LogisticRegression 1.0000
mice per_lab n_iter acc_mean acc_sd acc_p2_5 acc_p97_5 null_mean above_chance classifier fig3f: Naive Bayes, S1 81 5 2000 0.140 0.063 0.029 0.286 0.106 False fig3s3: Logistic Regression, S1 81 5 2000 0.071 0.054 0.000 0.200 0.070 False fig4j: Naive Bayes, S2 60 5 2000 0.176 0.046 0.086 0.286 0.107 False fig3s4: Naive Bayes, looser criterion 91 5 2000 0.117 0.058 0.029 0.229 0.110 False fig3s5: Naive Bayes, first full-task sessions 72 5 2000 0.170 0.048 0.086 0.257 0.114 False fig3f-positive-control: Naive Bayes, S1 + time zone 81 5 2000 0.405 0.084 0.257 0.571 0.118 True
# Positive control: the code's second threshold, and the mean confusion matrix (rows: true lab)
acc_pc, null_pc, names, conf = CLF["fig3f-positive-control"]
print(f"positive control, 0.001th percentile {np.percentile(acc_pc, 0.001):.3f} against the null mean {null_pc.mean():.3f}")
print(pd.DataFrame(conf, index=names, columns=names).round(3).to_string())
tz = np.array([ib.TIME_ZONE[l] for l in names])
same = (tz[:, None] == tz[None, :]) & ~np.eye(len(names), dtype=bool)
other = tz[:, None] != tz[None, :]
print(f"off-diagonal mass, same time zone: total {conf[same].sum():.3f} over {same.sum()} cells (mean {conf[same].mean():.4f}); "
f"other time zones: total {conf[other].sum():.3f} over {other.sum()} cells (mean {conf[other].mean():.4f})")
print("diagonal (correct) by lab:", dict(zip(names, np.round(np.diag(conf), 3))))
positive control, 0.001th percentile 0.171 against the null mean 0.118
Lab 1 Lab 2 Lab 3 Lab 4 Lab 5 Lab 6 Lab 7
Lab 1 0.258 0.376 0.000 0.000 0.000 0.367 0.0
Lab 2 0.301 0.278 0.000 0.000 0.000 0.422 0.0
Lab 3 0.000 0.000 0.476 0.153 0.370 0.000 0.0
Lab 4 0.000 0.000 0.155 0.375 0.470 0.000 0.0
Lab 5 0.000 0.000 0.325 0.460 0.215 0.000 0.0
Lab 6 0.351 0.416 0.000 0.000 0.000 0.233 0.0
Lab 7 0.000 0.000 0.000 0.000 0.000 0.000 1.0
off-diagonal mass, same time zone: total 4.166 over 12 cells (mean 0.3472); other time zones: total 0.000 over 30 cells (mean 0.0000)
diagonal (correct) by lab: {np.str_('Lab 1'): np.float64(0.258), np.str_('Lab 2'): np.float64(0.278), np.str_('Lab 3'): np.float64(0.476), np.str_('Lab 4'): np.float64(0.375), np.str_('Lab 5'): np.float64(0.215), np.str_('Lab 6'): np.float64(0.233), np.str_('Lab 7'): np.float64(1.0)}
# Random Forest (fig3s3): 100 trees per fit, 35 fits per subsample and 2000 subsamples with as many
# shuffles, about 8 s per subsample in one process. The 2000 do not fit the notebook's time limit; the
# first N_RF of the same sequence of subsamples run in 4 processes, with a bootstrap interval for the
# 2.5th percentile.
N_RF = 50
t_rf = time.time()
row_rf, CLF["fig3s3: Random Forest, S1"] = run_clf("fig3s3: Random Forest, S1", X1, y1, "rf", n_iter=N_RF, workers=4)
per_sub = (time.time() - t_rf) / N_RF
print(f"Random Forest: {per_sub:.2f} s per subsample in 4 processes; 2000 subsamples would take {2000 * per_sub / 60:.0f} min")
print(pd.Series(row_rf).to_string())
acc_rf, null_rf = CLF["fig3s3: Random Forest, S1"][:2]
rng_bs = np.random.default_rng(12)
bs = np.array([np.percentile(rng_bs.choice(acc_rf, len(acc_rf)), 2.5) for _ in range(5000)])
print(f"2.5th percentile of accuracy {np.percentile(acc_rf, 2.5):.3f}, bootstrap 95% interval "
f"{np.percentile(bs, 2.5):.3f} to {np.percentile(bs, 97.5):.3f}; shuffled mean {null_rf.mean():.3f} "
f"(s.e. {null_rf.std() / np.sqrt(N_RF):.3f}); subsamples with accuracy above the shuffled mean "
f"{int((acc_rf > null_rf.mean()).sum())} of {N_RF}")
for n in (25, 50):
print(f" first {n} subsamples: accuracy {acc_rf[:n].mean():.3f}, 2.5th percentile {np.percentile(acc_rf[:n], 2.5):.3f},"
f" shuffled mean {null_rf[:n].mean():.3f}")
Random Forest: 1.62 s per subsample in 4 processes; 2000 subsamples would take 54 min classifier fig3s3: Random Forest, S1 mice 81 per_lab 5 n_iter 50 acc_mean 0.130286 acc_sd 0.054559 acc_p2_5 0.035 acc_p97_5 0.257143 null_mean 0.1 above_chance False 2.5th percentile of accuracy 0.035, bootstrap 95% interval 0.029 to 0.057; shuffled mean 0.100 (s.e. 0.008); subsamples with accuracy above the shuffled mean 35 of 50 first 25 subsamples: accuracy 0.123, 2.5th percentile 0.046, shuffled mean 0.098 first 50 subsamples: accuracy 0.130, 2.5th percentile 0.035, shuffled mean 0.100
# Variant: the code's 8 mice per lab, where every lab of a dataset holds 8 or more
for data in CLF_DATA:
short = list(clf_counts.index[clf_counts[data] < 8])
print(f"{data}: 8 mice per lab {'cannot run, fewer in ' + ', '.join(short) if short else 'can run'}")
# Variant: Naive Bayes on S1 under the other P1 readings, with the same subsample size
for r in READINGS[1:]:
d = S1[r][S1[r].rt.notna()].dropna(subset=F_S1)
if d.lab.value_counts().reindex(ib.LABS).fillna(0).min() < K:
print(RN[r], "has a lab with fewer than", K, "mice")
continue
row, _ = run_clf(f"Naive Bayes, S1, {RN[r]}", d[F_S1].to_numpy(), d.lab.to_numpy(), "nb")
print(f"{RN[r]}: accuracy {row['acc_mean']:.3f} +- {row['acc_sd']:.3f}, 2.5th percentile {row['acc_p2_5']:.3f}, "
f"null mean {row['null_mean']:.3f}, above chance {row['above_chance']}")
S1: 8 mice per lab cannot run, fewer in Lab 4, Lab 7 S2: 8 mice per lab cannot run, fewer in Lab 2, Lab 4, Lab 5, Lab 6, Lab 7 looser criterion: 8 mice per lab cannot run, fewer in Lab 4, Lab 7 first full-task sessions: 8 mice per lab cannot run, fewer in Lab 2, Lab 4, Lab 5, Lab 7
contrasts:last: accuracy 0.138 +- 0.058, 2.5th percentile 0.029, null mean 0.110, above chance False 1b-replace has a lab with fewer than 5 mice 1b-replace,contrasts:last has a lab with fewer than 5 mice
Result: reproduced. The subsample is 5 mice per lab, the lowest lab count over the four datasets classified (Lab 4 and Lab 7 in S2, Lab 7 in the first full-task sessions). The Naive Bayes classifier on S1 (81 mice) has accuracy 0.140 +- 0.063, within 0.12 +- 0.051, against a shuffled mean of 0.106, within 0.11 +- 0.011. The 2.5th percentile of its accuracies (0.029) is below the shuffled mean, so it is not above chance, as in the paper. Under the pipeline's contrast check the accuracy is 0.138 and the 2.5th percentile 0.029 (null 0.110); the 1b-replace readings leave a lab with fewer than 5 mice. The code's 8 mice per lab cannot run, as Lab 4 and Lab 7 hold 7 and 6 mice in S1.
Result: reproduced. With the lab's time zone as a fourth feature the accuracy is 0.405 +- 0.084, and both the 2.5th percentile (0.257) and the code's 0.001th percentile (0.171) are above the shuffled mean of 0.118. In the mean confusion matrix all off-diagonal mass lies on labs in the same time zone (4.166 over 12 cells, against 0.000 over the 30 cells of other zones); Lab 7, alone in its zone, is always classified correctly.
Result: reproduced. Neither classifier is above chance. The Logistic Regression classifier (liblinear, one-vs-rest, which agrees with scikit-learn on every subsample checked) has accuracy 0.071 +- 0.054 over 2000 subsamples, 2.5th percentile 0.000 against a shuffled mean of 0.070. The Random Forest takes 3.7 s per subsample in 4 processes, so the 2000 subsamples of the criterion (about 2 h) do not fit the notebook's time limit; over the first 50 of the same sequence its accuracy is 0.130 +- 0.055 and its 2.5th percentile 0.035 (bootstrap 95% interval 0.029 to 0.057), below the shuffled mean of 0.100; 35 of the 50 subsamples are above that mean. The first 25 subsamples give the same result (2.5th percentile 0.046 against 0.098).
Result: reproduced. On the eight per-block values of S2 (60 mice), with 5 mice per lab, the Naive Bayes classifier has accuracy 0.176 +- 0.046, and its 2.5th percentile (0.086) is below the shuffled mean of 0.107, so it is not above chance. The code's 8 mice per lab cannot run, as five labs hold fewer at full task proficiency.
Result: partially reproduced. 91 mice meet the looser criterion, against 150 +- 15. Trials per session differ across labs (corrected p = 0.0022), as in the paper, and four of the other five variables do not (corrected p 0.078 to 0.92), but the number of trials per minute does (corrected p = 0.0022), where the paper found no difference. The Naive Bayes classifier, 5 mice per lab, is not above chance, as in the paper (accuracy 0.117 +- 0.058, 2.5th percentile 0.029 against a shuffled mean of 0.110). The claim holds in part: one of the six lab tests and the count differ.
Result: not reproduced. Under the main reading (legend sessions from P1b, the first full-task session at or after P1; 72 mice) the Kruskal-Wallis p is below 0.05 for the threshold in 20:80 blocks (0.022) and in 50:50 blocks (0.038) and for performance on 100% contrast (0.022); the paper's seven p values are 0.078 to 0.96. Every variant also has a p below 0.05 (smallest 0.001 to 0.025, with the code's P1b 0.007); with the code's Holm-Sidak correction, a variant, the smallest is 0.141 under the main reading. The Naive Bayes classifier on the seven variables, 5 mice per lab, is not above chance (accuracy 0.170 +- 0.048, 2.5th percentile 0.086 against a shuffled mean of 0.114).
Probabilistic choice model (fig5cf, fig5dg, fig5s2)¶
Sessions per the code: training days P1b-2 to P1b+3, split by protocol into basic and full; or
(b) the last three basic days before P1b and the first three full days. The 50% contrast, which the
paper does not settle for a mouse shown no 50% trials (answer of 2026-10-22): reading (a), the
Methods' model with the 50% weight left out for that mouse (drop50=False); reading (b), the
code's model, 50% trials dropped for every mouse (drop50=True).
def glm_trials(r, how):
if how == "code: P1b-2..P1b+3":
t = ib.window(Tm, P1b[r], -2, 3, ["training", "biased"])
return t[t.task == "training"], t[t.task == "biased"]
tb = ib.window(Tm, P1b[r], -60, -1, ["training"])
lastdays = tb.groupby("subject_id").tday0.apply(lambda x: sorted(x.unique())[-3:])
tb = tb[[d in lastdays[s] for s, d in zip(tb.subject_id, tb.tday0)]]
tf = ib.window(Tm, P1b[r], 0, 60, ["biased"])
firstdays = tf.groupby("subject_id").tday0.apply(lambda x: sorted(x.unique())[:3])
tf = tf[[d in firstdays[s] for s, d in zip(tf.subject_id, tf.tday0)]]
return tb, tf
GLM = {}
for r in PB:
for how in ("code: P1b-2..P1b+3", "(b) last 3 basic, first 3 full"):
tb, tf = glm_trials(r, how)
for drop50 in (False, True):
items, keys = [], []
for task, t in (("basic", tb), ("full", tf)):
for sid, d in t.groupby("subject_id"):
items.append((ib.glm_design(d, task == "full", drop50), task == "full", drop50))
keys.append((sid, task))
res = ib.fit_glms(items)
df = pd.DataFrame(res, index=pd.MultiIndex.from_tuples(keys, names=["subject_id", "task"]))
GLM[(r, how, drop50)] = df
print("fits:", {f"{RN[k[0]]} | {k[1]} | drop50={k[2]}": f"{len(v)} ({int(v.get('error', pd.Series(dtype=object)).notna().sum())} failed)"
for k, v in GLM.items()})
fits: {'main | code: P1b-2..P1b+3 | drop50=False': '142 (0 failed)', 'main | code: P1b-2..P1b+3 | drop50=True': '142 (0 failed)', 'main | (b) last 3 basic, first 3 full | drop50=False': '144 (0 failed)', 'main | (b) last 3 basic, first 3 full | drop50=True': '144 (0 failed)', 'main, code P1b | code: P1b-2..P1b+3 | drop50=False': '119 (0 failed)', 'main, code P1b | code: P1b-2..P1b+3 | drop50=True': '119 (0 failed)', 'main, code P1b | (b) last 3 basic, first 3 full | drop50=False': '132 (0 failed)', 'main, code P1b | (b) last 3 basic, first 3 full | drop50=True': '132 (0 failed)', 'contrasts:last | code: P1b-2..P1b+3 | drop50=False': '146 (0 failed)', 'contrasts:last | code: P1b-2..P1b+3 | drop50=True': '146 (0 failed)', 'contrasts:last | (b) last 3 basic, first 3 full | drop50=False': '146 (0 failed)', 'contrasts:last | (b) last 3 basic, first 3 full | drop50=True': '146 (0 failed)', '1b-replace | code: P1b-2..P1b+3 | drop50=False': '130 (0 failed)', '1b-replace | code: P1b-2..P1b+3 | drop50=True': '130 (0 failed)', '1b-replace | (b) last 3 basic, first 3 full | drop50=False': '138 (0 failed)', '1b-replace | (b) last 3 basic, first 3 full | drop50=True': '138 (0 failed)', '1b-replace,contrasts:last | code: P1b-2..P1b+3 | drop50=False': '131 (0 failed)', '1b-replace,contrasts:last | code: P1b-2..P1b+3 | drop50=True': '131 (0 failed)', '1b-replace,contrasts:last | (b) last 3 basic, first 3 full | drop50=False': '138 (0 failed)', '1b-replace,contrasts:last | (b) last 3 basic, first 3 full | drop50=True': '138 (0 failed)'}
fig5cf-glm-weights¶
In a logistic choice model fitted to each mouse, visual weights grew with contrast to above 3 at 100% contrast, while weights for past choices were much smaller and positive after both rewarded (basic 0.19, full 0.42) and unrewarded (basic 0.33, full 0.46) trials, indicating perseverance.
EXP_W = [(0.19, 0.019), (0.42, 0.042), (0.33, 0.033), (0.46, 0.046)]
rows = []
for (r, how, drop50), df in GLM.items():
m = df.groupby(level="task").mean(numeric_only=True)
cols = [c for c in ["c6_25", "c12_5", "c25_0", "c50_0", "c100_0"] if c in m.columns]
inc = all(np.all(np.diff(m.loc[t, cols].dropna().to_numpy()) > 0) for t in ("basic", "full"))
w = [m.loc["basic", "rewarded"], m.loc["full", "rewarded"], m.loc["basic", "unrewarded"], m.loc["full", "unrewarded"]]
rows.append(dict(reading=RN[r], sessions=how, drop50=drop50,
n=f"{(df.index.get_level_values('task') == 'basic').sum()},{(df.index.get_level_values('task') == 'full').sum()}",
with_50=int(df.get("c50_0", pd.Series(dtype=float)).notna().sum()),
w100_basic=m.loc["basic", "c100_0"], w100_full=m.loc["full", "c100_0"], increasing=inc,
rew_basic=w[0], rew_full=w[1], unrew_basic=w[2], unrew_full=w[3],
n_hist_in_tol=sum(abs(x - e) <= t for x, (e, t) in zip(w, EXP_W)),
ok=m.loc["basic", "c100_0"] > 3 and m.loc["full", "c100_0"] > 3 and inc and check(w, EXP_W)))
glm_tab = pd.DataFrame(rows)
print(glm_tab.round(4).to_string())
# Mean visual weights per contrast, main reading: over all mice with the weight, and over the mice with every weight
for (r, how, drop50), df in GLM.items():
if r != (MAIN, "legend"):
continue
for task in ("basic", "full"):
x = df.xs(task, level="task")[[c for c in ["c6_25", "c12_5", "c25_0", "c50_0", "c100_0"] if c in df.columns]]
x = x.dropna(axis=1, how="all")
xa = x.dropna()
inc_a = bool(np.all(np.diff(xa.mean().to_numpy()) > 0))
print(f"{how} | drop50={drop50} | {task}: all mice {x.mean().round(3).to_dict()} (n {x.notna().sum().to_dict()});"
f" mice with every weight (n {len(xa)}): {xa.mean().round(3).to_dict()}, increasing {inc_a}")
reading sessions drop50 n with_50 w100_basic w100_full increasing rew_basic rew_full unrew_basic unrew_full n_hist_in_tol ok
0 main code: P1b-2..P1b+3 False 70,72 7 3.6036 3.6005 False 0.2021 0.4299 0.2974 0.4404 4 False
1 main code: P1b-2..P1b+3 True 70,72 0 3.6040 3.6005 True 0.2013 0.4299 0.2966 0.4404 3 False
2 main (b) last 3 basic, first 3 full False 72,72 15 3.4833 3.8300 True 0.2031 0.4009 0.3540 0.3903 3 False
3 main (b) last 3 basic, first 3 full True 72,72 0 3.4850 3.8300 True 0.2023 0.4009 0.3527 0.3903 3 False
4 main, code P1b code: P1b-2..P1b+3 False 53,66 5 4.0252 3.7838 False 0.2022 0.4516 0.2620 0.4559 3 False
5 main, code P1b code: P1b-2..P1b+3 True 53,66 0 4.0245 3.7838 True 0.2019 0.4516 0.2612 0.4559 3 False
6 main, code P1b (b) last 3 basic, first 3 full False 66,66 15 3.6394 4.0424 True 0.2023 0.4313 0.3468 0.4147 4 True
7 main, code P1b (b) last 3 basic, first 3 full True 66,66 0 3.6413 4.0424 True 0.2015 0.4313 0.3454 0.4147 4 True
8 contrasts:last code: P1b-2..P1b+3 False 73,73 9 3.5643 3.5662 False 0.1942 0.4305 0.3020 0.4494 4 False
9 contrasts:last code: P1b-2..P1b+3 True 73,73 0 3.5652 3.5662 True 0.1935 0.4305 0.3005 0.4494 4 True
10 contrasts:last (b) last 3 basic, first 3 full False 73,73 15 3.4779 3.7740 True 0.1993 0.4002 0.3547 0.3940 3 False
11 contrasts:last (b) last 3 basic, first 3 full True 73,73 0 3.4796 3.7740 True 0.1977 0.4002 0.3530 0.3940 3 False
12 1b-replace code: P1b-2..P1b+3 False 61,69 6 3.8424 3.7143 False 0.1904 0.4431 0.2623 0.4486 3 False
13 1b-replace code: P1b-2..P1b+3 True 61,69 0 3.8428 3.7143 True 0.1895 0.4431 0.2614 0.4486 3 False
14 1b-replace (b) last 3 basic, first 3 full False 69,69 15 3.5729 3.9914 True 0.2011 0.4146 0.3521 0.3958 3 False
15 1b-replace (b) last 3 basic, first 3 full True 69,69 0 3.5747 3.9914 True 0.2002 0.4146 0.3507 0.3958 3 False
16 1b-replace,contrasts:last code: P1b-2..P1b+3 False 62,69 7 3.8308 3.7213 False 0.1890 0.4418 0.2684 0.4479 3 False
17 1b-replace,contrasts:last code: P1b-2..P1b+3 True 62,69 0 3.8319 3.7213 True 0.1873 0.4418 0.2671 0.4479 3 False
18 1b-replace,contrasts:last (b) last 3 basic, first 3 full False 69,69 15 3.5729 3.9888 True 0.2011 0.4141 0.3521 0.3895 3 False
19 1b-replace,contrasts:last (b) last 3 basic, first 3 full True 69,69 0 3.5747 3.9888 True 0.2002 0.4141 0.3507 0.3895 3 False
code: P1b-2..P1b+3 | drop50=False | basic: all mice {'c6_25': 0.806, 'c12_5': 1.751, 'c25_0': 2.522, 'c50_0': 8.046, 'c100_0': 3.604} (n {'c6_25': 70, 'c12_5': 70, 'c25_0': 70, 'c50_0': 7, 'c100_0': 70}); mice with every weight (n 7): {'c6_25': 0.929, 'c12_5': 1.552, 'c25_0': 2.351, 'c50_0': 8.046, 'c100_0': 3.249}, increasing False
code: P1b-2..P1b+3 | drop50=False | full: all mice {'c6_25': 0.916, 'c12_5': 1.843, 'c25_0': 2.631, 'c100_0': 3.6} (n {'c6_25': 72, 'c12_5': 72, 'c25_0': 72, 'c100_0': 72}); mice with every weight (n 72): {'c6_25': 0.916, 'c12_5': 1.843, 'c25_0': 2.631, 'c100_0': 3.6}, increasing True
code: P1b-2..P1b+3 | drop50=True | basic: all mice {'c6_25': 0.807, 'c12_5': 1.752, 'c25_0': 2.522, 'c100_0': 3.604} (n {'c6_25': 70, 'c12_5': 70, 'c25_0': 70, 'c100_0': 70}); mice with every weight (n 70): {'c6_25': 0.807, 'c12_5': 1.752, 'c25_0': 2.522, 'c100_0': 3.604}, increasing True
code: P1b-2..P1b+3 | drop50=True | full: all mice {'c6_25': 0.916, 'c12_5': 1.843, 'c25_0': 2.631, 'c100_0': 3.6} (n {'c6_25': 72, 'c12_5': 72, 'c25_0': 72, 'c100_0': 72}); mice with every weight (n 72): {'c6_25': 0.916, 'c12_5': 1.843, 'c25_0': 2.631, 'c100_0': 3.6}, increasing True
(b) last 3 basic, first 3 full | drop50=False | basic: all mice {'c6_25': 0.78, 'c12_5': 1.703, 'c25_0': 2.451, 'c50_0': 3.446, 'c100_0': 3.483} (n {'c6_25': 72, 'c12_5': 72, 'c25_0': 72, 'c50_0': 15, 'c100_0': 72}); mice with every weight (n 15): {'c6_25': 0.837, 'c12_5': 1.614, 'c25_0': 2.206, 'c50_0': 3.446, 'c100_0': 2.886}, increasing False
(b) last 3 basic, first 3 full | drop50=False | full: all mice {'c6_25': 0.945, 'c12_5': 1.88, 'c25_0': 2.683, 'c100_0': 3.83} (n {'c6_25': 72, 'c12_5': 72, 'c25_0': 72, 'c100_0': 72}); mice with every weight (n 72): {'c6_25': 0.945, 'c12_5': 1.88, 'c25_0': 2.683, 'c100_0': 3.83}, increasing True
(b) last 3 basic, first 3 full | drop50=True | basic: all mice {'c6_25': 0.781, 'c12_5': 1.705, 'c25_0': 2.453, 'c100_0': 3.485} (n {'c6_25': 72, 'c12_5': 72, 'c25_0': 72, 'c100_0': 72}); mice with every weight (n 72): {'c6_25': 0.781, 'c12_5': 1.705, 'c25_0': 2.453, 'c100_0': 3.485}, increasing True
(b) last 3 basic, first 3 full | drop50=True | full: all mice {'c6_25': 0.945, 'c12_5': 1.88, 'c25_0': 2.683, 'c100_0': 3.83} (n {'c6_25': 72, 'c12_5': 72, 'c25_0': 72, 'c100_0': 72}); mice with every weight (n 72): {'c6_25': 0.945, 'c12_5': 1.88, 'c25_0': 2.683, 'c100_0': 3.83}, increasing True
Result: partially reproduced. Under the main reading of P1b the 100% contrast weight is above 3 in both tasks (3.48 to 3.83) and the past-choice weights are positive, but no reading has all three parts. On the code's sessions with reading (a), the 50% weight kept for the 7 of 70 mice shown 50% trials in the basic task, all four history weights are within tolerance (rewarded 0.202 and 0.430, unrewarded 0.297 and 0.440, against 0.19, 0.42, 0.33 and 0.46) but the mean visual weights do not increase with contrast; with reading (b), 50% trials dropped, they increase and the basic-task unrewarded weight falls just below 0.297, the edge of its tolerance. With the code's P1b, a variant, the sessions of reading (b) meet all three parts under both 50% readings (rewarded 0.201 to 0.202 and 0.431, unrewarded 0.345 to 0.347 and 0.415), as does the pipeline's contrast check on the code's sessions with 50% trials dropped. The failure of reading (a) to increase is not an effect of averaging the 50% weight over 7 mice and the others over 70: over the 7 mice with every weight the means are 0.93, 1.55, 2.35, 8.05 and 3.25 for 6.25% to 100%, so the 50% weight exceeds the 100% weight in those mice too.
fig5dg-history-weights-higher-full¶
Previous choices influenced behavior more strongly in the full task than in the basic task, after both rewarded and unrewarded trials.
rows = []
for (r, how, drop50), df in GLM.items():
w = df[["rewarded", "unrewarded"]].unstack("task").dropna()
tr = stats.ttest_rel(w[("rewarded", "full")], w[("rewarded", "basic")])
tu = stats.ttest_rel(w[("unrewarded", "full")], w[("unrewarded", "basic")])
rows.append(dict(reading=RN[r], sessions=how, drop50=drop50, n=len(w), t_rew=tr.statistic, p_rew=tr.pvalue,
t_unrew=tu.statistic, p_unrew=tu.pvalue,
ok=tr.statistic > 0 and tu.statistic > 0 and tr.pvalue < 0.05 and tu.pvalue < 0.05))
print(pd.DataFrame(rows).to_string(float_format=lambda x: f"{x:.4g}"))
reading sessions drop50 n t_rew p_rew t_unrew p_unrew ok 0 main code: P1b-2..P1b+3 False 70 9.913 6.669e-15 3.537 0.0007277 True 1 main code: P1b-2..P1b+3 True 70 9.937 6.046e-15 3.556 0.0006851 True 2 main (b) last 3 basic, first 3 full False 72 9.597 1.871e-14 1.046 0.299 False 3 main (b) last 3 basic, first 3 full True 72 9.599 1.852e-14 1.086 0.2812 False 4 main, code P1b code: P1b-2..P1b+3 False 53 8.912 4.748e-12 3.555 0.0008148 True 5 main, code P1b code: P1b-2..P1b+3 True 53 8.917 4.666e-12 3.573 0.0007724 True 6 main, code P1b (b) last 3 basic, first 3 full False 66 10.16 4.643e-15 1.624 0.1093 False 7 main, code P1b (b) last 3 basic, first 3 full True 66 10.12 5.491e-15 1.664 0.101 False 8 contrasts:last code: P1b-2..P1b+3 False 73 10.27 9.324e-16 3.652 0.00049 True 9 contrasts:last code: P1b-2..P1b+3 True 73 10.36 6.379e-16 3.69 0.0004331 True 10 contrasts:last (b) last 3 basic, first 3 full False 73 9.578 1.765e-14 1.083 0.2825 False 11 contrasts:last (b) last 3 basic, first 3 full True 73 9.566 1.862e-14 1.13 0.2623 False 12 1b-replace code: P1b-2..P1b+3 False 61 10.49 3.336e-15 3.775 0.0003693 True 13 1b-replace code: P1b-2..P1b+3 True 61 10.52 2.985e-15 3.794 0.0003469 True 14 1b-replace (b) last 3 basic, first 3 full False 69 9.905 8.051e-15 1.023 0.31 False 15 1b-replace (b) last 3 basic, first 3 full True 69 9.881 8.883e-15 1.056 0.2945 False 16 1b-replace,contrasts:last code: P1b-2..P1b+3 False 62 10.62 1.693e-15 3.566 0.0007129 True 17 1b-replace,contrasts:last code: P1b-2..P1b+3 True 62 10.69 1.314e-15 3.605 0.0006293 True 18 1b-replace,contrasts:last (b) last 3 basic, first 3 full False 69 9.821 1.136e-14 0.8624 0.3915 False 19 1b-replace,contrasts:last (b) last 3 basic, first 3 full True 69 9.831 1.093e-14 0.8964 0.3732 False
Result: reproduced. On the code's sessions both history weights are larger in the full task under every reading and both 50% readings (main: rewarded t = 9.91 and 9.94, unrewarded t = 3.54 and 3.56, p < 0.001; over all readings rewarded t = 8.91 to 10.69 and unrewarded t = 3.54 to 3.79). On the sessions of reading (b) the unrewarded difference is not significant (p = 0.10 to 0.39). As for fig5cf-glm-weights, whose weights this claim tests, the criterion's sessions are the code's, with (b) a reading of the Methods, and the criterion allows a match under one reading.
fig5s2-glm-accuracy¶
The model predicted individual mouse choices well, with cross-validated accuracy of 81.03 +- 5.1% in the basic task and 82.1 +- 5.8% in the full task, similar across laboratories; mean condition numbers were 2.4 and 3.2.
EXP_A = [(81.03, 8.1), (82.1, 8.2), (2.4, 0.24), (3.2, 0.32)]
rows = []
for (r, how, drop50), df in GLM.items():
m = df.groupby(level="task").mean(numeric_only=True)
s = df.groupby(level="task").std(numeric_only=True)
for acc in ("acc_threshold", "acc_prob"):
v = [m.loc["basic", acc], m.loc["full", acc], m.loc["basic", "cond"], m.loc["full", "cond"]]
rows.append(dict(reading=RN[r], sessions=how, drop50=drop50, accuracy=acc,
basic=f"{v[0]:.1f} +- {s.loc['basic', acc]:.1f}", full=f"{v[1]:.1f} +- {s.loc['full', acc]:.1f}",
cond_basic=v[2], cond_full=v[3],
n_in_tol=sum(abs(x - e) <= t for x, (e, t) in zip(v, EXP_A)), ok=check(v, EXP_A)))
print(pd.DataFrame(rows).round(2).to_string())
# spread over fold seeds, one reading
tb, tf = glm_trials(PB[0], "code: P1b-2..P1b+3")
seed_acc = []
for seed in range(5):
items = [(ib.glm_design(d, False, True), False, True, 5, seed) for _, d in tb.groupby("subject_id")]
seed_acc.append(np.mean([x["acc_threshold"] for x in ib.fit_glms(items) if "error" not in x]))
print("basic-task accuracy (main, code sessions, no 50%) over fold seeds 0-4:", np.round(seed_acc, 2))
reading sessions drop50 accuracy basic full cond_basic cond_full n_in_tol ok 0 main code: P1b-2..P1b+3 False acc_threshold 81.9 +- 3.8 83.5 +- 3.0 2.89 3.14 3 False 1 main code: P1b-2..P1b+3 False acc_prob 74.3 +- 4.4 76.4 +- 3.9 2.89 3.14 3 False 2 main code: P1b-2..P1b+3 True acc_threshold 81.9 +- 3.8 83.5 +- 3.0 2.38 3.14 4 True 3 main code: P1b-2..P1b+3 True acc_prob 74.3 +- 4.4 76.4 +- 3.9 2.38 3.14 4 True 4 main (b) last 3 basic, first 3 full False acc_threshold 82.0 +- 3.4 83.7 +- 3.2 3.15 3.14 3 False 5 main (b) last 3 basic, first 3 full False acc_prob 74.1 +- 4.2 76.4 +- 4.0 3.15 3.14 3 False 6 main (b) last 3 basic, first 3 full True acc_threshold 81.9 +- 3.4 83.7 +- 3.2 2.37 3.14 4 True 7 main (b) last 3 basic, first 3 full True acc_prob 74.0 +- 4.2 76.4 +- 4.0 2.37 3.14 4 True 8 main, code P1b code: P1b-2..P1b+3 False acc_threshold 82.8 +- 2.9 84.2 +- 3.0 3.03 3.17 3 False 9 main, code P1b code: P1b-2..P1b+3 False acc_prob 75.6 +- 3.5 77.4 +- 3.7 3.03 3.17 3 False 10 main, code P1b code: P1b-2..P1b+3 True acc_threshold 82.8 +- 2.9 84.2 +- 3.0 2.41 3.17 4 True 11 main, code P1b code: P1b-2..P1b+3 True acc_prob 75.6 +- 3.5 77.4 +- 3.7 2.41 3.17 4 True 12 main, code P1b (b) last 3 basic, first 3 full False acc_threshold 82.6 +- 2.9 84.3 +- 3.1 3.24 3.18 3 False 13 main, code P1b (b) last 3 basic, first 3 full False acc_prob 74.9 +- 3.6 77.5 +- 3.8 3.24 3.18 3 False 14 main, code P1b (b) last 3 basic, first 3 full True acc_threshold 82.5 +- 2.9 84.3 +- 3.1 2.38 3.18 4 True 15 main, code P1b (b) last 3 basic, first 3 full True acc_prob 74.8 +- 3.6 77.5 +- 3.8 2.38 3.18 4 True 16 contrasts:last code: P1b-2..P1b+3 False acc_threshold 81.8 +- 3.9 83.4 +- 3.1 2.91 3.14 3 False 17 contrasts:last code: P1b-2..P1b+3 False acc_prob 74.1 +- 4.5 76.2 +- 3.9 2.91 3.14 3 False 18 contrasts:last code: P1b-2..P1b+3 True acc_threshold 81.8 +- 3.9 83.4 +- 3.1 2.38 3.14 4 True 19 contrasts:last code: P1b-2..P1b+3 True acc_prob 74.1 +- 4.4 76.2 +- 3.9 2.38 3.14 4 True 20 contrasts:last (b) last 3 basic, first 3 full False acc_threshold 81.9 +- 3.4 83.5 +- 3.3 3.12 3.14 3 False 21 contrasts:last (b) last 3 basic, first 3 full False acc_prob 74.0 +- 4.2 76.2 +- 4.1 3.12 3.14 3 False 22 contrasts:last (b) last 3 basic, first 3 full True acc_threshold 81.8 +- 3.4 83.5 +- 3.3 2.37 3.14 4 True 23 contrasts:last (b) last 3 basic, first 3 full True acc_prob 73.9 +- 4.2 76.2 +- 4.1 2.37 3.14 4 True 24 1b-replace code: P1b-2..P1b+3 False acc_threshold 82.4 +- 3.2 84.0 +- 3.1 2.71 3.16 3 False 25 1b-replace code: P1b-2..P1b+3 False acc_prob 75.0 +- 3.9 77.0 +- 4.0 2.71 3.16 3 False 26 1b-replace code: P1b-2..P1b+3 True acc_threshold 82.4 +- 3.2 84.0 +- 3.1 2.39 3.16 4 True 27 1b-replace code: P1b-2..P1b+3 True acc_prob 75.0 +- 3.9 77.0 +- 4.0 2.39 3.16 4 True 28 1b-replace (b) last 3 basic, first 3 full False acc_threshold 82.5 +- 3.0 84.2 +- 3.2 3.19 3.16 3 False 29 1b-replace (b) last 3 basic, first 3 full False acc_prob 74.6 +- 3.8 77.3 +- 4.0 3.19 3.16 3 False 30 1b-replace (b) last 3 basic, first 3 full True acc_threshold 82.3 +- 3.0 84.2 +- 3.2 2.38 3.16 4 True 31 1b-replace (b) last 3 basic, first 3 full True acc_prob 74.5 +- 3.8 77.3 +- 4.0 2.38 3.16 4 True 32 1b-replace,contrasts:last code: P1b-2..P1b+3 False acc_threshold 82.6 +- 3.2 84.0 +- 3.1 2.96 3.16 3 False 33 1b-replace,contrasts:last code: P1b-2..P1b+3 False acc_prob 75.1 +- 3.9 77.0 +- 4.0 2.96 3.16 3 False 34 1b-replace,contrasts:last code: P1b-2..P1b+3 True acc_threshold 82.5 +- 3.2 84.0 +- 3.1 2.40 3.16 4 True 35 1b-replace,contrasts:last code: P1b-2..P1b+3 True acc_prob 75.1 +- 3.9 77.0 +- 4.0 2.40 3.16 4 True 36 1b-replace,contrasts:last (b) last 3 basic, first 3 full False acc_threshold 82.5 +- 3.0 84.2 +- 3.1 3.19 3.16 3 False 37 1b-replace,contrasts:last (b) last 3 basic, first 3 full False acc_prob 74.6 +- 3.8 77.2 +- 3.9 3.19 3.16 3 False 38 1b-replace,contrasts:last (b) last 3 basic, first 3 full True acc_threshold 82.3 +- 3.0 84.2 +- 3.1 2.38 3.16 4 True 39 1b-replace,contrasts:last (b) last 3 basic, first 3 full True acc_prob 74.5 +- 3.8 77.2 +- 3.9 2.38 3.16 4 True
basic-task accuracy (main, code sessions, no 50%) over fold seeds 0-4: [81.86 81.84 81.89 81.88 81.86]
Result: reproduced. Under the main reading, on the code's sessions, with 50% trials dropped (reading (b), the code's model), the cross-validated accuracy (legend reading) is 81.9 +- 3.8% in the basic task and 83.5 +- 3.0% in the full task, and the condition numbers are 2.38 and 3.14: all four within tolerance. With the 50% weight kept for the mice shown 50% trials (reading (a)) the basic-task condition number is 2.89, outside 2.4 +- 0.24, and the other three values are within. The criterion takes the fits of fig5cf-glm-weights, and allows a match under one reading. The code's accuracy reading gives 74.3% and 76.4%, also within tolerance, and accuracy varies by less than 0.1% over fold seeds.
fig5s2-weights-similar-across-labs¶
Fitted model weights and predictive accuracy were similar across laboratories.
rows = []
for (r, how, drop50), df in GLM.items():
ps = {}
for task in ("basic", "full"):
d = df.xs(task, level="task")
cols = ["c6_25", "c12_5", "c25_0", "c100_0", "rewarded", "unrewarded", "Intercept"] + (["block"] if task == "full" else []) \
+ ["pseudo_r2", "acc_threshold"]
for c in cols:
ps[f"{task}:{c}"] = ib.lab_test(d[c], lab[d.index], "code")
ps = pd.Series(ps)
rows.append(dict(reading=RN[r], sessions=how, drop50=drop50, tests=len(ps), n_sig=int((ps < 0.05).sum()),
sig=", ".join(f"{k} {v:.3f}" for k, v in ps[ps < 0.05].items()), min_p=ps.min()))
print(pd.DataFrame(rows).to_string(float_format=lambda x: f"{x:.4g}"))
reading sessions drop50 tests n_sig sig min_p 0 main code: P1b-2..P1b+3 False 19 6 basic:c6_25 0.012, basic:c25_0 0.016, basic:c100_0 0.012, full:c6_25 0.001, full:c25_0 0.020, full:c100_0 0.022 0.001416 1 main code: P1b-2..P1b+3 True 19 6 basic:c6_25 0.011, basic:c25_0 0.016, basic:c100_0 0.012, full:c6_25 0.001, full:c25_0 0.020, full:c100_0 0.022 0.001416 2 main (b) last 3 basic, first 3 full False 19 7 basic:c6_25 0.046, basic:c25_0 0.006, basic:c100_0 0.002, full:c6_25 0.002, full:c12_5 0.030, full:c25_0 0.009, full:c100_0 0.010 0.001636 3 main (b) last 3 basic, first 3 full True 19 7 basic:c6_25 0.043, basic:c25_0 0.006, basic:c100_0 0.002, full:c6_25 0.002, full:c12_5 0.030, full:c25_0 0.009, full:c100_0 0.010 0.001636 4 main, code P1b code: P1b-2..P1b+3 False 19 2 basic:c6_25 0.010, full:c6_25 0.001 0.0007732 5 main, code P1b code: P1b-2..P1b+3 True 19 2 basic:c6_25 0.010, full:c6_25 0.001 0.0007732 6 main, code P1b (b) last 3 basic, first 3 full False 19 4 basic:c6_25 0.026, basic:c25_0 0.010, basic:c100_0 0.002, full:c6_25 0.001 0.001154 7 main, code P1b (b) last 3 basic, first 3 full True 19 4 basic:c6_25 0.025, basic:c25_0 0.011, basic:c100_0 0.002, full:c6_25 0.001 0.001154 8 contrasts:last code: P1b-2..P1b+3 False 19 8 basic:c6_25 0.008, basic:c25_0 0.012, basic:c100_0 0.011, full:c6_25 0.002, full:c12_5 0.048, full:c25_0 0.009, full:c100_0 0.017, full:pseudo_r2 0.039 0.002216 9 contrasts:last code: P1b-2..P1b+3 True 19 8 basic:c6_25 0.007, basic:c25_0 0.013, basic:c100_0 0.012, full:c6_25 0.002, full:c12_5 0.048, full:c25_0 0.009, full:c100_0 0.017, full:pseudo_r2 0.039 0.002216 10 contrasts:last (b) last 3 basic, first 3 full False 19 8 basic:c6_25 0.023, basic:c25_0 0.012, basic:c100_0 0.002, full:c6_25 0.003, full:c12_5 0.020, full:c25_0 0.004, full:c100_0 0.005, full:pseudo_r2 0.042 0.002134 11 contrasts:last (b) last 3 basic, first 3 full True 19 8 basic:c6_25 0.021, basic:c25_0 0.014, basic:c100_0 0.002, full:c6_25 0.003, full:c12_5 0.020, full:c25_0 0.004, full:c100_0 0.005, full:pseudo_r2 0.042 0.002263 12 1b-replace code: P1b-2..P1b+3 False 19 2 basic:c6_25 0.010, full:c6_25 0.001 0.0006488 13 1b-replace code: P1b-2..P1b+3 True 19 2 basic:c6_25 0.009, full:c6_25 0.001 0.0006488 14 1b-replace (b) last 3 basic, first 3 full False 19 4 basic:c6_25 0.022, basic:c25_0 0.013, basic:c100_0 0.003, full:c6_25 0.001 0.0005676 15 1b-replace (b) last 3 basic, first 3 full True 19 4 basic:c6_25 0.021, basic:c25_0 0.014, basic:c100_0 0.003, full:c6_25 0.001 0.0005676 16 1b-replace,contrasts:last code: P1b-2..P1b+3 False 19 2 basic:c6_25 0.006, full:c6_25 0.001 0.0006379 17 1b-replace,contrasts:last code: P1b-2..P1b+3 True 19 2 basic:c6_25 0.006, full:c6_25 0.001 0.0006379 18 1b-replace,contrasts:last (b) last 3 basic, first 3 full False 19 4 basic:c6_25 0.022, basic:c25_0 0.013, basic:c100_0 0.003, full:c6_25 0.001 0.0005685 19 1b-replace,contrasts:last (b) last 3 basic, first 3 full True 19 4 basic:c6_25 0.021, basic:c25_0 0.014, basic:c100_0 0.003, full:c6_25 0.001 0.0005685
Result: not reproduced. Under the main reading 6 (code's sessions) and 7 (sessions of reading (b)) of the 19 lab tests give p < 0.05, under both 50% readings, mostly the visual weights (6.25% contrast in both tasks, p = 0.001 to 0.046), where the criterion allows at most two for partial. With the code's P1b, a variant, 2 and 4 tests do; under the other variants 2 to 8.
fig5s1b-win-stay-lose-switch¶
After correcting for slow fluctuations in decision bound, most mice used a win-stay lose-switch strategy, in both the basic and full tasks.
def history_shift(t, cond_prefix, extra=None):
"""Fitted rightward % at 0% after a right minus after a left choice (of the previous or next
trial), separately after rewarded and unrewarded trials; fits with more than 50 trials."""
out = {}
pairs, keys = [], []
for (sid, rew, side), d in t.groupby(["subject_id", f"{cond_prefix}_reward", f"{cond_prefix}_choice"]):
if side == 0 or len(d) <= 50:
continue
pairs.append((d.signed_contrast.to_numpy(), d.choice_right.to_numpy()))
keys.append((sid, rew, side))
fits = ib.fit_many(pairs)
f = pd.DataFrame(fits, index=pd.MultiIndex.from_tuples(keys, names=["subject_id", "rew", "side"]))
p0 = f.apply(lambda row: 100 * ib.gamma_curve(row, 0.0) if row.notna().all() else np.nan, axis=1)
p0 = p0.unstack("side")
return (p0.get(1.0) - p0.get(-1.0)).unstack("rew")
HIST = {}
def strategy(r, by_contrast=False):
if r not in HIST:
tt = ib.history_columns(ib.window(Tm, P1b[r], -2, 3, ["training", "biased"]))
HIST[r] = tt[tt.choice_right.notna()]
tt = HIST[r]
res = {}
for task, t in (("basic", tt[tt.task == "training"]), ("full", tt[tt.task == "biased"])):
n_by_c = t.signed_contrast.value_counts()
t = t[t.signed_contrast.isin(n_by_c[n_by_c >= 100].index)]
if not by_contrast:
res[task] = history_shift(t, "prev") - history_shift(t, "next")
else:
out = {}
for name, cs in (("0", [0.0]), ("6.25", [6.25]), ("0+6.25", [0.0, 6.25]), ("100", [100.0])):
tp = t[t.prev_contrast.isin(cs) & (t.prev_reward == 1)]
tn = t[t.next_contrast.isin(cs) & (t.next_reward == 1)]
out[name] = (history_shift(tp, "prev") - history_shift(tn, "next")).get(1.0)
res[task] = pd.DataFrame(out)
return res
rows = []
STRAT = {}
for r in PB[:2]:
STRAT[r] = strategy(r)
for task, c in STRAT[r].items():
c = c.dropna()
win, lose = c[1.0], c[0.0]
rows.append(dict(reading=RN[r], task=task, mice=len(c), post_reward_median=win.median(), post_error_median=lose.median(),
frac_win_stay=(win > 0).mean(), frac_lose_switch=(lose < 0).mean(),
frac_both=((win > 0) & (lose < 0)).mean()))
ws = pd.DataFrame(rows)
print(ws.round(3).to_string())
print("\nmore than half with both, in each task, per reading:",
ws.groupby("reading").frac_both.apply(lambda x: bool((x > 0.5).all())).to_dict())
reading task mice post_reward_median post_error_median frac_win_stay frac_lose_switch frac_both
0 main basic 63 4.769 -8.938 0.714 0.762 0.587
1 main full 71 8.590 -9.865 0.972 0.887 0.859
2 main, code P1b basic 47 5.939 -8.975 0.745 0.745 0.596
3 main, code P1b full 66 8.227 -9.904 0.939 0.879 0.833
more than half with both, in each task, per reading: {'main': True, 'main, code P1b': True}
Result: reproduced. After correction, more than half the mice both stay after a reward and switch after an error, in each task (main: basic 0.587 of 63 mice, full 0.859 of 71; code P1b: 0.596 and 0.833). The median corrected shift in the basic task is 4.77% after rewards and -8.94% after errors (main). The P1 variants are not run for this claim, to keep the notebook within its time limit.
fig5s1c-updating-by-contrast¶
After rewarded trials, choice updating was largest when the previous stimulus had low contrast and much smaller after high-contrast rewarded trials.
rows = []
for r in PB[:2]:
res = strategy(r, by_contrast=True)
for task, d in res.items():
m = d.mean()
rows.append(dict(reading=RN[r], task=task, **{f"n_{k}": int(d[k].notna().sum()) for k in d.columns},
**{f"mean_{k}": m[k] for k in d.columns},
each_above_100=m["0"] > m["100"] and m["6.25"] > m["100"], pooled_above_100=m["0+6.25"] > m["100"]))
uc = pd.DataFrame(rows)
print(uc.round(2).to_string())
print("\nper reading, both tasks:", uc.groupby("reading")[["each_above_100", "pooled_above_100"]].all().to_dict())
reading task n_0 n_6.25 n_0+6.25 n_100 mean_0 mean_6.25 mean_0+6.25 mean_100 each_above_100 pooled_above_100
0 main basic 4 63 69 70 15.48 10.87 11.13 5.13 True True
1 main full 65 70 70 71 11.35 8.44 8.83 6.73 True True
2 main, code P1b basic 4 48 51 53 21.81 14.14 14.16 7.18 True True
3 main, code P1b full 66 66 66 66 9.67 9.44 8.18 7.17 True True
per reading, both tasks: {'each_above_100': {'main': True, 'main, code P1b': True}, 'pooled_above_100': {'main': True, 'main, code P1b': True}}
Result: reproduced. After rewarded trials the mean corrected updating after 0% and after 6.25% contrast exceeds that after 100% in both tasks, under the main reading (full task: 11.35 and 8.44 against 6.73%; basic task: 15.48 and 10.87 against 5.13%) and with the code's P1b. In the basic task the 0% value rests on 4 mice, as few 0% trials pass the 50-trial rule; with 0% and 6.25% pooled the result is the same (11.13 against 5.13%).
session-end-criteria¶
The session-ending criterion was not mandatory; 5,316 of 10,903 sessions ended earlier and 5,587 later, the latter continuing for a median of 19 +- 16 extra trials (m.a.d.).
End status from the rig settings (SUBJECT_DISENGAGED_TRIGGERED, _TRIALNUM); for sessions
without one, recomputed from the three criteria of the Figure 1, figure supplement 2 legend.
def end_table(sel, recompute_false=False):
s = S[S.subject_id.isin(sel)].copy()
recompute = s.disengaged.isna()
if recompute_false:
# variant: the status False recomputed from the trials too, as for a missing status
recompute = recompute | s.disengaged.astype(str).isin(["False", "0"])
trig = s.disengaged_trial.where(s.disengaged.isin([1, 2, 3]))
tt = T[T.session_id.isin(s.session_id[recompute])]
rc = {}
for sid, d in tt.groupby("session_id"):
d = d.sort_values("start_time")
rc[sid] = ib.end_criterion_trial(d.stimOn_times.to_numpy(), d.rt.to_numpy(), d.start_time.iloc[0])
s["trigger"] = trig
s.loc[recompute, "trigger"] = s.loc[recompute, "session_id"].map(rc)
s["met"] = s.trigger.notna()
s["extra"] = s.n_trials - s.trigger
return s, int(recompute.sum())
for name, sel in (("all project mice", mice), ("whole-training mice", complete)):
s, nre = end_table(sel)
day = s.groupby(["subject_id", "date"]).agg(met=("met", "any"), dur=("duration_min", "sum"))
day_met = day.met | (day.dur >= 90)
ex = s.extra[s.met]
print(f"{name}: sessions {len(s)} (recomputed {nre}), met an end criterion {int(s.met.sum())}, ended earlier {int((~s.met).sum())}")
print(f" training days {len(day)}, met (status or 90 min) {int(day_met.sum())}")
print(f" extra trials: median {ex.median():.1f}, m.a.d. {stats.median_abs_deviation(ex.dropna()):.1f}, "
f"negative {int((ex < 0).sum())}; without negatives median {ex[ex >= 0].median():.1f}, "
f"m.a.d. {stats.median_abs_deviation(ex[ex >= 0].dropna()):.1f}")
print(f" criterion of the trigger: {s.disengaged[s.disengaged.isin([1, 2, 3])].value_counts().sort_index().to_dict()}")
s, nre = end_table(mice, recompute_false=True)
ex = s.extra[s.met]
print(f"\nvariant, status False recomputed (all project mice): sessions recomputed {nre}, met an end criterion"
f" {int(s.met.sum())} of {len(s)} ({100 * s.met.mean():.0f}%), extra trials median {ex.median():.1f},"
f" m.a.d. {stats.median_abs_deviation(ex.dropna()):.1f}")
print(f"\nruntime so far {(time.time() - T0) / 60:.1f} min")
all project mice: sessions 6539 (recomputed 486), met an end criterion 5698, ended earlier 841
training days 6435, met (status or 90 min) 5683
extra trials: median 16.0, m.a.d. 14.0, negative 15; without negatives median 16.0, m.a.d. 14.0
criterion of the trigger: {1: 1511, 2: 3282, 3: 538}
whole-training mice: sessions 5347 (recomputed 191), met an end criterion 4708, ended earlier 639
training days 5270, met (status or 90 min) 4706
extra trials: median 15.0, m.a.d. 13.0, negative 13; without negatives median 15.0, m.a.d. 13.0
criterion of the trigger: {1: 1327, 2: 2758, 3: 488}
variant, status False recomputed (all project mice): sessions recomputed 1208, met an end criterion 5734 of 6539 (88%), extra trials median 16.0, m.a.d. 14.0 runtime so far 14.6 min
Result: not reproduced. The project mice have 6,539 sessions, against 10,903. 5,698 sessions met an end criterion and 841 ended earlier (13%), where the paper has 5,587 and 5,316 (49%). The median number of extra trials is 16.0 (m.a.d. 14.0), against 19 +- 1.9 and 16 +- 1.6. Only the count of sessions meeting a criterion is within tolerance, and the shares differ. Recomputing the end criteria also for the 722 sessions whose status is False, a variant, gives 5,734 of 6,539 (88%), with the same extra trials.
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 |
|---|---|
| cohort-counts | not reproduced |
| fig2g-days-to-proficiency | partially reproduced |
| fig2g-days-differ-across-labs | partially reproduced |
| fig2s1-trials-to-proficiency | partially reproduced |
| fig2h-proportion-learned-40-days | reproduced |
| fig2bc-threshold-bias-iqr | partially reproduced |
| fig2-abs-bias-threshold-during-training | reproduced |
| fig2s2-variability-decreases | partially reproduced |
| early-sessions-predict-slow-learners | blocked: methods underspecified |
| fig3c-easy-errors-basic | partially reproduced |
| fig3de-threshold-bias-basic | reproduced |
| fig3cde-no-lab-difference-medians | reproduced |
| fig3cde-no-lab-difference-variances | reproduced |
| fig3s2a-trial-duration | partially reproduced |
| fig3s2b-trials-per-session | partially reproduced |
| fig3f-classifier-chance-basic | reproduced |
| fig3f-positive-control | reproduced |
| fig3s3-other-classifiers | reproduced |
| lab-link | reproduced |
| fig3s1a-choice-consistency-basic | reproduced |
| fig3s1bc-choice-consistency-full | not reproduced |
| fig3s4-looser-criterion | partially reproduced |
| fig3s5-first-full-sessions | not reproduced |
| fig3s5a-prior-used-from-first-sessions | reproduced |
| full-task-training-time | partially reproduced |
| fig4cd-biasshift-largest-at-zero | reproduced |
| fig4de-biasshift-no-lab-difference | reproduced |
| fig4f-threshold-unchanged-by-block | reproduced |
| fig4gh-lapses-change-with-block | partially reproduced |
| fig4i-bias-shifts-with-block | partially reproduced |
| fig4fi-no-lab-difference | reproduced |
| fig4j-classifier-chance-full | reproduced |
| fig5cf-glm-weights | partially reproduced |
| fig5dg-history-weights-higher-full | reproduced |
| fig5s2-glm-accuracy | reproduced |
| fig5s2-weights-similar-across-labs | not reproduced |
| fig5s1b-win-stay-lose-switch | reproduced |
| fig5s1c-updating-by-contrast | reproduced |
| session-end-criteria | not reproduced |
How the analysis differs from the paper's:
- The dataset holds sessions from 2019-06-11 to 2020-03-23 only; the paper's mice began training in January 2019. Only the 136 project mice whose first session in the dataset is a first-stage session are used, against 206 that started training; every count and every test has fewer mice than the paper's.
- The files carry no training status. Basic task proficiency is recomputed from the trials as the pipeline's SessionTrainingStatus computes it (claims file header, answers of 2026-10-22), with "all contrasts introduced" required of each of the three sessions; full task proficiency is recomputed with Appendix 1, table 1d, over consecutive full-task days. The first full-task session follows P1 by 1 to 3 days for 31 of 73 mice under the main reading.
- P1b is the first full-task session at or after P1 (main reading); the code's P1b, at or after the first session meeting the 1b criteria, is a variant.
- The classifiers draw 5 mice per lab, the lowest lab count over the datasets classified, against 8 in the code. The Random Forest of fig3s3 was run on the first 50 of the 2000 subsamples, as 2000 would take about 2 h. Logistic Regression is fitted one-vs-rest, as scikit-learn did with the liblinear solver when the paper's code ran.
- The GLM is run with the 50% weight left out for mice shown no 50% trials (reading (a)) and with 50% trials dropped for every mouse (reading (b), the code's).
What was found about the dataset:
- It holds part of the paper's data: 178 mice and 6,615 sessions from 2019-06-11 on, against 206 mice and 10,903 sessions from January 2019.
- One recording is deposited twice, under two mice (CSHL_013 and CSHL_015, 2019-07-15).
- The training status of each session, which the paper's analyses select on, is not in the files.
probabilityLeftis described as the block's probability of a left stimulus, but in every basic-task session it varies from trial to trial between 0 and 1.session_start_timeis stated in UTC (+00:00) but holds local clock times.- 257,021 trials (6%) have no stimulus onset time, and 185 sessions have no onset time on any trial; 1,541 trials in 220 sessions have a response before the stimulus onset (down to -5,638 s). Trial durations, and the 1b reaction-time criterion, cannot be computed where onsets are missing; no proficiency window here fails for that alone.
- One session (ZM_1367, 2019-06-11) uses contrasts of 4% and 8%, which the paper does not describe.
- In 807 files the wheel position and its timestamps differ in length, and 16 files have no wheel series. In one session checked (ibl_witten_07), the wheel moves the opposite way to the choice on every trial.
- The archive's summary counts 178 subjects; one mouse (SWC_029) is not of the paper's project.