Repository navigation
Phase 4 PR 2: Add 3D headplot spline/coregistration parity - #77
Conversation
|
Claude finished @suraj-ranganath's task in 6m 47s —— View job Claude PR Review — Phase 4 PR 2: Headplot spline/coregistration parity
OverallSolid port. The spline A few medium-severity concerns and several minor ones — details inline. Listed below in rough priority order. FindingsMedium
Minor
Drive-by
What looks good
Suggested follow-ups (not blocking)
|
| 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))]) |
There was a problem hiding this comment.
🤖 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.
| @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, | ||
| ) |
There was a problem hiding this comment.
🤖 _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.
| @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]) |
There was a problem hiding this comment.
🤖 Two issues here:
-
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'scb_selectmeshrestores the appropriate default for either mesh. -
Hardcoded constant duplicated: the colin27 transform
0 -15 -15 0.05 0 -1.57 100 88 110also lives inpop_headplot.pyas_COLIN27_TRANSFORM. They will drift. Either drive both from one constant (and themheadnewdefault fromDEFAULT_TRANSFORM/default_headplot_transforminheadplot.py) or pass the transforms in viaparamsfrompop_headplot_dialog_specso 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) |
There was a problem hiding this comment.
🤖 _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.
| 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 |
There was a problem hiding this comment.
🤖 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.
| 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]") |
There was a problem hiding this comment.
🤖 Inconsistent padding factors:
_erp_maplimits(line 545) uses1.1, matching EEGLAB'spop_headplot.m:maplimits = [ -maxlim*1.1 maxlim*1.1 ]._shared_maplimits(lines 559 and 561) uses1.02for'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.
| 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()) | ||
|
|
||
|
|
There was a problem hiding this comment.
🤖 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 suspiciousSPLINE_REGULARIZATIONlives). - The mesh projection (
_project_electrodes_to_meshuses 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 withvalue_indicesvsicachansbookkeeping.
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", |
There was a problem hiding this comment.
🤖 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.





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:
headplotspline setup and 3D rendering backend.pop_headplotERP and component paths that create/load/reuse.splspline files.pop_headplotGUI 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.coregister()editor behindManual 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.setup={...},load=...,maplimits=..., andcolorbar='off'paths.make_simple_pop_demowithend; 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.transformcolin27headmesh.mat,colin27headmesh.xyz,colin27headmesh_license.txtStandard-10-5-Cap385.sfpThese are used through
importlib.resources; runtime code does not read fromsrc/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:
.splsetup files store spline matrices, projected electrodes, electrode labels, selected channel indices, transform, and mesh metadata.headplot('setup', ..., 'ica', 'on')behavior.viewoptions remain in EEGLAB/MATLAB coordinates while Matplotlib receives the converted camera azimuth.Align montages, andWarp montage.Warp montagefits 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
traditionalandglobalrescalefitting 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.pyuv run --no-sync pytest tests/test_phase4_plot_wrappers.py tests/test_visual_parity.py -q62 passed, 23 subtests passeduv run --no-sync pytest tests/test_phase4_plot_wrappers.py -q38 passedEEGPREP_SKIP_MATLAB=1 uv run --no-sync pytest -m "not slow"1293 passed, 227 skipped, 11 deselectedpop_headplot_erp_dialogpop_headplot_components_dialogcoregister_dialogcoregister()editor onsample_data/eeglab_data.setWarp montageand confirmed transform fields update with positive Resize valueseegprep-console --fullQA from the earlier PR pass:sample_data/eeglab_data.setpop_headplot(..., setup={...})sample_data/eeglab_data_with_ica_tmp.setpop_headplot(..., setup={...})LASTCOM/ALLCOMcontain replayable Python commandsRefs #64.