Skip to content

Phase 4 PR 2: Add 3D headplot spline/coregistration parity - #77

Merged
suraj-ranganath merged 4 commits into
feature/eeglab-completionfrom
phase/4-headplot-spline-coreg
May 28, 2026
Merged

suraj-ranganath merged 4 commits into
feature/eeglab-completionfrom
phase/4-headplot-spline-coreg

Conversation

@suraj-ranganath

@suraj-ranganath suraj-ranganath commented May 28, 2026 •

Copy link
Copy Markdown
Member

Summary

Phase 4 PR 2: 3D headplot spline/coregistration parity.

This implements the EEGLAB-style headplot workflow for Plot > ERP maps > In 3-D and Plot > Component maps > In 3-D:

  • Adds an EEGLAB-aligned headplot spline setup and 3D rendering backend.
  • Adds pop_headplot ERP and component paths that create/load/reuse .spl spline files.
  • Packages the required headplot support resources so EEGPrep does not depend on the vendored EEGLAB checkout at runtime.
  • Updates the pop_headplot GUI to match EEGLAB's spline/coregistration setup flow: load existing spline, compute a new spline, choose mesh/channel support files, enter a Talairach transform, open Manual coregistration, and configure plot items/options.
  • Implements the manual coregister() editor behind Manual coreg. with source/reference electrode toggles, source/reference electrode selection, mesh toggle, editable transform fields, Align montages, Warp montage, cancel/OK, and a rotatable 3D Matplotlib view.
  • Adds standalone coregistration helpers for reading electrode files, matching labels/fiducials, applying EEGLAB/DIPFIT traditional transforms, and fitting shared-scale or traditional 9-parameter transforms without runtime FieldTrip/EEGLAB dependencies.
  • Keeps GUI/console history replayable as valid Python, including setup={...}, load=..., maplimits=..., and colorbar='off' paths.
  • Updates visual parity capture for EEGLAB's initial headplot warning, the ERP/component setup dialogs, final ERP/component 3D headplots, and the manual coregistration editor.
  • Fixes a latent MATLAB syntax issue in the visual parity capture helper by closing make_simple_pop_demo with end; this is incidental tooling cleanup needed for the headplot captures.

Motivation

EEGLAB users expect Plot > ERP maps > In 3-D and Plot > Component maps > In 3-D to first establish a reusable spline/coregistration setup, then render using that setup. The previous EEGPrep behavior showed a simplified plotting dialog that looked like the feature was complete but did not model EEGLAB's required spline-file setup/reuse workflow. This PR makes the setup explicit, reusable, and available from both the GUI and eegprep-console.

The manual coregistration editor is important because the transform matrix is not just a text option in EEGLAB. Users can inspect the head mesh, source electrodes, reference electrodes, label overlays, electrode subsets, and then fit or fine-tune the transform before saving the spline setup. This PR ports that user flow instead of leaving Manual coreg. as a placeholder.

Runtime Resources

Packaged under src/eegprep/resources/headplot/:

  • mheadnew.mat, mheadnew.xyz, mheadnew.transform
  • colin27headmesh.mat, colin27headmesh.xyz, colin27headmesh_license.txt
  • Standard-10-5-Cap385.sfp

These are used through importlib.resources; runtime code does not read from src/eegprep/eeglab.

EEGLAB Parity Notes

Inspected EEGLAB pop_headplot.m, headplot.m, coregister.m, traditionaldipfit.m, mesh support files, and the dialog/coregistration setup flow.

Important behavior matched:

  • .spl setup files store spline matrices, projected electrodes, electrode labels, selected channel indices, transform, and mesh metadata.
  • ERP maps use shared map limits across requested latencies.
  • Component maps support negative component indices by inverting polarity.
  • ICA spline setup drops channels without usable coordinate fields and keeps spline indices relative to ICA values, matching EEGLAB's headplot('setup', ..., 'ica', 'on') behavior.
  • Numeric view options remain in EEGLAB/MATLAB coordinates while Matplotlib receives the converted camera azimuth.
  • Manual coregistration follows EEGLAB's visible workflow: source electrodes in green, reference electrodes in brown, mesh visibility toggle, labels toggles, electrode subset selection, transform fields, Align montages, and Warp montage.
  • Warp montage fits a positive-scale traditional transform so user-facing Resize fields do not show confusing reflection-style negative scale values.

Standalone note: EEGLAB delegates some automatic alignment methods to FieldTrip. EEGPrep implements the manual editor plus traditional and globalrescale fitting directly with SciPy so runtime remains standalone. Unsupported non-linear FieldTrip-only warping methods fail clearly rather than silently no-op.

