Skip to content

Add EEGLAB-style cart2topo, pop_reref, and pop_interp parity workflows - #52

Merged
arnodelorme merged 12 commits into
developfrom
ga/cart2topo-pop-reref
May 9, 2026
Merged

arnodelorme merged 12 commits into
developfrom
ga/cart2topo-pop-reref

Conversation

@suraj-ranganath

Copy link
Copy Markdown
Member

Summary

This PR adds EEGLAB-style support for cart2topo, pop_reref, and pop_interp, with GUI and visual parity infrastructure for the affected workflows.

What changed

  • Added cart2topo and exported it through the package API and Sphinx docs.
  • Added low-level reref support and expanded pop_reref to cover average/common reference paths, keepref, exclude, refloc, interpchan, Huber reference, multi-dataset GUI behavior, refica handling, and EEGLAB-style command history formatting.
  • Added pop_interp, pop_chansel, listdlg2, and pophelp support to mirror EEGLAB GUI helper flows.
  • Expanded the Qt dialog renderer and visual capture tooling for pophelp, channel selection, pop_reref, and pop_interp parity captures.
  • Added and updated tests for numerical behavior, GUI behavior, MATLAB parity, visual parity tooling, and docs/API exports.
  • Tightened ICLabel parity test constants so PSD comparisons allow a small single-precision absolute floor while preserving the existing relative tolerance.

Why

EEGPrep aims to preserve EEGLAB concepts, file organization, command history, and user experience while using Python APIs internally. These changes fill the requested cart2topo and pop_reref functionality and add supporting interpolation/channel-selection GUI flows needed for closer EEGLAB parity.

Validation

  • ./pre-commit.py --fix tests/test_ICL_feature_extractor_parity.py
  • uv run pytest tests/test_ICL_feature_extractor_parity.py -q -> 2 passed
  • uv run pytest tests/test_visual_parity.py tests/test_pop_interp.py tests/test_gui_pop_reref.py tests/test_pop_reref.py tests/test_guifunc_pophelp_chansel.py -q -> 73 passed
  • uv run pytest -> 1038 passed, 32 skipped, 44 warnings

@claude

claude Bot commented May 8, 2026 •

Copy link
Copy Markdown
Contributor

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


🤖 ### Code review

  • Overall assessment: needs changes
  • Highest-risk area: new planar/v4/spacetime interpolation in eeg_interp — degrees-vs-radians bug; pop_* history strings that aren't replayable in MATLAB EEGLAB
  • Merge recommendation: needs changes

Blocking

  • eeg_interp._planar_points / _theta_radius mishandle theta units — _theta_radius returns chanloc['theta'] directly, but EEGLAB chanlocs store theta in degrees (see topoplot.py:150 doing Th = np.deg2rad(Th), and the new cart2topo returning degrees). _planar_points then does radius * np.sin(theta) / np.cos(theta). The X/Y fallback branch (np.arctan2) is in radians, so the two branches return values in different units and the new 'invdist'/'v4'/'spacetime' methods compute electrode positions on the wrong arc. Inline suggestion posted on src/eegprep/functions/popfunc/eeg_interp.py:270-287.

