Skip to content

pop_clustedit: Restore cluster editing actions and content-sized rows - #1041

Merged
arnodelorme merged 9 commits into
developfrom
agent/issue-972-clustedit
Dec 1, 2026
Merged

arnodelorme merged 9 commits into
developfrom
agent/issue-972-clustedit

Conversation

@arnodelorme

@arnodelorme arnodelorme commented Dec 1, 2026 •

Copy link
Copy Markdown
Collaborator

🤖 Part of #972 and #875. Restore cluster editing actions and content-sized rows. Stacked on #1037.

Live MATLAB, EEGPrep before and after

Function output distances

Vertical control offsets

Native measurements and validation

Window height is 498 px in both applications. The maximum vertical offset is 0.407 px. On both real GUIs the N400 rename and create operations produced identical names, dataset indices and ICA component membership across all 11 or 12 resulting clusters. Twenty-seven workflow tests passed. With the EEGPrep dialog, select an action and press OK to apply it. Dipole buttons use std_dipplot when the loaded datasets contain fitted dipoles.

Full inventory report for the project team. pop_clustedit (p. 50). 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 37s —— View job


Code review

  • Overall assessment: Needs changes. One of the restored GUI actions can fail on a common path. I checked the create, rename, movecomp, dipole and dipparams branches, the dialog spec, the history commands, the docs and the new test.
  • Highest-risk area: the GUI sub-dialogs in pop_clustedit (reassign destination, rename guard).
  • Merge recommendation: Needs changes.

Blocking

None.

Important

  • The reassign destination list includes clusters that std_movecomp rejects (pop_clustedit.py:95). The list excludes only the ParentCluster and the source cluster. std_movecomp raises an error for any cluster that has children (std_movecomp.py:36-39). Picking an intermediate parent from multi-level clustering, or the clustlevel parent after Create new cluster when clustlevel != 1, raises ValueError after the user confirms the dialog. EEGLAB also leaves Outliers/Notclust clusters out of this list. Fix: list only leaf clusters that are not outlier clusters. There is an inline suggestion on that line. Fix this →
  • The packaged help is out of date (src/eegprep/resources/help/pop_clustedit.md). The GUI Help button still lists only plot, rename, merge, moveoutlier, movecomp and rejectoutliers. It also says plotting arrives in a later phase. AGENTS.md says: "When adding a user-facing function or GUI dialog with a Help button, add or update the corresponding Markdown help resource." Fix: add create, dipoles, componentdipoles and dipparams (with dipmode), and show an example action="create", name="Manual" call.

Nits

  • Rename on a protected cluster does nothing and gives no message (pop_clustedit.py:81-86). If ParentCluster, an Outliers* cluster or a Notclust* cluster is selected, Rename selected cluster quietly returns the cancelled tuple. EEGLAB shows a warning in this case. A short message box would tell the user why nothing happened.
  • Calling action="dipparams" from the API without dipmode stores None in STUDY.etc.dipparams.mode and writes a history command with no mode. Consider raising when dipmode is missing outside the GUI.

Test gaps

  • Reassign GUI path. The only new test covers API create. A test that runs gui=True with a scripted renderer that picks Reassign selected component(s) and then a destination row would check two things: the options[int(target["destination"]) - 1] mapping, and that non-leaf clusters are not offered.

EEGLAB parity notes

  • create adds an empty child named <name> <N> under the clustlevel parent and leaves the parent's components unchanged. That matches the intent of std_createclust, and the new test covers it.
  • The dipole buttons are enabled only when a loaded dataset has dipfit.model. dipparams offers apart/together/multicolor/centroid, all of which std_dipplot._VALID_MODES accepts.
  • pop_clustedit.m is not in the local src/eegprep/eeglab/ checkout, so I could not cite EEGLAB line numbers. The EEGLAB comparisons above are not line-verified.

name = reply[0].strip() or "Cls"
elif action == "movecomp" and to_cluster is None:
targets = cluster_list(study)
options = [n for n in range(2, len(targets) + 1) if n != cluster]

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: the reassign dialog lists clusters that std_movecomp rejects. The destination list excludes only the ParentCluster and the source cluster. But std_movecomp raises ValueError("Cannot move components if clusters have child clusters") for any cluster with children (

raise ValueError("Cannot move components to or from the ParentCluster")
if old.get("child") or new.get("child"):
raise ValueError("Cannot move components if clusters have child clusters")
positions = np.asarray(comps, dtype=int).ravel()
). Picking a non-leaf cluster, such as an intermediate parent from multi-level clustering, therefore raises an error after the user confirms the dialog. EEGLAB's movecomp branch also leaves out Notclust/Outliers clusters and clusters with children when it builds the destination list.

