nilearn / nilearn

Machine learning for NeuroImaging in Python
http://nilearn.github.io
Other
1.17k stars 590 forks source link

Passing a 4D image to `SecondLevelModel` #3058

Open NicolasGensollen opened 2 years ago

NicolasGensollen commented 2 years ago

See this Neurostars post

When passing a 4D image to SecondLevelModel.fit(), no error is raise although the documentation says that possible input values are either a list of FirstLevelModel, a list of images, or a pandas dataframe. When computing contrasts, this raises the following error:

TypeError: Cannot slice image objects; consider using `img.slicer[slice]` to generate a sliced image (see documentation for caveats) or slicing image array data with `img.dataobj[slice]` or `img.get_fdata()[slice]

which occurs when indexing the inputs here:

https://github.com/nilearn/nilearn/blob/5a740b1ce92da9c646cb6812f559ed73c2036f43/nilearn/glm/second_level/second_level.py#L124-L128

Nilearn version: 0.8.2.dev

Steps and code to reproduce bug

import pandas as pd
from nilearn.image import load_img
from nilearn.glm.second_level import SecondLevelModel
from nilearn.datasets import fetch_localizer_contrasts

n_samples = 16
data = fetch_localizer_contrasts(["left vs right button press"], n_samples,
                                 get_tmaps=True)
# This will fail:
# cmap_filenames = load_img(data.cmaps)
# This will work:
cmap_filenames = data.cmaps
design_matrix = pd.DataFrame([1] * n_samples, columns=['intercept'])
second_level_model = SecondLevelModel().fit(cmap_filenames, design_matrix=design_matrix)
z_map = second_level_model.compute_contrast(output_type='z_score')

Fix

If 4D images are allowed, update the docs and fix the indexing. Otherwise raise an error when checking the inputs in fit

bthirion commented 2 years ago

Thx ! Maybe there was a reason for not accepting 4D images, but I can't remember this right now...