Important

  • pop_interp GUI history is not MATLAB-replayable — pop_interp.py:68 interpolates the display string from pop_chansel (e.g. "Fp1 Cz") into EEG = pop_interp(EEG, {chanstr}, '{method}');. EEGLAB's pop_interp.m accepts numeric 1-based indices, cellstr, or chanlocs — not a space-separated label string. Emit { 'Fp1' 'Cz' } cellstr instead and add a history-format test for each GUI source branch.
  • pop_reref GUI history is not MATLAB-replayable either — tests/test_pop_reref.py:676-690 pins the emitted string to EEG = pop_reref( EEG, [0], 'keepref', 'on');. Channel index 0 is invalid in MATLAB. Same applies to the exclude branch. The 0-based Python API is documented, but the history artefact is the cross-language replay path; emit it 1-based.
  • AGENTS.md violations: bare local imports — qt.py:359, 391, 492 (pop_chansel, pophelp), qt.py:372, 389 (PySide6), listdlg2.py:62 (PySide6), pop_interp.py:205 (inputgui). None of these are circular-dependency breaks (visual_capture.py:14-17 already imports popfunc at module top) or wrapped optional-dependency guards. Move project imports to the top; fold the bare PySide6 imports into the same try/except pattern already used in qt._QDialog.
  • Duplicated helpers across modules — identical _chanlocs_as_list in pop_reref.py:381 and pop_interp.py:320; identical _is_number_like in pop_reref.py:566 and reref.py:157; near-identical refloc normalisation in _normalise_refloc_list (pop_reref.py:436) vs _normalise_reflocs (reref.py:136). Hoist into a shared module so a future schema change doesn't have to be applied in three places.
  • pop_reref._resolve_channels carries dead one_based_numbers kwarg — never set to True by any caller, no test, just a silent off-by-one switch waiting to be misused. Remove until needed.
  • pop_reref accepts options it does not implement — addrefchannel and enforcetype are listed in _VALID_OPTIONS but no code path consumes them; refica="backwardcomp" is validated but _update_ica (lines 600-603) does not branch on it (silently follows the "on" path). Either implement or reject.

Nits

  • qt.py:498 reads back widget._eegprep_value via hasattr — AGENTS.md explicitly calls out hasattr duck-typing. Use a small typed wrapper instead.
  • qt.py:63-66 dispatches layout margins on spec.function_name == "pop_interp". Push the value onto DialogSpec (e.g. content_margins) and remove the special case.
  • tools and visual_capture.capture_dataset_index_dialog (lines 244-254) have several widget locals (edit, help_button, cancel_button, ok_button) that are never referenced after creation — drop the names.
  • tests/test_ICL_feature_extractor_parity.py:25 raises ICLABEL_PSD_PARITY_ATOL from 1e-8 to 5e-8 (5×). The PR body explains this is to allow a single-precision floor, which is plausible (np.finfo(np.float32).eps ≈ 1.19e-7), but per AGENTS.md ("Never relax tolerances or hack around failures without proving the numerical expectation is wrong") please leave a one-line comment next to the constant citing the float32 cast site so the rationale survives.

Test gaps

  • No regression test for the _planar_points theta-units bug above. Add a case that interpolates with method='invdist' (or 'v4'/'spacetime') on chanlocs whose theta is set in degrees, and assert it matches the X/Y-fallback geometry.
  • No assertion on the EEGLAB-style history string produced by pop_interp (any GUI branch). Add one.
  • pop_reref GUI tests pin the non-portable [0]-style history; once that is fixed to 1-based, those tests need updating.

EEGLAB parity notes

  • The 0-based numeric API in pop_reref (and the exclude argument) is a deliberate, documented divergence from MATLAB EEGLAB. That is fine for the Python API, but the parity ask is the command history field — that artefact must be MATLAB-replayable for eegh/cross-tool workflows. Concretely: convert numeric channel indices in _format_ref_history_value, the exclude branch, and the pop_interp history to 1-based at emit time.
  • Areas checked and looking good: cart2topo matches MATLAB sign/units conventions; reref average/keepref/exclude math; ICA expansion via padded reref; pop_chansel quoting/escaping behaviour.

· Branch: ga/cart2topo-pop-reref

Comment thread src/eegprep/functions/guifunc/qt.py Resolved
Comment thread src/eegprep/functions/guifunc/qt.py Resolved
Comment thread tests/test_pop_reref.py Resolved
@suraj-ranganath

Copy link
Copy Markdown
Member Author

@claude review this PR

@claude

claude Bot commented May 8, 2026 •

Copy link
Copy Markdown
Contributor

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


