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

[FMT] apply black to maskers - part 2 #3803

Merged
merged 9 commits into from
Jul 5, 2023
Merged
Show file tree
Hide file tree
Changes from 5 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
7 changes: 1 addition & 6 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -33,14 +33,9 @@ exclude: |
| nilearn/interfaces/fmriprep/tests/test_load_confounds_strategy.py
| nilearn/interfaces/fmriprep/tests/utils.py
| nilearn/interfaces/fmriprep/tests/test_load_confounds.py
| nilearn/maskers/nifti_masker.py
| nilearn/maskers/nifti_spheres_masker.py
| nilearn/maskers/nifti_labels_masker.py
| nilearn/maskers/nifti_maps_masker.py
| nilearn/maskers/tests/test_nifti_spheres_masker.py
| nilearn/maskers/tests/test_nifti_labels_masker.py
| nilearn/maskers/tests/test_nifti_maps_masker.py
| nilearn/maskers/tests/test_nifti_masker.py
| nilearn/maskers/nifti_labels_masker.py
| nilearn/plotting/glass_brain_files/plot_align_svg.py
| nilearn/plotting/edge_detect.py
| nilearn/plotting/html_document.py
Expand Down
188 changes: 99 additions & 89 deletions nilearn/maskers/nifti_masker.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@


class _ExtractionFunctor:
func_name = 'nifti_masker_extractor'
func_name = "nifti_masker_extractor"

def __init__(self, mask_img_):
self.mask_img_ = mask_img_
Expand All @@ -31,33 +31,43 @@

def _get_mask_strategy(strategy):
"""Return the mask computing method based on a provided strategy."""
if strategy == 'background':
if strategy == "background":
return masking.compute_background_mask
elif strategy == 'epi':
elif strategy == "epi":
return masking.compute_epi_mask
elif strategy == 'whole-brain-template':
return partial(masking.compute_brain_mask, mask_type='whole-brain')
elif strategy == 'gm-template':
return partial(masking.compute_brain_mask, mask_type='gm')
elif strategy == 'wm-template':
return partial(masking.compute_brain_mask, mask_type='wm')
elif strategy == 'template':
warnings.warn("Masking strategy 'template' is deprecated."
"Please use 'whole-brain-template' instead.")
return partial(masking.compute_brain_mask, mask_type='whole-brain')
elif strategy == "whole-brain-template":
return partial(masking.compute_brain_mask, mask_type="whole-brain")
elif strategy == "gm-template":
return partial(masking.compute_brain_mask, mask_type="gm")
elif strategy == "wm-template":
return partial(masking.compute_brain_mask, mask_type="wm")
elif strategy == "template":
warnings.warn(
"Masking strategy 'template' is deprecated."
"Please use 'whole-brain-template' instead."
)
return partial(masking.compute_brain_mask, mask_type="whole-brain")
else:
raise ValueError(f"Unknown value of mask_strategy '{strategy}'. "
"Acceptable values are 'background', "
"'epi', 'whole-brain-template', "
"'gm-template', and "
"'wm-template'.")
raise ValueError(
f"Unknown value of mask_strategy '{strategy}'. "
"Acceptable values are 'background', "
"'epi', 'whole-brain-template', "
"'gm-template', and "
"'wm-template'."
)


