Skip to content

[Phase 1b] Add dataset metadata dialogs - #71

Merged
suraj-ranganath merged 3 commits into
feature/eeglab-completionfrom
phase/1b-dataset-metadata
May 27, 2026
Merged

suraj-ranganath merged 3 commits into
feature/eeglab-completionfrom
phase/1b-dataset-metadata

Conversation

@suraj-ranganath

Copy link
Copy Markdown
Member

Add pop_comments and pop_editset dataset-metadata workflows with GUI menu dispatch, EEGPrep console-compatible history, and packaged help. Adds focused unit, GUI, menu, console, sample-data, and visual parity coverage for this first Phase 1b slice.

Part of #67

@claude

claude Bot commented May 27, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @suraj-ranganath's task in 4m 10s —— View job


Claude Code PR Review

  • Read PR context and changed files list
  • Read CLAUDE.md / AGENTS.md instructions
  • Inspect EEGLAB reference (vendored checkout not present in CI; reviewed against MATLAB conventions documented in AGENTS.md)
  • Review pop_comments.py
  • Review pop_editset.py
  • Review GUI dispatch / menu / Qt renderer changes
  • Review tests
  • Review visual parity additions
  • Post inline comments + summary

Summary

This is a solid first slice of Phase 1b. Both pop_comments and pop_editset follow the EEGLAB-style structure laid out in AGENTS.md: pop wrappers in functions/popfunc/, dialog specs decoupled from the renderer, return_com=True history support, packaged Markdown help, menu dispatch wired up, console workspace coverage, and visual-parity capture entries. Tests exercise the GUI cancel path, command-line key/value editing, xmin event-latency shift, ICA matrix re-init, and a sample-data round-trip — good coverage for a first slice.

Main review points (inline)

  1. _history_value uses Python repr for Mappings / lists-of-Mappings (pop_editset.py:326-335) — breaks MATLAB-style history for chanlocs. Path is currently unreachable from the GUI but exposed via command line.
  2. _truthy_concat accepts "true"/"yes"/"on" strings (pop_comments.py:107-110) — speculative configurability beyond EEGLAB's 1 flag.
  3. pop_editset GUI cancel returns the original EEG; pop_comments returns a deepcopy (pop_editset.py:54-58) — the two new pop functions disagree on the cancel contract; tests pin both behaviors. Worth aligning.
  4. dataformat is effectively dead (pop_editset.py:68-71) — never applied (only consumed in a NotImplementedError branch), special-cased in _history_command only when sole option, advertised via _SUPPORTED_FIELDS. Suggest removing until file-format data assignment is real.
  5. Menu hard-codes "About this dataset" title (menu_actions.py:659-662) — diverges from EEGLAB's setname-based title and will hurt the visual-parity capture once a real dataset is loaded.
  6. _normalize_ica_index_field is a near-no-op (pop_editset.py:308-314) — only normalizes the empty case; non-empty values are already normalized by _as_int_array. Likely either unneeded or undercommented.

Smaller observations (not posted inline)

  • _history_command for pop_comments (line 113) records single-quoted MATLAB strings containing literal \n for multi-line comments — re-executing those is awkward in both MATLAB and the EEGPrep console. Worth a follow-up once the multi-line history round-trip story is decided.
  • pop_editset_dialog_spec exposes chanfile / weightfile / sphfile / icainds edit boxes (all enabled=False) that have no plumbing in _changed_options_from_gui. The visual placeholder is fine for Phase 1b, but the known_differences could mention "fields appear in spec but are not yet round-tripped" to make the gap explicit.
  • The pop_comments button styling (fixedSize(150, 45)) and pop_editset font-size override (11px) are added to the global _apply_eeglab_style stylesheet (qt.py:215-223). This is fine for now but will keep growing — a per-dialog extra_stylesheet field on DialogSpec would scale better.

Tests / docs

  • Tests look targeted and behavior-driven (no tautological asserts I spotted), and the parametrized console-workspace echo test covers the two new actions.
  • Markdown help resources are concise and link to related pop functions.

