Temmar et al. (2025), LINK: LSTM decoding in July to November 2022 (fig2a-irregular-shifts)¶

Paper: doi:10.52202/085713-4642. Dataset: DANDI:001201, version 0.261026.1912, streamed (see signals.ipynb). Claims file: claims/temmar-2025.yaml. Code read: github.com/chesteklab/LINK_dataset at 5e1c36a.

Claim Tested here
fig2a-irregular-shifts the LSTM part, on more sessions in the window (added after round 2 of the verification)

decoding.ipynb tests both parts of fig2a-irregular-shifts, but has an LSTM on only 3 of the 45 sessions in July to November 2022. The verifier asked for more. An LSTM on all 42 other window sessions is 11 rounds of four fits, 14 to 41 minutes at the 77 to 223 s per fit seen in this attempt's runs; at round 2's times (207 to 223 s per fit) it would have taken that notebook (48 minutes then) over the 60-minute limit. This notebook therefore runs the LSTM part on its own. It refits the 20 every-16th sessions of decoding.ipynb, the criterion's sample of all sessions (same training, seed 42, one thread per fit), and fits 24 of the 42 other window sessions, spread evenly over them in date order and chosen by that rule before any result was seen: 44 fits, 11 rounds of four. Ridge regression is fit on the same sessions for the LSTM's margin over it.

In [1]:
import os, time, resource
import numpy as np
import pandas as pd
import multiprocessing as mp
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
import link

T0 = time.time()
ITERS = int(os.environ.get("LINK_DEV_ITERS", link.LSTM_ITERS))   # 2000 (paper); lowered only while developing
N_WIN = int(os.environ.get("LINK_DEV_NWIN", "24"))                # window sessions fitted (see above)
LSTM_EVERY = 16                                                    # as decoding.ipynb
W0, W1 = pd.Timestamp("2022-07-01"), pd.Timestamp("2022-11-30")
A = link.assets()
REF_IDX = [i for i in range(len(A)) if i % LSTM_EVERY == 0]
WIN_ALL = [i for i in range(len(A)) if W0 <= A["date"][i] <= W1 and i % LSTM_EVERY != 0]
WIN_IDX = [WIN_ALL[j] for j in np.linspace(0, len(WIN_ALL) - 1, N_WIN).round().astype(int)]
WIN_REF = [i for i in REF_IDX if W0 <= A["date"][i] <= W1]
print(f"{len(A)} sessions; every-16th {len(REF_IDX)} (of them in the window {len(WIN_REF)}); "
      f"other window sessions {len(WIN_ALL)}, fitted here {len(WIN_IDX)}; LSTM iterations {ITERS}")
312 sessions; every-16th 20 (of them in the window 3); other window sessions 42, fitted here 24; LSTM iterations 2000

Load¶

As decoding.ipynb: the first 300 trials train and the remaining 75 test (Appendix C.1); SBP is z-scored per channel on the training bins.

In [2]:
def load(i):
    s = link.read_session(A["asset_id"][i], tcr=False)
    (xtr, ytr), (xte, yte) = link.split(s)
    mu, sd = link.zparams(xtr)
    xtr_z = ((xtr - mu) / sd).astype(np.float32)
    rr = link.rr_fit(xtr_z, ytr)
    return i, {"i": i, "date": A["date"][i], "style": s["style"], "xtr_z": xtr_z, "ytr": ytr,
               "xte_z": ((xte - mu) / sd).astype(np.float32), "yte": yte, "rr": rr,
               "n_test_trials": len(s["trials"]) - link.N_TRAIN_TRIALS, "xte_min": xte.min(), "xte_max": xte.max()}


t = time.time()
with ThreadPoolExecutor(4) as ex:
    SES = dict(ex.map(load, sorted(set(REF_IDX) | set(WIN_IDX))))
print(f"loaded and fit RR on {len(SES)} sessions in {time.time() - t:.0f} s; "
      f"peak memory {resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1e6:.2f} GB")
