Skip to content

Commit

Permalink
STY: Fix a number of code style issues reported by Codacy
Browse files Browse the repository at this point in the history
  • Loading branch information
sebastientourbier committed Jan 31, 2022
1 parent 7d080c2 commit 5c86f02
Show file tree
Hide file tree
Showing 8 changed files with 81 additions and 99 deletions.
2 changes: 1 addition & 1 deletion cmtklib/carbonfootprint.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ def create_carbon_footprint_message(bids_dir, emissions_csv_file, nb_of_subjects
----------
bids_dir : string
Path to root directory of the BIDS dataset
emissions_csv_file : string
Path to the `emissions.csv` file generated by `Codecarbon`.
Expand Down
1 change: 0 additions & 1 deletion cmtklib/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -180,7 +180,6 @@ def save_configparser_as_json(config, config_json_path, ini_mode=False, debug=Fa
print_error(
f" .. EXCEPTION: String {value} COULD NOT BE evaluated"
)
pass

if isinstance(value, dict):
if debug: # pragma: no cover
Expand Down
1 change: 0 additions & 1 deletion cmtklib/connectome.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@
InputMultiPath,
OutputMultiPath,
)
from nipype.interfaces import cmtk
from nipype.utils.filemanip import split_filename

from .util import mean_curvature, length
Expand Down
66 changes: 26 additions & 40 deletions cmtklib/diffusion.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@
OutputMultiPath,
InputMultiPath,
)
from nipype.utils.filemanip import split_filename

from traits.trait_types import List, Str, Int, Enum

