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

making it python 3 compatible #188

Closed
wants to merge 7 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
321 changes: 161 additions & 160 deletions bin/Notebooks/PyRadiomics Example.ipynb

Large diffs are not rendered by default.

440 changes: 440 additions & 0 deletions bin/Notebooks/Python3Notebook.ipynb

Large diffs are not rendered by default.

1,127 changes: 569 additions & 558 deletions bin/Notebooks/helloFeatureClass.ipynb

Large diffs are not rendered by default.

69 changes: 36 additions & 33 deletions bin/Notebooks/helloRadiomics.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
},
"outputs": [],
"source": [
"from __future__ import print_function, unicode_literals, division, absolute_import\n",
"import sys\n",
"import os\n",
"import logging\n",
Expand Down Expand Up @@ -96,9 +97,9 @@
"maskName = os.path.join(dataDir, testCase + '_label.nrrd')\n",
"\n",
"if not os.path.exists(imageName):\n",
" print 'Error: problem finding input image', imageName\n",
" print('Error: problem finding input image', imageName)\n",
"if not os.path.exists(maskName):\n",
" print 'Error: problem finding input labelmap', maskName"
" print('Error: problem finding input labelmap', maskName)"
]
},
{
Expand Down Expand Up @@ -152,7 +153,7 @@
"output_type": "stream",
"text": [
"Enabled input images:\n",
"\toriginal\n"
"\tOriginal\n"
]
}
],
Expand All @@ -172,9 +173,9 @@
"\n",
"# extractor.enableInputImages(wavelet={}, log={'sigma':[3.0]})\n",
"\n",
"print \"Enabled input images:\"\n",
"print(\"Enabled input images:\")\n",
"for imageType in extractor.inputImages.keys():\n",
" print '\\t' + imageType"
" print('\\t' + imageType)"
]
},
{
Expand Down Expand Up @@ -246,6 +247,7 @@
"\n",
" :math:`entropy = -\\displaystyle\\sum^{N_l}_{i=1}{p(i)\\log_2\\big(p(i)+\\epsilon\\big)}`\n",
"\n",
" Here, :math:`\\epsilon` is an arbitrarily small positive number (:math:`\\approx 2.2\\times10^{-16}`).\n",
" Entropy specifies the uncertainty/randomness in the\n",
" image values. It measures the average amount of\n",
" information required to encode the image values.\n",
Expand Down Expand Up @@ -391,13 +393,13 @@
}
],
"source": [
"print \"Active features:\"\n",
"for cls, features in extractor.enabledFeatures.iteritems():\n",
"print(\"Active features:\")\n",
"for cls, features in extractor.enabledFeatures.items():\n",
" if len(features) == 0:\n",
" features = extractor.getFeatureNames(cls)\n",
" for f in features:\n",
" print f\n",
" print eval('extractor.featureClasses[\"%s\"].get%sFeatureValue.__doc__' % (cls, f))"
" print(f)\n",
" print(eval('extractor.featureClasses[\"%s\"].get%sFeatureValue.__doc__' % (cls, f)))"
]
},
{
Expand All @@ -421,62 +423,63 @@
"Calculating features\n",
"\t\tComputing firstorder\n",
"Computed general_info_BoundingBox: (162; 84; 11; 47; 70; 7)\n",
"Computed general_info_GeneralSettings: {'verbose': True; 'binWidth': 25; 'label': 1; 'interpolator': 'sitkBSpline'; 'resampledPixelSpacing': None; 'padDistance': 5}\n",
"Computed general_info_GeneralSettings: {'verbose': True; 'label': 1; 'resampledPixelSpacing': None; 'binWidth': 25; 'interpolator': 'sitkBSpline'; 'padDistance': 5}\n",
"Computed general_info_ImageHash: 5c9ce3ca174f0f8324aa4d277e0fef82dc5ac566\n",
"Computed general_info_ImageSpacing: (0.7812499999999999; 0.7812499999999999; 6.499999999999998)\n",
"Computed general_info_InputImages: {'original': {}}\n",
"Computed general_info_InputImages: {'Original': {}}\n",
"Computed general_info_MaskHash: 9dc2c3137b31fd872997d92c9a92d5178126d9d3\n",
"Computed general_info_Version: v1.0.post11.dev0+g610dffc\n",
"Computed general_info_Version: v1.0.1.post6.dev0+g5b1e8bb\n",
"Computed general_info_VolumeNum: 2\n",
"Computed general_info_VoxelNum: 4137\n",
"Computed original_firstorder_InterquartileRange: 253.0\n",
"Computed original_firstorder_Skewness: 0.275650859086\n",
"Computed original_firstorder_Uniformity: 0.0451569635559\n",
"Computed original_firstorder_MeanAbsoluteDeviation: 133.447261953\n",
"Computed original_firstorder_Energy: 33122817481.0\n",
"Computed original_firstorder_Kurtosis: 2.18077293939\n",
"Computed original_firstorder_StandardDeviation: 156.611235894\n",
"Computed original_firstorder_10Percentile: 632.0\n",
"Computed original_firstorder_90Percentile: 1044.4\n",
"Computed original_firstorder_Minimum: 468.0\n",
"Computed original_firstorder_RobustMeanAbsoluteDeviation: 103.00138343\n",
"Computed original_firstorder_Median: 812.0\n",
"Computed original_firstorder_TotalEnergy: 131407662126.0\n",
"Computed original_firstorder_Range: 798.0\n",
"Computed original_firstorder_Maximum: 1266.0\n",
"Computed original_firstorder_Uniformity: 0.0451569635559\n",
"Computed original_firstorder_Mean: 825.235436307\n",
"Computed original_firstorder_TotalEnergy: 131407662126.0\n",
"Computed original_firstorder_MeanAbsoluteDeviation: 133.447261953\n",
"Computed original_firstorder_RootMeanSquared: 2829.57282108\n",
"Computed original_firstorder_90Percentile: 1044.4\n",
"Computed original_firstorder_Minimum: 468.0\n",
"Computed original_firstorder_InterquartileRange: 253.0\n",
"Computed original_firstorder_Entropy: 4.6019355539\n",
"Computed original_firstorder_StandardDeviation: 156.611235894\n",
"Computed original_firstorder_Range: 798.0\n",
"Computed original_firstorder_Variance: 24527.0792084\n",
"Computed original_firstorder_10Percentile: 632.0\n",
"Computed original_firstorder_Kurtosis: 2.18077293939\n",
"Computed original_firstorder_Mean: 825.235436307\n"
"Computed original_firstorder_Energy: 33122817481.0\n",
"Computed original_firstorder_Skewness: 0.275650859086\n",
"Computed original_firstorder_Median: 812.0\n"
]
}
],
"source": [
"print \"Calculating features\"\n",
"print(\"Calculating features\")\n",
"featureVector = extractor.execute(imageName, maskName)\n",
"\n",
"for featureName in featureVector.keys():\n",
" print \"Computed %s: %s\" % (featureName, featureVector[featureName])"
" print(\"Computed %s: %s\" % (featureName, featureVector[featureName]))"
]
}
],
"metadata": {
"anaconda-cloud": {},
"kernelspec": {
"display_name": "Python 2",
"display_name": "Python 3",
"language": "python",
"name": "python2"
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 2
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython2",
"version": "2.7.11"
"pygments_lexer": "ipython3",
"version": "3.5.2"
}
},
"nbformat": 4,
Expand Down
16 changes: 8 additions & 8 deletions bin/addClassToBaseline.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,17 +34,17 @@ def main():
if len(testCases) > 0: break

