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

STY: Apply ruff/refurb rules #3648

Merged
merged 9 commits into from
May 6, 2024
2 changes: 1 addition & 1 deletion nipype/algorithms/misc.py
Original file line number Diff line number Diff line change
Expand Up @@ -531,7 +531,7 @@ def remove_identical_paths(in_files):
commonprefix = op.commonprefix(in_files)
lastslash = commonprefix.rfind("/")
commonpath = commonprefix[0 : (lastslash + 1)]
for fileidx, in_file in enumerate(in_files):
for in_file in in_files:
path, name, ext = split_filename(in_file)
in_file = op.join(path, name)
name = in_file.replace(commonpath, "")
Expand Down
6 changes: 1 addition & 5 deletions nipype/interfaces/ants/registration.py
Original file line number Diff line number Diff line change
Expand Up @@ -1127,14 +1127,10 @@ def _format_metric_argument(**kwargs):
return retval

def _format_transform(self, index):
retval = []
retval.append("%s[ " % self.inputs.transforms[index])
parameters = ", ".join(
[str(element) for element in self.inputs.transform_parameters[index]]
)
retval.append("%s" % parameters)
retval.append(" ]")
return "".join(retval)
return f"{self.inputs.transforms[index]}[ {parameters} ]"

def _format_registration(self):
retval = []
Expand Down
2 changes: 1 addition & 1 deletion nipype/interfaces/cmtk/nx.py
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ def average_networks(in_files, ntwk_res_file, group_id):
ntwk = remove_all_edges(ntwk_res_file)
counting_ntwk = ntwk.copy()
# Sums all the relevant variables
for index, subject in enumerate(in_files):
for subject in in_files:
tmp = _read_pickle(subject)
iflogger.info("File %s has %i edges", subject, tmp.number_of_edges())
edges = list(tmp.edges())
Expand Down
2 changes: 1 addition & 1 deletion nipype/interfaces/cmtk/tests/test_nbs.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
def creating_graphs(tmpdir):
graphlist = []
graphnames = ["name" + str(i) for i in range(6)]
for idx, name in enumerate(graphnames):
for idx in range(len(graphnames)):
graph = np.random.rand(10, 10)
G = nx.from_numpy_array(graph)
out_file = tmpdir.strpath + graphnames[idx] + ".pck"
Expand Down
2 changes: 1 addition & 1 deletion nipype/interfaces/dipy/reconstruction.py
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ def _run_interface(self, runtime):
else:
nodiff = np.where(~gtab.b0s_mask)
nodiffidx = nodiff[0].tolist()
n = 20 if len(nodiffidx) >= 20 else len(nodiffidx)
n = min(20, len(nodiffidx))
idxs = np.random.choice(nodiffidx, size=n, replace=False)
noise_data = dsample.take(idxs, axis=-1)[noise_msk == 1, ...]

Expand Down
2 changes: 1 addition & 1 deletion nipype/interfaces/elastix/registration.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ def _list_outputs(self):
config = {}

with open(params) as f:
for line in f.readlines():
for line in f:
line = line.strip()
if not line.startswith("//") and line:
m = regex.search(line)
Expand Down
62 changes: 29 additions & 33 deletions nipype/interfaces/fsl/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -822,34 +822,32 @@ class FILMGLS(FSLCommand):
def _get_pe_files(self, cwd):
files = None
if isdefined(self.inputs.design_file):
fp = open(self.inputs.design_file)
for line in fp.readlines():
if line.startswith("/NumWaves"):
numpes = int(line.split()[-1])
files = []
for i in range(numpes):
files.append(self._gen_fname("pe%d.nii" % (i + 1), cwd=cwd))
break
fp.close()
with open(self.inputs.design_file) as fp:
for line in fp:
if line.startswith("/NumWaves"):
numpes = int(line.split()[-1])
files = [
self._gen_fname(f"pe{i + 1}.nii", cwd=cwd)
for i in range(numpes)
]
break
return files