Tests And QA

  • uv run --no-sync ruff check .
  • uv run --no-sync ruff format --check .
  • uv run --no-sync ty check
  • ./pre-commit.py
  • uv run --no-sync pytest tests/test_phase4_plot_wrappers.py tests/test_visual_parity.py -q
    • 62 passed, 23 subtests passed
  • uv run --no-sync pytest tests/test_phase4_plot_wrappers.py -q
    • 38 passed
  • EEGPREP_SKIP_MATLAB=1 uv run --no-sync pytest -m "not slow"
    • 1293 passed, 227 skipped, 11 deselected
  • Visual parity captures refreshed for:
    • pop_headplot_erp_dialog
    • pop_headplot_components_dialog
    • coregister_dialog
    • final ERP 3D headplot
    • final component 3D headplot
  • Live GUI smoke with Computer Use:
    • launched the manual coregister() editor on sample_data/eeglab_data.set
    • toggled source labels
    • toggled mesh visibility
    • edited the Yaw field and confirmed redraw
    • clicked Warp montage and confirmed transform fields update with positive Resize values
    • cancelled cleanly with no hanging Python process
  • Live eegprep-console --full QA from the earlier PR pass:
    • loaded sample_data/eeglab_data.set
    • ran/replayed ERP pop_headplot(..., setup={...})
    • loaded sample_data/eeglab_data_with_ica_tmp.set
    • ran component pop_headplot(..., setup={...})
    • verified LASTCOM/ALLCOM contain replayable Python commands

Refs #64.

@claude

claude Bot commented May 28, 2026 •

Copy link
Copy Markdown
Contributor

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


Claude PR Review — Phase 4 PR 2: Headplot spline/coregistration parity

  • Fetched base + PR diff (git diff origin/feature/eeglab-completion...HEAD)
  • Read pop_headplot.py, headplot.py, qt.py, the test additions, help, visual-parity changes
  • Cross-checked spline math (computeg, electrode normalization, projection, transform) against typical EEGLAB conventions
  • Posted inline comments on specific concerns
  • Final summary (this comment)

Overall

Solid port. The spline .spl file layout, the load-or-recompute UX, the GUI validator, the setup={...} / load=... history serialization, and the ICA channel filtering all line up cleanly with EEGLAB. The MATLAB parity test for G, gx, Xe, indices, transform is the right backbone, and the GUI-replay test (exec(command, ...)) is a nice end-to-end check. Help text and visual-parity capture updates are consistent with the new dialog. No correctness-breaking issues found.

A few medium-severity concerns and several minor ones — details inline. Listed below in rough priority order.

Findings

Medium

  1. SPLINE_REGULARIZATION is effectively a no-op (sigprocfunc/headplot.py:506). spline.g + 0.1 broadcasts a scalar to the entire G matrix, not the diagonal; combined with the 1ᵀc = 0 constraint, the perturbation cancels and the solved coefficients are identical to the unregularized case. EEGLAB does not regularize here. Either remove or replace with a real diagonal ridge (G + λI).

  2. MATLAB parity coverage is narrow (tests/test_phase4_plot_wrappers.py). Only spline-setup metadata is compared. _interpolate_values, _project_electrodes_to_mesh, and the ICA spline setup path are not parity-tested. Recommend extending with a second case that compares interpolated face/vertex values on a known input vector against EEGLAB.

  3. Both setup mode checkboxes can be off simultaneously (guifunc/qt.py:671-686). _set_headplot_setup_mode returns early on uncheck. The dialog state can drift from what _pre_accept_validate will infer. Use a true radio-button group or re-assert the clicked checkbox on uncheck.

