Skip to content

[Plot] Implement topography plot foundation - #72

Merged
suraj-ranganath merged 3 commits into
feature/eeglab-completionfrom
phase/4-topography-foundation
May 28, 2026
Merged

suraj-ranganath merged 3 commits into
feature/eeglab-completionfrom
phase/4-topography-foundation

Conversation

@suraj-ranganath

@suraj-ranganath suraj-ranganath commented May 27, 2026 •

Copy link
Copy Markdown
Member

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

@claude

claude Bot commented May 27, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @suraj-ranganath's task in 6m 47s —— View job


PR Review

  • Review changed files
  • Check EEGLAB parity against MATLAB reference
  • Check correctness of topoplot signal-processing changes
  • Check pop_topoplot wrapper, GUI, and history hooks
  • Review tests, docs, and help resources
  • Post inline comments and final review summary

Overall this is a clean, well-scoped foundation: pop_topoplot wraps topoplot with the right EEGLAB signature (EEG, typeplot, items, topotitle, rowcols, plotdip, *opts), the dialog spec is split between ERP/component variants with reasonable geometry, the menu/history/console wiring matches the other Phase 4 pop functions, and the headless tests + visual parity cases cover the main paths. The intentional deferral of DIPFIT and headplot is documented in both the docstring and the help markdown. Phase 4 placeholders are correctly trimmed (only pop_topoplot and topoplot removed; pop_chanplot, pop_envtopo, pop_headplot, etc. remain as future work).

Findings (inline)

  • _plot_map_pages — colorbar=colorbar and len(page_maps) == 1 silently drops the colorbar on every multi-map page. EEGLAB renders a single shared cbar for the figure, so the GUI's default 'colorbar','on' currently does nothing on the common cases (multiple latencies, multiple ICs).
  • _parse_items_text — regex \d+:\d+ rejects negative bounds (-100:200 ERP ranges), decimal bounds, and three-arg ranges (1:2:10). The dialog hint at line 110 invites latencies that cross zero, so the parser contradicts its own GUI hint.
  • GUI then validate — chanlocs/ICA checks live inside _erp_maps/_component_maps; EEGLAB pre-checks before opening the dialog. Minor UX gap when calling on a dataset without chanlocs/ICA.
  • Inverted-component label — IC -2 vs EEGLAB's IC 2 (inv.) convention.
  • plot_channel_locations history — emits a Python expression (topoplot([], EEG['chanlocs'], style='blank', ...)) while pop_topoplot's own _history_command emits Python-key=value-style. Worth picking one shape consistently for pop_saveh round-tripping.
  • topoplot empty-data path — empty data now silently flows into the blank channel-location plot; this is the intended EEGLAB behavior, but the test only asserts shape, not that any earlier caller depended on the old exception or on the legacy (plotrad, xi, yi) values.
  • _latency_positions — finite latency + xmax == xmin quietly maps to sample 0 with no error. EEGLAB raises "outside the epoch time range" here.

Looks good

  • Console workspace test covers the non-mutating bare-pop_topoplot(EEG) history flow.
  • Visual parity capture is hooked into both eeglab/eegprep targets with matching MATLAB title strings.
  • pop_topoplot.md help is concise, mentions the deferred DIPFIT/3-D headplot scope.
  • Headless tests use matplotlib.use("Agg") consistently and close figures.
    · branch phase/4-topography-foundation

@suraj-ranganath

suraj-ranganath commented May 27, 2026 •

Copy link
Copy Markdown
Member Author

🤖 Phase 4.1 implementation evidence

Problem
Plot-menu topography actions from EEGLAB were still placeholders: channel-location maps by label/number and pop_topoplot 2-D ERP/component scalp-map dialogs were not available in EEGPrep.

Approach
Added src/eegprep/functions/popfunc/pop_topoplot.py, extended sigprocfunc/topoplot.py for EEGLAB blank channel-location mode, wired Plot menu dispatch/history without mutating EEG datasets, added help/docs/public export, and added visual parity capture cases. DIPFIT overlays and 3-D pop_headplot remain deferred to later Phase 4 work.

Tests
Passed uv run --no-sync pytest tests/test_pop_topoplot.py tests/test_topoplot.py tests/test_gui_main_window.py tests/test_menu_placeholder_inventory.py tests/test_console_workspace.py tests/test_visual_parity.py -q with 168 passed, 3 skipped. Passed uv run --no-sync ruff check ., uv run --no-sync ruff format --check ., uv run --no-sync ty check, ./pre-commit.py, and EEGPREP_SKIP_MATLAB=1 uv run --no-sync pytest -m "not slow" with 1116 passed, 209 skipped, 11 deselected. After the final macOS visual-capture rounding polish, also passed uv run --no-sync pytest tests/test_visual_parity.py tests/test_pop_topoplot.py -q with 25 passed. The focused MATLAB topoplot skips are due this worktree's empty vendored EEGLAB reference path; GUI visual parity used the sibling ../eeglab checkout.

GUI side-by-side visual parity attachments

ERP scalp-map dialog, EEGLAB vs EEGPrep:

pop_topoplot ERP side by side

Component scalp-map dialog, EEGLAB vs EEGPrep:

pop_topoplot components side by side

@suraj-ranganath
suraj-ranganath force-pushed the phase/4-topography-foundation branch from 70da110 to f4d4da8 Compare May 27, 2026 07:27
Comment on lines +216 to +228
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
)

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.

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

Fix this →

Comment on lines +335 to +341
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()

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.

🤖 _parse_items_text only matches positive-integer two-arg ranges.

The regex \d+\s*:\s*\d+ accepts 1:10 but not:

  • negative bounds (-100:200 for ERP latencies, which is a frequent EEGLAB usage),
  • decimal bounds (0.5:10.5),
  • three-arg ranges (1:2:10 or -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.

Fix this →

Comment on lines +51 to +67
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")

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.

🤖 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)}")

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.

🤖 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"

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.

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

Comment on lines +130 to +136
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)

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.

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

  1. The function now returns (None, Zi, 0.5, xi, yi) for empty data with noplot='on', where Zi.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, but plotrad is now hardcoded to 0.5 rather than derived from electrode positions — verify this is acceptable for any callers that consume plotrad.
  2. The blank-path xi/yi come from np.meshgrid(xi_1d, yi_1d) (xi varies along axis 1), while the normal path uses np.meshgrid(yi, xi) with swapped assignment (xi varies along axis 0). For non-plotting consumers of xi/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.

Comment on lines +280 to +294
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

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.

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

@suraj-ranganath

Copy link
Copy Markdown
Member Author

@claude review this

@claude

claude Bot commented May 27, 2026 •

Copy link
Copy Markdown
Contributor

Claude encountered an error after 3m 36s —— View job


I'll analyze this and get back to you.

@suraj-ranganath
suraj-ranganath force-pushed the phase/4-topography-foundation branch from 9ce0df5 to 3e6ad13 Compare May 28, 2026 00:42
@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 55s —— View job


Follow-up review of phase/4-topography-foundation @ 3e6ad13

  • Inspect diff against origin/feature/eeglab-completion
  • Re-check pop_topoplot.py for prior review findings + any new issues
  • Re-check topoplot.py blank-mode behavior
  • Re-check menu wiring, history, console workspace
  • Check tests + help + docs
  • Post review summary

What was addressed since the last pass

  • ✅ Multi-map colorbar now uses a shared fig.colorbar(colorbar_image, ax=plotted_axes, shrink=0.7) for pages with >1 map (pop_topoplot.py:253-254).
  • ✅ _parse_items_text now supports signed bounds, decimals, and three-arg start:step:stop ranges via _parse_colon_sequence (pop_topoplot.py:360-401), with new test coverage in test_pop_topoplot.py::test_pop_topoplot_item_text_parses_eeglab_colon_ranges and test_pop_topoplot_gui_parses_signed_decimal_step_ranges.
  • ✅ Chanlocs / ICA preflight now runs before _run_gui via _validate_topoplot_inputs(EEG, typeplot) (pop_topoplot.py:59), covered by test_pop_topoplot_gui_preflights_missing_inputs_before_dialog.
  • ✅ plot_channel_locations history shape is now explicitly documented as "valid eegprep-console Python" matching pop_topoplot's _history_command style. Reasonable resolution.
  • ✅ _latency_positions now raises "outside the epoch time range" when xmax == xmin and any finite latency is requested, plus rejects ±inf — covered by test_pop_topoplot_rejects_finite_latency_when_epoch_range_collapsed.
  • ✅ topoplot empty-data path — old test now asserts the EEGLAB-style blank shape (handle=None, NaN Zi, plotrad=0.5, gridded xi/yi), and _blank_topoplot has a clear comment that Zi is decorative-only.

