Skip to content

Phase 5c STUDY component clustering - #90

Merged
suraj-ranganath merged 5 commits into
feature/study-standalone-completionfrom
phase/5c-study-clustering
May 30, 2026
Merged

suraj-ranganath merged 5 commits into
feature/study-standalone-completionfrom
phase/5c-study-clustering

Conversation

@suraj-ranganath

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

Copy link
Copy Markdown
Member

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

  • Added std_preclust/pop_preclust for building EEGLAB-shaped STUDY.etc.preclust matrices from ICA scalp maps, dipoles, and Phase 5b cached component measures.
  • Added deterministic pop_clust k-means clustering plus std_createclust to write EEGLAB-like STUDY.cluster parent/child structures.
  • Added cluster editing helpers for rename, merge, component reassignment, outlier movement, and distance-based outlier rejection.
  • Added pop_clustedit and std_clustplot as the GUI/API/console cluster edit and plot hooks.
  • Wired the Study menu, public lazy exports, help resources, docs, and visual parity capture cases.
  • Removed Phase 5c placeholders for pop_preclust, pop_clust, and pop_clustedit; after merging Phase 5b, pop_precomp is also an implemented Study action.
  • Merged origin/feature/study-standalone-completion and resolved Phase 5b/5c conflicts by adapting preclustering to read the landed parent-cluster measure cache.

Claude review and completion-audit follow-up

  • Addressed actionable Claude review findings for invalid cluster-count validation, Euclidean outlier thresholds, non-positive threshold errors, independent outlier/Cls numbering, blank GUI threshold handling, cluster_at copy semantics, redundant std_preclust copying, destination-parent preservation, and outlier reuse after source-cluster rename.
  • Re-audited issue Phase 5c: STUDY preclustering, clustering, and cluster editing parity #83 from first principles and added scoped fixes for blank optional numeric fields in clustering GUI submit paths, empty initialization of outlier cluster preclustdata, and direct bare eegprep-console coverage for pop_preclust, pop_clustedit(action="rename"), and pop_clustedit(action="plot").
  • Kept std_mergeclust's source-cluster parent/child hierarchy because local EEGLAB std_mergeclust.m uses 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:

pop_precomp(STUDY, ALLEEG, "components", erp="on", spec="on", ...)

The concrete source is STUDY["cluster"][0], using EEGLAB-style cached measure fields such as erpdata, erptimes, specdata, specfreqs, erspdata, ersptimes, erspfreqs, itcdata, itctimes, and itcfreqs. Phase 5b stores dataset and component axes separately; Phase 5c expands those 1-based axes into row-aligned sets/comps before writing STUDY["etc"]["preclust"]. The contract and merge decision are documented in .notes/implementation-notes.html and covered by tests/test_study_clustering.py plus tests/test_study_measures.py.

Tests and verification

  • uv run --no-sync pytest tests/test_study_clustering.py tests/test_study_measures.py - 28 passed
  • uv 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 passed
  • uv run --no-sync ruff check . - passed
  • uv run --no-sync ruff format --check . - passed
  • uv run --no-sync ty check - passed
  • EEGPREP_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 resolution

Parity and GUI QA

  • Inspected EEGLAB sources under /Users/suraj/Desktop/eegprep/src/eegprep/eeglab and /Users/suraj/Desktop/eeglab for std_preclust, pop_preclust, pop_clust, std_createclust, pop_clustedit, and cluster edit helpers.
  • Rechecked deterministic std_createclust behavior with local MATLAB R2026a command-line execution against the vendored EEGLAB source while auditing the phase scope.
  • Generated EEGLAB and EEGPrep visual parity captures for:
    • pop_preclust_dialog
    • pop_clust_dialog
    • pop_clustedit_dialog
  • Visual artifacts are local under .visual-parity/ and intentionally not committed.
  • Computer Use GUI QA inspected the pop_clust Qt dialog and canceled it cleanly.
  • Console QA ran pop_preclust -> pop_clust -> pop_clustedit(action="rename") through EEGPrepConsoleWorkspace and verified CURRENTSTUDY, STUDY.cluster, and LASTCOM sync; automated tests now also cover bare console pop_preclust and pop_clustedit(action="plot").