Nothing here is a blocker; the inline points (especially #1 and #4) are worth resolving before this lands on feature/eeglab-completion.
• Branch: phase/1b-dataset-metadata

@suraj-ranganath

suraj-ranganath commented May 27, 2026 •

Copy link
Copy Markdown
Member Author

🤖 Phase 1b PR 1 implementation note

Problem
Phase #67 still had dataset comments and dataset-info editing as placeholders, so users could not edit core dataset metadata from the GUI or keep those actions synchronized with eegprep-console history.

Approach
Added pop_comments and pop_editset modules under functions/popfunc, packaged help Markdown, lazy package exports, menu dispatch, console history conversion coverage, and visual parity capture cases. pop_editset covers dataset metadata now; the lower channel/ICA file controls are visible but disabled because real channel metadata editing is scheduled for later Phase 1b PRs.

Key code

if gui:
    result = inputgui(pop_editset_dialog_spec(EEG), renderer=renderer)
    if result is None:
        return (EEG, "") if return_com else EEG
    options = _changed_options_from_gui(EEG, result)
    if not options:
        return (EEG, "") if return_com else EEG

output = copy.deepcopy(EEG)
old_xmin = float(output.get("xmin", 0.0) or 0.0)
old_srate = float(output.get("srate", 1.0) or 1.0)
for key, value in options.items():
    if key == "dataformat":
        continue
    _assign_option(output, key, value, dataformat=str(options.get("dataformat", "ascii")))
if "xmin" in options:
    _adjust_event_latencies_for_xmin_change(output, old_xmin, old_srate)

Tests
Focused verification passed on the final commit: 151 passed, 3 skipped across pop_comments, pop_editset, GUI specs, menu inventory, package exports, main window dispatch, console workspace, and visual parity. Lint/format/type checks passed with ruff and ty. Broad verification passed with EEGPREP_SKIP_MATLAB=1 uv run --no-sync pytest -m "not slow": 1123 passed, 212 skipped, 11 deselected. The added MATLAB Engine parity tests are present and skip locally because this venv does not have the MATLAB runtime package installed.

Visual parity

pop_comments pop_editset
pop_comments_side_by_side.png pop_editset_side_by_side.png

Comment on lines +326 to +335
def _history_value(value: Any) -> str:
if _is_empty_value(value):
return "[]"
if isinstance(value, Mapping):
return repr(dict(value))
if isinstance(value, np.ndarray) and value.dtype == object:
value = value.tolist()
if isinstance(value, (list, tuple)) and any(isinstance(item, Mapping) for item in value):
return repr(value)
return format_history_value(value)

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.

🤖 _history_value falls back to Python repr() for Mapping and lists/tuples that contain mappings. That produces a Python-style literal (e.g. [{'labels': 'Cz'}]), not the MATLAB struct/cell array syntax EEGLAB history expects. If a caller does pop_editset(EEG, 'chanlocs', [{'labels': 'Cz'}]) the recorded history command can't be replayed in EEGLAB and arguably not even in this codebase's own console without further translation.

Given the dialog never exercises chanlocs/icaweights/icasphere from the GUI in this PR and the command-line chanlocs path is the only Mapping-bearing branch, consider one of:

  • restricting history coverage to scalar/text/numeric options for now (drop the Mapping/list-of-dict branch and raise/skip), or
  • emitting a MATLAB-style placeholder like '<struct>' so the history at least documents that something happened without misleading by-value contents.

This is also a parity claim worth a unit test once a representation is chosen.

Comment on lines +107 to +110
def _truthy_concat(value: bool | int | str) -> bool:
if isinstance(value, str):
return value.strip().lower() in {"1", "true", "yes", "on"}
return bool(value)

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.

🤖 _truthy_concat accepting "true"/"yes"/"on" strings doesn't match EEGLAB (which only takes the numeric 1 flag) and the signature concat: bool | int | str advertises it as a public knob. Per AGENTS.md "No speculative configurability… No backward compatibility by default," this looks like dead surface. Suggest reducing to bool(value) (with the existing tests narrowed to ints/bools) and trimming the type hint to bool | int.

Comment on lines +54 to +58
if result is None:
return (EEG, "") if return_com else EEG
options = _changed_options_from_gui(EEG, result)
if not options:
return (EEG, "") if return_com else EEG

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 GUI cancel / no-change paths return EEG itself (not a copy.deepcopy). Downstream callers can therefore mutate the session dataset through the returned reference, which is asymmetric with the success path (which returns a deepcopy). test_pop_editset_gui_cancel_or_no_changes_returns_original_without_history even pins this behavior with assert cancelled is eeg.

pop_comments on line 39 returns a deepcopy on cancel (its test asserts cancelled is not eeg). The two pop functions added in this PR disagree on the contract — worth aligning. I'd lean toward pop_comments's deepcopy, since "cancel" is a no-op in the user's mental model and the immutability invariant in the rest of the suite assumes pop_* returns a fresh dict.

Comment on lines +68 to +71
for key, value in options.items():
if key == "dataformat":
continue
_assign_option(output, key, value, dataformat=str(options.get("dataformat", "ascii")))

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.

🤖 dataformat is parsed into options and threaded into _assign_option, but the only place it's actually consumed is _assign_data's file-string branch, which always raises NotImplementedError. The history loop also special-cases dataformat only when it is the sole option:

if key == "dataformat" and len(options) == 1:
    continue

So today dataformat is effectively dead: never applied, sometimes recorded into history, and _SUPPORTED_FIELDS advertises it. Per AGENTS.md "no speculative configurability," I'd drop the field entirely until file-format data assignments are actually supported (Phase 1b channels), and remove dataformat= from _assign_option/_assign_data.

Comment on lines +659 to +662
elif name == "pop_comments":
from eegprep.functions.popfunc.pop_comments import pop_comments

out = pop_comments(selection, "About this dataset", return_com=True)

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 menu hard-codes "About this dataset" as the dialog title regardless of dataset. EEGLAB's pop_comments in the GUI builds its title from EEG.setname-style context (e.g. "Comments of dataset: <setname>") rather than a constant — see the MATLAB pop_comments.m header logic. For the eventual EEGLAB-parity capture this means the screenshot will diverge from MATLAB once a real dataset is loaded.

Two options: (1) pass f"About \"{eeg.get('setname', 'this dataset')}\"" (closer to MATLAB), or (2) pass "" and let pop_comments_dialog_spec's title or "Read/Enter text -- pop_comments()" fallback handle it. Either makes the visual parity test more robust than a constant string.

Comment on lines +308 to +314
def _normalize_ica_index_field(output: dict[str, Any]) -> None:
value = output.get("icachansind")
if value is None:
return
array = np.asarray(value)
if array.size == 0:
output["icachansind"] = np.array([], dtype=int)

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.

🤖 _normalize_ica_index_field only acts when the assigned array is empty — it leaves a non-empty icachansind whatever shape/dtype it landed in from the user. But _as_int_array (which the icachansind branch of _assign_option already calls) returns a 1-D int array, so this function is a no-op for assignments that go through pop_editset and only matters for pre-existing data on EEG. If that's the actual purpose (normalizing legacy session state), please add a brief comment; otherwise this helper duplicates _as_int_array and can be removed.

@suraj-ranganath
suraj-ranganath force-pushed the phase/1b-dataset-metadata branch from a9a0f0d to 7101a26 Compare May 27, 2026 07:17
@suraj-ranganath

Copy link
Copy Markdown
Member Author

@claude review this

@claude

claude Bot commented May 27, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @suraj-ranganath's task in 3m 37s —— View job


Claude Code PR Review

  • Read PR context and changed files list
  • Read CLAUDE.md / AGENTS.md instructions
  • Diff against origin/feature/eeglab-completion
  • Review pop_comments.py
  • Review pop_editset.py
  • Review GUI dispatch / menu / Qt renderer changes
  • Review tests + visual parity additions
  • Post summary

Status of previous review findings

The follow-up commit 7025715 (“Fix dataset metadata review issues”) addresses most of the prior inline points:

# Prior finding Status
1 _history_value falling back to repr() for Mapping/list-of-mapping ✅ Now raises NotImplementedError (covered by test_pop_editset_history_rejects_unserializable_channel_structures)
2 _truthy_concat accepting "true"/"yes"/"on" strings ✅ Now raises TypeError; signature trimmed to bool | int
3 Cancel-path deepcopy asymmetry between pop_comments and pop_editset ✅ Both now return copy.deepcopy(EEG) on cancel/no-change
4 Dead dataformat field ✅ Removed from _SUPPORTED_FIELDS, _assign_option, _assign_data, and _history_command; rejection covered by test
5 Menu hard-codes "About this dataset" title ❌ Not addressed — see below
6 _normalize_ica_index_field near no-op ✅ Now coerces non-empty values via _as_int_array (missing return was the actual bug)

Tests, console-workspace coverage, package exports, and _clear_ica_fields for stale-ICA replacement all look good.


Open findings (worth resolving)

1. Menu still passes a hard-coded title to pop_comments. menu_actions.py:662

out = pop_comments(selection, "About this dataset", return_com=True)

This was flagged in the previous round and remains unchanged. EEGLAB builds the dialog title from the loaded dataset (e.g. "Comments of dataset: <setname>"). With a real dataset loaded, the EEGPrep capture will diverge from the MATLAB capture in pop_comments_dialog. Suggest either f"Comments of dataset: {selection.get('setname','')}" (closer to MATLAB) or "" and let pop_comments_dialog_spec's title or "Read/Enter text -- pop_comments()" fallback handle it. Fix this →

2. qt.py renderer is starting to special-case dialogs by function_name. qt.py:215-223, 277-289
The stylesheet now grows per-dialog blocks (QDialog#pop_editset font size, QDialog#pop_comments button height) and _add_buttons branches on spec.function_name == "pop_comments" for both button sizing and layout order (insertWidget(0) to put CANCEL on the left). That's logic, not just styling, leaking into the generic renderer. Per AGENTS.md "no speculative configurability" cuts both ways — the next pop dialog that wants a different button layout will add another if function_name == branch. Suggest a tiny set of DialogSpec fields (e.g. button_size: tuple[int,int] | None, cancel_first: bool, extra_stylesheet: str | None) so the renderer stays dialog-agnostic. Not a blocker, but the pattern is one PR away from being painful.

3. _normalize_data_dimensions silently overrides an incompatible user-supplied pnts. pop_editset.py:301-310

if data.ndim == 2 and pnts > 1:
    frames = int(data.shape[1])
    if frames % pnts:
        if trials > 1 and frames // pnts > 0:
            ...
        else:
            pnts = frames
            trials = 1

test_pop_editset_pnts_metadata_keeps_data_dimensions_consistent pins this: pop_editset(eeg, "pnts", 7) on 20-frame data becomes pnts=20, trials=1 with no warning. That's "silently ignore the user's input," which feels wrong for a metadata edit function — EEGLAB's pop_editset typically errors on inconsistent epoch sizing. At minimum I'd raise a ValueError (or logger.warning and document the fallback). The current test would need to flip to pytest.raises. Fix this →

4. pop_comments history for the string-input path embeds a literal \n inside a single-quoted MATLAB string. pop_comments.py:114-119, pinned by test_pop_comments_concatenates_string_comments which asserts com == "comments = pop_comments(comments, '', 'second\nthird', 1);". In MATLAB, 'second\nthird' is the literal six characters s e c o n d \ n … — not a newline — so the recorded history can't be replayed to produce the same result. EEGLAB tends to use sprintf('\n') or char(10) concatenation. The EEG-dict path is the GUI-facing usage (less impactful), but for the string-comments path the history-replay claim is broken. Worth at least a follow-up TODO if not fixing here. (Was a smaller observation last round and didn't get picked up.)

Smaller observations (not blocking)

  • _history_value ndarray-of-object-mapping (pop_editset.py:380-389): if value is np.ndarray(dtype=object) containing dicts, the Mapping/list-of-Mapping early-returns don't catch it, and the tolist() + format_history_value path emits Python-style repr rather than raising. Easy to plug by checking value.dtype == object before the Mapping check, or by converting to list first.
  • Disabled dialog controls have no round-trip plumbing. chanfile, weightfile, sphfile, icainds exist in pop_editset_dialog_spec but _changed_options_from_gui ignores them. known_differences mentions the pickers are disabled, but not that the edit fields don't round-trip — tightening that sentence would help a future visual-parity reader.
  • Cancel paths always full-deepcopy, even though cancel never mutates EEG. For large datasets this is wasted work. A shallow copy.copy(EEG) would still satisfy the cancelled is not eeg invariant the tests pin. Marginal.

Tests / docs

  • Test additions are targeted and behavior-driven; the parametrized console-workspace echo test covers both new actions; MATLAB-parity tests are guarded by EEGPREP_SKIP_MATLAB and skip cleanly.
  • Help Markdown is concise and cross-links the sibling functions.
  • Visual-parity captures look reasonable, though see point refactor for packaging and test distribution #1 about the menu-supplied title once the capture runs on a real dataset.

Nothing here is a hard blocker for landing on feature/eeglab-completion, but #1 (menu title) and #3 (silent pnts coercion) should be addressed before merge; #4 (history \n) and #2 (renderer special-casing) are worth at least a tracked follow-up.
• Branch: phase/1b-dataset-metadata

@suraj-ranganath
suraj-ranganath force-pushed the phase/1b-dataset-metadata branch from e4c6966 to 0c8747b Compare May 27, 2026 17:51
@suraj-ranganath
suraj-ranganath merged commit e230439 into feature/eeglab-completion May 27, 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