Skip to content

[DIPFIT] Implement source-localization menu surfaces - #84

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

suraj-ranganath merged 2 commits into
feature/eeglab-completionfrom
phase/3-dipfit-workflows

Conversation

@suraj-ranganath

Copy link
Copy Markdown
Member

Add EEGPrep DIPFIT settings storage, standalone dipole plotting, menu dispatch, help resources, and explicit missing-backend errors for FieldTrip-dependent source-localization workflows. Adds focused tests and visual parity cases for the bundled DIPFIT dialogs.

Closes #63

@claude

claude Bot commented May 28, 2026 •

Copy link
Copy Markdown
Contributor

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


Code review

  • Overall assessment: Needs changes (two important behavior bugs in the dipplot path).
  • Highest-risk area: pop_dipplot default-component selection + GUI menu action discarding the figure.
  • Merge recommendation: Needs changes.

Blocking

None.

Important

  • pop_dipplot errors on default comps — src/eegprep/plugins/dipfit/pop_dipplot.py:41-46. one_based_indices(empty, default_all=True) returns [1..len(models)], so the default_components = localized_components(EEG) fallback is unreachable, and _validate_components_have_positions raises whenever any model is unlocalized. Bare pop_dipplot(EEG) and the Tools-menu action both hit this, even though the dialog hint says "[]=all available". Fix: set default_all=False so the fallback to default_components triggers, and add a test for a dataset with partially-fit components. See inline comment for a suggested patch.
  • Dipplot figure is silently discarded from the menu — src/eegprep/functions/guifunc/menu_actions.py:1064-1070. _plot_dipoles in pop_dipplot.py creates a Matplotlib figure but never calls fig.show(), and the dispatcher unpacks _figures and throws it away. With matplotlib's default non-interactive backend the user clicks "Component dipole plot" → fills the dialog → nothing visible appears. Either the dispatcher should call figure.show() on each returned figure or _plot_dipoles should show it itself (matching how other pop_* plot wrappers behave).

Nits

  • coord_transform clobbered on empty submit — src/eegprep/plugins/dipfit/pop_dipfit_settings.py:166-168. Unconditionally setting dipfit["coord_transform"] = _numeric_list(options["coord_transform"]) wipes the template's MNI rotation when the GUI line-edit is empty (No-Co-Reg unchecked). Suggest skipping the assignment when the parsed list is empty — see inline comment.
  • Hard-to-read conditional — src/eegprep/plugins/dipfit/pop_dipplot.py:154. if np.isfinite(float(rv)) if _is_scalar(rv) else False: would read more cleanly as if _is_scalar(rv) and np.isfinite(float(rv)):.

Test gaps

  • No test exercises pop_dipplot with an unspecified comps argument against an EEG where some dipfit.model entries have empty posxyz. Adding one would have caught the default-component bug above.
  • No test asserts the coord_transform template default survives a GUI-driven pop_dipfit_settings submit when the line edit text is empty.

EEGLAB parity notes

  • pop_dipfit_settings accepts chanomit= and electrodes= keywords; EEGLAB's MATLAB pop_dipfit_settings accepts only chansel. The extra keywords are convenient in Python but mean a verbatim history line pop_dipfit_settings(EEG, chanomit=[2]) will not replay in MATLAB. Mention this in the help/docstring if it isn't already, so EEGLAB users aren't surprised.
  • EEGLAB's pop_dipplot defaults comps to 1:length(EEG.dipfit.model) and silently filters to entries with valid posxyz. The Python port both selects all and raises on unlocalized — combine these (see the default_all=False fix above) to keep the menu's "all available" semantics.

