Skip to content

Implement STUDY metadata and design workflow - #89

Merged
suraj-ranganath merged 3 commits into
feature/study-standalone-completionfrom
phase/5a-study-metadata-design
May 30, 2026
Merged

suraj-ranganath merged 3 commits into
feature/study-standalone-completionfrom
phase/5a-study-metadata-design

Conversation

@suraj-ranganath

Copy link
Copy Markdown
Member

Summary

  • add STUDY metadata helpers for creation, datasetinfo sync, consistency checks, save/load/resave, and design editing
  • wire STUDY/CURRENTSTUDY synchronization through EEGPrepSession, GUI menu actions, and eegprep-console bare pop result handling
  • add STUDY GUI specs, help markdown, docs exports, visual parity cases, and focused tests

Verification

  • PYTHONPATH=src UV_PROJECT_ENVIRONMENT=/Users/suraj/Desktop/eegprep/.venv uv run --no-sync ruff check .
  • PYTHONPATH=src UV_PROJECT_ENVIRONMENT=/Users/suraj/Desktop/eegprep/.venv uv run --no-sync ruff format --check .
  • PYTHONPATH=src UV_PROJECT_ENVIRONMENT=/Users/suraj/Desktop/eegprep/.venv uv run --no-sync ty check
  • PYTHONPATH=src UV_PROJECT_ENVIRONMENT=/Users/suraj/Desktop/eegprep/.venv uv run --no-sync pytest tests/test_gui_pop_study.py tests/test_visual_parity.py
  • PYTHONPATH=src UV_PROJECT_ENVIRONMENT=/Users/suraj/Desktop/eegprep/.venv EEGPREP_SKIP_MATLAB=1 uv run --no-sync pytest -m "not slow"
  • EEGPREP_EEGLAB_ROOT=/Users/suraj/Desktop/eeglab PYTHONPATH=src UV_PROJECT_ENVIRONMENT=/Users/suraj/Desktop/eegprep/.venv uv run --no-sync python tools/visual_parity/capture.py --case pop_study_dialog --target eeglab --timeout 180
  • EEGPREP_EEGLAB_ROOT=/Users/suraj/Desktop/eeglab PYTHONPATH=src UV_PROJECT_ENVIRONMENT=/Users/suraj/Desktop/eegprep/.venv uv run --no-sync python tools/visual_parity/capture.py --case pop_studydesign_dialog --target eeglab --timeout 180

Closes #65

@claude

claude Bot commented May 30, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @suraj-ranganath's task in 12m 21s —— View job


Code review

  • Overall assessment: Needs changes — two findings affect data integrity (Save STUDY drops datasets; Load STUDY silently realigns metadata).
  • Highest-risk area: STUDY save/load round-trip in pop_savestudy / pop_loadstudy and the menu dispatch in menu_actions._study_action.
  • Merge recommendation: Needs changes.

Blocking

  • pop_savestudy receives the current EEG, not ALLEEG — menu_actions.py:701 passes self.session.EEG (single dataset) instead of self.session.ALLEEG. pop_savestudy then runs std_checkset(STUDY, as_alleeg_list(EEG)) (pop_savestudy.py:41-42) and sync_datasetinfo rebuilds STUDY.datasetinfo from that one dataset, so a multi-dataset STUDY is saved with only the currently selected dataset's row. The recorded history string (pop_savestudy(STUDY, EEG, ...) in pop_savestudy.py:50-57) is likewise unreplayable. Pass self.session.ALLEEG and emit STUDY = pop_savestudy(STUDY, ALLEEG, ...).

  • pop_loadstudy silently drops missing datasets and realigns metadata to surviving rows — pop_loadstudy.py:62-72 continues past any file that doesn't resolve, then calls std_checkset(study, alleeg) with the shortened list. sync_datasetinfo (_study_utils.py:91-105) reads existing[index-1] keyed by the loaded enumeration, so if file 2 of 5 is missing, the saved metadata for the original positions 3-5 is applied to surviving rows 2-4. Fields kept only in STUDY (session, run, comps, and custom factors) propagate this shift. No warning is surfaced. Either preserve datasetinfo row alignment when partial-loading (placeholder for missing files) or fail loudly with the missing paths.

