cap32-mi-eeg / load_cap32.py
Twu31's picture
Initial release: 5 MI sessions, 5 calibrator recordings, loader, reports
aaa76e5 verified
Raw
History Blame Contribute Delete
5.47 kB
#!/usr/bin/env python
"""Standalone loader for the cap32 recordings — numpy only, no project code needed.
Everything you need is in the .npz: raw µV, the per-sample label track, the trial table,
and the gap track that says which samples were reconstructed after a UDP drop. The paired
_raw.fif is the same signal in MNE's format with the task labels as annotations, for people
who would rather start from `mne.io.read_raw_fif`.
python load_cap32.py # summarise every session
python load_cap32.py data/mi/cap32_20260725_163251_hands-feet-math.npz --epochs
"""
from __future__ import annotations
import argparse
import json
from pathlib import Path
import numpy as np
HERE = Path(__file__).resolve().parent
# The paradigm writes these small integers into the `marker` track at imagery onset.
CODE_TO_LABEL = {1: "rest", 2: "left", 3: "right", 4: "feet", 5: "tongue", 6: "hands",
10: "math", 11: "words", 12: "song", 13: "navigate", 14: "rotation",
15: "face"}
def load(path):
"""-> dict with data (n_ch, N) µV, fs, ch_names, marker/trigger/gap tracks, trials, meta."""
d = np.load(path, allow_pickle=True)
out = {k: d[k] for k in d.files if k != "meta_json"}
out["fs"] = float(d["fs"])
out["ch_names"] = [str(c) for c in d["ch_names"]]
out["meta"] = json.loads(str(d["meta_json"])) if "meta_json" in d.files else {}
if "trial_name" in d.files:
out["trials"] = [
dict(i=int(d["trial_index"][k]), name=str(d["trial_name"][k]),
code=int(d["trial_code"][k]), onset=int(d["trial_onset"][k]),
cue_onset=int(d["trial_cue_onset"][k]), end=int(d["trial_end"][k]))
for k in range(len(d["trial_name"]))
]
return out
def valid_trials(rec):
"""Trials whose imagery window actually exists in the data.
The 2026-07-25 hands-rest session hit a receiver stall: the acquisition thread blocked
on a socket with no timeout, so trials 20-50 were all logged at the same frozen sample
index (the end of the file). They are kept in the table for provenance but carry no
signal — filter with this, never with len(trials)."""
n = rec["data"].shape[1]
ts = rec.get("trials", [])
return [t for i, t in enumerate(ts)
if t["onset"] < n and (i == 0 or t["onset"] > ts[i - 1]["onset"])]
def epochs(rec, tmin=-1.0, tmax=4.0, drop_filled=True):
"""-> X (n_trials, n_ch, n_times) µV, y (labels), times. Cut around imagery onset.
`drop_filled` removes trials that overlap samples reconstructed across a UDP drop —
those samples are linear interpolation, not EEG, and they are flagged in rec['gap']."""
fs, X, y = rec["fs"], [], []
lo, hi = int(round(tmin * fs)), int(round(tmax * fs))
gap = rec.get("gap")
for t in valid_trials(rec):
a, b = t["onset"] + lo, t["onset"] + hi
if a < 0 or b > rec["data"].shape[1]:
continue
if drop_filled and gap is not None and gap[a:b].any():
continue
X.append(rec["data"][:, a:b])
y.append(t["name"])
return np.asarray(X), np.asarray(y), np.arange(lo, hi) / fs
def to_mne(rec):
"""-> mne.io.RawArray with the standard_1020 montage and task annotations."""
import mne
info = mne.create_info(rec["ch_names"], rec["fs"], "eeg")
raw = mne.io.RawArray(rec["data"] * 1e-6, info, verbose="ERROR") # MNE wants volts
raw.set_montage(mne.channels.make_standard_montage("standard_1020"),
match_case=False, on_missing="ignore")
ts = valid_trials(rec)
if ts:
raw.set_annotations(mne.Annotations(
onset=[t["onset"] / rec["fs"] for t in ts],
duration=[(t["end"] - t["onset"]) / rec["fs"] for t in ts],
description=[t["name"] for t in ts]))
return raw
def summarise(path):
rec = load(path)
n = rec["data"].shape[1]
tr, vt = rec.get("trials", []), valid_trials(rec)
gap = rec.get("gap")
print(f"\n{path.name}")
print(f" {rec['data'].shape[0]} ch × {n} samp = {n/rec['fs']:.0f} s @ {rec['fs']:.0f} Hz, µV")
if tr:
cnt = {}
for t in vt:
cnt[t["name"]] = cnt.get(t["name"], 0) + 1
print(f" trials: {len(vt)} usable of {len(tr)} logged {cnt}")
if len(vt) < len(tr):
print(f" ⚠ {len(tr)-len(vt)} trial(s) logged after the stream stalled — no signal")
if gap is not None and gap.any():
print(f" gap-filled: {int(gap.sum())} samp ({100*gap.mean():.3f} %) — interpolated, not EEG")
link = rec["meta"].get("link")
if link:
print(f" link: {link.get('loss_pct', 0):.3f} % frame loss")
def main():
ap = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("path", nargs="?", help="a .npz (default: summarise all)")
ap.add_argument("--epochs", action="store_true", help="also cut and report epochs")
a = ap.parse_args()
paths = [Path(a.path)] if a.path else sorted((HERE / "data" / "mi").glob("*.npz"))
for p in paths:
summarise(p)
if a.epochs:
X, y, t = epochs(load(p))
if len(X):
print(f" epochs: X {X.shape} y {dict(zip(*np.unique(y, return_counts=True)))}"
f" t [{t[0]:.1f}, {t[-1]:.1f}] s")
if __name__ == "__main__":
main()