Skip to content

Commit 8f08e1c

Browse files
committed
Run autopep8 on misc.py
In-place run of the standard tool. Ref #662
1 parent e1a6a18 commit 8f08e1c

File tree

1 file changed

+73
-61
lines changed

1 file changed

+73
-61
lines changed

nipype/algorithms/misc.py

Lines changed: 73 additions & 61 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,7 @@ class PickAtlasOutputSpec(TraitedSpec):
5555

5656

5757
class PickAtlas(BaseInterface):
58+
5859
'''
5960
Returns ROI masks given an atlas and a list of labels. Supports dilation
6061
and left right masking (assuming the atlas is properly aligned).
@@ -88,9 +89,9 @@ def _get_brodmann_area(self):
8889
for lab in labels:
8990
newdata[origdata == lab] = 1
9091
if self.inputs.hemi == 'right':
91-
newdata[floor(float(origdata.shape[0]) / 2):, :, :] = 0
92+
newdata[floor(float(origdata.shape[0]) / 2):, :,:] = 0
9293
elif self.inputs.hemi == 'left':
93-
newdata[:ceil(float(origdata.shape[0]) / 2), :, :] = 0
94+
newdata[:ceil(float(origdata.shape[0]) / 2), :,:] = 0
9495

9596
if self.inputs.dilation_size != 0:
9697
newdata = grey_dilation(
@@ -162,6 +163,7 @@ class ModifyAffineOutputSpec(TraitedSpec):
162163

163164

164165
class ModifyAffine(BaseInterface):
166+
165167
'''
166168
Left multiplies the affine matrix with a specified values. Saves the volume as a nifti file.
167169
'''
@@ -216,6 +218,7 @@ class DistanceOutputSpec(TraitedSpec):
216218

217219

218220
class Distance(BaseInterface):
221+
219222
'''
220223
Calculates distance between two volumes.
221224
'''
@@ -231,7 +234,7 @@ def _find_border(self, data):
231234

232235
def _get_coordinates(self, data, affine):
233236
if len(data.shape) == 4:
234-
data = data[:, :, :, 0]
237+
data = data[:, :,:, 0]
235238
indices = np.vstack(np.nonzero(data))
236239
indices = np.vstack((indices, np.ones(indices.shape[1])))
237240
coordinates = np.dot(affine, indices)
@@ -251,7 +254,7 @@ def _eucl_min(self, nii1, nii2):
251254
dist_matrix = cdist(set1_coordinates.T, set2_coordinates.T)
252255
(point1, point2) = np.unravel_index(
253256
np.argmin(dist_matrix), dist_matrix.shape)
254-
return (euclidean(set1_coordinates.T[point1, :], set2_coordinates.T[point2, :]), set1_coordinates.T[point1, :], set2_coordinates.T[point2, :])
257+
return (euclidean(set1_coordinates.T[point1, :], set2_coordinates.T[point2,:]), set1_coordinates.T[point1,:], set2_coordinates.T[point2,:])
255258

256259
def _eucl_cog(self, nii1, nii2):
257260
origdata1 = nii1.get_data().astype(np.bool)
@@ -376,6 +379,7 @@ class OverlapOutputSpec(TraitedSpec):
376379

377380

378381
class Overlap(BaseInterface):
382+
379383
"""
380384
Calculates various overlap measures between two maps.
381385
@@ -438,25 +442,30 @@ def _list_outputs(self):
438442

439443

440444
class FuzzyOverlapInputSpec(BaseInterfaceInputSpec):
441-
in_ref = InputMultiPath( File(exists=True), mandatory=True,
445+
in_ref = InputMultiPath(File(exists=True), mandatory=True,
442446
desc="Reference image. Requires the same dimensions as in_tst.")
443-
in_tst = InputMultiPath( File(exists=True), mandatory=True,
447+
in_tst = InputMultiPath(File(exists=True), mandatory=True,
444448
desc="Test image. Requires the same dimensions as in_ref.")
445449
weighting = traits.Enum("none", "volume", "squared_vol", desc='""none": no class-overlap weighting is performed\
446450
"volume": computed class-overlaps are weighted by class volume\
447-
"squared_vol": computed class-overlaps are weighted by the squared volume of the class',usedefault=True)
448-
out_file = File("diff.nii", desc="alternative name for resulting difference-map", usedefault=True)
451+
"squared_vol": computed class-overlaps are weighted by the squared volume of the class', usedefault=True)
452+
out_file = File(
453+
"diff.nii", desc="alternative name for resulting difference-map", usedefault=True)
449454

450455

451456
class FuzzyOverlapOutputSpec(TraitedSpec):
452-
jaccard = traits.Float( desc="Fuzzy Jaccard Index (fJI), all the classes" )
453-
dice = traits.Float( desc="Fuzzy Dice Index (fDI), all the classes" )
454-
diff_file = File(exists=True, desc="resulting difference-map of all classes, using the chosen weighting" )
455-
class_fji = traits.List( traits.Float(), desc="Array containing the fJIs of each computed class" )
456-
class_fdi = traits.List( traits.Float(), desc="Array containing the fDIs of each computed class" )
457+
jaccard = traits.Float(desc="Fuzzy Jaccard Index (fJI), all the classes")
458+
dice = traits.Float(desc="Fuzzy Dice Index (fDI), all the classes")
459+
diff_file = File(
460+
exists=True, desc="resulting difference-map of all classes, using the chosen weighting")
461+
class_fji = traits.List(
462+
traits.Float(), desc="Array containing the fJIs of each computed class")
463+
class_fdi = traits.List(
464+
traits.Float(), desc="Array containing the fDIs of each computed class")
457465

458466

459467
class FuzzyOverlap(BaseInterface):
468+
460469
"""
461470
Calculates various overlap measures between two maps, using the fuzzy definition
462471
proposed in: Crum et al., Generalized Overlap Measures for Evaluation and Validation
@@ -475,76 +484,72 @@ class FuzzyOverlap(BaseInterface):
475484
>>> res = overlap.run() # doctest: +SKIP
476485
"""
477486

478-
input_spec = FuzzyOverlapInputSpec
487+
input_spec = FuzzyOverlapInputSpec
479488
output_spec = FuzzyOverlapOutputSpec
480489

481490
def _run_interface(self, runtime):
482491
ncomp = len(self.inputs.in_ref)
483-
assert( ncomp == len(self.inputs.in_tst) )
484-
weights = np.ones( shape=ncomp )
485-
486-
img_ref = np.array( [ nb.load( fname ).get_data() for fname in self.inputs.in_ref ] )
487-
img_tst = np.array( [ nb.load( fname ).get_data() for fname in self.inputs.in_tst ] )
492+
assert(ncomp == len(self.inputs.in_tst))
493+
weights = np.ones(shape=ncomp)
488494

495+
img_ref = np.array([nb.load(fname).get_data()
496+
for fname in self.inputs.in_ref])
497+
img_tst = np.array([nb.load(fname).get_data()
498+
for fname in self.inputs.in_tst])
489499

490500
msk = np.sum(img_ref, axis=0)
491-
msk[msk>0] = 1.0
501+
msk[msk > 0] = 1.0
492502
tst_msk = np.sum(img_tst, axis=0)
493-
tst_msk[tst_msk>0] = 1.0
494-
495-
#check that volumes are normalized
496-
#img_ref[:][msk>0] = img_ref[:][msk>0] / (np.sum( img_ref, axis=0 ))[msk>0]
497-
#img_tst[tst_msk>0] = img_tst[tst_msk>0] / np.sum( img_tst, axis=0 )[tst_msk>0]
503+
tst_msk[tst_msk > 0] = 1.0
498504

499505
self._jaccards = []
500506
volumes = []
501507

502-
diff_im = np.zeros( img_ref.shape )
508+
diff_im = np.zeros(img_ref.shape)
503509

504-
for ref_comp, tst_comp, diff_comp in zip( img_ref, img_tst, diff_im ):
505-
num = np.minimum( ref_comp, tst_comp )
506-
ddr = np.maximum( ref_comp, tst_comp )
507-
diff_comp[ddr>0]+= 1.0-(num[ddr>0]/ddr[ddr>0])
508-
self._jaccards.append( np.sum( num ) / np.sum( ddr ) )
509-
volumes.append( np.sum( ref_comp ) )
510+
for ref_comp, tst_comp, diff_comp in zip(img_ref, img_tst, diff_im):
511+
num = np.minimum(ref_comp, tst_comp)
512+
ddr = np.maximum(ref_comp, tst_comp)
513+
diff_comp[ddr > 0] += 1.0 - (num[ddr > 0] / ddr[ddr > 0])
514+
self._jaccards.append(np.sum(num) / np.sum(ddr))
515+
volumes.append(np.sum(ref_comp))
510516

511-
self._dices = 2.0*np.array(self._jaccards) / (np.array(self._jaccards) +1.0 )
517+
self._dices = 2.0 * \
518+
np.array(self._jaccards) / (np.array(self._jaccards) + 1.0)
512519

513520
if self.inputs.weighting != "none":
514521
weights = 1.0 / np.array(volumes)
515522
if self.inputs.weighting == "squared_vol":
516-
weights = weights**2
523+
weights = weights ** 2
517524

518-
weights = weights / np.sum( weights )
525+
weights = weights / np.sum(weights)
519526

520-
setattr( self, '_jaccard', np.sum( weights * self._jaccards ) )
521-
setattr( self, '_dice', np.sum( weights * self._dices ) )
527+
setattr(self, '_jaccard', np.sum(weights * self._jaccards))
528+
setattr(self, '_dice', np.sum(weights * self._dices))
522529

530+
diff = np.zeros(diff_im[0].shape)
523531

524-
diff = np.zeros( diff_im[0].shape )
532+
for w, ch in zip(weights, diff_im):
533+
ch[msk == 0] = 0
534+
diff += w * ch
525535

526-
for w,ch in zip(weights,diff_im):
527-
ch[msk==0] = 0
528-
diff+= w* ch
529-
530-
nb.save(nb.Nifti1Image(diff, nb.load( self.inputs.in_ref[0]).get_affine(),
531-
nb.load( self.inputs.in_ref[0]).get_header()), self.inputs.out_file )
536+
nb.save(
537+
nb.Nifti1Image(diff, nb.load(self.inputs.in_ref[0]).get_affine(),
538+
nb.load(self.inputs.in_ref[0]).get_header()), self.inputs.out_file)
532539

533-
534540
return runtime
535541

536542
def _list_outputs(self):
537543
outputs = self._outputs().get()
538544
for method in ("dice", "jaccard"):
539545
outputs[method] = getattr(self, '_' + method)
540-
#outputs['volume_difference'] = self._volume
541546
outputs['diff_file'] = os.path.abspath(self.inputs.out_file)
542-
outputs['class_fji'] = np.array(self._jaccards).astype(float).tolist();
543-
outputs['class_fdi']= self._dices.astype(float).tolist();
547+
outputs['class_fji'] = np.array(
548+
self._jaccards).astype(float).tolist();
549+
outputs['class_fdi'] = self._dices.astype(float).tolist();
544550
return outputs
545551

546552

547-
548553
class CreateNiftiInputSpec(BaseInterfaceInputSpec):
549554
data_file = File(exists=True, mandatory=True, desc="ANALYZE img file")
550555
header_file = File(
@@ -599,6 +604,7 @@ class TSNROutputSpec(TraitedSpec):
599604

600605

601606
class TSNR(BaseInterface):
607+
602608
"""Computes the time-course SNR for a time series
603609
604610
Typically you want to run this on a realigned time-series.
@@ -641,7 +647,7 @@ def _run_interface(self, runtime):
641647
betas = np.dot(np.linalg.pinv(X), np.rollaxis(data, 3, 2))
642648
datahat = np.rollaxis(np.dot(X[:, 1:],
643649
np.rollaxis(
644-
betas[1:, :, :, :], 0, 3)),
650+
betas[1:, :,:,:], 0, 3)),
645651
0, 4)
646652
data = data - datahat
647653
img = nb.Nifti1Image(data, img.get_affine(), header)
@@ -676,6 +682,7 @@ class GunzipOutputSpec(TraitedSpec):
676682

677683

678684
class Gunzip(BaseInterface):
685+
679686
"""
680687
681688
"""
@@ -717,7 +724,7 @@ def matlab2csv(in_array, name, reshape):
717724
if reshape == True:
718725
if len(np.shape(output_array)) > 1:
719726
output_array = np.reshape(output_array, (
720-
np.shape(output_array)[0]*np.shape(output_array)[1], 1))
727+
np.shape(output_array)[0] * np.shape(output_array)[1], 1))
721728
iflogger.info(np.shape(output_array))
722729
output_name = op.abspath(name + '.csv')
723730
np.savetxt(output_name, output_array, delimiter=',')
@@ -736,6 +743,7 @@ class Matlab2CSVOutputSpec(TraitedSpec):
736743

737744

738745
class Matlab2CSV(BaseInterface):
746+
739747
"""
740748
Simple interface to save the components of a MATLAB .mat file as a text file with comma-separated values (CSVs).
741749
@@ -766,7 +774,8 @@ def _run_interface(self, runtime):
766774
if isinstance(in_dict[key][0], np.ndarray):
767775
saved_variables.append(key)
768776
else:
769-
iflogger.info('One of the keys in the input file, {k}, is not a Numpy array'.format(k=key))
777+
iflogger.info(
778+
'One of the keys in the input file, {k}, is not a Numpy array'.format(k=key))
770779

771780
if len(saved_variables) > 1:
772781
iflogger.info(
@@ -828,7 +837,7 @@ def merge_csvs(in_list):
828837
in_file, delimiter=',', skiprows=1, usecols=range(1, n_cols))
829838
except ValueError, ex:
830839
in_array = np.loadtxt(
831-
in_file, delimiter=',', skiprows=1, usecols=range(1, n_cols-1))
840+
in_file, delimiter=',', skiprows=1, usecols=range(1, n_cols - 1))
832841
if idx == 0:
833842
out_array = in_array
834843
else:
@@ -846,7 +855,7 @@ def remove_identical_paths(in_files):
846855
out_names = list()
847856
commonprefix = op.commonprefix(in_files)
848857
lastslash = commonprefix.rfind('/')
849-
commonpath = commonprefix[0:(lastslash+1)]
858+
commonpath = commonprefix[0:(lastslash + 1)]
850859
for fileidx, in_file in enumerate(in_files):
851860
path, name, ext = split_filename(in_file)
852861
in_file = op.join(path, name)
@@ -864,10 +873,10 @@ def maketypelist(rowheadings, shape, extraheadingBool, extraheading):
864873
if rowheadings:
865874
typelist.append(('heading', 'a40'))
866875
if len(shape) > 1:
867-
for idx in range(1, (min(shape)+1)):
876+
for idx in range(1, (min(shape) + 1)):
868877
typelist.append((str(idx), float))
869878
else:
870-
for idx in range(1, (shape[0]+1)):
879+
for idx in range(1, (shape[0] + 1)):
871880
typelist.append((str(idx), float))
872881
if extraheadingBool:
873882
typelist.append((extraheading, 'a40'))
@@ -881,13 +890,13 @@ def makefmtlist(output_array, typelist, rowheadingsBool, shape, extraheadingBool
881890
fmtlist.append('%s')
882891
if len(shape) > 1:
883892
output = np.zeros(max(shape), typelist)
884-
for idx in range(1, min(shape)+1):
885-
output[str(idx)] = output_array[:, idx-1]
893+
for idx in range(1, min(shape) + 1):
894+
output[str(idx)] = output_array[:, idx - 1]
886895
fmtlist.append('%f')
887896
else:
888897
output = np.zeros(1, typelist)
889-
for idx in range(1, len(output_array)+1):
890-
output[str(idx)] = output_array[idx-1]
898+
for idx in range(1, len(output_array) + 1):
899+
output[str(idx)] = output_array[idx - 1]
891900
fmtlist.append('%f')
892901
if extraheadingBool:
893902
fmtlist.append('%s')
@@ -917,6 +926,7 @@ class MergeCSVFilesOutputSpec(TraitedSpec):
917926

918927

919928
class MergeCSVFiles(BaseInterface):
929+
920930
"""
921931
This interface is designed to facilitate data loading in the R environment.
922932
It takes input CSV files and merges them into a single CSV file.
@@ -1051,6 +1061,7 @@ class AddCSVColumnOutputSpec(TraitedSpec):
10511061

10521062

10531063
class AddCSVColumn(BaseInterface):
1064+
10541065
"""
10551066
Short interface to add an extra column and field to a text file
10561067
@@ -1108,6 +1119,7 @@ class CalculateNormalizedMomentsOutputSpec(TraitedSpec):
11081119

11091120

11101121
class CalculateNormalizedMoments(BaseInterface):
1122+
11111123
"""
11121124
Calculates moments of timeseries.
11131125
@@ -1147,4 +1159,4 @@ def calc_moments(timeseries_file, moment):
11471159
m2 = stats.moment(timeseries, 2, axis=0)
11481160
m3 = stats.moment(timeseries, moment, axis=0)
11491161
zero = (m2 == 0)
1150-
return np.where(zero, 0, m3 / m2**(moment/2.0))
1162+
return np.where(zero, 0, m3 / m2 ** (moment / 2.0))

0 commit comments

Comments
 (0)