Skip to content

[Phase 3] Implement ICLabel component workflows - #69

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

suraj-ranganath merged 3 commits into
feature/eeglab-completionfrom
phase/3-ica-iclabel-workflows

Conversation

@suraj-ranganath

Copy link
Copy Markdown
Member

Add GUI, API, console, help, and menu support for pop_icflag and pop_subcomp. This removes the matching Phase 3 placeholders while preserving EEGLAB indexing, ICLabel flag semantics, and component-removal history replay.\n\nPart of #63

@claude

claude Bot commented May 27, 2026 •

Copy link
Copy Markdown
Contributor

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


Claude PR Review for #69

Reviewed the Phase 3 ICLabel/component-removal workflows against the diff vs origin/feature/eeglab-completion. Overall the structure is clean, EEGLAB-style naming and module placement is consistent with AGENTS.md, and the new code paths are well-covered by unit tests, sample-data tests, and a visual-parity case for each new dialog.

Concrete findings posted inline; summary below.

  • Read AGENTS.md guidelines
  • Inspect PR diff vs origin/feature/eeglab-completion
  • Review pop_icflag.py (new)
  • Review pop_subcomp.py (refactor)
  • Review eeg_icflag.py (refactor)
  • Review GUI integration, help, console, tests
  • Post inline + summary review comments

Findings

Parity (EEGLAB) — please address before merge

  1. pop_subcomp.py:134 — icawinv not recomputed from trimmed weights. EEGLAB's pop_subcomp.m runs pinv(EEG.icaweights * EEG.icasphere) after trimming; this PR preserves columns of the original mixing instead. Identical only for square invertible ICA, divergent for rank-reduced decompositions (PCA-reduced runica, AMICA, etc.). See inline comment.
  2. pop_subcomp.py:137 — clears entire EEG.reject dict. EEGLAB only resets gcompreject to zeros; sibling fields (rejmanual, rejglobal, channel/trial flags) are preserved. The unit assertion at tests/test_gui_pop_subcomp.py:61 (out["reject"] == {}) bakes this divergence in.

Behavior

  1. pop_subcomp.py:90-91 — list path raises before the dialog opens. Selecting multiple datasets with no flags throws "Flag components first or pass components." before the user has a chance to do exactly that via the dialog's remove/retain fields. Defer the check until after the user submits a blank dialog.
  2. pop_subcomp.py:53-56 — list path always emits a history command even when every dataset hit the "No components specified, no rejection performed" warning. Inconsistent with the singleton branch on line 59.

Minor / nits

  1. pop_icflag.py:60-72 — _require_iclabel only runs in the singleton branch and is implicitly relied on through the recursive call for the list branch. The structure works, but rewriting as "handle list → loop → handle singleton" (singleton path first or list-recurse before any validation) would make the contract obvious. Not blocking.
  2. eeg_icflag.py:58 uses strict > / < (open interval). The test test_eeg_icflag_uses_eeglab_open_interval_thresholds documents this; matches pop_icflag.m behavior. 👍

What looked good

  • pop_icflag GUI threshold dialog spec matches the EEGLAB layout (7-class, min/max columns, blank == NaN).
  • pop_subcomp keeps EEGLAB 1-based component indexing and routes the retain field correctly to keepcomp=1.
  • Help markdown added for both functions in src/eegprep/resources/help/ (no docstring fallbacks).
  • Menu wiring through menu_actions.py (including _MULTIPLE_DATASET_ACTIONS and the placeholder removal in menu_placeholders.py) is consistent with the existing pattern.
  • Visual parity capture + manifest entries added for both dialogs, hooking the existing _write_matlab_simple_pop_dialog_script path with appropriate titles.
  • Sample-data integration test (test_pop_subcomp_removes_requested_sample_component, test_pop_icflag_flags_sample_components_with_iclabel_probabilities) exercises the real ICA decomposition end-to-end.
  • History strings round-trip through _console_python_command and remain replayable from the console.

Recommendation

