A first BCI on four channels: the chance band held to Level 6's helper, eyes closed against eyes open on the occipitotemporal replica with a time-split calibrate-then-apply and the decoder frozen (and the leaky split beside it), the P300 at 16, 8 and 4 channels on one dry-headset subject, a steady-state response by canonical correlation on the planted flicker with the alpha caveat measured, a blink switch labelled EOG, and the decoder run block by block

nb-7-15-bci Level 7 · Applied Electives ~3 min Used in L7.15 · A first BCI on four channels

Downloads from ds-eegbci, ds-brain-invaders when you run it.

Download the notebook (.ipynb) Outputs below are the ones stored when it was executed — you do not need to run anything to read it.

nb-7-15-bci · A first BCI on four channels (L7.15)

Lesson L7.15 · Level 7 · Status draft — for expert review; uncertain points carry TODO(confirm).

Decoding was taught in L7.1 and Level 6 for a reader who had them; this notebook re-teaches only what four channels need: what is decodable at rank four, the chance band an accuracy has to clear, the leakage a split can smuggle in, and calibrate-then-apply with the decoder frozen so the application runs arrays rather than a fit nobody inspected.

  1. Eyes closed against eyes open on the occipitotemporal replica, twelve ds-eegbci subjects, with a time-split calibrate-then-apply — each subject has one eyes-open minute and one eyes-closed minute, no shippable four-channel set has two sessions, and the notebook says so. The median accuracy with its chance band is a keyed number. Beside it, the split that looks better and is leakage.
  2. P300 at 16, 8 and 4 channels on one ds-brain-invaders subject: the 16-channel number reproduced in the shape of nb-7-1's pipelines, then a Pz-containing subset chosen by a stated rule. The AUC at four channels is a keyed number.
  3. A steady-state response to a periodic stimulus, detected by canonical correlation on the planted synthetic flicker — no SSVEP recording exists on this site, and the caveat about alpha is measurable.
  4. A blink switch, labelled EOG, because on a frontal geometry it is the fastest control there is.
  5. The decoder block by block, with the same features as offline.

Every number comes from replayed public data or the synthetic stream; no headset produced anything here.

In [1]:
# Setup: dependencies, the shared helpers, the course library, non-interactive plotting, a quiet downloader.
import importlib.util
import logging
import subprocess
import sys
import time
import warnings
from pathlib import Path

_needed = ("mne", "scipy", "matplotlib", "pandas", "pooch", "sklearn", "pyriemann")
_missing = [p for p in _needed if importlib.util.find_spec(p) is None]
if _missing:
    _req = next((d / "requirements.txt" for d in (Path.cwd(), *Path.cwd().parents)
                 if (d / "requirements.txt").exists()), None)
    _cmd = [sys.executable, "-m", "pip", "install", "-q"]
    _cmd += ["-r", str(_req)] if _req else ["mne==1.10.2", "pooch>=1.8", "scikit-learn>=1.5", "pyriemann>=0.8"]
    subprocess.check_call(_cmd)

_shared = next((d / "_shared" for d in (Path.cwd(), *Path.cwd().parents)
                if (d / "_shared" / "helpers_l7.py").exists()), None)
if _shared is None:
    # No checkout around this notebook -- a downloaded .ipynb, or a fresh Colab kernel. Fetch the shared
    # helpers the site publishes beside it. With a checkout present the walk-up above wins and nothing
    # is downloaded; the modules land in ./_shared/ and are reused on every later run.
    import json as _json
    import urllib.request as _urllib
    _base = "https://eeg.neurokinetikz.com/notebooks/_shared/"
    _shared = Path.cwd() / "_shared"
    _shared.mkdir(exist_ok=True)
    for _name in _json.loads(_urllib.urlopen(_base + "index.json").read())["modules"]:
        if not (_shared / _name).exists():
            _urllib.urlretrieve(_base + _name, _shared / _name)
sys.path.insert(0, str(_shared))
import helpers_l7 as L7
_loop = L7.import_eegloop()   # loop/eegloop on sys.path from any directory of a checkout; returns loop/

