Skip to content

Complete Phase 1b File/Edit parity - #74

Merged
suraj-ranganath merged 4 commits into
feature/eeglab-completionfrom
phase/1b-completion
May 28, 2026
Merged

suraj-ranganath merged 4 commits into
feature/eeglab-completionfrom
phase/1b-completion

Conversation

@suraj-ranganath

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

Copy link
Copy Markdown
Member

Summary

Closes #67.

Completes Phase 1b File/Edit parity on top of feature/eeglab-completion, excluding EEGBrowser/eegplot scrolling workflows that remain intentionally out of scope for the epic.

What Changed

  • Added remaining Phase 1b pop_* workflows:
    • pop_chanedit
    • pop_copyset
    • pop_editeventfield
    • pop_editeventvals
    • pop_fileio_brainvision_mat
    • pop_mergeset
    • pop_rmdat
    • pop_selectevent
  • Added user-facing multi-dataset selection via select_multiple_datasets, preserving Phase 1a's ordered 1-based CURRENTSET contract.
  • Added shared event helpers for event/urevent list normalization, field/index handling, sorting, and history value formatting.
  • Wired all new actions into File/Edit/Datasets menu dispatch, console exports, GUI visual capture cases, help Markdown, and package lazy exports.
  • Removed remaining Phase 1b placeholder metadata while keeping browser-dependent exclusions explicit.
  • Extended eegprep-console result handling so dataset-state commands like copy/merge/selection can update ALLEEG, EEG, CURRENTSET, LASTCOM, and ALLCOM through the shared session path.

Parity/UX Notes

  • EEGLAB source was inspected for each workflow before implementation, including eeglab.m, pop_chanedit.m, pop_copyset.m, pop_editeventfield.m, pop_editeventvals.m, pop_mergeset.m, pop_rmdat.m, pop_selectevent.m, and select_multiple_datasets.m.
  • pop_fileio_brainvision_mat is implemented as a .mat bridge to EEGPrep's File-IO loader because the EEGLAB path is plugin-backed rather than a core pop_fileio_brainvision_mat.m file.
  • GUI-emitted commands are Python-replayable and continue to populate unified history.
  • Visual parity side-by-side screenshots are attached in a PR comment as user attachments, not committed to the repo.

Tests

  • uv run --no-sync ruff check .
  • uv run --no-sync ruff format --check .
  • uv run --no-sync ty check
  • uv run --no-sync pytest tests/test_visual_parity.py -q
  • uv run --no-sync pytest tests/test_phase1b_file_edit_pop_functions.py tests/test_gui_main_window.py tests/test_menu_placeholder_inventory.py tests/test_console_workspace.py tests/test_package_exports.py tests/test_visual_parity.py -q
    • 170 passed, 2 skipped, 22 subtests passed
    • skips are MATLAB/EEGLAB-reference parity scaffolds when the local worktree does not include the vendored EEGLAB checkout
  • ./pre-commit.py
  • EEGPREP_SKIP_MATLAB=1 uv run --no-sync pytest -m "not slow"
    • 1207 passed, 216 skipped, 11 deselected

Visual Parity Artifacts Generated Locally

Generated under .visual-parity/ and intentionally not committed:

  • pop_chanedit_dialog/side_by_side.png
  • pop_copyset_dialog/side_by_side.png
  • pop_editeventfield_dialog/side_by_side.png
  • pop_editeventvals_dialog/side_by_side.png
  • pop_mergeset_dialog/side_by_side.png
  • pop_rmdat_dialog/side_by_side.png
  • pop_selectevent_dialog/side_by_side.png
  • select_multiple_datasets_dialog/side_by_side.png

@claude

claude Bot commented May 28, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @suraj-ranganath's task in 5m 50s —— View job


Claude PR Review — Phase 1b File/Edit parity

  • Read PR diff against origin/feature/eeglab-completion
  • Inspect new pop_* modules and event helpers for parity bugs
  • Inspect GUI menu wiring, console dispatch, and visual capture additions
  • Cross-check tests, package exports, and help resources
  • Post inline findings + final summary

Summary

