Skip to content

Read EEGLAB .set headers for the channel-count gate - #1564

Merged
neuromechanist merged 11 commits into
devfrom
feat/zarr-eeglab-header-count
Sep 29, 2026
Merged

neuromechanist merged 11 commits into
devfrom
feat/zarr-eeglab-header-count

Conversation

@neuromechanist

@neuromechanist neuromechanist commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

Summary

The Zarr converter's always-on channel-count gate now reads the channel count from EEGLAB .set headers, as it already does for EDF/BDF, BrainVision and FIF.

Problem (on003645, on hallu). The dataset mixes MEG .fif and EEG .set recordings. Its subject-level channels.tsv lists 404 MEG channels, and the EEG recordings inherit it. Their .set files hold 75 channels. file_declared_channel_count returned None for .set, so store 75 < sidecar 404 had no header to prove the store complete. All 108 EEG recordings were refused as channel_count_mismatch. A .fif in the same situation is served with a sidecar_overcount disclosure; a .set now gets the same treatment.

Changes

  • file_declared_channel_count: new .set branch (_eeglab_declared_channel_count)
    • The container is detected the way biosigIO's _is_matlab_v73 does it, from the MAT header text.
    • MATLAB v7.3: read through h5py metadata only. It reads EEG/nbchan, or the flat root when that root has nbchan/srate/pnts/data. An EEG group wins when both layouts exist. Dataset.shape gives the matrix's shape without reading any samples.
    • Classic MAT v5/v7: read by a small bounded streaming parser (_mat5_eeglab_header). It walks element headers, skips uncompressed variables by seeking, and decompresses in 1 MB chunks that it throws away. It stops once nbchan and data have both been seen, and never reads data past its dimensions.
      • Why not scipy.io.loadmat(variable_names=...): I measured it, and it does not keep the read cheap. A real EEGLAB export is ONE variable, EEG, with data inside it. loadmat(variable_names=["EEG"]) on a 100 MB inline-data .set peaked at 103 MB traced. The flat layout alone would be cheap. On the same files the new reader peaks at about 0.01 MB (uncompressed) and 5 MB (compressed).
    • Both layouts are handled, wrapped EEG struct and flat variables. The EEG field wins, as in biosigIO's _normalize_eeglab_dict. For a struct array, the first element is used.
    • The count is returned only where it equals what biosigIO serves (parity analysis below):
      • .fdt-backed: returns nbchan.
      • Inline: returns nbchan only if it equals the matrix's row count. On disagreement it returns None, with one ::warning::.
    • Other None cases each get one ::warning::, in the FIF branch's wording: unreadable, truncated or corrupt files, a missing nbchan or data, and a nonpositive, fractional or absurd (>100000) nbchan. With None, the gate falls back to channels.tsv alone, which is the old strict behavior. MemoryError is re-raised.
    • Docstrings updated: file_declared_channel_count and expected_channel_count_for's description of the two ground truths still holds.
  • Schema text: the in_file description in shared/zarr-index.schema.json now names FIF nchan and EEGLAB nbchan. Before, it listed only EDF/BDF and BrainVision. Text only, no structural change.
  • .memory/repeated-channel-labels-collapse-stores.md: .set is moved out of the "no cheap header" list, and the note records the loadmat trap.
  • Existing test updated: test_a_format_with_no_cheap_header_is_unknown_without_a_warning used .set as its example of a format with no header. It now uses KIT .con.
  • CHANGELOG.md is not touched; that text is written at release time.

Header count vs importer parity (biosigio 1.2.10, importers/eeglab.py)

Both _load and _load_v73 treat the data matrix as authoritative. chanlocs only names rows: a short chanlocs is padded and a long one is trimmed. A nbchan that disagrees with the matrix is only a warning, and the matrix rows are served. For a .fdt, the file is reshaped to (nbchan, pnts*trials) and refused when its size disagrees. So nbchan is a faithful count only where the matrix cannot disagree with it. I checked every case by importing the same real file with biosigIO and building a store:

Case Header biosigIO store Enabled
classic inline, wrapped or flat, compressed or not nbchan nbchan yes
classic with .fdt (wrapped/flat) nbchan nbchan yes
classic epoched with .fdt nbchan nbchan (flattened) yes
classic epoched inline 3-D nbchan import fails before the gate moot
chanlocs shorter / longer / repeated labels nbchan nbchan yes
v7.3 nested and flat, inline nbchan nbchan yes
v7.3 with .fdt nbchan nbchan yes
v7.3 square matrix nbchan nbchan yes
v7.3 epoched nbchan importer refuses (NotContinuous) moot
nbchan != matrix rows (classic or v7.3, over or under) None matrix rows refused: nbchan above the rows would wrongly refuse a faithful store

