Masset et al. (2025): VR task, population (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: fig3b-vr-ramp-population, fig3-common-value-fit, ed8b-slope-correlates-with-discount, ed7c-discount-not-related-to-ml-position, ed7de-gain-baseline-not-related-to-ml-position, ed8cd-vr-licking-not-related-to-discount. The other claims are in the other three notebooks (ed9g-models-agree in vr_reward_expectation.ipynb), or blocked (the four simulation claims; see the summary).

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)
print(f"loaded in {time.time() - T0:.0f} s")
dandiset 000251 version draft modified 2023-06-20T00:56:22.602125Z
loaded in 158 s

Data check¶

DANDI:000251 first: what the archive lists, the single-unit files, recordings deposited twice, and the open-loop units the VR claims use.

In [2]:
kinds = collections.Counter(p.split("_ses-")[1].rsplit("-", 1)[0] for p in assets if "_ses-" in p)
print(f"DANDI:{ms.DANDISET} {ms.DANDI_VERSION}: {len(assets)} files")
print(pd.Series(kinds).sort_index().to_string())
su = pd.DataFrame([dict(path=u["path"], kind=u["kind"], subject=u["subject"], start=u["start"][:19],
                        n_units=u["n_units"], ml=u["ml"], n_spikes=len(u["spikes"]),
                        n_trials=len(u["trials"]["trial_type"]),
                        trial_types=" | ".join(sorted(set(u["trials"]["trial_type"])))) for u in files])
print("\nSingle-unit files read:", len(su), "; units per file:", su.n_units.unique().tolist())
print("Subjects with single units:", sorted(su.subject.unique()))
print("Trial types by file kind:")
print(su.groupby("kind").trial_types.agg(lambda s: sorted(set("; ".join(s).split(" | ")))[:6]).to_string())
DANDI:000251 draft: 513 files
Ca-VS-MB                        12
Ca-VS-MB-SPD                    11
Ca-VS-MB-THREE-TP               10
Ca-VS-MB-TP-PAUSE                9
Ca-VS-VR                        16
Ca-VS-VR-BTW-TRACKS-FWD-TP       6
Ca-VS-VR-BTW-TRACKS-REWSIZE      4
Ca-VS-VR-BWD-TP                  6
Ca-VS-VR-CLOOP-PATTERN           6
Ca-VS-VR-CLOOP-SOLID             6
Ca-VS-VR-DYNSPD                  5
Ca-VS-VR-SPD                    15
Ca-VS-VR-THREE-TP               15
Ca-VS-VR-TP-BTW-TRACKS           6
Ca-VS-VR-TP-PAUSE               11
DAsensor-VS-VR                  10
DAsensor-VS-VR-SPD              10
DAsensor-VS-VR-THREE-TP          9
DAsensor-VS-VR-TP-PAUSE         10
SU-VR-ALL-OL                    78
SU-VR-ALL-SPD                   78
SU-VR-ALL-TP                    78
SU-VR-OL                       102