Code review

  • Overall assessment: ready to merge after a couple of small follow-ups
  • Highest-risk areas checked: eeg_interp planar/v4/spacetime theta-units; pop_reref/pop_interp history-string MATLAB replayability; AGENTS.md import rules
  • Merge recommendation: approve, modulo nits below

Verifying the prior review thread against the current tip (4a16b42):

Previously blocking — all fixed

  • _theta_radius degrees-vs-radians: fixed at eeg_interp.py:281 — now np.deg2rad(float(theta)). Regression test tests/test_eeg_interp.py:23 (test_planar_theta_radius_degrees_match_xy_fallback) compares the theta path to the X/Y-fallback path with rtol=1e-12. Solid.

Previously important — all fixed

  • pop_interp GUI history is MATLAB-replayable: qt.py:417 emits [1 2 …] (1-based) for datchan, EEG.chaninfo.removedchans([…]) for nondatchan, and ALLEEG(N).chanlocs([…]) / ALLEEG(N).chanlocs for the alleeg paths. Tests at tests/test_pop_interp.py:107 / :117 pin the history to EEG = pop_interp(EEG, [1], 'spherical');.
  • pop_reref history is 1-based: pop_reref.py:740 shifts numeric indices by +1. Test pins it: pop_reref(EEG, ref=[0], exclude=[3]) → EEG = pop_reref( EEG, [1], 'exclude', [4]); (tests/test_pop_reref.py:670). The GUI-numeric-text test at line 757 was correctly updated.
  • AGENTS.md import violations: top-level imports for pophelp, pop_chansel, inputgui (qt.py, pop_interp.py); PySide6 wrapped in optional-dependency guards in qt.py, listdlg2.py, pophelp.py with a shared _require_qt-style helper. Done.
  • Duplicated helpers: extracted to src/eegprep/functions/popfunc/_chanutils.py (chanlocs_as_list, is_number_like, normalise_reflocs); both pop_reref.py, pop_interp.py, and reref.py import from it. Done.
  • Dead one_based_numbers kwarg: removed from _resolve_channels. Done.
  • Silently-no-op options: _VALID_OPTIONS no longer lists addrefchannel/enforcetype; tests at test_pop_reref.py:701-707 assert they raise ValueError. refica="backwardcomp" is now a distinct branch in _update_ica (pop_reref.py:576-579) — it skips the icaact clear that the "on" path performs.

Previously nits — addressed

  • hasattr(widget, "_eegprep_value") replaced with Qt's typed property store (target.setProperty(_VALUE_PROPERTY, …) / widget.property(_VALUE_PROPERTY) at qt.py:467 / :500).
  • pop_interp-specific layout magic moved out of qt.py into DialogSpec.content_margins (pop_interp.py:168 sets content_margins=(23, 14, 25, 13)).
  • Float32 cast rationale comment added next to ICLABEL_PSD_PARITY_ATOL (tests/test_ICL_feature_extractor_parity.py:27-28).

Remaining nits (non-blocking)

  • reref._huber_average_reference has a dead initializer: reref.py:156 sets weights = np.ones((data.shape[0], 1), …) outside the loop, then :159 immediately overwrites it on the first iteration with np.ones_like(residual). Drop the line-156 init — every read of weights happens after the in-loop assignment.

  • pop_reref history echoes case-mismatched user input: pop_reref.py:311 lowercases keepref for processing, but _history_options reads from the original (un-lowercased) options dict. So pop_reref(EEG, [], keepref='ON') works correctly but emits 'keepref','ON' rather than EEGLAB's 'keepref','on'. Either lowercase at history-emit time in _format_history_value for known-string options, or normalise options[key] once after parsing. Tiny.

  • pophelp references PACKAGE_ROOT / 'eeglab' (pophelp.py:14-17) — i.e. src/eegprep/eeglab/. AGENTS.md (which this PR also updated) now says runtime must work without that directory. The code already handles missing dirs gracefully (if not eeglab_root.exists(): continue) and falls back to Python docstrings, so behaviour is correct, but readers may flag the path on a future audit. A short comment ("development-only path; package falls back to Python docs") would be enough.

  • Optional-dep guard duplicated across qt.py, listdlg2.py, pophelp.py — three near-identical _require_qt-style helpers and try/except ImportError blocks. Pulling them into a single guifunc/_qt.py would shrink the surface to one place. Pure cleanup, not in scope here.