Remaining / new findings

  1. (parity, real) Shared colorbar misrepresents component scales. _default_maplimits returns the string "absmax" for typeplot=0. Each subplot then computes its own vmin/vmax from its own Zi inside topoplot._maplimits_kwargs. The shared fig.colorbar at pop_topoplot.py:254 uses ax.images[-1] from the last plotted subplot, so the colorbar shows that one component's scale only. EEGLAB computes a single maplim before the loop and applies it to every subplot plus the cbar (pop_topoplot.m, search for maplim). Suggest computing a shared absmax for components too (mirror the ERP branch in _default_maplimits, just use absmax instead of clipped min/max).

  2. (precision, minor) _parse_colon_sequence drifts on decimal steps. Accumulating current += step lets FP error grow; for example 0:0.1:1 ends at 0.9999999999999999 instead of 1.0, and tolerance = abs(step) * 1e-10 is too tight to round trip. Prefer count-based generation:

    n = int(math.floor((stop - start) / step + 1e-9)) + 1
    values = [start + i * step for i in range(max(n, 0))]

    This matches MATLAB colon semantics without per-iteration drift. (No test exercises this case yet; the two new tests both happen to land on exact binary fractions.)

  3. (parity, optional) Inverted-component label. The author kept IC -2 with an explanatory comment. EEGLAB's pop_topoplot.m uses the absolute index in the title and only negates the values, not the label. If we want subject-matter-expert parity, f"IC {index}" + (" (inv.)" if component < 0 else "") is closer; if the comment is treated as documenting an intentional EEGPrep choice, that's fine — just worth confirming.

  4. (scope, contained) _matlab_scaled_pixmap rounding rewrite is macOS-only. The function returns early for non-Darwin, so the removed if ratio <= 1: return pixmap early-return and the round → math.floor swap only affect macOS captures. On macOS standard-density displays (ratio=1), the new code now upscales to MATLAB density (1.5x); previously it returned the pixmap unchanged. This is in scope as "final macOS visual-capture rounding polish" per the author's note, but worth a one-line PR note that all macOS visual parity refs may need a re-bake, not just topoplot.

  5. (robustness, minor) plot_channel_locations doesn't validate mode. Anything other than "numbers" silently falls back to labelpoint. The menu dispatch only ever passes "labels" / "numbers", so this is a low-impact nit — either narrow the type (Literal["labels", "numbers"]) or raise on unknown values to fail fast.

Looks good

  • The new test_pop_topoplot.py covers preflight, colon ranges, inverted components, NaN-only items, and GUI option round-trip.
  • _validate_topoplot_inputs is called before _run_gui, so the EEGLAB UX of "error before dialog" is preserved.
  • _blank_topoplot cleanly separates blank channel-location rendering from interpolated maps and consistently goes through _draw_head / _draw_electrode_labels, removing duplication.
  • Menu/console wiring keeps EEG immutable for plot-only actions and still records history — tests/test_console_workspace.py::test_non_mutating_pop_plot_call_records_history_without_storing_dataset and tests/test_gui_main_window.py::test_pop_topoplot_menu_actions_* lock that contract in.
  • Help (pop_topoplot.md), docs (generated/eegprep.pop_topoplot.rst, signal_processing.rst), and public export are all updated together.
  • Visual parity cases (pop_topoplot_erp_dialog, pop_topoplot_components_dialog) match the dialog spec used at runtime.

Nothing here is a merge-blocker; (1) is the only one I would push to fix before tagging the next Phase 4 PR, because it changes what users see on the screen. The rest are good-to-have.
· branch phase/4-topography-foundation

@suraj-ranganath
suraj-ranganath merged commit 5e8e8c0 into feature/eeglab-completion May 28, 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