Skip to content

Derive AcquisitionMetadata.n_channels from channel_types instead of storing it - #1166

Merged
bruAristimunha merged 3 commits into
NeuroTechX:developfrom
bruAristimunha:split/metadata-derive-n-channels
Aug 27, 2026
Merged

bruAristimunha merged 3 commits into
NeuroTechX:developfrom
bruAristimunha:split/metadata-derive-n-channels

Conversation

@bruAristimunha

Copy link
Copy Markdown
Collaborator

Split out of #1161 so the mechanical part is reviewable on its own. Net −265 lines.

The problem

AcquisitionMetadata stored n_channels next to channel_types, which describes the same fact. The two could disagree, and for 34 of the 147 catalogued datasets they did.

The cause was not carelessness — the field was being used with two different meanings:

Dreyer2023A.METADATA.acquisition
#   n_channels   = 27                                  <- EEG electrodes only
#   channel_types = {"eeg": 27, "emg": 2, "eog": 3}     <- 32
#   sensors       = [... 32 entries ...]                <- 32

48 datasets declare more than one channel type, so the two readings diverge for a third of the catalogue.

The fix

Delete the field; derive it.

@property
def n_channels(self) -> int:
    return sum(self.channel_types.values())

It now consistently means every recorded channel — the reading that each dataset's own sensors list and test_n_channels_matches_raw_data (which counts every non-stim channel) already assumed.

The 34 disagreements are not fixed so much as made impossible, which is why this adds no validator and no invariant test. validate_metadata_against_dataset needs no new assertion.

What that removes

  • 218 n_channels= arguments across 93 files
  • the enrichment branch in metadata/__init__.py whose only job was to backfill the value
  • two replace(...) defaults that also disagreed with their own channel_types

Behaviour change

For the 34 datasets that stored the EEG-only count, n_channels now reports the total. Dreyer2023A goes 27 → 32. One test asserted the old reading and now asserts the total; it is the only one in the suite that pinned a literal value for a multi-type dataset.

Documented under API changes, not Bugs: passing n_channels= to the constructor is no longer accepted.

Verification

  • n_channels != sum(channel_types): 34 → 0, and now unrepresentable
  • every AcquisitionMetadata(...) call site still passes sampling_rate and channel_types — checked by AST across the package, 0 broken
  • 1740 passed (the single failure, test_lee2024_data_path_downloads_the_real_upstream_inventory, is pre-existing on develop)
  • pre-commit clean

Closes #1163.

@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: d61a622314

ℹ️ 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 on lines +379 to +380
@property
def n_channels(self) -> int:

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Remove n_channels from the remaining coverage fixture

Running pytest -q moabb/tests/test_bids_enrichment.py::TestReadmeAcquisitionFields now produces 17 failures because test_field_present still includes n_channels in the constructor kwargs at moabb/tests/test_bids_enrichment.py:2164. Since this property replaces the constructor field, update that parametrized coverage test to derive the count through channel_types (and remove or adapt its n_channels case) so the normal test suite can pass.

Useful? React with 👍 / 👎.

AcquisitionMetadata stored `n_channels` next to `channel_types`, which
describes the same fact. The two could disagree, and for 34 of the 147
catalogued datasets they did.

The cause was not carelessness: the field was being used with two different
meanings. Dreyer2023A stored 27, counting only its EEG electrodes, while its
own channel_types ({eeg: 27, emg: 2, eog: 3}) and its own 32-entry sensors
list both describe 32 channels. 48 datasets declare more than one channel
type, so the two readings diverge for a third of the catalogue.

Rather than add a validator for a field that should not exist, the field is
gone and `n_channels` is a property over `channel_types`. It now consistently
means every recorded channel -- the reading that `sensors` and
`test_n_channels_matches_raw_data` (which counts every non-stim channel)
already assumed. The 34 disagreements are not fixed so much as made
impossible, and `validate_metadata_against_dataset` needs no new assertion.

218 `n_channels=` arguments come out across 93 files, together with the
enrichment branch in metadata/__init__.py whose only job was to backfill the
value. One test asserted the old EEG-only reading for Dreyer2023A and now
asserts the total.

Net -265 lines. Split out of NeuroTechXgh-1161 so the mechanical change is reviewable
on its own; closes NeuroTechXgh-1163.
@bruAristimunha
bruAristimunha force-pushed the split/metadata-derive-n-channels branch from d61a622 to d4f3eee Compare August 26, 2026 21:15
…nnels

The four GuttmannFlury2025 classes declared `"stim": 1` in `channel_types`.
That was harmless while `n_channels` was stored independently, but now that it
is `sum(channel_types.values())` it makes the four report 66 recorded channels
where 65 were recorded -- MOABB adds the stim channel itself, as
`test_metadata_matches_raw_data` says in the comment above the
`raw_counts.pop("stim", None)` it does before comparing.

