Skip to content

[STUDY] Implement measure precompute workflows - #91

Merged
suraj-ranganath merged 3 commits into
feature/study-standalone-completionfrom
phase/5b-study-measures
May 30, 2026
Merged

suraj-ranganath merged 3 commits into
feature/study-standalone-completionfrom
phase/5b-study-measures

Conversation

@suraj-ranganath

Copy link
Copy Markdown
Member

Add STUDY precompute, cached measure readers, and cached channel/component plotting so Phase 5b workflows work from API, GUI menus, and the console. Documents the measure storage contract and adds regression coverage for multi-dataset, component, cancel, history, and sample-data paths.

Closes #79

@claude

claude Bot commented May 30, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @suraj-ranganath's task in 7m 2s —— View job


Code review

  • Overall assessment: Looks good with a couple of EEGLAB parity gaps worth flagging.
  • Highest-risk area: std_precomp accepts a design parameter but never actually filters by condition; cached measures average across all trials.
  • Merge recommendation: Safe to merge — none of the findings block this PR, but please consider the parity notes for the follow-up phase.

Blocking

None.

Important

  • EEGLAB parity — design parameter is recorded but unused. src/eegprep/functions/studyfunc/std_precomp.py:80-112 validates design, stores it in measureinfo, and writes it into etc.eegprep.study_measures, but the actual ERP/spec/ERSP/ITC routines (_channel_erp, _component_erp, etc.) average over every trial in every dataset regardless of design conditions. EEGLAB's std_precomp uses the study design to drive condition-specific measure files. Either filter trials/datasets per the selected design cells, or surface this gap in the known_differences of the pop_precomp dialog spec (src/eegprep/functions/studyfunc/pop_precomp.py:91-94) and in the STUDY user guide so EEGLAB users do not misinterpret the cached arrays as condition-specific.

Nits

  • pop_chanplot._popup_index clamps both popups to len(MEASURE_OPTIONS) = 4. src/eegprep/functions/studyfunc/pop_chanplot.py:113-119, 314-319. The mode popup only has two options (Channels/Components); out-of-range values 3 or 4 silently fall back to "channels" via the mode_index == 2 check below. Either split the helper or pass an explicit max so the mode popup clamps to 2.
  • _run_chanplot records empty history and overwrites STUDY on cancel. src/eegprep/functions/guifunc/menu_actions.py:1238-1247 (pre-existing helper, but reused by the new menu wiring). When pop_chanplot returns (STUDY, "", None) on cancel, the dispatcher still calls self.session.STUDY = study and _add_history_from_gui(""), which both echoes and appends an empty command. Mirror the if not command: return short-circuit that _study_action uses for pop_studydesign/pop_precomp.
  • pop_chanplot shallow copy aliases STUDY["etc"]. src/eegprep/functions/studyfunc/pop_chanplot.py:60-61. study = dict(STUDY) followed by study.setdefault("etc", {})["last_chanplot"] = ... mutates the original STUDY's etc dict when it already exists. If the intent is to leave the input untouched, deepcopy etc (or just study["etc"]) before assigning.
  • pop_chanplot._history_command uses value not in (None, []). src/eegprep/functions/studyfunc/pop_chanplot.py:329-331. This raises ValueError: The truth value of an array with more than one element is ambiguous. if a caller passes a numpy array for channels/components. Switch to an is None/len == 0 check, or coerce to list before filtering.
  • Silently accepted EEGLAB options. src/eegprep/functions/studyfunc/std_precomp.py:69-72 swallows interp, savetrials, rmicacomps, rmclust, cell, erpim, erpimparams with no log line. EEGLAB users porting scripts will not notice their options are dropped. A logger.warning("std_precomp: ignoring EEGLAB-only option(s) %s", ...) would make the gap visible without changing behavior.

Test gaps

  • _remove_baseline is not exercised. tests/test_study_measures.py never passes an erpparams={'rmbase': [...]} to std_precomp, so the baseline-subtraction path in src/eegprep/functions/studyfunc/std_precomp.py:476-486 (including the "rmbase does not include any samples" failure) is uncovered. Add a small test that calls std_precomp(..., erpparams={"rmbase": [-100, 0]}) and asserts the pre-stimulus mean is ~0 in the cached ERP.
  • Design parameter behavior is untested. Without a test that pins design=N against expected per-condition results (or explicitly documents the "stored-but-unused" behavior), it is easy for a future change to silently drop the recorded design field.

EEGLAB parity notes

  • See the design-condition gap above. Everything else (field names erpdata/erptimes/specfreqs/erspbase/etc., 1-based inds/comps, parent-cluster storage, STUDY.changrp/STUDY.cluster layout) maps cleanly onto EEGLAB conventions and should feel familiar to EEGLAB users.

