Skip to content

Commit

Permalink
Auto-adaptation with 2to3 -j4 -w -n
Browse files Browse the repository at this point in the history
  • Loading branch information
loli committed Sep 20, 2017
1 parent a6713c9 commit 93885e2
Show file tree
Hide file tree
Showing 104 changed files with 484 additions and 477 deletions.
2 changes: 1 addition & 1 deletion bin/medpy_dicom_slices_to_volume.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ def main():
data_input = series.get_pixel_array()

if args.spacing:
print '{} {}'.format(*series.info.PixelSpacing)
print('{} {}'.format(*series.info.PixelSpacing))
return 0

logger.debug('Resulting shape is {}.'.format(data_input.shape))
Expand Down
13 changes: 7 additions & 6 deletions bin/medpy_diff.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
# own modules
from medpy.core import Logger
from medpy.io import load
from functools import reduce


# information
Expand Down Expand Up @@ -65,19 +66,19 @@ def main():
data_input2, _ = load(args.input2)

# compare dtype and shape
if not data_input1.dtype == data_input2.dtype: print 'Dtype differs: {} to {}'.format(data_input1.dtype, data_input2.dtype)
if not data_input1.dtype == data_input2.dtype: print('Dtype differs: {} to {}'.format(data_input1.dtype, data_input2.dtype))
if not data_input1.shape == data_input2.shape:
print 'Shape differs: {} to {}'.format(data_input1.shape, data_input2.shape)
print 'The voxel content of images of different shape can not be compared. Exiting.'
print('Shape differs: {} to {}'.format(data_input1.shape, data_input2.shape))
print('The voxel content of images of different shape can not be compared. Exiting.')
sys.exit(-1)

# compare image data
voxel_total = reduce(lambda x, y: x*y, data_input1.shape)
voxel_difference = len((data_input1 != data_input2).nonzero()[0])
if not 0 == voxel_difference:
print 'Voxel differ: {} of {} total voxels'.format(voxel_difference, voxel_total)
print 'Max difference: {}'.format(scipy.absolute(data_input1 - data_input2).max())
else: print 'No other difference.'
print('Voxel differ: {} of {} total voxels'.format(voxel_difference, voxel_total))
print('Max difference: {}'.format(scipy.absolute(data_input1 - data_input2).max()))
else: print('No other difference.')

logger.info("Successfully terminated.")

Expand Down
4 changes: 2 additions & 2 deletions bin/medpy_extract_min_max.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ def main():
sys.exit(0)

# write header line
print 'image;min;max\n'
print('image;min;max\n')

# iterate over input images
for image in args.images:
Expand All @@ -85,7 +85,7 @@ def main():
max_value = image_data.max()

# count number of labels and write
print '{};{};{}\n'.format(image.split('/')[-1], min_value, max_value)
print('{};{};{}\n'.format(image.split('/')[-1], min_value, max_value))

sys.stdout.flush()

Expand Down
4 changes: 2 additions & 2 deletions bin/medpy_extract_sub_volume.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,8 +120,8 @@ def _to_int_or_none(string):
return int(string)
def _to_int_or_none_double (string):
if 0 == len(string): return [None, None]
return map(_to_int_or_none, string.split(':'))
args.volume = map(_to_int_or_none_double, args.volume.split(','))
return list(map(_to_int_or_none, string.split(':')))
args.volume = list(map(_to_int_or_none_double, args.volume.split(',')))
args.volume = [(x[0], x[1]) for x in args.volume]
except (ValueError, IndexError) as e:
raise ArgumentError('Maleformed volume parameter "{}", see description with -h flag.'.format(args.volume), e)
Expand Down
3 changes: 1 addition & 2 deletions bin/medpy_graphcut_label.py
Original file line number Diff line number Diff line change
Expand Up @@ -137,8 +137,7 @@ def main():
# apply results to the region image
logger.info('Applying results...')
mapping = [0] # no regions with id 1 exists in mapping, entry used as padding
mapping.extend(map(lambda x: 0 if gcgraph.termtype.SINK == gcgraph.what_segment(int(x) - 1) else 1,
scipy.unique(region_image_data)))
mapping.extend([0 if gcgraph.termtype.SINK == gcgraph.what_segment(int(x) - 1) else 1 for x in scipy.unique(region_image_data)])
region_image_data = filter.relabel_map(region_image_data, mapping)