Overall this is a solid Phase 1b push: each new pop_* mirrors its EEGLAB counterpart, GUI wiring + ConsoleDatasetResult + select_multiple_datasets keep the session contract intact, and the test/parity scaffolding is thorough. Lazy package exports, help Markdown, menu placeholder cleanup, and visual capture cases are all consistent with the established patterns from Phase 1a.

Findings (inline)

Correctness (worth addressing before merge):

  • pop_editeventvals.py:258-261 — _renumber_urevent overwrites event.urevent with the event-list position, which silently corrupts the event ↔ EEG.urevent mapping on any dataset whose events already point to non-position-matching urevents. EEGLAB only allocates a new urevent for the inserted event.
  • pop_selectevent.py:223-237 — In the deleteepochs on / trials > 1 / deleteevents off branch, the locally renamed events are never written back to output["event"], so the rename silently drops. Set output["event"] = events before the pop_select call.
  • pop_rmdat.py:124-143 — _event_windows relies on selected events being latency-sorted for its start < windows[-1][1] merge step, but events_as_list preserves insertion order. Sort by events[index]["latency"] before iterating.
  • _event_utils.py:91-93 — is_boundary_event only matches the string "boundary"; EEGLAB also uses numeric -1. Add the numeric form so pop_rmdat / pop_selectevent treat MATLAB-style boundaries correctly.

Polish / behavior parity:

  • pop_fileio_brainvision_mat.py:29 — Replaces eeg["history"] instead of appending. EEGLAB convention is append-only.
  • pop_chanedit.py:103-113 — GUI submission emits a changefield entry for every pre-populated cell, producing a long history command even when the user changes nothing. Diff against current before emitting.
  • pop_editeventfield.py:163-168 — Dead assignment in the delold branch (overwritten by the next loop).
  • pop_chanedit.py:266-277 — _read_chanloc_file only handles whitespace-delimited rows without comment stripping; comma/tab .ced exports from EEGLAB will mis-parse.

Nothing here is a blocker for getting the Phase 1b file/edit surface in front of users, but #1 and #2 are silent data-shape bugs and would be good to fix before downstream phases start depending on these helpers.
· branch phase/1b-completion

@suraj-ranganath

suraj-ranganath commented May 28, 2026 •

Copy link
Copy Markdown
Member Author

🤖

Attachments

Phase 1b visual parity side-by-side

pop_chanedit_dialog_side_by_side.png pop_copyset_dialog_side_by_side.png
pop_chanedit_dialog_side_by_side.png pop_copyset_dialog_side_by_side.png
pop_editeventfield_dialog_side_by_side.png pop_editeventvals_dialog_side_by_side.png
pop_editeventfield_dialog_side_by_side.png pop_editeventvals_dialog_side_by_side.png
pop_mergeset_dialog_side_by_side.png pop_rmdat_dialog_side_by_side.png
pop_mergeset_dialog_side_by_side.png pop_rmdat_dialog_side_by_side.png
pop_selectevent_dialog_side_by_side.png select_multiple_datasets_dialog_side_by_side.png
pop_selectevent_dialog_side_by_side.png select_multiple_datasets_dialog_side_by_side.png

Comment on lines +258 to +261
def _renumber_urevent(events: list[dict[str, Any]]) -> None:
for index, event in enumerate(events, start=1):
if "urevent" in event and not _is_empty(event["urevent"]):
event["urevent"] = index

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.

_renumber_urevent silently overwrites pre-existing urevent links.

This sets event["urevent"] = index where index is the event-list position. In EEGLAB, event.urevent is an index into EEG.urevent, not into EEG.event. After an insert, the existing events keep their original urevent indices; only the new event needs a fresh urevent entry (with EEG.urevent extended). This function will silently corrupt the event ↔ urevent mapping for any dataset whose events already point to non-position-matching urevents (which is normal once events get reordered or deleted).

EEGLAB's pop_editeventvals.m only allocates a new urevent for the inserted event and leaves the rest untouched. Consider only setting event["urevent"] for the freshly inserted event (and extending EEG.urevent accordingly) instead of renumbering all events.

Fix this →

