dsets.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  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('part2ch10_raw')
  20. CandidateInfoTuple = namedtuple(
  21. 'CandidateInfoTuple',
  22. 'isNodule_bool, diameter_mm, series_uid, center_xyz',
  23. )
  24. @functools.lru_cache(1)
  25. def getCandidateInfoList(requireOnDisk_bool=True):
  26. # We construct a set with all series_uids that are present on disk.
  27. # This will let us use the data, even if we haven't downloaded all of
  28. # the subsets yet.
  29. mhd_list = glob.glob('data-unversioned/part2/luna/subset*/*.mhd')
  30. presentOnDisk_set = {os.path.split(p)[-1][:-4] for p in mhd_list}
  31. diameter_dict = {}
  32. with open('data/part2/luna/annotations.csv', "r") as f:
  33. for row in list(csv.reader(f))[1:]:
  34. series_uid = row[0]
  35. annotationCenter_xyz = tuple([float(x) for x in row[1:4]])
  36. annotationDiameter_mm = float(row[4])
  37. diameter_dict.setdefault(series_uid, []).append(
  38. (annotationCenter_xyz, annotationDiameter_mm)
  39. )
  40. candidateInfo_list = []
  41. with open('data/part2/luna/candidates.csv', "r") as f:
  42. for row in list(csv.reader(f))[1:]:
  43. series_uid = row[0]
  44. if series_uid not in presentOnDisk_set and requireOnDisk_bool:
  45. continue
  46. isNodule_bool = bool(int(row[4]))
  47. candidateCenter_xyz = tuple([float(x) for x in row[1:4]])
  48. candidateDiameter_mm = 0.0
  49. for annotation_tup in diameter_dict.get(series_uid, []):
  50. annotationCenter_xyz, annotationDiameter_mm = annotation_tup
  51. for i in range(3):
  52. delta_mm = abs(candidateCenter_xyz[i] - annotationCenter_xyz[i])
  53. if delta_mm > annotationDiameter_mm / 4:
  54. break
  55. else:
  56. candidateDiameter_mm = annotationDiameter_mm
  57. break
  58. candidateInfo_list.append(CandidateInfoTuple(
  59. isNodule_bool,
  60. candidateDiameter_mm,
  61. series_uid,
  62. candidateCenter_xyz,
  63. ))
  64. candidateInfo_list.sort(reverse=True)
  65. return candidateInfo_list
  66. class Ct:
  67. def __init__(self, series_uid):
  68. mhd_path = glob.glob(
  69. 'data-unversioned/part2/luna/subset*/{}.mhd'.format(series_uid)
  70. )[0]
  71. ct_mhd = sitk.ReadImage(mhd_path)
  72. ct_a = np.array(sitk.GetArrayFromImage(ct_mhd), dtype=np.float32)
  73. # CTs are natively expressed in https://en.wikipedia.org/wiki/Hounsfield_scale
  74. # HU are scaled oddly, with 0 g/cc (air, approximately) being -1000 and 1 g/cc (water) being 0.
  75. # The lower bound gets rid of negative density stuff used to indicate out-of-FOV
  76. # The upper bound nukes any weird hotspots and clamps bone down
  77. ct_a.clip(-1000, 1000, ct_a)
  78. self.series_uid = series_uid
  79. self.hu_a = ct_a
  80. self.origin_xyz = XyzTuple(*ct_mhd.GetOrigin())
  81. self.vxSize_xyz = XyzTuple(*ct_mhd.GetSpacing())
  82. self.direction_a = np.array(ct_mhd.GetDirection()).reshape(3, 3)
  83. def getRawCandidate(self, center_xyz, width_irc):
  84. center_irc = xyz2irc(
  85. center_xyz,
  86. self.origin_xyz,
  87. self.vxSize_xyz,
  88. self.direction_a,
  89. )
  90. slice_list = []
  91. for axis, center_val in enumerate(center_irc):
  92. start_ndx = int(round(center_val - width_irc[axis]/2))
  93. end_ndx = int(start_ndx + width_irc[axis])
  94. 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])
  95. if start_ndx < 0:
  96. # log.warning("Crop outside of CT array: {} {}, center:{} shape:{} width:{}".format(
  97. # self.series_uid, center_xyz, center_irc, self.hu_a.shape, width_irc))
  98. start_ndx = 0
  99. end_ndx = int(width_irc[axis])
  100. if end_ndx > self.hu_a.shape[axis]:
  101. # log.warning("Crop outside of CT array: {} {}, center:{} shape:{} width:{}".format(
  102. # self.series_uid, center_xyz, center_irc, self.hu_a.shape, width_irc))
  103. end_ndx = self.hu_a.shape[axis]
  104. start_ndx = int(self.hu_a.shape[axis] - width_irc[axis])
  105. slice_list.append(slice(start_ndx, end_ndx))
  106. ct_chunk = self.hu_a[tuple(slice_list)]
  107. return ct_chunk, center_irc
  108. @functools.lru_cache(1, typed=True)
  109. def getCt(series_uid):
  110. return Ct(series_uid)
  111. @raw_cache.memoize(typed=True)
  112. def getCtRawCandidate(series_uid, center_xyz, width_irc):
  113. ct = getCt(series_uid)
  114. ct_chunk, center_irc = ct.getRawCandidate(center_xyz, width_irc)
  115. return ct_chunk, center_irc
  116. class LunaDataset(Dataset):
  117. def __init__(self,
  118. val_stride=0,
  119. isValSet_bool=None,
  120. series_uid=None,
  121. ):
  122. self.candidateInfo_list = copy.copy(getCandidateInfoList())
  123. if series_uid:
  124. self.candidateInfo_list = [
  125. x for x in self.candidateInfo_list if x.series_uid == series_uid
  126. ]
  127. if isValSet_bool:
  128. assert val_stride > 0, val_stride
  129. self.candidateInfo_list = self.candidateInfo_list[::val_stride]
  130. assert self.candidateInfo_list
  131. elif val_stride > 0:
  132. del self.candidateInfo_list[::val_stride]
  133. assert self.candidateInfo_list
  134. log.info("{!r}: {} {} samples".format(
  135. self,
  136. len(self.candidateInfo_list),
  137. "validation" if isValSet_bool else "training",
  138. ))
  139. def __len__(self):
  140. return len(self.candidateInfo_list)
  141. def __getitem__(self, ndx):
  142. candidateInfo_tup = self.candidateInfo_list[ndx]
  143. width_irc = (32, 48, 48)
  144. candidate_a, center_irc = getCtRawCandidate(
  145. candidateInfo_tup.series_uid,
  146. candidateInfo_tup.center_xyz,
  147. width_irc,
  148. )
  149. candidate_t = torch.from_numpy(candidate_a)
  150. candidate_t = candidate_t.to(torch.float32)
  151. candidate_t = candidate_t.unsqueeze(0)
  152. pos_t = torch.tensor([
  153. not candidateInfo_tup.isNodule_bool,
  154. candidateInfo_tup.isNodule_bool
  155. ],
  156. dtype=torch.long,
  157. )
  158. return (
  159. candidate_t,
  160. pos_t,
  161. candidateInfo_tup.series_uid,
  162. torch.tensor(center_irc),
  163. )