Skip to content

[EEGBrowser] Implement eegplot browser foundation - #102

Merged
suraj-ranganath merged 2 commits into
feature/eegbrowser-completionfrom
phase/eegbrowser-1-foundation
May 31, 2026
Merged

suraj-ranganath merged 2 commits into
feature/eegbrowser-completionfrom
phase/eegbrowser-1-foundation

Conversation

@suraj-ranganath

Copy link
Copy Markdown
Member

Add the non-mutating eegplot browser model, public API, pop_eegplot wrapper, pyqtgraph Qt renderer, packaged help, and menu integration. Covers option parsing, normalization, events, winrej, decimation, sample-data rendering, and public exports for Phase 1.\n\nFixes #95

@claude

claude Bot commented May 31, 2026 •

Copy link
Copy Markdown
Contributor

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


🤖 PR Review — Phase 1 EEGBrowser Foundation

  • Read repo guidelines (CLAUDE.md / AGENTS.md)
  • Read changed files vs base origin/feature/eegbrowser-completion
  • Check EEGLAB parity for eegplot / pop_eegplot
  • Validate BrowserModel, options, normalization, decimation logic
  • Validate Qt renderer and event/winrej overlay
  • Check tests, conftest categorization, package exports
  • Post review feedback (with inline comments where useful)

Summary

Scope is consistent with what the description promises: a non-mutating model layer (BrowserData/BrowserState/BrowserModel) in sigprocfunc/eegplot.py, a PySide6 + pyqtgraph renderer in guifunc/eegbrowser.py, a pop_eegplot wrapper, packaged help, menu wiring, and tests. The model layer is cleanly separated from the GUI, options parsing accepts both Python kwargs and EEGLAB-style key/value pairs, channel-major shape and 3‑D flattening match EEGLAB conventions, and the GUI is gated behind an optional gui extra with a clear error message — all in line with AGENTS.md. Tests cover the headless model paths plus a single offscreen GUI smoke test, and tests/conftest.py marks tests/test_eegplot_gui.py as gui. Public-export and packaged-help expectations are wired through test_package_exports.py / test_public_api_examples.py. Phase-1 non-mutation is preserved (pop_eegplot returns EEG unchanged with a history string).

Findings (posted inline)

  1. eegbrowser.py:68-87 Display menu labels go stale after first toggle. Labels are computed once from the initial state and never re-set; clicking "X grid on" flips the state but the menu still reads "X grid on". Concrete fix: store the QActions on self and call setText with a label recomputed from current state inside each _toggle_* handler.
  2. eegplot.py:419-436 _apply_frequency_limits semantics. Two issues: (a) it mutates the caller's options dict in place, which makes the flow between _model_options and build_eegplot_model non-obvious; (b) it overwrites srate with samples per Hz, so in mode == "spectral" winlength is implicitly a Hz-range. That's undocumented in both the docstring and resources/help/eegplot.md.
  3. eegplot.py:200-232 + pop_eegplot.py:45 Double ICA recomputation. When component=True and EEG.icaact is empty, component_activations(EEG) runs once in _default_spacing (via _model_options), again in normalize_browser_data, and again as a "validation" call inside pop_eegplot. For real datasets this is the expensive weights @ sphere @ data matmul repeated 2–3×. Cache once in _model_options (or thread the array through options).
  4. eegplot.py:282-290 Decimation can crash on all-NaN segments. np.nanargmin/np.nanargmax raise ValueError: All-NaN slice encountered. Realistic for recordings with boundary-padded epochs or pre-rejected channels. Skip all-NaN segments or fall through to segment endpoints.
  5. eegbrowser.py:125-138 Continuous mode plots in sample indices but labels in seconds. x_values = np.arange(start, stop) is sample indices while the bottom axis advertises units="s", with ticks placed at current * srate and labelled as the seconds value. Works visually now but will mislead future zoom/click/ROI features. Suggest plotting in seconds (and adjusting winrej/event x-positions) or removing units="s".