EEGLAB parity sanity-check

  • cart2topo: signs/units (-sph_theta, 0.5 - sph_phi/180) and degree wrapping match EEGLAB's cart2topo.m method-2 output.
  • reref math (average, keepref, exclude, huber) and ICA expansion via pop_interp → padded reref look right.
  • pop_chansel quoting/escaping (_selected_string + _parse_text) matches EEGLAB's whitespace-vs-cellstr branching.

Nice cleanup pass — all of the prior blockers are resolved with regression coverage. The three nits above are non-blocking.


· Branch: ga/cart2topo-pop-reref

@suraj-ranganath

Copy link
Copy Markdown
Member Author

Visual parity screenshots

Captured side-by-side UI parity screenshots for the user-facing paths covered by this PR.

Left: EEGLAB reference. Right: EEGPrep current branch.

These images are uploaded as PR review artifacts and are not committed to the PR branch.

All covered UI components

All UI components side by side

Individual side-by-side captures

reref_dialog

reref_dialog side by side

reref_dialog_channel_ref

reref_dialog_channel_ref side by side

reref_dialog_huber_ref

reref_dialog_huber_ref side by side

reref_dialog_interp_removed

reref_dialog_interp_removed side by side

pop_interp_dialog

pop_interp_dialog side by side

pop_interp_removed_dialog

pop_interp_removed_dialog side by side

pop_interp_epoched_dialog

pop_interp_epoched_dialog side by side

pop_chansel_dialog

pop_chansel_dialog side by side

pop_interp_dataset_index_dialog

pop_interp_dataset_index_dialog side by side

pop_reref_help_dialog

pop_reref_help_dialog side by side

pop_interp_help_dialog

pop_interp_help_dialog side by side

Upload ref: refs/uploads/issues/52 at 8d5dc4006f49.

@suraj-ranganath

Copy link
Copy Markdown
Member Author

@claude review this

@claude

claude Bot commented May 9, 2026 •

Copy link
Copy Markdown
Contributor

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


Code review

  • Overall assessment: ready to merge — all prior blocking/important issues resolved
  • Highest-risk areas re-checked: eeg_interp theta-units, 1-based history emission, AGENTS.md import compliance, helper de-duplication, the new _accept_if_valid GUI validation layer added in 9957e85, the ICA channel-index normalization fix in e733099
  • Merge recommendation: approve, with two small suggestions below (non-blocking)

Verifying the prior review thread against the current tip (e733099):

Previously blocking — confirmed fixed

  • _theta_radius correctly returns np.deg2rad(float(theta)) (eeg_interp.py:281). Regression test test_planar_theta_radius_degrees_match_xy_fallback (tests/test_eeg_interp.py:23) compares the theta-fed and X/Y-fallback paths at rtol=1e-12.