That test is `@pytest.mark.download`, and NeuroTechXgh-1161 is the change that repairs
the monthly download job (it pointed at a file that does not exist and
collected nothing), so merging both would have surfaced this as an off-by-one
on four datasets.
…ive-n-channels

# Conflicts:
#	moabb/datasets/bnci/bnci_2025.py
@bruAristimunha
bruAristimunha merged commit 8d3c12d into NeuroTechX:develop Aug 27, 2026
13 checks passed
bruAristimunha added a commit that referenced this pull request Oct 4, 2026
…i2020_XP2, Iwama2023) (#1186)

* Add four OpenNeuro motor-imagery datasets

Lee2022 (ds004022), LioiXP1 (ds002336), Lioi2020 (ds002338) and
Iwama2023 (ds004444). NEMAR mirrors OpenNeuro under the same ids, so
each declares its ds id as nemar_id and needs no rehosting.

Ported from the deep-ceiling benchmark branch to current develop:
n_channels dropped from AcquisitionMetadata (#1166), Lee2022.data_path
now forwards path/verbose (flag contract), and the summary_imagery rows
use trials per class per subject, as the rest of the table does.

* Link #1186 in whats_new

* Iwama2023: take events from events.tsv only, drop the EDF Status trigger

The EDF's own Status channel marks rest onsets and a point ~1 s before
each task onset with the same code 1. It was read alongside the stim
channel built from events.tsv, so every session gained 20 spurious rest
epochs overlapping the imagery (rest 40 vs right_hand 20 per session).
Found in the real-data smoke test on subject 1: 640 rest vs 320 MI.

* Cache the Perronnet 2017 DOI that LioiXP1 cites

* fix(datasets): route verified OpenNeuro mirrors through NEMAR raw BIDS

* test: audit and trim #1186 tests (-9 tests, coverage unchanged)

The OpenNeuroMirrorMixin contract (provider policy, SDK raw selection with a
mocked HTTP transport, no sourcedata prefetch from get_data) is a shared
contract with one owner: run it once through Iwama2023 instead of replaying
it for every loader. test_mirror_flags stays parametrised because NEMAR ids,
subject-label mapping and target dirs are dataset-specific.

Tests collected in test_openneuro_mirror.py: 16 -> 7. Per-file coverage of
_openneuro_mirror.py (94%), iwama2023.py (43%), lee2022.py (40%),
lioi2020.py (29%), lioixp1.py (38%) unchanged (offline suite, no downloads).

* refactor: simplify #1186 loaders and tests (-274 LOC)

* refactor(datasets): shared loader helpers and montage-name compatibility

- resolve_montage_name (moabb.datasets._montage, re-exported by utils): MNE 1.13
  renamed standard_1005/1020 (and the other standard_* templates) to colin27_*,
  warns on the old names and 1.14 removes them. Returns the spelling the installed
  MNE knows; electrode files are byte-identical (dig positions checked equal on
  MNE 1.10.2, 1.12.1 and 1.13.2). Every make_standard_montage/set_montage call in
  moabb now goes through it; METADATA montage labels are descriptive and unchanged.
- download_and_extract_zip: download once, extract unless a marker exists,
  optional warn + forced re-download of a corrupted archive.
- read_raw_brainvision_repaired: repair stale DataFile/MarkerFile references in a
  temporary header (strict mode raises on missing entries/siblings).
- rename_stimulus_codes, edge_boundary_annotations; SetRawAnnotations keeps
  'EDGE boundary' markers.
- moabb.datasets._openneuro_mirror moved here verbatim (byte-identical copies in
  #1186 and #1189), with dataset-agnostic tests.

* DOC add PR number to the shared-helpers whats_new entries

* refactor: use shared loader helpers; exempt from NEMAR check; new montage names

Merges #1200 (datasets/shared-loader-helpers): local zip/BrainVision/EDGE-boundary
code replaced by moabb.datasets.utils helpers, montage calls spelled with the
MNE 1.13 colin27_* names via resolve_montage_name, new classes without a public
NEMAR mirror listed in NEMAR_ID_EXEMPT. Behaviour fingerprints unchanged.

* build: require mne>=1.13; spell colin27_* montages directly

MNE 1.13 renamed the standard_* templates to colin27_* (identical .elc
files). With the floor at 1.13 the resolve_montage_name shim and the
_montage module are not needed: every call site spells the new name.

* refactor(datasets): reuse existing code instead of new loader helpers

- download_and_extract_zip -> extend download_and_extract_subject_zip with
  keyword-only fname and redownload_corrupted (defaults keep the 10
  develop callers unchanged)
- read_raw_brainvision_repaired -> mne.io.read_raw_brainvision(overrides=)
  at the call sites (MNE >= 1.13)
- edge_boundary_annotations -> mne.Annotations(onsets, 0.0, 'EDGE boundary')
- drop_native_stim / relabel_annotations / write_dataset_description ->
  drop_channels / annotations.rename / mne_bids.make_dataset_description
- tests: no nested functions, Mock data_dl

* refactor: reuse MNE/mne-bids instead of removed mirror helpers

- drop_native_stim -> raw.drop_channels([...stim channels...])
- relabel_annotations -> raw.annotations.rename({present keys only})
- write_dataset_description -> mne_bids.make_dataset_description
  (adds DatasetType/GeneratedBy, BIDSVersion from mne-bids, doi: prefix)
- resolve_montage_name -> colin27_* spelled directly (mne>=1.13)
- tests: module-level httpx handler, Mock instead of monkeypatched lambdas

* fix(Lioi2020): align metadata with 10.1038/s41597-020-0498-3 (paper audit)

- ground AFz ("FCz as the reference electrode and AFz as the ground electrode")
- demographics from Table 3 (9 M / 8 F, 26-66 y, per-subject ages/sexes)
- n_trials 8 -> 1360 total (5 runs x 16 blocks x 17 subjects; MIpost
  duration not stated in the paper, assumed equal to MIpre)
- docstring: block timing per run; note on the paper's 'left hand' wording

Evidence: ~/Projects/moabb/.paper-audit/reports/mi-batch-1/Lioi2020/

* fix(LioiXP1): align metadata with 10.1038/s41597-020-0498-3 (paper audit)

- institution as in the data paper affiliation (Univ Rennes, Inria, CNRS,
  Inserm, IRISA)
- docstring/trials_context: Perronnet et al. 2017 report MIpre/MIpost not
  acquired for two participants and lost for a third, so per-subject run
  counts are not uniform (needs_real_data_check for the 780-block total)

Evidence: ~/Projects/moabb/.paper-audit/reports/mi-batch-1/LioiXP1/

* fix(Iwama2023): align metadata with 10.1038/s41597-023-02260-6 (paper audit)

- ground FCz -> CPz ("Cz and CPz channels were set as the reference and
  ground channel, respectively")
- gender 25 M / 5 F, right-handed, age 21.23 +/- 2.2 (Dataset 1 paragraph)
- investigators in the paper's author order
- docstring: 16 blocks = (pre + 6 NF + post) x 2 days, one EDF per block

Evidence: ~/Projects/moabb/.paper-audit/reports/mi-batch-1/Iwama2023/

* fix(Lee2022): align metadata with 10.18112/openneuro.ds004022.v1.0.0 (paper audit)

- per-subject ages/sexes and handedness (6 R / 1 L) from participants.tsv
- docstring: the README calls the 3 x 40-trial runs 'three sessions'; the
  release stores run-1..3 in one BIDS session, exposed as three runs

Evidence: ~/Projects/moabb/.paper-audit/reports/mi-batch-1/Lee2022/

* refactor(Lioi2020): rename to Lioi2020_XP2 (naming rule)

Rules 2+3: the primary data paper (Lioi et al., Sci Data 2020,
doi:10.1038/s41597-020-0498-3) describes both OpenNeuro releases and
states that "they were split in XP1 and XP2 for the sake of clarity";
this class is the second one ("XP2. The resource contains data from 17
subjects"), so it takes the FirstAuthorYear stem plus the official
variant suffix. code becomes "Lioi2020-XP2" (MOABB codes are
Camel-KebabCase) and the cache folder MNE-lioi2020-xp2-data; module,
registry, api.rst, whats_new, summary CSV and tests follow. Never
released, so no alias.

* refactor(LioiXP1): rename to Lioi2020_XP1 (naming rule)

Rules 2+3: the primary data paper (Lioi et al., Sci Data 2020,
doi:10.1038/s41597-020-0498-3) covers both OpenNeuro releases - "they
were split in XP1 and XP2 for the sake of clarity"; "XP1. The resource
contains data from 10 subjects" - so the class takes the FirstAuthorYear
stem of that paper plus the official variant suffix, and its primary
DOI / publication_year move from the bioRxiv preprint (10.1101/862375,
kept as a related paper) to the 2020 data paper. code becomes
"Lioi2020-XP1" (Camel-KebabCase); module, registry, api.rst, whats_new,
summary CSV and tests follow. Never released, so no alias.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
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.

34 of 147 datasets have self-contradictory channel metadata, and the validator that would catch it is never called

1 participant