ICA activations and reference (nodatchans) channels are neither in data nor in nbchan, so they cannot skew the count. Real files agree too:

  • A real on003645 .set (OpenNeuro ds003645 sub-002 run-1, MATLAB-written, flat, compressed, .fdt) reads as 75 in 0.003 s, and biosigIO imports 75 columns.
  • MNE's MATLAB-written EEGLAB test files (test_raw.set, test_raw_onefile.set, test_epochs.set, test_raw_h5.set) all match the importer.

Tests (real files written with scipy/h5py, no mocks)

  • TestEeglabDeclaredChannelCount (unit tests, each count cross-checked against biosigIO's import of the same file):
    • classic in every layout and compression, int16/float32 matrices, classic .fdt
    • v7.3 nested, flat, .fdt and square
    • epoched files, a short chanlocs, and EEG winning over flat variables
    • nbchan disagreeing with the matrix, unusable nbchan values, missing nbchan or data
    • garbage, empty, truncated and corrupted-zlib files, and a non-EEGLAB v7.3 file
    • memory: on a 19.2 MB inline .set, tracemalloc shows loadmat(variable_names=["EEG"]) peaking above 90% of the data size and the header read below a third of it. The bound is shown to tell the two reads apart.
    • a real store SHORT of a real header is still truncated / ChannelCountMismatch, with every sidecar value (None, 3, 5, 404).
  • TestConvertOneEeglabSidecarOvercount (through convert_one):
    • An inherited subject-level channels.tsv declaring 404 or 9 channels over a 3-channel .set publishes. It is synced, the entry carries channels_tsv_count_mismatch == {channels_tsv: N, in_file: 3, in_store: 3}, and the index is schema-valid. Covered for classic inline, classic .fdt, classic flat, v7.3 inline and v7.3 .fdt.
    • A matching sidecar adds no note.
    • An unusable header (nbchan 5 over 3 rows) is still refused as channel_count_mismatch against the sidecar alone, and nothing is synced.
    • A corrupt .set is refused before any store exists.
  • TestDeclaredFdtConvertOne.test_the_header_gate_reads_the_staged_set: the ADR 0073 declared-.fdt path discloses an over-declaring sidecar.
  • Mutation-checked, one change at a time: dropping the .set dispatch, trusting nbchan over the rows, dropping the v7.3 transpose rule, letting flat win over EEG, accepting nonpositive nbchan, distrusting .fdt, and loading EEG whole. Each one fails the suite.

Results

  • test_generate_zarr.py test_zarr_queue.py test_purge_non_raw_stores.py test_find_collapsed_channel_stores.py test_patch_power_line_frequency.py with biosigio 1.2.10: 965 passed, 5 skipped (Linux-only RLIMIT and /proc tests), 0 failed.
  • test_hallu_zarr_config.py: 51 passed locally. The other 74 need bash 4+ (this macOS has bash 3.2) and are left to Linux CI. No hallu file is touched.
  • bun test zarr mcp: 879 pass at the root and 679 in backend.
  • ruff: no new findings against origin/dev (compared by rule and message). ty: no findings in the changed ranges.

After the next release

  • Requeue on003645, whose 108 EEG recordings were declined: zarr_queue.py requeue --status done --dataset on003645 --execute, or run it with --dataset.
  • Other datasets with .set recordings under an over-declaring or inherited channels.tsv were likely refused the same way. Two ways to find them:
    • the index failures with code channel_count_mismatch on a .set path;
    • scripts/zarr/find_collapsed_channel_stores.py, which is read-only. Its default mode checks published stores and counts a store short of channels.tsv without an overcount note under short_of_channels_tsv. It does not list declined recordings, so the index's failure list is the main source for refusals.
  • ZARR_ENGINE_VERSION is not bumped (ADR 0033): discovery is unchanged, and refused recordings come back through a targeted requeue.

Review round 1

One commit per finding, all rebased on origin/dev.

  • The fidelity sweep reads the overcount note (Let the fidelity sweep read the overcount note). backend/src/services/zarr-fidelity-sweep.ts flagged channel_count_mismatch whenever a store's total was below its channels.tsv, so the stores this PR newly serves (on003645's 108 EEG recordings, 75 vs 404) would have been marked failed and left has_zarr_verified false; the same was already true for FIF/EDF since 0.10.9 and for on000117. A store short of its sidecar is now not a mismatch when its own index entry carries a channels_tsv_count_mismatch that parses against the shared zod schema and has in_store == in_file == the store's channel total. A store short of its header, short of the sidecar with no disclosure, with a malformed disclosure, or with a disclosure that does not match the served total is still flagged. This is a backend Worker behavior change; it ships with the next release. Tests drive runZarrFidelitySweep: disclosure present and consistent (verified), absent (failed), in_store < in_file (failed), inconsistent with the groups (failed), malformed (failed). Reverting the condition fails the first.
  • The header walk stops at data's dims (Stop the EEGLAB header walk at data's dims). _mat5_struct_fields skipped past data before its both-seen check, so a compressed EEG inflated every sample. It now returns as soon as both are read. The regression test writes a compressed EEG whose deflate stream is real for the header and the first 64 KiB of samples and garbage after; the count comes back, and with nbchan moved after data the same garbage is reached and the read returns None. The old code fails it.
  • Memory test margin (Widen the EEGLAB header memory test margin). The stream chunk is now 64 KiB (it bounded both the compressed input read and each skip step at 1 MiB). The test uses a 51.2 MB inline matrix, with nbchan both before and after data (the latter forces a full skip through the compressed matrix), against a bound of a sixteenth of the samples (3.2 MB). Measured parser peak is under 0.4 MB; loadmat peaks above 51 MB. This replaces the 19.2 MB / one-third bound described above.
  • Inflate cap (Cap bytes an EEGLAB header read may inflate). EEGLAB_MAX_HEADER_READ_BYTES = 256 MiB bounds the bytes one classic header read may inflate or inspect (seeks past uncompressed fields do not count); past it the read returns None with the usual single ::warning::. After the fix above, only the fields ahead of nbchan and data are inflated; in EEGLAB's order the largest is times, one double per sample. A MAT v5/v7 variable is capped at 2 GiB, so with inline single-precision samples times fits under the cap from 15 channels up; a read that reaches it (for example a very long .fdt-backed recording) is only unknown, the gate it had before this PR. Tested with a zlib bomb that declares cap + 1 MiB of zeros ahead of nbchan in a file under 2 MB: None in well under a second. The same shape just under the cap still counts.
  • Odd nbchan, documented (Document why odd EEGLAB nbchan is unknown). A fractional nbchan stays None: biosigIO truncates it for classic files and rounds it for v7.3, so no single integer is what it serves. A new test pins both importer readings of 3.6 (3 and 4) against the parser's None. nbchan below the matrix rows also stays None rather than serving as a lower bound: the count is published as in_file and used as proof of completeness, and a header its own matrix contradicts proves nothing. A v7.3 subtest now covers that case too.
  • Hand-built MAT v5 coverage (Test EEGLAB header on hand-built MAT files). A small in-test writer (Mat5) covers what scipy.io.savemat cannot produce, and every file it writes is cross-checked by scipy.io.loadmat and biosigIO's importer:
    • big-endian files, wrapped and flat, compressed or not, with nbchan as double, uint8 or int32 (the last two in a small data element, whose tag big-endian files store swapped). Making the small-element unpack little-endian only fails 14 subtests.
    • a 1xN EEG struct array: the first element wins, and an inconsistent first element is not rescued by a consistent second;
    • nbchan stored after data;
    • top-level variables before and after EEG, including a large matrix and flat nbchan/data decoys;
    • truncation at every 2% of a real compressed, uncompressed and big-endian file, plus every byte of the first 512. Each read returns None or the true count, never raises, and runs under a 5 s SIGALRM guard (1,716 subtests, about 1 s).

