Skip to content

[EEGBrowser] Add marking and rejection callbacks - #103

Merged
suraj-ranganath merged 7 commits into
feature/eegbrowser-completionfrom
phase/eegbrowser-3-marking
May 31, 2026
Merged

suraj-ranganath merged 7 commits into
feature/eegbrowser-completionfrom
phase/eegbrowser-3-marking

Conversation

@suraj-ranganath

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

Copy link
Copy Markdown
Member

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

@claude

claude Bot commented May 31, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @suraj-ranganath's task in 8m 54s —— View job


PR Review


Summary

Solid 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 apply_eegplot_rejections.

Blocking issues

  1. apply_eegplot_rejections does not clear pre-existing marks when winrej is empty. Opening the browser on epoched data that already has EEG.reject.rejmanual set, deleting everything, and clicking Accept leaves the stored marks intact. The early return at rows.size == 0 skips _store_epoch_marks. See inline at src/eegprep/functions/popfunc/pop_eegplot.py:96-106.

  2. trial2eegplot is 0-based; EEGLAB MATLAB trial2eegplot.m is 1-based. Python produces [marked*pnts, (marked+1)*pnts-1]; MATLAB produces [(i-1)*pnts+1, i*pnts]. The MATLAB parity test asserts np.testing.assert_allclose(rows, matlab_rows) which would fail under MATLAB — currently green only because the test is skipped locally. Also causes eegplot2trial to silently drop trials ≥ 2 when fed MATLAB-format rows (the rows[rows[:, 0] == 1, 0] = 0 hack only rescues epoch 1). See inline at src/eegprep/functions/sigprocfunc/eegplot.py:398-406 and tests/test_eegplot.py:221.

Non-blocking

  1. Mixed 0-/1-based winrej convention internally. Continuous add_winrej_region clamps to max(1, …) (1-based for eeg_eegrej) while _add_epoched_winrej builds 0-based starts. Either unify or call out the dual semantics in the docstring. (eegplot.py:481-505)

  2. eventFilter swallows all left-button viewport events. Safe today because setMouseEnabled is off, but brittle if pan/rubber-band/etc are reintroduced; also accepts clicks on axes/legend area. Suggest scoping to the data viewbox and resetting drag state on non-left events. (eegbrowser.py:130-159)

  3. _event_channel mapping inherits the pre-existing inverted y-axis. Channel 1 ends up at the bottom of the canvas rather than the top (EEGLAB convention); the new setelectrode click gesture inherits this. Pre-existing rendering issue, but worth a follow-up so screenshots line up with EEGLAB. (eegbrowser.py:400-408)

  4. Superpose mode shows only rejmanual + rejglobal. EEGLAB additionally overlays rejjp, rejkurt, rejthresh, rejconst, rejfreq. Probably acceptable as deferred parity, but a TODO referencing the missing categories would help future maintainers. (pop_eegplot.py:116-133)

Nits

  • accept_callback: Any could be typed Callable[[np.ndarray], None] | None in both open_eegbrowser and EEGBrowserWindow.
  • _event_sample is annotated int | None but only ever returns int; the None arm in the press handler is dead.
  • _pad_rows 1-D reshape branch could be a one-liner; the helper currently obscures rejmanualE (channel-major) vs trial vectors when both shapes look alike.

Tests

Coverage of helpers and accept/cancel is good. Two gaps worth filling:

  • A regression test for issue (1): epoched dataset with pre-existing rejmanual, accept with empty winrej, assert rejmanual is cleared.
  • Either the parity test from issue (2) needs to actually pass under MATLAB, or be reframed to assert the deliberate offset.
    — branch phase/eegbrowser-3-marking

Comment on lines +96 to +106
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

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.

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.

Fix this →

Comment on lines +398 to +406
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

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.

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:

  • eegplot2trial only papers over the first epoch MATLAB convention via rows[rows[:, 0] == 1, 0] = 0; trials ≥ 2 would not be np.isclose-aligned (e.g. 5/4 + 1 = 2.25), so MATLAB-format rows for trials 2+ would be silently dropped.
  • The continuous add_winrej_region clamps start to max(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.

Fix this →

Comment on lines +499 to +505
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)

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.

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.

Comment on lines +130 to +159
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)

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.

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:

  1. 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.
  2. 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.

Comment on lines +400 to +408
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

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.

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.

Comment thread tests/test_eegplot.py
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)

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.

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.

@suraj-ranganath

Copy link
Copy Markdown
Member Author

🤖 Visual parity follow-up

I missed adding this when opening the PR. I generated the supported main_window_continuous visual parity capture after installing GUI deps.

  • Capture: uv run --no-sync python tools/visual_parity/capture.py --case main_window_continuous --target both --timeout 180
  • Compare: uv run --no-sync python tools/visual_parity/compare.py --case main_window_continuous
  • Result: size mismatch false, mean absolute delta 0.029064, different pixel ratio 0.075288.

Browser-specific note: this branch has EEGBrowser semantics changes, but tools/visual_parity does not yet have an eegbrowser/eegplot capture case. I also attempted a direct MATLAB eegplot export; MATLAB opened the figure but exportapp failed with a local graphics-resource/export error. The attached image is the available repository visual-parity side-by-side, not a dedicated EEGBrowser interaction capture.

main_window_continuous side_by_side.png
main_window_continuous side_by_side.png

…nto phase/eegbrowser-3-marking

# Conflicts:
#	src/eegprep/functions/guifunc/eegbrowser.py
#	src/eegprep/functions/sigprocfunc/eegplot.py
#	tests/test_eegplot.py
@suraj-ranganath

Copy link
Copy Markdown
Member Author

🤖 EEGBrowser marked visual parity attached with gh attach

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 gh attach; they are not committed visual artifacts.

  • Continuous marked browser: uv run --no-sync python tools/visual_parity/capture.py --case eegbrowser_continuous_marked --target both --timeout 180; compare mean absolute delta 0.059935, different pixel ratio 0.377509, size mismatch false.
  • Epoched marked browser: uv run --no-sync python tools/visual_parity/capture.py --case eegbrowser_epoched_marked --target both --timeout 180; compare mean absolute delta 0.081357, different pixel ratio 0.633869, size mismatch false.
eegbrowser_continuous_marked_side_by_side.png eegbrowser_epoched_marked_side_by_side.png
eegbrowser_continuous_marked_side_by_side.png eegbrowser_epoched_marked_side_by_side.png

@suraj-ranganath

Copy link
Copy Markdown
Member Author

🤖 Updated the EEGBrowser marked-region visual parity attachments after tightening Phase 3 marking semantics. These images were uploaded with gh attach as GitHub user attachments, not committed visual artifacts.

Continuous marked browser: eegbrowser_continuous_marked_semantics_side_by_side.png

Epoched marked browser: eegbrowser_epoched_marked_semantics_side_by_side.png

Visual checks: eegbrowser_continuous_marked mean_abs_delta 0.060064, different_pixel_ratio 0.377509; eegbrowser_epoched_marked mean_abs_delta 0.078376, different_pixel_ratio 0.474917. The epoched fixture uses later epochs for screenshot capture to avoid an EEGLAB R2026a first-epoch drawing callback error while the unit tests still cover the first-epoch zero-boundary conversion semantics.

@suraj-ranganath suraj-ranganath changed the title Phase 3 EEGBrowser marking and rejection callbacks [EEGBrowser] Add marking and rejection callbacks May 31, 2026
@suraj-ranganath
suraj-ranganath merged commit 561f5f9 into feature/eegbrowser-completion May 31, 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