Skip to content

Commit

Permalink
fix error D209 from ruff (nilearn#4583)
Browse files Browse the repository at this point in the history
  • Loading branch information
Remi-Gau authored Oct 4, 2024
1 parent d04303f commit 706fcd6
Show file tree
Hide file tree
Showing 70 changed files with 272 additions and 137 deletions.
3 changes: 2 additions & 1 deletion examples/04_glm_first_level/plot_first_level_details.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
3 changes: 2 additions & 1 deletion nilearn/_utils/niimg_conversions.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
3 changes: 2 additions & 1 deletion nilearn/_utils/segmentation.py
Original file line number Diff line number Diff line change
Expand Up @@ -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())
)
Expand Down
3 changes: 2 additions & 1 deletion nilearn/_utils/tests/test_data_gen.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
6 changes: 4 additions & 2 deletions nilearn/_utils/tests/test_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down Expand Up @@ -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",
Expand Down
3 changes: 2 additions & 1 deletion nilearn/connectome/__init__.py
Original file line number Diff line number Diff line change
@@ -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,
Expand Down
3 changes: 2 additions & 1 deletion nilearn/connectome/group_sparse_cov.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
"""Implementation of algorithm for sparse multi-subjects learning of Gaussian \
graphical models."""
graphical models.
"""

# Authors: Philippe Gervais

Expand Down
6 changes: 4 additions & 2 deletions nilearn/connectome/tests/test_connectivity_matrices.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down Expand Up @@ -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
):
Expand Down
6 changes: 4 additions & 2 deletions nilearn/datasets/func.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
"""Downloading NeuroImaging datasets: \
functional datasets (task + resting-state)."""
functional datasets (task + resting-state).
"""

import fnmatch
import glob
Expand Down Expand Up @@ -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 = []
Expand Down
3 changes: 2 additions & 1 deletion nilearn/datasets/neurovault.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
"""Download statistical maps available \
on Neurovault (https://neurovault.org)."""
on Neurovault (https://neurovault.org).
"""

# Author: Jerome Dockes

Expand Down
3 changes: 2 additions & 1 deletion nilearn/datasets/tests/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."
):
Expand Down
3 changes: 2 additions & 1 deletion nilearn/decoding/decoder.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
3 changes: 2 additions & 1 deletion nilearn/decoding/searchlight.py
Original file line number Diff line number Diff line change
@@ -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 ([email protected])
# Alexandre Gramfort ([email protected])
Expand Down
6 changes: 4 additions & 2 deletions nilearn/decoding/space_net.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down Expand Up @@ -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, :]
Expand Down
9 changes: 6 additions & 3 deletions nilearn/decoding/space_net_solvers.py
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down Expand Up @@ -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)
Expand All @@ -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)])
Expand Down
9 changes: 6 additions & 3 deletions nilearn/decoding/tests/test_decoder.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand Down
9 changes: 6 additions & 3 deletions nilearn/decoding/tests/test_graph_net.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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(
Expand Down
9 changes: 6 additions & 3 deletions nilearn/decoding/tests/test_same_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down
3 changes: 2 additions & 1 deletion nilearn/decomposition/__init__.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down
3 changes: 2 additions & 1 deletion nilearn/decomposition/_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down
3 changes: 2 additions & 1 deletion nilearn/decomposition/canica.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
3 changes: 2 additions & 1 deletion nilearn/decomposition/tests/test_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
)
Expand Down
3 changes: 2 additions & 1 deletion nilearn/decomposition/tests/test_canica.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
12 changes: 8 additions & 4 deletions nilearn/decomposition/tests/test_multi_pca.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand All @@ -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."
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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
Expand Down
3 changes: 2 additions & 1 deletion nilearn/experimental/surface/_surface_image.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
Loading

0 comments on commit 706fcd6

Please sign in to comment.