Open risks

  • Exact MATLAB k-means label parity is not asserted because sklearn and MATLAB k-means seeding/replicates differ; tests assert deterministic Python behavior and EEGLAB-shaped cluster coverage.
  • pop_clustedit exposes 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.

@claude

claude Bot commented May 30, 2026 •

Copy link
Copy Markdown
Contributor

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


PR Review: Phase 5c STUDY component clustering

  • Read CLAUDE.md / AGENTS.md
  • Diff against origin/feature/study-standalone-completion
  • Review new studyfunc modules
  • Review menu wiring, lazy exports, visual capture, help, docs
  • Cross-check parity against EEGLAB (note: vendored MATLAB tree is absent in CI; review based on PR description + Python implementation)
  • Review tests
  • Post inline findings + summary

Summary

Solid Phase 5c implementation that respects the explicit Phase 5b coordination contract (STUDY.etc.eegprep.component_measures). New pop_preclust/pop_clust/pop_clustedit plus the std_* helpers, menu wiring, lazy exports, visual-parity cases, and help resources all hang together cleanly, and the test coverage exercises the GUI cancel paths, history replay, and console workspace sync. Code style follows the existing module conventions (Google docstrings, top-level imports, no compatibility shims). I left 9 inline findings, none blocking — they range from correctness gaps that diverge from EEGLAB semantics to API ergonomics nits.

Higher-priority correctness / parity concerns

  1. pop_clust.py:66-69 — clus_num < 2 is silently coerced to 2 instead of erroring (EEGLAB errors).
  2. std_mergeclust.py:52-71 — merged cluster's parent is set to the source clusters themselves, and each source cluster gets the merge as a child. This produces a non-tree hierarchy that diverges from EEGLAB and will trip downstream parent/child walkers.
  3. std_moveoutlier.py:53-59 — _find_outlier_cluster keys off the current cluster display name. After a rename, the existing outlier child won't be found and a duplicate outlier cluster is created on the next move.
  4. pop_clust.py:124-133 + std_rejectoutliers.py:37-42 — outlier detection compares squared distances to std(squared distances) * threshold. The user-visible threshold argument is documented in "std" units, but the units don't line up. Recommend switching to Euclidean distances (np.linalg.norm(..., axis=1)).
  5. std_movecomp.py:60-61 — destination cluster silently inherits source cluster's parent list when its parent is empty. EEGLAB's std_movecomp never touches parent.

Lower-priority / ergonomics

  1. std_createclust.py:53-72 — shared counter interleaves Cls N and outlier N numbering; should be two counters to match EEGLAB.
  2. pop_clustedit.py:39-50 — threshold field is parsed unconditionally on every GUI submit; can IndexError for non-rejectoutliers actions if the user clears the field.
  3. _cluster_utils.py:91-96 — cluster_at returns a deepcopy; document that or return a live reference. Easy to misuse.
  4. std_preclust.py:67-84 — redundant deepcopy (ensure_parent_cluster already deepcopies).

Things I checked that look good

  • Lazy export wiring in src/eegprep/__init__.py (alphabetized, no duplicates).
  • Menu placeholder cleanup leaves pop_precomp as the only remaining Phase 5b placeholder, with pop_eegplot correctly carrying the eegbrowser exclusion.
  • pop_* wrappers all support return_com=True and emit replayable history commands (python_literal handles float('inf'), lists of dict specs, numpy arrays).
  • visual_capture.py adds three new cluster-dialog captures with sensible demo STUDY fixtures.
  • Tests exercise: parent matrix from scalp maps, Phase 5b ERP contract path, missing-measure / missing-ICA error paths, deterministic k-means coverage, rename/merge/moveoutlier/plot edit hooks, history replay through exec(...), bare pop_clust auto-store via EEGPrepConsoleWorkspace, and the GUI cancel paths for all three dialogs.
  • Help resources cleanly reference the Phase 5b contract and call out unimplemented EEGLAB clustering branches (NN / affinity propagation / optimal k-means).
  • Docs (study_workflows.rst) updated with the new precluster→cluster→clustedit example.

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.
| Branch: phase/5c-study-clustering