Minor

  1. Mesh switch back to mheadnew.mat doesn’t restore its transform (guifunc/qt.py:688-695). Only switching to colin27 fires the override; switching back leaves the colin27 transform stranded. The hardcoded colin27 transform is also duplicated between qt.py and pop_headplot.py's _COLIN27_TRANSFORM.

  2. "Browse other" for mesh doesn’t trigger transform update (guifunc/qt.py:_select_file interaction). _select_file sets editable text on the combo without changing currentIndex, so currentIndexChanged doesn’t fire — a custom mesh picked via Browse silently keeps whatever transform was last set.

  3. Replay always recomputes the spline file (popfunc/pop_headplot.py:_prepare_spline_file). Replaying a history command with setup={...} overwrites the spline file even when it already exists. EEGLAB's pop_headplot reuses an existing spline. Cheap reuse here would make replays faster and match EEGLAB.

  4. Inconsistent maplimits padding factors (popfunc/pop_headplot.py). _erp_maplimits uses 1.1 (EEGLAB-matching), _shared_maplimits uses 1.02 for string options. Pick one constant.

  5. _default_transform_text(EEG, 0) ties dialog logic to _MESH_CHOICES ordering and uses mheadnew.transform as fallback (which contains 0 -3 -53 -0.2 0 -1.6 1000 1000 1000, different from EEGLAB's hardcoded pop_headplot.m default [0, -10, 0, -0.1, 0, -1.6, 1100, 1100, 1100] already living in DEFAULT_TRANSFORM). Prefer DEFAULT_TRANSFORM as the fallback.

Drive-by

  1. tools/visual_parity/capture.py line 1020 adds a missing MATLAB end for make_simple_pop_demo. This is a fix for an existing latent issue. Worth calling out in the PR description since it incidentally lives in a headplot-scoped diff.

What looks good

  • ICA path bookkeeping in _setup_channel_selection correctly stores value_indices as positions within the ICA values vector, and the spline-file indices round-trip cleanly.
  • _values_for_spline covers both "full nbchan" and "already filtered" inputs with a clear, testable condition.
  • History commands are valid Python and the GUI-result replay test executes them via exec(...).
  • Packaged resources via importlib.resources (no runtime dependency on src/eegprep/eeglab/) — matches AGENTS.md guidance.
  • pop_headplot_dialog_spec.known_differences explicitly flags the missing interactive 3-D coregistration editor — good "not a silent no-op" pattern.
  • Tests now reproduce the error paths ("cannot find spline file", "does not contain channel locations", "outside the epoch time range").

Suggested follow-ups (not blocking)

  • Replace the misleading SPLINE_REGULARIZATION constant.
  • Add a MATLAB-parity test for the rendered interpolated values (catches both _interpolate_values and _project_electrodes_to_mesh regressions).
  • Make _set_headplot_setup_mode enforce mutual exclusivity (or convert to QRadioButton).
  • Keep mesh-default transforms in one place (probably in sigprocfunc/headplot.py) and pull them through dialog params instead of duplicating in qt.py.
    · branch phase/4-headplot-spline-coreg

@suraj-ranganath

suraj-ranganath commented May 28, 2026 •

Copy link
Copy Markdown
Member Author

Attachments

🤖 Phase 4 PR 2 visual parity: headplot setup and 3D plots

headplot-erp-dialog.png headplot-components-dialog.png
headplot-erp-dialog.png headplot-components-dialog.png
headplot-erp-3d-plot.png headplot-component-3d-plot.png
headplot-erp-3d-plot.png headplot-component-3d-plot.png

🤖 Phase 4 PR 2 manual coregistration visual parity

side_by_side.png
side_by_side.png

def _interpolate_values(values: np.ndarray, spline: HeadplotSpline) -> np.ndarray:
centered = values - np.nanmean(values)
enum = values.size
system = np.vstack([spline.g + SPLINE_REGULARIZATION, np.ones((1, enum))])

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.

🤖 SPLINE_REGULARIZATION = 0.1 is added to every entry of G (broadcasting scalar to the full matrix), not just the diagonal. Because the system also enforces 1ᵀc = 0, the rank-1 perturbation 0.1·1·1ᵀ·c is identically zero on the feasible set, so this term has no mathematical effect on the solved coefficients. It is just confusing code — readers will assume Tikhonov-style ridge regularization is happening when it isn’t.

EEGLAB's headplot.m does not regularize here (C = pinv([G; ones(1,N)]) * [v; 0]). Either drop the constant or replace it with a real diagonal ridge (G + λI) and document the deviation from EEGLAB.

Also note: the new MATLAB parity test test_headplot_setup_spline_metadata_matches_eeglab only compares G, gx, Xe, indices, transform. The interpolation step (this line) is not compared against MATLAB output. Consider adding a parity test that solves the system on a known values vector and compares face-mean values to MATLAB.

Comment on lines +671 to +686
@staticmethod
def _set_headplot_setup_mode(widgets: Mapping[str, Any], params: Mapping[str, Any], checked: bool) -> None:
if not checked:
return
peer = widgets.get(params["peer"])
if peer is not None:
peer.setChecked(False)
load_enabled = params["mode"] == "load"
QtDialogRenderer._set_enabled(
[widgets[tag] for tag in params.get("load_targets", ()) if tag in widgets],
load_enabled,
)
QtDialogRenderer._set_enabled(
[widgets[tag] for tag in params.get("setup_targets", ()) if tag in widgets],
not load_enabled,
)

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.

🤖 _set_headplot_setup_mode returns early when checked=False, which means a user can click an already-checked compcb (or loadcb) to uncheck it and leave the dialog in a state where neither checkbox is set. _pre_accept_validate for pop_headplot falls through to the compute branch in that case, but the visible state is inconsistent: the UI doesn’t reflect what will actually happen, and the enabled/disabled state of the load/setup widgets reflects whichever mode was active last.

EEGLAB's matching callbacks (cb_load / cb_comp) force the radio behavior by always re-asserting one of the two. Suggest: when a checkbox is unchecked by the user, re-check it (treat it as a radio group), or convert to a true QRadioButton group so Qt enforces exclusivity.

Comment on lines +688 to +695
@staticmethod
def _set_headplot_transform_text(target: Any, index: int) -> None:
transforms = (
"",
"0 -15 -15 0.05 0 -1.57 100 88 110",
)
if index < len(transforms) and transforms[index]:
target.setText(transforms[index])

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.

🤖 Two issues here:

  1. Asymmetric mesh switch: only index 1 (colin27headmesh.mat) overrides the transform text. Switching back to index 0 (mheadnew.mat) does nothing, so the colin27 transform stays in the field — the user sees a stale, incorrect transform unless they re-type it. EEGLAB's cb_selectmesh restores the appropriate default for either mesh.

  2. Hardcoded constant duplicated: the colin27 transform 0 -15 -15 0.05 0 -1.57 100 88 110 also lives in pop_headplot.py as _COLIN27_TRANSFORM. They will drift. Either drive both from one constant (and the mheadnew default from DEFAULT_TRANSFORM / default_headplot_transform in headplot.py) or pass the transforms in via params from pop_headplot_dialog_spec so the GUI helper has no knowledge of mesh-specific values.

Also: when the user uses "Browse other" to pick a custom mesh, _select_file only sets editable text on the combo; it doesn’t change currentIndex, so currentIndexChanged never fires and the transform field is silently not updated. With a non-default mesh, the wrong template transform may stay loaded.

_validate_chanlocs(EEG)
compute_file = not _spline_file_is_ready(EEG, typeplot)
spline_value = str(_current_spline_file(EEG, typeplot) or "")
transform = _default_transform_text(EEG, 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.

🤖 _default_transform_text(EEG, 0) is always called with mesh_index=0, regardless of _MESH_CHOICES. Today that lines up with mheadnew.mat being first, but it ties two unrelated indexings together. Consider passing the mesh-popup default value (or the mesh name) through explicitly, especially since _default_transform_text's fallback reads mheadnew.transform — which contains 0 -3 -53 -0.2 0 -1.6 1000 1000 1000, not EEGLAB's hardcoded [0, -10, 0, -0.1, 0, -1.6, 1100, 1100, 1100] (which is what DEFAULT_TRANSFORM in headplot.py carries). The fallback path will surface a different transform than EEGLAB's pop_headplot.m default, which can surprise users who hit the fallback (unrecognized template, no chaninfo filename).

Suggest: have the fallback use DEFAULT_TRANSFORM from headplot.py rather than reading mheadnew.transform, or document that this file is the fallback source.

Comment on lines +396 to +412
if setup is not None and not _is_empty(setup):
setup_options = _normalise_setup_options(setup)
splinefile = str(setup_options.pop("splinefile"))
meshfile = setup_options.get("meshfile", DEFAULT_MESH)
chaninfo = dict(EEG.get("chaninfo") or {})
if "icachansind" not in chaninfo and not _is_empty(EEG.get("icachansind")):
chaninfo["icachansind"] = EEG["icachansind"]
headplot_setup(
EEG.get("chanlocs", []),
splinefile,
chaninfo=chaninfo,
ica="on" if int(typeplot) == 0 else "off",
**setup_options,
)
EEG[fieldname] = splinefile
EEG["headplotmeshfile"] = "" if Path(str(meshfile)).name == DEFAULT_MESH else str(meshfile)
return splinefile

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.

🤖 When a user replays the history command — which always contains setup={...} if setup was originally supplied — this re-runs headplot_setup from scratch and overwrites the spline file on disk, even if it already exists. EEGLAB's pop_headplot will reuse an existing spline file rather than always recomputing.

Consider: if Path(splinefile).exists() already, skip headplot_setup (or only re-run when a sentinel like recompute=True is passed). This keeps replays cheap and matches EEGLAB's reuse pattern. At minimum, the asymmetry is worth a short comment.

Comment on lines +542 to +568
def _erp_maplimits(EEG: dict[str, Any], items: np.ndarray) -> list[float]:
maps, _labels = _headplot_maps(EEG, 1, items)
data = np.asarray(maps, dtype=float)
limit = float(np.nanmax(np.abs(data)) * 1.1)
if not np.isfinite(limit) or limit == 0:
limit = 1.0
return [-limit, limit]


def _shared_maplimits(maps: list[np.ndarray], setting: Any) -> list[float]:
if isinstance(setting, str):
lower = setting.lower()
finite_values = np.concatenate([np.asarray(values, dtype=float).ravel() for values in maps])
finite_values = finite_values[np.isfinite(finite_values)]
if finite_values.size == 0:
finite_values = np.asarray([0.0])
if lower in {"maxmin", "minmax"}:
return [float(np.nanmin(finite_values) * 1.02), float(np.nanmax(finite_values) * 1.02)]
if lower == "absmax":
limit = float(np.nanmax(np.abs(finite_values)) * 1.02)
if not np.isfinite(limit) or limit == 0:
limit = 1.0
return [-limit, limit]
numeric = np.asarray(setting, dtype=float).ravel()
if numeric.size == 2:
return [float(numeric[0]), float(numeric[1])]
raise ValueError("headplot maplimits must be 'absmax', 'maxmin', or [min max]")

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 padding factors:

  • _erp_maplimits (line 545) uses 1.1, matching EEGLAB's pop_headplot.m: maplimits = [ -maxlim*1.1 maxlim*1.1 ].
  • _shared_maplimits (lines 559 and 561) uses 1.02 for 'maxmin' / 'absmax' string options.

For a single ERP plot, the chain is _erp_maplimits (1.1) → _shared_maplimits (1.02 path is skipped because input is numeric). For component plots with maplimits='absmax', the limits expand by only 1.02. EEGLAB does not use 1.02; suggest using a single padding constant (1.1 to match EEGLAB) and pulling it into a module-level constant.

Comment on lines +252 to +275
f"""
EEG = pop_loadset('{_matlab_string(SAMPLE_DATASET_PATH)}');
headplot('setup', EEG.chanlocs, '{_matlab_string(matlab_spline)}', ...
'chaninfo', EEG.chaninfo, 'meshfile', 'mheadnew.mat', ...
'transform', [{_matlab_vector(transform)}]);
S = load('{_matlab_string(matlab_spline)}', '-mat');
G = S.G; gx = S.gx; Xe = S.Xe; Ye = S.Ye; Ze = S.Ze;
indices = S.indices; transform = S.transform;
save('{_matlab_string(matlab_output)}', 'G', 'gx', 'Xe', 'Ye', 'Ze', 'indices', 'transform');
""",
nargout=0,
)
finally:
engine.quit()

py_spline = load_headplot_spline(python_spline)
ml = scipy.io.loadmat(matlab_output, squeeze_me=True)
np.testing.assert_allclose(py_spline.g, ml["G"], rtol=1e-10, atol=1e-10)
np.testing.assert_allclose(py_spline.gx, ml["gx"], rtol=1e-10, atol=1e-10)
np.testing.assert_allclose(py_spline.xe, ml["Xe"], rtol=1e-10, atol=1e-10)
np.testing.assert_array_equal(py_spline.indices + 1, np.asarray(ml["indices"], dtype=int).ravel())
np.testing.assert_allclose(py_spline.transform, np.asarray(ml["transform"], dtype=float).ravel())


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 MATLAB parity check is welcome but narrow. It compares only G, gx, Xe, indices, transform. It does not exercise:

  • The interpolation step (_interpolate_values — where the suspicious SPLINE_REGULARIZATION lives).
  • The mesh projection (_project_electrodes_to_mesh uses a custom 3-nearest-vertex averaging which is not what EEGLAB does verbatim).
  • The ICA spline setup path (ica='on'), which is the more complex code path with value_indices vs icachans bookkeeping.

Suggest adding a second parity case that calls headplot(values, splinefile) for both EEGLAB and EEGPrep on a known random values vector, and asserts allclose on the resulting per-vertex (or per-face) interpolated array. That catches the _interpolate_values and projection deviations.

" EEG.reject.rejkurtcol = [1 0.6 0.6];",
" EEG.reject.rejfreqcol = [1 0.6 0.6];",
"end",
"end",

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.

🤖 This added "end", closes make_simple_pop_demo. The function definition starts at line 896 but previously had no closing end, while capture_simple_pop_dialog below it (line 1053) does. In MATLAB, a single file must use end consistently across all function definitions, so the prior layout was a latent syntax issue.

Worth a one-line PR note since this is a fix that incidentally lands inside a headplot-focused diff. If a downstream branch picks the new close_headplot_warning snippet without this end, MATLAB will fail to parse.

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