if len(testCases) == 0:
print ("No baselinefiles containing testcases found, exiting...")
print("No baselinefiles containing testcases found, exiting...")
exit(-1)

newClasses = [cls for cls in featureClasses if
not os.path.exists(os.path.join(baselineDir, 'baseline_%s.csv' % (cls)))]

if len(newClasses) == 0:
print "No new classes to add, exiting..."
print("No new classes to add, exiting...")
exit(0)

print "Adding new classes: ", newClasses
print("Adding new classes: ", newClasses)

newBaseline = {}

Expand All @@ -59,21 +59,21 @@ def main():
for cls in newClasses:
newBaseline[cls] = {}

print "Computing new baseline"
print("Computing new baseline")
for testCase in testCases:
print "\tCalculating test case", testCase
print("\tCalculating test case", testCase)
imagePath = os.path.join(dataDir, testCase + '_image.nrrd')
maskPath = os.path.join(dataDir, testCase + '_label.nrrd')
image, mask = extractor.loadImage(imagePath, maskPath)
if image is None or mask is None:
print "Error during loading of image/mask, testcase:", testCase
print("Error during loading of image/mask, testcase:", testCase)
continue # testImage or mask not found / error during loading

provenance = extractor.getProvenance(imagePath, maskPath, mask)

image, mask, bb = imageoperations.cropToTumorMask(image, mask)
for cls in newClasses:
print "\t\tCalculating class", cls
print("\t\tCalculating class", cls)
newBaseline[cls][testCase] = collections.OrderedDict()
newBaseline[cls][testCase]["Patient ID"] = testCase
newBaseline[cls][testCase].update(provenance)
Expand All @@ -82,7 +82,7 @@ def main():
featureClass.calculateFeatures()
newBaseline[cls][testCase].update(featureClass.featureValues)