Previously important — confirmed fixed

  • History 1-based shift in pop_reref: numeric channel indices in _format_channel_history_value are uniformly +1-shifted (pop_reref.py:758-784); 'exclude'/'interpchan' go through the same shift (pop_reref.py:751-754).
  • pop_interp history: GUI emits [1 2 …] for datchan, EEG.chaninfo.removedchans([…]) for nondatchan, ALLEEG(N).chanlocs([…]) for the multi-dataset paths (qt.py:537-591). Test pin: EEG = pop_interp(EEG, [1], 'spherical');.
  • AGENTS.md imports: project imports moved to module top in qt.py, pop_interp.py; PySide6 imports wrapped in optional-dependency guards (_require_qt) in qt.py, listdlg2.py, pophelp.py.
  • Helper de-duplication: chanlocs_as_list, is_number_like, normalise_reflocs consolidated in src/eegprep/functions/popfunc/_chanutils.py; imported by pop_reref.py:15-19, pop_interp.py:14, reref.py:10.
  • Dead one_based_numbers kwarg: removed.
  • Silently-no-op options: addrefchannel/enforcetype no longer in _VALID_OPTIONS; tests assert they raise. refica="backwardcomp" is a distinct branch in _update_ica (pop_reref.py:585-591) — it skips the icaact clear that the "on" path performs.
  • hasattr(_eegprep_value): replaced with Qt's typed property store (setProperty/property at qt.py:597 / _read_widget at line 630).
  • pop_interp layout magic: moved out of qt.py into DialogSpec.content_margins (pop_interp.py:171).
  • Float32 cast rationale: comment added next to ICLABEL_PSD_PARITY_ATOL.
  • reref._huber_average_reference dead init: removed; weights are initialized inside the loop now.
  • pop_reref history keepref casing: _normalise_history_option_value lowercases keepref/refica at history-emit time (pop_reref.py:342-348).
  • pophelp eeglab/ path: removed in commit 7d4faea. _find_source now requires a packaged .md and raises a clear FileNotFoundError if missing (pophelp.py:78-82). Matches AGENTS.md guidance that runtime must work without src/eegprep/eeglab/.

New work since the prior review

Two notable additions beyond the prior review's scope:

  • 9957e85 — _accept_if_valid GUI validation layer (qt.py:344-466): catches bad input (non-numeric Huber threshold, empty/invalid channel text, out-of-range time ranges) and shows a QMessageBox.warning instead of accepting the dialog. validate_numeric_range callback is wired through pop_interp_dialog_spec. Tests: test_pop_interp.py:193, test_gui_pop_reref.py:130 cover both happy and error paths.

  • e733099 — ICA channel-index normalization (pop_reref.py:600): fixes a real bug where EEG['icachansind'] stored as an np.ndarray caused if any(index in resolved["exclude_indices"] for index in icachansind) to compare numpy 0-d arrays against Python ints, which can succeed or fail unpredictably depending on numpy version. The new _normalise_icachansind (pop_reref.py:659-662) flattens to a Python list of ints and is also called from _normalise_checkset_types. Good fix.

Remaining nits (non-blocking)

  • _widget_checked / _widget_text use hasattr for type dispatch (qt.py:459, 463). AGENTS.md flags hasattr as an anti-pattern, though the canonical case it warns about is "old vs new attribute name" not "QWidget protocol". The same pattern in _read_widget (qt.py:633-637) already exists from before this PR. If you want strictness, switch to isinstance(widget, qt_widgets.QCheckBox) etc.; otherwise leave for a future cleanup.

  • GUI numeric input is 0-based (qt.py:443-447 — _validate_channel_text accepts 0 ≤ index < len(labels)). This is consistent with the documented Python API but diverges from EEGLAB GUI muscle memory (where typing 1 selects the first channel). The history string artefact is correctly 1-based, so eegh round-trips work; only the live GUI input is off by one for users coming from MATLAB. Not in this PR's scope to fix, but worth noting in the user-facing docs/changelog if not already there.

EEGLAB parity sanity-check (re-run on tip)

  • cart2topo: signs/units (-sph_theta, 0.5 - sph_phi/180) and _wrap_degrees match cart2topo.m method-2.
  • reref math (average/keepref/exclude/huber) and ICA expansion via padded reref look correct.
  • pop_chansel quoting/escaping (_selected_string + _parse_text) matches EEGLAB's whitespace-vs-cellstr branching.
  • New pop_interp dialog validate_numeric_range mirrors pop_interp.m's if min(timerange) < EEG.xmin || max(timerange) > EEG.xmax warning, with the math.floor(max(values)) > upper floor matching the MATLAB floor() call.

Solid follow-up pass — every blocker from the prior review has a fix plus regression coverage, and the two new commits address real gaps rather than cosmetic ones. No new blockers.