Suggested fix: build the list from leaf clusters that are not outlier clusters, for example:

Suggested change
options = [n for n in range(2, len(targets) + 1) if n != cluster]
options = [
n
for n in range(2, len(targets) + 1)
if n != cluster
and not targets[n - 1]["child"]
and not targets[n - 1]["name"].lower().startswith(("outliers", "notclust"))
]

@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. The restored dipole plotting actions fail or plot the wrong clusters on the default GUI selection and do not open plot windows in the desktop GUI.
  • Highest-risk area: Dipole plotting (dipoles and componentdipoles) and outlier cluster filtering in pop_clustedit.py.
  • Merge recommendation: Needs changes.

Blocking

None.

Important

  • Important: Plot dipoles on the default All cluster centroids selection plots ParentCluster and outlier clusters, crashes on empty clusters, and writes unused arguments to history (src/eegprep/functions/studyfunc/pop_clustedit.py, lines 173 to 184 and line 230).
    In the dialog, clus_list defaults to [1] (All cluster centroids), which _clusters_from_list_selection expands to [1, 2, ..., N]. Passing that list to std_dipplot includes cluster 1 (ParentCluster), any outlier or Notclust clusters, and any empty clusters. As a result, clicking Plot dipoles on a clustered STUDY plots a duplicate ParentCluster subplot and writes STUDY["cluster"][0]["dipole"]. Worse, right after creating an empty cluster with Create new cluster (action="create"), clicking Plot dipoles (or calling pop_clustedit(study, datasets, action="dipoles") with clusters=None) raises ValueError: STUDY cluster <N> has no localized dipoles in the selection. Line 184 also writes all three keys (cluster, clusters, comps) into command_kwargs, so dipoles records unused cluster=1 and comps=[1] from clust_comp, while componentdipoles records unused clusters from clus_list (and passes clusters=[None] if cluster is omitted in an API call).
    Suggested fix: for componentdipoles, require cluster is not None (raising ValueError("componentdipoles requires a cluster index")) and record only {"cluster": cluster, "comps": comps}. For dipoles, when clusters is None or All cluster centroids (1 in clus_list) is selected, filter selected_clusters to indices >= 2 whose cluster has comps and whose lowercased name does not start with ("parentcluster", "outlier", "notclust") (matching EEGLAB functions/studyfunc/pop_clustedit.m, lines 505 to 511), and record only {"clusters": selected_clusters}.

  • Important: dipoles and componentdipoles never call show_figures, so clicking the dipole buttons in the GUI opens no plot window (src/eegprep/functions/studyfunc/pop_clustedit.py, lines 176 to 183).
    std_dipplot builds figures with plt.figure(...) without displaying them, menu_actions.py discards _figure on return, and eegprep console sessions turn interactive mode off (plt.ioff() in console.py, line 891) because pop_* functions display via show_figures(). In addition, dipmode="apart" creates one figure per cluster, so figure = figures[0] if figures else None drops the remaining figures if nothing displays figures.
    Suggested fix: import show_figures from eegprep.functions.popfunc.plot_utils and call show_figures(figures) after std_dipplot(...), matching pop_dipplot.py (line 64) and pop_chanplot.py (line 72).

  • Important: Outlier prefix checks match "outliers" but miss "outlier <N>" clusters from pop_clust / std_createclust (src/eegprep/functions/studyfunc/pop_clustedit.py, lines 85 and 101).
    std_moveoutlier and std_rejectoutliers name outlier clusters "Outliers ...", whereas std_createclust (and EEGLAB std_createclust.m, line 166) names k-means outlier clusters "outlier 1" (singular). Checking .startswith(("outliers", ...)) therefore offers "outlier 1" as a destination in Reassign selected component(s) and allows renaming it in Rename selected cluster. Also, if the selected source cluster in movecomp has child clusters, pop_clustedit opens the destination dialog first and only fails inside std_movecomp after confirmation.
    Suggested fix: match "outlier" instead of "outliers" (consistent with _cluster_utils.py, line 213), and return cancelled before opening the destination dialog when cluster is None, cluster == 1, not comps, or targets[cluster - 1]["child"] is non-empty.

