Temmar et al. (2025), LINK: the dataset, neural signals and tuning over time¶

Paper: Temmar, Gill, Wang et al., "Long-term Intracortical Neural activity and Kinematics (LINK): An intracortical neural dataset for chronic brain-machine interfaces, neuroscience, and machine learning", NeurIPS 2025 Datasets and Benchmarks, doi:10.52202/085713-4642.

Dataset: DANDI:001201, version 0.261026.1912 (doi:10.48324/dandi.001201/0.261026.1912), streamed. The paper cites no version, so the most recent published one is pinned. The dandiset has three published versions (0.251023.2336, 0.261015.2153, 0.261026.1912); the cell below shows that the three list the same 312 assets with the same asset identifiers, so the data the analysis uses do not differ between them.

Claims file: claims/temmar-2025.yaml, written from the version of record (NeurIPS proceedings) and the supplement (Appendices A to C, Figures S1 to S6). Code read for method details: github.com/chesteklab/LINK_dataset at commit 5e1c36a1282f90abb8d96963920a8b1fdd27a6e7.

This notebook tests the claims on the dataset's contents, the neural signals over time (Figure 2, S2, S4, S5) and single-channel tuning (Figure 3). The decoding claims (Figures 4 and 5) are in decoding.ipynb and multiday.ipynb.

Claim Notebook Tested
dataset-sessions this one tested
dataset-contents this one tested
figs2-throughput-improves this one tested
fig2a-sbp-decline this one tested
fig2a-irregular-shifts decoding.ipynb tested
fig2b-active-channels-decrease this one tested
fig2c-pr-decline this one tested
fig2c-ten-dimensions this one tested
figs4-bank-slopes this one tested
figs5-active-inactive-slopes this one tested
fig2d-population-drift this one tested
fig2e-trajectories-separable this one tested
fig3b-two-channels this one tested
fig3cd-tuning-stable this one tested
fig3d-weak-channels-low-tcr this one tested
fig3e-array-tuning this one tested
fig4a-sameday-stable, fig4a-lstm-beats-rr, fig4bc-dof-accuracy, fig4d-cross-day-decay, suppc1-shuffle-baseline decoding.ipynb tested, the LSTM on a subset of sessions
fig5a-multiday-short-term, fig5a-long-term-decay multiday.ipynb tested on a subset of day-0 sessions
fig5b-finetune none blocked, too large
In [1]:
import os, time, resource
import numpy as np
import pandas as pd
import requests
import matplotlib.pyplot as plt
from concurrent.futures import ThreadPoolExecutor
from scipy import stats
from sklearn.decomposition import PCA
import link

T0 = time.time()
SUBSET = int(os.environ.get("LINK_SUBSET", "0"))   # 0 = every session; set only while developing
A = link.assets()
print(len(A), "assets in version", link.VERSION)
meta = link.version_metadata()
print(meta["name"], "|", meta["doi"])
for v in ["0.251023.2336", "0.261015.2153"]:
    r = requests.get(f"{link.API}/dandisets/{link.DANDISET}/versions/{v}/assets/?page_size=1000", timeout=60).json()
    old = {x["path"]: x["asset_id"] for x in r["results"]}
    same = sum(old.get(p) == a for p, a in zip(A["path"], A["asset_id"]))
    print(f"version {v}: {len(old)} assets, {same} with the same path and asset id as {link.VERSION}")
312 assets in version 0.261026.1912
LINK: Long-Term Intracortical Neural Activity and Kinematics | 10.48324/dandi.001201/0.261026.1912
version 0.251023.2336: 312 assets, 312 with the same path and asset id as 0.261026.1912
version 0.261015.2153: 312 assets, 312 with the same path and asset id as 0.261026.1912

What one file holds¶

Everything in the first session file: its time series with shapes, units and conversion factors, every column of the trials and electrodes tables, and the subject.

In [2]:
lay = link.read_layout(A["asset_id"][0])
print(A["path"][0])
for k, v in lay["series"].items():
    print(f"  analysis/{k}: {v}")
print("trials columns:", lay["trial_columns"], "| rows:", lay["n_trials"])
print(lay["trials"].head(3).to_string())
print("electrodes columns:", list(lay["electrodes"].columns))
print(lay["electrodes"].head(4).to_string())
print(lay["electrodes"].groupby(["array_name", "bank"]).size())
print("identifier:", lay["identifier"], "| session_start_time:", lay["session_start_time"])
print("subject:", lay["subject"], "| first timestamp:", lay["first_t"], "s | bin steps:", lay["dt"])
sub-Monkey-N/sub-Monkey-N_ses-20200127_ecephys.nwb
  analysis/SpikingBandPower: {'shape': (27649, 96), 'unit': 'volts', 'conversion': 1e-06, 'n_timestamps': 27649, 'description': 'Spiking Band Power across time, in 20ms bins'}
  analysis/ThresholdCrossings: {'shape': (27649, 96), 'unit': 'volts', 'conversion': 1.0, 'n_timestamps': 27649, 'description': 'Threshold crossings (threshold = -4.5RMS) across time, in 20ms bins'}
  analysis/index_position: {'shape': (27649, 1), 'unit': 'flexion units', 'conversion': 1.0, 'n_timestamps': 27649, 'description': 'Index flexion position, from fully extended (0) to fully flexed (1)'}
  analysis/index_velocity: {'shape': (27649, 1), 'unit': 'flexion units per time bin', 'conversion': 1.0, 'n_timestamps': 27649, 'description': 'Velocity of index flexion'}
  analysis/mrs_position: {'shape': (27649, 1), 'unit': 'flexion units', 'conversion': 1.0, 'n_timestamps': 27649, 'description': 'Middle-ring-pinky flexion position, from fully extended (0) to fully flexed (1)'}
  analysis/mrs_velocity: {'shape': (27649, 1), 'unit': 'flexion units per time bin', 'conversion': 1.0, 'n_timestamps': 27649, 'description': 'Velocity of middle-ring-pinky flexion'}
trials columns: ['start_time', 'stop_time', 'trial_number', 'trial_count', 'run_id', 'index_target_position', 'mrs_target_position', 'target_style', 'trial_timeout', 'timeseries'] | rows: 375
   start_time  stop_time  trial_count target_style
0        8.41       9.67           64           CO
1        9.69      11.05           69           CO
2       11.07      12.95           95           CO
electrodes columns: ['id', 'array_name', 'group_name', 'bank', 'pin', 'row', 'col', 'imp', 'location']
   id array_name group_name bank  pin  row  col       imp         location
0   0    Lateral    Lateral    A    1    1    0  267000.0  Hand area of M1
1   1    Lateral    Lateral    A    2    0    0   72000.0  Hand area of M1
2   2    Lateral    Lateral    A    3    2    0  139000.0  Hand area of M1
3   3    Lateral    Lateral    A    4    3    0  232000.0  Hand area of M1
array_name  bank
Lateral     A       32
Medial      B       32
            C       32
dtype: int64
identifier: 2020-01-27_CO_nwb | session_start_time: 2020-01-27T00:00:00+00:00
subject: {'subject_id': 'Monkey N', 'date_of_birth': '2012-05-26T00:00:00+00:00', 'sex': 'M', 'species': 'Macaca mulatta'} | first timestamp: 8.41 s | bin steps: [0.019 0.02  0.021]

One pass over the dataset¶

Each file is streamed once and reduced to what the claims below use. Per session: the mean SBP and TCR per channel, the sums for a whole-dataset PCA, the participation ratio of the active channels, per-trial throughput, and checks of the contents. Per day (both sessions concatenated on two-session days, as signal_utils.calc_avg_sbps and the tuning code do): the mean SBP per channel, the tuning of each channel, and the per-day PCA trajectories of Figure 2E.

In [3]:
def trial_bounds(sess):
    ti = sess["trial_index"]
    return ti, np.append(ti[1:], len(sess["t"]))


