From 706fcd6e424e6237443b6454c1189fd5f4d7f091 Mon Sep 17 00:00:00 2001 From: Remi Gau Date: Fri, 4 Oct 2024 04:21:06 +0200 Subject: [PATCH] fix error D209 from ruff (#4583) --- .../plot_first_level_details.py | 3 +- nilearn/_utils/niimg_conversions.py | 3 +- nilearn/_utils/segmentation.py | 3 +- nilearn/_utils/tests/test_data_gen.py | 3 +- nilearn/_utils/tests/test_helpers.py | 6 ++-- nilearn/connectome/__init__.py | 3 +- nilearn/connectome/group_sparse_cov.py | 3 +- .../tests/test_connectivity_matrices.py | 6 ++-- nilearn/datasets/func.py | 6 ++-- nilearn/datasets/neurovault.py | 3 +- nilearn/datasets/tests/test_utils.py | 3 +- nilearn/decoding/decoder.py | 3 +- nilearn/decoding/searchlight.py | 3 +- nilearn/decoding/space_net.py | 6 ++-- nilearn/decoding/space_net_solvers.py | 9 +++-- nilearn/decoding/tests/test_decoder.py | 9 +++-- nilearn/decoding/tests/test_graph_net.py | 9 +++-- nilearn/decoding/tests/test_same_api.py | 9 +++-- nilearn/decomposition/__init__.py | 3 +- nilearn/decomposition/_base.py | 3 +- nilearn/decomposition/canica.py | 3 +- nilearn/decomposition/tests/test_base.py | 3 +- nilearn/decomposition/tests/test_canica.py | 3 +- nilearn/decomposition/tests/test_multi_pca.py | 12 ++++--- .../experimental/surface/_surface_image.py | 3 +- nilearn/glm/_base.py | 3 +- nilearn/glm/contrasts.py | 9 +++-- nilearn/glm/second_level/second_level.py | 9 +++-- nilearn/glm/tests/test_dmtx.py | 3 +- nilearn/glm/tests/test_first_level.py | 6 ++-- nilearn/glm/tests/test_hemodynamic_models.py | 12 ++++--- nilearn/glm/tests/test_paradigm.py | 12 ++++--- nilearn/glm/tests/test_second_level.py | 9 +++-- nilearn/image/tests/test_image.py | 15 +++++--- nilearn/image/tests/test_resampling.py | 3 +- nilearn/interfaces/bids/__init__.py | 3 +- nilearn/interfaces/fmriprep/__init__.py | 3 +- .../fmriprep/tests/test_load_confounds.py | 9 +++-- .../tests/test_load_confounds_components.py | 3 +- nilearn/maskers/multi_nifti_masker.py | 3 +- nilearn/maskers/tests/test_input_data.py | 3 +- nilearn/maskers/tests/test_nifti_masker.py | 3 +- nilearn/mass_univariate/__init__.py | 3 +- .../mass_univariate/permuted_least_squares.py | 3 +- .../tests/test_permuted_least_squares.py | 9 +++-- nilearn/plotting/displays/_axes.py | 6 ++-- nilearn/plotting/displays/_slicers.py | 6 ++-- nilearn/plotting/edge_detect.py | 3 +- nilearn/plotting/glass_brain.py | 3 +- nilearn/plotting/js_plotting_utils.py | 3 +- nilearn/plotting/tests/test_displays.py | 6 ++-- .../test_get_colorbar_and_data_ranges.py | 3 +- .../test_img_plotting/test_img_plotting.py | 3 +- .../tests/test_img_plotting/test_plot_anat.py | 3 +- .../test_img_plotting/test_plot_connectome.py | 36 ++++++++++++------- .../tests/test_img_plotting/test_plot_img.py | 3 +- .../test_img_plotting/test_plot_markers.py | 15 +++++--- nilearn/plotting/tests/test_surf_plotting.py | 6 ++-- nilearn/regions/__init__.py | 3 +- .../regions/hierarchical_kmeans_clustering.py | 3 +- nilearn/regions/tests/test_parcellations.py | 3 +- .../regions/tests/test_region_extractor.py | 6 ++-- .../regions/tests/test_signal_extraction.py | 12 ++++--- nilearn/reporting/html_report.py | 3 +- nilearn/reporting/tests/test_glm_reporter.py | 3 +- nilearn/reporting/tests/test_html_report.py | 24 ++++++++----- nilearn/reporting/tests/test_reporting.py | 6 ++-- nilearn/signal.py | 3 +- nilearn/surface/tests/test_surface.py | 3 +- pyproject.toml | 1 - 70 files changed, 272 insertions(+), 137 deletions(-) diff --git a/examples/04_glm_first_level/plot_first_level_details.py b/examples/04_glm_first_level/plot_first_level_details.py index 5c51f233d7..b185877fc8 100644 --- a/examples/04_glm_first_level/plot_first_level_details.py +++ b/examples/04_glm_first_level/plot_first_level_details.py @@ -194,7 +194,8 @@ def make_localizer_contrasts(design_matrix): def plot_contrast(first_level_model): """Specify, estimate and plot the main contrasts \ - for given a first model.""" + for given a first model. + """ design_matrix = first_level_model.design_matrices_[0] # Call the contrast specification within the function contrasts = make_localizer_contrasts(design_matrix) diff --git a/nilearn/_utils/niimg_conversions.py b/nilearn/_utils/niimg_conversions.py index 9f26e9ea14..301012cd5e 100644 --- a/nilearn/_utils/niimg_conversions.py +++ b/nilearn/_utils/niimg_conversions.py @@ -21,7 +21,8 @@ def _check_fov(img, affine, shape): """Return True if img's field of view correspond to given \ - shape and affine, False elsewhere.""" + shape and affine, False elsewhere. + """ img = check_niimg(img) return img.shape[:3] == shape and np.allclose(img.affine, affine) diff --git a/nilearn/_utils/segmentation.py b/nilearn/_utils/segmentation.py index 6b59edfbf9..799cb876cc 100644 --- a/nilearn/_utils/segmentation.py +++ b/nilearn/_utils/segmentation.py @@ -130,7 +130,8 @@ def _buildAB(lap_sparse, labels): def _mask_edges_weights(edges, weights, mask): """Remove edges of the graph connected to masked nodes, \ - as well as corresponding weights of the edges.""" + as well as corresponding weights of the edges. + """ mask0 = np.hstack( (mask[:, :, :-1].ravel(), mask[:, :-1].ravel(), mask[:-1].ravel()) ) diff --git a/nilearn/_utils/tests/test_data_gen.py b/nilearn/_utils/tests/test_data_gen.py index 4db1a0e41d..eb18536463 100644 --- a/nilearn/_utils/tests/test_data_gen.py +++ b/nilearn/_utils/tests/test_data_gen.py @@ -33,7 +33,8 @@ def test_add_metadata_to_bids_derivatives_default_path(tmp_path): """Check the filename created is the default value \ - of add_metadata_to_bids_dataset.""" + of add_metadata_to_bids_dataset. + """ target_dir = tmp_path / "derivatives" / "sub-01" / "ses-01" / "func" target_dir.mkdir(parents=True) json_file = add_metadata_to_bids_dataset( diff --git a/nilearn/_utils/tests/test_helpers.py b/nilearn/_utils/tests/test_helpers.py index 752f92fb94..eab8a06630 100644 --- a/nilearn/_utils/tests/test_helpers.py +++ b/nilearn/_utils/tests/test_helpers.py @@ -7,7 +7,8 @@ def _mock_args_for_testing_replace_parameter(): """Create mock deprecated & replacement parameters for use \ - with testing functions related to replace_parameters().""" + with testing functions related to replace_parameters(). + """ mock_kwargs_with_deprecated_params_used = { "unchanged_param_0": "unchanged_param_0_val", "deprecated_param_0": "deprecated_param_0_val", @@ -82,7 +83,8 @@ def mock_function( def test_transfer_deprecated_param_vals(): """Check that values assigned to deprecated parameters are \ - correctly reassigned to the replacement parameters.""" + correctly reassigned to the replacement parameters. + """ mock_input, replacement_params = _mock_args_for_testing_replace_parameter() expected_output = { "unchanged_param_0": "unchanged_param_0_val", diff --git a/nilearn/connectome/__init__.py b/nilearn/connectome/__init__.py index 5e5552109e..fc5dae4dea 100644 --- a/nilearn/connectome/__init__.py +++ b/nilearn/connectome/__init__.py @@ -1,6 +1,7 @@ """Tools for computing functional connectivity matrices \ and also implementation of algorithm for sparse multi subjects learning \ -of Gaussian graphical models.""" +of Gaussian graphical models. +""" from .connectivity_matrices import ( ConnectivityMeasure, diff --git a/nilearn/connectome/group_sparse_cov.py b/nilearn/connectome/group_sparse_cov.py index dfc5b53c4b..130756b457 100644 --- a/nilearn/connectome/group_sparse_cov.py +++ b/nilearn/connectome/group_sparse_cov.py @@ -1,5 +1,6 @@ """Implementation of algorithm for sparse multi-subjects learning of Gaussian \ -graphical models.""" +graphical models. +""" # Authors: Philippe Gervais diff --git a/nilearn/connectome/tests/test_connectivity_matrices.py b/nilearn/connectome/tests/test_connectivity_matrices.py index de4b215e0c..ddda440488 100644 --- a/nilearn/connectome/tests/test_connectivity_matrices.py +++ b/nilearn/connectome/tests/test_connectivity_matrices.py @@ -101,7 +101,8 @@ def random_spd(p, eig_min, cond, random_state=0): def _signals(n_subjects=N_SUBJECTS): """Generate signals and compute covariances \ - and apply confounds while computing covariances.""" + and apply confounds while computing covariances. + """ n_features = N_FEATURES signals = [] for k in range(n_subjects): @@ -646,7 +647,8 @@ def _assert_connectivity_precision(connectivities, covs): """Estimated precision matrix: \ - is positive definite, \ - its product with the true covariance matrix \ - is close to the identity matrix.""" + is close to the identity matrix. + """ for true_covariance_matrix, estimated_covariance_matrix in zip( covs, connectivities ): diff --git a/nilearn/datasets/func.py b/nilearn/datasets/func.py index ee6bca58ef..952b83988e 100644 --- a/nilearn/datasets/func.py +++ b/nilearn/datasets/func.py @@ -1,5 +1,6 @@ """Downloading NeuroImaging datasets: \ -functional datasets (task + resting-state).""" +functional datasets (task + resting-state). +""" import fnmatch import glob @@ -1293,7 +1294,8 @@ def fetch_abide_pcp( def _load_mixed_gambles(zmap_imgs): """Ravel zmaps (one per subject) along time axis, resulting, \ in a n_subjects * n_trials 3D niimgs and, and then make \ - gain vector y of same length.""" + gain vector y of same length. + """ X = [] y = [] mask = [] diff --git a/nilearn/datasets/neurovault.py b/nilearn/datasets/neurovault.py index 5bbf00bbe8..5a4f0bc044 100644 --- a/nilearn/datasets/neurovault.py +++ b/nilearn/datasets/neurovault.py @@ -1,5 +1,6 @@ """Download statistical maps available \ -on Neurovault (https://neurovault.org).""" +on Neurovault (https://neurovault.org). +""" # Author: Jerome Dockes diff --git a/nilearn/datasets/tests/test_utils.py b/nilearn/datasets/tests/test_utils.py index aabf888de3..4e00c17d8e 100644 --- a/nilearn/datasets/tests/test_utils.py +++ b/nilearn/datasets/tests/test_utils.py @@ -66,7 +66,8 @@ def test_get_dataset_descr_warning(): """Tests that function ``get_dataset_descr()`` gives a warning \ - when no description is available.""" + when no description is available. + """ with pytest.warns( UserWarning, match="Could not find dataset description." ): diff --git a/nilearn/decoding/decoder.py b/nilearn/decoding/decoder.py index c8caaaf9d7..a524668e5d 100644 --- a/nilearn/decoding/decoder.py +++ b/nilearn/decoding/decoder.py @@ -1057,7 +1057,8 @@ def _binarize_y(self, y): def _predict_dummy(self, n_samples): """Non-sparse scikit-learn based prediction steps for classification \ - and regression.""" + and regression. + """ if len(self.dummy_output_) == 1: dummy_output = self.dummy_output_[0] else: diff --git a/nilearn/decoding/searchlight.py b/nilearn/decoding/searchlight.py index 4635d4b3ce..1337c943de 100644 --- a/nilearn/decoding/searchlight.py +++ b/nilearn/decoding/searchlight.py @@ -1,7 +1,8 @@ """The searchlight is a widely used approach for the study \ of the fine-grained patterns of information in fMRI analysis, \ in which multivariate statistical relationships are iteratively tested \ -in the neighborhood of each location of a domain.""" +in the neighborhood of each location of a domain. +""" # Authors : Vincent Michel (vm.michel@gmail.com) # Alexandre Gramfort (alexandre.gramfort@inria.fr) diff --git a/nilearn/decoding/space_net.py b/nilearn/decoding/space_net.py index 1124a37650..d8e2a6971a 100644 --- a/nilearn/decoding/space_net.py +++ b/nilearn/decoding/space_net.py @@ -45,7 +45,8 @@ def _crop_mask(mask): """Crops input mask to produce tighter (i.e smaller) bounding box \ - with the same support (active voxels).""" + with the same support (active voxels). + """ idx = np.where(mask) if idx[0].size == 0: raise ValueError( @@ -809,7 +810,8 @@ def check_params(self): def _set_coef_and_intercept(self, w): """Set the loadings vector (coef) and the intercept of the fitted \ - model.""" + model. + """ self.w_ = np.array(w) if self.w_.ndim == 1: self.w_ = self.w_[np.newaxis, :] diff --git a/nilearn/decoding/space_net_solvers.py b/nilearn/decoding/space_net_solvers.py index d96c67b68f..3fe0c1ea15 100644 --- a/nilearn/decoding/space_net_solvers.py +++ b/nilearn/decoding/space_net_solvers.py @@ -177,7 +177,8 @@ def _squared_loss_derivative_lipschitz_constant( ): """Compute the lipschitz constant of the gradient of the smooth part \ of the Graph-Net regression problem (squared_loss + grad_weight*grad) \ - via power method.""" + via power method. + """ rng = np.random.RandomState(42) a = rng.randn(X.shape[1]) a /= sqrt(np.dot(a, a)) @@ -215,7 +216,8 @@ def _logistic_derivative_lipschitz_constant( """Compute the lipschitz constant of the gradient of the smooth part \ of the Graph-Net classification problem (logistic_loss + \ grad_weight*grad) via analytical formula on the logistic loss + \ - power method on the smooth part.""" + power method on the smooth part. + """ # L. constant for the data term (logistic) # data_constant = sp.linalg.norm(X, 2) ** 2 data_constant = logistic_loss_lipschitz_constant(X) @@ -238,7 +240,8 @@ def _logistic_derivative_lipschitz_constant( def _logistic_data_loss_and_spatial_grad(X, y, w, mask, grad_weight): """Compute the smooth part of the Graph-Net objective, \ - with logistic loss.""" + with logistic loss. + """ grad_buffer = np.zeros(mask.shape) grad_buffer[mask] = w[:-1] grad_mask = np.array([mask for _ in range(mask.ndim)]) diff --git a/nilearn/decoding/tests/test_decoder.py b/nilearn/decoding/tests/test_decoder.py index 9ebbf647c0..457204bef7 100644 --- a/nilearn/decoding/tests/test_decoder.py +++ b/nilearn/decoding/tests/test_decoder.py @@ -360,7 +360,8 @@ def test_check_unsupported_estimator(estimator): def test_parallel_fit(rand_X_Y): """Check that results of _parallel_fit is the same \ - for different controlled param_grid.""" + for different controlled param_grid. + """ X, y = make_regression( n_samples=N_SAMPLES, n_features=20, @@ -439,7 +440,8 @@ def test_parallel_fit_builtin_cv( ): """Check that the `fitted_param_name` output of _parallel_fit is \ a single value even if param_grid is wrapped in a list \ - for models with built-in CV.""" + for models with built-in CV. + """ # y will be replaced if this is a classification X, y = make_regression( n_samples=N_SAMPLES, @@ -912,7 +914,8 @@ def test_decoder_multiclass_classification_cross_validation( def test_decoder_multiclass_classification_apply_mask_shape(): """Test whether if _apply mask output has the same shape \ - as original matrix.""" + as original matrix. + """ X_init, _ = make_classification( n_samples=200, n_features=125, diff --git a/nilearn/decoding/tests/test_graph_net.py b/nilearn/decoding/tests/test_graph_net.py index 0806e1425f..2081dd2290 100644 --- a/nilearn/decoding/tests/test_graph_net.py +++ b/nilearn/decoding/tests/test_graph_net.py @@ -87,7 +87,8 @@ def test_adjointness(rng, size=4): def test_identity_adjointness(rng, size=4): """Test adjointess between _graph_net_data_function and \ - _graph_net_adjoint_data_function, with identity design matrix.""" + _graph_net_adjoint_data_function, with identity design matrix. + """ # A mask full of ones mask = np.ones((size, size, size), dtype=bool) @@ -184,7 +185,8 @@ def func_grad(w): def test_squared_loss_derivative_lipschitz_constant(rng): """Test Lipschitz-continuity of the derivative of squared_loss loss \ - function.""" + function. + """ X, y, w, mask, *_ = _make_data() grad_weight = 2.08e-1 @@ -235,7 +237,8 @@ def test_logistic_derivative_lipschitz_constant(rng): @pytest.mark.parametrize("l1_ratio", np.linspace(0.1, 1, 3)) def test_max_alpha_squared_loss(l1_ratio): """Tests that models with L1 regularization over the theoretical bound \ - are full of zeros, for logistic regression.""" + are full of zeros, for logistic regression. + """ X, y, _, _, mask_, X_ = _make_data() reg = BaseSpaceNet( diff --git a/nilearn/decoding/tests/test_same_api.py b/nilearn/decoding/tests/test_same_api.py index cbcf11b0cc..61a4b73781 100644 --- a/nilearn/decoding/tests/test_same_api.py +++ b/nilearn/decoding/tests/test_same_api.py @@ -202,7 +202,8 @@ def test_graph_net_and_tvl1_same_for_pure_l1_BaseSpaceNet( def test_graph_net_and_tvl1_same_for_pure_l1_logistic(max_iter=20, decimal=2): """Check graph_net_solver and tvl1_solver should give same results \ - when l1_ratio = 1.""" + when l1_ratio = 1. + """ iris = load_iris() X, y = iris.data, iris.target y = y > 0.0 @@ -232,7 +233,8 @@ def test_graph_net_and_tvl1_same_for_pure_l1_logistic_spacenet_classifier( standardize, max_iter=20, decimal=2 ): """Check graph_net_solver and tvl1_solver should give same results \ - when l1_ratio = 1.""" + when l1_ratio = 1. + """ iris = load_iris() X, y = iris.data, iris.target y = y > 0.0 @@ -266,7 +268,8 @@ def test_graph_net_and_tv_same_for_pure_l1_another_test( standardize, decimal=1 ): """Check that graph_net_solver and tvl1_solver give same results \ - when l1_ratio = 1.""" + when l1_ratio = 1. + """ dim = (3, 3, 3) X, y, _, mask = _make_data(masked=True, dim=dim) X, mask = to_niimgs(X, dim) diff --git a/nilearn/decomposition/__init__.py b/nilearn/decomposition/__init__.py index 73aaa9fcbf..c9a2101223 100644 --- a/nilearn/decomposition/__init__.py +++ b/nilearn/decomposition/__init__.py @@ -1,5 +1,6 @@ """The :mod:`nilearn.decomposition` module includes a subject level \ -variant of the :term:`ICA` called Canonical :term:`ICA`.""" +variant of the :term:`ICA` called Canonical :term:`ICA`. +""" from .canica import CanICA from .dict_learning import DictLearning diff --git a/nilearn/decomposition/_base.py b/nilearn/decomposition/_base.py index 2ef45d3150..991201403a 100644 --- a/nilearn/decomposition/_base.py +++ b/nilearn/decomposition/_base.py @@ -534,7 +534,8 @@ def inverse_transform(self, loadings): def _sort_by_score(self, data): """Sort components on the explained variance over data of estimator \ - components_.""" + components_. + """ components_score = self._raw_score(data, per_component=True) order = np.argsort(components_score)[::-1] self.components_ = self.components_[order] diff --git a/nilearn/decomposition/canica.py b/nilearn/decomposition/canica.py index 3ec8b51304..787cf1acec 100644 --- a/nilearn/decomposition/canica.py +++ b/nilearn/decomposition/canica.py @@ -212,7 +212,8 @@ def __init__( def _unmix_components(self, components): """Core function of CanICA than rotate components_ to maximize \ - independence.""" + independence. + """ random_state = check_random_state(self.random_state) seeds = random_state.randint(np.iinfo(np.int32).max, size=self.n_init) diff --git a/nilearn/decomposition/tests/test_base.py b/nilearn/decomposition/tests/test_base.py index abb737ec62..0c792d2ea9 100644 --- a/nilearn/decomposition/tests/test_base.py +++ b/nilearn/decomposition/tests/test_base.py @@ -91,7 +91,8 @@ def test_mask_reducer_single_image_same_with_multiple_jobs( data_for_mask_and_reduce, masker, shape_3d_default ): """Mask and reduce a 3D image and check results is the same \ - when split over several CPUs.""" + when split over several CPUs. + """ data_single = _mask_and_reduce( masker, data_for_mask_and_reduce[0], n_components=3 ) diff --git a/nilearn/decomposition/tests/test_canica.py b/nilearn/decomposition/tests/test_canica.py index dbb995dd95..f0914383b6 100644 --- a/nilearn/decomposition/tests/test_canica.py +++ b/nilearn/decomposition/tests/test_canica.py @@ -111,7 +111,8 @@ def canica_data(): def test_threshold_bound_error(): """Test that an error is raised when the threshold is higher \ - than the number of components.""" + than the number of components. + """ with pytest.raises(ValueError, match="Threshold must not be higher"): CanICA(n_components=4, threshold=5.0) diff --git a/nilearn/decomposition/tests/test_multi_pca.py b/nilearn/decomposition/tests/test_multi_pca.py index 0e5d7792ce..8768950ff4 100644 --- a/nilearn/decomposition/tests/test_multi_pca.py +++ b/nilearn/decomposition/tests/test_multi_pca.py @@ -58,7 +58,8 @@ def test_multi_pca_check_masker_attributes(multi_pca_data, mask_img): def test_multi_pca(multi_pca_data, mask_img): """Components are the same if we put twice the same data, \ - and that fit output is deterministic.""" + and that fit output is deterministic. + """ multi_pca = _MultiPCA(mask=mask_img, n_components=3, random_state=0) multi_pca.fit(multi_pca_data) @@ -79,7 +80,8 @@ def test_multi_pca_with_confounds_smoke(multi_pca_data, mask_img): def test_multi_pca_componenent_errors(mask_img): """Test that a ValueError is raised \ - if the number of components is too low.""" + if the number of components is too low. + """ multi_pca = _MultiPCA(mask=mask_img) with pytest.raises( ValueError, match="Object has no components_ attribute." @@ -129,7 +131,8 @@ def test_multi_pca_with_masker(multi_pca_data): def test_multi_pca_with_masker_without_cca_smoke(multi_pca_data): """Multi-pca can run with a masker \ - and without canonical correlation analysis.""" + and without canonical correlation analysis. + """ masker = MultiNiftiMasker(mask_args=dict(opening=0)) multi_pca = _MultiPCA( @@ -186,7 +189,8 @@ def test_multi_pca_score_single_subject(mask_img): def test_multi_pca_score_single_subject_n_components(mask_img): """Score is one for n_components == n_sample \ - in single subject configuration.""" + in single subject configuration. + """ data, _, _, _ = _make_multi_pca_test_data(with_activation=False) multi_pca = _MultiPCA( mask=mask_img, random_state=0, memory_level=0, n_components=5 diff --git a/nilearn/experimental/surface/_surface_image.py b/nilearn/experimental/surface/_surface_image.py index b2aa8bc3ab..a973f05577 100644 --- a/nilearn/experimental/surface/_surface_image.py +++ b/nilearn/experimental/surface/_surface_image.py @@ -62,7 +62,8 @@ def __init__( class Mesh(abc.ABC): """A surface :term:`mesh` having vertex, \ - coordinates and faces (triangles).""" + coordinates and faces (triangles). + """ n_vertices: int diff --git a/nilearn/glm/_base.py b/nilearn/glm/_base.py index d9d12a52f1..f877de5a0c 100644 --- a/nilearn/glm/_base.py +++ b/nilearn/glm/_base.py @@ -6,7 +6,8 @@ class BaseGLM(BaseEstimator, TransformerMixin, CacheMixin): """Implement a base class \ - for the :term:`General Linear Model`.""" + for the :term:`General Linear Model`. + """ # @auto_attr store the value as an object attribute after initial call # better performance than @property diff --git a/nilearn/glm/contrasts.py b/nilearn/glm/contrasts.py index b143aabe13..ece5da4a8c 100644 --- a/nilearn/glm/contrasts.py +++ b/nilearn/glm/contrasts.py @@ -275,12 +275,14 @@ def contrast_type(self): def effect_size(self): """Make access to summary statistics more straightforward \ - when computing contrasts.""" + when computing contrasts. + """ return self.effect def effect_variance(self): """Make access to summary statistics more straightforward \ - when computing contrasts.""" + when computing contrasts. + """ return self.variance def stat(self, baseline=0.0): @@ -571,7 +573,8 @@ def _compute_fixed_effects_params( contrasts, variances, precision_weighted, dofs ): """Compute the fixed effects t/F-statistic, contrast, variance, \ - given arrays of effects and variance.""" + given arrays of effects and variance. + """ tiny = 1.0e-16 contrasts, variances = np.asarray(contrasts), np.asarray(variances) variances = np.maximum(variances, tiny) diff --git a/nilearn/glm/second_level/second_level.py b/nilearn/glm/second_level/second_level.py index e0c49fc739..276dc8d833 100644 --- a/nilearn/glm/second_level/second_level.py +++ b/nilearn/glm/second_level/second_level.py @@ -266,7 +266,8 @@ def _check_effect_maps(effect_maps, design_matrix): def _get_con_val(second_level_contrast, design_matrix): """Check the contrast and return con_val \ - when testing one contrast or more.""" + when testing one contrast or more. + """ if second_level_contrast is None: if design_matrix.shape[1] == 1: second_level_contrast = np.ones([1]) @@ -343,7 +344,8 @@ def _process_second_level_input_as_dataframe(second_level_input): def _sort_input_dataframe(second_level_input): """Sort the pandas dataframe by subject_label to \ avoid inconsistencies with the design matrix row order when \ - automatically extracting maps.""" + automatically extracting maps. + """ columns = second_level_input.columns.tolist() column_index = columns.index("subject_label") sorted_matrix = sorted( @@ -354,7 +356,8 @@ def _sort_input_dataframe(second_level_input): def _process_second_level_input_as_firstlevelmodels(second_level_input): """Process second_level_input provided \ - as a list of FirstLevelModel objects.""" + as a list of FirstLevelModel objects. + """ sample_model = second_level_input[0] sample_condition = sample_model.design_matrices_[0].columns[0] sample_map = sample_model.compute_contrast( diff --git a/nilearn/glm/tests/test_dmtx.py b/nilearn/glm/tests/test_dmtx.py index 333a73e95b..4dd3967614 100644 --- a/nilearn/glm/tests/test_dmtx.py +++ b/nilearn/glm/tests/test_dmtx.py @@ -52,7 +52,8 @@ def design_matrix_light( min_onset=-24, ): """Perform same as make_first_level_design_matrix, \ - but only returns the computed matrix and associated name.""" + but only returns the computed matrix and associated name. + """ fir_delays = fir_delays or [0] dmtx = make_first_level_design_matrix( frame_times, diff --git a/nilearn/glm/tests/test_first_level.py b/nilearn/glm/tests/test_first_level.py index 739c6d2c90..ef862c0201 100644 --- a/nilearn/glm/tests/test_first_level.py +++ b/nilearn/glm/tests/test_first_level.py @@ -1626,7 +1626,8 @@ def test_first_level_from_bids_with_missing_events(tmp_path_factory): def test_first_level_from_bids_no_tr(tmp_path_factory): """Throw warning when t_r information cannot be inferred from the data \ - and t_r=None is passed.""" + and t_r=None is passed. + """ bids_dataset = _new_bids_dataset(tmp_path_factory.mktemp("no_events")) json_files = get_bids_files( main_path=bids_dataset, file_tag="bold", file_type="json" @@ -1707,7 +1708,8 @@ def test_first_level_from_bids_one_confound_missing(tmp_path_factory): def test_first_level_from_bids_all_confounds_missing(tmp_path_factory): """If all confound files are missing, \ - confounds should be an array of None.""" + confounds should be an array of None. + """ bids_dataset = _new_bids_dataset(tmp_path_factory.mktemp("no_confounds")) confound_files = get_bids_files( main_path=bids_dataset / "derivatives", diff --git a/nilearn/glm/tests/test_hemodynamic_models.py b/nilearn/glm/tests/test_hemodynamic_models.py index eb821115f8..959fcbb002 100644 --- a/nilearn/glm/tests/test_hemodynamic_models.py +++ b/nilearn/glm/tests/test_hemodynamic_models.py @@ -67,7 +67,8 @@ def test_hrf_norm_and_length( hrf_model, t_r, expected_integral, expected_length ): """Test that the hrf models are correctly normalized and \ - have correct lengths.""" + have correct lengths. + """ h = hrf_model(t_r) assert_almost_equal(h.sum(), expected_integral) @@ -204,7 +205,8 @@ def test_sample_condition_5(): def test_sample_condition_6(): """Test the experimental condition sampling -- overalapping onsets, \ - different durations.""" + different durations. + """ condition = ([0, 0, 10], [1, 2, 1], [1.0, 1.0, 1.0]) frame_times = np.linspace(0, 49, 50) @@ -218,7 +220,8 @@ def test_sample_condition_6(): def test_sample_condition_7(): """Test the experimental condition sampling -- different onsets, \ - overlapping offsets.""" + overlapping offsets. + """ condition = ([0, 10, 20], [11, 1, 1], [1.0, 1.0, 1.0]) frame_times = np.linspace(0, 49, 50) @@ -436,7 +439,8 @@ def test__regressor_names(): def test_design_warnings(): """Test that warnings are correctly raised \ - upon weird design specification.""" + upon weird design specification. + """ condition = ([-25, 20, 36.5], [0, 0, 0], [1, 1, 1]) frame_times = np.linspace(0, 69, 70) hrf_model = "spm" diff --git a/nilearn/glm/tests/test_paradigm.py b/nilearn/glm/tests/test_paradigm.py index 84844d35dc..2fd4e1696a 100644 --- a/nilearn/glm/tests/test_paradigm.py +++ b/nilearn/glm/tests/test_paradigm.py @@ -50,7 +50,8 @@ def test_check_events(): def test_check_events_errors(): """Test the function which tests that the events \ - data describes a valid experimental paradigm.""" + data describes a valid experimental paradigm. + """ events = basic_paradigm() # Errors checkins # Wrong type @@ -82,7 +83,8 @@ def test_check_events_errors(): def test_check_events_warnings(): """Test the function which tests that the events \ - data describes a valid experimental paradigm.""" + data describes a valid experimental paradigm. + """ events = basic_paradigm() # Warnings checkins # Missing trial type @@ -113,7 +115,8 @@ def test_check_events_warnings(): def write_events(events, tmpdir): """Write events of an experimental paradigm \ - to a file and return the address.""" + to a file and return the address. + """ tsvfile = os.path.join(tmpdir, "events.tsv") events.to_csv(tsvfile, sep="\t") return tsvfile @@ -162,7 +165,8 @@ def test_check_events_nan_designs(design): def test_sum_modulation_of_duplicate_events(): """Test the function check_events \ - when the paradigm contains duplicate events.""" + when the paradigm contains duplicate events. + """ events = duplicate_events_paradigm() # Check that a warning is given to the user diff --git a/nilearn/glm/tests/test_second_level.py b/nilearn/glm/tests/test_second_level.py index 76126ab957..fa1307aa4d 100644 --- a/nilearn/glm/tests/test_second_level.py +++ b/nilearn/glm/tests/test_second_level.py @@ -155,7 +155,8 @@ def test_second_level_input_as_3D_images(rng, affine_eye, tmp_path): def test_process_second_level_input_as_firstlevelmodels(): """Unit tests for function \ - _process_second_level_input_as_firstlevelmodels().""" + _process_second_level_input_as_firstlevelmodels(). + """ shapes, rk = [(7, 8, 9, 15)], 3 mask, fmri_data, design_matrices = generate_fake_fmri_data_and_design( shapes, rk @@ -826,7 +827,8 @@ def test_second_level_voxelwise_attribute_errors(attribute): """Tests that an error is raised when trying to access \ voxelwise attributes before fitting the model, \ before computing a contrast, \ - and when not setting ``minimize_memory`` to ``True``.""" + and when not setting ``minimize_memory`` to ``True``. + """ shapes = (SHAPE,) mask, fmri_data, _ = generate_fake_fmri_data_and_design(shapes) model = SecondLevelModel(mask_img=mask, minimize_memory=False) @@ -953,7 +955,8 @@ def test_non_parametric_inference_cluster_level_with_covariates( rng, ): """Test non-parametric inference with cluster-level inference in \ - the context of covariates.""" + the context of covariates. + """ shapes = ((7, 8, 9, 1),) mask, FUNCFILE, _ = write_fake_fmri_data_and_design( shapes, file_path=tmp_path diff --git a/nilearn/image/tests/test_image.py b/nilearn/image/tests/test_image.py index 5fe94aa756..7602ea12df 100644 --- a/nilearn/image/tests/test_image.py +++ b/nilearn/image/tests/test_image.py @@ -698,7 +698,8 @@ def test_new_img_like_accepts_paths(affine_eye, tmp_path, rng): def test_new_img_like_non_iterable_header(rng): """Tests that when an niimg's header is not iterable \ - and it is set to be copied, an error is not raised.""" + and it is set to be copied, an error is not raised. + """ fake_fmri_data = rng.uniform(size=_shape_4d_default()) fake_affine = rng.uniform(size=(4, 4)) fake_spatial_image = spatialimages.SpatialImage( @@ -736,7 +737,8 @@ def test_new_img_like_int64(shape_3d_default): def test_validity_threshold_value_in_threshold_img(shape_3d_default): """Check that invalid values to threshold_img's threshold parameter \ - raise Exceptions.""" + raise Exceptions. + """ maps, _ = generate_maps(shape_3d_default, n_regions=2) # testing to raise same error when threshold=None case @@ -788,7 +790,8 @@ def test_threshold_img_with_cluster_threshold( stat_img_test_data, threshold, two_sided, cluster_threshold, expected ): """Check that passing specific threshold and cluster threshold values \ - only gives cluster the right number of voxels with the right values.""" + only gives cluster the right number of voxels with the right values. + """ thr_img = threshold_img( img=stat_img_test_data, threshold=threshold, @@ -803,7 +806,8 @@ def test_threshold_img_with_cluster_threshold( def test_threshold_img_threshold_n_clusters(stat_img_test_data): """With a cluster threshold of 5 we get 8 clusters with |values| > 2 \ - and cluster sizes > 5.""" + and cluster sizes > 5. + """ thr_img = threshold_img( img=stat_img_test_data, threshold=2, @@ -1179,7 +1183,8 @@ def test_new_img_like_mgh_image(affine_eye, shape_3d_default): @pytest.mark.parametrize("image", [MGHImage, AnalyzeImage]) def test_new_img_like_boolean_data(affine_eye, image, shape_3d_default, rng): """Checks defaulting boolean input data to np.uint8 dtype is valid \ - forencoding with nibabel image classes MGHImage and AnalyzeImage.""" + forencoding with nibabel image classes MGHImage and AnalyzeImage. + """ data = rng.standard_normal(shape_3d_default).astype("uint8") in_img = image(dataobj=data, affine=affine_eye) diff --git a/nilearn/image/tests/test_resampling.py b/nilearn/image/tests/test_resampling.py index 738f9dc495..e85a53860c 100644 --- a/nilearn/image/tests/test_resampling.py +++ b/nilearn/image/tests/test_resampling.py @@ -724,7 +724,8 @@ def test_resampling_result_axis_permutation( @pytest.mark.parametrize("core_shape", [(3, 5, 4), (3, 5, 4, 2)]) def test_resampling_nan(affine_eye, core_shape, force_resample): """Test that when the data has NaNs they do not propagate to the \ - whole image.""" + whole image. + """ # create deterministic data, padded with one # voxel thickness of zeros core_data = ( diff --git a/nilearn/interfaces/bids/__init__.py b/nilearn/interfaces/bids/__init__.py index 5cafc202c6..956b4efcf2 100644 --- a/nilearn/interfaces/bids/__init__.py +++ b/nilearn/interfaces/bids/__init__.py @@ -1,5 +1,6 @@ """The :mod:`nilearn.interfaces.bids` module includes tools to work with \ -:term:`BIDS` format data.""" +:term:`BIDS` format data. +""" from .glm import save_glm_to_bids from .query import get_bids_files, parse_bids_filename diff --git a/nilearn/interfaces/fmriprep/__init__.py b/nilearn/interfaces/fmriprep/__init__.py index d24d8ea967..ebe8767b35 100644 --- a/nilearn/interfaces/fmriprep/__init__.py +++ b/nilearn/interfaces/fmriprep/__init__.py @@ -1,5 +1,6 @@ """The :mod:`nilearn.interfaces.fmriprep` module includes tools to preprocess \ -neuroimaging data and access :term:`fMRIPrep` generated confounds.""" +neuroimaging data and access :term:`fMRIPrep` generated confounds. +""" from .load_confounds import load_confounds from .load_confounds_strategy import load_confounds_strategy diff --git a/nilearn/interfaces/fmriprep/tests/test_load_confounds.py b/nilearn/interfaces/fmriprep/tests/test_load_confounds.py index b9501dc10d..75f5ae1741 100644 --- a/nilearn/interfaces/fmriprep/tests/test_load_confounds.py +++ b/nilearn/interfaces/fmriprep/tests/test_load_confounds.py @@ -26,7 +26,8 @@ def _simu_img(tmp_path, trend, demean): """Simulate an nifti image based on confound file \ - with some parts confounds and some parts noise.""" + with some parts confounds and some parts noise. + """ file_nii, _ = create_tmp_filepath(tmp_path, copy_confounds=True) # set the size of the image matrix nx = 5 @@ -302,7 +303,8 @@ def test_confounds2df(tmp_path, fmriprep_version): @pytest.mark.parametrize("fmriprep_version", ["1.4.x", "21.x.x"]) def test_load_single_confounds_file(tmp_path, fmriprep_version): """Check that the load_confounds function returns the same confounds \ - as _load_single_confounds_file.""" + as _load_single_confounds_file. + """ nii_file, confounds_file = create_tmp_filepath( tmp_path, copy_confounds=True, fmriprep_version=fmriprep_version ) @@ -340,7 +342,8 @@ def test_load_single_confounds_file(tmp_path, fmriprep_version): ) def test_check_strategy(strategy, message): """Check that flawed strategy options \ - generate meaningful error messages.""" + generate meaningful error messages. + """ with pytest.raises(ValueError) as exc_info: _check_strategy(strategy=strategy) assert message in exc_info.value.args[0] diff --git a/nilearn/interfaces/fmriprep/tests/test_load_confounds_components.py b/nilearn/interfaces/fmriprep/tests/test_load_confounds_components.py index 96b41b3b9e..f49eb0d239 100644 --- a/nilearn/interfaces/fmriprep/tests/test_load_confounds_components.py +++ b/nilearn/interfaces/fmriprep/tests/test_load_confounds_components.py @@ -32,7 +32,8 @@ def test_missing_keywords( tmp_path, strategy_keywords, expected_parameters, fmriprep_version ): """Check the strategy keywords are raising errors correctly in low \ - and high level functions with the exception of `high_pass`.""" + and high level functions with the exception of `high_pass`. + """ img, bad_conf = create_tmp_filepath( tmp_path, copy_confounds=True, diff --git a/nilearn/maskers/multi_nifti_masker.py b/nilearn/maskers/multi_nifti_masker.py index 0988837871..ce7635ef64 100644 --- a/nilearn/maskers/multi_nifti_masker.py +++ b/nilearn/maskers/multi_nifti_masker.py @@ -1,5 +1,6 @@ """Transformer used to apply basic transformations \ -on multi subject MRI data.""" +on multi subject MRI data. +""" # Author: Gael Varoquaux, Alexandre Abraham diff --git a/nilearn/maskers/tests/test_input_data.py b/nilearn/maskers/tests/test_input_data.py index f2d8ed5e24..f57ce50023 100644 --- a/nilearn/maskers/tests/test_input_data.py +++ b/nilearn/maskers/tests/test_input_data.py @@ -3,7 +3,8 @@ def test_import_from_input_data_with_warning(): """Tests that importing maskers from deprecated module ``input_data`` \ - still works.""" + still works. + """ from nilearn import input_data, maskers assert input_data != maskers diff --git a/nilearn/maskers/tests/test_nifti_masker.py b/nilearn/maskers/tests/test_nifti_masker.py index 4c3464a2f7..58630786d4 100644 --- a/nilearn/maskers/tests/test_nifti_masker.py +++ b/nilearn/maskers/tests/test_nifti_masker.py @@ -81,7 +81,8 @@ def test_resample(img_3d_rand_eye, mask_img_1): def test_resample_to_mask_warning(img_3d_rand_eye, affine_eye): """Check that a warning is raised when data is \ - being resampled to mask's resolution.""" + being resampled to mask's resolution. + """ # defining a mask with different fov than img mask = np.zeros((12, 12, 12)) mask[3:-3, 3:-3, 3:-3] = 10 diff --git a/nilearn/mass_univariate/__init__.py b/nilearn/mass_univariate/__init__.py index 1c9ee5009a..225a8bb52b 100644 --- a/nilearn/mass_univariate/__init__.py +++ b/nilearn/mass_univariate/__init__.py @@ -1,5 +1,6 @@ """Define a Massively Univariate Linear Model estimated \ -with OLS and permutation test.""" +with OLS and permutation test. +""" from .permuted_least_squares import permuted_ols diff --git a/nilearn/mass_univariate/permuted_least_squares.py b/nilearn/mass_univariate/permuted_least_squares.py index 9460f80122..b92deb84f5 100644 --- a/nilearn/mass_univariate/permuted_least_squares.py +++ b/nilearn/mass_univariate/permuted_least_squares.py @@ -1,5 +1,6 @@ """Massively Univariate Linear Model estimated \ -with OLS and permutation test.""" +with OLS and permutation test. +""" # Author: Benoit Da Mota, , sept. 2011 # Virgile Fritsch, , jan. 2014 diff --git a/nilearn/mass_univariate/tests/test_permuted_least_squares.py b/nilearn/mass_univariate/tests/test_permuted_least_squares.py index e6e5861bf4..3bd003314b 100644 --- a/nilearn/mass_univariate/tests/test_permuted_least_squares.py +++ b/nilearn/mass_univariate/tests/test_permuted_least_squares.py @@ -127,7 +127,8 @@ def cluster_level_design(rng): def run_permutations(tested_var, target_var, model_intercept): """Compute the Mean Squared Error between cumulative Density Function \ - as a proof of consistency of the permutation algorithm.""" + as a proof of consistency of the permutation algorithm. + """ all_mse = [] all_kstest_pvals = [] @@ -614,7 +615,8 @@ def test_permuted_ols_intercept_statsmodels_withcovar( def test_one_sided_versus_two_test(rng): """Check that a positive effect is always better \ - recovered with one-sided.""" + recovered with one-sided. + """ n_descriptors = 100 n_regressors = 1 target_var = rng.standard_normal((N_SAMPLES, n_descriptors)) @@ -659,7 +661,8 @@ def test_one_sided_versus_two_test(rng): def test_two_sided_recover_positive_and_negative_effects(): """Check that two-sided can actually recover \ - positive and negative effects.""" + positive and negative effects. + """ target_var1 = np.arange(0, 10).reshape((-1, 1)) # positive effect target_var = np.hstack((target_var1, -target_var1)) tested_var = np.arange(0, 20, 2) diff --git a/nilearn/plotting/displays/_axes.py b/nilearn/plotting/displays/_axes.py index 5d0d25997a..8ac34e10f5 100644 --- a/nilearn/plotting/displays/_axes.py +++ b/nilearn/plotting/displays/_axes.py @@ -252,7 +252,8 @@ def draw_scale_bar( def draw_position(self, size, bg_color, **kwargs): """``draw_position`` is not implemented in base class and \ - should be implemented in derived classes.""" + should be implemented in derived classes. + """ raise NotImplementedError( "'draw_position' should be implemented in derived classes" ) @@ -465,7 +466,8 @@ def transform_to_2d(self, data, affine): def draw_position(self, size, bg_color, **kwargs): """Not implemented as it does not make sense to draw crosses for \ the position of the cuts \ - since we are taking the max along one axis.""" + since we are taking the max along one axis. + """ pass def _add_markers(self, marker_coords, marker_color, marker_size, **kwargs): diff --git a/nilearn/plotting/displays/_slicers.py b/nilearn/plotting/displays/_slicers.py index 4ca26da33d..1fa70dcd00 100644 --- a/nilearn/plotting/displays/_slicers.py +++ b/nilearn/plotting/displays/_slicers.py @@ -90,7 +90,8 @@ def black_bg(self): @staticmethod def find_cut_coords(img=None, threshold=None, cut_coords=None): """Act as placeholder and is not implemented in the base class \ - and has to be implemented in derived classes.""" + and has to be implemented in derived classes. + """ # Implement this as a staticmethod or a classmethod when # subclassing raise NotImplementedError @@ -2167,7 +2168,8 @@ def get_slicer(display_mode): def _get_create_display_fun(display_mode, class_dict): """Help for functions \ :func:`~nilearn.plotting.displays.get_slicer` and \ - :func:`~nilearn.plotting.displays.get_projector`.""" + :func:`~nilearn.plotting.displays.get_projector`. + """ try: return class_dict[display_mode].init_with_figure except KeyError: diff --git a/nilearn/plotting/edge_detect.py b/nilearn/plotting/edge_detect.py index 6782efe9f8..1f9200b69f 100644 --- a/nilearn/plotting/edge_detect.py +++ b/nilearn/plotting/edge_detect.py @@ -19,7 +19,8 @@ def _orientation_kernel(t): """Structure elements for calculating the value of neighbors in several \ - directions.""" + directions. + """ sin = np.sin pi = np.pi t = pi * t diff --git a/nilearn/plotting/glass_brain.py b/nilearn/plotting/glass_brain.py index 76ac18c251..d67aa73656 100644 --- a/nilearn/plotting/glass_brain.py +++ b/nilearn/plotting/glass_brain.py @@ -81,7 +81,8 @@ def _get_mpl_patches( def _get_json_and_transform(direction): """Return the json filename and an affine transform, which has \ - been tweaked by hand to fit the MNI template.""" + been tweaked by hand to fit the MNI template. + """ direction_to_view_name = { "x": "side", "y": "back", diff --git a/nilearn/plotting/js_plotting_utils.py b/nilearn/plotting/js_plotting_utils.py index e88d6ce2d3..83bf4c9227 100644 --- a/nilearn/plotting/js_plotting_utils.py +++ b/nilearn/plotting/js_plotting_utils.py @@ -1,5 +1,6 @@ """Helps for views, i.e. interactive plots from html_surface and \ -html_connectome.""" +html_connectome. +""" import base64 import os diff --git a/nilearn/plotting/tests/test_displays.py b/nilearn/plotting/tests/test_displays.py index beba263d15..e9b54bb590 100644 --- a/nilearn/plotting/tests/test_displays.py +++ b/nilearn/plotting/tests/test_displays.py @@ -128,7 +128,8 @@ def test_glass_brain_axes(): def test_get_index_from_direction_exception(): """Tests that a ValueError is raised when an invalid direction \ - is given to function ``_get_index_from_direction``.""" + is given to function ``_get_index_from_direction``. + """ from nilearn.plotting.displays._axes import _get_index_from_direction with pytest.raises(ValueError, match="foo is not a valid direction."): @@ -227,7 +228,8 @@ def test_mosaic_slicer_tuple_cut_coords(cut_coords, img): @pytest.mark.parametrize("cut_coords", [None, 5, (1, 1, 1)]) def test_mosaic_slicer_img_none_false(cut_coords, img): """Tests for MosaicSlicer when img is ``None`` or ``False`` \ - while initializing the figure.""" + while initializing the figure. + """ slicer = MosaicSlicer.init_with_figure(img=None, cut_coords=cut_coords) slicer.add_overlay(img, cmap=plt.cm.gray, colorbar=True) slicer.close() diff --git a/nilearn/plotting/tests/test_img_plotting/test_get_colorbar_and_data_ranges.py b/nilearn/plotting/tests/test_img_plotting/test_get_colorbar_and_data_ranges.py index 2c1e9c8d36..1812d52e57 100644 --- a/nilearn/plotting/tests/test_img_plotting/test_get_colorbar_and_data_ranges.py +++ b/nilearn/plotting/tests/test_img_plotting/test_get_colorbar_and_data_ranges.py @@ -1,5 +1,6 @@ """Tests for private function \ - nilearn.plotting.img_plotting.get_colorbar_and_data_ranges.""" + nilearn.plotting.img_plotting.get_colorbar_and_data_ranges. +""" import numpy as np import pytest diff --git a/nilearn/plotting/tests/test_img_plotting/test_img_plotting.py b/nilearn/plotting/tests/test_img_plotting/test_img_plotting.py index 5ac57c378f..c2a7badd4c 100644 --- a/nilearn/plotting/tests/test_img_plotting/test_img_plotting.py +++ b/nilearn/plotting/tests/test_img_plotting/test_img_plotting.py @@ -149,7 +149,8 @@ def test_plot_threshold_for_uint8(affine_eye, plot_func): @pytest.fixture def expected_error_message(display_mode, cut_coords): """Return the expected error message depending on display_mode \ - and cut_coords. Used in test_invalid_cut_coords_with_display_mode.""" + and cut_coords. Used in test_invalid_cut_coords_with_display_mode. + """ if display_mode == "ortho" or ( display_mode == "tiled" and cut_coords == 2 ): diff --git a/nilearn/plotting/tests/test_img_plotting/test_plot_anat.py b/nilearn/plotting/tests/test_img_plotting/test_plot_anat.py index 6cd6569328..de870d437a 100644 --- a/nilearn/plotting/tests/test_img_plotting/test_plot_anat.py +++ b/nilearn/plotting/tests/test_img_plotting/test_plot_anat.py @@ -45,6 +45,7 @@ def test_plot_anat_3d_img(img_3d_mni, tmp_path): def test_plot_img_invalid(): """Check that we get a meaningful error message \ - when we give a wrong display_mode argument.""" + when we give a wrong display_mode argument. + """ with pytest.raises(ValueError): plot_anat(display_mode="zzz") diff --git a/nilearn/plotting/tests/test_img_plotting/test_plot_connectome.py b/nilearn/plotting/tests/test_img_plotting/test_plot_connectome.py index 8a45eccbe3..c3df3c2f48 100644 --- a/nilearn/plotting/tests/test_img_plotting/test_plot_connectome.py +++ b/nilearn/plotting/tests/test_img_plotting/test_plot_connectome.py @@ -91,7 +91,8 @@ def test_plot_connectome_display_mode( display_mode, node_coords, adjacency, base_params ): """Smoke test for plot_connectome with different values \ - for display_mode.""" + for display_mode. + """ plot_connectome( adjacency, node_coords, display_mode=display_mode, **base_params ) @@ -102,7 +103,8 @@ def test_plot_connectome_masked_array_sparse_matrix( node_coords, adjacency, base_params ): """Smoke tests for plot_connectome with masked arrays \ - and sparse matrices as inputs.""" + and sparse matrices as inputs. + """ masked_adjacency_matrix = np.ma.masked_array( adjacency, np.abs(adjacency) < 0.5 ) @@ -125,7 +127,8 @@ def test_plot_connectome_tuple_node_coords( adjacency, node_coords, base_params ): """Smoke test for plot_connectome where node_coords is not provided \ - as an array but as a list of tuples.""" + as an array but as a list of tuples. + """ plot_connectome( adjacency, [tuple(each) for each in node_coords], @@ -138,7 +141,8 @@ def test_plot_connectome_tuple_node_coords( @pytest.mark.parametrize("colorbar", [True, False]) def test_plot_connectome_colorbar(colorbar, adjacency, node_coords): """Smoke test for plot_connectome with default parameters \ - and with and without the colorbar.""" + and with and without the colorbar. + """ plot_connectome(adjacency, node_coords, colorbar=colorbar) plt.close() @@ -167,7 +171,8 @@ def test_plot_connectome_to_file( def test_plot_connectome_node_and_edge_kwargs(adjacency, node_coords): """Smoke test for plot_connectome with node_kwargs, edge_kwargs, \ - and edge_cmap arguments.""" + and edge_cmap arguments. + """ plot_connectome( adjacency, node_coords, @@ -184,7 +189,8 @@ def test_plot_connectome_node_and_edge_kwargs(adjacency, node_coords): def test_plot_connectome_with_too_high_edge_threshold(adjacency, node_coords): """Smoke-test where there is no edge to draw, \ - e.g. when edge_threshold is too high.""" + e.g. when edge_threshold is too high. + """ plot_connectome(adjacency, node_coords, edge_threshold=1e12) plt.close() @@ -281,7 +287,8 @@ def plot_connectome_edge_thresholding(node_coords, non_symmetric_matrix): ) def test_plot_connectome_exceptions_non_symmetric_adjacency(matrix): """Tests that warning messages are given when the adjacency matrix \ - ends up being non symmetric.""" + ends up being non symmetric. + """ node_coords = np.arange(2 * 3).reshape((2, 3)) with pytest.warns(UserWarning, match="A directed graph will be plotted."): plot_connectome(matrix, node_coords, display_mode="x") @@ -300,7 +307,8 @@ def test_plot_connectome_exceptions_wrong_number_node_colors( node_color, adjacency, node_coords ): """Tests that a wrong number of node colors raises \ - a ValueError in plot_connectome.""" + a ValueError in plot_connectome. + """ with pytest.raises( ValueError, match="Mismatch between the number of nodes" ): @@ -313,7 +321,8 @@ def test_plot_connectome_exception_wrong_edge_threshold( adjacency, node_coords ): """Tests that a TypeError is raised in plot_connectome \ - when edge threshold is neither a number nor a string.""" + when edge threshold is neither a number nor a string. + """ with pytest.raises( TypeError, match="should be either a number or a string" ): @@ -327,7 +336,8 @@ def test_plot_connectome_exception_wrong_edge_threshold_format( threshold, adjacency, node_coords ): """Tests that a ValueError is raised when edge_threshold is \ - an incorrectly formatted string.""" + an incorrectly formatted string. + """ with pytest.raises( ValueError, match=("should be a number followed by the percent sign"), @@ -339,7 +349,8 @@ def test_plot_connectome_exception_wrong_edge_threshold_format( def test_plot_connectome_wrong_shapes(): """Tests that ValueErrors are raised when wrong shapes for node_coords \ - or adjacency_matrix are given.""" + or adjacency_matrix are given. + """ kwargs = {"display_mode": "x"} node_coords = np.arange(2 * 3).reshape((2, 3)) adjacency_matrix = np.array([[1.0, 2.0], [2.0, 1.0]]) @@ -372,7 +383,8 @@ def test_plot_connectome_exceptions_providing_node_info_with_kwargs( node_kwargs, adjacency, node_coords, expected_error_node_kwargs ): """Tests that an error is raised when specifying node parameters \ - via node_kwargs in plot_connectome.""" + via node_kwargs in plot_connectome. + """ with pytest.raises(ValueError, match=expected_error_node_kwargs): plot_connectome( adjacency, node_coords, node_kwargs=node_kwargs, display_mode="x" diff --git a/nilearn/plotting/tests/test_img_plotting/test_plot_img.py b/nilearn/plotting/tests/test_img_plotting/test_plot_img.py index 84973e4017..ade6872a09 100644 --- a/nilearn/plotting/tests/test_img_plotting/test_plot_img.py +++ b/nilearn/plotting/tests/test_img_plotting/test_plot_img.py @@ -51,7 +51,8 @@ def test_plot_with_axes_or_figure(img_3d_mni): def test_plot_empty_slice(affine_mni): """Test that things don't crash when we give a map \ - with nothing above threshold. This is only a smoke test.""" + with nothing above threshold. This is only a smoke test. + """ img = Nifti1Image(np.zeros((20, 20, 20)), affine_mni) plot_img(img, display_mode="y", threshold=1) plt.close() diff --git a/nilearn/plotting/tests/test_img_plotting/test_plot_markers.py b/nilearn/plotting/tests/test_img_plotting/test_plot_markers.py index 302ec1cd35..4a7d468a16 100644 --- a/nilearn/plotting/tests/test_img_plotting/test_plot_markers.py +++ b/nilearn/plotting/tests/test_img_plotting/test_plot_markers.py @@ -99,7 +99,8 @@ def test_plot_markers_threshold(threshold, coords): def test_plot_markers_tuple_node_coords(coords): """Smoke test for plot_markers with node coordinates passed \ - as a list of tuples.""" + as a list of tuples. + """ plot_markers( [1, 2, 3, 4], [tuple(coord) for coord in coords], display_mode="x" ) @@ -119,7 +120,8 @@ def test_plot_markers_saving_to_file(coords, tmp_path): def test_plot_markers_node_kwargs(coords): """Smoke test for plot_markers testing that node_kwargs is working \ - and does not interfere with alpha.""" + and does not interfere with alpha. + """ node_kwargs = dict(marker="s") plot_markers( [1, 2, 3, 4], @@ -141,7 +143,8 @@ def test_plot_markers_node_kwargs(coords): ) def test_plot_markers_dimension_mismatch(matrix, coords): """Tests that an error is raised in plot_markers \ - when the length of node_values mismatches with node_coords.""" + when the length of node_values mismatches with node_coords. + """ with pytest.raises(ValueError, match="Dimension mismatch"): plot_markers(matrix, coords, display_mode="x") @@ -149,7 +152,8 @@ def test_plot_markers_dimension_mismatch(matrix, coords): @pytest.mark.parametrize("vmin,vmax", [(5, None), (None, 0)]) def test_plot_markers_bound_error(vmin, vmax, coords): """Tests that a ValueError is raised when vmin and vmax \ - have inconsistent values.""" + have inconsistent values. + """ with pytest.raises(ValueError): plot_markers( [1, 2, 2, 4], @@ -168,7 +172,8 @@ def test_plot_markers_node_values_errors(coords): def test_plot_markers_threshold_errors(coords): """Tests that a ValueError is raised when node_threshold is \ - higher than the max node_value.""" + higher than the max node_value. + """ with pytest.raises(ValueError, match="Provided 'node_threshold' value"): plot_markers([1, 2, 2, 4], coords, node_threshold=5, display_mode="x") diff --git a/nilearn/plotting/tests/test_surf_plotting.py b/nilearn/plotting/tests/test_surf_plotting.py index c5c7a6db24..54202455f3 100644 --- a/nilearn/plotting/tests/test_surf_plotting.py +++ b/nilearn/plotting/tests/test_surf_plotting.py @@ -258,7 +258,8 @@ def test_surface_figure(): @pytest.mark.skipif(is_plotly_installed(), reason="Plotly is installed.") def test_plotly_surface_figure_import_error(): """Test that an ImportError is raised when instantiating \ - a PlotlySurfaceFigure without having Plotly installed.""" + a PlotlySurfaceFigure without having Plotly installed. + """ with pytest.raises(ImportError, match="Plotly is required"): PlotlySurfaceFigure() @@ -269,7 +270,8 @@ def test_plotly_surface_figure_import_error(): ) def test_plotly_surface_figure_savefig_error(): """Test that an ImportError is raised when saving \ - a PlotlySurfaceFigure without having kaleido installed.""" + a PlotlySurfaceFigure without having kaleido installed. + """ with pytest.raises(ImportError, match="`kaleido` is required"): PlotlySurfaceFigure().savefig() diff --git a/nilearn/regions/__init__.py b/nilearn/regions/__init__.py index 7636aaaf7d..eff8fd3aad 100644 --- a/nilearn/regions/__init__.py +++ b/nilearn/regions/__init__.py @@ -1,5 +1,6 @@ """The :mod:`nilearn.regions` class module includes region extraction \ -procedure on a 4D statistical/atlas maps and its function.""" +procedure on a 4D statistical/atlas maps and its function. +""" from .hierarchical_kmeans_clustering import HierarchicalKMeans from .parcellations import Parcellations diff --git a/nilearn/regions/hierarchical_kmeans_clustering.py b/nilearn/regions/hierarchical_kmeans_clustering.py index 5b1fac3492..b2625a1fa8 100644 --- a/nilearn/regions/hierarchical_kmeans_clustering.py +++ b/nilearn/regions/hierarchical_kmeans_clustering.py @@ -24,7 +24,8 @@ def _remove_empty_labels(labels): def _adjust_small_clusters(array, n_clusters): """Take a ndarray of floats summing to n_clusters \ and try to round it while enforcing rounded array still sum \ - to n_clusters and every element is at least 1.""" + to n_clusters and every element is at least 1. + """ array_round = np.rint(array).astype(int) array_round = np.maximum(array_round, 1) diff --git a/nilearn/regions/tests/test_parcellations.py b/nilearn/regions/tests/test_parcellations.py index 92043c8416..56acfa028a 100644 --- a/nilearn/regions/tests/test_parcellations.py +++ b/nilearn/regions/tests/test_parcellations.py @@ -127,7 +127,8 @@ def test_parcellations_transform_single_nifti_image( method, n_parcel, test_image_2 ): """Test with NiftiLabelsMasker extraction of timeseries data \ - after building a parcellations image.""" + after building a parcellations image. + """ parcellator = Parcellations(method=method, n_parcels=n_parcel, verbose=0) parcellator.fit(test_image_2) # transform to signals diff --git a/nilearn/regions/tests/test_region_extractor.py b/nilearn/regions/tests/test_region_extractor.py index 1783da5233..379d88a7ca 100644 --- a/nilearn/regions/tests/test_region_extractor.py +++ b/nilearn/regions/tests/test_region_extractor.py @@ -357,7 +357,8 @@ def test_connected_label_regions_connect_diag_false(labels_img): def test_connected_label_regions_return_empty_for_large_min_size(labels_img): """If min_size is large and if all the regions are removed \ - then empty image will be returned.""" + then empty image will be returned. + """ extract_reg_min_size_large = connected_label_regions( labels_img, min_size=500 ) @@ -459,7 +460,8 @@ def test_connected_label_regions_check_labels_string_without_list( labels_img, affine_eye, shape_3d_default ): """If labels (or names to regions) given is a string without a list \ - we expect it to be split to regions extracted and returned as list.""" + we expect it to be split to regions extracted and returned as list. + """ labels_in_str = "region_a" labels_img_in_str = generate_labeled_regions( shape=shape_3d_default, affine=affine_eye, n_regions=1 diff --git a/nilearn/regions/tests/test_signal_extraction.py b/nilearn/regions/tests/test_signal_extraction.py index 858714f060..2b5d7ca2d5 100644 --- a/nilearn/regions/tests/test_signal_extraction.py +++ b/nilearn/regions/tests/test_signal_extraction.py @@ -338,7 +338,8 @@ def test_signals_extraction_with_labels_without_mask( signals, labels_data, labels_img, shape_3d_default, tmp_path ): """Test conversion between signals and images \ - using regions defined by labels.""" + using regions defined by labels. + """ data_img = signals_to_img_labels(signals=signals, labels_img=labels_img) assert data_img.shape == (shape_3d_default + (N_TIMEPOINTS,)) @@ -372,7 +373,8 @@ def test_signals_extraction_with_labels_without_mask_return_masked_atlas( signals, labels_img ): """Test masked_atlas is correct in conversion between signals and images \ - using regions defined by labels.""" + using regions defined by labels. + """ data_img = signals_to_img_labels(signals=signals, labels_img=labels_img) # test return_masked_atlas @@ -401,7 +403,8 @@ def test_signals_extraction_with_labels_with_mask( signals, labels_img, labels_data, mask_img, shape_3d_default, tmp_path ): """Test conversion between signals and images \ - using regions defined by labels with a mask.""" + using regions defined by labels with a mask. + """ data_img = signals_to_img_labels( signals=signals, labels_img=labels_img, mask_img=mask_img ) @@ -445,7 +448,8 @@ def test_signals_extraction_with_labels_with_mask_return_masked_atlas( signals, labels_img, mask_img ): """Test masked_atlas is correct in conversion between signals and images \ - using regions defined by labels and a mask.""" + using regions defined by labels and a mask. + """ data_img = signals_to_img_labels( signals=signals, labels_img=labels_img, mask_img=mask_img ) diff --git a/nilearn/reporting/html_report.py b/nilearn/reporting/html_report.py index 99bde6fb8a..a067dfc21e 100644 --- a/nilearn/reporting/html_report.py +++ b/nilearn/reporting/html_report.py @@ -193,7 +193,8 @@ def _update_template( def _define_overlay(estimator): """Determine whether an overlay was provided and \ - update the report text as appropriate.""" + update the report text as appropriate. + """ displays = estimator._reporting() if len(displays) == 1: # set overlay to None diff --git a/nilearn/reporting/tests/test_glm_reporter.py b/nilearn/reporting/tests/test_glm_reporter.py index aa6b68d55a..a7bade8d94 100644 --- a/nilearn/reporting/tests/test_glm_reporter.py +++ b/nilearn/reporting/tests/test_glm_reporter.py @@ -292,7 +292,8 @@ def test_plot_contrasts(): ) def test_masking_first_level_model(tmp_path): """Check that using NiftiMasker when instantiating FirstLevelModel \ - doesn't raise Error when calling generate_report().""" + doesn't raise Error when calling generate_report(). + """ shapes, rk = ((7, 7, 7, 5),), 3 mask, fmri_data, design_matrices = write_fake_fmri_data_and_design( shapes, rk, file_path=tmp_path diff --git a/nilearn/reporting/tests/test_html_report.py b/nilearn/reporting/tests/test_html_report.py index 045c190f20..46db5524c3 100644 --- a/nilearn/reporting/tests/test_html_report.py +++ b/nilearn/reporting/tests/test_html_report.py @@ -172,7 +172,8 @@ def test_reports_after_fit_3d_data_with_mask( ) def test_warning_in_report_after_empty_fit(masker_class, input_parameters): """Tests that a warning is both given and written in the report \ - if no images were provided to fit.""" + if no images were provided to fit. + """ masker = masker_class(**input_parameters) assert masker._report_content["warning_message"] is None masker.fit() @@ -188,7 +189,8 @@ def test_nifti_maps_masker_report_displayed_maps_errors( niftimapsmasker_inputs, displayed_maps ): """Tests that a TypeError is raised when the argument `displayed_maps` \ - of `generate_report()` is not valid.""" + of `generate_report()` is not valid. + """ masker = NiftiMapsMasker(**niftimapsmasker_inputs) masker.fit() with pytest.raises(TypeError, match=("Parameter ``displayed_maps``")): @@ -200,7 +202,8 @@ def test_nifti_maps_masker_report_maps_number_errors( niftimapsmasker_inputs, displayed_maps ): """Tests that a ValueError is raised when the argument `displayed_maps` \ - contains invalid map numbers.""" + contains invalid map numbers. + """ masker = NiftiMapsMasker(**niftimapsmasker_inputs) masker.fit() with pytest.raises( @@ -214,7 +217,8 @@ def test_nifti_maps_masker_report_list_and_arrays_maps_number( niftimapsmasker_inputs, displayed_maps, n_regions ): """Tests report generation for NiftiMapsMasker with displayed_maps \ - passed as a list of a Numpy arrays.""" + passed as a list of a Numpy arrays. + """ masker = NiftiMapsMasker(**niftimapsmasker_inputs) masker.fit() html = masker.generate_report(displayed_maps) @@ -234,7 +238,8 @@ def test_nifti_maps_masker_report_integer_and_all_displayed_maps( niftimapsmasker_inputs, displayed_maps, n_regions ): """Tests NiftiMapsMasker reporting with no image provided to fit \ - and displayed_maps provided as an integer or as 'all'.""" + and displayed_maps provided as an integer or as 'all'. + """ masker = NiftiMapsMasker(**niftimapsmasker_inputs) masker.fit() expected_n_maps = ( @@ -279,7 +284,8 @@ def test_nifti_spheres_masker_report_displayed_spheres_errors( displayed_spheres, ): """Tests that a TypeError is raised when the argument `displayed_spheres` \ - of `generate_report()` is not valid.""" + of `generate_report()` is not valid. + """ masker = NiftiSpheresMasker(seeds=[(1, 1, 1)]) masker.fit() with pytest.raises(TypeError, match=("Parameter ``displayed_spheres``")): @@ -288,7 +294,8 @@ def test_nifti_spheres_masker_report_displayed_spheres_errors( def test_nifti_spheres_masker_report_displayed_spheres_more_than_seeds(): """Tests that a warning is raised when number of `displayed_spheres` \ - is greater than number of seeds.""" + is greater than number of seeds. + """ displayed_spheres = 10 seeds = [(1, 1, 1)] masker = NiftiSpheresMasker(seeds=seeds) @@ -311,7 +318,8 @@ def test_nifti_spheres_masker_report_displayed_spheres_list(): def test_nifti_spheres_masker_report_displayed_spheres_list_more_than_seeds(): """Tests that a ValueError is raised when list of `displayed_spheres` \ - maximum is greater than number of seeds.""" + maximum is greater than number of seeds. + """ displayed_spheres = [1, 2, 3] seeds = [(1, 1, 1)] masker = NiftiSpheresMasker(seeds=seeds) diff --git a/nilearn/reporting/tests/test_reporting.py b/nilearn/reporting/tests/test_reporting.py index ce741abb56..896cac2812 100644 --- a/nilearn/reporting/tests/test_reporting.py +++ b/nilearn/reporting/tests/test_reporting.py @@ -81,7 +81,8 @@ def test_local_max_donut(shape, affine_eye): def test_cluster_nearest_neighbor(shape): """Check that _cluster_nearest_neighbor preserves within-cluster voxels, \ projects voxels to the correct cluster, \ - and handles singleton clusters.""" + and handles singleton clusters. + """ labeled = np.zeros(shape) # cluster 1 is half the volume, cluster 2 is a single voxel labeled[:, 5:, :] = 1 @@ -191,7 +192,8 @@ def test_get_clusters_table_more(shape, affine_eye, tmp_path): def test_get_clusters_table_relabel_label_maps(shape, affine_eye): """Check that the cluster's labels in label_maps match \ - their corresponding cluster IDs in the clusters table.""" + their corresponding cluster IDs in the clusters table. + """ data = np.zeros(shape) data[2:4, 5:7, 6:8] = 6.0 data[5:7, 7:9, 7:9] = 5.5 diff --git a/nilearn/signal.py b/nilearn/signal.py index 5275e4f2e2..90c48d0412 100644 --- a/nilearn/signal.py +++ b/nilearn/signal.py @@ -1045,7 +1045,8 @@ def _check_sample_mask_index(i, n_runs, runs, current_mask): def _sanitize_runs(n_time, runs): """Check runs are supplied in the correct format \ - and detect the number of unique runs.""" + and detect the number of unique runs. + """ if runs is not None and len(runs) != n_time: raise ValueError( f"The length of the run vector ({len(runs)}) " diff --git a/nilearn/surface/tests/test_surface.py b/nilearn/surface/tests/test_surface.py index 7475d72b51..e6c00b6d8d 100644 --- a/nilearn/surface/tests/test_surface.py +++ b/nilearn/surface/tests/test_surface.py @@ -37,7 +37,8 @@ class MeshLikeObject: """Class with attributes coordinates \ - and faces to be used for testing purposes.""" + and faces to be used for testing purposes. + """ def __init__(self, coordinates, faces): self._coordinates = coordinates diff --git a/pyproject.toml b/pyproject.toml index e02d86ef2e..8bd37ef569 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -146,7 +146,6 @@ ignore = [ "D105", "D205", "D208", - "D209", "D301", "E741", "ERA001",