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

Replace black and flake8 by ruff #95

Merged
merged 11 commits into from
Apr 26, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions .circleci/config.yml
Original file line number Diff line number Diff line change
Expand Up @@ -99,8 +99,7 @@ jobs:
name: Check style
command: |
isort --check .
black --check nigsp
flake8 ./nigsp
ruff check nigsp

merge_coverage:
working_directory: /tmp/src/nigsp
Expand Down
78 changes: 43 additions & 35 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -1,38 +1,46 @@
# See https://pre-commit.com for more information
# See https://pre-commit.com/hooks.html for more hooks
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.6.0
hooks:
- id: trailing-whitespace
- id: end-of-file-fixer
- id: check-yaml
- id: check-added-large-files
- id: check-case-conflict
- id: check-merge-conflict
- repo: https://github.com/psf/black
rev: 24.4.0
hooks:
- id: black
- repo: https://github.com/pycqa/isort
rev: 5.13.2
hooks:
- id: isort
- repo: https://github.com/pycqa/flake8
rev: 7.0.0
hooks:
- id: flake8
- repo: https://github.com/pycqa/pydocstyle
rev: 6.3.0
hooks:
- id: pydocstyle
- repo: https://github.com/pre-commit/pygrep-hooks
rev: v1.10.0
hooks:
- id: rst-backticks
- id: rst-directive-colons
- id: rst-inline-touching-normal
- repo: https://github.com/codespell-project/codespell
rev: v2.2.6
hooks:
- id: codespell
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.6.0
hooks:
- id: end-of-file-fixer
- id: check-yaml
- id: check-added-large-files
- id: check-case-conflict
- id: check-merge-conflict

- repo: https://github.com/pycqa/isort
rev: 5.13.2
hooks:
- id: isort

- repo: https://github.com/pycqa/pydocstyle
rev: 6.3.0
hooks:
- id: pydocstyle


- repo: https://github.com/pre-commit/pygrep-hooks
rev: v1.10.0
hooks:
- id: rst-backticks
- id: rst-directive-colons
- id: rst-inline-touching-normal

- repo: https://github.com/codespell-project/codespell
rev: v2.2.6
hooks:
- id: codespell


- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.3.7
hooks:
- id: ruff
name: ruff linter
args: [--fix]
files: nigsp
- id: ruff-format
name: ruff formatter
files: nigsp
62 changes: 22 additions & 40 deletions codecov.yml
Original file line number Diff line number Diff line change
@@ -1,43 +1,25 @@
comment: false
github_checks: # too noisy, even though "a" interactively disables them
annotations: false

codecov:
branch: master
strict_yaml_branch: master
require_ci_to_pass: true
bot: "codecov-io"
max_report_age: 48
disable_default_path_fixes: false
notify:
require_ci_to_pass: false

coverage:
precision: 2
round: down
range: "60...90"

parsers:
gcov:
branch_detection:
conditional: yes
loop: yes
method: no
macro: no