def trajectories(sessions, pcs_day):
    """Per-trial 3-PC trajectories for the two alignment readings of fig2e (claim criterion)."""
    out = []
    off = 0
    for s in sessions:
        st, en = trial_bounds(s)
        cls = link.trial_directions(s["trials"])
        for i in range(len(st)):
            if cls[i] < 0:
                continue
            v = s["kin"][st[i]:en[i], 3 if link.mrs_dominant(cls[i]) else 2].astype(float)
            rec = {"date": s["date"], "cls": int(cls[i]), "style": s["style"]}
            for name, k, pre, n in (("main", 1.0, 0, 37), ("code", 2.0, 7, 37)):
                on, al = link.onset_and_jerk(v, k)
                a0 = None if al is None else al - pre
                if a0 is None or a0 < 0 or a0 + n > en[i] - st[i]:
                    rec[name] = None
                else:
                    rec[name] = pcs_day[off + st[i] + a0: off + st[i] + a0 + n].astype(np.float32)
            out.append(rec)
        off += len(s["t"])
    return out


def reduce_day(rows):
    sessions = []
    for _, r in rows.iterrows():
        s = link.read_session(r["asset_id"], meta=True)
        s["date"] = r["date"]
        s["path"] = r["path"]
        sessions.append(s)
    recs = []
    for s in sessions:
        x = s["sbp"].astype(np.float64)
        tc = s["tcr"] * link.TCR_TO_HZ
        act = tc.mean(0) > 1
        pr, ev = link.participation_ratio(s["sbp"][:, act]) if act.any() else (np.nan, np.array([]))
        dpos = np.diff(s["kin"][:, :2].astype(float), axis=0)
        st, en = trial_bounds(s)
        recs.append({
            "date": s["date"], "path": s["path"], "style": s["style"], "identifier": s["identifier"],
            "start": s["start"], "n_trials": len(s["trials"]), "n_bins": len(s["t"]),
            "styles_in_trials": sorted(set(s["trials"]["target_style"])),
            "dt": np.unique(np.round(np.diff(s["t"]), 3)),
            "t_first": s["t"][0], "t_last": s["t"][-1],
            "series": s["series"], "trial_columns": s["trial_columns"], "electrodes": s["electrodes"],
            "electrode_columns": s["electrode_columns"],
            "sbp_mean": x.mean(0), "sbp_sum": x.sum(0), "sbp_xx": x.T @ x,
            "sbp_min": float(x.min()), "sbp_max": float(x.max()),
            "tcr_hz": tc.mean(0), "tcr_max_count": float(s["tcr"].max()),
            "tcr_integer": bool(np.all(s["tcr"] == np.round(s["tcr"]))),
            "kin_min": s["kin"].min(0), "kin_max": s["kin"].max(0),
            "vel_vs_back": [float(np.max(np.abs(s["kin"][1:, 2 + j] - dpos[:, j]))) for j in range(2)],
            "vel_vs_fwd": [float(np.max(np.abs(s["kin"][:-1, 2 + j] - dpos[:, j]))) for j in range(2)],
            "gaps": np.where(np.diff(s["t"]) > 0.03)[0],
            "gap_s": np.diff(s["t"])[np.diff(s["t"]) > 0.03],
            "vel_fwd_mismatch": np.where(np.abs(s["kin"][:-1, 2:] - dpos).max(1) > 1e-5)[0],
            "trial_len_vs_count": float(np.max(np.abs((en - st) - s["trials"]["trial_count"].to_numpy()))),
            "trial_dur_s": (s["trials"]["stop_time"] - s["trials"]["start_time"]).to_numpy(),
            "trial_count_s": s["trials"]["trial_count"].to_numpy() * link.BIN_S,
            "active": act, "pr": pr, "ev": ev,
            "tp": {k: link.throughput(s["trials"], k) for k in "abc"},
            "timeout": s["trials"]["trial_timeout"].to_numpy(),
            "target_min": s["trials"][["index_target_position", "mrs_target_position"]].min().to_numpy(),
            "target_max": s["trials"][["index_target_position", "mrs_target_position"]].max().to_numpy(),
        })
    sbp = np.concatenate([s["sbp"] for s in sessions]).astype(np.float64)
    pos = np.concatenate([s["kin"][:, :2] for s in sessions])
    tun = link.channel_tuning(sbp, pos)
    z = (sbp - sbp.mean(0)) / np.where(sbp.std(0) > 1e-8, sbp.std(0), 1)
    pcs = PCA(3).fit_transform(z)
    day = {"date": sessions[0]["date"], "sbp_mean": sbp.mean(0), "tuning": tun,
           "tcr_hz": np.concatenate([s["tcr"] for s in sessions]).mean(0) * link.TCR_TO_HZ,
           "traj": trajectories(sessions, pcs)}
    return recs, day


