Skip to content

New cluster test API - #12663

Merged
drammock merged 174 commits into
mne-tools:mainfrom
CarinaFo:new_cluster_stats_api_GSOC24
Sep 16, 2026
Merged

drammock merged 174 commits into
mne-tools:mainfrom
CarinaFo:new_cluster_stats_api_GSOC24

Conversation

@CarinaFo

@CarinaFo CarinaFo commented Jun 14, 2024 •

Copy link
Copy Markdown
Contributor

set up new cluster_test api that sets up design matrix based on Wilkinson formula (using formulaic package)

@drammock drammock left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

just a few comments to get you rolling. Maybe ping us when the formulaic bit is added? (or sooner if you have any questions in the meantime, of course!)

@hoechenberger

Copy link
Copy Markdown
Member

This might be related:

mne-tools/mne-incubator#31

cc @SophieHerbst

@cbrnr

cbrnr commented Jun 19, 2024

Copy link
Copy Markdown
Contributor

I think it is a great idea to revamp the current cluster permutation test API 🚀! Could you please share the reasoning behind choosing a pandas DataFrame as the container for evokeds and related meta info? If possible, I'd try to avoid using pandas (an optional dependency) when something similar could be achieved using, for example, a simple dictionary.

@CarinaFo

Copy link
Copy Markdown
Contributor Author

@cbrnr I think the main reason for a dataframe instead of a dictionary is that formulaic only allows for dataframes as input and we want to include Wilkinson formula support in the new cluster_test API.

@hoechenberger

hoechenberger commented Jun 19, 2024 •

Copy link
Copy Markdown
Member

@cbrnr I think the main reason for a dataframe instead of a dictionary is that formulaic only allows for dataframes as input and we want to include Wilkinson formula support in the new cluster_test API.

But this doesn't need to be user-facing, then, no? Just trying to understand. If a user passes in a list of TypedDicts or Dataclasses, you can internally create the DataFrames that need to be passed to formulaic. The user would then also get tab-completion assistance in their editor. But it's just a thought. Great work so far in any case!

@drammock

Copy link
Copy Markdown
Member

you can internally create the DataFrames that need to be passed to formulaic

This would still require pandas to be available though.

@hoechenberger

Copy link
Copy Markdown
Member

you can internally create the DataFrames that need to be passed to formulaic

This would still require pandas to be available though.

Sure
But it would provide a potentially more user-friendly API

@drammock

drammock commented Jun 19, 2024 •

Copy link
Copy Markdown
Member

you can internally create the DataFrames that need to be passed to formulaic

This would still require pandas to be available though.

Sure But it would provide a potentially more user-friendly API

For context, this is step 1 of a GSoC project. A later step involves (probably) creating helper functions that will create the necessary DataFrame for the user. That's not done here because:

  1. there are probably complicated use cases / designs that we won't foresee, so we want it to be possible for the user to pass in their own custom dataframe instead of our internally-generated one.
  2. we're actually not sure how helpful the helper function will be (at least in some cases): if what you need to pass in is a set of matched lists of subject IDs, evoked objects, and condition names, well then you might as well just call DataFrame(dict(subj=subj_list, cond=cond_list, data=evk_list)) yourself instead of calling the helper function. A helper function makes much more sense in other cases, like when dealing with Epochs objects where the conditions are intermixed within one object.

@larsoner

Copy link
Copy Markdown
Member

@CarinaFo I pushed a commit to add the dataset and add formulaic to our full and doc dependencies so that eventually CIs can use them properly. I added the tags [skip azp] [skip actions] to skip running those CIs. Feel free to git pull the changes back to your local machine!

If you look at the CI runs, you can see that CircleCI, which builds modified examples/tutorials in PRs, hit an error up on 9c8ec90:

sphinx.errors.ExtensionError: Could not find docstring in file "/home/circleci/project/tutorials/stats-sensor-space/76_new_cluster_test_api.py". A docstring is required by sphinx-gallery unless the file is ignored by "ignore_pattern"

Then I pushed a little commit to fix that in 47363b5, and now it hits a different error (which replicates what I saw locally when I tried to run the example):

../tutorials/stats-sensor-space/76_new_cluster_test_api.py unexpectedly failed to execute correctly:

    Traceback (most recent call last):
      File "/home/circleci/project/tutorials/stats-sensor-space/76_new_cluster_test_api.py", line 449, in <module>
        df_long = convert_wide_to_long(df)
      File "/home/circleci/project/tutorials/stats-sensor-space/76_new_cluster_test_api.py", line 431, in convert_wide_to_long
        data_2d = row["data"]
      File "/home/circleci/python_env/lib/python3.10/site-packages/pandas/core/series.py", line 1121, in __getitem__
        return self._get_value(key)
      File "/home/circleci/python_env/lib/python3.10/site-packages/pandas/core/series.py", line 1237, in _get_value
        loc = self.index.get_loc(label)
      File "/home/circleci/python_env/lib/python3.10/site-packages/pandas/core/indexes/base.py", line 3812, in get_loc
        raise KeyError(key) from err
    KeyError: 'data'

It would be good to keep CircleCI green at least so we can see renderings of the tutorial with each push. If you make sure python -i tutorials/stats-sensor-space/76_new_cluster_test_api.py runs cleanly locally each time before you push then it should work on CircleCI now as well!

@CarinaFo