import helpers
import helpers_l3 as L3
import helpers_l6 as L6
import helpers_l7 as L7
import eegloop
from eegloop.bci import (BCILoop, SSVEPDetector, StreamingPosterior, chance_interval, cut_epochs, fit_frozen, ssvep_cca, ssvep_decide,
                         temporal_split)
from eegloop.feedback import SignalSpec, build_chain
from eegloop.sources import ReplaySource, SyntheticSource, blocks
from eegloop.steps import Chain
from eegloop.steps.causal_filter import CausalFIR, fir_taps
from eegloop.steps.quality import QualityGate

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import mne
from scipy import signal as sps
from scipy.signal import lfilter
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import StratifiedKFold, cross_val_score

mne.set_log_level("WARNING")
logging.getLogger("pooch").setLevel(logging.WARNING)
warnings.filterwarnings("ignore", category=RuntimeWarning)
warnings.filterwarnings("ignore", category=FutureWarning)
plt.rcParams["figure.dpi"] = 72

SOURCE = "replay"
LOCAL_RECORDING = None      # a path to a recording of your own: a second pass on it, never shipped

DATASET = "ds-eegbci"
OC4 = ["O1", "O2", "T7", "T8"]
SUBJECTS = list(range(1, 13))
SEED = 20260920
_edf_before = set(Path(mne.get_config("MNE_DATA", str(Path.home() / "mne_data"))).rglob("*.edf"))
print(f"eegloop {eegloop.__version__} · mne {mne.__version__}")
eegloop 0.1.0 · mne 1.10.2

1 · What is decodable at rank four, and the band an accuracy has to clear

