Du, Lai, Hu & Ye (2026) on LINK: development sessions¶

Paper: Du Z, Lai ZY, Hu L, Ye T. "A Context-Conditional Audit of Trial-Pairing-Dependent Neural Gain in Motor-Cortex Decoding". bioRxiv preprint posted 2026-08-10, doi:10.64898/2026.08.04.742876. The claims file (claims/du-2026.yaml) was written from that preprint's full text (main text, legends, Tables 1 to 3, Methods); the supplement was not available.

Dataset: DANDI:001201 (LINK, Temmar et al.), pinned at version 0.251023.2336, streamed from the archive. This is the version the paper cites (Methods 4.2, Data availability; protocol, author step 1.3). Two later versions exist (0.261015.2153 and 0.261026.1912); they list the same 312 asset paths with the same sizes (next cell), so the analysis would read the same files; the pinned version is the cited one.

This notebook tests the claims on the 18 development sessions (nine dates with a CO and an RD session). Other notebooks of this entry: 01_synthetic.ipynb (synthetic calibration), 03_link_estimators.ipynb (estimator families), 04_link_temporal_capacity.ipynb (temporal offset and context capacity), 05_link_confirmation.ipynb (20 confirmation sessions), 06_mc_rtt.ipynb (DANDI:000129), 07_mc_maze.ipynb (DANDI:000139, data elsewhere). The estimators are ports of the paper's released code (tag v1.0-jne-submission, commit b042fbe), in du2026.py, each function naming its source.