Comment on lines +223 to +237
if deleteepochs and int(output.get("trials", 1) or 1) > 1:
epochs = _selected_epochs(events, selected_indices, int(output.get("trials", 1) or 1))
if str(options.get("invertepochs", "off")).lower() == "on":
all_epochs = set(range(1, int(output.get("trials", 1) or 1) + 1))
epochs = sorted(all_epochs - set(epochs))
if not epochs:
raise ValueError("Empty dataset: all epochs have been removed")
if deleteevents:
output["event"] = [events[index] for index in selected_indices]
output = pop_select(output, "trial", epochs)
elif deleteevents:
output["event"] = [events[index] for index in selected_indices]
else:
output["event"] = events
output["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.

renametype is silently dropped on epoched data when deleteevents is off.

The rename loop above mutates the local events list (a copy created by events_as_list), but it is never written back to output["event"] in this branch. The flow is:

  • deleteepochs on, trials > 1, deleteevents off → output["event"] keeps the un-mutated deepcopy of EEG["event"], so the rename never reaches the returned dataset.
  • deleteevents on (either branch) → rename is preserved because the comprehension reads from events.
  • else → output["event"] = events preserves the rename.

EEGLAB writes the renamed events back regardless of the deleteevents/deleteepochs combination. Set output["event"] = events before the pop_select call when there is a rename (or unconditionally before the branch), so an epoched "rename selected events, keep all epochs" run actually changes types.

Fix this →

Comment on lines +124 to +143
windows: list[list[float]] = []
for index in selected:
latency = float(events[index]["latency"])
start = latency + srate * float(timelims[0])
stop = latency + srate * float(timelims[1])
for boundary in boundary_latencies:
if start < boundary < stop:
if boundary < latency:
start = boundary
elif boundary > latency:
stop = boundary
start = max(1, start)
stop = min(pnts, stop)
if stop <= start:
continue
if windows and start < windows[-1][1]:
windows[-1][1] = max(windows[-1][1], stop)
else:
windows.append([start, stop])
return [[(start - 1) / srate, (stop - 1) / srate] for start, stop in windows]

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 window-merge step assumes events are latency-sorted, but events_as_list doesn't sort.

if windows and start < windows[-1][1]: windows[-1][1] = max(...) only correctly merges overlapping windows when the iteration is in ascending start order. The current loop processes selected (already in ascending event-index order), but events came from events_as_list(EEG.event), which returns events in whatever order they were stored. If the dataset has events out of latency order (or boundaries injected after the fact), this can either produce out-of-order windows (downstream pop_select failures) or silently drop windows that "look earlier" than the previous one.

EEGLAB's pop_rmdat.m sorts events / windows by latency before merging. The safest fix here is to sort selected by events[index]["latency"] before iterating, or sort the resulting windows list before returning.

Fix this →

Comment on lines +91 to +93
def is_boundary_event(event: dict[str, Any]) -> bool:
"""Return true for EEGLAB boundary events."""
return str(event.get("type", "")).lower() == "boundary"

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.

is_boundary_event only recognizes type == "boundary", missing EEGLAB's numeric -1 convention.

EEGLAB tolerates two encodings for boundary events: the string "boundary" and the numeric -1. Files imported from raw MATLAB pipelines sometimes carry the numeric form. str(event.get("type", "")).lower() == "boundary" does not match -1 (it stringifies to "-1"), so callers like pop_rmdat._event_windows and pop_selectevent._apply_selectevent_one will treat numeric boundaries as normal events. Consider also matching event.get("type") in (-1, -1.0).

Fix this →

raise ValueError("pop_fileio_brainvision_mat supports BrainVision Analyzer .mat files")
eeg, _command = pop_fileio(path, return_com=True, **kwargs)
command = f"EEG = pop_fileio_brainvision_mat({format_history_value(path)});"
eeg["history"] = command

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.

eeg["history"] = command replaces the dataset's history instead of appending.

pop_fileio returns an EEG whose history already contains its own import line. Overwriting it here drops that audit trail. EEGLAB's convention is to append each pop-function command to EEG.history, not to clobber the field. Suggested change:

existing = str(eeg.get("history") or "").strip()
eeg["history"] = f"{existing}\n{command}".lstrip()

This is mostly cosmetic for a fresh import (history typically only has one prior line), but the current behavior makes the wrapper diverge from every other pop_* import in this PR.

Fix this →

Comment on lines +103 to +113
def _run_gui(EEG: dict[str, Any], *, renderer: Any | None = None) -> dict[str, Any] | None:
result = inputgui(pop_chanedit_dialog_spec(EEG), renderer=renderer)
if result is None:
return None
channel = int(float(result.get("channel") or 1))
options: dict[str, Any] = {}
for field in _CHANNEL_FIELDS:
text = str(result.get(f"field_{field}") or "").strip()
if text:
options.setdefault("changefield", []).append([channel, field, _parse_field_value(text)])
return 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.

The GUI emits a changefield entry for every populated cell, even ones the user did not touch.

The dialog spec pre-populates each field_<name> edit with the current channel value (_display_value(current.get(field, ""))). On submission this loop walks every field; any non-empty text becomes a changefield triple. So a user who opens the dialog and clicks OK on a channel with labels, X, Y, Z, sph_*, theta, radius filled in will get a 9-element changefield list (and a 9-tuple history command) even though they changed nothing.

EEGLAB's pop_chanedit only records the actual edits the user makes. Consider comparing each submitted value against the original current.get(field, "") and emitting changefield only for differences — that would also shrink the history command to something replayable.

Fix this →

Comment on lines +163 to +168
if delold:
values = _coerce_field_values(value)
events = [{key_text: item} for item in values]
indices = list(range(len(events)))
eventdescription = [""]
delold = 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.

Dead assignment in the delold branch.

events = [{key_text: item} for item in values] is constructed here and then immediately overwritten by the loop below, which calls _field_value(...) and assigns into events[event_index][key_text]. The first comprehension's stored values never make it out. Inline the loop body or drop the temporary list to avoid the extra allocation and the future-reader trap.

Also, eventdescription = [""] is hard-coded to a single-slot list. If later options operate on a different field for the same delold pass, _ensure_description_slot will need to grow it; the current behavior is fine for one option but brittle if delold were combined with subsequent field commands.

Fix this →

Comment on lines +266 to +277
def _read_chanloc_file(value: Any) -> list[dict[str, Any]]:
path = Path(value[0] if isinstance(value, (list, tuple)) else value)
rows = [line.split() for line in path.read_text(encoding="utf-8").splitlines() if line.strip()]
if not rows:
return []
header = [item.lower() for item in rows[0]]
has_header = any(item in {"labels", "theta", "radius", "x", "y", "z"} for item in header)
fields = rows.pop(0) if has_header else ["labels", "theta", "radius"]
chanlocs = []
for row in rows:
chanlocs.append({field: _parse_field_value(item) for field, item in zip(fields, row)})
return chanlocs

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.

_read_chanloc_file only handles whitespace-delimited files.

line.split() and item.lower() will silently mis-parse .ced/.locs files that use commas or tabs with embedded headers, and there is no handling of comment lines (%/#) that EEGLAB's readlocs.m strips. The companion writer (_write_chanloc_file below) emits tab-delimited rows, so a roundtrip works in tests, but a user-supplied EEGLAB-exported .ced will not round-trip.

EEGLAB delegates to readlocs which sniffs the file type and supports several formats. Either:

  • restrict this loader to the EEGPrep-written subset and document that (e.g. raise on commas or % comments), or
  • delegate to an existing reader; even np.genfromtxt with delimiter=None would be closer to EEGLAB behavior.

Fix this →

@suraj-ranganath

Copy link
Copy Markdown
Member Author

🤖 Updated Phase 1b GUI parity captures after re-inspecting the EEGLAB GUI code and tightening the EEGPrep layouts/functionality. These are GitHub user attachments only; no image artifacts were committed.

File menu
File menu side-by-side

Edit menu
Edit menu side-by-side

Datasets menu
Datasets menu side-by-side

pop_chanedit
pop_chanedit side-by-side

pop_copyset
pop_copyset side-by-side

pop_editeventfield
pop_editeventfield side-by-side

pop_editeventvals
pop_editeventvals side-by-side

pop_mergeset
pop_mergeset side-by-side

pop_rmdat
pop_rmdat side-by-side

pop_selectevent
pop_selectevent side-by-side

select_multiple_datasets
select_multiple_datasets side-by-side

@suraj-ranganath

Copy link
Copy Markdown
Member Author

🤖 Updated pop_chanedit visual parity after fixing the channel-button row order. Insert chan is now on the row below Delete chan, matching the EEGLAB reference.

pop_chanedit updated side-by-side

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