Four channels give four spatial degrees of freedom. A decoder can find a direction in that space that separates two states whose scalp patterns differ — eyes closed from eyes open by posterior alpha, a flicker response by its frequency, a blink by its frontal sign — and it cannot find sensorimotor mu without C3/C4 or a P300 without a centro-parietal site (L7.10's matrix). Whatever it finds, the number it reports is judged against the chance band: the binomial interval a classifier with no information reaches by luck in n trials, reproduced here from Level 6's helper and held to it.

In [2]:
for n, p in ((10, 0.5), (60, 0.5), (120, 0.5), (200, 0.5)):
    lo, hi = chance_interval(n, p)
    assert (lo, hi) == L6.chance_band(n, p)
    print(f"n = {n:4d}, {int(p * 100)} % chance: 95 % of chance classifiers score between {lo:.3f} and {hi:.3f}")
print("\nthe band shrinks as the trial count grows; an accuracy inside it is not evidence of decoding")
n =   10, 50 % chance: 95 % of chance classifiers score between 0.200 and 0.800
n =   60, 50 % chance: 95 % of chance classifiers score between 0.367 and 0.633
n =  120, 50 % chance: 95 % of chance classifiers score between 0.408 and 0.592
n =  200, 50 % chance: 95 % of chance classifiers score between 0.430 and 0.570

the band shrinks as the trial count grows; an accuracy inside it is not evidence of decoding

2 · Eyes closed against eyes open on the occipitotemporal replica

Each ds-eegbci subject has one eyes-open minute (R01) and one eyes-closed minute (R02), on gel electrodes with no hardware filters, and the replica cuts O1, O2, T7 and T8 from them. Both minutes are cut into non-overlapping four-second windows through the same causal chain the online loop runs (a 4–30 Hz FIR), so offline and online features are one computation. The split is temporal: the decoder is fitted on the first 60 % of each minute, a window is skipped, and it is applied to the last part — because a second session does not exist on any shippable four-channel set, and a random split over one minute lets the classifier learn the minute's slow state and call it the class. The site's genuine cross-session case is L7.1's train-on-one-session, test-on-the-other evaluation of ds-bci-iv-2a — compute-only (CC BY-ND, twenty-two channels), but the shape of the guard is the one to copy. The random split is run too, on overlapping windows, to show what it inflates.

In [3]:
t0 = time.time()
FS = 160.0
WIN_S, BAND = 4.0, (4.0, 30.0)
taps = fir_taps(129, BAND, FS)
CLASSES = ("eyes-open", "eyes-closed")

def windows(x, label, win_s=WIN_S, step_s=WIN_S):
    n = x.shape[1]
    cues = [(float(t), label) for t in np.arange(0.0, n / FS - win_s + 1e-9, step_s)]
    return cut_epochs(x, FS, cues, tmin_s=0.0, tmax_s=win_s, classes=CLASSES)

rows, pooled_true, pooled_pred, leaky_rows = [], [], [], []
for s in SUBJECTS:
    xs = {}
    for run, label in ((1, "eyes-open"), (2, "eyes-closed")):
        raw = helpers.load_spine(DATASET, s, run=run).pick(OC4)
        x = raw.get_data() * 1e6
        x = lfilter(taps, [1.0], x - x.mean(axis=1, keepdims=True), axis=1)   # the causal chain, applied to the whole minute
        xs[label] = x[:, :int(60 * FS)]
    # non-overlapping windows, in time order, per condition
    Xo, yo, to = windows(xs["eyes-open"], "eyes-open"); Xc, yc, tc = windows(xs["eyes-closed"], "eyes-closed")
    fit_o, app_o = temporal_split(len(yo), apply_frac=0.4, gap=1); fit_c, app_c = temporal_split(len(yc), apply_frac=0.4, gap=1)
    X_fit = np.concatenate([Xo[fit_o], Xc[fit_c]]); y_fit = np.concatenate([yo[fit_o], yc[fit_c]])
    X_app = np.concatenate([Xo[app_o], Xc[app_c]]); y_app = np.concatenate([yo[app_o], yc[app_c]])
    dec = fit_frozen("csp_lda", X_fit, y_fit, classes=CLASSES, fs=FS, ch_names=OC4, tmin_s=0.0, tmax_s=WIN_S, folds=3, seed=SEED,
                     band=BAND, filter_delay_samples=64.0, n_components=4)
    pred = np.argmax(dec.predict_proba_batch(X_app), axis=1)
    acc = float(np.mean(pred == y_app))
    rows.append({"subject": f"S{s:03d}", "fit windows": len(y_fit), "apply windows": len(y_app), "cv on fit (acc)": round(dec.report["cv_accuracy"], 2), "apply accuracy": round(acc, 3)})
    pooled_true += y_app.tolist(); pooled_pred += pred.tolist()
    # the split that looks better: overlapping 1-s-step windows, shuffled 5-fold CV over the whole minute
    Xo2, yo2, _ = windows(xs["eyes-open"], "eyes-open", step_s=1.0); Xc2, yc2, _ = windows(xs["eyes-closed"], "eyes-closed", step_s=1.0)
    X2, y2 = np.concatenate([Xo2, Xc2]), np.concatenate([yo2, yc2])
    from eegloop.bci.pipelines import csp_lda
    leaky = cross_val_score(csp_lda(4), X2, y2, cv=StratifiedKFold(5, shuffle=True, random_state=SEED)).mean()
    leaky_rows.append(float(leaky))
tab = pd.DataFrame(rows)
median_acc = float(tab["apply accuracy"].median())
n_pool = len(pooled_true); pooled_acc = float(np.mean(np.asarray(pooled_true) == np.asarray(pooled_pred)))
lo, hi = chance_interval(n_pool, 0.5)
lo_s, hi_s = chance_interval(int(tab["apply windows"].iloc[0]), 0.5)
print(tab.to_string(index=False))
print(f"\n{len(SUBJECTS)} subjects, {int(tab['apply windows'].iloc[0])} apply windows each ({time.time() - t0:.0f} s)")
print(f"median apply accuracy {median_acc:.3f}; chance band for one subject's {int(tab['apply windows'].iloc[0])} windows: {lo_s:.2f}–{hi_s:.2f}")
print(f"pooled over subjects: {pooled_acc:.3f} on {n_pool} windows; chance band {lo:.3f}–{hi:.3f}")
print(f"\nthe split that leaks — overlapping 1-s-step windows, shuffled 5-fold CV over the whole minute: mean accuracy {np.mean(leaky_rows):.3f} "
      f"(median {np.median(leaky_rows):.3f}) — higher, and worth nothing: adjacent windows share three seconds of signal and the minute's slow state")
subject  fit windows  apply windows  cv on fit (acc)  apply accuracy
   S001           16             12             1.00           1.000
   S002           16             12             1.00           0.917
   S003           16             12             1.00           0.833
   S004           16             12             1.00           1.000
   S005           16             12             1.00           0.833
   S006           16             12             0.81           0.500
   S007           16             12             1.00           0.667
   S008           16             12             1.00           0.750
   S009           16             12             0.68           0.500
   S010           16             12             0.81           0.583
   S011           16             12             1.00           0.833
   S012           16             12             0.93           0.750

12 subjects, 12 apply windows each (3 s)
median apply accuracy 0.791; chance band for one subject's 12 windows: 0.25–0.75
pooled over subjects: 0.764 on 144 windows; chance band 0.417–0.583

the split that leaks — overlapping 1-s-step windows, shuffled 5-fold CV over the whole minute: mean accuracy 0.955 (median 0.978) — higher, and worth nothing: adjacent windows share three seconds of signal and the minute's slow state
In [4]:
fig, ax = plt.subplots(figsize=(9, 3.6))
x = np.arange(len(tab))
ax.bar(x - 0.2, tab["apply accuracy"], 0.4, label="time split: fit on the first part, apply to the last (honest)")
ax.bar(x + 0.2, leaky_rows, 0.4, label="shuffled CV on overlapping windows (leaks)", color="0.6")
ax.axhspan(lo_s, hi_s, color="0.85", alpha=0.6, lw=0, label=f"chance band, n = {int(tab['apply windows'].iloc[0])}")
ax.set_xticks(x, tab.subject, rotation=45, fontsize=8)
ax.set(ylim=(0, 1.02), ylabel="Accuracy", title="Eyes closed vs eyes open on O1/O2/T7/T8: what the honest split reports, and what the leaky one would")
ax.legend(fontsize=8, loc="lower right"); plt.tight_layout(); plt.show()
Figure 1 of notebook nb-7-15-bci, an output plot. The text around it states what it shows and the units of every axis.

3 · P300 at 16, 8 and 4 channels

ds-brain-invaders ran a visual oddball on a 16-channel dry headset that includes Pz; one subject is loaded, epoched with the same recipe nb-3-2 and nb-7-5 used (0.1–40 Hz, −0.2 to 0.8 s, the recording's reference, a 150 µV rejection), resampled to 128 Hz, and decoded with Xdawn + shrinkage LDA — nb-7-1's first P300 pipeline, scored by AUC because an oddball is imbalanced — at 16 channels, then at 8 and 4. The four-channel subset is chosen by a stated rule: the four sites nearest Pz on the unit sphere that the headset carries. Folds are in trial order, never shuffled. The decoders are fitted through the library and frozen, so the same arrays that score here are what an application would run.

In [5]:
t0 = time.time()
raw_bi = helpers.load_spine("ds-brain-invaders", 1)
raw_bi.filter(L3.HP_HZ, L3.LP_HZ, picks="eeg", method="fir", fir_design="firwin", phase="zero", verbose=False)
events_bi = mne.find_events(raw_bi, stim_channel="STI 014", shortest_event=1, verbose=False)
ep = mne.Epochs(raw_bi, events_bi, helpers.BI2014A_EVENT_ID, tmin=L3.EPOCH_TMIN, tmax=L3.EPOCH_TMAX, baseline=L3.EPOCH_BASELINE,
                picks="eeg", preload=True, verbose=False)
d = ep.get_data() * 1e6
keep = (d.max(2) - d.min(2)).max(1) <= L3.REJECT_PTP_UV
ep = ep[np.where(keep)[0]].resample(128.0, verbose=False)
X_bi = ep.get_data() * 1e6
y_bi = (ep.events[:, 2] == helpers.BI2014A_EVENT_ID["Target"]).astype(int)
names_bi = tuple(ep.ch_names)
print(f"ds-brain-invaders subject 1: {len(names_bi)} channels {names_bi}; {X_bi.shape[0]} epochs kept of {len(keep)} ({int(y_bi.sum())} targets), "
      f"{X_bi.shape[2]} samples at 128 Hz  ({time.time() - t0:.0f} s)")

# the subsets: the 8 of nb-7-5, and the four sites nearest Pz on the unit sphere among the headset's sites
_m = mne.channels.make_standard_montage("standard_1005"); _p = _m.get_positions()["ch_pos"]
_c = np.mean(np.array(list(_p.values())), axis=0)
unit = {n: (v - _c) / np.linalg.norm(v - _c) for n, v in _p.items()}
dist = sorted((float(np.linalg.norm(unit[c] - unit["Pz"])), c) for c in names_bi if c in unit)
NEAREST_4 = [c for _, c in dist[:4]]
SUBSETS = {"16 (full headset)": list(names_bi), "8 (midline + posterior, nb-7-5's)": [c for c in ("Fp1", "Fp2", "Cz", "P3", "Pz", "P4", "O1", "O2") if c in names_bi],
           f"4 (nearest Pz: {', '.join(NEAREST_4)})": NEAREST_4}
print("subsets:", {k: len(v) for k, v in SUBSETS.items()})
p300_rows, p300_dec = [], {}
for label, chs in SUBSETS.items():
    idx = [names_bi.index(c) for c in chs]
    dec = fit_frozen("xdawn_lda", X_bi[:, idx, :], y_bi, classes=("NonTarget", "Target"), fs=128.0, ch_names=chs, tmin_s=L3.EPOCH_TMIN, tmax_s=L3.EPOCH_TMAX,
                     folds=5, seed=SEED, n_components=2 if len(chs) >= 4 else 1)
    p300_dec[label] = dec
    p300_rows.append({"channels": label, "n_channels": len(chs), "cv AUC (folds in trial order)": round(dec.report["cv_auc"], 3), "cv accuracy": round(dec.report["cv_accuracy"], 3),
                      "chance band (acc)": f"{dec.report['chance']['band_95'][0]:.2f}–{dec.report['chance']['band_95'][1]:.2f}"})
p300_tab = pd.DataFrame(p300_rows)
print(p300_tab.to_string(index=False))
auc16 = float(p300_tab.iloc[0]["cv AUC (folds in trial order)"]); auc4 = float(p300_tab.iloc[2]["cv AUC (folds in trial order)"])
print(f"\nnb-7-1 reports Xdawn + LDA within-subject at 0.9117 AUC as a MEAN over subjects with moabb's own epoching (1–20 Hz, 0–0.8 s, 5-fold shuffled); "
      f"this is ONE subject with the L3 recipe and folds in trial order: {auc16:.3f} at 16 channels. Same family, different numbers, both stated.")
ds-brain-invaders subject 1: 16 channels ('Fp1', 'Fp2', 'F3', 'AFz', 'F4', 'T7', 'Cz', 'T8', 'P7', 'P3', 'Pz', 'P4', 'P8', 'O1', 'Oz', 'O2'); 509 epochs kept of 1188 (84 targets), 128 samples at 128 Hz  (2 s)
subsets: {'16 (full headset)': 16, "8 (midline + posterior, nb-7-5's)": 8, '4 (nearest Pz: Pz, P3, P4, Oz)': 4}
                         channels  n_channels  cv AUC (folds in trial order)  cv accuracy chance band (acc)
                16 (full headset)          16                          0.944        0.902         0.46–0.54
8 (midline + posterior, nb-7-5's)           8                          0.940        0.900         0.46–0.54
   4 (nearest Pz: Pz, P3, P4, Oz)           4                          0.846        0.839         0.46–0.54

nb-7-1 reports Xdawn + LDA within-subject at 0.9117 AUC as a MEAN over subjects with moabb's own epoching (1–20 Hz, 0–0.8 s, 5-fold shuffled); this is ONE subject with the L3 recipe and folds in trial order: 0.944 at 16 channels. Same family, different numbers, both stated.

4 · A steady-state response, by canonical correlation

No SSVEP recording exists on this site (ds-aszed is not a positive control: nb-4-5 found no response at its stated rate), so the detector runs on the planted synthetic flicker — 12 Hz from 20 to 40 s, 15 Hz from 60 to 80 s — where the answer is known. The detector is one QR and one SVD per candidate frequency, no fitting, no labels. And the caveat is measurable before it is stated: a standing alpha rhythm correlates with a 10 Hz reference in every window, flicker or not.

In [6]:
src = SyntheticSource("ssvep", seed=SEED, duration_s=90.0, pace="fast")
print("planted:", src.truth["flicker"])
det = SSVEPDetector(src.info.fs, src.info.n_channels, (12.0, 15.0), window_s=4.0, step_samples=64, margin=0.1)
decisions = []
for b in blocks(src, 32):
    r = det.update(b)
    if r is not None:
        decisions.append((b.t_end_s, r[0], r[1]))
t_dec = np.array([t for t, _, _ in decisions]); f_dec = np.array([np.nan if f is None else f for _, f, _ in decisions])
def frac(t0, t1, f):
    m = (t_dec >= t0) & (t_dec <= t1)
    return float(np.mean(f_dec[m] == f)) if f is not None else float(np.mean(np.isnan(f_dec[m])))
print(f"windows ending 25–40 s: 12 Hz in {frac(25, 40, 12.0) * 100:.0f} %; windows ending 65–80 s: 15 Hz in {frac(65, 80, 15.0) * 100:.0f} %; "
      f"no stimulus (45–58 s): no decision in {frac(45, 58, None) * 100:.0f} %")
r10 = [ssvep_cca(src._data[:, int(t0 * src.info.fs):int((t0 + 4) * src.info.fs)], src.info.fs, (10.0,))[10.0] for t0 in (5.0, 25.0, 65.0)]
print(f"the alpha caveat: CCA with a 10 Hz reference reads r = {', '.join(f'{r:.2f}' for r in r10)} at 5 s (no flicker), 25 s (12 Hz flicker), 65 s (15 Hz flicker) — "
      "a standing alpha rhythm looks like a 10 Hz response whatever flickers; stimulus frequencies belong outside the alpha band")
planted: [{'onset_s': 20.0, 'duration_s': 20.0, 'freq_hz': 12.0, 'amplitude_uv': 8.0}, {'onset_s': 60.0, 'duration_s': 20.0, 'freq_hz': 15.0, 'amplitude_uv': 8.0}]
windows ending 25–40 s: 12 Hz in 100 %; windows ending 65–80 s: 15 Hz in 100 %; no stimulus (45–58 s): no decision in 100 %
the alpha caveat: CCA with a 10 Hz reference reads r = 0.52, 0.42, 0.45 at 5 s (no flicker), 25 s (12 Hz flicker), 65 s (15 Hz flicker) — a standing alpha rhythm looks like a 10 Hz response whatever flickers; stimulus frequencies belong outside the alpha band

On a frontal geometry the fastest control is not EEG at all: a voluntary blink is a same-sign deflection on the frontal pair of a hundred microvolts or more, and the quality gate already labels it. A switch built on it is an electro-oculogram switch and is labelled so; it is honest, it works, and it is not a brain–computer interface.

In [7]:
blinks = SyntheticSource("blinks", seed=SEED, duration_s=120.0, blink_times_s=tuple(np.arange(6.0, 118.0, 7.0)), pace="fast")
gate = QualityGate(blinks.info.fs, blinks.info.ch_names, window_s=1.0, hold_s=0.5, mains_hz=60.0)
presses, last = [], -10.0
for b in blocks(blinks, 32):
    q = gate.process(b).flags["quality"]
    if "blink" in q["labels"] and b.t_end_s - last > 1.5:
        presses.append(b.t_end_s); last = b.t_end_s
onsets = blinks.truth["blink_onsets_s"]
hit = sum(any(abs(p - o) <= 1.5 for p in presses) for o in onsets)
print(f"{len(onsets)} planted blinks, {len(presses)} switch presses, {hit} within 1.5 s of a planted blink, {len(presses) - hit} spurious — an EOG switch on the frontal pair, labelled as such")
16 planted blinks, 16 switch presses, 16 within 1.5 s of a planted blink, 0 spurious — an EOG switch on the frontal pair, labelled as such

6 · The decoder block by block, with the same features as offline

The frozen eyes-closed/eyes-open decoder of one subject, applied to that subject's held-out minute as a stream through BCILoop in sliding mode — the same causal chain, the same window, the same arrays — so the posterior the application would show is the one the offline table reported.

In [8]:
s = SUBJECTS[0]
xs = {}
for run, label in ((1, "eyes-open"), (2, "eyes-closed")):
    raw = helpers.load_spine(DATASET, s, run=run).pick(OC4)
    x = raw.get_data() * 1e6
    xs[label] = (x - x.mean(axis=1, keepdims=True))[:, :int(60 * FS)]
# fit on the first part of each minute (raw, through the chain), as section 2 did
Xo, yo, _ = windows(lfilter(taps, [1.0], xs["eyes-open"], axis=1), "eyes-open"); Xc, yc, _ = windows(lfilter(taps, [1.0], xs["eyes-closed"], axis=1), "eyes-closed")
fit_o, app_o = temporal_split(len(yo), apply_frac=0.4, gap=1); fit_c, app_c = temporal_split(len(yc), apply_frac=0.4, gap=1)
dec = fit_frozen("csp_lda", np.concatenate([Xo[fit_o], Xc[fit_c]]), np.concatenate([yo[fit_o], yc[fit_c]]), classes=CLASSES, fs=FS, ch_names=OC4,
                 tmin_s=0.0, tmax_s=WIN_S, folds=3, seed=SEED, band=BAND, filter_delay_samples=64.0)
# the held-out part of the eyes-closed minute, as a stream: the last 40 % after the gap
t_start = float(app_c[0] * WIN_S)
stream = ReplaySource(xs["eyes-closed"][:, int(t_start * FS):], fs=FS, ch_names=OC4, pace="fast", block_samples=32)
chain = Chain([CausalFIR(taps, len(OC4))])
loop = BCILoop(stream, chain, block_samples=32, decoder=dec, mode="sliding", step_samples=32, smooth_s=0.5, threshold=0.7, dwell_s=1.0, refractory_s=2.0)
stats = loop.run([("test", 60.0)])
n_ec = sum(1 for d_ in stats.decisions if d_["label"] == "eyes-closed"); n_eo = sum(1 for d_ in stats.decisions if d_["label"] == "eyes-open")
print(f"S{s:03d}, held-out eyes-closed stretch ({stats.duration_s:.0f} s) through BCILoop: {stats.n_posteriors} posteriors, {len(stats.decisions)} decisions — "
      f"{n_ec} eyes-closed, {n_eo} eyes-open; decoder latency {dec.latency_samples:.0f} samples ({dec.latency_samples / FS * 1000:.0f} ms) plus the dwell")
print("latency note:", dec.latency_note)
S001, held-out eyes-closed stretch (24 s) through BCILoop: 101 posteriors, 10 decisions — 10 eyes-closed, 0 eyes-open; decoder latency 640 samples (4000 ms) plus the dwell
latency note: a window of 640 samples (4000 ms) is the delay; the causal filter before it adds 64 samples, exact; the decision rule's dwell is on top of both and is a choice, not a cost of the decoder

Your own recording, if you have one

When LOCAL_RECORDING names a file — a .bin with its sidecar as eegloop run --record-raw writes it, or an .npz — the cell below runs this notebook's measurement on it and prints the result titled as yours; when it is None the cell is skipped entirely, so nothing empty ships. Nothing from your recording is written into this notebook's outputs on the site: it is a second pass, never shipped (CONTRACTS, Phase 5).

In [9]:
if LOCAL_RECORDING is not None:
    mine = ReplaySource(LOCAL_RECORDING, pace="fast", block_samples=32)
    if tuple(mine.info.ch_names) != tuple(dec.ch_names):
        print(f"your recording has channels {mine.info.ch_names}; the frozen decoder was fitted on {dec.ch_names} — a decoder is a fact about its montage, so it is not applied")
    else:
        taps_mine = fir_taps(129, BAND, mine.info.fs)
        loop_mine = BCILoop(mine, Chain([CausalFIR(taps_mine, len(dec.ch_names))]), block_samples=32, decoder=dec, mode="sliding",
                            step_samples=32, smooth_s=0.5, threshold=0.7, dwell_s=1.0, refractory_s=2.0)
        st = loop_mine.run([("test", mine.duration_s)])
        per = {c: sum(1 for d_ in st.decisions if d_["label"] == c) for c in dec.classes}
        print(f"your recording — not shipped: {st.n_posteriors} posteriors, {len(st.decisions)} decisions {per}; no cues, so nothing here is an accuracy")
else:
    print("LOCAL_RECORDING is None: skipped (set it to a .bin with its sidecar, or an .npz, with the replica's channel names to run the frozen decoder over your own file)")
LOCAL_RECORDING is None: skipped (set it to a .bin with its sidecar, or an .npz, with the replica's channel names to run the frozen decoder over your own file)

7 · The numbers the lesson's exercises ask for

In [10]:
print("nb-7-15-bci — L7.15 numbers (draft; TODO(confirm) at author review)")
print()
print(f"(a) Eyes closed vs eyes open on the occipitotemporal-4 replica, {len(SUBJECTS)} ds-eegbci subjects, time-split calibrate-then-apply (4-s windows, 4–30 Hz causal FIR, CSP + LDA): "
      f"median apply accuracy {median_acc:.3f} with the chance band {lo_s:.2f}–{hi_s:.2f} for {int(tab['apply windows'].iloc[0])} windows; pooled {pooled_acc:.3f} on {n_pool} (band {lo:.3f}–{hi:.3f}). "
      f"The leaky split reports {np.mean(leaky_rows):.3f}.")
print(f"(b) P300 AUC on ds-brain-invaders subject 1 (Xdawn + shrinkage LDA, folds in trial order): {auc16:.3f} at 16 channels, {float(p300_tab.iloc[1]['cv AUC (folds in trial order)']):.3f} at 8, "
      f"{auc4:.3f} at 4 ({', '.join(NEAREST_4)}).")
print("(c) Fitting and applying on overlapping windows: adjacent windows share most of their samples and the minute's slow state, so a shuffled split scores the copy, not the class — "
      "the honest split is temporal, with a gap, or a second session.")
print()
print(f"SSVEP on the planted flicker: 12 Hz found in {frac(25, 40, 12.0) * 100:.0f} % of its windows, 15 Hz in {frac(65, 80, 15.0) * 100:.0f} %; the alpha caveat r ≈ {np.mean(r10):.2f} at 10 Hz throughout.")
nb-7-15-bci — L7.15 numbers (draft; TODO(confirm) at author review)

(a) Eyes closed vs eyes open on the occipitotemporal-4 replica, 12 ds-eegbci subjects, time-split calibrate-then-apply (4-s windows, 4–30 Hz causal FIR, CSP + LDA): median apply accuracy 0.791 with the chance band 0.25–0.75 for 12 windows; pooled 0.764 on 144 (band 0.417–0.583). The leaky split reports 0.955.
(b) P300 AUC on ds-brain-invaders subject 1 (Xdawn + shrinkage LDA, folds in trial order): 0.944 at 16 channels, 0.940 at 8, 0.846 at 4 (Pz, P3, P4, Oz).
(c) Fitting and applying on overlapping windows: adjacent windows share most of their samples and the minute's slow state, so a shuffled split scores the copy, not the class — the honest split is temporal, with a gap, or a second session.

SSVEP on the planted flicker: 12 Hz found in 100 % of its windows, 15 Hz in 100 %; the alpha caveat r ≈ 0.46 at 10 Hz throughout.

Cleanup

Only what this run fetched is deleted; the Brain Invaders subject is the notebooks' shared spine copy and is kept.

In [11]:
_edf_after = set(Path(mne.get_config("MNE_DATA", str(Path.home() / "mne_data"))).rglob("*.edf"))
_new = sorted(_edf_after - _edf_before)
for p_ in _new:
    p_.unlink(missing_ok=True)
assert len(tab) == len(SUBJECTS)
print(f"deleted {len(_new)} EDF file(s) this run fetched; kept everything that was already cached; cohort {len(tab)}/{len(SUBJECTS)}")
deleted 0 EDF file(s) this run fetched; kept everything that was already cached; cohort 12/12