Round 1 results

  • The five converter suites (test_generate_zarr.py test_zarr_queue.py test_purge_non_raw_stores.py test_find_collapsed_channel_stores.py test_patch_power_line_frequency.py) with biosigio 1.2.10 and mne 1.13.2: 973 passed, 5 skipped (Linux-only RLIMIT and /proc tests), 0 failed.
  • test_hallu_zarr_config.py: 51 passed; the other 74 need bash 4+ and are left to Linux CI. No hallu file is touched.
  • bun test zarr mcp: 884 pass at the root and 684 in backend, including zarr-fidelity-sweep and its route test.
  • ruff: no new findings against origin/dev (by rule and message). ty: diagnostic counts by rule and message are identical to origin/dev for both files.
  • The reviewer's fuzzer (truncation, byte flips and oversized length fields over 9 seed files), 4 seeds × 57,065 runs: 0 crashes, 0 hangs, 0 wrong values, 0 slow. The 1 GiB bomb from review now returns in 0.00 s, and on a 100 MB file the parser takes about 1 ms with a peak of 0.2 MB.

A .set had no header count, so a store short of an inherited
channels.tsv was refused even when it held every channel the file
declares (on003645: 75-channel EEG under a 404-row MEG sidecar).
Read nbchan from classic MAT v5/v7 (bounded streaming parse, never
the sample matrix) and v7.3 (h5py metadata), and return it only
where it equals the rows biosigIO serves. Tested with real files
through convert_one; mutations of each guard fail the suite.
The struct walk skipped past data before its both-seen check, so a compressed EEG inflated every sample. Return as soon as nbchan and data are read. Adds a hand-built MAT v5 writer to the tests and a regression test whose deflate stream is garbage after the first 64 KiB of samples. Tested: pytest TestEeglabDeclaredChannelCount.
Shrink the MAT stream chunk to 64 KiB and test a 51 MB matrix, with nbchan before and after data, against a 3.2 MB bound; the parser peaks under 0.4 MB. Tested: pytest never_loaded.
Add EEGLAB_MAX_HEADER_READ_BYTES (256 MiB) across one classic .set header read; past it the read gives up with the usual single warning. Tested: a zlib bomb declaring cap + 1 MiB of zeros before nbchan returns None in under a second; one just under the cap still counts.
Explain why a fractional nbchan (biosigIO truncates classic, rounds v7.3) and an nbchan below the matrix rows both return None. Tests pin the importer's two readings of 3.6 and add the v7.3 nbchan-below-rows case. Tested: pytest fractional/disagreeing.
Cover big-endian files (including small-element nbchan), a 1xN EEG struct array, nbchan after data, variables around EEG, and truncation at every 2% and each of the first 512 bytes of three real files, each read bounded by a 5 s alarm. Tested: pytest, 1716 subtests.
A store short of its channels.tsv no longer counts as channel_count_mismatch when its own index entry discloses channels_tsv_count_mismatch with in_store == in_file == the store's total. A store short of its header, or short of the sidecar with no valid disclosure, is still flagged. Tested: bun test zarr-fidelity-sweep (73 pass).
@github-actions