Important

  • pop_study "Create new STUDY" menu path skips the dialog — menu_actions.py:751 calls pop_study(None, self.session.ALLEEG) without gui=True; pop_study.py:44 defaults use_gui to False. Mirror the pop_study:edit branch.

  • pop_studydesign opens the GUI on non-interactive calls — pop_studydesign.py:39 sets use_gui = is_on(gui) if gui is not None else not bool(options). A scripted pop_studydesign(STUDY, ALLEEG, 2) launches Qt. Default use_gui to False.

  • pop_study dialog truncates datasetinfo to 10 rows — pop_study.py:113 and 135 slice [:10]. Rows 11+ aren't editable from the GUI, and known_differences doesn't mention the cap. EEGLAB's pop_study shows every dataset.

  • Dead return_com parameters — pop_loadstudy.py:20, pop_savestudy.py:22, pop_studyerp.py:13, pop_studywizard.py:15 declare return_com: bool = False but never branch on it; the functions unconditionally return a tuple. Either branch on it (matching std_editset/pop_reref) or drop it.

  • studyfunc/__init__.py eagerly imports every submodule — Sibling subpackages (popfunc, adminfunc, sigprocfunc, guifunc) are docstring-only. The eager imports pull in numpy and Qt, and force a circular-import workaround in std_checkset.py:22. Match the sibling pattern.

Nits

  • std_checkset.options is dead — std_checkset.py:13,18 discards options with _ = options. Remove or wire through.

  • _is_study_selection heuristic is broad — console.py:1202-1207 matches on any(key in value for key in ("datasetinfo", "design", "currentdesign")). The reliable canonical key is datasetinfo. Narrow the check.

Test gaps

  • No test for partial-load STUDY — tests/test_study_metadata.py doesn't exercise pop_loadstudy with one or more missing dataset files; a test that deletes one of the saved .set files before reload and asserts that surviving rows keep correct subject/session/run would catch the realignment bug.

  • No test for multi-dataset Save STUDY via menu — tests/test_gui_pop_study.py doesn't exercise _study_action("pop_savestudy", ...) against a session whose ALLEEG has multiple datasets but CURRENTSET is [1]; that scenario surfaces the EEG-vs-ALLEEG dispatch bug.

EEGLAB parity notes

  • STUDY pop_ history strings target LASTCOM as an assignment receiver* — e.g., pop_study.py:75-83 emits STUDY, ALLEEG, LASTCOM = pop_study(STUDY, ALLEEG, ...). EEGLAB's com is the recorded text, not a returned value; existing EEGPrep popfunc history strings use the bare form (EEG = pop_xxx(EEG, ...);). Drop LASTCOM from the targets tuple in the build_python_call call sites under studyfunc.

8 inline comments left on the changed lines for the items above.
· branch phase/5a-study-metadata-design

@suraj-ranganath

Copy link
Copy Markdown
Member Author

🤖 Visual parity captures for the Phase 5a STUDY dialogs.

pop_study_dialog
pop_study_dialog side-by-side

pop_studydesign_dialog
pop_studydesign_dialog side-by-side

Known visual differences: EEGPrep uses compact Phase 5a metadata/design forms and omits EEGLAB controls that belong to browse/component workflows outside this phase.

@@ -690,8 +699,21 @@ def _study_action(self, action: str, variant: str, parent: Any | None) -> None:
from eegprep.functions.studyfunc.pop_savestudy import pop_savestudy

study, command = pop_savestudy(self.session.STUDY, self.session.EEG, filename, savemode=variant or None)

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.

Blocking — passes single EEG instead of ALLEEG to pop_savestudy.

self.session.EEG is one dataset; pop_savestudy runs std_checkset(STUDY, as_alleeg_list(EEG)) (pop_savestudy.py:41-42) and sync_datasetinfo rebuilds STUDY.datasetinfo from that single entry. A STUDY with N datasets is saved with only the currently selected row, and any per-row metadata (subject/session/run/comps) for the other rows is lost.