Inline suggestions posted on std_precomp.py and pop_chanplot.py. Reviewed for correctness, EEGLAB parity, data structure compatibility, changed-behavior tests, and AGENTS.md compliance.
· Branch: phase/5b-study-measures

@suraj-ranganath

Copy link
Copy Markdown
Member Author

🤖 Problem
Phase 5b needed standalone STUDY measure precompute and cached measure plotting so users could move beyond study metadata into channel/component ERP, spectrum, ERSP, and ITC workflows without depending on the vendored EEGLAB checkout at runtime. The missing pieces were user-facing pop_precomp, cached readers, GUI/menu dispatch, console history replay, and documentation of the measure structures that Phase 5c clustering can consume.

Approach
Added std_precomp/pop_precomp for channel and parent-cluster component measures, storing EEGLAB-named fields such as erpdata, specdata, erspdata, itcdata, erptimes, specfreqs, ersptimes, and erspfreqs directly in STUDY.changrp or STUDY.cluster[0]. Added std_readdata/std_readerp/std_readspec/std_readersp for cached reads, extended pop_chanplot to plot cached channel and component measures while keeping the Phase 4 loaded-data ERP fallback, and wired the Study menu precompute actions through the shared EEGPrepSession history path.

Key code
The main storage contract lives in src/eegprep/functions/studyfunc/std_precomp.py: channel precompute builds one changrp entry per selected channel; component precompute writes the parent cluster with 1-based component ids and optional topo maps. pop_precomp returns replayable Python history commands, GUI cancel returns the original STUDY/ALLEEG plus an empty command, and pop_chanplot records STUDY["etc"]["last_chanplot"] for the last plotted cached measure.

Tests
Focused tests cover multi-dataset channel ERP/spectrum storage and readback, ERSP/ITC axes, component measures and topo storage, missing ICA errors, unknown channels, missing channel-location fallbacks, GUI cancel paths, component-mode plotting, menu dispatch, console auto-store/history replay, sample_data coverage, and visual parity manifest coverage.

Verification
uv run --no-sync pytest tests/test_study_measures.py -q: 9 passed.
uv run --no-sync pytest tests/test_phase4_plot_wrappers.py -q -k "chanplot or dialog_specs": 4 passed, 36 deselected.
uv run --no-sync pytest tests/test_console_workspace.py -q -k "pop_precomp or pop_study_result or pop_savestudy": 3 passed, 70 deselected.
uv run --no-sync pytest tests/test_sample_data_pop_functions.py -q -k "study or precomp": 5 passed, 43 deselected.
uv run --no-sync pytest tests/test_visual_parity.py -q -k "manifest or study": 3 passed, 21 deselected.
uv run --no-sync pytest tests/test_menu_placeholder_inventory.py tests/test_gui_main_window.py tests/test_package_exports.py -q: 249 passed, 8 skipped, 19 subtests passed.
uv run --no-sync ruff check .: passed.
uv run --no-sync ruff format --check .: 376 files already formatted.
uv run --no-sync ty check: passed.
EEGPREP_SKIP_MATLAB=1 uv run --no-sync pytest -m "not slow": 1581 passed, 228 skipped, 11 deselected.
./pre-commit.py: passed for 20 staged files.

Parity and GUI evidence
Inspected EEGLAB pop_precomp/std_precomp/std_readdata/std_readerp/std_readspec/std_readersp/pop_chanplot references from /Users/suraj/Desktop/eegprep/src/eegprep/eeglab. EEGPrep intentionally stores measures in STUDY JSON-safe arrays instead of EEGLAB .dat/.ica sidecars, and component measures stay on the parent cluster until Phase 5c owns clustering. The EEGPrep pop_precomp visual capture succeeds locally at .visual-parity/pop_precomp_dialog/eegprep.png and the capture case is registered. The EEGLAB side-by-side capture was attempted with EEGPREP_EEGLAB_ROOT=/Users/suraj/Desktop/eegprep/src/eegprep/eeglab and timed out after 180 seconds in the MATLAB visual harness, so no side-by-side user attachment is available from this run.

Open risks
No MATLAB Engine is installed in the Python environment, so MATLAB-enabled deterministic parity tests skipped. ERSP/ITC use EEGPrep newtimef-backed deterministic outputs and are shape/axis/contract tested rather than bit-exact against EEGLAB. GUI Agent Flow QA launched the PySide STUDY window, but Computer Use could not attach to Python.app on this machine; the menu dispatch, console synchronization, cancel paths, and visual capture path were verified through tests and terminal-backed probes.