@suraj-ranganath

Copy link
Copy Markdown
Member Author

🤖 Visual parity side-by-side captures for Phase 5c dialogs. These were generated from local .visual-parity/ artifacts and uploaded with gh attach; the image artifacts are not committed in this PR.

pop_preclust_dialog_side_by_side.png pop_clust_dialog_side_by_side.png
pop_preclust_dialog_side_by_side.png pop_clust_dialog_side_by_side.png
pop_clustedit_dialog_side_by_side.png
pop_clustedit_dialog_side_by_side.png

Comment on lines +66 to +69
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")

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.

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.

Suggested change
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")

Comment on lines +60 to +61
if not new.get("parent"):
new["parent"] = list(old.get("parent") or [])

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.

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_moveoutlier and pop_clustedit(action="movecomp") both route through here, so an outlier cluster created and later renamed/reparented can have its parent overwritten by the next moveoutlier call.

Recommend dropping this fallback (or making it an explicit parameter) so callers who want a destination parent re-write opt in.

Comment on lines +53 to +59
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

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.

_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 parent field 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.

Comment on lines +52 to +71
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"])

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 merge produces a non-tree hierarchy that diverges from EEGLAB:

  • The new merged cluster's parent is 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 child list (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.

Comment on lines +124 to +133
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

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 concerns in the outlier detection:

  1. distances here are squared distances (sum((x - c)**2)). spread = std(distances) therefore measures variance of squared distances, not std of distances. Comparing squared_distance > spread * threshold uses inconsistent units. EEGLAB's pop_clust outlier path compares Euclidean distance to std(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.

  2. The outliers=float("inf") default is correct for "no outliers", but consider asserting threshold > 0 defensively (passing -1 would silently mark everything as outlier).

Suggested fix:

Suggested change
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

Comment on lines +37 to +42
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

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.

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.

Comment on lines +67 to +84
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"

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.

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.

Comment on lines +53 to +72
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

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.

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.

Comment on lines +39 to +50
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])

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 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.

Comment on lines +91 to +96
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]

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.

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.

@suraj-ranganath

Copy link
Copy Markdown
Member Author

🤖 Updated the Phase 5c dialog visual parity pass after checking the local EEGLAB MATLAB sources for pop_preclust.m and pop_clustedit.m.

Changes pushed in af2a054:

  • Matched the EEGLAB row geometry and geomvert layout for both dialogs.
  • Added missing pop_preclust controls: in-dialog double-dipping Help, ERP low-pass, ERSP/ITC frequency ranges, scalp-map mode popup, and disabled-state styling.
  • Reworked pop_clustedit into the EEGLAB design popup, cluster/component listboxes, STATS button, plotting button matrix, and bottom editing button layout.

Verification:

  • uv run --no-sync pytest tests/test_study_clustering.py -> 16 passed
  • uv run --no-sync pytest tests/test_visual_parity.py -> 24 passed
  • uv run --no-sync ruff check . -> passed
  • uv run --no-sync ruff format --check . -> passed
  • uv run --no-sync ty check -> passed
  • EEGPREP_SKIP_MATLAB=1 uv run --no-sync pytest -m "not slow" -> 1615 passed, 228 skipped, 11 deselected

Updated side-by-side captures:

pop_preclust_dialog
pop_preclust_dialog side-by-side

pop_clustedit_dialog
pop_clustedit_dialog side-by-side

@suraj-ranganath
suraj-ranganath merged commit 85ddecc into feature/study-standalone-completion May 30, 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