Skip to content

Commit ccec546

Browse files
authored
Merge pull request nipy#3676 from DimitriPapadopoulos/SIM
STY: Apply ruff/flake8-simplify rules (SIM)
2 parents 0e0d600 + d040d84 commit ccec546

File tree

27 files changed

+111
-153
lines changed

27 files changed

+111
-153
lines changed

nipype/algorithms/misc.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -684,7 +684,7 @@ def _run_interface(self, runtime):
684684

685685
output_array = merge_csvs(self.inputs.in_files)
686686
_, name, ext = split_filename(self.inputs.out_file)
687-
if not ext == ".csv":
687+
if ext != ".csv":
688688
ext = ".csv"
689689

690690
out_file = op.abspath(name + ext)
@@ -725,7 +725,7 @@ def _run_interface(self, runtime):
725725
def _list_outputs(self):
726726
outputs = self.output_spec().get()
727727
_, name, ext = split_filename(self.inputs.out_file)
728-
if not ext == ".csv":
728+
if ext != ".csv":
729729
ext = ".csv"
730730
out_file = op.abspath(name + ext)
731731
outputs["csv_file"] = out_file
@@ -771,7 +771,7 @@ class AddCSVColumn(BaseInterface):
771771
def _run_interface(self, runtime):
772772
in_file = open(self.inputs.in_file)
773773
_, name, ext = split_filename(self.inputs.out_file)
774-
if not ext == ".csv":
774+
if ext != ".csv":
775775
ext = ".csv"
776776
out_file = op.abspath(name + ext)
777777

@@ -791,7 +791,7 @@ def _run_interface(self, runtime):
791791
def _list_outputs(self):
792792
outputs = self.output_spec().get()
793793
_, name, ext = split_filename(self.inputs.out_file)
794-
if not ext == ".csv":
794+
if ext != ".csv":
795795
ext = ".csv"
796796
out_file = op.abspath(name + ext)
797797
outputs["csv_file"] = out_file

nipype/interfaces/afni/base.py

+1-3
Original file line numberDiff line numberDiff line change
@@ -326,6 +326,4 @@ def _cmd_prefix(self):
326326

327327
def no_afni():
328328
"""Check whether AFNI is not available."""
329-
if Info.version() is None:
330-
return True
331-
return False
329+
return Info.version() is None

nipype/interfaces/afni/model.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -636,7 +636,7 @@ def _parse_inputs(self, skip=None):
636636
def _list_outputs(self):
637637
outputs = self.output_spec().get()
638638

639-
for key in outputs.keys():
639+
for key in outputs:
640640
if isdefined(self.inputs.get()[key]):
641641
outputs[key] = os.path.abspath(self.inputs.get()[key])
642642

@@ -722,7 +722,7 @@ class Synthesize(AFNICommand):
722722
def _list_outputs(self):
723723
outputs = self.output_spec().get()
724724

725-
for key in outputs.keys():
725+
for key in outputs:
726726
if isdefined(self.inputs.get()[key]):
727727
outputs[key] = os.path.abspath(self.inputs.get()[key])
728728

nipype/interfaces/afni/utils.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -234,7 +234,7 @@ def aggregate_outputs(self, runtime=None, needed_outputs=None):
234234
m = re.search(pattern, line)
235235
if m:
236236
d = m.groupdict()
237-
outputs.trait_set(**{k: int(d[k]) for k in d.keys()})
237+
outputs.trait_set(**{k: int(v) for k, v in d.items()})
238238
return outputs
239239

240240

nipype/interfaces/base/specs.py

+3-7
Original file line numberDiff line numberDiff line change
@@ -177,19 +177,15 @@ def get_traitsfree(self, **kwargs):
177177

178178
def _clean_container(self, objekt, undefinedval=None, skipundefined=False):
179179
"""Convert a traited object into a pure python representation."""
180-
if isinstance(objekt, TraitDictObject) or isinstance(objekt, dict):
180+
if isinstance(objekt, (TraitDictObject, dict)):
181181
out = {}
182182
for key, val in list(objekt.items()):
183183
if isdefined(val):
184184
out[key] = self._clean_container(val, undefinedval)
185185
else:
186186
if not skipundefined:
187187
out[key] = undefinedval
188-
elif (
189-
isinstance(objekt, TraitListObject)
190-
or isinstance(objekt, list)
191-
or isinstance(objekt, tuple)
192-
):
188+
elif isinstance(objekt, (TraitListObject, list, tuple)):
193189
out = []
194190
for val in objekt:
195191
if isdefined(val):
@@ -387,7 +383,7 @@ def __deepcopy__(self, memo):
387383
dup_dict = deepcopy(self.trait_get(), memo)
388384
# access all keys
389385
for key in self.copyable_trait_names():
390-
if key in self.__dict__.keys():
386+
if key in self.__dict__:
391387
_ = getattr(self, key)
392388
# clone once
393389
dup = self.clone_traits(memo=memo)

