Masset et al. (2025): cued delay task and both tasks (Mendeley deposit and DANDI:000251)¶

Paper. Masset P, Tano P, Kim HR, Malik AN, Pouget A, Uchida N (2025). Multi-timescale reinforcement learning in the brain. Nature 642:682-690. doi:10.1038/s41586-025-08929-9. The claims file (claims/masset-2025.yaml) was written from the accepted author manuscript in PubMed Central (main text, legends, Methods and Extended Data legends), with the paper's Mendeley code (doi:10.17632/tc43t3s7c5.1) and simulation code (github.com/pablotano8/multi_timescale_RL at 37f11c6).

Data. DANDI:000251, version draft, modified 2023-06-20T00:56:22Z. The dandiset has no published version, so the draft is the only version there is; it is pinned by its modification time, which the notebook checks. It holds the data of Kim et al. (2020), which the paper reuses: the VR task single units, one unit per file, and no cued delay task recordings. The cued delay units are in the paper's own deposit, Mendeley Data doi:10.17632/tc43t3s7c5.1 (version 1, 2025-04-09), file DA_SU_ODOR_NEW_W_OL.h5; its FinalAverageArray.mat (the paper's per-neuron table) and Valid_S.mat (the paper's neuron flags) link the two tasks' units. All files are streamed into memory.

Seeds. Random draws use each claim's seed, zlib.crc32(b"masset-2025/<claim id>"), and four more (plus 1000 to 4000); a second generator of a claim adds 1. Shared computations use the seed of the claim that defines them: the VR half splits that of fig3b-vr-ramp-population, the VR fit's initial values that of fig3-common-value-fit, the cued delay fits that of cued-delay-neurons.

The entry has four notebooks: vr_population.ipynb (VR claims on the population), vr_single_mouse.ipynb (single-mouse VR fits), vr_reward_expectation.ipynb (the common reward expectation model), cued_delay_and_cross_task.ipynb (link, cued delay and cross-task claims). The claims each one tests are listed below.

This notebook. Tested: link-units-across-tasks (a link claim this attempt adds), cued-delay-neurons, fig2b-anticipatory-licking, fig2c-mean-cue-response-decreases, fig2f-exponential-better-than-hyperbolic, fig2g-discount-factor-distribution, ed3f-discount-factor-reliable, fig2k-reward-timing-decoded, fig2k-better-than-single-discount, ed6e-exponential-decoding-better-than-hyperbolic, ed5-behavioral-neural-discount-uncorrelated, ed5g-single-animal-decoding, ed6g-decoding-matches-simulation, session-trial-counts, fig4a-discount-correlated-across-tasks, fig4b-bootstrap-correlation, ed10-cross-task-decoding. The cross-task claims use the VR population fit at the claims' seeds (refitted here); their seed range covers the cued delay fits and their own draws.

In [1]:
import os
for v in ("OMP_NUM_THREADS", "OPENBLAS_NUM_THREADS", "MKL_NUM_THREADS"):
    os.environ[v] = "1"
import time
import zlib
import collections
import warnings

import numpy as np
import pandas as pd
from scipy import stats
import matplotlib.pyplot as plt

import multiscale as ms

warnings.filterwarnings("ignore", category=RuntimeWarning)
pd.set_option("display.width", 200)
T0 = time.time()
OFFSETS = [0, 1000, 2000, 3000, 4000]


def seed(claim, offset=0):
    return zlib.crc32(f"masset-2025/{claim}".encode()) + offset


# --- load
info = ms.dandi_version_info()
print("dandiset", ms.DANDISET, "version", ms.DANDI_VERSION, "modified", info["modified"])
assert info["modified"].startswith(ms.DANDI_MODIFIED[:19])
assets = ms.dandi_assets()
files = ms.dandi_su_files(assets, kinds=("SU-VR-OL",))
odor = ms.odor_units()
aa = ms.average_array()
flags = ms.valid_flags()
print(f"loaded in {time.time() - T0:.0f} s")
dandiset 000251 version draft modified 2023-06-20T00:56:22.602125Z
loaded in 79 s

Data check¶

The Mendeley cued delay units (DA_SU_ODOR_NEW_W_OL.h5). The DANDI files are checked in vr_population.ipynb.

In [2]:
ou = pd.DataFrame([dict(key=u["key"], mouse=u["mouse"], session=u["session"], ml=u["ml"],
                        n_trials=len(u["grp"]), n_spikes=len(u["spikes"]), n_licks=len(u["licks"]),
                        groups=",".join(map(str, np.unique(u["grp"])))) for u in odor])
print(f"Cued delay units: {len(ou)}; by mouse:", ou.mouse.value_counts().sort_index().to_dict())
print("Group labels:", odor[0]["grp_label"])
print("Groups present in every unit:", ou.groups.unique().tolist())
osess = ou.groupby(["mouse", "session"]).n_trials.first()
print(f"Sessions (mouse and start time): {len(osess)}; trials per session mean {osess.mean():.1f}, "
      f"s.d. {osess.std():.1f}, range {osess.min()} to {osess.max()}")
print(f"ML position: {ou.ml.min():.1f} to {ou.ml.max():.1f} um")
ev = odor[0]["events"]
print("Event columns:", list(ev))
lag = np.concatenate([u["events"]["REW"] - u["events"]["VSTIM_ON"] - ms.DELAYS[u["grp"] - 1] for u in odor])
gap = np.concatenate([u["events"]["VSTIM_ON"] - u["events"]["TRIAL_START"] for u in odor])
print(f"Reward minus VSTIM_ON minus the group's delay (s): median {np.nanmedian(lag):.3f}, "
      f"range {np.nanmin(lag):.3f} to {np.nanmax(lag):.3f}")
print(f"VSTIM_ON minus TRIAL_START (s): median {np.nanmedian(gap):.3f}, range {np.nanmin(gap):.3f} to {np.nanmax(gap):.3f}")
Cued delay units: 67; by mouse: {3044: 32, 3045: 7, 3047: 1, 3048: 3, 3053: 2, 3054: 22}
Group labels: OdorId=1.0 CSUSDelay=600.0,OdorId=2.0 CSUSDelay=1500.0,OdorId=3.0 CSUSDelay=3750.0,OdorId=4.0 CSUSDelay=9375.0,
Groups present in every unit: ['1,2,3,4']
Sessions (mouse and start time): 39; trials per session mean 81.4, s.d. 12.7, range 50 to 108
ML position: 517.4 to 846.4 um
Event columns: ['TRIAL_START', 'VSTIM_ON', 'SCENE_MOVE', 'REW', 'VSTIM_OFF', 'TELEPORT', 'SCENE_PAUSE', 'SCENE_RESUME', 'TRIAL_END']
Reward minus VSTIM_ON minus the group's delay (s): median 0.045, range 0.030 to 0.367
VSTIM_ON minus TRIAL_START (s): median 1.304, range 1.289 to 1.514

VSTIM_ON comes 1.3 s after TRIAL_START, and the reward follows it by the group's delay plus about 50 ms in every trial: VSTIM_ON is the odor onset (the paper: odor 1.25 s after the trial start cue). The file does not name it so. Groups 1 to 4 are the delays 0.6, 1.5, 3.75 and 9.375 s (grp_label). Clock check for the cued delay units: the cue response should depend on the delay with the true labels and not with labels permuted across trials.

In [3]:
rng = np.random.default_rng(seed("cued-delay-neurons") + 1)
d_true, d_perm = [], []
for u in odor:
    r, d = ms.cue_responses(u)
    d_true.append(r[d == 0.6].mean() - r[d == 9.375].mean())
    dp = rng.permutation(d)
    d_perm.append(r[dp == 0.6].mean() - r[dp == 9.375].mean())
print(f"cue response 0.6 s minus 9.375 s cue, median over units: true labels {np.median(d_true):.2f} "
      f"spikes/s, permuted labels {np.median(d_perm):.2f}")
lk_true = np.median([ms.counts_aligned(u["licks"], u["events"]["REW"], 0, 1, 1)[0].mean() -
                     ms.counts_aligned(u["licks"], u["events"]["REW"], -1, 0, 1)[0].mean() for u in odor])
lk_shift = np.median([ms.counts_aligned(u["licks"], u["events"]["REW"] - 6, 0, 1, 1)[0].mean() -
                      ms.counts_aligned(u["licks"], u["events"]["REW"] - 6, -1, 0, 1)[0].mean() for u in odor])
print(f"licks 1 s after minus before reward: true times {lk_true:.2f}, times shifted by -6 s {lk_shift:.2f}")
cue response 0.6 s minus 9.375 s cue, median over units: true labels 5.33 spikes/s, permuted labels 0.28
licks 1 s after minus before reward: true times 2.33, times shifted by -6 s -0.08
In [4]:
vr, vr_dropped = ms.dandi_vr_units(files)
vr_rates = [ms.vr_trial_rates(u) for u in vr]
vr_mean = np.array([r.mean() for r in vr_rates])
vr_ml = np.array([u["ml"] for u in vr])
vr_mouse = np.array([u["mouse"] for u in vr])
vr_sel = (vr_mean > ms.RATE_MIN) & (vr_ml < ms.ML_MAX)
rates_sel = [r for r, s in zip(vr_rates, vr_sel) if s]
n_vr = len(rates_sel)
print(f"open-loop units {len(vr)} (left out: {vr_dropped}); selected (M6): {n_vr}")
print("by mouse:", dict(sorted(collections.Counter(vr_mouse[vr_sel]).items())))


def vr_run(off):
    ps = ms.vr_bootstrap_psths(rates_sel, np.random.default_rng(seed("fig3b-vr-ramp-population", off)))
    x0 = ms.cv_initial(n_vr, np.random.default_rng(seed("fig3-common-value-fit", off)))
    return dict(ps=ps, slopes=ms.ramp_slopes(ps), fits=ms.cv_fit_bootstraps(ps, x0))


t = time.time()
VR = {0: vr_run(0)}
f = VR[0]["fits"]
print(f"population fit at the claims' seeds (as in vr_population.ipynb): {time.time() - t:.0f} s; "
      f"gamma mean {f['gamma'].mean(0).mean():.3f}, s.d. {f['gamma'].mean(0).std(ddof=1):.3f}")
open-loop units 101 (left out: ['sub-3015/sub-3015_ses-SU-VR-OL-4.nwb']); selected (M6): 91
by mouse: {np.int64(3014): 2, np.int64(3015): 12, np.int64(3017): 1, np.int64(3021): 2, np.int64(3044): 31, np.int64(3045): 10, np.int64(3047): 1, np.int64(3048): 6, np.int64(3053): 3, np.int64(3054): 23}
population fit at the claims' seeds (as in vr_population.ipynb): 230 s; gamma mean 0.446, s.d. 0.237

Link: the units of the two tasks (link-units-across-tasks)¶

The units of DANDI:000251 (VR) and of the Mendeley cued delay file can be matched to the rows of the paper's per-neuron table (FinalAverageArray.mat), which gives each neuron's VR and cued delay recordings on one row.

Each unit is matched, within its mouse and among rows with the same number of trials, to the row whose per-trial spike counts (from the table's 10 ms rates) are closest. A match is accepted when the mean absolute difference is under 1 spike per trial and the next best row differs by more.

In [5]:
link_vr = ms.link_units(vr, aa, "vr", lambda u: u["trials"]["scene_move"])
link_od = ms.link_units(odor, aa, "odor", lambda u: u["events"]["VSTIM_ON"])
for name, link, n in (("DANDI VR units", link_vr, len(vr)), ("Mendeley cued delay units", link_od, len(odor))):
    diff = np.array([l[1] for l in link]); nxt = np.array([l[2] for l in link])
    ok = (diff < 1) & ~(nxt < 1)
    rows = [l[0] for l, k in zip(link, ok) if k]
    print(f"{name}: {ok.sum()} of {n} matched (difference {np.nanmin(diff):.2f} to {np.nanmax(diff):.2f} "
          f"spikes per trial; next best {np.nanmin(nxt):.2f} or more); distinct rows {len(set(rows))}")
vr_row = np.array([l[0] for l in link_vr]); od_row = np.array([l[0] for l in link_od])
row_ml = {r["row"]: r["ml"] for r in aa}
print("ML of the matched rows equals the files' ML:",
      all(abs(row_ml[r] - u["ml"]) < 0.01 for r, u in zip(vr_row, vr)),
      all(abs(row_ml[r] - u["ml"]) < 0.01 for r, u in zip(od_row, odor)))
print(f"Table rows: {sum('odor' in r for r in aa)} with the cued delay task, {sum('vr' in r for r in aa)} with VR")
print(f"Valid.OdorNew flags {flags['OdorNew'].sum()} rows, of which matched here {flags['OdorNew'][od_row].sum()}")
print(f"Valid.VR flags {flags['VR'].sum()} rows, of which matched here {flags['VR'][vr_row].sum()}")
unmatched_od = [r for r in aa if "odor" in r and r["row"] not in set(od_row)]
print(f"Table cued delay rows with no unit in the Mendeley file: {len(unmatched_od)}; their ML:",
      sorted(round(r["ml"]) for r in unmatched_od), "; mice:", sorted(r["mouse"] for r in unmatched_od))
both_rows = sorted(set(vr_row) & set(od_row))
print(f"Rows with a unit in both files: {len(both_rows)}")
print("Same mouse and same day for every pair:", all(
    odor[list(od_row).index(r)]["session"][:8] == vr[list(vr_row).index(r)]["start"][:10].replace("-", "")
    for r in both_rows))
DANDI VR units: 101 of 101 matched (difference 0.00 to 0.31 spikes per trial; next best 4.09 or more); distinct rows 101
Mendeley cued delay units: 67 of 67 matched (difference 0.01 to 0.32 spikes per trial; next best 3.82 or more); distinct rows 67
ML of the matched rows equals the files' ML: True True
Table rows: 78 with the cued delay task, 122 with VR
Valid.OdorNew flags 78 rows, of which matched here 67
Valid.VR flags 121 rows, of which matched here 101
Table cued delay rows with no unit in the Mendeley file: 11; their ML: [517, 517, 517, 517, 531, 567, 936, 1048, 1048, 1048, 1048] ; mice: [3044, 3044, 3044, 3044, 3049, 3049, 3049, 3049, 3050, 3053, 3054]
Rows with a unit in both files: 67
Same mouse and same day for every pair: False

Result: link-units-across-tasks. All 101 DANDI open-loop units and all 67 Mendeley cued delay units match one row each of the paper's table, at most 0.32 spikes per trial apart (the next best row at least 3.8 apart), and the matched rows carry the files' ML positions. The Mendeley file lacks 11 of the table's 78 cued delay rows, 5 of them at ML above 900 um. Every row with a cued delay unit also has a DANDI VR unit. Reproduced: the link holds for every unit in the files.

Cued delay task (Mendeley deposit)¶

Cue response (M1): rate 0.1 to 0.4 s after odor onset (VSTIM_ON), per trial. Fits (M2): for each of 100 random half splits, each half fitted with the exponential and the hyperbolic model; held-out R2 of each half's fit on the other half. Run under the seed of cued-delay-neurons and four more.

In [6]:
resp = [ms.cue_responses(u) for u in odor]
od_mouse = np.array([u["mouse"] for u in odor])
od_ml = np.array([u["ml"] for u in odor])
t = time.time()
OD = {off: ms.fit_neurons(resp, np.random.default_rng(seed("cued-delay-neurons", off))) for off in OFFSETS}
print(f"cued delay fits under 5 seeds: {time.time() - t:.0f} s")
mean_resp = np.array([np.mean([r[d == x].mean() for x in ms.DELAYS]) for r, d in resp])
print(f"cue response, mean over the four delays: {mean_resp.min():.2f} to {mean_resp.max():.2f} spikes/s")
print("half-fits with a delay missing from the half:",
      {off: int(np.isnan(OD[off]["firing"]).any(2).sum()) for off in OFFSETS})


print("half-fits with an undefined held-out R2 (all held-out responses equal):",
      {off: int(np.isnan(OD[off]["r2_exp"]).sum()) for off in OFFSETS})


def select_m3(fit, rate=None, ml=None):
    """M3; a neuron's held-out R2 is the mean over the half-fits where it is defined."""
    rate = mean_resp if rate is None else rate
    ml = od_ml if ml is None else ml
    r2 = np.nanmean(fit["r2_exp"], 0)
    return dict(r2=r2, sel=(r2 > 0) & (rate > ms.RATE_MIN) & (ml < ms.ML_MAX),
                r2_neg=r2 <= 0, low_rate=rate <= ms.RATE_MIN, high_ml=ml >= ms.ML_MAX)

M3 = {off: select_m3(OD[off]) for off in OFFSETS}
cued delay fits under 5 seeds: 182 s
cue response, mean over the four delays: 0.14 to 19.25 spikes/s
half-fits with a delay missing from the half: {0: 1, 1000: 0, 2000: 0, 3000: 0, 4000: 0}
half-fits with an undefined held-out R2 (all held-out responses equal): {0: 20, 1000: 29, 2000: 23, 3000: 25, 4000: 28}

cued-delay-neurons¶

Of 78 optogenetically identified VTA dopamine neurons recorded in the cued delay task, 50 pass the selection criteria.

In [7]:
for off in OFFSETS:
    m = M3[off]
    print(f"seed +{off}: selected {m['sel'].sum()}; held-out R2 <= 0: {m['r2_neg'].sum()}; mean cue response "
          f"<= 2 spikes/s: {m['low_rate'].sum()}; both: {(m['r2_neg'] & m['low_rate']).sum()}; ML >= 900: {(od_ml >= 900).sum()}")
sel0 = M3[0]["sel"]
print(f"\nrecorded (units in the Mendeley file): {len(odor)} (expected 78 +- 7.8); "
      f"Valid.OdorNew rows in the paper's table: {flags['OdorNew'].sum()}")
print(f"selected, claim seed: {sel0.sum()} (expected 50 +- 5)")
print("selected by mouse:", dict(sorted(collections.Counter(od_mouse[sel0]).items())))
print(f"held-out R2 (mean over 200 half-fits) range {M3[0]['r2'].min():.2f} to {M3[0]['r2'].max():.2f}")
# The 11 rows the paper's table flags (Valid.OdorNew) with no unit in the spike file. Their cue
# responses are taken from the table's 10 ms rates (0.1 to 0.4 s after odor onset), checked first
# on the 67 linked units against the spike counts.
chk = [(ms.cue_responses(u)[0], ms.table_cue_responses(aa[r])[0]) for u, r in zip(odor, od_row)]
dif = np.array([np.mean(np.abs(a - b)) for a, b in chk])
cor = np.array([np.corrcoef(a, b)[0, 1] for a, b in chk])
print(f"\ntable rates against spike counts, 67 linked units: mean absolute difference per trial "
      f"{dif.mean():.2f} spikes/s (largest {dif.max():.2f}); correlation over trials median {np.median(cor):.3f}, "
      f"smallest {cor.min():.3f}")
miss_rows = [r for r in aa if "odor" in r and r["row"] not in set(od_row)]
resp_miss = [ms.table_cue_responses(r) for r in miss_rows]
rate_miss = np.array([np.mean([r[d == x].mean() for x in ms.DELAYS]) for r, d in resp_miss])
ml_miss = np.array([r["ml"] for r in miss_rows])
ODM = {off: ms.fit_neurons(resp_miss, np.random.default_rng(seed("cued-delay-neurons", off) + 2)) for off in OFFSETS}
M3M = {off: select_m3(ODM[off], rate_miss, ml_miss) for off in OFFSETS}
print("All 78 flagged neurons (67 from the spike file, 11 from the table):")
for off in OFFSETS:
    a, b = M3[off], M3M[off]
    print(f"   seed +{off}: selected {a['sel'].sum() + b['sel'].sum()} (table units {b['sel'].sum()} of 11); "
          f"held-out R2 <= 0: {a['r2_neg'].sum() + b['r2_neg'].sum()}; mean cue response <= 2 spikes/s: "
          f"{a['low_rate'].sum() + b['low_rate'].sum()}; ML >= 900: {b['high_ml'].sum()}")
print(pd.DataFrame(dict(unit=[r["odor"]["name"] for r in miss_rows], ml=ml_miss.round(),
                        trials=[len(r) for r, _ in resp_miss], held_out_r2=M3M[0]["r2"].round(3),
                        cue_response=rate_miss.round(2), selected=M3M[0]["sel"])).to_string(index=False))
# fits of all 78 for the variants below
ODA = {off: {k: np.concatenate([OD[off][k], ODM[off][k]], 1) for k in OD[off]} for off in OFFSETS}
SELA = {off: np.r_[M3[off]["sel"], M3M[off]["sel"]] for off in OFFSETS}
seed +0: selected 43; held-out R2 <= 0: 17; mean cue response <= 2 spikes/s: 10; both: 3; ML >= 900: 0
seed +1000: selected 43; held-out R2 <= 0: 17; mean cue response <= 2 spikes/s: 10; both: 3; ML >= 900: 0
seed +2000: selected 45; held-out R2 <= 0: 16; mean cue response <= 2 spikes/s: 10; both: 4; ML >= 900: 0
seed +3000: selected 44; held-out R2 <= 0: 16; mean cue response <= 2 spikes/s: 10; both: 3; ML >= 900: 0
seed +4000: selected 43; held-out R2 <= 0: 18; mean cue response <= 2 spikes/s: 10; both: 4; ML >= 900: 0

recorded (units in the Mendeley file): 67 (expected 78 +- 7.8); Valid.OdorNew rows in the paper's table: 78
selected, claim seed: 43 (expected 50 +- 5)
selected by mouse: {np.int64(3044): 16, np.int64(3045): 6, np.int64(3053): 2, np.int64(3054): 19}
held-out R2 (mean over 200 half-fits) range -0.09 to 0.79
table rates against spike counts, 67 linked units: mean absolute difference per trial 0.43 spikes/s (largest 1.03); correlation over trials median 0.987, smallest 0.925
All 78 flagged neurons (67 from the spike file, 11 from the table):
   seed +0: selected 48 (table units 5 of 11); held-out R2 <= 0: 18; mean cue response <= 2 spikes/s: 11; ML >= 900: 5
   seed +1000: selected 48 (table units 5 of 11); held-out R2 <= 0: 18; mean cue response <= 2 spikes/s: 11; ML >= 900: 5
   seed +2000: selected 50 (table units 5 of 11); held-out R2 <= 0: 17; mean cue response <= 2 spikes/s: 11; ML >= 900: 5
   seed +3000: selected 49 (table units 5 of 11); held-out R2 <= 0: 17; mean cue response <= 2 spikes/s: 11; ML >= 900: 5
   seed +4000: selected 48 (table units 5 of 11); held-out R2 <= 0: 20; mean cue response <= 2 spikes/s: 11; ML >= 900: 5
          unit     ml  trials  held_out_r2  cue_response  selected
m3044s63r2e1u2  517.0      72        0.523         18.37      True
m3044s74r1e3u2  517.0      80        0.019          1.30     False
m3044s88r1e3u1  517.0      83        0.798          7.34      True
m3044s88r1e5u2  517.0      83        0.179          6.83      True
m3049s57r1e7u2 1048.0      53       -0.096          4.75     False
m3049s59r2e1u1 1048.0      83        0.703          5.38     False
m3049s59r2e6u3 1048.0      83        0.640         12.11     False
m3049s69r1e7u2 1048.0     124        0.152          3.88     False
m3050s71r1e5u1  936.0      85        0.207          8.57     False
m3053s64r1e0u2  567.0      85        0.378          4.24      True
m3054s62r1e4u2  531.0      80        0.417          2.70      True

Result: cued-delay-neurons. The Mendeley spike file holds 67 cued delay units, and 43 of them pass M3 under the claim's seed (17 with a held-out R2 at or below 0, 10 with a mean cue response at or below 2 spikes/s, 3 both, none at ML 900 um or more; 43 to 45 over the five seeds). The recorded count is outside 78 +- 7.8 at every seed, and the selected count outside 50 +- 5 except at seed plus 2000 (45). The selection behaves as in the paper (43 of 67 and 50 of 78 are both 0.64), and the shortfall is accounted for by the 11 neurons the paper's table flags (Valid.OdorNew) that are not in the deposit. The claims file allows those flags only as labels where they can be matched to deposited units, which the 11 are not, so they are a variant only: with their cue responses taken from the table's 10 ms rates, which match the spike counts of the 67 linked units (mean absolute difference 0.43 spikes/s per trial, median correlation 0.987), 48 of 78 pass M3 under the claim's seed (48 to 50 over the seeds), with exclusions 18, 11 and 5 (paper 17, 11 and 4). Partially reproduced: the effect is present, short of tolerance on the deposited units. Changed from reproduced in round 3, as the verifier agreed.

fig2b-anticipatory-licking¶

Mice lick in anticipation of reward, and the onset of anticipatory licking is later for cues predicting longer delays.

Lick rate per delay in 200 ms bins from -2 to 12 s around the odor, per unit's session, averaged over units. Onset readings: (a) first bin after the odor above the pre-cue mean plus half of the rise to the maximum before reward; (b) first bin after the odor above the pre-cue mean plus 2 s.d. of the pre-cue bins.

In [8]:
edges = np.arange(-2, 12.0001, 0.2)
centers = edges[:-1] + 0.1


def lick_psth(u):
    out = np.zeros((4, len(edges) - 1))
    for j in range(4):
        on = u["events"]["VSTIM_ON"][u["grp"] == j + 1]
        out[j] = ms.counts_aligned(u["licks"], on, -2, 12, 0.2)[0].mean(0) / 0.2
    return out

LP = np.array([lick_psth(u) for u in odor])


def onsets(P):
    out = {}
    pre = centers < 0
    for name in ("a", "b"):
        o = []
        for j, dly in enumerate(ms.DELAYS):
            x = P[j]
            base, sd = x[pre].mean(), x[pre].std(ddof=1)
            win = (centers > 0) & (centers < dly)
            thr = base + 0.5 * (x[win].max() - base) if name == "a" else base + 2 * sd
            above = np.where((centers > 0) & (x > thr))[0]
            o.append(centers[above[0]] if len(above) else np.nan)
        out[name] = np.array(o)
    return out

for label, k in (("all recorded units", np.ones(len(odor), bool)), ("selected units (M3)", sel0)):
    P = LP[k].mean(0)
    on = onsets(P)
    print(f"{label} (n = {k.sum()}): pre-cue rate {P[:, centers < 0].mean():.2f} licks/s; max before reward per delay "
          f"{[round(P[j][(centers > 0) & (centers < d)].max(), 2) for j, d in enumerate(ms.DELAYS)]}")
    for name in ("a", "b"):
        o = on[name]
        inc = bool(np.all(np.diff(o[1:]) > 0) and o[1] >= o[0])
        print(f"   onset reading ({name}), bin centres (s): {np.round(o, 2).tolist()}; increases with delay: {inc}")
fig, ax = plt.subplots(figsize=(6, 3))
for j in range(4):
    ax.plot(centers, LP.mean(0)[j], label=f"{ms.DELAYS[j]} s")
ax.set_xlabel("time from odor (s)"); ax.set_ylabel("licks/s"); ax.legend()
plt.show()
print(f"plotted lick rates range {LP.mean(0).min():.2f} to {LP.mean(0).max():.2f} licks/s")
all recorded units (n = 67): pre-cue rate 0.10 licks/s; max before reward per delay [np.float64(8.24), np.float64(7.46), np.float64(5.97), np.float64(3.89)]
   onset reading (a), bin centres (s): [0.3, 0.5, 2.3, 7.9]; increases with delay: True
   onset reading (b), bin centres (s): [0.3, 0.1, 0.1, 0.5]; increases with delay: False
selected units (M3) (n = 43): pre-cue rate 0.12 licks/s; max before reward per delay [np.float64(8.28), np.float64(7.47), np.float64(6.19), np.float64(4.15)]
   onset reading (a), bin centres (s): [0.3, 0.5, 2.3, 7.9]; increases with delay: True
   onset reading (b), bin centres (s): [0.1, 0.1, 0.1, 0.1]; increases with delay: False
No description has been provided for this image
plotted lick rates range 0.05 to 8.82 licks/s

Result: fig2b-anticipatory-licking. Under onset reading (a) the onset is at 0.3, 0.5, 2.3 and 7.9 s after the odor for the four delays, increasing with delay, over all 67 units and over the 43 selected. Reading (b) does not order them: pre-cue licking is near zero (0.10 licks/s), so 2 s.d. is crossed in the first bins. Reproduced under reading (a).

fig2c-mean-cue-response-decreases¶

The average cue response of the population decreases as the predicted reward delay increases.

Per neuron and delay, the mean cue response over trials, then the mean over the selected neurons. Readings: (a) 0 to 0.5 s after the odor, (b) 0.1 to 0.4 s (M1).

In [9]:
for name, win in (("(a) 0 to 0.5 s", (0, 0.5)), ("(b) 0.1 to 0.4 s", (0.1, 0.4))):
    per = []
    for u in odor:
        r, d = ms.cue_responses(u, win)
        per.append([r[d == x].mean() for x in ms.DELAYS])
    per = np.array(per)
    for off in OFFSETS:
        m = per[M3[off]["sel"]].mean(0)
        print(f"{name}, seed +{off} (n = {M3[off]['sel'].sum()}): population mean by delay {np.round(m, 2).tolist()}; "
              f"monotonic decrease: {bool(np.all(np.diff(m) < 0))}")
    m = per.mean(0)
    print(f"{name}, all 67 units: {np.round(m, 2).tolist()}")
per78 = np.array([[r[d == x].mean() for x in ms.DELAYS] for r, d in
                  [ms.cue_responses(u) for u in odor] + resp_miss])
m = per78[SELA[0]].mean(0)
print(f"0.1 to 0.4 s, with the table units, claim seed (n = {SELA[0].sum()}): {np.round(m, 2).tolist()}; "
      f"monotonic decrease: {bool(np.all(np.diff(m) < 0))}")
(a) 0 to 0.5 s, seed +0 (n = 43): population mean by delay [8.77, 6.72, 3.3, 2.71]; monotonic decrease: True
(a) 0 to 0.5 s, seed +1000 (n = 43): population mean by delay [8.77, 6.72, 3.3, 2.71]; monotonic decrease: True
(a) 0 to 0.5 s, seed +2000 (n = 45): population mean by delay [8.7, 6.72, 3.45, 2.76]; monotonic decrease: True
(a) 0 to 0.5 s, seed +3000 (n = 44): population mean by delay [8.67, 6.62, 3.34, 2.68]; monotonic decrease: True
(a) 0 to 0.5 s, seed +4000 (n = 43): population mean by delay [8.77, 6.72, 3.3, 2.71]; monotonic decrease: True
(a) 0 to 0.5 s, all 67 units: [7.05, 5.69, 3.31, 3.3]
(b) 0.1 to 0.4 s, seed +0 (n = 43): population mean by delay [11.68, 8.63, 3.7, 2.86]; monotonic decrease: True
(b) 0.1 to 0.4 s, seed +1000 (n = 43): population mean by delay [11.68, 8.63, 3.7, 2.86]; monotonic decrease: True
(b) 0.1 to 0.4 s, seed +2000 (n = 45): population mean by delay [11.66, 8.62, 3.93, 3.01]; monotonic decrease: True
(b) 0.1 to 0.4 s, seed +3000 (n = 44): population mean by delay [11.57, 8.49, 3.74, 2.84]; monotonic decrease: True
(b) 0.1 to 0.4 s, seed +4000 (n = 43): population mean by delay [11.68, 8.63, 3.7, 2.86]; monotonic decrease: True
(b) 0.1 to 0.4 s, all 67 units: [9.11, 7.08, 3.64, 3.59]
0.1 to 0.4 s, with the table units, claim seed (n = 48): [11.84, 8.86, 3.69, 2.97]; monotonic decrease: True

Result: fig2c-mean-cue-response-decreases. Over the 43 selected neurons the population mean falls monotonically with delay in both windows: 11.68, 8.63, 3.70 and 2.86 spikes/s in 0.1 to 0.4 s, and 8.77, 6.72, 3.30 and 2.71 in 0 to 0.5 s. Reproduced. With the 11 table units (48 neurons) the means are 11.84, 8.86, 3.69 and 2.97 spikes/s, also decreasing.

fig2f-exponential-better-than-hyperbolic¶

Across neurons, the exponential discount model fits held-out cue responses better than the hyperbolic model (P = 2.2 x 10-5).

In [10]:
for off in OFFSETS:
    s = M3[off]["sel"]
    diff = (np.nanmean(OD[off]["r2_exp"], 0) - np.nanmean(OD[off]["r2_hyp"], 0))[s]
    t_ = stats.ttest_1samp(diff, 0)
    print(f"seed +{off}: n = {s.sum()}, mean R2 difference (exp - hyp) {diff.mean():.4f}, "
          f"neurons with exp better {np.sum(diff > 0)}, t = {t_.statistic:.2f}, p = {t_.pvalue:.2g}")
s = M3[0]["sel"]
print(f"held-out R2, selected neurons: exponential mean {np.nanmean(OD[0]['r2_exp'], 0)[s].mean():.3f}, "
      f"hyperbolic {np.nanmean(OD[0]['r2_hyp'], 0)[s].mean():.3f}")
s = SELA[0]
diff = (np.nanmean(ODA[0]["r2_exp"], 0) - np.nanmean(ODA[0]["r2_hyp"], 0))[s]
t_ = stats.ttest_1samp(diff, 0)
print(f"with the table units, claim seed: n = {s.sum()}, mean R2 difference {diff.mean():.4f}, "
      f"t = {t_.statistic:.2f}, p = {t_.pvalue:.2g}")
seed +0: n = 43, mean R2 difference (exp - hyp) 0.0197, neurons with exp better 34, t = 4.78, p = 2.2e-05
seed +1000: n = 43, mean R2 difference (exp - hyp) 0.0201, neurons with exp better 34, t = 4.90, p = 1.5e-05
seed +2000: n = 45, mean R2 difference (exp - hyp) 0.0183, neurons with exp better 34, t = 4.52, p = 4.6e-05
seed +3000: n = 44, mean R2 difference (exp - hyp) 0.0194, neurons with exp better 33, t = 4.74, p = 2.3e-05
seed +4000: n = 43, mean R2 difference (exp - hyp) 0.0199, neurons with exp better 35, t = 4.80, p = 2.1e-05
held-out R2, selected neurons: exponential mean 0.456, hyperbolic 0.436
with the table units, claim seed: n = 48, mean R2 difference 0.0208, t = 5.21, p = 4.1e-06

Result: fig2f-exponential-better-than-hyperbolic. The mean held-out R2 difference (exponential minus hyperbolic) is 0.0197 over 43 neurons, 34 of which favour the exponential; t = 4.78, p = 2.2e-5 (paper 2.2 x 10-5). Reproduced. With the 11 table units (48 neurons): mean difference 0.0208, p = 4.1e-6.

fig2g-discount-factor-distribution¶

Inferred discount factors are widely distributed across neurons, 0.56 +- 0.21 (mean +- s.d.).

In [11]:
for off in OFFSETS:
    g = OD[off]["gamma"].mean(0)[M3[off]["sel"]]
    print(f"seed +{off}: n = {len(g)}, mean {g.mean():.3f}, s.d. {g.std(ddof=1):.3f}, range {g.min():.3f} to {g.max():.3f}")
g0 = OD[0]["gamma"].mean(0)[M3[0]["sel"]]
print(f"claim seed: mean {g0.mean():.3f} (expected 0.56 +- 0.056), s.d. {g0.std(ddof=1):.3f} (0.21 +- 0.021)")
for mouse in (3044, 3054):
    k = od_mouse[M3[0]["sel"]] == mouse
    print(f"mouse {mouse}: {k.sum()} neurons, mean {g0[k].mean():.3f}")
k = ~np.isin(od_mouse[M3[0]["sel"]], [3044, 3054])
print(f"other mice: {k.sum()} neurons, mean {g0[k].mean():.3f}")
for off in OFFSETS:
    g = ODA[off]["gamma"].mean(0)[SELA[off]]
    print(f"with the table units, seed +{off}: n = {len(g)}, mean {g.mean():.3f}, s.d. {g.std(ddof=1):.3f}")
seed +0: n = 43, mean 0.532, s.d. 0.227, range 0.071 to 0.914
seed +1000: n = 43, mean 0.532, s.d. 0.226, range 0.072 to 0.916
seed +2000: n = 45, mean 0.538, s.d. 0.223, range 0.072 to 0.912
seed +3000: n = 44, mean 0.536, s.d. 0.226, range 0.070 to 0.914
seed +4000: n = 43, mean 0.532, s.d. 0.226, range 0.072 to 0.912
claim seed: mean 0.532 (expected 0.56 +- 0.056), s.d. 0.227 (0.21 +- 0.021)
mouse 3044: 16 neurons, mean 0.454
mouse 3054: 19 neurons, mean 0.658
other mice: 8 neurons, mean 0.386
with the table units, seed +0: n = 48, mean 0.535, s.d. 0.217
with the table units, seed +1000: n = 48, mean 0.536, s.d. 0.216
with the table units, seed +2000: n = 50, mean 0.541, s.d. 0.214
with the table units, seed +3000: n = 49, mean 0.539, s.d. 0.216
with the table units, seed +4000: n = 48, mean 0.536, s.d. 0.216

Result: fig2g-discount-factor-distribution. Mean 0.532 and s.d. 0.227 over 43 neurons under the claim's seed, within 0.56 +- 0.056 and 0.21 +- 0.021. Reproduced. With the 11 table units (48 neurons): mean 0.535, s.d. 0.217, also within.

ed3f-discount-factor-reliable¶

Exponential-model parameters are consistent between the two halves of the trials; the mean correlation across neurons between halves is 0.84 for the gain, 0.9 for the baseline and 0.93 for the discount factor.

Per bootstrap, the Pearson correlation across neurons between the two halves' parameters (gain b, baseline a, discount factor gamma), then the mean over the 100 bootstraps. Readings: (a) the selected neurons, (b) all fitted units.

In [12]:
rows = []
for off in OFFSETS:
    for name, fit, k in (("(a) selected", OD[off], M3[off]["sel"]), ("(b) all fitted", OD[off], np.ones(len(odor), bool)),
                         ("(a) with table units", ODA[off], SELA[off]),
                         ("(b) with table units", ODA[off], np.ones(len(odor) + len(miss_rows), bool))):
        vals = {}
        for pname, col in (("gain", 1), ("baseline", 0), ("gamma", None)):
            x = fit["gamma"] if col is None else fit["exp"][:, :, col]
            rs = [stats.pearsonr(x[b, k], x[b + 100, k]) for b in range(100)]
            vals[pname] = np.mean([r[0] for r in rs])
            vals[f"max p {pname}"] = np.max([r[1] for r in rs])
        rows.append(dict(seed=off, neurons=name, n=k.sum(), **vals))
print(pd.DataFrame(rows).to_string(index=False, float_format=lambda x: f"{x:.3g}"))
print("expected: gain 0.84 +- 0.084, baseline 0.9 +- 0.09, gamma 0.93 +- 0.093")
 seed              neurons  n  gain  max p gain  baseline  max p baseline  gamma  max p gamma
    0         (a) selected 43 0.735    0.000817     0.877        2.06e-08  0.815     1.44e-06
    0       (b) all fitted 67 0.555     0.00876     0.876        2.65e-14  0.759     4.03e-08
    0 (a) with table units 48 0.749    0.000183     0.884        2.21e-10  0.796     5.33e-07
    0 (b) with table units 78  0.57     0.00435      0.88        1.97e-17  0.755     1.08e-08
 1000         (a) selected 43 0.752    0.000206     0.868        5.12e-08  0.814     1.37e-06
 1000       (b) all fitted 67 0.578     0.00968     0.879        5.36e-14  0.757     2.84e-08
 1000 (a) with table units 48 0.764    3.88e-05     0.877        1.21e-09  0.796     3.08e-06
 1000 (b) with table units 78 0.591     0.00191     0.884        6.95e-18  0.753     4.39e-10
 2000         (a) selected 45 0.671      0.0174     0.807        3.94e-05  0.717     0.000159
 2000       (b) all fitted 67 0.561     0.00378     0.884        6.09e-15  0.754     9.87e-08
 2000 (a) with table units 50 0.688     0.00435     0.824        7.57e-07  0.702     5.06e-05
 2000 (b) with table units 78 0.574    0.000497     0.887        1.04e-18  0.748     5.22e-09
 3000         (a) selected 44 0.693    0.000806     0.869        9.04e-09  0.771     9.42e-05
 3000       (b) all fitted 67 0.572    0.000418     0.878        1.67e-14  0.765     8.47e-09
 3000 (a) with table units 49 0.709    0.000138     0.879        1.69e-10  0.751      8.8e-05
 3000 (b) with table units 78 0.586    0.000191     0.883        1.06e-17   0.76     1.33e-10
 4000         (a) selected 43 0.723     0.00064     0.863         2.9e-09  0.817     2.83e-07
 4000       (b) all fitted 67 0.574     0.00127     0.876        4.84e-14  0.761     1.42e-07
 4000 (a) with table units 48 0.739     7.1e-05     0.875        1.46e-10  0.799     2.02e-07
 4000 (b) with table units 78 0.586    9.64e-05     0.882        1.87e-17  0.756      4.4e-09
expected: gain 0.84 +- 0.084, baseline 0.9 +- 0.09, gamma 0.93 +- 0.093

Result: ed3f-discount-factor-reliable. With the 43 selected neurons the mean split-half correlations are 0.735 (gain), 0.877 (baseline) and 0.815 (discount factor); with all 67, 0.555, 0.876 and 0.759; with the 11 table units added, 0.749, 0.884 and 0.796 (48 selected) and 0.570, 0.880 and 0.755 (all 78). Only the baseline is within tolerance under any reading; the gain and the discount factor are below 0.84 +- 0.084 and 0.93 +- 0.093 under every reading and seed. All correlations are positive with p below 0.02 in every bootstrap. The parameters agree between halves, less closely than reported: partially reproduced.

Decoding (fig2k-reward-timing-decoded, fig2k-better-than-single-discount, ed6e-exponential-decoding-better-than-hyperbolic)¶

M4: for each of the 200 half-fits, the discount matrix from that half's gammas over 0 to 12 s (120 points), and the other half's mean cue responses per delay, minus a baseline, each neuron scaled to its maximum over delays; regularised inverse with alpha = 2. Readings: (a) every singular component, (b) the first 12. Baseline: the Methods take it from the same half as the responses (main); the code from the half that gives the gammas (variant). The shuffle permutes neurons in the test responses, one permutation per decoding as in the code; every reading uses the same permutations (the same generator), so that the readings differ only in the decoder. Twenty draws of the permutations are made: the first is the test, and the share of the twenty with p < 0.05 shows how much the draw matters. Accuracy: 1-Wasserstein distance to the true delay (grid points 7, 16, 38 and 95). One-tailed signed-rank tests over the 200 decodings.

In [13]:
def other(k):
    return (k + 100) % 200


N_SHUFFLE = 20


def decode_set(fit, k_sel, rng, n_comp, baseline="methods", gam=None, matrix=None, n_shuffle=N_SHUFFLE):
    """M4 on the neurons k_sel. gam: (200, n) discount factors for the matrix (default: this
    task's own fits); the responses are the cued delay responses of the other half."""
    g = fit["gamma"][:, k_sel] if gam is None else gam
    F = fit["firing"][:, k_sel]
    A = fit["exp"][:, k_sel, 0]
    resp_test = F[[other(k) for k in range(200)]]
    base = A[[other(k) for k in range(200)]] if baseline == "methods" else A
    keep = ~np.isnan(resp_test).any((0, 2))
    W, WS = ms.run_decoding(g[:, keep], base[:, keep], resp_test[:, keep], rng, n_comp=n_comp,
                            matrix=None if matrix is None else matrix[:, keep], n_shuffle=n_shuffle)
    return W, WS, int((~keep).sum())


def single_discount(fit, k_sel):
    F = fit["firing"][:, k_sel]
    A, B = fit["exp"][:, k_sel, 0], fit["exp"][:, k_sel, 1]
    out = np.zeros((200, 4))
    for k in range(200):
        x = (F[other(k)] - A[k][:, None]) / B[k][:, None]
        keep = ~np.isnan(x).any(1)
        P = ms.single_discount_decode(x[keep], fit["gamma"][k, k_sel][keep].mean())
        out[k] = ms.wasserstein_to_point(P, ms.TRUE_IDX)
    return out


def hyp_matrix(fit, k_sel):
    kk = fit["hyp"][:, k_sel, 2]
    return 1 / (1 + kk[:, :, None] * ms.T_GRID[None, None, :])


DEC = {}
t = time.time()
for off in OFFSETS:
    s = M3[off]["sel"]
    for n_comp in (None, 12):
        for base in ("methods", "code"):
            rng = np.random.default_rng(seed("fig2k-reward-timing-decoded", off))
            W, WS, dropped = decode_set(OD[off], s, rng, n_comp, base)
            WH, _, _ = decode_set(OD[off], s, None, n_comp, base, matrix=hyp_matrix(OD[off], s), n_shuffle=0)
            DEC[(off, n_comp, base)] = dict(W=W, WS=WS, WH=WH, dropped=dropped)
    DEC[(off, "single")] = single_discount(OD[off], s)
print(f"decoding: {time.time() - t:.0f} s")
dW = max(np.nanmax(np.abs(DEC[(off, None, b)]["W"] - DEC[(off, 12, b)]["W"])) for off in OFFSETS for b in ("methods", "code"))
print(f"largest difference between the data distances of readings (a) and (b), any decoding: {dW:.2g} s")


def shuffle_pvals(W, WS):
    """p of each shuffle draw (draws x 4)."""
    return np.array([[ms.signrank_less(W[:, d], x[:, d]) for d in range(4)] for x in WS])
decoding: 25 s
largest difference between the data distances of readings (a) and (b), any decoding: 1.9e-06 s
In [14]:
def pvals(a, b):
    return [ms.signrank_less(a[:, d], b[:, d]) for d in range(4)]

rows = []
for (off, n_comp, base), v in [(k, v) for k, v in DEC.items() if len(k) == 3]:
    rows.append(dict(seed=off, components="all" if n_comp is None else n_comp, baseline=base,
                     **{f"W {d}": np.median(v["W"][:, j]) for j, d in enumerate(ms.DELAYS)},
                     **{f"shuffle {d}": np.median(v["WS"][0][:, j]) for j, d in enumerate(ms.DELAYS)},
                     **{f"p {d}": p for d, p in zip(ms.DELAYS, pvals(v["W"], v["WS"][0]))},
                     **{f"draws<0.05 {d}": q for d, q in zip(ms.DELAYS, (shuffle_pvals(v["W"], v["WS"]) < 0.05).mean(0))},
                     dropped=v["dropped"]))
D1 = pd.DataFrame(rows)
print("Median Wasserstein distance (s) and one-tailed p, data against shuffle (first draw); share of the 20 draws with p < 0.05:")
print(D1.to_string(index=False, float_format=lambda x: f"{x:.3g}"))
Median Wasserstein distance (s) and one-tailed p, data against shuffle (first draw); share of the 20 draws with p < 0.05:
 seed components baseline  W 0.6  W 1.5  W 3.75  W 9.375  shuffle 0.6  shuffle 1.5  shuffle 3.75  shuffle 9.375    p 0.6    p 1.5   p 3.75  p 9.375  draws<0.05 0.6  draws<0.05 1.5  draws<0.05 3.75  draws<0.05 9.375  dropped
    0        all  methods  0.397  0.837    2.48     3.55         1.15         1.93          3.45           7.13 1.24e-11 1.11e-34 3.95e-18 8.47e-32               1               1                1                 1        0
    0        all     code  0.399  0.826    2.35     4.04         1.14         1.98          3.48           6.26 1.14e-10 7.63e-35  1.9e-23 2.26e-21               1               1                1                 1        0
    0         12  methods  0.397  0.837    2.48     3.55         1.15         1.93          3.45           7.13 1.24e-11 1.11e-34 3.95e-18 8.47e-32               1               1                1                 1        0
    0         12     code  0.399  0.826    2.35     4.04         1.14         1.98          3.48           6.26 1.14e-10 7.63e-35  1.9e-23 2.26e-21               1               1                1                 1        0
 1000        all  methods  0.394  0.811    2.64     3.52         1.08         1.97           3.3            7.5  9.2e-12 5.18e-34 1.79e-10 2.02e-33               1               1                1                 1        0
 1000        all     code  0.393  0.796    2.41      4.3         1.09         2.15          3.27           6.79 1.93e-11 9.85e-35 2.21e-16 1.38e-18               1               1                1                 1        0
 1000         12  methods  0.394  0.811    2.64     3.52         1.08         1.97           3.3            7.5  9.2e-12 5.18e-34 1.79e-10 2.02e-33               1               1                1                 1        0
 1000         12     code  0.393  0.796    2.41      4.3         1.09         2.15          3.27           6.79 1.93e-11 9.85e-35 2.21e-16 1.38e-18               1               1                1                 1        0
 2000        all  methods  0.722  0.818    2.13     3.99         1.16         2.22          3.35           7.16   0.0124 7.18e-35 5.23e-22 2.13e-25               1               1                1                 1        0
 2000        all     code  0.704  0.794    2.01     4.08         1.18         2.22          3.37            6.2  0.00833 7.18e-35 5.69e-26 3.76e-22               1               1                1                 1        0
 2000         12  methods  0.722  0.818    2.13     3.99         1.16         2.22          3.35           7.16   0.0124 7.18e-35 5.23e-22 2.13e-25               1               1                1                 1        0
 2000         12     code  0.704  0.794    2.01     4.08         1.18         2.22          3.37            6.2  0.00833 7.18e-35 5.69e-26 3.76e-22               1               1                1                 1        0
 3000        all  methods  0.535  0.822    2.43     3.74         1.21         1.81          3.34           7.24 3.86e-08 7.29e-35  5.9e-21 3.07e-28               1               1                1                 1        0
 3000        all     code  0.542    0.8    2.23     4.14          1.2         1.92          3.37           6.61 1.37e-07 7.29e-35 4.92e-25 1.03e-23               1               1                1                 1        0
 3000         12  methods  0.535  0.822    2.43     3.74         1.21         1.81          3.34           7.24 3.86e-08 7.29e-35  5.9e-21 3.07e-28               1               1                1                 1        0
 3000         12     code  0.542    0.8    2.23     4.14          1.2         1.92          3.37           6.61 1.37e-07 7.29e-35 4.92e-25 1.03e-23               1               1                1                 1        0
 4000        all  methods  0.394  0.829    2.71     3.56          1.1         2.04          3.32            7.4 1.63e-13 7.86e-35  2.4e-14 5.25e-31               1               1                1                 1        0
 4000        all     code  0.395   0.81    2.38     4.16         1.07         2.24          3.26           6.73 3.41e-13 7.29e-35  1.1e-18    1e-18               1               1                1                 1        0
 4000         12  methods  0.394  0.829    2.71     3.56          1.1         2.04          3.32            7.4 1.63e-13 7.86e-35  2.4e-14 5.25e-31               1               1                1                 1        0
 4000         12     code  0.395   0.81    2.38     4.16         1.07         2.24          3.26           6.73 3.41e-13 7.29e-35  1.1e-18    1e-18               1               1                1                 1        0

Result: fig2k-reward-timing-decoded. Data beat shuffle at every delay under every reading (p at most 1.2e-10 under the claim's seed), and in all 20 shuffle draws. Readings (a) and (b) give the same data decodings (largest difference 1.9e-6 s), so the number of components does not matter here. With all components and the Methods baseline the median distances are 0.40, 0.84, 2.48 and 3.55 s, against 1.15, 1.93, 3.45 and 7.13 s for the shuffle. Reproduced.

In [15]:
rows = []
for (off, n_comp, base), v in [(k, v) for k, v in DEC.items() if len(k) == 3]:
    S1 = DEC[(off, "single")]
    rows.append(dict(seed=off, components="all" if n_comp is None else n_comp, baseline=base,
                     **{f"single {d}": np.median(S1[:, j]) for j, d in enumerate(ms.DELAYS)},
                     **{f"p {d}": p for d, p in zip(ms.DELAYS, pvals(v["W"], S1))}))
print("Single-discount decoder (M5): median distance (s), and one-tailed p that M4 is closer:")
print(pd.DataFrame(rows).to_string(index=False, float_format=lambda x: f"{x:.3g}"))
Single-discount decoder (M5): median distance (s), and one-tailed p that M4 is closer:
 seed components baseline  single 0.6  single 1.5  single 3.75  single 9.375  p 0.6    p 1.5  p 3.75  p 9.375
    0        all  methods       0.537        1.14         1.89           5.1  0.691  3.9e-32       1  7.1e-25
    0        all     code       0.537        1.14         1.89           5.1  0.802 2.28e-34       1 1.02e-13
    0         12  methods       0.537        1.14         1.89           5.1  0.691  3.9e-32       1  7.1e-25
    0         12     code       0.537        1.14         1.89           5.1  0.802 2.28e-34       1 1.02e-13
 1000        all  methods       0.529        1.14         1.88          5.19  0.251 6.63e-29       1 3.28e-33
 1000        all     code       0.529        1.14         1.88          5.19  0.292 4.46e-33       1 1.03e-10
 1000         12  methods       0.529        1.14         1.88          5.19  0.251 6.63e-29       1 3.28e-33
 1000         12     code       0.529        1.14         1.88          5.19  0.292 4.46e-33       1 1.03e-10
 2000        all  methods       0.577        1.16         1.92          5.16      1 1.67e-33       1 1.02e-09
 2000        all     code       0.577        1.16         1.92          5.16      1 1.48e-34   0.997 2.05e-15
 2000         12  methods       0.577        1.16         1.92          5.16      1 1.67e-33       1 1.02e-09
 2000         12     code       0.577        1.16         1.92          5.16      1 1.48e-34   0.997 2.05e-15
 3000        all  methods       0.549        1.17         1.93          5.16      1 1.18e-34       1 8.11e-17
 3000        all     code       0.549        1.17         1.93          5.16      1 7.74e-35       1 5.36e-13
 3000         12  methods       0.549        1.17         1.93          5.16      1 1.18e-34       1 8.11e-17
 3000         12     code       0.549        1.17         1.93          5.16      1 7.74e-35       1 5.36e-13
 4000        all  methods        0.53        1.14         1.89          5.12  0.175 6.76e-34       1  1.4e-23
 4000        all     code        0.53        1.14         1.89          5.12  0.185 7.18e-35       1 5.52e-09
 4000         12  methods        0.53        1.14         1.89          5.12  0.175 6.76e-34       1  1.4e-23
 4000         12     code        0.53        1.14         1.89          5.12  0.185 7.18e-35       1 5.52e-09

Result: fig2k-better-than-single-discount. The population decoder is closer than the single-discount decoder at 1.5 s (p = 3.9e-32) and 9.375 s (p = 7.1e-25), but not at 3.75 s (p = 1; medians 2.48 against 1.89 s), under every reading; at 0.6 s p = 0.69, as in the paper. Two of the three delays: partially reproduced.

In [16]:
rows = []
for (off, n_comp, base), v in [(k, v) for k, v in DEC.items() if len(k) == 3]:
    rows.append(dict(seed=off, components="all" if n_comp is None else n_comp, baseline=base,
                     **{f"hyp {d}": np.median(v["WH"][:, j]) for j, d in enumerate(ms.DELAYS)},
                     **{f"p {d}": p for d, p in zip(ms.DELAYS, pvals(v["W"], v["WH"]))}))
print("Hyperbolic discount matrix: median distance (s), and one-tailed p that the exponential matrix is closer:")
print(pd.DataFrame(rows).to_string(index=False, float_format=lambda x: f"{x:.3g}"))
Hyperbolic discount matrix: median distance (s), and one-tailed p that the exponential matrix is closer:
 seed components baseline  hyp 0.6  hyp 1.5  hyp 3.75  hyp 9.375  p 0.6    p 1.5   p 3.75  p 9.375
    0        all  methods    0.449    0.997       3.3       3.84  0.996 5.71e-29  1.2e-32 2.17e-14
    0        all     code    0.449    0.983      3.22       3.93  0.998 3.37e-32 2.48e-33  0.00948
    0         12  methods    0.449    0.997       3.3       3.84  0.996 5.71e-29  1.2e-32 2.17e-14
    0         12     code    0.449    0.983      3.22       3.93  0.998 3.37e-32 2.48e-33  0.00948
 1000        all  methods     0.45    0.988      3.36        3.8  0.719 2.08e-28 2.35e-32  2.2e-18
 1000        all     code    0.451    0.974      3.27       4.19  0.773 2.21e-30 2.38e-34   0.0339
 1000         12  methods     0.45    0.988      3.36        3.8  0.719 2.08e-28 2.35e-32  2.2e-18
 1000         12     code    0.451    0.974      3.27       4.19  0.773 2.21e-30 2.38e-34   0.0339
 2000        all  methods    0.458    0.967       3.1       4.63      1 1.09e-30 2.96e-29 3.14e-15
 2000        all     code    0.459    0.958      3.13       3.74      1 7.78e-33 1.85e-34    0.982
 2000         12  methods    0.458    0.967       3.1       4.63      1 1.09e-30 2.96e-29 3.14e-15
 2000         12     code    0.459    0.958      3.13       3.74      1 7.78e-33 1.85e-34    0.982
 3000        all  methods    0.456    0.991      3.37       4.02      1 6.36e-32 9.41e-35 1.14e-08
 3000        all     code    0.455    0.977      3.29       4.05      1 2.49e-34 7.86e-35   0.0819
 3000         12  methods    0.456    0.991      3.37       4.02      1 6.36e-32 9.41e-35 1.14e-08
 3000         12     code    0.455    0.977      3.29       4.05      1 2.49e-34 7.86e-35   0.0819
 4000        all  methods    0.451        1      3.34        3.9  0.756 2.41e-33  4.4e-33 8.74e-18
 4000        all     code    0.451    0.986      3.25       4.11  0.604 1.79e-34 3.62e-34 4.51e-05
 4000         12  methods    0.451        1      3.34        3.9  0.756 2.41e-33  4.4e-33 8.74e-18
 4000         12     code    0.451    0.986      3.25       4.11  0.604 1.79e-34 3.62e-34 4.51e-05

Result: ed6e-exponential-decoding-better-than-hyperbolic. The exponential matrix decodes better than the hyperbolic one at 1.5, 3.75 and 9.375 s under every reading at the claim's seed (p at most 0.0095). With the code's baseline the 9.375 s result changes with the seed (p = 0.98 under seed plus 2000); with the Methods' baseline it holds under all five seeds. The outcome rests on the Methods' baseline. The exponential matrix is not better at 0.6 s (p at least 0.996). Reproduced.

ed5-behavioral-neural-discount-uncorrelated¶

Discount factors fitted to anticipatory licking are not correlated with the neural discount factors in the two mice with most neurons (r = -0.29, P = 0.27 in m3044; r = -0.029, P = 0.9 in m3054).

Per unit, the session's mean lick rate per delay after the odor, fitted with the exponential model of M2 (four points); Spearman correlation with the neural gamma over the mouse's units. Windows: 0 to 0.6 s (Methods) and 0.2 to 0.8 s (code, variant). Neuron sets: (a) M3, (b) the code's set (held-out R2 > 0 and ML < 900 um, no rate cut).

In [17]:
def lick_gamma(u, win):
    r = [ms.counts_aligned(u["licks"], u["events"]["VSTIM_ON"][u["grp"] == j + 1], win[0], win[1],
                           win[1] - win[0])[0][:, 0].mean() / (win[1] - win[0]) for j in range(4)]
    return np.exp(ms.fit_exp(ms.DELAYS, np.array(r))[2]), r

rows = []
for wname, win in (("Methods 0-0.6 s", (0, 0.6)), ("code 0.2-0.8 s", (0.2, 0.8))):
    lg = np.array([lick_gamma(u, win)[0] for u in odor])
    for off in OFFSETS:
        gn = OD[off]["gamma"].mean(0)
        for sname, k in (("(a) M3", M3[off]["sel"]), ("(b) code set", (M3[off]["r2"] > 0) & (od_ml < 900))):
            for mouse in (3044, 3054):
                kk = k & (od_mouse == mouse)
                r, p = stats.spearmanr(lg[kk], gn[kk])
                rows.append(dict(window=wname, seed=off, neurons=sname, mouse=mouse, n=kk.sum(), r=r, p=p))
L5 = pd.DataFrame(rows)
print(L5[L5.seed == 0].to_string(index=False, float_format=lambda x: f"{x:.3f}"))
print("\nsmallest p over seeds:", L5.groupby(["window", "neurons", "mouse"]).p.min().round(3).to_dict())
         window  seed      neurons  mouse  n      r     p
Methods 0-0.6 s     0       (a) M3   3044 16 -0.473 0.064
Methods 0-0.6 s     0       (a) M3   3054 19 -0.095 0.699
Methods 0-0.6 s     0 (b) code set   3044 21 -0.335 0.138
Methods 0-0.6 s     0 (b) code set   3054 21 -0.022 0.924
 code 0.2-0.8 s     0       (a) M3   3044 16 -0.322 0.224
 code 0.2-0.8 s     0       (a) M3   3054 19 -0.176 0.471
 code 0.2-0.8 s     0 (b) code set   3044 21 -0.077 0.740
 code 0.2-0.8 s     0 (b) code set   3054 21 -0.067 0.774

smallest p over seeds: {('Methods 0-0.6 s', '(a) M3', 3044): 0.064, ('Methods 0-0.6 s', '(a) M3', 3054): 0.699, ('Methods 0-0.6 s', '(b) code set', 3044): 0.085, ('Methods 0-0.6 s', '(b) code set', 3054): 0.924, ('code 0.2-0.8 s', '(a) M3', 3044): 0.224, ('code 0.2-0.8 s', '(a) M3', 3054): 0.471, ('code 0.2-0.8 s', '(b) code set', 3044): 0.49, ('code 0.2-0.8 s', '(b) code set', 3054): 0.774}

Result: ed5-behavioral-neural-discount-uncorrelated. No correlation reaches p < 0.05 under the claim's seed: with the Methods window and the M3 neurons, r = -0.473 (p = 0.064, 16 neurons) in m3044 and r = -0.095 (p = 0.70, 19 neurons) in m3054; the code's window and neuron set give p from 0.14 to 0.92. Reproduced. The line above gives the smallest p over the five seeds.

ed5g-single-animal-decoding¶

Reward timing can also be decoded from the cue responses of the neurons of a single mouse, in the two mice with most neurons (m3044 and m3054), slightly less accurately than from the whole population.

M4 on each mouse's M3 neurons (Methods baseline). The shuffle permutations come from the claim's generator for m3044 and its second generator (seed plus 1) for m3054; both readings use the same permutations, and twenty draws are made as for Fig. 2k.

In [18]:
rows = []
for off in OFFSETS:
    for mouse in (3044, 3054):
        s = M3[off]["sel"] & (od_mouse == mouse)
        for n_comp in (None, 12):
            rng = np.random.default_rng(seed("ed5g-single-animal-decoding", off) + (mouse == 3054))
            W, WS, dropped = decode_set(OD[off], s, rng, n_comp, "methods")
            pd_ = shuffle_pvals(W, WS)
            rows.append(dict(seed=off, mouse=mouse, n=s.sum(), components="all" if n_comp is None else n_comp,
                             **{f"W {d}": np.median(W[:, j]) for j, d in enumerate(ms.DELAYS)},
                             **{f"p {d}": p for d, p in zip(ms.DELAYS, pd_[0])},
                             **{f"draws<0.05 {d}": q for d, q in zip(ms.DELAYS, (pd_ < 0.05).mean(0))},
                             **{f"median p {d}": q for d, q in zip(ms.DELAYS, np.median(pd_, 0))}))
print("p of the first shuffle draw; share of the 20 draws with p < 0.05; median p over the draws")
print(pd.DataFrame(rows).to_string(index=False, float_format=lambda x: f"{x:.3g}"))
print("population, claim seed:", {d: round(np.median(DEC[(0, None, 'methods')]["W"][:, j]), 3) for j, d in enumerate(ms.DELAYS)})
p of the first shuffle draw; share of the 20 draws with p < 0.05; median p over the draws
 seed  mouse  n components  W 0.6  W 1.5  W 3.75  W 9.375    p 0.6    p 1.5   p 3.75  p 9.375  draws<0.05 0.6  draws<0.05 1.5  draws<0.05 3.75  draws<0.05 9.375  median p 0.6  median p 1.5  median p 3.75  median p 9.375
    0   3044 16        all   0.38   1.06    1.98      8.3 3.61e-05 5.21e-09 9.37e-25    0.333               1               1                1              0.25      1.42e-05      3.77e-09       6.44e-21          0.0851
    0   3044 16         12   0.38   1.06    1.98      8.3 3.61e-05 5.21e-09 9.37e-25    0.333               1               1                1              0.25      1.42e-05      3.77e-09       6.44e-21          0.0851
    0   3054 19        all  0.417  0.924    2.43     3.76 2.17e-19 1.46e-18    8e-16 3.14e-32               1               1                1                 1      9.82e-19      1.34e-18       1.92e-18        1.64e-32
    0   3054 19         12  0.417  0.924    2.43     3.76 2.17e-19 1.46e-18    8e-16 3.14e-32               1               1                1                 1      9.82e-19      1.34e-18       1.92e-18        1.64e-32
 1000   3044 16        all   0.38   1.03    1.98     8.29  2.4e-08 2.45e-12 1.01e-24    0.463               1               1                1              0.05      2.66e-06       6.7e-14       2.45e-20           0.319
 1000   3044 16         12   0.38   1.03    1.98     8.29  2.4e-08 2.45e-12 1.01e-24    0.463               1               1                1              0.05      2.66e-06       6.7e-14       2.45e-20           0.319
 1000   3054 19        all  0.419  0.926    2.59     3.68  1.7e-14 8.42e-19 4.45e-15 1.28e-33               1               1                1                 1      2.92e-17      7.28e-19       4.47e-15        1.45e-33
 1000   3054 19         12  0.419  0.926    2.59     3.68  1.7e-14 8.42e-19 4.45e-15 1.28e-33               1               1                1                 1      2.92e-17      7.28e-19       4.47e-15        1.45e-33
 2000   3044 16        all   0.38   1.06    2.01     8.37 2.11e-09 6.85e-07 1.29e-20    0.405               1               1                1              0.15      1.01e-08      6.43e-10       8.58e-21           0.145
 2000   3044 16         12   0.38   1.06    2.01     8.37 2.11e-09 6.85e-07 1.29e-20    0.405               1               1                1              0.15      1.01e-08      6.43e-10       8.58e-21           0.145
 2000   3054 19        all  0.419  0.925    2.45     3.71 2.76e-16 1.11e-17 1.74e-18  4.8e-33               1               1                1                 1       2.6e-17      5.12e-17       3.49e-16        3.73e-32
 2000   3054 19         12  0.419  0.925    2.45     3.71 2.76e-16 1.11e-17 1.74e-18  4.8e-33               1               1                1                 1       2.6e-17      5.12e-17       3.49e-16        3.73e-32
 3000   3044 16        all   0.38   1.07    1.99     8.29 5.82e-09 3.49e-10 8.23e-21   0.0182               1               1                1               0.1      7.11e-08      8.92e-11       4.89e-22           0.355
 3000   3044 16         12   0.38   1.07    1.99     8.29 5.82e-09 3.49e-10 8.23e-21   0.0182               1               1                1               0.1      7.11e-08      8.92e-11       4.89e-22           0.355
 3000   3054 19        all  0.413  0.929    2.51     3.73 1.54e-17 4.63e-18  9.5e-18 1.04e-33               1               1                1                 1      6.99e-18      2.46e-17       2.56e-16        7.18e-33
 3000   3054 19         12  0.413  0.929    2.51     3.73 1.54e-17 4.63e-18  9.5e-18 1.04e-33               1               1                1                 1      6.99e-18      2.46e-17       2.56e-16        7.18e-33
 4000   3044 16        all  0.379    1.1    1.93     8.47 5.01e-11 5.61e-10 1.39e-21     0.47               1               1                1               0.1      5.41e-11      1.28e-09       3.08e-22           0.283
 4000   3044 16         12  0.379    1.1    1.93     8.47 5.01e-11 5.61e-10 1.39e-21     0.47               1               1                1               0.1      5.41e-11      1.28e-09       3.08e-22           0.283
 4000   3054 19        all  0.417  0.929    2.49     3.75 1.14e-18 4.13e-20 3.56e-19 5.27e-32               1               1                1                 1      2.79e-16      8.75e-17       1.27e-16        6.25e-32
 4000   3054 19         12  0.417  0.929    2.49     3.75 1.14e-18 4.13e-20 3.56e-19 5.27e-32               1               1                1                 1      2.79e-16      8.75e-17       1.27e-16        6.25e-32
population, claim seed: {np.float64(0.6): np.float64(0.397), np.float64(1.5): np.float64(0.837), np.float64(3.75): np.float64(2.482), np.float64(9.375): np.float64(3.548)}

Result: ed5g-single-animal-decoding. m3054 (19 neurons): data beat shuffle at all four delays (p at most 8e-16, and in all 20 draws). m3044 (16 neurons): at 0.6, 1.5 and 3.75 s (p at most 3.6e-5, all 20 draws) but not at 9.375 s (p = 0.33 in the first draw; 5 of 20 draws below 0.05, median p 0.085). Readings (a) and (b) give the same result. Median distances in m3054 (0.42, 0.92, 2.43, 3.76 s) are close to the population's (0.40, 0.84, 2.48, 3.55 s); m3044 is far off at 9.375 s (8.3 s). Three delays of four in m3044: partially reproduced. Under seed plus 3000 the first draw gives p = 0.018 at 9.375 s in m3044 (2 of 20 draws below 0.05).

ed6g-decoding-matches-simulation¶

Decoding accuracy from the recorded cue responses is comparable to decoding from responses simulated from each neuron's fitted exponential model with matched trial numbers; the data are marginally better at 0.6, 3.75 and 9.375 s and not at 1.5 s.

For each selected neuron, 20 trials per delay drawn as Poisson counts with mean a + b exp(c t) (the mean parameters over the 200 half-fits; code SimulationForRecovery_Olf.m), fitted as M2 and decoded as M4 (all components, Methods baseline). One-tailed signed-rank test that the data distance is smaller. One simulated data set per seed is the test; under the claim's seed nine more are drawn from the same generator, to show how much the outcome depends on the simulation.

In [19]:
rows = []
t = time.time()
N_SIM = 10


def simulate(off, rng):
    s = M3[off]["sel"]
    E = OD[off]["exp"].mean(0)[s]
    dl = np.repeat(ms.DELAYS, 20)
    sim = [(rng.poisson(a + b * np.exp(c * dl)).astype(float), dl) for a, b, c in E]
    SF = ms.fit_neurons(sim, rng)
    Wsim, _, _ = decode_set(SF, np.ones(s.sum(), bool), None, None, "methods", n_shuffle=0)
    return Wsim


for off in OFFSETS:
    rng = np.random.default_rng(seed("ed6g-decoding-matches-simulation", off))
    W = DEC[(off, None, "methods")]["W"]
    for draw in range(N_SIM if off == 0 else 1):
        Wsim = simulate(off, rng)
        rows.append(dict(seed=off, draw=draw, n=M3[off]["sel"].sum(),
                         **{f"data {d}": np.median(W[:, j]) for j, d in enumerate(ms.DELAYS)},
                         **{f"sim {d}": np.median(Wsim[:, j]) for j, d in enumerate(ms.DELAYS)},
                         **{f"p {d}": p for d, p in zip(ms.DELAYS, pvals(W, Wsim))}))
print(f"simulations: {time.time() - t:.0f} s")
S6 = pd.DataFrame(rows)
print(S6.to_string(index=False, float_format=lambda x: f"{x:.3g}"))
print("paper: p = 0.002, 0.999, < 1e-12, 0.027 at 0.6, 1.5, 3.75, 9.375 s")
pc = S6[[f"p {d}" for d in ms.DELAYS]].to_numpy()
agree = np.c_[pc[:, 0] < 0.05, pc[:, 1] >= 0.05, pc[:, 2] < 0.05, pc[:, 3] < 0.05]
S6["delays agreeing"] = agree.sum(1)
c0 = (S6.seed == 0).to_numpy()
print(f"claim seed, {c0.sum()} simulated data sets: share agreeing with the paper per delay "
      f"{np.round(agree[c0].mean(0), 2).tolist()}; delays agreeing per data set {S6['delays agreeing'][c0].tolist()}; "
      f"all four in {(agree[c0].all(1)).sum()}, three or more in {(agree[c0].sum(1) >= 3).sum()}")
print("first data set of each seed, delays agreeing:", S6[S6.draw == 0]["delays agreeing"].tolist())
simulations: 296 s
 seed  draw  n  data 0.6  data 1.5  data 3.75  data 9.375  sim 0.6  sim 1.5  sim 3.75  sim 9.375    p 0.6    p 1.5   p 3.75  p 9.375
    0     0 43     0.397     0.837       2.48        3.55    0.971    0.911       2.7       2.77 1.95e-08 1.54e-10    0.021        1
    0     1 43     0.397     0.837       2.48        3.55     1.06     1.03       2.8       3.03 3.45e-11 8.86e-23  0.00479        1
    0     2 43     0.397     0.837       2.48        3.55    0.826    0.946      1.86       3.66 2.87e-05 4.36e-15        1     0.22
    0     3 43     0.397     0.837       2.48        3.55    0.904    0.783      2.05       4.98 4.53e-07        1        1 3.49e-20
    0     4 43     0.397     0.837       2.48        3.55    0.926     1.08      2.19       4.01 5.16e-08 2.24e-25        1 1.71e-06
    0     5 43     0.397     0.837       2.48        3.55     1.08    0.801       1.7       4.55 3.29e-13    0.999        1 3.12e-11
    0     6 43     0.397     0.837       2.48        3.55    0.791    0.906      2.94       2.54   0.0174 8.78e-14  2.5e-06        1
    0     7 43     0.397     0.837       2.48        3.55        1    0.804      1.87        5.3 4.36e-10    0.973        1 1.17e-23
    0     8 43     0.397     0.837       2.48        3.55     1.11    0.881      2.54       2.85 1.09e-12 1.17e-05    0.288        1
    0     9 43     0.397     0.837       2.48        3.55    0.998    0.976      2.46       3.02 5.72e-09  6.5e-18    0.849        1
 1000     0 43     0.394     0.811       2.64        3.52     1.03    0.889      1.81       4.04 7.95e-10 1.02e-09        1 9.47e-09
 2000     0 45     0.722     0.818       2.13        3.99    0.474     1.03       2.5       2.98        1 3.44e-29 6.68e-07        1
 3000     0 44     0.535     0.822       2.43        3.74    0.882    0.969      1.68       3.54    0.407 1.32e-22        1    0.975
 4000     0 43     0.394     0.829       2.71        3.56     1.07     0.91      2.64       2.88 1.92e-13 1.52e-12    0.517        1
paper: p = 0.002, 0.999, < 1e-12, 0.027 at 0.6, 1.5, 3.75, 9.375 s
claim seed, 10 simulated data sets: share agreeing with the paper per delay [1.0, 0.3, 0.3, 0.4]; delays agreeing per data set [2, 2, 1, 3, 2, 3, 2, 3, 1, 1]; all four in 0, three or more in 3
first data set of each seed, delays agreeing: [2, 2, 1, 0, 1]

Result: ed6g-decoding-matches-simulation. Data against the first simulated data set (43 neurons, claim's seed): p = 2e-8 at 0.6 s and 0.021 at 3.75 s, as in the paper; p = 1.5e-10 at 1.5 s, where the paper finds no difference (0.999), and p = 1 at 9.375 s, where the paper finds the data better (0.027). The test agrees with the paper at two of the four delays: not reproduced. The outcome depends on the simulated data set: over 10 data sets under the claim's seed, the test agrees at 0.6 s in all, at 1.5 and 3.75 s in 3 and at 9.375 s in 4; no data set agrees at all four delays and 3 agree at three (the criterion's partial case). The first data sets of the five seeds agree at 2, 2, 1, 0 and 1 delays.

Both tasks¶

session-trial-counts¶

Mice performed 81.4 +- 12.5 trials per session across 36 cued delay sessions and 58.8 +- 21.7 trials per session across 60 VR sessions with recorded neurons.

Sessions are a mouse and a start time. Readings for the sessions: (a) every session with a unit, (b) sessions with a unit of the analysed set (M3, M6). The VR files hold only the open-loop trials of the standard track, and the cued delay file only the four odor trials, so the two trial readings of the criterion give the same counts.

In [20]:
def sess_stats(keys, ntr):
    df = pd.DataFrame(dict(key=keys, n=ntr)).groupby("key").n.first()
    return len(df), df.mean(), df.std()

rows = []
for name, k in (("(a) every unit", np.ones(len(vr), bool)), ("(b) M6 units", vr_sel)):
    n, m, sd = sess_stats([(u["subject"], u["start"]) for u, kk in zip(vr, k) if kk],
                          [len(u["trials"]["trial_type"]) for u, kk in zip(vr, k) if kk])
    rows.append(dict(task="VR (DANDI)", sessions=name, n_sessions=n, trials_mean=m, trials_sd=sd))
for name, k in (("(a) every unit", np.ones(len(odor), bool)), ("(b) M3 units", M3[0]["sel"])):
    n, m, sd = sess_stats([(u["mouse"], u["session"]) for u, kk in zip(odor, k) if kk],
                          [len(u["grp"]) for u, kk in zip(odor, k) if kk])
    rows.append(dict(task="cued delay (Mendeley)", sessions=name, n_sessions=n, trials_mean=m, trials_sd=sd))
print(pd.DataFrame(rows).to_string(index=False, float_format=lambda x: f"{x:.1f}"))
print("expected: cued delay 36 +- 3.6 sessions, 81.4 +- 8.14 trials; VR 60 +- 6 sessions, 58.8 +- 5.88 trials")
# Variant: the paper's 78 flagged cued delay neurons (the table's rows), sessions by the unit name
# (mouse and session number, for example m3044s63).
import re
sess_of = lambda r: re.match(r"(m\d+s\d+)", r["odor"]["name"]).group(1)
print("linked units: sessions by name", len({sess_of(aa[r]) for r in od_row}), "and by file start time",
      len({(u["mouse"], u["session"]) for u in odor}))
flag_rows = [r for r in aa if "odor" in r]
sel_rows = {od_row[i] for i in np.where(M3[0]["sel"])[0]} | {r["row"] for r, s in zip(miss_rows, M3M[0]["sel"]) if s}
rows = []
for name, rr in (("(a) every flagged neuron", flag_rows), ("(b) M3 neurons, claim seed", [r for r in flag_rows if r["row"] in sel_rows])):
    n, m, sd = sess_stats([sess_of(r) for r in rr], [r["odor"]["rate"].shape[0] for r in rr])
    rows.append(dict(task="cued delay (table, 78)", sessions=name, n_sessions=n, trials_mean=m, trials_sd=sd))
print(pd.DataFrame(rows).to_string(index=False, float_format=lambda x: f"{x:.1f}"))
for off in OFFSETS:
    sr = {od_row[i] for i in np.where(M3[off]["sel"])[0]} | {r["row"] for r, s in zip(miss_rows, M3M[off]["sel"]) if s}
    n, m, sd = sess_stats([sess_of(r) for r in flag_rows if r["row"] in sr], [r["odor"]["rate"].shape[0] for r in flag_rows if r["row"] in sr])
    print(f"   (b) with the table units, seed +{off}: {n} sessions, {m:.1f} +- {sd:.1f} trials")
print("sessions of the 11 table units that the spike file lacks:", sorted({sess_of(r) for r in miss_rows} - {sess_of(aa[r]) for r in od_row}))
                 task       sessions  n_sessions  trials_mean  trials_sd
           VR (DANDI) (a) every unit          66         58.8       19.5
           VR (DANDI)   (b) M6 units          62         59.2       19.8
cued delay (Mendeley) (a) every unit          39         81.4       12.7
cued delay (Mendeley)   (b) M3 units          30         82.6       13.7
expected: cued delay 36 +- 3.6 sessions, 81.4 +- 8.14 trials; VR 60 +- 6 sessions, 58.8 +- 5.88 trials
linked units: sessions by name 39 and by file start time 39
                  task                   sessions  n_sessions  trials_mean  trials_sd
cued delay (table, 78)   (a) every flagged neuron          44         81.9       14.3
cued delay (table, 78) (b) M3 neurons, claim seed          32         82.3       13.4
   (b) with the table units, seed +0: 32 sessions, 82.3 +- 13.4 trials
   (b) with the table units, seed +1000: 32 sessions, 82.3 +- 13.4 trials
   (b) with the table units, seed +2000: 34 sessions, 81.7 +- 13.5 trials
   (b) with the table units, seed +3000: 33 sessions, 82.3 +- 13.2 trials
   (b) with the table units, seed +4000: 32 sessions, 82.3 +- 13.4 trials
sessions of the 11 table units that the spike file lacks: ['m3049s57', 'm3049s59', 'm3049s69', 'm3050s71', 'm3053s64']

Result: session-trial-counts. On the deposited files, reading (a), every session with a unit: VR 66 sessions with 58.8 +- 19.5 trials, cued delay 39 sessions with 81.4 +- 12.7 trials, all within tolerance (60 +- 6, 58.8 +- 5.88, 36 +- 3.6, 81.4 +- 8.14), with no random draws. The VR count sits on the upper bound. Reading (b) gives 62 VR sessions (59.2 trials) and 30 cued delay sessions (82.6), the latter outside. Reproduced. The cued delay pass is weak evidence that the paper's count was reproduced, as it depends on the deposit being incomplete: the spike file lacks 11 of the paper's 78 flagged cued delay neurons, adding units can only add sessions, and the table puts the 78 in 44 sessions under reading (a) (81.9 trials), outside 36 +- 3.6, and 32 under reading (b) at the claim's seed (32 to 34 over the seeds). These table counts are a variant, as the claims file allows the flags only as labels of deposited units (see cued-delay-neurons). Changed from partially reproduced in round 3, as the verifier agreed.

fig4a-discount-correlated-across-tasks¶

For the 43 neurons recorded in both tasks, the discount factors inferred in the VR task and the cued delay task are correlated (Spearman r = 0.45, P = 0.0013).

Neurons are paired through the link (one row of the paper's table holds both recordings). Pairs that pass both M3 and M6; Spearman correlation of the mean gammas, one-tailed.

In [21]:
vr_sel_idx = np.where(vr_sel)[0]
row_to_vrpos = {vr_row[i]: j for j, i in enumerate(vr_sel_idx)}
row_to_od = {r: i for i, r in enumerate(od_row)}
same_day = {r: odor[row_to_od[r]]["session"][:8] == vr[list(vr_row).index(r)]["start"][:10].replace("-", "")
            for r in both_rows}
print(f"rows with both recordings: {len(both_rows)}; recorded on the same day: {sum(same_day.values())}")


def pairs(off):
    P = [(row_to_od[r], row_to_vrpos[r]) for r in both_rows if r in row_to_vrpos and M3[off]["sel"][row_to_od[r]]]
    return np.array(P)

rows = []
for off in OFFSETS:
    P = pairs(off)
    gv = VR[0]["fits"]["gamma"].mean(0)[P[:, 1]]
    go = OD[off]["gamma"].mean(0)[P[:, 0]]
    r, p = stats.spearmanr(gv, go, alternative="greater")
    sd = np.array([same_day[od_row[i]] for i in P[:, 0]])
    r2, p2 = stats.spearmanr(gv[sd], go[sd], alternative="greater")
    rows.append(dict(seed=off, n=len(P), r=r, p=p, n_same_day=sd.sum(), r_same_day=r2, p_same_day=p2))
print(pd.DataFrame(rows).to_string(index=False, float_format=lambda x: f"{x:.3g}"))
print("expected: 43 +- 4.3 neurons, r = 0.45 +- 0.045, one-tailed p < 0.05")
P0 = pairs(0)
print("pairs by mouse:", dict(sorted(collections.Counter(od_mouse[P0[:, 0]]).items())))
rows with both recordings: 67; recorded on the same day: 66
 seed  n     r        p  n_same_day  r_same_day  p_same_day
    0 40 0.462  0.00134          39       0.439      0.0026
 1000 40 0.461  0.00137          39       0.438     0.00267
 2000 42 0.468 0.000896          41       0.444      0.0018
 3000 41 0.471 0.000931          40       0.449     0.00184
 4000 40 0.461  0.00137          39       0.438     0.00267
expected: 43 +- 4.3 neurons, r = 0.45 +- 0.045, one-tailed p < 0.05
pairs by mouse: {np.int64(3044): 16, np.int64(3045): 4, np.int64(3053): 2, np.int64(3054): 18}

Result: fig4a-discount-correlated-across-tasks. 40 neurons pass both selections (43 +- 4.3); Spearman r = 0.462, one-tailed p = 0.0013 (0.45 +- 0.045). Reproduced. 39 of the 40 pairs were recorded on the same day (r = 0.439 over those).

fig4b-bootstrap-correlation¶

Correlations between the two tasks' discount factors over random pairs of bootstrap estimates are positive, 0.34 +- 0.104 (mean +- s.d.).

Each pair is one random half-fit of the VR model and one of the cued delay model, Spearman correlation over the paired neurons. Readings: (a) the code's draw (an index from 1 to 100, the first halves only), (b) a draw over all 200 half-fits. 10,000 pairs (Methods) and 100,000 (code, variant). One-sample one-tailed t-test against zero.

In [22]:
def rank_rows(x):
    return np.argsort(np.argsort(x, axis=1), axis=1).astype(float)

rows = []
for off in OFFSETS:
    P = pairs(off)
    GV = rank_rows(VR[0]["fits"]["gamma"][:, P[:, 1]])
    GO = rank_rows(OD[off]["gamma"][:, P[:, 0]])
    rng = np.random.default_rng(seed("fig4b-bootstrap-correlation", off))
    for reading, hi in (("(a) first halves", 100), ("(b) all 200", 200)):
        for npairs in (10000, 100000):
            iv, io = rng.integers(0, hi, npairs), rng.integers(0, hi, npairs)
            a = GV[iv] - GV[iv].mean(1, keepdims=True)
            b = GO[io] - GO[io].mean(1, keepdims=True)
            r = (a * b).sum(1) / np.sqrt((a ** 2).sum(1) * (b ** 2).sum(1))
            t_ = stats.ttest_1samp(r, 0, alternative="greater")
            rows.append(dict(seed=off, reading=reading, pairs=npairs, mean=r.mean(), sd=r.std(ddof=1), p=t_.pvalue))
print(pd.DataFrame(rows).to_string(index=False, float_format=lambda x: f"{x:.3g}"))
print("expected: mean 0.34 +- 0.034, s.d. 0.104 +- 0.0104, p < 0.05")
 seed          reading  pairs  mean    sd  p
    0 (a) first halves  10000 0.364 0.104  0
    0 (a) first halves 100000 0.363 0.104  0
    0      (b) all 200  10000 0.342 0.107  0
    0      (b) all 200 100000  0.34 0.108  0
 1000 (a) first halves  10000 0.363 0.106  0
 1000 (a) first halves 100000 0.364 0.106  0
 1000      (b) all 200  10000 0.337  0.11  0
 1000      (b) all 200 100000 0.338  0.11  0
 2000 (a) first halves  10000 0.355 0.113  0
 2000 (a) first halves 100000 0.355 0.113  0
 2000      (b) all 200  10000 0.336 0.116  0
 2000      (b) all 200 100000 0.336 0.115  0
 3000 (a) first halves  10000 0.356 0.115  0
 3000 (a) first halves 100000 0.357 0.116  0
 3000      (b) all 200  10000 0.339 0.116  0
 3000      (b) all 200 100000 0.337 0.116  0
 4000 (a) first halves  10000 0.365 0.104  0
 4000 (a) first halves 100000 0.362 0.104  0
 4000      (b) all 200  10000  0.34 0.108  0
 4000      (b) all 200 100000 0.339 0.108  0
expected: mean 0.34 +- 0.034, s.d. 0.104 +- 0.0104, p < 0.05

Result: fig4b-bootstrap-correlation. Under reading (b), all 200 half-fits, the mean is 0.342 and the s.d. 0.107 (10,000 pairs), within 0.34 +- 0.034 and 0.104 +- 0.0104, with p printed as 0; reading (a) gives 0.364 and 0.104, also within. Reproduced.

ed10-cross-task-decoding¶

Reward timing in the cued delay task can be decoded with the discount factors inferred in the VR task, better than shuffle for the 1.5, 3.75 and 9.375 s delays.

M4 on the paired neurons, with the discount matrix of each VR half-fit (fit k with cued delay fit k's other half as test responses). Baselines: the cued delay fit of the test half (Methods) and of fit k (code).

In [23]:
rows = []
for off in OFFSETS:
    P = pairs(off)
    k_od = np.zeros(len(odor), bool); k_od[P[:, 0]] = True
    order = np.argsort(P[:, 0])
    gv = VR[0]["fits"]["gamma"][:, P[order, 1]]
    for n_comp in (None, 12):
        for base in ("methods", "code"):
            rng = np.random.default_rng(seed("ed10-cross-task-decoding", off))
            W, WS, dropped = decode_set(OD[off], k_od, rng, n_comp, base, gam=gv)
            pd_ = shuffle_pvals(W, WS)
            rows.append(dict(seed=off, n=len(P), components="all" if n_comp is None else n_comp, baseline=base,
                             **{f"W {d}": np.median(W[:, j]) for j, d in enumerate(ms.DELAYS)},
                             **{f"shuffle {d}": np.median(WS[0][:, j]) for j, d in enumerate(ms.DELAYS)},
                             **{f"p {d}": p for d, p in zip(ms.DELAYS, pd_[0])},
                             **{f"draws<0.05 {d}": q for d, q in zip(ms.DELAYS, (pd_ < 0.05).mean(0))},
                             **{f"median p {d}": q for d, q in zip(ms.DELAYS, np.median(pd_, 0))}))
D10 = pd.DataFrame(rows)
print("p of the first shuffle draw; share of the 20 draws with p < 0.05; median p over the draws")
print(D10.to_string(index=False, float_format=lambda x: f"{x:.3g}"))
p of the first shuffle draw; share of the 20 draws with p < 0.05; median p over the draws
 seed  n components baseline  W 0.6  W 1.5  W 3.75  W 9.375  shuffle 0.6  shuffle 1.5  shuffle 3.75  shuffle 9.375  p 0.6    p 1.5   p 3.75  p 9.375  draws<0.05 0.6  draws<0.05 1.5  draws<0.05 3.75  draws<0.05 9.375  median p 0.6  median p 1.5  median p 3.75  median p 9.375
    0 40        all  methods   1.11   1.06    1.74     6.81        0.813            2          3.68           6.96      1 2.91e-15  2.5e-16   0.0975               0               1                1               0.3         0.999      1.07e-14       4.02e-14           0.104
    0 40        all     code   1.11   1.06    1.75      6.8        0.808         2.01          3.57           6.66      1 9.65e-17 2.73e-19    0.827               0               1                1                 0         0.999      1.65e-14       1.27e-16           0.794
    0 40         12  methods   1.11   1.06    1.74     6.81        0.813            2          3.68           6.96      1 2.91e-15  2.5e-16   0.0975               0               1                1               0.3         0.999      1.07e-14       4.02e-14           0.104
    0 40         12     code   1.11   1.06    1.75      6.8        0.808         2.01          3.57           6.66      1 9.65e-17 2.73e-19    0.827               0               1                1                 0         0.999      1.65e-14       1.27e-16           0.794
 1000 40        all  methods   1.08   1.04    1.77     6.82         0.83         1.99          3.41           7.21  0.997 1.27e-15 9.69e-19    0.178               0               1                1              0.15         0.999      3.19e-14       1.23e-18           0.163
 1000 40        all     code   1.07   1.06    1.77     6.61        0.794         1.98          3.27           6.98  0.996 2.51e-15 1.02e-16    0.146               0               1                1                 0         0.999      1.47e-13       1.07e-16           0.621
 1000 40         12  methods   1.08   1.04    1.77     6.82         0.83         1.99          3.41           7.21  0.997 1.27e-15 9.69e-19    0.178               0               1                1              0.15         0.999      3.19e-14       1.23e-18           0.163
 1000 40         12     code   1.07   1.06    1.77     6.61        0.794         1.98          3.27           6.98  0.996 2.51e-15 1.02e-16    0.146               0               1                1                 0         0.999      1.47e-13       1.07e-16           0.621
 2000 42        all  methods   1.14   1.06    1.76     6.62        0.799         2.07          4.12           6.92      1 5.61e-17 5.64e-21  0.00787               0               1                1              0.65             1      1.07e-14       1.14e-15          0.0365
 2000 42        all     code   1.13   1.07    1.78     5.96        0.778         2.11          3.89           6.61      1 6.83e-16 3.95e-20  0.00232               0               1                1              0.85             1       8.5e-13       3.23e-15          0.0062
 2000 42         12  methods   1.14   1.06    1.76     6.62        0.799         2.07          4.12           6.92      1 5.61e-17 5.64e-21  0.00787               0               1                1              0.65             1      1.07e-14       1.14e-15          0.0365
 2000 42         12     code   1.13   1.07    1.78     5.96        0.778         2.11          3.89           6.61      1 6.83e-16 3.95e-20  0.00232               0               1                1              0.85             1       8.5e-13       3.23e-15          0.0062
 3000 41        all  methods   1.21   1.07     1.7     6.79        0.829          1.9          3.39           6.87  0.997 1.65e-12 3.73e-16    0.286               0               1                1               0.1             1      3.84e-14       1.37e-16           0.202
 3000 41        all     code   1.21   1.06    1.74     6.83        0.832         1.88          3.65           6.62  0.996 7.51e-14 3.09e-17    0.773               0               1                1                 0             1      6.37e-14       2.24e-16           0.708
 3000 41         12  methods   1.21   1.07     1.7     6.79        0.829          1.9          3.39           6.87  0.997 1.65e-12 3.73e-16    0.286               0               1                1               0.1             1      3.84e-14       1.37e-16           0.202
 3000 41         12     code   1.21   1.06    1.74     6.83        0.832         1.88          3.65           6.62  0.996 7.51e-14 3.09e-17    0.773               0               1                1                 0             1      6.37e-14       2.24e-16           0.708
 4000 40        all  methods   1.15   1.03    1.78     7.01        0.777         1.96          3.47           6.71      1 3.92e-17 2.15e-15    0.778               0               1                1              0.05             1      1.88e-14       2.98e-16           0.158
 4000 40        all     code   1.13   1.04    1.85     6.69        0.771         2.02          3.43           6.33      1 6.83e-16  1.7e-15    0.931               0               1                1                 0             1      1.28e-13       3.84e-16           0.749
 4000 40         12  methods   1.15   1.03    1.78     7.01        0.777         1.96          3.47           6.71      1 3.92e-17 2.15e-15    0.778               0               1                1              0.05             1      1.88e-14       2.98e-16           0.158
 4000 40         12     code   1.13   1.04    1.85     6.69        0.771         2.02          3.43           6.33      1 6.83e-16  1.7e-15    0.931               0               1                1                 0             1      1.28e-13       3.84e-16           0.749

Result: ed10-cross-task-decoding. Data beat shuffle at 1.5 and 3.75 s under every reading and in all 20 draws (p at most 2.9e-15 under the claim's seed), but not at 9.375 s: p = 0.098 with the Methods baseline (6 of 20 draws below 0.05, median p 0.10) and 0.83 with the code's (none of 20). At 0.6 s p is at least 0.996, as in the paper. Two of the three delays: partially reproduced. Under seed plus 2000 9.375 s passes (p = 0.0079, 13 of 20 draws), which would make the claim reproduced.

Summary¶

Claim Outcome (claims' seeds)
link-units-across-tasks reproduced
cued-delay-neurons partially reproduced
fig2b-anticipatory-licking reproduced
fig2c-mean-cue-response-decreases reproduced
fig2f-exponential-better-than-hyperbolic reproduced
fig2g-discount-factor-distribution reproduced
ed3f-discount-factor-reliable partially reproduced
fig2k-reward-timing-decoded reproduced
fig2k-better-than-single-discount partially reproduced
ed6e-exponential-decoding-better-than-hyperbolic reproduced
ed5-behavioral-neural-discount-uncorrelated reproduced
ed5g-single-animal-decoding partially reproduced
ed6g-decoding-matches-simulation not reproduced
session-trial-counts reproduced
fig4a-discount-correlated-across-tasks reproduced
fig4b-bootstrap-correlation reproduced
ed10-cross-task-decoding partially reproduced

The outcomes under the other four seeds are in the tables above and in the attempt record.

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.

Differences from the paper's method. The cue responses are computed from the spike times of the Mendeley file, where the code reads precomputed per-trial rates (CellValuesArray.mat). Fits use scipy's bounded least squares from the code's start points and bounds. Half splits are disjoint. The Wasserstein distance to the true delay is computed exactly, where the code samples 100,000 points. The decoder's number of singular components and the baseline subtracted from the test responses are open; every combination is shown, and the two component readings give the same data decodings. Each shuffle test is repeated over 20 draws of the permutations; the first is the test. The 11 cued delay neurons the spike file lacks are taken from the paper's table (its 10 ms rates) only as variants. The cross-task claims use the VR population fit at the claims' seeds only.

The data. DANDI:000251 holds no cued delay recordings; the paper's Mendeley deposit holds 67 of the 78 cued delay units of its own table as spike times, so 11 (5 at ML above 900 um) are only in the table, as 10 ms rates. The Mendeley file does not say which event column is the odor onset (it is VSTIM_ON). Every deposited unit of both tasks matches one row of the paper's table.