loaded and fit RR on 44 sessions in 72 s; peak memory 1.35 GB
In [3]:
LD = pd.DataFrame([{"date": s["date"], "style": s["style"], "n_test_trials": s["n_test_trials"]} for s in SES.values()])
print("sessions by style:", LD["style"].value_counts().to_dict(), "| by year:", LD["date"].dt.year.value_counts().sort_index().to_dict())
print("test trials per session:", LD["n_test_trials"].value_counts().to_dict())
print("hold-out SBP (stored units, microvolts): %.3f to %.3f" % (min(s["xte_min"] for s in SES.values()), max(s["xte_max"] for s in SES.values())))
yk = np.vstack([s["yte"] for s in SES.values()])
for n, a, b in zip(link.KIN_NAMES, yk.min(0), yk.max(0)):
    print(f"  hold-out {n}: {a:.3f} to {b:.3f}")
print("window sessions fitted:", [A["date"][i].date().isoformat() for i in sorted(WIN_REF + WIN_IDX)])
sessions by style: {'CO': 23, 'RD': 21} | by year: {2020: 3, 2021: 7, 2022: 31, 2023: 3}
test trials per session: {75: 44}
hold-out SBP (stored units, microvolts): 0.550 to 121.472
  hold-out idx_pos: 0.000 to 1.000
  hold-out mrs_pos: 0.000 to 1.000
  hold-out idx_vel: -0.286 to 0.415
  hold-out mrs_vel: -0.225 to 0.262
window sessions fitted: ['2022-07-18', '2022-07-22', '2022-07-25', '2022-07-29', '2022-08-01', '2022-08-08', '2022-08-10', '2022-08-17', '2022-08-18', '2022-08-22', '2022-08-26', '2022-08-31', '2022-09-01', '2022-09-06', '2022-09-07', '2022-09-12', '2022-09-19', '2022-09-21', '2022-09-26', '2022-09-27', '2022-10-03', '2022-10-10', '2022-10-25', '2022-11-01', '2022-11-02', '2022-11-04', '2022-11-09']

Train the LSTMs¶

The training of decoding.ipynb (Appendix C.1), scored on each session's own hold-out.

In [4]:
def task(i):
    t0 = time.time()
    s = SES[i]
    state, onorm = link.lstm_train([(s["xtr_z"], s["ytr"])], seed=42, iters=ITERS)
    fit_s = time.time() - t0
    return {"i": i, "fit_s": fit_s, "r2": link.r2_per_output(s["yte"], link.lstm_predict(state, onorm, s["xte_z"]))}


t = time.time()
with ProcessPoolExecutor(4, mp_context=mp.get_context("fork")) as ex:
    RES = list(ex.map(task, REF_IDX + WIN_IDX))
fits = np.array([r["fit_s"] for r in RES])
print(f"{len(RES)} LSTMs in {(time.time() - t) / 60:.1f} min; seconds per fit {fits.min():.0f} to {fits.max():.0f} (median {np.median(fits):.0f})")
44 LSTMs in 35.3 min; seconds per fit 181 to 202 (median 189)

fig2a-irregular-shifts, LSTM part¶

Groups of channels show irregular SBP shifts in some periods, for example from about July to November 2022, and these shifts did not affect overall decoding performance.

The criterion's LSTM part: the median same-day LSTM R2 of the window sessions lies within the 10th to 90th percentile range of all sessions' values, here the 20 every-16th sessions as in decoding.ipynb.

In [5]:
R = pd.DataFrame([{"i": r["i"], "date": SES[r["i"]]["date"], "lstm": r["r2"].mean(),
                   "rr": link.r2_per_output(SES[r["i"]]["yte"], link.rr_predict(SES[r["i"]]["rr"], SES[r["i"]]["xte_z"])).mean()}
                  for r in RES])
R["ref"] = R["i"].isin(REF_IDX)
R["window"] = R["date"].between(W0, W1)
ref = R[R["ref"]]
lo, hi = np.percentile(ref["lstm"], [10, 90])
print(f"every-16th sessions (n = {len(ref)}): LSTM R2 median {ref['lstm'].median():.3f}, range {ref['lstm'].min():.3f} to "
      f"{ref['lstm'].max():.3f}; 10th to 90th percentile {lo:.3f} to {hi:.3f}")