Checked: changed files in src/eegprep/plugins/dipfit/*, menu_actions.py dispatch additions, _utils.py, visual_capture/visual_parity case additions, __init__.py lazy exports, and tests/test_dipfit_workflows.py coverage against the EEGLAB DIPFIT GUI flows.
· phase/3-dipfit-workflows

@suraj-ranganath

Copy link
Copy Markdown
Member Author

🤖 DIPFIT Phase 3 implementation spec and visual evidence

Problem: Phase 3 issue #63 still had bundled DIPFIT/source-localization menu actions registered as placeholders, so users could see EEGLAB DIPFIT menus but could not configure DIPFIT metadata, plot existing models, or get clear errors when FieldTrip-only workflows were unavailable.

Approach: This PR adds EEGPrep-owned DIPFIT modules under src/eegprep/plugins/dipfit/, wires the menu dispatcher and public exports, adds packaged help resources, and removes the Phase 3 DIPFIT placeholders. pop_dipfit_settings performs a real standalone workflow by storing EEGLAB-compatible EEG["dipfit"] settings and chansel; pop_dipplot performs a real standalone matplotlib dipole-position plot when model positions exist. FieldTrip/headmodel/gridsearch/nonlinear/multifit/leadfield/LORETA paths validate prerequisites and then raise a user-facing DIPFITUnavailableError instead of silently no-oping.

Key code: src/eegprep/plugins/dipfit/_utils.py centralizes template metadata, prerequisite checks, history formatting, and missing-backend messaging. src/eegprep/plugins/dipfit/_fieldtrip_workflows.py keeps FieldTrip-dependent wrappers explicit and testable. tools/visual_parity/capture.py adds DIPFIT visual cases and a capture-only override for EEGLAB's optional FieldTrip plugin check so reference screenshots can be captured without installing FieldTrip-lite.

Tests: Focused tests cover sample_data settings, missing channel locations, missing ICA/settings/model assets, multi-dataset settings GUI behavior, explicit FieldTrip limitation errors, standalone dipplot success/error paths, menu dispatch, visual parity case registration, and placeholder removal. Verified with ruff, format check, ty, focused Phase 3 tests, and EEGPREP_SKIP_MATLAB=1 uv run --no-sync pytest -m "not slow".

Visual parity artifacts are attached below as GitHub user attachments and are not committed to the repo. Side-by-side images are EEGLAB on the left and EEGPrep on the right. The headmodel screenshot is EEGPrep-only because EEGLAB opens a native MRI file picker before the parameter dialog.

pop_dipfit_settings
pop_dipfit_settings side by side

pop_dipfit_gridsearch
pop_dipfit_gridsearch side by side

pop_dipfit_nonlinear
pop_dipfit_nonlinear side by side

pop_dipplot
pop_dipplot side by side

pop_multifit
pop_multifit side by side

pop_leadfield
pop_leadfield side by side

pop_dipfit_loreta
pop_dipfit_loreta side by side

pop_dipfit_headmodel
pop_dipfit_headmodel EEGPrep

Comment on lines +41 to +46
default_components = localized_components(EEG)
components = one_based_indices(comps, limit=len(models), default_all=not bool(comps))
if not components:
components = default_components
if not components:
raise ValueError("No localized dipoles are available to plot")

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.

Severity: Important — likely-broken default behavior.

When comps is empty (None, "", or []) — which happens for the bare pop_dipplot(EEG) console call and for the GUI default ("Components indices ([]=all available)") — one_based_indices(empty, ..., default_all=True) returns [1..len(models)], so components is never empty and the default_components = localized_components(EEG) fallback on line 44 is unreachable. _validate_components_have_positions then raises Localization not found... whenever any model in EEG.dipfit.model has an empty posxyz, which is normal for partially-fit datasets (and is what EEGLAB silently skips).

This means selecting "Component dipole plot" from the Tools menu, or running pop_dipplot(EEG) from the console, errors out whenever some ICs are unlocalized — even though the dialog hint says "[]=all available".

Fix: let the empty case fall through to default_components:

Suggested change
default_components = localized_components(EEG)
components = one_based_indices(comps, limit=len(models), default_all=not bool(comps))
if not components:
components = default_components
if not components:
raise ValueError("No localized dipoles are available to plot")
default_components = localized_components(EEG)
components = one_based_indices(comps, limit=len(models), default_all=False)
if not components:
components = default_components
if not components:
raise ValueError("No localized dipoles are available to plot")
_validate_components_have_positions(models, components)

Worth adding a test that calls pop_dipplot(eeg) on a dataset where some models have empty posxyz and asserts the figure is built from only the localized ones.

Comment on lines +1064 to +1070
if name == "pop_dipplot":
from eegprep.plugins.dipfit.pop_dipplot import pop_dipplot

_figures, command = pop_dipplot(selection, return_com=True)
self._add_history_from_gui(command)
self._refresh()
return

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.

Severity: Important — figure may never be shown from the GUI menu.

pop_dipplot builds a Matplotlib Figure via plt.figure(...) and returns it without calling fig.show() or plt.show(). Here the dispatcher unpacks _figures and immediately discards it. On non-interactive matplotlib backends (or when matplotlib's interactive mode is off, which is the default in plain CPython), the user clicks "Component dipole plot" → fills the dialog → nothing visible happens. Only history is recorded.

Two options:

  • Call figure.show() (or plt.show(block=False)) on each returned figure inside _run_dipfit_function before discarding, so the dispatcher matches the other plot actions; or
  • Have pop_dipplot._plot_dipoles call fig.show() itself when invoked from a GUI/interactive context (similar to how other pop_* plot wrappers do).

Without one of these the menu action is a silent no-op outside of Jupyter / IPython interactive backends.

Comment on lines +166 to +168
if "coord_transform" in options:
dipfit["coord_transform"] = _numeric_list(options["coord_transform"])
usable = coordinate_channel_indices(out)

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.

Severity: Nit — clobbers template coord_transform on an empty GUI submit.

When the GUI runs with the BEM template (the default), _run_gui sets options["coord_transform"] to whatever text is in the coord_transform line edit unless "No Co-Reg." is checked. If the user clears that text (or it is somehow empty), _numeric_list("") returns [] and this assignment wipes the template's standard MNI rotation, leaving an unusable head-model registration.

Consider guarding with the same "skip when empty" rule used for the file fields above, so the template default survives an empty coord_transform submission:

if "coord_transform" in options:
    transform = _numeric_list(options["coord_transform"])
    if transform:
        dipfit["coord_transform"] = transform

If you want the user to be able to intentionally clear the transform, the No-Co-Reg checkbox already covers that.

@suraj-ranganath
suraj-ranganath force-pushed the phase/3-dipfit-workflows branch from 5473e8e to 7fed51f Compare May 28, 2026 21:09
@suraj-ranganath
suraj-ranganath merged commit 3d09d99 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