Reproducing Su et al. (2026) from dandiset 001950¶
Paper. Su Z, Kosillo P, Jung K, et al. Topographic structure and function of locus coeruleus noradrenaline neurons. Nature (2026), doi:10.1038/s41586-026-11026-0. The claims file was written from the bioRxiv preprint, version 1 (doi:10.64898/2026.04.10.717727), whose Methods and legends are cited below by section and figure (the Nature version numbers some supplementary figures as Extended Data).
Dataset. DANDI:001950, version
0.260928.2230. The paper names the dandiset without a version. This is the only published
version (2026-09-28), so it is pinned. The draft (modified 2026-10-06) holds the same 385 paths
with new files: their units tables add ten columns, among them the paper's LC-NE label
(opto_NE_paper), the antidromic classification (antidromic_tier_1) and the stable recording
windows, which the pinned version lacks; the data the analysis reads are otherwise the same in
the files compared. The data check prints this difference; the draft's LC-NE label is used only as a population
variant in the sensitivity section.
What the dandiset holds. One NWB file per session: 163 behavior and electrophysiology sessions (tetrodes and Neuropixels, all sorted units with opto-tagging metrics, CCF coordinates for some Neuropixels sessions, pupil diameter or tongue tracking for some), 136 behavior and fiber photometry sessions (LC-NE axons in PL and other regions), 84 behavior-only sessions, and two electrophysiology files without a trial table. It does not hold the anatomy, transcriptomics or slice data, the antidromic identification of cortex-projecting neurons, the per-trial spike amplitudes used as a drift regressor, the per-unit drift cuts, or the Q-learning model's variables.
Outside inputs. Selection criteria, analysis windows and the anatomical axes come from the paper's code, github.com/AllenNeuralDynamics/aind-beh-ephys-analysis at commit 971c1ca (metrics/beh_all.json, beh_only.json, basic_ephys_all.json, waveform_all.json, auc_windows.json, and the axes printed by F_spatial-axis-comparison.ipynb), and the Q-learning model from github.com/AllenNeuralDynamics/aind_stan_fit_sim at commit 89371ee (stan_qLearning_5params.stan), refitted here per session by maximum likelihood.
Revision after verification round 1. The Q-learning section adds a parameter-recovery check and a partially pooled refit within each mouse; a sensitivity section reruns the single-neuron results on the populations the code's model-based criteria and the draft's labels would give; the switch and outcome regressions add the trial-index drift stand-in; figs15q follows the code's lick procedure; figs14 adds band-pass filtered waveforms; figs16 adds the code's fit, detrending and a breakdown by mouse; figs15t runs every variant of the t-statistics and a within-session null.
| Claim | Tested here |
|---|---|
| lc-definition-counts, fig1-dense-axon-distribution, axon-length-and-branching, fig2c-primary-targets, fig2ef-dorsal-ventral-projections, fig3a-gene-expression-continuum, fig3c-pseudospace-dorsal-ventral, fig3d-retroseq-targets, fig3e-axes-separated, figs14k-patchseq-by-target | Blocked: anatomy, transcriptomics and slice data, not in the dandiset and not deposited at a pinned identifier |
| fig6f-cortex-projecting-rpe-biased | Blocked: the dandiset does not mark cortex-projecting neurons or hold the antidromic stimulation times |
| figs12-trials-per-session, iti-mean, fig4c-choice-history, fig5a-engagement-reward-history, fig5e-switch-history | Tested (behavior) |
| fig4g-go-cue-excitation, fig4h-tonic-phasic-anticorrelation, fig5b-baseline-predicts-ignore, figs15f-tonic-modulation-vs-engagement | Tested (single neurons) |
| fig5c-ignore-ventral, fig5d-ignore-on-anatomy-axes, fig5g-switch-dorsal, fig5h-switch-on-anatomy-axes, figs14-waveform-space | Tested (space) |
| fig5k-cortical-input-switch, figs17i-baseline-axons-vs-spiking | Tested in part (photometry against neurons; cortex-projecting neurons not marked) |
| fig6c-choice-change-rpe, fig6-outcome-responsive-fraction, fig6a-outcome-space, figs18d-outcome-not-on-anatomy-axes, fig6f-outcome-angles-nonuniform, fig6g-rpe-vs-no-reward-populations, fig6h-opposing-behavior, fig6i-axons-rpe, fig6j-cortical-input-more-positive, figs15t-crosscorrelogram-outcome-axis | Tested with a refitted Q-learning model |
| figs15q-spontaneous-vs-task-licks, figs16-pupil-spiking | Tested |
The notebook streams from each of the 383 files only the parts it uses; in three runs loading took 6 to 12 minutes and the whole notebook 25 to 36, depending on the network.
import time
import warnings
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import statsmodels.api as sm
from scipy import stats
from scipy.optimize import curve_fit
import lcne
warnings.filterwarnings("ignore")
pd.set_option("display.width", 220)
pd.set_option("display.max_columns", 40)
pd.set_option("display.max_rows", 200)
started = time.time()
assets_all = lcne.list_assets()
assets = assets_all[assets_all.kind != "ecephys"]
sessions = lcne.load_all(assets)
print(f"dandiset {lcne.DANDISET_ID} version {lcne.DANDISET_VERSION}: {len(assets_all)} files; "
f"loaded {len(sessions)} with a trial table in {time.time() - started:.0f} s")
dandiset 001950 version 0.260928.2230: 385 files; loaded 383 with a trial table in 420 s
Data check¶
Each check of the metadata against the values is stated under its output.
print("Files by kind:", assets_all.kind.value_counts().to_dict())
print("Subjects by kind:", assets_all.groupby("kind").subject.nunique().to_dict(),
"; distinct subjects:", assets_all.subject.nunique())
eo = assets_all[assets_all.kind == "ecephys"]
print("Files without a trial table (kind 'ecephys'):", eo.path.tolist())
draft = lcne.list_assets("draft")
cmp_ = assets_all.merge(draft, on="path", how="outer", suffixes=("_pinned", "_draft"), indicator=True)
diff_size = cmp_.size_draft - cmp_.size_pinned
print(f"Draft against {lcne.DANDISET_VERSION}: same paths {int((cmp_._merge == 'both').sum())} of {len(cmp_)}; files whose size differs {int((diff_size != 0).sum())}, "
f"by {sorted(diff_size.dropna().unique().astype(int).tolist())[:5]} bytes")
srows = []
for s in sessions:
tr = s["trials"]
g = lcne.go_trials(tr)
srows.append({"path": s["path"], "subject": s["subject"], "kind": s["kind"],
"rows": len(tr), "go": int(tr.go.sum()), "nogo": int((~tr.go).sum()),
"responded": int(g.responded.sum()), "ignored": int((~g.responded).sum()),
"auto_water": int(tr.auto_water.sum()),
"has_units": s["units"] is not None, "n_units": 0 if s["units"] is None else len(s["units"]),
"probe": None if s["units"] is None else s["units"].probe.iloc[0],
"pupil": s["pupil"] is not None, "fp_PL": s["fp"] is not None,
"reward_delay": np.nanmedian(tr.reward_delay), "response_window": np.nanmedian(tr.response_duration),
"p_sw_L": lcne.p_switch_after_loss(g)})
S = pd.DataFrame(srows)
print("\nSessions with a trial table by kind:", S.kind.value_counts().to_dict())
print(S.groupby("kind")[["rows", "go", "nogo", "responded", "ignored", "auto_water", "n_units"]].sum().to_string())
print("\nUnits by recording type:", S[S.has_units].groupby("probe").agg(sessions=("path", "size"), subjects=("subject", "nunique"), units=("n_units", "sum")).to_string())
print("\nSessions with pupil diameter:", int(S.pupil.sum()), "(of which with units:", int((S.pupil & S.has_units).sum()), ")",
"; sessions with PL photometry:", int(S.fp_PL.sum()), "from", S[S.fp_PL].subject.nunique(), "mice")
print("Reward delay (s) by kind:", S.groupby("kind").reward_delay.describe()[["min", "50%", "max"]].round(3).to_dict("index"))
print("Response window (s):", S.response_window.value_counts().round(2).to_dict())
Files by kind: {'behavior+ecephys': 163, 'behavior+fib': 136, 'behavior': 84, 'ecephys': 2}
Subjects by kind: {'behavior': 15, 'behavior+ecephys': 22, 'behavior+fib': 12, 'ecephys': 1} ; distinct subjects: 42
Files without a trial table (kind 'ecephys'): ['sub-763360/sub-763360_ses-763360-2025-04-15-12-16-29_ecephys.nwb', 'sub-763360/sub-763360_ses-763360-2025-04-16-13-29-55_ecephys.nwb']
Draft against 0.260928.2230: same paths 385 of 385; files whose size differs 323, by [-5240, -5216, -5200, -5176, -5136] bytes
Sessions with a trial table by kind: {'behavior+ecephys': 163, 'behavior+fib': 136, 'behavior': 84}
rows go nogo responded ignored auto_water n_units
kind
behavior 34356 33342 1014 30078 3264 23 0
behavior+ecephys 63178 61535 1643 58520 3015 0 14357
behavior+fib 74002 71107 2895 66222 4885 0 0
Units by recording type: sessions subjects units
probe
NP 57 18 14126
TT 106 4 231
Sessions with pupil diameter: 133 (of which with units: 97 ) ; sessions with PL photometry: 136 from 12 mice
Reward delay (s) by kind: {'behavior': {'min': 0.15, '50%': 0.301, 'max': 0.301}, 'behavior+ecephys': {'min': 0.2, '50%': 0.301, 'max': 0.301}, 'behavior+fib': {'min': 0.201, '50%': 0.201, 'max': 0.301}}
Response window (s): {1.8: 303, 1.5: 80}
The archive's summary gives 42 subjects; 42 subject folders are present, 41 of them with a
trial table (the two files of subject 763360 have none and are not used). The files' trial
tables hold no-go cues (trial_type CSminus) only in tetrode and photometry sessions, as the
Methods describe (no-go cues at P = 0.05 in tetrode and GCaMP experiments); they are about 3% of
rows. The reward delays (0.15 to 0.3 s) and response windows (1.5 or 1.8 s) printed above match
the Methods' 300 ms (200 ms for photometry) and "1.5 or 1.8 s"; some photometry sessions have 0.3
s, and some behavior-only sessions 0.15 s. Tetrode units are 231 units from 4 mice, Neuropixels
14,126 units from 18 mice: the Neuropixels files hold every sorted unit, not only LC-NE neurons.
# Recordings deposited twice: identical go-cue interval sequences or identical spike trains.
sig = {}
for s in sessions:
gc = s["trials"].goCue_start_time.values
key = tuple(np.round(np.diff(gc[:30]), 3))
sig.setdefault(key, []).append(s["path"])
dup_trials = [v for v in sig.values() if len(v) > 1]
print("Sessions sharing the sequence of their first 30 cue intervals:", dup_trials if dup_trials else "none")
spk_sig = {}
for s in sessions:
if s["spikes"]:
for r, sp in s["spikes"].items():
if len(sp) > 10:
spk_sig.setdefault((len(sp), round(float(np.diff(sp[:10]).sum()), 6)), []).append((s["path"].split("/")[1][:40], int(r)))
dup_spk = [v for v in spk_sig.values() if len(v) > 1]
print("Opto-tagged units with identical spike trains (count and first intervals):", dup_spk if dup_spk else "none")
# Clock: licks against the trial table. The choice time (reward_outcome_time, "time when choice is
# registered") should coincide with a lick; the contrast is the same distance with the trial times
# shifted by -1.5 s and +0.5 s.
rows = []
for s in sessions:
tr = s["trials"]
g = tr[tr.go]
licks = np.sort(np.concatenate([s["licks"]["left"], s["licks"]["right"]]))
if len(licks) == 0:
continue
resp = g[g.responded]
ign = g[~g.responded]
row = {"kind": s["kind"], "probe": "-" if s["units"] is None else s["units"].probe.iloc[0],
"ignored_with_lick_in_window": np.mean([np.any((licks > t) & (licks < t + w)) for t, w in zip(ign.goCue_start_time, ign.response_duration)]) if len(ign) else np.nan}
for sh in [0.0, -1.5, 0.5]:
ct = resp.reward_outcome_time.values + sh
k = np.clip(np.searchsorted(licks, ct), 1, len(licks) - 1)
near = np.minimum(np.abs(licks[k] - ct), np.abs(licks[k - 1] - ct))
row[f"lick_to_choice_s shift {sh:+.1f}"] = np.median(near)
rows.append(row)
L = pd.DataFrame(rows)
print("\nMedian distance (s) from the choice time to the nearest lick, and fraction of ignored go cues with a lick in the response window (medians over sessions):")
print(L.groupby(["kind", "probe"]).median().round(3).to_string())
print("Sessions without lick times:", len(sessions) - len(L))
Sessions sharing the sequence of their first 30 cue intervals: none Opto-tagged units with identical spike trains (count and first intervals): none
Median distance (s) from the choice time to the nearest lick, and fraction of ignored go cues with a lick in the response window (medians over sessions):
ignored_with_lick_in_window lick_to_choice_s shift +0.0 lick_to_choice_s shift -1.5 lick_to_choice_s shift +0.5
kind probe
behavior - 0.0 0.0 1.5 0.038
behavior+ecephys NP 0.0 0.0 1.5 0.046
TT 0.0 0.0 1.5 0.035
behavior+fib - 0.0 0.0 1.5 0.044
Sessions without lick times: 0
No session shares its sequence of cue intervals with another, and no two opto-tagged units share a spike train, so no recording was found deposited twice. Licks share the trial table's clock: in every kind of session the median distance from the choice time to the nearest lick is 0.000 s, against 1.5 s with the trial times shifted by -1.5 s (with a +0.5 s shift it is 0.035 to 0.046 s, as licks continue after a choice, so that shift does not separate them). In the median session no ignored go cue has a lick in its response window.
# Unit selection (metrics/beh_all.json and beh_only.json, see lcne.py).
from sklearn.linear_model import LogisticRegression
urows = []
for s in sessions:
if s["units"] is None:
continue
tr = s["trials"]
g = lcne.go_trials(tr)
t0, t1 = tr.start_time.min(), tr.stop_time.max()
u = s["units"]
ok = lcne.opto_pass(u)
for _, r in u[ok].iterrows():
sp = s["spikes"][r.row]
dur = sp[-1] - sp[0] if len(sp) > 1 else 0
isi_file = float(r.get("isi_violations_ratio", np.nan))
urows.append({"path": s["path"], "subject": s["subject"], "row": int(r.row), "unit_id": r.unit_id, "probe": r.probe,
"isi_file": isi_file, "isi_spikes": lcne.isi_violation_ratio(sp, dur),
"sd": lcne.slow_drift_ratio(sp, t0, t1), "trial_count": int(len(g)),
"p_max": float(r["maximum_increase_of_p(response_cond_laser)"]),
"x": float(r.get("x_coordinate_in_ccf_space", np.nan)), "y": float(r.get("y_coordinate_in_ccf_space", np.nan)),
"z": float(r.get("z_coordinate_in_ccf_space", np.nan)), "peak": float(r.peak),
"lat": float(r["spike_latency_at_maximum_p(response_cond_laser)"])})
U = pd.DataFrame(urows)
U["isi"] = np.where(np.isfinite(U.isi_file), U.isi_file, U.isi_spikes)
def diff_1(g):
X, y = lcne.history_matrix(g, 5)
if len(y) < 30 or len(set(y)) < 2:
return np.nan
m = LogisticRegression(C=1e6, max_iter=5000).fit(X, y)
return m.coef_[0][0] - m.coef_[0][5]
S["diff_1"] = [diff_1(lcne.go_trials(s["trials"])) for s in sessions]
S["beh_ok"] = (S.responded >= 90) & (S.p_sw_L >= 0.04) & (S.diff_1 >= 0)
U = U.merge(S[["path", "beh_ok"]], on="path")
U["isi_ok"] = U.isi <= lcne.ISI_MAX
U["sd_ok"] = U.sd <= lcne.SD_MAX
U["tc_ok"] = U.trial_count.between(*lcne.TRIAL_COUNT_BOUNDS)
U["selected"] = U.isi_ok & U.sd_ok & U.tc_ok & U.beh_ok
print("Units passing the opto-tagging, QC, peak and location criteria:", len(U), "from", U.subject.nunique(), "mice")
for c in ["isi_ok", "sd_ok", "tc_ok", "beh_ok"]:
print(f" of these passing {c}: {int(U[c].sum())}")
cells = U[U.selected].reset_index(drop=True)
print(f"Selected LC-NE units: {len(cells)} from {cells.subject.nunique()} mice and {cells.path.nunique()} sessions "
f"(paper: 241 units, 19 mice; code: 106 sessions); by type {cells.probe.value_counts().to_dict()}")
print("Sessions failing the session criteria (of", S.has_units.sum(), "with units):", int((~S.beh_ok & S.has_units).sum()))
npu = U[U.probe == "NP"]
print(f"ISI violation ratio, file column against recomputed from spikes (Neuropixels, {len(npu)} units): "
f"Pearson r = {np.corrcoef(npu.isi_file, npu.isi_spikes)[0, 1]:.4f}, max abs difference {np.nanmax(np.abs(npu.isi_file - npu.isi_spikes)):.4f}")
cells["has_ccf"] = np.isfinite(cells.x)
print("Selected units with CCF coordinates:", int(cells.has_ccf.sum()), "from", cells[cells.has_ccf].subject.nunique(),
"mice (paper: 103 to 115 cells, 15 mice)")
print("Units per mouse:", cells.subject.value_counts().to_dict())
cc = lcne.ccf_lps(cells[cells.has_ccf].rename(columns={"x": "x_coordinate_in_ccf_space", "y": "y_coordinate_in_ccf_space", "z": "z_coordinate_in_ccf_space"}))
print("CCF relative to bregma (mm), |ML|, AP (posterior +), DV (dorsal +): min", cc.min(0).round(2), "max", cc.max(0).round(2))
Units passing the opto-tagging, QC, peak and location criteria: 429 from 22 mice
of these passing isi_ok: 265
of these passing sd_ok: 400
of these passing tc_ok: 429
of these passing beh_ok: 429
Selected LC-NE units: 252 from 21 mice and 112 sessions (paper: 241 units, 19 mice; code: 106 sessions); by type {'NP': 130, 'TT': 122}
Sessions failing the session criteria (of 163 with units): 1
ISI violation ratio, file column against recomputed from spikes (Neuropixels, 297 units): Pearson r = 0.9993, max abs difference 0.0314
Selected units with CCF coordinates: 127 from 16 mice (paper: 103 to 115 cells, 15 mice)
Units per mouse: {'ZS061': 62, 'ZS062': 53, '754897': 17, '751766': 15, '782394': 15, '791691': 11, '751181': 10, '751769': 9, '758017': 9, '751004': 8, '758018': 6, '761038': 5, '781166': 5, '763590': 4, '784803': 4, 'ZS059': 4, '716325': 3, '752014': 3, '784806': 3, '785956': 3, 'ZS060': 3}
CCF relative to bregma (mm), |ML|, AP (posterior +), DV (dorsal +): min [ 0.52 4.65 -4.67] max [ 1.13 5.26 -3.22]
# The draft adds unit columns that the pinned version lacks; compare them with this selection.
draft_ids = draft.set_index("path").asset_id
def draft_units(path):
f = lcne.open_nwb(draft_ids[path])
u = f["units"]
cols = sorted(set(u.keys()) - set(lcne.open_nwb(assets_all.set_index("path").asset_id[path])["units"].keys())) if path == first_ep else None
out = pd.DataFrame({"row": np.arange(u["id"].shape[0]),
"opto_NE_paper": u["opto_NE_paper"][:] if "opto_NE_paper" in u else np.nan,
"antidromic_tier_1": u["antidromic_tier_1"][:] if "antidromic_tier_1" in u else np.nan})
out["path"] = path
return out, cols
ep_paths = S[S.has_units].path.tolist()
first_ep = ep_paths[0]
res_d = lcne.pmap(draft_units, ep_paths)
print("Unit columns in the draft and not in the pinned version (first file):", res_d[0][1])
DU = pd.concat([r[0] for r in res_d])
DU["opto_NE_paper"] = DU.opto_NE_paper.astype(float)
print(f"Draft: units marked opto_NE_paper {int(np.nansum(DU.opto_NE_paper))}; antidromic_tier_1 true {int(np.nansum(DU.antidromic_tier_1 == 1))}")
mine = U[(U.p_max >= 0.6) & U.isi_ok & U.sd_ok][["path", "row"]].assign(mine=True)
cmpu = DU.merge(mine, on=["path", "row"], how="left").fillna({"mine": False})
print(pd.crosstab(cmpu.opto_NE_paper == 1, cmpu.mine, rownames=["draft opto_NE_paper"], colnames=["this selection (basic_ephys_all criteria)"]).to_string())
sel_d = DU.merge(cells[["path", "row"]], on=["path", "row"])
print(f"Of the {len(cells)} selected units, marked opto_NE_paper in the draft: {int(np.nansum(sel_d.opto_NE_paper))}; antidromic_tier_1: {int(np.nansum(sel_d.antidromic_tier_1 == 1))}")
Unit columns in the draft and not in the pinned version (first file): ['antidromic_jitter', 'antidromic_latency', 'antidromic_tier_1', 'antidromic_tier_2', 'ephys_cut_end', 'ephys_cut_start', 'firing_rate_stability', 'opto_NE_paper', 'p_antidromic', 'p_collision'] Draft: units marked opto_NE_paper 267; antidromic_tier_1 true 45 this selection (basic_ephys_all criteria) False True draft opto_NE_paper False 14064 26 True 44 223 Of the 252 selected units, marked opto_NE_paper in the draft: 223; antidromic_tier_1: 9
The unit selection gives 252 LC-NE units from 21 mice and 112 sessions, against the paper's
241 units and 19 mice and the code's 106 sessions. The difference is expected: two of the code's
session criteria (aN and bias, from the hierarchical model fits), its per-unit drift cuts,
and its looser ISI bound for cortex-projecting units cannot be applied from the dandiset. With
the maximum-likelihood fits below standing in for the model's aN and bias, the selection
would keep fewer sessions (printed in the Q-learning section). The ISI violation ratio recomputed
from the spike times matches the files' Neuropixels column (r = 0.9993), which supports the same
computation for the tetrode units, which have no such column. Some numeric columns are stored as
strings in some files (isi_violations_ratio in 4 files and peak_to_valley in 54); the loader
converts them. The CCF coordinates, in mm, place the units 0.5 to 1.1 mm lateral, 4.7 to 5.3 mm
posterior to bregma and 3.2 to 4.7 mm below it, where LC is: the files' frame is the one the
paper's code assumes.
The draft's new opto_NE_paper column marks 267 units (the code's basic_ephys_all population,
274 units in the claims file). It agrees with this attempt's selection under the same criteria on
223 units; 44 are marked only in the draft and 26 are selected only here, a difference consistent
with the drift cuts and ISI bound that the pinned version does not hold. 223 of the 252 selected
units are marked in the draft, and 9 of them as cortex-projecting (45 units are marked so in
all).
# The pinned files' contents bearing on cortex-projecting neurons: every file with spikes is listed
# for stimulus, interval, acquisition and processing objects, unit columns on antidromic tests,
# and the stimulus epochs and antidromic processing steps named in its AIND metadata.
import json
import re
from collections import Counter
import h5py
STIM_PAT = re.compile(r"stim|laser|opto|antidrom|collision|pulse", re.I)
def scan_stimulation(row):
f = lcne.open_nwb(row.asset_id)
names = []
for top in ["stimulus/presentation", "stimulus/templates", "intervals", "acquisition", "processing"]:
if top in f:
for k in f[top].keys():
names.append(f"{top}/{k}")
if top == "processing" and isinstance(f[f"{top}/{k}"], h5py.Group):
names += [f"{top}/{k}/{kk}" for kk in f[f"{top}/{k}"].keys()]
js = f["general/aind_metadata/json_data"][()] if "general/aind_metadata/json_data" in f else b""
js = (js.decode() if isinstance(js, bytes) else str(js)).replace('\\"', '"')
ucols = list(f["units"].keys()) if "units" in f else []
return {"path": row.path, "names": names,
"unit_cols": [c for c in ucols if re.search(r"antidrom|collision|tier", c, re.I)],
"epochs": tuple(sorted(set(re.findall(r'"stimulus_name":\s*"([^"]*)"', js)))),
"modalities": tuple(sorted(set(re.findall(r'"stimulus_modalities":\s*\[([^\]]*)\]', js)))),
"antidromic_steps": len(set(re.findall(r'"name":\s*"(antidromic[^"]*)"', js)))}
ST = pd.DataFrame(lcne.pmap(scan_stimulation, list(assets_all[assets_all.kind.str.contains("ecephys")].itertuples())))
obj = Counter(n for l in ST.names for n in l)
print(f"Files with spikes scanned: {len(ST)}")
print("Objects under stimulus/, intervals/, acquisition/, processing/ (files holding each):")
print(pd.Series(obj).sort_index().to_string())
print("Objects whose name matches stim|laser|opto|antidrom|collision|pulse:", sorted(n for n in obj if STIM_PAT.search(n.split("/", 1)[1])))
print("Unit columns on antidromic tests:", sorted(set(c for l in ST.unit_cols for c in l)))
print("Stimulus epochs in the metadata:", ST.epochs.value_counts().to_dict())
print("Stimulus modalities in the metadata:", ST.modalities.value_counts().to_dict())
print("Files whose metadata names antidromic_tagging processing steps:", int((ST.antidromic_steps > 0).sum()), "of", len(ST))
Files with spikes scanned: 165
Objects under stimulus/, intervals/, acquisition/, processing/ (files holding each):
acquisition/left_lick_time 163
acquisition/left_reward_delivery_time 163
acquisition/right_lick_time 163
acquisition/right_reward_delivery_time 163
intervals/trials 163
processing/behavior 145
processing/behavior/pupil_diameter 97
processing/behavior/tongue_kinematics 48
processing/behavior/tongue_movements 41
Objects whose name matches stim|laser|opto|antidrom|collision|pulse: []
Unit columns on antidromic tests: []
Stimulus epochs in the metadata: {('Behavioral foraging task',): 106, ('The behavior auditory go cue',): 55, (): 4}
Stimulus modalities in the metadata: {('"Auditory"',): 161, (): 4}
Files whose metadata names antidromic_tagging processing steps: 56 of 165
Added after verification round 2, which asked for the check behind the block of
fig6f-cortex-projecting-rpe-biased to be in the notebook. None of the 165 files with spikes holds
a stimulus, interval, acquisition or processing object other than the task's trials, licks,
reward deliveries, pupil diameter and tongue tracking, and no units table has a column on
antidromic tests. The AIND metadata names only the behavioral task or the auditory go cue as
stimulus epochs. It lists antidromic_tagging processing steps in 56 files, but the stimulation
times those steps read ({session}_opto_session.csv in the paper's code) are not in the files.
Cortex-projecting neurons cannot be identified from the pinned version.
# Clock check for the spikes: decoding responded against ignored trials is not possible from the
# go-cue response alone, so the contrast is the go-cue response with the true cue times against
# times shifted by 1 s, 2 s and 3 s before the cue.
spk = {}
for s in sessions:
if s["spikes"]:
for r, sp in s["spikes"].items():
spk[(s["path"], int(r))] = np.sort(sp)
trials_by_path = {s["path"]: lcne.go_trials(s["trials"]) for s in sessions}
shift_rows = []
for _, c in cells.iterrows():
sp = spk[(c.path, c.row)]
gc = trials_by_path[c.path].goCue_start_time.values
row = {"path": c.path}
for sh in [0, -1.0, -2.0, -3.0]:
resp = lcne.rate_in_windows(sp, gc + sh, 0.01, 0.3)
base = lcne.rate_in_windows(sp, gc + sh, -2.0, -0.01)
row[f"shift {sh:+.0f} s"] = np.mean(resp - base)
shift_rows.append(row)
SH = pd.DataFrame(shift_rows)
print("Mean go-cue response (Hz, 0.01-0.3 s minus 2 s baseline) over selected units, by shift of the cue times:")
print(SH.drop(columns="path").describe().loc[["mean", "50%", "min", "max"]].round(2).to_string())
by_sess = SH.groupby("path")["shift +0 s"].mean()
print("Sessions whose mean response at the true cue times is not positive:", int((by_sess <= 0).sum()), "of", len(by_sess))
def window_mean(t, v, align, start, stop):
lo = np.searchsorted(t, align + start)
hi = np.searchsorted(t, align + stop)
cs = np.concatenate([[0], np.cumsum(np.nan_to_num(v))])
n = hi - lo
return np.where(n > 0, (cs[hi] - cs[lo]) / np.maximum(n, 1), np.nan)
# FP and pupil sampling rates.
fp_rate = [1 / np.median(np.diff(s["fp"][0])) for s in sessions if s["fp"] is not None]
pu_rate = [1 / np.median(np.diff(s["pupil"][0])) for s in sessions if s["pupil"] is not None]
print(f"\nPhotometry sampling rate (Hz): median {np.median(fp_rate):.2f}, range {min(fp_rate):.2f} to {max(fp_rate):.2f}")
print(f"Pupil sampling rate (Hz): median {np.median(pu_rate):.2f}, range {min(pu_rate):.2f} to {max(pu_rate):.2f}")
pv = np.concatenate([s["pupil"][1] for s in sessions if s["pupil"] is not None])
print(f"Pupil diameter values: {np.nanmin(pv):.3g} to {np.nanmax(pv):.3g}, median {np.nanmedian(pv):.3g}, NaN fraction {np.mean(~np.isfinite(pv)):.3f}")
pd_rows = []
for s in sessions:
if s["pupil"] is None:
continue
t, v = s["pupil"]
z = (v - np.nanmean(v)) / np.nanstd(v)
gc = lcne.go_trials(s["trials"]).goCue_start_time.values
for sh in [0.0, -3.0]:
pd_rows.append({"shift": sh, "dilation": np.nanmean(window_mean(t, z, gc + sh, 1.0, 2.0) - window_mean(t, z, gc + sh, -1.0, 0.0))})
PDl = pd.DataFrame(pd_rows)
print("Pupil (z) 1-2 s after minus 1 s before the go cue, over sessions; true cue times and cue times shifted by -3 s:")
print(PDl.groupby("shift").dilation.describe()[["count", "mean", "min", "max"]].round(3).to_string())
Mean go-cue response (Hz, 0.01-0.3 s minus 2 s baseline) over selected units, by shift of the cue times:
shift +0 s shift -1 s shift -2 s shift -3 s
mean 4.68 -0.04 0.00 -0.20
50% 4.11 -0.06 0.00 -0.17
min -0.10 -0.60 -0.62 -0.93
max 13.42 0.94 0.70 0.46
Sessions whose mean response at the true cue times is not positive: 0 of 112
Photometry sampling rate (Hz): median 20.00, range 20.00 to 20.01
Pupil sampling rate (Hz): median 20.84, range 20.80 to 21.06
Pupil diameter values: 8.41 to 178, median 88.4, NaN fraction 0.057
Pupil (z) 1-2 s after minus 1 s before the go cue, over sessions; true cue times and cue times shifted by -3 s:
count mean min max
shift
-3.0 133.0 -0.226 -0.444 -0.025
0.0 133.0 0.773 -0.017 1.356
The spikes share the trial table's clock: the go-cue response of the selected units averages about 4.7 Hz at the true cue times and about 0 Hz with the cue times shifted by 1, 2 or 3 s, and every one of the 112 sessions has a positive mean response. Pupil diameter dilates after the go cue in every session at the true times (mean 0.77 z) and not with the times shifted by 3 s (mean -0.23 z), so the pupil series shares the clock too. Photometry is sampled at 20 Hz per channel, as the Methods state. Pupil is sampled at about 21 Hz (the Methods give 22 to 24 Hz for the video); its units are not stated in the file (values 8 to 178, likely pixels).
iti-mean¶
Inter-trial intervals averaged 4.83 s (range 1.1 to 20 s).
def itis(s, end_rule, nogo_onsets):
tr = s["trials"].sort_values("goCue_start_time")
cue = tr.goCue_start_time.values
is_go = tr.go.values
if end_rule == "stop_time":
end = tr.stop_time.values
else:
end = cue + (3.0 if s["kind"] == "behavior+fib" else 3.1)
out = []
for i in range(len(tr) - 1):
if not nogo_onsets and not is_go[i]:
continue
if nogo_onsets:
j = i + 1
else:
later = np.where(is_go[i + 1:])[0]
if len(later) == 0:
continue
j = i + 1 + later[0]
out.append(cue[j] - end[i])
return np.array(out)
iti_rows = []
for end_rule in ["fixed 3.0 or 3.1 s", "stop_time"]:
for nogo in [True, False]:
v = np.concatenate([itis(s, end_rule, nogo) for s in sessions])
iti_rows.append({"trial end": end_rule, "no-go cues end an ITI": nogo, "n": len(v), "mean": v.mean(), "median": np.median(v),
"min": v.min(), "p1": np.percentile(v, 1), "p99": np.percentile(v, 99), "max": v.max(),
"mean within 4.83 +- 0.483": abs(v.mean() - 4.83) <= 0.483,
"range within 0.99 to 22": (v.min() >= 0.99) and (v.max() <= 22)})
ITI = pd.DataFrame(iti_rows)
print(ITI.round(3).to_string(index=False))
v = np.concatenate([itis(s, "fixed 3.0 or 3.1 s", True) for s in sessions])
print("\nMain reading (fixed trial end, every cue onset ends an ITI) by kind:")
for k in S.kind.unique():
vk = np.concatenate([itis(s, "fixed 3.0 or 3.1 s", True) for s in sessions if s["kind"] == k])
print(f" {k}: n {len(vk)}, mean {vk.mean():.2f}, median {np.median(vk):.2f}, min {vk.min():.2f}, max {vk.max():.2f}")
print("Fraction of intervals above 20 s:", np.mean(v > 20).round(4), "; below 1.1 s:", np.mean(v < 1.1).round(4))
cue_to_cue = np.concatenate([np.diff(s["trials"].goCue_start_time.values) for s in sessions])
print(f"Cue-to-cue intervals: mean {cue_to_cue.mean():.2f}, min {cue_to_cue.min():.2f}, max {cue_to_cue.max():.2f} s")
fig, ax = plt.subplots(figsize=(5, 3))
ax.hist(np.clip(v, 0, 40), bins=80, color="k")
ax.set_xlabel("ITI (s), end of trial to next cue; clipped at 40 s")
ax.set_ylabel("intervals")
plt.tight_layout()
plt.show()
print("Intervals above 40 s (drawn at 40):", int((v > 40).sum()), "of", len(v))
# The trial table's ITI_duration column (added after verification round 1).
itid = np.concatenate([s["trials"].ITI_duration.values for s in sessions])
print(f"\nITI_duration column: n {len(itid)}, mean {itid.mean():.2f}, min {itid.min():.2f}, median {np.median(itid):.2f}, max {itid.max():.2f} s")
for k in S.kind.unique():
vk = np.concatenate([s["trials"].ITI_duration.values for s in sessions if s["kind"] == k])
print(f" {k}: mean {vk.mean():.2f}, min {vk.min():.2f}, max {vk.max():.2f}, distinct values {len(np.unique(vk))}")
pre = np.concatenate([(s["trials"].goCue_start_time - s["trials"].start_time).values for s in sessions])
print(f"Trial start to go cue (the interval from the end of the previous trial, as start_time equals the previous stop_time): "
f"mean {pre.mean():.2f}, min {pre.min():.2f}, max {pre.max():.2f} s")
trial end no-go cues end an ITI n mean median min p1 p99 max mean within 4.83 +- 0.483 range within 0.99 to 22
fixed 3.0 or 3.1 s True 171153 4.427 3.349 0.217 1.101 16.138 292.378 True False
fixed 3.0 or 3.1 s False 165601 4.676 3.469 0.217 1.105 18.984 292.378 True False
stop_time True 171153 4.696 3.695 1.009 1.109 16.531 292.278 True False
stop_time False 165601 4.956 3.842 1.009 1.112 19.224 292.278 True False
Main reading (fixed trial end, every cue onset ends an ITI) by kind:
behavior+fib: n 73866, mean 4.01, median 2.96, min 1.21, max 292.38
behavior: n 34272, mean 4.95, median 3.84, min 0.22, max 149.89
behavior+ecephys: n 63015, mean 4.63, median 3.65, min 0.98, max 210.98 Fraction of intervals above 20 s: 0.0072 ; below 1.1 s: 0.0098 Cue-to-cue intervals: mean 7.48, min 3.32, max 295.38 s
Intervals above 40 s (drawn at 40): 82 of 171153 ITI_duration column: n 171536, mean 1.37, min 0.50, median 0.50, max 15.00 s behavior+fib: mean 0.50, min 0.50, max 0.50, distinct values 1 behavior: mean 1.76, min 0.50, max 15.00, distinct values 9528 behavior+ecephys: mean 2.18, min 0.50, max 15.00, distinct values 23404 Trial start to go cue (the interval from the end of the previous trial, as start_time equals the previous stop_time): mean 4.67, min 1.01, max 292.28 s
Result: partially reproduced. Under every reading the mean interval from the end of a trial
to the next cue is within 4.83 +- 0.483 s (4.43 to 4.96 s). The range is not: intervals reach
292 s (pauses in the session), and the shortest are 0.22 s in behavior-only sessions; 0.72% of
intervals exceed 20 s and the 1st to 99th percentiles are 1.10 to 16.1 s (fixed trial end, all
cues). The trial table's ITI_duration column is not the paper's interval: it is 0.5 s in every
photometry trial, averages 1.37 s and spans 0.5 to 15 s, so it cannot stand in for the generated
intervals the paper's range describes. Read literally as the Methods define it ("the times between
consecutive cue onsets"), the interval averages 7.48 s (3.32 to 295 s), outside the mean too; the
criterion's reading is asked of a reader (questions/001950.yaml).
fig4c-choice-history¶
Mice used reward and choice history to guide choices; a logistic regression of choice on outcome history has R2 = 0.60 and predicts 0.88 of choices, with coefficients decaying over past trials (exponential fit coefficient 3.95).
go_by_session = [(s["subject"], lcne.go_trials(s["trials"])) for s in sessions]
# history_matrix columns: R lags 1..L, N lags 1..L, C lags 1..L. R + N = C, so the three blocks
# are collinear; the models fit two blocks: R + C (the code's Figure 4c model,
# choice_reward_choice in F_behavior_w_FP.ipynb) and R + N (the variables the Methods name).
MODELS = {"R + C (code, Figure 4c)": lambda L: np.r_[0:L, 2 * L:3 * L], "R + N (Methods)": lambda L: np.r_[0:2 * L]}
def design(lags, cols, subjects=None):
Xs, ys = [], []
for subj, g in go_by_session:
if subjects is not None and subj not in subjects:
continue
X, y = lcne.history_matrix(g, lags)
if len(y):
Xs.append(X[:, cols])
ys.append(y)
return np.vstack(Xs), np.concatenate(ys)
def fit_choice(X, y):
m = sm.Logit(y, sm.add_constant(X)).fit(disp=0, maxiter=200)
p = m.predict(sm.add_constant(X))
return {"model": m, "coef": m.params[1:], "se": m.bse[1:], "mcfadden": 1 - m.llf / m.llnull,
"r2_corr": np.corrcoef(p, y)[0, 1] ** 2, "accuracy": np.mean((p > 0.5) == (y == 1))}
def exp_fit(lags_, beta, se=None):
"""y = A exp(-lag / tau) + C, weighted by the SEs, as _fit_exp_offset in F_behavior_w_FP.ipynb."""
y = np.asarray(beta, float)
sign = -1.0 if np.mean(y) < 0 else 1.0
y = sign * y
try:
(A, tau, C), _ = curve_fit(lambda t, A, tau, C: A * np.exp(-t / tau) + C, lags_, y, p0=(y[0] - y[-1], max((lags_[-1] - lags_[0]) / 3, 1e-3), y[-1]),
sigma=se, absolute_sigma=se is not None, maxfev=20000, bounds=([-np.inf, 1e-3, -np.inf], [np.inf, 100, np.inf]))
return sign * A, tau, sign * C
except Exception:
return np.nan, np.nan, np.nan
res_rows = []
pooled = {}
for mname, colf in MODELS.items():
for lags in [5, 10, 15]:
cols = colf(lags)
X, y = design(lags, cols)
f = fit_choice(X, y)
pooled[(mname, lags)] = f
A, tau, C = exp_fit(np.arange(1, lags + 1), f["coef"][:lags], f["se"][:lags])
res_rows.append({"model": mname, "lags": lags, "fit": "pooled", "n_choices": len(y), "McFadden R2": f["mcfadden"],
"squared corr R2": f["r2_corr"], "fraction predicted": f["accuracy"], "R exp A": A, "R exp tau": tau, "R exp C": C})
per = []
for subj in sorted(S.subject.unique()):
Xm, ym = design(lags, cols, {subj})
if len(ym) >= 200:
per.append(fit_choice(Xm, ym))
mc = np.mean([p["coef"][:lags] for p in per], axis=0)
A, tau, C = exp_fit(np.arange(1, lags + 1), mc)
res_rows.append({"model": mname, "lags": lags, "fit": f"mean of {len(per)} mice", "n_choices": np.nan,
"McFadden R2": np.mean([p["mcfadden"] for p in per]), "squared corr R2": np.mean([p["r2_corr"] for p in per]),
"fraction predicted": np.mean([p["accuracy"] for p in per]), "R exp A": A, "R exp tau": tau, "R exp C": C})
CH = pd.DataFrame(res_rows)
print(CH.round(3).to_string(index=False))
for mname in MODELS:
f5 = pooled[(mname, 5)]
print(f"\n{mname}, pooled, 5 lags; coefficients lag 1 first (SE):")
print(" first block:", np.round(f5["coef"][:5], 3), np.round(f5["se"][:5], 3))
print(" second block:", np.round(f5["coef"][5:], 3), np.round(f5["se"][5:], 3))
print(" rewarded coefficients all positive:", bool(np.all(f5["coef"][:5] > 0)), "; decreasing over lags:", bool(np.all(np.diff(f5["coef"][:5]) < 0)))
f15 = pooled[("R + C (code, Figure 4c)", 15)]
fig, ax = plt.subplots(figsize=(5, 3))
for name, sl, col in [("rewarded", slice(0, 15), "b"), ("choice", slice(15, 30), "k")]:
ax.errorbar(np.arange(1, 16), f15["coef"][sl], yerr=f15["se"][sl], color=col, label=name, marker="o", ms=3)
ax.axhline(0, color="0.7")
ax.set_xlabel("trials back")
ax.set_ylabel("coefficient (R + C, pooled)")
ax.legend(fontsize=8)
plt.tight_layout()
plt.show()
print("Plotted coefficient range:", np.round(f15["coef"].min(), 3), "to", np.round(f15["coef"].max(), 3))
r10 = CH[(CH.model == "R + N (Methods)") & (CH.lags == 10) & (CH.fit == "pooled")].iloc[0]
print(f"\nDecay constant of the exponential fit (the claims file's reading of 'coefficient of 3.95'), R + N pooled over 10 lags: "
f"tau = {r10['R exp tau']:.3f} trials (amplitude {r10['R exp A']:.3f}); over all fits tau = {CH['R exp tau'].min():.2f} to {CH['R exp tau'].max():.2f}; "
f"within 3.95 +- 0.395 in none: {not bool(((CH['R exp tau'] - 3.95).abs() <= 0.395).any())}")
model lags fit n_choices McFadden R2 squared corr R2 fraction predicted R exp A R exp tau R exp C
R + C (code, Figure 4c) 5 pooled 152905.0 0.600 0.677 0.895 2.902 1.443 -0.099
R + C (code, Figure 4c) 5 mean of 39 mice NaN 0.660 0.722 0.918 2.827 2.276 -0.269
R + C (code, Figure 4c) 10 pooled 150991.0 0.601 0.677 0.895 2.743 1.607 -0.100
R + C (code, Figure 4c) 10 mean of 39 mice NaN 0.666 0.727 0.919 2.856 1.848 -0.070
R + C (code, Figure 4c) 15 pooled 149081.0 0.600 0.676 0.895 2.710 1.603 -0.074
R + C (code, Figure 4c) 15 mean of 39 mice NaN 0.672 0.731 0.919 2.903 1.839 -0.053
R + N (Methods) 5 pooled 152905.0 0.600 0.677 0.895 4.553 1.234 0.067
R + N (Methods) 5 mean of 39 mice NaN 0.660 0.722 0.918 5.162 1.371 0.010
R + N (Methods) 10 pooled 150991.0 0.601 0.677 0.895 4.327 1.391 -0.017
R + N (Methods) 10 mean of 39 mice NaN 0.666 0.727 0.919 5.268 1.382 -0.010
R + N (Methods) 15 pooled 149081.0 0.600 0.676 0.895 4.277 1.407 -0.014
R + N (Methods) 15 mean of 39 mice NaN 0.672 0.731 0.919 5.322 1.406 -0.013
R + C (code, Figure 4c), pooled, 5 lags; coefficients lag 1 first (SE):
first block: [ 1.359 0.598 0.294 0.09 -0.025] [0.021 0.021 0.021 0.02 0.02 ]
second block: [0.735 0.362 0.179 0.171 0.159] [0.013 0.014 0.016 0.016 0.015]
rewarded coefficients all positive: False ; decreasing over lags: True
R + N (Methods), pooled, 5 lags; coefficients lag 1 first (SE):
first block: [2.094 0.959 0.474 0.261 0.134] [0.018 0.019 0.019 0.02 0.019]
second block: [0.735 0.362 0.179 0.171 0.159] [0.013 0.014 0.016 0.016 0.015]
rewarded coefficients all positive: True ; decreasing over lags: True
Plotted coefficient range: -0.125 to 1.401 Decay constant of the exponential fit (the claims file's reading of 'coefficient of 3.95'), R + N pooled over 10 lags: tau = 1.391 trials (amplitude 4.327); over all fits tau = 1.23 to 2.28; within 3.95 +- 0.395 in none: True
Result: reproduced. Pooled over all mice, the McFadden R2 is 0.600 to 0.601 and 0.895 of choices are predicted, under every number of lags and both models (the squared correlation is 0.68). The rewarded coefficients decay over lags; they are all positive in the R + N model, and in the code's R + C model positive for lags 1 to 4 and -0.025 at lag 5. The criterion does not test the exponential fit coefficient. Read as the claims file reads it, a decay constant in trials, it is not reproduced: tau is 1.39 trials for R + N pooled over 10 lags and 1.23 to 2.28 in every fit, against 3.95 +- 0.395. The amplitude of the same fit is 4.33 (4.28 over 15 lags), within tolerance (5 lags 4.55; per-mouse means 5.16 to 5.32; R + C 2.7 to 2.9). Which of the two the legend means is asked of a reader (questions/001950.yaml).
fig5a-engagement-reward-history¶
Whether mice respond to a go cue depends on reward history.
def engagement_design(g, lags):
resp = g.responded.values.astype(float)
rew = g.rewarded.values.astype(float)
X, y = [], []
for t in range(lags, len(g)):
X.append(rew[t - lags:t][::-1])
y.append(resp[t])
return np.array(X), np.array(y)
eng = {}
for lags in [1, 5, 10]:
coefs = []
for subj in sorted(S.subject.unique()):
Xs, ys = [], []
for sj, g in go_by_session:
if sj == subj:
X, y = engagement_design(g, lags)
if len(y):
Xs.append(X)
ys.append(y)
X, y = np.vstack(Xs), np.concatenate(ys)
if y.min() == y.max() or (1 - y).sum() < 10:
continue
try:
m = sm.Logit(y, sm.add_constant(X)).fit(disp=0, maxiter=200)
coefs.append({"subject": subj, **{f"lag{k + 1}": m.params[k + 1] for k in range(lags)}, "n": len(y)})
except Exception:
pass
C = pd.DataFrame(coefs)
eng[lags] = C
b = C.lag1
ci = stats.t.interval(0.95, len(b) - 1, loc=b.mean(), scale=stats.sem(b))
print(f"{lags} lag(s): {len(C)} mice; lag-1 reward coefficient mean {b.mean():.3f}, 95% CI {ci[0]:.3f} to {ci[1]:.3f}, "
f"positive in {int((b > 0).sum())} of {len(b)}; one-sample t p = {stats.ttest_1samp(b, 0).pvalue:.2g}")
print("Mice left out (fewer than 10 ignored go cues):", sorted(set(S.subject) - set(eng[5].subject)))
print("\n5-lag coefficients across mice (mean and SEM):")
print(eng[5].drop(columns=["subject", "n"]).agg(["mean", "sem"]).round(3).to_string())
1 lag(s): 40 mice; lag-1 reward coefficient mean 2.384, 95% CI 2.100 to 2.669, positive in 40 of 40; one-sample t p = 1.3e-19
5 lag(s): 40 mice; lag-1 reward coefficient mean 1.633, 95% CI 1.427 to 1.838, positive in 40 of 40; one-sample t p = 8.5e-19
10 lag(s): 40 mice; lag-1 reward coefficient mean 1.595, 95% CI 1.385 to 1.805, positive in 40 of 40; one-sample t p = 3.8e-18
Mice left out (fewer than 10 ignored go cues): ['758018']
5-lag coefficients across mice (mean and SEM):
lag1 lag2 lag3 lag4 lag5
mean 1.633 1.005 0.820 0.607 0.608
sem 0.102 0.093 0.068 0.072 0.064
Result: reproduced. Across 40 mice the coefficient of the previous trial's reward on responding to the go cue is 1.633 (95% CI 1.427 to 1.838) with 5 lags, positive in all 40 mice, and the CI excludes zero with 1 or 10 lags too. One mouse with fewer than 10 ignored go cues is left out.
fig5e-switch-history¶
Mice were likely to repeat choices when they had recently been rewarded for that lick direction, as shown by a logistic regression of switch against stay on no-reward and choice history.
def switch_design(g, lags):
r = g[g.responded].reset_index(drop=True)
c = 2 * r.choice_right.values - 1
unrew = ~r.rewarded.values.astype(bool)
X, y = [], []
for t in range(lags + 1, len(r)):
ref = c[t - 1]
n_ipsi = [(1.0 if c[t - k] == ref else -1.0) if unrew[t - k] else 0.0 for k in range(1, lags + 1)]
ch = [1.0 if c[t - k] == ref else -1.0 for k in range(2, lags + 2)]
X.append(n_ipsi + ch)
y.append(float(c[t] != ref))
return np.array(X), np.array(y)
for lags in [5, 10, 15]:
coefs = []
for subj in sorted(S.subject.unique()):
Xs, ys = [], []
for sj, g in go_by_session:
if sj == subj:
X, y = switch_design(g, lags)
if len(y):
Xs.append(X)
ys.append(y)
X, y = np.vstack(Xs), np.concatenate(ys)
try:
m = sm.Logit(y, sm.add_constant(X)).fit(disp=0, maxiter=200)
coefs.append({"subject": subj, "N1": m.params[1], "N2": m.params[2], "C2": m.params[lags + 1], "n": len(y)})
except Exception:
pass
C = pd.DataFrame(coefs)
b = C.N1
ci = stats.t.interval(0.95, len(b) - 1, loc=b.mean(), scale=stats.sem(b))
print(f"{lags} lags: {len(C)} mice; lag-1 no-reward coefficient mean {b.mean():.3f}, 95% CI {ci[0]:.3f} to {ci[1]:.3f}, "
f"positive in {int((b > 0).sum())}; lag-2 no-reward mean {C.N2.mean():.3f}; first choice-history coefficient mean {C.C2.mean():.3f}")
p_sw_after_rew = []
p_sw_after_unrew = []
for _, g in go_by_session:
r = g[g.responded].reset_index(drop=True)
sw = (r.choice_right.values[1:] != r.choice_right.values[:-1])
rw = r.rewarded.values[:-1].astype(bool)
p_sw_after_rew.append(sw[rw].mean())
p_sw_after_unrew.append(sw[~rw].mean())
print(f"\nP(switch) after a rewarded choice, median over sessions {np.nanmedian(p_sw_after_rew):.3f}; after an unrewarded choice {np.nanmedian(p_sw_after_unrew):.3f}")
5 lags: 41 mice; lag-1 no-reward coefficient mean 1.540, 95% CI 1.380 to 1.701, positive in 41; lag-2 no-reward mean 0.860; first choice-history coefficient mean -0.914
10 lags: 41 mice; lag-1 no-reward coefficient mean 2.011, 95% CI 1.169 to 2.853, positive in 41; lag-2 no-reward mean 1.231; first choice-history coefficient mean -1.270
15 lags: 40 mice; lag-1 no-reward coefficient mean 1.641, 95% CI 1.458 to 1.823, positive in 40; lag-2 no-reward mean 0.855; first choice-history coefficient mean -0.560 P(switch) after a rewarded choice, median over sessions 0.032; after an unrewarded choice 0.178
Result: reproduced. The lag-1 no-reward coefficient on switching is positive in every reading (5 lags 1.540, 95% CI 1.380 to 1.701, 41 mice; 10 lags 2.011, 1.169 to 2.853, 41 mice; 15 lags 1.641, 1.458 to 1.823, 40 mice). Switching follows 17.8% of unrewarded and 3.2% of rewarded choices (session medians).
fig4g-go-cue-excitation¶
Nearly all LC-NE neurons (240 of 241, 19 mice) increased their spike rate in the 300 ms after the go cue.
go_rows = []
for _, c in cells.iterrows():
sp = spk[(c.path, c.row)]
g = trials_by_path[c.path]
gc = g.goCue_start_time.values
resp = lcne.rate_in_windows(sp, gc, 0.01, 0.3)
base = lcne.rate_in_windows(sp, gc, -2.0, -0.01)
tonic = lcne.rate_in_windows(sp, gc, -0.5, 0.0)
t, p = stats.ttest_rel(resp, base)
ok = np.std(tonic) > 0 and np.std(resp) > 0
go_rows.append({"path": c.path, "row": c.row, "subject": c.subject, "probe": c.probe, "n_trials": len(gc),
"resp": resp.mean(), "base": base.mean(), "t": t, "p": p,
"tonic_phasic_r": stats.pearsonr(tonic, resp)[0] if ok else np.nan,
"rel_change": (resp.mean() - base.mean()) / base.mean() if base.mean() > 0 else np.nan})
GO = pd.DataFrame(go_rows)
n = len(GO)
a = int((GO.p < 0.05).sum())
b = int(((GO.p < 0.05) & (GO.resp > GO.base)).sum())
print(f"{n} neurons from {GO.subject.nunique()} mice")
print(f"(a) two-sided paired t-test p < 0.05: {a} of {n} ({100 * a / n:.1f}%)")
print(f"(b) p < 0.05 with response above baseline: {b} of {n} ({100 * b / n:.1f}%)")
print(f"Significantly decreased: {int(((GO.p < 0.05) & (GO.resp < GO.base)).sum())}")
print(f"Scaled to the paper's 241 neurons, (b) is {241 * b / n:.1f} (expected 240 +- 24)")
print("By mouse (significant increase / neurons):")
print(GO.assign(sig=(GO.p < 0.05) & (GO.resp > GO.base)).groupby("subject").sig.agg(["sum", "size"]).T.to_string())
for thr in [0.01, 0.001]:
print(f"With p < {thr}: increased {int(((GO.p < thr) & (GO.resp > GO.base)).sum())} of {n}")
print(f"Median response {GO.resp.median():.2f} Hz against baseline {GO.base.median():.2f} Hz")
252 neurons from 21 mice (a) two-sided paired t-test p < 0.05: 251 of 252 (99.6%) (b) p < 0.05 with response above baseline: 251 of 252 (99.6%) Significantly decreased: 0 Scaled to the paper's 241 neurons, (b) is 240.0 (expected 240 +- 24) By mouse (significant increase / neurons): subject 716325 751004 751181 751766 751769 752014 754897 758017 758018 761038 763590 781166 782394 784803 784806 785956 791691 ZS059 ZS060 ZS061 ZS062 sum 3 8 10 15 9 3 17 9 6 5 4 5 15 4 3 3 11 4 3 62 52 size 3 8 10 15 9 3 17 9 6 5 4 5 15 4 3 3 11 4 3 62 53 With p < 0.01: increased 251 of 252 With p < 0.001: increased 250 of 252 Median response 7.22 Hz against baseline 3.05 Hz
Result: reproduced. 251 of 252 selected neurons (21 mice) increased their rate in the 0.3 s after the go cue (paired t-test p < 0.05, both readings); scaled to 241 neurons this is 240.0, the paper's count. No neuron decreased significantly. 250 neurons pass at p < 0.001.
fig4h-tonic-phasic-anticorrelation¶
Neurons whose go-cue rate is more anticorrelated with their baseline rate have larger go-cue responses relative to baseline (r = -0.38).
def tonic_phasic(df, label):
d = df.dropna(subset=["tonic_phasic_r", "rel_change"])
d = d[np.isfinite(d.rel_change)]
r, p = stats.pearsonr(d.tonic_phasic_r, d.rel_change)
rs, ps = stats.spearmanr(d.tonic_phasic_r, d.rel_change)
print(f"{label}: n = {len(d)} neurons ({d.subject.nunique()} mice); Pearson r = {r:.3f}, p = {p:.2g}; Spearman rho = {rs:.3f}, p = {ps:.2g}; "
f"within -0.38 +- 0.038: {abs(r + 0.38) <= 0.038}")
return d
d4h = tonic_phasic(GO, "(a) selected neurons")
# (b) the code's basic_ephys_all.json population: opto criteria with p_max >= 0.6, ISI and slow
# drift ratio, without the trial-count and session criteria.
popb = U[(U.p_max >= 0.6) & U.isi_ok & U.sd_ok]
rows_b = []
for _, c in popb.iterrows():
sp = spk[(c.path, c.row)]
gc = trials_by_path[c.path].goCue_start_time.values
if len(gc) < 10:
continue
resp = lcne.rate_in_windows(sp, gc, 0.01, 0.3)
base = lcne.rate_in_windows(sp, gc, -2.0, -0.01)
tonic = lcne.rate_in_windows(sp, gc, -0.5, 0.0)
ok = np.std(tonic) > 0 and np.std(resp) > 0
rows_b.append({"subject": c.subject, "tonic_phasic_r": stats.pearsonr(tonic, resp)[0] if ok else np.nan,
"rel_change": (resp.mean() - base.mean()) / base.mean() if base.mean() > 0 else np.nan})
tonic_phasic(pd.DataFrame(rows_b), f"(b) basic_ephys_all population ({len(popb)} units)")
d_noout = d4h[d4h.rel_change < d4h.rel_change.quantile(0.98)]
print(f"Without the 2% largest relative changes: r = {stats.pearsonr(d_noout.tonic_phasic_r, d_noout.rel_change)[0]:.3f}")
fig, ax = plt.subplots(figsize=(4, 3))
ax.scatter(d4h.tonic_phasic_r, d4h.rel_change, s=8, color="k")
ax.set_ylim(-1, 20)
ax.set_xlabel("r(0.5 s before, 0.3 s after go cue)")
ax.set_ylabel("(response - baseline) / baseline")
plt.tight_layout()
plt.show()
print("x range", d4h.tonic_phasic_r.min().round(3), "to", d4h.tonic_phasic_r.max().round(3), "; y range", d4h.rel_change.min().round(2),
"to", d4h.rel_change.max().round(2), "; points outside the y axis:", int(((d4h.rel_change < -1) | (d4h.rel_change > 20)).sum()))
(a) selected neurons: n = 252 neurons (21 mice); Pearson r = -0.381, p = 4e-10; Spearman rho = -0.388, p = 1.7e-10; within -0.38 +- 0.038: True
(b) basic_ephys_all population (249 units): n = 249 neurons (21 mice); Pearson r = -0.379, p = 6.3e-10; Spearman rho = -0.387, p = 2.5e-10; within -0.38 +- 0.038: True Without the 2% largest relative changes: r = -0.392
x range -0.629 to 0.192 ; y range -0.05 to 4.62 ; points outside the y axis: 0
Result: reproduced. Across the 252 selected neurons, r = -0.381 (p = 4e-10); in the code's wider population (249 units) r = -0.379. Both are within -0.38 +- 0.038.
fig5b-baseline-predicts-ignore¶
LC-NE neurons had higher spike rates before ignored go cues than before responded ones; baseline rates in the 2 s before the go cue predicted the response in 46.5% of neurons.
def hit_table(units):
"""Per unit, respond-versus-ignore regressions of the 2 s baseline before each go cue."""
hit_rows = []
for _, c in units.iterrows():
sp = spk[(c.path, c.row)]
g = trials_by_path[c.path]
gc = g.goCue_start_time.values
base = lcne.rate_in_windows(sp, gc, -2.0, -0.01)
resp_win = lcne.rate_in_windows(sp, gc, 0.01, 0.3)
hit = g.responded.values.astype(float)
prev = np.concatenate([[np.nan], g.choice_right.values[:-1]])
svs_code = np.where(np.isfinite(prev) & g.responded.values, (g.choice_right.values != prev).astype(float), 0.0)
trial_idx = np.arange(len(g), dtype=float)
n_ign = int((1 - hit).sum())
row = {"path": c.path, "row": c.row, "subject": c.subject, "n_ignored": n_ign,
"base_ignored": base[hit == 0].mean() if n_ign else np.nan, "base_responded": base[hit == 1].mean(),
"resp_diff": resp_win[hit == 1].mean() - resp_win[hit == 0].mean() if n_ign else np.nan}
if n_ign >= 2:
row["t_methods"], row["p_methods"], _ = lcne.ols_t(base, [hit])
row["t_code"], row["p_code"], _ = lcne.ols_t(base, [hit, svs_code])
row["t_drift"], row["p_drift"], _ = lcne.ols_t(base, [hit, trial_idx])
hit_rows.append(row)
return pd.DataFrame(hit_rows)
HIT = hit_table(cells)
n_all = len(HIT)
for reg in ["methods", "code", "drift"]:
tcol, pcol = f"t_{reg}", f"p_{reg}"
k = int((HIT[pcol] < 0.05).sum())
ndef = int(HIT[pcol].notna().sum())
print(f"regressors {reg:7s}: p < 0.05 in {k}; of all {n_all} = {100 * k / n_all:.1f}%; of {ndef} with a coefficient = {100 * k / ndef:.1f}%; "
f"of these negative t (higher before ignored): {int(((HIT[pcol] < 0.05) & (HIT[tcol] < 0)).sum())}")
print("Regressor sets: methods = response; code = response and switch against the previous trial (0 when either is unresponded); "
"drift = response and trial index (a stand-in for the per-trial spike amplitude, which the dandiset lacks).")
print("Neurons without a coefficient (fewer than 2 ignored go cues in the session):", int(HIT.t_methods.isna().sum()))
d = HIT.dropna(subset=["base_ignored"])
tt = stats.ttest_rel(d.base_ignored, d.base_responded)
print(f"\nBaseline rate before ignored against responded go cues, across {len(d)} neurons: mean {d.base_ignored.mean():.3f} against "
f"{d.base_responded.mean():.3f} Hz; higher before ignored in {int((d.base_ignored > d.base_responded).sum())}; paired t = {tt.statistic:.2f}, p = {tt.pvalue:.2g}")
print("By mouse, fraction with p < 0.05 (methods regressors):")
print(HIT.groupby("subject").p_methods.apply(lambda v: f"{int((v < 0.05).sum())}/{len(v)}").to_string())
regressors methods: p < 0.05 in 122; of all 252 = 48.4%; of 225 with a coefficient = 54.2%; of these negative t (higher before ignored): 101 regressors code : p < 0.05 in 126; of all 252 = 50.0%; of 225 with a coefficient = 56.0%; of these negative t (higher before ignored): 105 regressors drift : p < 0.05 in 113; of all 252 = 44.8%; of 225 with a coefficient = 50.2%; of these negative t (higher before ignored): 101 Regressor sets: methods = response; code = response and switch against the previous trial (0 when either is unresponded); drift = response and trial index (a stand-in for the per-trial spike amplitude, which the dandiset lacks). Neurons without a coefficient (fewer than 2 ignored go cues in the session): 27 Baseline rate before ignored against responded go cues, across 231 neurons: mean 3.769 against 3.312 Hz; higher before ignored in 171; paired t = 7.38, p = 2.8e-12 By mouse, fraction with p < 0.05 (methods regressors): subject 716325 2/3 751004 3/8 751181 8/10 751766 6/15 751769 2/9 752014 0/3 754897 12/17 758017 5/9 758018 0/6 761038 4/5 763590 4/4 781166 1/5 782394 5/15 784803 0/4 784806 2/3 785956 2/3 791691 3/11 ZS059 0/4 ZS060 0/3 ZS061 50/62 ZS062 13/53
Result: reproduced. With the Methods' regressor, 48.4% of all 252 neurons have p < 0.05
(within 46.5 +- 4.65); over the 225 neurons with a coefficient it is 54.2%. The code's regressors
give 50.0% and 56.0%, the trial-index drift stand-in 44.8% and 50.2%. Most significant neurons
have higher rates before ignored cues (101 of 122). Across 231 neurons the baseline before
ignored go cues is higher (3.77 against 3.31 Hz, paired t p = 2.8e-12). Two tetrode mice hold 115
of the 252 neurons, and the fraction varies by mouse (13 of 53 to 50 of 62). On the populations
of the sensitivity section the fraction is 44.9% to 48.4%, and 51.3% on the draft's
opto_NE_paper units, just outside, so the outcome rests on the population: the main one, the
units passing every criterion computable from the dataset, is kept.
figs15f-tonic-modulation-vs-engagement¶
Across neurons, the correlation between baseline and go-cue spike rates (tonic modulation strength) correlates with the increase of spike rate on lick-response trials over trials without a response, and with the respond-versus-ignore t-statistics of the baseline rate (r = -0.59 for each).
M = GO[["path", "row", "tonic_phasic_r"]].merge(HIT, on=["path", "row"])
for ycol, label in [("resp_diff", "(top) response-window rate, responded minus ignored"),
("t_methods", "(bottom) respond-versus-ignore t (methods regressors)"),
("t_code", "(bottom, code regressors) respond-versus-ignore t")]:
d = M.dropna(subset=["tonic_phasic_r", ycol])
r, p = stats.pearsonr(d.tonic_phasic_r, d[ycol])
print(f"{label}: n = {len(d)}, r = {r:.3f}, p = {p:.2g}; within -0.59 +- 0.059: {abs(r + 0.59) <= 0.059}")
(top) response-window rate, responded minus ignored: n = 231, r = -0.266, p = 4.1e-05; within -0.59 +- 0.059: False (bottom) respond-versus-ignore t (methods regressors): n = 225, r = 0.258, p = 8.9e-05; within -0.59 +- 0.059: False (bottom, code regressors) respond-versus-ignore t: n = 225, r = 0.257, p = 9.7e-05; within -0.59 +- 0.059: False
Result: not reproduced. Tonic modulation strength correlates with the responded minus ignored response-window rate at r = -0.266 (p = 4.1e-05) and with the respond-versus-ignore t at r = +0.258 (methods) and +0.257 (code), all outside -0.59 +- 0.059. The first has the paper's sign and is weaker; the second has the opposite sign in this t convention (negative t is a higher rate before ignored cues).
fig5c-ignore-ventral¶
Neurons with higher activity before ignored trials lie more ventral in LC (103 cells, 15 mice; linear model R2 = 0.152).
ccf_cells = cells[cells.has_ccf].rename(columns={"x": "x_coordinate_in_ccf_space", "y": "y_coordinate_in_ccf_space", "z": "z_coordinate_in_ccf_space"})
ccf_cells["coord"] = list(lcne.ccf_lps(ccf_cells))
def spatial(df, col, label, seed):
d = df.dropna(subset=[col])
X = np.vstack(d.coord.values)
y = d[col].values.astype(float)
rng = np.random.default_rng(seed)
lin = lcne.linear_spatial_test(y, X, n_perm=5000, rng=rng)
knn = lcne.knn_spatial_test(y, X, n_perm=1000, rng=rng)
print(f"{label}: n = {lin['n']} neurons from {d.subject.nunique()} mice; linear R2 = {lin['r2']:.3f}, permutation p = {lin['p']:.4f}; "
f"unit gradient (|ML|, AP posterior +, DV dorsal +) = {np.round(lin['axis'], 3)}; kNN cross-validated R2 = {knn['r2']:.3f}, p = {knn['p']:.4f}")
return lin, knn
hit_ccf = ccf_cells.merge(HIT[["path", "row", "t_methods", "t_code", "t_drift"]], on=["path", "row"])
print("Analyses need at least 100 neurons (Methods, Analyzing relationships with space).")
for col in ["t_methods", "t_code", "t_drift"]:
lin, knn = spatial(hit_ccf, col, f"respond-versus-ignore t ({col[2:]} regressors)", seed=5)
d = hit_ccf.dropna(subset=["t_methods"])
dv = np.vstack(d.coord.values)[:, 2]
r, p = stats.pearsonr(dv, d.t_methods)
print(f"Pearson of t (methods) with DV (dorsal +): r = {r:.3f}, p = {p:.3g}; negative t (higher before ignored) in the ventral half: "
f"{int((d.t_methods[dv < np.median(dv)] < 0).sum())} of {int((dv < np.median(dv)).sum())}, dorsal half {int((d.t_methods[dv >= np.median(dv)] < 0).sum())} of {int((dv >= np.median(dv)).sum())}")
Analyses need at least 100 neurons (Methods, Analyzing relationships with space).
respond-versus-ignore t (methods regressors): n = 116 neurons from 14 mice; linear R2 = 0.029, permutation p = 0.3551; unit gradient (|ML|, AP posterior +, DV dorsal +) = [0.22 0.479 0.85 ]; kNN cross-validated R2 = 0.012, p = 0.0470
respond-versus-ignore t (code regressors): n = 116 neurons from 14 mice; linear R2 = 0.030, permutation p = 0.3361; unit gradient (|ML|, AP posterior +, DV dorsal +) = [0.175 0.508 0.844]; kNN cross-validated R2 = 0.010, p = 0.0500
respond-versus-ignore t (drift regressors): n = 116 neurons from 14 mice; linear R2 = 0.029, permutation p = 0.3417; unit gradient (|ML|, AP posterior +, DV dorsal +) = [-0.21 -0.177 0.962]; kNN cross-validated R2 = -0.011, p = 0.0819 Pearson of t (methods) with DV (dorsal +): r = 0.158, p = 0.0897; negative t (higher before ignored) in the ventral half: 41 of 58, dorsal half 32 of 58
Result: not reproduced. Over 116 neurons with CCF coordinates (14 mice), the linear spatial model of the respond-versus-ignore t gives R2 = 0.029 (permutation p = 0.36; code regressors 0.030, p = 0.34; drift stand-in 0.029, p = 0.34), against 0.152 (p = 1.4e-3). The gradient points dorsally, as the claim's direction requires, and t correlates with DV at r = 0.158 (p = 0.09); 41 of 58 ventral neurons and 32 of 58 dorsal neurons fire more before ignored cues. The kNN predictability is R2 = 0.012 (p = 0.047) against the paper's 0.0557 (p = 8.4e-3).
fig5d-ignore-on-anatomy-axes¶
Respond-versus-ignore t-statistics vary along the primary spatial axes of axonal projections and gene expression (r = 0.23 for each).
# Axes printed by F_spatial-axis-comparison.ipynb (cell 25) in the same frame (|ML|, AP posterior +,
# DV dorsal +). As the claims file has it since a reader's answer (questions/001950.yaml): b_z is the
# retrograde-tracing (LDA) axis, the legend's left value, and b_y the MERFISH (CCA) axis, the right value.
AXES = {"b_z retrograde LDA, left [0.024, 0.332, 0.943]": np.array([0.02394424, 0.33210898, 0.94293706]),
"b_y MERFISH CCA, right [-0.248, 0.499, 0.830]": np.array([-0.24792694, 0.49899099, 0.83038559]),
"b_x waveform [0.345, 0.228, 0.910]": np.array([0.34495102, 0.2281558, 0.91046896])}
ANAT = list(AXES)[:2]
def against_expected(res, expected):
"""Each anatomical axis against its expected r (claims file order: projection axis, then gene expression)."""
for name, (val, tol) in zip(ANAT, expected):
r, p = res[name]
print(f" {name.split(' [')[0]}: r = {r:.3f} against {val} +- {tol}: within {abs(r - val) <= tol}; "
f"positive with p < 0.05: {r > 0 and p < 0.05}")
def on_axes(df, col):
d = df.dropna(subset=[col])
X = np.vstack(d.coord.values)
X = X - X.mean(0)
out = {}
for name, ax in AXES.items():
r, p = stats.pearsonr(X @ ax, d[col])
out[name] = (r, p)
print(f" {name}: r = {r:.3f}, p = {p:.3g} (n = {len(d)})")
return out
for col in ["t_methods", "t_code", "t_drift"]:
print(f"respond-versus-ignore t ({col[2:]} regressors):")
against_expected(on_axes(hit_ccf, col), [(0.23, 0.023), (0.23, 0.023)])
respond-versus-ignore t (methods regressors):
b_z retrograde LDA, left [0.024, 0.332, 0.943]: r = 0.167, p = 0.074 (n = 116)
b_y MERFISH CCA, right [-0.248, 0.499, 0.830]: r = 0.165, p = 0.0762 (n = 116)
b_x waveform [0.345, 0.228, 0.910]: r = 0.167, p = 0.074 (n = 116)
b_z retrograde LDA, left: r = 0.167 against 0.23 +- 0.023: within False; positive with p < 0.05: False
b_y MERFISH CCA, right: r = 0.165 against 0.23 +- 0.023: within False; positive with p < 0.05: False
respond-versus-ignore t (code regressors):
b_z retrograde LDA, left [0.024, 0.332, 0.943]: r = 0.170, p = 0.0683 (n = 116)
b_y MERFISH CCA, right [-0.248, 0.499, 0.830]: r = 0.169, p = 0.0693 (n = 116)
b_x waveform [0.345, 0.228, 0.910]: r = 0.169, p = 0.0693 (n = 116)
b_z retrograde LDA, left: r = 0.170 against 0.23 +- 0.023: within False; positive with p < 0.05: False
b_y MERFISH CCA, right: r = 0.169 against 0.23 +- 0.023: within False; positive with p < 0.05: False
respond-versus-ignore t (drift regressors):
b_z retrograde LDA, left [0.024, 0.332, 0.943]: r = 0.162, p = 0.0823 (n = 116)
b_y MERFISH CCA, right [-0.248, 0.499, 0.830]: r = 0.157, p = 0.0932 (n = 116)
b_x waveform [0.345, 0.228, 0.910]: r = 0.159, p = 0.0873 (n = 116)
b_z retrograde LDA, left: r = 0.162 against 0.23 +- 0.023: within False; positive with p < 0.05: False
b_y MERFISH CCA, right: r = 0.157 against 0.23 +- 0.023: within False; positive with p < 0.05: False
Result: not reproduced. The respond-versus-ignore t correlates with position along the retrograde (LDA) axis b_z at r = 0.167 (p = 0.074) and along the MERFISH (CCA) axis b_y at r = 0.165 (p = 0.076), positive as in the paper but below 0.23 +- 0.023 and not significant; the code regressors and the drift stand-in give r = 0.157 to 0.170, p = 0.068 to 0.093. Both expected values are 0.23, so the pairing of axes and values, corrected in the claims file after a reader's answer, does not change the outcome. On the 207 units in sessions passing the refitted aN and bias criteria both r are within tolerance and significant (0.231, p = 0.024, and 0.235, p = 0.022), but not on the 229 units of the pooled fit (0.184 and 0.185, p = 0.06) or the draft's units (0.163 and 0.162, p = 0.10); the outcome on the main population stands, resting on the choice of population.
fig5g-switch-dorsal¶
Neurons with higher activity in the 500 ms after the go cue on switch than on stay choices lie more dorsal in LC (114 cells, 15 mice; linear model R2 = 0.168).
def switch_table(units):
"""Per unit, switch-versus-stay regressions of the rate 0.01 to 0.5 s after the go cue."""
sw_rows = []
for _, c in units.iterrows():
sp = spk[(c.path, c.row)]
g = trials_by_path[c.path]
rate = lcne.rate_in_windows(sp, g.goCue_start_time.values, 0.01, 0.5)
side = 2 * g.choice_right.values - 1
trial_idx = np.arange(len(g), dtype=float)
row = {"path": c.path, "row": c.row, "subject": c.subject}
for sdef in ["switch_prev_responded", "switch_prev_trial"]:
s_ = g[sdef].values
ok = np.isfinite(s_)
row[f"t_{sdef}_methods"], row[f"p_{sdef}_methods"], _ = lcne.ols_t(rate[ok], [s_[ok]])
row[f"t_{sdef}_code"], _, _ = lcne.ols_t(rate[ok], [s_[ok], side[ok], s_[ok] * side[ok]])
row[f"t_{sdef}_drift"], _, _ = lcne.ols_t(rate[ok], [s_[ok], trial_idx[ok]])
sw_rows.append(row)
return pd.DataFrame(sw_rows)
SW = switch_table(cells)
SW_COLS = [f"t_{a}_{b}" for a in ["switch_prev_responded", "switch_prev_trial"] for b in ["methods", "code"]]
# Added after verification round 1: the trial index as a stand-in drift regressor, with the Methods' regressor.
SW_DRIFT = [f"t_{a}_drift" for a in ["switch_prev_responded", "switch_prev_trial"]]
for col in SW_COLS + SW_DRIFT:
print(f"{col}: positive (higher on switch) in {int((SW[col] > 0).sum())} of {int(SW[col].notna().sum())}")
sw_ccf = ccf_cells.merge(SW, on=["path", "row", "subject"])
for i, col in enumerate(SW_COLS + SW_DRIFT):
spatial(sw_ccf, col, col, seed=10 + i)
t_switch_prev_responded_methods: positive (higher on switch) in 155 of 252 t_switch_prev_responded_code: positive (higher on switch) in 154 of 252 t_switch_prev_trial_methods: positive (higher on switch) in 162 of 252 t_switch_prev_trial_code: positive (higher on switch) in 158 of 252 t_switch_prev_responded_drift: positive (higher on switch) in 161 of 252 t_switch_prev_trial_drift: positive (higher on switch) in 164 of 252
t_switch_prev_responded_methods: n = 127 neurons from 16 mice; linear R2 = 0.022, permutation p = 0.4375; unit gradient (|ML|, AP posterior +, DV dorsal +) = [ 0.823 -0.568 -0.004]; kNN cross-validated R2 = -0.004, p = 0.0689
t_switch_prev_responded_code: n = 127 neurons from 16 mice; linear R2 = 0.013, permutation p = 0.6405; unit gradient (|ML|, AP posterior +, DV dorsal +) = [ 0.913 -0.121 0.391]; kNN cross-validated R2 = -0.018, p = 0.0959
t_switch_prev_trial_methods: n = 127 neurons from 16 mice; linear R2 = 0.031, permutation p = 0.2689; unit gradient (|ML|, AP posterior +, DV dorsal +) = [ 0.84 -0.173 0.515]; kNN cross-validated R2 = 0.030, p = 0.0190
t_switch_prev_trial_code: n = 127 neurons from 16 mice; linear R2 = 0.051, permutation p = 0.0910; unit gradient (|ML|, AP posterior +, DV dorsal +) = [0.628 0.282 0.726]; kNN cross-validated R2 = 0.008, p = 0.0370
t_switch_prev_responded_drift: n = 127 neurons from 16 mice; linear R2 = 0.015, permutation p = 0.5865; unit gradient (|ML|, AP posterior +, DV dorsal +) = [ 0.396 -0.896 0.202]; kNN cross-validated R2 = -0.007, p = 0.0609
t_switch_prev_trial_drift: n = 127 neurons from 16 mice; linear R2 = 0.055, permutation p = 0.0682; unit gradient (|ML|, AP posterior +, DV dorsal +) = [ 0.069 -0.086 0.994]; kNN cross-validated R2 = 0.064, p = 0.0080
Result: not reproduced. Under none of the six readings (four from the criterion and two with the trial index as a stand-in drift regressor) does the linear spatial model of the switch-versus-stay t reach p < 0.05: R2 = 0.013 to 0.055, p = 0.068 to 0.64 (127 neurons, 16 mice), against R2 = 0.168 (p = 3.0e-4). The two readings with switches against the previous trial and the code's regressors or the drift stand-in come nearest (R2 0.051, p = 0.091, and 0.055, p = 0.068) and have dorsal gradients (DV components 0.726 and 0.994). The kNN test gives p = 0.008 to 0.096. 154 to 164 of 252 neurons fire more on switch trials. On the smaller populations of the sensitivity section the best reading reaches p = 0.027 to 0.047 with R2 0.072 to 0.084, still far below 0.168.
fig5h-switch-on-anatomy-axes¶
Switch-versus-stay t-statistics vary along the primary spatial axes of axonal projections (r = 0.32) and gene expression (r = 0.30).
for col in SW_COLS + SW_DRIFT:
print(f"{col}:")
against_expected(on_axes(sw_ccf, col), [(0.32, 0.032), (0.30, 0.030)])
t_switch_prev_responded_methods:
b_z retrograde LDA, left [0.024, 0.332, 0.943]: r = -0.034, p = 0.706 (n = 127)
b_y MERFISH CCA, right [-0.248, 0.499, 0.830]: r = -0.055, p = 0.536 (n = 127)
b_x waveform [0.345, 0.228, 0.910]: r = -0.016, p = 0.858 (n = 127)
b_z retrograde LDA, left: r = -0.034 against 0.32 +- 0.032: within False; positive with p < 0.05: False
b_y MERFISH CCA, right: r = -0.055 against 0.3 +- 0.03: within False; positive with p < 0.05: False
t_switch_prev_responded_code:
b_z retrograde LDA, left [0.024, 0.332, 0.943]: r = 0.072, p = 0.423 (n = 127)
b_y MERFISH CCA, right [-0.248, 0.499, 0.830]: r = 0.059, p = 0.508 (n = 127)
b_x waveform [0.345, 0.228, 0.910]: r = 0.084, p = 0.35 (n = 127)
b_z retrograde LDA, left: r = 0.072 against 0.32 +- 0.032: within False; positive with p < 0.05: False
b_y MERFISH CCA, right: r = 0.059 against 0.3 +- 0.03: within False; positive with p < 0.05: False
t_switch_prev_trial_methods:
b_z retrograde LDA, left [0.024, 0.332, 0.943]: r = 0.138, p = 0.123 (n = 127)
b_y MERFISH CCA, right [-0.248, 0.499, 0.830]: r = 0.120, p = 0.178 (n = 127)
b_x waveform [0.345, 0.228, 0.910]: r = 0.151, p = 0.0897 (n = 127)
b_z retrograde LDA, left: r = 0.138 against 0.32 +- 0.032: within False; positive with p < 0.05: False
b_y MERFISH CCA, right: r = 0.120 against 0.3 +- 0.03: within False; positive with p < 0.05: False
t_switch_prev_trial_code:
b_z retrograde LDA, left [0.024, 0.332, 0.943]: r = 0.211, p = 0.0171 (n = 127)
b_y MERFISH CCA, right [-0.248, 0.499, 0.830]: r = 0.203, p = 0.0223 (n = 127)
b_x waveform [0.345, 0.228, 0.910]: r = 0.219, p = 0.0133 (n = 127)
b_z retrograde LDA, left: r = 0.211 against 0.32 +- 0.032: within False; positive with p < 0.05: True
b_y MERFISH CCA, right: r = 0.203 against 0.3 +- 0.03: within False; positive with p < 0.05: True
t_switch_prev_responded_drift:
b_z retrograde LDA, left [0.024, 0.332, 0.943]: r = 0.045, p = 0.612 (n = 127)
b_y MERFISH CCA, right [-0.248, 0.499, 0.830]: r = 0.030, p = 0.737 (n = 127)
b_x waveform [0.345, 0.228, 0.910]: r = 0.051, p = 0.566 (n = 127)
b_z retrograde LDA, left: r = 0.045 against 0.32 +- 0.032: within False; positive with p < 0.05: False
b_y MERFISH CCA, right: r = 0.030 against 0.3 +- 0.03: within False; positive with p < 0.05: False
t_switch_prev_trial_drift:
b_z retrograde LDA, left [0.024, 0.332, 0.943]: r = 0.229, p = 0.00965 (n = 127)
b_y MERFISH CCA, right [-0.248, 0.499, 0.830]: r = 0.220, p = 0.0129 (n = 127)
b_x waveform [0.345, 0.228, 0.910]: r = 0.228, p = 0.00988 (n = 127)
b_z retrograde LDA, left: r = 0.229 against 0.32 +- 0.032: within False; positive with p < 0.05: True
b_y MERFISH CCA, right: r = 0.220 against 0.3 +- 0.03: within False; positive with p < 0.05: True
Result: partially reproduced. With switches against the previous trial, the switch-versus-stay t correlates positively and significantly with both anatomical axes under the code's regressors (r = 0.211, p = 0.017, along the retrograde (LDA) axis b_z, and r = 0.203, p = 0.022, along the MERFISH (CCA) axis b_y) and under the Methods' regressor with the trial-index drift stand-in (r = 0.229, p = 0.0096, and 0.220, p = 0.013), against 0.32 +- 0.032 and 0.30 +- 0.030: significant but outside tolerance. The other four readings give r = -0.055 to 0.138, none significant. On the populations of the sensitivity section the largest values are 0.270 and 0.259 (p < 0.01), still outside.
fig5k-cortical-input-switch¶
LC-NE axonal fluorescence in prelimbic cortex and spiking of LC-NE neurons projecting to cortex are higher on switch than on stay choices.
fp_rows = []
for s in sessions:
if s["fp"] is None:
continue
t, sig_, iso = s["fp"]
z = (sig_ - np.nanmean(sig_)) / np.nanstd(sig_)
zi = (iso - np.nanmean(iso)) / np.nanstd(iso)
g = lcne.go_trials(s["trials"])
gc = g.goCue_start_time.values
inc = window_mean(t, z, gc, 0, 0.75) - window_mean(t, z, gc, -1.0, 0)
# quality: mean go-cue increase of the z-scored signal above 0.5 (photometry_combine.py threshold)
row = {"path": s["path"], "subject": s["subject"], "go_increase": np.nanmean(inc), "n_go": len(gc)}
y = window_mean(t, z, gc, 0, 0.75)
yi = window_mean(t, zi, gc, 0, 0.75)
outcome = g.rewarded.values.astype(float)
for sdef in ["switch_prev_responded", "switch_prev_trial"]:
s_ = g[sdef].values
ok = np.isfinite(s_)
row[f"t_{sdef}_methods"], _, _ = lcne.ols_t(y[ok], [s_[ok], yi[ok]])
row[f"t_{sdef}_code"], _, _ = lcne.ols_t(y[ok], [s_[ok], outcome[ok]])
yb = window_mean(t, z, gc, -2.0, 0)
yib = window_mean(t, zi, gc, -2.0, 0)
hit = g.responded.values.astype(float)
row["t_hit_methods"], _, _ = lcne.ols_t(yb, [hit, yib])
row["t_hit_noiso"], _, _ = lcne.ols_t(yb, [hit])
fp_rows.append(row)
FP = pd.DataFrame(fp_rows)
FPq = FP[FP.go_increase > 0.5]
print(f"PL photometry sessions: {len(FP)} from {FP.subject.nunique()} mice; passing the 0.5 z go-cue threshold: {len(FPq)} from {FPq.subject.nunique()} mice")
print("Go-cue increase (z) over sessions: min", FP.go_increase.min().round(2), "median", FP.go_increase.median().round(2), "max", FP.go_increase.max().round(2))
for thr in [0.25, 0.5, 1.0]:
print(f" sessions above {thr}: {int((FP.go_increase > thr).sum())}")
fk_rows = []
for col in SW_COLS:
fp_pos = int((FPq[col] > 0).sum())
fp_neg = int((FPq[col] <= 0).sum())
nr_pos = int((SW[col] > 0).sum())
nr_neg = int((SW[col] <= 0).sum())
odds, p = stats.fisher_exact([[fp_pos, fp_neg], [nr_pos, nr_neg]])
fk_rows.append({"reading": col, "photometry positive": fp_pos, "photometry not positive": fp_neg,
"neurons positive": nr_pos, "neurons not positive": nr_neg, "Fisher odds": odds, "Fisher p": p})
print(pd.DataFrame(fk_rows).round(5).to_string(index=False))
print("Per mouse, photometry sessions with positive switch t (switch against previous responded, methods regressors):")
print(FPq.groupby("subject").t_switch_prev_responded_methods.apply(lambda v: f"{int((v > 0).sum())}/{len(v)}").to_string())
col = "t_switch_prev_responded_methods"
for thr in [0.25, 1.0]:
d = FP[FP.go_increase > thr]
odds, p = stats.fisher_exact([[int((d[col] > 0).sum()), int((d[col] <= 0).sum())], [int((SW[col] > 0).sum()), int((SW[col] <= 0).sum())]])
print(f"Threshold {thr} z ({col}): photometry positive {int((d[col] > 0).sum())}/{len(d)} from {d.subject.nunique()} mice; Fisher p = {p:.2g}")
print("Cortex-projecting neurons (antidromic identification) are not marked in the dandiset; reading (ii) cannot be run.")
PL photometry sessions: 136 from 12 mice; passing the 0.5 z go-cue threshold: 63 from 7 mice
Go-cue increase (z) over sessions: min -0.68 median 0.45 max 1.41
sessions above 0.25: 94
sessions above 0.5: 63
sessions above 1.0: 13
reading photometry positive photometry not positive neurons positive neurons not positive Fisher odds Fisher p
t_switch_prev_responded_methods 54 9 155 97 3.75484 0.00018
t_switch_prev_responded_code 54 9 154 98 3.81818 0.00017
t_switch_prev_trial_methods 55 8 162 90 3.81944 0.00025
t_switch_prev_trial_code 55 8 158 94 4.09019 0.00014
Per mouse, photometry sessions with positive switch t (switch against previous responded, methods regressors):
subject
669492 13/15
699462 11/12
699472 5/7
749472 7/9
749624 5/5
754896 6/7
754898 7/8
Threshold 0.25 z (t_switch_prev_responded_methods): photometry positive 73/94 from 11 mice; Fisher p = 0.005
Threshold 1.0 z (t_switch_prev_responded_methods): photometry positive 10/13 from 3 mice; Fisher p = 0.38
Cortex-projecting neurons (antidromic identification) are not marked in the dandiset; reading (ii) cannot be run.
Result: partially reproduced. Of 63 PL photometry sessions passing the quality threshold (7 mice), 54 or 55 have higher fluorescence on switch than on stay choices, against 154 to 162 of the 252 neurons; Fisher's exact test gives p = 1.4e-4 to 2.5e-4 under every reading (paper p = 7.8e-5). Every one of the 7 mice has mostly positive sessions. The Methods give the 0.5 z threshold, not the window it is measured in; the window here is 0 to 0.75 s after the go cue against the second before it, and at thresholds of 0.25 z (94 sessions) and 1.0 z (13 sessions) Fisher's p is 0.005 (73 of 94 positive, 11 mice) and 0.38 (10 of 13, 3 mice). The cortex-projecting neurons, the other half of the statement and of reading (ii), are not marked in the dandiset and were not tested.
figs17i-baseline-axons-vs-spiking¶
Before go cues, axonal fluorescence differs from single-neuron spiking in how it relates to responding (Fisher p = 4.2e-4), while cortex-projecting neurons do not differ significantly from the population of single neurons.
rng17 = np.random.default_rng(17)
def fisher_perm(a, b, n_perm=5000):
a, b = np.asarray(a) > 0, np.asarray(b) > 0
obs = stats.fisher_exact([[a.sum(), (~a).sum()], [b.sum(), (~b).sum()]])[1]
pool = np.concatenate([a, b])
null = []
for _ in range(n_perm):
pr = rng17.permutation(pool)
x, y = pr[:len(a)], pr[len(a):]
null.append(stats.fisher_exact([[x.sum(), (~x).sum()], [y.sum(), (~y).sum()]])[1])
return obs, (1 + np.sum(np.array(null) <= obs)) / (n_perm + 1)
for fcol, ncol in [("t_hit_methods", "t_methods"), ("t_hit_methods", "t_code"), ("t_hit_noiso", "t_methods")]:
a = FPq[fcol].dropna().values
b = HIT[ncol].dropna().values
p_f, p_perm = fisher_perm(a, b)
pa, pb = np.mean(a > 0), np.mean(b > 0)
pp = (np.sum(a > 0) + np.sum(b > 0)) / (len(a) + len(b))
zval = (pa - pb) / np.sqrt(pp * (1 - pp) * (1 / len(a) + 1 / len(b)))
print(f"photometry {fcol} ({len(a)} sessions, {pa:.2f} positive) against neurons {ncol} ({len(b)}, {pb:.2f} positive): "
f"Fisher p = {p_f:.3g}, label-permutation p = {p_perm:.4f}; two-proportion z = {zval:.2f}, p = {2 * stats.norm.sf(abs(zval)):.3g}")
print("Cortex-projecting neurons are not marked in the dandiset; the second part (Welch and Fisher tests against the other neurons) cannot be run.")
photometry t_hit_methods (63 sessions, 0.40 positive) against neurons t_methods (225, 0.26 positive): Fisher p = 0.0403, label-permutation p = 0.0406; two-proportion z = 2.15, p = 0.0313
photometry t_hit_methods (63 sessions, 0.40 positive) against neurons t_code (225, 0.25 positive): Fisher p = 0.0264, label-permutation p = 0.0302; two-proportion z = 2.31, p = 0.021
photometry t_hit_noiso (63 sessions, 0.41 positive) against neurons t_methods (225, 0.26 positive): Fisher p = 0.0193, label-permutation p = 0.0216; two-proportion z = 2.39, p = 0.0168 Cortex-projecting neurons are not marked in the dandiset; the second part (Welch and Fisher tests against the other neurons) cannot be run.
Result: partially reproduced. The sign of the respond-versus-ignore t differs between photometry sessions (40% positive of 63) and neurons (26% of 225): Fisher p = 0.040 with label permutation p = 0.041 (code regressors 0.026 and 0.030; without the isosbestic regressor 0.019 and 0.022), weaker than the paper's 4.2e-4. The two-proportion z-test of the Methods gives p = 0.017 to 0.031. The absence for cortex-projecting neurons cannot be tested.
figs14-waveform-space¶
Dorsal LC-NE neurons have more symmetric spike waveforms and longer peak-to-trough times than ventral neurons; slope symmetry is spatially organized (kNN and linear p = 5.0e-4).
from scipy.signal import butter, sosfiltfilt
MS_PER_SAMPLE = 1000 / 30000 # waveform_generation_np.py
# Variant added after verification round 1: the Methods' 50 to 8,000 Hz band applied to the stored
# mean waveform (filtering is linear, so filtering the mean equals the mean of filtered spikes, up to
# edge effects on a short snippet); a third-order zero-phase Butterworth filter is a standard choice.
BANDPASS = butter(3, [50, 8000], btype="bandpass", fs=30000, output="sos")
def wf_features(wf, peak_raw):
"""Port of the feature loop of waveform_generation_np.py (post_w, post_trough_slope,
symmetry_slope_div_log) for one peak-channel mean waveform."""
wf = np.asarray(wf, dtype=float)
bl = np.nanmean(wf[:5])
peak = peak_raw - bl
wf = wf - bl
pi = int(np.argmin(wf))
if abs(wf[0] - wf[-1]) > 50 or pi == 0 or pi >= len(wf) - 1:
return np.nan, np.nan, np.nan
if peak < 0:
post_trough, post_i = np.max(wf[pi:]), np.argmax(wf[pi:]) + 1
pre_trough, pre_i = np.max(wf[:pi]), pi - np.argmax(wf[:pi])
else:
post_trough, post_i = np.min(wf[pi:]), np.argmin(wf[pi:]) + 1
pre_trough, pre_i = np.min(wf[:pi]), pi - np.argmin(wf[:pi])
slope_post = ((peak - post_trough) / peak) / (post_i * MS_PER_SAMPLE)
slope_pre = ((peak - pre_trough) / peak) / (pre_i * MS_PER_SAMPLE)
trough_slope = (post_trough / peak) / (post_i * MS_PER_SAMPLE)
return post_i * MS_PER_SAMPLE, trough_slope, np.log(slope_pre / slope_post + 1e-6)
wrows = []
for s in sessions:
if s["units"] is None or s["waveforms"] is None:
continue
u = s["units"].set_index("row")
for r, wf in s["waveforms"].items():
ur = u.loc[r]
if ur.probe != "NP" or not np.isfinite(float(ur.get("x_coordinate_in_ccf_space", np.nan))):
continue
isi = float(ur.get("isi_violations_ratio", np.nan))
lat = float(ur["spike_latency_at_maximum_p(response_cond_laser)"])
if not (isi <= 0.5 and float(ur.peak) < -50 and 0.005 <= lat <= 0.02):
continue
wf = np.asarray(wf, dtype=float)
wff = sosfiltfilt(BANDPASS, wf - wf[:5].mean())
pw, ts, sym = wf_features(wf, float(np.min(wf)))
pwf, tsf, symf = wf_features(wff, float(np.min(wff)))
wrows.append({"subject": s["subject"], "post_w_ms": pw, "post_trough_slope": ts, "symmetry_slope_div_log": sym,
"post_w_ms_filtered": pwf, "post_trough_slope_filtered": tsf, "symmetry_slope_div_log_filtered": symf,
"wf_min": float(np.min(wf) - np.mean(wf[:5])), "peak_col": float(ur.peak), "n_samples": len(wf),
"edge_diff": abs(wf[0] - wf[-1]), "coord": lcne.ccf_lps(pd.DataFrame([ur]))[0]})
WF = pd.DataFrame(wrows)
print(f"Neuropixels units under the waveform criteria (waveform_all.json: ISI <= 0.5, peak < -50 uV, latency 5-20 ms) with CCF: {len(WF)} from {WF.subject.nunique()} mice")
print(f"Waveform amplitude check: {WF.n_samples.iloc[0]} samples per waveform; trough relative to the first 5 samples {WF.wf_min.min():.1f} to {WF.wf_min.max():.1f}, "
f"against the units table's peak (uV) {WF.peak_col.min():.1f} to {WF.peak_col.max():.1f}; Pearson r = {np.corrcoef(WF.wf_min, WF.peak_col)[0, 1]:.3f}, "
f"median ratio {np.median(WF.wf_min / WF.peak_col):.2f}; waveforms failing the |first - last| > 50 gate: {int((WF.edge_diff > 50).sum())}")
print(WF[["post_w_ms", "post_trough_slope", "symmetry_slope_div_log", "post_w_ms_filtered", "post_trough_slope_filtered", "symmetry_slope_div_log_filtered"]].describe().round(3).to_string())
for suffix in ["", "_filtered"]:
print(f"\nFeatures from the {'stored' if not suffix else '50-8,000 Hz filtered'} mean waveforms:")
for i, col in enumerate(["symmetry_slope_div_log", "post_trough_slope", "post_w_ms"]):
d = WF.dropna(subset=[col + suffix])
spatial(d, col + suffix, col + suffix, seed=30 + i)
dv = np.vstack(d.coord.values)[:, 2]
r, p = stats.pearsonr(dv, d[col + suffix])
ra, pa = stats.pearsonr(dv, np.abs(d[col + suffix])) if col == "symmetry_slope_div_log" else (np.nan, np.nan)
print(f" Pearson with DV (dorsal +): r = {r:.3f}, p = {p:.3g}" + (f"; |log ratio| (0 = symmetric) with DV r = {ra:.3f}, p = {pa:.3g}" if col == "symmetry_slope_div_log" else ""))
Neuropixels units under the waveform criteria (waveform_all.json: ISI <= 0.5, peak < -50 uV, latency 5-20 ms) with CCF: 210 from 16 mice
Waveform amplitude check: 120 samples per waveform; trough relative to the first 5 samples -289.2 to -52.8, against the units table's peak (uV) -238.0 to -50.1; Pearson r = 0.950, median ratio 1.24; waveforms failing the |first - last| > 50 gate: 0
post_w_ms post_trough_slope symmetry_slope_div_log post_w_ms_filtered post_trough_slope_filtered symmetry_slope_div_log_filtered
count 210.000 210.000 210.000 210.000 210.000 210.000
mean 1.161 -0.278 0.581 1.148 -0.250 0.564
std 0.259 0.153 0.804 0.243 0.152 0.846
min 0.333 -0.807 -1.651 0.333 -0.759 -1.648
25% 1.000 -0.382 -0.055 1.000 -0.347 -0.141
50% 1.133 -0.276 0.638 1.133 -0.244 0.550
75% 1.300 -0.139 1.163 1.300 -0.116 1.217
max 2.000 -0.042 2.840 1.833 -0.014 2.616
Features from the stored mean waveforms:
symmetry_slope_div_log: n = 210 neurons from 16 mice; linear R2 = 0.049, permutation p = 0.0128; unit gradient (|ML|, AP posterior +, DV dorsal +) = [0.803 0.172 0.57 ]; kNN cross-validated R2 = -0.121, p = 0.4046 Pearson with DV (dorsal +): r = 0.156, p = 0.0237; |log ratio| (0 = symmetric) with DV r = 0.092, p = 0.186
post_trough_slope: n = 210 neurons from 16 mice; linear R2 = 0.053, permutation p = 0.0120; unit gradient (|ML|, AP posterior +, DV dorsal +) = [0.619 0.242 0.747]; kNN cross-validated R2 = -0.135, p = 0.4965 Pearson with DV (dorsal +): r = 0.201, p = 0.00351
post_w_ms: n = 210 neurons from 16 mice; linear R2 = 0.054, permutation p = 0.0100; unit gradient (|ML|, AP posterior +, DV dorsal +) = [0.571 0.366 0.735]; kNN cross-validated R2 = -0.068, p = 0.1229 Pearson with DV (dorsal +): r = 0.194, p = 0.00488 Features from the 50-8,000 Hz filtered mean waveforms:
symmetry_slope_div_log_filtered: n = 210 neurons from 16 mice; linear R2 = 0.054, permutation p = 0.0076; unit gradient (|ML|, AP posterior +, DV dorsal +) = [0.66 0.311 0.684]; kNN cross-validated R2 = -0.105, p = 0.3197 Pearson with DV (dorsal +): r = 0.186, p = 0.00684; |log ratio| (0 = symmetric) with DV r = 0.118, p = 0.0875
post_trough_slope_filtered: n = 210 neurons from 16 mice; linear R2 = 0.062, permutation p = 0.0040; unit gradient (|ML|, AP posterior +, DV dorsal +) = [0.631 0.25 0.734]; kNN cross-validated R2 = -0.113, p = 0.3736 Pearson with DV (dorsal +): r = 0.214, p = 0.00181
post_w_ms_filtered: n = 210 neurons from 16 mice; linear R2 = 0.050, permutation p = 0.0148; unit gradient (|ML|, AP posterior +, DV dorsal +) = [0.608 0.278 0.744]; kNN cross-validated R2 = -0.064, p = 0.1099 Pearson with DV (dorsal +): r = 0.192, p = 0.00513
Result: partially reproduced. Over 210 Neuropixels neurons with CCF (16 mice), slope symmetry has a linear spatial trend (R2 = 0.049, p = 0.013) but no kNN predictability (R2 = -0.121, p = 0.40), where the criterion needs both (paper p = 5.0e-4 for both). After filtering the mean waveforms at 50 to 8,000 Hz, as the Methods filter the traces, the same holds (linear p = 0.0076, kNN p = 0.32). The peak-to-trough time (post trough width) increases dorsally (r = 0.194 with DV, p = 0.0049; filtered 0.192). The log slope ratio increases dorsally (r = 0.156; filtered 0.186); whether that is "more symmetric" depends on how symmetry is read, and the two readings disagree: its distance from symmetry, |log ratio|, does not change with DV (r = 0.092, p = 0.19; filtered 0.118, p = 0.088). Post-trough slope has a linear trend (p = 0.012) and no kNN predictability (p = 0.50), as in the paper (p = 4.0e-3 and 0.59). The waveforms are in uV: their troughs (-289 to -53) follow the units table's peak (-238 to -50 uV, r = 0.950), so the 50 uV gate of the feature code applies as written, and no waveform fails it.
figs16-pupil-spiking¶
LC-NE spiking correlates with pupil size; pupil autocorrelation decays with a time constant of 3.37 +/- 1.03 s across sessions.
def pupil_tau(t, v, bin_s, max_lag_s=30.0, code_fit=False):
"""Autocorrelogram of the binned pupil trace and its exponential time constant. With
code_fit, as pupil_analysis.py and F_pupil_beh_ephys.ipynb (cell 25) at 971c1ca: lags to 20 s,
the autocorrelogram rescaled as (ac - ac[-1]) / (1 - ac[-1]), start tau 10 s, A and tau >= 0."""
ok = np.isfinite(v)
t, v = t[ok], v[ok]
if len(v) < 1000:
return np.nan
edges = np.arange(t[0], t[-1], bin_s)
idx = np.digitize(t, edges) - 1
sums = np.bincount(idx, weights=v, minlength=len(edges))
cnt = np.bincount(idx, minlength=len(edges))
x = np.where(cnt > 0, sums / np.maximum(cnt, 1), np.nan)
x = x - np.nanmean(x)
nlag = int(max_lag_s / bin_s)
ac = []
for k in range(nlag + 1):
a, b = x[:len(x) - k], x[k:]
m = np.isfinite(a) & np.isfinite(b)
ac.append(np.corrcoef(a[m], b[m])[0, 1])
ac = np.array(ac)
lags = np.arange(nlag + 1) * bin_s
f = lambda tt, A, tau, C: A * np.exp(-tt / tau) + C
try:
if code_fit:
y = (ac - ac[-1]) / (1 - ac[-1])
(A, tau, C), _ = curve_fit(f, lags, y, p0=(1, 10, 0), bounds=([0, 0, -np.inf], [np.inf, np.inf, np.inf]), maxfev=20000)
else:
(A, tau, C), _ = curve_fit(f, lags, ac, p0=(1, 3, 0), maxfev=20000)
return tau
except Exception:
return np.nan
tau_rows = []
for s in sessions:
if s["pupil"] is None:
continue
t, v = s["pupil"]
tau_rows.append({"path": s["path"], "subject": s["subject"], "tau 0.5 s bins, lags to 30 s": pupil_tau(t, v, 0.5),
"tau 0.1 s bins, lags to 30 s": pupil_tau(t, v, 0.1), "tau 0.5 s bins, lags to 20 s": pupil_tau(t, v, 0.5, 20.0),
"tau code fit (0.5 s bins, lags to 20 s, rescaled)": pupil_tau(t, v, 0.5, 20.0, code_fit=True)})
TAU = pd.DataFrame(tau_rows)
units_per_path = cells.path.value_counts()
for col in TAU.columns[2:]:
v = TAU[col].values
good = np.isfinite(v) & (v > 0) & (v < 100)
g = TAU[good]
w = g.path.map(units_per_path).fillna(0).values
wmean = np.sum(w * g[col]) / w.sum() if w.sum() else np.nan
print(f"{col}: {int(good.sum())} of {len(v)} sessions fitted; per session mean {g[col].mean():.2f} s, SD {g[col].std(ddof=1):.2f}, median {g[col].median():.2f}; "
f"within 3.37 +- 1.03: {abs(g[col].mean() - 3.37) <= 1.03}; weighted by selected units ({int(w.sum())} unit rows, as the code's 106 rows) {wmean:.2f} s")
def detrend(v):
x = np.arange(len(v), dtype=float)
return v - np.polyval(np.polyfit(x, v, 1), x)
pc_rows = []
for s in sessions:
if s["pupil"] is None or s["units"] is None:
continue
t, v = s["pupil"]
z = (v - np.nanmean(v)) / np.nanstd(v)
g = lcne.go_trials(s["trials"])
gc = g.goCue_start_time.values
pb = window_mean(t, v, gc, -1.0, 0)
gc_all = s["trials"].goCue_start_time.values
pb_code = window_mean(t, z, gc_all, -1.0, -0.1)
for _, c in cells[cells.path == s["path"]].iterrows():
sp = spk[(c.path, c.row)]
rb = lcne.rate_in_windows(sp, gc, -1.0, 0)
ok = np.isfinite(pb)
if ok.sum() < 20 or np.std(rb[ok]) == 0:
continue
row = {"subject": c.subject}
row["r"], row["p"] = stats.pearsonr(rb[ok], pb[ok])
row["r_detrended"], row["p_detrended"] = stats.pearsonr(detrend(rb[ok]), detrend(pb[ok]))
rc = lcne.rate_in_windows(sp, gc_all, -1.0, -0.01)
okc = np.isfinite(pb_code)
row["r_code"], row["p_code"] = stats.pearsonr(rc[okc], pb_code[okc])
pc_rows.append(row)
PC = pd.DataFrame(pc_rows)
for suffix, label in [("", "go cues, 1 s before (main)"), ("_detrended", "go cues, both linearly detrended over trials"),
("_code", "all cues, spikes -1 to -0.01 s, z-scored pupil -1 to -0.1 s (pupil_analysis.py)")]:
pos = int(((PC["p" + suffix] < 0.05) & (PC["r" + suffix] > 0)).sum())
neg = int(((PC["p" + suffix] < 0.05) & (PC["r" + suffix] < 0)).sum())
bt = stats.binomtest(pos, pos + neg, 0.5) if pos + neg else None
print(f"{label}: {len(PC)} neurons from {PC.subject.nunique()} mice; median r = {PC['r' + suffix].median():.3f}; significant positive {pos}, negative {neg}; "
f"binomial p = {bt.pvalue if bt else np.nan:.3g}")
print("By mouse (main; detrended), significant positive / negative of neurons:")
for subj, d in PC.groupby("subject"):
print(f" {subj}: {int(((d.p < 0.05) & (d.r > 0)).sum())}/{int(((d.p < 0.05) & (d.r < 0)).sum())} of {len(d)}, median r {d.r.median():.3f}; "
f"detrended {int(((d.p_detrended < 0.05) & (d.r_detrended > 0)).sum())}/{int(((d.p_detrended < 0.05) & (d.r_detrended < 0)).sum())}, median r {d.r_detrended.median():.3f}")
tau 0.5 s bins, lags to 30 s: 133 of 133 sessions fitted; per session mean 3.28 s, SD 1.01, median 3.07; within 3.37 +- 1.03: True; weighted by selected units (115 unit rows, as the code's 106 rows) 3.61 s tau 0.1 s bins, lags to 30 s: 133 of 133 sessions fitted; per session mean 3.21 s, SD 1.05, median 3.03; within 3.37 +- 1.03: True; weighted by selected units (115 unit rows, as the code's 106 rows) 3.56 s tau 0.5 s bins, lags to 20 s: 133 of 133 sessions fitted; per session mean 3.08 s, SD 0.96, median 2.91; within 3.37 +- 1.03: True; weighted by selected units (115 unit rows, as the code's 106 rows) 3.46 s tau code fit (0.5 s bins, lags to 20 s, rescaled): 133 of 133 sessions fitted; per session mean 3.08 s, SD 0.96, median 2.91; within 3.37 +- 1.03: True; weighted by selected units (115 unit rows, as the code's 106 rows) 3.46 s
go cues, 1 s before (main): 115 neurons from 4 mice; median r = -0.062; significant positive 4, negative 34; binomial p = 6.04e-07 go cues, both linearly detrended over trials: 115 neurons from 4 mice; median r = -0.065; significant positive 4, negative 39; binomial p = 3.11e-08 all cues, spikes -1 to -0.01 s, z-scored pupil -1 to -0.1 s (pupil_analysis.py): 115 neurons from 4 mice; median r = -0.067; significant positive 5, negative 35; binomial p = 1.38e-06 By mouse (main; detrended), significant positive / negative of neurons: ZS059: 0/2 of 3, median r -0.115; detrended 0/2, median r -0.120 ZS060: 0/0 of 2, median r -0.078; detrended 0/1, median r -0.060 ZS061: 2/22 of 61, median r -0.082; detrended 1/26, median r -0.080 ZS062: 2/10 of 49, median r -0.043; detrended 3/10, median r -0.036
Result: partially reproduced. The pupil autocorrelation time constant averages 3.28 s (SD 1.01) over 133 sessions in 0.5 s bins and 3.21 s in 0.1 s bins, within 3.37 +- 1.03. The code's procedure (lags to 20 s, the autocorrelogram rescaled by its last value, bounded fit) gives 3.08 s per session and 3.46 s weighted by the selected units, as the code averages over unit rows; all are within tolerance. The spike-pupil correlation before go cues goes the other way: of 115 selected neurons recorded with pupil (4 mice), 4 have significant positive and 34 significant negative correlations (binomial p = 6.0e-07; median r = -0.062). Linear detrending over trials (4 and 39) and the code's windows over all cues (5 and 35) give the same, and every mouse has more negative than positive significant neurons or none either way. The files hold no edge confidence, so the Methods' confidence threshold and bad-period exclusion could not be applied.
figs15q-spontaneous-vs-task-licks¶
LC-NE peak spike rates around spontaneous licks correlate with those around in-trial licks across neurons (r = 0.49).
# The code's procedure (F_spont_choice_lick_neuron.ipynb, cell 12 onwards, at 971c1ca): sensor licks
# cleaned of crosstalk and rebounds; lick trains per side, pooled; a train is in-trial when it starts
# 0 to 1.5 s after a go cue and spontaneous otherwise; kernel-smoothed rate around train starts
# (lcne.kernel_psth); the in-trial trace's mean from -5 to -4.05 s is subtracted from both traces;
# the peak is the maximum from -1 to 0.5 s; at least 5 spontaneous trains. The train gap is 0.5 s in
# the criterion (Methods, Lick bout detection) and 0.8 s in the code (load_licks default).
def lick_peaks(gap, in_trial_window=(0.0, 1.5)):
rows = []
for s in sessions:
if s["units"] is None or not (cells.path == s["path"]).any():
continue
L, R = lcne.clean_licks(s["licks"]["left"], s["licks"]["right"])
starts = np.sort(np.concatenate([lcne.lick_train_starts(L, gap), lcne.lick_train_starts(R, gap)]))
tr = s["trials"]
starts = starts[(starts > tr.start_time.min()) & (starts < tr.stop_time.max())]
gcs = tr.goCue_start_time.values[tr.go.values]
after = starts[:, None] - gcs[None, :]
in_trial = np.any((after >= in_trial_window[0]) & (after <= in_trial_window[1]), axis=1)
for _, c in cells[cells.path == s["path"]].iterrows():
sp = spk[(c.path, c.row)]
t_, m_in = lcne.kernel_psth(sp, starts[in_trial])
_, m_out = lcne.kernel_psth(sp, starts[~in_trial])
bl = np.nanmean(m_in[:20])
w = (t_ >= -1) & (t_ <= 0.5)
rows.append({"subject": c.subject, "n_in": int(in_trial.sum()), "n_spont": int((~in_trial).sum()),
"peak_in": np.nanmax(m_in[w] - bl), "peak_spont": np.nanmax(m_out[w] - bl)})
return pd.DataFrame(rows)
lk_res = []
for gap in [0.5, 0.8]:
LKc = lick_peaks(gap)
for min_n in [1, 5, 20]:
d = LKc[(LKc.n_spont >= min_n) & (LKc.n_in >= 1)].dropna(subset=["peak_in", "peak_spont"])
r, p = stats.pearsonr(d.peak_in, d.peak_spont)
lk_res.append({"train gap (s)": gap, "min spontaneous trains": min_n, "neurons": len(d), "mice": d.subject.nunique(), "Pearson r": round(r, 3),
"p": p, "Spearman rho": round(stats.spearmanr(d.peak_in, d.peak_spont)[0], 3), "within 0.49 +- 0.049": abs(r - 0.49) <= 0.049})
if gap == 0.5:
LK = LKc
print(pd.DataFrame(lk_res).to_string(index=False))
print("Trains per session (gap 0.5 s): in-trial median", int(LK.n_in.median()), "; spontaneous median", int(LK.n_spont.median()))
print("Peak rates (Hz, baseline-subtracted), gap 0.5 s: in-trial", LK.peak_in.min().round(2), "to", LK.peak_in.max().round(2),
"; spontaneous", LK.peak_spont.min().round(2), "to", LK.peak_spont.max().round(2))
# Earlier definition, kept as a variant: bouts of uncleaned licks split at 0.5 s; in-trial bouts start
# within the response window after any cue; spontaneous bouts start more than 1 s before or 5 s after
# every cue; peak of the mean rate in 50 ms bins from -0.5 to 0.5 s, without baseline subtraction.
BIN = 0.05
PSTH_EDGES = np.arange(-0.5, 0.5 + BIN, BIN)
def bouts(licks, gap=0.5):
licks = np.sort(licks)
if len(licks) == 0:
return licks
return licks[np.concatenate([[True], np.diff(licks) > gap])]
def peak_rate(sp, events):
if len(events) == 0:
return np.nan
counts = np.array([np.histogram(sp - e, PSTH_EDGES)[0] for e in events])
return counts.mean(0).max() / BIN
lk_rows = []
for s in sessions:
if s["units"] is None:
continue
licks = np.concatenate([s["licks"]["left"], s["licks"]["right"]])
b = bouts(licks)
tr = s["trials"]
cues = tr.goCue_start_time.values
win = np.nanmedian(tr.response_duration)
after = b[:, None] - cues[None, :]
in_trial = np.any((after >= 0) & (after <= win), axis=1)
near = np.any((after >= -1.0) & (after <= 5.0), axis=1)
spont = ~near & (b > tr.start_time.min()) & (b < tr.stop_time.max())
for _, c in cells[cells.path == s["path"]].iterrows():
sp = spk[(c.path, c.row)]
lk_rows.append({"subject": c.subject, "n_in": int(in_trial.sum()), "n_spont": int(spont.sum()),
"peak_in": peak_rate(sp, b[in_trial]), "peak_spont": peak_rate(sp, b[spont])})
LKo = pd.DataFrame(lk_rows)
for min_n in [5, 20]:
d = LKo[(LKo.n_in >= min_n) & (LKo.n_spont >= min_n)].dropna()
r, p = stats.pearsonr(d.peak_in, d.peak_spont)
print(f"Earlier definition, at least {min_n} bouts of each kind: n = {len(d)} ({d.subject.nunique()} mice); Pearson r = {r:.3f}, p = {p:.2g}")
train gap (s) min spontaneous trains neurons mice Pearson r p Spearman rho within 0.49 +- 0.049
0.5 1 252 21 0.580 4.813483e-24 0.430 False
0.5 5 252 21 0.580 4.813483e-24 0.430 False
0.5 20 243 21 0.583 1.496642e-23 0.424 False
0.8 1 252 21 0.608 7.983974e-27 0.458 False
0.8 5 252 21 0.608 7.983974e-27 0.458 False
0.8 20 227 21 0.618 2.667830e-25 0.460 False
Trains per session (gap 0.5 s): in-trial median 427 ; spontaneous median 75
Peak rates (Hz, baseline-subtracted), gap 0.5 s: in-trial 0.28 to 13.2 ; spontaneous 0.24 to 10.6
Earlier definition, at least 5 bouts of each kind: n = 229 (21 mice); Pearson r = 0.612, p = 6.2e-25 Earlier definition, at least 20 bouts of each kind: n = 127 (18 mice); Pearson r = 0.803, p = 6.4e-30
Result: partially reproduced. With the code's procedure (F_spont_choice_lick_neuron.ipynb: cleaned sensor licks, trains starting 0 to 1.5 s after a go cue counted as in-trial, kernel-smoothed rates, baseline subtracted, peak from -1 to 0.5 s), peak rates around spontaneous and in-trial lick trains correlate at r = 0.580 (p = 4.8e-24, 252 neurons) with the Methods' 0.5 s train gap and r = 0.608 with the code's 0.8 s gap; requiring at least 20 spontaneous trains gives 0.583 and 0.618. All are positive with p < 0.001 and above 0.49 +- 0.049. The earlier definition (no lick cleaning, spontaneous bouts away from every cue, 50 ms bins) gives 0.612 and 0.803 at 5 and 20 bouts of each kind. The code prefers licks detected from video, which the dandiset does not hold in that form; the lick-sensor fallback is used.
The Q-learning model¶
The claims below use the chosen value and the RPE of the paper's model, which the dandiset does not hold. The model (aind_stan_fit_sim at 89371ee, stan_qLearning_5params) is refitted here by maximum likelihood per session, with the same update and choice rule, Q starting at 0: the chosen value moves by aP or aN times the prediction error, the unchosen value is multiplied by aF, and P(right) = logistic(beta (Q_right - Q_left) + bias), as the Stan file has it. The paper fits it hierarchically in Stan, with mouse-level hyperparameters, 16 chains of 5,000 iterations, and averages each variable over at least 1,000 posterior draws (Methods, Behavioral model fitting; Extracting model parameters). That fit was not run: it needs cmdstan in the locked environment and its run time per mouse was not measured. The per-session maximum-likelihood fit is the standard non-hierarchical estimate of the same model; every outcome that uses it rests on this assumption.
# Q-learning variables per session: maximum-likelihood fit of stan_qLearning_5params to the
# responded trials of each session (a substitute for the paper's hierarchical fit).
q_by_path = {}
qrows = []
for s in sessions:
g = lcne.go_trials(s["trials"])
r = g[g.responded]
if len(r) < 30:
continue
x, nll = lcne.fit_q_session(r.choice_right.values, r.rewarded.values.astype(float))
Qs, pe, pr = lcne.q_trajectory(x, r.choice_right.values.astype(int), r.rewarded.values.astype(float))
c = r.choice_right.values.astype(int)
q_by_path[s["path"]] = pd.DataFrame({"trial": r.index, "Q_chosen": Qs[np.arange(len(c)), c], "RPE": pe,
"p_choice": np.where(c == 1, pr, 1 - pr)}).set_index("trial")
qrows.append({"path": s["path"], "subject": s["subject"], "aN": x[0], "aP": x[1], "aF": x[2], "beta": x[3], "bias": x[4],
"n": len(r), "nll_per_trial": nll / len(r), "accuracy": np.mean((pr > 0.5) == (c == 1))})
QP = pd.DataFrame(qrows)
print(f"Fitted {len(QP)} sessions; parameter medians:", QP[["aN", "aP", "aF", "beta", "bias"]].median().round(3).to_dict())
print("Fraction of choices predicted by the fitted model: median", QP.accuracy.median().round(3), "; sessions with aF at the bound 0:", int((QP.aF < 1e-3).sum()))
print("Sessions that would pass the code's aN >= 0.15 and |bias| <= 1.25 (beh_only.json), using these fits:",
int(((QP.aN >= 0.15) & (QP.bias.abs() <= 1.25)).sum()), "of", len(QP))
sel_q = QP[QP.path.isin(set(cells.path))]
print("Of the sessions of selected units:", int(((sel_q.aN >= 0.15) & (sel_q.bias.abs() <= 1.25)).sum()), "of", len(sel_q))
pass_q = set(QP[(QP.aN >= 0.15) & (QP.bias.abs() <= 1.25)].path)
print("Selected units in those sessions:", int(cells.path.isin(pass_q).sum()), "from", cells[cells.path.isin(pass_q)].subject.nunique(), "mice")
Fitted 382 sessions; parameter medians: {'aN': 0.252, 'aP': 0.602, 'aF': 0.223, 'beta': 4.216, 'bias': 0.045}
Fraction of choices predicted by the fitted model: median 0.91 ; sessions with aF at the bound 0: 107
Sessions that would pass the code's aN >= 0.15 and |bias| <= 1.25 (beh_only.json), using these fits: 261 of 382
Of the sessions of selected units: 95 of 112
Selected units in those sessions: 207 from 19 mice
The verifier asked how well the per-session fit recovers what the claims use. The cell below
simulates the model with 40 sessions' fitted parameters on those sessions' reward probabilities
(the trial table's reward_probabilityL/R), refits, and compares parameters and per-trial
variables. It then refits all sessions with partial pooling within each mouse
(lcne.fit_q_mouse), an empirical-Bayes approximation of the paper's hierarchical model ("Stan
was used to construct hierarchical models with mouse-level hyperparameters to govern
session-level parameters", Methods, Behavioral model fitting). Its variables (q_pool) are used
as a variant in the claims below and in the sensitivity section.
# Check of the per-session fit: simulate the model with each of 40 sessions' fitted parameters on
# that session's reward probabilities, refit, and compare parameters and per-trial variables.
sess_by_path = {s["path"]: s for s in sessions}
rngq = np.random.default_rng(64)
rec_rows = []
for path in rngq.choice(sorted(q_by_path), 40, replace=False):
g = lcne.go_trials(sess_by_path[path]["trials"])
r = g[g.responded]
true = QP.set_index("path").loc[path, ["aN", "aP", "aF", "beta", "bias"]].values.astype(float)
c, rw = lcne.simulate_q_session(true, r.reward_probabilityR.values / 100, r.reward_probabilityL.values / 100, rngq)
x, _ = lcne.fit_q_session(c, rw)
Qt, pet, _ = lcne.q_trajectory(true, c, rw)
Qf, pef, _ = lcne.q_trajectory(x, c, rw)
rec_rows.append({"path": path, "n": len(c), **{f"true_{k}": v for k, v in zip(["aN", "aP", "aF", "beta", "bias"], true)},
**{f"fit_{k}": v for k, v in zip(["aN", "aP", "aF", "beta", "bias"], x)},
"r_RPE": np.corrcoef(pet, pef)[0, 1], "r_Qchosen": np.corrcoef(Qt[np.arange(len(c)), c], Qf[np.arange(len(c)), c])[0, 1]})
REC = pd.DataFrame(rec_rows)
print(f"Parameter recovery over {len(REC)} simulated sessions ({REC.n.min()} to {REC.n.max()} trials):")
for k in ["aN", "aP", "aF", "beta", "bias"]:
print(f" {k}: Pearson r(true, fitted) = {np.corrcoef(REC['true_' + k], REC['fit_' + k])[0, 1]:.2f}; median |fitted - true| = {np.median(np.abs(REC['fit_' + k] - REC['true_' + k])):.3f}")
print(f"Per-trial variables, true against refitted parameters, median over sessions (min): RPE r = {REC.r_RPE.median():.3f} ({REC.r_RPE.min():.3f}); "
f"chosen value r = {REC.r_Qchosen.median():.3f} ({REC.r_Qchosen.min():.3f})")
# Partial pooling within each mouse (lcne.fit_q_mouse), an approximation of the hierarchical fit.
q_pool = {}
prow = []
for subj, paths in QP.groupby("subject").path:
data = []
for path in paths:
g = lcne.go_trials(sess_by_path[path]["trials"])
r = g[g.responded]
data.append((r.choice_right.values.astype(int), r.rewarded.values.astype(float), r.index))
for path, (c, rw, idx), x in zip(paths, data, lcne.fit_q_mouse([(c, rw) for c, rw, _ in data])):
Qs, pe, pr = lcne.q_trajectory(x, c, rw)
q_pool[path] = pd.DataFrame({"trial": idx, "Q_chosen": Qs[np.arange(len(c)), c], "RPE": pe,
"p_choice": np.where(c == 1, pr, 1 - pr)}).set_index("trial")
prow.append({"path": path, "subject": subj, "aN": x[0], "aP": x[1], "aF": x[2], "beta": x[3], "bias": x[4],
"r_RPE_ml": np.corrcoef(pe, q_by_path[path].RPE.values)[0, 1],
"r_Q_ml": np.corrcoef(Qs[np.arange(len(c)), c], q_by_path[path].Q_chosen.values)[0, 1]})
QPP = pd.DataFrame(prow)
print(f"\nPartial pooling: {len(QPP)} sessions of {QPP.subject.nunique()} mice; parameter medians:", QPP[["aN", "aP", "aF", "beta", "bias"]].median().round(3).to_dict())
print("Sessions with aF below 0.001: per-session fit", int((QP.aF < 1e-3).sum()), "; pooled", int((QPP.aF < 1e-3).sum()))
print(f"Per-trial variables, pooled against per-session fit, median over sessions (10th percentile): RPE r = {QPP.r_RPE_ml.median():.3f} ({QPP.r_RPE_ml.quantile(0.1):.3f}); "
f"chosen value r = {QPP.r_Q_ml.median():.3f} ({QPP.r_Q_ml.quantile(0.1):.3f})")
pass_q_pool = set(QPP[(QPP.aN >= 0.15) & (QPP.bias.abs() <= 1.25)].path)
print("Sessions passing aN >= 0.15 and |bias| <= 1.25 under the pooled fit:", len(pass_q_pool), "of", len(QPP),
"; selected units in them:", int(cells.path.isin(pass_q_pool).sum()))
Parameter recovery over 40 simulated sessions (213 to 851 trials): aN: Pearson r(true, fitted) = 0.78; median |fitted - true| = 0.044 aP: Pearson r(true, fitted) = 0.64; median |fitted - true| = 0.093 aF: Pearson r(true, fitted) = 0.56; median |fitted - true| = 0.122 beta: Pearson r(true, fitted) = 0.68; median |fitted - true| = 0.339 bias: Pearson r(true, fitted) = 0.96; median |fitted - true| = 0.137 Per-trial variables, true against refitted parameters, median over sessions (min): RPE r = 0.995 (0.593); chosen value r = 0.991 (0.190)
Partial pooling: 382 sessions of 41 mice; parameter medians: {'aN': 0.25, 'aP': 0.567, 'aF': 0.356, 'beta': 4.33, 'bias': 0.045}
Sessions with aF below 0.001: per-session fit 107 ; pooled 0
Per-trial variables, pooled against per-session fit, median over sessions (10th percentile): RPE r = 0.993 (0.974); chosen value r = 0.986 (0.946)
Sessions passing aN >= 0.15 and |bias| <= 1.25 under the pooled fit: 293 of 382 ; selected units in them: 229
The per-session fit recovers the per-trial variables the claims use far better than the parameters: on 40 simulated sessions the parameters are recovered with r = 0.56 (aF) to 0.96 (bias), but the RPE and chosen value computed with the refitted parameters correlate with the true ones at a median r of 0.995 and 0.991, and at worst 0.593 and 0.190. The partially pooled fit moves every aF off the bound at 0 (107 sessions there under the per-session fit), and its per-trial variables agree with the per-session fit's at a median r of 0.993 (RPE) and 0.986 (chosen value), 0.974 and 0.946 at the 10th percentile. Under the pooled fit, 293 sessions and 229 selected units pass the code's aN and bias criteria.
figs12-trials-per-session¶
Mice performed a few hundred trials per session (mean 342, range 94 to 558).
A trial is a go cue with a choice, counted as the code that draws Figure S12a counts it (the claims file, amended after a reader's answer): the rows makeSessionDF keeps with cut_interruptions=True, the longest stretch of choice trials without manual or extra water (F_behavior_w_FP.ipynb cell 19). The section comes after the model fit so that the code's two model-based session criteria can be shown as a variant with the refitted parameters.
# Trials per session as the code's session_len (Figure S12a): go cues with a choice in the
# longest stretch without manual or extra water (lcne.choice_trials).
recomp_diff, nogo_choice = 0, 0
crows = []
for s in sessions:
tr = s["trials"]
rc = lcne.recompute_interruptions(tr, s["deliveries"])
recomp_diff += int((rc.auto_manual_trial != tr.auto_manual_trial).sum() + (rc.extra_reward != tr.extra_reward).sum())
nogo_choice += int((~tr.go & tr.animal_response.isin([0, 1])).sum())
g = lcne.go_trials(tr)
crows.append({"path": s["path"], "n_cut": len(lcne.choice_trials(g)), "n_uncut": len(lcne.choice_trials(g, False)),
"interrupted": int((g.responded & (g.auto_manual_trial | g.extra_reward)).sum())})
C = S[["path", "subject", "kind", "go", "beh_ok"]].merge(pd.DataFrame(crows), on="path")
C = C.merge(QP[["path", "aN", "bias"]], on="path", how="left")
C["beh_ok_model"] = C.beh_ok & (C.aN >= 0.15) & (C.bias.abs() <= 1.25)
print("Interruption columns of the trial tables against their recomputation from the reward deliveries:",
recomp_diff, "rows differ")
print("No-go cues with a left or right response (the code's animal_response != 2 would keep them):", nogo_choice)
print("Sessions with an interruption among their choice trials:", int((C.interrupted > 0).sum()), "of", len(C),
"; choice trials dropped by the cut:", int((C.n_uncut - C.n_cut).sum()), "of", int(C.n_uncut.sum()))
def describe_counts(v):
v = np.asarray(v)
return f"n = {len(v)} sessions, mean {np.mean(v):.1f}, min {np.min(v)}, max {np.max(v)}"
lo, hi = 94 * 0.9, 558 * 1.1
sel_paths = set(cells.path)
readings = {"(a) sessions passing the computable beh_only.json criteria": C[C.beh_ok],
"(b) sessions of the selected units": C[C.path.isin(sel_paths)],
"(c) all sessions with a trial table": C,
"(a') (a) with the refitted model's aN and bias criteria": C[C.beh_ok_model],
"(a'') (a) with session_len >= 90 applied to the cut count": C[C.beh_ok & (C.n_cut >= 90)]}
res12 = []
for name, d in readings.items():
print(f"{name}: {d.subject.nunique()} mice")
for col, label in [("n_cut", "go cues with a choice, interruption cut (criterion)"),
("n_uncut", "go cues with a choice, no cut (variant)"), ("go", "all go cues (variant)")]:
v = d[col].values
ok_mean, ok_range = abs(np.mean(v) - 342) <= 34.2, (np.min(v) >= lo) and (np.max(v) <= hi)
res12.append({"reading": name.split(")")[0] + ")", "count": col, "sessions": len(v), "mean": round(np.mean(v), 1),
"min": int(np.min(v)), "max": int(np.max(v)), "mean_ok": ok_mean, "range_ok": ok_range})
print(f" {label}: {describe_counts(v)}; mean within 342 +- 34.2: {ok_mean}; "
f"range within {lo:.1f} to {hi:.1f}: {ok_range}")
print(pd.DataFrame(res12).to_string(index=False))
print("Reading (a) by kind (criterion count):")
for k, d in C[C.beh_ok].groupby("kind"):
print(f" {k}: {describe_counts(d.n_cut.values)}")
print("Code's set (F_behavior_w_FP.ipynb cell 11): 259 sessions, 32 mice; here (a)", int(C.beh_ok.sum()), "sessions,",
C[C.beh_ok].subject.nunique(), "mice; (a')", int(C.beh_ok_model.sum()), "sessions,", C[C.beh_ok_model].subject.nunique(), "mice")
print("Reading (a) sessions below 90 choice trials after the cut (the code applies session_len >= 90 to its own count):",
int((C[C.beh_ok].n_cut < 90).sum()))
fig, ax = plt.subplots(figsize=(5, 3))
bins = np.arange(0, C.n_cut.max() + 25, 25)
ax.hist(C.n_cut, bins=bins, color="0.75", label="(c) all sessions")
ax.hist(C[C.beh_ok].n_cut, bins=bins, color="0.35", label="(a) beh_only criteria")
ax.hist(C[C.path.isin(sel_paths)].n_cut, bins=bins, color="k", histtype="step", lw=1.5, label="(b) selected units")
for v in (94, 558):
ax.axvline(v, color="r", ls="--", lw=0.8)
ax.set_xlabel("go cues with a choice per session (interruption cut)")
ax.set_ylabel("sessions")
ax.legend(fontsize=7)
plt.tight_layout()
plt.show()
print("Plotted range:", C.n_cut.min(), "to", C.n_cut.max(), "trials; no points outside the axes.")
Interruption columns of the trial tables against their recomputation from the reward deliveries: 0 rows differ
No-go cues with a left or right response (the code's animal_response != 2 would keep them): 0
Sessions with an interruption among their choice trials: 49 of 383 ; choice trials dropped by the cut: 5513 of 154820
(a) sessions passing the computable beh_only.json criteria: 41 mice
go cues with a choice, interruption cut (criterion): n = 372 sessions, mean 393.0, min 52, max 851; mean within 342 +- 34.2: False; range within 84.6 to 613.8: False
go cues with a choice, no cut (variant): n = 372 sessions, mean 407.7, min 92, max 851; mean within 342 +- 34.2: False; range within 84.6 to 613.8: False
all go cues (variant): n = 372 sessions, mean 436.6, min 176, max 857; mean within 342 +- 34.2: False; range within 84.6 to 613.8: False
(b) sessions of the selected units: 21 mice
go cues with a choice, interruption cut (criterion): n = 112 sessions, mean 334.3, min 94, max 558; mean within 342 +- 34.2: True; range within 84.6 to 613.8: True
go cues with a choice, no cut (variant): n = 112 sessions, mean 360.6, min 128, max 558; mean within 342 +- 34.2: True; range within 84.6 to 613.8: True
all go cues (variant): n = 112 sessions, mean 380.3, min 176, max 586; mean within 342 +- 34.2: False; range within 84.6 to 613.8: True
(c) all sessions with a trial table: 41 mice
go cues with a choice, interruption cut (criterion): n = 383 sessions, mean 389.8, min 4, max 851; mean within 342 +- 34.2: False; range within 84.6 to 613.8: False
go cues with a choice, no cut (variant): n = 383 sessions, mean 404.2, min 9, max 851; mean within 342 +- 34.2: False; range within 84.6 to 613.8: False
all go cues (variant): n = 383 sessions, mean 433.4, min 94, max 857; mean within 342 +- 34.2: False; range within 84.6 to 613.8: False
(a') (a) with the refitted model's aN and bias criteria: 39 mice
go cues with a choice, interruption cut (criterion): n = 261 sessions, mean 387.1, min 74, max 804; mean within 342 +- 34.2: False; range within 84.6 to 613.8: False
go cues with a choice, no cut (variant): n = 261 sessions, mean 399.4, min 128, max 804; mean within 342 +- 34.2: False; range within 84.6 to 613.8: False
all go cues (variant): n = 261 sessions, mean 424.9, min 176, max 834; mean within 342 +- 34.2: False; range within 84.6 to 613.8: False
(a'') (a) with session_len >= 90 applied to the cut count: 40 mice
go cues with a choice, interruption cut (criterion): n = 368 sessions, mean 396.4, min 94, max 851; mean within 342 +- 34.2: False; range within 84.6 to 613.8: False
go cues with a choice, no cut (variant): n = 368 sessions, mean 410.4, min 128, max 851; mean within 342 +- 34.2: False; range within 84.6 to 613.8: False
all go cues (variant): n = 368 sessions, mean 438.0, min 176, max 857; mean within 342 +- 34.2: False; range within 84.6 to 613.8: False
reading count sessions mean min max mean_ok range_ok
(a) n_cut 372 393.0 52 851 False False
(a) n_uncut 372 407.7 92 851 False False
(a) go 372 436.6 176 857 False False
(b) n_cut 112 334.3 94 558 True True
(b) n_uncut 112 360.6 128 558 True True
(b) go 112 380.3 176 586 False True
(c) n_cut 383 389.8 4 851 False False
(c) n_uncut 383 404.2 9 851 False False
(c) go 383 433.4 94 857 False False
(a') n_cut 261 387.1 74 804 False False
(a') n_uncut 261 399.4 128 804 False False
(a') go 261 424.9 176 834 False False
(a'') n_cut 368 396.4 94 851 False False
(a'') n_uncut 368 410.4 128 851 False False
(a'') go 368 438.0 176 857 False False
Reading (a) by kind (criterion count):
behavior: n = 78 sessions, mean 348.2, min 52, max 624
behavior+ecephys: n = 162 sessions, mean 333.6, min 74, max 558
behavior+fib: n = 132 sessions, mean 492.3, min 186, max 851
Code's set (F_behavior_w_FP.ipynb cell 11): 259 sessions, 32 mice; here (a) 372 sessions, 41 mice; (a') 261 sessions, 39 mice
Reading (a) sessions below 90 choice trials after the cut (the code applies session_len >= 90 to its own count): 4
Plotted range: 4 to 851 trials; no points outside the axes.
Result: reproduced under reading (b). Counting go cues with a choice in the longest stretch without manual or extra water, as the criterion now defines a trial, the 112 sessions of the selected units average 334.3 trials with a range of 94 to 558, the paper's range exactly and a mean within 342 +- 34.2. The other session sets do not match: (a) 372 sessions passing the computable criteria average 393.0 (52 to 851), (c) all 383 sessions 389.8 (4 to 851), and the variants of (a) with the refitted model's criteria (261 sessions, 387.1, 74 to 804) or with the 90-trial bound on the cut count (368 sessions, 396.4, 94 to 851) are also above tolerance; the photometry sessions carry the longest counts (mean 492.3 in reading (a)). For reading (b) the count without the cut gives 360.6 (128 to 558), also within tolerance, and all go cues 380.3 (176 to 586), outside it. The table's interruption columns agree with their recomputation from the reward deliveries in every row, and no no-go cue has a response.
fig6c-choice-change-rpe¶
Changes of choice on consecutive trials correlate with the model's RPE (rank correlation rho = 0.84).
# L(c(t+1) = c(t)) from the pooled choice regression (R + C, 5 lags) and L(c(t)) from the Q model.
glm = pooled[("R + C (code, Figure 4c)", 5)]["model"]
def choice_change_table(qmap):
cc_rows = []
for s in sessions:
if s["path"] not in qmap:
continue
g = lcne.go_trials(s["trials"])
X, y = lcne.history_matrix(g, 5)
if len(y) < 10:
continue
p_right_next = glm.predict(sm.add_constant(X[:, np.r_[0:5, 10:15]], has_constant="add"))
q = qmap[s["path"]]
r = g[g.responded].reset_index(drop=True)
c = r.choice_right.values
# history_matrix row j predicts responded trial j + 5; so for trial t the next-trial prediction is row t - 4
t_idx = np.arange(4, len(r) - 1)
pn = p_right_next[t_idx - 4]
l_same = np.where(c[t_idx] == 1, pn, 1 - pn)
delta = l_same - q.p_choice.values[t_idx]
cc_rows.append(pd.DataFrame({"path": s["path"], "kind": s["kind"], "RPE": q.RPE.values[t_idx], "delta": delta - np.mean(delta)}))
return pd.concat(cc_rows)
def binned_spearman(df, nb):
means = []
for _, d in df.groupby("path"):
edges = np.linspace(d.RPE.min(), d.RPE.max(), nb + 1)
idx = np.clip(np.digitize(d.RPE, edges) - 1, 0, nb - 1)
means.append(pd.Series(d.delta.values).groupby(idx).mean().reindex(range(nb)).values)
m = np.nanmean(np.array(means), axis=0)
centers = np.arange(nb)
rho, p = stats.spearmanr(centers, m)
return rho, p, m
def report_6c(CC, label, show_means=True):
rho_b, p_b = stats.spearmanr(CC.RPE, CC.delta)
print(f"{label}: {CC.path.nunique()} sessions, {len(CC)} trials; (b) Spearman over pooled trials rho = {rho_b:.3f}, p = {p_b:.2g}")
for nb in [8, 9]:
rho_a, p_a, m = binned_spearman(CC, nb)
print(f" (a) {nb} equal-width RPE bins per session, averaged over sessions: rho = {rho_a:.3f}, p = {p_a:.2g}" + (f"; bin means {np.round(m, 3)}" if show_means else ""))
CC = choice_change_table(q_by_path)
for label, d in [("all sessions", CC), ("photometry sessions (as F_behavior_w_FP.ipynb)", CC[CC.kind == "behavior+fib"])]:
report_6c(d, label)
print("\nVariants (verification round 1):")
report_6c(CC[CC.path.isin(pass_q)], "sessions passing the refitted aN and bias criteria", show_means=False)
CC_pool = choice_change_table(q_pool)
report_6c(CC_pool, "Q variables from the partially pooled fit, all sessions", show_means=False)
report_6c(CC_pool[CC_pool.path.isin(pass_q_pool)], "partially pooled fit, sessions passing its aN and bias criteria", show_means=False)
all sessions: 382 sessions, 152901 trials; (b) Spearman over pooled trials rho = 0.552, p = 0
(a) 8 equal-width RPE bins per session, averaged over sessions: rho = 0.833, p = 0.01; bin means [-0.103 -0.105 -0.052 0.106 -0.032 0.003 0.086 0.388]
(a) 9 equal-width RPE bins per session, averaged over sessions: rho = 0.917, p = 0.00051; bin means [-0.103 -0.11 -0.074 0.014 0.003 -0.022 0.02 0.108 0.397] photometry sessions (as F_behavior_w_FP.ipynb): 136 sessions, 65542 trials; (b) Spearman over pooled trials rho = 0.581, p = 0 (a) 8 equal-width RPE bins per session, averaged over sessions: rho = 0.833, p = 0.01; bin means [-0.093 -0.104 -0.052 0.129 -0.019 0.007 0.088 0.432]
(a) 9 equal-width RPE bins per session, averaged over sessions: rho = 0.867, p = 0.0025; bin means [-0.092 -0.107 -0.073 0.024 0.013 -0.014 0.022 0.115 0.44 ] Variants (verification round 1): sessions passing the refitted aN and bias criteria: 261 sessions, 102936 trials; (b) Spearman over pooled trials rho = 0.539, p = 0
(a) 8 equal-width RPE bins per session, averaged over sessions: rho = 0.833, p = 0.01 (a) 9 equal-width RPE bins per session, averaged over sessions: rho = 0.867, p = 0.0025
Q variables from the partially pooled fit, all sessions: 382 sessions, 152901 trials; (b) Spearman over pooled trials rho = 0.577, p = 0
(a) 8 equal-width RPE bins per session, averaged over sessions: rho = 0.833, p = 0.01
(a) 9 equal-width RPE bins per session, averaged over sessions: rho = 0.917, p = 0.00051 partially pooled fit, sessions passing its aN and bias criteria: 293 sessions, 116042 trials; (b) Spearman over pooled trials rho = 0.569, p = 0
(a) 8 equal-width RPE bins per session, averaged over sessions: rho = 0.833, p = 0.01 (a) 9 equal-width RPE bins per session, averaged over sessions: rho = 0.867, p = 0.0025
Result: reproduced, resting on the binning and on the refitted model. With 8 equal-width RPE bins per session averaged over sessions, rho = 0.833 over all sessions and over the photometry sessions, within 0.84 +- 0.084; 9 bins give 0.917 and 0.867. Over pooled trials rho is 0.552 (all) and 0.581 (photometry), as the criterion anticipated for reading (b). The binned result is the same on the 261 sessions passing the refitted aN and bias criteria (0.833 and 0.867), with the Q variables of the partially pooled fit (0.833 and 0.917) and on the 293 sessions passing its criteria (0.833 and 0.867).
fig6-outcome-responsive-fraction¶
76.8% of LC-NE neurons had significant regressions of outcome-period activity.
# metrics/beh_all_NP/auc_windows.json and metrics/beh_all_TT/auc_windows.json (claims file):
# outcome response lags after the outcome time, for reward-excited and no-reward-excited neurons.
AUC_LAG = {"NP": {"reward": 0.736, "noreward": 1.782}, "TT": {"reward": 1.274, "noreward": 0.996}}
REC_SIDE = 1 # right LC (claims file header); ipsilateral choice = right
def outcome_fit(sp, g, q, lag, drift=False):
r = g[g.responded]
q = q.reindex(r.index)
outcome_time = r.reward_outcome_time.values + np.nan_to_num(r.reward_delay.values, nan=np.nanmedian(r.reward_delay))
counts = lcne.rate_in_windows(sp, outcome_time + lag, -0.75, 0.75) * 1.5
y = (counts - counts.mean()) / counts.std() if counts.std() > 0 else counts * np.nan
R = r.rewarded.values.astype(float)
side = REC_SIDE * (2 * r.choice_right.values - 1)
X = np.column_stack([R, side, R * side, q.Q_chosen.values] + ([r.index.values.astype(float)] if drift else []))
ok = np.isfinite(y) & np.all(np.isfinite(X), axis=1)
if ok.sum() < 20 or np.std(y[ok]) == 0:
return None
m = sm.OLS(y[ok], sm.add_constant(X[ok])).fit()
return {"t_R": m.tvalues[1], "p_R": m.pvalues[1], "b_R": m.params[1], "t_Q": m.tvalues[4], "b_Q": m.params[4], "F_p": m.f_pvalue}
def outcome_table(units, qmap, drift=False):
"""One row per unit (path, row, subject, probe): the outcome regression in the window with the
larger |t| of outcome, and the auROC sign of the outcome response."""
out_rows = []
for _, c in units.iterrows():
g = trials_by_path[c.path]
if c.path not in qmap:
continue
sp = spk[(c.path, c.row)]
fits = {w: outcome_fit(sp, g, qmap[c.path], AUC_LAG[c.probe][w], drift) for w in ["reward", "noreward"]}
fits = {k: v for k, v in fits.items() if v is not None}
if not fits:
continue
w = max(fits, key=lambda k: abs(fits[k]["t_R"]))
# outcome response sign from auROC in 1 s windows sliding from the response time to 2 s after it
r = g[g.responded]
rew = r.rewarded.values.astype(bool)
au = []
for st in np.arange(0, 1.01, 0.1):
rate = lcne.rate_in_windows(sp, r.reward_outcome_time.values, st, st + 1.0)
au.append(lcne.auroc(rate[rew], rate[~rew]))
au = np.array(au)
best = au[np.nanargmax(np.abs(au - 0.5))]
out_rows.append({"path": c.path, "row": c.row, "subject": c.subject, "probe": c.probe, "window": w, **fits[w], "auroc": best})
return pd.DataFrame(out_rows)
OUT = outcome_table(cells, q_by_path)
n = len(OUT)
ka = int((OUT.p_R < 0.05).sum())
kb = int((OUT.F_p < 0.05).sum())
print(f"{n} neurons with an outcome regression (of {len(cells)} selected)")
print(f"(a) outcome coefficient p < 0.05: {ka} ({100 * ka / n:.1f}%; of all {len(cells)} selected, {100 * ka / len(cells):.1f}%)")
print(f"(b) whole-model F-test p < 0.05: {kb} ({100 * kb / n:.1f}%; of all selected, {100 * kb / len(cells):.1f}%)")
print("Window kept:", OUT.window.value_counts().to_dict(), "; auROC above 0.5 (reward-excited):", int((OUT.auroc > 0.5).sum()), ", below:", int((OUT.auroc < 0.5).sum()))
print("By recording type, fraction (a):", OUT.groupby("probe").p_R.apply(lambda v: round(float(np.mean(v < 0.05)), 3)).to_dict())
OUT_drift = outcome_table(cells, q_by_path, drift=True)
print(f"Variant with the trial index as a stand-in drift regressor: (a) {100 * np.mean(OUT_drift.p_R < 0.05):.1f}%, (b) {100 * np.mean(OUT_drift.F_p < 0.05):.1f}% of {len(OUT_drift)}")
252 neurons with an outcome regression (of 252 selected)
(a) outcome coefficient p < 0.05: 192 (76.2%; of all 252 selected, 76.2%)
(b) whole-model F-test p < 0.05: 231 (91.7%; of all selected, 91.7%)
Window kept: {'reward': 138, 'noreward': 114} ; auROC above 0.5 (reward-excited): 144 , below: 108
By recording type, fraction (a): {'NP': 0.754, 'TT': 0.77}
Variant with the trial index as a stand-in drift regressor: (a) 77.4%, (b) 95.6% of 252
Result: reproduced, resting on the refitted model. The outcome coefficient has p < 0.05 in 192 of 252 neurons (76.2%), within 76.8 +- 7.68; the whole-model F-test reading gives 91.7%, outside. Tetrode and Neuropixels neurons give 77.0% and 75.4%. With the trial index as a stand-in drift regressor the fraction is 77.4% (F-test 95.6%); on the populations of the sensitivity section it is 75.4% to 77.4%, and 76.6% with the pooled-fit Q variables.
fig6a-outcome-space¶
Neurons excited by reward lie more dorsal and anterior in LC than neurons excited by no reward; their distribution in space is nonuniform (p = 3.0e-4).
out_ccf = ccf_cells.merge(OUT, on=["path", "row", "subject"])
lin, knn = spatial(out_ccf, "t_R", "outcome t", seed=60)
print("Gradient components: DV (dorsal +)", round(float(lin["axis"][2]), 3), "; AP (posterior +)", round(float(lin["axis"][1]), 3),
"-> positive t dorsal:", bool(lin["axis"][2] > 0), "; anterior:", bool(lin["axis"][1] < 0))
outcome t: n = 127 neurons from 16 mice; linear R2 = 0.119, permutation p = 0.0014; unit gradient (|ML|, AP posterior +, DV dorsal +) = [ 0.124 -0.981 -0.147]; kNN cross-validated R2 = 0.126, p = 0.0010 Gradient components: DV (dorsal +) -0.147 ; AP (posterior +) -0.981 -> positive t dorsal: False ; anterior: True
Result: partially reproduced. The outcome t is distributed nonuniformly in space (linear R2 = 0.119, p = 0.0014; kNN R2 = 0.126, p = 0.0010; 127 neurons), and positive (reward-excited) values lie anterior (AP component -0.981). The gradient's DV component is -0.147, slightly ventral, so the dorsal part of the claim does not hold.
figs18d-outcome-not-on-anatomy-axes¶
Reward-versus-no-reward t-statistics are not correlated with neuron position along the primary axes from other modalities (r = -0.01 and 0.01).
res18 = on_axes(out_ccf, "t_R")
print("Any axis with p < 0.05:", any(p < 0.05 for r, p in res18.values()))
b_z retrograde LDA, left [0.024, 0.332, 0.943]: r = -0.067, p = 0.457 (n = 127) b_y MERFISH CCA, right [-0.248, 0.499, 0.830]: r = -0.103, p = 0.247 (n = 127) b_x waveform [0.345, 0.228, 0.910]: r = -0.055, p = 0.536 (n = 127) Any axis with p < 0.05: False
Result: reproduced. The outcome t does not correlate with position on any of the three axes (r = -0.103, -0.067 and -0.055; p = 0.25, 0.46 and 0.54).
fig6f-outcome-angles-nonuniform¶
The angles of outcome and chosen-value coefficients cluster nonuniformly across LC-NE neurons (Rayleigh z = 19.53), separating RPE-like neurons from neurons excited by no reward.
theta = np.arctan2(OUT.b_Q.values, OUT.b_R.values)
z, p = lcne.rayleigh(theta)
print(f"Rayleigh test over {len(theta)} neurons: z = {z:.2f}, p = {p:.2g}; mean angle {np.degrees(np.angle(np.mean(np.exp(1j * theta)))):.1f} deg")
hist, edges = np.histogram(np.degrees(theta), bins=np.arange(-180, 181, 45))
print("Neurons per 45 deg sector (angle of (outcome, chosen value) coefficients):")
print(pd.Series(hist, index=[f"{a} to {a + 45}" for a in edges[:-1].astype(int)]).to_string())
rpe_like = int(((OUT.b_R > 0) & (OUT.b_Q < 0)).sum())
noreward = int((OUT.b_R < 0).sum())
print(f"RPE-like quadrant (outcome +, chosen value -): {rpe_like}; negative outcome coefficient: {noreward}; other: {len(OUT) - rpe_like - noreward}")
Rayleigh test over 252 neurons: z = 28.13, p = 2.8e-13; mean angle -66.1 deg Neurons per 45 deg sector (angle of (outcome, chosen value) coefficients): -180 to -135 31 -135 to -90 30 -90 to -45 38 -45 to 0 87 0 to 45 20 45 to 90 4 90 to 135 5 135 to 180 37 RPE-like quadrant (outcome +, chosen value -): 125; negative outcome coefficient: 103; other: 24
Result: partially reproduced. The coefficient angles are nonuniform (Rayleigh z = 28.13, p = 2.8e-13, 252 neurons), with most neurons in the RPE quadrant (125, outcome positive and chosen value negative) and the negative-outcome half (103); z is above 19.53 +- 1.953. Because z grows with the number of neurons, the sensitivity section also scales it to the paper's 241: 26.90 here and 22.43 to 27.12 on the other populations and with the pooled-fit Q, all above 21.48. Unscaled, the smaller populations give 19.56 (207 neurons) and 21.03 (226), within tolerance, so the outcome rests on the main population, the units passing every criterion computable from the dataset.
fig6g-rpe-vs-no-reward-populations¶
Neurons excited by reward scale with RPE, whereas neurons excited by no reward respond to lack of reward with little modulation by expected reward.
def rpe_groups(OUT, qmap, units=None, show=True):
"""Mean z-scored outcome-window rate by RPE quartile (reward-excited neurons) and, on
unrewarded trials, by chosen-value quartile (no-reward-excited neurons)."""
probe_of = (units if units is not None else cells).set_index(["path", "row"]).probe
g_rows = []
for _, o in OUT.iterrows():
g = trials_by_path[o.path]
r = g[g.responded]
q = qmap[o.path].reindex(r.index)
sp = spk[(o.path, o.row)]
lag = AUC_LAG[probe_of.loc[(o.path, o.row)]]["reward" if o.auroc > 0.5 else "noreward"]
ot = r.reward_outcome_time.values + np.nan_to_num(r.reward_delay.values, nan=np.nanmedian(r.reward_delay))
rate = lcne.rate_in_windows(sp, ot + lag, -0.75, 0.75)
zr = (rate - rate.mean()) / rate.std() if rate.std() > 0 else rate * 0
rq = pd.qcut(q.RPE.values, 4, labels=False, duplicates="drop")
unrew = ~r.rewarded.values.astype(bool)
qq = pd.qcut(q.Q_chosen.values[unrew], 4, labels=False, duplicates="drop")
g_rows.append({"group": "reward-excited" if o.auroc > 0.5 else "no-reward-excited", "path": o.path, "row": o.row,
**{f"rpe_q{k + 1}": zr[rq == k].mean() for k in range(4)},
**{f"unrew_Q_q{k + 1}": zr[unrew][qq == k].mean() for k in range(4)}})
G6 = pd.DataFrame(g_rows)
re_ = G6[G6.group == "reward-excited"]
nr_ = G6[G6.group == "no-reward-excited"]
m_re = re_[[f"rpe_q{k}" for k in range(1, 5)]].mean().values
an = stats.f_oneway(*[nr_[f"unrew_Q_q{k}"].dropna() for k in range(1, 5)])
rm = nr_[[f"unrew_Q_q{k}" for k in range(1, 5)]].dropna()
fr = stats.friedmanchisquare(*[rm[c] for c in rm.columns])
if show:
print(G6.groupby("group")[[f"rpe_q{k}" for k in range(1, 5)] + [f"unrew_Q_q{k}" for k in range(1, 5)]].agg(["mean", "sem"]).round(3).T.to_string())
print("Reward-excited mean rate by RPE quartile:", np.round(m_re, 3), "; increases monotonically:", bool(np.all(np.diff(m_re) > 0)))
print(f"No-reward-excited, unrewarded trials, rate across chosen-value quartiles: one-way ANOVA F = {an.statistic:.2f}, p = {an.pvalue:.3g} (n = {len(nr_)} neurons)")
print(f"Variant, within-neuron (Friedman) test: chi2 = {fr.statistic:.2f}, p = {fr.pvalue:.3g}")
print("No-reward-excited mean rate on unrewarded trials, by chosen-value quartile:", np.round(rm.mean().values, 3))
return {"n_re": len(re_), "n_nr": len(nr_), "re_quartiles": np.round(m_re, 3), "monotonic": bool(np.all(np.diff(m_re) > 0)),
"anova_p": an.pvalue, "friedman_p": fr.pvalue}
res6g = rpe_groups(OUT, q_by_path)
group no-reward-excited reward-excited
rpe_q1 mean 0.204 -0.251
sem 0.024 0.016
rpe_q2 mean 0.044 -0.116
sem 0.016 0.016
rpe_q3 mean -0.157 0.123
sem 0.020 0.017
rpe_q4 mean -0.101 0.272
sem 0.020 0.016
unrew_Q_q1 mean 0.231 -0.168
sem 0.029 0.025
unrew_Q_q2 mean 0.249 -0.186
sem 0.028 0.023
unrew_Q_q3 mean 0.180 -0.274
sem 0.029 0.020
unrew_Q_q4 mean 0.213 -0.265
sem 0.036 0.023
Reward-excited mean rate by RPE quartile: [-0.251 -0.116 0.123 0.272] ; increases monotonically: True
No-reward-excited, unrewarded trials, rate across chosen-value quartiles: one-way ANOVA F = 0.96, p = 0.414 (n = 108 neurons)
Variant, within-neuron (Friedman) test: chi2 = 3.13, p = 0.373
No-reward-excited mean rate on unrewarded trials, by chosen-value quartile: [0.219 0.24 0.165 0.213]
Result: reproduced. Reward-excited neurons (144) increase their outcome-window rate across RPE quartiles (-0.251, -0.116, 0.123, 0.272 z). In no-reward-excited neurons (108), the rate on unrewarded trials does not differ across chosen-value quartiles (ANOVA p = 0.41; Friedman p = 0.37).
fig6h-opposing-behavior¶
Neurons correlated with RPE and neurons excited by lack of reward have opposing correlations with choice behavior on subsequent trials.
def behavior_slopes(OUT, qmap, units=None):
"""Per neuron, slope of the change of choice likelihood (claim fig6c) over quartiles of the
outcome-window rate."""
probe_of = (units if units is not None else cells).set_index(["path", "row"]).probe
h_rows = []
for _, o in OUT.iterrows():
g = trials_by_path[o.path]
X, y = lcne.history_matrix(g, 5)
if len(y) < 10:
continue
pn = glm.predict(sm.add_constant(X[:, np.r_[0:5, 10:15]], has_constant="add"))
r = g[g.responded].reset_index(drop=True)
q = qmap[o.path]
c = r.choice_right.values
t_idx = np.arange(4, len(r) - 1)
l_same = np.where(c[t_idx] == 1, pn[t_idx - 4], 1 - pn[t_idx - 4])
delta = l_same - q.p_choice.values[t_idx]
delta = delta - delta.mean()
lag = AUC_LAG[probe_of.loc[(o.path, o.row)]]["reward" if o.auroc > 0.5 else "noreward"]
ot = r.reward_outcome_time.values + np.nan_to_num(r.reward_delay.values, nan=np.nanmedian(r.reward_delay))
rate = lcne.rate_in_windows(spk[(o.path, o.row)], ot + lag, -0.75, 0.75)[t_idx]
qb = pd.qcut(pd.Series(rate).rank(method="first"), 4, labels=False)
mean_delta = pd.Series(delta).groupby(qb.values).mean().values
slope = np.polyfit(np.arange(4), mean_delta, 1)[0]
h_rows.append({"group": "reward-excited" if o.auroc > 0.5 else "no-reward-excited", "path": o.path, "slope": slope})
return pd.DataFrame(h_rows)
def report_6h(H6, label):
re_s, nr_s = H6[H6.group == "reward-excited"].slope, H6[H6.group == "no-reward-excited"].slope
tt = stats.ttest_ind(re_s, nr_s)
print(f"{label}: reward-excited mean slope {re_s.mean():.4f} (n = {len(re_s)}, one-sample p = {stats.ttest_1samp(re_s, 0).pvalue:.3g}); "
f"no-reward-excited {nr_s.mean():.4f} (n = {len(nr_s)}, p = {stats.ttest_1samp(nr_s, 0).pvalue:.3g}); "
f"opposite signs: {bool(np.sign(re_s.mean()) != np.sign(nr_s.mean()))}; two-sample t = {tt.statistic:.2f}, p = {tt.pvalue:.3g}")
H6 = behavior_slopes(OUT, q_by_path)
print(H6.groupby("group").slope.agg(["count", "mean", "sem"]).to_string())
report_6h(H6, "all neurons")
print("\nVariants (verification round 1):")
report_6h(H6[H6.path.isin(pass_q)], "neurons in sessions passing the refitted aN and bias criteria")
count mean sem group no-reward-excited 108 0.002176 0.001383 reward-excited 144 0.012511 0.001130 all neurons: reward-excited mean slope 0.0125 (n = 144, one-sample p = 5.91e-21); no-reward-excited 0.0022 (n = 108, p = 0.119); opposite signs: False; two-sample t = 5.83, p = 1.67e-08 Variants (verification round 1): neurons in sessions passing the refitted aN and bias criteria: reward-excited mean slope 0.0125 (n = 109, one-sample p = 5.82e-14); no-reward-excited 0.0016 (n = 98, p = 0.253); opposite signs: False; two-sample t = 5.36, p = 2.26e-07
Result: not reproduced. The slope of the change of choice likelihood on the outcome-window rate is positive in reward-excited neurons (0.0125, p = 5.9e-21) and near zero, also positive, in no-reward-excited neurons (0.0022, p = 0.12). The groups differ (t-test p = 1.7e-08), but the slopes do not have opposite signs. Restricted to the sessions passing the refitted aN and bias criteria (0.0125 and 0.0016), on the other populations and with the pooled-fit Q variables (0.0120 and 0.0026), both slopes stay positive.
fig6i-axons-rpe¶
LC-NE axonal activity in prelimbic cortex after the choice outcome correlates with RPE, with regression angles that differ from the single-neuron population (Watson-Wheeler W = 0.1).
FP_SIDE = -1 # the PL fibers are in the left hemisphere (G_PL-L); ipsilateral choice = left
def fp_outcome_table(qmap):
fo_rows = []
for s in sessions:
if s["fp"] is None or s["path"] not in set(FPq.path) or s["path"] not in qmap:
continue
t, sig_, iso = s["fp"]
z = (sig_ - np.nanmean(sig_)) / np.nanstd(sig_)
zi = (iso - np.nanmean(iso)) / np.nanstd(iso)
g = lcne.go_trials(s["trials"])
r = g[g.responded]
q = qmap[s["path"]].reindex(r.index)
R = r.rewarded.values.astype(float)
side = FP_SIDE * (2 * r.choice_right.values - 1)
ot = r.reward_outcome_time.values + np.nan_to_num(r.reward_delay.values, nan=np.nanmedian(r.reward_delay))
for wname, (al, a0, a1) in {"Methods, 0-2 s after outcome": (ot, 0.0, 2.0),
"code, 1.5 s bin centred 0.7 s after choice": (r.reward_outcome_time.values, -0.05, 1.45)}.items():
y = window_mean(t, z, al, a0, a1)
yi = window_mean(t, zi, al, a0, a1)
for iso_name, X in [("with isosbestic", np.column_stack([R, side, R * side, q.Q_chosen.values, yi])),
("without isosbestic", np.column_stack([R, side, R * side, q.Q_chosen.values]))]:
ok = np.isfinite(y) & np.all(np.isfinite(X), axis=1)
m = sm.OLS(y[ok], sm.add_constant(X[ok])).fit()
fo_rows.append({"path": s["path"], "subject": s["subject"], "window": wname, "iso": iso_name,
"t_R": m.tvalues[1], "t_Q": m.tvalues[4], "b_R": m.params[1], "b_Q": m.params[4]})
return pd.DataFrame(fo_rows)
def report_6i(FO, OUT, rng, n_perm=5000):
theta_n = np.arctan2(OUT.b_Q.values, OUT.b_R.values)
for (wname, iso_name), d in FO.groupby(["window", "iso"]):
for unit in ["session", "mouse"]:
dd = d if unit == "session" else d.groupby("subject")[["t_R", "t_Q", "b_R", "b_Q"]].mean().reset_index()
th = np.arctan2(dd.b_Q.values, dd.b_R.values)
W, pw = lcne.watson_wheeler(th, theta_n, n_perm=n_perm, rng=rng)
print(f"{wname}, {iso_name}, per {unit} (n = {len(dd)}): mean outcome t {dd.t_R.mean():.2f}, mean chosen-value t {dd.t_Q.mean():.2f}; "
f"RPE sign: {bool(dd.t_R.mean() > 0 and dd.t_Q.mean() < 0)}; Watson-Wheeler against {len(theta_n)} neurons W = {W:.2f}, p = {pw:.4f}")
FO = fp_outcome_table(q_by_path)
report_6i(FO, OUT, np.random.default_rng(66))
Methods, 0-2 s after outcome, with isosbestic, per session (n = 63): mean outcome t 3.33, mean chosen-value t -3.21; RPE sign: True; Watson-Wheeler against 252 neurons W = 34.41, p = 0.0002 Methods, 0-2 s after outcome, with isosbestic, per mouse (n = 7): mean outcome t 3.21, mean chosen-value t -2.88; RPE sign: True; Watson-Wheeler against 252 neurons W = 9.38, p = 0.0048
Methods, 0-2 s after outcome, without isosbestic, per session (n = 63): mean outcome t 3.31, mean chosen-value t -3.24; RPE sign: True; Watson-Wheeler against 252 neurons W = 34.78, p = 0.0002 Methods, 0-2 s after outcome, without isosbestic, per mouse (n = 7): mean outcome t 3.18, mean chosen-value t -2.93; RPE sign: True; Watson-Wheeler against 252 neurons W = 9.36, p = 0.0042
code, 1.5 s bin centred 0.7 s after choice, with isosbestic, per session (n = 63): mean outcome t 3.17, mean chosen-value t -3.04; RPE sign: True; Watson-Wheeler against 252 neurons W = 27.80, p = 0.0002 code, 1.5 s bin centred 0.7 s after choice, with isosbestic, per mouse (n = 7): mean outcome t 3.33, mean chosen-value t -2.72; RPE sign: True; Watson-Wheeler against 252 neurons W = 7.55, p = 0.0162
code, 1.5 s bin centred 0.7 s after choice, without isosbestic, per session (n = 63): mean outcome t 3.18, mean chosen-value t -3.05; RPE sign: True; Watson-Wheeler against 252 neurons W = 27.96, p = 0.0002 code, 1.5 s bin centred 0.7 s after choice, without isosbestic, per mouse (n = 7): mean outcome t 3.34, mean chosen-value t -2.73; RPE sign: True; Watson-Wheeler against 252 neurons W = 7.56, p = 0.0194
Result: reproduced, resting on the refitted model. In every reading, PL axonal fluorescence after the outcome has a positive mean outcome t (3.17 to 3.34) and a negative mean chosen-value t (-2.72 to -3.24), the RPE sign, and the Watson-Wheeler test separates axonal from single-neuron angles (per session W = 27.8 to 34.8, p = 0.0002; per mouse, 7 mice, W = 7.6 to 9.4, p = 0.004 to 0.019).
fig6j-cortical-input-more-positive¶
Outcome regression t-statistics of cortex-projecting neurons and of axonal fluorescence are more positive than those of the single-neuron population (Fisher's exact test, p < 0.01).
for (wname, iso_name), d in FO.groupby(["window", "iso"]):
a = d.t_R.values
b = OUT.t_R.values
odds, p = stats.fisher_exact([[np.sum(a > 0), np.sum(a <= 0)], [np.sum(b > 0), np.sum(b <= 0)]])
print(f"{wname}, {iso_name}: photometry positive {int(np.sum(a > 0))}/{len(a)} ({np.mean(a > 0):.2f}) against neurons {int(np.sum(b > 0))}/{len(b)} ({np.mean(b > 0):.2f}); "
f"Fisher odds {odds:.2f}, p = {p:.3g}")
print("Reading (b), cortex-projecting against other neurons, cannot be run: the dandiset does not mark antidromically identified neurons.")
Methods, 0-2 s after outcome, with isosbestic: photometry positive 53/63 (0.84) against neurons 149/252 (0.59); Fisher odds 3.66, p = 0.000199 Methods, 0-2 s after outcome, without isosbestic: photometry positive 53/63 (0.84) against neurons 149/252 (0.59); Fisher odds 3.66, p = 0.000199 code, 1.5 s bin centred 0.7 s after choice, with isosbestic: photometry positive 55/63 (0.87) against neurons 149/252 (0.59); Fisher odds 4.75, p = 1.42e-05 code, 1.5 s bin centred 0.7 s after choice, without isosbestic: photometry positive 54/63 (0.86) against neurons 149/252 (0.59); Fisher odds 4.15, p = 5.57e-05 Reading (b), cortex-projecting against other neurons, cannot be run: the dandiset does not mark antidromically identified neurons.
Result: reproduced under reading (a). Outcome t is positive in 53 to 55 of 63 photometry sessions (0.84 to 0.87) against 149 of 252 neurons (0.59); Fisher p = 1.4e-05 to 2.0e-04, below 0.01 in every window. Reading (b), cortex-projecting neurons, cannot be run.
figs15t-crosscorrelogram-outcome-axis¶
The first PC of cross-correlograms between simultaneously recorded LC-NE neurons varies along the spatial axis of outcome responses, but not of waveform, respond-versus-ignore or switch-versus-stay.
from sklearn.decomposition import PCA
CCG_BIN = 0.05
CCG_LAGS = 20 # +-1 s
pair_rows, ccgs = [], []
for path, d in ccf_cells.groupby("path"):
if len(d) < 2:
continue
tr = trials_by_path[path]
t0, t1 = tr.start_time.min(), tr.stop_time.max()
edges = np.arange(t0, t1, CCG_BIN)
binned = {r: np.histogram(spk[(path, r)], edges)[0].astype(float) for r in d.row}
rows_ = list(d.itertuples())
for i in range(len(rows_)):
for j in range(i + 1, len(rows_)):
a = binned[rows_[i].row]
b = binned[rows_[j].row]
a = (a - a.mean()) / (a.std() + 1e-12)
b = (b - b.mean()) / (b.std() + 1e-12)
n = len(a)
cc = np.array([np.dot(a[max(0, -L):n - max(0, L)], b[max(0, L):n - max(0, -L)]) / (n - abs(L)) for L in range(-CCG_LAGS, CCG_LAGS + 1)])
ccgs.append(cc)
pair_rows.append({"path": path, "subject": rows_[i].subject, "ci": np.asarray(rows_[i].coord), "cj": np.asarray(rows_[j].coord)})
P = pd.DataFrame(pair_rows)
CCG = np.array(ccgs)
pca = PCA(n_components=3).fit(CCG)
P["pc1"] = pca.transform(CCG)[:, 0]
print(f"Pairs of simultaneously recorded selected neurons with CCF: {len(P)} from {P.path.nunique()} sessions and {P.subject.nunique()} mice; "
f"PC1 explains {pca.explained_variance_ratio_[0]:.3f} of the variance")
def feature_axis(df, col, seed):
dd = df.dropna(subset=[col])
return lcne.linear_spatial_test(dd[col].values.astype(float), np.vstack(dd.coord.values), n_perm=1, rng=np.random.default_rng(seed))["axis"]
def pair_positions(ax):
return {"(a) midpoint": np.array([(0.5 * (ci + cj)) @ ax for ci, cj in zip(P.ci, P.cj)]),
"(b) difference": np.array([abs(ci @ ax - cj @ ax) for ci, cj in zip(P.ci, P.cj)])}
def knn_within_session(y, pos, groups, n_perm, rng):
"""kNN test with PC1 permuted only among pairs of the same session (a variant that keeps
session-level differences in the null)."""
obs = lcne.knn_cv_r2(y, pos[:, None])
idx = [np.where(groups == g)[0] for g in np.unique(groups)]
null = []
for _ in range(n_perm):
yp = y.copy()
for ix in idx:
yp[ix] = y[rng.permutation(ix)]
null.append(lcne.knn_cv_r2(yp, pos[:, None]))
return (1 + np.sum(np.array(null) >= obs)) / (n_perm + 1)
feature_axes = {}
for name, df, col, seed in [("waveform (slope symmetry)", WF, "symmetry_slope_div_log", 71), ("respond-versus-ignore", hit_ccf, "t_methods", 72),
("switch-versus-stay", sw_ccf, "t_switch_prev_responded_methods", 73), ("reward-versus-no-reward", out_ccf, "t_R", 74)]:
feature_axes[name] = feature_axis(df, col, seed)
rng15 = np.random.default_rng(15)
rows15 = []
for name, ax in feature_axes.items():
for reading, pos in pair_positions(ax).items():
res = lcne.knn_spatial_test(P.pc1.values, pos[:, None], n_perm=1000, rng=rng15)
rows15.append({"axis": name, "reading": reading, "axis vector": np.round(ax, 3), "kNN R2": res["r2"], "p": res["p"]})
print(pd.DataFrame(rows15).round(4).to_string(index=False))
# Added after verification round 1: every variant of the respond-versus-ignore and switch-versus-stay
# t-statistics, and a null that permutes PC1 only within sessions.
rng15b = np.random.default_rng(151)
variant_axes = {"waveform (slope symmetry)": feature_axes["waveform (slope symmetry)"],
"reward-versus-no-reward": feature_axes["reward-versus-no-reward"]}
for i, col in enumerate(["t_methods", "t_code", "t_drift"]):
variant_axes[f"respond-versus-ignore {col[2:]}"] = feature_axis(hit_ccf, col, 72)
for col in SW_COLS + SW_DRIFT:
variant_axes[f"switch {col[2:]}"] = feature_axis(sw_ccf, col, 73)
rows15v = []
groups = P.path.values
for name, ax in variant_axes.items():
for reading, pos in pair_positions(ax).items():
res = lcne.knn_spatial_test(P.pc1.values, pos[:, None], n_perm=1000, rng=rng15b)
rows15v.append({"axis": name, "reading": reading, "kNN R2": res["r2"], "p": res["p"],
"p, within-session null": knn_within_session(P.pc1.values, pos, groups, 1000, rng15b)})
V15 = pd.DataFrame(rows15v)
print(V15.round(4).to_string(index=False))
for reading in ["(a) midpoint", "(b) difference"]:
v = V15[V15.reading == reading]
for pcol in ["p", "p, within-session null"]:
outc = v[v.axis == "reward-versus-no-reward"][pcol].iloc[0]
ri = v[v.axis.str.startswith("respond")][pcol]
sw_ = v[v.axis.str.startswith("switch")][pcol]
wf_ = v[v.axis.str.startswith("waveform")][pcol].iloc[0]
print(f"{reading}, {pcol}: outcome {outc:.3f}; waveform {wf_:.3f}; respond-versus-ignore variants with p >= 0.05: {int((ri >= 0.05).sum())} of {len(ri)}; "
f"switch variants with p >= 0.05: {int((sw_ >= 0.05).sum())} of {len(sw_)}")
Pairs of simultaneously recorded selected neurons with CCF: 229 from 30 sessions and 15 mice; PC1 explains 0.585 of the variance
axis reading axis vector kNN R2 p
waveform (slope symmetry) (a) midpoint [0.803, 0.172, 0.57] -0.2129 0.4316
waveform (slope symmetry) (b) difference [0.803, 0.172, 0.57] -0.0895 0.0529
respond-versus-ignore (a) midpoint [0.22, 0.479, 0.85] -0.1276 0.1069
respond-versus-ignore (b) difference [0.22, 0.479, 0.85] -0.0909 0.0410
switch-versus-stay (a) midpoint [0.823, -0.568, -0.004] 0.1833 0.0010
switch-versus-stay (b) difference [0.823, -0.568, -0.004] -0.1622 0.2438
reward-versus-no-reward (a) midpoint [0.124, -0.981, -0.147] 0.0812 0.0010
reward-versus-no-reward (b) difference [0.124, -0.981, -0.147] 0.0296 0.0030
axis reading kNN R2 p p, within-session null
waveform (slope symmetry) (a) midpoint -0.2129 0.4476 0.0519
waveform (slope symmetry) (b) difference -0.0895 0.0420 0.1319
reward-versus-no-reward (a) midpoint 0.0812 0.0010 0.1838
reward-versus-no-reward (b) difference 0.0296 0.0010 0.0300
respond-versus-ignore methods (a) midpoint -0.1276 0.1049 0.1538
respond-versus-ignore methods (b) difference -0.0909 0.0440 0.3217
respond-versus-ignore code (a) midpoint -0.0512 0.0150 0.1948
respond-versus-ignore code (b) difference -0.1074 0.0709 0.4515
respond-versus-ignore drift (a) midpoint -0.2388 0.7233 0.6334
respond-versus-ignore drift (b) difference -0.2455 0.4945 0.9730
switch switch_prev_responded_methods (a) midpoint 0.1833 0.0010 0.0240
switch switch_prev_responded_methods (b) difference -0.1622 0.2418 0.3596
switch switch_prev_responded_code (a) midpoint -0.1219 0.1059 0.6523
switch switch_prev_responded_code (b) difference -0.1640 0.2228 0.3896
switch switch_prev_trial_methods (a) midpoint -0.0260 0.0100 0.1778
switch switch_prev_trial_methods (b) difference -0.2385 0.4775 0.7852
switch switch_prev_trial_code (a) midpoint -0.1073 0.0939 0.1778
switch switch_prev_trial_code (b) difference -0.0230 0.0140 0.0480
switch switch_prev_responded_drift (a) midpoint 0.1307 0.0010 0.5115
switch switch_prev_responded_drift (b) difference -0.2239 0.5245 0.5285
switch switch_prev_trial_drift (a) midpoint -0.0471 0.0240 0.0200
switch switch_prev_trial_drift (b) difference -0.1143 0.1069 0.7243
(a) midpoint, p: outcome 0.001; waveform 0.448; respond-versus-ignore variants with p >= 0.05: 2 of 3; switch variants with p >= 0.05: 2 of 6
(a) midpoint, p, within-session null: outcome 0.184; waveform 0.052; respond-versus-ignore variants with p >= 0.05: 3 of 3; switch variants with p >= 0.05: 4 of 6
(b) difference, p: outcome 0.001; waveform 0.042; respond-versus-ignore variants with p >= 0.05: 2 of 3; switch variants with p >= 0.05: 5 of 6
(b) difference, p, within-session null: outcome 0.030; waveform 0.132; respond-versus-ignore variants with p >= 0.05: 3 of 3; switch variants with p >= 0.05: 5 of 6
Result: partially reproduced, resting on the null and the pair placement. Over 229 pairs (30 sessions, 15 mice), PC1 of the cross-correlograms is predicted by position along the outcome axis under both readings with the label-permutation null (kNN p = 0.001 for midpoints, 0.003 for differences). The absence on the other axes fails under that null: with midpoints the switch axis gives p = 0.001, and with differences the respond-versus-ignore axis gives p = 0.041; across all variants of the two t-statistics, 2 of 3 respond-versus-ignore and 2 (midpoints) or 5 (differences) of 6 switch variants give p >= 0.05. With PC1 permuted only within sessions, the difference reading gives the paper's pattern for the main variants (outcome p = 0.030; waveform 0.132, respond-versus-ignore 0.32, switch 0.36), while the midpoint reading loses the outcome axis (p = 0.18). The paper's bootstrap is not described, so which null applies is open.
Sensitivity to the population and to the Q-learning fit¶
Added after verification round 1. The verifier asked for the single-neuron results on the population the code's model-based session criteria would keep, and on the draft's opto_NE_paper units, and for the Q-dependent results with another fit. The table gives one column per population (with the per-session Q fit) and one for the main population with the partially pooled Q fit. Linear spatial p-values here use 2,000 permutations.
# Populations: the main selection; its units in sessions passing the model criteria (aN >= 0.15,
# |bias| <= 1.25, beh_only.json) under the per-session or the pooled fit; and the units the
# draft (unpublished) marks opto_NE_paper, in sessions passing the computable session criteria.
POP = {"main (252)": cells,
"aN, bias, per-session fit": cells[cells.path.isin(pass_q)],
"aN, bias, pooled fit": cells[cells.path.isin(pass_q_pool)]}
dn = DU[DU.opto_NE_paper == 1][["path", "row"]].merge(U, on=["path", "row"], how="left", indicator=True)
draft_pop = dn[(dn._merge == "both") & dn.beh_ok & dn.tc_ok].drop(columns="_merge").reset_index(drop=True)
draft_pop["has_ccf"] = np.isfinite(draft_pop.x)
print(f"Draft opto_NE_paper units: {int((DU.opto_NE_paper == 1).sum())}; with spike times here (passing the opto-tagging criteria): "
f"{int((dn._merge == 'both').sum())}; in sessions passing the session criteria and the trial count: {len(draft_pop)} "
f"from {draft_pop.subject.nunique()} mice ({len(draft_pop.merge(cells[['path', 'row']], on=['path', 'row']))} also in the main selection)")
POP["draft opto_NE_paper"] = draft_pop
for k, v in POP.items():
print(f" {k}: {len(v)} units, {v.subject.nunique()} mice, {v.path.nunique()} sessions, {int(v.has_ccf.sum())} with CCF")
def ccf_of(units):
d = units[units.has_ccf].rename(columns={"x": "x_coordinate_in_ccf_space", "y": "y_coordinate_in_ccf_space", "z": "z_coordinate_in_ccf_space"})
d = d[["path", "row", "subject", "x_coordinate_in_ccf_space", "y_coordinate_in_ccf_space", "z_coordinate_in_ccf_space"]].copy()
d["coord"] = list(lcne.ccf_lps(d))
return d
def lin_str(df, col, seed):
d = df.dropna(subset=[col])
res = lcne.linear_spatial_test(d[col].values.astype(float), np.vstack(d.coord.values), n_perm=2000, rng=np.random.default_rng(seed))
return f"R2 {res['r2']:.3f}, p {res['p']:.3g}, DV {res['axis'][2]:+.2f}, AP {res['axis'][1]:+.2f} (n {res['n']})"
def axes_str(df, col):
d = df.dropna(subset=[col])
X = np.vstack(d.coord.values)
X = X - X.mean(0)
out = [stats.pearsonr(X @ AXES[name], d[col]) for name in ANAT]
return f"b_z r {out[0][0]:.3f} (p {out[0][1]:.2g}), b_y r {out[1][0]:.3f} (p {out[1][1]:.2g})"
def fisher_str(a, b):
a, b = np.asarray(a), np.asarray(b)
p = stats.fisher_exact([[np.sum(a > 0), np.sum(a <= 0)], [np.sum(b > 0), np.sum(b <= 0)]])[1]
return f"{np.mean(a > 0):.2f} against {np.mean(b > 0):.2f}, p {p:.2g}"
def population_summary(units, qmap, fo_table):
out = {}
hit = hit_table(units)
sw = switch_table(units)
cc_ = ccf_of(units)
out["fig5b % p < 0.05 of all (methods; code)"] = f"{100 * np.mean(hit.p_methods < 0.05):.1f}; {100 * np.mean(hit.p_code < 0.05):.1f}"
tp = []
for _, c in units.iterrows():
sp = spk[(c.path, c.row)]
gc = trials_by_path[c.path].goCue_start_time.values
resp, tonic = lcne.rate_in_windows(sp, gc, 0.01, 0.3), lcne.rate_in_windows(sp, gc, -0.5, 0.0)
tp.append(stats.pearsonr(tonic, resp)[0] if np.std(tonic) > 0 and np.std(resp) > 0 else np.nan)
m = hit.assign(tonic_phasic_r=tp)
r_top = m.dropna(subset=["tonic_phasic_r", "resp_diff"])
r_bot = m.dropna(subset=["tonic_phasic_r", "t_methods"])
out["figs15f r top; bottom"] = (f"{stats.pearsonr(r_top.tonic_phasic_r, r_top.resp_diff)[0]:.3f}; "
f"{stats.pearsonr(r_bot.tonic_phasic_r, r_bot.t_methods)[0]:.3f}")
h_ccf = cc_.merge(hit, on=["path", "row", "subject"])
out["fig5c linear (methods)"] = lin_str(h_ccf, "t_methods", 5)
out["fig5d axes (methods)"] = axes_str(h_ccf, "t_methods")
s_ccf = cc_.merge(sw, on=["path", "row", "subject"])
for col in SW_COLS + SW_DRIFT:
out[f"fig5g linear, {col[2:]}"] = lin_str(s_ccf, col, 10)
out[f"fig5h axes, {col[2:]}"] = axes_str(s_ccf, col)
out["fig5k photometry against neurons positive switch t"] = fisher_str(FPq.t_switch_prev_responded_methods, sw.t_switch_prev_responded_methods)
out["figs17i photometry against neurons positive respond t"] = fisher_str(FPq.t_hit_methods.dropna(), hit.t_methods.dropna())
if qmap is None:
return out
o = outcome_table(units, qmap)
out["fig6 % outcome p < 0.05 (a); F (b)"] = f"{100 * np.mean(o.p_R < 0.05):.1f}; {100 * np.mean(o.F_p < 0.05):.1f} (n {len(o)})"
o_ccf = cc_.merge(o, on=["path", "row", "subject"])
out["fig6a linear"] = lin_str(o_ccf, "t_R", 60)
out["figs18d axes"] = axes_str(o_ccf, "t_R")
th = np.arctan2(o.b_Q.values, o.b_R.values)
z, p = lcne.rayleigh(th)
out["fig6f Rayleigh z (scaled to 241), p"] = f"{z:.2f} ({z * 241 / len(th):.2f}), {p:.2g}; RPE quadrant {int(((o.b_R > 0) & (o.b_Q < 0)).sum())}"
g6 = rpe_groups(o, qmap, units, show=False)
out["fig6g RPE quartiles (reward-excited); ANOVA p"] = f"{g6['re_quartiles']} monotonic {g6['monotonic']}; {g6['anova_p']:.2g}"
h6 = behavior_slopes(o, qmap, units)
re_s, nr_s = h6[h6.group == "reward-excited"].slope, h6[h6.group == "no-reward-excited"].slope
out["fig6h mean slopes reward-excited; no-reward-excited"] = f"{re_s.mean():+.4f}; {nr_s.mean():+.4f}, two-sample p {stats.ttest_ind(re_s, nr_s).pvalue:.2g}"
fo = fo_table[(fo_table.window == "Methods, 0-2 s after outcome") & (fo_table.iso == "with isosbestic")]
out["fig6j photometry against neurons positive outcome t"] = fisher_str(fo.t_R, o.t_R)
return out
FO_pool = fp_outcome_table(q_pool)
SENS = {name: population_summary(units, q_by_path, FO) for name, units in POP.items()}
SENS["main, pooled-fit Q"] = population_summary(cells, q_pool, FO_pool)
pd.set_option("display.max_colwidth", 80)
print(pd.DataFrame(SENS).fillna("").to_string())
print("\nfig6i with the pooled-fit Q variables:")
OUT_pool = outcome_table(cells, q_pool)
report_6i(FO_pool, OUT_pool, np.random.default_rng(67), n_perm=2000)
Draft opto_NE_paper units: 267; with spike times here (passing the opto-tagging criteria): 226; in sessions passing the session criteria and the trial count: 226 from 20 mice (223 also in the main selection) main (252): 252 units, 21 mice, 112 sessions, 127 with CCF aN, bias, per-session fit: 207 units, 19 mice, 95 sessions, 104 with CCF aN, bias, pooled fit: 229 units, 19 mice, 101 sessions, 114 with CCF draft opto_NE_paper: 226 units, 20 mice, 105 sessions, 110 with CCF
main (252) aN, bias, per-session fit aN, bias, pooled fit draft opto_NE_paper main, pooled-fit Q fig5b % p < 0.05 of all (methods; code) 48.4; 50.0 44.9; 45.9 47.2; 48.9 51.3; 52.7 48.4; 50.0 figs15f r top; bottom -0.266; 0.258 -0.268; 0.327 -0.268; 0.324 -0.287; 0.172 -0.266; 0.258 fig5c linear (methods) R2 0.029, p 0.339, DV +0.85, AP +0.48 (n 116) R2 0.055, p 0.159, DV +0.81, AP +0.53 (n 95) R2 0.035, p 0.294, DV +0.85, AP +0.27 (n 105) R2 0.027, p 0.433, DV +0.93, AP +0.25 (n 104) R2 0.029, p 0.339, DV +0.85, AP +0.48 (n 116) fig5d axes (methods) b_z r 0.167 (p 0.074), b_y r 0.165 (p 0.076) b_z r 0.231 (p 0.024), b_y r 0.235 (p 0.022) b_z r 0.184 (p 0.06), b_y r 0.185 (p 0.059) b_z r 0.163 (p 0.098), b_y r 0.162 (p 0.1) b_z r 0.167 (p 0.074), b_y r 0.165 (p 0.076) fig5g linear, switch_prev_responded_methods R2 0.022, p 0.435, DV -0.00, AP -0.57 (n 127) R2 0.037, p 0.287, DV +0.09, AP -0.33 (n 104) R2 0.039, p 0.215, DV +0.08, AP -0.34 (n 114) R2 0.029, p 0.365, DV +0.09, AP -0.45 (n 110) R2 0.022, p 0.435, DV -0.00, AP -0.57 (n 127) fig5h axes, switch_prev_responded_methods b_z r -0.034 (p 0.71), b_y r -0.055 (p 0.54) b_z r -0.020 (p 0.84), b_y r -0.047 (p 0.64) b_z r -0.026 (p 0.79), b_y r -0.052 (p 0.58) b_z r -0.004 (p 0.96), b_y r -0.029 (p 0.76) b_z r -0.034 (p 0.71), b_y r -0.055 (p 0.54) fig5g linear, switch_prev_responded_code R2 0.013, p 0.632, DV +0.39, AP -0.12 (n 127) R2 0.037, p 0.28, DV +0.36, AP -0.03 (n 104) R2 0.036, p 0.25, DV +0.34, AP -0.06 (n 114) R2 0.021, p 0.507, DV +0.40, AP -0.02 (n 110) R2 0.013, p 0.632, DV +0.39, AP -0.12 (n 127) fig5h axes, switch_prev_responded_code b_z r 0.072 (p 0.42), b_y r 0.059 (p 0.51) b_z r 0.101 (p 0.31), b_y r 0.082 (p 0.41) b_z r 0.095 (p 0.32), b_y r 0.076 (p 0.42) b_z r 0.093 (p 0.34), b_y r 0.079 (p 0.41) b_z r 0.072 (p 0.42), b_y r 0.059 (p 0.51) fig5g linear, switch_prev_trial_methods R2 0.031, p 0.271, DV +0.52, AP -0.17 (n 127) R2 0.057, p 0.116, DV +0.50, AP +0.05 (n 104) R2 0.048, p 0.142, DV +0.43, AP -0.04 (n 114) R2 0.055, p 0.098, DV +0.52, AP -0.10 (n 110) R2 0.031, p 0.271, DV +0.52, AP -0.17 (n 127) fig5h axes, switch_prev_trial_methods b_z r 0.138 (p 0.12), b_y r 0.120 (p 0.18) b_z r 0.178 (p 0.071), b_y r 0.159 (p 0.11) b_z r 0.148 (p 0.11), b_y r 0.128 (p 0.17) b_z r 0.184 (p 0.054), b_y r 0.163 (p 0.088) b_z r 0.138 (p 0.12), b_y r 0.120 (p 0.18) fig5g linear, switch_prev_trial_code R2 0.051, p 0.0795, DV +0.73, AP +0.28 (n 127) R2 0.084, p 0.0315, DV +0.64, AP +0.27 (n 104) R2 0.072, p 0.0385, DV +0.61, AP +0.21 (n 114) R2 0.076, p 0.027, DV +0.71, AP +0.32 (n 110) R2 0.051, p 0.0795, DV +0.73, AP +0.28 (n 127) fig5h axes, switch_prev_trial_code b_z r 0.211 (p 0.017), b_y r 0.203 (p 0.022) b_z r 0.254 (p 0.0093), b_y r 0.241 (p 0.014) b_z r 0.231 (p 0.013), b_y r 0.218 (p 0.02) b_z r 0.255 (p 0.0072), b_y r 0.245 (p 0.0099) b_z r 0.211 (p 0.017), b_y r 0.203 (p 0.022) fig5g linear, switch_prev_responded_drift R2 0.015, p 0.592, DV +0.20, AP -0.90 (n 127) R2 0.025, p 0.474, DV +0.26, AP -0.48 (n 104) R2 0.023, p 0.471, DV +0.26, AP -0.51 (n 114) R2 0.015, p 0.651, DV +0.31, AP -0.54 (n 110) R2 0.015, p 0.592, DV +0.20, AP -0.90 (n 127) fig5h axes, switch_prev_responded_drift b_z r 0.045 (p 0.61), b_y r 0.030 (p 0.74) b_z r 0.062 (p 0.53), b_y r 0.038 (p 0.7) b_z r 0.059 (p 0.53), b_y r 0.038 (p 0.69) b_z r 0.062 (p 0.52), b_y r 0.046 (p 0.63) b_z r 0.045 (p 0.61), b_y r 0.030 (p 0.74) fig5g linear, switch_prev_trial_drift R2 0.055, p 0.0645, DV +0.99, AP -0.09 (n 127) R2 0.078, p 0.047, DV +0.84, AP +0.13 (n 104) R2 0.065, p 0.056, DV +0.84, AP +0.04 (n 114) R2 0.075, p 0.0325, DV +0.88, AP +0.19 (n 110) R2 0.055, p 0.0645, DV +0.99, AP -0.09 (n 127) fig5h axes, switch_prev_trial_drift b_z r 0.229 (p 0.0096), b_y r 0.220 (p 0.013) b_z r 0.270 (p 0.0055), b_y r 0.258 (p 0.0082) b_z r 0.246 (p 0.0084), b_y r 0.233 (p 0.012) b_z r 0.269 (p 0.0045), b_y r 0.259 (p 0.0063) b_z r 0.229 (p 0.0096), b_y r 0.220 (p 0.013) fig5k photometry against neurons positive switch t 0.86 against 0.62, p 0.00018 0.86 against 0.64, p 0.001 0.86 against 0.62, p 0.00041 0.86 against 0.61, p 0.00015 0.86 against 0.62, p 0.00018 figs17i photometry against neurons positive respond t 0.40 against 0.26, p 0.04 0.40 against 0.25, p 0.035 0.40 against 0.24, p 0.024 0.40 against 0.23, p 0.0095 0.40 against 0.26, p 0.04 fig6 % outcome p < 0.05 (a); F (b) 76.2; 91.7 (n 252) 75.4; 91.8 (n 207) 76.4; 91.7 (n 229) 77.4; 92.0 (n 226) 76.6; 92.1 (n 252) fig6a linear R2 0.119, p 0.0025, DV -0.15, AP -0.98 (n 127) R2 0.199, p 0.0005, DV -0.14, AP -0.99 (n 104) R2 0.133, p 0.0005, DV -0.15, AP -0.99 (n 114) R2 0.108, p 0.0055, DV -0.15, AP -0.94 (n 110) R2 0.120, p 0.0025, DV -0.15, AP -0.98 (n 127) figs18d axes b_z r -0.067 (p 0.46), b_y r -0.103 (p 0.25) b_z r -0.055 (p 0.58), b_y r -0.104 (p 0.29) b_z r -0.059 (p 0.53), b_y r -0.095 (p 0.31) b_z r -0.088 (p 0.36), b_y r -0.126 (p 0.19) b_z r -0.067 (p 0.45), b_y r -0.104 (p 0.25) fig6f Rayleigh z (scaled to 241), p 28.13 (26.90), 2.8e-13; RPE quadrant 125 19.56 (22.77), 2.1e-09; RPE quadrant 101 21.49 (22.61), 2.9e-10; RPE quadrant 107 21.03 (22.43), 4.6e-10; RPE quadrant 106 28.36 (27.12), 2.2e-13; RPE quadrant 126 fig6g RPE quartiles (reward-excited); ANOVA p [-0.251 -0.116 0.123 0.272] monotonic True; 0.41 [-0.232 -0.096 0.086 0.252] monotonic True; 0.58 [-0.243 -0.11 0.112 0.254] monotonic True; 0.37 [-0.244 -0.104 0.111 0.264] monotonic True; 0.28 [-0.248 -0.12 0.099 0.27 ] monotonic True; 0.66 fig6h mean slopes reward-excited; no-reward-excited +0.0125; +0.0022, two-sample p 1.7e-08 +0.0125; +0.0016, two-sample p 2.3e-07 +0.0121; +0.0022, two-sample p 4.2e-07 +0.0132; +0.0017, two-sample p 1.6e-09 +0.0120; +0.0026, two-sample p 3e-07 fig6j photometry against neurons positive outcome t 0.84 against 0.59, p 0.0002 0.84 against 0.56, p 4.6e-05 0.84 against 0.56, p 3.4e-05 0.84 against 0.57, p 5.7e-05 0.87 against 0.60, p 1.6e-05 fig6i with the pooled-fit Q variables:
Methods, 0-2 s after outcome, with isosbestic, per session (n = 63): mean outcome t 3.43, mean chosen-value t -3.34; RPE sign: True; Watson-Wheeler against 252 neurons W = 38.90, p = 0.0005 Methods, 0-2 s after outcome, with isosbestic, per mouse (n = 7): mean outcome t 3.28, mean chosen-value t -2.99; RPE sign: True; Watson-Wheeler against 252 neurons W = 8.51, p = 0.0040 Methods, 0-2 s after outcome, without isosbestic, per session (n = 63): mean outcome t 3.41, mean chosen-value t -3.36; RPE sign: True; Watson-Wheeler against 252 neurons W = 39.60, p = 0.0005 Methods, 0-2 s after outcome, without isosbestic, per mouse (n = 7): mean outcome t 3.26, mean chosen-value t -3.03; RPE sign: True; Watson-Wheeler against 252 neurons W = 8.43, p = 0.0135
code, 1.5 s bin centred 0.7 s after choice, with isosbestic, per session (n = 63): mean outcome t 3.27, mean chosen-value t -3.16; RPE sign: True; Watson-Wheeler against 252 neurons W = 32.74, p = 0.0005 code, 1.5 s bin centred 0.7 s after choice, with isosbestic, per mouse (n = 7): mean outcome t 3.41, mean chosen-value t -2.82; RPE sign: True; Watson-Wheeler against 252 neurons W = 6.73, p = 0.0295 code, 1.5 s bin centred 0.7 s after choice, without isosbestic, per session (n = 63): mean outcome t 3.28, mean chosen-value t -3.17; RPE sign: True; Watson-Wheeler against 252 neurons W = 32.80, p = 0.0005 code, 1.5 s bin centred 0.7 s after choice, without isosbestic, per mouse (n = 7): mean outcome t 3.42, mean chosen-value t -2.84; RPE sign: True; Watson-Wheeler against 252 neurons W = 6.73, p = 0.0260
Result of the sensitivity checks. No outcome changes. On the 207 units in sessions passing the
refitted aN and bias criteria, the 229 under the pooled fit and the 226 draft opto_NE_paper
units, the results agree with the main population with these exceptions, which the claims' notes
record. fig5d-ignore-on-anatomy-axes is within tolerance and significant on the 207 units (r =
0.231, p = 0.024, and 0.235, p = 0.022) but not on the other populations (r = 0.162 to 0.185, p =
0.059 to 0.10). fig5g-switch-dorsal reaches p < 0.05 on the smaller populations under the reading
with switches against the previous trial (p = 0.027 to 0.047), with R2 0.072 to 0.084, below
0.168. fig5b-baseline-predicts-ignore gives 51.3% on the draft units, just outside 46.5 +- 4.65,
and 44.9% to 48.4% on the others. fig6f-outcome-angles-nonuniform gives unscaled z within
tolerance on the 207 and 226 units, but z scaled to 241 neurons is 22.4 to 27.1 everywhere. With
the pooled-fit Q variables, every Q-dependent result keeps its outcome (fig6i: RPE signs and
Watson-Wheeler p = 0.0005 per session, 0.004 to 0.030 per mouse).
Summary¶
A failure to reproduce here may be a failure of this attempt, not of the paper: see the reasoning and the differences from the paper's method.
| Claim | Outcome |
|---|---|
| Ten anatomy, transcriptomics and slice claims | Blocked: data not in the dandiset, outside data not pinned |
| fig6f-cortex-projecting-rpe-biased | Blocked: cortex-projecting neurons not marked, antidromic stimulation times not deposited (checked in the data check) |
| figs12-trials-per-session | Reproduced under reading (b), the sessions of the selected units (choice trials, interruption cut) |
| iti-mean | Partially reproduced (mean matches, range does not) |
| fig4c-choice-history | Reproduced (the fit's decay constant, which the criterion does not test, is not) |
| fig5a-engagement-reward-history | Reproduced |
| fig5e-switch-history | Reproduced |
| fig6c-choice-change-rpe | Reproduced (binning, refitted model) |
| fig4g-go-cue-excitation | Reproduced |
| fig4h-tonic-phasic-anticorrelation | Reproduced |
| figs15f-tonic-modulation-vs-engagement | Not reproduced |
| fig5b-baseline-predicts-ignore | Reproduced (51.3%, just outside, on the draft's units) |
| fig5c-ignore-ventral | Not reproduced |
| fig5d-ignore-on-anatomy-axes | Not reproduced (reproduced on the 207-unit model-criteria population only) |
| fig5g-switch-dorsal | Not reproduced |
| fig5h-switch-on-anatomy-axes | Partially reproduced |
| fig5k-cortical-input-switch | Partially reproduced (photometry part) |
| figs17i-baseline-axons-vs-spiking | Partially reproduced (axons against neurons, weaker) |
| fig6-outcome-responsive-fraction | Reproduced (refitted model) |
| fig6a-outcome-space | Partially reproduced (nonuniform and anterior, not dorsal) |
| figs18d-outcome-not-on-anatomy-axes | Reproduced |
| fig6f-outcome-angles-nonuniform | Partially reproduced (z larger; within tolerance on the 207- and 226-unit populations) |
| fig6g-rpe-vs-no-reward-populations | Reproduced |
| fig6h-opposing-behavior | Not reproduced |
| fig6i-axons-rpe | Reproduced (refitted model) |
| fig6j-cortical-input-more-positive | Reproduced (reading a) |
| figs14-waveform-space | Partially reproduced |
| figs15q-spontaneous-vs-task-licks | Partially reproduced (r larger) |
| figs15t-crosscorrelogram-outcome-axis | Partially reproduced (absences hold only under a within-session null) |
| figs16-pupil-spiking | Partially reproduced (tau matches, correlation sign opposite) |
How the analysis differs from the paper's. The unit selection cannot apply the code's model-based session criteria, its drift cuts or its cortex-projecting ISI bound, and gives 252 units from 21 mice in place of 241 from 19. The drift regressor (per-trial spike amplitude) is not in the dandiset; regressions omit it, with a trial-index stand-in shown as a variant. The Q-learning variables come from a per-session maximum-likelihood fit, not the hierarchical Bayesian fit; a partially pooled refit within each mouse is shown as a variant, and the per-trial variables recover well in simulation. Sensitivity checks rerun the single-neuron results on the populations that the model-based criteria and the draft's labels would give. Waveform features use the files' mean waveforms, also band-pass filtered. Licks are the lick-sensor times, cleaned as the code cleans them. The kNN permutation tests use 1,000 permutations, so their p-values cannot go below 0.001; no conclusion at 0.05 depends on this.
What was found about the dandiset. It holds the behavior, spiking, pupil and photometry of the
paper's physiology, and its clocks agree. It does not mark which units are the paper's LC-NE
neurons or which are cortex-projecting, nor hold the drift amplitudes, drift cuts or model
variables the analysis code reads; some numeric unit columns are stored as strings; the pupil
units are not stated, and the pupil series hold no edge confidence. The trial table's
ITI_duration column does not hold the paper's inter-trial intervals.
print(f"Notebook ran in {(time.time() - started) / 60:.1f} min")
Notebook ran in 29.3 min