Skip to content

Add Phase 4 time-frequency and statistics workflows - #85

Merged
suraj-ranganath merged 2 commits into
feature/eeglab-completionfrom
phase/4-timefreq-statistics
May 29, 2026
Merged

suraj-ranganath merged 2 commits into
feature/eeglab-completionfrom
phase/4-timefreq-statistics

Conversation

@suraj-ranganath

Copy link
Copy Markdown
Member

Add EEGLAB-style time-frequency, cross-coherence, signal statistics, and event statistics workflows with GUI/menu dispatch, help resources, visual parity cases, and sample-data tests. Removes the remaining channel viewprops placeholder because the non-scrolling channel overview is implemented while browser scrolling remains excluded.

Part of #64

@claude

claude Bot commented May 28, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @suraj-ranganath's task in 5m 39s —— View job


Code review

  • Overall assessment: Needs changes — three actionable bugs in the new dialogs/handlers.
  • Highest-risk area: pop_newtimef GUI option handling and pop_eventstat latency filter math.
  • Merge recommendation: Needs changes.

Blocking

None.

Important

1. pop_newtimef: default popup choice "Use 200 time points" is silently ignored. src/eegprep/functions/popfunc/pop_newtimef.py:206 defines ntimes_values = {1: 50, 2: 100, 3: 150, 5: 300, 6: 400}, skipping key 4. The dialog spec at pop_newtimef.py:94 ships ControlSpec("popupmenu", "|".join(_NTIMES_CHOICES), tag="ntimesout", value=4), so the default selection is the 4th entry, "Use 200 time points". Because index 4 is missing from the lookup, timesout is never written into options and the user gets the natural STFT time count instead of 200. Fix: add 4: 200. (inline suggestion posted)

2. pop_newtimef: the "Plot curve at each frequency" checkbox is a guaranteed NotImplementedError. pop_newtimef.py:168-169 writes options["plottype"] = "curve" whenever the checkbox is set; then _reject_unsupported_options at pop_newtimef.py:227-228 raises NotImplementedError("pop_newtimef curve plots are not yet available"). The dialog presents an interactive control that the wrapper can't honor. Either disable that checkbox in the spec, drop the assignment from _run_gui, or fail earlier with a clear "unsupported in EEGPrep" message before doing any work.

3. pop_eventstat latency-range filter math is wrong for epoched data. pop_eventstat.py:138-146 computes latency_ms = (latency - 1) / srate * 1000.0 + xmin * 1000.0. EEGLAB stores epoched event latency as a sample index into the concatenated pnts * trials buffer, so adding the per-epoch xmin offset to a global sample count silently mis-classifies which events fall in the requested ms window for any epoched dataset. For continuous data this happens to work because xmin=0. EEGLAB's eeg_point2lat handles this with explicit epoch index math; consider routing through eeg_point2lat (or replicating its logic) instead. The current tests only exercise latrange=[] so this path isn't covered.

Nits

  • newcrossf.py reaches into newtimef's private helpers (_as_epochs, _limits, _numeric_vector, _select_freqs, _select_times, _trial_stft, _winsize) via underscore-prefixed imports. Tolerable for this pair, but if either is refactored you'll need to touch both. A small shared module would document the contract.
  • _run_gui in pop_newtimef.py still writes options["plotphase"] = "off" (pop_newtimef.py:163) even though the newtimef core accepts no plotphase kwarg, so the assignment is dead.

Test gaps

  • The pop_newtimef/pop_newcrossf GUI replay tests in tests/test_phase4_timefreq_statistics.py skip the GUI path (plot="off" and direct CLI args), so the silent default-selection bug above is invisible to tests. A small assertion that running _run_gui's default dict produces timesout == 200 would catch it.
  • pop_eventstat is only tested with latrange=[], so the latency-conversion bug for epoched data is uncovered.