Other notes (not posted inline)

  • copy_model_with_state is exported in __all__ but unused in this PR — fine if it's planned for the next phase, otherwise drop it.
  • pop_eegplot docstring states Phase 1 is non-mutating but pop_eegplot.py:30-31 returns (None, "") when EEG is None and return_com=True — consistent with EEGLAB's pop_eegplot early-out behavior, but worth double-checking against the GUI dispatcher path which calls with a real EEG selection.
  • parse_eegplot_options correctly rejects unknown keys, but the show kwarg is consumed before it reaches parse_eegplot_options via kwargs.get("show", True). It's in _OPTION_NAMES so the check passes, but show is never an EEGLAB key — minor inconsistency.

Overall the foundation looks solid and well-tested for Phase 1. The five inline findings above are the items I'd address before merging.
| Branch

@suraj-ranganath

Copy link
Copy Markdown
Member Author

🤖 Phase 1 specification and verification

Problem: EEGPrep had no implemented eegplot/EEGBrowser runtime surface; pop_eegplot menu actions were classified as EEGBrowser placeholders, so users could not open an EEGLAB-style scrolling viewer from the public API or GUI menus.

Approach: Added src/eegprep/functions/sigprocfunc/eegplot.py for option parsing, BrowserData/BrowserState/BrowserModel, continuous/epoched/component/spectral/overlay normalization, winrej/event state, window bounds, and min/max decimation. Added src/eegprep/functions/guifunc/eegbrowser.py for a PySide6 + pyqtgraph renderer using optimized curves, LinearRegionItem winrej overlays, InfiniteLine event markers, grids, scale, basic scrolling, and spacing controls. Added src/eegprep/functions/popfunc/pop_eegplot.py, lifted the menu placeholder, exported eegplot/pop_eegplot, and added packaged help.

Key code:

def decimate_minmax(x_values: np.ndarray, y_values: np.ndarray, pixel_width: int) -> tuple[np.ndarray, np.ndarray]:
    x = np.asarray(x_values, dtype=float).ravel()
    y = np.asarray(y_values, dtype=float).ravel()
    if x.size != y.size:
        raise ValueError("x_values and y_values must have matching lengths")
    if x.size == 0:
        return x, y
    max_points = max(1, int(pixel_width)) * DECIMATION_SAMPLES_PER_PIXEL
    if x.size <= max_points:
        return x, y
    edges = np.linspace(0, x.size, max(1, int(pixel_width)) + 1, dtype=int)
    keep: set[int] = {0, x.size - 1}
    for start, stop in zip(edges[:-1], edges[1:]):
        if stop <= start:
            continue
        segment = y[start:stop]
        keep.add(start + int(np.nanargmin(segment)))
        keep.add(start + int(np.nanargmax(segment)))
    indices = np.fromiter(sorted(keep), dtype=int)
    return x[indices], y[indices]

Tests: Added focused headless tests for option parsing, normalization modes, epoched flattening/window bounds, event latency conversion, decimation, winrej state, sample_data/eeglab_data.set, pop_eegplot no-mutation behavior, and public exports/resources. Added a GUI smoke test that opens sample_data/eeglab_data.set offscreen and asserts a nonblank rendered browser without mutating EEG data.

Dependency decision: pyqtgraph was added to the gui extra because later EEGBrowser phases need performant large-trace drawing, built-in downsampling, view interaction, event lines, and editable regions. This is a better long-term foundation than maintaining custom QPainter trace, hit-test, and region code.

Visual evidence: Generated an offscreen EEGPrep render from sample_data/eeglab_data.set at /tmp/eegbrowser-phase1-eegprep.png. A true side-by-side EEGLAB attachment was not available from this CLI-only run because the vendored EEGLAB reference checkout is absent in this worktree and GitHub user-attachment upload is not exposed through the available tools.

