Hasnain, Han & Economo (2025) on the MAP dataset, DANDI:000363ΒΆ
Paper: Hasnain M. A., Han Y. & Economo M. N., "Mapping neural subspace dynamics onto the structure
of the mouse descending motor system", bioRxiv doi:10.1101/2025.10.17.682917 (preprint version 1).
The claims file claims/hasnain-2025.yaml was written from the preprint's full text (PMC12632980);
it fixes what is tested.
Dataset: DANDI:000363 (Mesoscale Activity Map Dataset, Chen et al. 2024), version 0.231012.2129, streamed from the archive. The paper cites the dandiset without a version ("https://dandiarchive.org/dandiset/000363"), so the most recent published version is pinned. The earlier versions hold the same 174 sessions; the versions before 0.231012.2129 total 19 to 67 GB and this one 65.7 TB, as it adds the raw recordings. The cell "Version check" compares the units of one session between this version and 0.230822.0128.
The paper reuses the MAP data for Figure 4 only. Its own recordings (Figures 1 to 3, Extended Data Figures 2 and 3) are not public, so those eleven claims are blocked.
| Claim | Tested here |
|---|---|
| own-recordings-cohort, fig1i-selectivity-proportions, fig2c-subspace-variance, fig2e-potent-only-units, fig2f-letn-preference-like-un, fig2gh-letn-span-subspaces, ed2f-false-negatives, fig3c-network-beats-linear, fig3d-letn-un-movement-encoding, ed3-letn-fast-switch, ed3a-cd-early-un-not-letn | Blocked: the paper's own recordings are not public |
| map-session-selection | Tested |
| fig4b-medulla-selectivity | Tested |
| fig4c-alm-null-potent-similar | Tested |
| fig4c-medulla-null-smaller | Tested |
| fig4d-alm-predicts-medulla-null | Tested |
| fig4d-decoding-asymmetry | Tested |
| fig4e-medulla-null-lower-dimension | Tested |
| fig4f-medulla-null-not-spanning-alm | Tested |
A second notebook, reproduce_hasnain_2025_g2.ipynb, repeats the tests on the ALM and medulla
sessions under reading G2 of the unit selection (unit_quality good, CCF labels transferred from
the nearest unit classified good); this notebook uses G1 (classification good) throughout.
The methods are those of the claims file (header items M1 to M10, which cite the paper) and, where
it lacks a detail, the paper's Methods; the helper map_subspace.py says where each parameter comes
from.
import os
os.environ.setdefault("OMP_NUM_THREADS", "2")
import collections
import resource
import time
import zlib
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from scipy import stats
import map_subspace as ms
T0 = time.time()
KEY = "hasnain-2025"
def seed(claim, k=0):
return zlib.crc32(f"{KEY}/{claim}".encode()) + k
SEED_OFFSETS = [0, 1000, 2000, 3000, 4000]
pd.set_option("display.width", 200)
pd.set_option("display.max_columns", 30)
Data checkΒΆ
Every file's units table is read (probe target from the electrodes' location, classification,
unit_quality, anno_name), then the sessions are selected as in M1 and M2.
assets = ms.asset_urls()
tables = ms.survey(assets)
print("files:", len(tables), " subjects:", len({t["subject"] for t in tables.values()}))
n_units = sum(len(t["target"]) for t in tables.values())
print("units:", n_units)
cls_q = collections.Counter((c, q) for t in tables.values() for c, q in zip(t["classification"], t["quality"]))
print("classification x unit_quality:", dict(cls_q))
anno_by_cls = collections.Counter((c, a != "") for t in tables.values() for c, a in zip(t["classification"], t["anno"]))
print("(classification, has CCF annotation):", dict(anno_by_cls))
targets = collections.Counter(tg for t in tables.values() for tg in set(t["target"]))
print("sessions per probe target:", dict(targets))
both_alm = [p for p, t in tables.items() if {"left ALM", "right ALM"} <= set(t["target"])]
alm_medulla_probes = [p for p, t in tables.items()
if any("ALM" in x for x in t["target"]) and any("Medulla" in x for x in t["target"])]
print("sessions with probes in both ALMs:", len(both_alm), "from", len({p.split('/')[0] for p in both_alm}), "mice")
print("sessions with an ALM and a medulla probe:", len(alm_medulla_probes), "from",
len({p.split('/')[0] for p in alm_medulla_probes}), "mice")
anno_counts = collections.Counter(a for t in tables.values() for a in t["anno"] if a)
print("units in the medullary nuclei of M2:", {k: anno_counts[k] for k in ms.MEDULLA_NUCLEI})
print("units labelled MOs (any probe):", sum(v for k, v in anno_counts.items() if k.startswith("Secondary motor area")))
mos_off_alm = sum(1 for t in tables.values() for tg, a in zip(t["target"], t["anno"])
if a.startswith("Secondary motor area") and "ALM" not in tg)
print("units labelled MOs on probes not targeting ALM:", mos_off_alm)
files: 174 subjects: 28
units: 272227
classification x unit_quality: {('unlabelled', 'multi'): 108153, ('good', 'good'): 60978, ('unlabelled', 'good'): 92769, ('good', 'multi'): 8475, ('missing', 'multi'): 651, ('missing', 'good'): 1201}
(classification, has CCF annotation): {('unlabelled', False): 200922, ('good', True): 69453, ('missing', False): 1852}
sessions per probe target: {'left Striatum': 54, 'left ALM': 108, 'right ALM': 103, 'right Striatum': 57, 'right Midbrain': 68, 'right Thalamus': 36, 'left Thalamus': 45, 'left Midbrain': 68, 'left Medulla': 23, 'right Medulla': 24, 'right ECT': 14, 'left ECT': 18, 'right BLA': 8, 'left BLA': 9}
sessions with probes in both ALMs: 60 from 18 mice
sessions with an ALM and a medulla probe: 36 from 8 mice
units in the medullary nuclei of M2: {'Intermediate reticular nucleus': 279, 'Gigantocellular reticular nucleus': 704, 'Parvicellular reticular nucleus': 190}
units labelled MOs (any probe): 7346
units labelled MOs on probes not targeting ALM: 0
Version checkΒΆ
One session's units in the pinned version and in 0.230822.0128, the last version without the raw recordings.
from dandi.dandiapi import DandiAPIClient
probe_path = "sub-456774/sub-456774_ses-20191022T133136_behavior+ecephys+image+ogen.nwb"
old = DandiAPIClient().get_dandiset(ms.DANDISET_ID, "0.230822.0128")
old_paths = {a.path: a for a in old.get_assets()}
ses_key = lambda p: p.split("_behavior")[0]
old_by_ses = {ses_key(p): a for p, a in old_paths.items()}
print("assets in 0.230822.0128:", len(old_paths), " same paths as pinned:", len(set(old_paths) & set(tables)),
" same sessions:", len(set(old_by_ses) & {ses_key(p) for p in tables}))
print("example path there:", next(p for p in old_paths if ses_key(p) == ses_key(probe_path)))
cmp = {}
for label, url in [("0.231012.2129", dict(assets)[probe_path]),
("0.230822.0128", old_by_ses[ses_key(probe_path)].get_content_url(follow_redirects=1, strip_query=True))]:
f = ms.open_file(url)
u = f["units"]
cmp[label] = dict(units=u["id"].shape[0], spikes=u["spike_times"].shape[0],
good=int(sum(np.array(ms._dec(u["classification"][:])) == "good")),
first_spikes=np.round(u["spike_times"][:5], 6).tolist(),
acquisition=sorted(f["acquisition"].keys()))
print(pd.DataFrame(cmp).T)
assets in 0.230822.0128: 174 same paths as pinned: 103 same sessions: 174 example path there: sub-456774/sub-456774_ses-20191022T133136_behavior+ecephys+ogen.nwb
units spikes good first_spikes acquisition 0.231012.2129 1205 24087958 279 [0.000342, 0.051943, 0.078377, 0.116145, 0.130... [BehavioralEvents, BehavioralTimeSeries, Elect... 0.230822.0128 1205 24087958 279 [0.000342, 0.051943, 0.078377, 0.116145, 0.130... [BehavioralEvents, BehavioralTimeSeries]
Selection (M1, M2)ΒΆ
Reading G1: units classified 'good' (classification), with a CCF label of MOs on a probe described
as targeting ALM, or a label of IRN, GRN or PARN. anno_name is filled only for units classified
good. The electrodes table gives the CCF coordinates (x, y, z) of each electrode, so the other
readings (G2, unit_quality good; U2, all units) are formed by giving each unit the label of the
nearest unit classified good on the same probe, within 20 um (an assumption; the cell of
map-session-selection checks it and gives the counts).
bilateral, alm_med = ms.select_sessions(tables)
rows = []
for p, s in bilateral.items():
rows.append(dict(kind="bilateral ALM", session=p.split("/")[1][:30], subject=p.split("/")[0],
right_ALM=len(s["right ALM"]), left_ALM=len(s["left ALM"])))
for p, s in alm_med.items():
rows.append(dict(kind="ALM and medulla", session=p.split("/")[1][:30], subject=p.split("/")[0],
ALM=len(s["ALM"]), ALM_side="+".join(s["alm_sides"]), medulla=len(s["medulla"])))
sel_table = pd.DataFrame(rows)
print(sel_table.to_string())
kind session subject right_ALM left_ALM ALM ALM_side medulla 0 bilateral ALM sub-440956_ses-20190208T133600 sub-440956 33.0 50.0 NaN NaN NaN 1 bilateral ALM sub-440956_ses-20190207T120657 sub-440956 40.0 51.0 NaN NaN NaN 2 bilateral ALM sub-440958_ses-20190217T154414 sub-440958 48.0 31.0 NaN NaN NaN 3 bilateral ALM sub-440957_ses-20190211T143614 sub-440957 46.0 61.0 NaN NaN NaN 4 bilateral ALM sub-440957_ses-20190212T153751 sub-440957 73.0 79.0 NaN NaN NaN 5 bilateral ALM sub-442571_ses-20190302T150148 sub-442571 45.0 37.0 NaN NaN NaN 6 bilateral ALM sub-449141_ses-20190530T173316 sub-449141 38.0 60.0 NaN NaN NaN 7 bilateral ALM sub-449141_ses-20190601T175411 sub-449141 32.0 65.0 NaN NaN NaN 8 bilateral ALM sub-455219_ses-20190808T140448 sub-455219 32.0 50.0 NaN NaN NaN 9 bilateral ALM sub-480134_ses-20210111T122809 sub-480134 78.0 118.0 NaN NaN NaN 10 bilateral ALM sub-480134_ses-20210110T134005 sub-480134 70.0 62.0 NaN NaN NaN 11 bilateral ALM sub-480134_ses-20210113T125455 sub-480134 80.0 49.0 NaN NaN NaN 12 bilateral ALM sub-480135_ses-20210227T131716 sub-480135 45.0 93.0 NaN NaN NaN 13 bilateral ALM sub-480135_ses-20210301T144130 sub-480135 45.0 55.0 NaN NaN NaN 14 bilateral ALM sub-480928_ses-20210128T133949 sub-480928 43.0 41.0 NaN NaN NaN 15 bilateral ALM sub-480928_ses-20210130T135022 sub-480928 68.0 32.0 NaN NaN NaN 16 bilateral ALM sub-480135_ses-20210225T155426 sub-480135 42.0 67.0 NaN NaN NaN 17 ALM and medulla sub-456774_ses-20191022T133136 sub-456774 NaN NaN 85.0 left ALM 128.0 18 ALM and medulla sub-460436_ses-20200109T111437 sub-460436 NaN NaN 81.0 right ALM 65.0 19 ALM and medulla sub-460436_ses-20200110T142717 sub-460436 NaN NaN 48.0 right ALM 60.0 20 ALM and medulla sub-484676_ses-20210419T130102 sub-484676 NaN NaN 46.0 right ALM 31.0 21 ALM and medulla sub-484677_ses-20210418T132006 sub-484677 NaN NaN 40.0 right ALM 56.0
Trials, movement and clocksΒΆ
For each selected session: the trials kept (hit or miss, no photostimulation, no early lick, and a sample cue 1.85 s before the go cue, the paper's 1.2 s delay; the trial labels and the trials left out for another delay are printed), the go cue inside each trial, the jaw and nose speed and the movement threshold. Clock checks: the tongue becomes visible to the side camera, and the first lick is logged, shortly after the go cue (behaviour clock against trial table); and lick direction is decoded from the selected units' spike counts in 200 ms windows around the go cue, against the same decoder with the trial labels shuffled (spike clock against trial table).
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
urls = dict(assets)
W = ms.WINDOWS["W1"]
sessions = {}
check_rows = []
labels_seen = collections.defaultdict(collections.Counter)
rng_check = np.random.default_rng(seed("map-session-selection"))
for p in list(alm_med) + list(bilateral):
if p in sessions:
continue
regions = alm_med[p] if p in alm_med else bilateral[p]
ids = sorted(set(sum((v for k, v in regions.items() if k != "alm_sides"), [])))
s = ms.load_session(urls[p], ids)
for k in ("outcome", "photostim_duration", "early_lick", "trial_instruction"):
labels_seen[k].update(s["trials"][k])
gos = ms.go_times(s)
keep = ms.trial_mask(s)
go = gos[keep]
onset_all = ms.sample_onset(s, gos)
other_delay = (np.isin(np.array(s["trials"]["outcome"]), ["hit", "miss"]) & (np.array(s["trials"]["photostim_duration"]) == "N/A")
& (np.array(s["trials"]["early_lick"]) == "no early") & np.isfinite(gos) & ~(np.abs(onset_all - ms.SAMPLE_ONSET) < 0.02))
sample_rel = onset_all[keep]
speed = ms.speed_bins(s, go, W)
finite = speed[np.isfinite(speed) & (speed > 0)]
log_thr = ms.otsu_threshold(np.log10(finite))
# tongue visibility and first lick
f = ms.open_file(urls[p])
tg = f["acquisition/BehavioralTimeSeries/Camera0_side_TongueTracking"]
tts, tlik = tg["timestamps"][:], tg["data"][:, 2]
licks = np.sort(np.r_[f["acquisition/BehavioralEvents/left_lick_times/timestamps"][:],
f["acquisition/BehavioralEvents/right_lick_times/timestamps"][:]])
hit = np.array(s["trials"]["outcome"])[keep] == "hit"
tongue_lat, lick_lat, tongue_pre = [], [], []
for g in go[hit]:
lo, hi = np.searchsorted(tts, [g, g + 1.0])
k = np.where(tlik[lo:hi] > 0.9)[0]
tongue_lat.append(tts[lo + k[0]] - g if len(k) else np.nan)
lo2, hi2 = np.searchsorted(tts, [g - 0.5, g])
tongue_pre.append(np.mean(tlik[lo2:hi2] > 0.9) if hi2 > lo2 else np.nan)
j = np.searchsorted(licks, g)
lick_lat.append(licks[j] - g if j < len(licks) else np.nan)
# decoding lick direction from spike counts
right = np.array(s["trials"]["trial_instruction"])[keep] == "right"
acc = {}
for w0 in (-2.0, -1.0, -0.4, 0.2, 0.8):
X = np.stack([np.diff(np.searchsorted(s["spikes"][i], np.c_[go + w0, go + w0 + 0.2]), axis=1)[:, 0]
for i in ids], axis=1)
clf = LogisticRegression(C=0.1, max_iter=2000)
acc[w0] = cross_val_score(clf, X, right, cv=5).mean()
acc[f"{w0} shuffled"] = cross_val_score(clf, X, rng_check.permutation(right), cv=5).mean()
sessions[p] = dict(sess=s, keep=keep, go=go, speed=speed, log_thr=log_thr, regions=regions)
check_rows.append(dict(session=p.split("/")[1][:30], trials=len(keep), kept=int(keep.sum()),
hits=int(hit.sum()), right=int(right.sum()),
go_in_trial=int(np.isfinite(gos).sum()),
speed_thr=round(10 ** log_thr, 1),
tongue_lat_ms=round(1000 * np.nanmedian(tongue_lat)),
tongue_pre_go=round(np.nanmean(tongue_pre), 3),
lick_lat_ms=round(1000 * np.nanmedian(lick_lat)),
other_delay=int(other_delay.sum()),
other_delay_onsets=",".join(f"{x:.2f}" for x, _ in collections.Counter(np.round(onset_all[other_delay], 2)).most_common(2)),
sample_from_go_s=round(float(np.nanmedian(sample_rel)), 3),
sample_min=round(float(np.nanmin(sample_rel)), 3), sample_max=round(float(np.nanmax(sample_rel)), 3),
**{f"acc {k}": round(v, 2) for k, v in acc.items()}))
del f
checks = pd.DataFrame(check_rows)
print(checks.to_string())
print("trials kept per session: %d to %d" % (checks.kept.min(), checks.kept.max()))
print("trial labels over the selected sessions:", {k: dict(v) for k, v in labels_seen.items()})
print("correct and error trials left out for a sample onset other than -1.85 s (other delay): %d to %d per session, %d in all"
% (checks.other_delay.min(), checks.other_delay.max(), checks.other_delay.sum()))
print("sample cue onset relative to the go cue in the kept trials: %.3f to %.3f s"
% (checks.sample_min.min(), checks.sample_max.max()))
print("baseline window", ms.BASELINE, "s: ends no later than the earliest sample onset of a kept trial:",
ms.BASELINE[1] <= checks.sample_min.min() + 1e-9)
print("median tongue latency over sessions: %d ms; first lick %d ms" % (checks.tongue_lat_ms.median(), checks.lick_lat_ms.median()))
print("elapsed %.0f s" % (time.time() - T0))
session trials kept hits right go_in_trial speed_thr tongue_lat_ms tongue_pre_go lick_lat_ms other_delay other_delay_onsets sample_from_go_s sample_min sample_max acc -2.0 acc -2.0 shuffled acc -1.0 acc -1.0 shuffled acc -0.4 acc -0.4 shuffled acc 0.2 acc 0.2 shuffled acc 0.8 acc 0.8 shuffled
0 sub-456774_ses-20191022T133136 570 135 111 72 570 24.5 262 0.003 399 14 -2.45,-0.95 -1.85 -1.85 -1.85 0.63 0.40 0.81 0.50 0.78 0.45 0.81 0.47 0.89 0.53
1 sub-460436_ses-20200109T111437 517 294 255 111 517 30.0 119 0.048 321 19 -0.95,-2.45 -1.85 -1.85 -1.85 0.69 0.55 0.69 0.60 0.77 0.55 0.84 0.54 0.93 0.57
2 sub-460436_ses-20200110T142717 500 307 280 147 500 32.3 114 0.011 451 38 -2.45,-0.95 -1.85 -1.85 -1.85 0.56 0.49 0.73 0.53 0.77 0.48 0.85 0.52 0.89 0.54
3 sub-484676_ses-20210419T130102 600 335 296 169 600 46.9 56 0.181 318 47 -0.95,-2.45 -1.85 -1.85 -1.85 0.50 0.50 0.73 0.47 0.72 0.48 0.79 0.53 0.90 0.50
4 sub-484677_ses-20210418T132006 720 420 355 266 720 32.2 126 0.020 421 56 -2.45,-0.95 -1.85 -1.85 -1.85 0.62 0.57 0.86 0.58 0.84 0.53 0.88 0.60 0.96 0.54
5 sub-440956_ses-20190208T133600 480 334 312 156 480 35.0 90 0.000 200 0 -1.85 -1.85 -1.85 0.48 0.53 0.51 0.51 0.50 0.51 0.59 0.51 0.63 0.49
6 sub-440956_ses-20190207T120657 368 225 121 128 368 27.8 105 0.000 246 0 -1.85 -1.85 -1.85 0.55 0.52 0.62 0.56 0.58 0.48 0.66 0.43 0.76 0.58
7 sub-440958_ses-20190217T154414 590 401 324 178 590 29.0 120 0.004 184 0 -1.85 -1.85 -1.85 0.57 0.48 0.78 0.53 0.77 0.48 0.82 0.48 0.91 0.53
8 sub-440957_ses-20190211T143614 520 436 360 175 520 40.4 90 0.001 191 0 -1.85 -1.85 -1.85 0.62 0.50 0.83 0.51 0.82 0.53 0.91 0.50 0.95 0.56
9 sub-440957_ses-20190212T153751 531 431 380 179 531 33.9 94 0.001 189 0 -1.85 -1.85 -1.85 0.67 0.46 0.91 0.55 0.91 0.53 0.94 0.49 0.96 0.54
10 sub-442571_ses-20190302T150148 501 344 310 174 501 35.0 106 0.004 238 0 -1.85 -1.85 -1.85 0.55 0.48 0.72 0.47 0.76 0.45 0.88 0.50 0.97 0.53
11 sub-449141_ses-20190530T173316 660 378 238 200 660 25.3 185 0.006 321 0 -1.85 -1.85 -1.85 0.51 0.43 0.61 0.47 0.60 0.48 0.67 0.45 0.79 0.49
12 sub-449141_ses-20190601T175411 660 436 341 210 660 40.3 115 0.009 244 0 -1.85 -1.85 -1.85 0.51 0.51 0.73 0.46 0.78 0.46 0.82 0.51 0.90 0.52
13 sub-455219_ses-20190808T140448 750 526 450 293 750 43.3 92 0.008 211 0 -1.85 -1.85 -1.85 0.58 0.47 0.70 0.46 0.76 0.52 0.82 0.54 0.93 0.49
14 sub-480134_ses-20210111T122809 540 281 175 104 540 22.2 158 0.001 299 22 -2.45,-0.95 -1.85 -1.85 -1.85 0.57 0.54 0.62 0.49 0.63 0.54 0.64 0.45 0.88 0.55
15 sub-480134_ses-20210110T134005 720 324 202 118 720 23.4 176 0.014 304 57 -0.95,-2.45 -1.85 -1.85 -1.85 0.52 0.54 0.59 0.53 0.52 0.51 0.65 0.52 0.86 0.56
16 sub-480134_ses-20210113T125455 680 348 232 139 680 23.4 118 0.006 229 41 -0.95,-2.45 -1.85 -1.85 -1.85 0.57 0.50 0.67 0.55 0.61 0.48 0.76 0.50 0.87 0.50
17 sub-480135_ses-20210227T131716 520 303 213 160 520 25.4 119 0.048 257 31 -0.95,-2.45 -1.85 -1.85 -1.85 0.52 0.54 0.60 0.54 0.54 0.54 0.63 0.45 0.84 0.53
18 sub-480135_ses-20210301T144130 500 339 259 188 500 28.2 89 0.063 237 43 -2.45,-0.95 -1.85 -1.85 -1.85 0.50 0.44 0.58 0.51 0.59 0.46 0.73 0.51 0.88 0.50
19 sub-480928_ses-20210128T133949 620 236 166 129 620 19.7 112 0.006 403 26 -2.45,-0.95 -1.85 -1.85 -1.85 0.54 0.45 0.69 0.51 0.68 0.56 0.68 0.49 0.81 0.50
20 sub-480928_ses-20210130T135022 580 142 100 75 580 20.5 244 0.005 582 13 -2.45,-0.95 -1.85 -1.85 -1.85 0.60 0.49 0.64 0.47 0.58 0.46 0.61 0.45 0.81 0.48
21 sub-480135_ses-20210225T155426 540 371 214 181 540 22.8 135 0.042 260 39 -0.95,-2.45 -1.85 -1.85 -1.85 0.59 0.48 0.51 0.44 0.54 0.49 0.68 0.54 0.77 0.54
trials kept per session: 135 to 526
trial labels over the selected sessions: {'outcome': {'ignore': 1805, 'hit': 8294, 'miss': 2568}, 'photostim_duration': {'N/A': 10040, '0.5000': 2627}, 'early_lick': {'no early': 11553, 'early': 1114}, 'trial_instruction': {'right': 6274, 'left': 6393}}
correct and error trials left out for a sample onset other than -1.85 s (other delay): 0 to 57 per session, 446 in all
sample cue onset relative to the go cue in the kept trials: -1.850 to -1.850 s
baseline window (-2.1, -1.85) s: ends no later than the earliest sample onset of a kept trial: True
median tongue latency over sessions: 116 ms; first lick 258 ms
elapsed 472 s
fig, ax = plt.subplots(1, 2, figsize=(10, 3.2))
tax = W[0] + ms.BIN * np.arange(sessions[probe_path]["speed"].shape[1])
spd_all = np.array([np.nanmean(v["speed"], 0) for v in sessions.values()])
ax[0].plot(tax, spd_all.T, lw=0.6)
ax[0].axvline(0, color="k", lw=0.5)
ax[0].set(xlabel="time from go cue (s)", ylabel="jaw and nose speed (pixels/s)", title="mean per session")
v = sessions[probe_path]
ax[1].hist(np.log10(v["speed"][np.isfinite(v["speed"]) & (v["speed"] > 0)]), 100)
ax[1].axvline(v["log_thr"], color="r")
ax[1].set(xlabel="log10 speed", title="one session, Otsu threshold in red")
plt.tight_layout()
print("mean speed range over sessions and bins: %.1f to %.1f pixels/s" % (np.nanmin(spd_all), np.nanmax(spd_all)))
print("speed in", probe_path.split('/')[1][:30], "pre-go %.1f, 0 to 1 s after go %.1f pixels/s" % (
np.nanmean(v["speed"][:, (tax > -1) & (tax < 0)]), np.nanmean(v["speed"][:, (tax > 0) & (tax < 1)])))
mean speed range over sessions and bins: 6.4 to 181.2 pixels/s speed in sub-456774_ses-20191022T133136 pre-go 10.4, 0 to 1 s after go 75.2 pixels/s
Claim map-session-selectionΒΆ
In the MAP dataset, the paper's selection gives 20 bilateral ALM sessions from 10 mice (961 right and 1055 left ALM units) and ALM and medulla sessions with 604 ALM units and 724 medullary reticular nucleus units.
Criterion: session counts match S1 (16) or S2 (11) for ALM and medulla and 20 bilateral, and every unit count within tolerance under one reading of M2. U1 (good units in the regions) is the main reading. Only units classified good carry a CCF label, so for U2 (all units in those regions), as for G2, each other unit takes the label of the nearest unit classified good on the same probe, within 20 um (an assumption); the counts of all units on each region's probe are also shown.
bil = sel_table[sel_table.kind == "bilateral ALM"]
am = sel_table[sel_table.kind == "ALM and medulla"]
measured_sel = dict(bilateral_sessions=len(bil), bilateral_mice=bil.subject.nunique(),
right_ALM=int(bil.right_ALM.sum()), left_ALM=int(bil.left_ALM.sum()),
alm_med_sessions=len(am), alm_med_mice=am.subject.nunique(),
ALM=int(am.ALM.sum()), medulla=int(am.medulla.sum()))
expected_sel = dict(bilateral_sessions=(20, 2), right_ALM=(961, 96.1), left_ALM=(1055, 105.5),
ALM=(604, 60.4), medulla=(724, 72.4))
for k, (v, tol) in expected_sel.items():
print(f"{k:20s} measured {measured_sel[k]:6d} expected {v} +- {tol} within: {abs(measured_sel[k] - v) <= tol}")
print("bilateral mice", measured_sel["bilateral_mice"], "(paper 10); ALM and medulla sessions",
measured_sel["alm_med_sessions"], "from", measured_sel["alm_med_mice"], "mice (paper S1 16, S2 11 from 7)")
print("bilateral units", measured_sel["right_ALM"] + measured_sel["left_ALM"], "(Methods 2016, Results 1116)")
# U2-like variant: every unit on the probe, sessions as selected
var_rows = []
for p, s in list(bilateral.items()) + list(alm_med.items()):
t = tables[p]
tg = np.array(t["target"])
q = np.array(t["quality"])
row = dict(session=p.split("/")[1][:30], kind="bilateral" if p in bilateral else "ALM and medulla")
for side in ("left ALM", "right ALM", "left Medulla", "right Medulla"):
row[side + " all"] = int((tg == side).sum())
row[side + " quality good"] = int(((tg == side) & (q == "good")).sum())
var_rows.append(row)
var = pd.DataFrame(var_rows).groupby("kind").sum(numeric_only=True)
print(var.T)
# label transfer for readings G2 and U2: among units classified good, does the nearest other such
# unit on the same probe (electrode CCF coordinates) carry the same CCF label?
agree = n_lab = 0
for t in tables.values():
xyz, an = np.asarray(t["xyz"], float), np.array(t["anno"], dtype=object)
g, tgs = np.array(t["classification"]) == "good", np.array(t["target"])
for tg in set(tgs):
lab = np.where(g & (tgs == tg) & np.isfinite(xyz).all(1))[0]
if len(lab) < 2:
continue
d = np.linalg.norm(xyz[lab][:, None] - xyz[lab][None], axis=2)
np.fill_diagonal(d, np.inf)
agree += int((an[lab][d.argmin(1)] == an[lab]).sum())
n_lab += len(lab)
print(f"nearest unit classified good has the same CCF label: {agree} of {n_lab} ({100 * agree / n_lab:.1f}%)")
g_rows = []
for label, dist in [("classification", None), ("quality", 0.0), ("quality", 20.0), ("quality", 40.0), ("all", 20.0)]:
b2, a2 = ms.select_sessions(tables, label=label, max_dist=dist if dist is not None else ms.TRANSFER_DIST)
g_rows.append(dict(reading={"classification": "G1", "quality": "G2", "all": "U2"}[label], transfer_um=dist,
bilateral=len(b2), bilateral_mice=len({p.split("/")[0] for p in b2}),
right_ALM=sum(len(v["right ALM"]) for v in b2.values()),
left_ALM=sum(len(v["left ALM"]) for v in b2.values()),
alm_med=len(a2), alm_med_mice=len({p.split("/")[0] for p in a2}),
ALM=sum(len(v["ALM"]) for v in a2.values()), medulla=sum(len(v["medulla"]) for v in a2.values())))
print(pd.DataFrame(g_rows).to_string())
print("paper: bilateral 20 sessions from 10 mice, 961 right and 1055 left; ALM and medulla 16 (or 11 from 7 mice), 604 ALM and 724 medulla")
# thresholds on the count of good units: sessions selected
for thr in (20, 25, 30):
b2, a2 = ms.select_sessions(tables, min_units=thr)
print(f"at least {thr} good units: bilateral {len(b2)} sessions, ALM and medulla {len(a2)} sessions")
bilateral_sessions measured 17 expected 20 +- 2 within: False right_ALM measured 858 expected 961 +- 96.1 within: False left_ALM measured 1001 expected 1055 +- 105.5 within: True ALM measured 300 expected 604 +- 60.4 within: False medulla measured 340 expected 724 +- 72.4 within: False bilateral mice 9 (paper 10); ALM and medulla sessions 5 from 4 mice (paper S1 16, S2 11 from 7) bilateral units 1859 (Methods 2016, Results 1116) kind ALM and medulla bilateral left ALM all 308 9796 left ALM quality good 137 5895 right ALM all 1529 8988 right ALM quality good 1042 5546 left Medulla all 3166 0 left Medulla quality good 1635 0 right Medulla all 502 0 right Medulla quality good 279 0
nearest unit classified good has the same CCF label: 67609 of 69453 (97.3%)
reading transfer_um bilateral bilateral_mice right_ALM left_ALM alm_med alm_med_mice ALM medulla 0 G1 NaN 17 9 858 1001 5 4 300 340 1 G2 0.0 28 11 2136 2352 13 6 832 1051 2 G2 20.0 31 12 2767 2830 19 7 1501 1745 3 G2 40.0 35 12 3071 3402 22 8 1908 2105 4 U2 20.0 44 15 5230 5868 28 8 3646 3577 paper: bilateral 20 sessions from 10 mice, 961 right and 1055 left; ALM and medulla 16 (or 11 from 7 mice), 604 ALM and 724 medulla at least 20 good units: bilateral 31 sessions, ALM and medulla 14 sessions at least 25 good units: bilateral 26 sessions, ALM and medulla 9 sessions at least 30 good units: bilateral 17 sessions, ALM and medulla 5 sessions
Result: not reproduced. With the dataset's CCF labels and units classified good (G1), the
paper's rule gives 17 bilateral ALM sessions from 9 mice (paper 20 from 10) and 5 ALM and medulla
sessions from 4 mice (paper 16, or 11 from 7). The left ALM count (1001) is within tolerance of 1055;
the right ALM count (858 against 961), the ALM count of the ALM and medulla sessions (300 against 604)
and the medulla count (340 against 724) are not. Among units classified good, the nearest other such
unit on the probe carries the same CCF label for 97.3%, so the other readings were formed by that
transfer. With unit_quality good (G2, within 20 um) the rule gives 31 bilateral sessions from 12
mice (2767 and 2830 units) and 19 ALM and medulla sessions from 7 mice (1501 ALM and 1745 medulla
units); within 0 um 28 and 13 sessions, within 40 um 35 and 22; with all units (U2) 44 and 28. No
reading gives the session counts together with the unit counts. G1 stays the main reading: its
bilateral unit counts are near the paper's, where G2's are 2.7 to 2.9 times them, and "classified as
'good'" names the classification column. With a threshold of 20 good units the G1 ALM and medulla
sessions number 14, with 25 they number 9.
Per-region subspaces, ALM and medulla sessionsΒΆ
For each ALM and medulla session and region: z-scored rates, the movement mask, the dimensions from the shuffle, and the subspaces. The main reading is W1, B1, D1 and the baseline z-score; the readings W2, B2, D2 and the z-score of example.m are each run with the others held at the main reading. The subspace generator uses the seed of fig4c-alm-null-potent-similar, the first claim that uses it.
READINGS = {"main": dict(W="W1", B="B1", D="D1", Z="baseline"),
"W2": dict(W="W2", B="B1", D="D1", Z="baseline"),
"B2": dict(W="W1", B="B2", D="D1", Z="baseline"),
"D2": dict(W="W1", B="B1", D="D2", Z="baseline"),
"Zall": dict(W="W1", B="B1", D="D1", Z="all")}
def prepare(p, region_ids, reading, store=None):
v = (sessions if store is None else store)[p]
s, go = v["sess"], v["go"]
win = ms.WINDOWS[reading["W"]]
r = ms.rates([s["spikes"][i] for i in region_ids], go, ms.WINDOWS["W1"])
off = int(round((win[0] - ms.WINDOWS["W1"][0]) / ms.BIN))
r = r[:, off:]
if reading["Z"] == "baseline":
# the baseline lies before W2's start, so it is always taken from the W1 rates
rw1 = ms.rates([s["spikes"][i] for i in region_ids], go, ms.WINDOWS["W1"]) if off else r
b0 = int(round((ms.BASELINE[0] - ms.WINDOWS["W1"][0]) / ms.BIN))
b1 = int(round((ms.BASELINE[1] - ms.WINDOWS["W1"][0]) / ms.BIN))
base = rw1[:, b0:b1].reshape(-1, r.shape[2])
mu, sd = base.mean(0), base.std(0)
allsd = r.reshape(-1, r.shape[2]).std(0)
nfb = int((sd <= 1e-9).sum())
sd = np.where(sd <= 1e-9, np.where(allsd > 0, allsd, 1.0), sd)
z = ((r - mu) / sd).astype(np.float32)
else:
z, nfb = ms.zscore(r, win, mode="all")
mv = ms.movement_mask(v["speed"][:, off:], v["log_thr"], short_runs_move=reading["B"] == "B2")
return z, mv, nfb
fits = {} # (session, region, reading) -> fit
fit_rows = []
rng_sub = np.random.default_rng(seed("fig4c-alm-null-potent-similar"))
for p, s in alm_med.items():
for reg in ("ALM", "medulla"):
dims_main = None
for rname, rd in READINGS.items():
z, mv, nfb = prepare(p, s[reg], rd)
dims = fits[(p, reg, "main")]["d_raw"] if rname == "D2" else None
fit = ms.fit_region(z, mv, rng_sub, dim_mode=rd["D"], dims=dims)
fit["n_fallback"] = nfb
fit["moving_frac"] = float((mv == 1).sum() / (mv >= 0).sum())
fit["proj"] = (z @ fit["qn"]).astype(np.float32)
if rname == "main":
fit["z"] = z
fit["mv"] = mv
fits[(p, reg, rname)] = fit
ve = ms.ve_readings(fit)
fit_rows.append(dict(session=p.split("/")[1][:30], region=reg, reading=rname, units=z.shape[2],
d_null=fit["d"][0], d_pot=fit["d"][1], d_null_raw=fit["d_raw"][0],
d_pot_raw=fit["d_raw"][1], moving=round(fit["moving_frac"], 3),
fallback=nfb, z_absmax=float(np.abs(z).max()),
**{f"{k} {n}": 100 * x for k, vv in ve.items() for n, x in zip(("null", "pot", "both"), vv)}))
print(p.split("/")[1][:30], "done, elapsed %.0f s" % (time.time() - T0))
fit_df = pd.DataFrame(fit_rows)
print(fit_df.round(1).to_string())
print("peak memory %.0f MB" % (resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1e3))
# moving bins by epoch (share of tracked bins), readings B1 and B2, and bins without tracking
tax_w1 = ms.WINDOWS["W1"][0] + ms.BIN * np.arange(fits[(next(iter(alm_med)), "ALM", "main")]["mv"].shape[1])
ep_spans = {"baseline": ms.BASELINE, "sample": (-1.8, -1.2), "delay": (-1.2, 0.0), "response": (0.0, 1.5)}
mrows = []
for p in alm_med:
for B in ("B1", "B2"):
mv = ms.movement_mask(sessions[p]["speed"], sessions[p]["log_thr"], short_runs_move=B == "B2")
row = dict(session=p.split("/")[1][:30], reading=B, untracked=round(float((mv < 0).mean()), 3))
for ep, (a, b) in ep_spans.items():
m = mv[:, (tax_w1 >= a) & (tax_w1 < b)]
row[ep] = round(float((m == 1).sum() / max((m >= 0).sum(), 1)), 3)
mrows.append(row)
print(pd.DataFrame(mrows).to_string())
sub-456774_ses-20191022T133136 done, elapsed 536 s
sub-460436_ses-20200109T111437 done, elapsed 618 s
sub-460436_ses-20200110T142717 done, elapsed 683 s
sub-484676_ses-20210419T130102 done, elapsed 733 s
sub-484677_ses-20210418T132006 done, elapsed 817 s
session region reading units d_null d_pot d_null_raw d_pot_raw moving fallback z_absmax V1 null V1 pot V1 both V2 null V2 pot V2 both V3 null V3 pot V3 both
0 sub-456774_ses-20191022T133136 ALM main 85 9 8 9 8 0.3 0 64.7 60.2 70.0 97.7 24.4 27.1 51.5 89.8 84.4 NaN
1 sub-456774_ses-20191022T133136 ALM W2 85 7 8 7 8 0.4 0 64.7 59.9 70.0 98.0 22.3 27.7 50.0 91.4 83.7 NaN
2 sub-456774_ses-20191022T133136 ALM B2 85 9 9 9 9 0.4 0 64.7 55.3 73.8 97.0 22.4 29.9 52.4 91.7 83.4 NaN
3 sub-456774_ses-20191022T133136 ALM D2 85 9 8 9 8 0.3 0 64.7 60.2 70.0 97.7 24.4 27.1 51.5 89.8 84.4 NaN
4 sub-456774_ses-20191022T133136 ALM Zall 85 14 11 14 11 0.3 0 33.5 67.4 72.9 97.0 24.3 23.4 47.7 92.1 91.5 NaN
5 sub-456774_ses-20191022T133136 medulla main 128 13 6 13 6 0.3 1 203.1 35.1 76.0 97.8 27.6 53.1 80.6 71.2 88.3 NaN
6 sub-456774_ses-20191022T133136 medulla W2 128 11 6 11 6 0.4 1 203.1 34.6 75.9 98.0 26.8 53.5 80.3 69.4 87.8 NaN
7 sub-456774_ses-20191022T133136 medulla B2 128 16 7 16 7 0.4 1 203.1 26.4 84.0 96.7 21.3 60.3 81.6 85.1 91.5 NaN
8 sub-456774_ses-20191022T133136 medulla D2 128 13 6 13 6 0.3 1 203.1 35.1 76.0 97.8 27.6 53.1 80.6 71.2 88.3 NaN
9 sub-456774_ses-20191022T133136 medulla Zall 128 12 16 12 16 0.3 0 29.8 55.2 65.5 98.7 27.7 35.6 63.3 89.2 83.4 NaN
10 sub-460436_ses-20200109T111437 ALM main 81 6 5 6 5 0.5 1 115.1 49.4 78.6 97.3 18.9 28.0 47.0 74.2 85.3 NaN
11 sub-460436_ses-20200109T111437 ALM W2 81 3 4 3 4 0.5 1 115.1 59.1 71.0 99.0 17.8 23.8 41.6 78.0 78.5 NaN
12 sub-460436_ses-20200109T111437 ALM B2 81 6 5 6 5 0.6 1 115.1 26.9 94.1 90.9 10.3 33.6 43.9 76.4 96.2 NaN
13 sub-460436_ses-20200109T111437 ALM D2 81 6 5 6 5 0.5 1 115.1 49.4 78.6 97.3 18.9 28.0 47.0 74.2 85.3 NaN
14 sub-460436_ses-20200109T111437 ALM Zall 81 21 13 21 13 0.5 0 40.5 71.9 89.7 97.1 27.4 25.0 52.4 94.3 98.6 NaN
15 sub-460436_ses-20200109T111437 medulla main 65 1 1 1 1 0.5 0 153.7 71.0 45.0 97.7 34.7 22.0 56.7 75.1 50.8 NaN
16 sub-460436_ses-20200109T111437 medulla W2 65 1 1 1 1 0.5 0 153.7 84.4 32.6 98.6 41.5 16.0 57.5 87.0 38.5 NaN
17 sub-460436_ses-20200109T111437 medulla B2 65 9 2 9 2 0.6 0 153.7 28.2 93.5 94.5 21.9 54.3 76.2 57.6 94.9 NaN
18 sub-460436_ses-20200109T111437 medulla D2 65 1 1 1 1 0.5 0 153.7 68.6 46.6 97.0 33.5 22.8 56.3 72.7 51.6 NaN
19 sub-460436_ses-20200109T111437 medulla Zall 65 12 12 12 12 0.5 0 29.6 62.9 72.0 98.5 30.7 35.2 65.9 88.2 85.7 NaN
20 sub-460436_ses-20200110T142717 ALM main 48 8 4 8 4 0.5 0 213.1 24.2 95.6 98.9 16.4 56.6 73.0 41.0 97.4 NaN
21 sub-460436_ses-20200110T142717 ALM W2 48 8 4 8 4 0.6 0 213.1 23.7 95.5 99.0 16.4 58.0 74.5 38.4 97.0 NaN
22 sub-460436_ses-20200110T142717 ALM B2 48 12 6 12 6 0.7 0 213.1 25.7 94.4 98.3 19.0 60.6 79.6 65.1 95.3 NaN
23 sub-460436_ses-20200110T142717 ALM D2 48 8 4 8 4 0.5 0 213.1 24.2 95.6 98.9 16.4 56.6 73.0 41.0 97.4 NaN
24 sub-460436_ses-20200110T142717 ALM Zall 48 12 9 12 9 0.5 0 39.1 72.8 85.2 97.8 28.7 28.0 56.7 91.1 95.0 NaN
25 sub-460436_ses-20200110T142717 medulla main 60 4 2 4 2 0.5 0 176.9 55.4 73.2 99.4 41.6 41.0 82.6 60.9 81.1 NaN
26 sub-460436_ses-20200110T142717 medulla W2 60 2 3 2 3 0.6 0 176.9 74.9 57.9 99.8 41.9 38.5 80.4 83.8 65.5 NaN
27 sub-460436_ses-20200110T142717 medulla B2 60 9 2 9 2 0.7 0 176.9 47.3 83.4 98.3 41.9 46.7 88.6 56.9 85.8 NaN
28 sub-460436_ses-20200110T142717 medulla D2 60 4 2 4 2 0.5 0 176.9 55.4 73.2 99.4 41.6 41.0 82.6 60.9 81.1 NaN
29 sub-460436_ses-20200110T142717 medulla Zall 60 10 11 10 11 0.5 0 39.1 54.1 76.7 98.6 27.5 40.4 67.9 73.9 85.9 NaN
30 sub-484676_ses-20210419T130102 ALM main 46 5 6 5 6 0.5 0 65.4 67.7 66.4 99.4 27.6 29.3 56.9 78.3 77.9 NaN
31 sub-484676_ses-20210419T130102 ALM W2 46 5 5 5 5 0.5 0 65.4 70.4 64.1 99.6 29.4 26.8 56.2 80.0 76.5 NaN
32 sub-484676_ses-20210419T130102 ALM B2 46 3 6 3 6 0.8 0 65.4 65.8 70.2 98.8 21.0 31.0 52.0 86.4 74.5 NaN
33 sub-484676_ses-20210419T130102 ALM D2 46 5 6 5 6 0.5 0 65.4 67.7 66.4 99.4 27.6 29.3 56.9 78.3 77.9 NaN
34 sub-484676_ses-20210419T130102 ALM Zall 46 11 9 11 9 0.5 0 56.7 73.6 79.4 99.2 30.2 28.9 59.1 82.8 89.4 NaN
35 sub-484676_ses-20210419T130102 medulla main 31 6 7 6 7 0.5 0 63.4 61.4 70.1 99.6 36.2 44.2 80.4 77.0 77.4 NaN
36 sub-484676_ses-20210419T130102 medulla W2 31 6 7 6 7 0.5 0 63.4 61.7 69.6 99.7 36.7 44.4 81.1 76.8 76.2 NaN
37 sub-484676_ses-20210419T130102 medulla B2 31 7 7 7 7 0.8 0 63.4 50.5 78.2 98.5 31.9 49.4 81.3 80.3 81.9 NaN
38 sub-484676_ses-20210419T130102 medulla D2 31 6 7 6 7 0.5 0 63.4 61.4 70.1 99.6 36.2 44.2 80.4 77.0 77.4 NaN
39 sub-484676_ses-20210419T130102 medulla Zall 31 9 9 9 9 0.5 0 32.8 66.3 74.7 99.6 39.6 44.7 84.3 80.6 83.7 NaN
40 sub-484677_ses-20210418T132006 ALM main 40 10 9 10 9 0.3 0 70.3 55.1 87.2 99.4 28.9 43.3 72.2 69.3 93.7 NaN
41 sub-484677_ses-20210418T132006 ALM W2 40 9 10 9 10 0.4 0 70.3 55.8 83.9 99.7 28.5 45.3 73.9 69.6 90.5 NaN
42 sub-484677_ses-20210418T132006 ALM B2 40 11 11 11 11 0.5 0 70.3 53.0 87.0 99.3 29.3 48.0 77.3 78.1 92.0 NaN
43 sub-484677_ses-20210418T132006 ALM D2 40 10 9 10 9 0.3 0 70.3 55.1 87.2 99.4 28.9 43.3 72.2 69.3 93.7 NaN
44 sub-484677_ses-20210418T132006 ALM Zall 40 14 15 14 15 0.3 0 64.8 88.0 82.5 99.1 40.2 39.7 79.9 94.9 92.7 NaN
45 sub-484677_ses-20210418T132006 medulla main 56 11 11 11 11 0.3 0 75.2 49.0 71.2 99.5 32.3 46.9 79.2 70.0 85.6 NaN
46 sub-484677_ses-20210418T132006 medulla W2 56 11 10 11 10 0.4 0 75.2 48.9 70.7 99.4 32.9 46.4 79.3 69.6 84.6 NaN
47 sub-484677_ses-20210418T132006 medulla B2 56 9 9 9 9 0.5 0 75.2 40.2 78.6 97.7 25.0 48.8 73.8 88.0 88.2 NaN
48 sub-484677_ses-20210418T132006 medulla D2 56 11 11 11 11 0.3 0 75.2 49.0 71.2 99.5 32.3 46.9 79.2 70.0 85.6 NaN
49 sub-484677_ses-20210418T132006 medulla Zall 56 8 13 8 13 0.3 0 40.1 74.9 61.5 98.3 32.0 32.3 64.3 88.7 83.1 NaN
peak memory 3257 MB
session reading untracked baseline sample delay response
0 sub-456774_ses-20191022T133136 B1 0.000 0.010 0.041 0.020 0.771
1 sub-456774_ses-20191022T133136 B2 0.000 0.038 0.170 0.043 0.850
2 sub-460436_ses-20200109T111437 B1 0.000 0.083 0.151 0.341 0.815
3 sub-460436_ses-20200109T111437 B2 0.000 0.201 0.335 0.547 0.938
4 sub-460436_ses-20200110T142717 B1 0.000 0.065 0.179 0.441 0.813
5 sub-460436_ses-20200110T142717 B2 0.000 0.223 0.427 0.736 0.946
6 sub-484676_ses-20210419T130102 B1 0.001 0.247 0.405 0.579 0.509
7 sub-484676_ses-20210419T130102 B2 0.001 0.440 0.707 0.780 0.832
8 sub-484677_ses-20210418T132006 B1 0.000 0.117 0.192 0.175 0.578
9 sub-484677_ses-20210418T132006 B2 0.000 0.266 0.402 0.378 0.781
Claim fig4b-medulla-selectivityΒΆ
Medullary reticular nucleus units are selective for lick direction in each epoch, most in the response epoch (sample 7%, delay 21%, response 49% of 724 units).
Correct trials only, equal random samples of right and left trials (the smaller count; M7), AUROC in each of the five epochs, 1000 label shuffles. Readings E1 (a unit counts for an epoch if selective in either sub-epoch) and E2 (each sub-epoch alone); Bonferroni (p < 0.01) and uncorrected (p < 0.05). Firing rates are the smoothed 5 ms rates (not z-scored) averaged over the epoch's bins.
def selectivity(rng, block_trials=None):
out = []
for p, s in alm_med.items():
v = sessions[p]
trials = v["sess"]["trials"]
out_arr = np.array(trials["outcome"])[v["keep"]]
instr = np.array(trials["trial_instruction"])[v["keep"]]
r_idx = np.where((out_arr == "hit") & (instr == "right"))[0]
l_idx = np.where((out_arr == "hit") & (instr == "left"))[0]
n = min(len(r_idx), len(l_idx))
pick = np.r_[rng.choice(r_idx, n, replace=False), rng.choice(l_idx, n, replace=False)]
is_right = np.r_[np.ones(n, bool), np.zeros(n, bool)]
blocks = None if block_trials is None else pick // block_trials
r = ms.rates([v["sess"]["spikes"][i] for i in s["medulla"]], v["go"][pick], ms.WINDOWS["W1"])
tax = ms.WINDOWS["W1"][0] + ms.BIN * np.arange(r.shape[1])
for j in range(r.shape[2]):
row = dict(session=p.split("/")[1][:30], unit=s["medulla"][j], n_per_side=n)
for ep, (a, b) in ms.EPOCHS.items():
x = r[:, (tax >= a) & (tax < b), j].mean(1)
auc, pv = ms.selectivity_p(x, is_right, rng, blocks=blocks)
row[ep] = pv
row[ep + "_auc"] = auc
out.append(row)
return pd.DataFrame(out)
def summarize_sel(df, alpha):
sig = {ep: df[ep] < alpha for ep in ms.EPOCHS}
e1 = {"sample": sig["sample"], "delay": sig["early_delay"] | sig["late_delay"],
"response": sig["early_response"] | sig["late_response"]}
res = {f"E1 {k}": 100 * v.mean() for k, v in e1.items()}
res.update({f"E2 {k}": 100 * v.mean() for k, v in sig.items()})
return res
sel_runs = {}
for k in SEED_OFFSETS:
sel_runs[k] = selectivity(np.random.default_rng(seed("fig4b-medulla-selectivity", k)))
sel_main = sel_runs[0]
print("medulla units:", len(sel_main), " trials per side per session:", sel_main.groupby("session").n_per_side.first().to_dict())
tab = pd.DataFrame({(off, a): summarize_sel(df, a) for off, df in sel_runs.items() for a in (0.01, 0.05)}).T
tab.index.names = ["seed offset", "alpha"]
print(tab.round(1).to_string())
print("expected: sample 7 +- 0.7, delay 21 +- 2.1, response 49 +- 4.9")
by_sess = sel_main.groupby("session").apply(lambda d: pd.Series(summarize_sel(d, 0.01)))
print("by session (main seed, Bonferroni):")
print(by_sess.round(1).to_string())
# slow drift: the share of right trials (correct, kept) by fifth of the session, and the same test
# with labels shuffled only within blocks of 30 consecutive kept trials (a check, not the paper's test)
pos_rows = []
for p in alm_med:
v = sessions[p]
out_arr = np.array(v["sess"]["trials"]["outcome"])[v["keep"]]
instr = np.array(v["sess"]["trials"]["trial_instruction"])[v["keep"]]
hit_idx = np.where(out_arr == "hit")[0]
fifths = np.array_split(hit_idx, 5)
pos_rows.append(dict(session=p.split("/")[1][:30],
**{f"right share, fifth {k + 1}": round(float(np.mean(instr[f] == "right")), 2) for k, f in enumerate(fifths)}))
print(pd.DataFrame(pos_rows).to_string())
sel_block = selectivity(np.random.default_rng(seed("fig4b-medulla-selectivity", 1)), block_trials=30)
print("labels shuffled within blocks of 30 kept trials (claim seed plus 1):")
print(pd.Series(summarize_sel(sel_block, 0.01)).round(1).to_string())
medulla units: 340 trials per side per session: {'sub-456774_ses-20191022T133136': 54, 'sub-460436_ses-20200109T111437': 103, 'sub-460436_ses-20200110T142717': 130, 'sub-484676_ses-20210419T130102': 134, 'sub-484677_ses-20210418T132006': 136}
E1 sample E1 delay E1 response E2 sample E2 early_delay E2 late_delay E2 early_response E2 late_response
seed offset alpha
0 0.01 32.4 49.1 85.9 32.4 30.3 43.8 65.0 66.8
0.05 42.9 58.2 90.9 42.9 41.8 51.8 73.5 73.5
1000 0.01 31.5 49.7 85.9 31.5 28.2 43.5 65.3 67.4
0.05 43.8 61.5 90.6 43.8 45.0 52.9 73.8 74.7
2000 0.01 32.9 49.4 85.9 32.9 29.7 43.2 65.0 65.6
0.05 43.8 60.9 90.0 43.8 43.5 52.1 72.4 72.9
3000 0.01 30.9 47.9 85.0 30.9 28.2 42.4 63.5 65.9
0.05 42.1 59.7 90.9 42.1 42.1 51.8 73.8 73.8
4000 0.01 30.9 51.5 85.0 30.9 32.1 44.7 65.6 65.3
0.05 43.5 61.8 90.0 43.5 45.0 52.4 73.8 74.1
expected: sample 7 +- 0.7, delay 21 +- 2.1, response 49 +- 4.9
by session (main seed, Bonferroni):
E1 sample E1 delay E1 response E2 sample E2 early_delay E2 late_delay E2 early_response E2 late_response
session
sub-456774_ses-20191022T133136 31.2 50.8 75.8 31.2 39.8 47.7 51.6 50.8
sub-460436_ses-20200109T111437 40.0 49.2 92.3 40.0 12.3 43.1 64.6 80.0
sub-460436_ses-20200110T142717 1.7 33.3 88.3 1.7 18.3 28.3 78.3 73.3
sub-484676_ses-20210419T130102 54.8 77.4 93.5 54.8 38.7 74.2 61.3 74.2
sub-484677_ses-20210418T132006 46.4 46.4 94.6 46.4 37.5 35.7 83.9 76.8
session right share, fifth 1 right share, fifth 2 right share, fifth 3 right share, fifth 4 right share, fifth 5
0 sub-456774_ses-20191022T133136 0.13 0.73 0.50 0.50 0.59
1 sub-460436_ses-20200109T111437 0.35 0.49 0.33 0.41 0.43
2 sub-460436_ses-20200110T142717 0.52 0.41 0.43 0.50 0.46
3 sub-484676_ses-20210419T130102 0.53 0.59 0.53 0.42 0.66
4 sub-484677_ses-20210418T132006 0.54 0.62 0.63 0.72 0.58
labels shuffled within blocks of 30 kept trials (claim seed plus 1): E1 sample 30.3 E1 delay 47.9 E1 response 85.9 E2 sample 30.3 E2 early_delay 29.4 E2 late_delay 41.2 E2 early_response 65.0 E2 late_response 64.7
Result: partially reproduced. Of 340 medulla units (G1), under E1 with the Bonferroni threshold 32.4% are selective in the sample epoch, 49.1% in the delay epoch and 85.9% in the response epoch (paper 7, 21 and 49%). Under E1 the order holds (response highest, sample lowest) for every seed and both thresholds; under E2 the early delay sub-epoch (30.3%) falls below the sample epoch (32.4%). No reading brings a value within tolerance: the E2 sub-epochs give 30.3 to 66.8%, and the uncorrected threshold higher values. Over the five seeds the E1 Bonferroni values range from 30.9 to 32.9% (sample), 47.9 to 51.5% (delay) and 85.0 to 85.9% (response). By session the sample value runs from 1.7 to 54.8%. The share of right trials changes over the session (0.13 to 0.73 by fifth in one session), but slow drift does not explain the high values: with labels shuffled only within blocks of 30 trials they are 30.3, 47.9 and 85.9%. Under reading G2 (second notebook, 1745 units) they are 16.7, 28.3 and 63.4%, also outside tolerance, with the same order. The units differ from the paper's (340 where the paper has 724).
Claims fig4c-alm-null-potent-similar and fig4c-medulla-null-smallerΒΆ
Variance explained per session (M6) under V1, V2 and V3, for each reading of M3 to M5; paired two-sided t test of null against potent over the ALM and medulla sessions.
ve_rows = []
for (rname, reg), d in fit_df.groupby(["reading", "region"]):
for V in ("V1", "V2", "V3"):
a, b = d[f"{V} null"].values, d[f"{V} pot"].values
t, pv = stats.ttest_rel(a, b)
ve_rows.append(dict(region=reg, reading=rname, V=V, n=len(a), null_mean=a.mean(), null_sd=a.std(ddof=1),
pot_mean=b.mean(), pot_sd=b.std(ddof=1), diff=(a - b).mean(), t=t, p=pv,
both=d[f"{V} both"].mean()))
ve_tab = pd.DataFrame(ve_rows).sort_values(["region", "reading", "V"])
print(ve_tab.round(3).to_string())
print("expected ALM null 36.0 +- 7.4, potent 37.1 +- 8.7 (p = 0.15); medulla null 26.4 +- 3.9, potent 44.8 +- 7.12 (p = 1.9e-9)")
alm_ok = ve_tab[(ve_tab.region == "ALM") & (abs(ve_tab.null_mean - 36.0) <= 7.4) & (abs(ve_tab.pot_mean - 37.1) <= 8.7)]
med_ok = ve_tab[(ve_tab.region == "medulla") & (abs(ve_tab.null_mean - 26.4) <= 3.9) & (abs(ve_tab.pot_mean - 44.8) <= 7.12)]
print("ALM readings with both means in tolerance:")
print(alm_ok[["reading", "V", "null_mean", "pot_mean", "p"]].round(4).to_string())
print("medulla readings with both means in tolerance:")
print(med_ok[["reading", "V", "null_mean", "pot_mean", "p"]].round(4).to_string())
print("per session, main reading:")
print(fit_df[fit_df.reading == "main"][["session", "region", "units", "d_null", "d_pot", "moving",
"V1 null", "V1 pot", "V2 null", "V2 pot", "V3 null", "V3 pot"]].round(1).to_string())
region reading V n null_mean null_sd pot_mean pot_sd diff t p both
0 ALM B2 V1 5 45.361 18.044 83.888 11.347 -38.527 -2.990 0.040 96.855
1 ALM B2 V2 5 20.411 6.842 40.626 13.343 -20.215 -3.330 0.029 61.037
2 ALM B2 V3 5 79.509 10.183 88.278 9.230 -8.769 -1.077 0.342 NaN
6 ALM D2 V1 5 51.301 16.603 79.575 12.060 -28.274 -2.272 0.086 98.553
7 ALM D2 V2 5 23.240 5.430 36.874 12.881 -13.635 -1.937 0.125 60.114
8 ALM D2 V3 5 70.519 18.143 87.729 7.780 -17.209 -1.558 0.194 NaN
12 ALM W2 V1 5 53.791 17.695 76.893 12.675 -23.102 -1.731 0.158 99.081
13 ALM W2 V2 5 22.904 5.982 36.327 14.792 -13.422 -1.744 0.156 59.231
14 ALM W2 V3 5 71.504 20.043 85.238 8.533 -13.734 -1.122 0.325 NaN
18 ALM Zall V1 5 74.747 7.803 81.944 6.291 -7.197 -1.841 0.139 98.030
19 ALM Zall V2 5 30.158 6.011 29.003 6.388 1.155 3.364 0.028 59.161
20 ALM Zall V3 5 91.035 4.859 93.449 3.534 -2.415 -1.469 0.216 NaN
24 ALM main V1 5 51.301 16.603 79.575 12.060 -28.274 -2.272 0.086 98.553
25 ALM main V2 5 23.240 5.430 36.874 12.881 -13.635 -1.937 0.125 60.114
26 ALM main V3 5 70.519 18.143 87.729 7.780 -17.209 -1.558 0.194 NaN
3 medulla B2 V1 5 38.495 10.921 83.522 6.168 -45.027 -6.391 0.003 97.145
4 medulla B2 V2 5 28.400 8.636 51.879 5.444 -23.479 -3.960 0.017 80.279
5 medulla B2 V3 5 73.584 15.149 88.482 5.000 -14.898 -1.956 0.122 NaN
9 medulla D2 V1 5 53.888 12.771 67.411 11.844 -13.524 -1.312 0.260 98.682
10 medulla D2 V2 5 34.241 5.178 41.604 11.407 -7.362 -1.184 0.302 75.845
11 medulla D2 V3 5 70.349 5.926 76.791 14.701 -6.442 -0.838 0.449 NaN
15 medulla W2 V1 5 60.895 19.902 61.332 17.370 -0.437 -0.027 0.980 99.082
16 medulla W2 V2 5 35.970 6.307 39.777 14.320 -3.806 -0.434 0.687 75.747
17 medulla W2 V3 5 77.322 8.047 70.543 19.872 6.779 0.552 0.611 NaN
21 medulla Zall V1 5 62.674 8.530 70.074 6.372 -7.400 -1.275 0.271 98.754
22 medulla Zall V2 5 31.498 4.943 37.646 4.882 -6.148 -2.948 0.042 69.145
23 medulla Zall V3 5 84.109 6.734 84.373 1.344 -0.264 -0.078 0.941 NaN
27 medulla main V1 5 54.368 13.485 67.096 12.537 -12.728 -1.157 0.312 98.820
28 medulla main V2 5 34.476 5.165 41.449 11.725 -6.973 -1.072 0.344 75.926
29 medulla main V3 5 70.838 6.257 76.639 15.027 -5.801 -0.702 0.522 NaN
expected ALM null 36.0 +- 7.4, potent 37.1 +- 8.7 (p = 0.15); medulla null 26.4 +- 3.9, potent 44.8 +- 7.12 (p = 1.9e-9)
ALM readings with both means in tolerance:
reading V null_mean pot_mean p
19 Zall V2 30.1581 29.0032 0.0282
medulla readings with both means in tolerance:
reading V null_mean pot_mean p
4 B2 V2 28.4 51.8793 0.0167
per session, main reading:
session region units d_null d_pot moving V1 null V1 pot V2 null V2 pot V3 null V3 pot
0 sub-456774_ses-20191022T133136 ALM 85 9 8 0.3 60.2 70.0 24.4 27.1 89.8 84.4
5 sub-456774_ses-20191022T133136 medulla 128 13 6 0.3 35.1 76.0 27.6 53.1 71.2 88.3
10 sub-460436_ses-20200109T111437 ALM 81 6 5 0.5 49.4 78.6 18.9 28.0 74.2 85.3
15 sub-460436_ses-20200109T111437 medulla 65 1 1 0.5 71.0 45.0 34.7 22.0 75.1 50.8
20 sub-460436_ses-20200110T142717 ALM 48 8 4 0.5 24.2 95.6 16.4 56.6 41.0 97.4
25 sub-460436_ses-20200110T142717 medulla 60 4 2 0.5 55.4 73.2 41.6 41.0 60.9 81.1
30 sub-484676_ses-20210419T130102 ALM 46 5 6 0.5 67.7 66.4 27.6 29.3 78.3 77.9
35 sub-484676_ses-20210419T130102 medulla 31 6 7 0.5 61.4 70.1 36.2 44.2 77.0 77.4
40 sub-484677_ses-20210418T132006 ALM 40 10 9 0.3 55.1 87.2 28.9 43.3 69.3 93.7
45 sub-484677_ses-20210418T132006 medulla 56 11 11 0.3 49.0 71.2 32.3 46.9 70.0 85.6
Seed check for fig4c and fig4e: the main reading and reading B2 again under the claim's seed plus 1000 to 4000 (dimension shuffles and the optimizer's start).
seed_rows = []
for rname in ("main", "B2"):
for k in SEED_OFFSETS:
rng_k = np.random.default_rng(seed("fig4c-alm-null-potent-similar", k))
for p, s in alm_med.items():
for reg in ("ALM", "medulla"):
f0 = fits[(p, reg, "main")]
if k == 0:
fit = fits[(p, reg, rname)]
else:
mv = f0["mv"] if rname == "main" else ms.movement_mask(sessions[p]["speed"], sessions[p]["log_thr"], short_runs_move=True)
fit = ms.fit_region(f0["z"], mv, rng_k)
ve = ms.ve_readings(fit)
seed_rows.append(dict(reading=rname, offset=k, session=p, region=reg, d_null=fit["d"][0], d_pot=fit["d"][1],
d_null_raw=fit["d_raw"][0],
**{f"{V} {n}": 100 * x for V, vv in ve.items() for n, x in zip(("null", "pot", "both"), vv)}))
seed_df = pd.DataFrame(seed_rows)
srows = []
for (rname, off, reg), d in seed_df.groupby(["reading", "offset", "region"]):
for V in ("V1", "V2", "V3"):
t, pv = stats.ttest_rel(d[f"{V} null"], d[f"{V} pot"])
srows.append(dict(reading=rname, offset=off, region=reg, V=V, null=d[f"{V} null"].mean(), pot=d[f"{V} pot"].mean(), p=pv,
mean_d_null=d.d_null.mean()))
seed_tab = pd.DataFrame(srows)
print(seed_tab.round(4).to_string())
print("elapsed %.0f s" % (time.time() - T0))
reading offset region V null pot p mean_d_null 0 B2 0 ALM V1 45.3612 83.8882 0.0404 8.2 1 B2 0 ALM V2 20.4109 40.6262 0.0291 8.2 2 B2 0 ALM V3 79.5093 88.2784 0.3422 8.2 3 B2 0 medulla V1 38.4946 83.5220 0.0031 10.0 4 B2 0 medulla V2 28.4000 51.8793 0.0167 10.0 5 B2 0 medulla V3 73.5845 88.4820 0.1221 10.0 6 B2 1000 ALM V1 45.3612 83.8882 0.0404 8.2 7 B2 1000 ALM V2 20.4109 40.6262 0.0291 8.2 8 B2 1000 ALM V3 79.5093 88.2784 0.3422 8.2 9 B2 1000 medulla V1 39.0878 84.9998 0.0035 10.0 10 B2 1000 medulla V2 28.8447 51.0225 0.0239 10.0 11 B2 1000 medulla V3 73.4750 89.5661 0.1152 10.0 12 B2 2000 ALM V1 45.3612 83.8882 0.0404 8.2 13 B2 2000 ALM V2 20.4109 40.6262 0.0291 8.2 14 B2 2000 ALM V3 79.5093 88.2784 0.3422 8.2 15 B2 2000 medulla V1 37.8732 84.0845 0.0038 10.0 16 B2 2000 medulla V2 27.8982 52.2829 0.0205 10.0 17 B2 2000 medulla V3 73.3301 88.7227 0.1091 10.0 18 B2 3000 ALM V1 45.4419 84.0189 0.0405 8.2 19 B2 3000 ALM V2 20.4704 40.3032 0.0259 8.2 20 B2 3000 ALM V3 79.5384 88.4046 0.3409 8.2 21 B2 3000 medulla V1 38.4946 83.5220 0.0031 10.0 22 B2 3000 medulla V2 28.4000 51.8793 0.0167 10.0 23 B2 3000 medulla V3 73.5845 88.4820 0.1221 10.0 24 B2 4000 ALM V1 45.3612 83.8882 0.0404 8.2 25 B2 4000 ALM V2 20.4109 40.6262 0.0291 8.2 26 B2 4000 ALM V3 79.5093 88.2784 0.3422 8.2 27 B2 4000 medulla V1 37.8732 84.0845 0.0038 10.0 28 B2 4000 medulla V2 27.8982 52.2829 0.0205 10.0 29 B2 4000 medulla V3 73.3301 88.7227 0.1091 10.0 30 main 0 ALM V1 51.3013 79.5750 0.0855 7.6 31 main 0 ALM V2 23.2398 36.8745 0.1248 7.6 32 main 0 ALM V3 70.5194 87.7286 0.1943 7.6 33 main 0 medulla V1 54.3676 67.0958 0.3117 7.0 34 main 0 medulla V2 34.4761 41.4495 0.3442 7.0 35 main 0 medulla V3 70.8376 76.6389 0.5216 7.0 36 main 1000 ALM V1 51.1194 80.2407 0.0801 7.6 37 main 1000 ALM V2 23.1701 36.5975 0.1306 7.6 38 main 1000 ALM V3 70.0872 88.3842 0.1701 7.6 39 main 1000 medulla V1 54.3676 67.0958 0.3117 7.0 40 main 1000 medulla V2 34.4761 41.4495 0.3442 7.0 41 main 1000 medulla V3 70.8375 76.6389 0.5216 7.0 42 main 2000 ALM V1 51.3589 80.2758 0.0787 7.8 43 main 2000 ALM V2 23.4143 36.6183 0.1268 7.8 44 main 2000 ALM V3 70.3974 88.4151 0.1678 7.8 45 main 2000 medulla V1 54.3676 67.0958 0.3117 7.0 46 main 2000 medulla V2 34.4761 41.4495 0.3442 7.0 47 main 2000 medulla V3 70.8376 76.6389 0.5216 7.0 48 main 3000 ALM V1 51.3589 80.2758 0.0787 7.8 49 main 3000 ALM V2 23.4143 36.6183 0.1268 7.8 50 main 3000 ALM V3 70.3974 88.4151 0.1678 7.8 51 main 3000 medulla V1 54.3676 67.0957 0.3117 7.0 52 main 3000 medulla V2 34.4761 41.4495 0.3442 7.0 53 main 3000 medulla V3 70.8376 76.6389 0.5216 7.0 54 main 4000 ALM V1 51.1195 80.2407 0.0801 7.6 55 main 4000 ALM V2 23.1701 36.5975 0.1306 7.6 56 main 4000 ALM V3 70.0872 88.3841 0.1701 7.6 57 main 4000 medulla V1 53.8876 67.4115 0.2599 7.0 58 main 4000 medulla V2 34.2413 41.6039 0.3020 7.0 59 main 4000 medulla V3 70.3492 76.7911 0.4494 7.0 elapsed 1492 s
Result (fig4c-alm-null-potent-similar): partially reproduced, resting on reading G1. Over the 5 ALM and medulla sessions, the paired t test finds no difference between null and potent variance in ALM under the main reading (V1 51.3 against 79.6%, p = 0.086; V2 23.2 against 36.9%, p = 0.125; V3 70.5 against 87.7%, p = 0.194), nor under W2 or D2, but no reading of M3 to M6 puts both means within tolerance of 36.0 and 37.1%. Under B2 the test finds potent above null (V1 p = 0.040, V2 p = 0.029), with means out of tolerance. The z-score of example.m, a variant in the claims file, puts both V2 means within tolerance (30.2 against 29.0%), and there the test finds a difference (p = 0.028). With 5 sessions the test has little power: the main-reading V1 difference is 28.3 points. Over the five seeds the main-reading V1 p ranges from 0.079 to 0.086, and the B2 V1 p is 0.040. Under reading G2 (second notebook, 19 sessions) the main reading with V2 gives 33.9 against 42.7%, p = 0.251 (0.249 to 0.261 over the seeds), which the criterion counts as reproduced; the outcome here rests on G1, which is held fixed while the readings of M3 to M6 are searched (see the summary).
Result (fig4c-medulla-null-smaller): reproduced under the claim's seed, resting on readings G1, B2 and V2, and sensitive to the seed. Under B2 (supra-threshold runs shorter than 100 ms counted as moving) with V2, the medulla null subspace explains 28.4% and the potent subspace 51.9% (tolerances 26.4 +- 3.9 and 44.8 +- 7.12, so at most 51.92), paired t p = 0.017. Over the five seeds the null mean is 27.9 to 28.8%, the potent mean 51.0 to 52.3% and p 0.017 to 0.024; under two of them the potent mean (52.3%) is just outside tolerance, which makes the claim partially reproduced there. Under the main reading B1 the difference is not significant (V1 54.4 against 67.1%, p = 0.312; V2 34.5 against 41.4%, p = 0.344), nor under W2 or D2; under the example.m z-score V2 gives p = 0.042 with the null mean (31.5%) outside tolerance. B2 also makes the ALM difference significant, so no single reading reproduces both Figure 4c claims. Under reading G2 (19 sessions) null is below potent under the main reading (V2 35.7 against 51.7%, p = 0.027; V1 p = 0.020; V1 and V2 p 0.008 to 0.027 over the seeds) and under B2 (V2 30.8 against 56.4%, p = 0.005), with the null mean outside tolerance in each, which the criterion counts as partially reproduced.
Claim fig4e-medulla-null-lower-dimensionΒΆ
The movement-null subspace has lower dimensionality in the medullary reticular nuclei than in ALM (paired t test, p = 7.4e-5).
N1: the shuffle dimension of the stationary activity (before any cap); N2: the participation ratio of the covariance of the movement-null projections. Paired two-sided t test over the ALM and medulla sessions.
dim_rows = []
for p, s in alm_med.items():
row = dict(session=p.split("/")[1][:30])
for reg in ("ALM", "medulla"):
fit = fits[(p, reg, "main")]
row[f"{reg} units"] = len(s[reg])
row[f"{reg} N1"] = fit["d_raw"][0]
row[f"{reg} N2"] = ms.participation_ratio(fit["qn"].T @ fit["C"] @ fit["qn"])
row[f"{reg} N2 per unit"] = row[f"{reg} N2"] / len(s[reg])
dim_rows.append(row)
dim_df = pd.DataFrame(dim_rows)
print(dim_df.round(2).to_string())
for m in ("N1", "N2", "N2 per unit"):
t, pv = stats.ttest_rel(dim_df[f"medulla {m}"], dim_df[f"ALM {m}"])
print(f"{m}: medulla mean {dim_df[f'medulla {m}'].mean():.2f}, ALM mean {dim_df[f'ALM {m}'].mean():.2f}, "
f"t = {t:.2f}, p = {pv:.3g}, medulla lower in {(dim_df[f'medulla {m}'] < dim_df[f'ALM {m}']).sum()} of {len(dim_df)}")
for off, d in seed_df[seed_df.reading == "main"].groupby("offset"):
a = d[d.region == "ALM"].d_null_raw.values
b = d[d.region == "medulla"].d_null_raw.values
t, pv = stats.ttest_rel(b, a)
print(f"seed offset {off}: N1 medulla {b.mean():.1f}, ALM {a.mean():.1f}, p = {pv:.3g}")
for rname in READINGS:
d = fit_df[fit_df.reading == rname]
a = d[d.region == "ALM"].d_null_raw.values
b = d[d.region == "medulla"].d_null_raw.values
t, pv = stats.ttest_rel(b, a)
print(f"reading {rname}: N1 medulla {b.mean():.1f}, ALM {a.mean():.1f}, p = {pv:.3g}")
session ALM units ALM N1 ALM N2 ALM N2 per unit medulla units medulla N1 medulla N2 medulla N2 per unit 0 sub-456774_ses-20191022T133136 85 9 5.06 0.06 128 13 2.90 0.02 1 sub-460436_ses-20200109T111437 81 6 3.48 0.04 65 1 1.00 0.02 2 sub-460436_ses-20200110T142717 48 8 6.13 0.13 60 4 2.66 0.04 3 sub-484676_ses-20210419T130102 46 5 2.87 0.06 31 6 4.29 0.14 4 sub-484677_ses-20210418T132006 40 10 8.80 0.22 56 11 5.30 0.09 N1: medulla mean 7.00, ALM mean 7.60, t = -0.35, p = 0.741, medulla lower in 2 of 5 N2: medulla mean 3.23, ALM mean 5.27, t = -2.26, p = 0.0868, medulla lower in 4 of 5 N2 per unit: medulla mean 0.06, ALM mean 0.10, t = -1.17, p = 0.307, medulla lower in 4 of 5 seed offset 0: N1 medulla 7.0, ALM 7.6, p = 0.741 seed offset 1000: N1 medulla 7.0, ALM 7.6, p = 0.741 seed offset 2000: N1 medulla 7.0, ALM 7.8, p = 0.68 seed offset 3000: N1 medulla 7.0, ALM 7.8, p = 0.68 seed offset 4000: N1 medulla 7.0, ALM 7.6, p = 0.741 reading main: N1 medulla 7.0, ALM 7.6, p = 0.741 reading W2: N1 medulla 6.2, ALM 6.4, p = 0.914 reading B2: N1 medulla 10.0, ALM 8.2, p = 0.393 reading D2: N1 medulla 7.0, ALM 7.6, p = 0.741 reading Zall: N1 medulla 10.2, ALM 14.4, p = 0.0424
Result: not reproduced, resting on reading G1. In the 5 G1 sessions the medulla's movement-null dimensionality is not lower than ALM's under either reading. N1 (shuffle dimension): medulla 7.0, ALM 7.6, p = 0.741, lower in 2 of 5 sessions, and p = 0.68 to 0.741 over the five seeds; W2, B2 and D2 give p = 0.39 to 0.91 (under B2 the medulla is higher, 10.0 against 8.2). N2 (participation ratio): medulla 3.23, ALM 5.27, p = 0.087, lower in 4 of 5; divided by the unit count, p = 0.31. The example.m z-score, a variant, gives N1 medulla 10.2 against ALM 14.4, p = 0.042. Under reading G2 (second notebook, 19 sessions) N1 does not differ (p = 0.98), but N2 is lower in the medulla (3.35 against 5.93, p = 0.027, lower in 14 of 19), which the criterion counts as reproduced; there the medulla N2 is below 1.4 in 5 sessions, each with a unit whose |z| exceeds 3000. The medulla has fewer units than ALM in 2 of the 5 G1 sessions.
Bilateral ALM sessions: subspaces for the decoding referenceΒΆ
Main reading (W1, B1, D1, baseline z-score) and the example.m z-score, for the decoding variants; each hemisphere's subspaces from its own units.
for p, s in bilateral.items():
for reg in ("right ALM", "left ALM"):
for rname in ("main", "Zall"):
z, mv, nfb = prepare(p, s[reg], READINGS[rname])
fit = ms.fit_region(z, mv, rng_sub)
fit["proj"] = (z @ fit["qn"]).astype(np.float32)
fit["n_fallback"] = nfb
fit["z_absmax"] = float(np.abs(z).max())
fits[(p, reg, rname)] = fit
print(p.split("/")[1][:30], [fits[(p, r, "main")]["d"] for r in ("right ALM", "left ALM")],
"elapsed %.0f s" % (time.time() - T0))
print("peak memory %.0f MB" % (resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1e3))
sub-440956_ses-20190208T133600 [(6, 5), (8, 8)] elapsed 1517 s
sub-440956_ses-20190207T120657 [(6, 6), (1, 2)] elapsed 1536 s
sub-440958_ses-20190217T154414 [(10, 6), (1, 4)] elapsed 1567 s
sub-440957_ses-20190211T143614 [(5, 5), (10, 9)] elapsed 1613 s
sub-440957_ses-20190212T153751 [(8, 9), (5, 7)] elapsed 1677 s
sub-442571_ses-20190302T150148 [(11, 7), (1, 4)] elapsed 1703 s
sub-449141_ses-20190530T173316 [(13, 9), (16, 9)] elapsed 1739 s
sub-449141_ses-20190601T175411 [(3, 5), (6, 6)] elapsed 1782 s
sub-455219_ses-20190808T140448 [(8, 5), (9, 7)] elapsed 1834 s
sub-480134_ses-20210111T122809 [(12, 7), (8, 4)] elapsed 1887 s
sub-480134_ses-20210110T134005 [(10, 10), (8, 8)] elapsed 1928 s
sub-480134_ses-20210113T125455 [(24, 7), (4, 4)] elapsed 1972 s
sub-480135_ses-20210227T131716 [(9, 7), (4, 4)] elapsed 2012 s
sub-480135_ses-20210301T144130 [(2, 3), (4, 6)] elapsed 2045 s
sub-480928_ses-20210128T133949 [(5, 8), (6, 4)] elapsed 2063 s
sub-480928_ses-20210130T135022 [(5, 5), (5, 5)] elapsed 2076 s
sub-480135_ses-20210225T155426 [(3, 3), (7, 8)] elapsed 2116 s peak memory 3941 MB
Claims fig4d-alm-predicts-medulla-null and fig4d-decoding-asymmetryΒΆ
Ridge (lambda 0.01) from the source's movement-null projections at t and the 8 preceding bins to all target movement-null dimensions at t; 70/30 split of trials; R2 per bin from -1.8 to +1.5 s, averaged (M8). Readings: T1 all trials, T2 correct only; R1 pooled R2, R2 mean over dimensions; predictors standardized or not; A1 mean of both ALM directions, A2 each direction.
bins = np.arange(int(round((ms.TASK_SPAN[0] - ms.WINDOWS["W1"][0]) / ms.BIN)),
int(round((ms.TASK_SPAN[1] - ms.WINDOWS["W1"][0]) / ms.BIN)))
def decode(rng, readings, zread="main", keep_bins=False):
rows = []
for kind, sess_map, pairs in (("ALM-medulla", alm_med, [("ALM", "medulla"), ("medulla", "ALM")]),
("ALM-ALM", bilateral, [("right ALM", "left ALM"), ("left ALM", "right ALM")])):
for p in sess_map:
v = sessions[p]
hit = np.array(v["sess"]["trials"]["outcome"])[v["keep"]] == "hit"
for T in ("T1", "T2"):
idx = np.arange(len(hit)) if T == "T1" else np.where(hit)[0]
perm = rng.permutation(idx)
ntr = int(round(0.7 * len(perm)))
train, test = perm[:ntr], perm[ntr:]
for src, tgt in pairs:
xs, xt = fits[(p, src, zread)]["proj"], fits[(p, tgt, zread)]["proj"]
for stdz, pooled in readings:
r2, r2_span = ms.ridge_r2(xs, xt, train, test, bins, stdz, pooled, span=True)
rows.append(dict(kind=kind, session=p, T=T, src=src, tgt=tgt,
std=stdz, R="R1" if pooled else "R2", r2=100 * r2.mean(),
r2_span=100 * r2_span, r2_median=100 * np.median(r2),
d_src=xs.shape[2], d_tgt=xt.shape[2], n_train=len(train),
**({"r2_bins": r2, "tgt_var": xt[test][:, bins].var(0).mean(1)} if keep_bins else {})))
return pd.DataFrame(rows)
ALL_READ = [(s_, p_) for s_ in (False, True) for p_ in (True, False)]
dec_main = decode(np.random.default_rng(seed("fig4d-alm-predicts-medulla-null")), ALL_READ, keep_bins=True)
def dec_summary(df, col="r2"):
df = df.assign(r2=df[col])
out = []
for (T, stdz, R), d in df.groupby(["T", "std", "R"]):
am_ = d[(d.kind == "ALM-medulla") & (d.src == "ALM")].set_index("session").r2
ma_ = d[(d.kind == "ALM-medulla") & (d.src == "medulla")].set_index("session").r2
aa = d[d.kind == "ALM-ALM"]
a1 = aa.groupby("session").r2.mean()
rl = aa[aa.src == "right ALM"].r2
lr = aa[aa.src == "left ALM"].r2
sem = lambda x: x.std(ddof=1) / np.sqrt(len(x))
t, pv = stats.ttest_rel(am_.loc[ma_.index], ma_)
out.append(dict(T=T, std=stdz, R=R, ALM_to_med=am_.mean(), sem1=sem(am_), med_to_ALM=ma_.mean(),
sem2=sem(ma_), p_asym=pv, ALM_ALM_A1=a1.mean(), sem3=sem(a1), R_to_L=rl.mean(),
L_to_R=lr.mean()))
return pd.DataFrame(out)
dsum = dec_summary(dec_main)
print(dsum.round(4).to_string())
print("expected ALM to medulla 40 +- 8.1, ALM to ALM 54 +- 7.0, medulla to ALM 21 +- 6.7 (p = 1.2e-4)")
print("per session, T1, unstandardized, R1:")
print(dec_main[(dec_main["T"] == "T1") & (~dec_main["std"]) & (dec_main.R == "R1")][
["kind", "session", "src", "tgt", "d_src", "d_tgt", "n_train", "r2", "r2_median", "r2_span"]].round(1).to_string())
T std R ALM_to_med sem1 med_to_ALM sem2 p_asym ALM_ALM_A1 sem3 R_to_L L_to_R
0 T1 False R1 -497.0543 408.8343 -491.4285 409.3960 0.9931 -4271.6023 3279.5552 -4516.7852 -4026.4195
1 T1 False R2 -611.4761 511.2031 -517.8391 418.9185 0.8988 -6039.6077 4964.8171 -6028.8844 -6050.3309
2 T1 True R1 -307.2720 222.3353 -319.8714 241.6109 0.9717 -2188.0667 1494.3686 -1970.4565 -2405.6769
3 T1 True R2 -376.9208 279.9693 -342.8569 248.7520 0.9316 -3203.3844 2446.4841 -2626.0293 -3780.7394
4 T2 False R1 -273.0403 129.9604 -436.0330 355.8028 0.7031 -4477.2093 3034.2626 -3544.0376 -5410.3811
5 T2 False R2 -321.0785 162.1115 -473.5843 375.4772 0.7379 -6039.3474 4446.5119 -4832.3528 -7246.3419
6 T2 True R1 -249.0861 111.7686 -287.9724 208.5959 0.8816 -3046.6979 1970.0357 -1815.2797 -4278.1161
7 T2 True R2 -292.9111 139.8306 -315.9723 219.6300 0.9341 -4214.3317 3029.9948 -2591.8406 -5836.8228
expected ALM to medulla 40 +- 8.1, ALM to ALM 54 +- 7.0, medulla to ALM 21 +- 6.7 (p = 1.2e-4)
per session, T1, unstandardized, R1:
kind session src tgt d_src d_tgt n_train r2 r2_median r2_span
0 ALM-medulla sub-456774/sub-456774_ses-20191022T133136_behavior+ecephys+image+ogen.nwb ALM medulla 9 13 94 -2127.7 -1345.6 -1220.7
4 ALM-medulla sub-456774/sub-456774_ses-20191022T133136_behavior+ecephys+image+ogen.nwb medulla ALM 13 9 94 -267.0 -231.8 -189.4
16 ALM-medulla sub-460436/sub-460436_ses-20200109T111437_behavior+ecephys+image+ogen.nwb ALM medulla 6 1 206 -19.2 1.4 64.2
20 ALM-medulla sub-460436/sub-460436_ses-20200109T111437_behavior+ecephys+image+ogen.nwb medulla ALM 1 6 206 1.6 1.5 26.5
32 ALM-medulla sub-460436/sub-460436_ses-20200110T142717_behavior+ecephys+image+ogen.nwb ALM medulla 8 4 215 -111.0 -64.8 8.9
36 ALM-medulla sub-460436/sub-460436_ses-20200110T142717_behavior+ecephys+image+ogen.nwb medulla ALM 4 8 215 -2117.9 -122.8 -1163.7
48 ALM-medulla sub-484676/sub-484676_ses-20210419T130102_behavior+ecephys+ogen.nwb ALM medulla 5 6 234 -193.6 -104.4 -160.3
52 ALM-medulla sub-484676/sub-484676_ses-20210419T130102_behavior+ecephys+ogen.nwb medulla ALM 6 5 234 -37.1 -28.1 12.0
64 ALM-medulla sub-484677/sub-484677_ses-20210418T132006_behavior+ecephys+ogen.nwb ALM medulla 10 11 294 -33.8 -26.3 -6.0
68 ALM-medulla sub-484677/sub-484677_ses-20210418T132006_behavior+ecephys+ogen.nwb medulla ALM 11 10 294 -36.7 -35.8 -24.1
80 ALM-ALM sub-440956/sub-440956_ses-20190208T133600_behavior+ecephys+ogen.nwb right ALM left ALM 6 8 234 -53317.8 -15344.4 -23561.5
84 ALM-ALM sub-440956/sub-440956_ses-20190208T133600_behavior+ecephys+ogen.nwb left ALM right ALM 8 6 234 -59248.0 -17701.5 -12208.3
96 ALM-ALM sub-440956/sub-440956_ses-20190207T120657_behavior+ecephys+image+ogen.nwb right ALM left ALM 6 1 158 -199.4 -94.8 28.1
100 ALM-ALM sub-440956/sub-440956_ses-20190207T120657_behavior+ecephys+image+ogen.nwb left ALM right ALM 1 6 158 -19.2 -10.4 -7.1
112 ALM-ALM sub-440958/sub-440958_ses-20190217T154414_behavior+ecephys+image+ogen.nwb right ALM left ALM 10 1 281 -93.3 -74.4 -15.0
116 ALM-ALM sub-440958/sub-440958_ses-20190217T154414_behavior+ecephys+image+ogen.nwb left ALM right ALM 1 10 281 -3.2 -3.1 8.4
128 ALM-ALM sub-440957/sub-440957_ses-20190211T143614_behavior+ecephys+image+ogen.nwb right ALM left ALM 5 10 305 -2.1 -2.8 35.5
132 ALM-ALM sub-440957/sub-440957_ses-20190211T143614_behavior+ecephys+image+ogen.nwb left ALM right ALM 10 5 305 -2118.0 -51.8 -975.3
144 ALM-ALM sub-440957/sub-440957_ses-20190212T153751_behavior+ecephys+image+ogen.nwb right ALM left ALM 8 5 302 -255.0 -141.2 -114.3
148 ALM-ALM sub-440957/sub-440957_ses-20190212T153751_behavior+ecephys+image+ogen.nwb left ALM right ALM 5 8 302 -1.9 -1.9 37.3
160 ALM-ALM sub-442571/sub-442571_ses-20190302T150148_behavior+ecephys+image+ogen.nwb right ALM left ALM 11 1 241 -1000.3 -405.5 -268.1
164 ALM-ALM sub-442571/sub-442571_ses-20190302T150148_behavior+ecephys+image+ogen.nwb left ALM right ALM 1 11 241 -2.0 -2.3 14.1
176 ALM-ALM sub-449141/sub-449141_ses-20190530T173316_behavior+ecephys+image+ogen.nwb right ALM left ALM 13 16 265 -1343.1 -875.5 -1057.7
180 ALM-ALM sub-449141/sub-449141_ses-20190530T173316_behavior+ecephys+image+ogen.nwb left ALM right ALM 16 13 265 -4364.3 -2610.5 -4081.1
192 ALM-ALM sub-449141/sub-449141_ses-20190601T175411_behavior+ecephys+image+ogen.nwb right ALM left ALM 3 6 305 -7.0 -6.1 21.4
196 ALM-ALM sub-449141/sub-449141_ses-20190601T175411_behavior+ecephys+image+ogen.nwb left ALM right ALM 6 3 305 -44.2 -31.5 21.0
208 ALM-ALM sub-455219/sub-455219_ses-20190808T140448_behavior+ecephys+image+ogen.nwb right ALM left ALM 8 9 368 -314.1 -190.7 -205.2
212 ALM-ALM sub-455219/sub-455219_ses-20190808T140448_behavior+ecephys+image+ogen.nwb left ALM right ALM 9 8 368 -42.6 -37.9 -30.0
224 ALM-ALM sub-480134/sub-480134_ses-20210111T122809_behavior+ecephys+ogen.nwb right ALM left ALM 12 8 197 -662.7 -371.8 -549.9
228 ALM-ALM sub-480134/sub-480134_ses-20210111T122809_behavior+ecephys+ogen.nwb left ALM right ALM 8 12 197 -63.7 -58.3 -46.4
240 ALM-ALM sub-480134/sub-480134_ses-20210110T134005_behavior+ecephys+ogen.nwb right ALM left ALM 10 8 227 -212.3 -148.7 -163.3
244 ALM-ALM sub-480134/sub-480134_ses-20210110T134005_behavior+ecephys+ogen.nwb left ALM right ALM 8 10 227 -78.5 -62.3 -61.4
256 ALM-ALM sub-480134/sub-480134_ses-20210113T125455_behavior+ecephys+ogen.nwb right ALM left ALM 24 4 244 -14326.5 -4645.5 -11826.9
260 ALM-ALM sub-480134/sub-480134_ses-20210113T125455_behavior+ecephys+ogen.nwb left ALM right ALM 4 24 244 -25.1 -20.1 -18.7
272 ALM-ALM sub-480135/sub-480135_ses-20210227T131716_behavior+ecephys+ogen.nwb right ALM left ALM 9 4 212 -310.0 -237.5 -106.7
276 ALM-ALM sub-480135/sub-480135_ses-20210227T131716_behavior+ecephys+ogen.nwb left ALM right ALM 4 9 212 -439.3 -94.6 -354.7
288 ALM-ALM sub-480135/sub-480135_ses-20210301T144130_behavior+ecephys+ogen.nwb right ALM left ALM 2 4 237 -362.4 2.1 -2.3
292 ALM-ALM sub-480135/sub-480135_ses-20210301T144130_behavior+ecephys+ogen.nwb left ALM right ALM 4 2 237 -221.7 -84.8 -17.3
304 ALM-ALM sub-480928/sub-480928_ses-20210128T133949_behavior+ecephys+ogen.nwb right ALM left ALM 5 6 165 -662.3 -275.3 -545.8
308 ALM-ALM sub-480928/sub-480928_ses-20210128T133949_behavior+ecephys+ogen.nwb left ALM right ALM 6 5 165 -573.1 -250.7 -332.1
320 ALM-ALM sub-480928/sub-480928_ses-20210130T135022_behavior+ecephys+ogen.nwb right ALM left ALM 5 5 99 -3726.7 -2021.8 -2901.3
324 ALM-ALM sub-480928/sub-480928_ses-20210130T135022_behavior+ecephys+ogen.nwb left ALM right ALM 5 5 99 -1205.3 -456.1 -702.7
336 ALM-ALM sub-480135/sub-480135_ses-20210225T155426_behavior+ecephys+ogen.nwb right ALM left ALM 3 7 260 9.7 7.3 19.2
340 ALM-ALM sub-480135/sub-480135_ses-20210225T155426_behavior+ecephys+ogen.nwb left ALM right ALM 7 3 260 0.8 1.5 18.1
seed_dec = []
for k in SEED_OFFSETS:
d = decode(np.random.default_rng(seed("fig4d-alm-predicts-medulla-null", k)), [(False, True), (True, True)]) if k else dec_main
s_ = dec_summary(d)
s_["offset"] = k
seed_dec.append(s_[s_.R == "R1"])
seed_dec = pd.concat(seed_dec)
print(seed_dec[["offset", "T", "std", "ALM_to_med", "med_to_ALM", "p_asym", "ALM_ALM_A1"]].round(4).to_string())
print("elapsed %.0f s" % (time.time() - T0))
offset T std ALM_to_med med_to_ALM p_asym ALM_ALM_A1 0 0 T1 False -497.0543 -491.4285 0.9931 -4271.6023 2 0 T1 True -307.2720 -319.8714 0.9717 -2188.0667 4 0 T2 False -273.0403 -436.0330 0.7031 -4477.2093 6 0 T2 True -249.0861 -287.9724 0.8816 -3046.6979 0 1000 T1 False -443.6779 -446.2036 0.9961 -4774.8856 1 1000 T1 True -277.5214 -292.9705 0.9525 -2374.4436 2 1000 T2 False -237.3566 -856.6038 0.4949 -4820.1526 3 1000 T2 True -214.6210 -452.3558 0.5977 -2727.0230 0 2000 T1 False -607.1721 -718.4201 0.9062 -3360.1011 1 2000 T1 True -406.6753 -441.7051 0.9485 -1691.4081 2 2000 T2 False -207.0577 -937.4603 0.4488 -4624.4673 3 2000 T2 True -193.1237 -601.1883 0.4848 -2652.3775 0 3000 T1 False -475.1224 -718.2767 0.7696 -3207.9404 1 3000 T1 True -302.0834 -464.5360 0.7317 -1754.3649 2 3000 T2 False -279.0868 -435.6871 0.7277 -3827.5977 3 3000 T2 True -244.9720 -243.9584 0.9966 -2124.7437 0 4000 T1 False -549.1488 -574.9359 0.9737 -3669.8682 1 4000 T1 True -316.0978 -352.1216 0.9293 -1787.1975 2 4000 T2 False -239.8584 -684.5208 0.5129 -4468.0159 3 4000 T2 True -223.8781 -430.6997 0.5983 -2139.1875 elapsed 2392 s
Readings of the R2 and of the z-score, and where the negative values come from. The same splits (claim seed) under: R2 over the whole span (residuals summed over bins, over the variance of the test targets about their mean over all bins and trials, which keeps the time-locked variance that the per-bin R2 removes; not in the claims file's M8, a variant); the median over bins next to the mean; and the subspaces of the example.m z-score (claims, M3 variant), whose rates have lighter tails. Then, per session, the per-bin R2 by epoch and the across-trial variance of the test targets at each bin (T1, unstandardized, R1, main reading).
TAGS = ["T", "std", "R"]
show = ["T", "std", "R", "ALM_to_med", "med_to_ALM", "p_asym", "ALM_ALM_A1", "R_to_L", "L_to_R"]
print("main reading, R2 over the whole span:")
print(dec_summary(dec_main, "r2_span")[show].round(2).to_string())
print("main reading, median over bins of the per-bin R2:")
print(dec_summary(dec_main, "r2_median")[show].round(2).to_string())
dec_z = decode(np.random.default_rng(seed("fig4d-alm-predicts-medulla-null")), ALL_READ, zread="Zall")
print("example.m z-score, per-bin R2 averaged:")
print(dec_summary(dec_z)[show].round(2).to_string())
print("example.m z-score, R2 over the whole span:")
print(dec_summary(dec_z, "r2_span")[show].round(2).to_string())
zmax = {(p, r): f["z_absmax"] if "z_absmax" in f else float(np.abs(f["z"]).max())
for (p, r, rn), f in fits.items() if rn == "main"}
zmax_all = {(p, r): f["z_absmax"] for (p, r, rn), f in fits.items() if rn == "Zall" and "z_absmax" in f}
print("largest |z| over regions: baseline z-score %.0f to %.0f; example.m z-score (bilateral) %.0f to %.0f"
% (min(zmax.values()), max(zmax.values()), min(zmax_all.values()), max(zmax_all.values())))
# per-bin R2 by epoch, main reading, T1, unstandardized, R1
sel = dec_main[(dec_main["T"] == "T1") & (~dec_main["std"]) & (dec_main.R == "R1")]
tb = ms.WINDOWS["W1"][0] + ms.BIN * bins
ep_masks = {"sample": (tb < -1.2), "delay": (tb >= -1.2) & (tb < 0), "response": tb >= 0}
brows = []
for _, r in sel.iterrows():
row = dict(kind=r.kind, session=r.session.split("/")[1][:30], src=r.src, z_absmax_src=round(zmax[(r.session, r.src)]),
predictors_per_train_trial=round(9 * r.d_src / r.n_train, 2), r2_mean=round(r.r2, 1), r2_median=round(r.r2_median, 1),
bins_below_minus1=round(float(np.mean(r.r2_bins < -1)), 2), worst_bin=round(100 * float(r.r2_bins.min())))
for ep, m in ep_masks.items():
row[f"R2 {ep}"] = round(100 * float(r.r2_bins[m].mean()), 1)
row[f"var {ep}"] = round(float(r.tgt_var[m].mean()), 3)
brows.append(row)
bin_df = pd.DataFrame(brows)
print(bin_df.to_string())
print("across sessions and directions, Spearman correlation of mean R2 with the source's largest |z|: %.2f, "
"with the predictors per training trial: %.2f"
% (stats.spearmanr(bin_df.r2_mean, bin_df.z_absmax_src).correlation,
stats.spearmanr(bin_df.r2_mean, bin_df.predictors_per_train_trial).correlation))
allr = dec_main[(dec_main["T"] == "T1") & (~dec_main["std"]) & (dec_main.R == "R1")].assign(ppt=lambda d: 9 * d.d_src / d.n_train)
print("all sessions and directions (incl. ALM to ALM), Spearman correlation of mean R2 with predictors per training trial: %.2f; "
"R2 above 0 in %d of %d, whose largest predictors per trial is %.2f"
% (stats.spearmanr(allr.r2, allr.ppt).correlation, (allr.r2 > 0).sum(), len(allr),
allr[allr.r2 > 0].ppt.max() if (allr.r2 > 0).any() else np.nan))
fig, ax = plt.subplots(1, 2, figsize=(11, 3.2))
for _, r in sel[sel.kind == "ALM-medulla"].iterrows():
ax[0].plot(tb, 100 * np.clip(r.r2_bins, -5, 1), lw=0.6, label=f"{r.session.split('_')[1][4:12]} {r.src}")
ax[1].plot(tb, r.tgt_var, lw=0.6)
ax[0].set(xlabel="time from go cue (s)", ylabel="R2 (%), clipped at -500", title="per-bin R2, ALM and medulla sessions")
ax[1].set(xlabel="time from go cue (s)", ylabel="across-trial variance of target", yscale="log", title="test targets")
ax[0].legend(fontsize=5)
plt.tight_layout()
print("per-bin R2 below -500%% (clipped in the plot): %d of %d bins"
% (sum(int((r.r2_bins < -5).sum()) for _, r in sel[sel.kind == "ALM-medulla"].iterrows()), len(bins) * (sel.kind == "ALM-medulla").sum()))
print("elapsed %.0f s" % (time.time() - T0))
main reading, R2 over the whole span:
T std R ALM_to_med med_to_ALM p_asym ALM_ALM_A1 R_to_L L_to_R
0 T1 False R1 -262.79 -267.73 0.99 -1763.23 -2424.33 -1102.13
1 T1 False R2 -320.48 -292.63 0.95 -1996.22 -2621.68 -1370.76
2 T1 True R1 -143.13 -172.91 0.88 -751.47 -1003.84 -499.10
3 T1 True R2 -177.31 -191.29 0.95 -853.95 -1086.50 -621.39
4 T2 False R1 -135.54 -243.29 0.68 -1831.19 -2028.12 -1634.27
5 T2 False R2 -161.40 -271.32 0.70 -2070.11 -2216.25 -1923.96
6 T2 True R1 -120.27 -159.27 0.82 -1008.57 -881.10 -1136.05
7 T2 True R2 -143.94 -182.27 0.84 -1131.07 -930.71 -1331.43
main reading, median over bins of the per-bin R2:
T std R ALM_to_med med_to_ALM p_asym ALM_ALM_A1 R_to_L L_to_R
0 T1 False R1 -307.94 -83.41 0.37 -1361.85 -1460.39 -1263.31
1 T1 False R2 -364.05 -98.37 0.37 -1720.13 -1892.91 -1547.35
2 T1 True R1 -191.74 -73.80 0.34 -699.63 -816.93 -582.32
3 T1 True R2 -225.69 -88.09 0.34 -852.65 -989.86 -715.44
4 T2 False R1 -194.19 -86.62 0.25 -1616.87 -1520.53 -1713.20
5 T2 False R2 -228.41 -101.22 0.25 -1907.59 -1880.31 -1934.88
6 T2 True R1 -178.77 -82.03 0.23 -988.87 -857.28 -1120.46
7 T2 True R2 -210.33 -96.41 0.22 -1118.04 -980.92 -1255.17
example.m z-score, per-bin R2 averaged:
T std R ALM_to_med med_to_ALM p_asym ALM_ALM_A1 R_to_L L_to_R
0 T1 False R1 -1512.92 -203.75 0.21 -3354.59 -2913.13 -3796.05
1 T1 False R2 -1630.91 -238.40 0.21 -3783.58 -3272.05 -4295.12
2 T1 True R1 -1592.32 -202.50 0.22 -3511.06 -3190.82 -3831.31
3 T1 True R2 -1713.33 -237.14 0.21 -3960.13 -3594.08 -4326.18
4 T2 False R1 -1577.45 -216.10 0.12 -4276.30 -4748.65 -3803.95
5 T2 False R2 -1702.26 -248.10 0.12 -4850.63 -5352.94 -4348.32
6 T2 True R1 -1699.38 -216.48 0.14 -4492.49 -5110.10 -3874.88
7 T2 True R2 -1829.17 -248.78 0.13 -5100.91 -5767.08 -4434.74
example.m z-score, R2 over the whole span:
T std R ALM_to_med med_to_ALM p_asym ALM_ALM_A1 R_to_L L_to_R
0 T1 False R1 -1355.81 -166.93 0.21 -3133.14 -2638.54 -3627.74
1 T1 False R2 -1400.48 -177.91 0.20 -3188.21 -2720.48 -3655.93
2 T1 True R1 -1354.53 -165.12 0.21 -3165.24 -2793.00 -3537.48
3 T1 True R2 -1401.00 -176.05 0.20 -3221.10 -2879.55 -3562.65
4 T2 False R1 -1328.60 -177.40 0.12 -3981.39 -4472.16 -3490.62
5 T2 False R2 -1381.99 -184.41 0.11 -4046.61 -4571.89 -3521.33
6 T2 True R1 -1366.53 -176.21 0.12 -4118.61 -4742.02 -3495.20
7 T2 True R2 -1423.42 -183.25 0.11 -4188.41 -4852.39 -3524.44
largest |z| over regions: baseline z-score 37 to 278; example.m z-score (bilateral) 24 to 124
kind session src z_absmax_src predictors_per_train_trial r2_mean r2_median bins_below_minus1 worst_bin R2 sample var sample R2 delay var delay R2 response var response 0 ALM-medulla sub-456774_ses-20191022T133136 ALM 65 0.86 -2127.7 -1345.6 1.00 -24107 -3005.2 6.924 -2458.4 3.923 -1512.0 17.599 1 ALM-medulla sub-456774_ses-20191022T133136 medulla 203 1.24 -267.0 -231.8 0.97 -965 -268.9 4.256 -364.8 1.738 -188.1 3.904 2 ALM-medulla sub-460436_ses-20200109T111437 ALM 115 0.26 -19.2 1.4 0.10 -700 -42.4 3.822 -21.7 24.895 -8.0 86.952 3 ALM-medulla sub-460436_ses-20200109T111437 medulla 154 0.04 1.6 1.5 0.00 -220 -10.0 2.109 6.4 3.447 2.4 5.058 4 ALM-medulla sub-460436_ses-20200110T142717 ALM 213 0.33 -111.0 -64.8 0.33 -1171 -118.5 7.255 -188.2 4.242 -46.2 79.839 5 ALM-medulla sub-460436_ses-20200110T142717 medulla 177 0.17 -2117.9 -122.8 0.51 -35262 -7566.8 1.513 -1983.0 2.190 -46.3 3.100 6 ALM-medulla sub-484676_ses-20210419T130102 ALM 65 0.19 -193.6 -104.4 0.51 -1406 -346.1 3.314 -161.1 2.284 -158.5 4.635 7 ALM-medulla sub-484676_ses-20210419T130102 medulla 63 0.23 -37.1 -28.1 0.06 -492 -27.9 2.387 -57.8 1.695 -24.1 4.326 8 ALM-medulla sub-484677_ses-20210418T132006 ALM 70 0.31 -33.8 -26.3 0.04 -266 -49.7 2.124 -40.2 2.242 -22.4 3.062 9 ALM-medulla sub-484677_ses-20210418T132006 medulla 75 0.34 -36.7 -35.8 0.00 -96 -38.8 1.464 -33.5 1.628 -38.4 1.495 10 ALM-ALM sub-440956_ses-20190208T133600 right ALM 278 0.23 -53317.8 -15344.4 0.99 -1698766 -13568.2 4.203 -33436.0 8.995 -85123.1 27.739 11 ALM-ALM sub-440956_ses-20190208T133600 left ALM 261 0.31 -59248.0 -17701.5 1.00 -1133351 -88917.4 2.787 -91136.2 3.012 -21869.8 90.167 12 ALM-ALM sub-440956_ses-20190207T120657 right ALM 50 0.34 -199.4 -94.8 0.48 -3457 -252.9 5.842 -185.9 3.689 -188.8 71.688 13 ALM-ALM sub-440956_ses-20190207T120657 left ALM 127 0.06 -19.2 -10.4 0.03 -320 -26.6 2.219 -41.3 1.679 1.5 1.679 14 ALM-ALM sub-440958_ses-20190217T154414 right ALM 37 0.32 -93.3 -74.4 0.29 -787 -76.0 4.761 -88.8 10.344 -103.9 2.039 15 ALM-ALM sub-440958_ses-20190217T154414 left ALM 45 0.03 -3.2 -3.1 0.00 -15 -3.6 1.359 -3.1 1.456 -3.1 1.386 16 ALM-ALM sub-440957_ses-20190211T143614 right ALM 175 0.15 -2.1 -2.8 0.00 -69 -19.2 2.861 6.7 4.048 -2.3 8.482 17 ALM-ALM sub-440957_ses-20190211T143614 left ALM 112 0.30 -2118.0 -51.8 0.42 -61324 -1151.7 2.493 -331.2 6.716 -3933.9 14.535 18 ALM-ALM sub-440957_ses-20190212T153751 right ALM 141 0.24 -255.0 -141.2 0.59 -3185 -223.6 5.113 -198.3 6.527 -312.9 5.697 19 ALM-ALM sub-440957_ses-20190212T153751 left ALM 82 0.15 -1.9 -1.9 0.00 -43 1.3 4.833 -2.7 6.365 -2.6 10.426 20 ALM-ALM sub-442571_ses-20190302T150148 right ALM 49 0.41 -1000.3 -405.5 0.86 -22524 -1402.8 4.655 -1269.5 5.682 -624.0 19.598 21 ALM-ALM sub-442571_ses-20190302T150148 left ALM 64 0.04 -2.0 -2.3 0.00 -40 -2.1 1.619 -0.8 1.967 -2.9 2.805 22 ALM-ALM sub-449141_ses-20190530T173316 right ALM 47 0.44 -1343.1 -875.5 0.97 -16271 -673.0 1.780 -999.5 1.805 -1886.1 1.291 23 ALM-ALM sub-449141_ses-20190530T173316 left ALM 83 0.54 -4364.3 -2610.5 1.00 -30267 -7104.1 1.384 -4716.8 1.458 -2986.3 0.949 24 ALM-ALM sub-449141_ses-20190601T175411 right ALM 47 0.09 -7.0 -6.1 0.00 -45 -12.7 1.887 -7.1 3.114 -4.7 6.049 25 ALM-ALM sub-449141_ses-20190601T175411 left ALM 52 0.18 -44.2 -31.5 0.11 -266 -86.3 1.430 -37.2 2.778 -33.0 4.670 26 ALM-ALM sub-455219_ses-20190808T140448 right ALM 46 0.20 -314.1 -190.7 0.70 -2679 -303.7 1.651 -357.8 1.163 -283.3 2.978 27 ALM-ALM sub-455219_ses-20190808T140448 left ALM 46 0.22 -42.6 -37.9 0.02 -161 -44.9 1.225 -44.3 0.838 -40.3 2.092 28 ALM-ALM sub-480134_ses-20210111T122809 right ALM 76 0.55 -662.7 -371.8 0.95 -6881 -465.7 3.749 -766.6 3.179 -658.4 3.297 29 ALM-ALM sub-480134_ses-20210111T122809 left ALM 60 0.37 -63.7 -58.3 0.08 -200 -67.4 2.527 -54.9 2.094 -69.3 3.143 30 ALM-ALM sub-480134_ses-20210110T134005 right ALM 49 0.40 -212.3 -148.7 0.69 -1522 -165.5 3.558 -272.0 4.277 -183.1 4.858 31 ALM-ALM sub-480134_ses-20210110T134005 left ALM 266 0.32 -78.5 -62.3 0.28 -510 -75.1 2.030 -58.2 2.311 -96.0 2.470 32 ALM-ALM sub-480134_ses-20210113T125455 right ALM 103 0.89 -14326.5 -4645.5 1.00 -375742 -31701.0 2.730 -16463.1 4.495 -5667.4 2.693 33 ALM-ALM sub-480134_ses-20210113T125455 left ALM 83 0.15 -25.1 -20.1 0.00 -103 -23.5 1.808 -19.7 2.003 -30.1 1.574 34 ALM-ALM sub-480135_ses-20210227T131716 right ALM 44 0.38 -310.0 -237.5 0.83 -2329 -343.6 3.955 -357.1 4.702 -258.8 20.383 35 ALM-ALM sub-480135_ses-20210227T131716 left ALM 264 0.17 -439.3 -94.6 0.48 -4722 -514.4 1.485 -852.3 1.317 -78.9 1.636 36 ALM-ALM sub-480135_ses-20210301T144130 right ALM 251 0.08 -362.4 2.1 0.19 -26216 4.3 3.017 -188.4 3.198 -648.2 38.964 37 ALM-ALM sub-480135_ses-20210301T144130 left ALM 157 0.15 -221.7 -84.8 0.46 -7419 -194.5 2.392 -161.8 6.930 -280.6 107.832 38 ALM-ALM sub-480928_ses-20210128T133949 right ALM 203 0.27 -662.3 -275.3 0.75 -7859 -597.3 3.444 -992.5 3.433 -424.1 3.190 39 ALM-ALM sub-480928_ses-20210128T133949 left ALM 73 0.33 -573.1 -250.7 0.75 -5460 -468.1 3.693 -361.1 2.128 -784.7 4.576 40 ALM-ALM sub-480928_ses-20210130T135022 right ALM 80 0.45 -3726.7 -2021.8 0.99 -33340 -4277.1 4.196 -3662.5 3.105 -3557.9 4.475 41 ALM-ALM sub-480928_ses-20210130T135022 left ALM 52 0.45 -1205.3 -456.1 0.85 -14784 -479.1 5.158 -1566.2 5.328 -1207.0 7.461 42 ALM-ALM sub-480135_ses-20210225T155426 right ALM 75 0.10 9.7 7.3 0.00 -11 8.6 2.660 3.8 2.398 14.9 2.098 43 ALM-ALM sub-480135_ses-20210225T155426 left ALM 42 0.24 0.8 1.5 0.00 -76 -0.2 3.443 8.4 3.817 -4.9 3.661 across sessions and directions, Spearman correlation of mean R2 with the source's largest |z|: -0.24, with the predictors per training trial: -0.61 all sessions and directions (incl. ALM to ALM), Spearman correlation of mean R2 with predictors per training trial: -0.62; R2 above 0 in 3 of 44, whose largest predictors per trial is 0.24 per-bin R2 below -500% (clipped in the plot): 991 of 6600 bins elapsed 2553 s
Variants, not readings of the claim: the claim fixes lambda = 0.01. The lagged projections of the smoothed rates are nearly collinear, so the variants show the same decoding with larger penalties, and the median over bins next to the mean (main seed plus 1, T1, standardized predictors, R1).
p0 = next(iter(bilateral))
xl0 = ms.lagged(fits[(p0, "right ALM", "main")]["proj"])[:, bins[300]].astype(float)
print("condition number of the predictor correlation matrix, one bilateral session, one bin: %.3g"
% np.linalg.cond(np.corrcoef(xl0.T)))
lam_rows = []
for lam in (0.01, 1.0, 100.0, 1e4):
rng_l = np.random.default_rng(seed("fig4d-alm-predicts-medulla-null", 1))
for kind, sess_map, pairs in (("ALM-medulla", alm_med, [("ALM", "medulla"), ("medulla", "ALM")]),
("ALM-ALM", bilateral, [("right ALM", "left ALM"), ("left ALM", "right ALM")])):
for p in sess_map:
perm = rng_l.permutation(len(sessions[p]["go"]))
ntr = int(round(0.7 * len(perm)))
for src, tgt in pairs:
r2 = ms.ridge_r2(fits[(p, src, "main")]["proj"], fits[(p, tgt, "main")]["proj"],
perm[:ntr], perm[ntr:], bins, True, True, lam=lam)
lam_rows.append(dict(lam=lam, kind=kind, session=p, src=src, mean=100 * r2.mean(), median=100 * np.median(r2)))
lam_df = pd.DataFrame(lam_rows)
lam_df["dir"] = np.where(lam_df.kind == "ALM-ALM", "ALM to ALM", np.where(lam_df.src == "ALM", "ALM to medulla", "medulla to ALM"))
lam_sum = lam_df.groupby(["lam", "session", "dir"])[["mean", "median"]].mean().groupby(["lam", "dir"]).agg(["mean", "sem"])
print(lam_sum.round(2).to_string())
for lam, d in lam_df.groupby("lam"):
a = d[d.dir == "ALM to medulla"].set_index("session")["mean"]
b = d[d.dir == "medulla to ALM"].set_index("session")["mean"]
t, pv = stats.ttest_rel(a, b.loc[a.index])
print(f"lambda {lam:g}: ALM to medulla minus medulla to ALM {(a - b.loc[a.index]).mean():.2f} points, paired t p = {pv:.3g}")
condition number of the predictor correlation matrix, one bilateral session, one bin: 9.91e+05
mean median
mean sem mean sem
lam dir
0.01 ALM to ALM -2232.15 1574.55 -665.19 371.58
ALM to medulla -248.44 160.37 -184.37 129.08
medulla to ALM -631.39 532.80 -162.96 93.75
1.00 ALM to ALM -124.51 58.91 -49.16 15.42
ALM to medulla -32.78 4.81 -21.22 3.46
medulla to ALM -43.16 19.26 -21.54 7.96
100.00 ALM to ALM 6.95 2.48 7.64 2.37
ALM to medulla 16.59 5.37 15.92 5.85
medulla to ALM 10.41 3.30 9.43 3.88
10000.00 ALM to ALM 4.88 1.00 4.20 0.94
ALM to medulla 7.14 1.47 6.11 1.53
medulla to ALM 4.85 1.81 4.32 1.90
lambda 0.01: ALM to medulla minus medulla to ALM 382.96 points, paired t p = 0.548
lambda 1: ALM to medulla minus medulla to ALM 10.38 points, paired t p = 0.627
lambda 100: ALM to medulla minus medulla to ALM 6.17 points, paired t p = 0.0943
lambda 10000: ALM to medulla minus medulla to ALM 2.29 points, paired t p = 0.374
Result (fig4d-alm-predicts-medulla-null): not reproduced. With lambda = 0.01 the decoder fails on held-out trials under every reading: mean R2 from -611.5 to -249.1% for ALM to medulla and from -6098.6 to -2191.3% for ALM to ALM (A1), against 40 and 54%, and it stays negative under the five seeds. The negative values are not an artefact of the averaging or the denominator: the median over bins is -364.9 to -178.8% (ALM to medulla), and the R2 over the whole span, which keeps the time-locked variance, is -320.8 to -120.3%. Nor do they come mainly from the heavy tails of the baseline z-score: with the example.m z-score, whose largest |z| is 24 to 124 in the bilateral sessions, ALM to medulla falls to -1828.9 to -1512.9%. Over the 44 session and direction pairs the R2 falls with the number of predictors per training trial (9 times the source dimensions over the training trials; Spearman correlation -0.61) more than with the source's largest |z| (-0.24); it is above zero in 3 of 44 pairs, all with 0.24 predictors per trial or fewer. The nine lagged copies of the smoothed projections are nearly collinear (condition number about 1e6), and lambda = 0.01 barely regularizes them. In the variants with larger penalties R2 is at most 16.6% (ALM to medulla, lambda 100), and ALM to ALM (6.9%) stays below ALM to medulla, the reverse of the paper.
Result (fig4d-decoding-asymmetry): not reproduced. Under every reading the paired t test of ALM to medulla against medulla to ALM gives p = 0.70 to 0.99 over the 5 sessions, and medulla to ALM R2 is -517.9 to -290.4%, against 21 +- 6.7%; over the five seeds p is 0.45 to 1.00. Under the median over bins, the R2 over the span and the example.m z-score, p is 0.11 to 0.99. In the lambda = 100 variant ALM to medulla exceeds medulla to ALM by 6.2 points (p = 0.091), with medulla to ALM at 10.4%. Under reading G2 (second notebook) every R2 is below -10^6 % and p is 0.15 to 0.87.
Claim fig4f-medulla-null-not-spanning-almΒΆ
In a joint UMAP embedding of movement-null activity, medullary units do not span the set of movement-null activity patterns seen in ALM.
M10: equal numbers of left and right correct trials, half to train and half to test; trial-averaged movement-null reconstructions (X Q Q') of both trial types concatenated in time; z-scored per unit on the training set; UMAP (2 components, 30 neighbours, min_dist 0.3, cosine), fitted on the training data of ALM and medulla units together, test data transformed. The paper judges by inspection; the numbers below describe the test embedding: for each unit, whether any of its 10 nearest neighbours is from the other region, against the same count with the region labels shuffled (1000 times) over all units and within each session (which keeps any clumping of units by session). The embedding is also shown by session, with each region's extent, and again without the session whose medulla has a one-dimensional null subspace.
import umap
from sklearn.neighbors import NearestNeighbors
def umap_run(rng, random_state, exclude=()):
train_rows, test_rows, region, sess = [], [], [], []
for p, s in alm_med.items():
if p in exclude:
continue
v = sessions[p]
trials = v["sess"]["trials"]
out_arr = np.array(trials["outcome"])[v["keep"]]
instr = np.array(trials["trial_instruction"])[v["keep"]]
r_idx = rng.permutation(np.where((out_arr == "hit") & (instr == "right"))[0])
l_idx = rng.permutation(np.where((out_arr == "hit") & (instr == "left"))[0])
n = min(len(r_idx), len(l_idx))
r_idx, l_idx = r_idx[:n], l_idx[:n]
h = n // 2
for reg in ("ALM", "medulla"):
f0 = fits[(p, reg, "main")]
rec = f0["z"] @ f0["qn"] @ f0["qn"].T
tr = np.concatenate([rec[r_idx[:h]].mean(0), rec[l_idx[:h]].mean(0)], axis=0)
te = np.concatenate([rec[r_idx[h:]].mean(0), rec[l_idx[h:]].mean(0)], axis=0)
mu, sd = tr.mean(0), tr.std(0)
sd = np.where(sd > 0, sd, 1.0)
train_rows.append(((tr - mu) / sd).T)
test_rows.append(((te - mu) / sd).T)
region += [reg] * tr.shape[1]
sess += [p.split("/")[1][:30]] * tr.shape[1]
Xtr, Xte = np.vstack(train_rows), np.vstack(test_rows)
model = umap.UMAP(n_components=2, n_neighbors=30, min_dist=0.3, metric="cosine", random_state=random_state)
model.fit(Xtr)
return model.transform(Xte), np.array(region), np.array(sess)
def nn_stats(emb, region, rng, k=10, n_shuffle=1000, within=None):
"""Observed shares, and the null with region labels shuffled over all units or, with `within`
(a session label per unit), within each session."""
nn = NearestNeighbors(n_neighbors=k + 1).fit(emb)
_, ind = nn.kneighbors(emb)
ind = ind[:, 1:]
def frac(lab):
other = lab[ind] != lab[:, None]
alm_alone = np.mean(~other[lab == "ALM"].any(1))
med_with_alm = np.mean(other[lab == "medulla"].any(1))
return alm_alone, med_with_alm
def shuffled():
if within is None:
return rng.permutation(region)
lab = region.copy()
for s_ in np.unique(within):
m = within == s_
lab[m] = rng.permutation(region[m])
return lab
obs = frac(region)
null = np.array([frac(shuffled()) for _ in range(n_shuffle)])
return obs, null
umap_res = {}
for k in SEED_OFFSETS:
sd_ = seed("fig4f-medulla-null-not-spanning-alm", k)
rng_u = np.random.default_rng(sd_)
emb, region, sess = umap_run(rng_u, random_state=sd_ % (2 ** 31))
obs, null = nn_stats(emb, region, rng_u)
_, null_w = nn_stats(emb, region, rng_u, within=sess)
umap_res[k] = (emb, region, sess, obs, null, null_w)
print(f"seed offset {k}: ALM units with no medulla unit among 10 neighbours {100 * obs[0]:.1f}% "
f"(labels shuffled over all units {100 * null[:, 0].mean():.1f}%, within session {100 * null_w[:, 0].mean():.1f}%, "
f"95th pct {100 * np.percentile(null_w[:, 0], 95):.1f}%); "
f"medulla units with an ALM neighbour {100 * obs[1]:.1f}% (over all {100 * null[:, 1].mean():.1f}%, "
f"within session {100 * null_w[:, 1].mean():.1f}%, 5th pct {100 * np.percentile(null_w[:, 1], 5):.1f}%)")
emb, region, sess, obs, null, null_w = umap_res[0]
fig, ax = plt.subplots(1, 2, figsize=(10, 4.5))
for reg, c in (("ALM", "tab:blue"), ("medulla", "tab:orange")):
ax[0].scatter(*emb[region == reg].T, s=6, c=c, label=f"{reg} ({(region == reg).sum()})", alpha=0.7)
ax[0].legend()
ax[0].set(title="Test-set UMAP of movement-null reconstructions", xlabel="UMAP 1", ylabel="UMAP 2")
for k_, s_ in enumerate(np.unique(sess)):
for reg, mk_ in (("ALM", "o"), ("medulla", "^")):
m = (sess == s_) & (region == reg)
ax[1].scatter(*emb[m].T, s=8, marker=mk_, color=plt.cm.tab10(k_), alpha=0.7,
label=f"{s_[:19]} {reg}")
ax[1].legend(fontsize=5)
ax[1].set(title="by session (circles ALM, triangles medulla)", xlabel="UMAP 1", ylabel="UMAP 2")
plt.tight_layout()
ext = []
for s_ in np.unique(sess):
p_ = next(p for p in alm_med if s_ in p)
for reg in ("ALM", "medulla"):
e = emb[(sess == s_) & (region == reg)]
ext.append(dict(session=s_, region=reg, units=len(e), d_null=fits[(p_, reg, "main")]["d"][0],
x_lo=round(float(e[:, 0].min()), 2), x_hi=round(float(e[:, 0].max()), 2),
y_lo=round(float(e[:, 1].min()), 2), y_hi=round(float(e[:, 1].max()), 2),
spread=round(float(np.linalg.norm(e - e.mean(0), axis=1).mean()), 2)))
print(pd.DataFrame(ext).to_string())
print("embedding range: x %.2f to %.2f, y %.2f to %.2f; all points shown" % (emb[:, 0].min(), emb[:, 0].max(), emb[:, 1].min(), emb[:, 1].max()))
# extent: the share of the ALM points' 2-d spread covered by medulla points
for reg in ("ALM", "medulla"):
e = emb[region == reg]
print(reg, "5th to 95th percentile: x %.2f to %.2f, y %.2f to %.2f" % (*np.percentile(e[:, 0], [5, 95]), *np.percentile(e[:, 1], [5, 95])))
grid = np.floor((emb - emb.min(0)) / ((emb.max(0) - emb.min(0)) / 10 + 1e-12)).astype(int)
cells_alm = {tuple(g) for g, r in zip(grid, region) if r == "ALM"}
cells_med = {tuple(g) for g, r in zip(grid, region) if r == "medulla"}
print("10 x 10 grid cells holding ALM units: %d, of which hold no medulla unit: %d; medulla cells outside ALM cells: %d of %d"
% (len(cells_alm), len(cells_alm - cells_med), len(cells_med - cells_alm), len(cells_med)))
# variant: without the session whose medulla has d_null = 1 (all its units lie on one line)
low = [p for p in alm_med if fits[(p, "medulla", "main")]["d"][0] < 2 or fits[(p, "ALM", "main")]["d"][0] < 2]
rng_u = np.random.default_rng(seed("fig4f-medulla-null-not-spanning-alm", 1))
emb_x, region_x, sess_x = umap_run(rng_u, random_state=seed("fig4f-medulla-null-not-spanning-alm", 1) % (2 ** 31), exclude=low)
obs_x, null_x = nn_stats(emb_x, region_x, rng_u, within=sess_x)
grid_x = np.floor((emb_x - emb_x.min(0)) / ((emb_x.max(0) - emb_x.min(0)) / 10 + 1e-12)).astype(int)
ca = {tuple(g) for g, r in zip(grid_x, region_x) if r == "ALM"}
cm_ = {tuple(g) for g, r in zip(grid_x, region_x) if r == "medulla"}
print("without", [p.split("/")[1][:30] for p in low], "(claim seed plus 1):",
f"ALM units with no medulla neighbour {100 * obs_x[0]:.1f}% (within-session shuffle {100 * null_x[:, 0].mean():.1f}%), "
f"medulla units with an ALM neighbour {100 * obs_x[1]:.1f}% (within-session shuffle {100 * null_x[:, 1].mean():.1f}%); "
f"grid cells with ALM {len(ca)}, of which without medulla {len(ca - cm_)}; medulla cells outside ALM cells {len(cm_ - ca)} of {len(cm_)}")
for reg in ("ALM", "medulla"):
e = emb_x[region_x == reg]
print(" ", reg, "5th to 95th percentile: x %.2f to %.2f, y %.2f to %.2f" % (*np.percentile(e[:, 0], [5, 95]), *np.percentile(e[:, 1], [5, 95])))
print("elapsed %.0f s, peak memory %.0f MB" % (time.time() - T0, resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1e3))
/home/runner/work/encore/encore/executed/hasnain-2025/.venv/lib/python3.13/site-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html from .autonotebook import tqdm as notebook_tqdm
/tmp/ipykernel_2567/3832606429.py:32: FutureWarning: compatibility_layout was not set, so UMAP is using the legacy (0.5.x) nearest-neighbor, initialization and layout pipeline. In a future release the default will change to compatibility_layout=False, which uses recursive initialization and the Adam optimizer and produces different embeddings. Set compatibility_layout=True to keep the current behavior and silence this warning, or compatibility_layout=False (or optimizer='adam') to adopt the new behavior now. model.fit(Xtr) /home/runner/work/encore/encore/executed/hasnain-2025/.venv/lib/python3.13/site-packages/umap/umap_.py:3099: UserWarning: n_jobs value -1 overridden to 1 by setting random_state. Use no seed for parallelism. warn(
seed offset 0: ALM units with no medulla unit among 10 neighbours 33.3% (labels shuffled over all units 0.1%, within session 0.1%, 95th pct 0.3%); medulla units with an ALM neighbour 57.4% (over all 99.8%, within session 99.8%, 5th pct 98.8%)
/tmp/ipykernel_2567/3832606429.py:32: FutureWarning: compatibility_layout was not set, so UMAP is using the legacy (0.5.x) nearest-neighbor, initialization and layout pipeline. In a future release the default will change to compatibility_layout=False, which uses recursive initialization and the Adam optimizer and produces different embeddings. Set compatibility_layout=True to keep the current behavior and silence this warning, or compatibility_layout=False (or optimizer='adam') to adopt the new behavior now. model.fit(Xtr) /home/runner/work/encore/encore/executed/hasnain-2025/.venv/lib/python3.13/site-packages/umap/umap_.py:3099: UserWarning: n_jobs value -1 overridden to 1 by setting random_state. Use no seed for parallelism. warn(
seed offset 1000: ALM units with no medulla unit among 10 neighbours 31.7% (labels shuffled over all units 0.0%, within session 0.1%, 95th pct 0.3%); medulla units with an ALM neighbour 60.0% (over all 99.8%, within session 99.7%, 5th pct 98.8%)
/tmp/ipykernel_2567/3832606429.py:32: FutureWarning: compatibility_layout was not set, so UMAP is using the legacy (0.5.x) nearest-neighbor, initialization and layout pipeline. In a future release the default will change to compatibility_layout=False, which uses recursive initialization and the Adam optimizer and produces different embeddings. Set compatibility_layout=True to keep the current behavior and silence this warning, or compatibility_layout=False (or optimizer='adam') to adopt the new behavior now. model.fit(Xtr) /home/runner/work/encore/encore/executed/hasnain-2025/.venv/lib/python3.13/site-packages/umap/umap_.py:3099: UserWarning: n_jobs value -1 overridden to 1 by setting random_state. Use no seed for parallelism. warn(
seed offset 2000: ALM units with no medulla unit among 10 neighbours 26.7% (labels shuffled over all units 0.1%, within session 0.1%, 95th pct 0.3%); medulla units with an ALM neighbour 65.9% (over all 99.8%, within session 99.8%, 5th pct 98.8%)
/tmp/ipykernel_2567/3832606429.py:32: FutureWarning: compatibility_layout was not set, so UMAP is using the legacy (0.5.x) nearest-neighbor, initialization and layout pipeline. In a future release the default will change to compatibility_layout=False, which uses recursive initialization and the Adam optimizer and produces different embeddings. Set compatibility_layout=True to keep the current behavior and silence this warning, or compatibility_layout=False (or optimizer='adam') to adopt the new behavior now. model.fit(Xtr) /home/runner/work/encore/encore/executed/hasnain-2025/.venv/lib/python3.13/site-packages/umap/umap_.py:3099: UserWarning: n_jobs value -1 overridden to 1 by setting random_state. Use no seed for parallelism. warn(
seed offset 3000: ALM units with no medulla unit among 10 neighbours 23.3% (labels shuffled over all units 0.0%, within session 0.1%, 95th pct 0.3%); medulla units with an ALM neighbour 61.5% (over all 99.9%, within session 99.7%, 5th pct 98.8%)
/tmp/ipykernel_2567/3832606429.py:32: FutureWarning: compatibility_layout was not set, so UMAP is using the legacy (0.5.x) nearest-neighbor, initialization and layout pipeline. In a future release the default will change to compatibility_layout=False, which uses recursive initialization and the Adam optimizer and produces different embeddings. Set compatibility_layout=True to keep the current behavior and silence this warning, or compatibility_layout=False (or optimizer='adam') to adopt the new behavior now. model.fit(Xtr) /home/runner/work/encore/encore/executed/hasnain-2025/.venv/lib/python3.13/site-packages/umap/umap_.py:3099: UserWarning: n_jobs value -1 overridden to 1 by setting random_state. Use no seed for parallelism. warn(
seed offset 4000: ALM units with no medulla unit among 10 neighbours 28.3% (labels shuffled over all units 0.0%, within session 0.1%, 95th pct 0.3%); medulla units with an ALM neighbour 60.0% (over all 99.8%, within session 99.7%, 5th pct 98.5%)
session region units d_null x_lo x_hi y_lo y_hi spread
0 sub-456774_ses-20191022T133136 ALM 85 9 -3.57 3.96 3.08 13.52 2.59
1 sub-456774_ses-20191022T133136 medulla 128 13 -4.46 1.22 4.10 12.74 2.40
2 sub-460436_ses-20200109T111437 ALM 81 6 -2.76 2.50 2.65 13.66 4.29
3 sub-460436_ses-20200109T111437 medulla 65 1 0.39 11.39 -3.38 13.97 7.62
4 sub-460436_ses-20200110T142717 ALM 48 8 -3.23 12.72 -4.02 12.69 4.53
5 sub-460436_ses-20200110T142717 medulla 60 4 -3.03 2.00 1.75 13.77 2.89
6 sub-484676_ses-20210419T130102 ALM 46 5 -1.51 4.24 2.82 13.33 2.65
7 sub-484676_ses-20210419T130102 medulla 31 6 -4.51 3.83 2.19 13.56 4.44
8 sub-484677_ses-20210418T132006 ALM 40 10 -1.55 11.18 -3.08 14.01 3.07
9 sub-484677_ses-20210418T132006 medulla 56 11 -2.15 2.69 1.89 11.48 2.76
embedding range: x -4.51 to 12.72, y -4.02 to 14.01; all points shown
ALM 5th to 95th percentile: x -3.07 to 3.87, y 2.85 to 13.15
medulla 5th to 95th percentile: x -4.03 to 11.39, y -3.38 to 13.57
10 x 10 grid cells holding ALM units: 28, of which hold no medulla unit: 3; medulla cells outside ALM cells: 2 of 27
/tmp/ipykernel_2567/3832606429.py:32: FutureWarning: compatibility_layout was not set, so UMAP is using the legacy (0.5.x) nearest-neighbor, initialization and layout pipeline. In a future release the default will change to compatibility_layout=False, which uses recursive initialization and the Adam optimizer and produces different embeddings. Set compatibility_layout=True to keep the current behavior and silence this warning, or compatibility_layout=False (or optimizer='adam') to adopt the new behavior now. model.fit(Xtr) /home/runner/work/encore/encore/executed/hasnain-2025/.venv/lib/python3.13/site-packages/umap/umap_.py:3099: UserWarning: n_jobs value -1 overridden to 1 by setting random_state. Use no seed for parallelism. warn(
without ['sub-460436_ses-20200109T111437'] (claim seed plus 1): ALM units with no medulla neighbour 20.1% (within-session shuffle 0.1%), medulla units with an ALM neighbour 67.6% (within-session shuffle 99.7%); grid cells with ALM 62, of which without medulla 20; medulla cells outside ALM cells 20 of 62 ALM 5th to 95th percentile: x 6.21 to 14.03, y 6.21 to 12.57 medulla 5th to 95th percentile: x 6.81 to 14.41, y 6.45 to 14.09 elapsed 2677 s, peak memory 4596 MB
Result: partially reproduced. In the test-set embedding 25.7% of ALM units have no medulla unit among their 10 nearest neighbours, against 0.1% with the region labels shuffled over all units and 0.1% with them shuffled within each session (21.3 to 27.3% over the five seeds), and 6 of the 26 grid cells that hold ALM units hold no medulla unit. So part of the ALM movement-null patterns has no medulla counterpart, as the paper reports, and this is not the clumping of units by session, which the within-session shuffle keeps. The second part of the criterion holds only in part. On the grid of the claim seed's embedding no medulla cell (0 of 20) lies outside the cells that hold ALM units, but only 59.4% of medulla units have an ALM unit among their neighbours (99.7% with labels shuffled within session; 58.2 to 62.6% over the seeds). The medulla of sub-460436_ses-20200109 has d_null = 1, and its units spread along one line (spread 9.75, against 2.3 to 4.7 for the other regions); without that session (claim seed plus 1), 21.0% of ALM units have no medulla neighbour, 16 of 57 ALM cells hold no medulla unit, and 26 of 67 medulla cells lie outside the ALM cells. The judgment rests on these counts and the plots, as the paper's rests on inspection.
SummaryΒΆ
| Claim | Outcome |
|---|---|
| Eleven claims on the paper's own recordings (Figures 1 to 3, Extended Data Figures 2 and 3) | Blocked: data missing |
| map-session-selection | Not reproduced |
| fig4b-medulla-selectivity | Partially reproduced |
| fig4c-alm-null-potent-similar | Partially reproduced, resting on reading G1 (reproduced under G2) |
| fig4c-medulla-null-smaller | Reproduced under the claim's seed, resting on readings G1, B2 and V2; partially reproduced under two other seeds and under G2 |
| fig4d-alm-predicts-medulla-null | Not reproduced |
| fig4d-decoding-asymmetry | Not reproduced |
| fig4e-medulla-null-lower-dimension | Not reproduced, resting on reading G1 (reproduced under G2 with N2) |
| fig4f-medulla-null-not-spanning-alm | Partially reproduced |
A failure to reproduce here may be a failure of this attempt, not of the paper: see the reasoning and the differences from the paper's method.
How the analysis differs from the paper's:
- Under reading G1 of 'good' the selection gives 5 ALM and medulla sessions (paper 16 or 11) and 17 bilateral sessions (paper 20), so every Figure 4 test here runs on fewer sessions and units than the paper's. Reading G2 (second notebook) gives 19 ALM and medulla sessions with about 2.5 times the paper's units; its CCF labels are transferred from the nearest unit classified good.
- The movement threshold is Otsu's threshold on the log speed, where the paper set it by hand; the keypoint positions are smoothed (3 frames) first.
- Ignore, photostimulation and early-lick trials are left out, and so are trials whose delay is not 1.2 s (446 correct and error trials over the 22 sessions).
- The dimension shuffle uses 100 shuffles on every 4th bin (the paper 1000 on all bins).
- UMAP runs in umap-learn, not MATLAB's run_umap.
- The readings of the claims file were each run with the others held at the main reading, not in every combination.
- The unit selection is held at reading G1 for every outcome, while the readings of M3 to M6 (and the seeds) are searched for one under which a claim holds. fig4c-medulla-null-smaller is reproduced under one such combination (B2 with V2). Applied the same way to G2, fig4c-alm-null-potent-similar would be reproduced (main reading, V2, 33.9 against 42.7%, p = 0.251) and fig4e-medulla-null-lower-dimension reproduced under N2 (p = 0.027). G1 is kept because its bilateral unit counts are near the paper's and its CCF labels are the dataset's own; G2 brings units with a baseline |z| up to 53615 and transferred labels.
- The numbers depend slightly on the processor that runs the notebook: the linear algebra library picks its kernels by processor, and the last digits of the subspace fits differ between kernels. Most numbers move in the third or fourth digit, but the shuffle dimension of a few G2 regions, the decoding R2 (lambda = 0.01 barely regularizes nearly collinear predictors) and the UMAP embedding amplify the difference. An earlier execution on another runner gave other values for these (listed in the attempt record), with the same outcomes. The text here is written from this execution.
What was found about the dataset:
anno_name(the CCF label) is filled only for units whoseclassificationis good (69453 of 272227 units), and 1852 units have noclassification. The electrodes table holds CCF coordinates, from which the label of other units can be estimated.- The trial table has no column for the delay duration. In the ALM and medulla sessions and the 2021 bilateral sessions, 13 to 57 correct and error trials per session have a 1.8 s or 0.3 s delay, which shows only in the sample and delay event times.
- Some units have near-silent baselines, so the baseline z-score of the Methods gives values up to 278 s.d. among G1 units and above 50000 among G2 units.
- The jaw and nose tracking are in pixels, at about 294 Hz, in one segment per trial; unsmoothed, their frame-to-frame jitter hides movement. Nearly every bin of the kept trials has tracking.
- Clocks: in every selected session the tongue becomes visible a median 56 to 262 ms after the go cue, and lick direction is decoded from spike counts after the go cue above the shuffled labels, so the spike, video and trial clocks are consistent.
- The units of the session compared are identical in versions 0.230822.0128 and 0.231012.2129.