def _filter_and_mask(
imgs, mask_img_, parameters,
memory_level=0, memory=Memory(location=None),
verbose=0, confounds=None, sample_mask=None,
copy=True, dtype=None
imgs,
mask_img_,
parameters,
memory_level=0,
memory=Memory(location=None),
verbose=0,
confounds=None,
sample_mask=None,
copy=True,
dtype=None,
):
"""Extract representative time series using given mask.

Expand All @@ -83,10 +93,10 @@
# Raise warning if a 3D niimg is provided.
if temp_imgs.ndim == 3:
warnings.warn(
'Starting in version 0.12, 3D images will be transformed to '
'1D arrays. '
'Until then, 3D images will be coerced to 2D arrays, with a '
'singleton first dimension representing time.',
"Starting in version 0.12, 3D images will be transformed to "
"1D arrays. "
"Until then, 3D images will be coerced to 2D arrays, with a "
"singleton first dimension representing time.",
DeprecationWarning,
)

Expand All @@ -97,29 +107,30 @@

if not _utils.niimg_conversions._check_same_fov(imgs, mask_img_):
warnings.warn(
'imgs are being resampled to the mask_img resolution. '
'This process is memory intensive. You might want to provide '
'a target_affine that is equal to the affine of the imgs '
'or resample the mask beforehand '
'to save memory and computation time.',
UserWarning
"imgs are being resampled to the mask_img resolution. "
"This process is memory intensive. You might want to provide "
"a target_affine that is equal to the affine of the imgs "
"or resample the mask beforehand "
"to save memory and computation time.",
UserWarning,
)
parameters = copy_object(parameters)
# now we can crop
mask_img_ = image.crop_img(mask_img_, copy=False)
parameters['target_shape'] = mask_img_.shape
parameters['target_affine'] = mask_img_.affine
parameters["target_shape"] = mask_img_.shape
parameters["target_affine"] = mask_img_.affine

data, affine = _filter_and_extract(
imgs, _ExtractionFunctor(mask_img_),
imgs,
_ExtractionFunctor(mask_img_),
parameters,
memory_level=memory_level,
memory=memory,
verbose=verbose,
confounds=confounds,
sample_mask=sample_mask,
copy=copy,
dtype=dtype
dtype=dtype,
)
# For _later_: missing value removal or imputing of missing data
# (i.e. we want to get rid of NaNs, if smoothing must be done
Expand Down Expand Up @@ -238,7 +249,7 @@
t_r=None,
target_affine=None,
target_shape=None,
mask_strategy='background',
mask_strategy="background",
mask_args=None,
dtype=None,
memory_level=1,
Expand Down Expand Up @@ -269,17 +280,17 @@
self.verbose = verbose
self.reports = reports
self._report_content = {
'description': (
'This report shows the input Nifti image overlaid '
'with the outlines of the mask (in green). We '
'recommend to inspect the report for the overlap '
'between the mask and its input image. '
"description": (
"This report shows the input Nifti image overlaid "
"with the outlines of the mask (in green). We "
"recommend to inspect the report for the overlap "
"between the mask and its input image. "
),
'warning_message': None
"warning_message": None,
}
self._overlay_text = (
'\n To see the input Nifti image before resampling, '
'hover over the displayed image.'
"\n To see the input Nifti image before resampling, "
"hover over the displayed image."
)
self._shelving = False
self.clean_kwargs = {
Expand All @@ -289,6 +300,7 @@
def generate_report(self):
"""Generate a report of the masker."""
from nilearn.reporting.html_report import generate_report

return generate_report(self)

def _reporting(self):
Expand All @@ -308,10 +320,10 @@
except ImportError:
with warnings.catch_warnings():
mpl_unavail_msg = (
'Matplotlib is not imported! '
'No reports will be generated.'
"Matplotlib is not imported! "
"No reports will be generated."
)
warnings.filterwarnings('always', message=mpl_unavail_msg)
warnings.filterwarnings("always", message=mpl_unavail_msg)

Check warning on line 326 in nilearn/maskers/nifti_masker.py

View check run for this annotation

Codecov / codecov/patch

nilearn/maskers/nifti_masker.py#L326

Added line #L326 was not covered by tests
warnings.warn(
category=ImportWarning,
message=mpl_unavail_msg,
Expand All @@ -323,8 +335,8 @@
if self._reporting_data is None:
return [None]

img = self._reporting_data['images']
mask = self._reporting_data['mask']
img = self._reporting_data["images"]
mask = self._reporting_data["mask"]

Check warning on line 339 in nilearn/maskers/nifti_masker.py

View check run for this annotation

Codecov / codecov/patch

nilearn/maskers/nifti_masker.py#L338-L339

Added lines #L338 - L339 were not covered by tests

if img is not None:
dim = image.load_img(img).shape
Expand All @@ -334,38 +346,38 @@

else: # images were not provided to fit
msg = (
'No image provided to fit in NiftiMasker. '
'Setting image to mask for reporting.'
"No image provided to fit in NiftiMasker. "
"Setting image to mask for reporting."
)
warnings.warn(msg)
self._report_content['warning_message'] = msg
self._report_content["warning_message"] = msg

Check warning on line 353 in nilearn/maskers/nifti_masker.py

View check run for this annotation

Codecov / codecov/patch

nilearn/maskers/nifti_masker.py#L353

Added line #L353 was not covered by tests
img = mask

# create display of retained input mask, image
# for visual comparison
init_display = plotting.plot_img(
img,
black_bg=False,
cmap='CMRmap_r',
cmap="CMRmap_r",
)
plt.close()
if mask is not None:
init_display.add_contours(
mask,
levels=[.5],
colors='g',
levels=[0.5],
colors="g",
linewidths=2.5,
)

if 'transform' not in self._reporting_data:
if "transform" not in self._reporting_data:
return [init_display]

# if resampling was performed
self._report_content['description'] += self._overlay_text
self._report_content["description"] += self._overlay_text

Check warning on line 376 in nilearn/maskers/nifti_masker.py

View check run for this annotation

Codecov / codecov/patch

nilearn/maskers/nifti_masker.py#L376

Added line #L376 was not covered by tests

# create display of resampled NiftiImage and mask
# assuming that resampl_img has same dim as img
resampl_img, resampl_mask = self._reporting_data['transform']
resampl_img, resampl_mask = self._reporting_data["transform"]

Check warning on line 380 in nilearn/maskers/nifti_masker.py

View check run for this annotation

Codecov / codecov/patch

nilearn/maskers/nifti_masker.py#L380

Added line #L380 was not covered by tests
if resampl_img is None: # images were not provided to fit
resampl_img = resampl_mask
elif len(dim) == 4:
Expand All @@ -375,24 +387,24 @@
final_display = plotting.plot_img(
resampl_img,
black_bg=False,
cmap='CMRmap_r',
cmap="CMRmap_r",
)
plt.close()
final_display.add_contours(
resampl_mask,
levels=[.5],
colors='g',
levels=[0.5],
colors="g",
linewidths=2.5,
)

return [init_display, final_display]

def _check_fitted(self):
if not hasattr(self, 'mask_img_'):
if not hasattr(self, "mask_img_"):
raise ValueError(
f'It seems that {self.__class__.__name__} has not been '
'fitted. '
'You must call fit() before calling transform().'
f"It seems that {self.__class__.__name__} has not been "
"fitted. "
"You must call fit() before calling transform()."
)

def fit(self, imgs=None, y=None):
Expand All @@ -413,38 +425,38 @@
# Load data (if filenames are given, load them)
if self.verbose > 0:
print(
f'[{self.__class__.__name__}.fit] '
f'Loading data from {_utils._repr_niimgs(imgs, shorten=False)}'
f"[{self.__class__.__name__}.fit] "
f"Loading data from {_utils._repr_niimgs(imgs, shorten=False)}"
)

# Compute the mask if not given by the user
if self.mask_img is None:
mask_args = (self.mask_args if self.mask_args is not None else {})
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:
print(f'[{self.__class__.__name__}.fit] Computing the mask')
self.mask_img_ = self._cache(compute_mask, ignore=['verbose'])(
print(f"[{self.__class__.__name__}.fit] Computing the mask")

Check warning on line 437 in nilearn/maskers/nifti_masker.py

View check run for this annotation

Codecov / codecov/patch

nilearn/maskers/nifti_masker.py#L437

Added line #L437 was not covered by tests
self.mask_img_ = self._cache(compute_mask, ignore=["verbose"])(
imgs, verbose=max(0, self.verbose - 1), **mask_args
)
else:
self.mask_img_ = _utils.check_niimg_3d(self.mask_img)

if self.reports: # save inputs for reporting
self._reporting_data = {'images': imgs, 'mask': self.mask_img_}
self._reporting_data = {"images": imgs, "mask": self.mask_img_}
else:
self._reporting_data = None

# If resampling is requested, resample also the mask
# Resampling: allows the user to change the affine, the shape or both
if self.verbose > 0:
print(f'[{self.__class__.__name__}.fit] Resampling mask')
print(f"[{self.__class__.__name__}.fit] Resampling mask")

Check warning on line 452 in nilearn/maskers/nifti_masker.py

View check run for this annotation

Codecov / codecov/patch

nilearn/maskers/nifti_masker.py#L452

Added line #L452 was not covered by tests

self.mask_img_ = self._cache(image.resample_img)(
self.mask_img_,
target_affine=self.target_affine,
target_shape=self.target_shape,
copy=False,
interpolation='nearest',
interpolation="nearest",
)

if self.target_affine is not None: # resample image to target affine
Expand All @@ -459,7 +471,7 @@
self.n_elements_ = int(data.sum())

if self.verbose > 10:
print(f'[{self.__class__.__name__}.fit] Finished fit')
print(f"[{self.__class__.__name__}.fit] Finished fit")

Check warning on line 474 in nilearn/maskers/nifti_masker.py

View check run for this annotation

Codecov / codecov/patch

nilearn/maskers/nifti_masker.py#L474

Added line #L474 was not covered by tests

if (
(self.target_shape is not None)
Expand All @@ -471,14 +483,12 @@
imgs,
target_affine=self.affine_,
copy=False,
interpolation='nearest',
interpolation="nearest",
)
else: # imgs not provided to fit
resampl_imgs = None

self._reporting_data['transform'] = [
resampl_imgs, self.mask_img_
]
self._reporting_data["transform"] = [resampl_imgs, self.mask_img_]

return self

Expand Down Expand Up @@ -535,22 +545,22 @@
self.__class__,
self,
ignore=[
'mask_img',
'mask_args',
'mask_strategy',
'_sample_mask',
'sample_mask',
"mask_img",
"mask_args",
"mask_strategy",
"_sample_mask",
"sample_mask",
],
)
params['clean_kwargs'] = self.clean_kwargs
params["clean_kwargs"] = self.clean_kwargs

data = self._cache(
_filter_and_mask,
ignore=[
'verbose',
'memory',
'memory_level',
'copy',
"verbose",
"memory",
"memory_level",
"copy",
],
shelve=self._shelving,
)(
Expand Down