· Branch: ga/cart2topo-pop-reref

@suraj-ranganath
suraj-ranganath marked this pull request as ready for review May 9, 2026 10:41
@claude

claude Bot commented May 9, 2026 •

Copy link
Copy Markdown
Contributor

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


Code review

  • Overall assessment: ready to merge — no new blockers, all prior issues remain resolved
  • Highest-risk areas re-checked: eeg_interp theta-units, 1-based history emission, AGENTS.md import compliance, _accept_if_valid GUI validation, _normalise_icachansind ICA-index fix, pophelp packaged-only resolution
  • Merge recommendation: approve

The only commit added since the last review is cef42e1 ("Document pop_reref GUI channel indexing"), which is documentation-only — it adds a user-facing note in docs/source/user_guide/quickstart.rst and src/eegprep/resources/help/pop_reref.md explaining that GUI numeric inputs are 0-based while EEGLAB-style history commands are 1-based. That directly addresses the one outstanding non-blocking observation from the prior review (the 0-based GUI vs MATLAB muscle-memory divergence). Good close.

Re-verified on tip cef42e1

Prior concern Status Where
_theta_radius returns radians via np.deg2rad ✅ fixed + regression test eeg_interp.py:281, tests/test_eeg_interp.py:23
pop_reref history channel indices are 1-based (incl. exclude/interpchan) ✅ fixed pop_reref.py:751-781
pop_interp history emits MATLAB-replayable [1 2 …] / EEG.chaninfo.removedchans([…]) / ALLEEG(N).chanlocs([…]) ✅ fixed qt.py:537-591, pop_interp.py:250-254
AGENTS.md import rules: project imports at top, PySide6 wrapped via _require_qt ✅ fixed qt.py:10-32, listdlg2.py:8-21, pophelp.py:17-23, pop_interp.py:12
Helpers de-duplicated into _chanutils.py (chanlocs_as_list, is_number_like, normalise_reflocs) ✅ fixed _chanutils.py
Dead one_based_numbers kwarg removed ✅ fixed —
Silent no-op options (addrefchannel, enforcetype) rejected; refica="backwardcomp" is a distinct branch ✅ fixed pop_reref.py:585-591
_eegprep_value replaced by Qt typed property ✅ fixed qt.py:597
pop_interp layout magic moved to DialogSpec.content_margins ✅ fixed pop_interp.py:180
ICLABEL float32 rationale comment ✅ fixed tests/test_ICL_feature_extractor_parity.py:27-28
Dead weights = np.ones(...) init in _huber_average_reference ✅ fixed —
keepref/refica history casing normalised ✅ fixed pop_reref._normalise_history_option_value
pophelp no longer falls back to src/eegprep/eeglab/ ✅ fixed pophelp.py:72-82 raises FileNotFoundError for missing packaged resources
_accept_if_valid GUI input validation (Huber threshold, channel labels, time range) ✅ added with happy + error-path tests qt.py:345-413, tests/test_gui_pop_reref.py:122, tests/test_pop_interp.py:189
_normalise_icachansind flattens to plain list[int] (numpy 0-d comparison fix) ✅ fixed pop_reref.py:600, pop_reref.py:659-662
0-based GUI numeric input documented for EEGLAB-muscle-memory users ✅ added (cef42e1) quickstart.rst:340-345, pop_reref.md:20-22

Remaining nits (non-blocking, carry over from prior review)

These were already flagged as non-blocking last round; not requesting changes here, just keeping the trail visible.

  • _widget_checked / _widget_text still use hasattr for protocol checks (qt.py:459, 463). AGENTS.md flags hasattr as an anti-pattern, though the canonical case it warns about is "old-vs-new attribute name"; this is closer to "is this a QWidget protocol member." isinstance(widget, qt_widgets.QCheckBox) would be stricter, but leaving as-is for a future cleanup is fine.
  • Three near-identical _require_qt/optional-dep blocks across qt.py:26-32, listdlg2.py:15-21, pophelp.py:17-23. Pure cleanup — single shared helper in guifunc/_qt.py would shrink the surface, but each duplicate is small and self-explanatory.