Claim Where Status
synthetic-template-null, synthetic-signal-ordering, synthetic-pair-breaking 01 tested (data generated by the paper's code)
link-development-sample, link-neural-only-r2, link-context-ladder-gain, link-context-only-r2, link-phase-only-replacement, link-task-contrast-by-context this notebook tested
nested-geometry-gain, nested-history-gain, nested-replacement-negative, replacement-source-diagnostics, permutation-negative, replacement-penalty-distance, replacement-ranks-lower, practical-mse-reduction, representative-trial, split-seed-stability, rff-link this notebook tested
estimator-family-link 03 tested
temporal-offset, context-capacity-contrast 04 tested
confirm-geometry-gain, confirm-history-contraction, confirm-replacement, confirm-table1-values 05 tested
rtt-data, rtt-gain, rff-rtt, estimator-family-nlb 06 tested (MC_Maze part of estimator-family-nlb in 07)
maze-gain, rff-maze 07 tested on MC_Maze (DANDI:000139 version 0.220113.0408, data elsewhere)
In [1]:
import collections, resource, time, zlib
import numpy as np
import pandas as pd
import du2026 as d

PAPER = "du-2026"
def claim_seed(claim_id):
    return zlib.crc32(f"{PAPER}/{claim_id}".encode())

T0 = time.time()
assets = d.list_assets(d.LINK_ID, d.LINK_VERSION)
by_date = collections.defaultdict(list)
for a in assets:
    by_date[d.session_date(a["path"])].append(a)
paired_dates = sorted(k for k, v in by_date.items() if len(v) > 1)
dev_assets = [a for k in paired_dates for a in sorted(by_date[k], key=lambda a: a["path"])]
print(f"{len(assets)} assets in DANDI:{d.LINK_ID} version {d.LINK_VERSION}, {len(by_date)} dates")
print("dates with more than one asset:", {k: len(v) for k, v in by_date.items() if len(v) > 1})
312 assets in DANDI:001201 version 0.251023.2336, 303 dates
dates with more than one asset: {'2021-10-15': 2, '2022-02-25': 2, '2022-04-08': 2, '2022-04-15': 2, '2022-04-29': 2, '2022-05-13': 2, '2022-08-10': 2, '2022-09-21': 2, '2022-11-02': 2}
In [2]:
# The header says the two later versions list the same assets: compare paths and sizes with the pinned version
pinned = {a["path"]: a["size"] for a in assets}
for version in ("0.261015.2153", "0.261026.1912"):
    other = {a["path"]: a["size"] for a in d.list_assets(d.LINK_ID, version)}
    print(f"version {version}: {len(other)} assets; same paths as {d.LINK_VERSION}: {set(other) == set(pinned)}; "
          f"same sizes: {other == pinned}")
version 0.261015.2153: 312 assets; same paths as 0.251023.2336: True; same sizes: True
version 0.261026.1912: 312 assets; same paths as 0.251023.2336: True; same sizes: True

Data check¶

Each development session is streamed once here for the checks; the fits below stream them again, one process per session.

In [3]:
sessions = [d.load_link_session(a["asset_id"], a["path"]) for a in dev_assets]
rows = []
for s in sessions:
    tr = s.trials
    dt = np.diff(s.timestamps)
    start_idx = np.array([int(np.argmin(np.abs(s.timestamps - t))) for t in tr.start_time])
    # usable-trial rule of link.py: the 25-bin window starting 8 bins after the start bin ends before start bin + trial_count
    usable = int(np.sum(start_idx + 8 + 24 < np.minimum(start_idx + tr.trial_count.to_numpy(), len(s.timestamps))))
    sbp, tcr = s.signals["SpikingBandPower"], s.signals["ThresholdCrossings"]
    rows.append(dict(
        date=s.date, task=s.task, target_style=",".join(sorted(tr.target_style.unique())),
        trials=len(tr), usable=usable, bins=len(s.timestamps),
        dt_ms_median=1000 * np.median(dt), dt_ms_min=1000 * dt.min(), dt_ms_max=1000 * dt.max(),
        trial_count_vs_duration=np.median(tr.trial_count / ((tr.stop_time - tr.start_time) / 0.02)),
        start_offset_ms=1000 * np.max(np.abs(s.timestamps[start_idx] - tr.start_time)),
        sbp_min=sbp.min(), sbp_max=sbp.max(), tcr_min=tcr.min(), tcr_max=tcr.max(),
        tcr_integer=bool(np.allclose(tcr, np.round(tcr))),
        pos_min=s.position.min(), pos_max=s.position.max(),
        vel_min=s.velocity.min(), vel_max=s.velocity.max(),
        targets=len(np.unique(np.c_[tr.index_target_position, tr.mrs_target_position], axis=0)),
        target_min=min(tr.index_target_position.min(), tr.mrs_target_position.min()),
        target_max=max(tr.index_target_position.max(), tr.mrs_target_position.max()),
    ))
check = pd.DataFrame(rows)
pd.set_option("display.width", 250, "display.max_columns", 40)
print(check.to_string(float_format=lambda v: f"{v:.4g}"))
print("units:", sessions[0].units)
print("tasks per paired date:", {dt: sorted(check.task[check.date == dt]) for dt in check.date.unique()})
print("target_style column agrees with the identifier's task:", bool((check.task == check.target_style).all()))
          date task target_style  trials  usable   bins  dt_ms_median  dt_ms_min  dt_ms_max  trial_count_vs_duration  start_offset_ms  sbp_min  sbp_max  tcr_min  tcr_max  tcr_integer  pos_min  pos_max  vel_min  vel_max  targets  target_min  target_max
0   2021-10-15   CO           CO     375     375  21825            20         19       1094                    1.019                0   0.7937    30.52        0        6         True  0.06596        1 -0.09982    0.154       23         0.1         0.9
1   2021-10-15   RD           RD     375     375  26836            20         19         21                    1.015                0    0.725    25.74        0        7         True        0        1  -0.2025   0.3075      375   9.266e-05      0.9994
2   2022-02-25   RD           RD     375     375  27135            20         19         21                    1.015                0   0.7188    16.64        0        6         True        0        1  -0.1384   0.5444      375   0.0005175      0.9946
3   2022-02-25   CO           CO     375     375  23816            20         19         21                    1.017                0   0.7188    15.84        0        6         True  0.03073   0.9815  -0.1196   0.1525       23         0.1         0.9
4   2022-04-08   CO           CO     375     375  22384            20         19         21                    1.018                0    0.725    21.08        0        5         True  0.05292        1  -0.1354   0.2096       23         0.1         0.9
5   2022-04-08   RD           RD     375     375  24997            20         19         21                    1.016                0      0.7    21.33        0        5         True    0.028        1  -0.1798   0.2542      375   0.0009816       0.998
6   2022-04-15   CO           CO     375     375  22568            20         19         21                    1.018                0    0.725    23.53        0        7         True  0.08375        1  -0.1133    0.215       23         0.1         0.9
7   2022-04-15   RD           RD     375     375  24874            20         19         21                    1.016                0   0.6625    28.11        0        7         True  0.00575        1  -0.2225   0.3613      375   0.0004213      0.9959
8   2022-04-29   RD           RD     375     375  24682            20         19         21                    1.016                0   0.7312    21.09        0        7         True  0.02105        1  -0.2452   0.2275      375    0.003954      0.9989
9   2022-04-29   CO           CO     375     375  22364            20         19         21                    1.019                0   0.6667    20.47        0        6         True  0.07888        1  -0.1623    0.183       23         0.1         0.9
10  2022-05-13   RD           RD     375     375  25290            20         19         21                    1.016                0     0.75    19.44        0        6         True   0.0315        1  -0.2189   0.2191      375    0.003375      0.9992
11  2022-05-13   CO           CO     375     375  23653            20         19         21                    1.018                0   0.7125    40.22        0        6         True  0.07848   0.9524  -0.1176   0.1144       23         0.1         0.9
12  2022-08-10   CO           CO     375     375  22292            20         19         21                    1.019                0   0.7688    24.92        0        7         True  0.08679   0.9907  -0.1227   0.1527       23         0.1         0.9
13  2022-08-10   RD           RD     375     375  23475            20         19         21                    1.017                0   0.6812    30.97        0       11         True        0        1   -0.182   0.2609      375   5.686e-05      0.9971
14  2022-09-21   CO           CO     375     375  22725            20         19         21                    1.018                0   0.7437    24.62        0        5         True  0.03825        1  -0.1743   0.1986       23         0.1         0.9
15  2022-09-21   RD           RD     375     375  25015            20         19         21                    1.016                0   0.7063    25.12        0        5         True        0        1  -0.2107   0.2626      375    0.001202      0.9999
16  2022-11-02   RD           RD     375     375  24786            20         19         21                    1.016                0   0.7063    21.62        0        8         True  0.03214        1  -0.2725   0.2356      375   0.0002862      0.9986
17  2022-11-02   CO           CO     375     375  22194            20         19         21                    1.018                0   0.6812    22.28        0        7         True  0.06155        1  -0.1351   0.1551       23         0.1         0.9
units: {'SpikingBandPower': 'volts', 'ThresholdCrossings': 'volts', 'index_position': 'flexion units', 'index_velocity': 'flexion units per time bin'}
tasks per paired date: {'2021-10-15': ['CO', 'RD'], '2022-02-25': ['CO', 'RD'], '2022-04-08': ['CO', 'RD'], '2022-04-15': ['CO', 'RD'], '2022-04-29': ['CO', 'RD'], '2022-05-13': ['CO', 'RD'], '2022-08-10': ['CO', 'RD'], '2022-09-21': ['CO', 'RD'], '2022-11-02': ['CO', 'RD']}
target_style column agrees with the identifier's task: True
In [4]:
# Recordings deposited more than once: compare every pair of sessions' SBP, TCR and position arrays
import hashlib
digests = {}
for s in sessions:
    for name, arr in [("SBP", s.signals["SpikingBandPower"]), ("TCR", s.signals["ThresholdCrossings"]), ("pos", s.position)]:
        digests.setdefault(name, []).append(hashlib.sha1(np.ascontiguousarray(arr).tobytes()).hexdigest())
for name, values in digests.items():
    dup = [(sessions[i].identifier, sessions[j].identifier) for i in range(len(values)) for j in range(i + 1, len(values)) if values[i] == values[j]]
    print(f"{name}: {len(set(values))} distinct arrays of {len(values)}; identical pairs: {dup}")
# near-duplicates: the largest correlation of the first 2000 SBP rows (channel mean) between sessions
first = np.array([s.signals["SpikingBandPower"][:2000].mean(axis=1) for s in sessions])
c = np.corrcoef(first)
np.fill_diagonal(c, np.nan)
print("largest between-session correlation of the first 2000 SBP bins:", round(float(np.nanmax(c)), 3))
# velocity against the first difference of position (velocity is described as derived post hoc)
for s in sessions[:18]:
    dp = np.diff(s.position, axis=0)
    r = [np.corrcoef(dp[:, k], s.velocity[1:, k])[0, 1] for k in range(2)]
    r_lag = [np.corrcoef(dp[:, k], s.velocity[:-1, k])[0, 1] for k in range(2)]
    ratio = [np.std(s.velocity[:, k]) / np.std(dp[:, k]) for k in range(2)]
    print(f"{s.identifier}: corr(velocity[t], position[t]-position[t-1]) = {r[0]:.3f}, {r[1]:.3f}; "
          f"with velocity[t-1] {r_lag[0]:.3f}, {r_lag[1]:.3f}; std ratio {ratio[0]:.2f}, {ratio[1]:.2f}")
SBP: 18 distinct arrays of 18; identical pairs: []
TCR: 18 distinct arrays of 18; identical pairs: []
pos: 18 distinct arrays of 18; identical pairs: []
largest between-session correlation of the first 2000 SBP bins: 0.164
2021-10-15_CO_nwb: corr(velocity[t], position[t]-position[t-1]) = 0.814, 0.868; with velocity[t-1] 1.000, 0.987; std ratio 1.00, 0.99
2021-10-15_RD_nwb: corr(velocity[t], position[t]-position[t-1]) = 0.818, 0.872; with velocity[t-1] 1.000, 1.000; std ratio 1.00, 1.00
2022-02-25_RD_nwb: corr(velocity[t], position[t]-position[t-1]) = 0.757, 0.891; with velocity[t-1] 1.000, 1.000; std ratio 1.00, 1.00
2022-02-25_CO_nwb: corr(velocity[t], position[t]-position[t-1]) = 0.862, 0.891; with velocity[t-1] 1.000, 1.000; std ratio 1.00, 1.00
2022-04-08_CO_nwb: corr(velocity[t], position[t]-position[t-1]) = 0.798, 0.904; with velocity[t-1] 1.000, 1.000; std ratio 1.00, 1.00
2022-04-08_RD_nwb: corr(velocity[t], position[t]-position[t-1]) = 0.856, 0.893; with velocity[t-1] 1.000, 1.000; std ratio 1.00, 1.00
2022-04-15_CO_nwb: corr(velocity[t], position[t]-position[t-1]) = 0.823, 0.885; with velocity[t-1] 1.000, 1.000; std ratio 1.00, 1.00
2022-04-15_RD_nwb: corr(velocity[t], position[t]-position[t-1]) = 0.833, 0.862; with velocity[t-1] 1.000, 1.000; std ratio 1.00, 1.00
2022-04-29_RD_nwb: corr(velocity[t], position[t]-position[t-1]) = 0.840, 0.842; with velocity[t-1] 1.000, 1.000; std ratio 1.00, 1.00
2022-04-29_CO_nwb: corr(velocity[t], position[t]-position[t-1]) = 0.817, 0.873; with velocity[t-1] 1.000, 1.000; std ratio 1.00, 1.00
2022-05-13_RD_nwb: corr(velocity[t], position[t]-position[t-1]) = 0.843, 0.834; with velocity[t-1] 1.000, 1.000; std ratio 1.00, 1.00
2022-05-13_CO_nwb: corr(velocity[t], position[t]-position[t-1]) = 0.826, 0.849; with velocity[t-1] 1.000, 1.000; std ratio 1.00, 1.00
2022-08-10_CO_nwb: corr(velocity[t], position[t]-position[t-1]) = 0.839, 0.883; with velocity[t-1] 1.000, 1.000; std ratio 1.00, 1.00
2022-08-10_RD_nwb: corr(velocity[t], position[t]-position[t-1]) = 0.880, 0.867; with velocity[t-1] 1.000, 1.000; std ratio 1.00, 1.00
2022-09-21_CO_nwb: corr(velocity[t], position[t]-position[t-1]) = 0.826, 0.698; with velocity[t-1] 1.000, 1.000; std ratio 1.00, 1.00
2022-09-21_RD_nwb: corr(velocity[t], position[t]-position[t-1]) = 0.869, 0.740; with velocity[t-1] 1.000, 1.000; std ratio 1.00, 1.00
2022-11-02_RD_nwb: corr(velocity[t], position[t]-position[t-1]) = 0.844, 0.788; with velocity[t-1] 1.000, 1.000; std ratio 1.00, 1.00
2022-11-02_CO_nwb: corr(velocity[t], position[t]-position[t-1]) = 0.849, 0.814; with velocity[t-1] 1.000, 1.000; std ratio 1.00, 1.00
In [5]:
# Clock check: decode finger velocity in the 25-bin trial windows from 40 ms of SBP whose end is
# shifted by `lag` bins from the behaviour bin (positive lag = neural data earlier). If the SBP
# series and the trials table share a clock, held-out R2 peaks at a small positive lag and falls
# away on both sides; an offset between the streams would move the peak.
from sklearn.linear_model import Ridge
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import r2_score
lags = [-25, -10, -5, -2, 0, 2, 5, 10, 25]
clock = []
for s in sessions:
    ds = d.build_link_dataset(s, context_mode="phase_only")  # the analysis windows: 25 bins from 8 bins after the start bin
    starts = np.array([int(np.argmin(np.abs(s.timestamps - t))) for t in s.trials.start_time.to_numpy()[ds.source_rows]])
    bins = starts[:, None] + 8 + np.arange(25)[None, :]
    sbp = s.signals["SpikingBandPower"]
    inside = (bins.min(axis=1) - 27 >= 0) & (bins.max(axis=1) + 25 < len(sbp))  # every lag stays inside the recording
    keep = np.flatnonzero(inside)
    position_of = {k: i for i, k in enumerate(keep)}
    tr = np.array([position_of[i] for i in ds.train_indices if inside[i]])
    te = np.array([position_of[i] for i in ds.test_indices if inside[i]])
    Y = ds.behavior[keep]
    row = {"session": s.identifier, "trials": int(inside.sum())}
    for lag in lags:
        X = np.stack([np.stack([sbp[b - lag - 2: b - lag].reshape(-1) for b in tb]) for tb in bins[keep]])
        m = make_pipeline(StandardScaler(), Ridge(alpha=1000.0)).fit(X[tr].reshape(-1, X.shape[-1]), Y[tr].reshape(-1, 2))
        row[lag] = r2_score(Y[te].reshape(-1, 2), m.predict(X[te].reshape(-1, X.shape[-1])), multioutput="variance_weighted")
    clock.append(row)
clock = pd.DataFrame(clock).set_index("session")
print("held-out R2 of velocity from 40 ms of SBP ending `lag` bins before the behaviour bin")
print(clock.round(3).to_string())
print("lag of the peak per session:", clock[lags].idxmax(axis=1).value_counts().to_dict())
held-out R2 of velocity from 40 ms of SBP ending `lag` bins before the behaviour bin
                   trials    -25    -10     -5     -2      0      2      5     10     25
session                                                                                 
2021-10-15_CO_nwb     373  0.026  0.119  0.156  0.241  0.304  0.207  0.083  0.021  0.006
2021-10-15_RD_nwb     374  0.046  0.098  0.168  0.267  0.304  0.214  0.102  0.043  0.028
2022-02-25_RD_nwb     374  0.027  0.078  0.098  0.151  0.198  0.208  0.118  0.031  0.008
2022-02-25_CO_nwb     374  0.036  0.071  0.101  0.187  0.253  0.290  0.241  0.099 -0.003
2022-04-08_CO_nwb     374 -0.002  0.038  0.082  0.146  0.165  0.121  0.049  0.018 -0.011
2022-04-08_RD_nwb     374  0.030  0.060  0.101  0.177  0.215  0.189  0.129  0.043  0.011
2022-04-15_CO_nwb     373  0.033  0.078  0.101  0.235  0.298  0.260  0.134  0.046  0.013
2022-04-15_RD_nwb     374  0.067  0.094  0.120  0.241  0.289  0.232  0.099  0.042  0.038
2022-04-29_RD_nwb     374  0.044  0.101  0.145  0.231  0.258  0.208  0.090  0.037  0.013
2022-04-29_CO_nwb     373  0.036  0.080  0.125  0.227  0.267  0.194  0.082  0.010 -0.018
2022-05-13_RD_nwb     373  0.031  0.076  0.163  0.226  0.229  0.173  0.071  0.023  0.009
2022-05-13_CO_nwb     374  0.034  0.087  0.115  0.204  0.216  0.170  0.077  0.010 -0.014
2022-08-10_CO_nwb     374  0.009  0.043  0.108  0.257  0.285  0.212  0.053  0.008 -0.004
2022-08-10_RD_nwb     373  0.025  0.062  0.127  0.215  0.309  0.241  0.066  0.018  0.011
2022-09-21_CO_nwb     373  0.014  0.049  0.062  0.143  0.179  0.128  0.029  0.008 -0.011
2022-09-21_RD_nwb     374  0.044  0.077  0.102  0.180  0.207  0.166  0.051  0.015  0.001
2022-11-02_RD_nwb     373  0.068  0.133  0.141  0.233  0.283  0.224  0.088  0.042  0.020
2022-11-02_CO_nwb     374  0.022  0.078  0.127  0.239  0.256  0.183  0.087  0.025 -0.012
lag of the peak per session: {0: 16, 2: 2}
In [6]:
print(f"data check done in {time.time() - T0:.0f} s; peak memory {resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1e6:.2f} GB")
data check done in 37 s; peak memory 0.68 GB

The fits¶

Every fit is the fully nested estimator (Methods 4.5; du2026.fully_nested, a port of evaluate_fully_nested_audit) unless named otherwise, with the windows of the run scripts: 160 ms of SBP or TCR ending at the behaviour bin, 100 ms of position history ending at the same bin, a 70/30 direction-stratified split with random_state 20260726. Per session:

  • SBP, the five contexts of the ladder (run_link_context_ladder.py).
  • SBP and TCR geometry by phase with 100 within-condition permutations, replacement ranks one to five and uniform random same-condition sources (Methods 4.7), and SBP geometry by phase and plus history with the three nonlinear-neural maps (Methods 4.6).
  • TCR plus history.
  • Neural-only Ridge (decoders_nested, the release's evaluate_decoders_nested, claims file).
  • SBP geometry by phase under split seeds 20260727 and 20260728 (Results 2.7).
  • Seed sensitivity (protocol, author step 3): SBP geometry by phase and plus history, and the neural-only R2, under split and refit seeds 20260726 plus 1000, 2000, 3000 and 4000.
In [7]:
SEED = 20260726
EXTRA = (1000, 2000, 3000, 4000)
RANDOM_SOURCE_SEEDS = tuple(claim_seed("replacement-ranks-lower") + k for k in (0,) + EXTRA)
def job(name, signal, context, estimator="nested", seed=SEED, keep=False, **kw):
    build = dict(signal=signal, context_mode=context, seed=seed)
    est = dict(kw)
    if estimator == "nested":
        est["seed"] = seed
    if estimator == "decoders":
        est.update(seed=seed, neural_only_only=True)
    return (name, build, estimator, est, keep)

jobs = []
for context in d.LADDER:
    kw = {}
    if context == "geometry_tensor":
        kw = dict(n_permutations=100, permutation_seed_offsets=EXTRA, n_ranks=5,
                  random_source_seeds=RANDOM_SOURCE_SEEDS, rff_seeds=d.RFF_SEEDS)
    if context == "causal_history":
        kw = dict(rff_seeds=d.RFF_SEEDS)
    jobs.append(job(f"SBP_{context}", "SpikingBandPower", context, keep=(context == "geometry_tensor"), **kw))
jobs.append(job("TCR_geometry_tensor", "ThresholdCrossings", "geometry_tensor", n_permutations=100,
                permutation_seed_offsets=EXTRA, n_ranks=5, random_source_seeds=RANDOM_SOURCE_SEEDS))
jobs.append(job("TCR_causal_history", "ThresholdCrossings", "causal_history"))
for k in (0,) + EXTRA:
    jobs.append(job(f"neural_only_{SEED + k}", "SpikingBandPower", "geometry_tensor", "decoders", seed=SEED + k))
for seed in d.SPLIT_SEEDS[1:]:
    jobs.append(job(f"SBP_geometry_tensor_{seed}", "SpikingBandPower", "geometry_tensor", seed=seed))
for k in EXTRA:
    for context in ("geometry_tensor", "causal_history"):
        jobs.append(job(f"SBP_{context}_{SEED + k}", "SpikingBandPower", context, seed=SEED + k))

t = time.time()
results = d.run_parallel(d.link_session_jobs, [(a["asset_id"], a["path"], jobs) for a in dev_assets])
print(f"{len(jobs)} fits per session on {len(results)} sessions in {(time.time() - t) / 60:.1f} min")

def table(name, field="gain"):
    return pd.DataFrame([{"date": r["date"], "task": r["task"], field: r[name][field]} for r in results])
def task_means(name, field="gain"):
    return table(name, field).groupby("task")[field].mean()
22 fits per session on 18 sessions in 22.5 min

link-development-sample¶

The LINK development set is the nine dates with both a CO and an RD session, 18 sessions and 6,750 usable trials from one macaque, with 375 usable trials in every analyzed session.

In [8]:
usable = pd.DataFrame([{"date": r["date"], "task": r["task"], "usable": r["SBP_geometry_tensor"]["n_usable"],
                        "trials_table": r["SBP_geometry_tensor"]["n_trials_table"]} for r in results])
print(usable.to_string())
both = [dt for dt in paired_dates if sorted(check.task[check.date == dt]) == ["CO", "RD"]]
print(f"dates with both a CO and an RD session: {len(both)}  (expected 9)")
print(f"sessions: {len(usable)}; subjects in the asset paths: {sorted(set(a['path'].split('/')[0] for a in dev_assets))}")
print(f"usable trials: {usable.usable.sum()}  (expected 6750, tolerance 675)")
print(f"sessions with 375 usable trials: {(usable.usable == 375).sum()} of {len(usable)}; "
      f"range {usable.usable.min()} to {usable.usable.max()}; trials dropped by the window rule: "
      f"{(usable.trials_table - usable.usable).sum()}")
          date task  usable  trials_table
0   2021-10-15   CO     375           375
1   2021-10-15   RD     375           375
2   2022-02-25   RD     375           375
3   2022-02-25   CO     375           375
4   2022-04-08   CO     375           375
5   2022-04-08   RD     375           375
6   2022-04-15   CO     375           375
7   2022-04-15   RD     375           375
8   2022-04-29   RD     375           375
9   2022-04-29   CO     375           375
10  2022-05-13   RD     375           375
11  2022-05-13   CO     375           375
12  2022-08-10   CO     375           375
13  2022-08-10   RD     375           375
14  2022-09-21   CO     375           375
15  2022-09-21   RD     375           375
16  2022-11-02   RD     375           375
17  2022-11-02   CO     375           375
dates with both a CO and an RD session: 9  (expected 9)
sessions: 18; subjects in the asset paths: ['sub-Monkey-N']
usable trials: 6750  (expected 6750, tolerance 675)
sessions with 375 usable trials: 18 of 18; range 375 to 375; trials dropped by the window rule: 0

Result: reproduced. Nine dates have both a CO and an RD session (the only dates with more than one asset), and each of the 18 sessions has 375 trials in its table, all 375 usable under the window rule of link.py: 6,750 usable trials in total.

link-neural-only-r2¶

In the LINK development sessions, neural-only Ridge decoding of finger velocity from 160 ms of SBP had held-out R2 of 0.308 in CO and 0.313 in RD, the same at every rung of the context ladder.

X, Y and the split do not depend on the context (the split is stratified by direction octant, which every rung shares), so one neural-only fit per session serves every rung.

In [9]:
no = table(f"neural_only_{SEED}", "neural_r2")
print(no.pivot(index="date", columns="task", values="neural_r2").round(4).to_string())
m = no.groupby("task").neural_r2.mean()
print(f"CO mean {m['CO']:.4f} (expected 0.308 +- 0.0308); RD mean {m['RD']:.4f} (expected 0.313 +- 0.0313)")
for k in (0,) + EXTRA:
    mm = task_means(f"neural_only_{SEED + k}", "neural_r2")
    print(f"seed {SEED + k}: CO {mm['CO']:.4f}, RD {mm['RD']:.4f}")
print("neural-only penalties chosen:", collections.Counter(r[f"neural_only_{SEED}"]["neural_alpha"] for r in results))
task            CO      RD
date                      
2021-10-15  0.3364  0.3387
2022-02-25  0.4157  0.2384
2022-04-08  0.2096  0.3031
2022-04-15  0.3777  0.3480
2022-04-29  0.3071  0.3368
2022-05-13  0.2783  0.2927
2022-08-10  0.3371  0.3609
2022-09-21  0.2078  0.2552
2022-11-02  0.2996  0.3424
CO mean 0.3077 (expected 0.308 +- 0.0308); RD mean 0.3129 (expected 0.313 +- 0.0313)
seed 20260726: CO 0.3077, RD 0.3129
seed 20261726: CO 0.3116, RD 0.3153
seed 20262726: CO 0.2969, RD 0.3125
seed 20263726: CO 0.3101, RD 0.3248
seed 20264726: CO 0.3056, RD 0.3205
neural-only penalties chosen: Counter({1000.0: 17, 10000.0: 1})

Result: reproduced. Neural-only Ridge from 160 ms of SBP gives held-out R2 of 0.3077 in CO and 0.3129 in RD (paper 0.308 and 0.313). Under the four other split seeds the task means stay between 0.2969 and 0.3248, inside both tolerances.

link-context-ladder-gain¶

In LINK with SBP, mean context-conditional neural gain fell along the context ladder, from 0.3012/0.3125 (CO/RD) beyond phase alone to 0.0657/0.0502 beyond direction by phase, 0.0443/0.0332 beyond additive geometry, 0.0193/0.0209 beyond geometry by phase, and 0.0077/0.0098 beyond geometry by phase plus measured-output history.

In [10]:
expected = {"phase_only": (0.3012, 0.3125), "condition_phase": (0.0657, 0.0502), "geometry_additive": (0.0443, 0.0332),
            "geometry_tensor": (0.0193, 0.0209), "causal_history": (0.0077, 0.0098)}
ladder = []
for context in d.LADDER:
    m = task_means(f"SBP_{context}")
    g = table(f"SBP_{context}").gain
    for task, exp in zip(("CO", "RD"), expected[context]):
        ladder.append(dict(context=d.LADDER_NAMES[context], task=task, mean_gain=m[task], expected=exp,
                           within_10pct=abs(m[task] - exp) <= 0.1 * exp))
    print(f"{d.LADDER_NAMES[context]:>30}: session gains {g.min():.4f} to {g.max():.4f}, {int((g > 0).sum())}/18 positive")
ladder = pd.DataFrame(ladder)
print(ladder.to_string(float_format=lambda v: f"{v:.4f}"))
falls = {task: bool(np.all(np.diff(ladder[ladder.task == task].mean_gain.to_numpy()) < 0)) for task in ("CO", "RD")}
print("falls at every step:", falls, "; values within tolerance:", int(ladder.within_10pct.sum()), "of 10")
print("per session (rows: date and task; columns: rung):")
print(pd.DataFrame({d.LADDER_NAMES[c]: table(f"SBP_{c}").set_index(["date", "task"]).gain for c in d.LADDER}).round(4).to_string())
                    phase only: session gains 0.1898 to 0.4112, 18/18 positive
            direction by phase: session gains 0.0281 to 0.0887, 18/18 positive
             additive geometry: session gains 0.0095 to 0.0622, 18/18 positive
             geometry by phase: session gains 0.0028 to 0.0335, 18/18 positive
  plus measured-output history: session gains -0.0006 to 0.0189, 17/18 positive
                        context task  mean_gain  expected  within_10pct
0                    phase only   CO     0.3012    0.3012          True
1                    phase only   RD     0.3125    0.3125          True
2            direction by phase   CO     0.0657    0.0657          True
3            direction by phase   RD     0.0502    0.0502          True
4             additive geometry   CO     0.0443    0.0443          True
5             additive geometry   RD     0.0332    0.0332          True
6             geometry by phase   CO     0.0193    0.0193          True
7             geometry by phase   RD     0.0209    0.0209          True
8  plus measured-output history   CO     0.0077    0.0077          True
9  plus measured-output history   RD     0.0098    0.0098          True
falls at every step: {'CO': True, 'RD': True} ; values within tolerance: 10 of 10
per session (rows: date and task; columns: rung):
                 phase only  direction by phase  additive geometry  geometry by phase  plus measured-output history
date       task                                                                                                    
2021-10-15 CO        0.3299              0.0782             0.0561             0.0230                        0.0123
           RD        0.3209              0.0672             0.0456             0.0227                        0.0089
2022-02-25 RD        0.2562              0.0281             0.0095             0.0028                       -0.0006
           CO        0.4112              0.0827             0.0528             0.0141                        0.0005
2022-04-08 CO        0.2107              0.0433             0.0305             0.0141                        0.0058
           RD        0.3059              0.0403             0.0223             0.0148                        0.0051
2022-04-15 CO        0.3779              0.0887             0.0622             0.0269                        0.0099
           RD        0.3414              0.0552             0.0343             0.0253                        0.0118
2022-04-29 RD        0.3321              0.0674             0.0441             0.0335                        0.0189
           CO        0.3030              0.0554             0.0320             0.0116                        0.0016
2022-05-13 RD        0.2948              0.0413             0.0253             0.0126                        0.0102
           CO        0.2750              0.0486             0.0299             0.0139                        0.0059
2022-08-10 CO        0.3191              0.0776             0.0528             0.0229                        0.0070
           RD        0.3660              0.0593             0.0505             0.0303                        0.0140
2022-09-21 CO        0.1898              0.0445             0.0348             0.0188                        0.0102
           RD        0.2535              0.0388             0.0292             0.0207                        0.0071
2022-11-02 RD        0.3415              0.0543             0.0382             0.0249                        0.0128
           CO        0.2943              0.0721             0.0474             0.0287                        0.0158

Result: reproduced. The task means are 0.3012/0.3125, 0.0657/0.0502, 0.0443/0.0332, 0.0193/0.0209 and 0.0077/0.0098 (CO/RD) along the five rungs, equal to the paper's values at the printed precision, so all 10 are within tolerance, and both task means fall at every step.

link-context-only-r2¶

Context-only R2 in LINK rose along the ladder from 0.0084/0.0055 (CO/RD) with phase alone to 0.6617/0.6839 with geometry by phase plus measured-output history.

In [11]:
cr = pd.DataFrame({d.LADDER_NAMES[c]: task_means(f"SBP_{c}", "context_r2") for c in d.LADDER}).T
print(cr.round(4).to_string())
print(f"phase only: CO {cr.loc['phase only', 'CO']:.4f}, RD {cr.loc['phase only', 'RD']:.4f} (criterion below 0.02; 10% tolerances 0.0084 +- 0.00084, 0.0055 +- 0.00055)")
print(f"plus history: CO {cr.loc['plus measured-output history', 'CO']:.4f} (0.6617 +- 0.06617), RD {cr.loc['plus measured-output history', 'RD']:.4f} (0.6839 +- 0.06839)")
pc = table("SBP_phase_only", "context_r2").context_r2
print(f"phase-only session context R2 range {pc.min():.4f} to {pc.max():.4f}")
task                              CO      RD
phase only                    0.0084  0.0055
direction by phase            0.4064  0.4524
additive geometry             0.4621  0.5175
geometry by phase             0.5702  0.5999
plus measured-output history  0.6617  0.6839
phase only: CO 0.0084, RD 0.0055 (criterion below 0.02; 10% tolerances 0.0084 +- 0.00084, 0.0055 +- 0.00055)
plus history: CO 0.6617 (0.6617 +- 0.06617), RD 0.6839 (0.6839 +- 0.06839)
phase-only session context R2 range -0.0021 to 0.0224

Result: reproduced. Context-only R2 is 0.0084/0.0055 (CO/RD) with phase only, below 0.02 and equal to the paper's values, and 0.6617/0.6839 with geometry by phase plus measured-output history, equal to the paper's.

link-phase-only-replacement¶

With phase-only context, the mean nearest-replacement gain in RD stayed positive (0.10498).

Under phase only every trial has the same context trajectory, so every distance is zero and the tie rule (lower trial index, Methods 4.7) picks the first other same-direction test trial.

In [12]:
pr = table("SBP_phase_only", "replacement_gain")
m = pr.groupby("task").replacement_gain.mean()
print(pr.pivot(index="date", columns="task", values="replacement_gain").round(4).to_string())
print(f"RD mean replacement gain, phase only: {m['RD']:.5f} (expected 0.10498 +- 0.010498); CO {m['CO']:.5f}")
print(f"RD sessions positive: {int((pr[pr.task == 'RD'].replacement_gain > 0).sum())}/9")
task            CO      RD
date                      
2021-10-15 -0.0489  0.0190
2022-02-25 -0.0534  0.1717
2022-04-08 -0.0505  0.1376
2022-04-15 -0.0769  0.1486
2022-04-29  0.0341 -0.0028
2022-05-13  0.0304  0.1339
2022-08-10 -0.0552  0.1067
2022-09-21  0.0769  0.1389
2022-11-02  0.0456  0.0912
RD mean replacement gain, phase only: 0.10498 (expected 0.10498 +- 0.010498); CO -0.01087
RD sessions positive: 8/9

Result: reproduced. Under phase only, the mean nearest-replacement gain over the nine RD sessions is 0.10498 (paper 0.10498), positive in 8 of 9 RD sessions; in CO it is -0.01087.

link-task-contrast-by-context¶

The descriptive RD-minus-CO gain contrast changed with the context; it was positive under phase only, negative under direction by phase and additive geometry, near zero under geometry by phase, and small positive after measured-output history.

Per date RD minus CO, mean over nine dates, 95% interval from 10,000 date resamples (generator seeded from the claim; the claim seed plus 1000 to 4000 give the interval's sensitivity).

In [13]:
contrast = []
for context in d.LADDER:
    p = table(f"SBP_{context}").pivot(index="date", columns="task", values="gain")
    diff = (p["RD"] - p["CO"]).to_numpy()
    cis = []
    for k in (0,) + EXTRA:
        rng = np.random.default_rng(claim_seed("link-task-contrast-by-context") + k)
        boots = np.array([rng.choice(diff, len(diff), replace=True).mean() for _ in range(10000)])
        cis.append(np.quantile(boots, [0.025, 0.975]))
    contrast.append(dict(context=d.LADDER_NAMES[context], mean=diff.mean(), ci_low=cis[0][0], ci_high=cis[0][1],
                         ci_contains_zero=bool(cis[0][0] <= 0 <= cis[0][1]),
                         ci_low_range=f"{min(c[0] for c in cis):.4f}..{max(c[0] for c in cis):.4f}",
                         ci_high_range=f"{min(c[1] for c in cis):.4f}..{max(c[1] for c in cis):.4f}",
                         dates_positive=int((diff > 0).sum())))
contrast = pd.DataFrame(contrast).set_index("context")
print(contrast.to_string(float_format=lambda v: f"{v:.4f}"))
g = abs(contrast.loc["geometry by phase", "mean"])
print(f"reading (b): |geometry by phase| {g:.4f} < |direction by phase| {abs(contrast.loc['direction by phase', 'mean']):.4f} "
      f"and < |additive geometry| {abs(contrast.loc['additive geometry', 'mean']):.4f}: "
      f"{g < abs(contrast.loc['direction by phase', 'mean']) and g < abs(contrast.loc['additive geometry', 'mean'])}")
                                mean  ci_low  ci_high  ci_contains_zero      ci_low_range     ci_high_range  dates_positive
context                                                                                                                    
phase only                    0.0113 -0.0396   0.0503              True  -0.0402..-0.0384    0.0503..0.0513               6
direction by phase           -0.0155 -0.0281  -0.0045             False  -0.0283..-0.0279  -0.0046..-0.0044               1
additive geometry            -0.0110 -0.0215  -0.0020             False  -0.0218..-0.0215  -0.0021..-0.0020               1
geometry by phase             0.0015 -0.0035   0.0077              True  -0.0036..-0.0034    0.0075..0.0077               4
plus measured-output history  0.0021 -0.0015   0.0067              True  -0.0015..-0.0014    0.0067..0.0067               4
reading (b): |geometry by phase| 0.0015 < |direction by phase| 0.0155 and < |additive geometry| 0.0110: True

Result: reproduced. The mean RD-minus-CO contrast over nine dates is positive under phase only (0.0113), negative under direction by phase (-0.0155) and additive geometry (-0.0110), near zero under geometry by phase (0.0015; its date-bootstrap interval, -0.0035 to 0.0077, contains zero, and its size is below the two negative rungs, so both readings hold) and positive after measured-output history (0.0021). The phase-only and history intervals also contain zero; the claim is judged on the signs of the means, as the criterion says.

nested-geometry-gain¶

With geometry-by-phase context, fully nested mean gain over the 18 LINK sessions was 0.02009 for SBP (18 of 18 sessions positive) and 0.01155 for TCR (17 of 18 positive).

In [14]:
def summary(name, field="gain", seed_key=None):
    t = table(name, field)
    by_date = {dt: g[field].to_numpy() for dt, g in t.groupby("date")}
    lo, hi = d.date_bootstrap(by_date, np.random.default_rng(claim_seed("nested-geometry-gain")))
    return dict(mean=t[field].mean(), positive=int((t[field] > 0).sum()), min=t[field].min(), max=t[field].max(),
                CO=t[t.task == "CO"][field].mean(), RD=t[t.task == "RD"][field].mean(), ci_low=lo, ci_high=hi)
for name, exp, exp_pos in [("SBP_geometry_tensor", 0.02009, 18), ("TCR_geometry_tensor", 0.01155, 17)]:
    s_ = summary(name)
    print(f"{name}: mean {s_['mean']:.5f} (expected {exp}), positive {s_['positive']}/18 (expected {exp_pos}), "
          f"range {s_['min']:.5f} to {s_['max']:.5f}, CO {s_['CO']:.5f}, RD {s_['RD']:.5f}, "
          f"date-clustered 95% interval {s_['ci_low']:.5f} to {s_['ci_high']:.5f}")
print("tolerances: SBP 0.00423, TCR 0.00446; counts 1.8 and 1.7")
vals = [np.mean(table("SBP_geometry_tensor" if k == 0 else f"SBP_geometry_tensor_{SEED + k}").gain) for k in (0,) + EXTRA]
pos = [int((table("SBP_geometry_tensor" if k == 0 else f"SBP_geometry_tensor_{SEED + k}").gain > 0).sum()) for k in (0,) + EXTRA]
print("SBP mean under seeds 20260726 +0/1000/2000/3000/4000:", np.round(vals, 5), "positive:", pos)
print(table("SBP_geometry_tensor").merge(table("TCR_geometry_tensor"), on=["date", "task"], suffixes=("_SBP", "_TCR")).round(5).to_string())
SBP_geometry_tensor: mean 0.02009 (expected 0.02009), positive 18/18 (expected 18), range 0.00283 to 0.03347, CO 0.01933, RD 0.02085, date-clustered 95% interval 0.01586 to 0.02401
TCR_geometry_tensor: mean 0.01155 (expected 0.01155), positive 17/18 (expected 17), range -0.00382 to 0.02571, CO 0.01042, RD 0.01269, date-clustered 95% interval 0.00711 to 0.01591
tolerances: SBP 0.00423, TCR 0.00446; counts 1.8 and 1.7
SBP mean under seeds 20260726 +0/1000/2000/3000/4000: [0.02009 0.01882 0.01907 0.01918 0.01795] positive: [18, 18, 18, 18, 18]
          date task  gain_SBP  gain_TCR
0   2021-10-15   CO   0.02304   0.00804
1   2021-10-15   RD   0.02272   0.01252
2   2022-02-25   RD   0.00283   0.00262
3   2022-02-25   CO   0.01408   0.00824
4   2022-04-08   CO   0.01409  -0.00382
5   2022-04-08   RD   0.01485   0.00271
6   2022-04-15   CO   0.02688   0.01901
7   2022-04-15   RD   0.02529   0.01339
8   2022-04-29   RD   0.03347   0.01769
9   2022-04-29   CO   0.01164   0.00496
10  2022-05-13   RD   0.01262   0.00563
11  2022-05-13   CO   0.01389   0.00623
12  2022-08-10   CO   0.02288   0.01917
13  2022-08-10   RD   0.03031   0.02571
14  2022-09-21   CO   0.01879   0.00992
15  2022-09-21   RD   0.02067   0.02047
16  2022-11-02   RD   0.02494   0.01344
17  2022-11-02   CO   0.02870   0.02202

Result: reproduced. Under geometry by phase the mean gain is 0.02009 for SBP with 18 of 18 sessions positive, and 0.01155 for TCR with 17 of 18 positive, equal to the paper's values; the date-clustered intervals are 0.01586 to 0.02401 and 0.00711 to 0.01591. Under the four other split seeds the SBP mean is 0.01795 to 0.01918, all 18 sessions positive (TCR was not re-run under other seeds).

nested-history-gain¶

Adding lag-matched measured-output history reduced fully nested mean gain to 0.00873 for SBP (17 of 18 sessions positive) and 0.00420 for TCR (16 of 18 positive).

In [15]:
for name, exp, exp_pos in [("SBP_causal_history", 0.00873, 17), ("TCR_causal_history", 0.0042, 16)]:
    s_ = summary(name)
    print(f"{name}: mean {s_['mean']:.5f} (expected {exp}), positive {s_['positive']}/18 (expected {exp_pos}), "
          f"range {s_['min']:.5f} to {s_['max']:.5f}, CO {s_['CO']:.5f}, RD {s_['RD']:.5f}, "
          f"date-clustered 95% interval {s_['ci_low']:.5f} to {s_['ci_high']:.5f}")
print("tolerances: SBP 0.00273, TCR 0.0021; counts 1.7 and 1.6")
for sig in ("SBP", "TCR"):
    print(f"{sig}: history mean {table(f'{sig}_causal_history').gain.mean():.5f} below geometry mean {table(f'{sig}_geometry_tensor').gain.mean():.5f}:",
          table(f"{sig}_causal_history").gain.mean() < table(f"{sig}_geometry_tensor").gain.mean())
vals = [np.mean(table("SBP_causal_history" if k == 0 else f"SBP_causal_history_{SEED + k}").gain) for k in (0,) + EXTRA]
pos = [int((table("SBP_causal_history" if k == 0 else f"SBP_causal_history_{SEED + k}").gain > 0).sum()) for k in (0,) + EXTRA]
print("SBP history mean under the five seeds:", np.round(vals, 5), "positive:", pos)
SBP_causal_history: mean 0.00873 (expected 0.00873), positive 17/18 (expected 17), range -0.00061 to 0.01894, CO 0.00766, RD 0.00980, date-clustered 95% interval 0.00599 to 0.01103
TCR_causal_history: mean 0.00420 (expected 0.0042), positive 16/18 (expected 16), range -0.00165 to 0.01246, CO 0.00329, RD 0.00510, date-clustered 95% interval 0.00214 to 0.00629
tolerances: SBP 0.00273, TCR 0.0021; counts 1.7 and 1.6
SBP: history mean 0.00873 below geometry mean 0.02009: True
TCR: history mean 0.00420 below geometry mean 0.01155: True
SBP history mean under the five seeds: [0.00873 0.00782 0.00774 0.00829 0.00742] positive: [17, 18, 17, 18, 18]

Result: reproduced. With measured-output history the mean gain is 0.00873 for SBP (17 of 18 positive) and 0.00420 for TCR (16 of 18 positive), equal to the paper's values and below each signal's geometry-by-phase mean. Under the four other seeds the SBP mean is 0.00742 to 0.00829, with 17 or 18 sessions positive.

nested-replacement-negative¶

Nearest source-context replacement made all four LINK mean gains negative, -0.00714 and -0.00407 for SBP (geometry by phase, plus history) and -0.00905 and -0.00537 for TCR.

In [16]:
exp = {"SBP_geometry_tensor": -0.00714, "SBP_causal_history": -0.00407, "TCR_geometry_tensor": -0.00905, "TCR_causal_history": -0.00537}
within = 0
for name, e in exp.items():
    t = table(name, "replacement_gain").replacement_gain
    ok = abs(t.mean() - e) <= abs(0.1 * e)
    within += ok
    print(f"{name}: mean replacement gain {t.mean():.5f} (expected {e} +- {abs(0.1 * e):.6f}; within: {ok}); "
          f"negative sessions {int((t < 0).sum())}/18; range {t.min():.5f} to {t.max():.5f}")
print("all four negative:", all(table(n, "replacement_gain").replacement_gain.mean() < 0 for n in exp), "; within tolerance:", within, "of 4")
for k in EXTRA:
    print(f"seed {SEED + k}: SBP geometry {table(f'SBP_geometry_tensor_{SEED + k}', 'replacement_gain').replacement_gain.mean():.5f}, "
          f"SBP history {table(f'SBP_causal_history_{SEED + k}', 'replacement_gain').replacement_gain.mean():.5f}; within tolerance: "
          f"{[bool(abs(table(f'{n}_{SEED + k}', 'replacement_gain').replacement_gain.mean() - exp[n]) <= abs(0.1 * exp[n])) for n in ('SBP_geometry_tensor', 'SBP_causal_history')]}")
SBP_geometry_tensor: mean replacement gain -0.00714 (expected -0.00714 +- 0.000714; within: True); negative sessions 16/18; range -0.01845 to 0.00121
SBP_causal_history: mean replacement gain -0.00407 (expected -0.00407 +- 0.000407; within: True); negative sessions 14/18; range -0.00823 to 0.00266
TCR_geometry_tensor: mean replacement gain -0.00905 (expected -0.00905 +- 0.000905; within: True); negative sessions 16/18; range -0.01821 to 0.00049
TCR_causal_history: mean replacement gain -0.00537 (expected -0.00537 +- 0.000537; within: True); negative sessions 15/18; range -0.01030 to 0.00040
all four negative: True ; within tolerance: 4 of 4
seed 20261726: SBP geometry -0.00887, SBP history -0.00496; within tolerance: [False, False]
seed 20262726: SBP geometry -0.00714, SBP history -0.00478; within tolerance: [True, False]
seed 20263726: SBP geometry -0.00831, SBP history -0.00428; within tolerance: [False, True]
seed 20264726: SBP geometry -0.00776, SBP history -0.00428; within tolerance: [True, True]

Result: reproduced. Nearest source-context replacement gives mean gains of -0.00714 and -0.00407 for SBP and -0.00905 and -0.00537 for TCR, all four negative and all within tolerance. The SBP values move with the split seed: under the four other seeds they are -0.00887 to -0.00714 (geometry) and -0.00496 to -0.00428 (history), so under seed plus 1000 both SBP values are outside their 10% tolerances, under plus 2000 the history value and under plus 3000 the geometry value is outside, and under plus 4000 both are inside.

replacement-source-diagnostics¶

For primary SBP geometry, every test trial had at least five eligible same-condition sources, the median over sessions of the maximum source reuse was three targets and the maximum over sessions four, and self-replacement reproduced the correct-pair predictions exactly.

In [17]:
diag = pd.DataFrame([{"date": r["date"], "task": r["task"], "eligible_min": r["SBP_geometry_tensor"]["eligible_sources_min"],
                      "reuse_max": r["SBP_geometry_tensor"]["source_reuse_max"],
                      "self_error": r["SBP_geometry_tensor"]["self_replacement_max_abs_error"]} for r in results])
print(diag.to_string())
print(f"minimum eligible sources over sessions: {diag.eligible_min.min()} (expected at least 5)")
print(f"median over sessions of the maximum reuse: {diag.reuse_max.median()} (expected 3); maximum: {diag.reuse_max.max()} (expected 4)")
print(f"largest self-replacement difference: {diag.self_error.max():.3g} (criterion below 1e-10)")
          date task  eligible_min  reuse_max  self_error
0   2021-10-15   CO             5          3         0.0
1   2021-10-15   RD             7          3         0.0
2   2022-02-25   RD             6          4         0.0
3   2022-02-25   CO             7          2         0.0
4   2022-04-08   CO             7          3         0.0
5   2022-04-08   RD             7          4         0.0
6   2022-04-15   CO             6          3         0.0
7   2022-04-15   RD             7          4         0.0
8   2022-04-29   RD             8          4         0.0
9   2022-04-29   CO            10          3         0.0
10  2022-05-13   RD             9          4         0.0
11  2022-05-13   CO             8          3         0.0
12  2022-08-10   CO             5          3         0.0
13  2022-08-10   RD             9          4         0.0
14  2022-09-21   CO             7          3         0.0
15  2022-09-21   RD             7          4         0.0
16  2022-11-02   RD             8          3         0.0
17  2022-11-02   CO             6          3         0.0
minimum eligible sources over sessions: 5 (expected at least 5)
median over sessions of the maximum reuse: 3.0 (expected 3); maximum: 4 (expected 4)
largest self-replacement difference: 0 (criterion below 1e-10)

Result: reproduced. The fewest eligible same-condition sources for any test trial is 5, the median over sessions of the largest reuse of one source is 3 and the largest over sessions is 4, and self-replacement reproduces the correct-pair predictions exactly (largest difference 0).

permutation-negative¶

The mean gain of 100 within-condition whole-trial permutations was negative in every LINK session, with an across-session mean of -0.0142.

In [18]:
for label, names in [("(a) 18 SBP geometry sessions", ["SBP_geometry_tensor"]),
                     ("(b) 36 SBP and TCR geometry sessions", ["SBP_geometry_tensor", "TCR_geometry_tensor"])]:
    vals = np.concatenate([table(n, "permutation_mean").permutation_mean.to_numpy() for n in names])
    print(f"{label}: negative {int((vals < 0).sum())}/{len(vals)}, mean {vals.mean():.5f} (expected -0.0142 +- 0.00142), "
          f"range {vals.min():.5f} to {vals.max():.5f}")
    for k in EXTRA:
        v = np.concatenate([[r[n]["permutation_means"][k] for r in results] for n in names])
        print(f"   permutation generator offset +{k}: negative {int((v < 0).sum())}/{len(v)}, mean {v.mean():.5f}")
(a) 18 SBP geometry sessions: negative 18/18, mean -0.01418 (expected -0.0142 +- 0.00142), range -0.01916 to -0.00752
   permutation generator offset +1000: negative 18/18, mean -0.01414
   permutation generator offset +2000: negative 18/18, mean -0.01405
   permutation generator offset +3000: negative 18/18, mean -0.01414
   permutation generator offset +4000: negative 18/18, mean -0.01426
(b) 36 SBP and TCR geometry sessions: negative 36/36, mean -0.01387 (expected -0.0142 +- 0.00142), range -0.01916 to -0.00752
   permutation generator offset +1000: negative 36/36, mean -0.01378
   permutation generator offset +2000: negative 36/36, mean -0.01381
   permutation generator offset +3000: negative 36/36, mean -0.01383
   permutation generator offset +4000: negative 36/36, mean -0.01391

Result: reproduced. Under reading (a), the 18 SBP geometry-by-phase sessions, the permutation mean is negative in 18 of 18 sessions with an across-session mean of -0.01418 (paper -0.0142); reading (b), with the TCR sessions, also holds (36 of 36, -0.01387). Four other permutation generators give -0.01405 to -0.01426 under reading (a).

replacement-penalty-distance¶

The replacement penalty had no consistent rank relation to the nearest-source context distance across sessions.

In [19]:
sp = table("SBP_geometry_tensor", "replacement_penalty_distance_spearman")
v = sp.replacement_penalty_distance_spearman
print(sp.round(3).to_string())
print(f"positive {int((v > 0).sum())}, negative {int((v < 0).sum())} of {len(v)}; mean {v.mean():.4f}")
by_date = {dt: g.replacement_penalty_distance_spearman.to_numpy() for dt, g in sp.groupby("date")}
for k in (0,) + EXTRA:
    lo, hi = d.date_bootstrap(by_date, np.random.default_rng(claim_seed("replacement-penalty-distance") + k))
    print(f"date-bootstrap 95% interval of the mean (generator +{k}): {lo:.4f} to {hi:.4f}; contains zero: {lo <= 0 <= hi}")
print("reading (a) not all of one sign:", bool((v > 0).any() and (v < 0).any()))
          date task  replacement_penalty_distance_spearman
0   2021-10-15   CO                                 -0.030
1   2021-10-15   RD                                 -0.089
2   2022-02-25   RD                                 -0.031
3   2022-02-25   CO                                 -0.041
4   2022-04-08   CO                                 -0.044
5   2022-04-08   RD                                  0.134
6   2022-04-15   CO                                 -0.016
7   2022-04-15   RD                                  0.045
8   2022-04-29   RD                                 -0.051
9   2022-04-29   CO                                  0.134
10  2022-05-13   RD                                  0.054
11  2022-05-13   CO                                  0.044
12  2022-08-10   CO                                 -0.017
13  2022-08-10   RD                                  0.026
14  2022-09-21   CO                                  0.068
15  2022-09-21   RD                                  0.003
16  2022-11-02   RD                                 -0.069
17  2022-11-02   CO                                 -0.014
positive 8, negative 10 of 18; mean 0.0058
date-bootstrap 95% interval of the mean (generator +0): -0.0204 to 0.0301; contains zero: True
date-bootstrap 95% interval of the mean (generator +1000): -0.0212 to 0.0304; contains zero: True
date-bootstrap 95% interval of the mean (generator +2000): -0.0200 to 0.0303; contains zero: True
date-bootstrap 95% interval of the mean (generator +3000): -0.0211 to 0.0304; contains zero: True
date-bootstrap 95% interval of the mean (generator +4000): -0.0202 to 0.0306; contains zero: True
reading (a) not all of one sign: True

Result: reproduced. The per-session Spearman correlations between nearest-source distance and replacement penalty are positive in 8 and negative in 10 of 18 sessions (reading a), and their mean, 0.0058, has a date-bootstrap interval of -0.0204 to 0.0301 that contains zero (reading b), under all five generators.

replacement-ranks-lower¶

Replacement with the first to fifth nearest sources and with a random same-condition source all lowered the across-session mean gain.

The random source is a uniform draw among the other same-condition test trials (a standard choice, claims file); five draws are shown, from the claim's seed and that seed plus 1000 to 4000.

In [20]:
for sig in ("SBP", "TCR"):
    name = f"{sig}_geometry_tensor"
    correct = table(name).gain.mean()
    ranks = np.array([r[name]["rank_gains"] for r in results]).mean(axis=0)
    rand = np.array([r[name]["random_source_gains"] for r in results]).mean(axis=0)
    print(f"{sig} geometry: correct-pair mean {correct:.5f}; rank 1-5 means {np.round(ranks, 5)}; "
          f"random-source means over five draws {np.round(rand, 5)}")
    print(f"   all six (ranks and the first random draw) below the correct-pair mean: {bool(np.all(ranks < correct) and rand[0] < correct)}; "
          f"every random draw below: {bool(np.all(rand < correct))}")
SBP geometry: correct-pair mean 0.02009; rank 1-5 means [-0.00714 -0.00868 -0.01047 -0.01138 -0.01167]; random-source means over five draws [-0.01428 -0.01382 -0.01393 -0.01409 -0.01433]
   all six (ranks and the first random draw) below the correct-pair mean: True; every random draw below: True
TCR geometry: correct-pair mean 0.01155; rank 1-5 means [-0.00905 -0.01085 -0.01092 -0.0112  -0.01208]; random-source means over five draws [-0.01275 -0.01369 -0.01401 -0.01379 -0.01411]
   all six (ranks and the first random draw) below the correct-pair mean: True; every random draw below: True

Result: reproduced. For SBP the correct-pair mean is 0.02009 and replacement with ranks one to five gives -0.00714 to -0.01167, and random same-condition sources -0.01382 to -0.01433 over five draws, all lower (reading a); for TCR the same holds (0.01155 against -0.00905 to -0.01411).

practical-mse-reduction¶

In LINK, SBP geometry-by-phase gain reduced context-model MSE by 4.92% on average (mean context RMSE 0.01407 to 0.01372), adding measured-output history reduced the remaining MSE by 2.72%, and the TCR reductions were 2.83% and 1.31%.

In [21]:
vals = [("SBP geometry % MSE reduction", table("SBP_geometry_tensor", "mse_reduction_percent").mse_reduction_percent.mean(), 4.92),
        ("SBP geometry mean context RMSE", table("SBP_geometry_tensor", "context_rmse").context_rmse.mean(), 0.01407),
        ("SBP geometry mean correct-pair RMSE", table("SBP_geometry_tensor", "exact_rmse").exact_rmse.mean(), 0.01372),
        ("SBP history % MSE reduction", table("SBP_causal_history", "mse_reduction_percent").mse_reduction_percent.mean(), 2.72),
        ("TCR geometry % MSE reduction", table("TCR_geometry_tensor", "mse_reduction_percent").mse_reduction_percent.mean(), 2.83),
        ("TCR history % MSE reduction", table("TCR_causal_history", "mse_reduction_percent").mse_reduction_percent.mean(), 1.31)]
within = 0
for label, v, e in vals:
    ok = abs(v - e) <= 0.1 * e
    within += ok
    print(f"{label}: {v:.5g} (expected {e} +- {0.1 * e:.4g}; within: {ok})")
print("within tolerance:", within, "of 6")
r = table("SBP_geometry_tensor", "mse_reduction_percent").mse_reduction_percent
print(f"SBP geometry session reductions {r.min():.2f} to {r.max():.2f}%")
SBP geometry % MSE reduction: 4.9186 (expected 4.92 +- 0.492; within: True)
SBP geometry mean context RMSE: 0.01407 (expected 0.01407 +- 0.001407; within: True)
SBP geometry mean correct-pair RMSE: 0.013717 (expected 0.01372 +- 0.001372; within: True)
SBP history % MSE reduction: 2.7214 (expected 2.72 +- 0.272; within: True)
TCR geometry % MSE reduction: 2.8304 (expected 2.83 +- 0.283; within: True)
TCR history % MSE reduction: 1.3144 (expected 1.31 +- 0.131; within: True)
within tolerance: 6 of 6
SBP geometry session reductions 0.61 to 7.99%

Result: reproduced. The mean percentage MSE reductions are 4.92 (SBP geometry), 2.72 (SBP plus history), 2.83 (TCR geometry) and 1.31 (TCR plus history), and the SBP geometry mean RMSE falls from 0.01407 to 0.01372; all six values are within tolerance.

representative-trial¶

The prespecified rule for the illustrative trajectory (session with median primary SBP geometry gain, then the held-out trial with median context-minus-correct trial MSE improvement) selects 2022-09-21 RD, trial 123.

In [22]:
geo = pd.DataFrame([{"date": r["date"], "task": r["task"], "gain": r["SBP_geometry_tensor"]["gain"], "i": i} for i, r in enumerate(results)])
geo = geo.sort_values(["gain", "date", "task"]).reset_index(drop=True)
print(geo.round(5).to_string())
lower = geo.iloc[(len(geo) - 1) // 2]
middle = geo.iloc[[(len(geo) - 1) // 2, len(geo) // 2]].sort_values(["date", "task"]).iloc[0]
for label, row in [("ninth in gain order (code: build_submission_figures.py figure8)", lower), ("earlier date of the two middle sessions", middle)]:
    r = results[int(row.i)]["SBP_geometry_tensor"]
    improvement = r["per_trial_context_mse"] - r["per_trial_exact_mse"]
    order = np.lexsort((r["test_indices"], improvement))
    position = int(order[(len(order) - 1) // 2])
    usable_index = int(r["test_indices"][position])
    # reading (c): the trial's position among the held-out trials in ascending trial order (test_indices
    # itself is in train_test_split's shuffled order, so an index into it is not a position)
    held_out_position = int(np.searchsorted(np.sort(r["test_indices"]), usable_index))
    print(f"{label}: {row.date} {row.task}; median trial: usable-trial index {usable_index}, "
          f"trials-table row {int(r['source_rows'][usable_index])}, position among the {len(order)} held-out trials "
          f"in trial order {held_out_position} (from 0)")
          date task     gain   i
0   2022-02-25   RD  0.00283   2
1   2022-04-29   CO  0.01164   9
2   2022-05-13   RD  0.01262  10
3   2022-05-13   CO  0.01389  11
4   2022-02-25   CO  0.01408   3
5   2022-04-08   CO  0.01409   4
6   2022-04-08   RD  0.01485   5
7   2022-09-21   CO  0.01879  14
8   2022-09-21   RD  0.02067  15
9   2021-10-15   RD  0.02272   1
10  2022-08-10   CO  0.02288  12
11  2021-10-15   CO  0.02304   0
12  2022-11-02   RD  0.02494  16
13  2022-04-15   RD  0.02529   7
14  2022-04-15   CO  0.02688   6
15  2022-11-02   CO  0.02870  17
16  2022-08-10   RD  0.03031  13
17  2022-04-29   RD  0.03347   8
ninth in gain order (code: build_submission_figures.py figure8): 2022-09-21 RD; median trial: usable-trial index 123, trials-table row 123, position among the 113 held-out trials in trial order 41 (from 0)
earlier date of the two middle sessions: 2021-10-15 RD; median trial: usable-trial index 260, trials-table row 260, position among the 113 held-out trials in trial order 77 (from 0)

Result: reproduced. Taking the ninth of the 18 sessions in gain order (the lower middle session, as the release's figure code does) selects 2022-09-21 RD, and its median-improvement held-out trial is trial 123 both as the row of the NWB trials table (reading a) and as the usable-trial index (reading b), which coincide because no trial is dropped. Under reading (c), its position among the 113 held-out trials in trial order is 41 counting from 0 (the 42nd), not 123. The other reading of the session tie (the earlier date of the two middle sessions) selects 2021-10-15 RD, trial 260, so the match rests on the first reading of the tie rule.

split-seed-stability¶

The fully nested SBP geometry-by-phase result was stable across three whole-trial split and refitting seeds, with CO means 0.0193, 0.0180 and 0.0158 and RD means 0.0209, 0.0223 and 0.0201.

In [23]:
exp = {20260726: (0.0193, 0.0209), 20260727: (0.0180, 0.0223), 20260728: (0.0158, 0.0201)}
within, positive = 0, True
for seed in d.SPLIT_SEEDS:
    name = "SBP_geometry_tensor" if seed == SEED else f"SBP_geometry_tensor_{seed}"
    m = task_means(name)
    for task, e in zip(("CO", "RD"), exp[seed]):
        ok = abs(m[task] - e) <= 0.1 * e
        within += ok
        positive &= m[task] > 0
        print(f"seed {seed} {task}: {m[task]:.4f} (expected {e} +- {0.1 * e:.5f}; within: {ok})")
print("all six positive:", bool(positive), "; within tolerance:", within, "of 6")
seed 20260726 CO: 0.0193 (expected 0.0193 +- 0.00193; within: True)
seed 20260726 RD: 0.0209 (expected 0.0209 +- 0.00209; within: True)
seed 20260727 CO: 0.0180 (expected 0.018 +- 0.00180; within: True)
seed 20260727 RD: 0.0223 (expected 0.0223 +- 0.00223; within: True)
seed 20260728 CO: 0.0158 (expected 0.0158 +- 0.00158; within: True)
seed 20260728 RD: 0.0201 (expected 0.0201 +- 0.00201; within: True)
all six positive: True ; within tolerance: 6 of 6

Result: reproduced. Under split seeds 20260726, 20260727 and 20260728 the CO means are 0.0193, 0.0180 and 0.0158 and the RD means 0.0209, 0.0223 and 0.0201, equal to the paper's six values and all positive.

rff-link¶

In LINK SBP, nonlinear-neural geometry-by-phase means were positive for both tasks under every map (combined range 0.00310 to 0.00404), and the measured-output-history mean ranged from 0.00111 to 0.00142.

In [24]:
rows_ = []
for seed in d.RFF_SEEDS:
    for context in ("geometry_tensor", "causal_history"):
        t = pd.DataFrame([{"task": r["task"], "gain": r[f"SBP_{context}"]["rff"][seed]["gain"]} for r in results])
        rows_.append(dict(map_seed=seed, context=d.LADDER_NAMES[context], CO=t[t.task == "CO"].gain.mean(),
                          RD=t[t.task == "RD"].gain.mean(), all18=t.gain.mean(), positive=int((t.gain > 0).sum())))
rff = pd.DataFrame(rows_)
print(rff.to_string(float_format=lambda v: f"{v:.5f}"))
geo_ = rff[rff.context == "geometry by phase"]
his_ = rff[rff.context == "plus measured-output history"]
lo_g, hi_g = 0.0031 - 0.00031, 0.00404 + 0.000404
lo_h, hi_h = 0.00111 - 0.000111, 0.00142 + 0.000142
print(f"geometry CO and RD positive under every map: {bool((geo_[['CO', 'RD']] > 0).all().all())}")
print(f"reading (a), 18-session geometry means {geo_.all18.min():.5f} to {geo_.all18.max():.5f}, inside {lo_g:.5f}..{hi_g:.5f}: {bool(geo_.all18.between(lo_g, hi_g).all())}")
six = np.r_[geo_.CO, geo_.RD]
print(f"reading (b), six task means {six.min():.5f} to {six.max():.5f}, inside: {bool(np.all((six >= lo_g) & (six <= hi_g)))}")
print(f"history 18-session means {his_.all18.min():.5f} to {his_.all18.max():.5f}, inside {lo_h:.6f}..{hi_h:.6f}: {bool(his_.all18.between(lo_h, hi_h).all())}")
print("RFF penalties chosen (geometry):", collections.Counter(r["SBP_geometry_tensor"]["rff"][s]["alpha"] for r in results for s in d.RFF_SEEDS))
print(f"notebook run time {(time.time() - T0) / 60:.1f} min; peak memory of this process {resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1e6:.2f} GB")
   map_seed                       context      CO      RD   all18  positive
0  20260802             geometry by phase 0.00401 0.00320 0.00361        16
1  20260802  plus measured-output history 0.00116 0.00107 0.00111        18
2  20260803             geometry by phase 0.00391 0.00417 0.00404        17
3  20260803  plus measured-output history 0.00116 0.00168 0.00142        18
4  20260804             geometry by phase 0.00351 0.00269 0.00310        17
5  20260804  plus measured-output history 0.00133 0.00109 0.00121        18
geometry CO and RD positive under every map: True
reading (a), 18-session geometry means 0.00310 to 0.00404, inside 0.00279..0.00444: True
reading (b), six task means 0.00269 to 0.00417, inside: False
history 18-session means 0.00111 to 0.00142, inside 0.000999..0.001562: True
RFF penalties chosen (geometry): Counter({10000.0: 41, 100000.0: 13})
notebook run time 23.2 min; peak memory of this process 0.68 GB

Result: reproduced. With the three nonlinear-neural maps, the CO and RD geometry-by-phase means are positive under every map (0.00269 to 0.00417). Under reading (a) the 18-session geometry means span 0.00310 to 0.00404 and the history means 0.00111 to 0.00142, equal to the paper's ranges. Reading (b), the six task means, does not hold: the lowest, 0.00269, is below the widened bound of 0.00279.

Summary¶

Claim Outcome
link-development-sample reproduced
link-neural-only-r2 reproduced
link-context-ladder-gain reproduced
link-context-only-r2 reproduced
link-phase-only-replacement reproduced
link-task-contrast-by-context reproduced
nested-geometry-gain reproduced
nested-history-gain reproduced
nested-replacement-negative reproduced (seed sensitive)
replacement-source-diagnostics reproduced
permutation-negative reproduced
replacement-penalty-distance reproduced
replacement-ranks-lower reproduced
practical-mse-reduction reproduced
representative-trial reproduced (on one reading of the session tie rule)
split-seed-stability reproduced
rff-link reproduced (reading a)

How the analysis differs from the paper's: the estimators are ports of the paper's released code (commit b042fbe) and read the NWB files by streaming them; the bootstrap intervals use generators seeded from the claims, not the release's seed 20260802; the seed sensitivity of the protocol was run for the SBP geometry-by-phase and plus-history fits and the neural-only R2, not for the other ladder rungs or for TCR.

What was found about the dataset: the 18 development sessions are as the paper describes (nine dates, 375 usable trials each, one subject); no session is deposited twice; SBP, TCR, position and velocity share one 20 ms clock (velocity decoding from SBP peaks at lag 0 in 16 sessions and 2 bins in 2); the released velocity is the forward first difference of the released position (velocity[t] = position[t+1] - position[t]: correlation 1.000 and SD ratio 1.00 for both components in 17 sessions, and 1.000 and 0.987 in 2021-10-15 CO, the session with the timestamp gap), which the files do not state; the threshold-crossing series is labelled in volts though it holds integer counts (0 to 11 per bin). One session (2021-10-15 CO) has a gap of 1094 ms in its 20 ms timestamps.