# save resulting mask
Expand Down
5 changes: 2 additions & 3 deletions bin/medpy_graphcut_label_bgreduced.py
Original file line number Diff line number Diff line change
Expand Up @@ -146,8 +146,7 @@ def main():
# apply results to the region image
logger.info('Applying results...')
mapping = [0] # no regions with id 1 exists in mapping, entry used as padding
mapping.extend(map(lambda x: 0 if gcgraph.termtype.SINK == gcgraph.what_segment(int(x) - 1) else 1,
scipy.unique(region_image_data)))
mapping.extend([0 if gcgraph.termtype.SINK == gcgraph.what_segment(int(x) - 1) else 1 for x in scipy.unique(region_image_data)])
region_image_data = filter.relabel_map(region_image_data, mapping)

# generating final image by increasing the size again
Expand Down Expand Up @@ -179,7 +178,7 @@ def __xd_iterator_pass_on(arr, view, fun):
Like xd_iterator, but the fun return values are always passed on to the next and only the last returned.
"""
# create list of iterations
iterations = [[None] if dim in view else range(arr.shape[dim]) for dim in range(arr.ndim)]
iterations = [[None] if dim in view else list(range(arr.shape[dim])) for dim in range(arr.ndim)]

# iterate, create slicer, execute function and collect results
passon = None
Expand Down
3 changes: 1 addition & 2 deletions bin/medpy_graphcut_label_w_regional.py
Original file line number Diff line number Diff line change
Expand Up @@ -160,8 +160,7 @@ def main():
# apply results to the region image
logger.info('Applying results...')
mapping = [0] # no regions with id 1 exists in mapping, entry used as padding
mapping.extend(map(lambda x: 0 if gcgraph.termtype.SINK == gcgraph.what_segment(int(x) - 1) else 1,
scipy.unique(region_image_data)))
mapping.extend([0 if gcgraph.termtype.SINK == gcgraph.what_segment(int(x) - 1) else 1 for x in scipy.unique(region_image_data)])
region_image_data = filter.relabel_map(region_image_data, mapping)

# save resulting mask
Expand Down
6 changes: 3 additions & 3 deletions bin/medpy_grid.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,14 +108,14 @@ def list_of_integers_or_int(string, separator=','):

def list_of_integers(string, separator=','):
values = string.split(separator)
if not scipy.all(map(str.isdigit, values)):
if not scipy.all(list(map(str.isdigit, values))):
raise argparse.ArgumentTypeError('{} is not a "{}" separated list of integers'.format(string, separator))
return map(int, values)
return list(map(int, values))

def list_of_floats(string, separator=','):
values = string.split(separator)
try:
return map(float, values)
return list(map(float, values))
except ValueError:
raise argparse.ArgumentTypeError('{} is not a "{}" separated list of floats'.format(string, separator))

Expand Down
18 changes: 9 additions & 9 deletions bin/medpy_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,20 +68,20 @@ def main():

def printInfo(data, header):
# print image information
print '\nInformations obtained from image header:'
print 'header type={}'.format(type(header))
print('\nInformations obtained from image header:')
print('header type={}'.format(type(header)))
try:
print 'voxel spacing={}'.format(get_pixel_spacing(header))
print('voxel spacing={}'.format(get_pixel_spacing(header)))
except AttributeError:
print 'Failed to retrieve voxel spacing.'
print('Failed to retrieve voxel spacing.')
try:
print 'offset={}'.format(get_offset(header))
print('offset={}'.format(get_offset(header)))
except AttributeError:
print 'Failed to retrieve offset.'
print('Failed to retrieve offset.')

print '\nInformations obtained from image array:'
print 'datatype={},dimensions={},shape={}'.format(data.dtype, data.ndim, data.shape)
print 'first and last element: {} / {}'.format(data.flatten()[0], data.flatten()[-1])
print('\nInformations obtained from image array:')
print('datatype={},dimensions={},shape={}'.format(data.dtype, data.ndim, data.shape))
print('first and last element: {} / {}'.format(data.flatten()[0], data.flatten()[-1]))

def getArguments(parser):
"Provides additional validation of the arguments collected by argparse."
Expand Down
6 changes: 3 additions & 3 deletions bin/medpy_itk_smoothing.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,9 +113,9 @@ def main():
def getArguments(parser):
"Provides additional validation of the arguments collected by argparse."
args = parser.parse_args()
args.iterations = map(float, args.iterations.split(','))
args.conductances = map(float, args.conductances.split(','))
args.timesteps = map(float, args.timesteps.split(','))
args.iterations = list(map(float, args.iterations.split(',')))
args.conductances = list(map(float, args.conductances.split(',')))
args.timesteps = list(map(float, args.timesteps.split(',')))
return args

def getParser():
Expand Down
4 changes: 2 additions & 2 deletions bin/medpy_join_masks.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,10 +73,10 @@ def main():

# check if their shapes and voxel spacings are all equal
s0 = images[0][0].shape
if not numpy.all(map(lambda i: i[0].shape == s0, images[1:])):
if not numpy.all([i[0].shape == s0 for i in images[1:]]):
raise argparse.ArgumentError(args.input, 'At least one input image is of a different shape than the others.')
vs0 = header.get_pixel_spacing(images[0][1])
if not numpy.all(map(lambda i: header.get_pixel_spacing(i[1]) == vs0, images[1:])):
if not numpy.all([header.get_pixel_spacing(i[1]) == vs0 for i in images[1:]]):
raise argparse.ArgumentError(args.input, 'At least one input image has a different voxel spacing than the others.')

# execute operation
Expand Down
4 changes: 2 additions & 2 deletions bin/medpy_label_count.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ def main():
elif args.verbose: logger.setLevel(logging.INFO)

# write header line
print 'image;labels\n'
print('image;labels\n')

# iterate over input images
for image in args.images:
Expand All @@ -74,7 +74,7 @@ def main():
count = len(numpy.unique(image_data))

# count number of labels and write
print '{};{}\n'.format(image.split('/')[-1], count)
print('{};{}\n'.format(image.split('/')[-1], count))

sys.stdout.flush()

Expand Down
78 changes: 39 additions & 39 deletions bin/others/analyzeforest.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,26 +23,26 @@
def main():
rdf_file = sys.argv[1]

print 'Analyzing RDF {}:'.format(rdf_file)
print '####################################################'
print('Analyzing RDF {}:'.format(rdf_file))
print('####################################################')
rdf = pickle.load(open(rdf_file, 'r'))

print '\nBase information:'
print '\tForest type: {}'.format(type(rdf))
print '\tBase estimator type: {}'.format(type(rdf.base_estimator))
for name, value in rdf.get_params().iteritems():
print '\t{}: {}'.format(name, value)
print '\tN feature: {}'.format(rdf.n_features_)
print '\tN classes: {}'.format(rdf.n_classes_)
print '\tN estimators: {}'.format(len(rdf.estimators_))

print '\nNote on max_features attribute:'
print '\tIf int, then consider max_features features at each split.\n\t\
print('\nBase information:')
print('\tForest type: {}'.format(type(rdf)))
print('\tBase estimator type: {}'.format(type(rdf.base_estimator)))
for name, value in rdf.get_params().items():
print('\t{}: {}'.format(name, value))
print('\tN feature: {}'.format(rdf.n_features_))
print('\tN classes: {}'.format(rdf.n_classes_))
print('\tN estimators: {}'.format(len(rdf.estimators_)))

print('\nNote on max_features attribute:')
print('\tIf int, then consider max_features features at each split.\n\t\
If float, then max_features is a percentage and int(max_features * n_features) features are considered at each split.\n\t\
If "auto", then max_features=sqrt(n_features).\n\t\
If "sqrt", then max_features=sqrt(n_features).\n\t\
If "log2", then max_features=log2(n_features).\n\t\
If None, then max_features=n_features.'
If None, then max_features=n_features.')

# prepare counters
fu = numpy.zeros((rdf.n_features_, rdf.estimators_[0].max_depth), numpy.int) # feature usage # !TODO: Dangerous if max_depth is set to None, what happens then?
Expand All @@ -54,7 +54,7 @@ def main():
# prepare constants
TREE_LEAF = -1 # !TODO: Use the value defined in scikit-learn here, rather than defining it by myself

print '\nParsing trees...',
print('\nParsing trees...', end=' ')
for no, e in enumerate(rdf.estimators_):
t = e.tree_
ts.append(t.node_count)
Expand All @@ -78,18 +78,18 @@ def recursive(idx, depth):
max_depth = recursive(0, 0) # Note: first node is considered depth level 1
td.append(max_depth)

print no,
print(no, end=' ')
sys.stdout.flush()

print 'done.'
print('done.')

print 'Trimming results...',
print('Trimming results...', end=' ')
fu = fu[:,:max(td)+1]
print 'done.'
print('done.')

print '\nGeneral tree information:'
print '\tMean/median/max/min tree depth: {} / {} / {} / {}'.format(numpy.mean(td), numpy.median(td), numpy.max(td), numpy.min(td))
print '\tMean/median/max/min tree size (in nodes incl leafs): {} / {} / {} / {}'.format(numpy.mean(ts), numpy.median(ts), numpy.max(ts), numpy.min(ts))
print('\nGeneral tree information:')
print('\tMean/median/max/min tree depth: {} / {} / {} / {}'.format(numpy.mean(td), numpy.median(td), numpy.max(td), numpy.min(td)))
print('\tMean/median/max/min tree size (in nodes incl leafs): {} / {} / {} / {}'.format(numpy.mean(ts), numpy.median(ts), numpy.max(ts), numpy.min(ts)))

#print '\nFeature\tnode appearances:'
#for fidx, val in enumerate(numpy.sum(fu, 1)):
Expand All @@ -100,7 +100,7 @@ def recursive(idx, depth):
# nz = numpy.nonzero(farr)
# print '{}\t{}'.format(fidx, nz[0][0])

print 'Loading feature names...',
print('Loading feature names...', end=' ')
fn_ = numpy.load(sys.argv[2])
fn = []
for n in fn_:
Expand All @@ -109,20 +109,20 @@ def recursive(idx, depth):
else:
for i in range(0, 11):
fn.append('{}_bin{}'.format(n, i))
print 'done.'
print('done.')
with open(sys.argv[3], 'w') as f:
for i, n in enumerate(fn):
f.write('{}\t{}\n'.format(i, n))


print 'Creating full csv files...',
print('Creating full csv files...', end=' ')
div = numpy.sum(fu, 0, dtype=numpy.float)
rc = fu / div
with open(sys.argv[4], 'w') as f:
numpy.savetxt(f, rc, '%.5f', '\t', '\n', 'feature_ids X depth, val=occurences of forst {}'.format(sys.argv[1]))
print 'done.'
print('done.')

print 'Grouping by sequence...',
print('Grouping by sequence...', end=' ')
sequence_keys = []
for n in fn:
sequence_keys.append(n.split('.')[1])
Expand All @@ -132,12 +132,12 @@ def recursive(idx, depth):
for sk, row in zip(sequence_keys, rc):
idx = numpy.where(sequences_unique==sk)[0][0]
grouped_by_sequence[idx] += row
print sequences_unique
print(sequences_unique)
with open(sys.argv[5], 'w') as f:
numpy.savetxt(f, grouped_by_sequence, '%.5f', '\t', '\n', 'sequences X depth, val=occurences of forst {}'.format(sys.argv[1]))
print 'done.'
print('done.')

print 'Grouping by features...',
print('Grouping by features...', end=' ')
feature_keys = []
for n in fn:
feature_keys.append('.'.join(n.split('.')[2:]))
Expand All @@ -147,20 +147,20 @@ def recursive(idx, depth):
for fk, row in zip(feature_keys, rc):
idx = numpy.where(features_unique==fk)[0][0]
grouped_by_feature[idx] += row
print '\n'.join(features_unique)
print('\n'.join(features_unique))
with open(sys.argv[6], 'w') as f:
numpy.savetxt(f, grouped_by_feature, '%.5f', '\t', '\n', 'features X depth, val=occurences of forst {}'.format(sys.argv[1]))
print 'done.'
print('done.')


print 'Writing rdf feature importances...',
print('Writing rdf feature importances...', end=' ')
feature_importances = rdf.feature_importances_
with open(sys.argv[7], 'w') as f:
for n, imp in zip(fn, feature_importances):
f.write('{}\t{}\n'.format(n, imp))
print 'done.'
print('done.')

print 'Writing rdf feature importances grouped...',
print('Writing rdf feature importances grouped...', end=' ')
grouped_by_feature = [0] * len(features_unique)
with open(sys.argv[8], 'w') as f:
for n, imp in zip(fn, feature_importances):
Expand All @@ -172,18 +172,18 @@ def recursive(idx, depth):
grouped_by_feature[idx] += imp
for n, imp in zip(features_unique, grouped_by_feature):
f.write('{}\t{}\n'.format(n, imp))
print 'done.'
print('done.')

sys.exit(0)

print 'Writing rdf/et node usage...',
print('Writing rdf/et node usage...', end=' ')
etocc = etocc[:numpy.nonzero(etocc)[0][-1]+1]
rdfocc = rdfocc[:numpy.nonzero(rdfocc)[0][-1]+1]
print sys.argv[9]
print(sys.argv[9])
with open(sys.argv[9], 'w') as f:
f.write('ET node occurences\t{}\n'.format('\t'.join(map(str, etocc))))
f.write('RDF node occurences\t{}\n'.format('\t'.join(map(str, rdfocc))))
print 'done.'
print('done.')

if __name__ == "__main__":
main()
Expand Down
Loading

0 comments on commit 93885e2

Please sign in to comment.