EEGLAB parity sanity-check

  • cart2topo: signs (-sph_theta), units (0.5 - sph_phi/180), and _wrap_degrees match cart2topo.m method-2 output.
  • reref (average/keepref/exclude/huber) and ICA expansion via padded reref — math looks right; the icachansind normalization fix removes a real numpy-version-dependent comparison bug.
  • pop_chansel quoting/escaping matches EEGLAB's whitespace-vs-cellstr branching.
  • pop_interp dialog validate_numeric_range mirrors pop_interp.m's if min(timerange) < EEG.xmin || max(timerange) > EEG.xmax warning, with math.floor(max(...)) matching MATLAB floor() semantics.

Final pass — every prior blocker is fixed with regression coverage, the new commit closes the documentation gap, and the two remaining nits are explicitly non-blocking. No new blockers.

--- · Branch: ga/cart2topo-pop-reref

@arnodelorme

Copy link
Copy Markdown
Collaborator

@claude can you do a PR review focusing on potential backward compatibility issues

@claude

claude Bot commented May 9, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @arnodelorme's task in 5m 43s —— View job


Backward-compatibility review

  • Inventory PR diff against origin/develop
  • Audit changes to existing public APIs (pop_reref, eeg_interp, __init__ exports)
  • Audit ICLabel parity tolerance changes
  • Audit AGENTS.md / docs / GUI infra for user-visible breaks
  • Audit data structures, EEG dict semantics, file formats
  • Post review

Scope: focused review of behaviors that existing eegprep callers may depend on, comparing tip cef42e1 against origin/develop. Setting aside parity / EEGLAB-correctness concerns covered in the prior reviews.

Bottom line: the public API is mostly additive, but pop_reref has three subtle behavioral regressions that could break users who upgrade in place. The most important is that EEG['ref'] is no longer always set to 'average' after pop_reref(EEG, []). Worth either fixing or calling out in release notes.


Behavioral changes in pop_reref(EEG, []) / pop_reref(EEG, None)

These are the same call patterns existing eegprep code uses (pop_reref_helper.py:20, ICL_feature_extractor.py:38, bids_preproc.py:951). Old develop semantics vs. tip semantics differ as follows:

1. EEG['ref'] is no longer unconditionally normalised to 'average' (regression)

pop_reref.py:559-566 — _update_legacy_ref:

def _update_legacy_ref(EEG, ref_indices):
    if "ref" not in EEG:
        return
    if not ref_indices:
        if str(EEG["ref"]).lower() == "common":
            EEG["ref"] = "average"
    elif str(EEG["ref"]).lower() == "average":
        EEG["ref"] = "common"

Compare with develop:

EEG['ref'] = 'average'                                  # unconditional
for iChan in range(len(EEG['chanlocs'])):
    EEG['chanlocs'][iChan]['ref'] = 'average'

Concrete cases that change:

  • Input EEG['ref'] == 'unknown' (common after pop_loadset on un-rereferenced data, and produced by some BIDS loaders): old code set it to 'average'; tip leaves it as 'unknown'.
  • Input has no 'ref' key at all (some test fixtures, hand-built EEG dicts): old code added the key with value 'average'; tip silently does nothing.
  • Input EEG['ref'] == 'M1' (any specific previous reference): old code clobbered it to 'average'; tip leaves it as 'M1'.

bids_preproc.py:1085 literally tags BIDS metadata 'CommonAverageReference': 'pop_reref', so downstream code that subsequently checks EEG['ref'] == 'average' (e.g. plot styling, sidecar JSON, audit reports) will silently regress for any input whose 'ref' wasn't already 'common'. The fix is one line — add a final EEG["ref"] = "average" for the empty-ref_indices branch (the per-channel chanlocs[i]['ref'] = 'average' is already correct via reref._update_references at reref.py:139-151). Fix this →

