Skip to content

[Phase 3] Implement rejection and component workflows - #76

Merged
suraj-ranganath merged 3 commits into
feature/eeglab-completionfrom
phase/3-rejection-component-workflows
May 28, 2026
Merged

suraj-ranganath merged 3 commits into
feature/eeglab-completionfrom
phase/3-rejection-component-workflows

Conversation

@suraj-ranganath

Copy link
Copy Markdown
Member

Implement non-browser Phase 3 rejection and component workflows, including rejection mark superposition, automated/statistical rejection wrappers, channel/continuous rejection, component selection, and viewprops. Adds GUI/menu/console wiring, help resources, visual parity cases, sample-data tests, and deterministic EEG_REJSUPERPOSE MATLAB parity coverage.

Part of #63

@claude

claude Bot commented May 28, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @suraj-ranganath's task in 6m 41s —— View job


Claude Code PR Review

  • Fetch PR diff and analyze structure
  • Read core new modules (_rejection.py, pop_rej*, pop_autorej, pop_selectcomps, pop_viewprops)
  • Read GUI/menu wiring (menu_actions.py, visual_capture.py)
  • Cross-check EEGLAB parity for select dialogs
  • Review tests
  • Post inline comments + summary

Summary

Big, well-organized PR — pulls 12 rejection workflows + pop_viewprops together behind a clean _rejection.py toolkit, wires every entry-point through MenuActionDispatcher, ships dialog specs + Markdown help + visual-parity cases, and adds a deterministic MATLAB-engine parity test for eeg_rejsuperpose. The shared helpers (one_based_indices, expand_values, bool_marks, _time_window) consolidate what would otherwise be a lot of duplicated logic.

The findings below are about behavioral parity gaps, not structure.

Issues found (high → low)

1. pop_autorej doesn't actually drop high-amplitude epochs. pop_eegthresh is called with reject=0, so the threshold-flagged trials are only marked in EEG.reject.rejthresh and remain in the dataset that subsequently feeds the joint-probability loop. EEGLAB's pop_autorej.m passes reject=1 and removes them before iterating. The returned out["trials"] is wrong, and the rejected list reports indices that weren't dropped. The existing test happens to still pass because it only checks 2 in rejected and out["trials"] <= eeg["trials"]. See inline comment on pop_autorej.py:104.

2. pop_rejspec "Multitaper" choice is silently FFT. Dialog offers FFT|Multitaper and the history command's default is "multitaper", but spectrum_marks always runs np.fft.fft. Replay diverges from "live" behavior. Inline comment on pop_rejspec.py:84.

3. pop_rejchan programmatic threshold fallback is 400. GUI default is 5 (z-score). A direct call without an explicit threshold key will almost never flag anything. Inline comment on pop_rejchan.py:93.

4. pop_viewprops channel mode renders only labels. No spectopo / erpimage / topo panels — just axis.text of the channel label. The known_differences note only mentions scrolling activity being omitted. Either implement the per-channel property panel or expand the known-differences entry and gate the menu accordingly. Inline comment on pop_viewprops.py:88-97.

5. eeg_rejsuperpose row sizing is wrong when Rothertype=1 and nbchan != ncomp. Buffer is sized by the primary family; the cross-family OR silently truncates rows via _or_matrix's min(out.shape[0], values.shape[0]). Recommend only OR-ing the per-trial vector across families. Inline comment on eeg_rejsuperpose.py:33-35.