CarinaFo commented Sep 6, 2026 •

Copy link
Copy Markdown
Contributor Author

I rewrote the tutorial and I think I found another improvement/feature we should probably implement. In the tutorial, the reference used by the cluster test by default was non-target, so the t-values were negative. In the example plot, we visualised the evoked difference by setting target - non-target contrast. I think for the user the cluster t-values might be confusing/misinterpreted. I need to verify, but I guess cluster_test sorts the contrast alphabetically by default. The cluster_test function does return the reference (which is great), but we should allow the user to change the reference or at least document the default behaviour?

I also noticed that cluster_result.n_permutations gives the wrong number of permutations (1024) even though the test runs an exact test here (15 permutations). But I think this should be a separate PR.

Let me know what you think @scott-huberty (again, great work, the API is already so much better).

Update: The merge conflict is from a recent PR that fixes TFCE (#14286), maybe good to keep that PR in mind before finalising the new cluster test API

@larsoner

larsoner commented Sep 16, 2026 •

Copy link
Copy Markdown
Member

Sounds like all that might now be needed to merge is to address the docstring issue, fix a merge conflict, and maybe the n_permutations bug, leaving the condition order/sign to another PR. (Though one easy change would be to keep the original order first seen, so if A comes before B then the contrast is A-B, if B before A then B-A. I might try this to see how easy it is.)

Okay for me to do these last fix ups and merge @scott-huberty @wmvanvliet @CarinaFo ?

* upstream/main: (91 commits)
  Fix static doc viewing in IDEs (mne-tools#14195)
  Fix COLA for odd sizes (mne-tools#14312)
  add type hints to mne/_fiff/ module (mne-tools#14278)
  ENH: wire the JupyterLite build into the docs (JupyterLite split 5/5) (mne-tools#14157)
  MAINT: Update pre-commit hook versions (mne-tools#14306)
  Small documentation fix for "Frequency and time-frequency sensor analysis" tutorial (mne-tools#14304)
  FIX: don't mutate cached ICA sources in plot_sources properties (mne-tools#14303)
  Fix bug with lite backend closing (mne-tools#14302)
  Fix for NumPy eig change [circle deploy] (mne-tools#14300)
  No PyQt5 [circle deploy] [skip azp] [skip actions]
  ENH: add the JupyterLite notebook setup cell (JupyterLite split 4/5) (mne-tools#14150)
  FIX: Ver [circle deploy] [skip azp] [skip actions]
  Hotfix
  fix EDF round-trip (mne-tools#14296)
  Brain GUI modernization (Phase 7) (mne-tools#14270)
  Fix bug with SciPy 1.18.0 EEGLAB reading (mne-tools#14293)
  remove plotting abs as the defauls for plotting volumetric (mne-tools#13989)
  Coregistration GUI modernisation (phase 4) (mne-tools#14285)
  Dipole GUI interactivity and visual enhancements (phase 2) (mne-tools#14291)
  Width [circle deploy] [skip azp] [skip actions]
  ...
@larsoner larsoner changed the title new cluster test API New cluster test API Sep 16, 2026

@scott-huberty scott-huberty left a comment

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.

+1 for merge : )

@larsoner
larsoner dismissed drammock’s stale review September 16, 2026 17:04

Checked and all comments have been addressed!

@drammock drammock left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

just a small suggestion to interleave the code + text a bit more in the tutorial.

Comment on lines +151 to +167
# The smallest cluster p-value is about 0.06, so no cluster is significant at
# alpha = 0.05 -- and with five subjects none ever could be. Here is why.
#
# The null distribution is built by sign-flipping the five per-subject
# difference scores. There are ``2 ** 5 = 32`` ways to assign signs, but
# flipping every sign only mirrors the partition, so just ``2 ** (5 - 1) = 16``
# are distinct. Because the test is exact, all 16 are evaluated rather than
# sampled at random -- which is why ``cluster_result.n_permutations`` below
# reports 16 rather than the 1024 requested by default. Fifteen of those are
# surrogates (you will see ``15/15`` in the progress log); the sixteenth is the
# arrangement actually observed.
#
# The finest p-value this can resolve is therefore ``1 / 16 = 0.0625``, so even the
# most extreme possible cluster lands just above 0.05. The near-0.0625 result
# means the observed cluster *was* the most extreme one -- there is simply not
# enough data to reach significance. Detecting an effect here would need more
# subjects; that, not the specific p-value, is the takeaway.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this section is great!

vlim = np.abs(stat_obs).max()

fig, ax = plt.subplots(layout="constrained")
im = ax.imshow(

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this is fine for now, but a better visualization might be to create an EvokedArray from the stat_obs and plot t-value as a function of time for each sensor, visualized as a joint plot (so you see topomaps at times where the t-vals are high across channels). With a heatmap, the neighbor relationships across channels get obscured/lost.

@drammock
drammock enabled auto-merge (squash) September 16, 2026 17:18
@drammock
drammock merged commit c85b815 into mne-tools:main Sep 16, 2026
26 checks passed
@wmvanvliet

Copy link
Copy Markdown
Contributor

congrats! This is amazing! 🎉

@larsoner larsoner added the release-highlight Will be put in the highlight section of the release announcement label Dec 1, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

release-highlight Will be put in the highlight section of the release announcement

Projects

None yet

Development

Successfully merging this pull request may close these issues.

10 participants