Skip to content

Stream 9: Importers and dataset files (F10, F15, F18–F23, F26, F34, F119) - #575

Merged
suraj-ranganath merged 11 commits into
developfrom
stream9-importers
Nov 7, 2026
Merged

suraj-ranganath merged 11 commits into
developfrom
stream9-importers

Conversation

@suraj-ranganath

@suraj-ranganath suraj-ranganath commented Nov 7, 2026 •

Copy link
Copy Markdown
Member

Summary

Stream 9 of the release-readiness GUI audit: importer option dialogs, native readers, MATLAB v7.3 .set loading, save-as layout, and safe companion-file paths.

Fixes #554
Fixes #497
Fixes #561

Not in this PR: #538 (pop_load_frombids / BIDS None chanlocs) — owned by Stream 10 (fix_streams.md).

Findings

Finding Fix
F10 Import option dialogs for ASCII/BIOSIG/BVA/CNT/EGI/event/epoch/channel/Presentation/ERPLAB; Cancel preserves state; history is replayable
F15 / #497 MATLAB v7.3 HDF5 .set keeps full labels, nested refs, empty events, and channel-major data
F18 MFF folder picker; defusedxml in the mne extra
F19 Event import options; capitalized reserved fields rejected with advice
F20 Channel-event options; both edge types kept when edges coincide
F21 ASCII options; transpose samples×channels; float32; empty setname/chanlocs unless supplied
F22 Epoch import options; explicit fields/header lines
F23 CNT/EGI wire native readers; BVA float32; all time ranges via native pop_loadbv
F26 Save as keeps two-file layout; appends .set
F34 Helpful errors for corrupt/missing companions
F119 Native Neuroscan .EEG epoch reader; keep rejected sweeps (EEGLAB parity)
#561 pop_loadbv / pop_loadset reject companion paths that leave the header directory

Intentional differences from EEGLAB

F119 verdict (EEGLAB source)

EEGLAB loadeeg.m / pop_loadeeg.m (neuroscanio) default accepttype='all' and expose an accept field — rejected sweeps are kept. eegprep matches that. The fewer-trial count is a FieldTrip File-IO difference (accepted-count at byte 364), not EEGLAB. Documented in docs/source/user_guide/storage.rst + changelog (74519da7).

Full EEGLAB reference suite (jamming)

  • HEAD 74519da7 (docs on code tip e3cc265f); EEGLAB d0963be9; suite fec88f9f
  • Logs: ~/eegprep-bench/logs/s9_ref/
  • AGGREGATE tests=3937 · passed≈3876 · failed=5 · skipped=56
shard result
heavy 3 passed, 29 deselected
hybrid 1 failed, 142 passed, 4 skipped
stats 257 passed
study 338 passed, 27 skipped
misc 569 passed, 9 skipped
core 3 failed, 2111 passed, 14 skipped
parity 1 failed, 9 passed, 2 skipped

Failures vs develop

failure vs develop
test_matlab_tutorial_figures_retain_their_plot_target_between_calls known develop flake
test_average_reference_matches_matlab_on_64_channel_float32 (max_abs≈0.109) known develop flake
test_bids_preproc ×2 (…/eegprep-s9/data missing) same on develop/S5/S11 (bench data path)
test_parity_subcomps_subtracted TimeoutError 900s (suite) one-off incident — solo re-run PASSED on tip 74519da7 and develop 1bdd1a28

No new S9 code failures. Tolerances unchanged.

Tests

  • tests/test_stream9_*.py, tests/test_pop_loadset.py updates
  • Local: 94 stream9/loadset tests passed offscreen (--timeout=30)
  • Full reference suite above

Before merge (executor checklist)

  • Hands-on GUI retest side by side with EEGLAB (label non-pinned plugin comparisons)
  • MATLAB parity on jamming under flock ~/eegprep-bench/matlab.lock
  • CI green (on 74519da7)
  • Claude review read and answered (clean at e3cc265; docs-only 74519da7 follows)
  • Suraj explicit squash-merge approval