win = R[R["window"]]
med = win["lstm"].median()
print(f"window sessions with an LSTM: {len(win)} of {len(WIN_ALL) + len(WIN_REF)}; LSTM R2 median {med:.3f}, "
      f"range {win['lstm'].min():.3f} to {win['lstm'].max():.3f}; within the 10th to 90th percentile range: {lo <= med <= hi}")
for lab, d in (("window sessions among the every-16th", win[win["ref"]]), ("window sessions fitted here only", win[~win["ref"]])):
    print(f"  {lab}: n = {len(d)}, median {d['lstm'].median():.3f}")
print(f"  window sessions above the 90th percentile: {(win['lstm'] > hi).sum()}, below the 10th: {(win['lstm'] < lo).sum()}")
lo2, hi2 = np.percentile(R["lstm"], [10, 90])
print(f"variant, percentiles over every session fitted here (n = {len(R)}, {len(win)} of them in the window): {lo2:.3f} to {hi2:.3f}; "
      f"window median within: {lo2 <= med <= hi2}")
out = R[R["ref"] & ~R["window"]]
lo3, hi3 = np.percentile(out["lstm"], [10, 90])
print(f"variant, percentiles over the every-16th sessions outside the window (n = {len(out)}): {lo3:.3f} to {hi3:.3f}; "
      f"window median within: {lo3 <= med <= hi3}")
print(f"LSTM minus RR: median {(win['lstm'] - win['rr']).median():.3f} in the window, {(ref['lstm'] - ref['rr']).median():.3f} over the every-16th sessions")
print(f"RR R2 of these window sessions: median {win['rr'].median():.3f}")
every-16th sessions (n = 20): LSTM R2 median 0.591, range 0.514 to 0.666; 10th to 90th percentile 0.529 to 0.651
window sessions with an LSTM: 27 of 45; LSTM R2 median 0.641, range 0.500 to 0.739; within the 10th to 90th percentile range: True
  window sessions among the every-16th: n = 3, median 0.652
  window sessions fitted here only: n = 24, median 0.639
  window sessions above the 90th percentile: 11, below the 10th: 1
variant, percentiles over every session fitted here (n = 44, 27 of them in the window): 0.541 to 0.665; window median within: True
variant, percentiles over the every-16th sessions outside the window (n = 17): 0.524 to 0.616; window median within: False
LSTM minus RR: median 0.303 in the window, 0.301 over the every-16th sessions
RR R2 of these window sessions: median 0.330

Result: reproduced. The LSTM part holds on 27 of the 45 window sessions, so with decoding.ipynb both parts of the criterion hold. The 20 every-16th sessions, refit here, give the same summary of LSTM R2 as in decoding.ipynb (median 0.591, 10th to 90th percentile 0.529 to 0.651); the values of single sessions are not printed side by side. The median over the 27 window sessions with an LSTM (24 fitted here and the 3 among the every-16th) is 0.641, inside that range; over the 24 alone it is 0.639. The window decodes a little better than the dataset as a whole: 11 of the 27 are above the 90th percentile and 1 below the 10th, and against the 17 every-16th sessions outside the window (0.524 to 0.616) the median would be above the range. With the percentiles over all 44 sessions fitted here (0.541 to 0.665) it is inside. The LSTM's margin over RR is the same in the window (median 0.303) as over the every-16th sessions (0.301). The shift part and the RR part hold in decoding.ipynb. The pass is narrow: the median is 0.010 below a 90th percentile estimated from 20 sessions, and 18 window sessions are unfitted. The outcome was partially reproduced after round 2, and the third verification round agreed with the change to reproduced.

Summary¶

Claim Outcome
fig2a-irregular-shifts reproduced (with the shift and RR parts from decoding.ipynb)

How the analysis differs from the paper's: the LSTM is trained on 24 of the 42 window sessions outside the every-16th, for time, and the reference distribution is the 20 every-16th sessions; the paper gives no measure of "did not affect", and the criterion's rule is used.

What was found about the dataset: same-day LSTM decoding in July to November 2022 is at or slightly above its level over the dataset.

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