ignore:
- "docs"
- "tests"
- "_version.py"
- "__init__.py"
- "**/__init__.py"
- "due.py"
- ".*rc"
- "versioneer.py"
- "setup.py"
- "nigsp/tests"
- "nigsp/_version.py"
- "nigsp/__init__.py"
- "nigsp/**/__init__.py"
- "nigsp/due.py"
- "nigsp/.*rc"
- "nigsp/versioneer.py"
- "nigsp/setup.py"
comment:
layout: "reach,diff,flags,tree"
behavior: default
require_changes: false
status:
patch:
default:
informational: true
target: 95%
if_no_uploads: error
if_not_found: success
if_ci_failed: error
project:
default: false
library:
informational: true
target: 90%
if_no_uploads: error
if_not_found: success
if_ci_failed: error
21 changes: 10 additions & 11 deletions nigsp/_version.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, env=
stderr=(subprocess.PIPE if hide_stderr else None),
)
break
except EnvironmentError:
except EnvironmentError: # noqa
e = sys.exc_info()[1]
if e.errno == errno.ENOENT:
continue
Expand All @@ -94,7 +94,7 @@ def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, env=
return None, None
else:
if verbose:
print("unable to find command, tried %s" % (commands,))
print(f"unable to find command, tried {commands}")
return None, None
stdout = p.communicate()[0].strip()
if sys.version_info[0] >= 3:
Expand All @@ -116,7 +116,7 @@ def versions_from_parentdir(parentdir_prefix, root, verbose):
"""
rootdirs = []

for i in range(3):
for _ in range(3):
dirname = os.path.basename(root)
if dirname.startswith(parentdir_prefix):
return {
Expand All @@ -132,8 +132,8 @@ def versions_from_parentdir(parentdir_prefix, root, verbose):

if verbose:
print(
"Tried directories %s but none started with prefix %s"
% (str(rootdirs), parentdir_prefix)
f"Tried directories {str(rootdirs)} but none started with prefix "
f"{parentdir_prefix}"
)
raise NotThisMethod("rootdir doesn't start with parentdir_prefix")

Expand All @@ -147,7 +147,7 @@ def git_get_keywords(versionfile_abs):
# _version.py.
keywords = {}
try:
f = open(versionfile_abs, "r")
f = open(versionfile_abs, "r") # noqa: UP015
for line in f.readlines():
if line.strip().startswith("git_refnames ="):
mo = re.search(r'=\s*"(.*)"', line)
Expand All @@ -162,7 +162,7 @@ def git_get_keywords(versionfile_abs):
if mo:
keywords["date"] = mo.group(1)
f.close()
except EnvironmentError:
except EnvironmentError: # noqa
pass
return keywords

Expand Down Expand Up @@ -302,9 +302,8 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):
if verbose:
fmt = "tag '%s' doesn't start with prefix '%s'"
print(fmt % (full_tag, tag_prefix))
pieces["error"] = "tag '%s' doesn't start with prefix '%s'" % (
full_tag,
tag_prefix,
pieces["error"] = (
f"tag '{full_tag}' doesn't start with prefix '{tag_prefix}'"
)
return pieces
pieces["closest-tag"] = full_tag[len(tag_prefix) :]
Expand Down Expand Up @@ -524,7 +523,7 @@ def get_versions():
# versionfile_source is the relative path from the top of the source
# tree (where the .git directory might live) to this file. Invert
# this to find the root from __file__.
for i in cfg.versionfile_source.split("/"):
for _ in cfg.versionfile_source.split("/"):
root = os.path.dirname(root)
except NameError:
return {
Expand Down
3 changes: 1 addition & 2 deletions nigsp/blocks.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ def export_metric(scgraph, outext, outprefix):
"""
if outext in io.EXT_NIFTI:
try:
import nibabel as _
import nibabel as _ # noqa: F401
except ImportError:
LGR.warning(
"The necessary library for nifti export (nibabel) "
Expand Down Expand Up @@ -118,7 +118,6 @@ def plot_metric(scgraph, outprefix, atlas=None, thr=None):
"""
# Check that atlas format is supported.
try:
atlas.header
atlas_plot = atlas
except AttributeError:
try:
Expand Down
1 change: 0 additions & 1 deletion nigsp/cli/run.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
"""Parser for crispy-octo-broccoli."""

import argparse
Expand Down
2 changes: 1 addition & 1 deletion nigsp/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ def fetch_file(osf_id, path, filename):
)
)
ssl._create_default_https_context = ssl._create_unverified_context
url = "https://osf.io/{}/download".format(osf_id)
url = f"https://osf.io/{osf_id}/download"
full_path = os.path.join(path, filename)
if not os.path.isfile(full_path):
urlretrieve(url, full_path)
Expand Down
2 changes: 1 addition & 1 deletion nigsp/due.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
__version__ = "0.0.9"


class InactiveDueCreditCollector(object):
class InactiveDueCreditCollector:
"""Just a stub at the Collector which would not do anything"""

def _donothing(self, *args, **kwargs):
Expand Down
4 changes: 2 additions & 2 deletions nigsp/objects.py
Original file line number Diff line number Diff line change
Expand Up @@ -130,15 +130,15 @@ def compute_graph_energy(self, mean=False): # pragma: no cover
)
return self

def split_graph(self, index=None, keys=["low", "high"]):
def split_graph(self, index=None, keys=["low", "high"]): # noqa: B006
"""Implement timeseries.median_cutoff_frequency_idx as class method."""
if index is None:
index = self.index

if index == "median": # pragma: no cover
index = operations.median_cutoff_frequency_idx(self.energy)

elif type(index) is not int:
elif not isinstance(index, int):
raise ValueError(
f"Unknown option {index} for frequency split index. "
"Declared index must be either an integer or 'median'"
Expand Down
12 changes: 6 additions & 6 deletions nigsp/operations/laplacian.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,8 @@ def compute_laplacian(mtx, negval="absolute", selfloops=False):
numpy.ndarray
The laplacian of mtx
numpy.ndarray
The degree matrix of mtx as a (mtx.ndim-1)D array, updated with selfloops in case.
The degree matrix of mtx as a (mtx.ndim-1)D array, updated with selfloops in
case.

Raises
------
Expand Down Expand Up @@ -104,8 +105,7 @@ def compute_laplacian(mtx, negval="absolute", selfloops=False):


def normalisation(lapl, degree, norm="symmetric", fix_zeros=True):
"""
Normalise a Laplacian (L) matrix using either symmetric or random walk normalisation.
"""Normalise a Laplacian (L) matrix using either symmetric or random walk normalisation.

Parameters
----------
Expand All @@ -125,8 +125,8 @@ def normalisation(lapl, degree, norm="symmetric", fix_zeros=True):
It normalises the outflow, i.e. it is column-optimised (each column = 0).
Normally used in e.g. physical distribution networks.
fix_zeros : bool, optional
Whether to change 0 elements in the degree matrix to 1 to avoid multiplying by 0.
Default is to do so.
Whether to change 0 elements in the degree matrix to 1 to avoid multiplying by
0. Default is to do so.

Returns
-------
Expand All @@ -145,7 +145,7 @@ def normalisation(lapl, degree, norm="symmetric", fix_zeros=True):
Notes
-----
https://en.wikipedia.org/wiki/Laplacian_matrix
"""
""" # noqa: E501
deg = deepcopy(degree)
if lapl.ndim - deg.ndim > 1:
raise NotImplementedError(
Expand Down
5 changes: 3 additions & 2 deletions nigsp/operations/metrics.py
Original file line number Diff line number Diff line change
Expand Up @@ -206,7 +206,8 @@ def _fc(timeseries, mean=False):
timeseries : numpy.ndarray
A 2- or 3-D matrix containing timeseries along axis 1.
mean : bool, optional
If timeseries is 3D and this is True, return the average FC along the last axis.
If timeseries is 3D and this is True, return the average FC along the last
axis.

Returns
-------
Expand Down Expand Up @@ -236,7 +237,7 @@ def _fc(timeseries, mean=False):
fcorr = fcorr.mean(axis=2).squeeze()
return fcorr

if type(timeseries) is dict:
if isinstance(timeseries, dict):
fc = dict()
for k in timeseries.keys():
fc[k] = _fc(timeseries[k], mean)
Expand Down
14 changes: 8 additions & 6 deletions nigsp/operations/nifti.py
Original file line number Diff line number Diff line change
Expand Up @@ -175,9 +175,11 @@ def apply_atlas(data, atlas, mask=None):
data : numpy.ndarray
A 3- or 4- D matrix (normally nifti data) of timeseries.
atlas : numpy.ndarray
A 2- or 3- D matrix representing the atlas, each parcel represented by a different int.
A 2- or 3- D matrix representing the atlas, each parcel represented by a
different int.
mask : None or numpy.ndarray, optional
A 2- or 3- D matrix representing a mask, all voxels == 0 are excluded from the computation.
A 2- or 3- D matrix representing a mask, all voxels == 0 are excluded from the
computation.

Returns
-------
Expand Down Expand Up @@ -230,8 +232,8 @@ def apply_atlas(data, atlas, mask=None):
parcels = np.empty([len(labels), data.shape[-1]], dtype="float32")

# Compute averages
for n, l in enumerate(labels):
parcels[n, :] = data[atlas == l].mean(axis=0)
for n, label in enumerate(labels):
parcels[n, :] = data[atlas == label].mean(axis=0)

return parcels

Expand Down Expand Up @@ -302,8 +304,8 @@ def unfold_atlas(data, atlas, mask=None):
if data.shape[ax] > 1:
out = out[..., np.newaxis].repeat(data.shape[ax], axis=-1)

for n, l in enumerate(labels):
out[atlas == l] = data[n, ...]
for n, label in enumerate(labels):
out[atlas == label] = data[n, ...]

return out

Expand Down
Loading