Repository navigation
Complete Phase 1b File/Edit parity - #74
Conversation
|
Claude finished @suraj-ranganath's task in 5m 50s —— View job Claude PR Review — Phase 1b File/Edit parity
SummaryOverall this is a solid Phase 1b push: each new Findings (inline)Correctness (worth addressing before merge):
Polish / behavior parity:
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. |
b502377 to
df469c8
Compare
| 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 |
There was a problem hiding this comment.
_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.
| 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" |
There was a problem hiding this comment.
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:
deleteepochson,trials > 1,deleteeventsoff →output["event"]keeps the un-mutated deepcopy ofEEG["event"], so the rename never reaches the returned dataset.deleteeventson (either branch) → rename is preserved because the comprehension reads fromevents.else→output["event"] = eventspreserves 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.
| 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] |
There was a problem hiding this comment.
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.
| def is_boundary_event(event: dict[str, Any]) -> bool: | ||
| """Return true for EEGLAB boundary events.""" | ||
| return str(event.get("type", "")).lower() == "boundary" |
There was a problem hiding this comment.
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).
| 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 |
There was a problem hiding this comment.
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.
| 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 |
There was a problem hiding this comment.
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.
| if delold: | ||
| values = _coerce_field_values(value) | ||
| events = [{key_text: item} for item in values] | ||
| indices = list(range(len(events))) | ||
| eventdescription = [""] | ||
| delold = False |
There was a problem hiding this comment.
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.
| 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 |
There was a problem hiding this comment.
_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.genfromtxtwithdelimiter=Nonewould be closer to EEGLAB behavior.
|
🤖 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. |




















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
pop_*workflows:pop_chaneditpop_copysetpop_editeventfieldpop_editeventvalspop_fileio_brainvision_matpop_mergesetpop_rmdatpop_selecteventselect_multiple_datasets, preserving Phase 1a's ordered 1-basedCURRENTSETcontract.eegprep-consoleresult handling so dataset-state commands like copy/merge/selection can updateALLEEG,EEG,CURRENTSET,LASTCOM, andALLCOMthrough the shared session path.Parity/UX Notes
eeglab.m,pop_chanedit.m,pop_copyset.m,pop_editeventfield.m,pop_editeventvals.m,pop_mergeset.m,pop_rmdat.m,pop_selectevent.m, andselect_multiple_datasets.m.pop_fileio_brainvision_matis implemented as a.matbridge to EEGPrep's File-IO loader because the EEGLAB path is plugin-backed rather than a corepop_fileio_brainvision_mat.mfile.Tests
uv run --no-sync ruff check .uv run --no-sync ruff format --check .uv run --no-sync ty checkuv run --no-sync pytest tests/test_visual_parity.py -quv 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 -q170 passed, 2 skipped, 22 subtests passed./pre-commit.pyEEGPREP_SKIP_MATLAB=1 uv run --no-sync pytest -m "not slow"1207 passed, 216 skipped, 11 deselectedVisual Parity Artifacts Generated Locally
Generated under
.visual-parity/and intentionally not committed:pop_chanedit_dialog/side_by_side.pngpop_copyset_dialog/side_by_side.pngpop_editeventfield_dialog/side_by_side.pngpop_editeventvals_dialog/side_by_side.pngpop_mergeset_dialog/side_by_side.pngpop_rmdat_dialog/side_by_side.pngpop_selectevent_dialog/side_by_side.pngselect_multiple_datasets_dialog/side_by_side.png