2. EEG['icaact'] is now cleared by default (behavior change)

Default refica='on' (pop_reref.py:307). The 'on' path at pop_reref.py:585-591 always assigns EEG["icaact"] = np.array([]).

Old develop code preserved EEG['icaact'] unchanged (only cleared it on the channel-mismatch error path).

This is more correct per EEGLAB semantics (re-referencing invalidates cached IC activations, and EEGLAB clears icaact), but it is a real behavior change for any caller that did pop_reref(EEG, []) and then read EEG['icaact'] directly without re-running eeg_checkset to recompute it. Worth a release-notes / changelog mention; not a code fix.

3. pop_reref(EEG) (single-arg) now blocks on a GUI dialog instead of raising TypeError

Old signature: def pop_reref(EEG, ref): — calling pop_reref(EEG) raised TypeError: missing 1 required positional argument: 'ref'.

New signature (pop_reref.py:36-43):

def pop_reref(EEG=_UNSET, ref=_UNSET, *args, gui=None, ...):
    ...
    has_processing_args = ref is not _UNSET
    if gui is None:
        gui = not has_processing_args

So pop_reref(EEG) → gui=True → opens a Qt dialog. Headless scripts / CI jobs that previously caught a TypeError will now hang waiting for user input (or crash with a Qt-not-available error in headless environments). The defensive fix is pop_reref(EEG, []) (matches existing eegprep code) — but that requires user awareness. Recommend that pop_reref(EEG) in a non-interactive context fall through to ref=[] rather than launching a GUI, or at minimum check os.isatty() / a EEGPREP_NONINTERACTIVE env var before launching. Not a blocker, but worth flagging in release notes.

4. Numeric-ref behavior change (was: ValueError; now: real common-reference)

Develop's pop_reref(EEG, 'Cz'), pop_reref(EEG, 32), pop_reref(EEG, ['Cz','FCz']) all raised ValueError("Feature not implemented: The ref parameter must be empty or None"). Tip implements all three. The deleted test test_error_non_empty_ref confirms the diff explicitly drops the error path.

This is "previously unimplemented, now implemented" — usually fine — but the 0-based index convention (docs/source/user_guide/quickstart.rst:340-345 / pop_reref.md:20-22) could trip up MATLAB users who copy-paste pop_reref(EEG, 32) from EEGLAB code expecting channel #32 and instead get channel #33 (0-based index 32). Tip emits 1-based history so eegh round-trips work, but the live Python call is silently off-by-one for that workflow. Documentation now covers this; nothing to fix in code.


Other behavioral surfaces — checked, no regression

  • eeg_interp signature unchanged (line 24). New methods ('invdist', 'v4', 'spacetime') are additive, and _normalise_method only relaxes case-sensitivity (e.g., 'SPHERICAL' now succeeds where it would have raised ValueError before — strictly more permissive, fine).
  • Top-level package additions (cart2topo, pop_chansel, pop_interp in __init__.py:21,26,44) are net-new exports; no name collisions with existing symbols.
  • DialogSpec.content_margins default = (42, 17, 42, 13) (spec.py:47) matches the previously hardcoded value in qt.py, so existing dialogs that don't override it render identically.
  • pyproject.toml package-data drops the glob resources/eeglab/**/* (line 126). I checked git ls-tree -r origin/develop -- src/eegprep/resources/eeglab — empty, so the glob never matched anything in installed wheels and dropping it is a no-op for users.
  • reref() low-level helper (sigprocfunc/reref.py) is a new module — not previously exported, no compat concern.
  • ICLABEL_PSD_PARITY_ATOL raised 1e-8 → 5e-8 is a test-only constant and doesn't affect users.

Recommendation

@arnodelorme
arnodelorme merged commit 361f2ff into develop May 9, 2026
9 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

Development

Successfully merging this pull request may close these issues.

2 participants