def _get_numcons(self):
numtcons = 0
numfcons = 0
if isdefined(self.inputs.tcon_file):
fp = open(self.inputs.tcon_file)
for line in fp.readlines():
if line.startswith("/NumContrasts"):
numtcons = int(line.split()[-1])
break
fp.close()
with open(self.inputs.tcon_file) as fp:
for line in fp:
if line.startswith("/NumContrasts"):
numtcons = int(line.split()[-1])
break
if isdefined(self.inputs.fcon_file):
fp = open(self.inputs.fcon_file)
for line in fp.readlines():
if line.startswith("/NumContrasts"):
numfcons = int(line.split()[-1])
break
fp.close()
with open(self.inputs.fcon_file) as fp:
for line in fp:
if line.startswith("/NumContrasts"):
numfcons = int(line.split()[-1])
break
return numtcons, numfcons

def _list_outputs(self):
Expand Down Expand Up @@ -1297,19 +1295,17 @@ def _get_numcons(self):
numtcons = 0
numfcons = 0
if isdefined(self.inputs.tcon_file):
fp = open(self.inputs.tcon_file)
for line in fp.readlines():
if line.startswith("/NumContrasts"):
numtcons = int(line.split()[-1])
break
fp.close()
with open(self.inputs.tcon_file) as fp:
for line in fp:
if line.startswith("/NumContrasts"):
numtcons = int(line.split()[-1])
break
if isdefined(self.inputs.fcon_file):
fp = open(self.inputs.fcon_file)
for line in fp.readlines():
if line.startswith("/NumContrasts"):
numfcons = int(line.split()[-1])
break
fp.close()
with open(self.inputs.fcon_file) as fp:
for line in fp:
if line.startswith("/NumContrasts"):
numfcons = int(line.split()[-1])
break
return numtcons, numfcons

def _list_outputs(self):
Expand Down
8 changes: 4 additions & 4 deletions nipype/interfaces/io.py
Original file line number Diff line number Diff line change
Expand Up @@ -975,7 +975,7 @@ def _list_outputs(self):
if self.inputs.sort_filelist:
filelist = human_order_sorted(filelist)
outputs[key] = simplify_list(filelist)
for argnum, arglist in enumerate(args):
for arglist in args:
maxlen = 1
for arg in arglist:
if isinstance(arg, (str, bytes)) and hasattr(self.inputs, arg):
Expand Down Expand Up @@ -1250,7 +1250,7 @@ def _list_outputs(self):
if self.inputs.sort_filelist:
filelist = human_order_sorted(filelist)
outputs[key] = simplify_list(filelist)
for argnum, arglist in enumerate(args):
for arglist in args:
maxlen = 1
for arg in arglist:
if isinstance(arg, (str, bytes)) and hasattr(self.inputs, arg):
Expand Down Expand Up @@ -1995,7 +1995,7 @@ def _list_outputs(self):
if file_object.exists()
]
)
for argnum, arglist in enumerate(args):
for arglist in args:
maxlen = 1
for arg in arglist:
if isinstance(arg, (str, bytes)) and hasattr(self.inputs, arg):
Expand Down Expand Up @@ -2609,7 +2609,7 @@ def _list_outputs(self):
if not args:
outputs[key] = self._get_files_over_ssh(template)

