Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[MAINT] Improve error for nifti masker when fit is called without imgs or mask_img #4151

Merged
merged 2 commits into from
Dec 12, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
6 changes: 6 additions & 0 deletions nilearn/maskers/nifti_masker.py
Original file line number Diff line number Diff line change
Expand Up @@ -428,6 +428,12 @@ def fit(self, imgs=None, y=None):

# Compute the mask if not given by the user
if self.mask_img is None:
if imgs is None:
raise ValueError(
"Parameter 'imgs' must be provided to "
f"{self.__class__.__name__}.fit() "
"if no mask is passed to mask_img."
)
mask_args = self.mask_args if self.mask_args is not None else {}
compute_mask = _get_mask_strategy(self.mask_strategy)
if self.verbose > 0:
Expand Down
15 changes: 12 additions & 3 deletions nilearn/maskers/tests/test_nifti_masker.py
Original file line number Diff line number Diff line change
Expand Up @@ -353,18 +353,27 @@ def test_joblib_cache(tmp_path):
shutil.rmtree(cachedir, ignore_errors=True)


def test_fit_no_mask_no_img_error():
"""Check error is raised when no mask and no img is provided."""
mask = NiftiMasker(mask_img=None)
with pytest.raises(
ValueError, match="Parameter 'imgs' must be provided to "
):
mask.fit()


def test_mask_strategy_errors(rng):
"""Check that mask_strategy errors are raised."""
# Error with unknown mask_strategy
img = rng.uniform(size=(9, 9, 5))
img = nibabel.Nifti1Image(img, np.eye(4))
mask = NiftiMasker(mask_strategy="oops")
with pytest.raises(
ValueError, match="Unknown value of mask_strategy 'oops'"
):
mask.fit()
mask.fit(img)
# Warning with deprecated 'template' strategy,
# plus an exception because there's no resulting mask
img = rng.uniform(size=(9, 9, 5))
img = nibabel.Nifti1Image(img, np.eye(4))
mask = NiftiMasker(mask_strategy="template")
with pytest.warns(
UserWarning, match="Masking strategy 'template' is deprecated."
Expand Down