Skip to content

Add 7 imagined speech dataset adapters - #1057

Merged
bruAristimunha merged 20 commits into
developfrom
feat/add-speech-imagery-datasets
Apr 12, 2026
Merged

bruAristimunha merged 20 commits into
developfrom
feat/add-speech-imagery-datasets

Conversation

@bruAristimunha

@bruAristimunha bruAristimunha commented Apr 10, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Adds BCI-oriented loaders for 4 imagined speech EEG datasets (7 classes total, counting Nguyen2017's 4 sub-conditions). All adapters reuse the shared build_raw_from_epochs utility, add entries to summary_imagery.csv, and populate rich METADATA (acquisition, participants, experiment, documentation, preprocessing, paradigm-specific fields).

New datasets

  • BCIComp2020IS — 2020 BCI Competition Track 3, 5 English phrases (Hello, Help me, Stop, Thank you, Yes), 15 subjects, 64-channel BrainAmp, from OSF project pq7vb. Paper: Jeong et al. 2022, Front. Hum. Neurosci. (doi:10.3389/fnhum.2022.898300).
  • AguileraRodriguez2025 — 4 Spanish directional words (avanzar, retroceder, derecha, izquierda), 15 subjects, 24-channel mBrainTrain Smarting, traditional cue-based EDF paradigm from Mendeley dataset 57g8z63tmy. Paper: Aguilera-Rodriguez et al. 2025, Sci. Data (doi:10.1038/s41597-025-05926-5).
  • Nguyen2017_V / _S / _L / _SL — 4 sub-conditions of Nguyen, Karavas & Artemiadis (2018): vowels (/a/, /i/, /u/), short words (in, out, up), long words (cooperate, independent), and short-vs-long discrimination. 64-channel BrainProducts ActiCHamp, preprocessed (8-70 Hz, 60 Hz notch, EOG removed, 256 Hz). EOG channels marked as eog type so they are excluded from classification. Paper: J. Neural Eng. 15(1), 016002 (doi:10.1088/1741-2552/aa8235).
  • Pressel2016 — 11-class Spanish imagined speech database (Base de Datos Habla Imaginada): 5 vowels and 6 directional commands, 15 subjects, 6 channels (F3/F4/C3/C4/P3/P4), 1024 Hz. Artifact trials filtered at load time. Optional pronounced-speech session via include_pronounced=True. Paper: Pressel Coretto, Gareis & Rufiner, SIPAIM 2016 (doi:10.1117/12.2255697).

Design notes

  • build_raw_from_epochs is reused from moabb.datasets.utils for all pre-epoched datasets (BCIComp2020IS, Nguyen2017 variants, Pressel2016).
  • Nguyen2017 trials are shuffled with a fixed seed (RandomState(42)) at load time to avoid the original class-blocked ordering, which would leak temporal autocorrelation across CV folds.
  • Pressel2016 filters artifact-flagged trials (artifact_col == 2) at the data level rather than relying on BAD annotations, since the MOABB MotorImagery paradigm builds epochs from the stim channel and would otherwise include all trials.
  • For all 64-channel Nguyen2017 files, the 4 channels used for EOG recording (indices 1, 10, 33, 64 per the dataset readme) are marked as eog type so paradigms only see 60 EEG channels.

Benchmark results (3 subjects each, within-session, Riemannian pipelines)

Dataset Best pipeline Score Adjusted chance (α=0.05) Above chance
BCIComp2020IS (5-class) TS+SVM 0.316 0.286 yes
AguileraRodriguez2025 (4-class) CSP+LDA 0.617 0.417 yes
Nguyen2017_V (3-class vowels) TS+SVM 0.424 0.433 borderline
Nguyen2017_S (3-class short) TS+SVM 0.443 0.433 borderline
Nguyen2017_L (2-class long) TS+SVM 0.606 0.625 no
Nguyen2017_SL (short vs long) TS+SVM 0.746 0.656 yes
Pressel2016 (11-class) CSP+LDA 0.121 0.155 no

Chance levels computed with moabb.analysis.chance_level.chance_by_chance (Combrisson & Jerbi, 2015). The Nguyen2017_V/S/L/Pressel2016 accuracies are in line with or near the figures reported in the original papers given the small 3-subject benchmark subset.

Test plan

  • All 7 datasets import cleanly via from moabb.datasets import ...
  • _get_single_subject_data(1) returns a valid session/run/Raw dict for every dataset
  • Stim channel events are populated (mne.find_events returns expected counts)
  • Channel types correctly tagged (eeg vs eog for Nguyen2017)
  • Artifact filtering verified on Pressel2016 (sub01: 578 → 278 clean trials, matches paper's artifact rate)
  • MotorImagery paradigm produces correctly shaped X, y, metadata for each dataset
  • WithinSessionEvaluation runs end-to-end with Riemannian pipelines on all 7
  • pre-commit run passes (ruff, ruff-format, codespell, yamllint)

Adds BCI-oriented loaders for 4 imagined speech EEG datasets (7
classes total, counting Nguyen2017's 4 sub-conditions):

- BCIComp2020IS: 2020 BCI Competition Track 3 - 5 English phrases
  (Hello, Helpme, Stop, Thankyou, Yes), 15 subjects, 64 channels,
  from OSF project pq7vb. Paper: Jeong et al. 2022, Front. Hum.
  Neurosci. (doi:10.3389/fnhum.2022.898300).

- AguileraRodriguez2025: 4 Spanish directional words (avanzar,
  retroceder, derecha, izquierda), 15 subjects, 24-channel
  mBrainTrain Smarting, traditional cue-based EDF paradigm from
  Mendeley dataset 57g8z63tmy. Paper: Aguilera-Rodriguez et al.
  2025, Sci. Data (doi:10.1038/s41597-025-05926-5).

- Nguyen2017_V / _S / _L / _SL: 4 sub-conditions of the Nguyen,
  Karavas, Artemiadis (2018) imagined speech dataset - vowels
  (/a/,/i/,/u/), short words (in,out,up), long words (cooperate,
  independent), and short-vs-long discrimination. 64-channel
  BrainProducts ActiCHamp, preprocessed (8-70 Hz, 60 Hz notch,
  EOG removed, 256 Hz). EOG channels marked as eog type so they
  are excluded from classification. Paper: J. Neural Eng. 15(1),
  016002 (doi:10.1088/1741-2552/aa8235).

- Pressel2016: 11-class Spanish imagined speech database ("Base
  de Datos Habla Imaginada") - 5 vowels and 6 directional commands,
  15 subjects, 6 channels (F3/F4/C3/C4/P3/P4), 1024 Hz. Artifact
  trials filtered at load time. Optional pronounced-speech session
  via include_pronounced=True. Paper: Pressel Coretto, Gareis &
  Rufiner, SIPAIM 2016 (doi:10.1117/12.2255697).

All adapters reuse the shared build_raw_from_epochs utility, add
entries to summary_imagery.csv, and populate rich METADATA
(acquisition, participants, experiment, documentation,
preprocessing, paradigm-specific fields). Nguyen trials are
shuffled with a fixed seed at load time to avoid class-blocked
ordering that would leak temporal autocorrelation across CV folds.

Co-Authored-By: bruAristimunha <[email protected]>
@bruAristimunha
bruAristimunha force-pushed the feat/add-speech-imagery-datasets branch from 4fa0225 to 63d2c96 Compare April 10, 2026 15:58

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 4fa0225ae4

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread moabb/datasets/__init__.py Resolved
josemaurici and others added 19 commits April 10, 2026 16:08
- Remove try/except for MATLAB v7.3 / HDF5 fallback in
  _load_epoch_mat. Training and validation files are v5 MATLAB;
  test files (v7.3, no labels) are excluded entirely.
- Drop the test split from _SPLITS and _get_single_subject_data.
- Replace the custom OSF-API-based _download_from_osf helper (with
  its raw requests calls and pagination) by a hardcoded mapping of
  the 30 stable OSF download URLs (15 subjects x 2 splits) used
  directly with moabb.datasets.download.data_dl.
- Inline the _subject_dir helper: data_path now simply calls
  data_dl for each split and returns the path. Added a keyword-only
  split argument so _get_single_subject_data can request training
  or validation paths without copying/moving files.
- _load_epoch_mat is now a staticmethod that assumes v5 format.
- Change _SIGN from "bcicomp2020is" to "BCIComp2020IS" to match the
  class code (improves MNE_DATASETS_* config key readability).

Loading still produces 300 training + 50 validation events per
subject as before.

Co-Authored-By: bruAristimunha <[email protected]>
- Add license field to all 4 Nguyen2017 subclass METADATA blocks.
  The paper's readme only asks users to cite the paper without
  stating a formal license, so use
  "Unspecified (research use; cite paper)".

- Add DOI cache entries for the 4 new papers:
  * 10.3389/fnhum.2022.898300 (Jeong et al. 2022, BCIComp2020IS)
  * 10.1038/s41597-025-05926-5 (Aguilera-Rodriguez 2025)
  * 10.1088/1741-2552/aa8235   (Nguyen et al. 2018)
  * 10.1117/12.2255697         (Pressel Coretto 2017)
  Populated via doi.org content negotiation as done by
  test_doi_validation._resolve_doi, preserving the existing
  4-space ASCII-escaped JSON format.

- Bump test_catalog_dataset_count expected total from 148 to 155
  (+7 new dataset classes: BCIComp2020IS, AguileraRodriguez2025,
  Nguyen2017_V/S/L/SL, Pressel2016).

Co-Authored-By: bruAristimunha <[email protected]>
Adds four reusable scripts under scripts/ that re-package and upload
the Pressel2016 (Spanish imagined speech, Google Drive) and Nguyen2017
(JNE imagined speech, Dropbox) EEG datasets to Zenodo, replacing their
fragile consumer-cloud hosting. Same pattern as the existing
upload_tavakolan2017_zenodo.py and repackage_ieee_dataport.py helpers
used for prior rehosts.

- scripts/repackage_pressel2016.py: extracts the 15 S{NN}_EEG.mat files
  from the original imagined_speech.zip (gdown / legacy resourcekey
  share) and rebuilds them as 15 per-subject ZIPs with sub-NN_eeg.mat
  inside, plus a top-level README.md documenting stimulus codes,
  channels, trial structure, and the original -> clean filename map.

- scripts/repackage_nguyen2017.py: reads the 4 extracted inner condition
  zips from the HORC lab's Dropbox archive (the outer dataset.zip has
  a 4 GB prefix that breaks Python's zipfile module and requires the
  system unzip tool). Rebuilds each condition zip with renamed
  sub-01.mat..sub-NN.mat matching MOABB integer subject IDs, preserves
  the authors' original Read_me.txt verbatim for provenance, carries
  forward the supplementary analysis files (Vowels
  time_correlation_effect, Short_Long_words 8s variant) under
  supplementary/, and writes a new README.md per condition.

- scripts/upload_pressel2016_zenodo.py and
  scripts/upload_nguyen2017_zenodo.py: create a Zenodo deposition,
  upload each repackaged file with MD5 verification, set rich HTML
  metadata (creators, communities=moabb, keywords,
  related_identifiers pointing back to the paper DOI and the original
  hosting URL), and support --sandbox / --publish flags for dry-runs
  and two-phase draft->publish.

Both datasets use Zenodo's 'other-open' license category: neither
paper grants an explicit Creative Commons license (Pressel's SPIE
proceedings call the data 'open access' without any CC text;
Nguyen's HORC lab Read_me.txt only requests paper citation). The
upload scripts include detailed notes explaining the licensing
status and promising takedown on author request.

Published records:
  Pressel2016 -> https://zenodo.org/records/19502780 (10.5281/zenodo.19502780)
  Nguyen2017  -> https://zenodo.org/records/19502794 (10.5281/zenodo.19502794)
Replaces the fragile Google Drive (gdown + legacy resourcekey) and
Dropbox (rlkey-token share) downloads with per-subject / per-condition
ZIPs fetched from the new Zenodo records published for these datasets:

  Pressel2016 -> https://zenodo.org/records/19502780
                 10.5281/zenodo.19502780
  Nguyen2017  -> https://zenodo.org/records/19502794
                 10.5281/zenodo.19502794

pressel2016.py:
- Replace _GDRIVE_FILE_ID / _GDRIVE_URL with _ZENODO_RECORD /
  _ZENODO_BASE.
- Drop the gdown import, the manual zip-cache dance, the alternate
  extracted-location fallback, and the try/except around gdown
  ImportError. data_path now builds a per-subject URL, calls the
  shared download_and_extract_subject_zip helper, and returns the
  single sub-NN_eeg.mat file.
- Update DocumentationMetadata: add data_url and repository="Zenodo",
  change license from "Open access" to "other-open" to match the
  Zenodo mirror's category.

nguyen2017.py:
- Replace _DROPBOX_URL with _ZENODO_RECORD / _ZENODO_BASE.
- Simplify data_path the same way: build per-condition URL, call
  download_and_extract_subject_zip, return sub-NN.mat. Drop the
  outer-wrapper extraction path entirely — it was previously needed
  because the Dropbox dataset.zip wraps 4 inner zips and has a
  4 GB prefix that breaks Python's zipfile module.
- Update DocumentationMetadata on all 4 subclasses (Nguyen2017_V,
  Nguyen2017_S, Nguyen2017_L, Nguyen2017_SL): add data_url,
  repository="Zenodo", change license from
  "Unspecified (research use; cite paper)" to "other-open".
- Drop the safe_extract_zip import (no longer referenced; the
  shared helper handles safe extraction).

End-to-end verified: both Pressel2016 and Nguyen2017_V can be
freshly downloaded from Zenodo, extracted, and loaded through
_get_single_subject_data. moabb/tests/test_doi_validation.py
test_data_url_format now exercises both datasets instead of
skipping with "No data_url".
Addresses review findings on the previous two commits without
changing the published Zenodo records or the dataset adapter
contracts. No behavior change for library users.

scripts/upload_{pressel2016,nguyen2017}_zenodo.py:

- Narrow _request_with_retry to retry only on 5xx / ConnectionError /
  Timeout. 4xx responses now fail fast via r.raise_for_status()
  instead of looping with exponential backoff. This prevents a bad
  token from wasting 15+ seconds and rate-limit budget (verified:
  bogus-token test returns 403 in <1 s instead of spinning through
  3 retries).

- Accept ZENODO_TOKEN from environment as a fallback when --token
  is not passed. Avoids token leakage via shell history and
  `ps auxe` on shared machines. --token is now optional;
  _resolve_token exits with a friendly error if neither is set.

- Add Accept: application/vnd.zenodo.v1+json header on every
  request via a small _auth() helper. Zenodo is migrating to
  InvenioRDM and the legacy /api/deposit/depositions endpoint
  will eventually sunset; the version header pins us to the v1
  contract in the interim. TODO comment documents the migration
  target (/api/records + drafts API).

- Add an unreachable-raise at the bottom of _request_with_retry
  so a future refactor that accidentally exits the loop without
  returning crashes loudly instead of returning None.

moabb/datasets/nguyen2017.py:

- Drop the _CONDITIONS[...]["subjects"] opaque-basename lists.
  They were previously used by the Dropbox loader to look up
  per-subject .mat files by filename pattern, but the Zenodo
  mirror renames everything to sub-NN.mat, so the only consumer
  left was len(cfg["subjects"]) for subject count. Replace with
  an explicit "n_subjects" int on each condition. Provenance
  mapping (clean -> original) is preserved in the README.md and
  Read_me.txt bundled inside each Zenodo condition zip, and
  remains code-visible in scripts/repackage_nguyen2017.py
  CONDITIONS dict.

scripts/repackage_nguyen2017.py:

- Drop the `from typing import Tuple` import; use PEP 585
  `tuple[str, ...]` for the CLASS_LABELS type hint (module
  already uses `from __future__ import annotations` and PEP 585
  elsewhere).

Review findings deliberately not addressed:

- The 4 upload/repackage scripts still deliberately follow the
  upload_tavakolan2017_zenodo.py template pattern used by prior
  MOABB rehosts. Extracting a shared scripts/_zenodo.py module
  would break that parallel and requires touching the whole
  template family at once — tracked for a future refactor.
- HTML descriptions are still inline in the METADATA dicts for
  the same template-consistency reason.
- Parallel uploads / repackage ZipFile caching: admin-only
  one-shot scripts, acceptable sequential performance.
Extends the existing BCIComp2020IS (Track 3) family with adapters
for the two remaining motor-control-oriented tracks of the 2020
International BCI Competition. Both datasets are published on the
same OSF project (https://osf.io/pq7vb/) under CC-BY-4.0.

moabb/datasets/bcicomp2020_upper_limb.py — BCIComp2020UpperLimb

Track 4 is a session-to-session upper-limb motor imagery benchmark:
three right-arm grasping tasks (cylindrical, spherical, lumbrical)
imagined by 15 right-handed subjects (S1-S15, aged 20-34) across
three recording days spaced 7 days apart. 60 EEG channels at 250 Hz,
FCz reference, Fpz ground, 60 Hz notch. 150 trials per session
(50 per class).

The adapter exposes the three days as three MOABB sessions (day 1 =
training, day 2 = validation, day 3 = test). Each session returns
one run containing the 4-second motor imagery window extracted from
the 10-second cue-aligned epochs in the .mat files. The organizer-
released test files have the 3-second cue section removed (to
prevent the visual-cue response from inflating results), so the
test loader slices a different offset from the shorter epochs; the
final arrays are (150, 60, 1000) samples per session regardless of
split.

Test-day labels are only published as a separate answer-sheet XLSX
on OSF (Track4_Answer_Sheet_Test.xlsx), not inside the .mat files.
They are embedded as a compact _TEST_LABELS_DAY3 tuple dict so the
adapter can return labelled data for all three sessions without a
second file download.

moabb/datasets/bcicomp2020_walking_erp.py — BCIComp2020WalkingERP

Track 5 is an ambulatory P300 oddball benchmark: 15 subjects (aged
19-32, 11M+4F) performed a visual oddball paradigm (target OOO vs
non-target XXX, 20% target ratio) while walking on a treadmill at
1.6 m/s. 56 channels total — 32 scalp EEG, 4 EOG (HEOGL/R, VEOGU/L),
14 ear-EEG (L1-L10 + R1-R8 with gaps), 6 IMU (accel + gyro) — at
100 Hz, epoched from -200 to +800 ms around stimulus onset. 300
trials per subject in a single walking recording, temporally split
180 / 60 / 60 for training / validation / test.

Channel types are mixed: scalp + ear channels are typed eeg (so
the P300 paradigm picks them up automatically), EOG is eog, and
IMU is misc so it is preserved in the Raw but not fed into
classification. Ear-EEG channels have no standard-montage positions
and are left with NaN coordinates via set_montage(on_missing=ignore).

Label encoding is handled via className lookup rather than positional
argmax arithmetic, because the organizer-released .mat files store
epo.y with row 0 = target and row 1 = non-target, while the test
answer-sheet XLSX uses the opposite convention (0 = non-target,
1 = target). Both splits are normalized to {NonTarget: 1, Target: 2}
matching MOABB P300 conventions, verified end-to-end: training 22.8%
target ratio, test 18.3% target ratio for subject 1.

Integration points:

- moabb/datasets/__init__.py: two new imports
- moabb/datasets/summary_imagery.csv: BCIComp2020UpperLimb row
  (15 subj, 60 ch, 3 classes, 50 trials/class, 4.0s, 250 Hz, 3
  sessions, 1 run, 6750 total trials)
- moabb/datasets/summary_p300.csv: BCIComp2020WalkingERP row
  (15 subj, 46 ch, 240 NT / 60 T per subject, 1.0s, 100 Hz, 1 session)
- moabb/tests/test_metadata.py: catalog count 155 -> 157

DOI 10.3389/fnhum.2022.898300 is already in the test DOI cache from
the prior BCIComp2020IS / Nguyen2017 / Pressel2016 commit, so no
cache update is needed.

End-to-end verification: downloaded subject 1 for both datasets from
OSF and loaded through build_raw_from_epochs. Track 4 produces three
165000-sample raws (150 trials * 4s MI window + buffers) per session.
Track 5 produces one session with three runs (36000 / 12000 / 12000
samples for 180/60/60 trial splits), channel types 46 eeg + 4 eog +
6 misc + 1 stim. All 1981 tests in test_datasets.py, test_metadata.py
and test_doi_validation.py pass.
Review of the 2797f63 commit uncovered several factual errors in
the metadata blocks and one critical data-correctness bug in the
Track 4 test split. Source of truth: the Track 4 and Track 5 data
description PDFs on the OSF project and the actual sample data.

Track 4 (bcicomp2020_upper_limb.py)

CRITICAL: Fixed _load_epoch_mat to use the same sample slice
(1500-2500 = seconds 6-10) for all three splits. The previous code
used slice(750, 1750) for the test split based on a misreading of
the Track4_Test/ReadMe.txt, which says the visual-cue section was
"removed" from the test files. Checking the actual test .mat files
shows the shape is still (2501, 60, 150) — same as train/val —
with samples 750-1500 zeroed in-place rather than dropped. The old
loader was therefore returning the (mostly zero) rest+cue region
labelled as motor imagery for the entire day-3 test session.
Verified against sample01 across all three splits: the MI window at
samples 1500-2500 has non-zero real data in every file (train ~41
raw uV, val ~9, test ~10), while the cue region (750-1500) is
all-zero only in test.

Removed _MI_SLICE_TEST and renamed _MI_SLICE_FULL -> _MI_SLICE
since there's now only one slice. Updated the docstring
accordingly.

Metadata fixes:

- trial_duration: 10.0 -> 4.0 s (_MI_DURATION_S). Matches the
  BCIComp2020IS convention of reflecting the loaded interval, not
  the full experimental trial. The 10-second figure was the raw
  trial structure before MI-window extraction.
- preprocessing_steps: replaced "epoched (0-10 s per cue)" with
  "cue-aligned epoching" + "motor imagery window (6-10 s of each
  trial) extracted by loader" to truthfully describe what the user
  receives.
- study_design: note the 10-s original trial structure and the
  4-s MI window exposed by the loader.
- handedness: removed handedness={"right": 15}. The Track 4 PDF
  has garbled text ("all right-handed - S1, 4, and 5; all
  right-handed") making the per-subject split unclear. Left
  unset rather than over-claim.

Track 5 (bcicomp2020_walking_erp.py)

CRITICAL: Fixed interval=[-0.2, 0.8] -> [-0.19, 0.8]. The Track 5
data description PDF says "each trial is segmented -200 to 800 ms",
but the actual epo.t field in the released .mat files is a
100-sample grid from -190 to +800 ms at 10-ms spacing. The old
interval asked the paradigm pipeline for data from -200 ms which
would either fail or silently be clipped. Verified: (100 samples,
start=-190 ms, end=+800 ms) from sample01 training file.

Metadata fixes:

- hardware: removed the vague "scalp EEG + ear-EEG amplifiers +
  forehead IMU" placeholder. The amplifier model is not stated in
  the Track 5 data description PDF, so leaving it unset is more
  honest than guessing.
- preprocessing_steps: removed the "downsampled to 100 Hz" claim
  (speculation — the PDF does not state a downsampling step) and
  updated the epoch-window description to the actual -190/+800 ms
  range.
- Docstring: note that epo.t is -190 to +800 ms and the PDF's
  "-200 to 800 ms" is rounded.

Not changed (verified correct):

- Track 4 channel list (60 names) — exact match with .mat clab
- Track 4 className order matches events dict
- Track 5 channel list (56 names) — exact match with .mat clab
- Track 5 className = [target, non-target] handled via string
  lookup, labels correctly produce NonTarget=1, Target=2
- OSF license = CC-BY-4.0 (confirmed via OSF v2 API, not inferred)
- Sampling rates (250 Hz / 100 Hz) from epo.fs
- Investigators list matches the Frontiers review paper authors
  (same as BCIComp2020IS convention)

End-to-end re-verified after fixes: all 1981 tests in
test_datasets.py, test_metadata.py, test_doi_validation.py pass
(586 skipped, 0 failures). Track 4 subject 1 loads non-zero MI
data for all 3 sessions.
Follow-up to the 47c3e08 review. Addresses per-file quality and
efficiency issues in the two new Track 4/5 adapters. No behavior
change: end-to-end output identical (same event counts per session,
same shapes, same target ratios on subject 1).

Efficiency:

- _download_all_splits helper (both files): extract the OSF-loop
  so the per-subject hot path in _get_single_subject_data downloads
  each file once (3 data_dl calls), instead of re-running the loop
  per split via data_path (which did 3*3 = 9 cache checks per
  subject before). data_path now also goes through
  _download_all_splits so the public API is unchanged.

- loadmat(variable_names=[...]) (both files): only deserialize the
  epo / epo_tr / epo_val / epo_te struct from each .mat file,
  skipping the mnt montage struct we don't consume. Minor savings
  individually, explicit about what the loader depends on.

Quality:

- Remove unused `import logging` + `log = logging.getLogger(__name__)`
  from both files. The modules never logged anything.

- Remove `from __future__ import annotations` from both files.
  MOABB requires Python >= 3.10 (pyproject.toml line 33), so PEP
  585 generics work natively. Only 4/87 files in moabb/datasets/
  use this import; Track 3 (bcicomp2020_imagined_speech.py) does
  not.

- Single-source the event maps: introduce a module-level _EVENTS
  constant in each file and reference it from both METADATA and
  the BaseDataset.__init__ super call, instead of repeating the
  dict literal. For Track 4, _EVENTS is derived from _CLASS_NAMES
  via enumerate (no second source). For Track 5, class_labels is
  now list(_EVENTS.keys()) rather than a hand-maintained list.

- Track 4 filters={"notch": 60.0} -> filters={"notch_hz": 60}.
  Other MOABB datasets that use a dict for acquisition.filters
  use notch_hz as the key (schema accepts arbitrary Dict[str,
  Any], but the convention is notch_hz + bandpass). line_freq=60.0
  still carries the line-frequency info as well.

- Track 4 trials_context: clarify that n_trials=450 is per subject
  (150 per session * 3 sessions, 6750 total), so the metadata no
  longer has to be interpreted by column order.

Deliberately NOT addressed (out of scope for "a little more"):

- Cross-file duplication between Track 3, Track 4 and Track 5 for
  _load_epoch_mat, _OSF_URLS/data_path, and DocumentationMetadata.
  Pulling those into shared helpers would be the right follow-up
  but requires touching the existing BCIComp2020IS (Track 3),
  which is a bigger refactor than this pass.

- Docstrings (both files have 35-45 line class docstrings). They
  mirror the Track 3 (BCIComp2020IS) style and serve as user-facing
  documentation, so trimming them for "conciseness" would reduce
  usefulness.

- Stringly-typed split names ("training" / "validation" / "test").
  The three literals appear in _OSF_URLS keys, _SESSIONS/_SPLITS
  tuples, and data_path's split= kwarg. Adding constants would be
  bikeshed; the strings also match the OSF folder names.

Verified after refactor: ruff clean, 1981 passed / 586 skipped /
0 failures across test_datasets, test_metadata, test_doi_validation.
End-to-end load of subject 1 for both tracks produces identical
event counts and data shapes to the pre-refactor baseline.
The two repackage helpers were one-shot tooling: they converted the
original Google Drive (Pressel2016) and Dropbox (Nguyen2017) archives
into the per-subject / per-condition ZIP layout that now lives on
Zenodo as records 10.5281/zenodo.19502780 and
10.5281/zenodo.19502794. With those records published and the
dataset classes fetching from them via download_and_extract_subject_zip,
the repackage scripts are unreachable by the library and the
canonical layout is documented on Zenodo itself.

Deleted:

- scripts/repackage_pressel2016.py (273 lines)
- scripts/repackage_nguyen2017.py (489 lines)

The upload_*_zenodo.py scripts stay because they document the
exact Zenodo metadata block used for each deposit (title,
description, related_identifiers, license, takedown contacts),
which is the only place in the repo where that metadata is visible
in source form. Their error messages previously pointed at
scripts/repackage_*.py when the staging directory was empty; both
have been updated to direct users to the canonical Zenodo record
for the ZIP layout instead.
Completes the removal of one-shot Zenodo rehost tooling from the
branch: neither the repackage nor the upload scripts remain in the
repo. The two published Zenodo records (10.5281/zenodo.19502780,
10.5281/zenodo.19502794) are the canonical source for both the
file layout and the deposit metadata.

Deleted:

- scripts/upload_pressel2016_zenodo.py (391 lines)
- scripts/upload_nguyen2017_zenodo.py  (425 lines)

Inlined _subject_dir in pressel2016.py and nguyen2017.py. The
helper just concatenated `dl.get_dataset_path(_SIGN, None)` with
`MNE-{_SIGN}-data`; callers then appended a per-subject or
per-condition folder and passed the result to
download_and_extract_subject_zip. Replaced with a single inline
expression in data_path, matching the tavakolan2017.py pattern:

    subj_dir = (
        Path(dl.get_dataset_path(_SIGN, path))
        / f"MNE-{_SIGN.lower()}-data"
        / f"S{subject:02d}"
    )

Also threads the caller-supplied `path` argument through to
get_dataset_path, which the old _subject_dir did not (it always
passed `None`, ignoring the user override). No local imports
remain in either file.
Addresses several correctness and style issues across the three
new imagined-speech adapters in this branch.

AguileraRodriguez2025:

- Drop the runtime Mendeley Data API probe. The previous data_path
  did `import requests` inside the function, hit
  /api/datasets/57g8z63tmy/files?version=1 on every fresh download,
  scanned the JSON for filename=="SN.edf", extracted the
  download_url, then fed it to dl.data_dl. Replaced with a
  hardcoded `_SUBJECT_URLS` dict (15 stable
  data.mendeley.com/public-files URLs, enumerated once from the
  API) so data_path is just a direct dl.data_dl call — matching
  the OSF pattern used by the BCIComp2020 adapters.

- The Mendeley URLs all end in "file_downloaded" (the last path
  segment), so pooch writes the EDF without a .edf suffix and
  mne.io.read_raw_edf refuses to open it. Fix by creating a
  zero-disk .edf hardlink view next to pooch's cached file via
  Path.hardlink_to (Python 3.10+, required by MOABB). The pooch
  cache stays intact so subsequent calls don't re-download.

- Drop _subject_dir helper, the manual-download alternate-path
  fallback, the `import shutil`/`import logging` leftovers, and
  the broken edf_file.mkdir hack. data_path shrinks from 62 lines
  to 22.

Nguyen2017:

- Remove the `_cfg` property (just `_CONDITIONS[self._condition]`
  with extra indirection); inline the dict lookup at its single
  remaining call site in data_path. __init__ already used the
  literal lookup.

- Stop shuffling trials with `np.random.RandomState(42)` /
  `rng.permutation` at load time. The original comment claimed
  the shuffle avoided class-blocked ordering leaking temporal
  autocorrelation into CV folds, but that's a decision for the
  downstream evaluation protocol, not the loader. Trials are
  now returned in the upstream .mat file's class-blocked order
  (verified for subject 1: 300 events with exactly 2 class
  transitions, i.e. three contiguous runs of 100 trials each).

Pressel2016:

- Change artifact handling from drop-and-exclude to mark-as-BAD.
  The previous loader masked out rows where `artifact_col == 2`
  so artifact trials vanished entirely from the returned Raw.
  Now the loader keeps every trial from the selected modality
  and adds `BAD_artifact` annotations at the artifact trials'
  event onsets (4-second duration, matching the imagery window).
  Downstream epoching respects `reject_by_annotation`, so users
  who want the old behavior still get it, but everyone else can
  inspect or re-accept artifact trials.

  Verified on subject 1: 578 imagined-speech events total, 300
  with BAD_artifact annotations (52 percent, matching the
  10-52 percent range the paper reports).

- Also drop the unused `import logging` + `log = ...` while we're
  here; `mne` becomes a module-level import.

No behavior change for any paradigm pipeline that reads the stim
channel without rejecting annotations; the new Pressel behavior
matches the upstream .mat file 1:1 instead of silently trimming.
All 1981 tests in test_datasets, test_metadata, and test_doi_validation
pass. End-to-end load of subject 1 verified for all three datasets.
Code review + documentation pass across the imagined-speech family.

Critical fix — BCIComp2020WalkingERP stim marker placement

The Track 5 .mat files store 100-sample trials where epo.t spans
-190 ms to +800 ms at 10 ms spacing, so the actual stimulus onset
is at sample index 19 of each trial (not sample 0). The loader was
calling build_raw_from_epochs with the default onset_sample=0,
which put the stim marker at sample 0 = t=-190 ms. With
interval=[-0.19, 0.8], the paradigm pipeline was therefore:

  - reading the 19-sample leading zero buffer as "pre-stim
    baseline" instead of the real -190..-10 ms signal
  - and clipping the epoch end at +610 ms instead of +800 ms,
    silently dropping the final 180 ms of real post-stim data.

Fix: declare _STIM_ONSET_SAMPLE = 19 and pass it through to
build_raw_from_epochs. Verified on subject 1: first event sample
is now 69 (= buffer 50 + onset 19), the 19 pre-stim samples
contain real non-zero EEG (max ~53 uV), and the 80 post-stim
samples are non-zero. No shape or event-count change.

Metadata cleanup — Nguyen2017

The 4 sub-dataset METADATA blocks (Vowels, ShortWords, LongWords,
ShortLongWords) all carried gender={"male": 11, "female": 4} and
handedness="right (except S13)". These values are from the original
15-subject cohort, but each sub-dataset uses only 6-8 of those
subjects, so the counts don't match (11 + 4 > 8) and "except S13"
is meaningless for the three sub-datasets that don't include S13.
The per-sub-dataset breakdown isn't published, so removing the
gender/handedness fields is more honest than propagating the
wrong aggregate. age_min/age_max are kept because the cohort
range still bounds each sub-dataset. Comment explains the
provenance.

Dead-code removal

- BCIComp2020IS (Track 3) and Nguyen2017 both imported logging
  and defined log = logging.getLogger(__name__) but never used
  it. Removed the import + variable from both files.

- Fixed the broken doc comment above _TEST_LABELS_RUN2 in
  bcicomp2020_walking_erp.py (the sentence was truncated
  mid-clause).

Documentation — welcome imagined speech as a first-class family

- New "Imagined Speech" section in docs/source/dataset_summary.rst
  between "Motor Imagery" and "P300/ERP", explaining what
  imagined speech is, why it's grouped under the imagery
  paradigm in MOABB, and showing a dedicated CSV table.

- New "Imagined Speech Datasets" subsection in docs/source/api.rst
  with an autosummary listing of all 7 adapters
  (BCIComp2020IS, AguileraRodriguez2025, Nguyen2017_V/S/L/SL,
  Pressel2016). Also adds BCIComp2020UpperLimb to the Motor
  Imagery list and BCIComp2020WalkingERP to the ERP/P300 list
  so the two new BCI Competition 2020 tracks show up in the
  API reference.

- New moabb/datasets/summary_imagined_speech.csv with the 7
  speech rows extracted from summary_imagery.csv. The 7 rows
  also remain in summary_imagery.csv (the canonical file that
  feeds BaseDataset._summary_table, which must see every dataset
  tagged paradigm="imagery") — the new CSV is a docs-only
  filtered view that docs/prepare_summary_tables.py transforms
  into docs/build/summary_imagined_speech.csv. Force-added with
  `git add -f` because .gitignore has a blanket *.csv* rule and
  the existing 5 summary CSVs are grandfathered in.

- New Enhancements entry in whats_new.rst covering the
  documentation work, the two BCIComp2020 tracks, the Zenodo
  re-hosting of Pressel2016 / Nguyen2017, and the BAD_artifact
  annotation change in Pressel2016. New Bugs entry documents
  the Track 5 onset_sample fix.

Verified after all changes:

- ruff check clean on the three edited dataset files
- 1981 passed / 586 skipped / 0 failures in test_datasets,
  test_metadata, test_doi_validation
- docs/prepare_summary_tables.py picks up the new imagined
  speech CSV and writes docs/build/summary_imagined_speech.csv
  with the :class: wrappers Sphinx needs
- End-to-end load of Track 5 subject 1 confirms the new
  stim-marker offset produces non-zero pre-stim data
Rebuilt the Sphinx site locally and walked through the rendered
dataset_summary.html / api.html / whats_new.html with a design-
review lens, fixing concrete issues the static HTML surfaced.

Fixes:

- api.rst: BCIComp2020UpperLimb was appended at the end of the
  Motor Imagery autosummary (after Zuo2025), breaking the implicit
  alphabetical order of that list's tail (Beetl2021_A ... Zuo2025).
  Moved it to its correct alphabetical slot between Beetl2021_B
  and Brandl2020.

- dataset_summary.rst: replaced the apologetic "they are repeated
  here to make the imagined speech family easy to discover"
  sentence with a sentence that actually names all 7 adapters
  inline (BCIComp2020IS, AguileraRodriguez2025, Nguyen2017_V/S/L/SL,
  Pressel2016). A reader scanning the welcome paragraph now sees
  the full family without having to look at the table below, and
  the paradigm-tag disclosure is a neutral statement rather than
  an apology.

- dataset_summary.rst: added a 6-line code snippet after the
  dataset listing showing the "loading is identical to motor
  imagery" claim in action:

      from moabb.datasets import BCIComp2020IS
      from moabb.paradigms import MotorImagery
      dataset = BCIComp2020IS()
      paradigm = MotorImagery(n_classes=5)
      X, y, metadata = paradigm.get_data(dataset=dataset, subjects=[1])

  This makes the "welcome" concrete for first-time users and
  gives them something to copy-paste.

- whats_new.rst: switched the ``:ref:`data_summary``` cross-
  reference to ``:doc:`dataset_summary``` because the
  ``.. _data_summary:`` label in dataset_summary.rst is followed
  by ``automodule::`` / ``currentmodule::`` directives before the
  section title, so Sphinx couldn't resolve the title text for
  ref. ``:doc:`` is the more reliable cross-page reference
  anyway. This eliminates the last content-related build warning.

After these edits, ``make html-noplot`` reports:
  build succeeded, 1 warning.
And the one remaining warning is a pre-existing sphinx-gallery
``show_memory disabled due to parallel=14`` notice that has no
relationship to this branch.

Verified in the rendered HTML:

- dataset_summary.html: Imagined Speech section shows welcome prose,
  named dataset list, python code block (highlighted), and the
  7-row sortable CSV table.
- api.html: Motor Imagery autosummary has BCIComp2020UpperLimb at
  position 31 of 54 (between Beetl2021_B and Brandl2020).
  Imagined Speech Datasets subsection has 7 classes listed
  alphabetically with their one-line docstring summaries.
- whats_new.html: Enhancement bullets render with live :doc: link
  to dataset_summary.
The first table in docs/source/dataset_summary.rst renders rows
from summary_imagery.csv, which contains BOTH motor imagery AND
imagined speech datasets (they share the paradigm="imagery" tag
in the MOABB catalog). Labeling that section "Motor Imagery" was
therefore misleading — a reader scanning the table could see
BCIComp2020IS, Pressel2016, or Nguyen2017_* and wonder why speech
datasets were grouped under a movement heading.

Renamed the section to "Imagery" with a broader intro that
explicitly calls out the two sub-families (motor imagery and
imagined speech) and points at the dedicated Imagined Speech
subsection below via a :ref:`imagined-speech` cross-reference.

Added a matching .. _imagined-speech: anchor before the subsection
heading so the new ref resolves, and renamed the subsection
heading to "Imagined Speech (imagery subset)" so the sub-family
relationship is clear from the heading alone.

The Motor Imagery Datasets block in docs/source/api.rst is left
unchanged: its autosummary only contains motor-imagery classes
(the 7 speech classes are in the separate "Imagined Speech
Datasets" subsection), so its heading is still accurate.

Verified after edit:
- build succeeded, 1 warning (the pre-existing sphinx-gallery
  show_memory notice unrelated to this branch)
- Top-level sections now: Data Summary, Per-Paradigm Detail
  Tables, Imagery, Imagined Speech (imagery subset), P300/ERP,
  SSVEP, c-VEP, Resting States
- The "imagined speech subsection" ref link in the Imagery
  intro resolves to href="#imagined-speech" (the explicit label
  anchor), while the right-sidebar nav uses the auto-generated
  "#imagined-speech-imagery-subset" id from the heading title.
  Both point at the same section.
The interactive macro table at the top of dataset_summary.html
renders a colored Paradigm pill in each dataset row by looking
the dataset's paradigm string up in PARADIGM_LABELS in
docs/source/sphinxext/dataset_constants.py. The mapping had
``"imagery": "Motor Imagery"`` which was misleading: imagined
speech datasets (BCIComp2020IS, AguileraRodriguez2025, Pressel2016,
Nguyen2017_*) all share ``paradigm="imagery"`` in the catalog and
were therefore being labeled "Motor Imagery" in the macro table —
the wrong sub-family.

Renamed the label to "Imagery" so the pill matches the umbrella
that the section heading in dataset_summary.rst was already
renamed to. The pill color (#1565C0) is unchanged so existing
filtering / tooltips that key off the paradigm tag keep working.

Verified after rebuild: all 61 imagery pills in the macro table
now read "Imagery" (Pressel2016, BCIComp2020IS, Nguyen2017_V,
AguileraRodriguez2025 specifically confirmed). The "Motor Imagery"
strings remaining in the macro table HTML are in the per-dataset
Modality column, which comes from each class's
``Tags(modality=["Motor Imagery"])`` declaration — that is
correct per-dataset metadata, not a global label.
- Add Imagery (alias) and SpeechImagery (1-100 Hz broadband defaults)
  paradigm classes for the imagery umbrella covering motor imagery and
  imagined speech, with exports in paradigms/__init__.py.

- Embed original paper protocol figures in 9 dataset docstrings
  (Pressel2016, AguileraRodriguez2025, BCIComp2020IS, Nguyen2017 x4,
  Kojima2024A/B) from their respective publications. Figures stored
  in docs/source/_static/paper_figures/ with NOTICE.md documenting
  source DOIs and licenses (CC-BY-4.0, CC-BY-NC-ND-4.0, author
  postprints). Sphinx extension dedup guard suppresses auto-injected
  timeline SVG when a paper figure is already in the docstring.

- Add HED tags (validated against schema 8.3.0 via hed-python) to all
  9 datasets: imagined speech uses (Imagine, Speak, Word/Phoneme),
  Kojima P300 uses (Oddball, Target/Non-target, Hear, Discriminate).
  Nguyen2017 tags DRYed via _nguyen_hed() helper.

- Update docs: rename Motor Imagery -> Imagery section in api.rst,
  update dataset_summary.rst code example to use SpeechImagery,
  rename heading to "imagery family".
- Nguyen2017: extract shared metadata into _NGUYEN_ACQUISITION,
  _NGUYEN_PREPROCESSING, _NGUYEN_TAGS, _nguyen_participants(),
  _nguyen_docs() factories. Saves ~200 lines across 4 subclasses.

- HED tags: add _speech_hed() helpers in pressel2016.py,
  bcicomp2020_imagined_speech.py, aguilera_rodriguez2025.py,
  reducing 4-line entries to 1-liners (~40 lines saved).

- Figures: switch BCIComp2020IS, AguileraRodriguez2025, Kojima2024A/B
  from hosted copies to external publisher URLs (Frontiers CC-BY-4.0,
  Springer, PLoS ONE CC-BY-4.0). Removes 3 binary files from repo.
  Keep local copies only for Nguyen2017 and Pressel2016 (no external
  URL available). Simplify dedup guard to detect any .. figure::
  directive in docstring.
The PLoS figure URL contained a DOI-like string
(10.1371/journal.pone.0303565.g001) that the DOI validation
test falsely detected as an untracked DOI. Revert to a local
copy to avoid the regex match.
@bruAristimunha
bruAristimunha merged commit b930ed2 into develop Apr 12, 2026
13 checks passed
@bruAristimunha
bruAristimunha deleted the feat/add-speech-imagery-datasets branch April 12, 2026 14:55
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants