Repository navigation
[Plot] Implement topography plot foundation - #72
Conversation
|
Claude finished @suraj-ranganath's task in 6m 47s —— View job PR Review
Overall this is a clean, well-scoped foundation: Findings (inline)
Looks good
|
|
🤖 Phase 4.1 implementation evidence Problem Approach Tests |
70da110 to
f4d4da8
Compare
| colorbar = _is_on(options.pop("colorbar", "on")) | ||
| maplimits = options.pop("maplimits", _default_maplimits(maps, typeplot)) | ||
| for page_start in range(0, len(maps), per_page): | ||
| page_maps = maps[page_start : page_start + per_page] | ||
| page_labels = labels[page_start : page_start + per_page] | ||
| fig, axes = plt.subplots(rows, cols, squeeze=False, figsize=(cols * 2.1, rows * 2.0)) | ||
| for ax, values, label in zip(axes.ravel(), page_maps, page_labels): | ||
| if values is None: | ||
| ax.axis("off") | ||
| continue | ||
| topoplot( | ||
| values, chanlocs, axes=ax, colorbar=colorbar and len(page_maps) == 1, maplimits=maplimits, **options | ||
| ) |
There was a problem hiding this comment.
🤖 Multi-map colorbar is silently suppressed — EEGLAB parity gap.
colorbar=colorbar and len(page_maps) == 1 means a colorbar is only drawn when a page contains exactly one subplot. For the common cases (multiple ERP latencies, multiple ICs), this evaluates to False and no colorbar is rendered anywhere, even when the GUI's "additional options" line keeps the default colorbar='on'. EEGLAB renders a single shared cbar for the whole figure when more than one map is plotted (see pop_topoplot.m near cbar('vert',0,[-maplim maplim])).
Consider drawing one shared colorbar per fig (e.g. with fig.colorbar(im, ax=axes, shrink=0.7) using the last im returned from topoplot) whenever colorbar is on and len(page_maps) > 1, so the dialog's "additional options" default actually does something visible.
| def _parse_items_text(text: str) -> list[float]: | ||
| stripped = text.strip() | ||
| if re.fullmatch(r"\d+\s*:\s*\d+", stripped): | ||
| start, stop = [int(part.strip()) for part in stripped.split(":")] | ||
| step = 1 if stop >= start else -1 | ||
| return [float(value) for value in range(start, stop + step, step)] | ||
| return _parse_numeric_sequence(stripped).tolist() |
There was a problem hiding this comment.
🤖 _parse_items_text only matches positive-integer two-arg ranges.
The regex \d+\s*:\s*\d+ accepts 1:10 but not:
- negative bounds (
-100:200for ERP latencies, which is a frequent EEGLAB usage), - decimal bounds (
0.5:10.5), - three-arg ranges (
1:2:10or-100:50:300).
For any of the above, the function falls through to _parse_numeric_sequence, which splits on whitespace/commas only. 1:2:10 therefore reaches _parse_float_token("1:2:10") and raises ValueError. That contradicts the EEGLAB dialog hint at line 110 (range: -100 to 600 ms, NaN -> empty), which invites users to type colon ranges crossing zero.
Suggested: accept an optional sign and an optional step: so the GUI hint is honest. The regex can be replaced with something like r"(-?\d+(?:\.\d+)?)\s*:\s*(?:(-?\d+(?:\.\d+)?)\s*:\s*)?(-?\d+(?:\.\d+)?)" and the body adjusted to build a np.arange accordingly.
| if EEG is None: | ||
| return ([], "") if return_com else [] | ||
|
|
||
| typeplot = int(typeplot) | ||
| if gui is None: | ||
| gui = items is None | ||
| if gui: | ||
| result = _run_gui(EEG, typeplot=typeplot, renderer=renderer) | ||
| if result is None: | ||
| return ([], "") if return_com else [] | ||
| items = result["items"] | ||
| topotitle = result["topotitle"] | ||
| rowcols = result["rowcols"] | ||
| plotdip = result["plotdip"] | ||
| kwargs = {**kwargs, **result["options"]} | ||
| elif items is None: | ||
| raise ValueError("items must be provided when gui=False") |
There was a problem hiding this comment.
🤖 Chanlocs / ICA validation happens after the GUI runs.
EEGLAB's pop_topoplot.m performs if isempty(EEG.chanlocs) error(...) and if typeplot == 0 && isempty(EEG.icawinv) error(...) before it opens the dialog (see top of functions/popfunc/pop_topoplot.m). Here the checks live in _erp_maps / _component_maps, so an EEGPrep user who picks Plot → Component scalp maps in 2-D on an EEG without ICA will fill in the dialog, click OK, and only then get a no ICA data for this set, first run ICA error.
Consider moving _require_chanlocs(EEG) (and an equivalent icawinv.size == 0 check when typeplot == 0) to run before _run_gui so the message matches EEGLAB's pre-flight behavior. The current _run_topoplot menu path swallows the GUI cancellation cleanly, but raising late is a noticeable UX regression for the missing-data case.
| raise ValueError(f"component index {index} is outside available ICA components") | ||
| values = icawinv[:, index - 1] | ||
| maps.append(-values if component < 0 else values) | ||
| labels.append(f"IC {int(component)}") |
There was a problem hiding this comment.
🤖 Component subplot title for inverted polarity.
labels.append(f"IC {int(component)}") renders inverted components as IC -2. EEGLAB's pop_topoplot.m labels these as IC 2 (inv.) (positive index plus an explicit suffix when polarity is flipped). For history-replay and EEGLAB-trained users, the negative-number form may be confusing — they will read it as "component −2" rather than "component 2 with inverted polarity." Consider f"IC {index}" + (" (inv.)" if component < 0 else "") to stay closer to EEGLAB.
| chanlocs = chanlocs_as_list(EEG.get("chanlocs", [])) | ||
| if not chanlocs: | ||
| raise ValueError("cannot plot topography without channel location file") | ||
| electrodes = "numpoint" if mode == "numbers" else "labelpoint" |
There was a problem hiding this comment.
🤖 plot_channel_locations history is Python-flavored, not EEGLAB-flavored.
The recorded command is
"topoplot([], EEG['chanlocs'], style='blank', electrodes='numpoint')"which is a Python expression rather than an EEGLAB-style cell-pair string (topoplot([], EEG.chanlocs, 'style', 'blank', 'electrodes', 'numpoint')). Most other pop_* paths in this codebase emit MATLAB-syntax history (see _history_command below, which uses key=value) — but elsewhere the eegh / pop_saveh round-trip preserves an EEGLAB-style shape. Mixing forms in the same history file means the pop_saveh output for a session that touched both topoplot and other functions won't replay cleanly in either Python or MATLAB.
Recommend either making the whole module emit Python-style (it already does for _history_command) or moving this one line to the same EEGLAB 'key','value' cell-pair convention used elsewhere. Worth picking one explicitly and noting in the help / docstring.
| datavector = np.array([] if datavector is None else datavector).flatten() | ||
| if datavector.size == 0 or style == 'blank': | ||
| blank_kwargs = dict(kwargs) | ||
| blank_kwargs.pop('noplot', None) | ||
| blank_kwargs.pop('electrodes', None) | ||
| blank_kwargs.pop('ELECTRODES', None) | ||
| return _blank_topoplot(chan_locs, noplot=noplot, electrodes=ELECTRODES, gridscale=gridscale, **blank_kwargs) |
There was a problem hiding this comment.
🤖 Behavior change: empty data + non-blank style no longer raises.
Previously topoplot(np.array([]), chan_locs, noplot='on') raised one of IndexError/ValueError/UnboundLocalError (asserted by the old test). Now empty data silently routes to _blank_topoplot, even when the caller did not pass style='blank'. That is the intended EEGLAB parity (Plot → Channel locations), but two side effects deserve attention:
- The function now returns
(None, Zi, 0.5, xi, yi)for empty data withnoplot='on', whereZi.shape == (gridscale, gridscale)filled with NaN. Callers that previously depended on the exception (or on the legacy(handle, Zi, plotrad, xi, yi)shape from the interpolation branch) will not notice the shape change immediately, butplotradis now hardcoded to0.5rather than derived from electrode positions — verify this is acceptable for any callers that consumeplotrad. - The blank-path
xi/yicome fromnp.meshgrid(xi_1d, yi_1d)(xi varies along axis 1), while the normal path usesnp.meshgrid(yi, xi)with swapped assignment (xi varies along axis 0). For non-plotting consumers ofxi/yi(parity tests, ICLabel feature extractors), this orientation flip would matter if the blank path ever returns to a numerical pipeline. Worth a one-line comment that the blank Zi is decorative only.
| def _latency_positions(EEG: dict[str, Any], latencies_ms: np.ndarray) -> np.ndarray: | ||
| pnts = int(EEG.get("pnts", 0)) | ||
| xmin = float(EEG.get("xmin", 0)) | ||
| xmax = float(EEG.get("xmax", xmin)) | ||
| if pnts <= 0: | ||
| raise ValueError("EEG.pnts must be positive") | ||
| positions = np.zeros_like(latencies_ms, dtype=int) | ||
| finite = np.isfinite(latencies_ms) | ||
| if xmax != xmin and np.any(finite): | ||
| positions[finite] = np.rint(((latencies_ms[finite] / 1000.0) - xmin) / (xmax - xmin) * (pnts - 1)).astype(int) | ||
| valid = ~finite | ((positions >= 0) & (positions < pnts)) | ||
| if not np.all(valid): | ||
| raise ValueError("requested latency is outside the epoch time range") | ||
| positions[np.isnan(latencies_ms)] = 0 | ||
| return positions |
There was a problem hiding this comment.
🤖 Edge case: NaN-only latencies_ms with xmax == xmin.
If the caller passes items=[float('nan')] and the EEG has xmin == xmax (e.g. a single-sample dataset, or one of the test fixtures), _latency_positions skips the xmax != xmin branch and leaves positions zero everywhere. That is fine for the NaN-only case (the loop short-circuits on np.isnan(latency)), but if even one latency is finite it gets position = 0 silently with no error, which means it maps to sample 0 regardless of the requested latency.
Recommend adding an early check: if any finite latency is present and xmax == xmin, raise (matches EEGLAB's "outside the epoch time range" error). The current valid mask only inspects (positions >= 0) & (positions < pnts), which always passes here because positions are zero.
|
@claude review this |
|
Claude encountered an error after 3m 36s —— View job I'll analyze this and get back to you. |
9ce0df5 to
3e6ad13
Compare
|
@claude review this |
|
Claude finished @suraj-ranganath's task in 3m 55s —— View job Follow-up review of
|


Add EEGPrep topography plotting foundation for channel-location maps and pop_topoplot 2-D ERP/component scalp maps. Wires the Plot menu, help, docs, console-safe history, headless tests, and visual parity capture cases while leaving headplot/DIPFIT overlays for later Phase 4 work.
Part of #64