Notes

  • Only S9-owned files/methods edited (menu_actions import region, listed popfuncs, pop_saveset F26 only, pyproject.toml/uv.lock for defusedxml).
  • No beads. Tolerances unchanged. Never merge without Suraj approval.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Code review skipped — your organization has no extra usage available to pay for this review.

If your organization's extra usage balance is empty, an organization admin can add extra usage credits at claude.ai/admin-settings/usage. If its monthly spend limit was reached, an admin can raise it on the same page. If neither applies, contact Anthropic support.

Once extra usage is available, someone with write access to this repository can comment @claude review on this pull request to trigger a review.

@claude

claude Bot commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @suraj-ranganath's task in 3m 4s —— View job


Code review

  • Overall assessment: Needs changes. The importer dialogs, Cancel paths, history replay and the new readers look sound. The main problem is that the pop_loadbv and pop_loadset read the file a header names wherever it is #561 path hardening rejects symlinked companion files, which breaks DataLad and git-annex datasets.
  • Highest-risk area: companion-file path checks in pop_loadset._sidecar_path and pop_loadbv._referenced_file.
  • Merge recommendation: Needs changes.

Blocking

None.

Important

  • .set and BrainVision files from DataLad or git-annex datasets now fail to load (pop_loadset.py L217-225, pop_loadbv.py L636-647). Both checks call .resolve() on the companion file, which follows symlinks. Annexed .fdt, .eeg and .vmrk files are symlinks into .git/annex/objects/, so a normal OpenNeuro download now raises "leaves the dataset directory". This also affects pop_load_frombids.
    • Suggested fix: check the reference string (must be a bare filename with no drive) instead of the resolved target. If you also want to block symlinks, decide that explicitly and document it.
    • Details are in the inline comment.

Nits

  • pop_fileio._reader_for_suffix checks for defusedxml with its own import_module call. extras.import_optional_dependency already does this; add "defusedxml": "mne" to OPTIONAL_LIBRARIES and use that helper instead.
  • The try/except (ValueError, OSError, TypeError) in pop_loadset covers the whole new v7.3 decoder. A decoder bug on a valid file is reported as "not a valid .set … re-export", which sends users the wrong way. Catch only the open/parse errors.

Test gaps

  • New tests are in stream-named files. Tests for modules that already have test files went into new tests/test_stream9_*.py files: test_pop_loadbv.py, test_pop_saveset.py, test_pop_importevent_current.py, test_pop_importepoch_current.py and test_pop_loadset.py. AGENTS.md says "Test files generally mirror source module names" and "Extend the closest existing test first." Move the F19/F22/F23/F26/pop_loadbv and pop_loadset read the file a header names wherever it is #561/F34/F15 cases into those files.
  • test_f18_mff_reader_has_xml_dependency is tautological. It only checks that defusedxml parses XML and that _reader_for_suffix returns a function named read_raw_egi. A useful version would load a tiny .mff folder through pop_fileio, or check that the install-hint error appears when defusedxml is missing.
  • Symlink tests lock in the regression. The test_561_* cases at L79/L92 expect symlinks to be rejected. Whichever way the Important item is resolved, add a test where the companion file is a same-directory symlink to a file elsewhere, as git-annex creates.

EEGLAB parity notes

  • I couldn't compare against the .m sources (pop_importdata.m, pop_biosig.m, pop_importerplab.m, pop_chanevent.m, pop_saveset.m) because src/eegprep/eeglab/ isn't in this checkout. Parity for the dialog defaults was not checked. The following still need the side-by-side GUI and MATLAB check in your checklist:
    • pop_biosig's keepref choice for a single reference channel versus several;
    • pop_importdata auto-transposing a 2-D input whenever rows > columns and nbchan is unset (this also applies to programmatic numpy arrays, not only ASCII);
    • _save_two_files now using two files for any dataset that has a datfile.
  • This PR changes core readers (pop_loadset, pop_chanevent edge typing, pop_importdata dtype/orientation, pop_saveset). Under AGENTS.md it needs the EEGLAB reference-suite run (MATLAB backend) recorded in the PR body before merge.