print "Writing new baseline"
print("Writing new baseline")
for cls in newClasses:
baselineFile = os.path.join(baselineDir, 'baseline_%s.csv' % (cls))
with open(baselineFile, 'wb') as baseline:
Expand Down
16 changes: 8 additions & 8 deletions bin/batchExamples/DatasetHierarchyReader.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ def readReconstructionsDirectory(self, studyDirectory, subfolders, create=False)
recDirectory = os.path.join(studyDirectory, "Reconstructions")
if not os.path.exists(recDirectory):
os.mkdir(recDirectory)
print "\tCreated:", recDirectory
print("\tCreated:", recDirectory)

return recDirectory, images

Expand All @@ -67,7 +67,7 @@ def readSegmentationsDirectory(self, studyDirectory, subfolders, create=False):
segDirectory = os.path.join(studyDirectory, "Segmentations")
if not os.path.exists(segDirectory):
os.mkdir(segDirectory)
print "\tCreated:", segDirectory
print("\tCreated:", segDirectory)

return segDirectory, labels

Expand All @@ -82,7 +82,7 @@ def readResourcesDirectory(self, studyDirectory, subfolders, create=False):
resDirectory = os.path.join(studyDirectory, "Resources")
if not os.path.exists(resDirectory):
os.mkdir(resDirectory)
print "\tCreated:", resDirectory
print("\tCreated:", resDirectory)

return resDirectory, resources

