Repository navigation
Phase 5c STUDY component clustering - #90
suraj-ranganath merged 5 commits into
Conversation
|
Claude finished @suraj-ranganath's task in 6m 45s —— View job PR Review: Phase 5c STUDY component clustering
SummarySolid Phase 5c implementation that respects the explicit Phase 5b coordination contract ( Higher-priority correctness / parity concerns
Lower-priority / ergonomics
Things I checked that look good
No blocking issues — the findings above are worth a follow-up pass before relying on this in MATLAB-parity workflows, especially items 2–4 which affect cluster hierarchy semantics. |
| if clus_num < 2: | ||
| clus_num = 2 | ||
| if clus_num > data.shape[0]: | ||
| raise ValueError("Number of clusters cannot exceed the number of preclustered components") |
There was a problem hiding this comment.
Silently coercing clus_num < 2 to 2 (line 67) is surprising for an API caller — they may have intentionally passed 1 (or 0) and expect a clear failure. The next branch on line 68 already raises when clus_num is too large; this should symmetrically raise for clus_num < 2 instead of mutating user input. EEGLAB's pop_clust errors out on clusters < 2 as well.
| if clus_num < 2: | |
| clus_num = 2 | |
| if clus_num > data.shape[0]: | |
| raise ValueError("Number of clusters cannot exceed the number of preclustered components") | |
| if clus_num < 2: | |
| raise ValueError("Number of clusters must be at least 2") | |
| if clus_num > data.shape[0]: | |
| raise ValueError("Number of clusters cannot exceed the number of preclustered components") |
| if not new.get("parent"): | ||
| new["parent"] = list(old.get("parent") or []) |
There was a problem hiding this comment.
Quietly inheriting the destination cluster's parent from the source cluster diverges from EEGLAB's std_movecomp, which never edits parent membership. Two real consequences:
- A cluster that was deliberately reparented (e.g., after a manual edit) will silently regain
old's parent the first time a component is moved in. std_moveoutlierandpop_clustedit(action="movecomp")both route through here, so an outlier cluster created and later renamed/reparented can have its parent overwritten by the nextmoveoutliercall.
Recommend dropping this fallback (or making it an explicit parameter) so callers who want a destination parent re-write opt in.
| def _find_outlier_cluster(study: dict[str, Any], cluster_index: int) -> int: | ||
| cluster_name = str(cluster_at(study, cluster_index).get("name") or "") | ||
| prefix = f"outliers {cluster_name} ".lower() | ||
| for index, cluster in enumerate(cluster_list(study), start=1): | ||
| if str(cluster.get("name") or "").lower().startswith(prefix): | ||
| return index | ||
| return 0 |
There was a problem hiding this comment.
_find_outlier_cluster keys off the cluster's current display name. Once the user renames cluster 2 from Cls 2 to (e.g.) Alpha 2, the existing outlier child created earlier under the prefix Outliers Cls 2 … will no longer be matched, and the next std_moveoutlier(STUDY, ALLEEG, 2, comps) call silently creates a second outlier cluster (Outliers Alpha 2 N). That breaks the EEGLAB invariant that a parent cluster has at most one outlier child.
Two viable fixes:
- Persist a back-reference (e.g.,
cluster["outlier_child"] = "Outliers Cls 2 5") when creating the outlier child, and look that up here instead. - Match outlier children by their
parentfield instead of by name-prefix.
Either prevents the rename → duplicate-outlier regression and is consistent with EEGLAB's behavior where outlier children stay paired with their source through rename.
| new_number = next_cluster_number(clusters) | ||
| entry: dict[str, Any] = { | ||
| "name": f"{name} {new_number}", | ||
| "sets": sets[:, order].tolist(), | ||
| "comps": comps[order].tolist(), | ||
| "parent": parents, | ||
| "child": [], | ||
| "algorithm": ["manual_merge", merge_indices.tolist()], | ||
| "preclust": {"preclustparams": [], "preclustdata": []}, | ||
| } | ||
| if merged_data: | ||
| entry["preclust"] = { | ||
| "preclustparams": deepcopy( | ||
| (cluster_at(study, int(merge_indices[0])).get("preclust") or {}).get("preclustparams", []) | ||
| ), | ||
| "preclustdata": np.concatenate(merged_data, axis=0)[order, :].tolist(), | ||
| } | ||
| clusters.append(entry) | ||
| for index in merge_indices: | ||
| clusters[int(index) - 1].setdefault("child", []).append(entry["name"]) |
There was a problem hiding this comment.
The merge produces a non-tree hierarchy that diverges from EEGLAB:
- The new merged cluster's
parentis the list of merged sibling cluster names (lines 56-57), not the common upstream parent (e.g.,ParentCluster). - Symmetrically each merged source cluster gets the merged cluster appended to its
childlist (lines 70-71), making siblings into each other's parents/children.
In EEGLAB's std_mergeclust.m the new cluster sits as a child of the shared parent cluster, and the source clusters are not turned into the new cluster's parents. The current behavior will trip downstream code that walks parent/child chains (e.g. cluster plot, design selection, future pop_clustedit traversals) and breaks the "single ParentCluster at the root" assumption used elsewhere in this same module.
Suggest: set entry["parent"] = list(parent_cluster_names) to the upstream parent (look it up via the first source cluster's parent), and add the new cluster as a child of that parent only, not of each source cluster.
| def _mark_outliers(data: np.ndarray, labels: np.ndarray, centers: np.ndarray, threshold: float) -> np.ndarray: | ||
| output = labels.copy() | ||
| for label in sorted(set(labels.tolist())): | ||
| rows = np.flatnonzero(labels == label) | ||
| distances = np.sum((data[rows] - centers[label - 1]) ** 2, axis=1) | ||
| spread = float(np.std(distances)) | ||
| if spread == 0: | ||
| continue | ||
| output[rows[distances > spread * threshold]] = 0 | ||
| return output |
There was a problem hiding this comment.
Two concerns in the outlier detection:
-
distanceshere are squared distances (sum((x - c)**2)).spread = std(distances)therefore measures variance of squared distances, not std of distances. Comparingsquared_distance > spread * thresholduses inconsistent units. EEGLAB'spop_clustoutlier path compares Euclidean distance tostd(distance) * threshold. The current formula will mark fewer/more outliers than expected for a given threshold and will not be intuitively comparable to MATLAB output. -
The
outliers=float("inf")default is correct for "no outliers", but consider assertingthreshold > 0defensively (passing-1would silently mark everything as outlier).
Suggested fix:
| def _mark_outliers(data: np.ndarray, labels: np.ndarray, centers: np.ndarray, threshold: float) -> np.ndarray: | |
| output = labels.copy() | |
| for label in sorted(set(labels.tolist())): | |
| rows = np.flatnonzero(labels == label) | |
| distances = np.sum((data[rows] - centers[label - 1]) ** 2, axis=1) | |
| spread = float(np.std(distances)) | |
| if spread == 0: | |
| continue | |
| output[rows[distances > spread * threshold]] = 0 | |
| return output | |
| def _mark_outliers(data: np.ndarray, labels: np.ndarray, centers: np.ndarray, threshold: float) -> np.ndarray: | |
| output = labels.copy() | |
| for label in sorted(set(labels.tolist())): | |
| rows = np.flatnonzero(labels == label) | |
| distances = np.linalg.norm(data[rows] - centers[label - 1], axis=1) | |
| spread = float(np.std(distances)) | |
| if spread == 0: | |
| continue | |
| output[rows[distances > spread * threshold]] = 0 | |
| return output |
| centroid = np.mean(data, axis=0, keepdims=True) | ||
| distances = np.sum((data - centroid) ** 2, axis=1) | ||
| spread = float(np.std(distances)) | ||
| if spread == 0: | ||
| continue | ||
| outliers = np.flatnonzero(distances > spread * float(th)) + 1 |
There was a problem hiding this comment.
Same units mismatch as pop_clust._mark_outliers (distances are squared, but threshold is applied to std(distances) — a variance-like quantity rather than a length scale). For consistency with the user-visible threshold arg of "outlier std" units, compute the Euclidean distance to the centroid and take its std:
distances = np.linalg.norm(data - centroid, axis=1)
spread = float(np.std(distances))Otherwise this helper and pop_clust.outliers=… apply different thresholds for the same conceptual setting.
| study = deepcopy(study) | ||
| study.setdefault("etc", {}).setdefault("eegprep", {}) | ||
| preclust = { | ||
| "preclustdata": clustdata.tolist(), | ||
| "preclustparams": stored_specs, | ||
| "preclustcomps": _preclust_components(sets, comps), | ||
| "clustlevel": cluster_index, | ||
| } | ||
| study["etc"]["preclust"] = preclust | ||
| study["etc"]["eegprep"]["preclust_contract"] = { | ||
| "component_measure_root": "STUDY.etc.eegprep.component_measures", | ||
| "rows": "STUDY.etc.preclust.preclustcomps", | ||
| } | ||
| study["cluster"][cluster_index - 1]["preclust"] = { | ||
| "preclustparams": stored_specs, | ||
| "preclustdata": clustdata.tolist(), | ||
| } | ||
| study["saved"] = "no" |
There was a problem hiding this comment.
Minor: ensure_parent_cluster (called on line 40) already deepcopies study, so the additional deepcopy(study) here is redundant. Either drop the second deepcopy or move the mutations under the first copy. Not a correctness bug, but a measurable cost for large STUDYs.
| for label in labels_to_make: | ||
| selected = np.flatnonzero(labels == label) | ||
| if selected.size == 0: | ||
| continue | ||
| cluster_name = f"outlier {next_number}" if label == 0 else f"{name} {next_number}" | ||
| entry: dict[str, Any] = { | ||
| "name": cluster_name, | ||
| "sets": sets[:, selected].astype(int).tolist(), | ||
| "comps": comps[selected].astype(int).tolist(), | ||
| "parent": [parent_name], | ||
| "child": [], | ||
| "algorithm": algorithm or [], | ||
| "preclust": { | ||
| "preclustparams": deepcopy(preclustparams), | ||
| "preclustdata": preclustdata[selected, :].tolist() if preclustdata.size else [], | ||
| }, | ||
| } | ||
| clusters.append(entry) | ||
| parent["child"].append(cluster_name) | ||
| next_number += 1 |
There was a problem hiding this comment.
next_number is incremented unconditionally across both real and outlier child clusters. When a label set contains 0 (outliers), the first child becomes outlier 1 and the next real cluster becomes Cls 2 (skipping Cls 1). EEGLAB numbers Cls N independently from outlier numbering — outliers use their own counter, and Cls numbering starts from the next available Cls-prefixed integer.
Suggest tracking two counters (one for name clusters, one for outlier clusters) so the resulting cluster names line up with EEGLAB's Cls 1, Cls 2, … + outlier 1, outlier 2, … rather than interleaving.
| if gui: | ||
| result = inputgui(pop_clustedit_dialog_spec(study), renderer=renderer) | ||
| if result is None: | ||
| return (study, "", None) if return_com else study | ||
| action = _action_from_gui(result.get("action")) | ||
| cluster = _optional_int(result.get("cluster")) | ||
| to_cluster = _optional_int(result.get("to_cluster")) | ||
| comps = numeric_vector(result.get("comps", []), dtype=int).tolist() | ||
| clusters = numeric_vector(result.get("clusters", []), dtype=int).tolist() | ||
| name = str(result.get("name") or name) | ||
| threshold = float(numeric_vector(result.get("threshold", threshold), dtype=float)[0]) | ||
|
|
There was a problem hiding this comment.
When the dialog returns a result, threshold = float(numeric_vector(result.get("threshold", threshold), dtype=float)[0]) will raise IndexError if the user clears the threshold edit and submits (numeric_vector("", dtype=float) returns an empty array). The same pattern is safer elsewhere via _optional_int — consider a _optional_float (or a fallback to the default) so a non-rejection action like rename/plot doesn't fail because of an unrelated empty threshold field in the same dialog.
| def cluster_at(study: dict[str, Any], cluster_index: int) -> dict[str, Any]: | ||
| """Return a 1-based cluster entry.""" | ||
| clusters = cluster_list(study) | ||
| if cluster_index < 1 or cluster_index > len(clusters): | ||
| raise ValueError(f"cluster index must be 1-based and within 1..{len(clusters)}") | ||
| return clusters[cluster_index - 1] |
There was a problem hiding this comment.
cluster_at returns a normalized deepcopy (via cluster_list → normalize_cluster → deepcopy). Several callers (e.g., std_renameclust, std_movecomp, std_mergeclust) read fields from this copy and then re-fetch cluster_list(study) and assign by index. That works but is non-obvious and easy to break: any future caller that does cluster_at(study, idx)["comps"] = ... will silently no-op.
Either document the copy semantics in the docstring ("Returns a normalized snapshot; modifications do not propagate") or return a live reference (cluster_list first, then index) so callers can mutate intuitively.
|
🤖 Updated the Phase 5c dialog visual parity pass after checking the local EEGLAB MATLAB sources for Changes pushed in
Verification:
Updated side-by-side captures: |





Motivation
Closes #83. Implements Phase 5c STUDY component preclustering, clustering, cluster editing, and cluster plotting hooks on top of the merged Phase 5a/5b STUDY/session and measure-precompute contracts.
Implementation summary
std_preclust/pop_preclustfor building EEGLAB-shapedSTUDY.etc.preclustmatrices from ICA scalp maps, dipoles, and Phase 5b cached component measures.pop_clustk-means clustering plusstd_createclustto write EEGLAB-likeSTUDY.clusterparent/child structures.pop_clusteditandstd_clustplotas the GUI/API/console cluster edit and plot hooks.pop_preclust,pop_clust, andpop_clustedit; after merging Phase 5b,pop_precompis also an implemented Study action.origin/feature/study-standalone-completionand resolved Phase 5b/5c conflicts by adapting preclustering to read the landed parent-cluster measure cache.Claude review and completion-audit follow-up
Clsnumbering, blank GUI threshold handling,cluster_atcopy semantics, redundantstd_preclustcopying, destination-parent preservation, and outlier reuse after source-cluster rename.preclustdata, and direct bareeegprep-consolecoverage forpop_preclust,pop_clustedit(action="rename"), andpop_clustedit(action="plot").std_mergeclust's source-cluster parent/child hierarchy because local EEGLABstd_mergeclust.muses that model; the parity decision is documented in.notes/implementation-notes.html.Phase 5b coordination contract
Phase 5c does not implement broad measure precompute. After Phase 5b merged, ERP, spectrum, ERSP, and ITC clustering inputs are read from the parent cluster cache created by:
The concrete source is
STUDY["cluster"][0], using EEGLAB-style cached measure fields such aserpdata,erptimes,specdata,specfreqs,erspdata,ersptimes,erspfreqs,itcdata,itctimes, anditcfreqs. Phase 5b stores dataset and component axes separately; Phase 5c expands those 1-based axes into row-alignedsets/compsbefore writingSTUDY["etc"]["preclust"]. The contract and merge decision are documented in.notes/implementation-notes.htmland covered bytests/test_study_clustering.pyplustests/test_study_measures.py.Tests and verification
uv run --no-sync pytest tests/test_study_clustering.py tests/test_study_measures.py- 28 passeduv run --no-sync pytest tests/test_plugin_menu.py tests/test_menu_placeholder_inventory.py tests/test_console_workspace.py tests/test_gui_pop_study.py tests/test_study_metadata.py tests/test_study_clustering.py tests/test_study_measures.py- 129 passeduv run --no-sync ruff check .- passeduv run --no-sync ruff format --check .- passeduv run --no-sync ty check- passedEEGPREP_SKIP_MATLAB=1 uv run --no-sync pytest -m "not slow"- 1615 passed, 228 skipped, 11 deselected, 163 warnings./pre-commit.py- passed on 30 staged files after the Phase 5b merge resolutionParity and GUI QA
/Users/suraj/Desktop/eegprep/src/eegprep/eeglaband/Users/suraj/Desktop/eeglabforstd_preclust,pop_preclust,pop_clust,std_createclust,pop_clustedit, and cluster edit helpers.std_createclustbehavior with local MATLAB R2026a command-line execution against the vendored EEGLAB source while auditing the phase scope.pop_preclust_dialogpop_clust_dialogpop_clustedit_dialog.visual-parity/and intentionally not committed.pop_clustQt dialog and canceled it cleanly.pop_preclust->pop_clust->pop_clustedit(action="rename")throughEEGPrepConsoleWorkspaceand verifiedCURRENTSTUDY,STUDY.cluster, andLASTCOMsync; automated tests now also cover bare consolepop_preclustandpop_clustedit(action="plot").Open risks
pop_clusteditexposes Phase 5c edit/plot hooks but does not port every EEGLAB plot button to full measure visualizations; Phase 5b now supplies the underlying measure plotting surface used for later integration.