Checked: Cancel/return-com paths in menu_actions, 1-based index handling (listdlg2, pnts reshape, Neuroscan sweep header offsets, chanevent value indices), the v7.3 HDF5 decoder, history replay, and AGENTS.md compliance.

Comment on lines +217 to +225
def _sidecar_path(datfile: str, file_path: Path) -> Path:
path = Path(datfile)
if path.is_absolute():
return path
return file_path.parent / path.name
path = Path(datfile.replace("\\", "/"))
candidate = path if path.is_absolute() else file_path.parent / path
if PureWindowsPath(datfile).drive or candidate.resolve().parent != file_path.parent.resolve():
raise ValueError(
f"pop_loadset: sample reference {datfile!r} leaves the dataset directory. "
"Keep the .set and .fdt together and use the companion filename in the header."
)
return candidate

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Important: .set files from DataLad or git-annex datasets no longer load

candidate.resolve() follows the .fdt symlink. In a DataLad or git-annex checkout, which is how OpenNeuro EEGLAB-format datasets are usually fetched, every annexed file is a symlink into <repo>/.git/annex/objects/.... The resolved parent therefore never equals file_path.parent.resolve(), so pop_loadset (and pop_load_frombids through it) raises leaves the dataset directory on a normal OpenNeuro download. pop_loadbv._referenced_file has the same problem with annexed .eeg and .vmrk files (pop_loadbv.py#L636-L647).

#561 is about the header string pointing elsewhere (.., a subdirectory, an absolute path). You can enforce that by checking the reference string, without following symlinks:

name = datfile.replace("\\", "/")
if PureWindowsPath(datfile).drive or Path(name).name != name:
    raise ValueError(...)
return file_path.parent / name

If you also want to block hostile symlinks, decide that explicitly and document it. Rejecting every symlink target breaks the most common way researchers get public EEG data. Whichever you choose, update test_561_* (the symlink cases at tests/test_stream9_dataset_files.py:79,92) and the "including symlink targets" sentence in pop_loadbv.md.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed. Companion checks now validate the header string (bare filename only). Same-directory DataLad/git-annex symlinks are allowed; .. / absolute / drive / separator references still raise. Tests updated accordingly.

Comment on lines +124 to +129
try:
import_module("defusedxml")
except ImportError as exc:
raise ImportError(
f'{feature}: MFF XML support is missing. Install it with pip install "eegprep[mne]".'
) from exc

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Nit: this duplicates an existing helper

eegprep.extras.import_optional_dependency already builds the "install eegprep[<extra>]" error from OPTIONAL_LIBRARIES (extras.py#L13-L19). AGENTS.md says: "Before writing any utility, helper … search for existing implementations" and lists "Parallel implementations of existing helpers" as a failure pattern.

Suggested fix: add "defusedxml": "mne" to OPTIONAL_LIBRARIES, replace this block with import_optional_dependency("defusedxml", feature=feature), and drop the importlib.import_module import.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed. Added "defusedxml": "mne" to OPTIONAL_LIBRARIES and switched _reader_for_suffix to import_optional_dependency.

Comment on lines +66 to +70
except (ValueError, OSError, TypeError) as exc:
raise ValueError(
f"pop_loadset: {file_path!r} is not a valid MATLAB .set dataset (MAT file). "
"Re-export the dataset from its source or restore an intact copy."
) from exc

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Nit: decoder bugs get reported as corrupt files

This try covers both opening the file and the whole new _read_set_h5 / dataset_from_mat decode. Any TypeError or ValueError from a decoding gap, such as a v7.3 field shape _read_value doesn't handle yet, reaches the user as "is not a valid MATLAB .set dataset … Re-export the dataset". The file is fine in that case, so the advice is wrong. AGENTS.md lists "Over-protective try/except blocks" as a failure pattern.

Suggested fix: wrap only the open/parse step. For example, catch OSError from h5py.File and scipy.io.matlab.MatReadError/ValueError from loadmat, and let decoding errors propagate.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed. Open/parse failures stay as the corrupt-file message; decoder TypeError/ValueError propagate.

…decoder errors

- Allow same-directory companion symlinks (DataLad/git-annex); reject path/drive references in the header string
- Use import_optional_dependency for defusedxml
- Narrow pop_loadset open/parse exception handling so decoder errors propagate

Copy link
Copy Markdown
Member Author

Claude review follow-up (head 4d2b4ec9)

Addressed the Important item and both nits:

  1. pop_loadbv and pop_loadset read the file a header names wherever it is #561 / DataLad annex symlinks (Important) — _sidecar_path / _referenced_file now check the header string only (bare filename; reject .., /, \\, drives). Same-directory annex/DataLad symlinks load again. Tests updated so adjacent symlinks are allowed; path/absolute references still raise.
  2. defusedxml helper (nit) — OPTIONAL_LIBRARIES["defusedxml"] = "mne" and import_optional_dependency in pop_fileio.
  3. Decoder try/except (nit) — open/parse errors only; decoder TypeError/ValueError propagate.

Declined / deferred: wholesale move of tests/test_stream9_*.py into older module-named files (large refactor; new cases stay stream-local for this PR). Improved the F18 dependency regression test.

MATLAB parity (jamming)

Under flock ~/matlab.lock with the batch engine at head before the Claude follow-up (tree covering F15/#497/#561/F10–F26/F119 readers):

134 passed, 2 skipped in 37.11s (tests/test_stream9_{dataset_files,import_options,readers}.py, test_pop_loadset{,_h5}.py, test_pop_importevent_current.py, test_pop_importepoch_current.py, test_pop_loadbv.py, test_cnt_eeglab_tests.py, test_egi_raw_eeglab_tests.py). Skips: neuroscanio plugin absent on the pinned EEGLAB tree (CNT upstream comparisons — labelled non-pinned).

After the Claude follow-up commits, the #561 / extras / decoder unit tests were re-run offscreen locally: 63 passed.

GUI retest (box :3, EEGLAB on jamming)

Finding eegprep EEGLAB
F21 / F10 ASCII options Full importdata dialog (srate, pnts, xmin, nbchan, ref, ICA, …) — screenshots/pr575_F21_ascii_opts_eegprep_*.png Matching dialog — screenshots/pr575_F21_ascii_opts_eeglab_*.png
F19 event import options Fields / append / headerlines / timeunit / align — pr575_F19_importevent_opts_eegprep_*.png Audit reference pr575_F19_importevent_opts_eeglab_audit.png
F20 channel events Edge / transition / delete options — pr575_F20_chanevent_opts_eegprep_*.png Audit reference pr575_F20_chanevent_opts_eeglab_audit.png
F15 HDF5 load Labels FPz,EOG1,…; event type square; 32×30504 — pr575_F15_hdf5_loaded_eegprep_*.png (MATLAB suite)
F26 Save as noext → noext.set+.fdt; two-file preserved (API) —
F34 errors Helpful corrupt / missing-.fdt messages with function name + fix —

F18 MFF folder picker and F119 Neuroscan covered by Qt/function tests; MFF/CNT/.EEG EEGLAB comparisons that need non-pinned plugins (mffmatlabio / neuroscanio / Fileio) are labelled as such.

Intentional differences

Retriggering Claude on this head. Not merging — needs Suraj's explicit squash-merge approval.

@suraj-ranganath
suraj-ranganath marked this pull request as draft November 7, 2026 17:49
@suraj-ranganath
suraj-ranganath marked this pull request as ready for review November 7, 2026 17:49
@claude

claude Bot commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @suraj-ranganath's task in 2m 16s —— View job


Code review (re-review at 4d2b4ec)

  • Overall assessment: Needs changes. The three earlier items are fixed. One new problem: pop_fileio now reads every .eeg file as Neuroscan, so BrainVision .eeg files that loaded on develop now fail.
  • Highest-risk area: .eeg routing in pop_fileio.
  • Merge recommendation: Needs changes.

Previous review items

  • ✅ Companion-file checks (pop_loadbv and pop_loadset read the file a header names wherever it is #561): pop_loadset._sidecar_path and pop_loadbv._referenced_file now check the header string. Symlinks in the same folder, as DataLad/git-annex creates, load again. References with .., a drive letter, or a path separator still raise.
  • ✅ defusedxml check: now uses extras.import_optional_dependency("defusedxml"), with "defusedxml": "mne" added to OPTIONAL_LIBRARIES.
  • ✅ Decoder errors: only errors from opening or parsing the file become the "not a valid .set" message. Decoder errors propagate. The new required-field check (data/nbchan/pnts/srate) also gives corrupt files a clear message.
  • The tests stay in the test_stream9_* files. The author decided that, so I'm not raising it again.

Blocking

None.

Important

  • BrainVision .eeg files are now sent to the Neuroscan reader (pop_fileio.py L80-81).
    • On develop, .eeg used mne.io.read_raw_brainvision. Now every .eeg file goes to _read_neuroscan_epochs.
    • The generic File-IO menu lists *.eeg and calls pop_fileio. A user who selects the .eeg file of a normal .vhdr/.eeg/.vmrk recording now gets a Neuroscan header error with no hint to choose the .vhdr file.
    • EEGLAB's File-IO (FieldTrip ft_filetype) reads .eeg as BrainVision when a .vhdr with the same name sits next to it, and as Neuroscan otherwise.
    • Suggested fix: send .eeg to pop_loadbv when path.with_suffix(".vhdr") exists, and to the Neuroscan reader otherwise.
    • Add a regression test that loads a BrainVision triplet through pop_fileio on its .eeg file. Details and code are in the inline comment. Fix this →

Nits

None.

Test gaps

  • No test calls pop_fileio on a BrainVision .eeg file. The tests only cover the Neuroscan .EEG path, so they don't catch the routing problem above.

EEGLAB parity notes

  • src/eegprep/eeglab/ isn't in this checkout, so I still couldn't compare against the .m files. These still need to be confirmed in your side-by-side check:
    • pop_importdata now auto-transposes any 2-D input with more rows than columns when nbchan is unset. This includes numpy arrays passed in code, not only ASCII files.
    • With the default save mode, pop_saveset now writes two files for any dataset that has a datfile (F26). Previously this only happened with savemode='resave'.
    • The Neuroscan .EEG reader places its per-sweep events (trial, accept, correct, response, rt) at the first sample of each epoch (latency = trial*points + 1), not at time 0. It also adds a non-standard offset field. If this is meant to match FieldTrip's trl layout, say so in storage.rst.
  • This PR changes core readers (pop_loadset, pop_chanevent, pop_importdata, pop_saveset). Your MATLAB run (134 passed, 2 skipped) covered stream-scoped tests on jamming. AGENTS.md also asks for the full EEGLAB reference suite with the MATLAB backend (--eeglab-backend=matlab, pinned EEGLAB and eeglab_tests commits) to be recorded in the PR body before merge.

Also checked:

  • The v7.3 HDF5 decoder: struct arrays vs. scalar structs, char rows, MATLAB_empty, axis reversal, and null references.
  • icachansind and urevent are converted to 0-based exactly once now that both formats share one load path.
  • pop_chanevent value indices for the two edge directions.
  • The 1-based Neuroscan sweep header offsets.
  • Cancel and empty-com handling in menu_actions.
  • The circular-import break in pop_loadset_h5.

Comment on lines +80 to +81
elif suffix == ".eeg":
eeg = _read_neuroscan_epochs(path, **options)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Important: BrainVision .eeg files are now sent to the Neuroscan reader

On develop, pop_fileio("x.eeg") used mne.io.read_raw_brainvision. This branch removes that path and sends every .eeg file to _read_neuroscan_epochs. BrainVision recordings are almost always saved as x.vhdr + x.eeg + x.vmrk, so a user who picks the .eeg file now gets a Neuroscan header error, or a wrongly shaped dataset if the bytes happen to parse. The error doesn't mention BrainVision or say which file to choose. This can happen from the GUI: the generic File-IO picker lists *.eeg (menu_actions.py#L651-L653) and then calls pop_fileio (L620-L623).

EEGLAB's File-IO (FieldTrip ft_filetype) has the same ambiguity. It reads .eeg as brainvision_eeg when a .vhdr with the same name sits next to it, and as ns_eeg otherwise.

Suggested fix: before the Neuroscan branch, check for a sibling header. pop_loadbv already maps .eeg to .vhdr in _header_path:

elif suffix == ".eeg" and blockrange is None and path.with_suffix(".vhdr").is_file():
    eeg = pop_loadbv(path, srange=samples, chans=channels)
    channels = None
    samples = None
elif suffix == ".eeg":
    eeg = _read_neuroscan_epochs(path, **options)

Add a test that writes a binary BrainVision triplet (_write_binary_brainvision already exists in tests/test_stream9_dataset_files.py), calls pop_fileio on the .eeg file, and checks the data. Also mention the sibling-.vhdr rule in pop_fileio.md.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed. .eeg/.EEG now use pop_loadbv when a sibling .vhdr/.ahdr exists (FieldTrip ft_filetype parity) and the Neuroscan epoch reader otherwise. Regression tests cover both paths.

Route .eeg/.EEG through pop_loadbv when a sibling .vhdr/.ahdr exists (FieldTrip ft_filetype parity); otherwise use the Neuroscan epoch reader.

Copy link
Copy Markdown
Member Author

Follow-up on Claude re-review + CI (head will be the latest stream9-importers tip after this push)

  • BrainVision .eeg routing (Important): fixed — sibling .vhdr/.ahdr → pop_loadbv; else Neuroscan.
  • CI: updated storage/CLI expectations for F26 two-file save and F34 companion wording; fixed pop_importevent history math.isnan on string field names (TypeError in the EEGLAB Python-backend suite).

Retriggering Claude. Still not merging.

- Guard math.isnan in pop_importevent history formatting
- Accept companion-file wording in missing-.fdt test
- Expect two-file resample output in CLI transform manifest
@suraj-ranganath
suraj-ranganath marked this pull request as draft November 7, 2026 18:05
@suraj-ranganath
suraj-ranganath marked this pull request as ready for review November 7, 2026 18:05
@claude

claude Bot commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @suraj-ranganath's task in 1m 3s —— View job


Code review (re-review at 90f004a)

  • Overall assessment: Needs changes, but only one small item. The BrainVision .eeg routing fix and the CI fixes are correct. The new .ahdr support routes the same file to two different readers, and those readers disagree on the channel count.
  • Highest-risk area: .ahdr routing in pop_fileio (L64-L69, L91).
  • Merge recommendation: Needs changes.

Previous review items

  • ✅ BrainVision .eeg routing: pop_fileio now switches to a sibling .vhdr (or .ahdr) before it dispatches. It falls back to the Neuroscan reader only when no header exists, which matches FieldTrip ft_filetype. History keeps the filename the caller passed (source_path). Tests cover .eeg/.EEG with channel/sample selection and blockrange. pop_fileio.md, storage.rst and the changelog are updated.
  • ✅ CI fixes: _history_number now checks isinstance(value, Real) before math.isnan, so string or array field names no longer raise TypeError. A test covers NaN timeunit/align and array fields. The test_cli_transforms and test_storage expectations now match F26 (two-file save) and F34 (the new "companion" wording).

Blocking

None.

Important

  • One .ahdr file loads with two different channel layouts (pop_fileio.py L91 vs _reader_for_suffix L127).
    • Without blockrange, .ahdr goes to pop_loadbv, which reads NumberOfChannels channels.
    • With blockrange, it goes to MNE, which expects one extra unlabelled channel. test_pop_fileio_brainvision_data_path_retains_blockrange has to rewrite the .eeg file with an extra row before MNE will read it.
    • The data is multiplexed, so at most one of these readers interleaves a real .ahdr recording correctly. The other produces scrambled data without raising an error.
    • Suggested fix: send every .ahdr import through one reader. For example, convert blockrange to srange and always use pop_loadbv, after confirming which channel layout is correct. Otherwise, leave .ahdr out of the sibling detection for now. See the inline comment. Fix this →

Nits

  • The comment at tests/test_pop_loadbv.py:471 explains a workaround. AGENTS.md says: "Never use comments to justify workarounds." Fixing the Important item above removes it.

Test gaps

None beyond the .ahdr item. Once there is one reader, both .ahdr tests should use the same on-disk file.

EEGLAB parity notes

  • These items from the earlier reviews are still open. They are already on your checklist:
    • The side-by-side check of pop_importdata auto-transposing 2-D input.
    • The side-by-side check of the F26 default two-file save.
    • Running the full EEGLAB reference suite with --eeglab-backend=matlab at the pinned commits, with the result recorded in the PR body. The posted run (134 passed, 2 skipped) covered only the Stream 9 test files.

Checked: the diff since 4d2b4ec (pop_fileio header detection and history path, pop_importevent history NaN handling, docs and help updates, test expectation changes).

eeg = _read_neuroscan_epochs(path, **options)
elif suffix == ".raw":
eeg = pop_readegi(path, **options)
elif suffix in {".vhdr", ".ahdr"} and blockrange is None:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Important: one .ahdr recording loads with two different channel layouts, depending on blockrange

Without blockrange, .ahdr goes to pop_loadbv, which reads NumberOfChannels channels. With blockrange, it goes to mne.io.read_raw_brainvision, which expects one extra unlabelled channel in the .eeg data. The new tests show this. test_pop_fileio_detects_brainvision_data_from_sibling_header writes an .ahdr file with 2 channels. test_pop_fileio_brainvision_data_path_retains_blockrange has to rewrite the data with 3 channels before MNE will read it (test_pop_loadbv.py#L469-L473). Because the data is multiplexed, at most one of these readers interleaves a real .ahdr file correctly. The other reader produces scrambled data without raising an error.

That test comment also explains a workaround. AGENTS.md says: "Never use comments to justify workarounds."

Suggested fix: send every .ahdr import through one reader. One option is to convert blockrange (in seconds) to srange and always call pop_loadbv. If MNE handles the extra channel correctly, make pop_loadbv handle it too. Otherwise, keep .ahdr out of the sibling-header detection until pop_loadbv and MNE agree. Then use the same on-disk .ahdr file in both tests and remove the comment.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed. All .vhdr/.ahdr imports go through pop_loadbv; blockrange is converted to sample indices. The MNE dual path and the fixture workaround comment are gone.

Route all .vhdr/.ahdr imports through pop_loadbv; convert blockrange seconds to sample indices. Remove the MNE dual-path and fixture workaround.

Copy link
Copy Markdown
Member Author

Claude follow-up (.ahdr dual reader)

Fixed at the tip of stream9-importers: every .vhdr/.ahdr import uses pop_loadbv only; blockrange converts to sample indices. Retriggering Claude. Not merging.

@suraj-ranganath
suraj-ranganath marked this pull request as draft November 7, 2026 18:16
@suraj-ranganath
suraj-ranganath marked this pull request as ready for review November 7, 2026 18:16
@claude

claude Bot commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @suraj-ranganath's task in 48s —— View job


Code review (re-review at e3cc265)

  • Overall assessment: Looks good. The .ahdr problem from the last review is fixed and the new code is correct. I found no new issues.
  • Highest-risk area: converting BrainVision blockrange seconds to samples in pop_fileio (L91-L114).
  • Merge recommendation: The code is ready to merge. The merge checklist still needs the full EEGLAB reference-suite run (see below).

Previous review items

  • ✅ .ahdr dual reader: every .vhdr/.ahdr import, with or without blockrange, now goes through pop_loadbv. The MNE BrainVision branch is gone from _reader_for_suffix. Both test families write the same on-disk layout, and the workaround comment is removed.

Blocking

None.

Important

None.

Nits

None.

Test gaps

None. The new tests cover:

  • both header suffixes, and both header and .eeg paths;
  • two sampling rates;
  • start, end, clipped and sub-sample blockrange boundaries;
  • empty ranges, and samples falling outside the window;
  • event latency relative to the window, float32 output, and the history string.

The MNE importorskip is gone, so these tests run on a plain pip install eegprep.

EEGLAB parity notes

  • Rounding matches MNE. For the formats that still use MNE (EDF/BDF/GDF/CNT), first = round(start*srate) with an exclusive last = round(stop*srate) gives the same boundaries as MNE's raw.crop(tmin, tmax, include_tmax=False). Both use round-half-even, so the two paths agree.
  • .ahdr layout not checked against a real file. pop_loadbv reads NumberOfChannels channels, while MNE's reader expected one extra channel. Nothing in the PR checks this against a real .ahdr recording; every fixture is synthetic. If you have a real file, add it to the side-by-side retest before merge.
  • Reference suite still missing from the PR body. This PR changes core readers (pop_loadset, pop_chanevent, pop_importdata, pop_saveset). AGENTS.md requires the full EEGLAB reference-suite run (--eeglab-backend=matlab, at the pinned EEGLAB and eeglab_tests commits) recorded in the PR body before merge. The posted 134 passed, 2 skipped run covered only the Stream 9 test files.

Checked: the full diff since 90f004a (pop_fileio BrainVision branch, _reader_for_suffix, pop_fileio.md, changelog, tests/test_pop_loadbv.py), and how pop_loadbv handles .ahdr headers, metadata=True and srange. I could not run the tests here because running them in this job needs approval, so this review is from reading the code.

Copy link
Copy Markdown
Member Author

Tip verification (head e3cc265f, tree a81c876f)

Local Codex tip 37f0429f matches remote tree a81c876f — no further push needed.

MATLAB parity (jamming, flock ~/matlab.lock, batch engine)

At tip e3cc265f:

189 passed, 2 skipped in 39.03s — EXIT 0.

Suite: test_stream9_{dataset_files,import_options,readers}.py, test_pop_loadset{,_h5}.py, test_pop_importevent_current.py, test_pop_importepoch_current.py, test_pop_loadbv.py, test_cnt_eeglab_tests.py, test_egi_raw_eeglab_tests.py.

Skips: neuroscanio absent on pinned EEGLAB (CNT upstream comparisons — labelled non-pinned).

CI

All required checks green on e3cc265f (ubuntu 3.12/3.13, macos, windows, EEGLAB Python backend, base extras, ruff/ty, pre-commit, docs, Claude review).

Claude

Re-review at e3cc265: Looks good / ready to merge. All Important items and nits from earlier rounds fixed and acknowledged. No new issues. Claude's remaining checklist note (full EEGLAB reference suite beyond the Stream 9 files) is recorded; S9-scoped MATLAB suite above is what this PR covers.

Not merging — needs Suraj's explicit squash-merge approval.

loadeeg/pop_loadeeg default accepttype='all' and expose accept; FieldTrip remains the differing reader.
@suraj-ranganath
suraj-ranganath merged commit 64e8d2f into develop Nov 7, 2026
10 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant