dsets.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. import copy
  2. import csv
  3. import functools
  4. import glob
  5. import os
  6. import random
  7. from collections import namedtuple
  8. import SimpleITK as sitk
  9. import numpy as np
  10. import torch
  11. import torch.cuda
  12. from torch.utils.data import Dataset
  13. from util.disk import getCache
  14. from util.util import XyzTuple, xyz2irc
  15. from util.logconf import logging
  16. log = logging.getLogger(__name__)
  17. # log.setLevel(logging.WARN)
  18. # log.setLevel(logging.INFO)
  19. log.setLevel(logging.DEBUG)
  20. raw_cache = getCache('part2ch09_raw')
  21. NoduleInfoTuple = namedtuple('NoduleInfoTuple', 'isMalignant_bool, diameter_mm, series_uid, center_xyz')
  22. @functools.lru_cache(1)
  23. def getNoduleInfoList(requireDataOnDisk_bool=True):
  24. # We construct a set with all series_uids that are present on disk.
  25. # This will let us use the data, even if we haven't downloaded all of
  26. # the subsets yet.
  27. mhd_list = glob.glob('data-unversioned/part2/luna/subset*/*.mhd')
  28. dataPresentOnDisk_set = {os.path.split(p)[-1][:-4] for p in mhd_list}
  29. diameter_dict = {}
  30. with open('data/part2/luna/annotations.csv', "r") as f:
  31. for row in list(csv.reader(f))[1:]:
  32. series_uid = row[0]
  33. annotationCenter_xyz = tuple([float(x) for x in row[1:4]])
  34. annotationDiameter_mm = float(row[4])
  35. diameter_dict.setdefault(series_uid, []).append((annotationCenter_xyz, annotationDiameter_mm))
  36. noduleInfo_list = []
  37. with open('data/part2/luna/candidates.csv', "r") as f:
  38. for row in list(csv.reader(f))[1:]:
  39. series_uid = row[0]
  40. if series_uid not in dataPresentOnDisk_set and requireDataOnDisk_bool:
  41. continue
  42. isMalignant_bool = bool(int(row[4]))
  43. candidateCenter_xyz = tuple([float(x) for x in row[1:4]])
  44. candidateDiameter_mm = 0.0
  45. for annotationCenter_xyz, annotationDiameter_mm in diameter_dict.get(series_uid, []):
  46. for i in range(3):
  47. delta_mm = abs(candidateCenter_xyz[i] - annotationCenter_xyz[i])
  48. if delta_mm > annotationDiameter_mm / 4:
  49. break
  50. else:
  51. candidateDiameter_mm = annotationDiameter_mm
  52. break
  53. noduleInfo_list.append(NoduleInfoTuple(isMalignant_bool, candidateDiameter_mm, series_uid, candidateCenter_xyz))
  54. noduleInfo_list.sort(reverse=True)
  55. return noduleInfo_list
  56. class Ct(object):
  57. def __init__(self, series_uid):
  58. mhd_path = glob.glob('data-unversioned/part2/luna/subset*/{}.mhd'.format(series_uid))[0]
  59. ct_mhd = sitk.ReadImage(mhd_path)
  60. ct_ary = np.array(sitk.GetArrayFromImage(ct_mhd), dtype=np.float32)
  61. # CTs are natively expressed in https://en.wikipedia.org/wiki/Hounsfield_scale
  62. # HU are scaled oddly, with 0 g/cc (air, approximately) being -1000 and 1 g/cc (water) being 0.
  63. # This gets rid of negative density stuff used to indicate out-of-FOV
  64. ct_ary[ct_ary < -1000] = -1000
  65. # This nukes any weird hotspots and clamps bone down
  66. ct_ary[ct_ary > 1000] = 1000
  67. self.series_uid = series_uid
  68. self.ary = ct_ary
  69. self.origin_xyz = XyzTuple(*ct_mhd.GetOrigin())
  70. self.vxSize_xyz = XyzTuple(*ct_mhd.GetSpacing())
  71. self.direction_tup = tuple(int(round(x)) for x in ct_mhd.GetDirection())
  72. def getRawNodule(self, center_xyz, width_irc):
  73. center_irc = xyz2irc(center_xyz, self.origin_xyz, self.vxSize_xyz, self.direction_tup)
  74. slice_list = []
  75. for axis, center_val in enumerate(center_irc):
  76. start_ndx = int(round(center_val - width_irc[axis]/2))
  77. end_ndx = int(start_ndx + width_irc[axis])
  78. assert center_val >= 0 and center_val < self.ary.shape[axis], repr([self.series_uid, center_xyz, self.origin_xyz, self.vxSize_xyz, center_irc, axis])
  79. if start_ndx < 0:
  80. # log.warning("Crop outside of CT array: {} {}, center:{} shape:{} width:{}".format(
  81. # self.series_uid, center_xyz, center_irc, self.ary.shape, width_irc))
  82. start_ndx = 0
  83. end_ndx = int(width_irc[axis])
  84. if end_ndx > self.ary.shape[axis]:
  85. # log.warning("Crop outside of CT array: {} {}, center:{} shape:{} width:{}".format(
  86. # self.series_uid, center_xyz, center_irc, self.ary.shape, width_irc))
  87. end_ndx = self.ary.shape[axis]
  88. start_ndx = int(self.ary.shape[axis] - width_irc[axis])
  89. slice_list.append(slice(start_ndx, end_ndx))
  90. ct_chunk = self.ary[tuple(slice_list)]
  91. return ct_chunk, center_irc
  92. @functools.lru_cache(1, typed=True)
  93. def getCt(series_uid):
  94. return Ct(series_uid)
  95. @raw_cache.memoize(typed=True)
  96. def getCtRawNodule(series_uid, center_xyz, width_irc):
  97. ct = getCt(series_uid)
  98. ct_chunk, center_irc = ct.getRawNodule(center_xyz, width_irc)
  99. return ct_chunk, center_irc
  100. class LunaDataset(Dataset):
  101. def __init__(self,
  102. test_stride=0,
  103. isTestSet_bool=None,
  104. series_uid=None,
  105. sortby_str='random',
  106. ):
  107. self.noduleInfo_list = copy.copy(getNoduleInfoList())
  108. if series_uid:
  109. self.noduleInfo_list = [x for x in self.noduleInfo_list if x[2] == series_uid]
  110. if test_stride > 1:
  111. if isTestSet_bool:
  112. self.noduleInfo_list = self.noduleInfo_list[::test_stride]
  113. else:
  114. del self.noduleInfo_list[::test_stride]
  115. if sortby_str == 'random':
  116. random.shuffle(self.noduleInfo_list)
  117. elif sortby_str == 'series_uid':
  118. self.noduleInfo_list.sort(key=lambda x: (x[2], x[3])) # sorting by series_uid, center_xyz)
  119. elif sortby_str == 'malignancy_size':
  120. pass
  121. else:
  122. raise Exception("Unknown sort: " + repr(sortby_str))
  123. log.info("{!r}: {} {} samples".format(
  124. self,
  125. len(self.noduleInfo_list),
  126. "testing" if isTestSet_bool else "training",
  127. ))
  128. def __len__(self):
  129. return len(self.noduleInfo_list)
  130. def __getitem__(self, ndx):
  131. nodule_tup = self.noduleInfo_list[ndx]
  132. width_irc = (24, 48, 48)
  133. nodule_ary, center_irc = getCtRawNodule(
  134. nodule_tup.series_uid,
  135. nodule_tup.center_xyz,
  136. width_irc,
  137. )
  138. nodule_tensor = torch.from_numpy(nodule_ary).to(torch.float32)
  139. nodule_tensor = nodule_tensor.unsqueeze(0)
  140. cls_tensor = torch.tensor([
  141. not nodule_tup.isMalignant_bool,
  142. nodule_tup.isMalignant_bool
  143. ],
  144. dtype=torch.long,
  145. )
  146. return nodule_tensor, cls_tensor, nodule_tup.series_uid, center_irc