dsets.py 6.4 KB

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