for argnum, arglist in enumerate(args):
for arglist in args:
maxlen = 1
for arg in arglist:
if isinstance(arg, (str, bytes)) and hasattr(self.inputs, arg):
Expand Down
2 changes: 1 addition & 1 deletion nipype/interfaces/nipy/preprocess.py
Original file line number Diff line number Diff line change
Expand Up @@ -203,7 +203,7 @@ def _run_interface(self, runtime):
# nipy does not encode euler angles. return in original form of
# translation followed by rotation vector see:
# http://en.wikipedia.org/wiki/Rodrigues'_rotation_formula
for i, mo in enumerate(motion):
for mo in motion:
params = [
"%.10f" % item for item in np.hstack((mo.translation, mo.rotation))
]
Expand Down
45 changes: 21 additions & 24 deletions nipype/pipeline/engine/workflows.py
Original file line number Diff line number Diff line change
Expand Up @@ -483,16 +483,11 @@ def write_graph(
def write_hierarchical_dotfile(
self, dotfilename=None, colored=False, simple_form=True
):
dotlist = ["digraph %s{" % self.name]
dotlist.append(
self._get_dot(prefix=" ", colored=colored, simple_form=simple_form)
)
dotlist.append("}")
dotstr = "\n".join(dotlist)
dotlist = self._get_dot(prefix=" ", colored=colored, simple_form=simple_form)
dotstr = f"digraph {self.name}{{\n{dotlist}\n}}"
if dotfilename:
fp = open(dotfilename, "w")
fp.writelines(dotstr)
fp.close()
with open(dotfilename, "w") as fp:
fp.writelines(dotstr)
else:
logger.info(dotstr)

Expand Down Expand Up @@ -532,7 +527,7 @@ def export(
lines.append(wfdef)
if include_config:
lines.append(f"{self.name}.config = {self.config}")
for idx, node in enumerate(nodes):
for node in nodes:
nodename = node.fullname.replace(".", "_")
# write nodes
nodelines = format_node(
Expand Down Expand Up @@ -1068,23 +1063,25 @@ def _get_dot(
nodename = fullname.replace(".", "_")
dotlist.append("subgraph cluster_%s {" % nodename)
if colored:
dotlist.append(
prefix + prefix + 'edge [color="%s"];' % (colorset[level + 1])
)
dotlist.append(prefix + prefix + "style=filled;")
dotlist.append(
prefix + prefix + 'fillcolor="%s";' % (colorset[level + 2])
dotlist.extend(
(
f'{prefix * 2}edge [color="{colorset[level + 1]}"];',
f"{prefix * 2}style=filled;",
f'{prefix * 2}fillcolor="{colorset[level + 2]}";',
)
)
dotlist.append(
node._get_dot(
prefix=prefix + prefix,
hierarchy=hierarchy + [self.name],
colored=colored,
simple_form=simple_form,
level=level + 3,
dotlist.extend(
(
node._get_dot(
prefix=prefix + prefix,
hierarchy=hierarchy + [self.name],
colored=colored,
simple_form=simple_form,
level=level + 3,
),
"}",
)
)
dotlist.append("}")
else:
for subnode in self._graph.successors(node):
if node._hierarchy != subnode._hierarchy:
Expand Down
2 changes: 1 addition & 1 deletion nipype/pipeline/plugins/somaflow.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ def __init__(self, plugin_args=None):
def _submit_graph(self, pyfiles, dependencies, nodes):
jobs = []
soma_deps = []
for idx, fname in enumerate(pyfiles):
for fname in pyfiles:
name = os.path.splitext(os.path.split(fname)[1])[0]
jobs.append(Job(command=[sys.executable, fname], name=name))
for key, values in list(dependencies.items()):
Expand Down
2 changes: 1 addition & 1 deletion nipype/sphinxext/apidoc/docstring.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ class InterfaceDocstring(NipypeDocstring):
_name_rgx = re.compile(
r"^\s*(:(?P<role>\w+):`(?P<name>[a-zA-Z0-9_.-]+)`|"
r" (?P<name2>[a-zA-Z0-9_.-]+))\s*",
re.X,
re.VERBOSE,
)

def __init__(
Expand Down
2 changes: 1 addition & 1 deletion nipype/sphinxext/plot_workflow.py
Original file line number Diff line number Diff line change
Expand Up @@ -484,7 +484,7 @@ def contains_doctest(text):
return False
except SyntaxError:
pass
r = re.compile(r"^\s*>>>", re.M)
r = re.compile(r"^\s*>>>", re.MULTILINE)
m = r.search(text)
return bool(m)

Expand Down
8 changes: 1 addition & 7 deletions nipype/utils/docparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -166,13 +166,7 @@ def insert_doc(doc, new_items):
# Add rest of documents
tmpdoc.extend(doclist[2:])
# Insert newlines
newdoc = []
for line in tmpdoc:
newdoc.append(line)
newdoc.append("\n")
# We add one too many newlines, remove it.
newdoc.pop(-1)
return "".join(newdoc)
return "\n".join(tmpdoc)


def build_doc(doc, opts):
Expand Down