Expand All @@ -102,7 +102,7 @@ def findImageAndLabelPair(self, imageFilepaths, maskFilepaths, keywordSettings):
conditions.
"""

keywordSettings = {k: [str(keyword.strip()) for keyword in v.split(',')] for (k, v) in keywordSettings.iteritems()}
keywordSettings = {k: [str(keyword.strip()) for keyword in v.split(',')] for (k, v) in keywordSettings.items()}

matchedImages = []
for imageFilepath in imageFilepaths:
Expand All @@ -117,14 +117,14 @@ def findImageAndLabelPair(self, imageFilepaths, maskFilepaths, keywordSettings):
matchedMasks.append(maskFilepath)

if len(matchedImages) < 1:
print "ERROR: No Images Matched"
print("ERROR: No Images Matched")
elif len(matchedImages) > 1:
print "ERROR: Multiple Images Matched"
print("ERROR: Multiple Images Matched")

if len(matchedMasks) < 1:
print "ERROR: No Masks Matched"
print("ERROR: No Masks Matched")
elif len(matchedMasks) > 1:
print "ERROR: Multiple Masks Matched"
print("ERROR: Multiple Masks Matched")

if (len(matchedImages) == 1) and (len(matchedMasks) == 1):
return matchedImages[0], matchedMasks[0]
Expand Down
11 changes: 6 additions & 5 deletions bin/batchExamples/GenerateInputCSV_Datasethierarchy.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from __future__ import print_function, unicode_literals, division, absolute_import
import os
import csv
from DatasetHierarchyReader import DatasetHierarchyReader
from .DatasetHierarchyReader import DatasetHierarchyReader


def main():
Expand All @@ -15,12 +16,12 @@ def main():
keywordSettings['mask'] = 'label'
keywordSettings['maskExclusion'] = ''

print "Scanning files..."
print("Scanning files...")

datasetReader = DatasetHierarchyReader(inputDirectory, filetype=filetype)
datasetHierarchyDict = datasetReader.ReadDatasetHierarchy()

print "Found %s patients, writing csv" % (str(len(datasetHierarchyDict.keys())))
print("Found %s patients, writing csv" % (str(len(datasetHierarchyDict.keys()))))

try:
with open(outputFile, 'wb') as outFile:
Expand All @@ -42,8 +43,8 @@ def main():
# ReaderName is not extracted using DatasetHierarchyReader, set it to 'N/A'
cw.writerow([patientID, studyDate, 'N/A', imageFilepath, maskFilepath])

except Exception, e:
print e
except Exception as e:
print(e)


if __name__ == '__main__':
Expand Down
19 changes: 10 additions & 9 deletions bin/batchExamples/GenerateInputCSV_Filename.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from __future__ import print_function, unicode_literals, division, absolute_import
import os
import csv

Expand Down Expand Up @@ -32,22 +33,22 @@ def main():
outputFile = DATA_ROOT_PATH + r"/Included/FileList.csv"
filetype = ".nrrd"

print "Scanning files..."
print("Scanning files...")

datasetHierarchyDict = scanpatients(inputDirectory, filetype)

print "Found %s patients, writing csv" % (len(datasetHierarchyDict.keys()))
print("Found %s patients, writing csv" % (len(datasetHierarchyDict.keys())))

try:
with open(outputFile, 'wb') as outFile:
cw = csv.writer(outFile, lineterminator='\n')

for patient, Studies in sorted(datasetHierarchyDict.iteritems(), key=lambda t: t[0]):
for Study, im_fileList in sorted(Studies['reconstructions'].iteritems(), key=lambda t: t[0]):
for patient, Studies in sorted(datasetHierarchyDict.items(), key=lambda t: t[0]):
for Study, im_fileList in sorted(Studies['reconstructions'].items(), key=lambda t: t[0]):
for i_idx, im_file in enumerate(im_fileList):

if Studies['segmentations'].has_key(Study):
for Reader, seg_fileList in sorted(Studies['segmentations'][Study].iteritems(), key=lambda t: t[0]):
for Reader, seg_fileList in sorted(Studies['segmentations'][Study].items(), key=lambda t: t[0]):
for s_idx, seg_file in enumerate(sorted(seg_fileList)):

i_name = Study
Expand All @@ -57,8 +58,8 @@ def main():
if s_idx > 0: s_name += " (%s)" % (str(s_idx + 1))

cw.writerow([patient, i_name, s_name, im_file, seg_file])
except Exception, e:
print e
except Exception as e:
print(e)


def scanpatients(f, filetype):
Expand All @@ -74,9 +75,9 @@ def scanpatients(f, filetype):
outputDict[PtNo] = {'reconstructions': {}}
outputDict[PtNo]['segmentations'] = {}

for SqKey, SqVal in SqDic.iteritems():
for SqKey, SqVal in SqDic.items():
if ("ROI_" + SqVal) in fname:
for ReaderKey, ReaderVal in LabelDic.iteritems():
for ReaderKey, ReaderVal in LabelDic.items():
if (ReaderKey + '_') in fname:
if not outputDict[PtNo]['segmentations'].has_key(SqVal):
outputDict[PtNo]['segmentations'][SqVal] = {}
Expand Down
8 changes: 4 additions & 4 deletions bin/batchExamples/batchprocessing.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ def main():
radiomics.logger.handlers[0].setLevel(logging.WARNING)

logging.info('Loading CSV')
print "Loading CSV"
print("Loading CSV")

flists = []
try:
Expand All @@ -43,8 +43,8 @@ def main():
except Exception:
logging.error('CSV READ FAILED:\n%s', traceback.format_exc())

print "Loading Done"
print ("Patients: " + str(len(flists)))
print("Loading Done")
print("Patients: " + str(len(flists)))

kwargs = {}
kwargs['binWidth'] = 25
Expand All @@ -60,7 +60,7 @@ def main():
# extractor.enableInputImages(wavelet= {'level': 2})
for idx, entry in enumerate(flists, start=1):

print "(%d/%d) Processing Patient: %s, Study: %s, Reader: %s" % (idx, len(flists), entry[0], entry[1], entry[2])
print("(%d/%d) Processing Patient: %s, Study: %s, Reader: %s" % (idx, len(flists), entry[0], entry[1], entry[2]))
logging.info("(%d/%d) Processing Patient: %s, Study: %s, Reader: %s", idx, len(flists), entry[0], entry[1],
entry[2])

Expand Down
Loading