Nits

  • Nit: Dipole plot parameters always resets the dropdown to apart (src/eegprep/functions/studyfunc/pop_clustedit.py, line 133).
    ControlSpec("popupmenu", "|".join(DIP_MODES), tag="mode", value=1) ignores any existing STUDY["etc"]["dipparams"]["mode"]. Initialize value from the stored mode index when present so reopening Params preserves the current choice.

  • Nit: has_dipoles can raise or misclassify non-list dipfit["model"] values (src/eegprep/functions/studyfunc/pop_clustedit.py, lines 220 to 222).
    len(eeg["dipfit"].get("model", [])) raises TypeError if model is None, treats a string template name or rejected empty dipole entries (posxyz == []) as localized dipoles, and misses a 1-IC dict struct. Reusing localized_components(eeg) from eegprep.plugins.dipfit._utils handles all of those cases.

Test gaps

  • Dipole actions and GUI button enablement (tests/test_study_clustering.py).
    The new tests cover API create, GUI movecomp filtering, and missing dipmode validation, but none exercise action="dipoles", action="componentdipoles", action="dipparams" with a valid mode, or has_dipoles in pop_clustedit_dialog_spec. Add a test with localized dipfit models that runs action="create" followed by GUI action="dipoles" on the default clus_list=[1] selection and verifies that only non-empty, non-outlier child clusters are plotted.

EEGLAB parity notes

  • vertexpand=2.1 in supergui.py (offset = control.vertexpand - 1, height control.vertexpand * height) matches EEGLAB functions/guifunc/supergui.m (lines 302 to 304) and functions/studyfunc/pop_clustedit.m (line 392).
  • EEGLAB pop_dipparams.m configures MRI projection and density toggles (density, projlines, centrline, projimg, axistight), whereas EEGPrep's dipparams action configures std_dipplot's display mode (apart, together, multicolor, centroid) for the standalone 3D Matplotlib view and documents this in src/eegprep/resources/help/pop_clustedit.md.

Tests run in a detached worktree (tests/test_study_clustering.py, tests/test_study_end_to_end.py, tests/test_gui_pop_study.py, tests/test_gui_geometry.py, tests/test_guifunc_primitives.py, tests/test_guifunc_pophelp_chansel.py, tests/test_study_dipplot_eeglab_tests.py): 213 passed, 67 skipped (Linux-measured MATLAB geometry references on macOS), 9 deselected. Checked for correctness bugs, EEGLAB parity, data structure compatibility, changed-behavior tests, and CLAUDE.md/AGENTS.md compliance.

@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. One remaining issue in componentdipoles corrupts the stored cluster dipole centroid and hides component dipoles when dipparams is set to centroid.
  • Highest-risk area: action="componentdipoles" in src/eegprep/functions/studyfunc/pop_clustedit.py.
  • Merge recommendation: Needs changes.

Blocking

None.

Important

  • Important: componentdipoles forwards dipparams["mode"] instead of mode="comps" and overwrites STUDY.cluster[cluster - 1]["dipole"] with the selected subset (src/eegprep/functions/studyfunc/pop_clustedit.py, lines 199 to 205).
    pop_clustedit calls study, _, figures = std_dipplot(study, datasets, clusters=[cluster], comps=comps, mode=study.get("etc", {}).get("dipparams", {}).get("mode")). Two bugs follow from this call:
    1. When the user sets Display mode to "centroid" via Params (action="dipparams"), std_dipplot sets include_dipoles = (mode != "centroid"), so Plot dipole(s) draws zero component dipoles and shows only a "centroid" marker computed from comps. Even in "apart" or default mode, std_dipplot draws a "<cluster> centroid" diamond at the subset average (on top of the component when one component is selected). In EEGLAB functions/studyfunc/std_dipplot.m (line 27 and lines 114 to 120), 'mode' is ignored when 'comps' is passed, and EEGPrep's std_dipplot provides mode="comps" specifically to plot component dipoles without a centroid marker.
    2. std_dipplot writes selection["centroid"] (computed only over comps) back into study["cluster"][cluster - 1]["dipole"]. Calling action="componentdipoles" with comps=[1] after action="dipoles" therefore replaces the full cluster centroid with component 1's coordinates, and menu_actions.py saves that modified STUDY into the session. In EEGLAB std_plotcompdip (functions/studyfunc/std_dipplot.m, lines 626 to 630), STUDY.cluster(cls).dipole is computed over the full cluster only when missing and is never overwritten by a component subset.
      Suggested fix: pass mode="comps" to std_dipplot in the componentdipoles branch and do not overwrite study with the subset centroid returned by that call (for example, _unused, _, figures = std_dipplot(study, datasets, clusters=[cluster], comps=comps, mode="comps"), optionally populating study["cluster"][cluster - 1]["dipole"] via std_dipplot(study, datasets, clusters=[cluster], plot=False) first only if "dipole" is not already present).

