Skip to content

[GUI] Match the pop_leadfield dialog on configured MRI data - #1038

Merged
arnodelorme merged 3 commits into
developfrom
agent/issue-1000-leadfield
Dec 1, 2026
Merged

arnodelorme merged 3 commits into
developfrom
agent/issue-1000-leadfield

Conversation

@arnodelorme

@arnodelorme arnodelorme commented Dec 1, 2026 •

Copy link
Copy Markdown
Collaborator

The public leadfield dialog follows the selected atlas for the source file, coordinate transform, and downsampling. The transform button previews supported source positions with the configured head model. The largest vertical offset after the change was 0.49 px. This PR stacks on #1028.

pop_leadfield.fit-triptych

distances

The 30 registered sample electrodes gave the same BEM leadfields at three explicit MNI locations within 3.37e−15 relative to FieldTrip. The installed standalone LORETA grid is an approximation. The other bundled MATLAB atlas files are not distributed by EEGPrep.

Native captures and verification

The clean jamming capture verified the checkout imports before opening each window. Focused geometry and DIPFIT test results were 209 passed in 3.73s.

Fixes #1000. Part of #875.

Full inventory report for the project team. pop_leadfield (p. 88). PDF · Editable Word.

@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 Dec 1, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @arnodelorme's task in 1m 21s —— View job


Code review

  • Overall assessment: The new dialog logic is coherent and the test matches it. One regression: choosing an unbundled atlas now ends in a raw scipy error after OK, where it used to give EEGPrep's clear "not bundled" message.
  • Highest-risk area: pop_leadfield OK path for the Colin27, ICBM152 and AFNI choices.
  • Merge recommendation: Needs changes.

Blocking

None.

Important

src/eegprep/plugins/dipfit/pop_leadfield.py: the Colin27, ICBM152 and AFNI choices now pass bare file names to the leadfield code. The new dipfit_source_model callback fills sourcemodel with names such as head_modelColin27_5003_Standard-10-5-Cap339.mat. EEGPrep doesn't ship these files.

  • Before: these choices left the field empty, and _leadfield_options_from_result raised "that source model file is not bundled … Leave the LORETA-KEY choice selected".
  • Now: that branch can no longer be reached for choices 1, 2 and 4.
    • For Colin27 and ICBM152, _source_points_from_option takes the .mat branch at L243, which runs before the is_file() check at L257. loadmat then raises scipy's own OSError, which has no pop_leadfield context and no fix, after the dialog has closed.
    • For AFNI, TTatlas+tlrc.HEAD hits the generic AFNI DIPFITUnavailableError.
  • Fix: in _leadfield_options_from_result, raise the "not bundled" error for choices 1, 2 and 4 unless the text is a file that exists.

See the inline comment.

Nits

src/eegprep/functions/guifunc/qt.py (dipfit_source_model): dialog-specific values are hard-coded in the shared Qt renderer. These are the Colin27 transform string, the indices 4, <2, 3 and >=3, and the downsample defaults "4" and "1". Meanwhile the file names arrive through params. The nearby dipfit_template callback takes all of its per-choice values from params. Pass transforms and downsample lists, plus the custom index, from pop_leadfield_dialog_spec. Then all of the leadfield choice data lives in pop_leadfield.py.

Test gaps

  • No test covers accepting the dialog with choice 1, 2 or 4. Add one to tests/test_dipfit_workflows.py that picks choice 1, accepts the dialog, and asserts that the pop_leadfield: … not bundled error is raised.
  • No test covers the new transform_browse preview action, _preview_source_model. A headless test could call the action with values={"sourcemodel": "loreta-key", "sourcemodel2mni": ""} on a configured EEG and check that it returns without error. This is optional, since the action only draws a plot.

EEGLAB parity notes

  • I couldn't compare against plugins/dipfit/pop_leadfield.m because it isn't vendored in this checkout. I didn't check the per-choice transform (0 -24 -45 0 0 -1.5707963 1000 1000 1000 for both surface models) or the AFNI downsample default of 4 against the MATLAB source.
  • The preview applies sourcemodel2mni to the points. pop_leadfield itself still computes the leadfield at the untransformed points and only stores coordtransform; that was already the case before this PR. As a result, the preview can show source positions that differ from the ones the leadfield is computed at. Confirm that this matches what EEGLAB does.