Fix: pass self.session.ALLEEG. The recorded history string pop_savestudy(STUDY, EEG, ...) (pop_savestudy.py:50-57) should also become STUDY = pop_savestudy(STUDY, ALLEEG, ...) so replay reproduces the same STUDY.

Suggested change
study, command = pop_savestudy(self.session.STUDY, self.session.EEG, filename, savemode=variant or None)
study, command = pop_savestudy(self.session.STUDY, self.session.ALLEEG, filename, savemode=variant or None)

Ref:

from eegprep.functions.studyfunc.pop_savestudy import pop_savestudy
study, command = pop_savestudy(self.session.STUDY, self.session.EEG, filename, savemode=variant or None)
self.session.echo_command(command)
self.session.set_study(study, command=command)
self._refresh()
return

Comment on lines +62 to +72
def _load_datasets(study: dict[str, Any]) -> list[dict[str, Any]]:
datasets = []
for info in study.get("datasetinfo") or []:
path = dataset_path(info)
if path is None:
continue
if not path.is_absolute() and not path.exists():
path = Path(study.get("filepath") or "") / path
if path.exists():
datasets.append(pop_loadset(str(path)))
return datasets

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.

Blocking — partial load silently scrambles datasetinfo rows.

When a file at original position k is missing, _load_datasets continues and the loaded list compacts. pop_loadstudy then calls std_checkset(study, alleeg) (line 44), and sync_datasetinfo (_study_utils.py:96-101) overlays each loaded row with existing[index - 1] keyed by the new enumeration. If files 2 and 4 of 5 are missing, the metadata from saved rows 3 and 5 ends up overlaid onto loaded rows 2 and 3 — every field that lives only in STUDY.datasetinfo (notably session, run, comps, and any custom factor added via std_editset) is silently rebound to the wrong dataset. The user also gets no warning that any files were missing.

Fix: either preserve STUDY.datasetinfo row alignment when partial-loading (insert a placeholder / None for missing files, or short-circuit sync_datasetinfo when len(datasets) != len(existing)), or raise/log a clear error listing the missing paths so the user can rebase filepath before retrying. The current "drop silently" path is the dangerous case.

Ref:

def _load_datasets(study: dict[str, Any]) -> list[dict[str, Any]]:
datasets = []
for info in study.get("datasetinfo") or []:
path = dataset_path(info)
if path is None:
continue
if not path.is_absolute() and not path.exists():
path = Path(study.get("filepath") or "") / path
if path.exists():
datasets.append(pop_loadset(str(path)))
return datasets

Comment on lines 745 to 751
else:
if not self.session.ALLEEG:
self._warn(parent, "Load at least one dataset before creating a study")
return
from eegprep.functions.studyfunc.pop_study import pop_study

study, alleeg, command = pop_study(None, self.session.ALLEEG)

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 — Create-new-STUDY menu path skips the dialog.

pop_study defaults use_gui to False when gui is None (pop_study.py:44), so this branch silently builds a STUDY from current ALLEEG with no chance for the user to set name/task/notes or per-dataset metadata. It also can't be cancelled. Mirror the pop_study:edit branch (menu_actions.py:736-744): pass gui=True and treat empty command as cancel.

Suggested change
else:
if not self.session.ALLEEG:
self._warn(parent, "Load at least one dataset before creating a study")
return
from eegprep.functions.studyfunc.pop_study import pop_study
study, alleeg, command = pop_study(None, self.session.ALLEEG)
else:
if not self.session.ALLEEG:
self._warn(parent, "Load at least one dataset before creating a study")
return
from eegprep.functions.studyfunc.pop_study import pop_study
study, alleeg, command = pop_study(None, self.session.ALLEEG, gui=True)
if not command:
return

Ref:

if not command:
return
else:
if not self.session.ALLEEG:
self._warn(parent, "Load at least one dataset before creating a study")
return
from eegprep.functions.studyfunc.pop_study import pop_study
study, alleeg, command = pop_study(None, self.session.ALLEEG)
self.session.echo_command(command)
self.session.set_study(study, alleeg, command=command)