groups = [g for _, g in A.groupby("date")]
if SUBSET:
    groups = groups[:: max(1, len(groups) // SUBSET)][:SUBSET]
t = time.time()
with ThreadPoolExecutor(4) as ex:
    results = list(ex.map(reduce_day, groups))
S = pd.DataFrame([r for rs, _ in results for r in rs]).sort_values(["date", "style"]).reset_index(drop=True)
D = pd.DataFrame([d for _, d in results]).sort_values("date").reset_index(drop=True)
print(f"{len(S)} sessions on {len(D)} days read in {time.time() - t:.0f} s; "
      f"peak memory {resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1e6:.2f} GB")
312 sessions on 303 days read in 671 s; peak memory 1.34 GB

Data check¶

In [4]:
first = S["date"].min()
S["day"] = (S["date"] - first).dt.days
D["day"] = (D["date"] - first).dt.days
print("subjects: 1 (Monkey N) in every file:", lay["subject"])
print("sessions by style:", S["style"].value_counts().to_dict())
print("sessions by year:", S["date"].dt.year.value_counts().sort_index().to_dict())
print("styles inside each file's trials table equal to its file style:",
      all(r["styles_in_trials"] == [r["style"]] for _, r in S.iterrows()))
print("trials per session:", S["n_trials"].value_counts().to_dict())
print("bins per session: min", S["n_bins"].min(), "max", S["n_bins"].max())
print("timestamp steps (s) seen:", sorted(set(np.concatenate(S["dt"].to_list()).round(3))))
print("first timestamp per session (s): min %.3f max %.3f" % (S["t_first"].min(), S["t_first"].max()))
print("session_start_time is midnight of the file date:",
      all(pd.Timestamp(r["start"]).tz_localize(None) == r["date"] for _, r in S.iterrows()))
units = {(k, v["unit"], v["conversion"]) for sr in S["series"] for k, v in sr.items()}
print("series, unit, conversion (all files):", sorted(units))
print("every series shares the SBP timestamps:", all(v["same_t"] for sr in S["series"] for v in sr.values()))
print("SBP range over all bins: %.3f to %.3f (file values)" % (S["sbp_min"].min(), S["sbp_max"].max()))
print("TCR counts per bin are integers:", S["tcr_integer"].all(), "| max count per bin", S["tcr_max_count"].max())
km = np.vstack(S["kin_min"]).min(0); kx = np.vstack(S["kin_max"]).max(0)
for n, a, b in zip(link.KIN_NAMES, km, kx):
    print(f"  {n}: {a:.3f} to {b:.3f}")
tmin = np.vstack(S["target_min"]).min(0); tmax = np.vstack(S["target_max"]).max(0)
print("target positions IDX %.2f to %.2f, MRS %.2f to %.2f" % (tmin[0], tmax[0], tmin[1], tmax[1]))
print("trial timeouts (ms):", sorted(set(np.concatenate(S["timeout"].to_list()))))
print("largest |trial bins from trial_index - trial_count| over sessions:", S["trial_len_vs_count"].max())
dd = np.concatenate([a - b for a, b in zip(S["trial_dur_s"], S["trial_count_s"])])
print("stop - start minus trial_count x 20 ms (s): median %.3f, range %.3f to %.3f" % (np.median(dd), dd.min(), dd.max()))
el0 = S["electrodes"].iloc[0]
same_layout = all((e[["id", "array_name", "bank", "row", "col"]].values == el0[["id", "array_name", "bank", "row", "col"]].values).all() for e in S["electrodes"])
print("electrode layout identical in every file:", same_layout)
imp = np.vstack([e["imp"].to_numpy(float) for e in S["electrodes"]])
print("impedance (ohm): %d of %d values NaN, range %.0f to %.0f" % (np.isnan(imp).sum(), imp.size, np.nanmin(imp), np.nanmax(imp)))
print("sessions whose impedances are all NaN:", int(np.isnan(imp).all(1).sum()))
gl = np.concatenate([np.zeros(0)] + list(S["gap_s"]))
print("time gaps (steps over 30 ms): %d sessions have any, %d gaps in all, %s s long" % (
    sum(len(g) > 0 for g in S["gaps"]), len(gl), f"{gl.min():.2f} to {gl.max():.1f}" if len(gl) else "none"))
mis = sum(len(m) for m in S["vel_fwd_mismatch"])
mis_gap = sum(np.isin(m, g).sum() for m, g in zip(S["vel_fwd_mismatch"], S["gaps"]))
print("velocity[t] equals pos[t+1] - pos[t] (a forward difference) except at %d bins, %d of which are the bin "
      "before a time gap" % (mis, mis_gap))
print("velocity[t] minus pos[t] - pos[t-1] (backward difference), largest |difference| per finger:",
      np.round(np.vstack(S["vel_vs_back"]).max(0), 4))
subjects: 1 (Monkey N) in every file: {'subject_id': 'Monkey N', 'date_of_birth': '2012-05-26T00:00:00+00:00', 'sex': 'M', 'species': 'Macaca mulatta'}
sessions by style: {'CO': 156, 'RD': 156}
sessions by year: {2020: 43, 2021: 117, 2022: 107, 2023: 45}
styles inside each file's trials table equal to its file style: True
trials per session: {375: 312}
bins per session: min 20828 max 35253
timestamp steps (s) seen: [np.float64(0.019), np.float64(0.02), np.float64(0.021), np.float64(1.046), np.float64(1.094), np.float64(1.139), np.float64(1.163), np.float64(1.309), np.float64(1.462), np.float64(1.5), np.float64(2.025), np.float64(2.028), np.float64(2.029), np.float64(2.03), np.float64(2.032), np.float64(2.033), np.float64(2.038), np.float64(2.043), np.float64(2.044), np.float64(4.035), np.float64(5.025), np.float64(5.026), np.float64(5.027), np.float64(5.029), np.float64(5.033), np.float64(5.034), np.float64(5.036), np.float64(5.037), np.float64(5.038), np.float64(5.041), np.float64(5.043), np.float64(7.536), np.float64(7.541), np.float64(7.543), np.float64(10.028), np.float64(10.029), np.float64(10.031), np.float64(10.032), np.float64(10.033), np.float64(10.034), np.float64(10.035), np.float64(10.038), np.float64(10.039), np.float64(10.04), np.float64(10.041), np.float64(10.043), np.float64(10.044), np.float64(32.429), np.float64(240.058), np.float64(363.802), np.float64(443.403), np.float64(470.97), np.float64(472.915)]
first timestamp per session (s): min 3.179 max 45.970
session_start_time is midnight of the file date: True
series, unit, conversion (all files): [('SpikingBandPower', 'volts', 1e-06), ('ThresholdCrossings', 'volts', 1.0), ('index_position', 'flexion units', 1.0), ('index_velocity', 'flexion units per time bin', 1.0), ('mrs_position', 'flexion units', 1.0), ('mrs_velocity', 'flexion units per time bin', 1.0)]
every series shares the SBP timestamps: True
SBP range over all bins: 0.044 to 642.963 (file values)
TCR counts per bin are integers: True | max count per bin 15.0
  idx_pos: 0.000 to 1.000
  mrs_pos: 0.000 to 1.000
  idx_vel: -0.347 to 0.559
  mrs_vel: -0.442 to 0.350
target positions IDX 0.00 to 1.00, MRS 0.00 to 1.00
trial timeouts (ms): [np.float64(2000.0), np.float64(4000.0), np.float64(5000.0), np.float64(7500.0), np.float64(10000.0), np.float64(20000.0), np.float64(30000.0)]
largest |trial bins from trial_index - trial_count| over sessions: 0.0
stop - start minus trial_count x 20 ms (s): median -0.020, range -0.021 to -0.019
electrode layout identical in every file: True
impedance (ohm): 7776 of 29952 values NaN, range 13000 to 19027000
sessions whose impedances are all NaN: 81
time gaps (steps over 30 ms): 29 sessions have any, 72 gaps in all, 1.05 to 472.9 s long
velocity[t] equals pos[t+1] - pos[t] (a forward difference) except at 72 bins, 72 of which are the bin before a time gap
velocity[t] minus pos[t] - pos[t-1] (backward difference), largest |difference| per finger: [0.6923 0.8331]

Clock check. The behaviour and neural series share one timestamp vector in every file (above). To check that the neural data and the trial table share a clock, the next cell decodes the movement direction class of each trial from the mean SBP of the 0 to 500 ms after its start, with the trial table as stored and with the start times shifted by whole trials (labels from trial i paired with the neural data of trial i + k). Nearest-centroid, 5-fold cross-validation, per session, on a few sessions.

In [5]:
def clock_check(asset_id, shifts=(0, 1, 2, 5)):
    s = link.read_session(asset_id, tcr=False, kin=False)
    st = s["trial_index"]
    cls = link.trial_directions(s["trials"])
    X = np.array([s["sbp"][a:a + 25].mean(0) for a in st])
    X = (X - X.mean(0)) / X.std(0)
    out = {}
    for k in shifts:
        y = cls[: len(cls) - k] if k else cls
        Xk = X[k:]
        ok = y >= 0
        out[k] = nc_cv_accuracy(Xk[ok], y[ok], np.random.default_rng(0))
    return out


def nc_cv_accuracy(X, y, rng, folds=5):
    idx = rng.permutation(len(y))
    correct = 0
    for f in range(folds):
        te = idx[f::folds]
        tr = np.setdiff1d(idx, te)
        labs = np.unique(y[tr])
        cent = np.array([X[tr][y[tr] == c].mean(0) for c in labs])
        pred = labs[np.argmin(((X[te][:, None, :] - cent[None]) ** 2).sum(-1), axis=1)]
        correct += (pred == y[te]).sum()
    return correct / len(y)


chk = S.groupby("date").head(1).iloc[np.linspace(0, len(S.groupby("date").head(1)) - 1, 6).astype(int)]
for _, r in chk.iterrows():
    aid = A.set_index("path").loc[r["path"], "asset_id"]
    print(r["date"].date(), r["style"], {k: round(v, 3) for k, v in clock_check(aid).items()})
2020-01-27 CO {0: np.float64(0.626), 1: np.float64(0.394), 2: np.float64(0.18), 5: np.float64(0.106)}
2021-03-19 RD {0: np.float64(0.404), 1: np.float64(0.22), 2: np.float64(0.145), 5: np.float64(0.119)}
2021-08-05 CO {0: np.float64(0.516), 1: np.float64(0.271), 2: np.float64(0.175), 5: np.float64(0.149)}
2022-03-18 CO {0: np.float64(0.5), 1: np.float64(0.284), 2: np.float64(0.177), 5: np.float64(0.138)}
2022-09-19 CO {0: np.float64(0.382), 1: np.float64(0.204), 2: np.float64(0.118), 5: np.float64(0.144)}
2023-06-22 RD {0: np.float64(0.318), 1: np.float64(0.188), 2: np.float64(0.142), 5: np.float64(0.092)}

dataset-sessions¶

The dataset holds 312 sessions recorded on 303 days spanning 1,242 days, two sessions (one CO, one RD) on 9 days, each session 375 successful trials, from days 349 to 1591 after implant.

In [6]:
per_day = S.groupby("date")["style"].apply(lambda s: "+".join(sorted(s)))
two = per_day[per_day.str.contains(r"\+")]
span = (S["date"].max() - S["date"].min()).days
print("sessions (files):", len(S))
print("recording days:", S["date"].nunique())
print("span, last minus first date:", span, "days;", S["date"].min().date(), "to", S["date"].max().date())
print("days with two sessions:", len(two), "| their styles:", two.value_counts().to_dict())
print("sessions with a trial count other than 375:", S.loc[S["n_trials"] != 375, ["date", "style", "n_trials"]].to_dict("records"))
print("implant date in the files or the dandiset metadata: none (the subject has only a date of birth,",
      lay["subject"]["date_of_birth"], ")")
sessions (files): 312
recording days: 303
span, last minus first date: 1242 days; 2020-01-27 to 2023-06-22
days with two sessions: 9 | their styles: {'CO+RD': 9}
sessions with a trial count other than 375: []
implant date in the files or the dandiset metadata: none (the subject has only a date of birth, 2012-05-26T00:00:00+00:00 )

Result: reproduced. The pinned version holds 312 session files on 303 dates spanning 1,242 days (2020-01-27 to 2023-06-22); on 9 dates there are two files, each a CO and an RD session, and every session has 375 trials. All five counts match. The days after implant (349 to 1591) cannot be compared: the files and the dandiset metadata give the subject's date of birth but no implant date.

dataset-contents¶

Each session holds SBP and TCR for 96 motor-cortex channels and the position and velocity of the two finger groups in 20 ms bins, with per-trial target positions, start times, lengths and target style, and per-channel array locations and impedances.

In [7]:
need_series = {"SpikingBandPower": 96, "ThresholdCrossings": 96, "index_position": 1, "index_velocity": 1,
               "mrs_position": 1, "mrs_velocity": 1}
need_trials = ["start_time", "stop_time", "trial_number", "trial_count", "run_id", "index_target_position",
               "mrs_target_position", "target_style", "trial_timeout", "timeseries"]
gaps = []
for _, r in S.iterrows():
    for n, ch in need_series.items():
        v = r["series"].get(n)
        if v is None or v["shape"][1] != ch or v["shape"][0] != r["n_bins"]:
            gaps.append((r["path"], n))
    miss = [c for c in need_trials if c not in r["trial_columns"]]
    if miss:
        gaps.append((r["path"], "trials " + ",".join(miss)))
    miss = [c for c in ("array_name", "bank", "row", "col", "imp") if c not in r["electrode_columns"]]
    if miss:
        gaps.append((r["path"], "electrodes " + ",".join(miss)))
steps = np.concatenate(S["dt"].to_list())
print("files checked:", len(S), "| files with a missing part:", len({g[0] for g in gaps}))
print("missing parts and how many files lack each:", pd.Series([g[1] for g in gaps]).value_counts().to_dict())
print("files without the imp column, by year:", S.loc[["imp" not in c for c in S["electrode_columns"]], "date"].dt.year.value_counts().sort_index().to_dict())
print("timestamp steps within a run of bins: %s s; %d sessions also have gaps over 30 ms (see the data check)" % (
    sorted(set(steps[steps < 0.03].round(3))), sum(len(g) > 0 for g in S["gaps"])))
print("velocity is the forward difference of binned position, except at %d bins (%d before a gap)" % (mis, mis_gap))
files checked: 312 | files with a missing part: 81
missing parts and how many files lack each: {'electrodes imp': 81}
files without the imp column, by year: {2020: 14, 2021: 2, 2022: 49, 2023: 16}
timestamp steps within a run of bins: [np.float64(0.019), np.float64(0.02), np.float64(0.021)] s; 29 sessions also have gaps over 30 ms (see the data check)
velocity is the forward difference of binned position, except at 72 bins (72 before a gap)

Result: partially reproduced. Every one of the 312 files holds 96-channel SpikingBandPower and ThresholdCrossings series and the four position and velocity series on one shared timestamp vector, a trials table with every column Appendix B.3 lists, and an electrodes table with array, bank, row and column. The one gap is the impedance: 81 files have no imp column at all. Appendix A.2 says that no impedances are reported for a session without a measurement within three weeks, so the gap may be what the paper describes, but the criterion asks for the column in every file. Within a run of bins the timestamps step by 0.019 to 0.021 s; some sessions also have pauses between runs of bins (the data check gives their count and length). Velocity is the forward difference of the binned position (velocity at bin t is position at t + 1 minus position at t) except at the bins listed above, and so is not the backward difference.

figs2-throughput-improves¶

The monkey's real-time task performance, measured as average Fitts' law throughput per day, appears to improve gradually over the dataset.

Readings (a), (b), (c) of the criterion; per day the mean over all trials of both sessions; the first trial of each session has no previous target in the file and is left out.

In [8]:
tp_rows = []
for k in "abc":
    daily = S.groupby("day")["tp"].apply(lambda col: np.nanmean(np.concatenate([d[k] for d in col])))
    r = link.linfit(daily.index, daily.values)
    tp_rows.append({"reading": k, "days": len(daily), "first 30 days mean": daily.iloc[:30].mean(),
                    "last 30 days mean": daily.iloc[-30:].mean(), "slope bits/s per year": r.slope * 365.25,
                    "r": r.rvalue, "p": r.pvalue})
    by_year = daily.groupby((first + pd.to_timedelta(daily.index, "D")).year).mean().round(3).to_dict()
    print(k, "mean per year:", by_year)
print(pd.DataFrame(tp_rows).to_string(index=False))
nonpos = sum(int(np.sum((t["a"][1:] <= 0) | ~np.isfinite(t["a"][1:]))) for t in S["tp"])
print("trials with acquisition time <= 0 under reading (a):", nonpos)
a mean per year: {2020: 3.657, 2021: 3.961, 2022: 4.325, 2023: 3.849}
b mean per year: {2020: 1.324, 2021: 1.413, 2022: 1.467, 2023: 1.491}
c mean per year: {2020: 4.856, 2021: 5.337, 2022: 5.873, 2023: 5.634}
reading  days  first 30 days mean  last 30 days mean  slope bits/s per year        r            p
      a   303            3.314804           3.832302               0.238097 0.305505 5.757074e-08
      b   303            1.283981           1.486509               0.068349 0.643651 7.730515e-37
      c   303            4.482047           5.609441               0.454615 0.496753 2.754538e-20
trials with acquisition time <= 0 under reading (a): 998

Result: reproduced. Under all three readings the daily mean throughput rises over the dataset: reading (a) by 0.238 bits/s per year (r = 0.31, p = 5.8e-08), (b) by 0.068 (p = 7.7e-37) and (c) by 0.455 (p = 2.8e-20), over 303 days. Under reading (a) the yearly means rise from 3.66 in 2020 to 4.33 in 2022 and fall to 3.85 in the six months of 2023, so the rise is not monotonic. Under readings (a) and (c), 998 trials whose length (stop minus start) is at most the 750 ms hold get no throughput.

fig2a-sbp-decline¶

Average SBP across channels decreased gradually by about 0.033 microvolts per month, as estimated by a linear model fit to every channel's mean SBP on every day.

In [9]:
M = np.vstack(D["sbp_mean"])        # days x channels, file units
dayx = np.repeat(D["day"].to_numpy(), 96)
res = {}
for name, scale in (("(a) x0.25", link.SBP_CODE_SCALE), ("(b) as stored", 1.0)):
    r = link.linfit(dayx, (M * scale).ravel())
    res[name] = r
    print(f"{name}: slope {r.slope:.3e} per day = {r.slope * link.DAYS_PER_MONTH:.4f} per month, "
          f"intercept {r.intercept:.3f}, p = {r.pvalue:.2g}, points {len(dayx)}")
print("mean SBP over channels, first and last 30 days (file units): %.3f, %.3f" % (M[:30].mean(), M[-30:].mean()))
print("channel-day values (file units): %.3f to %.3f; values above 10: %d" % (M.min(), M.max(), (M > 10).sum()))
fig, ax = plt.subplots(figsize=(8, 3))
ax.scatter(D["date"].repeat(96), M.ravel(), s=1, alpha=.3)
ax.plot(D["date"], res["(b) as stored"].intercept + res["(b) as stored"].slope * D["day"], "r")
ax.set_ylim(0, 10); ax.set_ylabel("mean SBP (file units)")
plt.show()
(a) x0.25: slope -2.776e-04 per day = -0.0084 per month, intercept 0.879, p = 2.5e-285, points 29088
(b) as stored: slope -1.110e-03 per day = -0.0338 per month, intercept 3.517, p = 2.5e-285, points 29088
mean SBP over channels, first and last 30 days (file units): 3.610, 2.282
channel-day values (file units): 1.021 to 46.400; values above 10: 311
No description has been provided for this image

Result: reproduced, under unit reading (b). With the values as stored (microvolts by the files' conversion factor of 1e-6 V), the linear fit to 29,088 channel-day means has a slope of -1.110e-03 per day, -0.0338 microvolts per month, within the tolerance of -0.033 +- 0.0033, and the per-day value equals the supplement's -1.11e-3. Reading (a), the stored values times 0.25, gives -0.0084 per month, outside it. The code's converter divides the stored SBP by 0.25 before its analysis multiplies by 0.25, so the code's own path is reading (b).

fig2b-active-channels-decrease¶

The number of active channels, those with mean TCR above 1 Hz on a day, appears to decrease over time.

CO session on two-session days, the day's only session otherwise.

In [10]:
P = S.sort_values(["date", "style"]).groupby("date").head(1).reset_index(drop=True)   # "CO" sorts before "RD"
P["n_active"] = [a.sum() for a in P["active"]]
r = link.linfit(P["day"], P["n_active"])
print(f"days {len(P)}; slope {r.slope:.4f} channels per day ({r.slope * 365.25:.1f} per year), r = {r.rvalue:.3f}, p = {r.pvalue:.2g}")
print("active channels, first 30 sessions: mean %.1f (range %d to %d); last 30: mean %.1f (range %d to %d)" % (
    P["n_active"][:30].mean(), P["n_active"][:30].min(), P["n_active"][:30].max(),
    P["n_active"][-30:].mean(), P["n_active"][-30:].min(), P["n_active"][-30:].max()))
print("days with no active channel:", int((P["n_active"] == 0).sum()))
days 303; slope -0.0177 channels per day (-6.5 per year), r = -0.388, p = 2.6e-12
active channels, first 30 sessions: mean 44.6 (range 32 to 79); last 30: mean 25.9 (range 18 to 37)
days with no active channel: 0

Result: reproduced. The count of channels with mean TCR above 1 Hz falls by 6.5 channels per year (slope -0.0177 per day, r = -0.39, p = 2.6e-12, 303 days), from a mean of 44.6 in the first 30 sessions to 25.9 in the last 30.

fig2c-pr-decline¶

The participation ratio of the active channels' SBP decreased by about 0.07 per month, as estimated by a linear model.

In [11]:
ok = np.isfinite(P["pr"])
r = link.linfit(P["day"][ok], P["pr"][ok])
print(f"CO session on two-session days: days {ok.sum()}, slope {r.slope * link.DAYS_PER_MONTH:.4f} PR per month, p = {r.pvalue:.2g}")
print("PR first 30 days mean %.2f, last 30 mean %.2f, range %.2f to %.2f" % (P["pr"][ok][:30].mean(), P["pr"][ok][-30:].mean(), P["pr"][ok].min(), P["pr"][ok].max()))
# variant: both sessions on two-session days (PR of the concatenated active-channel SBP is not kept;
# the variant uses each session as a point)
ok2 = np.isfinite(S["pr"])
r2 = link.linfit(S["day"][ok2], S["pr"][ok2])
print(f"variant, every session a point: sessions {ok2.sum()}, slope {r2.slope * link.DAYS_PER_MONTH:.4f} PR per month, p = {r2.pvalue:.2g}")
CO session on two-session days: days 303, slope -0.0708 PR per month, p = 1.5e-08
PR first 30 days mean 7.90, last 30 mean 6.13, range 1.24 to 16.00
variant, every session a point: sessions 312, slope -0.0720 PR per month, p = 6.3e-09

Result: reproduced. The participation ratio of the active channels falls by 0.0708 per month (p = 1.5e-08, 303 days), within the tolerance of -0.07 +- 0.007; using every session as a point gives -0.0720.

fig2c-ten-dimensions¶

Generally, 10 dimensions were sufficient to capture the majority of the variance of the active channels.

In [12]:
frac10 = np.array([ev[:10].sum() / ev.sum() if len(ev) else np.nan for ev in P["ev"]])
okd = np.isfinite(frac10)
print("days:", okd.sum())
print("(a) PR <= 10 on %.3f of days (median PR %.2f)" % ((P["pr"][okd] <= 10).mean(), P["pr"][okd].median()))
print("(b) top 10 PCs explain > 50%% on %.3f of days" % (frac10[okd] > 0.5).mean())
print("(c) top 10 PCs explain > 80%% on %.3f of days" % (frac10[okd] > 0.8).mean())
print("variance explained by 10 PCs: median %.3f, range %.3f to %.3f" % (np.median(frac10[okd]), frac10[okd].min(), frac10[okd].max()))
print("days with 10 or fewer active channels (10 PCs explain all):", int((P["n_active"][okd] <= 10).sum()))
days: 303
(a) PR <= 10 on 0.848 of days (median PR 7.86)
(b) top 10 PCs explain > 50% on 1.000 of days
(c) top 10 PCs explain > 80% on 0.446 of days
variance explained by 10 PCs: median 0.791, range 0.574 to 1.000
days with 10 or fewer active channels (10 PCs explain all): 2

Result: reproduced, under reading (a). The daily PR is at most 10 on 84.8% of days (median 7.86). The top 10 PCs explain more than half the variance on every day (reading b) and more than 80% on 44.6% of days (reading c, not reproduced under it).

figs4-bank-slopes¶

Mean SBP decreases over time in each 32-channel bank, with lower overall activity and a shallower slope on the lateral bank (-0.58e-3) than on the two medial banks (-1.34e-3 and -1.40e-3), against -1.11e-3 for all channels.

Banks from the electrodes table: bank A is on the lateral array, B and C on the medial array; Medial 1 is taken as bank B and Medial 2 as bank C (the paper does not say which is which; both medial values are shown).

In [13]:
el = S["electrodes"].iloc[0]
print(el.groupby(["bank", "array_name"]).size().to_dict())
groups_b = {"Lateral (A)": el["bank"].eq("A").to_numpy(), "Medial 1 (B)": el["bank"].eq("B").to_numpy(),
            "Medial 2 (C)": el["bank"].eq("C").to_numpy(), "all": np.ones(96, bool)}
rows = []
for scale_name, scale in (("(a) x0.25", 0.25), ("(b) as stored", 1.0)):
    for fit in ("(a) channel-day points", "(b) daily bank mean"):
        for g, m in groups_b.items():
            Y = M[:, m] * scale
            if fit.startswith("(a)"):
                r = link.linfit(np.repeat(D["day"].to_numpy(), m.sum()), Y.ravel())
            else:
                r = link.linfit(D["day"], Y.mean(1))
            rows.append({"unit": scale_name, "fit": fit, "group": g, "slope per day": r.slope, "mean SBP": Y.mean()})
T4 = pd.DataFrame(rows)
print(T4.pivot_table(index=["unit", "fit"], columns="group", values="slope per day").map(lambda v: f"{v:.2e}").to_string())
print(T4[T4["fit"].str.startswith("(a)")].pivot_table(index="unit", columns="group", values="mean SBP").round(3).to_string())
{('A', 'Lateral'): 32, ('B', 'Medial'): 32, ('C', 'Medial'): 32}
group                                Lateral (A) Medial 1 (B) Medial 2 (C)        all
unit          fit                                                                    
(a) x0.25     (a) channel-day points   -1.46e-04    -3.36e-04    -3.51e-04  -2.78e-04
              (b) daily bank mean      -1.46e-04    -3.36e-04    -3.51e-04  -2.78e-04
(b) as stored (a) channel-day points   -5.84e-04    -1.34e-03    -1.40e-03  -1.11e-03
              (b) daily bank mean      -5.84e-04    -1.34e-03    -1.40e-03  -1.11e-03
group          Lateral (A)  Medial 1 (B)  Medial 2 (C)    all
unit                                                         
(a) x0.25            0.547         0.637         0.893  0.692
(b) as stored        2.188         2.549         3.571  2.770

Result: reproduced, under unit reading (b). With the stored values, the slopes are -5.84e-04 (lateral, bank A), -1.34e-03 (bank B), -1.40e-03 (bank C) and -1.11e-03 (all channels) per day, all four equal to the supplement's values to the printed digits, and the lateral bank has the lowest mean SBP (2.19, against 2.55 and 3.57). The two fit readings give the same slopes, since every day has a value for every channel. Under unit reading (a) every slope is a quarter of these, outside the tolerances.

figs5-active-inactive-slopes¶

Grouped per session into active and inactive channels by TCR, mean SBP of active channels declines faster (-1.29e-3) than all channels, while the slope for inactive channels is near zero (0.54e-3), and inactive channels have lower SBP.

Each session classifies its own channels (mean TCR above 1 Hz in the session), and each session is a point.

In [14]:
rows = []
SM = np.vstack(S["sbp_mean"])
AM = np.vstack(S["active"])
for scale_name, scale in (("(a) x0.25", 0.25), ("(b) as stored", 1.0)):
    for g, mask in (("active", AM), ("inactive", ~AM)):
        xs = np.repeat(S["day"].to_numpy()[:, None], 96, 1)[mask]
        ys = (SM * scale)[mask]
        ra = link.linfit(xs, ys)
        okg = mask.any(1)
        gm = np.array([(SM[i, mask[i]] * scale).mean() for i in np.where(okg)[0]])
        rb = link.linfit(S["day"][okg], gm)
        rows.append({"unit": scale_name, "group": g, "(a) channel-session slope": ra.slope,
                     "(b) session-mean slope": rb.slope, "mean SBP": ys.mean(), "sessions with group": okg.sum()})
print(pd.DataFrame(rows).to_string(index=False, float_format=lambda v: f"{v:.3e}"))
         unit    group  (a) channel-session slope  (b) session-mean slope  mean SBP  sessions with group
    (a) x0.25   active                 -3.153e-04              -2.904e-04 9.346e-01                  312
    (a) x0.25 inactive                 -1.340e-04              -1.126e-04 5.372e-01                  310
(b) as stored   active                 -1.261e-03              -1.162e-03 3.739e+00                  312
(b) as stored inactive                 -5.362e-04              -4.504e-04 2.149e+00                  310

Result: not reproduced. With the stored values and channel-session points (fit reading a), the active channels' slope is -1.261e-03 per day, within the tolerance of -1.29e-3, and inactive channels have the lower mean SBP (2.15 against 3.74). The inactive slope is -5.36e-04: the size of the supplement's 0.54e-3, with the opposite sign, so it is outside the tolerance. The negative sign agrees with Section 4.1 ("All categories saw steady decreases in average SBP"). Fit reading (b) gives -1.162e-03 and -4.50e-04. The criterion reproduces the claim only when both slopes are within tolerance and gives no partial outcome, so the opposite sign decides it. Whether the supplement's +0.54e-3 lost a minus sign is asked of a reader (questions/temmar-2025.yaml); against -0.54e-3 the claim would be reproduced.

fig2d-population-drift¶

In a PCA fit to SBP z-scored per channel across the whole dataset, the per-day and per-quarter centroids of the top 3 PCs move through PC space over time, while the standard deviation of the top 3 PCs per quarter changes little except in two quarters.

The PCA of the whole-dataset z-scored SBP is computed from per-session sums (the mean and covariance of all bins), which gives the same components as fitting scikit-learn's PCA to the concatenated matrix. Centroids and per-quarter standard deviations of the scores follow from the same sums.

In [15]:
N = S["n_bins"].sum()
mu = np.vstack(S["sbp_sum"]).sum(0) / N
C = sum(S["sbp_xx"]) / N - np.outer(mu, mu)
sd = np.sqrt(np.diag(C))
R = C / np.outer(sd, sd)
w, V = np.linalg.eigh(R)
order = np.argsort(w)[::-1]
W = V[:, order[:3]]
print("variance explained by PC1-3 (z-scored):", np.round(w[order[:3]] / w.sum(), 3))
S["quarter"] = S["date"].dt.to_period("Q")
cent_day = np.array([W.T @ ((r["sbp_sum"] / r["n_bins"] - mu) / sd) for _, r in S.iterrows()])
qrows = []
for q, g in S.groupby("quarter"):
    n = g["n_bins"].sum()
    m = np.vstack(g["sbp_sum"]).sum(0) / n
    Cq = sum(g["sbp_xx"]) / n - np.outer(m, m)
    Cz = Cq / np.outer(sd, sd)
    sds = np.sqrt(np.diag(W.T @ Cz @ W))
    qrows.append({"quarter": str(q), "sessions": len(g), "centroid": W.T @ ((m - mu) / sd), "sd_pc": sds,
                  "sd_rms": float(np.sqrt(np.mean(sds ** 2)))})
Q = pd.DataFrame(qrows)
for _, q in Q.iterrows():
    print(q["quarter"], q["sessions"], "centroid", np.round(q["centroid"], 3), "sd", np.round(q["sd_pc"], 3), "rms %.3f" % q["sd_rms"])
move = np.linalg.norm(Q["centroid"].iloc[-1] - Q["centroid"].iloc[0])
print("distance first to last quarter centroid: %.3f; mean within-quarter SD (rms over 3 PCs): %.3f" % (move, Q["sd_rms"].mean()))
med = Q["sd_rms"].median()
far = Q[np.abs(Q["sd_rms"] - med) > 0.25 * med]
print("quarters with SD more than 25%% from the median (%.3f): %d %s" % (med, len(far), far["quarter"].tolist()))
for thr in (0.15, 0.25, 0.5):
    print(f"  at {int(thr*100)}%: {int((np.abs(Q['sd_rms'] - med) > thr * med).sum())} quarters")
print("per-day centroid range per PC:", np.round(cent_day.min(0), 2), np.round(cent_day.max(0), 2))
print("path length of quarter centroids: %.3f" % np.sum(np.linalg.norm(np.diff(np.vstack(Q["centroid"]), axis=0), axis=1)))
variance explained by PC1-3 (z-scored): [0.303 0.049 0.044]
2020Q1 17 centroid [12.281  1.848 -0.207] sd [3.113 0.761 1.122] rms 1.961
2020Q2 1 centroid [6.927 0.801 0.233] sd [2.215 0.503 0.903] rms 1.411
2020Q3 12 centroid [6.556 0.936 0.466] sd [3.326 0.777 1.134] rms 2.078
2020Q4 13 centroid [5.394 0.785 0.63 ] sd [2.527 0.896 0.923] rms 1.637
2021Q1 22 centroid [ 4.953 -2.24   0.78 ] sd [3.201 6.576 1.117] rms 4.271
2021Q2 32 centroid [1.824 0.29  0.975] sd [2.59  0.788 0.885] rms 1.644
2021Q3 45 centroid [ 0.133 -0.215  0.567] sd [2.804 1.537 1.426] rms 2.021
2021Q4 18 centroid [-1.353 -0.023  0.233] sd [2.417 0.969 0.861] rms 1.584
2022Q1 28 centroid [-3.021  0.358 -0.008] sd [2.498 0.574 0.964] rms 1.581
2022Q2 33 centroid [-3.034 -0.066 -0.047] sd [2.977 0.694 1.783] rms 2.043
2022Q3 34 centroid [-3.114  0.045 -3.022] sd [2.86  0.909 3.817] rms 2.804
2022Q4 12 centroid [-4.799 -0.037 -1.267] sd [2.905 0.783 2.245] rms 2.167
2023Q1 23 centroid [-4.846 -0.345  0.314] sd [2.471 0.687 1.472] rms 1.708
2023Q2 22 centroid [-4.6   -0.346  0.635] sd [2.112 0.546 0.914] rms 1.366
distance first to last quarter centroid: 17.044; mean within-quarter SD (rms over 3 PCs): 2.020
quarters with SD more than 25% from the median (1.834): 3 ['2021Q1', '2022Q3', '2023Q2']
  at 15%: 5 quarters
  at 25%: 3 quarters
  at 50%: 2 quarters
per-day centroid range per PC: [ -9.11 -28.07 -21.93] [14.25  2.49  2.48]
path length of quarter centroids: 27.132

Result: partially reproduced. The centroids move: the first and last quarters' centroids are 17.04 apart in the space of the top 3 PCs, against a mean within-quarter standard deviation of 2.02, and the first PC's quarterly centroid falls from 12.28 to -4.60. The spread is less stable than the rule asks: 3 quarters (2021Q1, 2022Q3, 2023Q2) have a 3-PC standard deviation more than 25% from the median, where the rule allows two. At 50% two quarters (2021Q1 at 4.27 and 2022Q3 at 2.80 against a median of 1.83) stand out, as the paper's "except for two quarters" says.

fig2e-trajectories-separable¶

Average neural trajectories in the top 3 PCs for the eight movement directions remain visually separable in both the first year (2020) and the last (2023) of the dataset.

In [16]:
TR = pd.DataFrame([t for d in D["traj"] for t in d])
TR["year"] = pd.to_datetime(TR["date"]).dt.year
print("trials with a direction:", len(TR), "| by class:", TR["cls"].value_counts().sort_index().to_dict())
for name in ("main", "code"):
    print(f"alignment {name}: trials dropped (no onset or window outside the trial): {TR[name].isna().sum()} of {len(TR)}")
    for yr in (2020, 2023):
        g = TR[(TR["year"] == yr) & TR[name].notna()]
        if len(g) == 0:
            print(f"  {yr}: no trials")
            continue
        X = np.stack([a.ravel() for a in g[name]])
        y = g["cls"].to_numpy()
        acc = nc_cv_accuracy(X, y, np.random.default_rng(yr))
        k = int(round(acc * len(y)))
        p = stats.binomtest(k, len(y), 1 / 8, alternative="greater").pvalue
        maj = g["cls"].value_counts(normalize=True).max()
        # null: labels permuted
        accn = nc_cv_accuracy(X, np.random.default_rng(1).permutation(y), np.random.default_rng(yr))
        print(f"  {yr}: trials {len(y)}, days {g['date'].nunique()}, accuracy {acc:.3f} (chance 1/8, "
              f"majority class {maj:.3f}, permuted labels {accn:.3f}), binomial p = {p:.2g}")
trials with a direction: 116683 | by class: {0: 14520, 1: 18823, 2: 14682, 3: 10247, 4: 14650, 5: 18560, 6: 14780, 7: 10421}
alignment main: trials dropped (no onset or window outside the trial): 1067 of 116683
  2020: trials 15951, days 43, accuracy 0.212 (chance 1/8, majority class 0.158, permuted labels 0.125), binomial p = 1.4e-207
  2023: trials 16511, days 45, accuracy 0.220 (chance 1/8, majority class 0.184, permuted labels 0.114), binomial p = 1.7e-253
alignment code: trials dropped (no onset or window outside the trial): 92544 of 116683
  2020: trials 3948, days 43, accuracy 0.232 (chance 1/8, majority class 0.178, permuted labels 0.122), binomial p = 3.3e-76
  2023: trials 3530, days 45, accuracy 0.221 (chance 1/8, majority class 0.190, permuted labels 0.116), binomial p = 3.7e-56

Result: reproduced. Classified by direction from their 37-bin trajectories in the day's top 3 PCs, trials are classified with accuracy 0.212 in 2020 (15,951 trials) and 0.220 in 2023 (16,511 trials), against chance of 1/8 (binomial p below 1e-200 in both years), the majority-class rate (0.158 and 0.184) and permuted labels (0.125 and 0.114). The code's alignment (2 SD, from 150 ms before) gives 0.232 and 0.221, but drops 92,544 of 116,683 trials, whose window starts before the trial or that have no onset. Separable here means better than chance; the accuracies are low in absolute terms.

Tuning (fig3b, fig3cd, fig3d, fig3e)¶

In [17]:
TUN = np.stack(D["tuning"])                     # days x channels x (idx, mrs)
ANG = np.arctan2(TUN[..., 1], TUN[..., 0])      # 0 = IDX flexion, 90 deg = MRS flexion
STR = np.linalg.norm(TUN, axis=2)
cmed = np.array([link.circ_median(ANG[:, c]) for c in range(96)])
ciqr = np.array([link.circ_iqr(ANG[:, c]) for c in range(96)])
smed = np.median(STR, 0)
TCRD = np.vstack(D["tcr_hz"])                   # days x channels, Hz
tcr_mean = TCRD.mean(0)
act_ds = tcr_mean > 1
print("tuning strength over all channel-days: 1%%, 99%% quantiles %.4f, %.4f (paper's axis 0 to 0.06)" % tuple(np.percentile(STR, [1, 99])))
print("channels active over the dataset (mean TCR > 1 Hz):", act_ds.sum())
tuning strength over all channel-days: 1%, 99% quantiles 0.0009, 0.0554 (paper's axis 0 to 0.06)
channels active over the dataset (mean TCR > 1 Hz): 53

fig3b-two-channels¶

Channel 7 is strongly tuned to MRS flexion throughout the dataset, whereas channel 32 shows large shifts in tuning angle; both are active, with average TCR above 1 Hz across the dataset.

In [18]:
for c in (7, 32):
    print(f"channel {c}: array {el['array_name'][c]}, bank {el['bank'][c]}; circular median angle {np.degrees(cmed[c]):.1f} deg, "
          f"circular IQR {np.degrees(ciqr[c]):.1f} deg, median strength {smed[c]:.4f}, mean TCR {tcr_mean[c]:.2f} Hz")
print("over channels: median strength %.4f, median circular IQR %.1f deg" % (np.median(smed), np.degrees(np.median(ciqr))))
print("rank of channel 7's median strength: %d of 96" % (1 + (smed > smed[7]).sum()))
print("rank of channel 32's circular IQR: %d of 96" % (1 + (ciqr > ciqr[32]).sum()))
channel 7: array Lateral, bank A; circular median angle 81.1 deg, circular IQR 18.6 deg, median strength 0.0245, mean TCR 3.12 Hz
channel 32: array Medial, bank B; circular median angle -122.9 deg, circular IQR 146.9 deg, median strength 0.0256, mean TCR 36.45 Hz
over channels: median strength 0.0070, median circular IQR 46.9 deg
rank of channel 7's median strength: 6 of 96
rank of channel 32's circular IQR: 6 of 96

Result: reproduced. Channel 7 has a circular median tuning angle of 81.1 degrees (MRS flexion is 90), a circular IQR of 18.6 degrees and a median strength of 0.0245, sixth of 96 channels (median over channels 0.0070). Channel 32 has a circular IQR of 146.9 degrees, sixth largest (median over channels 46.9). Their mean TCR over the dataset is 3.12 and 36.45 Hz.

fig3cd-tuning-stable¶

Per-channel tuning angles generally appear consistent through the dataset; in most channels the circular IQR of tuning angle is small, so their tunings did not change much.

In [19]:
for lim in (45, 90):
    for lab, m in (("(i) all 96", np.ones(96, bool)), ("(ii) active", act_ds)):
        f = (np.degrees(ciqr[m]) < lim).mean()
        print(f"circular IQR < {lim} deg, {lab} ({m.sum()} channels): fraction {f:.3f}")
print("circular IQR quantiles (deg) 10/25/50/75/90:", np.round(np.degrees(np.percentile(ciqr, [10, 25, 50, 75, 90])), 1))
circular IQR < 45 deg, (i) all 96 (96 channels): fraction 0.479
circular IQR < 45 deg, (ii) active (53 channels): fraction 0.453
circular IQR < 90 deg, (i) all 96 (96 channels): fraction 0.771
circular IQR < 90 deg, (ii) active (53 channels): fraction 0.774
circular IQR quantiles (deg) 10/25/50/75/90: [ 25.7  34.8  46.9  80.9 125.3]

Result: reproduced, under reading (b). 77.1% of all channels (and 77.4% of the 53 active ones) have a circular IQR of tuning angle below 90 degrees. Under reading (a), below 45 degrees, it is 47.9% and 45.3%, under half, so the outcome rests on the wider threshold. The median circular IQR is 46.9 degrees.

fig3d-weak-channels-low-tcr¶

Many channels have very low tuning strength throughout the arrays' lifespan, and such channels typically have low average TCR per day.

In [20]:
tcr_med = np.median(TCRD, 0)
rho, p = stats.spearmanr(smed, tcr_med)
low = smed <= np.percentile(smed, 25)
u = stats.mannwhitneyu(tcr_med[low], tcr_med[~low], alternative="two-sided")
print(f"Spearman rho (median strength vs median daily TCR, 96 channels) = {rho:.3f}, p = {p:.2g}")
print(f"lowest-quartile strength channels ({low.sum()}): median TCR {np.median(tcr_med[low]):.2f} Hz; "
      f"others ({(~low).sum()}): {np.median(tcr_med[~low]):.2f} Hz; Mann-Whitney U = {u.statistic:.0f}, p = {u.pvalue:.2g}")
print("median strength quantiles 0/25/50/75/100:", np.round(np.percentile(smed, [0, 25, 50, 75, 100]), 4))
Spearman rho (median strength vs median daily TCR, 96 channels) = 0.925, p = 3e-41
lowest-quartile strength channels (24): median TCR 0.40 Hz; others (72): 0.87 Hz; Mann-Whitney U = 88, p = 5.3e-11
median strength quantiles 0/25/50/75/100: [0.0025 0.0046 0.007  0.0144 0.0331]

Result: reproduced. Over the 96 channels, median tuning strength and median daily TCR correlate with Spearman rho = 0.925 (p = 3e-41), and the 24 channels in the lowest quartile of strength have a median TCR of 0.40 Hz against 0.87 Hz for the others (Mann-Whitney p = 5.3e-11).

fig3e-array-tuning¶

Channels on the medial array are mainly tuned to MRS flexion, with some to IDX flexion, while channels on the lateral array are more tuned to extension of both fingers, so channels on the same array tend to have similar tuning angles.

In [21]:
deg = np.degrees(cmed)
med_arr = el["array_name"].eq("Medial").to_numpy()
def within(a, c, h):
    return np.abs(((a - c + 180) % 360) - 180) <= h
for lab, m in (("all channels", np.ones(96, bool)), ("active channels", act_ds)):
    mm, ll = med_arr & m, ~med_arr & m
    in_flex = within(deg[mm], 45, 67.5)          # -22.5 to 112.5
    near90, near0 = within(deg[mm], 90, 45).sum(), within(deg[mm], 0, 45).sum()
    in_ext = within(deg[ll], -135, 67.5)         # -202.5 to -67.5
    print(f"{lab}: medial {mm.sum()} channels, {in_flex.mean():.3f} in -22.5..112.5 deg, {near90} within 45 deg of 90, "
          f"{near0} within 45 deg of 0; lateral {ll.sum()} channels, {in_ext.mean():.3f} in -202.5..-67.5 deg")
mm, ll = ~med_arr, med_arr
print("variant, with the array names swapped (file Lateral read as medial): medial-sector fraction %.3f, "
      "near 90: %d, near 0: %d; lateral-sector fraction %.3f" % (within(deg[mm], 45, 67.5).mean(),
      within(deg[mm], 90, 45).sum(), within(deg[mm], 0, 45).sum(), within(deg[ll], -135, 67.5).mean()))
print("lateral circular medians (deg):", np.round(np.sort(deg[~med_arr])).astype(int).tolist())
print("medial circular medians (deg):", np.round(np.sort(deg[med_arr])).astype(int).tolist())
print("channel 47 in the electrodes table (Figure S1 places it on the medial array, row 5, column 5):",
      el.loc[47, ["id", "array_name", "bank", "row", "col"]].to_dict())
print("channels per array and bank:", el.groupby(["array_name", "bank"]).size().to_dict())
all channels: medial 64 channels, 0.031 in -22.5..112.5 deg, 0 within 45 deg of 90, 3 within 45 deg of 0; lateral 32 channels, 0.062 in -202.5..-67.5 deg
active channels: medial 39 channels, 0.026 in -22.5..112.5 deg, 0 within 45 deg of 90, 2 within 45 deg of 0; lateral 14 channels, 0.071 in -202.5..-67.5 deg
variant, with the array names swapped (file Lateral read as medial): medial-sector fraction 0.812, near 90: 11, near 0: 17; lateral-sector fraction 0.922
lateral circular medians (deg): [-119, -49, -13, 12, 13, 14, 20, 20, 24, 24, 25, 26, 28, 29, 36, 37, 41, 42, 45, 53, 67, 67, 70, 76, 81, 84, 87, 88, 119, 125, 147, 172]
medial circular medians (deg): [-158, -149, -147, -143, -142, -140, -140, -138, -136, -136, -135, -134, -133, -132, -132, -132, -132, -131, -131, -130, -130, -130, -130, -130, -130, -130, -130, -129, -129, -129, -128, -128, -128, -128, -128, -128, -127, -127, -125, -124, -124, -123, -123, -123, -123, -123, -122, -121, -121, -120, -119, -118, -118, -117, -111, -110, -109, -29, -13, 1, 154, 155, 174, 180]
channel 47 in the electrodes table (Figure S1 places it on the medial array, row 5, column 5): {'id': 47, 'array_name': 'Medial', 'bank': 'B', 'row': 5, 'col': 5}
channels per array and bank: {('Lateral', 'A'): 32, ('Medial', 'B'): 32, ('Medial', 'C'): 32}

Result: not reproduced. With the arrays as the files label them, the medial channels' circular median angles are near -130 degrees (extension of both fingers): 2 of 64 (0.031) fall in the flexion sector of -22.5 to 112.5 degrees. Most lateral channels are tuned to flexion (12 to 88 degrees), and 2 of 32 (0.062) fall in the extension sector. The pattern is the paper's with the array names swapped: read that way, 81.2% of the file's lateral channels are in the flexion sector and 92.2% of its medial channels in the extension sector, though more of the flexion channels are within 45 degrees of IDX flexion (17) than of MRS flexion (11). The files' labels agree with Figure S1 (the table gives channel 47 as Medial, bank B, row 5, column 5) and with the lower SBP of the lateral bank (figs4), so the files and this sentence of the paper disagree on which array is which, or the paper's angles have another sign convention.

Summary¶

Claim Outcome
dataset-sessions reproduced
dataset-contents partially reproduced (81 files without impedances)
figs2-throughput-improves reproduced
fig2a-sbp-decline reproduced (stored values in microvolts)
fig2b-active-channels-decrease reproduced
fig2c-pr-decline reproduced
fig2c-ten-dimensions reproduced (PR at most 10)
figs4-bank-slopes reproduced
figs5-active-inactive-slopes not reproduced (inactive slope of opposite sign; asked of a reader)
fig2d-population-drift partially reproduced
fig2e-trajectories-separable reproduced
fig3b-two-channels reproduced
fig3cd-tuning-stable reproduced (90-degree reading)
fig3d-weak-channels-low-tcr reproduced
fig3e-array-tuning not reproduced (asked of a reader)

The decoding claims are in decoding.ipynb and multiday.ipynb.

A failure to reproduce here may be a failure of this attempt, not of the paper: see the reasoning and the differences from the paper's method.

How the analysis differs from the paper's: the readings each criterion names are all run and shown; the PCA of Figure 2D is computed from per-session sums, which gives the same components as a fit to the concatenated matrix; the first trial of each session, which has no previous target in the file, has no direction or throughput; tuning uses position, as the main text and code do.

What was found about the dataset: the counts match the paper exactly; the stored SBP is in microvolts, as its conversion factor says, and the code's division by 0.25 and multiplication by 0.25 cancel; ThresholdCrossings is labelled in volts though it holds integer counts per bin; 81 files have no impedance column; the files give no implant date; velocity is a forward difference; some sessions have pauses inside them; and the tuning angles by array are the paper's with the array names swapped.

In [22]:
print(f"notebook time {(time.time() - T0) / 60:.1f} min; peak memory {resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1e6:.2f} GB")
notebook time 11.4 min; peak memory 1.34 GB