nb-7-10-headband · What a four-channel headband measures (L7.10)¶
Lesson L7.10 · Level 7 · Status draft — for expert review; uncertain points carry TODO(confirm).
A four-electrode headband is not a small research cap. It is a different instrument, and the difference is a set of facts — which four sites, what rate, what bandwidth, what reference, what the device filtered before you saw the stream — from which the analyses that remain available follow. This notebook reads those facts, then measures what they imply.
- The two geometries, as facts. The course's library names each device once, in one table; everywhere else
a device is its montage class —
frontotemporal-4(TP9, AF7, AF8, TP10) oroccipitotemporal-4(O1, O2, T7, T8). The nearest research-cap sites to TP9 and TP10 are computed from electrode positions, not asserted (they turn out to be T9/T10, then TP7/TP8 — and neither is TP9/TP10). - A first-look report of a four-channel stream, with the checklist of L0.6 applied to four channels.
- The occipitotemporal replica on
ds-eegbci: all four of its sites are in the 64-channel cap, so the emulation is exact in geometry (and only in geometry — the electrodes, the contact and the front-end are a gel research amplifier's). Eyes-closed against eyes-open alpha on twelve subjects. - The frontotemporal geometry on synthetic data with its real channel names — because the cap has AF7/AF8 and TP7/TP8 but not TP9/TP10, and no licensed recording of that geometry is on the site yet.
- The bandwidth is the band, not the Nyquist frequency: measured on the replica, then stated for the case the exercise asks about.
- What an on-device notch and a 1–40 Hz filter remove from what you can later check, measured with the live quality gate's own criteria.
- Which analyses survive which geometry — a matrix, with the reason in every cell.
Everything here runs on replayed or synthetic data. SOURCE = 'device' is a route for your own headset and is
never used to produce anything on the site (CONTRACTS, Phase 5: no live output is an answer key).
# Setup: dependencies, the shared helpers, the course library, non-interactive plotting, a quiet downloader.
import importlib.util
import json
import logging
import subprocess
import sys
import time
import warnings
from pathlib import Path
_needed = ("mne", "scipy", "matplotlib", "pandas", "pooch")
_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"]
subprocess.check_call(_cmd)
# The shared helpers and the course library are found by walking up from the working directory
# (notebooks/L7/ or notebooks/), never through an absolute path.
_shared = next((d / "_shared" for d in (Path.cwd(), *Path.cwd().parents)
if (d / "_shared" / "helpers.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/
_site_data = next((d / "site" / "public" / "data" for d in (Path.cwd(), *Path.cwd().parents)
if (d / "site" / "public" / "data" / "widgets").exists()), None)
import helpers
import eegloop
from eegloop.check import bandwidth_edge_hz, line_ratio, run_check
from eegloop.sources import ReplaySource, SyntheticSource, blocks
from eegloop.sources.brainflow import BOARDS, board_table
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
mne.set_log_level("WARNING")
logging.getLogger("pooch").setLevel(logging.WARNING) # silence the downloader at the source: no cache paths in outputs
warnings.filterwarnings("ignore", category=RuntimeWarning)
plt.rcParams["figure.dpi"] = 72
# Which stream this notebook runs on. The site, CI and every number below use 'replay' (ds-eegbci) and
# 'synthetic'; 'device' opens your own headset through the driver and produces nothing that ships.
SOURCE = "replay"
LOCAL_RECORDING = None # a path to a recording of your own (a .bin with its sidecar, or .npz): a second pass on it, never shipped
DATASET = "ds-eegbci"
OC4 = ["O1", "O2", "T7", "T8"] # occipitotemporal-4, in the montage's stated order
FT4 = ["TP9", "AF7", "AF8", "TP10"] # frontotemporal-4
SUBJECTS = list(range(1, 13)) # S001–S012: R01 eyes open, R02 eyes closed
_edf_before = set(Path(mne.get_config("MNE_DATA", str(Path.home() / "mne_data"))).rglob("*.edf"))
print(f"eegloop {eegloop.__version__} · mne {mne.__version__} · numpy {np.__version__}")
1 · The two geometries, as facts¶
The library names a device exactly once, in its board table (eegloop.sources.brainflow.BOARDS), with a date
on every fact and a TODO(confirm) on every one a report from the device has yet to settle. Lessons say "the
driver's board table" and describe a device by its montage class. Print the table, then compute — rather
than assert — which research-cap sites are nearest to the two the cap lacks.
print(board_table())
print()
for key, b in BOARDS.items():
print(f"{key:14s} {b['montage']:20s} {', '.join(b['channels']):22s} {b['fs']:g} Hz filters: {b['reported_filters'][:70]}…")
# Electrode positions: the site's own positions.json (MNE standard_1005 on a unit sphere) when the checkout is
# here, else the same montage straight from MNE — the answer is the same, the source is stated.
if _site_data is not None and (_site_data / "widgets" / "w-montage-explorer" / "positions.json").exists():
_pos = json.loads((_site_data / "widgets" / "w-montage-explorer" / "positions.json").read_text())
XYZ = {n: np.array(e["xyz"]) for n, e in _pos["electrodes"].items()}
EEGBCI64 = list(_pos["montages"]["eegbci-64"])
print(f"\npositions: site/public/data/widgets/w-montage-explorer/positions.json ({len(XYZ)} electrodes); "
f"montages there: {', '.join(k for k in _pos['montages'] if k.endswith('-4'))}")
else:
_m = mne.channels.make_standard_montage("standard_1005")
_p = _m.get_positions()["ch_pos"]
_c = np.mean(np.array(list(_p.values())), axis=0)
XYZ = {n: (v - _c) / np.linalg.norm(v - _c) for n, v in _p.items()}
EEGBCI64 = None
print("\npositions: MNE standard_1005 (the site's positions.json was not found)")
def nearest(site, candidates, k=3):
d = sorted(((float(np.linalg.norm(XYZ[c] - XYZ[site])), c) for c in candidates if c in XYZ and c != site))
return [(c, round(dist, 3)) for dist, c in d[:k]]
cand = EEGBCI64 or [c for c in XYZ if c in {"TP7", "TP8", "T7", "T8", "P7", "P8", "AF7", "AF8", "O1", "O2"}]
for site in ("TP9", "TP10", "AF7", "AF8"):
print(f"nearest 64-cap sites to {site:4s}: {nearest(site, cand)}")
print("\nSo the occipitotemporal-4 geometry is exactly a subset of the 64-channel cap, and the frontotemporal-4 "
"geometry is not: the cap has AF7/AF8 but no TP9/TP10, and its nearest sites to those two -- T9/T10, then "
"TP7/TP8, by the distances above -- are different locations, not the same electrode under another name. "
"The replica below uses only the exact geometry.")
2 · A first-look report of a four-channel stream¶
Lesson L0.6's first look, applied to four channels. Everything the report reads is metadata a stream carries
or a fact the catalog records; nothing is a judgment about a product. On SOURCE = 'replay' the stream is
ds-eegbci S001 R02 (eyes closed) restricted to the occipitotemporal sites.
t0 = time.time()
raw_full = helpers.load_spine(DATASET, 1, run=2)
raw_oc4 = raw_full.copy().pick(OC4)
rep = helpers.first_look_report(raw_oc4, DATASET)
for k in ("dataset", "description", "sfreq_hz", "nyquist_hz", "n_channels", "eeg_channels", "duration_s",
"highpass_hz_in_header", "lowpass_hz_in_header", "montage_attached", "n_annotations"):
print(f"{k:24s} {rep.get(k)}")
print()
rows = helpers.first_look_checks(raw_oc4, DATASET, mains_hz=60.0, expected_n_channels=4, consistency=False)
for r in rows:
print(f"[{r['status']:4s}] {r['item']:18s} {r['value']}" + (f" — {r['note']}" if r['note'] else ""))
print(f"\n({time.time() - t0:.1f} s)")
The channel-count row says four EEG channels of four, as expected, and says nothing about whether four is enough — that is section 7's question. The sampling-rate row matches the documented 160 Hz, and the header's low-pass value is what the file says, not what the amplifier passed: section 5 measures that.
3 · The occipitotemporal replica across twelve subjects¶
ds-eegbci has one eyes-open minute (R01) and one eyes-closed minute (R02) per subject. On the four sites of the
replica, the eyes-closed alpha peak is measured with the same estimator every lesson on this site uses
(helpers.alpha_peak: the largest residual above a straight-line fit of log power against log frequency,
reported only when it exceeds 3 dB), restricted to O1 and O2. The fraction of subjects with a detectable
peak on the replica is the second number the lesson's exercises ask for.
t0 = time.time()
records = []
psd_example = {}
for s in SUBJECTS:
for run, cond in ((1, "eyes-open"), (2, "eyes-closed")):
raw = helpers.load_spine(DATASET, s, run=run)
missing = [c for c in OC4 if c not in raw.ch_names]
if missing:
print(f"S{s:03d} R{run:02d}: missing {missing}; skipped")
continue
sub = raw.copy().pick(OC4)
pk = helpers.alpha_peak(sub, picks=("O1", "O2"))
records.append({"subject": f"S{s:03d}", "condition": cond, "alpha_peak_hz": pk["freq_hz"],
"db_above_trend": pk["db_above_trend"]})
if s == 1:
spec = sub.compute_psd(method="welch", fmin=1, fmax=79, n_fft=int(2 * sub.info["sfreq"]), verbose=False)
psd_example[cond] = spec
tab = pd.DataFrame(records)
ec = tab[tab.condition == "eyes-closed"].set_index("subject")
eo = tab[tab.condition == "eyes-open"].set_index("subject")
n_ec_peak = int(ec.alpha_peak_hz.notna().sum())
n_eo_peak = int(eo.alpha_peak_hz.notna().sum())
print(f"{len(ec)} subjects on the occipitotemporal-4 replica (O1+O2):")
print(f" eyes closed: {n_ec_peak}/{len(ec)} with a peak ≥ 3 dB above trend "
f"(median peak {ec.alpha_peak_hz.median():.2f} Hz, median height {ec.db_above_trend.median():.1f} dB)")
print(f" eyes open: {n_eo_peak}/{len(eo)} with a peak ≥ 3 dB above trend "
f"(median height {eo.db_above_trend.median():.1f} dB)")
print(f"\n({time.time() - t0:.1f} s)")
display(pd.concat({"eyes-closed": ec[["alpha_peak_hz", "db_above_trend"]], "eyes-open": eo[["alpha_peak_hz", "db_above_trend"]]}, axis=1).round(2))
fig, axes = plt.subplots(1, 2, figsize=(13, 4.2))
ax = axes[0]
for cond, spec in psd_example.items():
p, f = spec.get_data(return_freqs=True)
for i, ch in enumerate(spec.ch_names):
ax.semilogy(f, p[i] * 1e12, lw=1.2 if ch in ("O1", "O2") else 0.8, alpha=1 if ch in ("O1", "O2") else 0.5,
color="C0" if cond == "eyes-closed" else "C1", label=f"{cond} {ch}" if ch in ("O1", "O2") else None)
ax.axvspan(8, 12, color="0.85", alpha=0.5, lw=0)
ax.set(xlabel="Frequency (Hz)", ylabel="Power (µV²/Hz)", xlim=(1, 79),
title="S001 on the occipitotemporal-4 replica: O1/O2 bold, T7/T8 faint")
ax.legend(fontsize=8, ncol=2)
ax = axes[1]
x = np.arange(len(ec))
ax.bar(x - 0.2, ec.db_above_trend.values, 0.4, label="eyes closed", color="C0")
ax.bar(x + 0.2, eo.db_above_trend.values, 0.4, label="eyes open", color="C1")
ax.axhline(3, color="k", lw=0.8, ls="--", label="3 dB criterion")
ax.set_xticks(x, ec.index, rotation=45, fontsize=8)
ax.set(ylabel="Alpha peak height above trend (dB)", title=f"{n_ec_peak}/{len(ec)} subjects show an eyes-closed peak on O1+O2")
ax.legend(fontsize=8)
plt.tight_layout(); plt.show()
What this is, and is not. The four channels are four of the cap's 64: the geometry is the headband's, the electrodes, contact, reference and amplifier are a research system's. The number says what an eyes-closed alpha peak looks like at these sites, on gel, with no hardware filters. On a dry headband at those sites the peak is measured by the same estimator, and the sidecar of any such recording says which front-end it came from.
4 · The frontotemporal geometry, on synthetic data with its real names¶
The cap has no TP9 or TP10, so the frontotemporal geometry has no exact replica here. The library's synthetic
stream carries the real channel names of that geometry with planted answers — a standing 10 Hz weighted towards
the posterior-temporal pair, frontal blinks, a mains line — and the acceptance report eegloop check runs on
any stream runs on it. Every number in this section is planted, not recorded, and the report says so in its
first line.
src = SyntheticSource("alpha-schedule", duration_s=40.0, pace="fast")
print("stream:", src.info.kind, src.info.ch_names, f"{src.info.fs:g} Hz;", "planted:",
{k: src.truth[k] for k in ("alpha_bursts", "mains_hz", "line_uv", "drift_ppm")})
report = run_check(src, seconds=30.0, mains_hz=float(src.truth["mains_hz"]))
for r in report["rows"]:
print(f"[{r['status']:4s}] {r['item']:18s} {r['value']}")
print()
for r in report["per_channel"]:
print(f" {r['channel']:5s} SD {r['sd_uv']:5.1f} µV line60 {r['line_60_ratio']:5.1f} edge {r['bandwidth_edge_hz']} labels {r['gate_labels']}")
The same report on a headband would carry the driver's descriptor, the measured rate against the claimed one, the
package-counter accounting and the timestamp structure — the rows that only a live stream can fill. Those rows
are what site/notes/device-<key>.md holds once the author has run the report on the device itself; nothing
from such a run appears in a notebook (CONTRACTS, Phase 5, rule 6).
5 · The bandwidth is the band, not the Nyquist frequency¶
A 160 Hz stream has a Nyquist frequency of 80 Hz. Whether there is anything to analyse up to 80 Hz is a separate fact: the amplifier's own roll-off. The library's report measures the bandwidth edge — the frequency above which the spectrum stays 20 dB below its 4–20 Hz level for the rest of the way to Nyquist — and it is measured here on the replica, on a research cap documented as having no hardware filters.
x_oc4 = raw_oc4.get_data(picks=OC4) * 1e6
x_oc4 = x_oc4 - x_oc4.mean(axis=1, keepdims=True)
sf = float(raw_oc4.info["sfreq"])
edges = {ch: bandwidth_edge_hz(x_oc4[i], sf) for i, ch in enumerate(OC4)}
print(f"ds-eegbci S001 R02 on the replica: Nyquist {sf / 2:g} Hz; bandwidth edge per channel (20 dB below the 4–20 Hz level):")
for ch, e in edges.items():
print(f" {ch:4s} {'none below Nyquist' if e is None else f'{e:.0f} Hz'}")
fig, ax = plt.subplots(figsize=(8, 4))
for i, ch in enumerate(OC4):
f, p = sps.welch(x_oc4[i], fs=sf, nperseg=int(2 * sf))
ax.semilogy(f, p, lw=1.1, label=ch)
ax.axvline(sf / 2, color="k", ls="--", lw=0.8, label=f"Nyquist {sf / 2:g} Hz")
for ch, e in edges.items():
if e is not None:
ax.axvline(e, color="0.6", ls=":", lw=0.8)
ax.set(xlabel="Frequency (Hz)", ylabel="Power (µV²/Hz)", xlim=(1, sf / 2), title="Where the spectrum stops carrying anything is a measurement, not the rate")
ax.legend(fontsize=8); plt.tight_layout(); plt.show()
# The case the exercise asks about, as arithmetic: a stream sampled at 250 Hz whose documented band ends at 100 Hz.
rate, band_end = 250.0, 100.0
print(f"\nA stream at {rate:g} Hz: Nyquist {rate / 2:g} Hz. Documented band 0–{band_end:g} Hz.")
print(f"Highest frequency you may analyse: {min(rate / 2, band_end):g} Hz — the ceiling is the band, not the Nyquist frequency.")
6 · What an on-device notch and a 1–40 Hz filter remove from what you can later check¶
One of the two geometries' devices offers an optional on-device notch and a 1–40 Hz band-pass (the driver's
board table records that they must be OFF for this course, and that the switch is TODO(confirm)). The cost of
leaving them on is not the mains line or the beta band. It is the diagnostics: the live quality gate reads the
line ratio, the 25–100 Hz muscle band and the DC level of a flat channel from the raw block, and a stream that
arrives notched and band-limited has had exactly that evidence removed. Measure it on the replica, with the same
operations applied offline at this recording's mains frequency.
def gate_label_rates(x, fs, names, mains):
src = ReplaySource(x, fs=fs, ch_names=names, pace="fast", block_samples=32)
gate = QualityGate(fs, names, window_s=1.0, hold_s=0.0, mains_hz=mains)
counts, n = {c: {} for c in names}, 0
for b in blocks(src, 32):
q = gate.process(b).flags["quality"]
if not q["ready"]:
continue
n += 1
for c, row in q["per_channel"].items():
for lab in row["labels"]:
counts[c][lab] = counts[c].get(lab, 0) + 1
return {c: {k: round(v / n, 3) for k, v in d.items()} for c, d in counts.items()}, n
raw_dev = raw_oc4.copy()
raw_dev.notch_filter(60.0, verbose=False) # "the on-device notch", at this recording's mains
raw_dev.filter(1.0, 40.0, verbose=False) # "the on-device 1–40 Hz band-pass"
x_dev = raw_dev.get_data(picks=OC4) * 1e6
x_dev = x_dev - x_dev.mean(axis=1, keepdims=True)
before, n_b = gate_label_rates(x_oc4, sf, OC4, 60.0)
after, n_a = gate_label_rates(x_dev, sf, OC4, 60.0)
print(f"{'channel':8s} {'line ratio @60':>15s} {'bandwidth edge':>15s} gate labels (fraction of 1-s windows)")
for i, ch in enumerate(OC4):
lr0, lr1 = line_ratio(x_oc4[i], sf, 60.0), line_ratio(x_dev[i], sf, 60.0)
e0, e1 = bandwidth_edge_hz(x_oc4[i], sf), bandwidth_edge_hz(x_dev[i], sf)
print(f"{ch:8s} raw {lr0:6.1f} → {lr1:5.1f} {str(e0 or 'none'):>6s} → {str(e1 or 'none'):>5s} raw {before[ch]} → device-filtered {after[ch]}")
print("\nAfter the device's filters the line ratio is near 1 on every channel: the gate can no longer tell a coupled electrode from a clean "
"one, the bandwidth edge sits at the filter rather than at the amplifier, and the 25–100 Hz muscle band the gate reads is gone. "
"The stream looks cleaner. What it can no longer show you is whether it is.")
7 · Which analyses survive which geometry¶
The matrix L7.5 fills for three device classes, filled here for the two four-electrode geometries. Each cell gives the reason: a site that is or is not there, a band that is or is not inside the hardware passband, a number measured above. Nothing in it ranks the two; they answer different questions.
def cell(ok, why):
return f"{'yes' if ok else 'no'} — {why}"
posterior_ft = [c for c in FT4 if c.startswith(("TP", "P", "O"))]
matrix = pd.DataFrame(index=["eyes-closed alpha peak / IAF", "alpha reactivity (EC vs EO)", "blink detection", "muscle (EMG) detection",
"line-noise diagnostic", "SSVEP (occipital flicker response)", "P300 (centro-parietal)", "mu ERD (C3/C4)"],
columns=["frontotemporal-4 (TP9, AF7, AF8, TP10)", "occipitotemporal-4 (O1, O2, T7, T8)"])
matrix.iloc[0] = [cell(True, "TP9/TP10 sit over posterior temporal cortex; alpha is visible but weaker than at O1/O2 (synthetic only here; TODO(confirm) on a licensed recording)"),
cell(True, f"O1/O2: {n_ec_peak}/{len(ec)} subjects ≥ 3 dB on the replica (section 3)")]
matrix.iloc[1] = [cell(True, "same sites as above; the contrast is the test of whether a channel records EEG at all"),
cell(True, f"EC {ec.db_above_trend.median():.1f} dB against EO {eo.db_above_trend.median():.1f} dB median height (section 3)")]
matrix.iloc[2] = [cell(True, "AF7/AF8 are frontal: a blink is a same-sign deflection there (the gate's criterion)"),
cell(False, "no frontal site; the gate says 'no frontal channel in this montage' and does not claim to see blinks")]
matrix.iloc[3] = [cell(True, "25–100 Hz RMS on any channel; temporalis sits under TP9/TP10"),
cell(True, "25–100 Hz RMS on any channel; temporalis sits under T7/T8")]
matrix.iloc[4] = [cell(True, "if the stream arrives unfiltered (the board table records no on-device filter for this class; TODO(confirm))"),
cell(True, "only if the optional on-device notch is OFF (section 6)")]
matrix.iloc[5] = [cell(False, "no occipital site; a flicker response is measured where it is largest"),
cell(True, "O1/O2 (the library's CCA detector; L7.15)")]
matrix.iloc[6] = [cell(False, "no Pz or Cz"), cell(False, "no Pz or Cz — neither geometry; L7.5's point about which site the P300 needs")]
matrix.iloc[7] = [cell(False, "no C3/C4"), cell(False, "no C3/C4 — motor imagery is unavailable on both, and lesson L7.15 says so")]
pd.set_option("display.max_colwidth", 200)
display(matrix)
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).
if LOCAL_RECORDING is not None:
from eegloop.check import render_check
mine = ReplaySource(LOCAL_RECORDING, pace="fast", block_samples=32)
rep = run_check(mine, seconds=min(60.0, mine.duration_s), mains_hz=60.0)
print(render_check(rep, title="Your recording — not shipped"))
edges = [r["bandwidth_edge_hz"] for r in rep["per_channel"]]
print("bandwidth edge per channel:", [None if e is None else round(e) for e in edges], "Hz — the band, not the Nyquist frequency")
else:
print("LOCAL_RECORDING is None: skipped (set it to a .bin with its sidecar, or an .npz, to run the first-look report on your own file)")
8 · The numbers the lesson's exercises ask for¶
Printed here so the answer keys can cite a cell rather than a memory. Every number is a draft for expert
review (TODO(confirm) at author review); the first is definitional, the second is measured above.
print("nb-7-10-headband — L7.10 numbers (draft; TODO(confirm) at author review)")
print()
print("(a) Highest frequency you may analyse in a 250 Hz stream whose documented band ends at 100 Hz: 100 Hz (the band, not the 125 Hz Nyquist).")
print(f"(b) Subjects with an eyes-closed alpha peak ≥ 3 dB above trend on the occipitotemporal-4 replica (O1+O2), ds-eegbci S001–S{len(ec):03d} R02: "
f"{n_ec_peak} of {len(ec)} (eyes open: {n_eo_peak} of {len(eo)}).")
print("(c) Survives on frontotemporal-4 only: blink detection. On occipitotemporal-4 only: SSVEP. On both: alpha peak/reactivity, EMG detection, "
"the line-noise diagnostic (if unfiltered). On neither: P300 (no Pz/Cz), mu ERD (no C3/C4).")
print()
print(f"Bandwidth edge on the replica (S001 R02): " + ", ".join(f"{ch} {'none' if e is None else f'{e:.0f} Hz'}" for ch, e in edges.items()))
Cleanup¶
Only what this run fetched is deleted; the cohort is asserted so a partial download cannot report a number for fewer subjects than the text claims. Recordings of your own are never touched.
_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(ec) == len(SUBJECTS) and len(eo) == len(SUBJECTS), f"cohort incomplete: {len(ec)} eyes-closed, {len(eo)} eyes-open of {len(SUBJECTS)}"
print(f"deleted {len(_new)} EDF file(s) this run fetched; kept everything that was already cached; cohort {len(SUBJECTS)}/{len(SUBJECTS)}")