gui = options.pop("gui", gui)
if designind is None:
designind = int(options.pop("designind", study.get("currentdesign") or 1))
use_gui = is_on(gui) if gui is not None else not bool(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.

Important — opens GUI on non-interactive calls.

When a caller writes pop_studydesign(STUDY, ALLEEG, 2), designind is consumed positionally on line 25, options is empty, and not bool(options) is True, so this heuristic launches Qt despite no gui=True. This breaks headless scripting and contradicts the default gui: bool | None = None declared in the signature.

Default use_gui to False (consistent with pop_study.py:44); require explicit gui=True to open the dialog.

Suggested change
use_gui = is_on(gui) if gui is not None else not bool(options)
use_gui = is_on(gui) if gui is not None else False

Ref:

if designind is None:
designind = int(options.pop("designind", study.get("currentdesign") or 1))
use_gui = is_on(gui) if gui is not None else not bool(options)
if use_gui:
result = inputgui(pop_studydesign_dialog_spec(study, datasets), renderer=renderer)
if result is None:
return study, datasets, ""
options.update(_options_from_gui(result))
designind = int(result.get("designind") or designind or 1)

Comment on lines +113 to +135
for index, info in enumerate((checked.get("datasetinfo") or [])[:10], start=1):
controls.extend(
(
ControlSpec("text", str(index)),
ControlSpec("edit", tag=f"dataset_{index}_filename", value=_display_path(info), enabled=False),
ControlSpec("edit", tag=f"dataset_{index}_subject", value=str(info.get("subject") or "")),
ControlSpec(
"edit", tag=f"dataset_{index}_session", value=_display_optional_number(info.get("session"))
),
ControlSpec("edit", tag=f"dataset_{index}_run", value=_display_optional_number(info.get("run"))),
ControlSpec("edit", tag=f"dataset_{index}_condition", value=str(info.get("condition") or "")),
ControlSpec("edit", tag=f"dataset_{index}_group", value=str(info.get("group") or "")),
)
)
controls.append(
ControlSpec(
"text",
"Important note: Removed datasets will not be saved before being deleted from EEGPrep memory",
)
)
dataset_row_geometry = (0.22, 2.6, 0.9, 0.7, 0.55, 1.3, 0.9)
geometry = [(1,), (1.2, 5), (1.2, 5), (1.2, 5), dataset_row_geometry]
geometry.extend(dataset_row_geometry for _info in (checked.get("datasetinfo") or [])[:10])

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 — dialog hides datasets beyond row 10.

Both the controls loop (line 113) and the geometry list (line 135) slice [:10]. For a STUDY with >10 datasets, rows 11..N are not rendered and not editable from the GUI; _dataset_row_commands iterates the full ALLEEG so rows beyond 10 keep their stale values, but the user has no way to fix them. EEGLAB's pop_study shows all rows. The known_differences tuple (lines 147-149) doesn't mention this cap, so the visual_parity capture is also misleading.

Fix: drop the [:10] slices and let the dialog scroll, or — at minimum — surface a "+N rows hidden" notice and call it out in known_differences. If the cap stays, document it in src/eegprep/resources/help/pop_study.md as well.

Ref:

ControlSpec("text", "group", font_weight="bold"),
]
for index, info in enumerate((checked.get("datasetinfo") or [])[:10], start=1):
controls.extend(
(
ControlSpec("text", str(index)),
ControlSpec("edit", tag=f"dataset_{index}_filename", value=_display_path(info), enabled=False),
ControlSpec("edit", tag=f"dataset_{index}_subject", value=str(info.get("subject") or "")),
ControlSpec(
"edit", tag=f"dataset_{index}_session", value=_display_optional_number(info.get("session"))
),
ControlSpec("edit", tag=f"dataset_{index}_run", value=_display_optional_number(info.get("run"))),
ControlSpec("edit", tag=f"dataset_{index}_condition", value=str(info.get("condition") or "")),
ControlSpec("edit", tag=f"dataset_{index}_group", value=str(info.get("group") or "")),
)
)
controls.append(
ControlSpec(
"text",
"Important note: Removed datasets will not be saved before being deleted from EEGPrep memory",
)
)
dataset_row_geometry = (0.22, 2.6, 0.9, 0.7, 0.55, 1.3, 0.9)
geometry = [(1,), (1.2, 5), (1.2, 5), (1.2, 5), dataset_row_geometry]
geometry.extend(dataset_row_geometry for _info in (checked.get("datasetinfo") or [])[:10])
geometry.append((1,))
return DialogSpec(
title=title,
controls=tuple(controls),
geometry=tuple(geometry),
function_name="pop_study",
eeglab_source="functions/studyfunc/pop_study.m",
help_text="pop_study",
size=(850, 560),
content_margins=(34, 18, 34, 14),
row_spacing=4,
known_differences=(
"EEGPrep Phase 5a edits loaded dataset metadata; dataset browsing is provided by pop_studywizard.",
),
)