Expand All @@ -44,32 +43,32 @@ def compute_length_array(trkfile=None, streams=None, savefname="lengths.npy"):
Returns
-------
leng : numpy.array
fibers_length : numpy.array
Array of fiber lengths
"""
if streams is None and trkfile is not None:
print("Compute length array for fibers in %s" % trkfile)
print(f'Compute length array for fibers in {trkfile}')
streams, hdr = tv.read(trkfile, as_generator=True)
n_fibers = hdr["n_count"]
if n_fibers == 0:
msg = (
"Header field n_count of trackfile %s is set to 0. No track seem to exist in this file."
% trkfile
f'Header field n_count of trackfile {trkfile} is set to 0. '
"No track seem to exist in this file."
)
print(msg)
raise Exception(msg)
else:
n_fibers = len(streams)

leng = np.zeros(n_fibers, dtype=np.float)
fibers_length = np.zeros(n_fibers, dtype=np.float)
for i, fib in enumerate(streams):
leng[i] = length(fib[0])
fibers_length[i] = length(fib[0])

# store length array
np.save(savefname, leng)
print("Store lengths array to: %s" % savefname)
np.save(savefname, fibers_length)
print(f'Store lengths array to: {savefname}')

return leng
return fibers_length


def filter_fibers(intrk, outtrk="", fiber_cutoff_lower=20, fiber_cutoff_upper=500):
Expand All @@ -92,7 +91,7 @@ def filter_fibers(intrk, outtrk="", fiber_cutoff_lower=20, fiber_cutoff_upper=50
print("Cut Fiber Filtering")
print("===================")

print("Input file for fiber cutting is: %s" % intrk)
print(f'Input file for fiber cutting is: {intrk}')

if outtrk == "":
_, filename = os.path.split(intrk)
Expand All @@ -119,10 +118,10 @@ def filter_fibers(intrk, outtrk="", fiber_cutoff_lower=20, fiber_cutoff_upper=50

# print("Compute length array for cutted fibers")
# le = compute_length_array(streams=outstreams)
print("Write out file: %s" % outtrk)
print("Number of fibers out : %d" % hdrnew["n_count"])
print(f'Write out file: {outtrk}')
print(f'Number of fibers out : {hdrnew["n_count"]}')
tv.write(outtrk, outstreams, hdrnew)
print("File wrote : %d" % os.path.exists(outtrk))
print(f'File wrote : {os.path.exists(outtrk)}')

# ----
# extension idea
Expand Down Expand Up @@ -174,7 +173,7 @@ def _run_interface(self, runtime):
axis_dict = {"x": 0, "y": 1, "z": 2}
f = open(self.inputs.table, "r")
header = ""
for h in range(self.inputs.header_lines):
for _ in range(self.inputs.header_lines):
header += f.readline()
if self.inputs.delimiter == " ":
table = np.loadtxt(f)
Expand Down Expand Up @@ -303,7 +302,7 @@ def _run_interface(self, runtime):
process = subprocess.Popen(
fslmaths_cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT
)
proc_stdout = process.communicate()[0].strip()
_ = process.communicate()[0].strip()

fslmaths_cmd = "fslmaths %s -kernel sphere %s -dilD %s" % (
os.path.abspath(self.inputs.pve_wm_file),
Expand All @@ -315,7 +314,7 @@ def _run_interface(self, runtime):
process = subprocess.Popen(
fslmaths_cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT
)
proc_stdout = process.communicate()[0].strip()
_ = process.communicate()[0].strip()

fslmaths_cmd = "fslmaths %s -kernel sphere %s -dilD %s" % (
os.path.abspath(self.inputs.pve_gm_file),
Expand All @@ -327,7 +326,7 @@ def _run_interface(self, runtime):
process = subprocess.Popen(
fslmaths_cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT
)
proc_stdout = process.communicate()[0].strip()
_ = process.communicate()[0].strip()

fslmaths_cmd = "fslmaths %s -kernel gauss %s -fmean %s" % (
os.path.abspath(self.inputs.pve_csf_file),
Expand All @@ -339,7 +338,7 @@ def _run_interface(self, runtime):
process = subprocess.Popen(
fslmaths_cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT
)
proc_stdout = process.communicate()[0].strip()
_ = process.communicate()[0].strip()

fslmaths_cmd = "fslmaths %s -kernel gauss %s -fmean %s" % (
os.path.abspath(self.inputs.pve_wm_file),
Expand All @@ -351,7 +350,7 @@ def _run_interface(self, runtime):
process = subprocess.Popen(
fslmaths_cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT
)
proc_stdout = process.communicate()[0].strip()
_ = process.communicate()[0].strip()

fslmaths_cmd = "fslmaths %s -kernel gauss %s -fmean %s" % (
os.path.abspath(self.inputs.pve_gm_file),
Expand All @@ -363,7 +362,7 @@ def _run_interface(self, runtime):
process = subprocess.Popen(
fslmaths_cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT
)
proc_stdout = process.communicate()[0].strip()
_ = process.communicate()[0].strip()

pve_csf = nib.load(os.path.abspath(self.inputs.pve_csf_file)).get_data()
pve_wm = nib.load(os.path.abspath(self.inputs.pve_wm_file)).get_data()
Expand All @@ -387,14 +386,11 @@ def _run_interface(self, runtime):

def _list_outputs(self):
outputs = self._outputs().get()

pve_files = []
pve_files.append(os.path.abspath(self.inputs.pve_csf_file))
pve_files.append(os.path.abspath(self.inputs.pve_gm_file))
pve_files.append(os.path.abspath(self.inputs.pve_wm_file))

outputs["partial_volume_files"] = pve_files

outputs["partial_volume_files"] = [
os.path.abspath(self.inputs.pve_csf_file),
os.path.abspath(self.inputs.pve_gm_file),
os.path.abspath(self.inputs.pve_wm_file)
]
return outputs


Expand Down Expand Up @@ -505,7 +501,7 @@ def _run_interface(self, runtime):

f = open(self.inputs.bvecs, "r")
header = ""
for h in range(self.inputs.header_lines):
for _ in range(self.inputs.header_lines):
header += f.readline()
if self.inputs.delimiter == " ":
table = np.loadtxt(f)
Expand All @@ -526,14 +522,6 @@ def _run_interface(self, runtime):
else:
np.savetxt(out_f, table, delimiter=self.inputs.delimiter)

# with open(os.path.abspath('flipped_bvecs.bvec'), 'w') as out_f:
# np.savetxt(out_f, table, header=header, delimiter=self.inputs.delimiter)

# out_f = file(os.path.abspath('flipped_bvecs.bvec'), 'w')
# if self.inputs.header_lines > 0:
# out_f.write(header)
# np.savetxt(out_f, table, header=header, delimiter=self.inputs.delimiter)
# out_f.close()
return runtime

def _list_outputs(self):
Expand Down Expand Up @@ -657,7 +645,5 @@ def _run_interface(self, runtime):

def _list_outputs(self):
outputs = self._outputs().get()

outputs["out_gmwmi_file"] = os.path.abspath(self.inputs.out_gmwmi_file)

return outputs
2 changes: 1 addition & 1 deletion cmtklib/interfaces/afni.py
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,7 @@ def _list_outputs(self):
if isdefined(self.inputs.out_file):
if outputs[name]:
print('out_file: {}'.format(outputs[name]))
_, base, ext = split_filename(outputs[name])
_, _, ext = split_filename(outputs[name])
if ext == "":
outputs[name] = outputs[name] + "+orig.BRIK"
else:
Expand Down
49 changes: 24 additions & 25 deletions cmtklib/interfaces/dipy.py
Original file line number Diff line number Diff line change
Expand Up @@ -1153,35 +1153,35 @@ def _run_interface(self, runtime):
hdr = imref.header.copy()

gtab = self._get_gradient_table()
gtab = gradient_table(bvals=gtab.bvals, bvecs=gtab.bvecs,
small_delta=self.inputs.small_delta,
big_delta=self.inputs.big_delta)

map_model_both_aniso = mapmri.MapmriModel(gtab,
radial_order=self.inputs.radial_order,
anisotropic_scaling=True,
laplacian_regularization=self.inputs.laplacian_regularization,
laplacian_weighting=self.inputs.laplacian_weighting,
positivity_constraint=self.inputs.positivity_constraint
)
gtab = gradient_table(
bvals=gtab.bvals, bvecs=gtab.bvecs,
small_delta=self.inputs.small_delta,
big_delta=self.inputs.big_delta
)

map_model_both_aniso = mapmri.MapmriModel(
gtab,
radial_order=self.inputs.radial_order,
anisotropic_scaling=True,
laplacian_regularization=self.inputs.laplacian_regularization,
laplacian_weighting=self.inputs.laplacian_weighting,
positivity_constraint=self.inputs.positivity_constraint
)

IFLOGGER.info('Fitting MAP-MRI model')
mapfit_both_aniso = map_model_both_aniso.fit(data)

'''maps'''
maps = {}
maps["rtop"] = mapfit_both_aniso.rtop() # '''1/Volume of pore'''
maps["rtap"] = mapfit_both_aniso.rtap() # '''1/AREA ...'''
maps["rtpp"] = mapfit_both_aniso.rtpp() # '''1/length ...'''
maps["msd"] = mapfit_both_aniso.msd(
) # '''similar to mean diffusivity'''
maps["qiv"] = mapfit_both_aniso.qiv(
) # '''almost reciprocal of rtop'''
maps["ng"] = mapfit_both_aniso.ng() # '''general non Gaussianity'''
maps[
"ng_perp"] = mapfit_both_aniso.ng_perpendicular() # '''perpendicular to main direction (likely to be non gaussian in white matter)'''
maps["ng_para"] = mapfit_both_aniso.ng_parallel(
) # '''along main direction (likely to be gaussian)'''
maps = {
"rtop": mapfit_both_aniso.rtop(),
"rtap": mapfit_both_aniso.rtap(),
"rtpp": mapfit_both_aniso.rtpp(),
"msd": mapfit_both_aniso.msd(),
"qiv": mapfit_both_aniso.qiv(),
"ng": mapfit_both_aniso.ng(),
"ng_perp": mapfit_both_aniso.ng_perpendicular(),
"ng_para": mapfit_both_aniso.ng_parallel()
}

''' The most related to white matter anisotropy are:
rtpp, for anisotropy
Expand All @@ -1208,7 +1208,6 @@ def _run_interface(self, runtime):
def _list_outputs(self):
outputs = self._outputs().get()
outputs['model'] = self._gen_filename('mapmri', ext='.pklz')

for metric in ["rtop", "rtap", "rtpp", "msd", "qiv", "ng", "ng_perp", "ng_para"]:
outputs["{}_file".format(metric)] = self._gen_filename(metric)
return outputs
2 changes: 1 addition & 1 deletion cmtklib/interfaces/fsl.py
Original file line number Diff line number Diff line change
Expand Up @@ -355,7 +355,7 @@ class Eddy(FSLCommand):
output_spec = EddyOutputSpec

def __init__(self, **inputs):
return super(Eddy, self).__init__(**inputs)
super(Eddy, self).__init__(**inputs)

def _run_interface(self, runtime):
if not isdefined(self.inputs.out_file):
Expand Down
Loading

0 comments on commit 5c86f02

Please sign in to comment.