Comment on lines +100 to +106
source_files = (
"head_modelColin27_5003_Standard-10-5-Cap339.mat",
"tess_cortex_mid_low_2000V.mat",
"loreta-key",
"TTatlas+tlrc.HEAD",
"",
)

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: unbundled atlas choices now fail with a raw scipy error after OK.

Before this change, the Colin27 and ICBM152 choices left the File name field empty. _leadfield_options_from_result then raised its clear message: "that source model file is not bundled". Now the callback fills in a bare name like head_modelColin27_5003_Standard-10-5-Cap339.mat, so that check never runs. On OK, the name goes to _source_points_from_option. The .mat branch at

return np.asarray(data[key], dtype=float)
if lower.endswith(".mat"):
data = loadmat(path, squeeze_me=True, struct_as_record=False)
points = _find_mat_points(data)
if points is None:
raise ValueError(
f"pop_leadfield: {path} has no source positions in pos, vertices, or Vertices. "
"Save an N x 3 array under one of those names."
)
return points
runs before the is_file() check at
)
if not Path(path).is_file():
raise FileNotFoundError(
f"pop_leadfield: source model file {path} was not found. "
"Pass an existing .npy, .npz, or .mat position file, or sourcemodel='loreta-key'."
)
, so loadmat raises scipy's own OSError. That error doesn't name pop_leadfield or give a fix, and the dialog has already closed. The AFNI choice now hits the generic AFNI DIPFITUnavailableError rather than the "not bundled" guidance.

Suggested fix: keep the displayed names. In _leadfield_options_from_result, raise the "not bundled" error for choices 1, 2 and 4 unless the text is a file that exists. Add a test that picks choice 1, accepts the dialog, and asserts that this message is raised.

@arnodelorme arnodelorme left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

This review was written by an AI assistant during a nightly check, not by Arno.

Code review

  • Overall assessment: Needs changes.
  • Highest-risk area: _preview_source_model in src/eegprep/plugins/dipfit/pop_leadfield.py.
  • Merge recommendation: Needs changes.

Blocking

None.

Important

  1. src/eegprep/plugins/dipfit/pop_leadfield.py (_preview_source_model, L180-L183): radian DIPFIT transform passed to traditional instead of traditionaldipfit.
    pop_leadfield_dialog_spec sets surface_transform = "0 -24 -45 0 0 -1.5707963 1000 1000 1000" (-pi/2 radians, matching plugins/dipfit/pop_leadfield.m lines 76 and 86), and EEGLAB's preview callback plugins/dipfit/plot3dmeshalign.m (lines 169 and 228) applies traditionaldipfit(transform) (as does load_afni_atlas.py line 52). _preview_source_model instead calls traditional(transform) (_coordinates.py L151-L154), which treats rotations as degrees with the opposite Z rotation sign and rejects 6 element vectors. On surface_transform, [0.05, 0, 0.08] maps to [49.98, -25.37, 35.0] mm instead of [0.0, 26.0, 35.0] mm, leaving custom surface meshes rotated roughly 88 degrees off in the preview.
    Suggested fix: Import traditionaldipfit instead of traditional from eegprep.plugins.dipfit._coordinates and call apply_transform(traditionaldipfit(transform), points).

  2. src/eegprep/plugins/dipfit/pop_leadfield.py (_preview_source_model, L185-L188): BEM preview plots the outer scalp (vol["bnd"][0]) instead of the inner brain mesh (vol["bnd"][vol["source"]]).
    In standard_vol.npz (standardBEM), vol["bnd"][0] is the scalp (176 x 208 x 174 mm) while vol["bnd"][2] (vol["source"], computed by prepare_headmodel_sens in ft_dipolefitting.py L122-L123) is the brain surface (145 x 185 x 149 mm). Both EEGLAB plot3dmeshalign.m (lines 158 to 160, f.vol.bnd(3)) and the spherical branch right below (min(vol["r"])) draw the brain surface so the user can see whether source points lie inside the volume tested by inside_headmodel. Plotting vol["bnd"][0] makes points in the skull or scalp appear inside the brain mesh.
    Suggested fix: Use surface = vol["bnd"][vol["source"]].

