Reproducing Peterson et al. (2021) from dandiset 000055¶

Paper. Peterson SM, Singh SH, Wang NXR, Rao RPN, Brunton BW (2021). Behavioral and neural variability of naturalistic arm movements. eNeuro 8(3), ENEURO.0007-21.2021. doi:10.1523/ENEURO.0007-21.2021. The claims file was written from the version of record in Europe PMC (PMC8225404): main text, Methods, legends, Tables 1 and 2 and the legends of the Extended Data figures.

Dataset. DANDI:000055 (AJILE12), version 0.220127.0436. The paper cites no DANDI version: its data statement points to the curated epochs on Figshare, and the dandiset was published later. This is the only published version, and the draft lists the same 55 files with the same total size, so the published version is pinned. The files are streamed; nothing is downloaded.

What the dataset holds. 12 subjects and 55 subject-days of preprocessed ECoG (500 Hz), pose of nine key points (30 frames per second), 8088 contralateral wrist movement events with the paper's ten features, coarse behaviour labels, and an electrode table with MNI positions, a good flag and the paper's regression R2 per electrode. Sex and age are not in it.

Outside input. The projection of electrodes onto the eight AAL regions is the paper's own output on Figshare (doi:10.6084/m9.figshare.12114408.v1), used for the region claims (data: with_inputs) and checked by the link claim roi-projection-link.

Event sets. Reading a is every event in the files. Reading b drops ECoG segments with missing samples, with power below 0 dB or with 115-125 Hz power more than 3 SD above the subject's segments (Methods); the summary of segment power these tests use is an assumption (helper docstring). The false positives the paper removed are not marked in the files, so they cannot be dropped.

Claim Tested here
subject-days, roi-projection-link (link claims) tested
cohort, fig2-event-counts, fig2-features-differ-across-subjects, fig2-reach-shape, fig2-bimanual-skew tested
extfig2-1c-contralateral-larger, extfig2-2-feature-correlations, fig2-days-and-waking tested
fig3-group-lfb-decrease-hfb-increase, fig3-sensorimotor-largest, fig3-lfb-more-widespread tested (the last blocked: its readings disagree)
fig4-precentral-subject-variability, fig5-band-power-differs-across-subjects, table1-subject-band-power-ci tested
fig5-recording-day-effects, extfig5-1-baseline-reduces-day-variability, discussion-day-changes-small tested
fig6b-best-models-sensorimotor, fig6-r2-at-most-025, fig6c-angle-and-day-most-informative, extfig6-2-angle-most-retained, fig6d-upward-reaches-enhance-pattern, fig6d-angle-and-day-largest-coefficients tested

The notebook reads about 8000 ECoG segments of 10 s from 55 files of 8 to 20 GB each; that step took 20 to 35 minutes in recent runs (the time is printed below). The regression models take a few minutes.

In [1]:
import os
import time
import warnings

os.environ["OMP_NUM_THREADS"] = "1"
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from scipy import stats

import ajile

pd.set_option("display.width", 220)
pd.set_option("display.max_columns", 40)
pd.set_option("display.max_rows", 300)
warnings.filterwarnings("ignore", category=RuntimeWarning)
SUBJECTS = [f"{i:02d}" for i in range(1, 13)]
In [2]:
started = time.time()
assets = ajile.list_assets()
sessions = ajile.load_sessions(assets)
# LOAD-BEH-END
print(f"{len(sessions)} files of dandiset {ajile.DANDISET_ID} version {ajile.DANDISET_VERSION}, "
      f"{assets.size_gb.sum():.0f} GB in all; metadata, events and wrist traces read in "
      f"{time.time() - started:.0f} s")
55 files of dandiset 000055 version 0.220127.0436, 846 GB in all; metadata, events and wrist traces read in 26 s
In [3]:
# One table of events. Time of day from the midnight clock of the files (see the helper).
rows = []
for s in sessions:
    e = s["events"].copy()
    e["subject"], e["day"], e["k"] = s["subject"], s["day"], np.arange(len(e))
    rows.append(e)
ev = pd.concat(rows, ignore_index=True)
ev = ev.rename(columns={"Reach_magnitude_px": "magnitude", "Reach_angle_degrees": "angle_file",
                        "Onset_speed_px_per_sec": "speed", "Speech_ratio": "speech",
                        "Bimanual_ratio": "bimanual_ratio", "Bimanual_overlap": "bimanual_overlap",
                        "Bimanual_class": "bimanual_class"})