Comment on lines +106 to +112
study.setdefault("etc", {}).setdefault("eegprep", {})["study_measures"] = {
"kind": kind,
"design": int(design),
"computed": computed,
"storage": "STUDY in-memory JSON-safe arrays",
"recompute": "on" if is_on(recompute) else "off",
}

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 — EEGLAB parity gap. design is validated and recorded here, but _channel_erp/_component_erp/_channel_spec/_channel_time_frequency all average over every trial in every dataset; nothing actually filters by the selected design's condition cells. EEGLAB's std_precomp computes condition-specific measure files keyed off the design. Either implement design-aware trial filtering, or call this out explicitly in pop_precomp_dialog_spec.known_differences and the STUDY user guide so EEGLAB users don't read these cached arrays as condition-specific.

Adding a regression test that pins per-condition expected values (or asserts the current "averaged across conditions" behavior with a code comment explaining why) would also lock in the contract for the next phase.

Comment on lines +69 to +72
ignored = {"interp", "savetrials", "rmicacomps", "rmclust", "cell", "erpim", "erpimparams"}
unsupported = sorted(key for key in options if key not in ignored)
if unsupported:
raise ValueError(f"Unknown std_precomp option(s): {', '.join(unsupported)}")

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.

Nit. EEGLAB-only options (interp, savetrials, rmicacomps, rmclust, cell, erpim, erpimparams) are silently dropped. EEGLAB users porting scripts will not notice their flags had no effect. A one-line warning would make the gap visible without changing behavior:

ignored_present = sorted(key for key in options if key in ignored)
if ignored_present:
    logger.warning("std_precomp: ignoring EEGLAB-only option(s): %s", ", ".join(ignored_present))

Comment on lines +60 to +61
study = dict(STUDY)
study.setdefault("etc", {})["last_chanplot"] = last_selection

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.

Nit — aliasing. study = dict(STUDY) is a shallow copy. When STUDY already has an etc dict, setdefault("etc", {}) returns the same dict reference held by the input, and ["last_chanplot"] = ... mutates STUDY["etc"] in place. If the intent is to leave the input untouched, copy etc explicitly:

Suggested change
study = dict(STUDY)
study.setdefault("etc", {})["last_chanplot"] = last_selection
study = dict(STUDY)
study["etc"] = {**(STUDY.get("etc") or {}), "last_chanplot": last_selection}

Comment on lines +314 to +319
def _popup_index(value: Any, default: int) -> int:
try:
index = int(value)
except (TypeError, ValueError):
index = default
return max(1, min(index, len(MEASURE_OPTIONS)))

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.

Nit. _popup_index clamps to len(MEASURE_OPTIONS) = 4 but it's also used for the mode popup at line 114, which only has 2 options (Channels|Components). Out-of-range mode values (3, 4) silently fall through to "channels" via the mode_index == 2 check rather than being clamped to a valid mode index. Either split the helper or accept an explicit maximum argument:

Suggested change
def _popup_index(value: Any, default: int) -> int:
try:
index = int(value)
except (TypeError, ValueError):
index = default
return max(1, min(index, len(MEASURE_OPTIONS)))
def _popup_index(value: Any, default: int, maximum: int = len(MEASURE_OPTIONS)) -> int:
try:
index = int(value)
except (TypeError, ValueError):
index = default
return max(1, min(index, maximum))

and call _popup_index(result.get("mode"), 1, maximum=2) at line 114.

Comment on lines +322 to +332
def _history_command(*, channels: Any, components: Any, measure: str, mode: str) -> str:
pieces = ["STUDY", "ALLEEG"]
kwargs = {
"channels": channels,
"components": components,
"measure": measure,
"mode": mode,
}
rendered = [python_literal(piece) if piece not in {"STUDY", "ALLEEG"} else piece for piece in pieces]
rendered.extend(f"{key}={python_literal(value)}" for key, value in kwargs.items() if value not in (None, []))
return f"pop_chanplot({', '.join(rendered)})"

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.

Nit. value not in (None, []) raises ValueError: The truth value of an array with more than one element is ambiguous. if a caller passes a numpy array for channels/components. The GUI flow normalizes to lists via .tolist() at line 116-117, so this is fine in practice, but the public API accepts Any for channels/components. Suggest coercing or using an explicit empty/None check:

def _is_empty_arg(value: Any) -> bool:
    if value is None:
        return True
    if isinstance(value, np.ndarray):
        return value.size == 0
    if isinstance(value, (list, tuple)):
        return len(value) == 0
    return False

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