Single-unit files read: 336 ; units per file: [1]
Subjects with single units: ['3014', '3015', '3017', '3021', '3044', '3045', '3047', '3048', '3053', '3054']
Trial types by file kind:
kind
SU-VR-ALL-OL     [same=1.0; same=1.0; same=1.0; same=1.0; same=...
SU-VR-ALL-SPD    [gain=0.5, gain=1.0, gain=2.0, gain=2.0; gain=...
SU-VR-ALL-TP     [ytpst=1000.0 scnpz=1000.0, ytpst=1000.0 scnpz...
SU-VR-OL         [same=1.0; same=1.0; same=1.0; same=1.0; same=...
In [3]:
# Recordings deposited twice: files whose spike trains are identical.
groups = collections.defaultdict(list)
for u in files:
    groups[u["spike_key"]].append(u["path"].split("/")[1].replace(".nwb", ""))
dups = [g for g in groups.values() if len(g) > 1]
print(f"{len(groups)} distinct spike trains in {len(files)} files; {len(dups)} deposited more than once")
print(collections.Counter(tuple(sorted(x.split("_ses-")[1].rsplit("-", 1)[0] for x in g)) for g in dups))
print("Examples:", dups[:3])
print("Groups that mix kinds other than SU-VR-OL with SU-VR-ALL-OL:",
      [g for g in dups if not all(("SU-VR-OL" in x or "SU-VR-ALL-OL" in x) for x in g)])
# What the files say about the copies: identifiers, session IDs, descriptions and start times.
by_name = {u["path"].split("/")[1].replace(".nwb", ""): u for u in files}
dg = [[by_name[x] for x in g] for g in dups]
print("\nIn the 78 groups: same identifier", sum(len({u["identifier"] for u in g}) == 1 for g in dg),
      "; same session_id", sum(len({u["session_id"] for u in g}) == 1 for g in dg),
      "; same subject and session start time", sum(len({(u["subject"], u["start"]) for u in g}) == 1 for g in dg))
print("example group:", [(u["identifier"], u["session_id"], u["start"]) for u in dg[0]])
print("session descriptions of all files:", dict(collections.Counter(u["session_desc"] for u in files)))
print("units table descriptions of all files:", dict(collections.Counter(u["unit_desc"] for u in files)))
by_start = collections.defaultdict(set)
for u in files:
    by_start[(u["subject"], u["start"])].add(u["spike_key"])
print(f"subject and start time pairs: {len(by_start)}, of which {sum(len(k) > 1 for k in by_start.values())} "
      "hold more than one distinct spike train (different units of one session)")
desc = ms.dandi_description()
print("dandiset description:", desc)
print("description mentions duplicates or copies:", any(w in desc.lower() for w in ("duplicate", "copy", "copies", "twice", "same unit")))
vr, vr_dropped = ms.dandi_vr_units(files)
print(f"\nOpen-loop units (SU-VR-OL files, one copy of each spike train, only 'same=1.0' trials): {len(vr)}")
print("Left out, an OL-named file whose trials include teleports:", vr_dropped)
for p in vr_dropped:
    u = next(x for x in files if x["path"] == p)
    print("   its trial types:", dict(collections.Counter(u["trials"]["trial_type"])))
257 distinct spike trains in 336 files; 78 deposited more than once
Counter({('SU-VR-ALL-OL', 'SU-VR-OL'): 77, ('SU-VR-ALL-OL', 'SU-VR-ALL-TP', 'SU-VR-OL'): 1})
Examples: [['sub-3014_ses-SU-VR-ALL-OL-1', 'sub-3014_ses-SU-VR-OL-2'], ['sub-3015_ses-SU-VR-ALL-OL-10', 'sub-3015_ses-SU-VR-OL-11'], ['sub-3015_ses-SU-VR-ALL-OL-11', 'sub-3015_ses-SU-VR-OL-12']]
Groups that mix kinds other than SU-VR-OL with SU-VR-ALL-OL: [['sub-3015_ses-SU-VR-ALL-OL-3', 'sub-3015_ses-SU-VR-ALL-TP-3', 'sub-3015_ses-SU-VR-OL-4']]

In the 78 groups: same identifier 0 ; same session_id 0 ; same subject and session start time 78
example group: [('SU_VR_ALL_OL_1', 'SU_VR_ALL_OL_1', '2018-11-08T16:11:30-04:56'), ('SU_VR_OL_2', 'SU_VR_OL_2', '2018-11-08T16:11:30-04:56')]
session descriptions of all files: {'Data for Kim et al. 2020.': 336}
units table descriptions of all files: {'Autogenerated by NWBFile': 336}
subject and start time pairs: 165, of which 59 hold more than one distinct spike train (different units of one session)
dandiset description: This dandiset contains the data associated with "A Unified Framework for Dopamine Signals across Timescales" (Kim et al. 2020). It is comprised of fiber photometry data, single-unit recordings, stimulus variables, and behavioral measurements across a wide variety of experimental manipulations. 
description mentions duplicates or copies: False

Open-loop units (SU-VR-OL files, one copy of each spike train, only 'same=1.0' trials): 101
Left out, an OL-named file whose trials include teleports: ['sub-3015/sub-3015_ses-SU-VR-OL-4.nwb']
   its trial types: {np.str_('ytpst=1000.0 scnpz=1000.0'): 125, np.str_('ytpst=65.0 scnpz=1000.0'): 13, np.str_('ytpst=1000.0 scnpz=70.0'): 13, np.str_('ytpst=40.0 scnpz=1000.0'): 13}

The SU-VR-ALL-OL files repeat the spike trains of SU-VR-OL files, unit by unit, under other session numbers, and one SU-VR-OL file of mouse 3015 holds the same unit as an SU-VR-ALL-TP file, with a teleport trial table (a teleport session filed as open loop). The two files of a pair have different identifiers and session IDs and the same generic descriptions. They share the subject and session start time, as do files that hold different units of one session, so the start time does not mark them as copies, and the dandiset's description does not mention them. Each unit is counted once here; the teleport file is left out.

In [4]:
vu = pd.DataFrame([dict(subject=u["subject"], start=u["start"][:19], ml=u["ml"],
                        n_trials=len(u["trials"]["trial_type"]), n_spikes=len(u["spikes"]),
                        first_spike=u["spikes"][0], last_spike=u["spikes"][-1],
                        trial_start=np.nanmin(u["trials"]["start_time"]),
                        trial_stop=np.nanmax(u["trials"]["stop_time"]), n_licks=len(u["licks"]))
                   for u in vr])
print("Open-loop units by subject:")
print(vu.subject.value_counts().sort_index().to_string())
sessions = vu.groupby(["subject", "start"]).n_trials.first()
print(f"\nSessions (subject and start time): {len(sessions)}; units per session:",
      dict(collections.Counter(vu.groupby(["subject", "start"]).size())))
print(f"Trials per session: mean {sessions.mean():.1f}, s.d. {sessions.std():.1f}, "
      f"range {sessions.min()} to {sessions.max()}")
print(f"ML position (um, implant_ML): {vu.ml.min():.1f} to {vu.ml.max():.1f}; above 900: {(vu.ml > 900).sum()}")
print(f"Spike times (s): {vu.first_spike.min():.2f} to {vu.last_spike.max():.1f}; trials span "
      f"{vu.trial_start.min():.1f} to {vu.trial_stop.max():.1f} s")
d = np.concatenate([u["trials"]["rew"] - u["trials"]["scene_move"] for u in vr])
print(f"Reward minus scene motion onset (s): median {np.nanmedian(d):.3f}, 1st to 99th percentile "
      f"{np.nanpercentile(d, 1):.3f} to {np.nanpercentile(d, 99):.3f}, min {np.nanmin(d):.3f}, "
      f"max {np.nanmax(d):.3f}, trials without reward {np.isnan(d).sum()} of {len(d)}")
print("Units without licks recorded:", (vu.n_licks == 0).sum())
Open-loop units by subject:
subject
3014     2
3015    12
3017     1
3021     2
3044    37
3045    13
3047     1
3048     6
3053     3
3054    24

Sessions (subject and start time): 66; units per session: {1: 44, 2: 11, 3: 9, 4: 2}
Trials per session: mean 58.8, s.d. 19.5, range 25 to 125
ML position (um, implant_ML): 319.6 to 846.4; above 900: 0
Spike times (s): 0.00 to 2680.0; trials span 5.8 to 2670.0 s
Reward minus scene motion onset (s): median 7.308, 1st to 99th percentile 7.263 to 7.808, min 7.092, max 7.951, trials without reward 11 of 5739
Units without licks recorded: 0

The files carry no flag for optogenetic identification; every unit is taken as an identified dopamine neuron, as the dandiset's single units are described in Kim et al. (2020). The reward comes a median 7.31 s after scene motion onset in the files, where the paper gives 7.35 s.

Clock check. Dopamine neurons respond to reward and mice lick around it. Both should show at the trial table's reward times and not at times shifted into the inter-trial interval.

In [5]:
def contrast(spike_list, align_list, shift):
    out = []
    for s, a in zip(spike_list, align_list):
        a = a[np.isfinite(a)] + shift
        post = ms.counts_aligned(s, a, 0, 0.5, 0.5)[0][:, 0].mean() / 0.5
        pre = ms.counts_aligned(s, a, -0.5, 0, 0.5)[0][:, 0].mean() / 0.5
        out.append(post - pre)
    return np.array(out)

for shift in (0.0, 5.0, -5.0):
    sp = contrast([u["spikes"] for u in vr], [u["trials"]["rew"] for u in vr], shift)
    lk = contrast([u["licks"] for u in vr], [u["trials"]["rew"] for u in vr], shift)
    print(f"reward times shifted by {shift:+.0f} s: spikes 0.5 s after minus before, median "
          f"{np.median(sp):+.2f} spikes/s ({(sp > 0).mean():.0%} of units > 0); licks {np.median(lk):+.2f}/s")
reward times shifted by +0 s: spikes 0.5 s after minus before, median +2.47 spikes/s (89% of units > 0); licks +1.00/s
reward times shifted by +5 s: spikes 0.5 s after minus before, median +0.00 spikes/s (50% of units > 0); licks -0.04/s
reward times shifted by -5 s: spikes 0.5 s after minus before, median -0.10 spikes/s (40% of units > 0); licks +0.00/s

VR task (DANDI:000251)¶

Neurons as M6: the open-loop units with a mean rate above 2 spikes/s over 3.05 to 7.35 s after scene motion onset (all trials) and ML below 900 um. Each unit's trials are split at random in halves 100 times; each half gives a PSTH of 43 bins of 0.1 s. The common value model (M7) is fitted to each half (200 fits). This is run under the claims' seeds and four more; the sections below use the first and give the range over the five.

In [6]:
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)
print(f"open-loop units {len(vr)}; mean rate <= 2 spikes/s: {(vr_mean <= ms.RATE_MIN).sum()}; "
      f"ML >= 900: {(vr_ml >= ms.ML_MAX).sum()}; selected (M6): {vr_sel.sum()}")
print("selected by mouse:", dict(sorted(collections.Counter(vr_mouse[vr_sel]).items())))
print("trials per selected unit:", min(len(r) for r, s in zip(vr_rates, vr_sel) if s), "to",
      max(len(r) for r, s in zip(vr_rates, vr_sel) if s))
rates_sel = [r for r, s in zip(vr_rates, vr_sel) if s]
n_vr = len(rates_sel)
# The window ends 7.35 s after scene motion onset (claim, M6); the reward comes a median 7.31 s after it.
late = np.concatenate([u["trials"]["rew"] - u["trials"]["scene_move"] for u, s in zip(vr, vr_sel) if s])
late = 7.35 - late[np.isfinite(late)]
print(f"time of the window after reward (s), selected units' trials: median {np.median(late):.3f}, "
      f"95th percentile {np.percentile(late, 95):.3f}; trials with reward after the window end {np.mean(late < 0):.1%}")
lb = np.array([r.mean(0) for r in rates_sel])
print(f"mean rate over selected neurons, bins 40 to 43 (spikes/s): {np.round(lb[:, 39:].mean(0), 2).tolist()}")


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 = {off: vr_run(off) for off in OFFSETS}
print(f"VR bootstraps and fits under 5 seeds: {time.time() - t:.0f} s")
for off in OFFSETS:
    f = VR[off]["fits"]
    print(f"seed +{off}: fits that met the tolerance {f['ok'].sum()} of {len(f['ok'])}; iterations "
          f"median {np.median(f['nit']):.0f}; sum of squared errors median {np.median(f['sse']):.0f}")
open-loop units 101; mean rate <= 2 spikes/s: 10; ML >= 900: 0; selected (M6): 91
selected 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}
trials per selected unit: 25 to 125
time of the window after reward (s), selected units' trials: median 0.042, 95th percentile 0.078; trials with reward after the window end 19.7%
mean rate over selected neurons, bins 40 to 43 (spikes/s): [4.6, 4.5, 4.14, 4.43]
VR bootstraps and fits under 5 seeds: 1147 s
seed +0: fits that met the tolerance 9 of 200; iterations median 10000; sum of squared errors median 5715
seed +1000: fits that met the tolerance 10 of 200; iterations median 10000; sum of squared errors median 5717
seed +2000: fits that met the tolerance 15 of 200; iterations median 10000; sum of squared errors median 5723
seed +3000: fits that met the tolerance 16 of 200; iterations median 10000; sum of squared errors median 5722
seed +4000: fits that met the tolerance 10 of 200; iterations median 10000; sum of squared errors median 5713

fig3b-vr-ramp-population¶

In the VR task, 90 dopamine neurons ramp up on average before reward (mean slope 0.097, P = 0.0175), but single neurons vary, 53 with significant positive slopes, 32 with significant negative slopes and 5 not significant.

In [7]:
def slope_stats(sl):
    m = sl.mean(0)
    p = stats.ttest_1samp(sl, 0).pvalue
    return dict(n=sl.shape[1], mean=m.mean(), p=stats.ttest_1samp(m, 0).pvalue,
                pos=int(((p < 0.05) & (m > 0)).sum()), neg=int(((p < 0.05) & (m < 0)).sum()),
                ns=int((p >= 0.05).sum()))

S = {off: slope_stats(VR[off]["slopes"]) for off in OFFSETS}


def slopes_sd42(ps):
    """Variant: the z-score s.d. over bins 1 to 42, leaving out the last bin, which reaches past the
    median reward time."""
    flat = np.concatenate([ps[:, 0], ps[:, 1]], 0)
    z = (flat - flat[:, :, :ms.EARLY_NORM].mean(2, keepdims=True)) / flat[:, :, :42].std(2, ddof=1, keepdims=True)
    return (z[:, :, 33:39].mean(2) - z[:, :, 5:11].mean(2)) / 2.8
print(pd.DataFrame(S).T.to_string(float_format=lambda x: f"{x:.4g}"))
s0 = S[0]
print(f"\nclaim seed: {s0['n']} neurons; mean slope {s0['mean']:.4f} (expected 0.097 +- 0.0097), "
      f"t-test p = {s0['p']:.4f}; positive {s0['pos']} (53 +- 5.3), negative {s0['neg']} (32 +- 3.2), "
      f"n.s. {s0['ns']} (5 +- 0.5)")
v42 = slope_stats(slopes_sd42(VR[0]["ps"]))
print(f"variant, s.d. over bins 1 to 42, claim seed: mean slope {v42['mean']:.4f}, p = {v42['p']:.4f}; "
      f"positive {v42['pos']}, negative {v42['neg']}, n.s. {v42['ns']}")
m0 = VR[0]["slopes"].mean(0)
print(f"per-neuron mean slope range {m0.min():.3f} to {m0.max():.3f}")
for mouse in (3044, 3054):
    k = vr_mouse[vr_sel] == mouse
    print(f"mouse {mouse}: {k.sum()} neurons, mean slope {m0[k].mean():.3f}")
k = ~np.isin(vr_mouse[vr_sel], [3044, 3054])
print(f"other mice: {k.sum()} neurons, mean slope {m0[k].mean():.3f}")
fig, ax = plt.subplots(figsize=(4, 3))
ax.hist(m0, 20)
ax.set_xlabel("ramp slope (normalised rate per s)")
ax.set_ylabel("neurons")
plt.show()
      n    mean       p  pos  neg  ns
0    91 0.08359 0.01786   51   34   6
1000 91 0.08347 0.01794   51   34   6
2000 91 0.08328 0.01817   51   34   6
3000 91  0.0833 0.01813   51   34   6
4000 91 0.08373 0.01773   51   34   6

claim seed: 91 neurons; mean slope 0.0836 (expected 0.097 +- 0.0097), t-test p = 0.0179; positive 51 (53 +- 5.3), negative 34 (32 +- 3.2), n.s. 6 (5 +- 0.5)
variant, s.d. over bins 1 to 42, claim seed: mean slope 0.0849, p = 0.0172; positive 51, negative 34, n.s. 6
per-neuron mean slope range -0.676 to 0.766
mouse 3044: 31 neurons, mean slope 0.005
mouse 3054: 23 neurons, mean slope 0.225
other mice: 37 neurons, mean slope 0.061
No description has been provided for this image

Result: fig3b-vr-ramp-population. 91 neurons pass M6 (expected 90 +- 9). Under the claim's seed the mean slope is 0.084 (p = 0.018), below 0.097 +- 0.0097; 51 neurons have significant positive slopes (53 +- 5.3), 34 negative (32 +- 3.2) and 6 none (5 +- 0.5). The population slope is positive with p < 0.05 and the neuron count is within tolerance, but a class count is not (and the mean slope is outside tolerance): partially reproduced, under the criterion's own rule. The table gives the other four seeds. The last bin reaches a median 0.042 s past the reward (95th percentile 0.078 s); with the z-score s.d. taken over bins 1 to 42 only, the mean slope is 0.0849 (p = 0.017) and the counts are the same (51, 34, 6).

fig3-common-value-fit¶

A model with one convex value function shared across neurons and a discount factor, gain and baseline per neuron captures the diversity of ramping, with discount factors distributed as 0.42 +- 0.23 (mean +- s.d.).

In [8]:
def cv_summary(fits):
    g = fits["gamma"].mean(0)
    V = fits["V"].mean(0)
    d2 = np.diff(V, 2)
    chord = np.linspace(V[0], V[-1], len(V))
    return dict(mean=g.mean(), sd=g.std(ddof=1), p20=np.percentile(g, 20), p70=np.percentile(g, 70),
                p90=np.percentile(g, 90), frac_d2_pos=(d2 > 0).mean(),
                frac_below_chord=(V[1:-1] <= chord[1:-1]).mean())

CV = {off: cv_summary(VR[off]["fits"]) for off in OFFSETS}
print(pd.DataFrame(CV).T.to_string(float_format=lambda x: f"{x:.3f}"))
c0 = CV[0]
gam_vr = VR[0]["fits"]["gamma"].mean(0)
print(f"\nclaim seed: gamma mean {c0['mean']:.3f} (0.42 +- 0.042), s.d. {c0['sd']:.3f} (0.23 +- 0.023); "
      f"range {gam_vr.min():.3f} to {gam_vr.max():.3f}")
print(f"percentiles 20/70/90: {c0['p20']:.3f}, {c0['p70']:.3f}, {c0['p90']:.3f} (paper 0.25, 0.56, 0.88)")
print(f"value function: second difference positive at {c0['frac_d2_pos']:.0%} of bins (reading a); "
      f"at or below the chord at {c0['frac_below_chord']:.0%} of interior bins (reading b)")
V0 = VR[0]["fits"]["V"].mean(0)
print("mean value function, every 6th bin:", np.round(V0[::6], 3))
gs = VR[0]["fits"]["gamma"]
print(f"per-fit mean gamma over neurons: {gs.mean(1).min():.3f} to {gs.mean(1).max():.3f}; "
      f"split-half Spearman of gammas (mean over bootstraps): "
      f"{np.mean([stats.spearmanr(gs[k], gs[k + 100])[0] for k in range(100)]):.3f}")
pred = VR[0]["fits"]
fig, axs = plt.subplots(1, 2, figsize=(8, 3))
axs[0].plot(np.arange(43) * 0.1 + ms.VR_START, V0)
axs[0].set_xlabel("time after scene motion (s)")
axs[0].set_ylabel("value (mean over fits)")
axs[1].hist(gam_vr, 20)
axs[1].set_xlabel("discount factor (per s)")
plt.show()
      mean    sd   p20   p70   p90  frac_d2_pos  frac_below_chord
0    0.446 0.237 0.220 0.555 0.731        0.683             1.000
1000 0.447 0.243 0.227 0.563 0.784        0.683             1.000
2000 0.440 0.235 0.229 0.558 0.735        0.683             1.000
3000 0.437 0.231 0.231 0.558 0.725        0.683             1.000
4000 0.446 0.234 0.223 0.562 0.752        0.659             1.000

claim seed: gamma mean 0.446 (0.42 +- 0.042), s.d. 0.237 (0.23 +- 0.023); range 0.050 to 0.962
percentiles 20/70/90: 0.220, 0.555, 0.731 (paper 0.25, 0.56, 0.88)
value function: second difference positive at 68% of bins (reading a); at or below the chord at 100% of interior bins (reading b)
mean value function, every 6th bin: [0.02  0.028 0.047 0.093 0.162 0.312 0.587 0.975]
per-fit mean gamma over neurons: 0.381 to 0.568; split-half Spearman of gammas (mean over bootstraps): 0.663
No description has been provided for this image

The fit is capped at 10,000 iterations (an assumption: the code caps fmincon at 2000 iterations of another algorithm, and few fits reach the tolerance). Variants: the first 10 bootstraps (20 fits) at 3000 and 30,000 iterations, against the same 20 fits at 10,000; then all 200 fits of the claims' seed at 30,000 iterations.

In [9]:
x0 = ms.cv_initial(n_vr, np.random.default_rng(seed("fig3-common-value-fit")))
ps10 = VR[0]["ps"][:10]
sl10 = VR[0]["slopes"][np.r_[0:10, 100:110]].mean(0)
from concurrent.futures import ProcessPoolExecutor
def _job(a):
    return ms.cv_fit(a[0], x0, maxiter=a[1])
for it in (3000, 10000, 30000):
    t = time.time()
    with ProcessPoolExecutor(4) as ex:
        F = list(ex.map(_job, [(ps10[k % 10, k // 10], it) for k in range(20)]))
    g = np.array([f["gamma"] for f in F]).mean(0)
    print(f"{it} iterations ({time.time() - t:.0f} s): median SSE {np.median([f['sse'] for f in F]):.0f}, "
          f"gamma mean {g.mean():.3f}, s.d. {g.std(ddof=1):.3f}, Spearman with slope {stats.spearmanr(g, sl10)[0]:.3f}")
3000 iterations (7 s): median SSE 5783, gamma mean 0.479, s.d. 0.232, Spearman with slope 0.618
10000 iterations (23 s): median SSE 5734, gamma mean 0.443, s.d. 0.235, Spearman with slope 0.718
30000 iterations (63 s): median SSE 5734, gamma mean 0.442, s.d. 0.236, Spearman with slope 0.732
In [10]:
# Variant: all 200 fits of the claims' seed at 30,000 iterations, against the same fits at 10,000.
t = time.time()
F30 = ms.cv_fit_bootstraps(VR[0]["ps"], x0, maxiter=30000)
g30 = F30["gamma"].mean(0)
r30 = stats.spearmanr(g30, VR[0]["slopes"].mean(0))
print(f"30,000 iterations, 200 fits ({time.time() - t:.0f} s): met the tolerance {F30['ok'].sum()} of 200; "
      f"median SSE {np.median(F30['sse']):.0f} (10,000: {np.median(VR[0]['fits']['sse']):.0f})")
print(f"gamma mean {g30.mean():.3f}, s.d. {g30.std(ddof=1):.3f} (10,000: {gam_vr.mean():.3f}, {gam_vr.std(ddof=1):.3f}); "
      f"Spearman of the two fits' gammas {stats.spearmanr(g30, gam_vr)[0]:.3f}")
print(f"Spearman with slope r = {r30[0]:.3f}, p = {r30[1]:.2g} (10,000: "
      f"{stats.spearmanr(gam_vr, VR[0]['slopes'].mean(0))[0]:.3f}; expected 0.81 +- 0.081)")
30,000 iterations, 200 fits (603 s): met the tolerance 96 of 200; median SSE 5710 (10,000: 5715)
gamma mean 0.442, s.d. 0.238 (10,000: 0.446, 0.237); Spearman of the two fits' gammas 0.989
Spearman with slope r = 0.726, p = 3.8e-16 (10,000: 0.709; expected 0.81 +- 0.081)

Result: fig3-common-value-fit. Under the claims' seeds the per-neuron discount factors have mean 0.446 and s.d. 0.237, within 0.42 +- 0.042 and 0.23 +- 0.023, and the mean value function is convex under both readings (second difference positive at 68% of bins; at or below the chord at every interior bin): reproduced. The 90th percentile (0.731) is lower than the 0.88 the Methods give. The result rests on the iteration cap (an assumption): on 20 fits, 3000 iterations give a higher mean than 10,000, and 30,000 about the same as 10,000; all 200 fits of the claims' seed at 30,000 iterations give mean 0.442 and s.d. 0.238, also within tolerance (variants above). The table gives the other four seeds.

ed8b-slope-correlates-with-discount¶

The inferred VR discount factor and the ramp slope are strongly correlated (r = 0.81).

In [11]:
R8 = {off: stats.spearmanr(VR[off]["fits"]["gamma"].mean(0), VR[off]["slopes"].mean(0)) for off in OFFSETS}
for off in OFFSETS:
    print(f"seed +{off}: Spearman r = {R8[off][0]:.3f}, p = {R8[off][1]:.2g}")
print(f"claim seed: r = {R8[0][0]:.3f} (expected 0.81 +- 0.081), n = {n_vr}")
seed +0: Spearman r = 0.709, p = 3.6e-15
seed +1000: Spearman r = 0.716, p = 1.6e-15
seed +2000: Spearman r = 0.753, p = 7.3e-18
seed +3000: Spearman r = 0.744, p = 3e-17
seed +4000: Spearman r = 0.708, p = 4.2e-15
claim seed: r = 0.709 (expected 0.81 +- 0.081), n = 91

Result: ed8b-slope-correlates-with-discount. Spearman r = 0.709 (p = 3.6e-15, 91 neurons) under the claims' seeds, below 0.81 +- 0.081. Slope and discount factor are strongly and positively correlated, but r is outside tolerance: partially reproduced. The iteration variants above show r rising with the number of iterations: on all 200 fits of the claims' seed, 30,000 iterations give r = 0.726, still below 0.729.

ed7c-discount-not-related-to-ml-position and ed7de-gain-baseline-not-related-to-ml-position¶

The VR discount factor is not correlated with the medio-lateral position of the implant (r = 0.015, P = 0.89). The VR baseline and gain are not significantly correlated with the medio-lateral position of the implant (baseline r = -0.011, P = 0.92; gain r = -0.19, P = 0.069).

Per-neuron means over the 200 fits; the gain is the code's stored gain, a / gamma^0.1. Pearson correlation, two-tailed.

In [12]:
ml_sel = vr_ml[vr_sel]
print(f"ML of the selected neurons: {ml_sel.min():.0f} to {ml_sel.max():.0f} um, {len(np.unique(ml_sel))} distinct values")
rows = []
for off in OFFSETS:
    f = VR[off]["fits"]
    for name, key in (("gamma", "gamma"), ("baseline", "base"), ("gain", "gain")):
        r, p = stats.pearsonr(ml_sel, f[key].mean(0))
        rows.append(dict(seed=off, parameter=name, r=r, p=p))
ML = pd.DataFrame(rows)
print(ML.pivot(index="seed", columns="parameter", values=["r", "p"]).to_string(float_format=lambda x: f"{x:.3f}"))
ML of the selected neurons: 320 to 846 um, 10 distinct values
                 r                      p            
parameter baseline   gain  gamma baseline  gain gamma
seed                                                 
0            0.026 -0.175 -0.031    0.806 0.097 0.772
1000         0.029 -0.177 -0.035    0.786 0.093 0.742
2000         0.031 -0.171 -0.033    0.774 0.104 0.756
3000         0.030 -0.174 -0.027    0.776 0.100 0.800
4000         0.028 -0.175 -0.038    0.792 0.097 0.719

Result: ed7c-discount-not-related-to-ml-position. Pearson r = -0.031, p = 0.77 under the claims' seeds (paper r = 0.015, P = 0.89): no effect at p < 0.05, reproduced. The table gives the other seeds.

Result: ed7de-gain-baseline-not-related-to-ml-position. baseline r = 0.026 (p = 0.81), gain r = -0.175 (p = 0.097) under the claims' seeds; neither has p < 0.05, reproduced. The gain trend is negative, as in the paper (r = -0.19, P = 0.069).

ed8cd-vr-licking-not-related-to-discount¶

In the VR task, the ramp in anticipatory licking is not correlated with the neural discount factor in either of the two mice with most neurons, whichever pair of the three lick windows measures the ramp.

Per neuron, the lick rate of its session in the Methods windows before each trial's reward (early -3.45 to -2.95 s, middle -1.95 to -1.45 s, late -0.75 to -0.25 s), averaged over trials with a reward; modulation indices (A - B) / (A + B). The code (VR_Behavior_Revision.m) takes 100 ms bins aligned on scene motion onset (bins 40 to 45, 55 to 60, 67 to 72, that is 3.9 to 4.5, 5.4 to 6.0 and 6.6 to 7.2 s after it); that is shown as a variant.

In [13]:
def lick_windows(u, wins, align):
    a = align(u)
    a = a[np.isfinite(a)]
    return [ms.counts_aligned(u["licks"], a, w0, w1, w1 - w0)[0][:, 0].mean() / (w1 - w0) for w0, w1 in wins]

WIN_METHODS = [(-3.45, -2.95), (-1.95, -1.45), (-0.75, -0.25)]
WIN_CODE = [(3.9, 4.5), (5.4, 6.0), (6.6, 7.2)]
sel_units = [u for u, s in zip(vr, vr_sel) if s]
mice_sel = vr_mouse[vr_sel]
rows = []
for wname, wins, align in (("Methods, reward-aligned", WIN_METHODS, lambda u: u["trials"]["rew"]),
                           ("code, scene-aligned", WIN_CODE, lambda u: u["trials"]["scene_move"])):
    L = np.array([lick_windows(u, wins, align) for u in sel_units])
    early, middle, late = L.T
    mi = {"late-early": (late - early) / (late + early), "late-middle": (late - middle) / (late + middle),
          "middle-early": (middle - early) / (middle + early)}
    for off in OFFSETS:
        g = VR[off]["fits"]["gamma"].mean(0)
        for mouse in (3044, 3054):
            k = mice_sel == mouse
            for name, x in mi.items():
                ok = k & np.isfinite(x)
                r, p = stats.spearmanr(g[ok], x[ok])
                rows.append(dict(windows=wname, seed=off, mouse=mouse, index=name, n=ok.sum(), r=r, p=p))
LK = pd.DataFrame(rows)
print(LK[LK.seed == 0].to_string(index=False, float_format=lambda x: f"{x:.3f}"))
print("\nsmallest p over the five seeds, Methods windows:",
      LK[LK.windows.str.startswith("Methods")].groupby(["mouse", "index"]).p.min().round(3).to_dict())
                windows  seed  mouse        index  n      r     p
Methods, reward-aligned     0   3044   late-early 31  0.119 0.522
Methods, reward-aligned     0   3044  late-middle 31 -0.045 0.811
Methods, reward-aligned     0   3044 middle-early 31  0.173 0.352
Methods, reward-aligned     0   3054   late-early 23 -0.064 0.773
Methods, reward-aligned     0   3054  late-middle 23 -0.010 0.964
Methods, reward-aligned     0   3054 middle-early 23 -0.053 0.811
    code, scene-aligned     0   3044   late-early 31  0.126 0.498
    code, scene-aligned     0   3044  late-middle 31 -0.098 0.600
    code, scene-aligned     0   3044 middle-early 31  0.206 0.266
    code, scene-aligned     0   3054   late-early 23 -0.091 0.678
    code, scene-aligned     0   3054  late-middle 23 -0.010 0.964
    code, scene-aligned     0   3054 middle-early 23 -0.098 0.655

smallest p over the five seeds, Methods windows: {(3044, 'late-early'): 0.522, (3044, 'late-middle'): 0.811, (3044, 'middle-early'): 0.315, (3054, 'late-early'): 0.682, (3054, 'late-middle'): 0.843, (3054, 'middle-early'): 0.707}

Result: ed8cd-vr-licking-not-related-to-discount. With the Methods windows none of the six correlations has p < 0.05 under the claims' seeds (smallest p 0.35, m3044 middle against early); the code's windows give the same (smallest p 0.27). Reproduced. The line above gives the smallest p over the five seeds.

Summary¶

Claim Outcome (claims' seeds)
fig3b-vr-ramp-population partially reproduced
fig3-common-value-fit reproduced, resting on the iteration cap
ed8b-slope-correlates-with-discount partially reproduced
ed7c-discount-not-related-to-ml-position reproduced
ed7de-gain-baseline-not-related-to-ml-position reproduced
ed8cd-vr-licking-not-related-to-discount 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 common value model is fitted with L-BFGS-B over the discount factors and the value function, with the gains and baselines solved exactly at each step, capped at 10,000 iterations, where the code uses fmincon (interior point, 2000 iterations); few fits reach the tolerance, and the variant shows that the cap moves the result. Half splits are disjoint (the code's halves share one trial when the trial count is odd). PSTHs are spike counts in 0.1 s bins from 3.05 to 7.35 s after scene motion onset; the code averages 10 ms rates in 43 slightly overlapping bins ending at the mean reward time. The VR licking windows are taken before each trial's reward (Methods); the code's windows, aligned on scene motion, are a variant.

The dataset. 78 open-loop units are deposited twice (SU-VR-OL and SU-VR-ALL-OL files with identical spike trains) under different identifiers and session IDs; only the subject and start time, which distinct units of one session also share, are the same, and one SU-VR-OL file of mouse 3015 holds a teleport session (the same unit as an SU-VR-ALL-TP file). The files carry no optogenetic identification flag and no description of the units. The reward comes a median 7.31 s after scene motion onset (7.35 s in the paper). The dandiset has no published version.