Reproducing Mah, Schiereck, Bossio and Constantinople (2023) from DANDI:001169¶
Paper. Mah A, Schiereck SS, Bossio V, Constantinople CM (2023). Distinct value computations support rapid sequential decisions. Nature Communications 14, 7573. doi:10.1038/s41467-023-43250-x.
Dataset. DANDI:001169, version 0.260825.1909 (doi:10.48324/dandi.001169/0.260825.1909). The paper cites no version of the dandiset (it cites the Zenodo deposit doi:10.5281/zenodo.10031483), and 0.260825.1909 is the only published version, so it is pinned. Its 23,034 NWB files hold one behavioral session each, for 291 rats. Each file is streamed from the archive into memory and never written to disk.
Text the claims were written from. The version of record (Europe PMC, PMC10663503) with the Methods and the
Supplementary Information; the claims file is claims/mah-2023.yaml. The paper's code was read at
github.com/constantinoplelab/published, folder rat_behavior, commit b7b68ca8c107.
Claims. 32 claims from the paper and one link claim added here (pre-cue-session-link). Tested here: 28. Blocked: 5.
| claim | tested or blocked |
|---|---|
| cohort-size | tested |
| fig1e-wait-time-increases-with-reward | tested |
| fig1f-wait-time-block-effect | tested |
| fig1i-initiation-block-effect | tested |
| suppfig2-initiation-block-effect-after-unrewarded | tested |
| suppfig3-wait-time-not-affected-by-previous-outcome | tested |
| fig2a-wait-time-converges-in-mixed-blocks | tested |
| suppfig5-mixed-to-adaptation-transitions | tested |
| fig2c-d-regression-on-previous-rewards | tested |
| fig2e-tau-differ | tested |
| fig2f-tau-uncorrelated | tested |
| fig2g-h-fast-slow-tau-groups | tested |
| fig2j-wait-time-not-sensitive-to-previous-offer | tested |
| fig2k-initiation-sensitive-to-previous-offer | tested |
| fig2l-sensitivity-greater-for-initiation | tested |
| suppfig6-results-without-detrending | tested |
| fig3c-wait-time-by-catch-probability | tested |
| fig3i-retrospective-model-captures-initiation | tested |
| bayes-observer-offer-reduces-uncertainty | tested |
| suppfig12-no-sex-differences | tested |
| suppfig14-contextual-effects-without-threshold | tested |
| fig3j-inferential-beats-retrospective-for-wait-times | blocked, too_large (estimate in the last section) |
| suppfig8-belief-state-not-distinguished | blocked, too_large (needs the fits of fig3j) |
| fig3f-inferential-model-not-sensitive-to-previous-offer | tested, with the inferential model fitted per rat |
| suppfig9-wait-times-reflect-misinferences | tested, with the model's block labels, which need no fit |
| fig3l-lambda-groups-wait-time-dynamics | tested, with the sub-optimal model fitted per rat |
| fig4a-wait-time-block-sensitivity-emerges | blocked, data_missing (sessions that fail the inclusion criterion) |
| fig4c-initiation-previous-reward-stable | blocked, data_missing |
| fig4d-overshoot-grows-with-training | blocked, data_missing |
| pre-cue-session-link (link claim) | tested, with the session labels of Figure5.m |
| fig5b-pre-cue-initiation-sensitive-to-offer | tested, with the session labels of Figure5.m |
| fig5c-pre-cue-initiation-still-sensitive-to-previous-reward | tested, with the session labels of Figure5.m |
| fig5d-pre-cue-initiation-depends-on-previous-block | tested, with the session labels of Figure5.m |
Where a method detail comes from is said in the helper module mah2023.py beside each function, and in the
sections below.
import os
os.environ.setdefault("OMP_NUM_THREADS", "1")
os.environ.setdefault("OPENBLAS_NUM_THREADS", "1")
import time, resource, warnings
import numpy as np
import pandas as pd
from scipy.stats import wilcoxon, mannwhitneyu, pearsonr
import mah2023 as m
warnings.filterwarnings("ignore", category=RuntimeWarning)
pd.set_option("display.width", 160)
T0 = time.time()
Loading¶
All 23,034 sessions are read (the processed trial table, the catch probability column of the raw trial table, and the subject metadata). With parallel requests this took 6 to 14 minutes in the runs so far, depending on the archive's response.
assets = m.list_assets()
print("assets in version", m.VERSION, ":", len(assets))
t = time.time()
sessions_all, trials_all = m.load_all(assets, workers=32, progress=5000)
print(f"read in {(time.time() - t) / 60:.1f} min; peak memory {resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1e6:.2f} GB")
S, TR, DUP = m.prepare(sessions_all, trials_all)
R = m.rat_arrays(TR)
RATS = sorted(R)
print("sessions kept", len(S), "; duplicates dropped", len(DUP), "; rats", len(RATS), "; trials", len(TR))
assets in version 0.260825.1909 : 23034
5000 of 23034 sessions read, 109 s
10000 of 23034 sessions read, 217 s
15000 of 23034 sessions read, 327 s
20000 of 23034 sessions read, 442 s
read in 8.5 min; peak memory 1.69 GB
sessions kept 23033 ; duplicates dropped 1 ; rats 291 ; trials 10408699
Data check¶
What was loaded, checked against the dataset's description and the paper.
print("files whose folder is not the subject id:", int((sessions_all.path.str.split('/').str[0] != 'sub-' + sessions_all.subject).sum()))
print("subjects:", sessions_all.subject.nunique(), "(archive summary 291; paper 291)")
sex = S.groupby("subject").sex.agg(lambda x: ",".join(sorted(set(x))))
print("sex per rat:", sex.value_counts().to_dict(), "(paper, Subjects: 184 male, 107 female; Training for male and female rats: 160 and 114)")
print("protocols:", sessions_all.protocol.value_counts().to_dict())
print("age field:", sessions_all.age.replace('', '(empty)').value_counts().to_dict())
print("training stage in processed trials:", TR.stage.value_counts().to_dict(), "(stage 8 of the paper is coded 9)")
print("raw and processed tables: same rows in", int(sessions_all.raw_rows_match.sum()), "of", len(sessions_all),
"sessions; reward mismatches", int(sessions_all.raw_volume_mismatch.sum()),
"; largest start time difference", sessions_all.raw_start_maxdiff.max(), "s")
print("raw is_catch differs from the processed catch flag on", int(sessions_all.raw_catch_mismatch.sum()), "trials;",
"processed catch trials with reward_delay != 100:", int((TR['catch'] & (TR.reward_delay != 100)).sum()))
print("processed table has a catch probability column:", bool(sessions_all.has_prob_catch_column.any()))
print()
print("duplicated recordings (same rat, identical offers, wait times and initiation times):")
dups = sessions_all[sessions_all.duplicated(['subject', 'fingerprint'], keep=False)]
print(dups[['path', 'n_trials', 'session_start_time']].to_string())
files whose folder is not the subject id: 0
subjects: 291 (archive summary 291; paper 291)
sex per rat: {'M': 184, 'F': 107} (paper, Subjects: 184 male, 107 female; Training for male and female rats: 160 and 114)
protocols: {'RWTautowait2': 22943, 'RWTautowait': 86, 'RWTautowaitWP': 5}
age field: {'(empty)': 21853, 'P6M/P24M': 1181}
training stage in processed trials: {9: 10408699} (stage 8 of the paper is coded 9)
raw and processed tables: same rows in 23034 of 23034 sessions; reward mismatches 0 ; largest start time difference 0.0 s
raw is_catch differs from the processed catch flag on 176009 trials; processed catch trials with reward_delay != 100: 0
processed table has a catch probability column: False
duplicated recordings (same rat, identical offers, wait times and initiation times):
path n_trials session_start_time
13778 sub-L011/sub-L011_ses-RWTautowait2-20221004-095612-x.nwb 226 2022-10-04T09:56:25-04:00
13781 sub-L011/sub-L011_ses-RWTautowait2-20221004-095612.nwb 226 2022-10-04T09:56:25-04:00
per_rat = S.groupby("subject").agg(sessions=("sidx", "size"), trials=("n_trials", "sum"))
print("sessions per rat: median", per_rat.sessions.median(), "range", per_rat.sessions.min(), "to", per_rat.sessions.max())
print("trials per rat: median", per_rat.trials.median(), "range", per_rat.trials.min(), "to", per_rat.trials.max())
print("trials per session: median", S.n_trials.median(), "range", S.n_trials.min(), "to", S.n_trials.max())
print()
print("blocks (1 mixed, 2 high, 3 low):", TR.block.value_counts().sort_index().to_dict())
print("offered volumes (raw):", TR.volume_raw.value_counts().sort_index().to_dict())
fem = TR.merge(S[['sidx', 'sex']], on='sidx').groupby('sex').volume_raw.agg(lambda x: sorted(set(x)))
print("volumes by sex:", fem.to_dict())
for b, vs in ((2, [20, 40, 80]), (3, [5, 10, 20])):
bad = TR[(TR.block == b) & ~TR.vol.isin(vs)]
print(f"block {b}: trials with a volume outside {vs}:", len(bad))
print("catch probability values per session:", sessions_all.catch_percentage_values.value_counts().to_dict())
print("catch trials share:", round(TR['catch'].mean(), 3), "(paper 15 to 25%, 35% early in stage 8)")
print()
for c, unit in (("wt", "s"), ("wt_unthr", "s"), ("iti", "s"), ("reward_delay", "s"), ("wt_thresh", "s")):
x = TR[c]
print(f"{c:13s} [{unit}] n={x.notna().sum():9d} min={x.min():8.3f} median={x.median():8.3f} max={x.max():9.3f}")
co = TR['catch'] & TR.optout
print("catch trials that are hits:", int((TR['catch'] & TR.hit).sum()), "; opt-outs on non-catch trials:", int((TR.optout & ~TR['catch']).sum()))
print("hit trials with wait_time equal to reward_delay:", round(float(np.mean(np.isclose(TR.wt_unthr[TR.hit], TR.reward_delay[TR.hit], atol=1e-3))), 5), "(to 1 ms; wait times are stored to 0.1 ms)")
print("unthresholded catch wait times of 100 s (timed out):", int((TR.wt_unthr[TR['catch']] >= 100).sum()))
sessions per rat: median 71.0 range 15 to 232
trials per rat: median 33493.0 range 5266 to 129864
trials per session: median 435.0 range 200 to 1326
blocks (1 mixed, 2 high, 3 low): {1: 5771728, 2: 2223568, 3: 2413403}
offered volumes (raw): {4: 765484, 5: 1642577, 8: 648177, 10: 1374860, 16: 872406, 20: 1848594, 32: 504361, 40: 1117653, 64: 505892, 80: 1128695}
volumes by sex: {'F': [4, 5, 8, 10, 16, 20, 32, 40, 64, 80], 'M': [5, 10, 20, 40, 80]}
block 2: trials with a volume outside [20, 40, 80]: 0
block 3: trials with a volume outside [5, 10, 20]: 0
catch probability values per session: {'0.15': 9994, '0.25': 8503, '0.2': 3140, '0.35': 876, '0.3': 360, '0.1': 105, '0.15,0.35': 47, '0.25,0.35': 8, '0.15,0.2': 1}
catch trials share: 0.188 (paper 15 to 25%, 35% early in stage 8)
wt [s] n= 6060844 min= 0.000 median= 2.226 max= 49.730
wt_unthr [s] n= 6129303 min= 0.000 median= 2.268 max= 100.000 iti [s] n= 10395089 min= 0.000 median= 0.861 max= 6319.122
reward_delay [s] n= 10408699 min= 0.000 median= 2.328 max= 100.000 wt_thresh [s] n= 10408699 min= 16.329 median= 27.152 max= 50.162 catch trials that are hits: 0 ; opt-outs on non-catch trials: 245912
hit trials with wait_time equal to reward_delay: 0.99999 (to 1 ms; wait times are stored to 0.1 ms) unthresholded catch wait times of 100 s (timed out): 15871
# The wait time threshold (mean + 1 SD of the rat's catch-trial wait times, parse_data_from_mysql.m) recomputed
# from wait_time_unthresholded, and whether wait_time is wait_time_unthresholded with values above it removed.
rows = []
for r in RATS:
d = R[r]
w = d["wt_unthr"][d["catch"]]
thr = np.nanmean(w) + np.nanstd(w, ddof=1)
stored = TR.wt_thresh.values[TR.subject.values == r][0]
above = d["wt_unthr"] > stored
rows.append(dict(rat=r, recomputed=thr, stored=stored,
removed_ok=bool(np.all(np.isnan(d["wt"][above]))),
kept_equal=bool(np.allclose(d["wt"][~above & np.isfinite(d["wt"])], d["wt_unthr"][~above & np.isfinite(d["wt"])]))))
thr = pd.DataFrame(rows)
print("rats whose stored threshold is within 0.1 s of mean + 1 SD of catch wait times:", int((abs(thr.recomputed - thr.stored) < 0.1).sum()), "of", len(thr))
print("largest difference:", round(float(abs(thr.recomputed - thr.stored).max()), 3), "s")
print("rats where wait_time is NaN above the threshold:", int(thr.removed_ok.sum()), "; equal to the unthresholded value below it:", int(thr.kept_equal.sum()))
rats whose stored threshold is within 0.1 s of mean + 1 SD of catch wait times: 287 of 291 largest difference: 0.184 s rats where wait_time is NaN above the threshold: 291 ; equal to the unthresholded value below it: 291
# Inclusion criterion: the dataset is built from the lab's A structs (A_Structs_Final), which hold only the
# sessions that pass screen_perf.m. If so, the slope of catch-trial wait time on offer (wait times above
# mean + 2 SD of the session removed) should be positive in almost every session.
from numpy.polynomial import polynomial as P_
slopes = []
for sidx, g in TR[TR['catch']].groupby("sidx"):
w = g.wt_unthr.values.astype(float)
ok = np.isfinite(w)
w2 = w.copy(); w2[w2 > np.nanmean(w) + 2 * np.nanstd(w, ddof=1)] = np.nan
ok = np.isfinite(w2)
if ok.sum() > 5:
slopes.append(np.polyfit(g.volume_raw.values[ok], w2[ok], 1)[0])
slopes = np.array(slopes)
print("sessions with more than 5 catch wait times:", len(slopes), "; slope > 0 in", int((slopes > 0).sum()),
f"({(slopes > 0).mean():.1%})")
sessions with more than 5 catch wait times: 23033 ; slope > 0 in 20035 (87.0%)
# Clock and alignment. (1) The processed inter_trial_interval against the raw events: for trials after an
# unrewarded trial it should equal the first center poke measured from the trial start (getITI.m).
rng_check = np.random.default_rng(11)
pick = rng_check.choice(len(assets), 12, replace=False)
chk = []
for i in pick:
x = m.iti_from_events(assets[i])
y = x[~x.prev_hit & np.isfinite(x.center_in) & np.isfinite(x.iti)]
z = x[x.prev_hit & np.isfinite(x.center_in) & np.isfinite(x.iti)]
chk.append(dict(path=assets[i]["path"].split("/")[1][:40], n=len(x), max_abs_diff_unrewarded=float(np.max(np.abs(y.iti - y.center_in))) if len(y) else np.nan,
share_post_reward_not_longer=float(np.mean(z.iti <= z.center_in + 1e-6)) if len(z) else np.nan))
print(pd.DataFrame(chk).to_string())
# (2) Block labels against behavior: the high minus low block contrast in z-scored initiation time and in 20 uL
# wait time, with the true labels and with the labels shifted within each rat by 200 trials.
def contrast(shift):
di, dw = [], []
for r in RATS:
d = R[r]
blk = np.roll(d["block"], shift)
L = m.nanz(m.clip99(d["iti"]))
di.append(np.nanmean(L[blk == 2]) - np.nanmean(L[blk == 3]))
co = d["catch"] & d["optout"] & (d["vol"] == 20)
dw.append(np.nanmean(d["wt"][co & (blk == 2)]) - np.nanmean(d["wt"][co & (blk == 3)]))
return np.nanmean(di), np.nanmean(dw)
for sh in (0, 200, -200):
a, b = contrast(sh)
print(f"labels shifted by {sh:5d} trials: initiation time high - low {a:+.3f} z; 20 uL wait time high - low {b:+.3f} s")
path n max_abs_diff_unrewarded share_post_reward_not_longer 0 sub-S019_ses-RWTautowait2-20210316-11381 425 7.240875e-12 1.0 1 sub-J029_ses-RWTautowait2-20220317-12230 778 4.525547e-13 1.0 2 sub-J060_ses-RWTautowait2-20230228-15111 472 4.001799e-13 1.0 3 sub-L010_ses-RWTautowait2-20220826-09431 406 3.979039e-13 1.0 4 sub-J065_ses-RWTautowait2-20230410-10165 451 2.273737e-13 1.0 5 sub-G044_ses-RWTautowait2-20220218-13362 310 4.547474e-13 1.0 6 sub-E007_ses-RWTautowait2-20220511-13280 319 4.547474e-13 1.0 7 sub-S042_ses-RWTautowait2-20230109-15220 395 4.121148e-13 1.0 8 sub-G040_ses-RWTautowait2-20210922-14070 441 4.307665e-13 1.0 9 sub-L011_ses-RWTautowait2-20230314-09444 316 4.547474e-13 1.0 10 sub-G041_ses-RWTautowait2-20210915-16164 504 2.270129e-13 1.0 11 sub-M033_ses-RWTautowait2-20210701-12152 489 9.094947e-13 1.0 labels shifted by 0 trials: initiation time high - low -0.190 z; 20 uL wait time high - low -1.313 s
labels shifted by 200 trials: initiation time high - low -0.065 z; 20 uL wait time high - low +0.024 s labels shifted by -200 trials: initiation time high - low +0.031 z; 20 uL wait time high - low -0.003 s
The checks above are summarized in the summary at the end. Analyses below use the processed trial table:
wait_time (thresholded, as the lab's parser leaves it), wait_time_unthresholded, inter_trial_interval
(the time to initiate trial t, measured before its center poke, as getITI.m defines it), block_type,
reward_volume_ul (female volumes mapped to the male ones), is_catch, is_opt_out, is_rewarded,
is_violation, and the raw table's catch_percentage. Trials of a rat are concatenated over its sessions in
date order, as the lab's A struct is; the one duplicated session is counted once.
# Per-rat measures used by several claims (each claim's section says which).
t = time.time()
rng_tau = np.random.default_rng(2023) # random starts of the exponential fits (claims fig2e, fig2f, fig2g-h)
rows, WD, LD, LS, LN, TB = [], {}, {}, {}, {}, {}
for r in RATS:
d = R[r]
be = m.block_effects(d)
wp, ip, im = m.wt_by_previous(d), m.iti_by_previous(d, "code"), m.iti_by_previous(d, "methods")
mp, mpw = m.mixed_by_previous_block(d), m.mixed_by_previous_block(d, within_session=True)
WD[r] = m.wt_dynamics(d)
LD[r] = m.lat_dynamics(d, detrend="pooled")
LS[r] = m.lat_dynamics(d, detrend="session")
LN[r] = m.lat_dynamics(d, detrend=None)
TB[r] = m.taus(d, rng_tau)
be.update(rat=r, wp_lo=wp[0], wp_hi=wp[1], wp_p=wp[2], ip_lo=ip[0], ip_hi=ip[1], ip_p=ip[2],
im_lo=im[0], im_hi=im[1], im_p=im[2], mix_after_hi=mp[0], mix_after_lo=mp[1],
mixw_after_hi=mpw[0], mixw_after_lo=mpw[1])
rows.append(be)
PR = pd.DataFrame(rows).set_index("rat")
PR["sex"] = S.groupby("subject").sex.first().reindex(PR.index)
print(f"per-rat measures for {len(PR)} rats in {time.time() - t:.0f} s")
OFF = np.arange(-20, 21)
def popmean(D, key):
return np.nanmean(np.stack([D[r][key] for r in RATS]), 0)
def window(curve, a, b):
return float(np.nanmean(curve[(OFF >= a) & (OFF <= b)]))
per-rat measures for 291 rats in 10 s
cohort-size¶
The dataset comes from 291 rats, with a median of 33,493 behavioral trials and 71 sessions per rat.
Counted as Figure1.m does: sessions as the number of dates and trials as the number of trials per rat, over the included stage 8 sessions (the dataset holds only these). The duplicated session is counted once.
n_rats = len(RATS)
med_trials = float(per_rat.trials.median()); med_sess = float(per_rat.sessions.median())
print("rats:", n_rats, "(expected 291, tolerance 0)")
print("median trials per rat:", med_trials, "(expected 33493 +- 3349)")
print("median sessions per rat:", med_sess, "(expected 71 +- 7)")
print("with the duplicate kept: median sessions", sessions_all.groupby('subject').size().median(),
", median trials", sessions_all.groupby('subject').n_trials.sum().median())
print("rats with sessions dated on or after their pre-cue switch date in Figure5.m are among the 291 (see fig5 claims)")
rats: 291 (expected 291, tolerance 0) median trials per rat: 33493.0 (expected 33493 +- 3349) median sessions per rat: 71.0 (expected 71 +- 7) with the duplicate kept: median sessions 71.0 , median trials 33493.0 rats with sessions dated on or after their pre-cue switch date in Figure5.m are among the 291 (see fig5 claims)
Result: reproduced. The dandiset holds 291 rats, with a median of 33,493 trials and 71 sessions per rat, exactly the paper's numbers. One session of rat L011 is deposited twice; counting it once or twice leaves both medians unchanged.
fig1e-wait-time-increases-with-reward¶
In mixed blocks, rats wait longer for larger offered rewards; mean wait time on catch trials rises with offer across 5, 10, 20, 40 and 80 uL.
Per rat, mean wait time on opt-out catch trials in mixed blocks for each offer (wtcurves.m); then the mean over rats.
WC = np.stack(PR.wt_curve.values)
mix = np.nanmean(WC[:, 0], 0)
print("population mean wait time in mixed blocks (s), 5 to 80 uL:", mix.round(3))
print("increases at each step:", bool(np.all(np.diff(mix) > 0)), "; steps:", np.diff(mix).round(3))
inc = np.diff(WC[:, 0], axis=1) > 0
print("rats with an increase at each step (5-10, 10-20, 20-40, 40-80):", inc.sum(0), "of", np.isfinite(np.diff(WC[:, 0], axis=1)).sum(0))
print("rats increasing at every step:", int(inc.all(1).sum()))
print("range of per-rat means:", np.nanmin(WC[:, 0]).round(2), "to", np.nanmax(WC[:, 0]).round(2), "s")
population mean wait time in mixed blocks (s), 5 to 80 uL: [10.451 10.773 11.105 13.027 13.809] increases at each step: True ; steps: [0.322 0.332 1.922 0.782] rats with an increase at each step (5-10, 10-20, 20-40, 40-80): [226 237 291 276] of [291 291 291 291] rats increasing at every step: 171 range of per-rat means: 6.39 to 24.71 s
Result: reproduced. The population mean wait time in mixed blocks rises at every step, from 10.45 s at 5 uL to 13.81 s at 80 uL (steps 0.32, 0.33, 1.92 and 0.78 s). All 291 rats wait longer for 40 than for 20 uL; 171 rats increase at every step.
fig1f-wait-time-block-effect¶
Rats wait about 10% less for 20 uL in high blocks than in low blocks, across the population.
Per rat, mean wait time on 20 uL opt-out catch trials in high and low blocks; ratio high over low; mean over rats (expected 0.90 +- 0.025). Signed-rank test across rats, reading (a) z-scored wait times (Methods) and (b) raw seconds (Figure1.m). Per-rat one-tailed rank-sum (wtcurves.m).
ratio_wt = PR.wt20_hi / PR.wt20_lo
pa = wilcoxon(PR.wt20z_hi, PR.wt20z_lo); pb = wilcoxon(PR.wt20_hi, PR.wt20_lo)
print("mean wait time ratio (high / low, 20 uL):", round(ratio_wt.mean(), 4), "; median", round(ratio_wt.median(), 4),
"; range", round(ratio_wt.min(), 3), "to", round(ratio_wt.max(), 3), "; rats", ratio_wt.notna().sum())
print("rats with ratio < 1:", int((ratio_wt < 1).sum()))
print("(a) z-scored, signed-rank: p =", f"{pa.pvalue:.3g}", " (b) seconds, signed-rank: p =", f"{pb.pvalue:.3g}", " (paper p = 8.26e-49)")
print("rats with per-rat one-tailed rank-sum p < 0.05 (high shorter):", int((PR.p_wt_rank_left < 0.05).sum()), "of", PR.p_wt_rank_left.notna().sum())
print("mean 20 uL wait time: high", round(PR.wt20_hi.mean(), 3), "s, low", round(PR.wt20_lo.mean(), 3), "s")
mean wait time ratio (high / low, 20 uL): 0.8942 ; median 0.8897 ; range 0.76 to 1.23 ; rats 291 rats with ratio < 1: 279 (a) z-scored, signed-rank: p = 4.61e-47 (b) seconds, signed-rank: p = 8.18e-47 (paper p = 8.26e-49) rats with per-rat one-tailed rank-sum p < 0.05 (high shorter): 244 of 291 mean 20 uL wait time: high 10.852 s, low 12.165 s
Result: reproduced. The mean ratio of 20 uL wait times, high over low blocks, is 0.894 (expected 0.90 +- 0.025), below 1 in 279 of 291 rats. The signed-rank test gives p = 4.61e-47 on z-scored wait times (the Methods) and p = 8.18e-47 in seconds (Figure1.m), against the paper's 8.26e-49; both are below 0.001. By the per-rat one-tailed rank-sum, 244 rats wait less in high blocks at p < 0.05 (the paper gives no count).
fig1i-initiation-block-effect¶
Rats initiate trials more quickly in high blocks than in low blocks, across the population.
Per rat, mean trial initiation time over all trials (99th percentile cut over the rat's pooled times) in high and low blocks (iticurves.m); signed-rank across rats on (a) z-scored and (b) raw means; mean per-rat ratio.
ratio_iti = PR.iti_hi / PR.iti_lo
pa = wilcoxon(PR.itiz_hi, PR.itiz_lo); pb = wilcoxon(PR.iti_hi, PR.iti_lo)
print("mean initiation time ratio (high / low):", round(ratio_iti.mean(), 4), "; median", round(ratio_iti.median(), 4),
"; range", round(ratio_iti.min(), 3), "to", round(ratio_iti.max(), 3))
print("rats with ratio < 1:", int((ratio_iti < 1).sum()), "of", len(ratio_iti))
print("(a) z-scored signed-rank p =", f"{pa.pvalue:.3g}", "; (b) seconds signed-rank p =", f"{pb.pvalue:.3g}", " (paper p = 1.82e-49)")
print("rats with per-rat one-tailed rank-sum p < 0.05:", int((PR.p_iti_rank_left < 0.05).sum()))
print("mean initiation time (s): high", round(PR.iti_hi.mean(), 3), ", low", round(PR.iti_lo.mean(), 3), ", mixed", round(PR.iti_mix.mean(), 3))
mean initiation time ratio (high / low): 0.5617 ; median 0.545 ; range 0.311 to 1.016 rats with ratio < 1: 290 of 291 (a) z-scored signed-rank p = 1.82e-49 ; (b) seconds signed-rank p = 1.84e-49 (paper p = 1.82e-49) rats with per-rat one-tailed rank-sum p < 0.05: 202 mean initiation time (s): high 2.214 , low 4.005 , mixed 3.001
Result: reproduced. The mean ratio of initiation times, high over low blocks, is 0.562, below 1 in 290 of 291 rats. The signed-rank test gives p = 1.82e-49 on z-scored times and 1.84e-49 in seconds; the paper prints 1.82e-49.
suppfig2-initiation-block-effect-after-unrewarded¶
The block sensitivity of trial initiation times comes from trials after unrewarded trials; after rewarded trials initiation times do not differ between high and low blocks in the same direction.
FigureS2.m: z-scored initiation times (over all trials) split by whether the previous trial was rewarded; per-rat means in high and low blocks; signed-rank across rats, two-tailed (legend) and one-tailed low > high (code).
for k, lab in (("postunrew", "after unrewarded"), ("postrew", "after rewarded")):
lo, hi = PR[f"itiz_{k}_lo"], PR[f"itiz_{k}_hi"]
two = wilcoxon(lo, hi); one = wilcoxon(lo, hi, alternative="greater")
print(f"{lab:17s}: mean z low {lo.mean():+.3f}, high {hi.mean():+.3f}, high - low {(hi - lo).mean():+.3f};"
f" rats with high < low {int((hi < lo).sum())} of {int((hi.notna() & lo.notna()).sum())};"
f" two-tailed p = {two.pvalue:.3g}; one-tailed (low > high) p = {one.pvalue:.3g}")
allone = wilcoxon(PR.itiz_lo, PR.itiz_hi, alternative="greater")
print("all trials, one-tailed p =", f"{allone.pvalue:.3g}", "(legend's third value 9.17e-50; post-unrewarded 9.07e-50; post-rewarded 1)")
after unrewarded : mean z low +0.267, high -0.084, high - low -0.351; rats with high < low 291 of 291; two-tailed p = 1.8e-49; one-tailed (low > high) p = 9.02e-50 after rewarded : mean z low -0.105, high -0.088, high - low +0.016; rats with high < low 95 of 291; two-tailed p = 3.85e-09; one-tailed (low > high) p = 1 all trials, one-tailed p = 9.12e-50 (legend's third value 9.17e-50; post-unrewarded 9.07e-50; post-rewarded 1)
Result: reproduced. After unrewarded trials, initiation is faster in high blocks in all 291 rats (mean z difference -0.351; two-tailed p = 1.8e-49, one-tailed p = 9.02e-50, the legend 9.07e-50). After rewarded trials the one-tailed test (low slower than high) gives p = 1, as in the legend; the two-tailed test is significant (p = 3.85e-09) but in the other direction, high blocks slightly slower (+0.016 z, 95 of 291 rats faster in high). The all-trials one-tailed p is 9.12e-50 (legend 9.17e-50), which supports the claims file's reading that the legend's p values come from the code's one-tailed tests.
suppfig3-wait-time-not-affected-by-previous-outcome¶
Wait times show no major differences after rewarded and after unrewarded trials.
FigureS3.m: per rat, the 20 uL wait time ratio (high over low) on opt-out catch trials after rewarded and after unrewarded trials; the population mean ratio must be below 1 in both. The difference between subsets and a signed-rank test of it are reported (variant).
rr = PR.wt20_postrew_hi / PR.wt20_postrew_lo
ru = PR.wt20_postunrew_hi / PR.wt20_postunrew_lo
print("mean ratio after rewarded:", round(rr.mean(), 4), "(rats", rr.notna().sum(), "; below 1:", int((rr < 1).sum()), ")")
print("mean ratio after unrewarded:", round(ru.mean(), 4), "(rats", ru.notna().sum(), "; below 1:", int((ru < 1).sum()), ")")
ok = rr.notna() & ru.notna()
print("difference (rewarded - unrewarded): mean", round((rr - ru)[ok].mean(), 4), "; signed-rank p =", f"{wilcoxon(rr[ok], ru[ok]).pvalue:.3g}")
mean ratio after rewarded: 0.899 (rats 291 ; below 1: 267 ) mean ratio after unrewarded: 0.8968 (rats 291 ; below 1: 270 ) difference (rewarded - unrewarded): mean 0.0022 ; signed-rank p = 0.636
Result: reproduced. The mean 20 uL wait time ratio (high over low) is 0.899 after rewarded trials and 0.897 after unrewarded trials, both below 1. The two subsets differ by a mean of 0.0022 (signed-rank p = 0.636).
fig2a-wait-time-converges-in-mixed-blocks¶
After a transition into a mixed block, wait times converge to a common value whether the previous block was high or low, while trial initiation times in mixed blocks keep depending on the previous block.
Transition curves (block_dynamics_wt.m, block_dynamics_latency.m; 20 trials either side, 10-point smoothing per rat, then the mean over rats). Part (1): the gap between the high-to-mixed and low-to-mixed curves over trials 1 to 20 (and 10 to 20) of the mixed block, as a fraction of the gap over trials -20 to -1, must be smaller for wait times than for initiation times; the initiation curves are detrended as the code does (one line over pooled sessions) and as the Methods do (per session). Part (2): mean z-scored initiation time over whole mixed blocks after high against after low blocks (FigureS4.m), two-tailed signed-rank p < 0.05 with higher values after high blocks. The code finds transitions on the rat's concatenated trials, so a session that starts in a mixed block after a session that ended in a high or low block counts as a transition; a variant uses transitions within sessions only.
gaps = {}
for name, D in (("wait time", WD), ("initiation, pooled detrend (code)", LD), ("initiation, per-session detrend (Methods)", LS)):
g = popmean(D, "htom") - popmean(D, "ltom")
pre, p1, p2 = window(g, -20, -1), window(g, 1, 20), window(g, 10, 20)
gaps[name] = (pre, p1, p2)
print(f"{name:42s} gap high-to-mixed minus low-to-mixed: trials -20..-1 {pre:+.3f}, 1..20 {p1:+.3f}, 10..20 {p2:+.3f};"
f" relative 1..20 {abs(p1 / pre):.3f}, 10..20 {abs(p2 / pre):.3f}")
for name in list(gaps)[1:]:
w, l = gaps["wait time"], gaps[name]
print(f"part (1) with {name}: window 1..20 {abs(w[1] / w[0]) < abs(l[1] / l[0])}, window 10..20 {abs(w[2] / w[0]) < abs(l[2] / l[0])}")
for lab, a, b in (("code, concatenated trials", PR.mix_after_hi, PR.mix_after_lo), ("within sessions", PR.mixw_after_hi, PR.mixw_after_lo)):
t2 = wilcoxon(a, b)
print(f"part (2), {lab}: mean z after high {a.mean():+.3f}, after low {b.mean():+.3f}; rats higher after high {int((a > b).sum())} of {int((a.notna() & b.notna()).sum())}; signed-rank p = {t2.pvalue:.3g}")
print("curves (population means), trials -20..20:")
for name, D in (("wt htom", WD), ("wt ltom", WD), ("iti htom", LD), ("iti ltom", LD)):
print(f" {name}: {np.round(popmean(D, name.split()[1]), 3).tolist()}")
wait time gap high-to-mixed minus low-to-mixed: trials -20..-1 -0.333, 1..20 -0.108, 10..20 -0.027; relative 1..20 0.325, 10..20 0.082 initiation, pooled detrend (code) gap high-to-mixed minus low-to-mixed: trials -20..-1 -0.107, 1..20 +0.247, 10..20 +0.258; relative 1..20 2.312, 10..20 2.423 initiation, per-session detrend (Methods) gap high-to-mixed minus low-to-mixed: trials -20..-1 -0.118, 1..20 +0.232, 10..20 +0.243; relative 1..20 1.973, 10..20 2.063 part (1) with initiation, pooled detrend (code): window 1..20 True, window 10..20 True part (1) with initiation, per-session detrend (Methods): window 1..20 True, window 10..20 True part (2), code, concatenated trials: mean z after high +0.053, after low -0.072; rats higher after high 291 of 291; signed-rank p = 1.8e-49 part (2), within sessions: mean z after high +0.086, after low -0.089; rats higher after high 291 of 291; signed-rank p = 1.8e-49 curves (population means), trials -20..20: wt htom: [-0.154, -0.14, -0.132, -0.121, -0.12, -0.118, -0.111, -0.11, -0.108, -0.108, -0.111, -0.113, -0.112, -0.112, -0.107, -0.105, -0.104, -0.105, -0.113, -0.116, -0.116, -0.118, -0.116, -0.111, -0.11, -0.106, -0.099, -0.08, -0.063, -0.051, -0.036, -0.024, -0.016, -0.004, 0.002, 0.008, 0.006, 0.007, 0.008, -0.007, -0.029] wt ltom: [0.222, 0.189, 0.195, 0.2, 0.207, 0.202, 0.207, 0.21, 0.214, 0.215, 0.222, 0.226, 0.216, 0.222, 0.23, 0.235, 0.237, 0.24, 0.238, 0.221, 0.203, 0.191, 0.177, 0.155, 0.132, 0.107, 0.081, 0.065, 0.056, 0.047, 0.041, 0.034, 0.032, 0.035, 0.033, 0.027, 0.019, 0.019, 0.012, -0.01, -0.027] iti htom: [-0.102, -0.095, -0.09, -0.088, -0.088, -0.085, -0.082, -0.08, -0.079, -0.079, -0.079, -0.08, -0.078, -0.076, -0.076, -0.077, -0.083, -0.07, -0.046, -0.019, 0.012, 0.047, 0.077, 0.109, 0.116, 0.146, 0.157, 0.16, 0.159, 0.156, 0.148, 0.141, 0.133, 0.125, 0.121, 0.12, 0.115, 0.11, 0.106, 0.105, 0.094] iti ltom: [0.049, 0.047, 0.04, 0.04, 0.038, 0.038, 0.039, 0.036, 0.035, 0.035, 0.033, 0.031, 0.033, 0.031, 0.028, 0.026, 0.02, 0.007, -0.005, -0.021, -0.038, -0.058, -0.077, -0.096, -0.101, -0.114, -0.121, -0.128, -0.132, -0.135, -0.137, -0.138, -0.139, -0.139, -0.139, -0.139, -0.139, -0.139, -0.138, -0.139, -0.139]
Result: reproduced. Over trials 1 to 20 of the mixed block, the gap between the wait time curves after high and after low blocks is 0.325 of its size before the transition (0.082 over trials 10 to 20), while for initiation times it is 2.31 times that size with the code's detrending and 1.97 times with the Methods' (2.42 and 2.06 over trials 10 to 20). Initiation time over whole mixed blocks is higher after high blocks (mean z +0.053 against -0.072) in all 291 rats, signed-rank p = 1.8e-49, and the same with transitions counted only within sessions.
suppfig5-mixed-to-adaptation-transitions¶
Longer timescale contrast effects also appear at transitions from mixed into high or low blocks for trial initiation times, but not for wait times.
Mixed-to-low and mixed-to-high curves as above. Over trials -20 to -1 (the mixed block) the initiation curve before a low block must lie above the one before a high block, and the wait time curves must differ by less than the initiation curves there, each as a fraction of its gap over trials 1 to 20.
for name, D in (("wait time", WD), ("initiation, pooled detrend (code)", LD), ("initiation, per-session detrend (Methods)", LS)):
g = popmean(D, "mtol") - popmean(D, "mtoh")
pre, post = window(g, -20, -1), window(g, 1, 20)
print(f"{name:42s} mixed-to-low minus mixed-to-high: trials -20..-1 {pre:+.3f}, 1..20 {post:+.3f}, relative {abs(pre / post):.3f}")
for name, D in (("initiation, pooled", LD), ("initiation, per session", LS)):
per = np.array([window(D[r]["mtol"] - D[r]["mtoh"], -20, -1) for r in RATS])
print(f"{name}: rats with the curve before low above the curve before high over -20..-1: {int(np.sum(per > 0))} of {int(np.isfinite(per).sum())}")
wait time mixed-to-low minus mixed-to-high: trials -20..-1 +0.013, 1..20 +0.095, relative 0.134 initiation, pooled detrend (code) mixed-to-low minus mixed-to-high: trials -20..-1 +0.062, 1..20 +0.254, relative 0.244 initiation, per-session detrend (Methods) mixed-to-low minus mixed-to-high: trials -20..-1 +0.049, 1..20 +0.242, relative 0.204 initiation, pooled: rats with the curve before low above the curve before high over -20..-1: 276 of 291 initiation, per session: rats with the curve before low above the curve before high over -20..-1: 261 of 291
Result: reproduced. In the mixed block before a transition, the initiation curve before a low block lies above the one before a high block (mean difference +0.062 with the code's detrending, +0.049 with the Methods'; 276 and 261 of 291 rats). As a fraction of their gap after the transition, the wait time curves differ less there (0.134) than the initiation curves (0.244 and 0.204).
fig2c-d-regression-on-previous-rewards¶
In mixed blocks, wait times are explained by the current offer and barely by previous offers, while trial initiation times reflect an exponentially decaying effect of previous rewards.
regress_wt_vs_rew.m and regress_latency_vs_rew.m (log2 offers, mixed blocks, offers from other blocks NaN, least squares with a constant), coefficients after the code's zeroing from the first one whose 95% interval contains 0 (as Figure2.m plots them), and before it (variant). Initiation times with 10 previous rewards (code) and 9 (Methods). The 95% interval across rats is the t interval of the mean.
from scipy.stats import t as tdist
def mean_ci(X):
mu = np.nanmean(X, 0); se = np.nanstd(X, 0, ddof=1) / np.sqrt(np.isfinite(X).sum(0))
q = tdist.ppf(0.975, np.isfinite(X).sum(0) - 1)
return mu, mu - q * se, mu + q * se
for lab, key in (("zeroed (Figure2.m)", "b_wt"), ("raw", "b_wt_raw")):
B = np.stack([TB[r][key] for r in RATS])
mu, lo, hi = mean_ci(B)
print(f"wait time, {lab}: current {mu[0]:+.4f} [{lo[0]:+.4f}, {hi[0]:+.4f}]; previous 1..9 {np.round(mu[1:10], 4).tolist()}")
print(f" current excludes 0: {lo[0] > 0}; |current| > every |previous|: {abs(mu[0]) > np.max(np.abs(mu[1:10]))}")
for lab, key in (("10 back, zeroed (code)", "b_iti"), ("9 back, zeroed (Methods)", "b_iti9"), ("10 back, raw", "b_iti_raw"), ("9 back, raw", "b_iti9_raw")):
B = np.stack([TB[r][key] for r in RATS])
mu = np.nanmean(B, 0)
k = 10 if "10" in lab else 9
ok = bool(np.all(mu[:3] < 0) and abs(mu[0]) > abs(mu[1]) > abs(mu[2]))
print(f"initiation, {lab}: lags 1..{k} {np.round(mu[:k], 4).tolist()}; lags 1-3 negative and shrinking: {ok}")
B = np.stack([TB[r]["b_iti"] for r in RATS])
print("rats with lag-1 initiation coefficient < 0:", int((B[:, 0] < 0).sum()), "of", len(B))
wait time, zeroed (Figure2.m): current +0.2110 [+0.2038, +0.2182]; previous 1..9 [-0.0033, 0.0, -0.0003, 0.0003, 0.0, 0.0, 0.0, 0.0, 0.0] current excludes 0: True; |current| > every |previous|: True wait time, raw: current +0.2113 [+0.2042, +0.2184]; previous 1..9 [-0.0061, -0.0117, -0.0097, -0.0125, -0.0128, -0.0096, -0.0114, -0.0081, -0.0099] current excludes 0: True; |current| > every |previous|: True initiation, 10 back, zeroed (code): lags 1..10 [-0.0299, -0.0225, -0.0104, -0.005, -0.0019, -0.0008, -0.0003, -0.0002, -0.0002, -0.0002]; lags 1-3 negative and shrinking: True initiation, 9 back, zeroed (Methods): lags 1..9 [-0.0301, -0.0227, -0.0105, -0.005, -0.0019, -0.0009, -0.0003, -0.0003, -0.0002]; lags 1-3 negative and shrinking: True initiation, 10 back, raw: lags 1..10 [-0.03, -0.0241, -0.012, -0.0072, -0.0035, -0.0022, -0.0009, -0.0013, -0.0009, -0.0008]; lags 1-3 negative and shrinking: True initiation, 9 back, raw: lags 1..9 [-0.0303, -0.0242, -0.012, -0.0072, -0.0036, -0.0022, -0.001, -0.0014, -0.0009]; lags 1-3 negative and shrinking: True rats with lag-1 initiation coefficient < 0: 250 of 291
Result: reproduced. In the mean over rats, the current offer coefficient for wait time is +0.211 (95% interval +0.204 to +0.218), larger in size than every previous offer coefficient (all within 0.004 of 0 after the code's zeroing, within 0.013 before it). The initiation time coefficients for 1, 2 and 3 trials back are negative and shrink with lag (-0.030, -0.023, -0.010 with 10 previous rewards; the same with 9, and before zeroing). Offers are the male volumes, as the claims file's common method says.
fig2e-tau-differ¶
The time constants of exponential fits to the previous trial coefficients differ between trial initiation times and wait times, with longer time constants for initiation times.
y = D exp(-x/tau) fitted by least squares from 10 random starts (fmincon in the code; L-BFGS-B here, a standard substitute); tau 0 when the coefficients are all 0. Methods reading: the 9 previous coefficients of each regression. Code reading: wait time over the current and 9 previous coefficients (times 10), initiation time over lags 1 to 10, with the code's rules for tau = 0.
TAU = pd.DataFrame({k: [TB[r][k] for r in RATS] for k in ["tau_wt_methods", "tau_iti_methods", "tau_wt_code", "tau_iti_code"]}, index=RATS)
for lab, a, b in (("Methods", "tau_wt_methods", "tau_iti_methods"), ("code", "tau_wt_code", "tau_iti_code")):
w = wilcoxon(TAU[a], TAU[b])
print(f"{lab:7s}: mean tau wait time {TAU[a].mean():.3f} (zero in {int((TAU[a] == 0).sum())} rats), initiation {TAU[b].mean():.3f}"
f" (zero in {int((TAU[b] == 0).sum())}); median {TAU[a].median():.3f} vs {TAU[b].median():.3f}; signed-rank p = {w.pvalue:.3g}")
print(f" rats with initiation tau > wait time tau: {int((TAU[b] > TAU[a]).sum())} of {len(TAU)}; tau at the upper bound 10: {int((TAU[b] >= 9.99).sum())}")
Methods: mean tau wait time 0.066 (zero in 248 rats), initiation 2.061 (zero in 18); median 0.000 vs 1.645; signed-rank p = 1.25e-45
rats with initiation tau > wait time tau: 267 of 291; tau at the upper bound 10: 9
code : mean tau wait time 0.098 (zero in 248 rats), initiation 2.034 (zero in 26); median 0.000 vs 1.650; signed-rank p = 2.28e-44
rats with initiation tau > wait time tau: 261 of 291; tau at the upper bound 10: 8
Result: reproduced. The time constants differ by the signed-rank test (p = 1.25e-45 under the Methods' reading and 2.28e-44 under the code's; the paper prints 1.3e-49), and the mean initiation time tau (2.06 and 2.03) is above the mean wait time tau (0.066 and 0.098). The wait time tau is 0 in 248 of 291 rats under both readings. The exponential is fitted by an exact least-squares profile over tau in place of fmincon's random starts (deviation).
fig2f-tau-uncorrelated¶
Across rats, the time constants for wait times and trial initiation times are not correlated.
Pearson correlation of the per-rat taus of fig2e-tau-differ, under both of its readings. Absence: reproduced when p >= 0.05.
Result: reproduced. The per-rat time constants are not correlated: r = -0.033, p = 0.572 (Methods' reading) and r = +0.023, p = 0.693 (code's reading). Both are far from significance. The Methods reading is close to the legend's r = -0.03, p = 0.53; the code's reading has the opposite sign, though it is near 0. The Results print r = 0.08, p = 0.18.
fig2g-h-fast-slow-tau-groups¶
Rats split by fast or slow temporal integration of initiation times (tau below the 20th or above the 80th percentile) differ in their initiation time regression coefficients but not in their wait time coefficients.
myTauShuffleTest.m with 500 shuffles, on the code's coefficients (initiation lags 1 to 10; wait time current and 9 previous), groups from the initiation taus of each reading of fig2e-tau-differ. The code fits every coefficient but the constant, so for wait times the current offer (about 0.2) is the first of the 10; times 10 it is near 2, beyond the shuffled fits' bound D <= 1, while the observed fits are not scaled. Shown as variants, not the paper's test: the 9 previous wait time coefficients only (the Methods' coefficients), and the observed fits on the same scale and bounds as the shuffled ones. The share of shuffled fits with D at its bound is printed for each.
rng_sh = np.random.default_rng(77)
BL = np.stack([TB[r]["b_iti"] for r in RATS])[:, :10]; BW = np.stack([TB[r]["b_wt"] for r in RATS])[:, :10]
BWM = np.stack([TB[r]["b_wt_methods"] for r in RATS])[:, 1:10] # the 9 previous offers only (Methods)
for lab, key in (("code taus", "tau_iti_code"), ("Methods taus", "tau_iti_methods")):
tl = TAU[key].values
fq, lq = tl < np.percentile(tl, 20), tl > np.percentile(tl, 80)
pl = m.tau_shuffle_test(fq, lq, BL, 500, rng_sh)
pw = m.tau_shuffle_test(fq, lq, BW, 500, rng_sh)
print(f"{lab}: fast {int(fq.sum())} rats, slow {int(lq.sum())} rats (N = {int(fq.sum() + lq.sum())}; paper 116)")
print(f" initiation: observed tau fast {pl[2]:.3f}, slow {pl[3]:.3f}, difference {pl[1]:+.3f}; p = {pl[0]:.3f} (paper 0.02); shuffled fits with D at the bound 1: {pl[4]:.3f}")
print(f" wait time (current + 9 previous, the code): observed tau fast {pw[2]:.3f}, slow {pw[3]:.3f}, difference {pw[1]:+.3f}; p = {pw[0]:.3f} (paper 0.1); shuffled fits with D at the bound 1: {pw[4]:.3f}")
# variants for the wait time test (not the paper's test): previous offers only; observed fits on the shuffle scale
for vlab, B_, ss in (("9 previous only", BWM, False), ("current + 9 previous, same scale", BW, True), ("9 previous only, same scale", BWM, True)):
pv = m.tau_shuffle_test(fq, lq, B_, 500, rng_sh, same_scale=ss)
print(f" variant, wait time ({vlab}): observed tau fast {pv[2]:.3f}, slow {pv[3]:.3f}, difference {pv[1]:+.3f}; p = {pv[0]:.3f}; shuffled fits with D at 1: {pv[4]:.3f}")
print(" mean initiation coefficients lags 1..5, fast:", np.round(BL[fq, :5].mean(0), 4).tolist(), "slow:", np.round(BL[lq, :5].mean(0), 4).tolist())
print(" mean wait time coefficients current..4 back, fast:", np.round(BW[fq, :5].mean(0), 4).tolist(), "slow:", np.round(BW[lq, :5].mean(0), 4).tolist())
code taus: fast 58 rats, slow 58 rats (N = 116; paper 116) initiation: observed tau fast 0.907, slow 3.895, difference -2.988; p = 0.000 (paper 0.02); shuffled fits with D at the bound 1: 0.000 wait time (current + 9 previous, the code): observed tau fast 0.572, slow 0.648, difference -0.076; p = 0.187 (paper 0.1); shuffled fits with D at the bound 1: 1.000
variant, wait time (9 previous only): observed tau fast 0.694, slow 0.111, difference +0.584; p = 0.223; shuffled fits with D at 1: 0.151 variant, wait time (current + 9 previous, same scale): observed tau fast 2.233, slow 2.587, difference -0.354; p = 0.000; shuffled fits with D at 1: 1.000
variant, wait time (9 previous only, same scale): observed tau fast 0.694, slow 0.181, difference +0.513; p = 0.249; shuffled fits with D at 1: 0.155 mean initiation coefficients lags 1..5, fast: [-0.0206, -0.0079, -0.0012, 0.0, 0.0] slow: [-0.0112, -0.0283, -0.0157, -0.0103, -0.0056] mean wait time coefficients current..4 back, fast: [0.1863, -0.0029, -0.0008, -0.0005, 0.0017] slow: [0.2353, -0.0012, 0.0, 0.0, 0.0]
Methods taus: fast 58 rats, slow 58 rats (N = 116; paper 116) initiation: observed tau fast 0.908, slow 3.880, difference -2.973; p = 0.000 (paper 0.02); shuffled fits with D at the bound 1: 0.000 wait time (current + 9 previous, the code): observed tau fast 0.574, slow 0.647, difference -0.073; p = 0.200 (paper 0.1); shuffled fits with D at the bound 1: 1.000
variant, wait time (9 previous only): observed tau fast 0.694, slow 0.111, difference +0.584; p = 0.235; shuffled fits with D at 1: 0.153 variant, wait time (current + 9 previous, same scale): observed tau fast 2.241, slow 2.582, difference -0.341; p = 0.000; shuffled fits with D at 1: 1.000
variant, wait time (9 previous only, same scale): observed tau fast 0.694, slow 0.181, difference +0.513; p = 0.260; shuffled fits with D at 1: 0.137 mean initiation coefficients lags 1..5, fast: [-0.0208, -0.008, -0.0012, 0.0, 0.0] slow: [-0.0117, -0.0281, -0.0159, -0.0106, -0.0059] mean wait time coefficients current..4 back, fast: [0.1873, -0.0029, -0.0008, -0.0005, 0.0017] slow: [0.2346, -0.0012, 0.0, 0.0, 0.0]
Result: reproduced. With 58 rats in each group (N = 116, as the paper), the shuffle test on the initiation time coefficients gives p = 0.000 under both readings of the taus (the paper 0.02), and on the wait time coefficients p = 0.187 (code taus) and 0.200 (Methods taus), not significant, as in the paper (p = 0.1). This test includes the current offer coefficient (about 0.19 to 0.23), and every shuffled wait time fit has D at its bound of 1, so its null is not on the observed fits' scale. With the 9 previous coefficients only (the Methods'), the variant gives p = 0.223 and 0.235 (0.249 and 0.260 with the observed fits on the shuffle scale; 15% of shuffled fits at the bound), also not significant. The variant that keeps the current coefficient and puts the observed fits on the shuffle scale gives p = 0.000, but there every fit, observed and shuffled, sits at the bound.
fig2j-wait-time-not-sensitive-to-previous-offer¶
In mixed blocks, wait times for 20 uL do not depend on whether the previous offer was smaller or larger than 20 uL, for 87% of rats (253 of 291) and for the population.
waittime_20ul_by_previous_vol.m per rat (two-tailed rank-sum); count of rats with p < 0.05 (expected 38 +- 4). Population: two-tailed rank-sum on the per-rat means (legend), signed-rank as a variant (Figure2.m).
nsig = int((PR.wp_p < 0.05).sum())
print("rats with p < 0.05:", nsig, "of", int(PR.wp_p.notna().sum()), "; not significant:", int((PR.wp_p >= 0.05).sum()))
a, b = PR.wp_lo.dropna(), PR.wp_hi.dropna()
print("population mean z wait time: previous < 20 uL", round(a.mean(), 4), ", previous > 20 uL", round(b.mean(), 4))
print("rank-sum on per-rat means: p =", round(mannwhitneyu(a, b).pvalue, 3), "; signed-rank (variant): p =", round(wilcoxon(PR.wp_lo, PR.wp_hi, nan_policy="omit").pvalue, 3), "(paper 0.8)")
rats with p < 0.05: 38 of 291 ; not significant: 253 population mean z wait time: previous < 20 uL -0.0068 , previous > 20 uL 0.005 rank-sum on per-rat means: p = 0.708 ; signed-rank (variant): p = 0.808 (paper 0.8)
Result: reproduced. 38 of 291 rats have p < 0.05 (expected 38 +- 4), so 253 do not, the paper's count. At the population, z-scored wait times after offers below and above 20 uL do not differ (-0.007 against +0.005; rank-sum on per-rat means p = 0.708, signed-rank p = 0.808, the paper 0.8).
fig2k-initiation-sensitive-to-previous-offer¶
In mixed blocks, trial initiation times are slower after offers smaller than 20 uL than after offers larger than 20 uL, significantly so for 89% of rats (256 of 291) and for the population.
Two readings of which trials: all mixed-block trials (latency_post20ul_by_previous_vol.m) and 20 uL mixed-block trials (Methods). Per-rat two-tailed rank-sum; count with p < 0.05 (expected 256 +- 26). Population: rank-sum on per-rat means (legend) and signed-rank (Figure2.m).
for lab, k in (("code, all mixed-block trials", "ip"), ("Methods, 20 uL mixed-block trials", "im")):
lo, hi, p = PR[f"{k}_lo"], PR[f"{k}_hi"], PR[f"{k}_p"]
print(f"{lab}: rats with p < 0.05: {int((p < 0.05).sum())}; of these slower after smaller offers: {int(((p < 0.05) & (lo > hi)).sum())};"
f" mean z after < 20 {lo.mean():+.3f}, after > 20 {hi.mean():+.3f};"
f" rank-sum p = {mannwhitneyu(lo, hi).pvalue:.3g}; signed-rank p = {wilcoxon(lo, hi).pvalue:.3g}; rats slower after smaller {int((lo > hi).sum())}")
code, all mixed-block trials: rats with p < 0.05: 255; of these slower after smaller offers: 255; mean z after < 20 +0.099, after > 20 -0.149; rank-sum p = 9.34e-97; signed-rank p = 1.84e-49; rats slower after smaller 290 Methods, 20 uL mixed-block trials: rats with p < 0.05: 265; of these slower after smaller offers: 202; mean z after < 20 +0.000, after > 20 -0.083; rank-sum p = 9.71e-25; signed-rank p = 9.36e-29; rats slower after smaller 227
Result: reproduced. Using all mixed-block trials (the code), 255 rats have p < 0.05 (expected 256 +- 26), all slower after smaller offers, and the population is slower after smaller offers (mean z +0.099 against -0.149; rank-sum p = 9.34e-97, signed-rank p = 1.84e-49, the legend 1.84e-49). Using 20 uL trials only (the Methods), 265 rats have p < 0.05, of which 202 are slower after smaller offers, and the population effect is smaller but holds (+0.000 against -0.083; rank-sum p = 9.71e-25).
fig2l-sensitivity-greater-for-initiation¶
Sensitivity to the previous offer is larger for trial initiation times than for wait times across rats.
Sensitivity = mean after offers below 20 uL minus mean after offers above, per rat (Methods; Figure2.m); paired signed-rank; under each reading of fig2k.
sw = PR.wp_lo - PR.wp_hi
print("wait time sensitivity: mean", round(sw.mean(), 4), "; rats", int(sw.notna().sum()))
for lab, k in (("code reading", "ip"), ("Methods reading", "im")):
si = PR[f"{k}_lo"] - PR[f"{k}_hi"]
w = wilcoxon(si, sw, nan_policy="omit")
print(f"{lab}: initiation sensitivity mean {si.mean():+.4f}; rats with initiation > wait time sensitivity {int((si > sw).sum())}; signed-rank p = {w.pvalue:.3g} (paper 6.21e-38)")
wait time sensitivity: mean -0.0119 ; rats 291 code reading: initiation sensitivity mean +0.2476; rats with initiation > wait time sensitivity 247; signed-rank p = 6.09e-38 (paper 6.21e-38) Methods reading: initiation sensitivity mean +0.0828; rats with initiation > wait time sensitivity 183; signed-rank p = 2.19e-08 (paper 6.21e-38)
Result: reproduced. Mean sensitivity to the previous offer is +0.248 for initiation times (code's reading) against -0.012 for wait times, signed-rank p = 6.09e-38 (the paper 6.21e-38); under the Methods' reading it is +0.083, p = 2.19e-08.
suppfig6-results-without-detrending¶
Satiety effects on trial initiation times are modest, and the results, including the dynamics at block transitions, do not change qualitatively without detrending.
The initiation transition curves without the trial-number regression (block_dynamics_latency.m with detrending off); part (2) of fig2a (which does not detrend) and the ordering of the curves over trials 1 to 20 of the mixed block (above after high blocks, below after low blocks).
for name, D in (("no detrend", LN), ("pooled detrend", LD)):
h, l = popmean(D, "htom"), popmean(D, "ltom")
print(f"{name:15s}: mean over trials 1..20 after high {window(h, 1, 20):+.3f}, after low {window(l, 1, 20):+.3f};"
f" before (-20..-1) high block {window(h, -20, -1):+.3f}, low block {window(l, -20, -1):+.3f}")
per = np.array([window(LN[r]["htom"] - LN[r]["ltom"], 1, 20) for r in RATS])
print("rats with post-high above post-low over 1..20 without detrending:", int(np.sum(per > 0)), "of", int(np.isfinite(per).sum()))
# satiety: slope of z-scored initiation time against trial number, pooled per rat
sl = []
for r in RATS:
d = R[r]; L = d["iti"].copy(); L[d["first"]] = np.nan; z = m.nanz(m.clip99(L)); ok = np.isfinite(z)
sl.append(np.polyfit(d["trial"][ok] + 1, z[ok], 1)[0] * 100)
sl = np.array(sl)
print("trend of z-scored initiation time per 100 trials: median", round(float(np.median(sl)), 4), "; 5th to 95th percentile", np.round(np.percentile(sl, [5, 95]), 4).tolist())
print("part (2) of fig2a is computed without detrending: see that section (p printed there)")
no detrend : mean over trials 1..20 after high +0.147, after low -0.109; before (-20..-1) high block -0.059, low block +0.033 pooled detrend : mean over trials 1..20 after high +0.122, after low -0.124; before (-20..-1) high block -0.078, low block +0.029 rats with post-high above post-low over 1..20 without detrending: 291 of 291
trend of z-scored initiation time per 100 trials: median 0.0505 ; 5th to 95th percentile [0.0094, 0.1221] part (2) of fig2a is computed without detrending: see that section (p printed there)
Result: reproduced. Without detrending, initiation times over trials 1 to 20 of the mixed block are still higher after high blocks (+0.147) than after low blocks (-0.109), in all 291 rats, and part (2) of fig2a, which does not detrend, holds (p = 1.8e-49). The trend that detrending removes is small: a median 0.05 z per 100 trials.
fig3c-wait-time-by-catch-probability¶
Rats' wait times in mixed blocks depend in a graded way on the catch probability, as the wait time model predicts.
wtByPCatch.m: per rat and catch probability, mean wait time on catch trials in mixed blocks by offer, leaving out
the rat's first 1000 trials; then the mean over rats with data at that probability. The catch probability of
each trial is the raw table's catch_percentage (the processed table has none). Rats per cohort are the rats with
data at that probability, which is what the figure averages; the rat's most common probability is a variant.
The dataset also holds probability 0.3, not among the paper's five.
PC = {r: m.wt_by_pcatch(R[r]) for r in RATS}
means, counts = {}, {}
for p in m.PCATCH:
M = np.stack([PC[r][p] for r in RATS]); has = np.isfinite(M).any(1)
means[p] = np.nanmean(M[has], 0); counts[p] = int(has.sum())
print(f"p = {p:.2f}: rats {counts[p]:3d}; mean wait time 5..80 uL {np.round(means[p], 2).tolist()}")
print("expected rats: 0.1: 3, 0.15: 183, 0.2: 61, 0.25: 151, 0.35: 39")
dec = (means[0.15] > means[0.2]) & (means[0.2] > means[0.25])
print("offers where the mean decreases from 0.15 to 0.2 to 0.25:", int(dec.sum()), "of 5", dec.tolist())
cp = TR.groupby("subject").catch_p.agg(lambda x: x.round(2).mode().iloc[0])
print("variant, rats by their most common catch probability:", cp.value_counts().sort_index().to_dict())
# variant: opt-out catch trials only (the claims file's common method; wtByPCatch.m does not ask for an opt-out)
nco = int(sum(int((R[r]["catch"] & ~R[r]["optout"] & np.isfinite(R[r]["wt"])).sum()) for r in RATS))
print("catch trials with a wait time but no opt-out, all rats:", nco)
PCo = {r: m.wt_by_pcatch(R[r], optout=True) for r in RATS}
mo = {p: np.nanmean(np.stack([PCo[r][p] for r in RATS]), 0) for p in m.PCATCH}
deco = (mo[0.15] > mo[0.2]) & (mo[0.2] > mo[0.25])
print("variant, opt-out only: 20 uL means at 0.15, 0.2, 0.25:", [round(float(mo[p][2]), 2) for p in (0.15, 0.2, 0.25)], "; offers decreasing:", int(deco.sum()), "of 5")
p = 0.10: rats 3; mean wait time 5..80 uL [12.6, 13.59, 14.58, 17.26, 18.54] p = 0.15: rats 188; mean wait time 5..80 uL [11.28, 11.71, 12.1, 14.42, 15.14] p = 0.20: rats 61; mean wait time 5..80 uL [10.25, 10.61, 11.08, 13.06, 13.83] p = 0.25: rats 151; mean wait time 5..80 uL [10.1, 10.34, 10.61, 12.43, 13.04] p = 0.30: rats 8; mean wait time 5..80 uL [8.99, 9.38, 9.59, 11.14, 11.95] p = 0.35: rats 40; mean wait time 5..80 uL [9.39, 9.79, 9.89, 11.49, 12.45] expected rats: 0.1: 3, 0.15: 183, 0.2: 61, 0.25: 151, 0.35: 39 offers where the mean decreases from 0.15 to 0.2 to 0.25: 5 of 5 [True, True, True, True, True]
variant, rats by their most common catch probability: {0.15000000596046448: 107, 0.20000000298023224: 42, 0.25: 126, 0.30000001192092896: 6, 0.3499999940395355: 10}
catch trials with a wait time but no opt-out, all rats: 140
variant, opt-out only: 20 uL means at 0.15, 0.2, 0.25: [12.1, 11.08, 10.61] ; offers decreasing: 5 of 5
Result: reproduced. Rats with data at each catch probability number 3, 188, 61, 151 and 40 for 0.1, 0.15, 0.2, 0.25 and 0.35, all within tolerance of 3, 183, 61, 151 and 39. At all 5 offers the mean wait time decreases from 0.15 to 0.2 to 0.25 (at 20 uL 12.10, 11.08, 10.61 s). The 0.1 cohort waits longest and the 0.35 cohort among the shortest. The dandiset also holds probability 0.3, for 8 rats, which the paper does not list. wtByPCatch.m does not ask for an opt-out; 140 catch trials over all rats have a wait time without one, and with opt-out trials only the 20 uL means are the same to 0.01 s and the decrease holds at all 5 offers.
fig3i-retrospective-model-captures-initiation¶
A retrospective model with a learning rate scaled by changes in the inferred block posterior captures the slow and fast dynamics of trial initiation times at block transitions and their dependence on previous rewards, while a static learning rate or an unsigned prediction error gain does not.
Simulated initiation times TI = D/kappa on rat J004's trials, as Figure3.m and FigureS7.m do (they load J004), 50 simulations each, log-normal noise. Equation 10 model: alpha_0 = 0.1042, D = 0.2527 (Figure3.m), smoothing 15, noise variance 8 (Figure3.m) and 4 (Methods). Alternatives (G = 1 and G = |delta|): alpha_0 = 0.05, 0.4 and 0.8, noise 4, smoothing 20 (FigureS7.m). Each script's own scaling of D and initial kappa is used. Overshoot = maximum of the high-to-mixed curve over trials 1 to 20 minus its value at trial 20; persistent gap = mean over trials 1 to 20 of the high-to-mixed minus the low-to-mixed curve. For Fig. 3i, the Equation 10 model's simulated times (noise 1.5, as Figure3.m) for each rat go through latency_post20ul_by_previous_vol.m; the per-rat parameters of Figure3.m come from fits that are not in the dataset, so J004's parameters are used for every rat (an assumption).
The overshoot measure has no threshold, and on a noisy, smoothed curve its maximum over 20 trials exceeds the end value even when nothing changes. A noise-only control (a constant time with the same noise and smoothing) gives the size the measures reach by chance, and the noise-free curves without smoothing give the models' own shapes.
rng_sim = np.random.default_rng(724)
dJ = R["J004"]
good, vols, new = m.model_trials(dJ)
belief, prior = m.infer_blocks(vols, new, m.transition_matrix(reading="code"))
lv = np.log2(vols.astype(float))
def simulate(model, alpha0, D, noise, smooth, nsims=50, inner=1):
if model == "flat": # noise-only control: a constant time, the Equation 10 model's mean
g, lvv, nw = good, lv, new
k = np.full(len(lvv), np.nan)
opt = np.full(len(lvv), float(np.nanmean(D / m.retrospective_kappa(lv, new, belief[:, 0], 0.1042, "alphaPH"))))
elif model == "alphaPH":
g, lvv, nw, bm = good, lv, new, belief[:, 0]
else: # these scripts use the trials with an initiation time
g = np.isfinite(dJ["iti"])
o = dJ["order"][g]; nw = np.r_[True, o[1:] != o[:-1]]
lvv = np.log2(dJ["vol"][g].astype(float)); bm = None
if model != "flat":
k = m.retrospective_kappa(lvv, nw, bm, alpha0, model)
opt = D / k
hs, ls = [], []
for _ in range(nsims):
iti = np.full(len(dJ["vol"]), np.nan)
iti[g] = opt if noise is None else m.lognormal_noise(opt, noise, rng_sim, inner)
c = m.lat_dynamics(dJ, smooth=smooth, iti=iti)
hs.append(c["htom"]); ls.append(c["ltom"])
h, l = np.nanmean(hs, 0), np.nanmean(ls, 0)
over = float(np.nanmax(h[(OFF >= 1) & (OFF <= 20)]) - h[OFF == 20][0])
gap = window(h - l, 1, 20)
return over, gap, h, l
res = {}
for noise in (8, 4):
o, g_, h, l = simulate("alphaPH", 0.1042, 0.2527 * 25, noise, 15)
res[("alphaPH", noise)] = (o, g_)
print(f"Equation 10 model, noise {noise}: overshoot {o:+.4f}, persistent gap {g_:+.4f}; both present: {o > 0 and g_ > 0}")
print(" high-to-mixed curve, trials 0..20:", np.round(h[20:], 3).tolist())
for model, Dscale, inner in (("vanilla", 10, 10), ("rpe", 15, 1)):
for a0 in (0.05, 0.4, 0.8):
o, g_, h, l = simulate(model, a0, 0.2527 * Dscale, 4, 20, inner=inner)
print(f"{model:8s} alpha_0 {a0:.2f}: overshoot {o:+.4f}, persistent gap {g_:+.4f}; lacks one of the two: {not (o > 0 and g_ > 0)}")
o0, g0, _, _ = simulate(model, a0, 0.2527 * Dscale, None, 20, nsims=1)
print(f" without noise (variant): overshoot {o0:+.4f}, persistent gap {g0:+.4f}")
o0, g0, _, _ = simulate("alphaPH", 0.1042, 0.2527 * 25, None, 15, nsims=1)
print(f"Equation 10 model without noise (variant): overshoot {o0:+.4f}, persistent gap {g0:+.4f}")
# Controls the measures were not given (verifier, round 1). (1) Noise-only: a flat time with the same noise and
# smoothing, 20 repeats of 50 simulations each; what the overshoot and gap measures give with no dynamics.
for noise, sm in ((8, 15), (4, 15), (4, 20)):
oo = [simulate("flat", 0, 0.2527 * 25, noise, sm)[:2] for _ in range(20)]
oo = np.array(oo)
print(f"noise-only control, noise {noise}, smoothing {sm}: overshoot mean {oo[:, 0].mean():+.4f} (95th percentile {np.percentile(oo[:, 0], 95):+.4f}, positive in {int((oo[:, 0] > 0).sum())} of 20);"
f" gap mean {oo[:, 1].mean():+.4f} (95th percentile {np.percentile(oo[:, 1], 95):+.4f})")
# (2) Noise-free curves without smoothing, and the full noise-free high-to-mixed and low-to-mixed curves
print("noise-free, unsmoothed:")
for model, a0, Ds in (("alphaPH", 0.1042, 25), ("vanilla", 0.05, 10), ("vanilla", 0.4, 10), ("vanilla", 0.8, 10), ("rpe", 0.05, 15), ("rpe", 0.4, 15), ("rpe", 0.8, 15)):
o0, g0, h0, l0 = simulate(model, a0, 0.2527 * Ds, None, 1, nsims=1)
print(f" {model:8s} alpha_0 {a0:.4f}: overshoot {o0:+.4f}, gap {g0:+.4f}")
print(" high-to-mixed, trials -5..20:", np.round(h0[15:], 3).tolist())
print(" low-to-mixed, trials -5..20:", np.round(l0[15:], 3).tolist())
Equation 10 model, noise 8: overshoot +0.0162, persistent gap +0.2393; both present: True high-to-mixed curve, trials 0..20: [-0.038, -0.013, 0.023, 0.049, 0.075, 0.103, 0.128, 0.132, 0.163, 0.183, 0.197, 0.21, 0.215, 0.212, 0.204, 0.196, 0.201, 0.197, 0.179, 0.198, 0.198]
Equation 10 model, noise 4: overshoot +0.0808, persistent gap +0.2865; both present: True high-to-mixed curve, trials 0..20: [-0.062, -0.024, 0.015, 0.05, 0.082, 0.123, 0.153, 0.162, 0.199, 0.224, 0.245, 0.26, 0.268, 0.262, 0.257, 0.248, 0.25, 0.24, 0.212, 0.226, 0.188]
vanilla alpha_0 0.05: overshoot +0.0000, persistent gap -0.3793; lacks one of the two: True
without noise (variant): overshoot +0.0000, persistent gap -1.1990
vanilla alpha_0 0.40: overshoot +0.0591, persistent gap -0.0298; lacks one of the two: True
without noise (variant): overshoot +0.1247, persistent gap -0.0502
vanilla alpha_0 0.80: overshoot +0.0810, persistent gap +0.0041; lacks one of the two: False
without noise (variant): overshoot +0.1128, persistent gap -0.0001
rpe alpha_0 0.05: overshoot +0.0266, persistent gap -0.1072; lacks one of the two: True
without noise (variant): overshoot +0.0000, persistent gap -0.8295
rpe alpha_0 0.40: overshoot +0.0204, persistent gap +0.0124; lacks one of the two: False
without noise (variant): overshoot +0.0742, persistent gap +0.0253
rpe alpha_0 0.80: overshoot +0.0284, persistent gap +0.0055; lacks one of the two: False
without noise (variant): overshoot +0.0831, persistent gap +0.0129
Equation 10 model without noise (variant): overshoot +0.1613, persistent gap +1.1019
noise-only control, noise 8, smoothing 15: overshoot mean +0.0189 (95th percentile +0.0459, positive in 16 of 20); gap mean +0.0000 (95th percentile +0.0100)
noise-only control, noise 4, smoothing 15: overshoot mean +0.0182 (95th percentile +0.0575, positive in 15 of 20); gap mean +0.0036 (95th percentile +0.0199)
noise-only control, noise 4, smoothing 20: overshoot mean +0.0113 (95th percentile +0.0291, positive in 13 of 20); gap mean -0.0002 (95th percentile +0.0104)
noise-free, unsmoothed:
alphaPH alpha_0 0.1042: overshoot +0.4307, gap +1.2439
high-to-mixed, trials -5..20: [-1.175, -1.18, -1.147, -1.148, nan, -1.161, -1.081, -0.951, -0.406, -0.445, 0.604, 0.289, 0.793, 0.953, 1.091, 0.993, 0.897, 1.25, 0.892, 1.018, 1.258, 0.915, 0.964, 0.994, 0.781, 0.828]
low-to-mixed, trials -5..20: [1.606, 1.453, 1.589, 1.502, nan, 1.559, 1.247, 0.683, -0.196, -0.513, -1.059, -0.77, -0.95, -0.617, -0.813, -0.467, -0.776, -1.072, -0.871, -0.978, -0.855, -1.183, -0.896, -1.148, -0.977, -1.027]
vanilla alpha_0 0.0500: overshoot +0.0000, gap -1.2108
high-to-mixed, trials -5..20: [-0.898, -0.898, -0.9, -0.904, nan, -0.909, -0.899, -0.857, -0.814, -0.771, -0.734, -0.695, -0.654, -0.62, -0.594, -0.571, -0.543, -0.518, -0.483, -0.443, -0.402, -0.358, -0.34, -0.315, -0.297, -0.281]
low-to-mixed, trials -5..20: [1.274, 1.271, 1.232, 1.24, nan, 1.243, 1.162, 1.076, 0.994, 0.924, 0.863, 0.821, 0.779, 0.706, 0.696, 0.668, 0.633, 0.588, 0.513, 0.44, 0.415, 0.369, 0.347, 0.362, 0.346, 0.327]
vanilla alpha_0 0.4000: overshoot +0.3054, gap +0.1057
high-to-mixed, trials -5..20: [-0.976, -0.952, -0.957, -0.968, nan, -0.979, -0.823, -0.499, -0.247, -0.084, 0.012, 0.097, 0.16, 0.132, 0.081, -0.004, -0.032, -0.032, 0.092, 0.186, 0.282, 0.36, 0.185, 0.08, 0.11, 0.055]
low-to-mixed, trials -5..20: [0.909, 0.865, 0.836, 0.909, nan, 0.75, 0.312, 0.055, -0.088, -0.114, -0.099, -0.029, -0.015, 0.08, 0.009, 0.041, -0.128, -0.197, -0.259, -0.348, -0.338, -0.354, -0.237, -0.182, -0.078, -0.032]
vanilla alpha_0 0.8000: overshoot +0.2684, gap +0.1768
high-to-mixed, trials -5..20: [-0.851, -0.824, -0.849, -0.86, nan, -0.875, -0.484, 0.014, 0.196, 0.179, 0.171, 0.189, 0.232, 0.151, 0.02, -0.068, -0.012, -0.007, 0.157, 0.292, 0.34, 0.341, 0.103, 0.045, 0.105, 0.073]
low-to-mixed, trials -5..20: [0.663, 0.65, 0.613, 0.729, nan, 0.46, 0.044, -0.181, -0.212, -0.138, -0.091, -0.003, 0.007, 0.231, 0.043, 0.075, -0.137, -0.255, -0.237, -0.322, -0.25, -0.237, -0.026, 0.001, 0.111, 0.075]
rpe alpha_0 0.0500: overshoot +0.0010, gap -0.7871
high-to-mixed, trials -5..20: [-1.422, -1.418, -1.416, -1.415, nan, -1.417, -1.331, -1.174, -1.023, -0.906, -0.802, -0.701, -0.606, -0.532, -0.493, -0.467, -0.45, -0.426, -0.363, -0.3, -0.245, -0.175, -0.165, -0.135, -0.131, -0.132]
low-to-mixed, trials -5..20: [1.422, 1.43, 1.417, 1.424, nan, 1.394, 1.16, 0.924, 0.747, 0.62, 0.518, 0.473, 0.401, 0.384, 0.335, 0.316, 0.217, 0.119, 0.043, -0.056, -0.128, -0.177, -0.181, -0.184, -0.177, -0.172]
rpe alpha_0 0.4000: overshoot +0.2149, gap +0.2128
high-to-mixed, trials -5..20: [-0.911, -0.897, -0.898, -0.902, nan, -0.91, -0.307, 0.22, 0.319, 0.227, 0.205, 0.243, 0.316, 0.203, 0.043, 0.025, 0.012, -0.006, 0.256, 0.378, 0.383, 0.395, 0.104, 0.138, 0.201, 0.18]
low-to-mixed, trials -5..20: [0.583, 0.586, 0.509, 0.568, nan, 0.434, 0.015, -0.238, -0.214, -0.176, -0.072, -0.034, 0.03, 0.251, 0.07, 0.051, -0.159, -0.233, -0.106, -0.325, -0.143, -0.084, 0.117, 0.088, 0.299, 0.141]
rpe alpha_0 0.8000: overshoot +0.2192, gap +0.1843
high-to-mixed, trials -5..20: [-0.839, -0.82, -0.846, -0.848, nan, -0.859, -0.286, 0.175, 0.252, 0.155, 0.143, 0.177, 0.245, 0.127, 0.011, -0.003, 0.022, -0.022, 0.223, 0.315, 0.311, 0.341, 0.079, 0.119, 0.145, 0.121]
low-to-mixed, trials -5..20: [0.58, 0.58, 0.504, 0.646, nan, 0.353, 0.006, -0.246, -0.189, -0.13, -0.086, -0.027, 0.003, 0.236, 0.069, 0.093, -0.147, -0.226, -0.138, -0.307, -0.159, -0.162, 0.075, 0.031, 0.191, 0.078]
rng_sim3i = np.random.default_rng(3)
lo_m, hi_m = [], []
for r in RATS:
d = R[r]
g, v, nw = m.model_trials(d)
b, _ = m.infer_blocks(v, nw, m.transition_matrix(reading="code"))
k = m.retrospective_kappa(np.log2(v.astype(float)), nw, b[:, 0], 0.1042, "alphaPH")
iti = np.full(len(d["vol"]), np.nan)
iti[g] = m.lognormal_noise(0.2527 * 25 / k, 1.5, rng_sim3i)
dd = dict(d); dd["iti"] = iti
a, bb, _ = m.iti_by_previous(dd, "code")
lo_m.append(a); hi_m.append(bb)
lo_m, hi_m = np.array(lo_m), np.array(hi_m)
print("model, mean z initiation time after offers < 20 uL:", round(float(np.nanmean(lo_m)), 4), "; after > 20 uL:", round(float(np.nanmean(hi_m)), 4),
"; rats higher after smaller:", int(np.sum(lo_m > hi_m)), "of", int(np.isfinite(lo_m - hi_m).sum()))
print("rats (fig2k, code reading): after < 20", round(PR.ip_lo.mean(), 4), ", after > 20", round(PR.ip_hi.mean(), 4))
model, mean z initiation time after offers < 20 uL: 0.0521 ; after > 20 uL: -0.0494 ; rats higher after smaller: 290 of 291 rats (fig2k, code reading): after < 20 0.0988 , after > 20 -0.1487
# Fig. 3i direction over alpha_0: the Equation 10 model without noise (initiation time D x 25 / kappa), D 0.2527,
# for each rat, at alpha_0 from 0.01 to 0.8 (J004's fit is 0.1042).
A0_3I = [0.01, 0.05, 0.1042, 0.2, 0.4, 0.8]
dif3i = {a0: [] for a0 in A0_3I}
for r in RATS:
d = R[r]
g, v, nw = m.model_trials(d)
b, _ = m.infer_blocks(v, nw, m.transition_matrix(reading="code"))
for a0 in A0_3I:
k = m.retrospective_kappa(np.log2(v.astype(float)), nw, b[:, 0], a0, "alphaPH")
iti = np.full(len(d["vol"]), np.nan); iti[g] = 0.2527 * 25 / k
dd = dict(d); dd["iti"] = iti
a, bb, _ = m.iti_by_previous(dd, "code")
dif3i[a0].append(a - bb)
for a0 in A0_3I:
x = np.array(dif3i[a0])
print(f"alpha_0 {a0:6.4f}: noise-free model, mean z after < 20 minus after > 20 {np.nanmean(x):+.4f} (range {np.nanmin(x):+.4f} to {np.nanmax(x):+.4f});"
f" rats higher after smaller {int(np.sum(x > 0))} of {int(np.isfinite(x).sum())}")
alpha_0 0.0100: noise-free model, mean z after < 20 minus after > 20 +0.0771 (range -0.0732 to +0.2076); rats higher after smaller 273 of 291 alpha_0 0.0500: noise-free model, mean z after < 20 minus after > 20 +0.2506 (range +0.0030 to +0.4097); rats higher after smaller 291 of 291 alpha_0 0.1042: noise-free model, mean z after < 20 minus after > 20 +0.3548 (range -0.0007 to +0.5638); rats higher after smaller 290 of 291 alpha_0 0.2000: noise-free model, mean z after < 20 minus after > 20 +0.5176 (range +0.0103 to +0.8297); rats higher after smaller 291 of 291 alpha_0 0.4000: noise-free model, mean z after < 20 minus after > 20 +0.7964 (range +0.0263 to +1.2809); rats higher after smaller 291 of 291 alpha_0 0.8000: noise-free model, mean z after < 20 minus after > 20 +1.0759 (range +0.0457 to +1.7378); rats higher after smaller 291 of 291
Result: partially reproduced. The Equation 10 model shows both an overshoot after the high-to-mixed transition (+0.016 with noise variance 8, +0.081 with 4) and a persistent post-high above post-low gap (+0.239 and +0.287). The static learning rate lacks one of the two at alpha_0 0.05 and 0.4, but at 0.8 shows both by a margin of +0.0041 in the gap (-0.0001 without noise). The unsigned prediction error gain lacks the gap only at 0.05; at 0.4 and 0.8 it shows both, with gaps of +0.012 and +0.006 (+0.025 and +0.013 without noise), small beside the Equation 10 model's. As the criterion has no threshold, the alternatives fail it at three of six settings.
The measures do not separate the models well, and the two controls point different ways. The noise-only control (a flat time) gives a mean overshoot of +0.019, +0.018 and +0.011 (95th percentiles +0.046, +0.058 and +0.029) and gaps with 95th percentiles of +0.010 to +0.020, for noise 8, 4 and 4 and smoothing 15, 15 and 20. Against those percentiles, every alternative lacks one feature at every alpha_0: the static rate's gap at 0.8 (+0.0041) and the unsigned gain's overshoots at 0.4 and 0.8 (+0.020 and +0.028, below +0.029) are within noise. The Equation 10 model shows both at noise 4 (overshoot +0.081 against +0.058) but its overshoot at noise 8 (+0.016) is within noise. Without noise or smoothing, every model shows an overshoot (+0.43 for the Equation 10 model, +0.21 to +0.31 for the alternatives at 0.4 and 0.8), and the alternatives at 0.4 and 0.8 show gaps of +0.11 to +0.21, against +1.24 for the Equation 10 model, so there the alternatives show both. The criterion sets no threshold, and as written the alternatives fail it at three of six settings, so the outcome stays partially reproduced.
With J004's parameters for every rat (an assumption), the model's initiation times are higher after offers below 20 uL (+0.052 z) than above (-0.049 z), in 290 of 291 rats, as the rats are. The direction does not depend on J004's alpha_0: without noise, at alpha_0 from 0.01 to 0.8 the model's initiation times are higher after offers below 20 uL by +0.077 to +1.076 z on average, in 273 of 291 rats at 0.01, 290 at 0.1042 and all 291 at 0.05, 0.2, 0.4 and 0.8.
fig3f-inferential-model-not-sensitive-to-previous-offer¶
Wait times predicted by the inferential model fitted to each rat are, like the rats' wait times, not sensitive to the previous offer for 20 uL in mixed blocks.
The inferential model as GenerateSynthData_Bayes.m computes it: the most likely block on each trial with a wait time (code's transition matrix, belief reset at session starts), kappa for that block, wait time by Equation 1 with tau = 2.5 s and C = max(1 - catch probability), parameters [kappa_mixed, kappa_high, kappa_low, D] in [0, 1] scaled as the script does. Fitted per rat on all data by maximum likelihood (Methods, Fitting and evaluating models: 100 random starts; scipy's bounded L-BFGS-B in place of fmincon), with log-normal noise of variance 8 (Methods, Behavioral models). The fitting code is not in the paper's repository; the likelihood is taken over opt-out catch trials, the trials where the wait time is the rat's choice (an assumption). Then, as Figure3.m does, the rat's wait times are replaced by one noisy draw from the fitted model (WTMdl) and passed through waittime_20ul_by_previous_vol.m; population two-tailed rank-sum on the per-rat means (the claim's reading), reproduced when p >= 0.05. The noise-free predictions (WTOpt) are a variant. A parameter recovery check on J004 comes first.
rng_inf = np.random.default_rng(3103)
# recovery: J004's fit, data drawn from it, refitted
pJ, _, nJ, _, stJ = m.fit_inferential(R["J004"], rng_inf, 100)
dsyn = dict(R["J004"]); wsyn = np.full(len(dsyn["vol"]), np.nan)
wsyn[stJ["good"]] = m.lognormal_noise(m.inferential_wt_opt(pJ, stJ), m.WT_NOISE, rng_inf); dsyn["wt"] = wsyn
pJ2, *_ = m.fit_inferential(dsyn, rng_inf, 100)
print("recovery on J004 (kappa_mixed, kappa_high, kappa_low, D): generating", np.round(pJ, 4).tolist(), "; recovered", np.round(pJ2, 4).tolist())
t = time.time()
F3 = []
for r in RATS:
d = R[r]
p_, nll_, nobs_, nev_, st_ = m.fit_inferential(d, rng_inf, 100)
wo = m.inferential_wt_opt(p_, st_)
row = dict(rat=r, k_mi=p_[0], k_hi=p_[1], k_lo=p_[2], D=p_[3], nll=nll_, n_obs=nobs_, evals=nev_)
for lab, w_ in (("mdl", m.lognormal_noise(wo, m.WT_NOISE, rng_inf)), ("opt", wo)):
dd = dict(d); ww = np.full(len(d["vol"]), np.nan); ww[st_["good"]] = w_; dd["wt"] = ww
a_, b_, pp_ = m.wt_by_previous(dd)
row.update({f"{lab}_lo": a_, f"{lab}_hi": b_, f"{lab}_p": pp_})
row["mislabel_mixed"] = float(np.mean(st_["blk"][d["block"][st_["good"]] == 1] != 0))
F3.append(row)
F3 = pd.DataFrame(F3).set_index("rat")
T_FIT_RAT = (time.time() - t) / len(RATS)
print(f"fitted {len(F3)} rats in {time.time() - t:.0f} s; mean L-BFGS-B evaluations per start {F3.evals.mean():.0f}; opt-out catch trials per rat, median {F3.n_obs.median():.0f}")
print("fitted parameters, median over rats:", F3[["k_mi", "k_hi", "k_lo", "D"]].median().round(4).to_dict(),
"; rats with kappa_high > kappa_mixed > kappa_low:", int(((F3.k_hi > F3.k_mi) & (F3.k_mi > F3.k_lo)).sum()),
"; fits at a bound (within 1e-4):", int((F3[["k_mi", "k_hi", "k_lo", "D"]].lt(1e-4) | F3[["k_mi", "k_hi", "k_lo", "D"]].gt(1 - 1e-4)).any(axis=1).sum()))
print("mixed-block trials the model labels high or low, median over rats:", round(float(F3.mislabel_mixed.median()), 3))
for lab, nm in (("mdl", "one noisy draw (WTMdl, as Figure3.m)"), ("opt", "noise-free (WTOpt, variant)")):
lo, hi = F3[f"{lab}_lo"], F3[f"{lab}_hi"]
print(f"model, {nm}: mean z after < 20 uL {lo.mean():+.4f}, after > 20 uL {hi.mean():+.4f}; sensitivity {(lo - hi).mean():+.4f};"
f" rank-sum on per-rat means p = {mannwhitneyu(lo, hi).pvalue:.3g}; signed-rank (variant) p = {wilcoxon(lo, hi).pvalue:.3g};"
f" rats with per-rat p < 0.05: {int((F3[f'{lab}_p'] < 0.05).sum())}")
print(f"rats (fig2j): mean z after < 20 uL {PR.wp_lo.mean():+.4f}, after > 20 uL {PR.wp_hi.mean():+.4f}; sensitivity {(PR.wp_lo - PR.wp_hi).mean():+.4f}")
recovery on J004 (kappa_mixed, kappa_high, kappa_low, D): generating [0.5391, 0.7903, 0.4813, 0.1547] ; recovered [0.5424, 0.7872, 0.4782, 0.1537]
fitted 291 rats in 188 s; mean L-BFGS-B evaluations per start 192; opt-out catch trials per rat, median 3441
fitted parameters, median over rats: {'k_mi': 0.2245, 'k_hi': 0.2533, 'k_lo': 0.196, 'D': 0.1093} ; rats with kappa_high > kappa_mixed > kappa_low: 197 ; fits at a bound (within 1e-4): 6
mixed-block trials the model labels high or low, median over rats: 0.085
model, one noisy draw (WTMdl, as Figure3.m): mean z after < 20 uL +0.0330, after > 20 uL -0.0320; sensitivity +0.0650; rank-sum on per-rat means p = 9.52e-11; signed-rank (variant) p = 3.51e-09; rats with per-rat p < 0.05: 16
model, noise-free (WTOpt, variant): mean z after < 20 uL +0.2566, after > 20 uL -0.1916; sensitivity +0.4482; rank-sum on per-rat means p = 1.49e-68; signed-rank (variant) p = 6.78e-37; rats with per-rat p < 0.05: 198
rats (fig2j): mean z after < 20 uL -0.0068, after > 20 uL +0.0050; sensitivity -0.0119
Result: not reproduced (assumed). Fitted to each rat's opt-out catch-trial wait times (on J004 the fit recovers its generating parameters, 0.539, 0.790, 0.481, 0.155, to within 0.004), the inferential model's wait times, one noisy draw as Figure3.m uses, are longer after offers below 20 uL (+0.033 z) than above (-0.032 z), and the rank-sum on per-rat means gives p = 9.52e-11 (signed-rank p = 3.51e-09). By the claim's test the model is sensitive to the previous offer; without noise the difference is +0.448 z (p = 1.49e-68). The rats' own difference is -0.012 z (fig2j). The model's effect comes from the mixed-block trials it labels high or low (a median of 8.5% per rat): a small previous offer makes a low block likelier, and kappa_low is the smallest of the three in most rats (kappa_high > kappa_mixed > kappa_low in 197 of 291), which lengthens the wait. The effect is small: +0.065 z with noise, about a quarter of the rats' initiation time sensitivity (+0.248 z, fig2l), and only 16 rats reach p < 0.05 against the rats' 38. It rests on the likelihood over opt-out catch trials and on L-BFGS-B in place of fmincon, choices the paper does not state; 6 of 291 fits have a parameter within 1e-4 of a bound.
suppfig9-wait-times-reflect-misinferences¶
Within mixed blocks, wait times for 20 uL differ between trials the inferential model labels as high and as low blocks, so wait times reflect mistaken inferences.
FigureS9.m: per rat, mean wait time on catch trials in mixed blocks labelled high and labelled low by the model's most likely block (BlkInf), for 20 uL; signed-rank across rats. The labels come from the block inference alone (Equations 3 to 6, H0 = 1/40, belief reset at session starts, GenerateSynthData_Bayes.m), which has no fitted parameter, so they are the same in any fit. FigureS9.m takes them on the held-out test sets; with folds of whole sessions (an assumption: the folds are not given, and the code resets the inference at every session) each trial gets the label it gets on all data, so the labels on all sessions are used. Code's transition matrix, with Equation 6's as a variant. Reproduced when p < 0.001 with shorter waits on trials labelled high.
for rd in ("code", "methods"):
hi9, lo9, mi9, nhi, nlo = [], [], [], [], []
for r in RATS:
d = R[r]
g, v, nw = m.model_trials(d)
b, _ = m.infer_blocks(v, nw, m.transition_matrix(reading=rd))
lab = np.full(len(d["vol"]), -1); lab[g] = np.argmax(b, 1) # 0 mixed, 1 high, 2 low
base = (d["block"] == 1) & d["catch"] & (d["vol"] == 20)
hi9.append(m._m(d["wt"][base & (lab == 1)])); lo9.append(m._m(d["wt"][base & (lab == 2)])); mi9.append(m._m(d["wt"][base & (lab == 0)]))
nhi.append(int(np.isfinite(d["wt"][base & (lab == 1)]).sum())); nlo.append(int(np.isfinite(d["wt"][base & (lab == 2)]).sum()))
hi9, lo9, mi9 = map(np.array, (hi9, lo9, mi9))
ok = np.isfinite(hi9) & np.isfinite(lo9)
print(f"transition matrix {rd}: rats with both labels {int(ok.sum())} of {len(RATS)}; 20 uL catch trials per rat labelled high, median {np.median(nhi):.0f}, labelled low {np.median(nlo):.0f}")
print(f" mean wait time (s): labelled high {np.nanmean(hi9):.3f}, labelled mixed {np.nanmean(mi9):.3f}, labelled low {np.nanmean(lo9):.3f};"
f" rats shorter when labelled high {int(np.sum(hi9[ok] < lo9[ok]))} of {int(ok.sum())}; signed-rank p = {wilcoxon(hi9[ok], lo9[ok]).pvalue:.3g}")
transition matrix code: rats with both labels 291 of 291; 20 uL catch trials per rat labelled high, median 27, labelled low 24 mean wait time (s): labelled high 10.854, labelled mixed 11.066, labelled low 11.898; rats shorter when labelled high 230 of 291; signed-rank p = 9.72e-23
transition matrix methods: rats with both labels 291 of 291; 20 uL catch trials per rat labelled high, median 37, labelled low 34 mean wait time (s): labelled high 10.847, labelled mixed 11.056, labelled low 11.823; rats shorter when labelled high 238 of 291; signed-rank p = 2.57e-25
Result: reproduced (assumed). On 20 uL catch trials in mixed blocks, rats wait less when the model labels the trial high (10.85 s) than low (11.90 s), shorter in 230 of 291 rats, signed-rank p = 9.72e-23 (Equation 6's matrix: 238 rats, p = 2.57e-25). The labels need no fitted parameter; the outcome rests on taking them on all sessions, which equals the held-out test sets when the folds are whole sessions (an assumption).
fig3l-lambda-groups-wait-time-dynamics¶
Rats with optimal and poor inference (high or low lambda of the sub-optimal inferential model) differ in their wait time dynamics at transitions from mixed into low or high blocks, but not in their trial initiation time dynamics.
The sub-optimal inferential model as GenerateSynthData_Bayes_subopt_onlylambda_flat.m computes it (Equation 8; params kappa_mixed, kappa_high, kappa_low, D, lambda in [0, 1]; belief and prior flat at session starts), fitted per rat with the likelihood of fig3f (an assumption, as there). The labels, and so the likelihood, change with lambda only in steps, so a gradient search cannot move lambda: lambda is profiled over a grid of 41 values from 0 to 1, and the other 4 parameters are fitted at each (2 starts, one warm), a standard choice in place of 100 random starts. Curves: block_dynamics_wt.m and block_dynamics_latency.m with 30 trials either side and 10-trial smoothing (Figure3.m), pooled detrending for initiation times (the code; per-session detrending as a variant). Groups below the 20th and above the 80th percentile of lambda (the Methods and the Results), and below the 40th and above the 60th (Figure3.m) as a variant. Where ties at a percentile leave a group nearly empty, the rats at the percentile join it (a tie-break). myLambdaShuffleTest.m with 500 shuffles on trials -20 to 20; logistic p1 is D (upper asymptote), p2 C (inverse temperature). Reproduced when the wait time test has p < 0.05 for C at mixed to low and for D (legend) or C (Results) at mixed to high, and the initiation tests do not reach p < 0.05 for those same parameters.
lab_fn = m.subopt_labels()
rng_lam = np.random.default_rng(1105)
t = time.time()
LAM = {r: m.fit_subopt_lambda(R[r], rng_lam, np.linspace(0, 1, 41), lab_fn, nstarts=2) for r in RATS}
lam = np.array([LAM[r][0] for r in RATS])
print(f"sub-optimal model fitted for {len(lam)} rats in {time.time() - t:.0f} s; lambda median {np.median(lam):.3f},"
f" 20th and 80th percentiles {np.percentile(lam, 20):.3f} and {np.percentile(lam, 80):.3f}; at 1: {int((lam == 1).sum())}, at 0: {int((lam == 0).sum())}")
nll_drop = np.array([LAM[r][3].max() - LAM[r][2] for r in RATS])
print("likelihood gain of the best lambda over the worst on the grid, median over rats:", round(float(np.median(nll_drop)), 1))
t = time.time()
W30 = {r: m.wt_dynamics(R[r], twin=30, smooth=10) for r in RATS}
L30 = {r: m.lat_dynamics(R[r], twin=30, smooth=10, detrend="pooled") for r in RATS}
L30s = {r: m.lat_dynamics(R[r], twin=30, smooth=10, detrend="session") for r in RATS}
print(f"transition curves in {time.time() - t:.0f} s")
rng_lsh = np.random.default_rng(1106)
names = ["D (p1)", "C (p2)", "x0 (p3)", "A (p4)"]
for lo_pct, hi_pct in ((20, 80), (40, 60)):
hiL, loL = lam > np.percentile(lam, hi_pct), lam < np.percentile(lam, lo_pct)
# ties at a percentile (many rats at lambda 0 or 1) can leave Figure3.m's strict rule with no rats; then the
# rats at the percentile join the group (a tie-break, stated)
if hiL.sum() < 10:
print(f" only {int(hiL.sum())} rats above the {hi_pct}th percentile ({np.percentile(lam, hi_pct):.3f}); the rats at it join the high group")
hiL = lam >= np.percentile(lam, hi_pct)
if loL.sum() < 10:
print(f" only {int(loL.sum())} rats below the {lo_pct}th percentile ({np.percentile(lam, lo_pct):.3f}); the rats at it join the low group")
loL = lam <= np.percentile(lam, lo_pct)
print(f"split {lo_pct}/{hi_pct}: low lambda {int(loL.sum())} rats, high lambda {int(hiL.sum())} rats (N = {int(loL.sum() + hiL.sum())})")
sets = [("wait time", W30), ("initiation", L30)] + ([("initiation, per-session detrend", L30s)] if lo_pct == 20 else [])
res3l = {}
for lab_, D_ in sets:
for tr in ("mtol", "mtoh"):
lo_c = np.stack([D_[r][tr] for r, f in zip(RATS, loL) if f]); hi_c = np.stack([D_[r][tr] for r, f in zip(RATS, hiL) if f])
pv, ob, plo, phi = m.lambda_shuffle_test(lo_c, hi_c, 500, 30, rng_lsh)
res3l[(lab_, tr)] = pv
print(f" {lab_:32s} {tr}: p " + ", ".join(f"{n_} {p_:.3f}" for n_, p_ in zip(names, pv))
+ f"; params low {np.round(plo, 3).tolist()}, high {np.round(phi, 3).tolist()}")
wt_ok = res3l[("wait time", "mtol")][1] < 0.05
for rd, j in (("legend, D at mixed to high", 0), ("Results, C at mixed to high", 1)):
ok_wt = wt_ok and res3l[("wait time", "mtoh")][j] < 0.05
ok_ti = res3l[("initiation", "mtol")][1] >= 0.05 and res3l[("initiation", "mtoh")][j] >= 0.05
print(f" reading {rd}: wait time part {ok_wt}; initiation absence {ok_ti}")
sub-optimal model fitted for 291 rats in 143 s; lambda median 0.775, 20th and 80th percentiles 0.000 and 1.000; at 1: 69, at 0: 59 likelihood gain of the best lambda over the worst on the grid, median over rats: 44.8
transition curves in 5 s only 0 rats above the 80th percentile (1.000); the rats at it join the high group only 0 rats below the 20th percentile (0.000); the rats at it join the low group split 20/80: low lambda 59 rats, high lambda 69 rats (N = 128)
wait time mtol: p D (p1) 0.318, C (p2) 0.242, x0 (p3) 0.240, A (p4) 0.480; params low [0.096, 0.296, 12.583, -0.025], high [0.116, 0.491, 9.728, -0.024]
wait time mtoh: p D (p1) 0.000, C (p2) 0.355, x0 (p3) 0.179, A (p4) 0.006; params low [-0.077, 0.911, 9.853, -0.018], high [-0.125, 0.795, 8.044, -0.05]
initiation mtol: p D (p1) 0.468, C (p2) 0.129, x0 (p3) 0.041, A (p4) 0.191; params low [0.158, 0.474, 3.321, -0.02], high [0.159, 0.545, 2.536, -0.024]
initiation mtoh: p D (p1) 0.028, C (p2) 0.494, x0 (p3) 0.378, A (p4) 0.013; params low [-0.126, 0.862, 0.0, -0.073], high [-0.137, 0.863, 0.0, -0.083]
initiation, per-session detrend mtol: p D (p1) 0.391, C (p2) 0.132, x0 (p3) 0.029, A (p4) 0.431; params low [0.149, 0.484, 3.409, -0.026], high [0.152, 0.562, 2.583, -0.026]
initiation, per-session detrend mtoh: p D (p1) 0.007, C (p2) 0.470, x0 (p3) 0.395, A (p4) 0.004; params low [-0.122, 0.794, 0.0, -0.063], high [-0.134, 0.785, 0.0, -0.074] reading legend, D at mixed to high: wait time part False; initiation absence False reading Results, C at mixed to high: wait time part False; initiation absence True split 40/60: low lambda 113 rats, high lambda 104 rats (N = 217)
wait time mtol: p D (p1) 0.005, C (p2) 0.197, x0 (p3) 0.294, A (p4) 0.079; params low [0.063, 0.633, 9.308, -0.039], high [0.113, 0.451, 10.224, -0.025]
wait time mtoh: p D (p1) 0.000, C (p2) 0.237, x0 (p3) 0.403, A (p4) 0.007; params low [-0.077, 1.028, 8.188, -0.02], high [-0.119, 0.776, 8.557, -0.048]
initiation mtol: p D (p1) 0.254, C (p2) 0.398, x0 (p3) 0.064, A (p4) 0.101; params low [0.151, 0.527, 3.165, -0.017], high [0.156, 0.539, 2.619, -0.022]
initiation mtoh: p D (p1) 0.006, C (p2) 0.245, x0 (p3) 0.335, A (p4) 0.062; params low [-0.126, 0.935, 0.0, -0.076], high [-0.137, 0.852, 0.0, -0.081] reading legend, D at mixed to high: wait time part False; initiation absence False reading Results, C at mixed to high: wait time part False; initiation absence True
Result: not reproduced (assumed). The fitted lambdas pile up at the bounds (59 rats at 0, 69 at 1, median 0.775), so the 20th and 80th percentiles are 0 and 1 and the groups are the rats at them (59 and 69, N = 128 against the paper's 116). At mixed to low, the wait time slope C does not differ between the groups (p = 0.242; 0.197 with the 40/60 split), which the criterion needs. At mixed to high, the wait time upper asymptote D differs (p = 0.000 under both splits) but its slope C does not (0.355 and 0.237). The initiation times also differ in D at mixed to high (p = 0.028; 0.007 with per-session detrending, 0.006 with the 40/60 split), so the absence fails under the legend's reading, while their C does not differ at either transition (0.129 to 0.494). Neither reading of the criterion holds under either split. The outcome rests on the sub-optimal model fitted here with the likelihood of fig3f and a grid over lambda, and on the tie-break that forms the groups. The paper's 20/80 split gives N = 116, which ties at the bounds could not give, so the paper's lambdas are not distributed as the refit's (128 rats at the bounds here), and the 20/80 groups here come from the tie-break, not the paper's rule. The failure may be the refit's and cannot be separated from it. The 40/60 split, which has no ties, fails as well (wait time C at mixed to low p = 0.197; initiation D at mixed to high p = 0.006).
bayes-observer-offer-reduces-uncertainty¶
In simulations of a Bayes optimal observer, hearing the reward offer reduces the uncertainty of beliefs about the hidden block (posterior variance below prior variance).
Prior (Equation 5) and posterior (Equation 3) on each rat's trials with H0 = 1/40, as GenerateSynthData_Bayes.m computes them (trials with a wait time; belief reset at session starts, where there is no prior). Transition matrices: the code's (mixed to high or low with H0/2 each) and Equation 6's (H0 each). Readings of "variance": (a) the variance of the three block probabilities, which is larger for a more peaked, less uncertain belief; (b) the variance of the block value with low, mixed, high coded 1, 2, 3, which is smaller for a less uncertain belief. Tests over per-rat means, over the trials of one rat, and over all rats' trials pooled (signed-rank).
code_ = np.array([2.0, 3.0, 1.0]) # order mixed, high, low -> low 1, mixed 2, high 3
def value_var(Pm):
mu = Pm @ code_
return Pm @ (code_ ** 2) - mu ** 2
DA, DB = [], []
for rd in ("code", "methods"):
Pm = m.transition_matrix(reading=rd)
va_p, va_b, vb_p, vb_b, trial_a, trial_b = [], [], [], [], [], []
for r in RATS:
g, v, nw = m.model_trials(R[r])
b, pr = m.infer_blocks(v, nw, Pm)
ok = ~nw
a_p, a_b = np.var(pr[ok], 1), np.var(b[ok], 1)
b_p, b_b = value_var(pr[ok]), value_var(b[ok])
va_p.append(a_p.mean()); va_b.append(a_b.mean()); vb_p.append(b_p.mean()); vb_b.append(b_b.mean())
trial_a.append(np.mean(a_b > a_p)); trial_b.append(np.mean(b_b < b_p))
if rd == "code":
DA.append(a_b - a_p); DB.append(b_b - b_p)
va_p, va_b, vb_p, vb_b = map(np.array, (va_p, va_b, vb_p, vb_b))
print(f"transition matrix {rd}:")
print(f" (a) variance of block probabilities: prior {va_p.mean():.4f}, posterior {va_b.mean():.4f}; rats with posterior larger {int((va_b > va_p).sum())};"
f" per-rat signed-rank p = {wilcoxon(va_b, va_p).pvalue:.3g}; share of trials with a more peaked posterior, median over rats {np.median(trial_a):.3f}")
print(f" (b) variance of block value: prior {vb_p.mean():.4f}, posterior {vb_b.mean():.4f}; rats with posterior smaller {int((vb_b < vb_p).sum())};"
f" per-rat signed-rank p = {wilcoxon(vb_b, vb_p).pvalue:.3g}; share of trials with smaller posterior variance, median over rats {np.median(trial_b):.3f}")
# trial-level test, pooled over rats, for one rat as an example and for all trials
g, v, nw = m.model_trials(R["J004"]); b, pr = m.infer_blocks(v, nw, m.transition_matrix())
ok = ~nw
print("J004 over trials: (a) p =", f"{wilcoxon(np.var(b[ok], 1), np.var(pr[ok], 1)).pvalue:.3g}", "; (b) p =", f"{wilcoxon(value_var(b[ok]), value_var(pr[ok])).pvalue:.3g}", "; trials", int(ok.sum()))
DA, DB = np.concatenate(DA), np.concatenate(DB)
print("all rats' trials pooled (code's matrix):", len(DA), "trials; (a) posterior minus prior, mean", f"{DA.mean():+.4f}, signed-rank p = {wilcoxon(DA).pvalue:.3g}",
"; (b) mean", f"{DB.mean():+.4f}, signed-rank p = {wilcoxon(DB).pvalue:.3g}")
transition matrix code: (a) variance of block probabilities: prior 0.1570, posterior 0.1694; rats with posterior larger 291; per-rat signed-rank p = 1.8e-49; share of trials with a more peaked posterior, median over rats 0.655 (b) variance of block value: prior 0.1041, posterior 0.0818; rats with posterior smaller 291; per-rat signed-rank p = 1.8e-49; share of trials with smaller posterior variance, median over rats 0.674
transition matrix methods: (a) variance of block probabilities: prior 0.1413, posterior 0.1580; rats with posterior larger 291; per-rat signed-rank p = 1.8e-49; share of trials with a more peaked posterior, median over rats 0.706 (b) variance of block value: prior 0.1349, posterior 0.1017; rats with posterior smaller 291; per-rat signed-rank p = 1.8e-49; share of trials with smaller posterior variance, median over rats 0.726 J004 over trials: (a) p = 5.31e-257 ; (b) p = 0 ; trials 11311
all rats' trials pooled (code's matrix): 6037811 trials; (a) posterior minus prior, mean +0.0124, signed-rank p = 0 ; (b) mean -0.0222, signed-rank p = 0
Result: reproduced. With either transition matrix, the posterior is less uncertain than the prior in every rat under both readings: the variance of the block probabilities rises (0.157 to 0.169 with the code's matrix) and the variance of the block value falls (0.104 to 0.082), per-rat signed-rank p = 1.8e-49 in each case. Over trials, p = 5.31e-257 and p = 0 for rat J004 and p = 0 for both readings with all rats' 6,037,811 trials pooled (mean change +0.0124 and -0.0222).
suppfig12-no-sex-differences¶
Male and female rats do not differ in their wait time ratios or trial initiation time ratios.
FigureS12.m: per-rat ratios of fig1f (20 uL, seconds) and fig1i (seconds), rank-sum between sexes, sex from the subject metadata. Absence: reproduced when both p >= 0.05.
mm, ff = PR.sex == "M", PR.sex == "F"
print("males", int(mm.sum()), ", females", int(ff.sum()), "(paper 184 and 107; Methods also 160 and 114)")
for lab, x in (("wait time ratio", ratio_wt), ("initiation time ratio", ratio_iti)):
p = mannwhitneyu(x[mm].dropna(), x[ff].dropna()).pvalue
print(f"{lab}: males mean {x[mm].mean():.4f} (median {x[mm].median():.4f}), females mean {x[ff].mean():.4f} (median {x[ff].median():.4f}); rank-sum p = {p:.3f}")
for lab, D in (("wait time", WD), ("initiation", LD)):
for sx in ("M", "F"):
rs = [r for r in RATS if PR.sex[r] == sx]
h = np.nanmean([D[r]["htom"] for r in rs], 0); l = np.nanmean([D[r]["ltom"] for r in rs], 0)
print(f" {lab} dynamics, {sx}: high-to-mixed minus low-to-mixed, trials -20..-1 {window(h - l, -20, -1):+.3f}, 1..20 {window(h - l, 1, 20):+.3f}")
males 184 , females 107 (paper 184 and 107; Methods also 160 and 114) wait time ratio: males mean 0.8923 (median 0.8870), females mean 0.8977 (median 0.8920); rank-sum p = 0.238 initiation time ratio: males mean 0.5634 (median 0.5522), females mean 0.5588 (median 0.5401); rank-sum p = 0.557 wait time dynamics, M: high-to-mixed minus low-to-mixed, trials -20..-1 -0.344, 1..20 -0.088 wait time dynamics, F: high-to-mixed minus low-to-mixed, trials -20..-1 -0.315, 1..20 -0.143 initiation dynamics, M: high-to-mixed minus low-to-mixed, trials -20..-1 -0.112, 1..20 +0.241 initiation dynamics, F: high-to-mixed minus low-to-mixed, trials -20..-1 -0.097, 1..20 +0.256
Result: reproduced. The dandiset's metadata give 184 males and 107 females. Wait time ratios (0.892 against 0.898) and initiation time ratios (0.563 against 0.559) do not differ between sexes, rank-sum p = 0.238 and 0.557 (the paper 0.23 and 0.59).
suppfig14-contextual-effects-without-threshold¶
Without removing wait times more than 1 SD above the pooled mean, the contextual effects on wait times are qualitatively similar, with longer average wait times, mainly in low blocks.
FigureS14.m: per rat, mean wait time on opt-out catch trials by offer and block with wait_time_unthresholded
and with wait_time; then the mean over rats. Reproduced when, unthresholded, the 20 uL wait time is shorter in
high than in low blocks by the signed-rank test at p < 0.001, and the unthresholded population mean is longer at
every offer in every block.
WU = np.stack(PR.wt_curve_unthr.values)
mu_u, mu_t = np.nanmean(WU, 0), np.nanmean(WC, 0)
for i, b in enumerate(["mixed", "high", "low"]):
print(f"{b:5s}: unthresholded {np.round(mu_u[i], 2).tolist()} thresholded {np.round(mu_t[i], 2).tolist()} difference {np.round(mu_u[i] - mu_t[i], 2).tolist()}")
ok = np.isfinite(mu_u) & np.isfinite(mu_t)
print("longer unthresholded at every offer and block that exists:", bool(np.all(mu_u[ok] > mu_t[ok])), "; cells", int(ok.sum()))
w = wilcoxon(WU[:, 1, 2], WU[:, 2, 2], nan_policy="omit")
print("unthresholded 20 uL: high", round(np.nanmean(WU[:, 1, 2]), 3), "s, low", round(np.nanmean(WU[:, 2, 2]), 3), "s; ratio", round(np.nanmean(WU[:, 1, 2] / WU[:, 2, 2]), 4), "; signed-rank p =", f"{w.pvalue:.3g}")
print("slope 5 to 20 uL in low blocks: unthresholded", round(float(mu_u[2, 2] - mu_u[2, 0]), 3), "s, thresholded", round(float(mu_t[2, 2] - mu_t[2, 0]), 3), "s (shown, not judged)")
mixed: unthresholded [12.23, 12.46, 12.67, 14.15, 14.76] thresholded [10.45, 10.77, 11.1, 13.03, 13.81] difference [1.78, 1.69, 1.57, 1.12, 0.95] high : unthresholded [nan, nan, 12.51, 13.78, 14.43] thresholded [nan, nan, 10.85, 12.5, 13.34] difference [nan, nan, 1.66, 1.27, 1.09] low : unthresholded [14.35, 14.43, 14.47, nan, nan] thresholded [11.49, 11.78, 12.16, nan, nan] difference [2.86, 2.66, 2.31, nan, nan] longer unthresholded at every offer and block that exists: True ; cells 11 unthresholded 20 uL: high 12.513 s, low 14.474 s; ratio 0.8678 ; signed-rank p = 1.02e-43 slope 5 to 20 uL in low blocks: unthresholded 0.119 s, thresholded 0.672 s (shown, not judged)
Result: reproduced. Without the threshold, 20 uL wait times are still shorter in high than in low blocks (12.51 against 14.47 s, signed-rank p = 1.02e-43), and the population mean is longer at all 11 offer and block combinations, most in low blocks (2.31 to 2.86 s longer, against 0.95 to 1.78 s in mixed blocks). The low block curve is flatter unthresholded (0.12 s from 5 to 20 uL against 0.67 s).
pre-cue-session-link¶
Link claim (added by this attempt): the switch dates of Figure5.m mark the dandiset's pre-initiation cue sessions of the 16 rats it names.
Nothing in the files marks a session as run on the pre-initiation cue task (all are protocol RWTautowait2, and
the task arguments carry no cue setting), so the sessions are labelled with the rats and start dates that
Figure5.m lists (the code pairs startDates(rr) with rat rr, so the first 16 of its 20 dates are used). The link
is checked against the behavior the task change should produce (Methods, Pre-initiation cue task; Fig. 5b): once
the offer is cued before initiation, initiation times depend on the current offer. Per rat, z-scored initiation
time in mixed blocks by current offer, leaving out post-violation trials (iti_by_reward.m), before and after the
date. A rat is linked when, after the date, the one-way ANOVA over offers has p < 0.05 and the slope over log2
offer is more negative than before (below 0 for the 4 rats with no earlier sessions). This rule was written after
a first look at the same check, so it is a description of it, not a blind test.
Sx = S.copy(); Sx["date"] = Sx.start.dt.tz_convert("America/New_York").dt.tz_localize(None).dt.normalize()
AFTER, LINK = {}, []
for r_, d0 in zip(m.PRECUE_RATS, m.PRECUE_START):
d = R[r_]
sd = Sx[Sx.subject == r_].set_index("order").date.reindex(d["order"]).values
AFTER[r_] = sd >= np.datetime64(d0)
ns_before = len(np.unique(d["order"][~AFTER[r_]])); ns_after = len(np.unique(d["order"][AFTER[r_]]))
row = dict(rat=r_, start=d0, sessions_before=ns_before, sessions_after=ns_after)
for lab, msk in (("before", ~AFTER[r_]), ("after", AFTER[r_])):
if msk.sum() > 100:
_, p_, sl_ = m.iti_by_reward(m.subset_rat(d, msk))
else:
p_, sl_ = np.nan, np.nan
row[f"p_{lab}"], row[f"slope_{lab}"] = p_, sl_
before_sl = 0.0 if np.isnan(row["slope_before"]) else row["slope_before"]
row["linked"] = bool(row["p_after"] < 0.05 and row["slope_after"] < before_sl)
LINK.append(row)
LINK = pd.DataFrame(LINK).set_index("rat")
print(LINK.round(4).to_string())
print("rats linked:", int(LINK.linked.sum()), "of", len(LINK))
print("protocols of these rats' sessions:", sorted(set(S[S.subject.isin(m.PRECUE_RATS)].protocol)))
print("Figure5.m lists", len(m.PRECUE_RATS), "rats and 20 start dates")
start sessions_before sessions_after p_before slope_before p_after slope_after linked rat M041 2022-10-04 64 34 0.0927 -0.0015 0.0000 -0.0605 True M042 2022-10-04 62 14 0.3049 -0.0074 0.0000 -0.0625 True M043 2022-10-04 58 61 0.1339 -0.0078 0.0000 -0.0664 True M044 2022-10-04 61 89 0.7991 -0.0045 0.0000 -0.0854 True M045 2022-12-13 0 69 NaN NaN 0.0000 -0.0839 True M046 2022-12-13 0 57 NaN NaN 0.0000 -0.0866 True M047 2022-12-13 0 69 NaN NaN 0.0000 -0.0726 True M048 2022-12-13 0 73 NaN NaN 0.0000 -0.0900 True G070 2022-10-24 69 37 0.1676 0.0022 0.0000 -0.0675 True E005 2022-10-24 59 21 0.9268 0.0012 0.0139 -0.0412 True E008 2022-10-24 78 74 0.1029 0.0142 0.0000 -0.0579 True G078 2022-11-07 102 27 0.1983 0.0088 0.0000 -0.0548 True G076 2022-11-14 53 55 0.9387 -0.0051 0.0000 -0.0833 True G069 2022-11-14 127 75 0.4073 -0.0030 0.0000 -0.0549 True S042 2022-12-21 56 25 0.7235 0.0002 0.1510 -0.0206 False S050 2022-12-22 22 11 0.5772 -0.0110 0.5969 -0.0312 False rats linked: 14 of 16 protocols of these rats' sessions: ['RWTautowait2'] Figure5.m lists 16 rats and 20 start dates
Result: partially reproduced. 14 of the 16 rats are linked: after the switch date their initiation times depend on the current offer (ANOVA p < 0.05, slopes -0.041 to -0.090 z per doubling), while before it the ANOVA is not significant in any of the 12 switched rats (slopes -0.011 to +0.014). S042 (p = 0.151 after) and S050 (p = 0.597 after) are not confirmed; they have 25 and 11 sessions after the date in the dandiset. Nothing in the files marks these sessions: all are protocol RWTautowait2.
fig5b-pre-cue-initiation-sensitive-to-offer¶
With the reward cue played before trial initiation, trial initiation times become sensitive to the offered reward.
The 16 rats of Figure5.m. Pre-cue sessions for the 12 that switched: (a) from the switch date (Figure5.m) and (b) after their first 30 pre-cue sessions (Methods); for the 4 others, all sessions. Original-task sessions: those before the date. Per rat, iti_by_reward.m (z-scored initiation time by offer in mixed blocks, post-violation trials left out, one-way ANOVA). The Methods include every session of these rats, but the dandiset holds only those that pass the inclusion criterion.
def precue_mask(r_, reading):
d = R[r_]
if r_ in m.PRECUE_ONLY:
return np.ones(len(d["vol"]), bool)
after = AFTER[r_]
if reading == "date":
return after
o = d["order"]
first_after = np.unique(o[after])
keep = first_after[30:] if len(first_after) > 30 else np.array([], int)
return np.isin(o, keep)
F5 = {}
for reading in ("date", "after 30 sessions"):
rows = []
for r_ in m.PRECUE_RATS:
msk = precue_mask(r_, reading)
mp_, pp_, _ = m.iti_by_reward(m.subset_rat(R[r_], msk)) if msk.sum() > 100 else (np.full(5, np.nan), np.nan, np.nan)
if r_ not in m.PRECUE_ONLY:
mo_, po_, _ = m.iti_by_reward(m.subset_rat(R[r_], ~AFTER[r_]))
else:
mo_, po_ = np.full(5, np.nan), np.nan
rows.append(dict(rat=r_, n_trials_precue=int(msk.sum()), p_precue=pp_, p_original=po_, **{f"pre_{v}": x for v, x in zip(m.VOLUMES, mp_)}, **{f"orig_{v}": x for v, x in zip(m.VOLUMES, mo_)}))
F5[reading] = pd.DataFrame(rows).set_index("rat")
t5 = F5[reading]
pre_mean = t5[[f"pre_{v}" for v in m.VOLUMES]].mean().values
orig_mean = t5[[f"orig_{v}" for v in m.VOLUMES]].mean().values
sw = [r_ for r_ in m.PRECUE_RATS if r_ not in m.PRECUE_ONLY]
print(f"reading {reading}: rats with pre-cue data {int(t5.p_precue.notna().sum())}")
print(" pre-cue mean z by offer 5..80:", np.round(pre_mean, 3).tolist(), "; decreases at each step:", bool(np.all(np.diff(pre_mean) < 0)))
print(" original-task mean z by offer:", np.round(orig_mean, 3).tolist())
print(f" ANOVA p < 0.05: pre-cue {int((t5.p_precue < 0.05).sum())} of {int(t5.p_precue.notna().sum())} (switched rats {int((t5.p_precue[sw] < 0.05).sum())} of 12);"
f" original task {int((t5.p_original < 0.05).sum())} of {int(t5.p_original.notna().sum())}")
print(F5["date"][["n_trials_precue", "p_precue", "p_original"]].round(4).to_string())
reading date: rats with pre-cue data 16 pre-cue mean z by offer 5..80: [0.102, 0.091, 0.025, -0.09, -0.126] ; decreases at each step: True original-task mean z by offer: [0.0, -0.007, 0.012, 0.007, -0.012] ANOVA p < 0.05: pre-cue 14 of 16 (switched rats 10 of 12); original task 0 of 12
reading after 30 sessions: rats with pre-cue data 11
pre-cue mean z by offer 5..80: [0.117, 0.1, 0.042, -0.109, -0.152] ; decreases at each step: True
original-task mean z by offer: [0.0, -0.007, 0.012, 0.007, -0.012]
ANOVA p < 0.05: pre-cue 11 of 11 (switched rats 7 of 12); original task 0 of 12
n_trials_precue p_precue p_original
rat
M041 18334 0.0000 0.0927
M042 7078 0.0000 0.3049
M043 29940 0.0000 0.1339
M044 36513 0.0000 0.7991
M045 25242 0.0000 NaN
M046 22284 0.0000 NaN
M047 23762 0.0000 NaN
M048 23682 0.0000 NaN
G070 12896 0.0000 0.1676
E005 6818 0.0139 0.9268
E008 25058 0.0000 0.1029
G078 14349 0.0000 0.1983
G076 26334 0.0000 0.9387
G069 39573 0.0000 0.4073
S042 7514 0.1510 0.7235
S050 4465 0.5969 0.5772
Result: reproduced. On the pre-cue sessions, the population mean z-scored initiation time falls at every step from 5 to 80 uL (+0.102 to -0.126 from the switch date; +0.117 to -0.152 after 30 pre-cue sessions), while on the original task it is flat (0.000 to -0.012). 14 of 16 rats reach ANOVA p < 0.05 on the pre-cue task (11 of the 11 with enough sessions after 30 pre-cue sessions) and 0 of 12 on the original task. The dandiset holds only the sessions that pass the inclusion criterion, where the Methods use all sessions of these rats.
fig5c-pre-cue-initiation-still-sensitive-to-previous-reward¶
On the pre-initiation cue task, trial initiation times for 20 uL in mixed blocks are still modulated by the previous reward, for 13 of 16 rats and for the population.
Pre-cue sessions as in fig5b (both readings); per rat the test of fig2k under each of its readings (all mixed-block trials, the code; 20 uL trials, the Methods), z-scored within the pre-cue sessions as Figure5.m does; count with p < 0.05 (expected 13 +- 1); population two-tailed rank-sum on per-rat means, p < 0.001 with slower initiation after smaller offers.
Which reading the paper supports. The Fig. 5c legend analyses "behavior on trials offering 20μL conditioned on the previous reward offer", and the claim says "for 20 uL", which is the Methods' reading. On this task the cued current offer drives initiation (fig5b), and trials after a violation repeat the previous offer (Methods, Pre-initiation cue task), so with all mixed-block trials (Figure5.m) a smaller previous offer goes with a smaller current one more often than by chance. The 20 uL reading is adopted (an assumption); all readings are shown, and the all-trials reading is also run with post-violation trials left out.
T5C = {}
for reading in ("date", "after 30 sessions"):
for rd, dpv in (("code", False), ("methods", False), ("code", True), ("methods", True)):
lo, hi, ps = [], [], []
for r_ in m.PRECUE_RATS:
msk = precue_mask(r_, reading)
a_, b_, p_ = m.iti_by_previous(m.subset_rat(R[r_], msk), rd, drop_post_vio=dpv) if msk.sum() > 100 else (np.nan, np.nan, np.nan)
lo.append(a_); hi.append(b_); ps.append(p_)
lo, hi, ps = map(np.array, (lo, hi, ps))
T5C[(reading, rd, dpv)] = pd.DataFrame(dict(after_smaller=lo, after_larger=hi, p=ps), index=m.PRECUE_RATS)
ok = np.isfinite(lo) & np.isfinite(hi)
print(f"sessions {reading:17s}, trials {rd:7s}{' no post-violation' if dpv else '':18s}: rats with p < 0.05 {int(np.sum(ps < 0.05))} of {int(np.isfinite(ps).sum())}"
f" ({int(np.sum((ps < 0.05) & (lo > hi)))} slower after smaller); mean z after < 20 {np.nanmean(lo):+.3f}, after > 20 {np.nanmean(hi):+.3f}; rats slower after smaller {int(np.sum(lo > hi))};"
f" rank-sum p = {mannwhitneyu(lo[ok], hi[ok]).pvalue:.3g}; signed-rank p = {wilcoxon(lo[ok], hi[ok]).pvalue:.3g}")
print("per rat, sessions from the switch date, 20 uL trials (the Fig. 5c legend's reading):")
print(T5C[("date", "methods", False)].assign(difference=lambda x: x.after_smaller - x.after_larger).round(4).to_string())
sessions date , trials code : rats with p < 0.05 13 of 16 (13 slower after smaller); mean z after < 20 +0.090, after > 20 -0.122; rats slower after smaller 16; rank-sum p = 1.86e-06; signed-rank p = 3.05e-05 sessions date , trials methods : rats with p < 0.05 14 of 16 (9 slower after smaller); mean z after < 20 +0.058, after > 20 -0.042; rats slower after smaller 11; rank-sum p = 0.0676; signed-rank p = 0.0182 sessions date , trials code no post-violation: rats with p < 0.05 15 of 16 (4 slower after smaller); mean z after < 20 -0.108, after > 20 -0.072; rats slower after smaller 5; rank-sum p = 0.3; signed-rank p = 0.0654 sessions date , trials methods no post-violation: rats with p < 0.05 15 of 16 (7 slower after smaller); mean z after < 20 -0.066, after > 20 -0.047; rats slower after smaller 8; rank-sum p = 0.611; signed-rank p = 0.495
sessions after 30 sessions, trials code : rats with p < 0.05 9 of 11 (8 slower after smaller); mean z after < 20 +0.073, after > 20 -0.083; rats slower after smaller 10; rank-sum p = 0.000182; signed-rank p = 0.00195
sessions after 30 sessions, trials methods : rats with p < 0.05 10 of 11 (6 slower after smaller); mean z after < 20 +0.081, after > 20 +0.022; rats slower after smaller 7; rank-sum p = 0.47; signed-rank p = 0.206
sessions after 30 sessions, trials code no post-violation: rats with p < 0.05 11 of 11 (3 slower after smaller); mean z after < 20 -0.069, after > 20 -0.027; rats slower after smaller 3; rank-sum p = 0.431; signed-rank p = 0.147
sessions after 30 sessions, trials methods no post-violation: rats with p < 0.05 10 of 11 (4 slower after smaller); mean z after < 20 -0.016, after > 20 +0.015; rats slower after smaller 4; rank-sum p = 0.793; signed-rank p = 0.577
per rat, sessions from the switch date, 20 uL trials (the Fig. 5c legend's reading):
after_smaller after_larger p difference
M041 0.0970 0.0022 0.0000 0.0948
M042 0.2186 -0.0096 0.0000 0.2282
M043 0.1191 0.2235 0.0000 -0.1044
M044 -0.0401 -0.0228 0.0000 -0.0173
M045 0.3043 0.1398 0.0000 0.1645
M046 0.0778 -0.0120 0.0000 0.0898
M047 0.1008 -0.0262 0.0000 0.1270
M048 -0.0076 -0.1257 0.0000 0.1180
G070 -0.0580 -0.1510 0.0000 0.0930
E005 -0.1437 -0.1168 0.0013 -0.0268
E008 -0.0510 -0.0517 0.0000 0.0007
G078 0.0760 -0.1903 0.1145 0.2663
G076 0.2188 0.0401 0.0000 0.1786
G069 -0.1124 -0.0496 0.0000 -0.0629
S042 -0.1360 -0.1287 0.0000 -0.0073
S050 0.2570 -0.1955 0.1086 0.4525
Result: partially reproduced (assumed). Under the reading the Fig. 5c legend gives (20 uL trials, sessions from the switch date), 14 of 16 rats have p < 0.05 (expected 13 +- 1), but only 9 of them are slower after smaller offers, 11 of 16 rats are slower after smaller offers, and the population rank-sum gives p = 0.0676, not below 0.001 (signed-rank p = 0.0182). The count matches and the population test does not. With all mixed-block trials (Figure5.m), 13 rats have p < 0.05, all 16 are slower after smaller offers, and p = 1.86e-06, but this rests on the trials after violations: with those left out, the mean is lower after smaller offers (-0.108 against -0.072 z), 5 of 16 rats are slower after smaller offers, and p = 0.30. After 30 pre-cue sessions, 11 rats remain (9 with p < 0.05 and p = 0.000182 with all trials; 10 and p = 0.47 with 20 uL trials). The 20 uL reading is adopted as the one the legend and the claim name.
The second cell checks why the trials after violations matter. Within a session and block, every trial after a violation repeats the previous offer (share 1.000 in all 16 rats; 0.985 to 0.996 over all such trials, against 0.195 to 0.226 after other trials). So on the all-trials reading, the post-violation trials have a current cued offer equal to the previous one, and on this task the cued offer drives initiation time (fig5b). The trials that do not repeat are a session's first trials, whose previous trial in the concatenated data is the last trial of the previous session, as the code takes it. Leaving out post-violation trials from the 20 uL test removes only these: 455 of 18,075 trials, all a session's first trial, with a mean z initiation time of +2.920 against -0.057 for the rest. These few trials move the 20 uL population test from p = 0.0676 to 0.611, so under the adopted reading the population effect fails with or without them. The per-rat count of 14 is weak support: 5 of the 14 rats are significant in the opposite direction, and three have mean differences near 0 with p < 0.0001 (E008 +0.0007, S042 -0.0073, M044 -0.0173).
fig5d-pre-cue-initiation-depends-on-previous-block¶
On the pre-initiation cue task, how quickly rats initiate trials in mixed blocks still depends on the previous block.
Pre-cue sessions as in fig5b; initiation time transition curves as in fig2a (pooled detrending, the code; per session, the Methods). Per rat, mean over trials 1 to 20 of the mixed block after high and after low blocks; reproduced when the population mean is higher after high blocks with a two-tailed signed-rank test across the 16 rats at p < 0.05.
for reading in ("date", "after 30 sessions"):
for det in ("pooled", "session"):
h_, l_ = [], []
for r_ in m.PRECUE_RATS:
msk = precue_mask(r_, reading)
if msk.sum() < 100:
h_.append(np.nan); l_.append(np.nan); continue
c_ = m.lat_dynamics(m.subset_rat(R[r_], msk), detrend=det)
h_.append(window(c_["htom"], 1, 20)); l_.append(window(c_["ltom"], 1, 20))
h_, l_ = np.array(h_), np.array(l_)
ok = np.isfinite(h_) & np.isfinite(l_)
print(f"sessions {reading:17s}, detrend {det:7s}: after high {np.nanmean(h_):+.3f}, after low {np.nanmean(l_):+.3f};"
f" rats higher after high {int(np.sum(h_ > l_))} of {int(ok.sum())}; signed-rank p = {wilcoxon(h_[ok], l_[ok]).pvalue:.3g}")
sessions date , detrend pooled : after high +0.149, after low -0.132; rats higher after high 16 of 16; signed-rank p = 3.05e-05
sessions date , detrend session: after high +0.138, after low -0.121; rats higher after high 16 of 16; signed-rank p = 3.05e-05 sessions after 30 sessions, detrend pooled : after high +0.118, after low -0.116; rats higher after high 11 of 11; signed-rank p = 0.000977
sessions after 30 sessions, detrend session: after high +0.110, after low -0.113; rats higher after high 11 of 11; signed-rank p = 0.000977
Result: reproduced. On the pre-cue sessions, initiation times over trials 1 to 20 of mixed blocks are higher after high blocks (+0.149) than after low blocks (-0.132) in all 16 rats, signed-rank p = 3.05e-05; the same holds with per-session detrending and after 30 pre-cue sessions (11 of 11 rats, p = 0.000977).
Blocked claims¶
Model fits (fig3j, suppfig8). fig3j needs each rat's wait times fitted by the inferential and retrospective models with 100 random starts per fit (Methods, Fitting and evaluating models), on all data and on 5 cross-validation folds; suppfig8 adds the belief state model. The fitting code is not in the paper's repository, so the trials in the likelihood, the folds and the starting ranges are open. The cell below times one evaluation of the retrospective likelihood (GenerateSynthData_AlphaPHModel.m), compiled, and estimates the refit from the evaluations per start counted in fig3f's fits. The timings depend on the machine: in the runs of this notebook the estimate was 2.6 to 2.7 h (this attempt) and 4.3 h (the verifier) for the retrospective refit on one core, and 0.7 h and 1.2 h for the inferential and belief state fits, about 3.3 h and 5.5 h in all, each beyond the notebook limit of 1 h.
# One evaluation of each model's likelihood on J004, the retrospective one compiled (numba), and the refit estimated
# from the L-BFGS-B evaluations per start counted in the inferential fits of fig3f.
d = R["J004"]
g, v, nw = m.model_trials(d)
Rv = np.log2(d["vol_raw"][g].astype(float)); ridx = np.array([m.VOL_IDX[int(x)] for x in v])
obs = np.flatnonzero((d["optout"] & d["catch"])[g] & (d["wt"][g] > 0)); lx = np.log(d["wt"][g][obs])
Cj = float(np.nanmax(1 - d["catch_p"]))
retro = m.retro_wt_nll()
retro(0.1, 0.5, Rv, ridx, nw, obs, lx, Cj, m.WT_TAU, m.WT_NOISE) # compile
t = time.time()
for _ in range(200):
retro(0.1, 0.5, Rv, ridx, nw, obs, lx, Cj, m.WT_TAU, m.WT_NOISE)
t_ret = (time.time() - t) / 200
t = time.time()
m._retro_wt_nll_py(0.1, 0.5, Rv, ridx, nw, obs, lx, Cj, m.WT_TAU, m.WT_NOISE)
t_ret_py = time.time() - t
t = time.time()
for _ in range(200):
st_ = m.inferential_setup(d)
t_inf_setup = (time.time() - t) / 200
evals, starts, fits, rats = float(F3.evals.mean()), 100, 6, len(RATS)
mean_trials = np.mean([np.isfinite(R[r]["wt"]).sum() for r in RATS])
scale = mean_trials / len(v)
est_ret = t_ret * scale * evals * starts * fits * rats / 3600
est_inf_fits = T_FIT_RAT * fits * rats / 3600 # inferential and belief state fits, as fig3f's per-rat fit
print(f"J004: {len(v)} trials with a wait time; mean over rats {mean_trials:.0f}; evaluations per start (fig3f) {evals:.0f}")
print(f"retrospective likelihood, one evaluation: compiled {t_ret * 1e3:.3f} ms, pure Python {t_ret_py * 1e3:.1f} ms")
print(f"inferential fit per rat (fig3f, 100 starts, all data): {T_FIT_RAT:.2f} s")
print(f"estimated refit for fig3j (all data and 5 folds, 100 starts): retrospective {est_ret:.2f} h on one core,"
f" {est_ret / 4:.2f} h on 4; inferential and belief state {2 * est_inf_fits:.2f} h on one core (notebook limit 1 h)")
J004: 11351 trials with a wait time; mean over rats 20828; evaluations per start (fig3f) 192 retrospective likelihood, one evaluation: compiled 0.157 ms, pure Python 19.7 ms inferential fit per rat (fig3f, 100 starts, all data): 0.65 s estimated refit for fig3j (all data and 5 folds, 100 starts): retrospective 2.68 h on one core, 0.67 h on 4; inferential and belief state 0.63 h on one core (notebook limit 1 h)
Learning (fig4a, fig4c, fig4d). Figure 4 uses all stage 8 sessions, including those that fail the inclusion criterion (Methods, Learning dynamics; Figure4.m reads the lab's S structs, "data over training that gets removed in A struct"). The dandiset was converted from the A structs (A_Structs_Final), which hold only the included sessions (parse_data_from_mysql.m keeps the sessions screen_perf.m passes). The data check above finds a positive slope of catch-trial wait time on offer in 87% of sessions, which is consistent with that selection but does not prove it, as the check is simpler than screen_perf.m. The excluded sessions are not in the dandiset. A partial test on the included sessions was not run: the three claims are about how behavior changes from the first stage 8 sessions, and the sessions the criterion removes are those early ones, so a trend over the included sessions would test a different selection, not a part of the paper's.
Summary¶
| claim | outcome |
|---|---|
| cohort-size | reproduced |
| fig1e-wait-time-increases-with-reward | reproduced |
| fig1f-wait-time-block-effect | reproduced |
| fig1i-initiation-block-effect | reproduced |
| suppfig2-initiation-block-effect-after-unrewarded | reproduced |
| suppfig3-wait-time-not-affected-by-previous-outcome | reproduced |
| fig2a-wait-time-converges-in-mixed-blocks | reproduced |
| suppfig5-mixed-to-adaptation-transitions | reproduced |
| fig2c-d-regression-on-previous-rewards | reproduced |
| fig2e-tau-differ | reproduced |
| fig2f-tau-uncorrelated | reproduced |
| fig2g-h-fast-slow-tau-groups | reproduced |
| fig2j-wait-time-not-sensitive-to-previous-offer | reproduced |
| fig2k-initiation-sensitive-to-previous-offer | reproduced |
| fig2l-sensitivity-greater-for-initiation | reproduced |
| suppfig6-results-without-detrending | reproduced |
| fig3c-wait-time-by-catch-probability | reproduced |
| fig3i-retrospective-model-captures-initiation | partially reproduced (assumed) |
| fig3f-inferential-model-not-sensitive-to-previous-offer | not reproduced (assumed) |
| suppfig9-wait-times-reflect-misinferences | reproduced (assumed) |
| fig3l-lambda-groups-wait-time-dynamics | not reproduced (assumed) |
| bayes-observer-offer-reduces-uncertainty | reproduced |
| suppfig12-no-sex-differences | reproduced |
| suppfig14-contextual-effects-without-threshold | reproduced |
| pre-cue-session-link (link claim) | partially reproduced |
| fig5b-pre-cue-initiation-sensitive-to-offer | reproduced |
| fig5c-pre-cue-initiation-still-sensitive-to-previous-reward | partially reproduced (assumed) |
| fig5d-pre-cue-initiation-depends-on-previous-block | reproduced |
| fig3j, suppfig8 | blocked, too_large |
| fig4a, fig4c, fig4d | blocked, data_missing |
A failure to reproduce here may be a failure of this attempt, not of the paper: see the reasoning and the differences from the paper's method.
How the analysis differs from the paper's. The paper's MATLAB functions were rewritten in Python and applied to the trials as the dandiset holds them, concatenated per rat in date order as the lab's A struct is. Exponential fits use an exact least-squares profile over tau in place of fmincon from random starts. Where the Methods and the code differ (z-scored or raw means, 9 or 10 previous rewards, per-session or pooled detrending, all or 20 uL trials, the hazard matrix), both were run; they agree on every outcome but fig5c, where the 20 uL reading of the Fig. 5c legend fails the population test and the code's all-trials reading passes only through the trials after violations, and the 20 uL reading is adopted. The Fig. 3i part of fig3i uses one rat's parameters for all rats, because the per-rat fits are not in the dandiset. For fig3f and fig3l the inferential and sub-optimal inferential models were fitted per rat here, by maximum likelihood over opt-out catch trials (the fitting code is not public); suppfig9 uses the model's block labels, which need no fit, on all sessions. The Fig. 5 claims use the rats and switch dates listed in Figure5.m as session labels, checked by a link claim, and only the sessions that pass the inclusion criterion. The model comparison fits of Fig. 3 (fig3j, suppfig8) were not run (estimated at 3.3 h and 5.5 h on one core in two runs, beyond the notebook limit), and the learning claims are blocked.
What was found about the dataset. It holds what the paper's Figs 1 to 3 and Supplementary Figs 1 to 6, 12 and 14
need, and reproduces the paper's counts exactly (291 rats, 184 male and 107 female, median 71 sessions and 33,493
trials) and several of its p values to three digits. Processed and raw trial tables agree row by row. One session
(L011, 2022-10-04) is deposited twice, once with a "-x" suffix. The processed table lacks the catch probability; it
is only in the raw table. The raw is_catch disagrees with the processed catch flag on 176,009 trials. The dandiset
holds only the sessions that pass the paper's inclusion criterion, which it does not say, so the learning analyses
of Fig. 4 cannot be run. Nothing marks the pre-initiation cue sessions of Fig. 5; the switch dates in the paper's
code mark them for 14 of 16 rats, and these sessions are part of the 291-rat data. The age field is empty in 21,853 of
23,034 files.
print(f"notebook run time {(time.time() - T0) / 60:.1f} min; peak memory {resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1e6:.2f} GB")
notebook run time 25.6 min; peak memory 3.49 GB