EEGLAB parity notes

  • The "Plot curve at each frequency" / plottype='curve' and bootstrap/alpha options are advertised in the dialog but rejected at runtime. Consider greying out / hiding controls whose backend support is missing (mirroring EEGLAB's behavior when a feature is unavailable) so the dialog is self-documenting.
  • newtimef's deterministic STFT-only core deviates from EEGLAB's default wavelet path, but this is called out in the docstring and help resource; calling that out in the dialog (e.g., a small "STFT only" hint) would help users not be surprised by spectra that don't match MATLAB output bit-for-bit.

Checked: correctness, EEGLAB parity, data structure compatibility, changed-behavior tests, AGENTS.md compliance, and history-string replay paths. Inline suggestions posted for findings 1–3.

@suraj-ranganath

Copy link
Copy Markdown
Member Author

🤖 Implementation spec for Phase 4 time-frequency/statistics.

Problem
Phase 4 still had Plot-menu placeholders for pop_newtimef, pop_newcrossf, pop_signalstat, and pop_eventstat. The Plot menu also still treated pop_viewprops:channels as a Phase 4 placeholder even though a non-scrolling channel overview exists and EEGBrowser scrolling remains explicitly out of scope.

Approach
Added a new timefreq helper package with deterministic STFT-backed newtimef/newcrossf cores, plus signalstat with EEGLAB-compatible deterministic statistics. Added pop_newtimef, pop_newcrossf, pop_signalstat, and pop_eventstat wrappers with GUI specs, valid Python history commands, public exports, help Markdown, menu dispatch, and visual parity capture cases. Unsupported EEGLAB bootstrap/shuffle/time-warp/curve options now raise clear NotImplementedError messages instead of silently changing behavior.

Key code
The signalstat parity point is MATLAB's quantile rule for trim limits: position = n*q + 0.5 with endpoint clamping. That is implemented in src/eegprep/functions/sigprocfunc/signalstat.py and covered by the MATLAB parity test in tests/test_phase4_timefreq_statistics.py. The GUI dispatch path is covered so these actions no longer fall through to the coming-soon dialog.

Tests
Ran focused Phase 4/statistics tests, menu placeholder inventory, rejection menu inventory, visual parity config, package exports, GUI main-window tests, ruff, format check, ty, and EEGPREP_SKIP_MATLAB=1 uv run --no-sync pytest -m "not slow". The broad non-slow run passed: 1318 passed, 228 skipped, 11 deselected. The focused signalstat MATLAB parity test passed before the MATLAB-skipped broad run.

@suraj-ranganath

Copy link
Copy Markdown
Member Author

🤖 Visual parity capture evidence for the new Phase 4 dialogs was generated locally and is intentionally not committed to the repo.

Generated side-by-side images:

  • /tmp/eegprep_phase4_timefreq_visual_both/pop_newtimef_channels_dialog/side_by_side.png
  • /tmp/eegprep_phase4_timefreq_visual_both/pop_newtimef_components_dialog/side_by_side.png
  • /tmp/eegprep_phase4_timefreq_visual_both/pop_newcrossf_channels_dialog/side_by_side.png
  • /tmp/eegprep_phase4_timefreq_visual_both/pop_newcrossf_components_dialog/side_by_side.png
  • /tmp/eegprep_phase4_timefreq_visual_both/pop_signalstat_channels_dialog/side_by_side.png
  • /tmp/eegprep_phase4_timefreq_visual_both/pop_signalstat_components_dialog/side_by_side.png
  • /tmp/eegprep_phase4_timefreq_visual_both/pop_eventstat_dialog/side_by_side.png

Capture commands used the repo visual parity harness against EEGLAB and EEGPrep for each case, followed by compare.py report generation. I could not upload these as GitHub user attachments from this environment because the available Chrome DevTools session is logged out of GitHub and gh does not expose GitHub's private user-attachment upload path.



def _add_popup_options(options: dict[str, Any], ntimesout: int, nfreqs: int, basenorm: int, freqs: list[float]) -> None:
ntimes_values = {1: 50, 2: 100, 3: 150, 5: 300, 6: 400}

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.

Important — default "Use 200 time points" silently does nothing.

The popup default at line 94 is value=4 (the 4th choice, "Use 200 time points"), but ntimes_values skips key 4 — so for the default GUI run, no timesout is ever written to options and the user gets the natural STFT count instead of 200.

Suggested fix:

Suggested change
ntimes_values = {1: 50, 2: 100, 3: 150, 5: 300, 6: 400}
ntimes_values = {1: 50, 2: 100, 3: 150, 4: 200, 5: 300, 6: 400}

Reference:

ControlSpec("popupmenu", "|".join(_NTIMES_CHOICES), tag="ntimesout", value=4),
ControlSpec("spacer"),
ControlSpec("text", "Frequency limits [min max] (Hz) or sequence", font_weight="bold"),

Comment on lines +168 to +169
if bool(result.get("plotcurve", False)):
options["plottype"] = "curve"

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.

Important — this checkbox always crashes the GUI run.

Setting options["plottype"] = "curve" here is then rejected by _reject_unsupported_options at line 227-228 with NotImplementedError("pop_newtimef curve plots are not yet available"). The dialog renders the "Plot curve at each frequency" checkbox as a live option, but any user who checks it triggers an exception from the GUI path.

Either disable/hide the checkbox in pop_newtimef_dialog_spec, or skip writing plottype here and surface the limitation via a clearer GUI-side message before the rejection runs.

Comment on lines +138 to +146
def _event_in_latency_range(EEG: dict[str, Any], event: dict[str, Any], bounds: np.ndarray) -> bool:
try:
latency = float(np.asarray(event.get("latency")).squeeze())
except (TypeError, ValueError):
return False
srate = float(EEG.get("srate", 1) or 1)
xmin = float(EEG.get("xmin", 0) or 0)
latency_ms = (latency - 1) / srate * 1000.0 + xmin * 1000.0
return bool(bounds[0] <= latency_ms <= bounds[1])

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.

Important — latency-range filter is incorrect for epoched datasets.

EEGLAB stores epoched event.latency as a sample index into the concatenated pnts × trials buffer, so adding the per-epoch xmin offset to a global sample count silently mis-classifies events when the dataset has more than one trial. Continuous data happens to work because xmin == 0.

EEGLAB's eeg_point2lat does the proper per-epoch math; consider delegating to it (or replicating that logic) so this filter behaves correctly for epoched datasets. Worth adding a regression test that exercises latrange against a multi-trial fixture.

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