6. pop_rejmenu stylesheet dead rule (QPushButton#butspec). No control uses that object name; the spectra section uses butfreq. Inline nit on pop_rejmenu.py:240.

Smaller notes (not posted inline)

  • pop_rejchan exposes a "std" measure in _channel_measure but it isn't selectable from the dialog popup (only Probability / Kurtosis / Spectrum). Either add it to the dropdown or document why.
  • pop_rejcont direct-call freqlimit default is [35, min(128, srate/2)], but the GUI default is "20 40". Either align them or document the difference.
  • parse_numeric_sequence in _rejection.py: the inline list comprehension parse_numeric_sequence(item, dtype=dtype) if isinstance(item, str) else [dtype(item)] calls dtype(item) on raw ints/floats. For dtype=int, int(0.79) truncates to 0. This is fine for the current call sites (always int-yielding values) but it's a foot-gun if reused.
  • pop_eegthresh._apply_one re-reads EEG.trials from out.get("trials", data.shape[2]) — but out = copy_eeg(EEG) already mirrors EEG. Safe today; just noting.

Positive notes

  • The eeg_rejsuperpose MATLAB-engine parity test (test_eeg_rejsuperpose_matches_eeglab_for_deterministic_marks) is well-scoped and skip-safe — that's exactly the kind of test that keeps OR-superposition honest.
  • Lazy imports in MenuActionDispatcher are preserved as you added 13 new entry-points — good for GUI startup time.
  • Migrating pop_rejchan out of the placeholder inventory and asserting action_kind("pop_rejchan") == "implemented" is the right pattern (test_menu_placeholder_inventory.py:42).

What I did not verify

  • Numeric parity against EEGLAB for pop_eegthresh, pop_jointprob, pop_rejkurt, pop_rejtrend, pop_rejspec, pop_rejcont, pop_rejchan, pop_autorej (no MATLAB-engine parity tests added for these). Worth following up at least for the deterministic ones (pop_eegthresh, pop_rejtrend) where matching is straightforward.
  • Visual parity captures — only inspected the spec wiring, not generated screenshots.
    • Branch: phase/3-rejection-component-workflows

@suraj-ranganath

Copy link
Copy Markdown
Member Author

🤖 Phase 3 implementation/spec and GUI evidence

Problem: Phase 3 issue #63 still had component-selection and non-browser rejection menu placeholders after the ICLabel PR. EEGLAB exposes these through functions/popfunc and functions/adminfunc/pop_rejmenu.m; EEGPrep needed standalone Python implementations that preserve EEGLAB rejection fields/history while explicitly excluding EEGPlot/EEGBrowser scrolling paths.

Approach: Added shared rejection helpers plus eeg_rejsuperpose, pop_eegthresh, pop_jointprob, pop_rejkurt, pop_rejtrend, pop_rejspec, pop_rejchan, pop_rejcont, pop_autorej, pop_rejepoch, pop_rejmenu, pop_selectcomps, and pop_viewprops. Wired each into menus, console-valid history conversion, public lazy exports, help resources, and visual parity capture cases. pop_rejmenu keeps EEGLAB's sectioned rejection-manager shape but disables browser/scrolling buttons rather than half-implementing EEGPlot.

Key code: The shared helper layer in src/eegprep/functions/popfunc/_rejection.py centralizes 1-based UI indices, data-vs-ICA activation selection, reject-field updates, threshold/probability/kurtosis/trend/spectrum marks, and console history formatting so the wrappers use the same semantics. Menu dispatch updates the shared EEGPrepSession so GUI actions and eegprep-console remain synchronized.

Tests: tests/test_rejection_workflows.py covers sample data, synthetic epoched data, ICA-present and missing-ICA paths, cancel/no-op paths, replayable console commands, and deterministic MATLAB parity for eeg_rejsuperpose when MATLAB + EEGLAB source are available. tests/test_gui_rejection_dialogs.py covers dialog specs and menu dispatch behavior. Visual parity captures were regenerated for every new GUI dialog.

Verification run locally:

uv run --no-sync ruff check .
uv run --no-sync ruff format --check .
uv run --no-sync ty check
./pre-commit.py
EEGPREP_SKIP_MATLAB=1 uv run --no-sync pytest -m "not slow"
EEGPREP_EEGLAB_ROOT=/Users/suraj/Desktop/eeglab uv run --no-sync pytest tests/test_rejection_workflows.py::test_eeg_rejsuperpose_matches_eeglab_for_deterministic_marks -q
EEGPREP_EEGLAB_ROOT=/Users/suraj/Desktop/eeglab uv run --no-sync python tools/visual_parity/capture.py --case <each Phase 3 dialog> --target both --output-dir /tmp/eegprep_phase3_visual_parity --timeout 180

Non-slow pytest result: 1190 passed, 215 skipped, 11 deselected.

Visual parity side-by-side images are attached below; these are upload artifacts, not committed repo files.

Phase 3 visual parity

pop_autorej_dialog_side_by_side.png pop_eegthresh_dialog_side_by_side.png
pop_autorej_dialog_side_by_side.png pop_eegthresh_dialog_side_by_side.png
pop_jointprob_dialog_side_by_side.png pop_rejchan_dialog_side_by_side.png
pop_jointprob_dialog_side_by_side.png pop_rejchan_dialog_side_by_side.png
pop_rejcont_dialog_side_by_side.png pop_rejkurt_dialog_side_by_side.png
pop_rejcont_dialog_side_by_side.png pop_rejkurt_dialog_side_by_side.png
pop_rejmenu_dialog_side_by_side.png pop_rejspec_dialog_side_by_side.png
pop_rejmenu_dialog_side_by_side.png pop_rejspec_dialog_side_by_side.png
pop_rejtrend_dialog_side_by_side.png pop_selectcomps_dialog_side_by_side.png
pop_rejtrend_dialog_side_by_side.png pop_selectcomps_dialog_side_by_side.png
pop_viewprops_dialog_side_by_side.png
pop_viewprops_dialog_side_by_side.png

Comment on lines +104 to +108
out, _command = pop_eegthresh(
EEG, 1, electrodes, -threshold, threshold, EEG.get("xmin", 0), EEG.get("xmax", 0), 0, 0, return_com=True
)
marks = np.asarray((out.get("reject") or {}).get("rejthresh", []), dtype=bool)
rejected = set((np.flatnonzero(marks) + 1).tolist())

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.

pop_autorej accumulates threshold-rejected epochs into rejected but never removes them from out.

EEGLAB's pop_autorej.m calls pop_eegthresh(EEG, 1, ..., 0, 1) — the trailing 1 is the reject flag, so the high-amplitude epochs are dropped before the joint-probability loop runs. Here the call passes 0 for reject, so:

  • out["trials"] is unchanged after the threshold step.
  • remaining = list(range(1, work["trials"] + 1)) then starts from the full set, so when the jointprob loop reports current = [k] it maps to the k-th surviving epoch including the high-amplitude ones. Indices accumulated into rejected from later iterations therefore can collide with already-counted threshold indices.
  • The returned dataset still contains the worst-amplitude trials, defeating the whole purpose of the function.

Suggested fix: pass reject=1 to pop_eegthresh (and rebuild remaining/rejected from the post-rejection trial count), matching EEGLAB.

Suggested change
out, _command = pop_eegthresh(
EEG, 1, electrodes, -threshold, threshold, EEG.get("xmin", 0), EEG.get("xmax", 0), 0, 0, return_com=True
)
marks = np.asarray((out.get("reject") or {}).get("rejthresh", []), dtype=bool)
rejected = set((np.flatnonzero(marks) + 1).tolist())
out, _command = pop_eegthresh(
EEG, 1, electrodes, -threshold, threshold, EEG.get("xmin", 0), EEG.get("xmax", 0), 0, 1, return_com=True
)
marks = np.asarray((EEG.get("reject") or {}).get("rejthresh", np.zeros(int(EEG.get("trials", 1) or 1)))).astype(bool)
# pop_eegthresh stores marks on the pre-rejection dataset before dropping; recover the original 1-based indices.
rejected = set((np.flatnonzero(_pre_marks_from(EEG, electrodes, threshold)) + 1).tolist())

(or simpler: capture the indices returned by pop_eegthresh directly before dropping, then translate current against a remaining list rebuilt after the drop). Fix this →

Comment on lines +82 to +84
ControlSpec("text", "Spectrum computation method"),
ControlSpec("spacer"),
ControlSpec("popupmenu", "FFT|Multitaper", tag="method", value=2),

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.

The dialog offers FFT|Multitaper (with Multitaper as the default value=2) but the implementation only ever computes an FFT.

spectrum_marks in _rejection.py uses np.fft.fft regardless of options["method"]. The chosen method is just written into the history command (_history_command's default is even "multitaper"), so:

  • Recorded history can read 'method', 'multitaper' while the actual marks come from an FFT — replay produces a different result than the live computation says it did.
  • A user picking "Multitaper" gets silent FFT-based marks.

Either implement the multitaper branch (e.g. via scipy.signal.windows.dpss with averaged tapers) or, if multitaper is out of scope, remove the popup option and default to FFT in _history_command. The dialog should not offer a control that has no effect. Fix this →

raise ValueError("EEG data must be 2-D or 3-D")
elec = one_based_indices(options.get("elec"), limit=int(out.get("nbchan", flat.shape[0])), default_all=True)
selected = [item - 1 for item in elec]
threshold = parse_numeric_sequence(options.get("threshold", 400), dtype=float)

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.

Programmatic threshold default of 400 doesn't match the GUI default (5) or EEGLAB's z-score default.

The dialog spec sets threshold to "5" and the docstring promises a z-score interpretation; EEGLAB's pop_rejchan.m also defaults to a small z-score threshold (5 for normalized kurtosis). When a caller invokes pop_rejchan(EEG, "measure", "kurt") without a threshold key, this falls back to 400 — which is essentially an unreachable threshold for normalized scores and almost certainly never returns any flagged channels.

Either drop the default and require an explicit threshold (raise on missing) or align it with the GUI default of 5. Fix this →

Comment on lines +88 to +97
fig_obj, axes = plt.subplots(1, min(len(indices), PLOTS_PER_FIGURE), squeeze=False)
labels = _channel_labels(EEG)
for axis, index in zip(axes.ravel(), indices[:PLOTS_PER_FIGURE]):
axis.axis("off")
label = labels[index - 1] if index - 1 < len(labels) else str(index)
axis.text(0.5, 0.5, label, ha="center", va="center", fontsize=10)
axis.set_title(str(index))
fig_obj.suptitle("View channels properties - pop_viewprops()")
fig_obj.tight_layout()
return [fig_obj]

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.

Channel mode of pop_viewprops shows only channel labels — no actual properties.

When typecomp=1 (channel mode), _plot_props draws a row of axes whose only content is axis.text(0.5, 0.5, label, ...) and a numeric title. EEGLAB's pop_viewprops for channels produces a property panel with topography, spectrum, and ERP-image thumbnails per channel. The known_differences note only mentions that scrolling activity is omitted; it doesn't acknowledge that the entire per-channel property visualization is missing.

If the channel property rendering is intentionally out of scope for this phase, the known_differences text should call that out (so the visual parity reviewer doesn't expect parity), and the dialog spec should probably disable the channel mode entry-point (or the menu wiring should route Plot > Channel properties to a coming-soon stub) until it lands. Fix this →

Comment on lines +33 to +35
row_count = int(out.get("nbchan", 0) or 0) if int(bool(typerej)) else _component_count(out)
rejglobal = np.zeros(trials, dtype=bool)
rejglobal_e = np.zeros((row_count, trials), dtype=bool)

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.

rejglobalE is sized by nbchan for typerej=1, but the function may then OR in icarejXxxxE matrices that have ncomp rows.

When typerej=1 and Rothertype=1, the second _add_family("ica", ...) call ORs icarejmanualE/icarejjpE/etc. into a buffer sized (nbchan, trials). If ncomp != nbchan (very common — e.g. ICA on a subset of channels), _or_matrix silently truncates rows:

rows = min(out.shape[0], values.shape[0])
out[:rows, :cols] |= values[:rows, :cols]

So component-level marks past row nbchan are dropped without warning, and the row indices of the surviving ones no longer correspond to channels OR components — they get mixed.

Symmetrically, typerej=0 allocates by _component_count and would lose channel rows. EEGLAB's eeg_rejsuperpose keeps the data and ICA per-row matrices distinct and only ORs along the trial vector when crossing families. Recommend either: (a) skip OR-ing the per-row matrix from the other family entirely (only superpose the per-trial vector when Rothertype=1), or (b) raise/warn when nbchan != ncomp and Rothertype=1. Fix this →

Comment on lines +239 to +240
QPushButton#butfreq { background: #cc99ff; max-width: 30px; padding: 0; }
QPushButton#butspec { background: #cc99ff; max-width: 30px; padding: 0; }

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: QPushButton#butspec rule is dead. No control in the spec ever sets tag="butspec" — the spectra section uses tag="butfreq" via threshold_rows("Find abnormal spectra (slow)", "freq", ...). Either drop the unused rule or rename to match the active tag.

@suraj-ranganath
suraj-ranganath force-pushed the phase/3-rejection-component-workflows branch from 604d690 to 423fd5f Compare May 28, 2026 10:02
@suraj-ranganath

Copy link
Copy Markdown
Member Author

@claude review this

@claude

claude Bot commented May 28, 2026 •

Copy link
Copy Markdown
Contributor

Claude Code PR Review

Working on review...

  • Set up working branch
  • Read core new modules (_rejection.py, pop_rej*, pop_autorej, pop_selectcomps, pop_viewprops)
  • Read GUI/menu wiring and visual capture changes
  • Read tests
  • Cross-check against the prior review feedback
  • Post review summary

View job run · Branch: phase/3-rejection-component-workflows

@suraj-ranganath
suraj-ranganath merged commit 01687e8 into feature/eeglab-completion May 28, 2026
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