Repository navigation
[Phase 4] Add plotting core wrappers - #75
Conversation
|
Claude finished @suraj-ranganath's task in 6m 18s —— View job Claude PR Review — #75 (Phase 4 plotting wrappers)Thanks for the broad Phase 4 surface — wrappers, core plotters, GUI dialogs, Plot-menu wiring, help resources, and headless tests all land coherently. Inline comments posted; summary below. Todo
FindingsCorrectness
Surface / parity gaps in GUI optionsSeveral dialogs collect rich option sets but the wrappers only consume a few:
Either implement them or trim the dialog specs so users aren't misled. Either path is fine for a phased rollout — just make the gap explicit (help text or Lower-priority observations
What looks good
Not addressed (out of scope for this review)
|
|
🤖 Phase 4 plotting core specification Problem Phase 4 needs Plot-menu workflows that are usable without EEGLAB at runtime while preserving familiar EEGLAB entry points, labels, history strings, and GUI option dialogs. PR #72 added the topography foundation; this PR fills the next layer of plotting wrappers around spectra, ERP arrays, ERP images, property views, envelopes, comparisons, head maps, and STUDY channel-measure handoff. Approach Added shared plotting helpers in Key code The wrappers share one normalization/history path so GUI, Python API, and def history_command(name: str, positional: list[Any], kwargs: dict[str, Any] | None = None) -> str:
pieces = [python_literal(value) for value in positional]
pieces.extend(f"{key}={python_literal(value)}" for key, value in (kwargs or {}).items())
return f"{name}({', '.join(pieces)})"The Plot menu dispatch calls the new wrappers without mutating EEG data, and only appends the returned history command when a plot action actually runs. Channel/component variants fail clearly when required data or ICA fields are missing. Tests Ran Visual parity Added visual parity cases for every new GUI option dialog. Captured side-by-side EEGLAB vs EEGPrep images locally under |
|
🤖 GUI visual parity evidence for Phase 4 plotting wrappers. Local artifacts are under Side-by-side screenshotspop_spectopo channels dialog pop_spectopo components dialog pop_prop channels dialog pop_prop components dialog pop_timtopo dialog pop_plottopo dialog pop_plotdata dialog pop_erpimage channels dialog pop_erpimage components dialog pop_envtopo dialog pop_comperp channels dialog pop_comperp components dialog pop_headplot ERP dialog (EEGPrep only; EEGLAB capture opens spline/coregistration workflow) pop_headplot components dialog (EEGPrep only; EEGLAB capture opens spline/coregistration workflow) |
| trace_2d = trace if trace.ndim == 2 else trace[:, np.newaxis] | ||
| erp_ax.plot(times, np.nanmean(trace_2d, axis=1), color="black") | ||
| erp_ax.axhline(0, color="0.7", linewidth=0.6) | ||
| erp_ax.set_xlabel("Time (ms)") | ||
| erp_ax.set_ylabel("uV") | ||
| spectra, freqs, _std = compute_spectra(trace_2d.T, trace_2d.shape[0], float(EEG.get("srate", 1) or 1)) | ||
| spec_ax.plot(freqs, spectra[0], color="black") |
There was a problem hiding this comment.
Spectrum is computed per-trial, not over the whole channel/component.
trace_2d has shape (pnts, trials). After .T, compute_spectra is given (trials, pnts) and treats each trial as a separate "channel," so spectra[0] plots only the first trial's spectrum — not the across-trial spectrum EEGLAB's pop_prop shows. EEGLAB does spectopo(reshape(EEG.data(chan,:,:), 1, []), EEG.pnts, EEG.srate, ...) — a single concatenated row.
| trace_2d = trace if trace.ndim == 2 else trace[:, np.newaxis] | |
| erp_ax.plot(times, np.nanmean(trace_2d, axis=1), color="black") | |
| erp_ax.axhline(0, color="0.7", linewidth=0.6) | |
| erp_ax.set_xlabel("Time (ms)") | |
| erp_ax.set_ylabel("uV") | |
| spectra, freqs, _std = compute_spectra(trace_2d.T, trace_2d.shape[0], float(EEG.get("srate", 1) or 1)) | |
| spec_ax.plot(freqs, spectra[0], color="black") | |
| trace_2d = trace if trace.ndim == 2 else trace[:, np.newaxis] | |
| erp_ax.plot(times, np.nanmean(trace_2d, axis=1), color="black") | |
| erp_ax.axhline(0, color="0.7", linewidth=0.6) | |
| erp_ax.set_xlabel("Time (ms)") | |
| erp_ax.set_ylabel("uV") | |
| flat = trace_2d.reshape(1, -1) | |
| spectra, freqs, _std = compute_spectra(flat, flat.shape[1], float(EEG.get("srate", 1) or 1)) | |
| spec_ax.plot(freqs, spectra[0], color="black") |
| } | ||
|
|
||
|
|
||
| def _plot_one_property(EEG: dict[str, Any], typecomp: int, index: int, _spec_opt: Any): |
There was a problem hiding this comment.
spec_opt is collected by the dialog (default 'freqrange', [2, 50]) and forwarded into _plot_one_property, but the parameter is captured as _spec_opt and never used to influence the spectrum subplot. The dialog suggests user-controllable spectral options, but currently any value (freqrange, plot limits, etc.) is silently dropped. Either:
- parse
spec_optand forward the relevant kwargs (freqrange, etc.) intocompute_spectra/plot_spectra, or - remove the dialog row / document the limitation in
resources/help/pop_prop.mdso users don't expect it to work.
| """Plot largest component ERP envelopes and component maps.""" | ||
| if EEG is None: | ||
| return (None, "") if return_com else None | ||
| dataset = EEG[-1] if isinstance(EEG, list) else EEG |
There was a problem hiding this comment.
When called with a list of datasets, the wrapper silently uses only the last one (EEG[-1]). EEGLAB's pop_envtopo typically supports two-condition comparisons or grand-average envelopes across ALLEEG datasets; quietly throwing away all but the last is surprising. If this is intentional for Phase 4, please either:
- raise
NotImplementedErrorwhenlen(EEG) > 1so callers don't silently lose data, or - document the simplification in
resources/help/pop_envtopo.mdso users see it in the Help button.
(Also note the dispatcher passes the whole selection list when allow_multiple=True — see menu_actions.py:828.)
| icaweights = np.asarray(dataset.get("icaweights", []), dtype=float) | ||
| icasphere = np.asarray(dataset.get("icasphere", []), dtype=float) | ||
| if icaweights.size == 0 or icasphere.size == 0: | ||
| raise ValueError("pop_envtopo requires ICA weights") | ||
| weights = icaweights @ icasphere | ||
| figure = envtopo( |
There was a problem hiding this comment.
weights = icaweights @ icasphere is (ncomp × n_icachannels), but data returned from data_time_slice covers all nbchan channels in EEG.data. If channels were rejected after ICA fit (so nbchan != len(icachansind)), the inner weight_values @ values in envtopo() will raise a shape mismatch error from numpy that doesn't explain the underlying mismatch. Consider selecting data[icachansind, :, :] (1-based → 0-based) before averaging, or at minimum raising a clearer ValueError when shapes don't line up.
| pnts = int(EEG.get("pnts", 0) or 0) | ||
| if pnts <= 0: | ||
| raise ValueError("EEG.pnts must be positive") | ||
| times = np.asarray(EEG.get("times", []), dtype=float).ravel() | ||
| if times.size == pnts: | ||
| xmax = float(EEG.get("xmax", 0) or 0) | ||
| if times.size > 1 and np.nanmax(np.abs(times)) <= max(abs(xmax), 1.0) * 2: | ||
| return times * 1000.0 | ||
| return times | ||
| xmin = float(EEG.get("xmin", 0) or 0) | ||
| xmax = float(EEG.get("xmax", xmin) or xmin) | ||
| return np.linspace(xmin * 1000.0, xmax * 1000.0, pnts) |
There was a problem hiding this comment.
The times.size == pnts branch uses a heuristic — abs(times).max() <= max(|xmax|, 1) * 2 — to decide whether EEG.times is already in milliseconds. For datasets where times are stored in seconds with |xmax| near zero (e.g. xmin=-0.05, xmax=0.05), the bound max(|xmax|, 1)*2 = 2 will incorrectly classify millisecond-scale times (≤ 100 ms ≈ 100) as seconds and re-multiply by 1000 — or vice-versa for other ranges.
EEGLAB's EEG.times is unambiguously stored in ms (see eeg_checkset.m). It would be simpler and safer to trust the EEGLAB convention: if times.size == pnts, return as-is; otherwise fall back to linspace(xmin*1000, xmax*1000, pnts). If you want to defend against mis-stored datasets, raise rather than guess.
| kwargs: dict[str, Any] = { | ||
| "dataflag": int(dataflag), | ||
| "timerange": timerange, | ||
| "process": process, | ||
| "freqs": freqs, | ||
| "freqrange": freqrange, | ||
| "percent": percent, | ||
| } | ||
| kwargs.update(options) | ||
| pieces = ["EEG", *(f"{key}={python_literal(value)}" for key, value in kwargs.items())] | ||
| return f"pop_spectopo({', '.join(pieces)})" |
There was a problem hiding this comment.
The history command always includes every keyword even when it's None/empty (freqs=[], freqrange=[], timerange=None, process='EEG'). The CLI command shown to users via eegprep-console ends up very noisy, e.g. pop_spectopo(EEG, dataflag=1, timerange=None, process='EEG', freqs=[], freqrange=[], percent=100.0).
Consider only including non-default kwargs, matching history_command from _plot_utils.py (which skips None). Other plot wrappers in this PR already use history_command — this is the only one that hand-rolls its own builder, and the divergence is the reason for the noise.
| spectra = 10.0 * np.log10(np.maximum(power, np.finfo(float).tiny)) | ||
| specstd = np.zeros_like(spectra) | ||
| return spectra, freqs, specstd |
There was a problem hiding this comment.
specstd is returned as np.zeros_like(spectra) rather than an actual cross-segment standard deviation. EEGLAB's spectopo returns the std across Welch segments (or across epochs if boundaries/overlap are set). A pure-zero specstd will cause downstream consumers (and any caller looking at result["specstd"]) to silently see "no variability." Either:
- compute it from per-segment power via
scipy.signal.spectrogramand convert to dB, or - return
Noneso the absence is explicit.
| sub_indices = _dataset_indices(datsub, len(datasets), allow_empty=True) | ||
| erp1 = _grand_erp([datasets[index] for index in add_indices], int(flag), kwargs.get("chans")) | ||
| erp2 = ( | ||
| _grand_erp([datasets[index] for index in sub_indices], int(flag), kwargs.get("chans")) | ||
| if sub_indices.size | ||
| else None | ||
| ) | ||
| erpsub = erp1 - erp2 if erp2 is not None else None |
There was a problem hiding this comment.
When gui=True and the GUI dialog is the source of inputs, the addavg/addstd/addall/subavg/... checkboxes and the mode/alpha/lowpass options are collected and forwarded into kwargs, but _grand_erp / _plot_comperp only consume chans and title. So all of:
- RMS vs. average (
mode) - low-pass display filter (
lowpass) - standard-deviation overlay (
addstd/substd/diffstd) - single-trial overlay (
addall/suball/diffall) - significance highlighting (
alpha)
…appear in the dialog but are silently ignored at runtime. That risks user surprise: someone checks "Use RMS" and gets a plain average. Either honor the options or trim the dialog spec down to what the wrapper actually implements for Phase 4. Same goes for tplotopt ('ydir', -1).
| def _headplot_maps(EEG: dict[str, Any], typeplot: int, items: np.ndarray) -> tuple[list[np.ndarray], list[str]]: | ||
| if items.size == 0: | ||
| raise ValueError("items must contain at least one latency or component index") | ||
| if typeplot: | ||
| data, _times = data_time_slice(EEG, None) | ||
| erp = np.nanmean(data, axis=2) | ||
| all_times = eeg_times_ms(EEG) | ||
| maps = [] | ||
| labels = [] | ||
| for latency in items: | ||
| frame = int(np.argmin(np.abs(all_times - latency))) | ||
| maps.append(erp[:, frame]) | ||
| labels.append(f"{latency:g} ms") | ||
| return maps, labels |
There was a problem hiding this comment.
For the ERP case, latencies coming straight from the GUI's items field default to "0" (line 55) — meaning the dialog only ever plots a single latency at 0 ms unless the user types more values. That's fine, but the snapping code (argmin(abs(all_times - latency))) silently picks the closest frame even if the requested latency is far outside the data range (e.g. latency=1e6 when xmax=400). Consider validating that requested latencies fall within [xmin*1000, xmax*1000] and raising a clear error otherwise, matching EEGLAB's headplot() which errors out for out-of-range latencies.
| def headplot(values: Any, chanlocs: Any, *, title: str = "3-D scalp map"): | ||
| """Plot channel or component weights on a 3-D head sphere. | ||
|
|
||
| EEGLAB's full ``headplot`` uses spline/mesh resources. EEGPrep currently | ||
| provides a standalone static 3-D map over channel coordinates and fails | ||
| clearly when usable 3-D channel locations are missing. | ||
| """ | ||
| locs = chanlocs_as_list(chanlocs) | ||
| coordinates = np.asarray([_xyz(loc) for loc in locs], dtype=float) | ||
| if coordinates.size == 0 or not np.isfinite(coordinates).all(): | ||
| raise ValueError("headplot requires channel locations with X/Y/Z coordinates") | ||
| data = np.asarray(values, dtype=float).ravel() | ||
| if data.size != coordinates.shape[0]: | ||
| raise ValueError("headplot values must have one value per channel") | ||
|
|
||
| fig = plt.figure(figsize=(5.5, 5.0)) | ||
| ax = fig.add_subplot(111, projection="3d") | ||
| _draw_head_sphere(ax) | ||
| scatter = ax.scatter( | ||
| coordinates[:, 0], | ||
| coordinates[:, 1], | ||
| coordinates[:, 2], | ||
| c=data, | ||
| cmap="RdBu_r", | ||
| s=70, | ||
| depthshade=False, | ||
| ) | ||
| for point, loc in zip(coordinates, locs): | ||
| label = str(loc.get("labels") or "") | ||
| if label: | ||
| ax.text(point[0], point[1], point[2], label, fontsize=8) | ||
| fig.colorbar(scatter, ax=ax, shrink=0.7) | ||
| ax.set_title(title) | ||
| ax.set_axis_off() | ||
| ax.set_box_aspect((1, 1, 1)) | ||
| fig.tight_layout() | ||
| return fig |
There was a problem hiding this comment.
The current rendering is more of a 3-D channel scatter on a wireframe than an interpolated scalp surface — EEGLAB's headplot() produces a smooth spline-interpolated scalp map by triangulating the standard mesh and projecting via the spline file. Calling this headplot will probably confuse EEGLAB users who expect that look.
Two suggestions:
- Make the difference visible to users by including a one-line note in
resources/help/pop_headplot.mdso it's surfaced via the Help button (the current help text doesn't mention the simplification). - Add a
topoplot-style interpolation fallback (or reuse the existingtopoplotinterpolation on a hemisphere mesh) as a follow-up. Not blocking for Phase 4 if scoped that way.
| values = numeric_vector(result.get("index", 1), dtype=int) | ||
| return { | ||
| "index": int(values[0]) if values.size else 1, | ||
| "options": { | ||
| "title": str(result.get("title", "") or ""), | ||
| "smooth": numeric_vector(result.get("smooth", [])).tolist(), | ||
| "decimate": numeric_vector(result.get("decimate", [])).tolist(), | ||
| "limits": numeric_vector(result.get("limtime", [])).tolist(), | ||
| "plotmap": bool(result.get("plotmap", False)), | ||
| "erp": bool(result.get("erp", True)), | ||
| "cbar": bool(result.get("cbar", True)), | ||
| "caxis": numeric_vector(result.get("caxis", [])).tolist(), | ||
| "sortingeventfield": str(result.get("field", "") or ""), | ||
| "sortingtype": str(result.get("type", "") or ""), | ||
| "sortingwin": numeric_vector(result.get("eventrange", [])).tolist(), | ||
| "renorm": str(result.get("renorm", "") or ""), | ||
| "align": numeric_vector(result.get("align", [])).tolist(), | ||
| "nosort": bool(result.get("nosort", False)), | ||
| "noplot": bool(result.get("noplot", False)), | ||
| "phasesort": numeric_vector(result.get("phase", [])).tolist(), | ||
| "coher": numeric_vector(result.get("coher", [])).tolist(), | ||
| "plotamps": bool(result.get("plotamps", False)), | ||
| "spec": numeric_vector(result.get("spec", [])).tolist(), | ||
| "vert": numeric_vector(result.get("vert", [])).tolist(), | ||
| "others": str(result.get("others", "") or ""), | ||
| }, | ||
| } |
There was a problem hiding this comment.
Every option harvested from the dialog (smooth, decimate, limits, plotmap, cbar, caxis, sortingeventfield, sortingtype, sortingwin, renorm, align, nosort, noplot, phasesort, coher, plotamps, spec, vert, others) is forwarded into kwargs, but the only ones the underlying erpimage() actually consumes are times, title, and sort_values. Even basic features users would expect — sort by event field, decimate, color-axis — are silently ignored.
Because the wrapper passes this collected dict through history_command, the recorded console command will look like a fully parameterized call, e.g.
pop_erpimage(EEG, 1, 1, smooth=[5], decimate=[2], limits=[-100, 600], plotmap=True, ...)
…but rerunning that command will reproduce the same minimal plot. That hurts the EEGLAB-parity claim and the "console history is replayable" contract. Suggest either implementing at least sort/smooth/decimate or trimming the dialog spec to match what's supported in Phase 4.
| for channel in selected: | ||
| erps = [] | ||
| for eeg in datasets: | ||
| if int(eeg.get("trials", 1) or 1) <= 1: | ||
| raise ValueError("pop_chanplot ERP measure plotting requires epoched datasets") | ||
| erps.append(np.nanmean(eeg_epoch_data(eeg)[channel, :, :], axis=1)) | ||
| ax.plot(times, np.nanmean(np.stack(erps, axis=0), axis=0), label=labels[channel]) |
There was a problem hiding this comment.
times = eeg_times_ms(datasets[0]) is taken from the first dataset and reused for every dataset's ERP. If the datasets differ in pnts/xmin/xmax (which can happen in a STUDY combining multiple subjects), this silently misaligns the per-dataset trial averages. Either:
- validate that every dataset shares
(pnts, srate, xmin, xmax)and raise a clear error otherwise, or - resample/interpolate to a common time grid before stacking.
This isn't hypothetical — STUDY tutorials in EEGLAB explicitly warn that subjects often need to be epoched/aligned to a shared latency vector before group ERP plotting.
| def _run_gui(EEG: dict[str, Any], *, renderer: Any | None = None) -> dict[str, Any] | None: | ||
| result = inputgui(pop_plottopo_dialog_spec(EEG), renderer=renderer) | ||
| if result is None: | ||
| return None | ||
| return { | ||
| "chans": numeric_vector(result.get("chans", []), dtype=int).tolist(), | ||
| "options": { | ||
| "title": str(result.get("title", "") or ""), | ||
| "singletrials": bool(result.get("singletrials", False)), | ||
| "rect": bool(result.get("rect", False)), | ||
| "options": str(result.get("options", "") or ""), | ||
| }, | ||
| } |
There was a problem hiding this comment.
The dialog collects singletrials, rect, and a free-form options string, but they're never threaded down to plottopo(). Two consequences:
- Checking "Plot single trials" or "Plot in rect. array" silently has no effect.
- The "Other plot options" line is parsed nowhere — it ends up as a stray string in
kwargs["options"]and only surfaces in the recorded history command.
plottopo() already supports ydir; adding rect (square grid vs scalp-like layout) and singletrials (don't average across trials) would be small wins. At minimum, drop the controls that don't do anything so the dialog doesn't promise behavior the wrapper can't deliver.
d03fff0 to
b7be5e6
Compare
|
@claude review this |
|
Claude finished @suraj-ranganath's task in 3m 53s —— View job Claude PR Re-review — Phase 4 plotting wrappers (after fixups)Re-reviewed Todo
What was fixed since the first pass
Remaining minor observations (non-blocking)
|





















Add Phase 4 plotting wrappers for spectra, ERP images, topographic summaries, channel/component properties, envelopes, comparison plots, head maps, and STUDY channel-measure handoff. Wires the Plot menu, help resources, visual parity cases, and headless sample-data coverage.
Part of #64