github-actions Bot commented Sep 29, 2026 •

Copy link
Copy Markdown

📦 Package Preview

Your package is ready to test!

bun install -g nemar-cli@PR1564

Version: 0.10.10-PR1564.00ce4ec
Commit: 00ce4ec


🤖 Updated on each push.

The comment said 15 channels; its own arithmetic gives 16.
Comment only, not tested.
@neuromechanist

Copy link
Copy Markdown
Contributor Author

Review record, round 1 fixes (Sonnet review of 92b487c, head now 00ce4ec).

No critical or important findings. The sweep excuse zarrFidelityDisclosedSidecarOvercount needs a schema-valid disclosure with in_store === in_file === the store's group total; a store short of its header, or with a missing, malformed or mismatched disclosure, still fails channel_count_mismatch, and the converter refuses header-short stores before publishing. The 256 MiB inflate cap and the early return in _mat5_struct_fields behave as designed, covered by real-file, hand-built-layout, truncation and zlib-bomb tests with no mocks. Checks run by the reviewer: bun test on the sweep file (66 pass), biome, and the EEGLAB pytest subset (24 tests, 1750 subtests).

Suggestions:

  • The cap comment said "15 channels"; corrected to 16 in 00ce4ec (comment only).
  • Skipped, intentionally: requiring disclosure.channels_tsv === parsed.count in the sweep. The sweep's parseChannelsTsv skips rows with a blank name, while the converter's channels_tsv_row_count counts every non-blank line, so the two counts can legitimately differ and the check would flag healthy stores. The excuse is already bounded by in_store === in_file, so it cannot hide a header-short store.
  • Third item (tag read near the budget edge): negligible, needs no change.

@neuromechanist
neuromechanist merged commit 825d089 into dev Sep 29, 2026
12 checks passed
@neuromechanist
neuromechanist deleted the feat/zarr-eeglab-header-count branch September 29, 2026 20:25
neuromechanist added a commit that referenced this pull request Sep 29, 2026
The chunked annex fetch and the EEGLAB header count shipped in 0.10.10
but were missing from its entry; adds them under Fixed and the Hallu
ListBucket and requeue notes under Deploy coupling. Format test passes.

This branch was previously deployed

1 inactive deployment
npm — 00ce4ec0 Deployed Sep 29, 2026 by neuromechanist via publish #2998
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.

1 participant