Approve once the two parity issues (#1 and #2) are addressed (or explicitly deferred with a follow-up tracking issue) and the list-mode dialog UX (#3) is loosened. #4 and the nits can land in the same change or a quick follow-up.
· branch phase/3-ica-iclabel-workflows

@suraj-ranganath

Copy link
Copy Markdown
Member Author

🤖 Phase 3 PR 1 specification

Problem: Issue #63 needs ICA-adjacent data workflows to stop being placeholders before later component views, rejection, and DIPFIT work can build on them. The missing PR1 surface was pop_icflag and GUI/API/console-ready pop_subcomp, including menu dispatch, history replay, help resources, and visual parity coverage.

Approach: Added eegprep.plugins.ICLabel.pop_icflag over eeg_icflag, preserved EEGLAB's open-interval threshold semantics and reject-field behavior, and removed pop_icflag from placeholder metadata. Reworked pop_subcomp to support return_com, GUI input, flagged-component defaults, keepcomp, 1-based component arguments, ICLabel/DIPFIT trimming, menu dispatch, and console-valid history. Browser/plot confirmation remains explicitly out of scope for later Phase 3/4 work.

Key code: pop_icflag normalizes a 7x2 threshold matrix, writes only EEG.reject.gcompreject, and emits a pasteable command with keyword thresholds. pop_subcomp computes activations from icaweights*icasphere over icachansind, projects remaining components through icawinv, clears ICA activations/rejection state like EEGLAB, and keeps component indices user-facing and 1-based.

Tests: Added GUI/unit coverage for pop_icflag and pop_subcomp, sample_data integration tests, console command-order routing coverage, package export coverage, menu placeholder inventory updates, and visual parity cases for both dialogs. Verified with focused GUI/console/sample tests, ruff check, ruff format --check, ty check, visual parity capture/compare against /Users/suraj/Desktop/eeglab, and EEGPREP_SKIP_MATLAB=1 uv run --no-sync pytest -m "not slow".

@suraj-ranganath

Copy link
Copy Markdown
Member Author

🤖 GUI visual parity evidence for Phase 3 PR 1.

pop_icflag dialog:
pop_icflag side by side

pop_subcomp dialog:
pop_subcomp side by side

Comment on lines +90 to +91
if isinstance(EEG, list) and not any(_flagged_components(item) for item in EEG):
raise ValueError("No components are flagged for rejection. Flag components first or pass components.")

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 list path raises before the dialog can open. If a user selects several datasets and none have flagged components yet, they cannot even open pop_subcomp to type a component list manually — but the dialog itself accepts a manually typed remove/retain list and is supposed to handle that case (see the help text at pop_subcomp_dialog_spec which says "Leave blank to remove flagged components in each selected dataset"). The error message ("Flag components first or pass components") references options the user can't reach from here.

Consider letting the dialog open, then deferring the "no components specified" feedback to _remove_components (which already logs a warning and skips), or only raising when the user submits a blank dialog and no datasets are flagged.

output["setname"] = f"{output.get('setname', '')} pruned with ICA".strip()
output["icaact"] = np.array([])
output["icaweights"] = weights[keep_mask, :]
output["icawinv"] = mixing[:, keep_mask]

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.

🤖 Parity divergence from EEGLAB. pop_subcomp.m recomputes the unmixing inverse from the trimmed weights:

EEG.icaweights = EEG.icaweights(compkeep, :);
EEG.icawinv    = pinv(EEG.icaweights * EEG.icasphere);

EEGPrep instead preserves the corresponding columns of the original mixing matrix (mixing[:, keep_mask]). For square invertible ICA these are numerically close, but for rank-reduced decompositions (e.g. PCA-pre-whitened runica, where weights is k × N with k < N) pinv(W_keep @ S) and original_mixing[:, keep] are different matrices. Downstream callers that re-derive activations from icawinv (notably plotting and back-projection) would see different scales than they would in EEGLAB.

Suggest replacing the line with something like output["icawinv"] = finite_pinv(finite_matmul(weights[keep_mask, :], sphere)) to match EEGLAB exactly.

output["icawinv"] = mixing[:, keep_mask]
output["specicaact"] = np.array([])
output["specdata"] = np.array([])
output["reject"] = {}

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.

🤖 Parity divergence from EEGLAB. pop_subcomp.m only resets gcompreject and leaves the rest of the rejection struct alone:

EEG.reject.gcompreject = zeros(size(EEG.icaweights,1), 1);

Clearing the whole reject dict drops sibling fields like rejmanual, rejglobal, channel/trial rejection flags, etc. The unit test at tests/test_gui_pop_subcomp.py:61 is asserting the current behavior (out["reject"] == {}), so that assertion also needs to change.

Suggested replacement:

existing_reject = dict(output.get("reject") or {})
existing_reject["gcompreject"] = np.zeros(int(keep_mask.sum()), dtype=int)
output["reject"] = existing_reject

Comment on lines +53 to +56
if isinstance(EEG, list):
outputs = [pop_subcomp(item, components, plotag, keepcomp, gui=False, return_com=False) for item in EEG]
command = _history_command(components, plotag, keepcomp)
return (outputs, command) if return_com else outputs

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.

🤖 Inconsistent with the single-dataset branch (line 59), which only emits a history command when something was actually removed. The list branch always emits a command, even when every dataset bailed out via logger.warning("No components specified, no rejection performed"). Replaying the resulting history would then re-do nothing-but-still-noisy pop_subcomp calls.

Consider filtering by whether any dataset returned a non-empty command, e.g. only set command = _history_command(...) when any(...) removal succeeded, or capture per-item history strings and skip blanks.

Comment on lines +60 to +72
if thresholds is None:
thresholds = DEFAULT_ICFLAG_THRESHOLDS
thresholds = _normalize_thresholds(thresholds)

if isinstance(EEG, list):
output = [pop_icflag(item, thresholds, gui=False, return_com=False) for item in EEG]
command = _history_command(thresholds)
return (output, command) if return_com else output

_require_iclabel(EEG)
output = eeg_icflag(copy.deepcopy(EEG), thresholds)
command = _history_command(thresholds)
return (output, command) if return_com else output

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.

🤖 Minor: when EEG is a list (line 64), _require_iclabel is never called on the individual datasets in this top-level branch — the validation only runs in the singleton path (line 69), which is reached through each recursive call at line 65. That recursion happens inside pop_icflag(item, ...), so the singleton call site does see the check. This is fine, but if anyone refactors the dispatch later it would be easy to lose the per-item validation. Worth a one-line comment, or moving the recursive list handling above the singleton path so the structure makes the per-item validation explicit.

Also: the recursive call on line 65 deep-copies inside eeg_icflag/pop_icflag (line 70 makes a deepcopy). Good — the input list is not mutated.

@suraj-ranganath

Copy link
Copy Markdown
Member Author

@claude review this

@claude

claude Bot commented May 27, 2026 •

Copy link
Copy Markdown
Contributor

Claude encountered an error after 5m 13s —— View job


Claude PR Review for #69 (re-review)

Re-reviewing the latest state of the PR per @suraj-ranganath's request.

  • Read AGENTS.md guidelines
  • Inspect PR diff vs origin/feature/eeglab-completion
  • Review pop_subcomp.py (recompute icawinv, partial reject clear, list-mode dialog UX, conditional history)
  • Review pop_icflag.py (validation structure)
  • Review eeg_icflag.py (open-interval semantics)
  • Review tests, GUI integration, help, console wiring
  • Post updated review summary
· branch [`phase/3-ica-iclabel-workflows`](https://github.com/sccn/eegprep/tree/phase/3-ica-iclabel-workflows)

@suraj-ranganath
suraj-ranganath force-pushed the phase/3-ica-iclabel-workflows branch from b725419 to 3f085f8 Compare May 27, 2026 18:05
@suraj-ranganath

Copy link
Copy Markdown
Member Author

@claude review this

@claude

claude Bot commented May 27, 2026 •

Copy link
Copy Markdown
Contributor

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


Claude PR Review for #69 (re-review)

  • Read AGENTS.md guidelines
  • Inspect PR diff vs origin/feature/eeglab-completion
  • Review pop_subcomp.py (recompute icawinv, partial reject clear, list-mode dialog UX, conditional history)
  • Review pop_icflag.py (validation structure)
  • Review eeg_icflag.py (open-interval semantics)
  • Review tests, GUI integration, help, console wiring
  • Post updated review summary

TL;DR

The follow-up commit cleanly resolves the actionable items from my first pass and adds two nice bonus improvements (MATLAB-style start:step:stop component ranges, Fortran-order reshape for epoched data). However, two of my original "parity" findings were wrong — I verified them against the live sccn/eeglab source and want to retract them. One of those wrong findings was acted on, which now introduces a small divergence from EEGLAB. Details below.

Corrections to my previous review

I fetched functions/popfunc/pop_subcomp.m from sccn/eeglab@develop and re-read the relevant block (lines 208–216):

EEG.data(EEG.icachansind,:,:) = compproj;
EEG.setname = [ EEG.setname ' pruned with ICA'];
EEG.icaact  = [];
goodinds    = setdiff_bc(1:size(EEG.icaweights,1), components);
EEG.icawinv     = EEG.icawinv(:,goodinds);
EEG.icaweights  = EEG.icaweights(goodinds,:);
EEG.specicaact  = [];
EEG.specdata    = [];
EEG.reject      = [];
  • refactor for packaging and test distribution #1 (icawinv recompute from trimmed weights) — INCORRECT, retracted. EEGLAB does EEG.icawinv = EEG.icawinv(:,goodinds) (line 212), which preserves the columns of the original mixing matrix. The PR's mixing[:, keep_mask] (pop_subcomp.py:133) matches EEGLAB exactly. The new test test_component_removal_preserves_eeglab_icawinv_columns is correctly named. Sorry for the noise.
  • Refactor #2 (EEG.reject full clear) — INCORRECT, retracted. EEGLAB does EEG.reject = []; (line 216), which wipes the entire reject struct (subfields and all). The original PR code (output["reject"] = {}) matched EEGLAB; the new code (preserve sibling fields, zero only gcompreject) now diverges from EEGLAB. See note below.

New observation introduced by the follow-up commit

pop_subcomp.py:136-137 now diverges from EEGLAB. Acting on my (incorrect) review point #2, the code is now:

output["reject"] = dict(output.get("reject") or {})
output["reject"]["gcompreject"] = np.zeros(int(keep_mask.sum()), dtype=int)

EEGLAB's behavior (EEG.reject = [];) discards the entire reject struct — rejmanual, rejglobal, channel/trial flags, everything. The PR now preserves sibling fields, which is defensible (those flags are user-visible state that arguably shouldn't be silently wiped) but is not EEGLAB parity. The unit test at tests/test_gui_pop_subcomp.py:62 (out["reject"]["rejmanual"] == [1, 0]) bakes the new behavior in.

Two clean options:

  1. Revert to EEGLAB parity — restore output["reject"] = {} (or None) and drop the rejmanual assertion. Matches EEGLAB exactly.
  2. Keep the divergence — leave the code as-is, but add a short comment at line 136 noting "EEGLAB clears EEG.reject = []; we preserve sibling rejection state intentionally." That makes the deviation explicit for future readers and parity reviewers.

I do not have a strong preference — both are reasonable — but as written there is no signal in the code that this is intentional, which will trip up the next parity pass. Fix this →

Items from previous review — status

# Finding Status
1 icawinv not recomputed Retracted (was wrong) — current code matches EEGLAB
2 Full reject clear Retracted (was wrong) — but the change made in response now diverges, see above
3 List path raises before dialog opens ✅ Fixed in _run_gui (pre-check removed); new test test_multiple_datasets_with_no_flags_can_enter_components_in_gui covers it
4 List branch always emits history ✅ Fixed via if any(result[1] for result in results) at pop_subcomp.py:56; new test test_multiple_dataset_noop_does_not_emit_history covers the no-op case
5 _require_iclabel only runs in singleton branch ✅ Improved — _flag_dataset helper makes per-item validation explicit; new test test_missing_iclabel_in_dataset_list_raises_clear_error covers it

Additional improvements in the follow-up commit

  • MATLAB-style ranges in component text. _parse_component_token (pop_subcomp.py:175-190) now handles 1:2, 1:2:10, and reverse steps, matching EEGLAB GUI input expectations. Covered by test_gui_accepts_eeglab_style_component_ranges. 👍
  • Fortran-order data reshape. data_2d = data.reshape(data_shape[0], -1, order="F") and the inverse reshape at line 129 keep multi-trial layout consistent with MATLAB's column-major storage. For matmul-only operations this is functionally equivalent regardless of order, but the explicit order="F" signals intent and is the safer choice if any future code starts indexing into data_2d by sample-then-trial. 👍

What still looks good (unchanged from first pass)

  • EEGLAB 1-based component indexing preserved end-to-end.
  • pop_icflag open-interval semantics (probs > min & probs < max) match pop_icflag.m:82.
  • eeg_icflag.py:60-61 correctly resets only gcompreject while preserving sibling fields — matches pop_icflag.m:85 (EEG.reject.gcompreject = flagReject;).
  • Help markdown, menu wiring, console history, and visual parity capture all consistent with the existing pattern.

Recommendation

Approve once the new EEG.reject divergence is either reverted to {} (matching EEGLAB) or documented inline as an intentional deviation. Everything else from the previous round is addressed, and I owe an apology for sending the author down a wrong path on points #1 and #2 — the PR is in better shape than my first review suggested.
· branch phase/3-ica-iclabel-workflows

@suraj-ranganath
suraj-ranganath merged commit f857fc4 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