Skip to content

[Phase 4] Add plotting core wrappers - #75

Merged
suraj-ranganath merged 4 commits into
feature/eeglab-completionfrom
phase/4-plotting-core-wrappers
May 28, 2026
Merged

suraj-ranganath merged 4 commits into
feature/eeglab-completionfrom
phase/4-plotting-core-wrappers

Conversation

@suraj-ranganath

Copy link
Copy Markdown
Member

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

@claude

claude Bot commented May 28, 2026 •

Copy link
Copy Markdown
Contributor

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

  • Read PR diff vs feature/eeglab-completion
  • Audit new pop_* wrappers for EEGLAB parity and return_com handling
  • Audit new sigprocfunc/* core plotting helpers
  • Check menu wiring + visual parity capture changes
  • Skim tests for soundness
  • Post inline comments + summary

Findings

Correctness

  • pop_prop plots only the first trial's spectrum — compute_spectra(trace_2d.T, …) treats trials as channels; spectra[0] is trial 1 only. Should be trace_2d.reshape(1, -1) so the channel/component spectrum spans the whole epoch concatenation, as in EEGLAB's spectopo(reshape(EEG.data(chan,:,:),1,[]),…). Inline patch suggested.
  • pop_envtopo ignores all-but-last when given an ALLEEG list (EEG[-1]). The dispatcher passes the whole list when allow_multiple=True, so the user can't see what got dropped. Raise or document.
  • pop_envtopo shape mismatch risk when nbchan != len(icachansind) — weights @ values raises a generic numpy error. Slice by icachansind or fail with a clear message.
  • pop_chanplot reuses times from the first dataset for all datasets — if STUDY datasets differ in pnts/xmin/xmax, ERPs silently misalign.

Surface / parity gaps in GUI options

Several dialogs collect rich option sets but the wrappers only consume a few:

  • pop_erpimage: smooth/decimate/limits/plotmap/cbar/caxis/sort* are forwarded into kwargs and only title/sort_values are honored. The history command looks parameterized but isn't replayable.
  • pop_comperp: mode (RMS), lowpass, addstd/substd/diffstd, addall/etc., alpha, tplotopt all silently ignored.
  • pop_plottopo: singletrials, rect, options ignored.
  • pop_prop: spec_opt collected (default 'freqrange', [2, 50]) and never used.

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 NotImplementedError).

Lower-priority observations

  • _plot_utils.eeg_times_ms heuristic (|times|.max() ≤ max(|xmax|,1)*2) can mis-classify short epochs whose times are in ms. EEGLAB stores EEG.times in ms by convention — trust that, drop the heuristic.
  • spectopo.compute_spectra returns specstd = zeros_like(spectra). Return None or compute it from Welch segments; the silent zero will mislead any consumer that inspects it.
  • pop_spectopo._history_command hand-rolls its own builder and emits every kwarg (freqs=[], freqrange=[], timerange=None, …). Other wrappers use history_command which already skips None; consolidate for cleaner replayable commands.
  • sigprocfunc/headplot.py: the 3-D scatter on a wireframe is named headplot but doesn't perform EEGLAB's spline-interpolated scalp surface. Worth a note in the help resource so the difference is visible to users.
  • pop_headplot snaps requested ERP latencies via argmin(|all_times - latency|) even when the requested latency is far outside the data range — silent rather than clear.

What looks good

  • Lazy imports in _LAZY_EXPORTS + clean menu_actions dispatch table — Phase-4 entries cleanly excluded from menu_placeholders.py.
  • return_com=True handling and the EEGLAB-style positional signatures are consistent across all eight new pop_* wrappers.
  • New tests/test_phase4_plot_wrappers.py exercises headless paths against real sample_data and validates _assert_python_command for every wrapper — nice coverage with no mocking.
  • Visual-parity capture additions (cases.json, MATLAB helper, visual_capture.py capture_* helpers) follow the existing pattern faithfully.

Not addressed (out of scope for this review)

  • Whether the simplified headplot/envtopo outputs meet the visual-parity threshold once screenshots are compared.
    · Branch

@suraj-ranganath

Copy link
Copy Markdown
Member Author

🤖 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 src/eegprep/functions/popfunc/_plot_utils.py and low-level matplotlib/Agg-safe helpers in src/eegprep/functions/sigprocfunc/ for spectopo, plottopo, timtopo, erpimage, envtopo, and headplot. Added user-facing wrappers pop_spectopo, pop_prop, pop_timtopo, pop_plottopo, pop_headplot, pop_plotdata, pop_erpimage, pop_envtopo, pop_comperp, and pop_chanplot, each with return_com=True, valid Python console history, help Markdown, sample-data coverage, and menu dispatch. Removed these wrappers from ordinary placeholder metadata while keeping browser/scrolling actions excluded.

Key code

The wrappers share one normalization/history path so GUI, Python API, and eegprep-console see pasteable commands instead of MATLAB-only syntax:

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 uv run --no-sync ruff check ., uv run --no-sync ruff format --check ., uv run --no-sync ty check, ./pre-commit.py, focused plotting/menu/visual tests (84 passed, 26 subtests passed), and EEGPREP_SKIP_MATLAB=1 uv run --no-sync pytest -m "not slow" (1186 passed, 214 skipped, 11 deselected). New tests/test_phase4_plot_wrappers.py covers headless sample-data spectra/property/headplot flows, synthetic epoched ERP/channel flows, ICA/component flows, pop_comperp, pop_chanplot, parseable history, and clear missing-field errors.

Visual parity

Added visual parity cases for every new GUI option dialog. Captured side-by-side EEGLAB vs EEGPrep images locally under .visual-parity/<case>/side_by_side.png for spectra, properties, timtopo, plottopo, plotdata, erpimage, envtopo, and comperp dialogs. pop_headplot EEGPrep captures exist, but EEGLAB’s headplot path opens its spline/coregistration workflow instead of a normal modal inputgui, so the generic capture harness times out there; this is called out for follow-up exact mesh/spline parity.

@suraj-ranganath

Copy link
Copy Markdown
Member Author

🤖 GUI visual parity evidence for Phase 4 plotting wrappers.

Local artifacts are under .visual-parity/<case>/ and are not committed. Headplot is included as EEGPrep-only capture because EEGLAB pop_headplot enters its spline/coregistration workflow and times out in the generic modal capture harness.

Side-by-side screenshots

pop_spectopo channels dialog

side_by_side.png

pop_spectopo components dialog

side_by_side.png

pop_prop channels dialog

side_by_side.png

pop_prop components dialog

side_by_side.png

pop_timtopo dialog

side_by_side.png

pop_plottopo dialog

side_by_side.png

pop_plotdata dialog

side_by_side.png

pop_erpimage channels dialog

side_by_side.png

pop_erpimage components dialog

side_by_side.png

pop_envtopo dialog

side_by_side.png

pop_comperp channels dialog

side_by_side.png

pop_comperp components dialog

side_by_side.png

pop_headplot ERP dialog (EEGPrep only; EEGLAB capture opens spline/coregistration workflow)

eegprep.png

pop_headplot components dialog (EEGPrep only; EEGLAB capture opens spline/coregistration workflow)

eegprep.png

Comment on lines +111 to +117
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")

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.

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.

Suggested change
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")

Fix this →

}


def _plot_one_property(EEG: dict[str, Any], typecomp: int, index: int, _spec_opt: Any):

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.

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_opt and forward the relevant kwargs (freqrange, etc.) into compute_spectra/plot_spectra, or
  • remove the dialog row / document the limitation in resources/help/pop_prop.md so 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

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.

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 NotImplementedError when len(EEG) > 1 so callers don't silently lose data, or
  • document the simplification in resources/help/pop_envtopo.md so 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.)

Comment on lines +43 to +48
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(

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.

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.

Comment on lines +42 to +53
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)

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

Comment on lines +203 to +213
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)})"

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

Comment on lines +98 to +100
spectra = 10.0 * np.log10(np.maximum(power, np.finfo(float).tiny))
specstd = np.zeros_like(spectra)
return spectra, freqs, specstd

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.

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.spectrogram and convert to dB, or
  • return None so the absence is explicit.

Comment on lines +45 to +52
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

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.

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).

Comment on lines +82 to +95
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

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

Comment on lines +13 to +49
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

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 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:

  1. Make the difference visible to users by including a one-line note in resources/help/pop_headplot.md so it's surfaced via the Help button (the current help text doesn't mention the simplification).
  2. Add a topoplot-style interpolation fallback (or reuse the existing topoplot interpolation on a hemisphere mesh) as a follow-up. Not blocking for Phase 4 if scoped that way.

Comment on lines +190 to +216
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 ""),
},
}

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.

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.

Comment on lines +45 to +51
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])

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.

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.

Comment on lines +73 to +85
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 ""),
},
}

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 dialog collects singletrials, rect, and a free-form options string, but they're never threaded down to plottopo(). Two consequences:

  1. Checking "Plot single trials" or "Plot in rect. array" silently has no effect.
  2. 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.

@suraj-ranganath

Copy link
Copy Markdown
Member Author

🤖 Updated GUI parity screenshots after the latest dialog fixes. These are GitHub user attachments, not repo artifacts.

Dialog Side-by-side
pop_prop channels pop_prop channels
pop_prop components pop_prop components
pop_erpimage channels pop_erpimage channels
pop_erpimage components pop_erpimage components
pop_comperp channels pop_comperp channels
pop_comperp components pop_comperp components

@suraj-ranganath
suraj-ranganath force-pushed the phase/4-plotting-core-wrappers branch from d03fff0 to b7be5e6 Compare May 28, 2026 10:22
@suraj-ranganath

Copy link
Copy Markdown
Member Author

@claude review this

@claude

claude Bot commented May 28, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @suraj-ranganath's task in 3m 53s —— View job


Claude PR Re-review — Phase 4 plotting wrappers (after fixups)

Re-reviewed phase/4-plotting-core-wrappers at 3 commits ahead of feature/eeglab-completion. Most of my earlier findings are addressed; remaining notes are minor and non-blocking.

Todo

  • Pull the latest branch and diff vs origin/feature/eeglab-completion
  • Verify earlier review findings have been addressed
  • Re-audit new pop_* wrappers
  • Re-audit core plotting helpers in sigprocfunc/
  • Spot-check menu wiring + visual parity additions
  • Skim updated tests (tests/test_phase4_plot_wrappers.py tests/test_menu_placeholder_inventory.py → 22 passed)
  • Post review summary

What was fixed since the first pass

Earlier finding Status
pop_prop plotted only trial 1's spectrum ✅ Fixed: flat = trace_2d.reshape(1, -1) (pop_prop.py:138)
pop_prop spec_opt collected but ignored ✅ Parsed via parse_plot_options_text and forwarded into compute_spectra (freqrange, winsize, overlap, nfft) (pop_prop.py:137-150)
pop_envtopo silently took only the last dataset of a list ✅ Raises NotImplementedError when len(EEG) > 1 (pop_envtopo.py:36-40)
pop_envtopo shape mismatch on rejected channels ✅ Slices data[icachansind, :, :] and emits a clear ValueError (pop_envtopo.py:58-62)
eeg_times_ms heuristic mis-classified short epochs ✅ Heuristic removed — trusts EEGLAB ms convention (_plot_utils.py:40-50)
spectopo returned np.zeros_like(spectra) as specstd ✅ Now returns None (spectopo.py:62, 75-105); covered by test_pop_spectopo_component_path_plots_component_maps
pop_spectopo history was noisy with empty kwargs ✅ Uses the shared history_command, which skips None/empty (pop_spectopo.py:97-104)
pop_erpimage dialog options silently ignored ✅ _raise_for_unsupported_gui_options / _raise_for_unsupported_kwargs now error clearly for sort/coher/spec/etc. instead of producing misleading replayable commands (pop_erpimage.py:314-348)
pop_comperp mode/lowpass/std/all/diff silently ignored ✅ mode='rms' and lowpass implemented (pop_comperp.py:60-66, 170-183); std/all/diff/alpha raise NotImplementedError (pop_comperp.py:241-261)
pop_headplot snapped out-of-range latencies silently ✅ Validates against [xmin*1000, xmax*1000] and raises (pop_headplot.py:92-93); covered by test_plot_wrappers_fail_clearly_when_required_fields_are_missing
headplot help didn't note the simplification ✅ resources/help/pop_headplot.md adds the spline/mesh note
pop_chanplot reused first dataset's times for all subjects ✅ _validate_time_grid raises a clear error for mismatches (pop_chanplot.py:75-90); covered by test_pop_chanplot_validates_time_grid

Remaining minor observations (non-blocking)

pop_plottopo — rect checkbox still has no effect

The dialog still exposes "Plot in rect. array" (pop_plottopo.py:79) and _run_gui forwards it as options["rect"], but the wrapper never pops or acts on it — only singletrials, title, and the parsed options text are honored. Since sigprocfunc/plottopo.py only renders a rect grid (no scalp-coordinate placement), the toggle has no behavioral state to switch to. Either drop the checkbox from the dialog or implement scalp-coordinate placement (matching EEGLAB's default mode).

pop_plottopo — GUI default ydir differs from CLI default

Dialog default is 'ydir', 1 (positive-up), but the Python signature default is ydir=-1 (EEGLAB convention, negative-up). A user clicking through the dialog gets a different orientation than someone calling pop_plottopo(EEG, [1, 2]) from the console. Worth aligning (probably default the dialog to 'ydir', -1 to match EEGLAB).

pop_chanplot has no GUI dialog

The menu action calls pop_chanplot(STUDY, ALLEEG, return_com=True) directly (menu_actions.py:1104), which always plots every channel. There's no dialog for channel selection or measure choice. Phase 4 is documented as the channel-measure handoff, but the menu UX is currently "click → all channels, no choice." Either add a small dialog (channels + measure) or note in resources/help/pop_chanplot.md that STUDY UI/cluster selection is Phase 5.

pop_comperp dialog vs runtime — non-issue, just confirming

The dialog still shows fields the wrapper doesn't implement (alpha, addstd, addall, etc.), but they now raise NotImplementedError in _run_gui instead of being silently dropped. That's the right phased-rollout behavior — just a heads-up that a Phase-5 user who flips addstd will hit the error at GUI submit time. Help text in resources/help/pop_comperp.md could call out which checkboxes are wired vs. not, but that's cosmetic.

pop_envtopo — command_kwargs recorded as captured, before pops

command_kwargs = dict(kwargs) is taken before the function pops compnums/compsplot/title/options/limcontrib/subcomps (pop_envtopo.py:52, 65-80). The replayable command therefore contains keys (e.g. options="…") that are passed through **kwargs to a second pop_envtopo call — fine since the wrapper still pops them on replay, but compnums aliasing (kwargs.pop("compnums", kwargs.pop("components", None))) means a replayed command using components= will be re-accepted via the alias. Nothing broken, just calling out the alias for future maintainers.

What looks good

  • Lazy _LAZY_EXPORTS additions and the _run_plot_function dispatch in menu_actions.py are clean; placeholders correctly removed for all eight Phase-4 entries.
  • history_command is now the single normalization point and skips None/empty values; _assert_python_command in tests catches non-ast.parseable strings across every wrapper.
  • tests/test_phase4_plot_wrappers.py exercises real sample_data, the synthetic-ICA helper, dialog spec layouts, RMS mode, time-grid validation, decimation+limits, projchan, and missing-field errors — 22/22 pass locally.
  • Visual parity additions (capture helpers + cases.json) follow the existing pattern; pop_headplot is documented as EEGPrep-only capture because EEGLAB's path opens the spline/coregistration window.

Not addressed (out of scope for this review)

  • Whether the simplified headplot/envtopo outputs visually match EEGLAB closely enough; the team has acknowledged pop_headplot parity is follow-up.
  • Implementing the remaining pop_erpimage / pop_comperp options (sort, coher, spec, std overlays). These now error clearly, which is fine for Phase 4.

Overall: ready to merge from a correctness/parity-contract standpoint. The remaining items above are small polish issues and can land as a follow-up.
· Branch

@suraj-ranganath

Copy link
Copy Markdown
Member Author

🤖 Updated visual parity artifact after the pop_plottopo dialog/default review fixes.\n\npop_plottopo side-by-side

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