# The files' angle is atan2(dy, dx) in image coordinates (checked below); the paper's angle
# negates it (y up) and folds 90-270 degrees onto 90 to -90 (Methods; code).
ev["angle"] = ajile.fold_angle(-ev["angle_file"])
ev["hour"] = ev["start_time"] / 3600.0
ev["tod_bin"] = np.clip((ev["hour"] // 8).astype(int), 0, 2)
FEATURES = ["day", "hour", "duration", "magnitude", "angle", "speed", "speech",
            "bimanual_ratio", "bimanual_overlap", "bimanual_class"]
print(len(ev), "events")
8088 events

Data check¶

Counts by subject and day, units and ranges of every variable used, and the clocks of the data streams. Each check of the metadata against the data is stated under its output.

In [4]:
info = pd.DataFrame([{
    "subject": s["subject"], "day": s["day"], "subject_id": s["subject_id"], "session_id": s["session_id"],
    "session_start_time": s["session_start_time"], "electrodes": len(s["electrodes"]),
    "good": int(s["electrodes"]["good"].sum()), "events": len(s["events"]), "wrist": s["reach_event_desc"],
    "ecog_hours": round(s["ecog_shape"][0] / s["ecog_rate"] / 3600, 2), "ecog_Hz": s["ecog_rate"],
    "pose_hours": round(s["pose_shape"][0] / s["pose_rate"] / 3600, 2), "pose_Hz": s["pose_rate"],
    "first_event_h": round(s["events"].start_time.min() / 3600, 2),
    "last_event_h": round(s["events"].start_time.max() / 3600, 2)} for s in sessions])
print(info.to_string(index=False))
print("\nSubjects:", info.subject.nunique(), "; files:", len(info), "; events:", int(info.events.sum()))
print("subject_id and session_id agree with the file names:",
      bool((info.subject_id == info.subject).all() and (info.session_id.astype(int) == info.day).all()))
print("Subject fields in the files:", sorted({tuple(s["subject_fields"]) for s in sessions}))
print("ECoG unit and conversion:", {(s["ecog_unit"], s["ecog_conversion"]) for s in sessions},
      "; pose unit:", {s["pose_unit"] for s in sessions})
LOC = ["x", "y", "z", "group_name", "low_freq_R2", "high_freq_R2"]
print("Electrode positions, groups and stored R2 identical across a subject's files:",
      all(sessions[i]["electrodes"][LOC].equals(sessions[j]["electrodes"][LOC])
          for i in range(len(sessions)) for j in range(len(sessions))
          if sessions[i]["subject"] == sessions[j]["subject"]))
print("Good flags differ between a subject's files:",
      sorted({s["subject"] for s in sessions for t in sessions
              if s["subject"] == t["subject"] and not np.array_equal(s["electrodes"].good.values, t["electrodes"].good.values)}))
subject  day subject_id session_id               session_start_time  electrodes  good  events   wrist  ecog_hours  ecog_Hz  pose_hours  pose_Hz  first_event_h  last_event_h
     01    3         01          3        2000-01-02T19:00:00-05:00          94    85     156 r_wrist       24.00    500.0        24.0     30.0           0.50         21.04
     01    4         01          4        2000-01-03T19:00:00-05:00          94    91     196 r_wrist       24.00    500.0        24.0     30.0           0.43         23.55
     01    5         01          5        2000-01-04T19:00:00-05:00          94    91     199 r_wrist       24.00    500.0        24.0     30.0           0.55         22.28
     01    7         01          7 2000-01-07T03:31:22.414000-05:00          94    91     190 r_wrist       15.48    500.0        24.0     30.0           8.98         23.83
     02    3         02          3        2000-01-02T19:00:00-05:00          86    85      51 l_wrist       24.00    500.0        24.0     30.0           6.01         22.00
     02    4         02          4        2000-01-03T19:00:00-05:00          86    85      94 l_wrist       24.00    500.0        24.0     30.0           0.10         23.75
     02    5         02          5        2000-01-04T19:00:00-05:00          86    81      82 l_wrist       24.00    500.0        24.0     30.0           0.50         22.35
     02    6         02          6        2000-01-05T19:00:00-05:00          86    80      78 l_wrist       24.00    500.0        24.0     30.0           1.39         20.04
     03    3         03          3        2000-01-02T19:00:00-05:00          96    79     198 r_wrist       24.00    500.0        24.0     30.0           0.10         23.78
     03    4         03          4        2000-01-03T19:00:00-05:00          96    71     193 r_wrist       24.00    500.0        24.0     30.0           0.67         24.00
     03    5         03          5        2000-01-04T19:00:00-05:00          96    76     137 r_wrist       24.00    500.0        24.0     30.0           0.04          8.10
     03    6         03          6        2000-01-05T19:00:00-05:00          96    79     114 r_wrist       24.00    500.0        24.0     30.0           8.54         22.62
     04    3         04          3 2000-01-03T03:20:48.322000-05:00          84    67      35 l_wrist       15.65    500.0        24.0     30.0          13.70         23.98
     04    4         04          4        2000-01-03T19:00:00-05:00          84    80      98 l_wrist       24.00    500.0        24.0     30.0           0.07         23.92
     04    5         04          5        2000-01-04T19:00:00-05:00          84    81      43 l_wrist       24.00    500.0        24.0     30.0           0.24         22.13
     04    6         04          6        2000-01-05T19:00:00-05:00          84    82      82 l_wrist       24.00    500.0        24.0     30.0           5.34         23.51
     04    7         04          7        2000-01-06T19:00:00-05:00          84    77     159 l_wrist       24.00    500.0        24.0     30.0           0.45         23.80
     05    3         05          3        2000-01-02T19:00:00-05:00         106   104      56 l_wrist       24.00    500.0        24.0     30.0           0.07         20.34
     05    4         05          4        2000-01-03T19:00:00-05:00         106   104      48 l_wrist       24.00    500.0        24.0     30.0           0.25         20.36
     05    7         05          7        2000-01-06T19:00:00-05:00         106   100     163 l_wrist       24.00    500.0        24.0     30.0           0.22         23.53
     06    3         06          3 2000-01-03T03:07:20.566000-05:00          80    70     166 r_wrist       15.88    500.0        24.0     30.0           8.27         22.12
     06    4         06          4        2000-01-03T19:00:00-05:00          80    70     199 r_wrist       24.00    500.0        24.0     30.0           5.72         23.95
     06    5         06          5        2000-01-04T19:00:00-05:00          80    76     193 r_wrist       24.00    500.0        24.0     30.0           0.06         23.99
     06    6         06          6        2000-01-05T19:00:00-05:00          80    74     198 r_wrist       24.00    500.0        24.0     30.0           0.55         20.95
     06    7         06          7        2000-01-06T19:00:00-05:00          80    79     200 r_wrist       24.00    500.0        24.0     30.0           5.13         23.99
     07    3         07          3        2000-01-02T19:00:00-05:00          64    63      93 l_wrist       24.00    500.0        24.0     30.0           0.06         23.73
     07    4         07          4        2000-01-03T19:00:00-05:00          64    63     112 l_wrist       24.00    500.0        24.0     30.0           0.18         23.50
     07    5         07          5        2000-01-04T19:00:00-05:00          64    63     199 l_wrist       24.00    500.0        24.0     30.0           4.04         22.51
     07    6         07          6        2000-01-05T19:00:00-05:00          64    63     197 l_wrist       24.00    500.0        24.0     30.0           0.59         22.81
     07    7         07          7        2000-01-06T19:00:00-05:00          64    61     199 l_wrist       24.00    500.0        24.0     30.0           1.21         23.94
     08    3         08          3        2000-01-02T19:00:00-05:00          92    83     197 l_wrist       24.00    500.0        24.0     30.0           0.19         23.62
     08    4         08          4        2000-01-03T19:00:00-05:00          92    82     197 l_wrist       24.00    500.0        24.0     30.0           0.43         24.01
     08    5         08          5        2000-01-04T19:00:00-05:00          92    87     173 l_wrist       24.00    500.0        24.0     30.0           7.15         21.21
     08    6         08          6        2000-01-05T19:00:00-05:00          92    82     198 l_wrist       24.00    500.0        24.0     30.0           0.70         23.00
     08    7         08          7        2000-01-06T19:00:00-05:00          92    85     200 l_wrist       24.00    500.0        24.0     30.0           4.69         23.76
     09    3         09          3        2000-01-02T19:00:00-05:00         126   124      15 r_wrist       24.00    500.0        24.0     30.0           6.69         21.10
     09    4         09          4        2000-01-03T19:00:00-05:00         126   123      18 r_wrist       24.00    500.0        24.0     30.0           5.85         19.31
     09    5         09          5        2000-01-04T19:00:00-05:00         126   116     109 r_wrist       24.00    500.0        24.0     30.0           7.38         22.40
     09    6         09          6        2000-01-05T19:00:00-05:00         126   121      38 r_wrist       24.00    500.0        24.0     30.0           6.20         22.70
     09    7         09          7        2000-01-06T19:00:00-05:00         126   106      31 r_wrist       24.00    500.0        24.0     30.0           4.96         21.39
     10    3         10          3        2000-01-02T19:00:00-05:00         126   121     184 r_wrist       24.00    500.0        24.0     30.0           2.76         23.89
     10    4         10          4        2000-01-03T19:00:00-05:00         126   121     154 r_wrist       24.00    500.0        24.0     30.0           0.83         22.28
     10    5         10          5        2000-01-04T19:00:00-05:00         126   117     112 r_wrist       24.00    500.0        24.0     30.0           2.81         23.80
     10    6         10          6        2000-01-05T19:00:00-05:00         126   121     157 r_wrist       24.00    500.0        24.0     30.0           2.59         22.18
     10    7         10          7        2000-01-06T19:00:00-05:00         126   106     199 r_wrist       24.00    500.0        24.0     30.0           1.88         23.90
     11    3         11          3        2000-01-02T19:00:00-05:00         106   103     199 r_wrist       24.00    500.0        24.0     30.0           0.62         23.08
     11    4         11          4        2000-01-03T19:00:00-05:00         106   103     194 r_wrist       24.00    500.0        24.0     30.0           0.72         21.36
     11    5         11          5        2000-01-04T19:00:00-05:00         106   105     195 r_wrist       24.00    500.0        24.0     30.0           0.51         23.63
     11    6         11          6        2000-01-05T19:00:00-05:00         106   105     198 r_wrist       24.00    500.0        24.0     30.0           0.05         21.93
     11    7         11          7        2000-01-06T19:00:00-05:00         106   105     196 r_wrist       24.00    500.0        24.0     30.0           1.08         22.07
     12    3         12          3        2000-01-02T19:00:00-05:00         124   112     200 r_wrist       24.00    500.0        24.0     30.0           3.53         20.79
     12    4         12          4        2000-01-03T19:00:00-05:00         124   115     200 r_wrist       24.00    500.0        24.0     30.0           4.94         23.80
     12    5         12          5        2000-01-04T19:00:00-05:00         124   113     200 r_wrist       24.00    500.0        24.0     30.0           2.09         22.40
     12    6         12          6        2000-01-05T19:00:00-05:00         124   113     197 r_wrist       24.00    500.0        24.0     30.0           1.06         23.11
     12    7         12          7        2000-01-06T19:00:00-05:00         124   111     199 r_wrist       24.00    500.0        24.0     30.0           2.57         21.77

Subjects: 12 ; files: 55 ; events: 8088
subject_id and session_id agree with the file names: True
Subject fields in the files: [('species', 'subject_id')]
ECoG unit and conversion: {('volts', 1e-06)} ; pose unit: {'meters'}
Electrode positions, groups and stored R2 identical across a subject's files: True
Good flags differ between a subject's files: ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12']
In [5]:
# Columns of the reaches table in every file: is any event marked as a false positive or verified?
rc = pd.Series({f"S{s['subject']} day {s['day']}": ", ".join(s["reach_columns"]) for s in sessions})
for cols_, files in rc.groupby(rc).groups.items():
    print(f"{len(files)} files: {cols_}")
print("Any column naming false positives, verification or removal:",
      [c for s in sessions for c in s["reach_columns"] if any(w in c.lower() for w in ["false", "verif", "remov", "valid", "fp"])])
55 files: start_time, stop_time, Reach_magnitude_px, Reach_angle_degrees, Onset_speed_px_per_sec, Speech_ratio, Bimanual_ratio, Bimanual_overlap, Bimanual_class
Any column naming false positives, verification or removal: []
In [6]:
# Electrode groups and their descriptions in each subject's first file, beside the data
# descriptor's Table 2 (Peterson et al. 2022, Sci Data 9:184, doi:10.1038/s41597-022-01280-y,
# "Surface electrodes: # good/total", "Depth electrodes: # good/total"; totals given here).
DESC_T2 = {"01": (86, 8), "02": (70, 16), "03": (80, 16), "04": (84, 0), "05": (106, 0), "06": (80, 0),
           "07": (64, 0), "08": (92, 0), "09": (98, 28), "10": (86, 40), "11": (106, 0), "12": (92, 32)}
for sub in SUBJECTS:
    s = [x for x in sessions if x["subject"] == sub][0]
    n = s["electrodes"].group_name.value_counts()
    print(f"S{sub} ({len(s['electrodes'])} electrodes; descriptor {DESC_T2[sub][0]} surface + {DESC_T2[sub][1]} depth): "
          + "; ".join(f"{g} {int(n.get(g, 0))} '{d}'" for g, d in s["group_desc"].items()))
S01 (94 electrodes; descriptor 86 surface + 8 depth): ECG 0 'electrocardiogram'; EOG 0 'electrooculogram'; GRID 64 'ECoG grid'; LAT 6 'left anterior temporal'; LID 8 'left insular depth'; LMT 4 'left medial temporal'; LPT 6 'left posterior temporal'; LTO 6 'left temporal occipital'
S02 (86 electrodes; descriptor 70 surface + 16 depth): GRID 64 'ECoG grid'; RDA 8 'right depth anterior'; RDP 8 'right depth posterior'; RST 6 'right temporal'
S03 (96 electrodes; descriptor 80 surface + 16 depth): GRID 64 'ECoG grid'; LAD 8 'left anterior depth'; LAT 8 'left anterior temporal'; LMT 8 'left medial temporal'; LPD 8 'left posterior depth'
S04 (84 electrodes; descriptor 84 surface + 0 depth): GRID 64 'ECoG grid'; RAT 6 'right anterior temporal'; RMT 6 'right medial temporal'; RPT 8 'right posterior temporal'
S05 (106 electrodes; descriptor 106 surface + 0 depth): GRID 64 'ECoG grid'; RAT 6 'right anterior temporal'; RF 16 'right frontal'; RMT 6 'right medial temporal'; RPT 8 'right posterior temporal'; RTP 6 'right temporal pole'
S06 (80 electrodes; descriptor 80 surface + 0 depth): L Grid 64 'Left ECoG grid'; LO 16 'left occipital'
S07 (64 electrodes; descriptor 64 surface + 0 depth): RFGRID 64 'Right Frontal ECoG grid'
S08 (92 electrodes; descriptor 92 surface + 0 depth): GRID 64 'ECoG grid'; RAT 6 'right anterior temporal'; RMT 6 'right medial temporal'; ROF 8 'right orbitofrontal'; RPT 8 'right posterior temporal'
S09 (126 electrodes; descriptor 98 surface + 28 depth): Grid 64 'ECoG grid'; LAT 6 'left anterior temporal'; LF 8 'left frontal'; LID 13 'left insular depth'; LMT 6 'left medial temporal'; LPT 6 'left posterior temporal'; LTO 8 'left temporal occipital'; RAT 0 'right anterior temporal'; RATD 5 'right anterior temporal depth'; RFD 5 'right frontal depth'; RPT 0 'right posterior temporal'; RPTD 5 'right posterior temporal depth'
S10 (126 electrodes; descriptor 86 surface + 40 depth): AHD 4 'anterior hippocampal depth'; AID 14 'anterior insular depth'; GRID 53 'ECoG grid'; LAT 5 'left anterior temporal'; LMT 5 'left medial temporal'; LOF 4 'left orbitofrontal'; LPT 5 'left posterior temporal'; LTP 6 'left temporal pole'; MHD 4 'medial hippocampal depth'; MID 14 'medial insular depth'; PID 12 'posterior insular depth'
S11 (106 electrodes; descriptor 106 surface + 0 depth): Grid 64 'ECoG grid'; LAT 16 'left anterior temporal'; LATD 6 'left anterior temporal depth'; LMT 0 'left medial temporal'; LMTD 6 'left medial temporal depth'; LPT 8 'left posterior temporal'; LTP 0 'left temporal pole'; LTPD 6 'left temporal pole depth'
S12 (124 electrodes; descriptor 92 surface + 32 depth): AHD 8 'anterior hippocampal depth'; AID 8 'anterior insular depth'; GRID 64 'ECoG grid'; LAT 4 'left anterior temporal'; LMT 4 'left medial temporal'; LOF 8 'left orbitofrontal'; LPT 6 'left posterior temporal'; LTP 6 'left temporal pole'; PHD 8 'posterior hippocampal depth'; PID 8 'posterior insular depth'; RPTD 0 'right posterior temporal depth'

The files hold 12 subjects and 55 subject-days, ECoG at 500 Hz and pose at 30 frames per second. The ECoG is stored with a conversion of 1e-6 to volts, so the stored values are microvolts; the pose is labelled meters but holds pixels (the data descriptor gives pixels, and the values span hundreds). The subject has no sex or age in the files or the archive's metadata. Three files hold less than 24 h of ECoG and start later (S01 day 7, S04 day 3, S06 day 3); the clocks of these files are checked below.

The reaches table has the same nine columns in every file, and none marks false positives or verified events. The electrode groups whose description says depth are listed above beside the data descriptor's Table 2; S10 and S11 are counted differently there (see claim cohort).

In [7]:
desc = {c: None for c in ["start_time", "stop_time", "duration", "magnitude", "angle_file", "angle", "speed",
                          "speech", "bimanual_ratio", "bimanual_overlap", "bimanual_class", "hour"]}
print(ev[list(desc)].describe().T[["count", "mean", "min", "50%", "max"]].round(3).to_string())
print("\nMissing values in any feature:", int(ev[list(desc)].isna().sum().sum()))
print("Bimanual ratio exactly 0.5 (the code's fill for missing values):", int((ev.bimanual_ratio == 0.5).sum()))
print("Bimanual overlap above 1 (the file calls it a fraction of the movement):",
      int((ev.bimanual_overlap > 1).sum()), "events")
print("Bimanual class values:", sorted(ev.bimanual_class.unique()))
print("Events per day, largest:", int(ev.groupby(["subject", "day"]).size().max()),
      "(Methods: up to 200 per day)")
print("Reach durations (stop - start) within 0.5-4 s (Methods' movement duration rule):",
      int(ev.duration.between(0.5, 4).sum()), "of", len(ev), "; shortest", round(ev.duration.min(), 3), "s")
                   count       mean      min        50%        max
start_time        8088.0  50271.031  154.627  52081.266  86440.332
stop_time         8088.0  50272.222  156.360  52082.049  86440.899
duration          8088.0      1.191    0.233      1.100      3.933
magnitude         8088.0    102.092    3.927     87.687    680.562
angle_file        8088.0    -33.694 -179.980    -67.154    179.848
angle             8088.0     23.309  -89.936     39.038     89.998
speed             8088.0    133.749    0.000    103.494   1492.070
speech            8088.0      0.310    0.000      0.302      0.827
bimanual_ratio    8088.0      0.256    0.000      0.137      1.000
bimanual_overlap  8088.0      0.575    0.000      0.467      3.833
bimanual_class    8088.0      0.726    0.000      1.000      1.000
hour              8088.0     13.964    0.043     14.467     24.011

Missing values in any feature: 0
Bimanual ratio exactly 0.5 (the code's fill for missing values): 26
Bimanual overlap above 1 (the file calls it a fraction of the movement): 1708 events
Bimanual class values: [np.float64(0.0), np.float64(1.0)]
Events per day, largest: 200 (Methods: up to 200 per day)
Reach durations (stop - start) within 0.5-4 s (Methods' movement duration rule): 7760 of 8088 ; shortest 0.233 s
In [8]:
# Reach angle convention: angle and magnitude from the wrist trace (onset to the largest
# displacement within the reach), compared with the files' values.
rows = []
for s in sessions:
    w = "R_Wrist" if s["reach_event_desc"] == "r_wrist" else "L_Wrist"
    tr = s["wrist"][w]
    for k, d in enumerate(s["events"].duration.values):
        n = int(round(d * ajile.POSE_HZ))
        seg = tr[k, 45:46 + min(n, 45)]
        if np.isnan(seg).any():
            continue
        dd = seg - seg[0]
        r = np.linalg.norm(dd, axis=1)
        j = r.argmax()
        rows.append((s["events"]["Reach_angle_degrees"].values[k], np.degrees(np.arctan2(dd[j, 1], dd[j, 0])),
                     s["events"]["Reach_magnitude_px"].values[k], r[j], d <= 1.5))
ang = pd.DataFrame(rows, columns=["file_angle", "trace_angle", "file_mag", "trace_mag", "within_window"])
circ = lambda a, b: np.abs((a - b + 180) % 360 - 180)
a = ang[ang.within_window]
print(f"{len(a)} reaches of at most 1.5 s with a full trace")
print("median |file angle - trace angle|, image coordinates:", round(np.median(circ(a.file_angle, a.trace_angle)), 2),
      "deg; with the trace angle negated (y up):", round(np.median(circ(a.file_angle, -a.trace_angle)), 2), "deg")
print("median file magnitude / trace magnitude:", round(np.median(a.file_mag / a.trace_mag), 3))
print("Folded angle (paper convention, +90 up): share of events above 0:", round((ev.angle > 0).mean(), 3))
6376 reaches of at most 1.5 s with a full trace
median |file angle - trace angle|, image coordinates: 1.46 deg; with the trace angle negated (y up): 116.58 deg
median file magnitude / trace magnitude: 0.99
Folded angle (paper convention, +90 up): share of events above 0: 0.683

The files' reach angle is the angle of the reach in image coordinates (y pointing down), not yet negated, so upward reaches have negative values; the paper's angle (+90 for upward) is its negation folded onto -90 to 90, as the code does. The files do not say which convention they use. The magnitudes match the traces.

In [9]:
# Clock of the pose and of the event times: contralateral wrist displacement from its mean
# position over -1.5 to -1 s, at the events and at the events shifted by -30 s.
def median_disp(tr, base_slice=slice(0, 16)):
    base = np.nanmean(tr[:, base_slice], 1)
    return np.nanmedian(np.linalg.norm(tr - base[:, None], axis=2), 0)

rows = []
for s in sessions:
    w = "R_Wrist" if s["reach_event_desc"] == "r_wrist" else "L_Wrist"
    m = median_disp(s["wrist"][w])
    rows.append({"subject": s["subject"], "day": s["day"], "disp_at_-1s": m[15].round(1),
                 "disp_at_0s": m[45].round(1), "disp_at_+1s": m[75].round(1)})
clk = pd.DataFrame(rows)
print(clk.to_string(index=False))
print("Sessions where the contralateral wrist moves less than 10 pixels by +1 s:",
      clk[clk["disp_at_+1s"] < 10][["subject", "day"]].values.tolist())
subject  day  disp_at_-1s  disp_at_0s  disp_at_+1s
     01    3          1.1         2.1         59.2
     01    4          1.2         2.5         78.1
     01    5          0.7         1.9         54.6
     01    7          0.5         2.2         86.4
     02    3          1.0         3.8         61.8
     02    4          1.2         4.5         70.5
     02    5          1.7         3.1         55.6
     02    6          1.6         3.2         45.0
     03    3          1.0         2.1         78.9
     03    4          1.1         3.1         63.7
     03    5          0.9         2.6         46.6
     03    6          1.5         4.2         53.0
     04    3          1.0         2.7         44.7
     04    4          1.4         3.5         38.5
     04    5          1.1         3.4         52.5
     04    6          1.0         4.2         73.7
     04    7          1.2         3.5         54.2
     05    3          1.7         4.1         32.9
     05    4          1.4         2.8         63.5
     05    7          1.1         2.5         54.2
     06    3          0.6         1.3         75.8
     06    4          0.6         1.2         77.0
     06    5          0.5         1.1         85.7
     06    6          0.5         1.4         74.7
     06    7          0.7         1.3         73.1
     07    3          0.8         1.4         37.1
     07    4          0.7         2.0         33.8
     07    5          0.5         1.4         45.9
     07    6          0.6         1.7         56.7
     07    7          0.7         1.4         53.4
     08    3          0.9         2.4        165.2
     08    4          1.3         3.0        181.0
     08    5          1.3         2.7        119.6
     08    6          0.9         2.1        149.2
     08    7          0.8         2.2        127.0
     09    3          1.1         2.5         28.5
     09    4          1.1         1.5         28.6
     09    5          0.8         2.0         34.7
     09    6          1.0         2.5         22.2
     09    7          1.5         3.1         29.4
     10    3          0.9         2.3         58.9
     10    4          1.1         2.3         60.5
     10    5          0.9         2.5         49.3
     10    6          0.7         2.3         54.5
     10    7          1.0         2.2         66.6
     11    3          0.7         1.4         77.2
     11    4          0.8         1.9         50.9
     11    5          0.7         1.4         48.3
     11    6          0.7         1.6         49.4
     11    7          0.6         1.6         79.1
     12    3          0.5         1.3        100.4
     12    4          0.5         1.1         84.0
     12    5          0.5         1.4         84.9
     12    6          0.5         1.3         77.7
     12    7          0.4         1.3         80.4
Sessions where the contralateral wrist moves less than 10 pixels by +1 s: []

In every file the contralateral wrist is still before the event time and moves after it, so the pose and the event table share a clock, including in the three files with less than 24 h of ECoG (whose events lie between 8 and 24 h). The shifted control needs the ECoG and is below.

In [10]:
# Time of day: the coarse behaviour labels by hour. Sleep should fall at night if the files
# start at midnight, as the data descriptor says.
lab = pd.concat([s["epochs"].assign(subject=s["subject"]) for s in sessions])
lab["hour"] = ((lab.start + lab.stop) / 2 / 3600).astype(int)
sleep = lab[lab.label == "Sleep/rest"].groupby("hour").size().reindex(range(24), fill_value=0)
print("Sleep/rest labels by hour of the file clock:\n", sleep.to_string())
print("Share of Sleep/rest labels at 0-8 h:", round(sleep[:8].sum() / sleep.sum(), 3),
      "; events at 0-8 h:", round((ev.hour < 8).mean(), 3))
print("session_start_time values:", sorted(info.session_start_time.unique()))
Sleep/rest labels by hour of the file clock:
 hour
0      993
1     1173
2     1202
3     1328
4     1258
5     1067
6      839
7      654
8      496
9      409
10     339
11     358
12     339
13     320
14     401
15     381
16     318
17     258
18     345
19     282
20     289
21     542
22     936
23    1081
Share of Sleep/rest labels at 0-8 h: 0.545 ; events at 0-8 h: 0.148
session_start_time values: ['2000-01-02T19:00:00-05:00', '2000-01-03T03:07:20.566000-05:00', '2000-01-03T03:20:48.322000-05:00', '2000-01-03T19:00:00-05:00', '2000-01-04T19:00:00-05:00', '2000-01-05T19:00:00-05:00', '2000-01-06T19:00:00-05:00', '2000-01-07T03:31:22.414000-05:00']

Sleep labels fall mostly in the first hours of the file clock, which fits files that start at midnight local time. The files' session_start_time of 19:00 at UTC-5 is midnight UTC, so the stated time zone is not the local one; the three late files have start times of 03:07 to 03:31 at UTC-5, the start of their ECoG (checked below). The hour of an event is taken from the file clock.

In [11]:
# Duplicates: identical event tables or wrist traces in two files.
keys = {}
for s in sessions:
    k1 = np.round(s["events"].start_time.values, 3).tobytes()
    k2 = np.nan_to_num(s["wrist"]["R_Wrist"]).round(2).tobytes()
    keys.setdefault(("events", hash(k1)), []).append((s["subject"], s["day"]))
    keys.setdefault(("wrist", hash(k2)), []).append((s["subject"], s["day"]))
dups = {k: v for k, v in keys.items() if len(v) > 1}
print("Files with identical event times or identical wrist traces:", dups if dups else "none")
Files with identical event times or identical wrist traces: none

ECoG: projection matrices and event segments¶

The paper's projection of electrodes onto the eight regions (AAL atlas through the Measure Projection Toolbox) is taken from its own output on Figshare (doi:10.6084/m9.figshare.12114408.v1), which the claims file names as the paper's output of that step. Claim roi-projection-link checks that its rows can be matched to the dataset's electrodes. The bad electrodes are those of each subject's first file, as the paper's code takes them.

In [12]:
roi_meta = ajile.roi_files()
roi_mats, weights_check = {}, {}
for sub in SUBJECTS:
    roi_mats[sub] = ajile.read_roi_matrix(sub, roi_meta)
first_good = {}
for s in sessions:
    first_good.setdefault(s["subject"], s["electrodes"]["good"].values.copy())
for s in sessions:
    s["subject_good"] = first_good[s["subject"]]
print("Figshare files read (name, md5):")
for sub in SUBJECTS:
    print(f"  aal_{sub}_elecs2ROI.csv", roi_meta[f"aal_{sub}_elecs2ROI.csv"][1])
Figshare files read (name, md5):
  aal_01_elecs2ROI.csv 2f21bb61045296257e648323f9d58644
  aal_02_elecs2ROI.csv ddc5de6527a31405f0ec67f4a81ef8ea
  aal_03_elecs2ROI.csv 4f8b58ab393be10af1d59389a0c387de
  aal_04_elecs2ROI.csv 2e84691cbf15b005142eb079e559fceb
  aal_05_elecs2ROI.csv 6b5969a62e21a8407d936b1d3b86c1be
  aal_06_elecs2ROI.csv 5e75a457f63eb70226b013a1b0a71383
  aal_07_elecs2ROI.csv c1d620aea4f38cf280d5bf06787ef47c
  aal_08_elecs2ROI.csv 7be91f3f41c5883b144e9116a3c36e0b
  aal_09_elecs2ROI.csv 4579d56608e6b245fc715e1ad69fc396
  aal_10_elecs2ROI.csv fd66592385d1eca9bd3afdac2cac4dbb
  aal_11_elecs2ROI.csv fd7aaadaa43193a7f2f13b686090b4b9
  aal_12_elecs2ROI.csv 1b212f9a9c38fba07d00bc01e057ad13
In [13]:
started = time.time()
weights = {sub: ajile.roi_weights(roi_mats[sub], first_good[sub]) for sub in SUBJECTS}
ecog = ajile.load_ecog(ajile.ecog_jobs(sessions, weights))
# LOAD-ECOG-END
print(f"ECoG segments of {sum(sum(r['ok']) for r in ecog)} events read and reduced in "
      f"{(time.time() - started) / 60:.1f} min")
ECoG segments of 8087 events read and reduced in 22.4 min
In [14]:
# Per-event ECoG measures, aligned with the event table.
REG = {n: i for i, n in enumerate(ajile.ROI_NAMES)}
ev["ok"] = np.concatenate([r["ok"] for r in ecog])
for key in ["q_all", "q_hf", "q_log"]:
    ev[key] = np.concatenate([r[key] for r in ecog])
spec = np.full((len(ev), 8, len(ajile.FREQS), len(ajile.TIMES)), np.nan, dtype=np.float32)
i = 0
for r in ecog:
    for ok, sp in zip(r["ok"], r["roi_spec"]):
        if ok:
            spec[i] = sp
        i += 1
for kind in ["roi_band", "roi_band_raw"]:
    for meas in ["lfb_mean", "lfb_median", "hfb_mean", "hfb_median"]:
        vals = np.full((len(ev), 8), np.nan)
        i = 0
        for r in ecog:
            for ok, b in zip(r["ok"], r[kind]):
                if ok:
                    vals[i] = b[meas]
                i += 1
        for reg, j in REG.items():
            ev[f"{kind}:{reg}:{meas}"] = vals[:, j]
# Bad segments (Methods): power below 0 dB, or 115-125 Hz power more than 3 SD above the mean
# of the subject's segments. False positives are not marked in the files (see the data check).
thr = ev[ev.ok].groupby("subject").q_hf.agg(lambda v: v.mean() + 3 * v.std())
ev["bad_missing"] = ev.ok & ~np.isfinite(ev.q_all)          # segments with missing (NaN) samples
ev["bad_low"] = ev.q_all < 0
ev["bad_hf"] = ev.q_hf > ev.subject.map(thr)
ev["keep_b"] = ev.ok & ~ev.bad_missing & ~ev.bad_low & ~ev.bad_hf
TIMES, FREQS = ajile.TIMES, ajile.FREQS
print("Events with a full ECoG segment:", int(ev.ok.sum()), "of", len(ev))
print("Segments with missing (NaN) samples:", int(ev.bad_missing.sum()), "in",
      ev[ev.bad_missing].groupby(["subject", "day"]).size().to_dict())
print("Segments below 0 dB:", int(ev.bad_low.sum()), "; 115-125 Hz above 3 SD:", int((ev.bad_hf & ~ev.bad_low).sum()),
      "; kept (reading b):", int(ev.keep_b.sum()))
print("Other reading of the 0 dB test (mean of the log density below 0 dB):", int((ev.q_log < 0).sum()), "of",
      int(ev.ok.sum()), "segments would go, so that reading is not usable")
print(ev[ev.ok].groupby("subject")[["q_all", "q_hf"]].agg(["min", "median", "max"]).round(1).to_string())
Events with a full ECoG segment: 8087 of 8088
Segments with missing (NaN) samples: 124 in {('01', 3): 1, ('01', 4): 1, ('01', 5): 4, ('02', 4): 1, ('02', 5): 2, ('04', 4): 1, ('04', 6): 1, ('04', 7): 3, ('06', 3): 1, ('06', 4): 7, ('06', 6): 8, ('06', 7): 11, ('07', 7): 6, ('08', 3): 4, ('08', 4): 2, ('08', 6): 3, ('08', 7): 1, ('10', 3): 7, ('10', 5): 1, ('10', 6): 23, ('10', 7): 16, ('11', 3): 2, ('11', 4): 1, ('11', 5): 3, ('11', 6): 1, ('11', 7): 3, ('12', 3): 2, ('12', 4): 3, ('12', 5): 3, ('12', 7): 2}
Segments below 0 dB: 1 ; 115-125 Hz above 3 SD: 74 ; kept (reading b): 7888
Other reading of the 0 dB test (mean of the log density below 0 dB): 7931 of 8087 segments would go, so that reading is not usable
        q_all               q_hf             
          min median   max   min median   max
subject                                      
01        5.2    7.6  11.6 -14.1  -12.3  -9.7
02        8.0   11.8  20.8 -14.6  -12.3  -8.8
03        6.7   10.1  18.1 -14.3  -11.5   6.8
04        5.2    6.6  12.1 -13.5  -12.0 -10.3
05        6.0    9.6  17.5 -13.8  -11.7  -8.0
06        6.9    9.0  14.3 -10.0   -7.8  -1.9
07        7.4   10.3  14.9 -11.5  -10.7  -8.7
08        3.7    5.5  10.7 -12.3  -10.3  -6.6
09        3.2    7.1  13.3 -17.8  -16.3 -14.1
10        3.8    8.4  12.5 -15.1  -13.5  -7.3
11      -11.9   11.6  18.0 -25.4   -9.9  -3.4
12        4.6    7.5  13.0 -14.7  -13.5 -11.6
In [15]:
# segment_power against MNE's own Morlet transform, on one segment of the data.
from mne.time_frequency import tfr_array_morlet
import h5py, remfile
s0 = sessions[0]
f0 = h5py.File(remfile.File(ajile.asset_url(s0["asset_id"])), "r")
c0 = int(round(s0["events"].start_time.values[0] * ajile.FS))
x0 = f0["acquisition/ElectricalSeries/data"][c0 - 2500:c0 + 2500, :8].T.astype(float)
f0.close()
mine = ajile.segment_power(x0)
ref = tfr_array_morlet(x0[None], sfreq=ajile.FS, freqs=FREQS, n_cycles=FREQS / 4, zero_mean=True, use_fft=False,
                       decim=ajile.DECIM, output="power", verbose=False)[0][..., 5:96]
print("largest difference from MNE tfr_array_morlet(use_fft=False), dB:", float(np.abs(mine - 10 * np.log10(ref)).max()))
print("segment amplitude range (microvolts):", round(float(x0.min()), 1), round(float(x0.max()), 1))
largest difference from MNE tfr_array_morlet(use_fft=False), dB: 1.021405182655144e-12
segment amplitude range (microvolts): -185.8 300.2
In [16]:
# Clock of the ECoG against the events: precentral and postcentral band power change from the
# -1.5 to -1 s baseline to 0-0.5 s, at the event time and at a pseudo-event 3 s earlier
# (-3 to -2.5 s against -4.5 to -4 s) in the same segments; median over events per file.
ti = lambda lo, hi: np.nonzero((TIMES >= lo - 1e-6) & (TIMES <= hi + 1e-6))[0]
lf = np.nonzero((FREQS >= 8) & (FREQS <= 32))[0]
hf = np.nonzero((FREQS >= 76) & (FREQS <= 100))[0]
def band_change(sp, band, t_on, t_base):
    return sp[..., band, :][..., t_on].mean((-1, -2)) - sp[..., band, :][..., t_base].mean((-1, -2))
rows = []
for (sub, day), g in ev[ev.keep_b].groupby(["subject", "day"]):
    sp = spec[g.index][:, [REG["precentral"], REG["postcentral"]]]
    row = {"subject": sub, "day": day, "n": len(g)}
    for name, band in [("HFB", hf), ("LFB", lf)]:
        true = band_change(sp, band, ti(0, 0.5), ti(-1.5, -1))
        pseudo = band_change(sp, band, ti(-3, -2.5), ti(-4.5, -4))
        best = np.argmax(np.abs(np.median(true, 0)))
        row[f"{name}_event"] = round(float(np.median(true[:, best])), 2)
        row[f"{name}_pseudo"] = round(float(np.median(pseudo[:, best])), 2)
    rows.append(row)
clock = pd.DataFrame(rows)
print(clock.to_string(index=False))
clock_ok = (clock.HFB_event > 0) & (clock.LFB_event < 0) & (clock.HFB_event > clock.HFB_pseudo) & (clock.LFB_event < clock.LFB_pseudo)
print("Files with HFB up, LFB down at the event and both larger than at the pseudo-event:", int(clock_ok.sum()), "of", len(clock))
print("Files where this does not hold:", clock[~clock_ok][["subject", "day"]].values.tolist())
subject  day   n  HFB_event  HFB_pseudo  LFB_event  LFB_pseudo
     01    3 154       0.08       -0.01      -1.07       -0.14
     01    4 194       0.12        0.05      -1.54       -0.04
     01    5 194       0.31       -0.10      -1.67        0.14
     01    7 190       0.25        0.08      -1.61        0.10
     02    3  51       0.26       -0.27      -0.09        0.03
     02    4  93       0.13       -0.25      -0.60        0.12
     02    5  79      -0.09        0.14      -0.51        0.20
     02    6  75       0.61       -0.04      -0.42        0.37
     03    3 198       1.82       -0.25      -3.13        0.09
     03    4 193       1.57        0.03      -1.50        0.00
     03    5 137       1.18       -0.25      -1.07       -0.16
     03    6 109       1.20       -0.19      -0.80        0.00
     04    3  35      -0.16        0.08      -0.56        0.29
     04    4  97       0.27        0.08      -0.22       -0.06
     04    5  43       0.58        0.01      -0.28        0.17
     04    6  81       1.01       -0.03      -0.21       -0.08
     04    7 156       0.94        0.05      -0.14        0.05
     05    3  56       0.21       -0.03      -0.85        0.06
     05    4  48       0.39       -0.12      -0.90        0.38
     05    7 159       0.32        0.14      -0.38       -0.14
     06    3 164       1.98       -0.23      -1.60        0.24
     06    4 191       2.02       -0.05      -1.38        0.04
     06    5 193       2.09       -0.26      -0.82       -0.12
     06    6 186       1.87       -0.03      -0.90       -0.03
     06    7 177       2.03       -0.11      -1.04       -0.20
     07    3  93       1.53        0.10      -0.86       -0.13
     07    4 110       1.34        0.16      -0.69       -0.25
     07    5 197       1.02        0.00      -0.78       -0.04
     07    6 194       1.10       -0.07      -0.97        0.05
     07    7 190       1.22       -0.08      -0.82        0.04
     08    3 193       0.90       -0.14      -0.07        0.07
     08    4 191       0.94       -0.13      -0.19        0.02
     08    5 172       0.76       -0.08      -0.11        0.03
     08    6 193       0.90       -0.04       0.07       -0.14
     08    7 198       0.32        0.11       0.08       -0.09
     09    3  15       0.34        0.06      -0.54       -0.37
     09    4  18      -0.13        0.61      -0.61        0.13
     09    5 109       0.18       -0.12      -0.46        0.05
     09    6  38       0.45       -0.12      -0.91       -0.29
     09    7  31       0.34        0.03      -1.25        0.20
     10    3 176       0.17       -0.05      -0.69        0.07
     10    4 154       0.10        0.04      -0.30        0.09
     10    5 108       0.42        0.00      -0.47       -0.07
     10    6 129       0.35        0.14      -0.61        0.17
     10    7 179       0.46       -0.14      -0.32       -0.06
     11    3 197       0.67       -0.03      -3.23        0.18
     11    4 192       0.61        0.12      -1.85        0.06
     11    5 192       0.81        0.13      -1.55        0.06
     11    6 197       0.55       -0.07      -2.30        0.17
     11    7 190       0.92        0.04      -3.04       -0.17
     12    3 197       0.23       -0.12      -0.66       -0.07
     12    4 197       0.12       -0.09      -0.43       -0.02
     12    5 194       0.07       -0.11      -0.52        0.02
     12    6 197       0.16        0.06      -0.52       -0.18
     12    7 194       0.14       -0.06      -0.62       -0.02
Files with HFB up, LFB down at the event and both larger than at the pseudo-event: 50 of 55
Files where this does not hold: [['02', 5], ['04', 3], ['08', 6], ['08', 7], ['09', 4]]
In [17]:
# The three files with less than 24 h of ECoG: event times on the ECoG clock with the offset
# of the helper (ECoG ends at midnight) against no offset (ECoG starts at midnight).
late = [s for s in sessions if ajile.ecog_offset(s) > 1]
alt = ajile.load_ecog(ajile.ecog_jobs(late, weights, offset=False), workers=3)
for s, r in zip(late, alt):
    g = ev[(ev.subject == s["subject"]) & (ev.day == s["day"]) & ev.keep_b]
    pre = REG["precentral"]
    a_h = band_change(spec[g.index][:, pre], hf, ti(0, 0.5), ti(-1.5, -1))
    a_l = band_change(spec[g.index][:, pre], lf, ti(0, 0.5), ti(-1.5, -1))
    sp_b = np.array([x[pre] for x, ok in zip(r["roi_spec"], r["ok"]) if ok and np.isfinite(x[pre]).all()])
    b_h = band_change(sp_b, hf, ti(0, 0.5), ti(-1.5, -1)) if len(sp_b) else np.array([np.nan])
    b_l = band_change(sp_b, lf, ti(0, 0.5), ti(-1.5, -1)) if len(sp_b) else np.array([np.nan])
    print(f"S{s['subject']} day {s['day']}: offset {ajile.ecog_offset(s):.1f} s; with offset {len(a_h)} events, "
          f"precentral HFB {np.median(a_h):+.2f} dB, LFB {np.median(a_l):+.2f} dB; without offset {len(sp_b)} events in "
          f"range, HFB {np.median(b_h):+.2f} dB, LFB {np.median(b_l):+.2f} dB; ReachEvents minus offset-corrected "
          f"times, max |diff| {np.max(np.abs(s['reach_event_times'] - (s['events'].start_time.values - ajile.ecog_offset(s)))):.3f} s")
S01 day 7: offset 30682.4 s; with offset 190 events, precentral HFB +0.10 dB, LFB -1.61 dB; without offset 58 events in range, HFB -0.15 dB, LFB +0.03 dB; ReachEvents minus offset-corrected times, max |diff| 0.001 s
S04 day 3: offset 30048.3 s; with offset 35 events, precentral HFB -0.07 dB, LFB -0.31 dB; without offset 13 events in range, HFB +0.02 dB, LFB +0.48 dB; ReachEvents minus offset-corrected times, max |diff| 0.001 s
S06 day 3: offset 29240.6 s; with offset 164 events, precentral HFB +1.98 dB, LFB -1.60 dB; without offset 81 events in range, HFB -0.07 dB, LFB +0.27 dB; ReachEvents minus offset-corrected times, max |diff| 0.001 s

Claim subject-days¶

The dataset's subjects and recording days are the paper's subjects S01 to S12 and the recording days the paper lists for each.

In [18]:
TABLE2 = {"01": [3, 4, 5, 7], "02": [3, 4, 5, 6], "03": [3, 4, 5, 6], "05": [3, 4, 7]}
TABLE2 = {s: TABLE2.get(s, [3, 4, 5, 6, 7]) for s in SUBJECTS}
days = info.groupby("subject").day.apply(list).to_dict()
for sub in SUBJECTS:
    print(f"S{sub}: dataset days {days[sub]}, Table 2 {TABLE2[sub]}, match {days[sub] == TABLE2[sub]}")
print("All 12 match:", all(days[s] == TABLE2[s] for s in SUBJECTS), "; subject-days:", sum(len(v) for v in days.values()))
S01: dataset days [3, 4, 5, 7], Table 2 [3, 4, 5, 7], match True
S02: dataset days [3, 4, 5, 6], Table 2 [3, 4, 5, 6], match True
S03: dataset days [3, 4, 5, 6], Table 2 [3, 4, 5, 6], match True
S04: dataset days [3, 4, 5, 6, 7], Table 2 [3, 4, 5, 6, 7], match True
S05: dataset days [3, 4, 7], Table 2 [3, 4, 7], match True
S06: dataset days [3, 4, 5, 6, 7], Table 2 [3, 4, 5, 6, 7], match True
S07: dataset days [3, 4, 5, 6, 7], Table 2 [3, 4, 5, 6, 7], match True
S08: dataset days [3, 4, 5, 6, 7], Table 2 [3, 4, 5, 6, 7], match True
S09: dataset days [3, 4, 5, 6, 7], Table 2 [3, 4, 5, 6, 7], match True
S10: dataset days [3, 4, 5, 6, 7], Table 2 [3, 4, 5, 6, 7], match True
S11: dataset days [3, 4, 5, 6, 7], Table 2 [3, 4, 5, 6, 7], match True
S12: dataset days [3, 4, 5, 6, 7], Table 2 [3, 4, 5, 6, 7], match True
All 12 match: True ; subject-days: 55

Result: reproduced. The dataset's subjects 01 to 12 have exactly the days of Table 2 (55 subject-days), so the subjects are matched by number.

Claim roi-projection-link¶

The rows of the paper's projection matrices (Figshare) can be matched one to one to the dataset's electrodes, and the weights fit the electrodes' positions.

In [19]:
cent_rows = {}
rows = []
rng_link = np.random.default_rng(55)
for sub in SUBJECTS:
    df = roi_mats[sub]
    el = [s for s in sessions if s["subject"] == sub][0]["electrodes"]
    n_rows = len(df) - 1
    zero = np.nonzero(df.iloc[1:].transpose().mean().values == 0)[0]
    cen = pd.read_csv(roi_meta[f"aal_{sub}_ROIcentroids_Lside.csv"][0])
    cen = cen.iloc[[df.columns.get_loc(c) for c in ajile.ROI_COLUMNS]].to_numpy(float)
    w = weights[sub]
    xyz = el[["x", "y", "z"]].to_numpy(float).copy()
    xyz[:, 0] = -np.abs(xyz[:, 0])                       # right hemisphere mirrored to the left
    dist = np.linalg.norm(xyz[:, None, :] - cen[None], axis=2)
    use = w.sum(1) > 0
    agree = np.mean(np.argmax(w[use], 1) == np.argmin(dist[use], 1))
    null = np.mean([np.mean(np.argmax(w[use], 1) == np.argmin(dist[use][rng_link.permutation(use.sum())], 1))
                    for _ in range(200)])
    rho = stats.spearmanr(w[use].ravel(), -dist[use].ravel())[0]
    rows.append({"subject": sub, "electrodes": len(el), "matrix_rows": n_rows, "all_zero_rows": len(zero),
                 "zero_row_groups": ",".join(sorted(set(el.group_name.values[zero]))) if n_rows == len(el) else
                 f"rows {zero.min()}-{zero.max()} (beyond the {len(el)} electrodes)",
                 "rows_used": len(w), "top_weight_is_nearest_centroid": round(agree, 3),
                 "same_with_order_shuffled": round(null, 3), "spearman_weight_vs_proximity": round(rho, 3)})
link = pd.DataFrame(rows)
print(link.to_string(index=False))
print("Subjects whose rows match the electrodes one to one:", int((link.rows_used == link.electrodes).sum()), "of 12")
print("Subjects where the weights fit positions better than with the order shuffled:",
      int((link.top_weight_is_nearest_centroid > link.same_with_order_shuffled).sum()), "of 12")
dens = pd.concat([roi_mats[s].iloc[0] for s in SUBJECTS], axis=1).mean(1)
print("Regions with mean electrode density > 3 (Methods):",
      [c for c in dens.index if dens[c] > 3], "\nthe eight of the claims file:", ajile.ROI_COLUMNS)
subject  electrodes  matrix_rows  all_zero_rows                       zero_row_groups  rows_used  top_weight_is_nearest_centroid  same_with_order_shuffled  spearman_weight_vs_proximity
     01          94           98              4 rows 94-97 (beyond the 94 electrodes)         94                           0.765                     0.206                         0.925
     02          86           86              0                                               86                           0.741                     0.236                         0.921
     03          96           96             16                               LAD,LPD         96                           0.671                     0.184                         0.929
     04          84           84              0                                               84                           0.687                     0.185                         0.936
     05         106          106              0                                              106                           0.750                     0.166                         0.936
     06          80           80              0                                               80                           0.643                     0.258                         0.922
     07          64           64              0                                               64                           0.587                     0.176                         0.916
     08          92           92              0                                               92                           0.747                     0.163                         0.937
     09         126          126              0                                              126                           0.758                     0.183                         0.931
     10         126          126              0                                              126                           0.752                     0.180                         0.936
     11         106          106              0                                              106                           0.786                     0.178                         0.935
     12         124          124              8                                   AID        124                           0.705                     0.217                         0.920
Subjects whose rows match the electrodes one to one: 12 of 12
Subjects where the weights fit positions better than with the order shuffled: 12 of 12
Regions with mean electrode density > 3 (Methods): ['Precentral_L', 'Frontal_Mid_L', 'Postcentral_L', 'Parietal_Inf_L', 'SupraMarginal_L', 'Temporal_Sup_L', 'Temporal_Mid_L', 'Temporal_Inf_L'] 
the eight of the claims file: ['Frontal_Mid_L', 'Precentral_L', 'Postcentral_L', 'Parietal_Inf_L', 'SupraMarginal_L', 'Temporal_Sup_L', 'Temporal_Mid_L', 'Temporal_Inf_L']
/tmp/ipykernel_2311/2382600970.py:30: Pandas4Warning: Starting with pandas version 4.0 all arguments of mean will be keyword-only.
  dens = pd.concat([roi_mats[s].iloc[0] for s in SUBJECTS], axis=1).mean(1)

Result: reproduced. For all 12 subjects the projection matrix has one row per electrode of the NWB file (S01 has four extra all-zero rows at the end, dropped by the code's rule), the all-zero rows of S03 and S12 fall on depth electrode groups (LAD and LPD; AID), and the region with the largest weight is the region with the nearest centroid for 0.59 to 0.79 of electrodes, against 0.16 to 0.26 with the electrode order shuffled; the Spearman correlation of weight with proximity is 0.92 to 0.94. The regions with mean density above 3 are the eight of the claims file.

Claim cohort¶

Twelve subjects (8 male, 4 female, 29.4 +- 7.9 years) had on average 87.0 +- 12.9 surface electrodes; five also had 23.2 +- 12.1 depth electrodes; five were implanted in the right hemisphere and seven in the left.

In [20]:
rows = []
for sub in SUBJECTS:
    s = [x for x in sessions if x["subject"] == sub][0]
    el = s["electrodes"]
    depth_groups = [g for g, d in s["group_desc"].items() if "depth" in d.lower()]
    is_depth = el.group_name.isin(depth_groups)
    rows.append({"subject": sub, "surface": int((~is_depth).sum()), "depth": int(is_depth.sum()),
                 "depth_groups": ",".join(depth_groups), "wrist": s["reach_event_desc"],
                 "mean_x": round(el.x.mean(), 1)})
coh = pd.DataFrame(rows)
print(coh.to_string(index=False))
hemi_right = (coh.wrist == "l_wrist").sum()
print(f"\nsubjects {len(coh)}; surface electrodes mean {coh.surface.mean():.1f} +- {coh.surface.std():.1f} (SD); "
      f"subjects with depth electrodes {(coh.depth > 0).sum()}, their mean {coh[coh.depth > 0].depth.mean():.1f} +- "
      f"{coh[coh.depth > 0].depth.std():.1f}; right hemisphere (left wrist events, x > 0) {hemi_right}")
print("Right hemisphere by wrist agrees with the sign of mean x:", bool(((coh.wrist == "l_wrist") == (coh.mean_x > 0)).all()))
print("Sex and age: not in the files or the archive's metadata (subject fields:", sessions[0]["subject_fields"], ")")
both = coh.copy()
both["all"] = both.surface + both.depth
print("Variant, every electrode counted: mean", round(both["all"].mean(), 1))
d2 = pd.DataFrame(DESC_T2, index=["surface", "depth"]).T
print("Variant, the data descriptor's Table 2 counts: surface mean", round(d2.surface.mean(), 1), "+-",
      round(d2.surface.std(), 1), "; subjects with depth electrodes", int((d2.depth > 0).sum()), ", their mean",
      round(d2[d2.depth > 0].depth.mean(), 1), "+-", round(d2[d2.depth > 0].depth.std(), 1))
print("Subjects whose file counts differ from the descriptor's:",
      {s: (int(r.surface), int(r.depth), DESC_T2[s]) for s, r in coh.set_index("subject").iterrows() if (r.surface, r.depth) != DESC_T2[s]})
subject  surface  depth         depth_groups   wrist  mean_x
     01       86      8                  LID r_wrist   -53.7
     02       70     16              RDA,RDP l_wrist    54.5
     03       80     16              LAD,LPD r_wrist   -49.3
     04       84      0                      l_wrist    49.0
     05      106      0                      l_wrist    53.9
     06       80      0                      r_wrist   -41.5
     07       64      0                      l_wrist    48.8
     08       92      0                      l_wrist    54.1
     09       98     28    LID,RATD,RFD,RPTD r_wrist   -38.1
     10       78     48  AHD,AID,MHD,MID,PID r_wrist   -40.9
     11       88     18       LATD,LMTD,LTPD r_wrist   -51.1
     12       92     32 AHD,AID,PHD,PID,RPTD r_wrist   -45.8

subjects 12; surface electrodes mean 84.8 +- 11.6 (SD); subjects with depth electrodes 7, their mean 23.7 +- 13.4; right hemisphere (left wrist events, x > 0) 5
Right hemisphere by wrist agrees with the sign of mean x: True
Sex and age: not in the files or the archive's metadata (subject fields: ['species', 'subject_id'] )
Variant, every electrode counted: mean 98.7
Variant, the data descriptor's Table 2 counts: surface mean 87.0 +- 12.9 ; subjects with depth electrodes 6 , their mean 23.3 +- 12.0
Subjects whose file counts differ from the descriptor's: {'10': (78, 48, (86, 40)), '11': (88, 18, (106, 0))}

Result: partially reproduced. 12 subjects, a mean of 84.8 surface electrodes (87.0 +- 12.9), a mean of 23.7 depth electrodes in the subjects that have them (23.2 +- 12.1) and 5 right-hemisphere subjects match. Seven subjects have electrode groups described as depth in the files, where the paper says five. Sex and age are not in the dataset, so those two values are not testable. The data descriptor's Table 2 gives S10 86 surface and 40 depth electrodes and S11 106 surface and none, where the group descriptions in the files give 78 and 48, and 88 and 18. With the descriptor's counts the surface mean is 87.0 +- 12.9 and six subjects have depth electrodes (23.3 +- 12.0), still not five.

Claim fig2-event-counts¶

Each subject contributed between 151 and 947 movement events (median 640 across subjects).

In [21]:
cnt = pd.DataFrame({"a_all_events": ev.groupby("subject").size(),
                    "b_bad_segments_dropped": ev[ev.keep_b].groupby("subject").size()})
print(cnt.T.to_string())
for c in cnt:
    v = cnt[c]
    print(f"{c}: fewest {v.min()} (151 +- 15.1), most {v.max()} (947 +- 94.7), median {v.median():.1f} (640 +- 64); "
          f"within: {abs(v.min() - 151) <= 15.1}, {abs(v.max() - 947) <= 94.7}, {abs(v.median() - 640) <= 64}")
print("Total events:", len(ev), "; the data descriptor (Peterson et al. 2022, Sci Data) states 6931 verified events")
subject                  01   02   03   04   05   06   07   08   09   10   11   12
a_all_events            741  305  642  417  267  956  800  965  211  806  982  996
b_bad_segments_dropped  732  298  637  412  263  911  784  947  211  746  968  979
a_all_events: fewest 211 (151 +- 15.1), most 996 (947 +- 94.7), median 770.5 (640 +- 64); within: False, True, False
b_bad_segments_dropped: fewest 211 (151 +- 15.1), most 979 (947 +- 94.7), median 739.0 (640 +- 64); within: False, True, False
Total events: 8088 ; the data descriptor (Peterson et al. 2022, Sci Data) states 6931 verified events

Result: not reproduced. The dataset holds 211 to 996 events per subject (median 770.5); after dropping segments with missing samples, below 0 dB or with high 115-125 Hz power, 211 to 979 (median 739). The fewest (211 against 151 +- 15.1) and the median (against 640 +- 64) are outside tolerance under both readings; the most is within. The files hold 8088 events, where the data descriptor states 6931, and no event is marked as a false positive. The reaches table has the same nine columns in all 55 files and none marks an event as a false positive or as verified, so reading b cannot drop the false positives: the outcome rests on reading a and on reading b without that step.

Claim fig2-features-differ-across-subjects¶

All ten behavioural and environmental features differ significantly across subjects.

In [22]:
rows = []
for label, sel in [("b", ev.keep_b), ("a", np.ones(len(ev), bool))]:
    for f in FEATURES:
        groups = [g[f].values for _, g in ev[sel].groupby("subject")]
        h, p = stats.kruskal(*groups)
        rows.append({"reading": label, "feature": f, "H": round(h, 1), "p": p, "p_below_0001": p < 0.001})
kw = pd.DataFrame(rows)
print(kw.to_string(index=False))
print("All ten p < 0.001, reading b:", bool(kw[kw.reading == "b"].p_below_0001.all()),
      "; reading a:", bool(kw[kw.reading == "a"].p_below_0001.all()))
print("Largest p:", kw.groupby("reading").p.max().to_dict())
reading          feature      H             p  p_below_0001
      b              day  374.6  1.513673e-73          True
      b             hour  311.7  3.064764e-60          True
      b         duration  189.8  9.854386e-35          True
      b        magnitude 1434.3 4.898135e-301          True
      b            angle  196.6  3.856062e-36          True
      b            speed 1952.9  0.000000e+00          True
      b           speech 1258.0 5.034370e-263          True
      b   bimanual_ratio  584.1 3.449371e-118          True
      b bimanual_overlap  381.6  4.894647e-75          True
      b   bimanual_class  474.0  1.092334e-94          True
      a              day  383.4  2.037577e-75          True
      a             hour  306.2  4.412741e-59          True
      a         duration  189.4  1.154554e-34          True
      a        magnitude 1464.6 1.364256e-307          True
      a            angle  200.9  4.872987e-37          True
      a            speed 2029.7  0.000000e+00          True
      a           speech 1272.5 3.773064e-266          True
      a   bimanual_ratio  585.9 1.452830e-118          True
      a bimanual_overlap  389.9  8.405715e-77          True
      a   bimanual_class  473.5  1.434644e-94          True
All ten p < 0.001, reading b: True ; reading a: True
Largest p: {'a': 1.154554497329939e-34, 'b': 9.85438624058106e-35}

Result: reproduced. All ten Kruskal-Wallis tests across subjects give p < 0.001 under both event sets (largest p 9.9e-35).

Claim fig2-reach-shape¶

Reach duration and reach magnitude vary little across subjects, with most reaches lasting under 2 s and covering under 200 pixels, and reach angle distributions tend to be bimodal with peaks near +90 and -90 degrees, with few side-to-side reaches.

In [23]:
from scipy.stats import gaussian_kde
grid = np.linspace(-90, 90, 361)
def bimodal(a):
    dens = gaussian_kde(a, bw_method="scott")(grid)
    peaks = [i for i in range(1, len(grid) - 1) if dens[i] > dens[i - 1] and dens[i] >= dens[i + 1]]
    # ends of the range count as maxima when the density rises towards them
    if dens[0] > dens[1]:
        peaks.append(0)
    if dens[-1] > dens[-2]:
        peaks.append(len(grid) - 1)
    top = sorted(peaks, key=lambda i: -dens[i])[:2]
    locs = sorted(grid[top])
    zero = dens[np.argmin(np.abs(grid))]
    ok = len(locs) == 2 and abs(locs[0] + 90) <= 15 and abs(locs[1] - 90) <= 15 and zero < dens[top].min()
    return ok, locs, zero / dens[top].min() if len(top) else np.nan
E = ev[ev.keep_b]
rows = []
for sub, g in list(E.groupby("subject")) + [("pooled", E)]:
    ok, locs, rel = bimodal(g.angle.values)
    rows.append({"subject": sub, "n": len(g), "median_duration_s": round(g.duration.median(), 2),
                 "share_under_2s": round((g.duration < 2).mean(), 3), "median_magnitude_px": round(g.magnitude.median(), 1),
                 "share_under_200px": round((g.magnitude < 200).mean(), 3), "angle_peaks": np.round(locs, 1).tolist(),
                 "density_at_0_over_lower_peak": round(rel, 2), "bimodal_at_pm90": ok,
                 "share_within_30deg_of_0": round((g.angle.abs() < 30).mean(), 3)})
rs = pd.DataFrame(rows)
print(rs.to_string(index=False))
subj = rs[rs.subject != "pooled"]
pool = rs[rs.subject == "pooled"].iloc[0]
dm = (subj.share_under_2s > 0.5) & (subj.share_under_200px > 0.5)
print(f"\nduration and magnitude part: pooled {pool.share_under_2s > 0.5 and pool.share_under_200px > 0.5}, "
      f"subjects {int(dm.sum())} of 12")
print(f"angle part: pooled {pool.bimodal_at_pm90}, subjects {int(subj.bimodal_at_pm90.sum())} of 12")
print("Variant, reading a (all events):")
E2 = ev
print(" share under 2 s", round((E2.duration < 2).mean(), 3), "; under 200 px", round((E2.magnitude < 200).mean(), 3),
      "; pooled angle bimodal at +-90:", bimodal(E2.angle.values)[0], np.round(bimodal(E2.angle.values)[1], 1).tolist())
subject    n  median_duration_s  share_under_2s  median_magnitude_px  share_under_200px   angle_peaks  density_at_0_over_lower_peak  bimodal_at_pm90  share_within_30deg_of_0
     01  732               1.03           0.933                 89.5              0.947 [-71.0, 75.5]                          0.95            False                    0.187
     02  298               1.07           0.943                 79.0              0.946        [40.0]                          0.91            False                    0.362
     03  637               1.03           0.942                 82.1              0.973 [-51.0, 71.0]                          1.35            False                    0.253
     04  412               1.03           0.930                 72.7              0.971        [68.0]                          0.53            False                    0.294
     05  263               1.03           0.954                 72.3              0.928 [-54.0, 63.5]                          0.92            False                    0.259
     06  911               1.17           0.887                 93.3              0.933 [-63.5, 71.0]                          1.80            False                    0.261
     07  784               1.07           0.935                 60.7              0.991 [-71.0, 70.5]                          1.39            False                    0.246
     08  947               1.07           0.911                171.3              0.591 [-66.0, 71.0]                          0.72            False                    0.201
     09  211               1.27           0.896                 43.5              1.000 [-60.5, 62.5]                          0.60            False                    0.175
     10  746               1.20           0.881                 83.9              0.929 [-62.0, 66.0]                          0.63            False                    0.237
     11  968               1.07           0.943                 73.8              0.990 [-73.0, 74.5]                          0.96            False                    0.173
     12  979               1.13           0.899                 95.1              0.951 [-69.0, 67.5]                          0.96            False                    0.212
 pooled 7888               1.10           0.918                 87.6              0.915 [-71.5, 75.0]                          0.99            False                    0.229

duration and magnitude part: pooled True, subjects 12 of 12
angle part: pooled False, subjects 0 of 12
Variant, reading a (all events):
 share under 2 s 0.917 ; under 200 px 0.915 ; pooled angle bimodal at +-90: False [-71.5, 75.0]
In [24]:
fig, axes = plt.subplots(1, 3, figsize=(12, 3))
for sub, g in E.groupby("subject"):
    axes[0].hist(g.duration, bins=np.linspace(0, 4, 41), histtype="step", density=True)
    axes[1].hist(g.magnitude, bins=np.linspace(0, 700, 71), histtype="step", density=True)
    axes[2].plot(grid, gaussian_kde(g.angle, bw_method="scott")(grid), lw=1)
axes[0].set_xlabel("reach duration (s)"); axes[1].set_xlabel("reach magnitude (pixels)"); axes[2].set_xlabel("reach angle (deg, +90 up)")
plt.tight_layout(); plt.show()
print("Plotted ranges: duration", round(E.duration.min(), 2), "-", round(E.duration.max(), 2), "s; magnitude",
      round(E.magnitude.min(), 1), "-", round(E.magnitude.max(), 1), "px (none outside the axes)")
No description has been provided for this image
Plotted ranges: duration 0.23 - 3.93 s; magnitude 3.9 - 680.6 px (none outside the axes)
In [25]:
# Sensitivity, not the criterion: how far a Gaussian KDE without boundary correction pulls peaks
# in from the ends of a bounded range. Synthetic folded angles whose density peaks exactly at
# +-90 (90 minus a half-normal of SD 25 degrees, either sign), and the same KDE with the data
# reflected at -90 and +90 (a standard boundary correction).
rng_kde = np.random.default_rng(2)
def kde_peaks(a, reflect=False):
    data = np.r_[a, -180 - a, 180 - a] if reflect else a
    kde = gaussian_kde(data, bw_method="scott")
    if reflect:
        kde.set_bandwidth(kde.factor * (len(data) / len(a)) ** 0.2)   # Scott's bandwidth of the original n
    dens = kde(grid)
    peaks = [i for i in range(1, len(grid) - 1) if dens[i] > dens[i - 1] and dens[i] >= dens[i + 1]]
    peaks += [i for i, j in [(0, 1), (len(grid) - 1, len(grid) - 2)] if dens[i] > dens[j]]
    return sorted(float(v) for v in np.round(grid[sorted(peaks, key=lambda i: -dens[i])[:2]], 1))
for n in [250, 900]:
    syn = np.sign(rng_kde.random(n) - 0.5) * (90 - np.abs(rng_kde.normal(0, 25, n)))
    syn = np.clip(syn, -90, 90)
    print(f"synthetic, n = {n}: Scott KDE peaks {kde_peaks(syn)}; reflected KDE peaks {kde_peaks(syn, True)}")
rows = []
for sub, g in list(E.groupby("subject")) + [("pooled", E)]:
    pk = kde_peaks(g.angle.values, True)
    rows.append({"subject": sub, "criterion_KDE_peaks": kde_peaks(g.angle.values), "reflected_KDE_peaks": pk,
                 "reflected_within_15_of_pm90": len(pk) == 2 and pk[0] <= -75 and pk[1] >= 75})
kr = pd.DataFrame(rows)
print(kr.to_string(index=False))
print("Reflected KDE: two highest maxima within 15 degrees of -90 and +90 in",
      int(kr[kr.subject != "pooled"].reflected_within_15_of_pm90.sum()), "of 12 subjects; pooled",
      bool(kr[kr.subject == "pooled"].reflected_within_15_of_pm90.iloc[0]))
synthetic, n = 250: Scott KDE peaks [-72.5, 70.0]; reflected KDE peaks [-90.0, 89.5]
synthetic, n = 900: Scott KDE peaks [-73.5, 74.0]; reflected KDE peaks [-90.0, 90.0]
subject criterion_KDE_peaks reflected_KDE_peaks  reflected_within_15_of_pm90
     01       [-71.0, 75.5]       [-90.0, 90.0]                         True
     02              [40.0]              [90.0]                        False
     03       [-51.0, 71.0]              [90.0]                        False
     04              [68.0]              [90.0]                        False
     05       [-54.0, 63.5]              [90.0]                        False
     06       [-63.5, 71.0]              [90.0]                        False
     07       [-71.0, 70.5]              [90.0]                        False
     08       [-66.0, 71.0]       [-90.0, 90.0]                         True
     09       [-60.5, 62.5]       [-89.0, 89.5]                         True
     10       [-62.0, 66.0]       [-90.0, 90.0]                         True
     11       [-73.0, 74.5]       [-90.0, 90.0]                         True
     12       [-69.0, 67.5]       [-90.0, 90.0]                         True
 pooled       [-71.5, 75.0]       [-90.0, 90.0]                         True
Reflected KDE: two highest maxima within 15 degrees of -90 and +90 in 6 of 12 subjects; pooled True

Result: partially reproduced. More than half of the reaches last under 2 s and cover under 200 pixels pooled (0.918 and 0.915) and in all 12 subjects. The angle part does not hold: the two highest maxima of the angle density lie at -71.5 and 75.0 degrees pooled, and within 15 degrees of +-90 in no subject (S02 and S04 have a single maximum, and in S03, S06 and S07 the density at 0 exceeds the lower peak); 22.9% of reaches lie within 30 degrees of horizontal. With a KDE reflected at -90 and +90 (a sensitivity output, not the criterion), the two highest maxima lie within 15 degrees of +-90 pooled and in 6 of 12 subjects, not more than half. On synthetic angles whose density peaks at +-90 the criterion's KDE puts the peaks at -72.5 and 70.0 (n = 250) and at -73.5 and 74.0 degrees (n = 900), so part of the shortfall comes from the KDE's boundary bias.

Claim fig2-bimanual-skew¶

Bimanual ratio and bimanual overlap are skewed toward unimanual movement of the contralateral arm, less so for subjects 02, 04 and 05, while the bimanual class is mostly bimanual.

In [26]:
def bim_table(E):
    rows = []
    for sub, g in list(E.groupby("subject")) + [("pooled", E)]:
        rows.append({"subject": sub, "median_ratio": round(g.bimanual_ratio.median(), 3),
                     "ratio_skewed": g.bimanual_ratio.median() < 0.5,
                     "overlap_skewness": round(stats.skew(g.bimanual_overlap), 3),
                     "overlap_skewed": stats.skew(g.bimanual_overlap) > 0,
                     "share_class_bimanual": round(g.bimanual_class.mean(), 3),
                     "class_mostly_bimanual": g.bimanual_class.mean() > 0.5})
    return pd.DataFrame(rows)
for label, E_ in [("b", ev[ev.keep_b]), ("a", ev)]:
    bt = bim_table(E_)
    subj = bt[bt.subject != "pooled"]
    pool = bt[bt.subject == "pooled"].iloc[0]
    top_ratio = subj.sort_values("median_ratio", ascending=False).subject.head(5).tolist()
    low_skew = subj.sort_values("overlap_skewness").subject.head(5).tolist()
    named = all(s in top_ratio for s in ["02", "04", "05"]) and all(s in low_skew for s in ["02", "04", "05"])
    print(f"Reading {label}")
    print(bt.to_string(index=False))
    print(f"ratio part: pooled {pool.ratio_skewed}, subjects {int(subj.ratio_skewed.sum())}/12; overlap part: pooled "
          f"{pool.overlap_skewed}, subjects {int(subj.overlap_skewed.sum())}/12; class part: pooled {pool.class_mostly_bimanual}, "
          f"subjects {int(subj.class_mostly_bimanual.sum())}/12")
    print(f"five highest median ratios {top_ratio}; five lowest overlap skewness {low_skew}; S02, S04, S05 in both: {named}\n")
Reading b
subject  median_ratio  ratio_skewed  overlap_skewness  overlap_skewed  share_class_bimanual  class_mostly_bimanual
     01         0.103          True             1.629            True                 0.643                   True
     02         0.283          True             0.670            True                 0.876                   True
     03         0.206          True             0.906            True                 0.783                   True
     04         0.380          True             0.911            True                 0.888                   True
     05         0.300          True             0.662            True                 0.882                   True
     06         0.095          True             1.011            True                 0.812                   True
     07         0.308          True             0.611            True                 0.815                   True
     08         0.137          True             1.250            True                 0.688                   True
     09         0.108          True             1.307            True                 0.640                   True
     10         0.143          True             1.061            True                 0.732                   True
     11         0.078          True             1.189            True                 0.705                   True
     12         0.023          True             1.506            True                 0.507                   True
 pooled         0.136          True             1.114            True                 0.725                   True
ratio part: pooled True, subjects 12/12; overlap part: pooled True, subjects 12/12; class part: pooled True, subjects 12/12
five highest median ratios ['04', '07', '05', '02', '03']; five lowest overlap skewness ['07', '05', '02', '03', '04']; S02, S04, S05 in both: True

Reading a
subject  median_ratio  ratio_skewed  overlap_skewness  overlap_skewed  share_class_bimanual  class_mostly_bimanual
     01         0.105          True             1.621            True                 0.648                   True
     02         0.283          True             0.656            True                 0.872                   True
     03         0.209          True             0.900            True                 0.785                   True
     04         0.383          True             0.908            True                 0.890                   True
     05         0.297          True             0.640            True                 0.884                   True
     06         0.093          True             1.017            True                 0.810                   True
     07         0.302          True             0.600            True                 0.811                   True
     08         0.140          True             1.280            True                 0.690                   True
     09         0.108          True             1.307            True                 0.640                   True
     10         0.145          True             1.022            True                 0.742                   True
     11         0.078          True             1.196            True                 0.701                   True
     12         0.023          True             1.498            True                 0.509                   True
 pooled         0.137          True             1.110            True                 0.726                   True
ratio part: pooled True, subjects 12/12; overlap part: pooled True, subjects 12/12; class part: pooled True, subjects 12/12
five highest median ratios ['04', '07', '05', '02', '03']; five lowest overlap skewness ['07', '05', '02', '03', '04']; S02, S04, S05 in both: True

Result: reproduced. The median bimanual ratio is below 0.5 and the overlap skewness positive pooled and in all 12 subjects, the class is bimanual for more than half of the events pooled (0.725) and in all 12, and S02, S04 and S05 are among the five subjects with the highest median ratio and among the five with the lowest overlap skewness, under both event sets.

Claim extfig2-1c-contralateral-larger¶

Across all 12 subjects, the median displacement of the contralateral wrist after movement onset is substantially greater than that of the ipsilateral wrist, confirming that event detection mainly picked contralateral movements.

In [27]:
t_pose = np.round(np.arange(91) / ajile.POSE_HZ + ajile.POSE_WIN[0], 3)
post = (t_pose >= 0) & (t_pose <= 1.5)
def disp(tr, reading):
    base = np.nanmean(tr[:, :16], 1) if reading == "a" else tr[:, 45]   # -1.5 to -1 s, or onset
    return np.linalg.norm(tr - base[:, None], axis=2)
rows = []
for sub in SUBJECTS:
    ss = [s for s in sessions if s["subject"] == sub]
    contra = "R_Wrist" if ss[0]["reach_event_desc"] == "r_wrist" else "L_Wrist"
    ipsi = "L_Wrist" if contra == "R_Wrist" else "R_Wrist"
    keep = np.concatenate([ev[(ev.subject == sub) & (ev.day == s["day"])].keep_b.values for s in ss])
    row = {"subject": sub, "contra": contra}
    for reading in ["a", "b"]:
        c = np.concatenate([disp(s["wrist"][contra], reading) for s in ss])[keep]
        i_ = np.concatenate([disp(s["wrist"][ipsi], reading) for s in ss])[keep]
        cm, im = np.nanmedian(c, 0)[post].max(), np.nanmedian(i_, 0)[post].max()
        row[f"{reading}_contra_peak_px"] = round(cm, 1)
        row[f"{reading}_ipsi_peak_px"] = round(im, 1)
        row[f"{reading}_ratio"] = round(cm / im, 2)
    rows.append(row)
cw = pd.DataFrame(rows)
print(cw.to_string(index=False))
for r in ["a", "b"]:
    print(f"reading {r}: contralateral peak larger in {(cw[f'{r}_contra_peak_px'] > cw[f'{r}_ipsi_peak_px']).sum()} of 12; "
          f"ratio min {cw[f'{r}_ratio'].min()}, median {cw[f'{r}_ratio'].median()}")
subject  contra  a_contra_peak_px  a_ipsi_peak_px  a_ratio  b_contra_peak_px  b_ipsi_peak_px  b_ratio
     01 R_Wrist              71.5             9.0     7.93              69.8             6.7    10.44
     02 L_Wrist              60.2            35.8     1.68              60.8            35.2     1.73
     03 R_Wrist              63.4            22.4     2.83              62.4            19.1     3.28
     04 L_Wrist              55.0            49.2     1.12              53.0            40.3     1.32
     05 L_Wrist              51.7            44.7     1.15              51.7            48.1     1.08
     06 R_Wrist              79.8            11.7     6.81              79.1            10.1     7.86
     07 L_Wrist              50.2            22.6     2.22              47.1            19.3     2.44
     08 L_Wrist             150.3            21.1     7.13             143.7            16.0     8.98
     09 R_Wrist              38.7             7.0     5.49              38.7             4.9     7.87
     10 R_Wrist              68.5            22.0     3.11              64.9            15.1     4.29
     11 R_Wrist              60.4            10.8     5.60              59.2             8.0     7.37
     12 R_Wrist              88.2             2.3    37.81              84.4             2.0    42.01
reading a: contralateral peak larger in 12 of 12; ratio min 1.12, median 4.3
reading b: contralateral peak larger in 12 of 12; ratio min 1.08, median 5.83

Result: reproduced. The peak of the median contralateral displacement exceeds the ipsilateral one in all 12 subjects under both readings of the rest position (ratios 1.12 to 37.8 under reading a, 1.08 to 42.0 under reading b). In S04 and S05 the two are close (ratios 1.08 to 1.32).

Claim extfig2-2-feature-correlations¶

Over all events, reach magnitude correlates with reach duration (r = 0.26) and onset speed (r = 0.56), reach duration with bimanual overlap (r = 0.48), and the bimanual features with one another (overlap and ratio 0.51, class and ratio 0.50, overlap and class 0.61).

In [28]:
PAIRS = [("magnitude", "duration", 0.26), ("magnitude", "speed", 0.56), ("duration", "bimanual_overlap", 0.48),
         ("bimanual_overlap", "bimanual_ratio", 0.51), ("bimanual_class", "bimanual_ratio", 0.50),
         ("bimanual_overlap", "bimanual_class", 0.61)]
rows = []
for label, E_ in [("b", ev[ev.keep_b]), ("a", ev)]:
    corr = E_[FEATURES].corr()
    for x, y, paper in PAIRS:
        r = corr.loc[x, y]
        rows.append({"reading": label, "pair": f"{x} - {y}", "r": round(r, 3), "paper": paper,
                     "within_10pct": abs(r - paper) <= 0.1 * paper + 1e-9})
cr = pd.DataFrame(rows)
print(cr.to_string(index=False))
print("Within tolerance:", cr.groupby("reading").within_10pct.sum().to_dict(), "of 6")
print("\nPer subject, reading b (r):")
print(pd.DataFrame({f"{x}-{y}": ev[ev.keep_b].groupby("subject").apply(lambda g: g[x].corr(g[y])).round(2)
                    for x, y, _ in PAIRS}).to_string())
reading                              pair     r  paper  within_10pct
      b              magnitude - duration 0.233   0.26         False
      b                 magnitude - speed 0.604   0.56          True
      b       duration - bimanual_overlap 0.503   0.48          True
      b bimanual_overlap - bimanual_ratio 0.502   0.51          True
      b   bimanual_class - bimanual_ratio 0.494   0.50          True
      b bimanual_overlap - bimanual_class 0.599   0.61          True
      a              magnitude - duration 0.231   0.26         False
      a                 magnitude - speed 0.609   0.56          True
      a       duration - bimanual_overlap 0.505   0.48          True
      a bimanual_overlap - bimanual_ratio 0.501   0.51          True
      a   bimanual_class - bimanual_ratio 0.494   0.50          True
      a bimanual_overlap - bimanual_class 0.598   0.61          True
Within tolerance: {'a': 5, 'b': 5} of 6

Per subject, reading b (r):
         magnitude-duration  magnitude-speed  duration-bimanual_overlap  bimanual_overlap-bimanual_ratio  bimanual_class-bimanual_ratio  bimanual_overlap-bimanual_class
subject                                                                                                                                                                 
01                     0.31             0.51                       0.51                             0.58                           0.54                             0.61
02                     0.22             0.55                       0.68                             0.32                           0.38                             0.48
03                     0.19             0.56                       0.54                             0.50                           0.47                             0.56
04                     0.27             0.54                       0.71                             0.35                           0.41                             0.47
05                     0.29             0.57                       0.66                             0.37                           0.38                             0.46
06                     0.34             0.40                       0.59                             0.49                           0.37                             0.51
07                     0.35             0.56                       0.46                             0.51                           0.52                             0.59
08                     0.21             0.56                       0.58                             0.52                           0.52                             0.61
09                     0.37             0.48                       0.36                             0.59                           0.52                             0.63
10                     0.34             0.51                       0.53                             0.48                           0.47                             0.62
11                     0.20             0.54                       0.49                             0.43                           0.46                             0.60
12                     0.31             0.41                       0.31                             0.63                           0.56                             0.68

Result: partially reproduced. Five of the six correlations are within tolerance (0.604, 0.503, 0.502, 0.494, 0.599); reach magnitude and duration give r = 0.233, just below the tolerance of 0.26 +- 0.026, under both event sets (0.231 with all events).

Claim fig2-days-and-waking¶

Reach counts were fairly even across recording days except for subjects 04, 05 and 09, each with one day holding most events, and events occurred mostly during waking hours.

In [29]:
for label, E_ in [("b", ev[ev.keep_b]), ("a", ev)]:
    per_day = E_.groupby(["subject", "day"]).size().unstack(fill_value=0)
    busiest = (per_day.max(1) / per_day.sum(1)).round(3)
    awake = E_.groupby("subject").hour.apply(lambda h: (h >= 8).mean()).round(3)
    out = pd.DataFrame({"busiest_day_share": busiest, "share_08_24h": awake})
    print(f"Reading {label}\n", per_day.to_string(), "\n", out.T.to_string())
    over = out.index[out.busiest_day_share > 0.5].tolist()
    print(f"subjects whose busiest day holds more than half: {over}; named 04, 05, 09; "
          f"waking part (more than half at 08-24 h) holds in {(out.share_08_24h > 0.5).sum()} of 12\n")
Reading b
 day        3    4    5    6    7
subject                         
01       154  194  194    0  190
02        51   93   79   75    0
03       198  193  137  109    0
04        35   97   43   81  156
05        56   48    0    0  159
06       164  191  193  186  177
07        93  110  197  194  190
08       193  191  172  193  198
09        15   18  109   38   31
10       176  154  108  129  179
11       197  192  192  197  190
12       197  197  194  197  194 
 subject               01     02     03     04     05     06     07     08     09     10     11     12
busiest_day_share  0.265  0.312  0.311  0.379  0.605  0.212  0.251  0.209  0.517  0.240  0.204  0.201
share_08_24h       0.964  0.641  0.708  0.852  0.833  0.902  0.889  0.907  0.839  0.866  0.793  0.854
subjects whose busiest day holds more than half: ['05', '09']; named 04, 05, 09; waking part (more than half at 08-24 h) holds in 12 of 12

Reading a
 day        3    4    5    6    7
subject                         
01       156  196  199    0  190
02        51   94   82   78    0
03       198  193  137  114    0
04        35   98   43   82  159
05        56   48    0    0  163
06       166  199  193  198  200
07        93  112  199  197  199
08       197  197  173  198  200
09        15   18  109   38   31
10       184  154  112  157  199
11       199  194  195  198  196
12       200  200  200  197  199 
 subject               01     02     03     04     05     06     07     08     09     10     11     12
busiest_day_share  0.269  0.308  0.308  0.381  0.610  0.209  0.249  0.207  0.517  0.247  0.203  0.201
share_08_24h       0.961  0.639  0.710  0.854  0.835  0.899  0.888  0.906  0.839  0.867  0.796  0.853
subjects whose busiest day holds more than half: ['05', '09']; named 04, 05, 09; waking part (more than half at 08-24 h) holds in 12 of 12

/tmp/ipykernel_2311/1511546009.py:3: Pandas4Warning: Starting with pandas version 4.0 all arguments of max will be keyword-only.
  busiest = (per_day.max(1) / per_day.sum(1)).round(3)
/tmp/ipykernel_2311/1511546009.py:3: Pandas4Warning: Starting with pandas version 4.0 all arguments of sum will be keyword-only.
  busiest = (per_day.max(1) / per_day.sum(1)).round(3)
/tmp/ipykernel_2311/1511546009.py:3: Pandas4Warning: Starting with pandas version 4.0 all arguments of max will be keyword-only.
  busiest = (per_day.max(1) / per_day.sum(1)).round(3)
/tmp/ipykernel_2311/1511546009.py:3: Pandas4Warning: Starting with pandas version 4.0 all arguments of sum will be keyword-only.
  busiest = (per_day.max(1) / per_day.sum(1)).round(3)

Result: partially reproduced. One day holds more than half of the events for S05 (0.605) and S09 (0.517) and for no other subject, but not for S04, whose busiest day holds 0.379. More than half of the events fall at 08 to 24 h in all 12 subjects (0.641 to 0.964), so the waking part holds.

Claim fig3-group-lfb-decrease-hfb-increase¶

At the group level, low-frequency power decreases and high-frequency power increases at movement initiation in several cortical regions, as in controlled movement experiments.

In [30]:
rng_fig3 = np.random.default_rng(3)
keep = ev.keep_b.values
subj_med = np.stack([np.median(spec[np.nonzero(keep & (ev.subject.values == sub))[0]], axis=0) for sub in SUBJECTS])
base_i = ti(-1.5, -1)
group = subj_med.mean(0)
subj_c = subj_med - np.median(group[..., base_i], axis=-1, keepdims=True)[None]     # plot_specs_group
masked = np.stack([ajile.boot_sig_mask(np.moveaxis(subj_c[:, r], 0, -1), base_i, rng_fig3) for r in range(8)])
unmasked = subj_c.mean(0)
LF34 = np.nonzero((FREQS >= 4) & (FREQS <= 30))[0]
HF50 = np.nonzero((FREQS >= 50) & (FREQS <= 120))[0]
t_a, t_b = ti(0, 0.5), np.array([np.argmin(np.abs(TIMES))])
rows = []
for r, name in enumerate(ajile.ROI_NAMES):
    row = {"region": name}
    for lab, tt in [("a_0-0.5s", t_a), ("b_t0", t_b)]:
        row[f"{lab}_LF4-30"] = round(float(masked[r][LF34][:, tt].mean()), 3)
        row[f"{lab}_HF50-120"] = round(float(masked[r][HF50][:, tt].mean()), 3)
    row["unmasked_a_LF"] = round(float(unmasked[r][LF34][:, t_a].mean()), 3)
    row["unmasked_a_HF"] = round(float(unmasked[r][HF50][:, t_a].mean()), 3)
    row["significant_bins"] = int((masked[r] != 0).sum())
    rows.append(row)
f3 = pd.DataFrame(rows)
print(f3.to_string(index=False))
named = ["precentral", "postcentral", "inferior parietal"]
for lab in ["a_0-0.5s", "b_t0"]:
    holds = f3[f3.region.isin(named)].apply(lambda r: r[f"{lab}_LF4-30"] < 0 and r[f"{lab}_HF50-120"] > 0, axis=1)
    print(f"reading {lab}: pattern holds in {int(holds.sum())} of 3 named regions",
          dict(zip(named, holds.values)))
print("Regions with the pattern under reading a:",
      f3[(f3["a_0-0.5s_LF4-30"] < 0) & (f3["a_0-0.5s_HF50-120"] > 0)].region.tolist())
           region  a_0-0.5s_LF4-30  a_0-0.5s_HF50-120  b_t0_LF4-30  b_t0_HF50-120  unmasked_a_LF  unmasked_a_HF  significant_bins
   middle frontal           -0.405              0.223       -0.363          0.215         -0.405          0.223              1436
       precentral           -0.885              0.496       -0.748          0.460         -0.885          0.496              1353
      postcentral           -0.890              0.507       -0.742          0.477         -0.890          0.507              1434
inferior parietal           -0.663              0.277       -0.592          0.278         -0.663          0.277              1337
    supramarginal           -0.304              0.014       -0.201          0.000         -0.304          0.049               700
superior temporal           -0.143             -0.003       -0.114         -0.007         -0.156         -0.008               380
  middle temporal           -0.005              0.003        0.000          0.004         -0.027          0.011               233
inferior temporal            0.000              0.012        0.000          0.006         -0.011          0.034               205
reading a_0-0.5s: pattern holds in 3 of 3 named regions {'precentral': np.True_, 'postcentral': np.True_, 'inferior parietal': np.True_}
reading b_t0: pattern holds in 3 of 3 named regions {'precentral': np.True_, 'postcentral': np.True_, 'inferior parietal': np.True_}
Regions with the pattern under reading a: ['middle frontal', 'precentral', 'postcentral', 'inferior parietal', 'supramarginal', 'middle temporal']
In [31]:
fig, axes = plt.subplots(2, 4, figsize=(13, 5), sharex=True, sharey=True)
tsel = ti(-1.5, 1.5)
for r, ax in enumerate(axes.ravel()):
    im = ax.pcolormesh(TIMES[tsel], FREQS, masked[r][:, tsel], cmap="RdBu_r", vmin=-1, vmax=1, shading="nearest")
    ax.axvline(0, color="k", lw=1)
    ax.set_title(ajile.ROI_NAMES[r], fontsize=9)
axes[1, 0].set_xlabel("time (s)"); axes[1, 0].set_ylabel("frequency (Hz)")
fig.colorbar(im, ax=axes, label="dB (masked)")
plt.show()
print("masked values shown, -1.5 to 1.5 s: range", round(float(masked[..., tsel].min()), 2), "to",
      round(float(masked[..., tsel].max()), 2), "dB; values beyond +-1 dB:", int((np.abs(masked[..., tsel]) > 1).sum()))
No description has been provided for this image
masked values shown, -1.5 to 1.5 s: range -1.31 to 0.7 dB; values beyond +-1 dB: 53

Result: reproduced. After masking, the mean over 4-30 Hz is negative and over 50-120 Hz positive in precentral (-0.885 and 0.496 dB), postcentral (-0.890, 0.507) and inferior parietal (-0.663, 0.277) over 0 to 0.5 s, and also at the time bin of onset (reading b). Over 0 to 0.5 s, middle frontal, supramarginal and middle temporal show the same pattern (middle temporal only weakly, -0.005 and +0.003 dB); at the onset bin supramarginal's high-frequency value and middle temporal's low-frequency value are 0.000, so for those two it holds only over 0 to 0.5 s.

Claim fig3-sensorimotor-largest¶

Spectral power changes are largest in precentral, postcentral and inferior parietal regions, and the three temporal regions show minimal movement-related changes.

In [32]:
temporal = ["superior temporal", "middle temporal", "inferior temporal"]
def check_rank(vals):
    order = list(pd.Series(vals).sort_values(ascending=False).index)
    top3 = set(order[:3]) == set(named)
    temp_below = all(vals[t] < min(vals[n] for n in named) for t in temporal)
    return order, top3, temp_below, sum(n in order[:3] for n in named)
res = {}
va = {n: float(np.abs(masked[r][:, t_a]).mean()) for r, n in enumerate(ajile.ROI_NAMES)}
vc = {n: float(np.abs(masked[r][:, ti(-0.5, 0.5)]).mean()) for r, n in enumerate(ajile.ROI_NAMES)}
vl = {n: float(np.abs(masked[r][LF34][:, t_a]).mean()) for r, n in enumerate(ajile.ROI_NAMES)}
vh = {n: float(np.abs(masked[r][HF50][:, t_a]).mean()) for r, n in enumerate(ajile.ROI_NAMES)}
print(pd.DataFrame({"a_all_freqs_0-0.5": va, "b_LF": vl, "b_HF": vh, "c_all_freqs_-0.5-0.5": vc}).round(3).to_string())
for lab, v in [("a", va), ("c", vc)]:
    order, top3, tb, k = check_rank(v)
    print(f"reading {lab}: order {order}; named three are the top three {top3} ({k} of 3); temporal below all three {tb}")
ol, tl, tbl, kl = check_rank(vl)
oh, th, tbh, kh = check_rank(vh)
print(f"reading b: LF order {ol}\n           HF order {oh}\n  top three in both {tl and th} (LF {kl}/3, HF {kh}/3); "
      f"temporal below all three in both {tbl and tbh}")
                   a_all_freqs_0-0.5   b_LF   b_HF  c_all_freqs_-0.5-0.5
middle frontal                 0.236  0.405  0.223                 0.167
precentral                     0.512  0.885  0.496                 0.354
postcentral                    0.523  0.890  0.507                 0.368
inferior parietal              0.336  0.663  0.277                 0.247
supramarginal                  0.093  0.304  0.017                 0.072
superior temporal              0.039  0.143  0.003                 0.037
middle temporal                0.004  0.005  0.005                 0.011
inferior temporal              0.009  0.000  0.012                 0.007
reading a: order ['postcentral', 'precentral', 'inferior parietal', 'middle frontal', 'supramarginal', 'superior temporal', 'inferior temporal', 'middle temporal']; named three are the top three True (3 of 3); temporal below all three True
reading c: order ['postcentral', 'precentral', 'inferior parietal', 'middle frontal', 'supramarginal', 'superior temporal', 'middle temporal', 'inferior temporal']; named three are the top three True (3 of 3); temporal below all three True
reading b: LF order ['postcentral', 'precentral', 'inferior parietal', 'middle frontal', 'supramarginal', 'superior temporal', 'middle temporal', 'inferior temporal']
           HF order ['postcentral', 'precentral', 'inferior parietal', 'middle frontal', 'supramarginal', 'inferior temporal', 'middle temporal', 'superior temporal']
  top three in both True (LF 3/3, HF 3/3); temporal below all three in both True

Result: reproduced. Under all three readings, postcentral, precentral and inferior parietal are the three regions with the largest mean absolute masked power, and the three temporal regions are below all of them (for example reading a: 0.523, 0.512, 0.336 dB against at most 0.039 for the temporal regions).

Claim fig3-lfb-more-widespread¶

Low-frequency power decreases are more spatially widespread than high-frequency increases and are also present in supramarginal and superior temporal regions.

In [33]:
neg_lf = {n: int((masked[r][LF34][:, t_a] < 0).sum()) for r, n in enumerate(ajile.ROI_NAMES)}
pos_hf = {n: int((masked[r][HF50][:, t_a] > 0).sum()) for r, n in enumerate(ajile.ROI_NAMES)}
print(pd.DataFrame({"significant negative 4-30 Hz bins": neg_lf, "significant positive 50-120 Hz bins": pos_hf}).to_string())
a_lf, a_hf = sum(v > 0 for v in neg_lf.values()), sum(v > 0 for v in pos_hf.values())
b_lf, b_hf = sum(neg_lf.values()) / len(LF34), sum(pos_hf.values()) / len(HF50)
print(f"reading a: regions with LF decreases {a_lf}, with HF increases {a_hf}; LF larger {a_lf > a_hf}")
print(f"reading b: LF bins per frequency {b_lf:.2f}, HF bins per frequency {b_hf:.2f}; LF larger {b_lf > b_hf}")
print("supramarginal and superior temporal have LF decreases:", neg_lf["supramarginal"] > 0, neg_lf["superior temporal"] > 0)
                   significant negative 4-30 Hz bins  significant positive 50-120 Hz bins
middle frontal                                    30                                   84
precentral                                        30                                   84
postcentral                                       30                                   84
inferior parietal                                 30                                   84
supramarginal                                     30                                   12
superior temporal                                 24                                    0
middle temporal                                    2                                    4
inferior temporal                                  0                                   10
reading a: regions with LF decreases 7, with HF increases 7; LF larger False
reading b: LF bins per frequency 35.20, HF bins per frequency 25.86; LF larger True
supramarginal and superior temporal have LF decreases: True True
In [34]:
# Seed stability of the bootstrap mask: the same masks with ten other seeds.
rows = []
for seed in range(10):
    m_ = np.stack([ajile.boot_sig_mask(np.moveaxis(subj_c[:, r], 0, -1), base_i, np.random.default_rng(100 + seed))
                   for r in range(8)])
    nl = [int((m_[r][LF34][:, t_a] < 0).sum()) for r in range(8)]
    ph = [int((m_[r][HF50][:, t_a] > 0).sum()) for r in range(8)]
    pattern = [bool(m_[r][LF34][:, t_a].mean() < 0 and m_[r][HF50][:, t_a].mean() > 0) for r in range(8)]
    rows.append({"seed": 100 + seed, **{f"LF-:{n[:12]}": v for n, v in zip(ajile.ROI_NAMES, nl)},
                 **{f"HF+:{n[:12]}": v for n, v in zip(ajile.ROI_NAMES, ph)},
                 "a_LF_regions": sum(v > 0 for v in nl), "a_HF_regions": sum(v > 0 for v in ph),
                 "b_LF_per_f": round(sum(nl) / len(LF34), 2), "b_HF_per_f": round(sum(ph) / len(HF50), 2),
                 "fig3_pattern_in_named_3": sum(pattern[REG[n]] for n in named)})
sd = pd.DataFrame(rows)
print(sd.T.to_string())
print("Reading a, low-frequency regions more than high-frequency in", int((sd.a_LF_regions > sd.a_HF_regions).sum()),
      "of 10 seeds, equal in", int((sd.a_LF_regions == sd.a_HF_regions).sum()), "; reading b, low larger in",
      int((sd.b_LF_per_f > sd.b_HF_per_f).sum()), "of 10; supramarginal and superior temporal low-frequency decreases in",
      int(((sd["LF-:supramargina"] > 0) & (sd["LF-:superior tem"] > 0)).sum()), "of 10; fig3 pattern in all 3 named regions in",
      int((sd.fig3_pattern_in_named_3 == 3).sum()), "of 10")
                              0       1       2       3       4       5       6       7      8       9
seed                     100.00  101.00  102.00  103.00  104.00  105.00  106.00  107.00  108.0  109.00
LF-:middle front          30.00   30.00   30.00   30.00   30.00   30.00   30.00   30.00   30.0   30.00
LF-:precentral            30.00   30.00   30.00   30.00   30.00   30.00   30.00   30.00   30.0   30.00
LF-:postcentral           30.00   30.00   30.00   30.00   30.00   30.00   30.00   30.00   30.0   30.00
LF-:inferior par          30.00   30.00   30.00   30.00   30.00   30.00   30.00   30.00   30.0   30.00
LF-:supramargina          30.00   30.00   30.00   30.00   30.00   30.00   30.00   30.00   30.0   30.00
LF-:superior tem          24.00   24.00   25.00   25.00   25.00   24.00   24.00   24.00   24.0   24.00
LF-:middle tempo           2.00    3.00    3.00    3.00    3.00    1.00    3.00    2.00    3.0    1.00
LF-:inferior tem           0.00    0.00    0.00    0.00    0.00    0.00    0.00    0.00    0.0    0.00
HF+:middle front          84.00   84.00   84.00   84.00   84.00   84.00   84.00   84.00   84.0   84.00
HF+:precentral            84.00   84.00   84.00   84.00   84.00   84.00   84.00   84.00   84.0   84.00
HF+:postcentral           84.00   84.00   84.00   84.00   84.00   84.00   84.00   84.00   84.0   84.00
HF+:inferior par          84.00   84.00   84.00   84.00   84.00   84.00   84.00   84.00   84.0   84.00
HF+:supramargina          11.00   11.00   12.00   12.00   13.00   11.00   11.00   12.00   11.0   12.00
HF+:superior tem           0.00    0.00    0.00    0.00    0.00    0.00    0.00    0.00    0.0    0.00
HF+:middle tempo           4.00    3.00    4.00    3.00    3.00    4.00    4.00    4.00    4.0    3.00
HF+:inferior tem           8.00    9.00    9.00    7.00    9.00    8.00    8.00    7.00    6.0    9.00
a_LF_regions               7.00    7.00    7.00    7.00    7.00    7.00    7.00    7.00    7.0    7.00
a_HF_regions               7.00    7.00    7.00    7.00    7.00    7.00    7.00    7.00    7.0    7.00
b_LF_per_f                35.20   35.40   35.60   35.60   35.60   35.00   35.40   35.20   35.4   35.00
b_HF_per_f                25.64   25.64   25.79   25.57   25.79   25.64   25.64   25.64   25.5   25.71
fig3_pattern_in_named_3    3.00    3.00    3.00    3.00    3.00    3.00    3.00    3.00    3.0    3.00
Reading a, low-frequency regions more than high-frequency in 0 of 10 seeds, equal in 10 ; reading b, low larger in 10 of 10; supramarginal and superior temporal low-frequency decreases in 10 of 10; fig3 pattern in all 3 named regions in 10 of 10

Result: blocked (methods underspecified). The two readings disagree. Reading a counts 7 regions with low-frequency decreases and 7 with high-frequency increases (no difference); reading b gives 35.2 significant low-frequency bins per frequency against 25.9 high-frequency (low-frequency larger). Supramarginal and superior temporal both have significant 4-30 Hz decreases (30 and 24 bins). With ten other bootstrap seeds, reading a gives 7 against 7 regions every time and reading b 35.0 to 35.6 against 25.5 to 25.8 bins per frequency, so the readings disagree under every seed; supramarginal and superior temporal keep their low-frequency decreases and the pattern of fig3-group-lfb-decrease-hfb-increase holds in the three named regions under every seed.

Claim fig4-precentral-subject-variability¶

In the precentral region every subject shows the low/high-frequency pattern, but amplitudes and frequency bands vary; subjects 03, 06, 07, 08 and 11 have increases up to 120 Hz, subjects 09 and 12 mainly at 60-80 Hz, and subjects 04 and 08 have narrower low-frequency decreases.

In [35]:
pre = REG["precentral"]
sp4 = subj_med[:, pre] - subj_med[:, pre][..., base_i].mean(-1, keepdims=True)     # plot_specs_single_region
spectrum = pd.DataFrame(sp4[..., t_a].mean(-1), index=SUBJECTS, columns=FREQS)
print("Precentral spectrum, mean over 0-0.5 s (dB):")
print(spectrum.round(2).to_string())
lfb_i, hfb_i = (FREQS >= 8) & (FREQS <= 32), (FREQS >= 76) & (FREQS <= 100)
p1 = (spectrum.loc[:, lfb_i].mean(1) < 0) & (spectrum.loc[:, hfb_i].mean(1) > 0)
print("\n(1) LFB mean < 0 and HFB mean > 0:", p1.to_dict(), "->", bool(p1.all()))
p2 = {s: bool(spectrum.loc[s, 116] > 0 and spectrum.loc[s, 121] > 0) for s in ["03", "06", "07", "08", "11"]}
print("(2) 116 and 121 Hz positive:", p2, "->", all(p2.values()))
p3 = {}
for s in ["09", "12"]:
    hi = spectrum.loc[s, FREQS >= 56]
    peak_f = hi.idxmax()
    p3[s] = (int(peak_f), round(hi.max(), 3), round(spectrum.loc[s, (FREQS >= 101)].mean(), 3),
             bool(61 <= peak_f <= 76 and spectrum.loc[s, FREQS >= 101].mean() < hi.max() / 2))
print("(3) peak frequency, peak, mean 101-121 Hz, holds:", p3, "->", all(v[-1] for v in p3.values()))
low = spectrum.loc[:, FREQS <= 46]
width = {s: int((low.loc[s] < low.loc[s].min() / 2).sum()) for s in SUBJECTS}
fewest = sorted(width, key=lambda s: (width[s], s))[:3]
ties = sorted(width.values())[2]
print("(4) width of the decrease (1-46 Hz bins below half the most negative value):", width)
print("    three fewest:", fewest, "; third-smallest width", ties, "shared by",
      [s for s in SUBJECTS if width[s] == ties], "; S04 and S08 among them:", "04" in fewest and "08" in fewest)
# The bin count ties four subjects at 3 bins. Tie-break by the width in Hz of the run of the
# spectrum below half its minimum, around the minimum, with linear interpolation between bins.
def width_hz(v, f):
    m = int(np.argmin(v)); h = v[m] / 2
    lo = m
    while lo > 0 and v[lo - 1] < h:
        lo -= 1
    hi = m
    while hi < len(v) - 1 and v[hi + 1] < h:
        hi += 1
    left = f[lo] if lo == 0 else f[lo - 1] + (h - v[lo - 1]) / (v[lo] - v[lo - 1]) * (f[lo] - f[lo - 1])
    right = f[hi] if hi == len(v) - 1 else f[hi] + (h - v[hi]) / (v[hi + 1] - v[hi]) * (f[hi + 1] - f[hi])
    return right - left
whz = {s: round(width_hz(low.loc[s].values.astype(float), FREQS[FREQS <= 46].astype(float)), 1) for s in SUBJECTS}
fewest_hz = sorted(whz, key=lambda s: whz[s])[:3]
print("    width in Hz (interpolated):", whz, "\n    three narrowest:", fewest_hz,
      "; S04 and S08 among them:", "04" in fewest_hz and "08" in fewest_hz)
print("Parts holding:", int(p1.all()) + int(all(p2.values())) + int(all(v[-1] for v in p3.values())) +
      int("04" in fewest and "08" in fewest), "of 4")
Precentral spectrum, mean over 0-0.5 s (dB):
     1     6     11    16    21    26    31    36    41    46    51    56    61    66    71    76    81    86    91    96    101   106   111   116   121
01 -0.56 -1.12 -1.65 -2.18 -1.65 -1.14 -1.10 -0.95 -0.76 -0.58 -0.28 -0.18 -0.15 -0.03  0.01  0.04  0.06  0.10  0.10  0.05  0.16  0.11  0.17  0.10  0.04
02 -0.45 -0.49 -0.54 -0.86 -0.54 -0.43 -0.47 -0.16  0.15  0.32  0.06  0.15  0.12  0.31  0.24  0.36  0.15  0.17  0.38  0.35  0.29  0.37  0.02  0.31  0.42
03 -0.56 -1.25 -2.19 -2.91 -2.18 -1.09 -0.64 -0.32  0.05  0.26  0.45  0.76  1.04  1.20  1.27  1.36  1.43  1.42  1.51  1.56  1.61  1.43  1.35  1.40  1.22
04 -0.36 -0.50 -0.47 -0.22 -0.08  0.02  0.15  0.15  0.01  0.10  0.27  0.35  0.37  0.42  0.48  0.50  0.34  0.53  0.49  0.51  0.46  0.50  0.39  0.36  0.35
05 -0.17 -0.37 -0.84 -0.93 -0.56 -0.39 -0.24 -0.08 -0.02  0.02  0.14  0.17  0.25  0.24  0.31  0.24  0.22  0.18  0.34  0.45  0.34  0.11  0.21  0.31  0.25
06  1.20  0.33 -0.54 -1.23 -1.65 -1.46 -1.03 -0.24  0.34  0.50  0.61  0.88  1.25  1.53  1.63  1.66  1.76  1.88  1.86  1.71  1.68  1.63  1.67  1.62  1.50
07 -0.54 -1.01 -1.39 -1.26 -0.53 -0.21  0.13  0.42  0.66  0.85  1.02  1.14  1.09  1.21  1.19  1.16  1.16  1.12  1.24  1.20  1.16  1.14  1.10  1.11  1.05
08  0.20  0.08 -0.02 -0.02 -0.00 -0.16 -0.13  0.01  0.12  0.21  0.20  0.26  0.40  0.41  0.44  0.47  0.50  0.45  0.53  0.47  0.41  0.36  0.41  0.38  0.36
09 -0.61 -0.68 -0.60 -0.67 -0.32 -0.33 -0.01  0.10  0.34  0.25  0.17  0.23  0.02  0.37  0.35  0.27  0.17  0.17  0.03 -0.16  0.14  0.09  0.08 -0.04 -0.02
10 -0.65 -0.82 -0.63 -0.48 -0.36 -0.17 -0.15 -0.09 -0.06 -0.03  0.01  0.11  0.23  0.15  0.19  0.19  0.24  0.13  0.17  0.21  0.18  0.17  0.14  0.18  0.12
11 -0.79 -0.99 -1.79 -2.99 -3.29 -1.85 -0.68 -0.71 -0.62 -0.28  0.07  0.24  0.28  0.38  0.32  0.24  0.28  0.27  0.19  0.23  0.24  0.27  0.25  0.19  0.21
12 -0.40 -0.73 -0.92 -0.56 -0.47 -0.32 -0.18 -0.02 -0.01 -0.12 -0.02  0.24  0.28  0.29  0.27  0.13  0.13  0.09  0.18  0.10  0.07  0.09  0.08  0.03 -0.05

(1) LFB mean < 0 and HFB mean > 0: {'01': True, '02': True, '03': True, '04': True, '05': True, '06': True, '07': True, '08': True, '09': True, '10': True, '11': True, '12': True} -> True
(2) 116 and 121 Hz positive: {'03': True, '06': True, '07': True, '08': True, '11': True} -> True
(3) peak frequency, peak, mean 101-121 Hz, holds: {'09': (66, np.float32(0.373), np.float32(0.05), True), '12': (66, np.float32(0.289), np.float32(0.045), True)} -> True
(4) width of the decrease (1-46 Hz bins below half the most negative value): {'01': 6, '02': 6, '03': 3, '04': 3, '05': 3, '06': 4, '07': 3, '08': 2, '09': 4, '10': 4, '11': 4, '12': 4}
    three fewest: ['08', '03', '04'] ; third-smallest width 3 shared by ['03', '04', '05', '07'] ; S04 and S08 among them: True
    width in Hz (interpolated): {'01': np.float64(25.8), '02': np.float64(24.7), '03': np.float64(17.2), '04': np.float64(14.4), '05': np.float64(16.9), '06': np.float64(19.2), '07': np.float64(17.3), '08': np.float64(9.4), '09': np.float64(19.7), '10': np.float64(18.0), '11': np.float64(16.8), '12': np.float64(19.5)} 
    three narrowest: ['08', '04', '11'] ; S04 and S08 among them: True
Parts holding: 4 of 4
/tmp/ipykernel_2311/985419306.py:7: Pandas4Warning: Starting with pandas version 4.0 all arguments of mean will be keyword-only.
  p1 = (spectrum.loc[:, lfb_i].mean(1) < 0) & (spectrum.loc[:, hfb_i].mean(1) > 0)

Result: reproduced. All four parts hold: every subject has a negative LFB and positive HFB mean in precentral; S03, S06, S07, S08 and S11 are positive at 116 and 121 Hz; S09 and S12 peak at 66 Hz with the 101-121 Hz mean below half the peak; S08 has the narrowest decrease (2 bins, 9.4 Hz). S04 ties with S03, S05 and S07 at 3 bins; by the interpolated width S04 is second narrowest (14.4 Hz), so it is among the three.

Claim fig5-band-power-differs-across-subjects¶

Precentral LFB and HFB power in the 0.5 s after movement onset differs significantly across subjects.

In [36]:
E = ev[ev.keep_b]
for meas in ["mean", "median"]:
    for band in ["lfb", "hfb"]:
        col = f"roi_band:precentral:{band}_{meas}"
        h, p = stats.kruskal(*[g[col].values for _, g in E.groupby("subject")])
        print(f"band {meas}, {band.upper()}: Kruskal-Wallis H = {h:.1f}, p = {p:.3g}, n = {len(E)} events in 12 subjects")
band mean, LFB: Kruskal-Wallis H = 796.1, p = 1.31e-163, n = 7888 events in 12 subjects
band mean, HFB: Kruskal-Wallis H = 1262.0, p = 7.06e-264, n = 7888 events in 12 subjects
band median, LFB: Kruskal-Wallis H = 801.5, p = 9.09e-165, n = 7888 events in 12 subjects
band median, HFB: Kruskal-Wallis H = 1234.0, p = 7.79e-258, n = 7888 events in 12 subjects

Result: reproduced. Kruskal-Wallis across the 12 subjects gives p = 1.3e-163 (LFB) and 7.1e-264 (HFB) with the band mean, and p < 1e-150 with the code's median.

Claim table1-subject-band-power-ci¶

Each subject's precentral band power lies in the 95% bootstrap interval Table 1 gives; LFB power is below baseline and HFB power above it for most subjects.

In [37]:
TABLE1 = {"01": [(-1.87, -1.29), (0.03, 0.23)], "02": [(-1.12, -0.31), (0.07, 0.64)], "03": [(-2.11, -1.73), (1.39, 1.67)],
          "04": [(-0.17, 0.01), (0.32, 0.52)], "05": [(-0.7, -0.38), (0.2, 0.48)], "06": [(-1.63, -1.11), (2.02, 2.37)],
          "07": [(-0.84, -0.51), (1.14, 1.34)], "08": [(-0.3, 0.04), (0.36, 0.63)], "09": [(-0.57, -0.08), (-0.11, 0.23)],
          "10": [(-0.87, -0.35), (0.01, 0.3)], "11": [(-2.3, -1.86), (0.09, 0.34)], "12": [(-0.66, -0.44), (0.06, 0.2)]}
rng_t1 = np.random.default_rng(1)
rows, inside = [], {}
for sub in SUBJECTS:
    g = E[E.subject == sub]
    for bi_, band in enumerate(["lfb", "hfb"]):
        lo, hi = TABLE1[sub][bi_]
        row = {"subject": sub, "band": band.upper(), "paper_ci": f"{lo} to {hi}"}
        for bm in ["mean", "median"]:
            v = g[f"roi_band:precentral:{band}_{bm}"].values
            for stat_name, fn in [("mean", np.mean), ("median", np.median)]:
                est = fn(v)
                key = f"{stat_name}_of_band{bm}"
                row[key] = round(est, 3)
                inside.setdefault(key, []).append(lo <= est <= hi)
        v = g[f"roi_band:precentral:{band}_mean"].values
        boot = np.array([np.mean(v[rng_t1.integers(0, len(v), len(v))]) for _ in range(5000)])
        row["bootstrap_ci_mean_of_bandmean"] = f"{np.percentile(boot, 2.5):.2f} to {np.percentile(boot, 97.5):.2f}"
        rows.append(row)
t1 = pd.DataFrame(rows)
print(t1.to_string(index=False))
print("\nPoint estimates inside the paper's interval, of 24 subject and band pairs:",
      {k: int(sum(v)) for k, v in inside.items()})
lfb_neg = (t1[t1.band == "LFB"]["mean_of_bandmean"] < 0).sum()
hfb_pos = (t1[t1.band == "HFB"]["mean_of_bandmean"] > 0).sum()
print(f"LFB below baseline in {lfb_neg} of 12 subjects; HFB above in {hfb_pos} of 12 (mean of band mean)")
subject band       paper_ci  mean_of_bandmean  median_of_bandmean  mean_of_bandmedian  median_of_bandmedian bootstrap_ci_mean_of_bandmean
     01  LFB -1.87 to -1.29            -1.454              -1.509              -1.407                -1.574                -1.68 to -1.22
     01  HFB   0.03 to 0.23             0.078               0.080               0.111                 0.117                  0.02 to 0.14
     02  LFB -1.12 to -0.31            -0.678              -0.417              -0.469                -0.215                -0.95 to -0.41
     02  HFB   0.07 to 0.64             0.185               0.254               0.481                 0.474                  0.01 to 0.37
     03  LFB -2.11 to -1.73            -1.858              -1.861              -1.779                -1.761                -2.03 to -1.68
     03  HFB   1.39 to 1.67             1.414               1.540               1.469                 1.552                  1.30 to 1.53
     04  LFB  -0.17 to 0.01            -0.139              -0.083              -0.102                -0.097                -0.22 to -0.06
     04  HFB   0.32 to 0.52             0.461               0.444               0.478                 0.485                  0.38 to 0.55
     05  LFB  -0.7 to -0.38            -0.540              -0.503              -0.460                -0.495                -0.68 to -0.39
     05  HFB    0.2 to 0.48             0.257               0.289               0.346                 0.358                  0.14 to 0.37
     06  LFB -1.63 to -1.11            -1.287              -0.911              -1.185                -0.915                -1.47 to -1.11
     06  HFB   2.02 to 2.37             1.782               1.991               1.961                 2.134                  1.64 to 1.92
     07  LFB -0.84 to -0.51            -0.541              -0.529              -0.712                -0.678                -0.65 to -0.44
     07  HFB   1.14 to 1.34             1.153               1.179               1.113                 1.132                  1.08 to 1.23
     08  LFB   -0.3 to 0.04            -0.090              -0.009              -0.031                 0.015                -0.15 to -0.03
     08  HFB   0.36 to 0.63             0.490               0.456               0.529                 0.523                  0.42 to 0.56
     09  LFB -0.57 to -0.08            -0.395              -0.489              -0.320                -0.367                -0.58 to -0.19
     09  HFB  -0.11 to 0.23             0.082               0.108               0.054                 0.168                 -0.07 to 0.23
     10  LFB -0.87 to -0.35            -0.384              -0.325              -0.296                -0.201                -0.46 to -0.30
     10  HFB    0.01 to 0.3             0.180               0.201               0.180                 0.192                  0.11 to 0.25
     11  LFB  -2.3 to -1.86            -1.973              -2.146              -2.019                -2.072                -2.13 to -1.81
     11  HFB   0.09 to 0.34             0.223               0.315               0.195                 0.301                  0.13 to 0.32
     12  LFB -0.66 to -0.44            -0.494              -0.519              -0.478                -0.461                -0.58 to -0.41
     12  HFB    0.06 to 0.2             0.123               0.141               0.152                 0.148                  0.07 to 0.18

Point estimates inside the paper's interval, of 24 subject and band pairs: {'mean_of_bandmean': 23, 'median_of_bandmean': 21, 'mean_of_bandmedian': 21, 'median_of_bandmedian': 20}
LFB below baseline in 12 of 12 subjects; HFB above in 12 of 12 (mean of band mean)

Result: partially reproduced. With the mean over events of the band mean, 23 of 24 subject and band values lie inside the paper's intervals; S06 HFB is 1.78 dB against 2.02 to 2.37. The other readings give 20 to 21 of 24. LFB is below baseline and HFB above it in all 12 subjects.

Claim fig5-recording-day-effects¶

Precentral band power differs significantly across recording days in LFB for subjects 03, 05, 06, 07, 08 and 11, and in HFB for subjects 03, 04, 07, 08 and 10, despite baseline subtraction.

In [38]:
PAPER_SIG = {("03", "lfb"), ("05", "lfb"), ("06", "lfb"), ("07", "lfb"), ("08", "lfb"), ("11", "lfb"),
             ("03", "hfb"), ("04", "hfb"), ("07", "hfb"), ("08", "hfb"), ("10", "hfb")}
rows = []
for meas in ["mean", "median"]:
    for band in ["lfb", "hfb"]:
        for sub in SUBJECTS:
            g = E[E.subject == sub]
            h, p = stats.kruskal(*[d[f"roi_band:precentral:{band}_{meas}"].values for _, d in g.groupby("day")])
            rows.append({"measure": meas, "band": band.upper(), "subject": sub, "p": p, "significant": p < 0.05,
                         "paper_significant": (sub, band) in PAPER_SIG})
dayk = pd.DataFrame(rows)
dayk["agrees"] = dayk.significant == dayk.paper_significant
print(dayk.pivot_table(index=["band", "subject"], columns="measure", values="p").round(4).to_string())
print("\nAgreement with the paper's 24 subject and band pairs:", dayk.groupby("measure").agrees.sum().to_dict())
for meas in ["mean", "median"]:
    d = dayk[dayk.measure == meas]
    print(f"band {meas}: significant here but not in the paper {d[d.significant & ~d.paper_significant][['band','subject']].values.tolist()}; "
          f"in the paper but not here {d[~d.significant & d.paper_significant][['band','subject']].values.tolist()}")
measure         mean  median
band subject                
HFB  01       0.0680  0.0884
     02       0.4000  0.3814
     03       0.0033  0.0087
     04       0.0000  0.0000
     05       0.9070  0.7982
     06       0.8888  0.9680
     07       0.0331  0.0103
     08       0.0068  0.0072
     09       0.5416  0.5471
     10       0.0150  0.0058
     11       0.3317  0.3954
     12       0.4649  0.6848
LFB  01       0.7774  0.7718
     02       0.2058  0.0721
     03       0.0000  0.0000
     04       0.2190  0.4401
     05       0.0263  0.0877
     06       0.0009  0.0001
     07       0.0013  0.0034
     08       0.0065  0.0213
     09       0.4121  0.6751
     10       0.4545  0.8142
     11       0.0000  0.0000
     12       0.5325  0.1140

Agreement with the paper's 24 subject and band pairs: {'mean': 24, 'median': 23}
band mean: significant here but not in the paper []; in the paper but not here []
band median: significant here but not in the paper []; in the paper but not here [['LFB', '05']]

Result: reproduced. With the band mean, the Kruskal-Wallis tests across days agree with the paper on all 24 subject and band pairs (the 11 significant pairs and the 13 others); with the code's band median, 23 of 24 (LFB S05 gives p = 0.088).

Claim extfig5-1-baseline-reduces-day-variability¶

Subtracting the -1.5 to -1 s baseline reduces the variability of band power across recording days, though clear variability remains.

In [39]:
# Electrode band power (band mean), with and without baseline subtraction, for kept events.
el = {}
i = 0
for s, r in zip(sessions, ecog):
    for k, ok in enumerate(r["ok"]):
        if keep[i]:
            for kind in ["el_band", "el_band_raw"]:
                for band in ["lfb", "hfb"]:
                    el.setdefault((s["subject"], kind, band), []).append((s["day"], r[kind][k][f"{band}_mean"]))
        i += 1
rows_a, rows_b = [], []
for sub in SUBJECTS:
    good = first_good[sub]
    for band in ["lfb", "hfb"]:
        g = E[E.subject == sub]
        sd = {}
        for kind, col in [("with", f"roi_band:precentral:{band}_mean"), ("without", f"roi_band_raw:precentral:{band}_mean")]:
            sd[kind] = g.groupby("day")[col].mean().std()
        rows_a.append({"subject": sub, "band": band.upper(), "sd_with": round(sd["with"], 3), "sd_without": round(sd["without"], 3)})
        for kind in ["with", "without"]:
            items = el[(sub, "el_band" if kind == "with" else "el_band_raw", band)]
            days_ = np.array([d for d, _ in items])
            vals = np.array([v for _, v in items])[:, good]
            dm = np.array([vals[days_ == d].mean(0) for d in np.unique(days_)])
            sd[kind + "_el"] = dm.std(0, ddof=1)
        for k_ in range(good.sum()):
            rows_b.append({"subject": sub, "band": band.upper(), "sd_with": sd["with_el"][k_], "sd_without": sd["without_el"][k_]})
ra, rb = pd.DataFrame(rows_a), pd.DataFrame(rows_b)
print("Reading a, precentral region per subject (SD across days of day means, dB):")
print(ra.pivot(index="subject", columns="band", values=["sd_with", "sd_without"]).to_string())
for band in ["LFB", "HFB"]:
    a_ = ra[ra.band == band]
    b_ = rb[rb.band == band]
    print(f"{band}: reading a, SD lower with baseline in {(a_.sd_with < a_.sd_without).sum()} of {len(a_)} subjects "
          f"(median {a_.sd_with.median():.3f} against {a_.sd_without.median():.3f} dB); reading b, in "
          f"{(b_.sd_with < b_.sd_without).sum()} of {len(b_)} good electrodes ({(b_.sd_with < b_.sd_without).mean():.3f}; "
          f"median {b_.sd_with.median():.3f} against {b_.sd_without.median():.3f} dB)")
print("Day effects that remain (claim fig5-recording-day-effects, band mean): significant subject and band pairs",
      int(dayk[(dayk.measure == "mean") & dayk.significant].shape[0]))
Reading a, precentral region per subject (SD across days of day means, dB):
        sd_with        sd_without       
band        HFB    LFB        HFB    LFB
subject                                 
01        0.094  0.111      0.524  0.845
02        0.185  0.414      0.747  0.884
03        0.237  0.828      0.402  0.640
04        0.332  0.165      0.794  0.540
05        0.027  0.202      0.435  1.194
06        0.076  0.438      0.247  0.357
07        0.140  0.245      0.298  0.336
08        0.154  0.135      0.691  1.073
09        0.296  0.201      1.114  1.697
10        0.139  0.103      0.360  1.359
11        0.128  0.524      0.181  0.449
12        0.058  0.103      0.625  0.999
LFB: reading a, SD lower with baseline in 9 of 12 subjects (median 0.202 against 0.865 dB); reading b, in 1006 of 1096 good electrodes (0.918; median 0.246 against 0.831 dB)
HFB: reading a, SD lower with baseline in 12 of 12 subjects (median 0.140 against 0.480 dB); reading b, in 988 of 1096 good electrodes (0.901; median 0.217 against 0.592 dB)
Day effects that remain (claim fig5-recording-day-effects, band mean): significant subject and band pairs 11

Result: reproduced. The SD across days is lower with baseline subtraction for 9 of 12 subjects in LFB and 12 of 12 in HFB (reading a) and for 0.918 and 0.901 of good electrodes (reading b). Variability remains: 11 subject and band pairs have significant day effects after baseline subtraction (median SD with baseline 0.20 and 0.14 dB in the precentral region).

Claim discussion-day-changes-small¶

Day-to-day changes in baseline-subtracted spectral power are small (about 1-2 dB) compared with spectral power without baseline subtraction (about 10-50 dB).

In [40]:
rows = []
for sub in SUBJECTS:
    g = E[E.subject == sub]
    for band in ["lfb", "hfb"]:
        col = f"roi_band:precentral:{band}_mean"
        dm = g.groupby("day")[col].mean()
        raw = g[f"roi_band_raw:precentral:{band}_mean"].mean()
        rows.append({"subject": sub, "band": band.upper(), "largest_day_change_dB": round((dm - g[col].mean()).abs().max(), 3),
                     "day_mean_range_dB": round(dm.max() - dm.min(), 3), "level_uV_dB": round(raw, 2),
                     "level_V_dB": round(raw - 120, 2)})
dc = pd.DataFrame(rows)
print(dc.to_string(index=False))
print(f"\nlargest day change {dc.largest_day_change_dB.max():.3f} dB (holds at <= 2.2: {(dc.largest_day_change_dB <= 2.2).all()}); "
      f"range of day means up to {dc.day_mean_range_dB.max():.3f} dB")
print(f"levels without baseline: microvolts {dc.level_uV_dB.min():.1f} to {dc.level_uV_dB.max():.1f} dB "
      f"(within 9-55: {dc.level_uV_dB.between(9, 55).all()}); volts {dc.level_V_dB.min():.1f} to {dc.level_V_dB.max():.1f} dB "
      f"(within 9-55: {dc.level_V_dB.between(9, 55).all()})")
subject band  largest_day_change_dB  day_mean_range_dB  level_uV_dB  level_V_dB
     01  LFB                  0.135              0.244        36.18      -83.82
     01  HFB                  0.126              0.224        16.19     -103.81
     02  LFB                  0.510              0.893        32.89      -87.11
     02  HFB                  0.229              0.452        17.54     -102.46
     03  LFB                  1.011              1.801        33.72      -86.28
     03  HFB                  0.269              0.514        18.83     -101.17
     04  LFB                  0.324              0.412        33.09      -86.91
     04  HFB                  0.572              0.846        17.83     -102.17
     05  LFB                  0.280              0.402        34.12      -85.88
     05  HFB                  0.040              0.051        19.39     -100.61
     06  LFB                  0.575              1.065        35.37      -84.63
     06  HFB                  0.127              0.180        23.02      -96.98
     07  LFB                  0.333              0.604        36.30      -83.70
     07  HFB                  0.227              0.352        18.31     -101.69
     08  LFB                  0.212              0.349        32.02      -87.98
     08  HFB                  0.219              0.431        21.78      -98.22
     09  LFB                  0.369              0.471        32.75      -87.25
     09  HFB                  0.562              0.759        12.45     -107.55
     10  LFB                  0.156              0.265        33.59      -86.41
     10  HFB                  0.179              0.321        16.26     -103.74
     11  LFB                  0.667              1.148        35.42      -84.58
     11  HFB                  0.146              0.290        18.66     -101.34
     12  LFB                  0.154              0.266        33.68      -86.32
     12  HFB                  0.085              0.158        17.29     -102.71

largest day change 1.011 dB (holds at <= 2.2: True); range of day means up to 1.801 dB
levels without baseline: microvolts 12.4 to 36.3 dB (within 9-55: True); volts -107.5 to -83.7 dB (within 9-55: False)

Result: reproduced. The largest deviation of a day mean from the subject mean is 1.01 dB (the range of day means reaches 1.80 dB), and the power without baseline subtraction is 12.4 to 36.3 dB with the data in microvolts, inside 9 to 55 dB; in volts it would be -107.5 to -83.7 dB.

Regression claims (Figure 6 and Extended Data Figure 6-2)¶

The method is the claims file's opening comment: per subject, good electrode and band, forward selection by OLS adjusted R2 over the design columns, then 200 day-balanced splits (90/10, Methods) with a Huber fit of the full model and, for the Delta R2 of each selected feature, a refit with that feature shuffled among the training events. The fits minimise sklearn's HuberRegressor objective (the code's model), many at a time (helper huber_fit); the first cell compares them with sklearn. Delta R2 refits are run where the full model's R2 exceeds 0.05 in either band, the electrodes Figure 6c-d show (legend); elsewhere only R2, coefficients and selection are used. The variants the claims name are run beside the main analysis: the code's 80/20 split, the code's band median, the code's Delta R2 (refit scored on shuffled test events), the code's selection of electrodes by LFB R2, and the code's inclusion of bad electrodes. The code's log(x + 1) transforms are not run as a variant.

In [41]:
# Regression inputs per subject: the kept events (reading b, as the code's power files hold),
# the design of the ten features, the electrode band power (all electrodes; the bad ones are
# used only for the code's variant), and 200 day-balanced splits for each split ratio.
rng_fig6 = np.random.default_rng(6)
E = ev[ev.keep_b]
keep = ev.keep_b.values
Y = {}
i = 0
for s, r in zip(sessions, ecog):
    for k in range(len(r["ok"])):
        if keep[i]:
            for meas in ["mean", "median"]:
                for band in ["lfb", "hfb"]:
                    Y.setdefault((s["subject"], meas, band), []).append(r["el_band"][k][f"{band}_{meas}"])
        i += 1
Y = {key: np.array(v) for key, v in Y.items()}
design, splits = {}, {}
for sub in SUBJECTS:
    g = E[E.subject == sub]
    assert len(g) == len(Y[(sub, "mean", "lfb")])
    design[sub] = ajile.regression_design(g)
    splits[sub] = {pt: ajile.day_balanced_splits(g.day.values, rng_fig6, 200, pt) for pt in (0.9, 0.8)}
REG_FEATS = list(design[SUBJECTS[0]][1])
n_el = {sub: Y[(sub, "mean", "lfb")].shape[1] for sub in SUBJECTS}
print("Features:", REG_FEATS)
print("Per subject: events, design columns, electrodes (good), test events per split at 90/10 and 80/20:")
for sub in SUBJECTS:
    print(f"  S{sub}: {len(Y[(sub, 'mean', 'lfb')])} events, {design[sub][0].shape[1]} columns, {n_el[sub]} electrodes "
          f"({int(first_good[sub].sum())} good), {splits[sub][0.9][1].shape[1]} and {splits[sub][0.8][1].shape[1]} test events")
Features: ['duration', 'magnitude', 'speed', 'angle', 'speech', 'bimanual_ratio', 'bimanual_overlap', 'bimanual_class', 'day', 'time_of_day']
Per subject: events, design columns, electrodes (good), test events per split at 90/10 and 80/20:
  S01: 732 events, 15 columns, 94 electrodes (85 good), 72 and 144 test events
  S02: 298 events, 15 columns, 86 electrodes (85 good), 28 and 56 test events
  S03: 637 events, 15 columns, 96 electrodes (79 good), 60 and 124 test events
  S04: 412 events, 16 columns, 84 electrodes (67 good), 40 and 80 test events
  S05: 263 events, 14 columns, 106 electrodes (104 good), 24 and 51 test events
  S06: 911 events, 16 columns, 80 electrodes (70 good), 90 and 180 test events
  S07: 784 events, 16 columns, 64 electrodes (63 good), 75 and 155 test events
  S08: 947 events, 16 columns, 92 electrodes (83 good), 90 and 185 test events
  S09: 211 events, 16 columns, 126 electrodes (124 good), 20 and 40 test events
  S10: 746 events, 16 columns, 126 electrodes (121 good), 70 and 145 test events
  S11: 968 events, 16 columns, 106 electrodes (103 good), 95 and 190 test events
  S12: 979 events, 16 columns, 124 electrodes (112 good), 95 and 195 test events
In [42]:
# The batched Huber fit (helper huber_fit) against sklearn's HuberRegressor, which the code uses,
# on the first 20 splits of one electrode per subject (the electrode whose LFB power correlates
# best with reach angle), with the columns forward selection keeps.
from sklearn.linear_model import HuberRegressor
rows = []
for sub in SUBJECTS:
    X, groups = design[sub]
    Xn = X.to_numpy(float)
    y = Y[(sub, "mean", "lfb")][:, int(np.nanargmax(np.abs(np.corrcoef(X["angle"], Y[(sub, "mean", "lfb")].T)[0, 1:])))]
    cols = sorted(ajile.forward_select(Xn, y))
    Z = np.column_stack([Xn[:, cols], np.ones(len(y))])
    tr, te = splits[sub][0.9]
    W, _ = ajile.huber_fit(Z[tr[:20]], y[tr[:20]])
    for k in range(20):
        m = HuberRegressor().fit(Z[tr[k], :-1], y[tr[k]])
        rows.append({"subject": sub, "coef_diff": np.abs(np.r_[m.coef_, m.intercept_] - W[k]).max(),
                     "r2_diff": abs(m.score(Z[te[k], :-1], y[te[k]]) - ajile._r2(y[te[k]], Z[te[k]] @ W[k]))})
hc = pd.DataFrame(rows)
print(f"{len(hc)} fits: largest coefficient difference {hc.coef_diff.max():.2e}, largest withheld R2 difference "
      f"{hc.r2_diff.max():.2e} (median {hc.r2_diff.median():.1e})")
240 fits: largest coefficient difference 1.16e-03, largest withheld R2 difference 4.40e-05 (median 1.9e-06)
In [43]:
# The models. Stage 1 fits the full model for every electrode and band (forward selection and
# 200 splits); the Delta R2 refits are needed only where the full model's R2 exceeds 0.05 (the
# electrodes Figure 6c-d show), so stage 2 refits those, in both bands. The same for the code's
# 80/20 split (good electrodes), and the full model for the code's median band power.
def seed_of(sub, e, band, variant):
    return int(sub) * 100000 + e * 100 + (band == "hfb") * 10 + variant

def fit(keys, meas, per_train, full_only, variant):
    jobs = []
    for sub, e, band in keys:
        X, groups = design[sub]
        tr, te = splits[sub][per_train]
        jobs.append((X, groups, Y[(sub, meas, band)][:, e], tr, te, seed_of(sub, e, band, variant), full_only))
    rows = []
    for (sub, e, band), out in zip(keys, ajile.run_models(jobs)):
        row = {"subject": sub, "electrode": e, "band": band, "good": bool(first_good[sub][e])}
        if out is None:
            rows.append(row)
            continue
        row.update({"r2": out["r2"], "selected": out["selected"]})
        row.update({f"coef:{f}": v for f, v in out["coef"].items()})
        row.update({f"coefsdm:{f}": v for f, v in out["coef_sd_of_mean"].items()})
        row.update({f"keep:{f}": v for f, v in out["keep_prob"].items()})
        if not full_only:
            row.update({f"dr2:{f}": v for f, v in out["delta_r2"].items()})
            row.update({f"dr2code:{f}": v for f, v in out["delta_r2_code"].items()})
        rows.append(row)
    return pd.DataFrame(rows)

def two_stage(meas, per_train, electrodes, variant):
    keys = [(sub, e, band) for sub in SUBJECTS for e in electrodes(sub) for band in ["lfb", "hfb"]]
    full = fit(keys, meas, per_train, True, variant)
    over = full[full.r2 > 0.05][["subject", "electrode"]].drop_duplicates()
    keys2 = [(s_, e, band) for s_, e in over.itertuples(index=False) for band in ["lfb", "hfb"]]
    refit = fit(keys2, meas, per_train, False, variant)
    out = full.merge(refit[["subject", "electrode", "band"] + [c for c in refit if c.startswith("dr2")]],
                     on=["subject", "electrode", "band"], how="left")
    assert np.allclose(full.set_index(["subject", "electrode", "band"]).loc[refit.set_index(["subject", "electrode", "band"]).index].r2,
                       refit.r2)
    return out, len(keys), len(keys2)

started = time.time()
reg, n1, n2 = two_stage("mean", 0.9, lambda sub: range(n_el[sub]), 0)
t_main = time.time() - started
reg82, m1, m2 = two_stage("mean", 0.8, lambda sub: np.nonzero(first_good[sub])[0], 1)
t_82 = time.time() - started - t_main
regmed = fit([(sub, e, band) for sub in SUBJECTS for e in np.nonzero(first_good[sub])[0] for band in ["lfb", "hfb"]],
             "median", 0.9, True, 2)
print(f"main (90/10, band mean, all electrodes): {n1} full models, {n2} with refits, {t_main / 60:.1f} min; "
      f"80/20 (good electrodes): {m1} and {m2}, {t_82 / 60:.1f} min; band median: {len(regmed)} full models; "
      f"total {(time.time() - started) / 60:.1f} min")
for name, d in [("main", reg), ("80/20", reg82), ("median", regmed)]:
    print(f"{name}: models with nothing to fit (flat power) {int(d.r2.isna().sum())}, of which good {int((d.r2.isna() & d.good).sum())}; "
          f"models with no feature selected {int((d.selected.str.len() == 0).sum())}")
G = reg[reg.good]
main (90/10, band mean, all electrodes): 2368 full models, 86 with refits, 1.1 min; 80/20 (good electrodes): 2192 and 84, 0.9 min; band median: 2192 full models; total 2.7 min
main: models with nothing to fit (flat power) 32, of which good 0; models with no feature selected 9
80/20: models with nothing to fit (flat power) 0, of which good 0; models with no feature selected 9
median: models with nothing to fit (flat power) 0, of which good 0; models with no feature selected 10

Claim fig6-r2-at-most-025¶

All regression models explain at most 25% of the variance of withheld single-event power.

In [44]:
rows = []
for name, d in [("main (90/10, band mean, good electrodes)", G), ("code's 80/20 split", reg82), ("code's band median", regmed)]:
    for band in ["lfb", "hfb"]:
        x = d[d.band == band].dropna(subset=["r2"])
        top = x.loc[x.r2.idxmax()]
        rows.append({"variant": name, "band": band.upper(), "models": len(x), "max_R2": round(top.r2, 3),
                     "at": f"S{top.subject} e{top.electrode}", "median_R2": round(x.r2.median(), 4),
                     "share_R2_over_0.05": round((x.r2 > 0.05).mean(), 3), "min_R2": round(x.r2.min(), 3)})
print(pd.DataFrame(rows).to_string(index=False))
print("\nPer subject (main): largest R2 and electrodes with R2 > 0.05, by band")
print(G.groupby(["subject", "band"]).r2.agg(["max", lambda v: int((v > 0.05).sum()), "count"])
      .rename(columns={"<lambda_0>": "over_0.05"}).unstack().round(3).to_string())
mx = G.r2.max()
print(f"\nLargest full-model withheld R2 over good electrodes, subjects and bands: {mx:.3f}; at most 0.275: {mx <= 0.275}")
print(f"With bad electrodes too: {reg.r2.max():.3f}")
# For reference only: the R2 the files store per electrode (the paper's own results), against these.
stored = pd.concat([s["electrodes"].assign(subject=s["subject"], electrode=np.arange(len(s["electrodes"])))
                    for s in sessions if s["day"] == min(x["day"] for x in sessions if x["subject"] == s["subject"])])
for band, col in [("lfb", "low_freq_R2"), ("hfb", "high_freq_R2")]:
    m = G[G.band == band].merge(stored[["subject", "electrode", col]], on=["subject", "electrode"]).dropna(subset=["r2", col])
    print(f"stored {col}: max {stored[col].max():.3f}; Spearman with the R2 here over {len(m)} good electrodes "
          f"{stats.spearmanr(m.r2, m[col])[0]:.3f}; median difference (here minus stored) {np.median(m.r2 - m[col]):+.4f}")
                                 variant band  models  max_R2      at  median_R2  share_R2_over_0.05  min_R2
main (90/10, band mean, good electrodes)  LFB    1096   0.149  S01 e6    -0.0143               0.020  -0.149
main (90/10, band mean, good electrodes)  HFB    1096   0.189 S04 e57    -0.0140               0.013  -0.189
                      code's 80/20 split  LFB    1096   0.153  S01 e6    -0.0070               0.024  -0.158
                      code's 80/20 split  HFB    1096   0.192 S04 e57    -0.0072               0.016  -0.157
                      code's band median  LFB    1096   0.155  S01 e6    -0.0148               0.017  -0.156
                      code's band median  HFB    1096   0.203 S04 e57    -0.0144               0.010  -0.141

Per subject (main): largest R2 and electrodes with R2 > 0.05, by band
           max        over_0.05     count     
band       hfb    lfb       hfb lfb   hfb  lfb
subject                                       
01       0.042  0.149         0  11    85   85
02       0.011 -0.010         0   0    85   85
03       0.120  0.140         1   6    79   79
04       0.189  0.065         2   1    67   67
05       0.020  0.010         0   0   104  104
06       0.060  0.031         1   0    70   70
07       0.185  0.038         6   0    63   63
08       0.116  0.041         3   0    83   83
09       0.057  0.041         1   0   124  124
10       0.005  0.011         0   0   121  121
11       0.040  0.086         0   4   103  103
12       0.013  0.033         0   0   112  112

Largest full-model withheld R2 over good electrodes, subjects and bands: 0.189; at most 0.275: True
With bad electrodes too: 0.189
stored low_freq_R2: max 0.149; Spearman with the R2 here over 1088 good electrodes 0.718; median difference (here minus stored) -0.0051
stored high_freq_R2: max 0.255; Spearman with the R2 here over 1088 good electrodes 0.643; median difference (here minus stored) -0.0052

Result: reproduced. The largest split-averaged full-model withheld R2 over the 1096 good electrodes of the 12 subjects and both bands is 0.189 (HFB, S04), at most 0.275; the largest in LFB is 0.149 (S01). With the code's 80/20 split it is 0.192, with the code's band median 0.203, and with bad electrodes included 0.189. The median R2 is -0.014 in both bands, and 2.0% (LFB) and 1.3% (HFB) of good electrodes exceed 0.05. For reference only, the R2 stored in the files reach 0.149 and 0.255, and their Spearman correlation with the values here is 0.718 and 0.643.

Claim fig6b-best-models-sensorimotor¶

Regression models with the highest withheld R2 are mainly at electrodes over frontoparietal sensorimotor areas, for both bands.

In [45]:
FP5 = ["middle frontal", "precentral", "postcentral", "inferior parietal", "supramarginal"]
SM3 = ["precentral", "postcentral", "inferior parietal"]
TEMP = ["superior temporal", "middle temporal", "inferior temporal"]
raw_w = {sub: ajile.roi_weights(roi_mats[sub], first_good[sub], normalise=False) for sub in SUBJECTS}
def region_of(sub, e):
    w = raw_w[sub][e]
    return ajile.ROI_NAMES[int(np.argmax(w))] if w.sum() > 0 else "none"
for d in (G, reg, reg82):
    d["region"] = [region_of(s_, e) for s_, e in zip(d.subject, d.electrode)]

def project(d, col):
    """Projection-weighted mean over each subject's good electrodes, then the mean over subjects."""
    per = []
    for sub in SUBJECTS:
        v = np.zeros(n_el[sub])
        x = d[d.subject == sub]
        v[x.electrode.values] = np.nan_to_num(x[col].values.astype(float))
        with np.errstate(invalid="ignore"):
            per.append(weights[sub].T @ v)
    return pd.Series(np.nanmean(per, 0), index=ajile.ROI_NAMES), pd.Series(np.sum(np.isfinite(per), 0), index=ajile.ROI_NAMES)

holds6b = {}
for band in ["lfb", "hfb"]:
    d = G[G.band == band]
    hi = d[d.r2 > 0.05]
    proj, n_sub = project(d, "r2")
    tab = pd.DataFrame({"electrodes": d.groupby("region").size(), "R2_over_0.05": hi.groupby("region").size(),
                        "median_R2": d.groupby("region").r2.median().round(4), "projected_R2": proj.round(4),
                        "subjects_covering": n_sub}).fillna(0)
    print(f"{band.upper()}:\n{tab.to_string()}")
    share = hi.region.isin(FP5).mean()
    med_sm, med_t = d[d.region.isin(SM3)].r2.median(), d[d.region.isin(TEMP)].r2.median()
    top3 = list(proj.sort_values(ascending=False).index[:3])
    a = bool(share > 0.5 and med_sm > med_t)
    b = all(r in FP5 for r in top3)
    holds6b[band] = (a, b)
    print(f"  reading a: {len(hi)} electrodes with R2 > 0.05, share in the five frontoparietal regions {share:.3f}; "
          f"median R2 sensorimotor {med_sm:.4f} against temporal {med_t:.4f}; holds {a}")
    print(f"  reading b: three highest projected R2 {top3}; all frontoparietal: {b}")
print("Holds (reading a, reading b):", holds6b)
LFB:
                   electrodes  R2_over_0.05  median_R2  projected_R2  subjects_covering
inferior parietal         118           3.0    -0.0105       -0.0099                 12
inferior temporal         285           0.0    -0.0158       -0.0225                 12
middle frontal            143           3.0    -0.0163       -0.0114                 12
middle temporal           149           0.0    -0.0183       -0.0239                 12
postcentral                83           6.0    -0.0054       -0.0043                 12
precentral                109          10.0    -0.0095        0.0000                 12
superior temporal         143           0.0    -0.0150       -0.0240                 12
supramarginal              66           0.0    -0.0130       -0.0203                 12
  reading a: 22 electrodes with R2 > 0.05, share in the five frontoparietal regions 1.000; median R2 sensorimotor -0.0097 against temporal -0.0158; holds True
  reading b: three highest projected R2 ['precentral', 'postcentral', 'inferior parietal']; all frontoparietal: True
HFB:
                   electrodes  R2_over_0.05  median_R2  projected_R2  subjects_covering
inferior parietal         118           1.0    -0.0134       -0.0156                 12
inferior temporal         285           0.0    -0.0140       -0.0226                 12
middle frontal            143           1.0    -0.0153       -0.0217                 12
middle temporal           149           0.0    -0.0160       -0.0235                 12
postcentral                83           5.0    -0.0086       -0.0107                 12
precentral                109           6.0    -0.0123       -0.0129                 12
superior temporal         143           1.0    -0.0148       -0.0223                 12
supramarginal              66           0.0    -0.0186       -0.0230                 12
  reading a: 14 electrodes with R2 > 0.05, share in the five frontoparietal regions 0.929; median R2 sensorimotor -0.0117 against temporal -0.0147; holds True
  reading b: three highest projected R2 ['postcentral', 'precentral', 'inferior parietal']; all frontoparietal: True
Holds (reading a, reading b): {'lfb': (True, True), 'hfb': (True, True)}

Result: reproduced. Under reading a, all 22 good electrodes with LFB R2 > 0.05 and 13 of 14 (0.929) with HFB R2 > 0.05 are assigned to the five frontoparietal regions, and the median R2 of precentral, postcentral and inferior parietal electrodes is above that of temporal electrodes in both bands (-0.0097 against -0.0158 in LFB, -0.0117 against -0.0147 in HFB). Under reading b, the three regions with the highest projected R2 are precentral, postcentral and inferior parietal in both bands. Few electrodes exceed 0.05, from 4 subjects in LFB and 6 in HFB.

Claim fig6c-angle-and-day-most-informative¶

Reach angle and day of recording are the most informative features for single-event power, especially for low-frequency power.

In [46]:
FEAT_ORDER = ["angle", "day", "duration", "magnitude", "speed", "speech", "bimanual_ratio", "bimanual_overlap",
              "bimanual_class", "time_of_day"]
def ranked(d, band, prefix, select_band=None, fn=np.median):
    """Median over electrodes with R2 > 0.05 (in `select_band`, default the same band) of a per-feature column."""
    sb = select_band or band
    ok = d[(d.band == sb) & (d.r2 > 0.05)][["subject", "electrode"]]
    x = d[d.band == band].merge(ok, on=["subject", "electrode"])
    vals = pd.Series({f: fn(x[f"{prefix}{f}"].values) for f in FEAT_ORDER})
    return vals.sort_values(ascending=False), len(x)
variants6c = [("main", G, "dr2:", None), ("code's Delta R2", G, "dr2code:", None),
              ("code's selection by LFB R2", G, "dr2:", "lfb"), ("code's 80/20 split", reg82[reg82.good], "dr2:", None),
              ("with bad electrodes", reg, "dr2:", None)]
tabs, top2 = {}, {}
for name, d, prefix, sb in variants6c:
    for band in ["lfb", "hfb"]:
        v, n = ranked(d, band, prefix, sb)
        tabs[(name, band.upper(), n)] = v.round(4)
        top2[(name, band)] = list(v.dropna().index[:2])
print("Median Delta R2 over electrodes with R2 > 0.05 (variant, band, electrodes):")
print(pd.DataFrame(tabs).loc[FEAT_ORDER].to_string())
for k, v in top2.items():
    print(f"  {k[0]}, {k[1].upper()}: two largest {v}; angle and day both: {set(v) == {'angle', 'day'}}")
Median Delta R2 over electrodes with R2 > 0.05 (variant, band, electrodes):
                    main         code's Delta R2         code's selection by LFB R2         code's 80/20 split         with bad electrodes        
                     LFB     HFB             LFB     HFB                        LFB     HFB                LFB     HFB                 LFB     HFB
                      22      14              22      14                         22      22                 26      17                  29      16
angle             0.0659  0.0333          0.0648  0.0326                     0.0659  0.0043             0.0596  0.0309              0.0400  0.0277
day               0.0173  0.0682          0.0175  0.0643                     0.0173  0.0009             0.0108  0.0685              0.0235  0.0700
duration          0.0000  0.0003          0.0000  0.0006                     0.0000  0.0000             0.0000  0.0000              0.0000  0.0003
magnitude         0.0000  0.0035          0.0000  0.0031                     0.0000  0.0000             0.0000  0.0030              0.0000  0.0043
speed             0.0000  0.0000          0.0000  0.0000                     0.0000  0.0000             0.0000  0.0000              0.0000  0.0015
speech            0.0000  0.0000          0.0000  0.0000                     0.0000  0.0000             0.0000  0.0000              0.0000  0.0000
bimanual_ratio    0.0000  0.0000          0.0000  0.0000                     0.0000  0.0000             0.0000  0.0000              0.0000  0.0000
bimanual_overlap  0.0000  0.0000          0.0000  0.0000                     0.0000  0.0000             0.0000  0.0000              0.0008  0.0000
bimanual_class    0.0000  0.0000          0.0000  0.0000                     0.0000  0.0000             0.0000  0.0000              0.0000  0.0000
time_of_day       0.0017  0.0021          0.0015  0.0008                     0.0017  0.0008             0.0013  0.0022              0.0019  0.0021
  main, LFB: two largest ['angle', 'day']; angle and day both: True
  main, HFB: two largest ['day', 'angle']; angle and day both: True
  code's Delta R2, LFB: two largest ['angle', 'day']; angle and day both: True
  code's Delta R2, HFB: two largest ['day', 'angle']; angle and day both: True
  code's selection by LFB R2, LFB: two largest ['angle', 'day']; angle and day both: True
  code's selection by LFB R2, HFB: two largest ['angle', 'day']; angle and day both: True
  code's 80/20 split, LFB: two largest ['angle', 'day']; angle and day both: True
  code's 80/20 split, HFB: two largest ['day', 'angle']; angle and day both: True
  with bad electrodes, LFB: two largest ['angle', 'day']; angle and day both: True
  with bad electrodes, HFB: two largest ['day', 'angle']; angle and day both: True

Result: reproduced. Over the 22 good electrodes with LFB R2 > 0.05, reach angle (median Delta R2 0.066) and recording day (0.017) have the two largest median Delta R2; time of day follows (0.0017) and the seven other features have a median of 0. In HFB (14 electrodes) day (0.068) and angle (0.033) are the two largest. Every variant (the code's Delta R2, selection by LFB R2, the 80/20 split, bad electrodes included) gives angle and day as the two largest in both bands.

Claim extfig6-2-angle-most-retained¶

Reach angle is the feature most often retained by forward selection in sensorimotor regions, followed by reach duration, reach magnitude, bimanual ratio and bimanual overlap.

In [47]:
keep_proj = {}
for band in ["lfb", "hfb"]:
    d = G[G.band == band]
    keep_proj[band] = pd.DataFrame({f: project(d, f"keep:{f}")[0] for f in FEAT_ORDER})
    print(f"{band.upper()}: retention probability projected onto the regions (mean over subjects)")
    print(keep_proj[band].round(3).to_string())
angle_top = {}
for band in ["lfb", "hfb"]:
    for r in SM3:
        row = keep_proj[band].loc[r]
        angle_top[(band, r)] = bool(row["angle"] > row.drop("angle").max())
print("\nAngle above every other feature:", angle_top, "->", all(angle_top.values()))
ORDER = ["duration", "magnitude", "bimanual_ratio", "bimanual_overlap"]
order_holds = {}
for lab, regs in [("a, three sensorimotor regions", SM3), ("b, all eight regions", ajile.ROI_NAMES)]:
    m = pd.concat([keep_proj[b].loc[regs] for b in ["lfb", "hfb"]]).mean().sort_values(ascending=False)
    order_holds[lab[0]] = list(m.index[1:5]) == ORDER
    print(f"reading {lab}: ranking {[(f, round(v, 3)) for f, v in m.items()]}; second to fifth {list(m.index[1:5])}; "
          f"order holds {order_holds[lab[0]]}")
print("Retention over good electrodes, not projected (mean over electrodes, both bands):",
      G[[f"keep:{f}" for f in FEAT_ORDER]].mean().round(3).to_dict())
LFB: retention probability projected onto the regions (mean over subjects)
                   angle    day  duration  magnitude  speed  speech  bimanual_ratio  bimanual_overlap  bimanual_class  time_of_day
middle frontal     0.624  0.269     0.189      0.213  0.441   0.367           0.270             0.209           0.257        0.215
precentral         0.679  0.321     0.265      0.231  0.375   0.370           0.318             0.301           0.315        0.211
postcentral        0.662  0.303     0.281      0.298  0.338   0.338           0.400             0.273           0.304        0.234
inferior parietal  0.491  0.279     0.330      0.364  0.388   0.345           0.304             0.310           0.264        0.222
supramarginal      0.486  0.250     0.348      0.320  0.373   0.305           0.341             0.263           0.245        0.220
superior temporal  0.496  0.240     0.307      0.339  0.267   0.301           0.323             0.327           0.264        0.201
middle temporal    0.422  0.247     0.301      0.277  0.293   0.387           0.316             0.278           0.287        0.198
inferior temporal  0.421  0.274     0.250      0.206  0.305   0.446           0.322             0.242           0.303        0.205
HFB: retention probability projected onto the regions (mean over subjects)
                   angle    day  duration  magnitude  speed  speech  bimanual_ratio  bimanual_overlap  bimanual_class  time_of_day
middle frontal     0.463  0.227     0.268      0.336  0.393   0.302           0.250             0.188           0.352        0.210
precentral         0.606  0.279     0.345      0.397  0.391   0.338           0.282             0.316           0.327        0.208
postcentral        0.607  0.292     0.386      0.388  0.363   0.393           0.335             0.307           0.309        0.205
inferior parietal  0.448  0.269     0.327      0.379  0.286   0.353           0.304             0.233           0.286        0.193
supramarginal      0.409  0.239     0.333      0.347  0.245   0.404           0.344             0.280           0.299        0.165
superior temporal  0.431  0.232     0.245      0.338  0.241   0.349           0.314             0.333           0.345        0.177
middle temporal    0.345  0.227     0.210      0.356  0.256   0.356           0.321             0.309           0.390        0.172
inferior temporal  0.289  0.246     0.245      0.390  0.257   0.267           0.307             0.316           0.392        0.199

Angle above every other feature: {('lfb', 'precentral'): True, ('lfb', 'postcentral'): True, ('lfb', 'inferior parietal'): True, ('hfb', 'precentral'): True, ('hfb', 'postcentral'): True, ('hfb', 'inferior parietal'): True} -> True
reading a, three sensorimotor regions: ranking [('angle', 0.582), ('speed', 0.357), ('speech', 0.356), ('magnitude', 0.343), ('bimanual_ratio', 0.324), ('duration', 0.322), ('bimanual_class', 0.301), ('day', 0.29), ('bimanual_overlap', 0.29), ('time_of_day', 0.212)]; second to fifth ['speed', 'speech', 'magnitude', 'bimanual_ratio']; order holds False
reading b, all eight regions: ranking [('angle', 0.492), ('speech', 0.351), ('speed', 0.326), ('magnitude', 0.324), ('bimanual_ratio', 0.316), ('bimanual_class', 0.309), ('duration', 0.289), ('bimanual_overlap', 0.28), ('day', 0.262), ('time_of_day', 0.202)]; second to fifth ['speech', 'speed', 'magnitude', 'bimanual_ratio']; order holds False
Retention over good electrodes, not projected (mean over electrodes, both bands): {'keep:angle': 0.42, 'keep:day': 0.263, 'keep:duration': 0.302, 'keep:magnitude': 0.333, 'keep:speed': 0.318, 'keep:speech': 0.343, 'keep:bimanual_ratio': 0.327, 'keep:bimanual_overlap': 0.279, 'keep:bimanual_class': 0.291, 'keep:time_of_day': 0.202}

Result: partially reproduced. Reach angle has the highest projected retention probability in precentral, postcentral and inferior parietal in both bands (0.448 to 0.679, against at most 0.400 for any other feature in these regions). The order of the next four does not hold: averaged over the three sensorimotor regions and both bands, the second to fifth features are onset speed, speech ratio, reach magnitude and bimanual ratio, and over all eight regions speech ratio, onset speed, reach magnitude and bimanual ratio; reach duration is sixth and seventh. The second to tenth features lie close together (0.202 to 0.357).

Claim fig6d-upward-reaches-enhance-pattern¶

Upward reaches are associated with lower low-frequency power and higher high-frequency power, that is, a larger version of the average movement response.

In [48]:
rows = []
for name, d, sb in [("main", G, None), ("code's selection by LFB R2", G, "lfb"), ("with bad electrodes", reg, None),
                    ("code's 80/20 split", reg82[reg82.good], None)]:
    for band in ["lfb", "hfb"]:
        ok = d[(d.band == (sb or band)) & (d.r2 > 0.05)][["subject", "electrode"]]
        x = d[d.band == band].merge(ok, on=["subject", "electrode"])["coef:angle"]
        rows.append({"variant": name, "band": band.upper(), "electrodes": len(x), "median_angle_coef": round(x.median(), 4),
                     "share_negative": round((x < 0).mean(), 3), "q25": round(x.quantile(.25), 4), "q75": round(x.quantile(.75), 4)})
a6d = pd.DataFrame(rows)
print(a6d.to_string(index=False))
m = a6d[a6d.variant == "main"].set_index("band").median_angle_coef
print(f"main: LFB median below 0 {m['LFB'] < 0}; HFB median above 0 {m['HFB'] > 0}")
print("Median angle coefficient by subject (main, electrodes with R2 > 0.05 in the band):")
print(G[G.r2 > 0.05].groupby(["subject", "band"])["coef:angle"].median().unstack().round(3).to_string())
                   variant band  electrodes  median_angle_coef  share_negative     q25     q75
                      main  LFB          22            -1.0272           0.955 -1.2960 -0.6187
                      main  HFB          14             0.5348           0.000  0.2596  0.6722
code's selection by LFB R2  LFB          22            -1.0272           0.955 -1.2960 -0.6187
code's selection by LFB R2  HFB          22             0.2024           0.136  0.0000  0.4082
       with bad electrodes  LFB          29            -0.8146           0.828 -1.0986 -0.4725
       with bad electrodes  HFB          16             0.5146           0.000  0.1809  0.6275
        code's 80/20 split  LFB          26            -0.9725           0.962 -1.1209 -0.6269
        code's 80/20 split  HFB          17             0.5404           0.000  0.3442  0.7021
main: LFB median below 0 True; HFB median above 0 True
Median angle coefficient by subject (main, electrodes with R2 > 0.05 in the band):
band       hfb    lfb
subject              
01         NaN -1.353
03       0.520 -0.518
04       0.433  0.000
06       0.598    NaN
07       0.730    NaN
08       0.486    NaN
09       0.000    NaN
11         NaN -0.994

Result: reproduced. Over good electrodes with R2 > 0.05 in the band, the median reach-angle coefficient is -1.027 in LFB (22 electrodes, 95.5% negative) and 0.535 in HFB (14 electrodes, none negative). The code's selection by LFB R2 gives -1.027 and 0.202, bad electrodes included -0.815 and 0.515, and the 80/20 split -0.973 and 0.540, so the signs hold in every variant. By subject the LFB medians are -1.353 to 0 (4 subjects) and the HFB medians 0 to 0.730 (6 subjects).

Claim fig6d-angle-and-day-largest-coefficients¶

Reach angle and day of recording have the largest coefficient magnitudes among the features, and the SD of the recording-day coefficients is large.

In [49]:
res6d = {}
for name, d, sb in [("main", G, None), ("code's selection by LFB R2", G, "lfb"), ("with bad electrodes", reg, None),
                    ("code's 80/20 split", reg82[reg82.good], None)]:
    tab = {}
    for band in ["lfb", "hfb"]:
        va, n = ranked(d, band, "coef:", sb, fn=lambda v: np.median(np.abs(v)))
        vb, _ = ranked(d, band, "coef:", sb, fn=lambda v: abs(np.median(v)))
        tab[(band.upper(), "a: median |coef|", n)] = va.round(4)
        tab[(band.upper(), "b: |median coef|", n)] = vb.round(4)
        res6d[(name, band, "a")] = list(va.dropna().index[:2])
        res6d[(name, band, "b")] = list(vb.dropna().index[:2])
    print(f"{name}:\n{pd.DataFrame(tab).loc[FEAT_ORDER].to_string()}")
for k, v in res6d.items():
    print(f"  {k[0]}, {k[1].upper()}, reading {k[2]}: two largest {v}; angle and day: {set(v) == {'angle', 'day'}}")
main:
                              LFB                               HFB                 
                 a: median |coef| b: |median coef| a: median |coef| b: |median coef|
                               22               22               14               14
angle                      1.0272           1.0272           0.5348           0.5348
day                        0.6598           0.6598           0.7332           0.7332
duration                   0.1604           0.0000           0.0992           0.0000
magnitude                  0.0000           0.0000           0.2314           0.2278
speed                      0.0000           0.0000           0.0000           0.0000
speech                     0.0856           0.0000           0.0000           0.0000
bimanual_ratio             0.0000           0.0000           0.0000           0.0000
bimanual_overlap           0.0000           0.0000           0.0000           0.0000
bimanual_class             0.0513           0.0000           0.0000           0.0000
time_of_day                0.1875           0.1875           0.1912           0.1912
code's selection by LFB R2:
                              LFB                               HFB                 
                 a: median |coef| b: |median coef| a: median |coef| b: |median coef|
                               22               22               22               22
angle                      1.0272           1.0272           0.2024           0.2024
day                        0.6598           0.6598           0.1336           0.1336
duration                   0.1604           0.0000           0.0000           0.0000
magnitude                  0.0000           0.0000           0.0000           0.0000
speed                      0.0000           0.0000           0.0000           0.0000
speech                     0.0856           0.0000           0.0000           0.0000
bimanual_ratio             0.0000           0.0000           0.0000           0.0000
bimanual_overlap           0.0000           0.0000           0.0000           0.0000
bimanual_class             0.0513           0.0000           0.0068           0.0000
time_of_day                0.1875           0.1875           0.1083           0.1083
with bad electrodes:
                              LFB                               HFB                 
                 a: median |coef| b: |median coef| a: median |coef| b: |median coef|
                               29               29               16               16
angle                      0.9863           0.8146           0.5146           0.5146
day                        0.6842           0.6842           0.7857           0.7857
duration                   0.0000           0.0000           0.0992           0.0000
magnitude                  0.0000           0.0000           0.2997           0.2997
speed                      0.0000           0.0000           0.0979           0.0979
speech                     0.0000           0.0000           0.0000           0.0000
bimanual_ratio             0.0000           0.0000           0.0000           0.0000
bimanual_overlap           0.1031           0.1031           0.0000           0.0000
bimanual_class             0.0000           0.0000           0.0000           0.0000
time_of_day                0.2092           0.2092           0.1912           0.1912
code's 80/20 split:
                              LFB                               HFB                 
                 a: median |coef| b: |median coef| a: median |coef| b: |median coef|
                               26               26               17               17
angle                      0.9725           0.9725           0.5404           0.5404
day                        0.5638           0.5638           0.7637           0.7637
duration                   0.1688           0.0000           0.1288           0.0000
magnitude                  0.0000           0.0000           0.2676           0.1686
speed                      0.0000           0.0000           0.0000           0.0000
speech                     0.0000           0.0000           0.0000           0.0000
bimanual_ratio             0.0000           0.0000           0.0000           0.0000
bimanual_overlap           0.0000           0.0000           0.0000           0.0000
bimanual_class             0.0542           0.0000           0.0000           0.0000
time_of_day                0.1758           0.1758           0.2012           0.2012
  main, LFB, reading a: two largest ['angle', 'day']; angle and day: True
  main, LFB, reading b: two largest ['angle', 'day']; angle and day: True
  main, HFB, reading a: two largest ['day', 'angle']; angle and day: True
  main, HFB, reading b: two largest ['day', 'angle']; angle and day: True
  code's selection by LFB R2, LFB, reading a: two largest ['angle', 'day']; angle and day: True
  code's selection by LFB R2, LFB, reading b: two largest ['angle', 'day']; angle and day: True
  code's selection by LFB R2, HFB, reading a: two largest ['angle', 'day']; angle and day: True
  code's selection by LFB R2, HFB, reading b: two largest ['angle', 'day']; angle and day: True
  with bad electrodes, LFB, reading a: two largest ['angle', 'day']; angle and day: True
  with bad electrodes, LFB, reading b: two largest ['angle', 'day']; angle and day: True
  with bad electrodes, HFB, reading a: two largest ['day', 'angle']; angle and day: True
  with bad electrodes, HFB, reading b: two largest ['day', 'angle']; angle and day: True
  code's 80/20 split, LFB, reading a: two largest ['angle', 'day']; angle and day: True
  code's 80/20 split, LFB, reading b: two largest ['angle', 'day']; angle and day: True
  code's 80/20 split, HFB, reading a: two largest ['day', 'angle']; angle and day: True
  code's 80/20 split, HFB, reading b: two largest ['day', 'angle']; angle and day: True

Result: reproduced. Over good electrodes with R2 > 0.05, reach angle and the SD of the recording-day coefficients have the two largest values under both readings in both bands: in LFB angle 1.027 and day 0.660 (then time of day 0.188), in HFB day 0.733 and angle 0.535 (then reach magnitude 0.231 under reading a). The code's selection by LFB R2, the inclusion of bad electrodes and the 80/20 split give the same two in both bands and readings. The day SD is the second largest value in LFB and the largest in HFB.

In [50]:
# The fig6b-d criteria on the electrodes the stored R2 select (the paper's own per-electrode R2 in
# the files, low_freq_R2 and high_freq_R2, above 0.05), and the overlap of those sets with the
# sets selected by the R2 here. Delta R2 refits are run for the stored-selected good electrodes
# that lack them, with the seeds of the main fit.
st = pd.concat([stored[["subject", "electrode", col]].rename(columns={col: "r2_stored"}).assign(band=band)
                for band, col in [("lfb", "low_freq_R2"), ("hfb", "high_freq_R2")]])
Gs = G.merge(st, on=["subject", "electrode", "band"], how="left")
for band in ["lfb", "hfb"]:
    d = Gs[Gs.band == band]
    ours = set(map(tuple, d[d.r2 > 0.05][["subject", "electrode"]].values))
    theirs = set(map(tuple, d[d.r2_stored > 0.05][["subject", "electrode"]].values))
    print(f"{band.upper()}: R2 > 0.05 here {len(ours)} electrodes ({len({s_ for s_, _ in ours})} subjects), stored {len(theirs)} "
          f"({len({s_ for s_, _ in theirs})} subjects), in both {len(ours & theirs)}; by subject here "
          f"{dict(pd.Series([s_ for s_, _ in ours]).value_counts().sort_index())}, stored "
          f"{dict(pd.Series([s_ for s_, _ in theirs]).value_counts().sort_index())}")
need = Gs[(Gs.r2_stored > 0.05) & Gs["dr2:angle"].isna()][["subject", "electrode"]].drop_duplicates()
extra = fit([(s_, e, band) for s_, e in need.itertuples(index=False) for band in ["lfb", "hfb"]], "mean", 0.9, False, 0)
print(f"refits for stored-selected electrodes without them: {len(need)} electrodes")
if len(extra):
    ix = ["subject", "electrode", "band"]
    chk = Gs.set_index(ix).loc[extra.set_index(ix).index]
    assert np.allclose(chk.r2, extra.r2)
    Gs = Gs.set_index(ix)
    dcols = [c for c in extra if c.startswith("dr2")]
    Gs.loc[extra.set_index(ix).index, dcols] = extra.set_index(ix)[dcols].values
    Gs = Gs.reset_index()
# Select by the stored R2: ranked() and the angle medians select on the column r2.
S_ = Gs.assign(r2_here=Gs.r2, r2=Gs.r2_stored)
print("\nfig6b reading a with the stored selection (share of selected electrodes in the five frontoparietal regions):")
for band in ["lfb", "hfb"]:
    hi = S_[(S_.band == band) & (S_.r2 > 0.05)]
    print(f"  {band.upper()}: {hi.region.isin(FP5).sum()} of {len(hi)} ({hi.region.isin(FP5).mean():.3f}); regions "
          f"{dict(hi.region.value_counts())}")
print("For reference only (the paper's own values): median stored R2 sensorimotor against temporal, and the three "
      "highest projected stored R2:")
for band in ["lfb", "hfb"]:
    d = S_[S_.band == band]
    proj, _ = project(d, "r2")
    print(f"  {band.upper()}: {d[d.region.isin(SM3)].r2.median():.4f} against {d[d.region.isin(TEMP)].r2.median():.4f}; "
          f"{list(proj.sort_values(ascending=False).index[:3])}")
print("\nfig6c with the stored selection, median Delta R2:")
for band in ["lfb", "hfb"]:
    for prefix in ["dr2:", "dr2code:"]:
        v, n = ranked(S_, band, prefix)
        print(f"  {band.upper()} {prefix} ({n} electrodes): {v.round(4).head(4).to_dict()}; angle and day the two largest: "
              f"{set(v.index[:2]) == {'angle', 'day'}}")
print("\nfig6d with the stored selection:")
for band in ["lfb", "hfb"]:
    x = S_[(S_.band == band) & (S_.r2 > 0.05)]["coef:angle"]
    va, n = ranked(S_, band, "coef:", fn=lambda v: np.median(np.abs(v)))
    vb, _ = ranked(S_, band, "coef:", fn=lambda v: abs(np.median(v)))
    print(f"  {band.upper()} ({n} electrodes): median angle coefficient {x.median():+.4f} ({(x < 0).mean():.3f} negative); "
          f"reading a {va.round(4).head(3).to_dict()}; reading b {vb.round(4).head(3).to_dict()}; "
          f"angle and day the two largest: a {set(va.index[:2]) == {'angle', 'day'}}, b {set(vb.index[:2]) == {'angle', 'day'}}")
# The day and time-of-day coefficient: the mean over splits of the SD of the one-hot coefficients
# (used above) against the SD of the split-averaged one-hot coefficients, on both selections.
print("\nDay and time-of-day value under the two definitions (reading a, median |value|):")
for lab, d in [("selection here", G), ("stored selection", S_)]:
    for band in ["lfb", "hfb"]:
        va, n = ranked(d, band, "coef:", fn=lambda v: np.median(np.abs(v)))
        vs, _ = ranked(d, band, "coefsdm:", fn=lambda v: np.median(np.abs(v)))
        print(f"  {lab}, {band.upper()} ({n}): mean of per-split SD day {va['day']:.4f}, time of day {va['time_of_day']:.4f}; "
              f"SD of mean day {vs['day']:.4f}, time of day {vs['time_of_day']:.4f}; two largest with the SD of mean "
              f"{list(vs.index[:2])}")
LFB: R2 > 0.05 here 22 electrodes (4 subjects), stored 23 (5 subjects), in both 18; by subject here {'01': np.int64(11), '03': np.int64(6), '04': np.int64(1), '11': np.int64(4)}, stored {'01': np.int64(10), '03': np.int64(5), '05': np.int64(2), '09': np.int64(3), '11': np.int64(3)}
HFB: R2 > 0.05 here 14 electrodes (6 subjects), stored 22 (8 subjects), in both 12; by subject here {'03': np.int64(1), '04': np.int64(2), '06': np.int64(1), '07': np.int64(6), '08': np.int64(3), '09': np.int64(1)}, stored {'01': np.int64(1), '03': np.int64(2), '04': np.int64(5), '05': np.int64(2), '06': np.int64(1), '07': np.int64(5), '08': np.int64(3), '09': np.int64(3)}
refits for stored-selected electrodes without them: 12 electrodes

fig6b reading a with the stored selection (share of selected electrodes in the five frontoparietal regions):
  LFB: 22 of 23 (0.957); regions {'precentral': np.int64(8), 'postcentral': np.int64(7), 'inferior parietal': np.int64(4), 'middle frontal': np.int64(3), 'inferior temporal': np.int64(1)}
  HFB: 18 of 22 (0.818); regions {'precentral': np.int64(8), 'postcentral': np.int64(5), 'inferior parietal': np.int64(4), 'middle temporal': np.int64(2), 'middle frontal': np.int64(1), 'superior temporal': np.int64(1), 'inferior temporal': np.int64(1)}
For reference only (the paper's own values): median stored R2 sensorimotor against temporal, and the three highest projected stored R2:
  LFB: -0.0057 against -0.0090; ['precentral', 'postcentral', 'inferior parietal']
  HFB: -0.0052 against -0.0097; ['postcentral', 'precentral', 'inferior parietal']

fig6c with the stored selection, median Delta R2:
  LFB dr2: (23 electrodes): {'angle': 0.0629, 'day': 0.0129, 'time_of_day': 0.0007, 'duration': 0.0}; angle and day the two largest: True
  LFB dr2code: (23 electrodes): {'angle': 0.0657, 'day': 0.0143, 'time_of_day': 0.0011, 'duration': 0.0}; angle and day the two largest: True
  HFB dr2: (22 electrodes): {'day': 0.0496, 'angle': 0.0189, 'time_of_day': 0.0021, 'duration': 0.0}; angle and day the two largest: True
  HFB dr2code: (22 electrodes): {'day': 0.0535, 'angle': 0.0209, 'time_of_day': 0.0012, 'magnitude': 0.0001}; angle and day the two largest: True

fig6d with the stored selection:
  LFB (23 electrodes): median angle coefficient -1.0264 (0.913 negative); reading a {'angle': 1.0264, 'day': 0.6354, 'time_of_day': 0.2092}; reading b {'angle': 1.0264, 'day': 0.6354, 'time_of_day': 0.2092}; angle and day the two largest: a True, b True
  HFB (22 electrodes): median angle coefficient +0.4976 (0.091 negative); reading a {'day': 0.6675, 'angle': 0.4982, 'time_of_day': 0.1874}; reading b {'day': 0.6675, 'angle': 0.4976, 'time_of_day': 0.1874}; angle and day the two largest: a True, b True

Day and time-of-day value under the two definitions (reading a, median |value|):
  selection here, LFB (22): mean of per-split SD day 0.6598, time of day 0.1875; SD of mean day 0.6575, time of day 0.1875; two largest with the SD of mean ['angle', 'day']
  selection here, HFB (14): mean of per-split SD day 0.7332, time of day 0.1912; SD of mean day 0.7292, time of day 0.1912; two largest with the SD of mean ['day', 'angle']
  stored selection, LFB (23): mean of per-split SD day 0.6354, time of day 0.2092; SD of mean day 0.6344, time of day 0.2092; two largest with the SD of mean ['angle', 'day']
  stored selection, HFB (22): mean of per-split SD day 0.6675, time of day 0.1874; SD of mean day 0.6668, time of day 0.1874; two largest with the SD of mean ['day', 'angle']

Electrodes selected by the stored R2 (sensitivity, not the criterion). The electrodes with R2 > 0.05 here and those with stored R2 > 0.05 overlap in 18 electrodes in LFB (22 here, 23 stored) and 12 in HFB (14 here, 22 stored). The stored sets come from 5 subjects in LFB and 8 in HFB, against 4 and 6 here. With the stored selection, 22 of 23 LFB and 18 of 22 HFB electrodes are in the five frontoparietal regions (fig6b, reading a, share part). Angle (0.063) and day (0.013) have the two largest median Delta R2 in LFB, and day (0.050) and angle (0.019) in HFB, with the code's Delta R2 too (fig6c). The median angle coefficient is -1.026 in LFB and +0.498 in HFB (fig6d, upward reaches). Angle and the day SD are the two largest coefficient values under both readings in both bands (fig6d, largest coefficients). The fig6b-d results are the same on either set of electrodes. Taken as the SD of the split-averaged one-hot coefficients, not the mean over splits of the per-split SD, the day value is 0.658 against 0.660 in LFB and 0.729 against 0.733 in HFB, and angle and day stay the two largest.

In [51]:
# How much the assumed reading of the bad-segment rule matters: the main ECoG numbers with only
# the segments with missing samples dropped (no 0 dB or 115-125 Hz rule).
E_alt = ev[ev.ok & ~ev.bad_missing]
print("events:", len(E_alt), "against", len(E))
for band in ["lfb", "hfb"]:
    col = f"roi_band:precentral:{band}_mean"
    h, p = stats.kruskal(*[g[col].values for _, g in E_alt.groupby("subject")])
    ins = sum(TABLE1[s][0 if band == "lfb" else 1][0] <= E_alt[E_alt.subject == s][col].mean() <= TABLE1[s][0 if band == "lfb" else 1][1]
              for s in SUBJECTS)
    sig = [s for s in SUBJECTS if stats.kruskal(*[d[col].values for _, d in E_alt[E_alt.subject == s].groupby("day")])[1] < 0.05]
    print(f"{band.upper()}: across subjects p = {p:.3g}; Table 1 means inside {ins} of 12; day effects in {sig}")
events: 7963 against 7888
LFB: across subjects p = 1.46e-165; Table 1 means inside 12 of 12; day effects in ['03', '05', '06', '07', '08', '11']
HFB: across subjects p = 7.68e-263; Table 1 means inside 10 of 12; day effects in ['03', '04', '07', '08', '10']

Summary¶

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

Claim Outcome
subject-days (link) reproduced
roi-projection-link (link, Figshare projection matrices) reproduced
cohort partially reproduced (seven subjects with depth electrodes, not five; sex and age not in the dataset)
fig2-event-counts not reproduced (211 to 996 events per subject, median 770.5)
fig2-features-differ-across-subjects reproduced
fig2-reach-shape partially reproduced (angle peaks near +-70, not +-90)
fig2-bimanual-skew reproduced
extfig2-1c-contralateral-larger reproduced
extfig2-2-feature-correlations partially reproduced (5 of 6)
fig2-days-and-waking partially reproduced (S04's busiest day holds 38%)
fig3-group-lfb-decrease-hfb-increase reproduced
fig3-sensorimotor-largest reproduced
fig3-lfb-more-widespread blocked, methods underspecified (readings disagree)
fig4-precentral-subject-variability reproduced (one tie broken by interpolated width)
fig5-band-power-differs-across-subjects reproduced
table1-subject-band-power-ci partially reproduced (23 of 24)
fig5-recording-day-effects reproduced (24 of 24)
extfig5-1-baseline-reduces-day-variability reproduced
discussion-day-changes-small reproduced
fig6-r2-at-most-025 reproduced (largest R2 0.189)
fig6b-best-models-sensorimotor reproduced
fig6c-angle-and-day-most-informative reproduced
extfig6-2-angle-most-retained partially reproduced (angle first; the order of the next four differs)
fig6d-upward-reaches-enhance-pattern reproduced
fig6d-angle-and-day-largest-coefficients reproduced

How the analysis differs from the paper's. The paper's preprocessing, event pruning and visual removal of false positives were done before the data were deposited; the dataset holds 8088 events and marks none as false positives, so all are kept, for the behavioural claims and for every ECoG claim. The bad-segment rules use an assumed summary of segment power; with only segments with missing samples dropped, the across-subject tests, the day effects and the Table 1 outcome (22 of 24 inside) do not change (last data check above). Region power uses the paper's Figshare projection matrices, not a new projection from the AAL atlas. Bad electrodes are those of each subject's first file. The Morlet transform is computed by FFT and matches MNE's direct convolution. The regression models minimise the objective of sklearn's HuberRegressor by a batched Newton method, which matches sklearn's fits to 4.4e-05 in withheld R2; Delta R2 refits are run only at electrodes whose full-model R2 exceeds 0.05, the electrodes Figure 6c-d show. The day and time-of-day coefficient is the mean over splits of the SD of their one-hot coefficients; the SD of the split-averaged coefficients changes it by at most 0.004. On the electrodes selected by the R2 stored in the files, the fig6b-d results are the same. The code's log(x + 1) transforms of reach magnitude and onset speed are not run as a variant. In the code's Delta R2 variant the refit is shared with the main version and only the test events are shuffled.

What was found about the dataset. (1) In three files (S01 day 7, S04 day 3, S06 day 3) the ECoG covers only the end of the day but its starting_time is 0, while the event table and pose use a clock from midnight; the ECoG must be shifted by 8.1 to 8.5 h, as ReachEvents and the neural response show. (2) The files hold 8088 events; the data descriptor states 6931 verified events, and the paper's counts per subject are lower than the files'. (3) The reach angle is stored in image coordinates (upward negative) and unfolded, without saying so. (4) The pose is labelled meters but is in pixels. (5) session_start_time gives midnight UTC labelled as 19:00 at UTC-5. (6) Bimanual overlap is described as a fraction but reaches 3.83 (it is in seconds). (7) 124 event segments contain missing ECoG samples. (8) Sex and age are not recorded. (9) Seven subjects have electrode groups described as depth, where the paper says five.