Repository navigation
[EEGBrowser] Add marking and rejection callbacks - #103
Conversation
|
Claude finished @suraj-ranganath's task in 8m 54s —— View job PR Review
SummarySolid phase-3 progress: helpers are well-decomposed, the accept/cancel split is clean, and the session-callback wiring keeps the GUI/console state synchronized. Test coverage spans helpers, GUI hooks, and the dispatcher callback. The main concerns are correctness around the 0-/1-based winrej convention and one short-circuit in Blocking issues
Non-blocking
Nits
TestsCoverage of helpers and accept/cancel is good. Two gaps worth filling:
|
| rows = np.asarray(winrej if winrej is not None else [], dtype=float) | ||
| if rows.size == 0: | ||
| return (out, command) if return_com else out | ||
| if rows.ndim == 1: | ||
| rows = rows.reshape(1, -1) | ||
|
|
||
| trials = int(out.get("trials", 1) or 1) | ||
| if trials <= 1: | ||
| if int(bool(reject)): | ||
| out = eeg_eegrej(out, eegplot2event(rows, -1)) | ||
| return (out, command) if return_com else out |
There was a problem hiding this comment.
Bug: empty winrej does not clear pre-existing rejection marks.
If a user opens the browser on an epoched dataset that already has EEG.reject.rejmanual populated, deletes all the marks, and clicks Update Marks/Reject, this function short-circuits at rows.size == 0 and never reaches _store_epoch_marks (or pop_rejepoch). The pre-existing rejmanual/rejmanualE therefore remain set, contradicting EEGLAB behavior where the browser's marks fully overwrite the stored ones.
Empty rows should still call _store_epoch_marks with all-False marks (for the epoched path) so that an "I deleted everything" action actually clears state. For continuous data + reject=1, an empty eegplot2event is correctly a no-op, but the epoched mark-update path is the broken case.
| marked = np.flatnonzero(trial_marks) | ||
| rows = np.zeros((marked.size, 5 + row_marks.shape[0]), dtype=float) | ||
| if marked.size == 0: | ||
| return rows | ||
| rows[:, 0] = marked * int(pnts) | ||
| rows[:, 1] = (marked + 1) * int(pnts) - 1 | ||
| rows[:, 2:5] = np.tile(np.asarray(_normalize_color(color), dtype=float), (marked.size, 1)) | ||
| rows[:, 5:] = row_marks[:, marked].T | ||
| return rows |
There was a problem hiding this comment.
Parity gap vs MATLAB trial2eegplot.m (0-based vs 1-based).
EEGLAB MATLAB emits [(i-1)*pnts+1, i*pnts] for 1-based trial i — so for pnts=4, rej=[1 0 1] MATLAB yields [[1,4,...],[9,12,...]]. This implementation produces [marked*pnts, (marked+1)*pnts-1] → [[0,3,...],[8,11,...]].
The skipped parity test at tests/test_eegplot.py:222 asserts
np.testing.assert_allclose(rows, matlab_rows)which would fail under MATLAB. Two related downstream consequences:
eegplot2trialonly papers over the first epoch MATLAB convention viarows[rows[:, 0] == 1, 0] = 0; trials ≥ 2 would not benp.isclose-aligned (e.g.5/4 + 1 = 2.25), so MATLAB-format rows for trials 2+ would be silently dropped.- The continuous
add_winrej_regionclamps start tomax(1, …)(1-based), but epoched winrej here is 0-based — the two modes use different conventions.
Either align Python with MATLAB's 1-based scheme (preferred for parity and unifying both modes), or document the intentional Python convention and update the parity test to compare under a +1 shift so it actually verifies behavior.
| if pnts is not None: | ||
| return _add_epoched_winrej(regions, start_value, end_value, n_channels, int(total_samples), int(pnts), color) | ||
| start_value = max(1, min(start_value, int(total_samples))) | ||
| end_value = max(1, min(end_value, int(total_samples))) | ||
| mask = _new_mask(n_channels, channel_index) | ||
| new_region = WinRejRegion(float(start_value), float(end_value), _normalize_color(color), tuple(mask)) | ||
| return _merge_continuous_regions([*regions, new_region], n_channels) |
There was a problem hiding this comment.
Mixed 0-/1-based winrej convention is fragile.
For continuous data, start_value = max(1, …) produces 1-based latencies (matching eeg_eegrej), but _add_epoched_winrej builds 0-based starts (epoch*pnts). Without a doc-string note this trips up future readers and is easy to misuse from callers.
Also: a user click drag from the very left edge that resolves to sample 0 is silently bumped to 1. Acceptable, but unexpected without a comment.
Suggest adding a brief docstring line clarifying that the resulting region semantics differ by pnts (epoched: 0-based half-inclusive; continuous: 1-based latencies for eeg_eegrej). If you can settle on a single convention internally (and convert at the EEGLAB IO boundary), that would be the cleaner long-term fix.
| def eventFilter(self, watched: Any, event: Any) -> bool: # noqa: N802 | ||
| """Handle EEGLAB-style mark/unmark mouse gestures on the plot viewport.""" | ||
| qt_widgets, _pg = _require_gui() | ||
| qt_core = QtCore | ||
| if qt_core is None or watched is not self.plot.viewport(): | ||
| return super().eventFilter(watched, event) | ||
| if event.type() == qt_core.QEvent.MouseButtonPress and event.button() == qt_core.Qt.LeftButton: | ||
| sample = self._event_sample(event) | ||
| if sample is None: | ||
| return False | ||
| self._drag_start_sample = sample | ||
| self._drag_start_pos = event.position() if hasattr(event, "position") else event.pos() | ||
| self._drag_channel_index = self._event_channel(event) if self.model.state.setelectrode else None | ||
| return True | ||
| if event.type() == qt_core.QEvent.MouseButtonRelease and event.button() == qt_core.Qt.LeftButton: | ||
| if self._drag_start_sample is None: | ||
| return False | ||
| sample = self._event_sample(event) | ||
| if sample is None: | ||
| sample = self._drag_start_sample | ||
| moved = self._mouse_moved(event) | ||
| if moved: | ||
| self.mark_samples(self._drag_start_sample, sample, channel_index=self._drag_channel_index) | ||
| else: | ||
| self.toggle_sample(sample, channel_index=self._drag_channel_index) | ||
| self._drag_start_sample = None | ||
| self._drag_start_pos = None | ||
| self._drag_channel_index = None | ||
| return True | ||
| return super().eventFilter(watched, event) |
There was a problem hiding this comment.
eventFilter unconditionally swallows left-button events on the viewport.
Returning True on every press/release stops pyqtgraph from receiving the event. That's safe today because setMouseEnabled(x=False, y=False) already disables pan/zoom, but if a future change re-enables interaction (rubber-band zoom, hover tooltips, etc.) this filter will silently break those gestures. Two small things would harden this:
- Only consume the event when the click actually lands inside the plot's data viewbox (
self.plot.getPlotItem().vb.sceneBoundingRect().contains(scene_point)), so clicks on axes/legend/title still propagate. - Reset
self._drag_start_*if a non-left button event arrives between press and release (e.g., right-click mid-drag) so the next drag starts from a clean state.
Also: the press handler returns False when _event_sample returns None but as far as I can tell _event_sample only ever returns an int (the Optional annotation is misleading). If None is genuinely impossible, drop the conditional and tighten the type.
| def _event_channel(self, event: Any) -> int | None: | ||
| point = event.position() if hasattr(event, "position") else event.pos() | ||
| scene_point = self.plot.viewport().mapToScene(point.toPoint() if hasattr(point, "toPoint") else point) | ||
| view_point = self.plot.getPlotItem().vb.mapSceneToView(scene_point) | ||
| screen_index = int(round(float(view_point.y()))) | ||
| channel_index = self.model.state.channel_offset + screen_index | ||
| if 0 <= channel_index < self.model.data.n_channels: | ||
| return channel_index | ||
| return None |
There was a problem hiding this comment.
Channel mapping likely inverted vs EEGLAB display order.
view_point.y() increases upward in pyqtgraph (the existing renderer puts screen_index 0 at y=0, which is the bottom trace because setYRange(-0.5, dispchans-0.5) isn't inverted). Mapping screen_index = round(view.y()) then matches the renderer, so clicking the topmost visible trace toggles the highest-numbered visible channel — i.e. opposite of EEGLAB, where channel 1 sits on top.
This is consistent with the existing trace rendering (pre-existing issue, not introduced here) but the new setelectrode click gesture inherits the inversion, which will confuse EEGLAB users when comparing screenshots side-by-side. Worth filing a follow-up to invert the y axis (or remap screen_index ↔ channel) in one place so both the trace order and the click mapping match EEGLAB.
| matlab_events = np.asarray(eeglab.eegplot2event(rows, -1), dtype=float) | ||
| matlab_trial, matlab_elec = eeglab.eegplot2trial(rows, 4, 3, color, [], nargout=2) | ||
|
|
||
| np.testing.assert_allclose(rows, matlab_rows) |
There was a problem hiding this comment.
This assertion will almost certainly fail when MATLAB is available.
rows here is Python trial2eegplot output (0-based starts: [0, 3], [8, 11]), while matlab_rows comes from EEGLAB's MATLAB trial2eegplot.m, which returns 1-based [(i-1)*pnts+1, i*pnts] → [1, 4], [9, 12]. np.testing.assert_allclose(rows, matlab_rows) would diff on every start/end value. The test is green only because MATLAB is skipped on this checkout (per the PR notes).
Either fix the Python trial2eegplot to match MATLAB's 1-based convention (preferred — see comment on src/eegprep/functions/sigprocfunc/eegplot.py), or rewrite this assertion to explicitly compare under the Python +0 / MATLAB +1 offset so the parity test actually documents the intentional difference. As written, this is a parity test that does not test parity.
…nto phase/eegbrowser-3-marking # Conflicts: # src/eegprep/functions/guifunc/eegbrowser.py # src/eegprep/functions/sigprocfunc/eegplot.py # tests/test_eegplot.py
|
🤖 EEGBrowser marked visual parity attached with Phase 2 is now merged into the epic branch, so I added and ran browser-specific visual parity cases for Phase 3 marked-region behavior. The side-by-side images below were uploaded as GitHub user attachments with
|
|
🤖 Updated the EEGBrowser marked-region visual parity attachments after tightening Phase 3 marking semantics. These images were uploaded with Visual checks: |





Add EEGLAB-style winrej marking, channel-mask editing, conversion helpers, and accept/cancel callbacks to the EEGPrep browser. Accepted marks now update epoched rejection fields, persist continuous mark-only windows in explicit EEGPrep winrej fields, or reject continuous data through eeg_eegrej while keeping cancel/failure paths session-safe.
Fixes #97
Part of #94