Comment on lines +3 to +26
from eegprep.functions.studyfunc.pop_loadstudy import pop_loadstudy
from eegprep.functions.studyfunc.pop_savestudy import pop_savestudy
from eegprep.functions.studyfunc.pop_study import pop_study
from eegprep.functions.studyfunc.pop_studydesign import pop_studydesign
from eegprep.functions.studyfunc.pop_studyerp import pop_studyerp
from eegprep.functions.studyfunc.pop_studywizard import pop_studywizard
from eegprep.functions.studyfunc.std_checkset import std_checkdatasetinfo, std_checkset
from eegprep.functions.studyfunc.std_editset import std_editset
from eegprep.functions.studyfunc.std_makedesign import std_makedesign
from eegprep.functions.studyfunc.std_selectdesign import std_selectdesign

__all__ = [
"pop_loadstudy",
"pop_savestudy",
"pop_study",
"pop_studydesign",
"pop_studyerp",
"pop_studywizard",
"std_checkdatasetinfo",
"std_checkset",
"std_editset",
"std_makedesign",
"std_selectdesign",
]

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 — inconsistent with sibling subpackage __init__.py files.

popfunc/__init__.py, adminfunc/__init__.py, sigprocfunc/__init__.py, and guifunc/__init__.py are all docstring-only. The eager imports here pull in numpy (via _study_utils) and Qt (via inputgui through pop_study/pop_studydesign) on any from eegprep.functions.studyfunc import ..., and they force the local-import workaround at std_checkset.py:22 to break the cycle this __init__.py introduces.

src/eegprep/__init__.py already re-exports the public STUDY entry points, so no caller depends on eegprep.functions.studyfunc.pop_* being preloaded. Make this file docstring-only like its siblings.

Suggested change
from eegprep.functions.studyfunc.pop_loadstudy import pop_loadstudy
from eegprep.functions.studyfunc.pop_savestudy import pop_savestudy
from eegprep.functions.studyfunc.pop_study import pop_study
from eegprep.functions.studyfunc.pop_studydesign import pop_studydesign
from eegprep.functions.studyfunc.pop_studyerp import pop_studyerp
from eegprep.functions.studyfunc.pop_studywizard import pop_studywizard
from eegprep.functions.studyfunc.std_checkset import std_checkdatasetinfo, std_checkset
from eegprep.functions.studyfunc.std_editset import std_editset
from eegprep.functions.studyfunc.std_makedesign import std_makedesign
from eegprep.functions.studyfunc.std_selectdesign import std_selectdesign
__all__ = [
"pop_loadstudy",
"pop_savestudy",
"pop_study",
"pop_studydesign",
"pop_studyerp",
"pop_studywizard",
"std_checkdatasetinfo",
"std_checkset",
"std_editset",
"std_makedesign",
"std_selectdesign",
]
"""EEGLAB-style STUDY helper functions."""

Ref:

"""EEGLAB-style STUDY helper functions."""
from eegprep.functions.studyfunc.pop_loadstudy import pop_loadstudy
from eegprep.functions.studyfunc.pop_savestudy import pop_savestudy
from eegprep.functions.studyfunc.pop_study import pop_study
from eegprep.functions.studyfunc.pop_studydesign import pop_studydesign
from eegprep.functions.studyfunc.pop_studyerp import pop_studyerp
from eegprep.functions.studyfunc.pop_studywizard import pop_studywizard
from eegprep.functions.studyfunc.std_checkset import std_checkdatasetinfo, std_checkset
from eegprep.functions.studyfunc.std_editset import std_editset
from eegprep.functions.studyfunc.std_makedesign import std_makedesign
from eegprep.functions.studyfunc.std_selectdesign import std_selectdesign
__all__ = [
"pop_loadstudy",
"pop_savestudy",
"pop_study",
"pop_studydesign",
"pop_studyerp",
"pop_studywizard",
"std_checkdatasetinfo",
"std_checkset",
"std_editset",
"std_makedesign",
"std_selectdesign",
]

*args: Any,
filepath: str | Path | None = None,
load_datasets: bool = True,
return_com: bool = False,

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 — return_com parameter is dead.

Declared here but never read; the function unconditionally returns (study, alleeg, command) at line 52. Same lying signature appears in pop_savestudy.py:22, pop_studyerp.py:13, pop_studywizard.py:15. A caller writing pop_savestudy(STUDY) expecting STUDY per the declared default gets a 2-tuple instead.

Either branch on return_com (matching std_editset.py / pop_reref.py) and return just the primary object when False, or drop the parameter from these four signatures.

Ref:

def pop_loadstudy(
filename: str | Path | None = None,
*args: Any,
filepath: str | Path | None = None,
load_datasets: bool = True,
return_com: bool = False,
**kwargs: Any,
) -> tuple[dict[str, Any], list[dict[str, Any]], str]:
"""Load a STUDY JSON file saved by ``pop_savestudy``."""
options = parse_key_value_args(args, kwargs, lowercase_kwargs=True)
filename = options.pop("filename", filename)
filepath = options.pop("filepath", filepath)
load_datasets = bool(options.pop("load_datasets", load_datasets))
if options:
raise ValueError(f"Unknown pop_loadstudy option(s): {', '.join(sorted(options))}")
if filename is None:
raise ValueError("pop_loadstudy requires a filename")
path = _study_path(filename, filepath)
with path.open(encoding="utf-8") as stream:
payload = json.load(stream)
if not isinstance(payload, dict):
raise ValueError("STUDY file must contain a JSON object")
study = ensure_study(payload)
old_filepath = study.get("filepath", "")
study["filename"] = path.name
study["filepath"] = str(path.parent)
study["etc"].setdefault("oldfilepath", old_filepath)
alleeg = _load_datasets(study) if load_datasets else []
study, alleeg = std_checkset(study, alleeg)
study["saved"] = "yes"
command = build_python_call(
("STUDY", "ALLEEG", "LASTCOM"),
"pop_loadstudy",
filename=path.name,
filepath=str(path.parent),
)
return study, alleeg, command

Comment on lines +13 to +18
options: str | None = None,
*,
return_com: bool = False,
) -> Any:
"""Normalize a STUDY dict and refresh dataset/design consistency metadata."""
_ = 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 — options parameter is dead.

Accepted and immediately discarded with _ = options. The console wrapper exposes this surface (callers see std_checkset(STUDY, ALLEEG, options=...) work without effect). Either wire it through (mirror the corresponding EEGLAB options arg) or drop it from the signature.

Ref:

def std_checkset(
STUDY: dict[str, Any] | None,
ALLEEG: list[dict[str, Any]] | None,
options: str | None = None,
*,
return_com: bool = False,
) -> Any:
"""Normalize a STUDY dict and refresh dataset/design consistency metadata."""
_ = options
datasets = as_alleeg_list(ALLEEG)
study = sync_datasetinfo(ensure_study(STUDY), datasets)

@suraj-ranganath
suraj-ranganath merged commit 2cc5aaa 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