nipype/interfaces/cmtk/cmtk.py

+6-6
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,7 @@ def get_rois_crossed(pointsmm, roiData, voxelSize):
7777
x = int(pointsmm[j, 0] / float(voxelSize[0]))
7878
y = int(pointsmm[j, 1] / float(voxelSize[1]))
7979
z = int(pointsmm[j, 2] / float(voxelSize[2]))
80-
if not roiData[x, y, z] == 0:
80+
if roiData[x, y, z] != 0:
8181
rois_crossed.append(roiData[x, y, z])
8282
rois_crossed = list(
8383
dict.fromkeys(rois_crossed).keys()
@@ -91,7 +91,7 @@ def get_connectivity_matrix(n_rois, list_of_roi_crossed_lists):
9191
for idx_i, roi_i in enumerate(rois_crossed):
9292
for idx_j, roi_j in enumerate(rois_crossed):
9393
if idx_i > idx_j:
94-
if not roi_i == roi_j:
94+
if roi_i != roi_j:
9595
connectivity_matrix[roi_i - 1, roi_j - 1] += 1
9696
connectivity_matrix = connectivity_matrix + connectivity_matrix.T
9797
return connectivity_matrix
@@ -371,7 +371,7 @@ def cmat(
371371
di["fiber_length_mean"] = 0
372372
di["fiber_length_median"] = 0
373373
di["fiber_length_std"] = 0
374-
if not u == v: # Fix for self loop problem
374+
if u != v: # Fix for self loop problem
375375
G.add_edge(u, v, **di)
376376
if "fiblist" in d:
377377
numfib.add_edge(u, v, weight=di["number_of_fibers"])
@@ -400,7 +400,7 @@ def cmat(
400400
pickle.dump(I, f, pickle.HIGHEST_PROTOCOL)
401401

402402
path, name, ext = split_filename(matrix_mat_name)
403-
if not ext == ".mat":
403+
if ext != ".mat":
404404
ext = ".mat"
405405
matrix_mat_name = matrix_mat_name + ext
406406

@@ -608,7 +608,7 @@ def _run_interface(self, runtime):
608608

609609
matrix_mat_file = op.abspath(self.inputs.out_matrix_mat_file)
610610
path, name, ext = split_filename(matrix_mat_file)
611-
if not ext == ".mat":
611+
if ext != ".mat":
612612
ext = ".mat"
613613
matrix_mat_file = matrix_mat_file + ext
614614

@@ -673,7 +673,7 @@ def _list_outputs(self):
673673

674674
matrix_mat_file = op.abspath(self.inputs.out_matrix_mat_file)
675675
path, name, ext = split_filename(matrix_mat_file)
676-
if not ext == ".mat":
676+
if ext != ".mat":
677677
ext = ".mat"
678678
matrix_mat_file = matrix_mat_file + ext
679679

nipype/interfaces/cmtk/convert.py

+7-7
Original file line numberDiff line numberDiff line change
@@ -194,17 +194,17 @@ def _run_interface(self, runtime):
194194
for data in self.inputs.data_files:
195195
_, data_name, _ = split_filename(data)
196196
cda = cf.CData(name=data_name, src=data, fileformat="NumPy")
197-
if not string.find(data_name, "lengths") == -1:
197+
if 'lengths' in data_name:
198198
cda.dtype = "FinalFiberLengthArray"
199-
if not string.find(data_name, "endpoints") == -1:
199+
if 'endpoints' in data_name:
200200
cda.dtype = "FiberEndpoints"
201-
if not string.find(data_name, "labels") == -1:
201+
if 'labels' in data_name:
202202
cda.dtype = "FinalFiberLabels"
203203
a.add_connectome_data(cda)
204204

205205
a.print_summary()
206206
_, name, ext = split_filename(self.inputs.out_file)
207-
if not ext == ".cff":
207+
if ext != '.cff':
208208
ext = ".cff"
209209
cf.save_to_cff(a, op.abspath(name + ext))
210210

@@ -213,7 +213,7 @@ def _run_interface(self, runtime):
213213
def _list_outputs(self):
214214
outputs = self._outputs().get()
215215
_, name, ext = split_filename(self.inputs.out_file)
216-
if not ext == ".cff":
216+
if ext != '.cff':
217217
ext = ".cff"
218218
outputs["connectome_file"] = op.abspath(name + ext)
219219
return outputs
@@ -281,7 +281,7 @@ def _run_interface(self, runtime):
281281
metadata.set_email("My Email")
282282

283283
_, name, ext = split_filename(self.inputs.out_file)
284-
if not ext == ".cff":
284+
if ext != '.cff':
285285
ext = ".cff"
286286
cf.save_to_cff(newcon, op.abspath(name + ext))
287287

@@ -290,7 +290,7 @@ def _run_interface(self, runtime):
290290
def _list_outputs(self):
291291
outputs = self._outputs().get()
292292
_, name, ext = split_filename(self.inputs.out_file)
293-
if not ext == ".cff":
293+
if ext != '.cff':
294294
ext = ".cff"
295295
outputs["connectome_file"] = op.abspath(name + ext)
296296
return outputs

nipype/interfaces/cmtk/nx.py

+6-6
Original file line numberDiff line numberDiff line change
@@ -166,8 +166,8 @@ def average_networks(in_files, ntwk_res_file, group_id):
166166
for edge in edges:
167167
data = ntwk.edge[edge[0]][edge[1]]
168168
if ntwk.edge[edge[0]][edge[1]]["count"] >= count_to_keep_edge:
169-
for key in list(data.keys()):
170-
if not key == "count":
169+
for key in data:
170+
if key != "count":
171171
data[key] = data[key] / len(in_files)
172172
ntwk.edge[edge[0]][edge[1]] = data
173173
avg_ntwk.add_edge(edge[0], edge[1], **data)
@@ -183,8 +183,8 @@ def average_networks(in_files, ntwk_res_file, group_id):
183183
avg_edges = avg_ntwk.edges()
184184
for edge in avg_edges:
185185
data = avg_ntwk.edge[edge[0]][edge[1]]
186-
for key in list(data.keys()):
187-
if not key == "count":
186+
for key in data:
187+
if key != "count":
188188
edge_dict[key] = np.zeros(
189189
(avg_ntwk.number_of_nodes(), avg_ntwk.number_of_nodes())
190190
)
@@ -342,7 +342,7 @@ def add_node_data(node_array, ntwk):
342342
node_ntwk = nx.Graph()
343343
newdata = {}
344344
for idx, data in ntwk.nodes(data=True):
345-
if not int(idx) == 0:
345+
if int(idx) != 0:
346346
newdata["value"] = node_array[int(idx) - 1]
347347
data.update(newdata)
348348
node_ntwk.add_node(int(idx), **data)
@@ -354,7 +354,7 @@ def add_edge_data(edge_array, ntwk, above=0, below=0):
354354
data = {}
355355
for x, row in enumerate(edge_array):
356356
for y in range(np.max(np.shape(edge_array[x]))):
357-
if not edge_array[x, y] == 0:
357+
if edge_array[x, y] != 0:
358358
data["value"] = edge_array[x, y]
359359
if data["value"] <= below or data["value"] >= above:
360360
if edge_ntwk.has_edge(x + 1, y + 1):

nipype/interfaces/dcmstack.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -152,7 +152,7 @@ def _run_interface(self, runtime):
152152
meta_filter = dcmstack.make_key_regex_filter(exclude_regexes, include_regexes)
153153
stack = dcmstack.DicomStack(meta_filter=meta_filter)
154154
for src_path in src_paths:
155-
if not imghdr.what(src_path) == "gif":
155+
if imghdr.what(src_path) != "gif":
156156
src_dcm = pydicom.dcmread(src_path, force=self.inputs.force_read)
157157
stack.add_dcm(src_dcm)
158158
nii = stack.to_nifti(embed_meta=True)

nipype/interfaces/dipy/tests/test_base.py

+8-8
Original file line numberDiff line numberDiff line change
@@ -109,10 +109,10 @@ def test_create_interface_specs():
109109
assert new_interface.__name__ == "MyInterface"
110110
current_params = new_interface().get()
111111
assert len(current_params) == 4
112-
assert "params1" in current_params.keys()
113-
assert "params2_files" in current_params.keys()
114-
assert "params3" in current_params.keys()
115-
assert "out_params" in current_params.keys()
112+
assert "params1" in current_params
113+
assert "params2_files" in current_params
114+
assert "params3" in current_params
115+
assert "out_params" in current_params
116116

117117

118118
@pytest.mark.skipif(
@@ -184,10 +184,10 @@ def run(self, in_files, param1=1, out_dir="", out_ref="out1.txt"):
184184
params_in = new_specs().inputs.get()
185185
params_out = new_specs()._outputs().get()
186186
assert len(params_in) == 4
187-
assert "in_files" in params_in.keys()
188-
assert "param1" in params_in.keys()
189-
assert "out_dir" in params_out.keys()
190-
assert "out_ref" in params_out.keys()
187+
assert "in_files" in params_in
188+
assert "param1" in params_in
189+
assert "out_dir" in params_out
190+
assert "out_ref" in params_out
191191

192192
with pytest.raises(ValueError):
193193
new_specs().run()

nipype/interfaces/freesurfer/base.py

+1-4
Original file line numberDiff line numberDiff line change
@@ -269,7 +269,4 @@ def no_freesurfer():
269269
used with skipif to skip tests that will
270270
fail if FreeSurfer is not installed"""
271271

272-
if Info.version() is None:
273-
return True
274-
else:
275-
return False
272+
return Info.version() is None

nipype/interfaces/fsl/base.py

+1-4
Original file line numberDiff line numberDiff line change
@@ -262,10 +262,7 @@ def no_fsl():
262262
used with skipif to skip tests that will
263263
fail if FSL is not installed"""
264264

265-
if Info.version() is None:
266-
return True
267-
else:
268-
return False
265+
return Info.version() is None
269266

270267

271268
def no_fsl_course_data():

nipype/interfaces/fsl/model.py

+15-20
Original file line numberDiff line numberDiff line change
@@ -142,13 +142,12 @@ class Level1Design(BaseInterface):
142142
output_spec = Level1DesignOutputSpec
143143

144144
def _create_ev_file(self, evfname, evinfo):
145-
f = open(evfname, "w")
146-
for i in evinfo:
147-
if len(i) == 3:
148-
f.write(f"{i[0]:f} {i[1]:f} {i[2]:f}\n")
149-
else:
150-
f.write("%f\n" % i[0])
151-
f.close()
145+
with open(evfname, "w") as f:
146+
for i in evinfo:
147+
if len(i) == 3:
148+
f.write(f"{i[0]:f} {i[1]:f} {i[2]:f}\n")
149+
else:
150+
f.write("%f\n" % i[0])
152151

153152
def _create_ev_files(
154153
self,
@@ -319,7 +318,7 @@ def _create_ev_files(
319318

320319
for fconidx in ftest_idx:
321320
fval = 0
322-
if con[0] in con_map.keys() and fconidx in con_map[con[0]]:
321+
if con[0] in con_map and fconidx in con_map[con[0]]:
323322
fval = 1
324323
ev_txt += contrast_ftest_element.substitute(
325324
cnum=ftest_idx.index(fconidx) + 1,
@@ -403,9 +402,8 @@ def _run_interface(self, runtime):
403402
fsf_txt += cond_txt
404403
fsf_txt += fsf_postscript.substitute(overwrite=1)
405404

406-
f = open(os.path.join(cwd, "run%d.fsf" % i), "w")
407-
f.write(fsf_txt)
408-
f.close()
405+
with open(os.path.join(cwd, "run%d.fsf" % i), "w") as f:
406+
f.write(fsf_txt)
409407

410408
return runtime
411409

@@ -946,9 +944,8 @@ def _run_interface(self, runtime):
946944
for i, rundir in enumerate(ensure_list(self.inputs.feat_dirs)):
947945
fsf_txt += fsf_dirs.substitute(runno=i + 1, rundir=os.path.abspath(rundir))
948946
fsf_txt += fsf_footer.substitute()
949-
f = open(os.path.join(os.getcwd(), "register.fsf"), "w")
950-
f.write(fsf_txt)
951-
f.close()
947+
with open(os.path.join(os.getcwd(), "register.fsf"), "w") as f:
948+
f.write(fsf_txt)
952949

953950
return runtime
954951

@@ -1414,9 +1411,8 @@ def _run_interface(self, runtime):
14141411

14151412
# write design files
14161413
for i, name in enumerate(["design.mat", "design.con", "design.grp"]):
1417-
f = open(os.path.join(cwd, name), "w")
1418-
f.write(txt[name])
1419-
f.close()
1414+
with open(os.path.join(cwd, name), "w") as f:
1415+
f.write(txt[name])
14201416

14211417
return runtime
14221418

@@ -1583,9 +1579,8 @@ def _run_interface(self, runtime):
15831579
if ("fts" in key) and (nfcons == 0):
15841580
continue
15851581
filename = key.replace("_", ".")
1586-
f = open(os.path.join(cwd, filename), "w")
1587-
f.write(val)
1588-
f.close()
1582+
with open(os.path.join(cwd, filename), "w") as f:
1583+
f.write(val)
15891584

15901585
return runtime
15911586

nipype/interfaces/fsl/tests/test_base.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,7 @@ def test_gen_fname(args, desired_name):
7979
cmd = fsl.FSLCommand(command="junk", output_type="NIFTI_GZ")
8080
pth = os.getcwd()
8181
fname = cmd._gen_fname("foo.nii.gz", **args)
82-
if "dir" in desired_name.keys():
82+
if "dir" in desired_name:
8383
desired = os.path.join(desired_name["dir"], desired_name["file"])
8484
else:
8585
desired = os.path.join(pth, desired_name["file"])

0 commit comments

Comments
 (0)