Comment on lines +68 to +87
def _build_menus(self) -> None:
menu = self.menuBar().addMenu("Display")
xgrid_action = menu.addAction("X grid off" if self.model.state.xgrid else "X grid on")
xgrid_action.triggered.connect(self._toggle_xgrid)
ygrid_action = menu.addAction("Y grid off" if self.model.state.ygrid else "Y grid on")
ygrid_action.triggered.connect(self._toggle_ygrid)
scale_action = menu.addAction("Hide scale" if self.model.state.scale else "Show scale")
scale_action.triggered.connect(self._toggle_scale)

def _toggle_xgrid(self) -> None:
self.model.state.xgrid = not self.model.state.xgrid
self.canvas.redraw()

def _toggle_ygrid(self) -> None:
self.model.state.ygrid = not self.model.state.ygrid
self.canvas.redraw()

def _toggle_scale(self) -> None:
self.model.state.scale = not self.model.state.scale
self.canvas.redraw()

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 "Display" menu labels are baked in at build time based on the initial state, so they go stale after the first toggle.

For example, the xgrid_action label is "X grid off" if self.model.state.xgrid else "X grid on" once. After the user clicks it, state.xgrid flips but the menu text still reads "X grid on". Same for ygrid_action and scale_action.

Suggest storing the QActions on the window and refreshing their text in the toggle handlers (or using QAction.setText with a small helper that recomputes the label from current state). Otherwise the menu is misleading after the very first interaction.
Fix this →

Comment on lines +419 to +436
def _apply_frequency_limits(array: np.ndarray, options: dict[str, Any]) -> np.ndarray:
freqs = options.get("freqs")
freqlimits = options.get("freqlimits")
if freqs is None and freqlimits is None:
return array
if freqs is None or freqlimits is None:
raise ValueError("freqs and freqlimits must be supplied together")
freq_values = np.asarray(freqs, dtype=float).ravel()
bounds = np.asarray(freqlimits, dtype=float).ravel()
if freq_values.size != array.shape[1] or bounds.size != 2:
raise ValueError("freqs must match data samples and freqlimits must contain [start end]")
start = int(np.argmin(np.abs(freq_values - bounds[0])))
end = int(np.argmin(np.abs(freq_values - bounds[1])))
if end < start:
start, end = end, start
options["srate"] = float((end - start + 1) / max(freq_values[end] - freq_values[start], 1.0))
options["limits"] = (float(freq_values[start]), float(freq_values[end]))
return array[:, start : end + 1, :]

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.

Two things worth flagging here:

  1. Side-effect on the options dict. _apply_frequency_limits quietly overwrites options["srate"] and options["limits"] on the caller's dict (the same dict that _model_options returned and that build_eegplot_model reads after normalize_browser_data returns). This makes the relationship between the user-supplied srate and the final state unobvious. Prefer returning the derived (array, srate, limits) triple and letting the caller decide whether to assign.
  2. Hijacking srate for spectral mode. The value assigned is (end - start + 1) / max(freq_values[end] - freq_values[start], 1.0) — units of samples per Hz, not Hz. It only works because time_to_sample/visible_sample_bounds treat srate as a generic multiplier. The user-facing implication is that winlength in spectral mode is interpreted in Hz, but neither the docstring nor help/eegplot.md mentions that. Worth either documenting the unit semantics for mode == "spectral" or routing spectral rendering through an explicit frequency-axis path instead.