Nits

  1. src/eegprep/plugins/dipfit/pop_leadfield.py (_preview_source_model, L173-L179 and L201-L203): modal dialog parenting and unbundled preset error in the preview button.
    Calling fig.show() directly skips show_figures(fig) (plot_utils.py L24-L60), which parents the Matplotlib window above the active modal QDialog and suppresses warnings on file backends. Clicking ... on the Colin27 or ICBM152 choices also calls _source_points_from_option before _leadfield_options_from_result, showing scipy.io.loadmat's raw [Errno 2] No such file or directory warning instead of pop_leadfield's "that source model file is not bundled" message.
    Suggested fix: Validate options = _leadfield_options_from_result(values) before loading options["sourcemodel"], and display the figure with show_figures(fig).

Test gaps

  • test_gui_leadfield_loreta_key_choice_fills_the_source_field exercises _preview_source_model only on standardBESA with an empty sourcemodel2mni. Add coverage with a nonzero radian rotation in sourcemodel2mni (checking the scattered points against traditionaldipfit) and with model="standardBEM" (checking the plotted trisurf vertices match vol["bnd"][vol["source"]]).

EEGLAB parity notes

  • _preview_source_model transforms source points with sourcemodel2mni for display (matching plot3dmeshalign.m), while pop_leadfield computes the leadfield on untransformed points and only stores coordtransform (existing behavior on lines 82 to 88). For a custom source file paired with a nonempty sourcemodel2mni, the previewed coordinates will differ from the coordinates used for the leadfield.

Tests run in a detached worktree at e5bcc9f3e9b1f185af9c88e4b5952c2e34439463: PYTHONPATH=<worktree>/src .venv/bin/python -m pytest tests/test_dipfit_workflows.py tests/test_dipfit_loreta_key.py (44 passed, 1 deselected in 17.28s).

@arnodelorme arnodelorme left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

This review was written by an AI assistant during a nightly check, not by Arno.

Code review

  • Overall assessment: Looks good.
  • Highest-risk area: None identified.
  • Merge recommendation: Safe to merge.

Blocking

None.

Important

None.

Nits

None.

Test gaps

None.

EEGLAB parity notes

None.

Checked pop_leadfield_dialog_spec and dipfit_source_model widget state transitions against plugins/dipfit/pop_leadfield.m, _preview_source_model coordinate transforms (traditionaldipfit), BEM brain mesh selection (vol["bnd"][vol["source"]]), spherical head model fallback, modal figure display (show_figures) against plugins/dipfit/plot3dmeshalign.m, unbundled source model error handling in _leadfield_options_from_result, Sphinx documentation in docs/source/api/ica_and_components.rst, changed behavior tests, and AGENTS.md compliance.

Tests run in a detached worktree at 9d59390537ca48025b1bc24e0daf3c8d51ca77c3:

  • PYTHONPATH=/Users/arno/.orchestrator/pr-reviews/eegprep-1038/src .venv/bin/python -m pytest /Users/arno/.orchestrator/pr-reviews/eegprep-1038/tests/test_dipfit_workflows.py /Users/arno/.orchestrator/pr-reviews/eegprep-1038/tests/test_dipfit_loreta_key.py: 47 passed, 1 deselected in 14.55s.
  • .venv/bin/ruff check and .venv/bin/ruff format --check on the modified Python files: passed.

@arnodelorme
arnodelorme changed the base branch from agent/issue-998-dipfit_headmodel to develop December 1, 2026 17:43
@arnodelorme
arnodelorme merged commit ea98958 into develop Dec 1, 2026
3 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.

[GUI] Match the pop_leadfield dialog to EEGLAB

1 participant