Repository navigation
[EEGBrowser] Implement eegplot browser foundation - #102
suraj-ranganath merged 2 commits into
Conversation
|
Claude finished @suraj-ranganath's task in 4m 44s —— View job 🤖 PR Review — Phase 1 EEGBrowser Foundation
SummaryScope is consistent with what the description promises: a non-mutating model layer ( Findings (posted inline)
Other notes (not posted inline)
Overall the foundation looks solid and well-tested for Phase 1. The five inline findings above are the items I'd address before merging. |
|
🤖 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. |
| 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() |
There was a problem hiding this comment.
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 →
| 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, :] |
There was a problem hiding this comment.
Two things worth flagging here:
- Side-effect on the options dict.
_apply_frequency_limitsquietly overwritesoptions["srate"]andoptions["limits"]on the caller's dict (the same dict that_model_optionsreturned and thatbuild_eegplot_modelreads afternormalize_browser_datareturns). This makes the relationship between the user-suppliedsrateand the final state unobvious. Prefer returning the derived(array, srate, limits)triple and letting the caller decide whether to assign. - 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 becausetime_to_sample/visible_sample_boundstreatsrateas a generic multiplier. The user-facing implication is thatwinlengthin spectral mode is interpreted in Hz, but neither the docstring norhelp/eegplot.mdmentions that. Worth either documenting the unit semantics formode == "spectral"or routing spectral rendering through an explicit frequency-axis path instead.
| 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, | ||
| ) |
There was a problem hiding this comment.
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.
| 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] |
There was a problem hiding this comment.
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.
| 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) |
There was a problem hiding this comment.
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.
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