Comment on lines +200 to +232
def normalize_browser_data(data: Any, options: dict[str, Any]) -> BrowserData:
"""Normalize array, EEG, component, spectral, and overlay inputs."""
source_eeg = data if isinstance(data, dict) else None
component = bool(options.get("component", False))
if source_eeg is not None:
raw_data = component_activations(source_eeg) if component else source_eeg.get("data")
else:
raw_data = data
array = _as_channel_data(raw_data)
array = _apply_frequency_limits(array, options)
flat = flatten_browser_data(array)
labels = _channel_labels(source_eeg, array.shape[0], options["eloc_file"], component=component)
mode = _browser_mode(array, component=component, freqs=options.get("freqs"))
data2 = options.get("data2")
flat_data2 = None
data2_array = None
if data2 is not None and not _is_empty(data2):
data2_array = _as_channel_data(data2)
data2_array = _apply_frequency_limits(data2_array, options)
if data2_array.shape != array.shape:
raise ValueError("data2 must have the same normalized shape as data")
data2_array = np.array(data2_array, dtype=float, copy=True)
flat_data2 = flatten_browser_data(data2_array)
return BrowserData(
data=np.array(array, dtype=float, copy=True),
flat_data=flat,
pnts=int(array.shape[1]),
trials=int(array.shape[2]),
channel_labels=labels,
mode=mode,
data2=data2_array,
flat_data2=flat_data2,
)

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.

For the component-mode + EEG-dict path, component_activations(source_eeg) is invoked here on every model build, and _default_spacing already calls component_activations(source_eeg) from _model_options when component=True and spacing is not supplied. When EEG.icaact is empty, both calls recompute weights @ sphere @ data, which is the expensive path for full-resolution datasets.

Cheap fix: compute activations once in _model_options (or pass through a cached array via options["_component_data"]) and reuse them here. Similar story for pop_eegplot.py:45, where component_activations(EEG) is called as a validation step and then eegplot will recompute internally.

Comment on lines +282 to +290
keep: set[int] = {0, x.size - 1}
for start, stop in zip(edges[:-1], edges[1:]):
if stop <= start:
continue
segment = y[start:stop]
keep.add(start + int(np.nanargmin(segment)))
keep.add(start + int(np.nanargmax(segment)))
indices = np.fromiter(sorted(keep), dtype=int)
return x[indices], y[indices]

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.

If any segment is all-NaN (e.g., after submean on a trace that was already NaN, or for boundary-padded epochs), np.nanargmin/np.nanargmax raise ValueError: All-NaN slice encountered. The renderer would crash mid-redraw for the affected channel.

For typical clean data this is fine, but Phase 1 will get exercised on real recordings. Suggest either skipping all-NaN segments with if not np.isfinite(segment).any(): continue or catching the ValueError and falling through to the segment endpoints.

Comment on lines +125 to +138
def _configure_axes(self) -> None:
start, stop = visible_sample_bounds(self.model.data, self.model.state)
self.plot.setXRange(float(start), float(stop), padding=0)
self.plot.setYRange(-0.5, float(self.model.state.dispchans) - 0.5, padding=0.04)
labels = []
for screen_index, channel_index in enumerate(self._visible_channels()):
labels.append((float(screen_index), self.model.data.channel_labels[channel_index]))
self.plot.getAxis("left").setTicks([labels])
self.plot.getAxis("bottom").setLabel(
"Epoch" if self.model.data.epoched else "Time", units="" if self.model.data.epoched else "s"
)
self.plot.getAxis("bottom").setTicks([self._x_ticks(start, stop)])
if self.model.state.plottitle:
self.plot.setTitle(self.model.state.plottitle)

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.

In continuous mode the canvas plots traces against raw sample indices (x_values = np.arange(start, stop)), but the bottom axis labels (_x_ticks) and label units="s" advertise seconds. The two stay visually aligned only because ticks are placed at current * srate while showing f"{current:g}", so the numeric labels happen to match elapsed seconds.

This works for static viewing, but anything that interprets axis values directly — future zoom/pan, ROI drawing, "click to set time" — will see sample indices, not seconds, and the unit suffix will lie. Worth either plotting in seconds (x_values / srate) and adjusting the winrej/event x positions accordingly, or dropping units="s" so the unit is unitless ticks-as-seconds.

@suraj-ranganath
suraj-ranganath merged commit c9dc4cf 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