Nits

None.

Test gaps

  • Component dipole plotting under dipmode="centroid" and cluster centroid preservation (tests/test_study_clustering.py, lines 682 to 694).
    test_clustedit_dipole_actions_filter_all_centroids_and_record_minimal_history discards _comp_study and checks only comp_fig is not None. Set plotted["etc"]["dipparams"] = {"mode": "centroid"} before the action="componentdipoles" call and assert both that comp_fig.axes[0] labels the selected component dipole ("Cls 1: S01 IC2 (RV 4.0%)") rather than "Cls 1 centroid" and that _comp_study["cluster"][2]["dipole"]["posxyz"] still equals plotted["cluster"][2]["dipole"]["posxyz"].

EEGLAB parity notes

  • vertexpand=2.1 in supergui.py (offset = control.vertexpand - 1, height control.vertexpand * height) matches EEGLAB functions/guifunc/supergui.m (lines 302 to 304) and functions/studyfunc/pop_clustedit.m (line 392).
  • Filtering All cluster centroids in _dipole_all_clusters to non-empty clusters whose names do not start with ("parentcluster", "outlier", "notclust"), and matching singular "outlier" prefixes from std_createclust, matches EEGLAB functions/studyfunc/pop_clustedit.m (lines 505 to 511) and functions/studyfunc/std_createclust.m (line 166).

Tests run in a detached worktree at commit c920cf815c7539c9868fe99d7ac81fb419adc763 (tests/test_study_clustering.py, tests/test_study_end_to_end.py, tests/test_study_dipplot_eeglab_tests.py, tests/test_gui_pop_study.py, tests/test_gui_geometry.py, tests/test_guifunc_primitives.py, plus ruff check on the modified Python files): 215 passed, 70 skipped (MATLAB geometry references measured on Linux), 7 deselected, and ruff check passed. Checked for correctness bugs, EEGLAB parity, data structure compatibility, tests for changed behavior, and CLAUDE.md/AGENTS.md compliance.

@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. Checked pop_clustedit actions (create, rename, movecomp, dipoles, componentdipoles, dipparams), supergui vertexpand layout, dialog specs, history command generation, documentation, and changed tests at commit aca3f837b6d1c35297f7a781f500727e1e096956.
  • Highest-risk area: None identified.
  • Merge recommendation: Safe to merge.

Blocking

None.

Important

None.

Nits

None.

Test gaps

None.

EEGLAB parity notes

  • vertexpand=2.1 in supergui.py shifts the vertical origin by (vertexpand - 1) * height and scales height by vertexpand, matching EEGLAB functions/guifunc/supergui.m (lines 302 to 304) and functions/studyfunc/pop_clustedit.m (line 392).
  • action="componentdipoles" populates STUDY.cluster[cluster - 1]["dipole"] over the full cluster when missing and plots selected component dipoles with mode="comps" without overwriting the stored cluster centroid, matching EEGLAB std_plotcompdip in functions/studyfunc/std_dipplot.m (lines 626 to 635).
  • _dipole_all_clusters and outlier guards exclude ParentCluster, Notclust, singular and plural outlier prefixes, and empty clusters, matching EEGLAB functions/studyfunc/pop_clustedit.m (lines 505 to 511 and lines 656 to 660) and functions/studyfunc/std_createclust.m (line 166).

Tests run in a detached worktree at commit aca3f837b6d1c35297f7a781f500727e1e096956 (tests/test_study_clustering.py, tests/test_study_end_to_end.py, tests/test_study_dipplot_eeglab_tests.py, tests/test_gui_pop_study.py, tests/test_gui_geometry.py, tests/test_guifunc_primitives.py, tests/test_guifunc_pophelp_chansel.py, plus ruff check and ruff format --check on the modified Python files): 226 passed, 70 skipped (MATLAB geometry references measured on Linux), 9 deselected, and ruff checks passed. Checked for correctness bugs, EEGLAB parity, data structure compatibility, tests for changed behavior, and CLAUDE.md/AGENTS.md compliance.

@arnodelorme
arnodelorme changed the base branch from agent/issue-973-precomp to develop December 1, 2026 17:45
@arnodelorme
arnodelorme merged commit 99efaa6 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.

1 participant