[d9566e]: / sybil / serie.py

Download this file

278 lines (236 with data), 8.7 kB

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
import functools
from typing import List, Optional, NamedTuple, Literal
from argparse import Namespace
import torch
import numpy as np
import pydicom
import torchio as tio
from sybil.datasets.utils import order_slices, VOXEL_SPACING
from sybil.utils.loading import get_sample_loader
class Meta(NamedTuple):
paths: list
thickness: float
pixel_spacing: list
manufacturer: str
slice_positions: list
voxel_spacing: torch.Tensor
class Label(NamedTuple):
y: int
y_seq: np.ndarray
y_mask: np.ndarray
censor_time: int
class Serie:
def __init__(
self,
dicoms: List[str],
voxel_spacing: Optional[List[float]] = None,
label: Optional[int] = None,
censor_time: Optional[int] = None,
file_type: Literal["png", "dicom"] = "dicom",
split: Literal["train", "dev", "test"] = "test",
):
"""Initialize a Serie.
Parameters
----------
`dicoms` : List[str]
[description]
`voxel_spacing`: Optional[List[float]], optional
The voxel spacing associated with input CT
as (row spacing, col spacing, slice thickness)
`label` : Optional[int], optional
Whether the patient associated with this serie
has or ever developped cancer.
`censor_time` : Optional[int]
Number of years until cancer diagnostic.
If less than 1 year, should be 0.
`file_type`: Literal['png', 'dicom']
File type of CT slices
`split`: Literal['train', 'dev', 'test']
Dataset split into which the serie falls into.
Assumed to be test by default
"""
if label is not None and censor_time is None:
raise ValueError("censor_time should also provided with label.")
if file_type == "png" and voxel_spacing is None:
raise ValueError("voxel_spacing should be provided for PNG files.")
self._censor_time = censor_time
self._label = label
args = self._load_args(file_type)
self._args = args
self._loader = get_sample_loader(split, args)
self._meta = self._load_metadata(dicoms, voxel_spacing, file_type)
self._check_valid(args)
self.resample_transform = tio.transforms.Resample(target=VOXEL_SPACING)
self.padding_transform = tio.transforms.CropOrPad(
target_shape=tuple(args.img_size + [args.num_images]), padding_mode=0
)
def has_label(self) -> bool:
"""Check if there is a label associated with this serie.
Returns
-------
bool
[description]
"""
return self._label is not None
def get_label(self, max_followup: int = 6) -> Label:
"""Get the label for this Serie.
Parameters
----------
max_followup : int, optional
[description], by default 6
Returns
-------
Tuple[bool, np.array, np.array, int]
[description]
Raises
------
ValueError
[description]
"""
if not self.has_label():
raise ValueError("No label in this serie.")
# First convert months to years
year_to_cancer = self._censor_time # type: ignore
y_seq = np.zeros(max_followup, dtype=np.float64)
y = int((year_to_cancer < max_followup) and self._label) # type: ignore
if y:
y_seq[year_to_cancer:] = 1
else:
year_to_cancer = min(year_to_cancer, max_followup - 1)
y_mask = np.array(
[1] * (year_to_cancer + 1) + [0] * (max_followup - (year_to_cancer + 1)),
dtype=np.float64,
)
return Label(y=y, y_seq=y_seq, y_mask=y_mask, censor_time=year_to_cancer)
def get_raw_images(self) -> List[np.ndarray]:
"""
Load raw images from serie
Returns
-------
List[np.ndarray]
List of CT slices of shape (1, C, H, W)
"""
loader = get_sample_loader("test", self._args, apply_augmentations=False)
input_dicts = [loader.get_image(path) for path in self._meta.paths]
images = [i["input"] for i in input_dicts]
return images
@functools.lru_cache
def get_volume(self) -> torch.Tensor:
"""
Load loaded 3D CT volume
Returns
-------
torch.Tensor
CT volume of shape (1, C, N, H, W)
"""
input_dicts = [
self._loader.get_image(path) for path in self._meta.paths
]
x = torch.cat([i["input"].unsqueeze(0) for i in input_dicts], dim=0)
# Convert from (T, C, H, W) to (C, T, H, W)
x = x.permute(1, 0, 2, 3)
x = tio.ScalarImage(
affine=torch.diag(self._meta.voxel_spacing),
tensor=x.permute(0, 2, 3, 1),
)
x = self.resample_transform(x)
x = self.padding_transform(x)
x = x.data.permute(0, 3, 1, 2)
x.unsqueeze_(0)
return x
def _load_metadata(self, paths, voxel_spacing, file_type):
"""Extract metadata from dicom files efficiently
Parameters
----------
`paths` : List[str]
List of paths to dicom files
`voxel_spacing`: Optional[List[float]], optional
The voxel spacing associated with input CT
as (row spacing, col spacing, slice thickness)
`file_type` : Literal['png', 'dicom']
File type of CT slices
Returns
-------
Tuple[list]
slice_positions: list of indices for dicoms along z-axis
"""
if file_type == "dicom":
slice_positions = []
processed_paths = []
for path in paths:
dcm = pydicom.dcmread(path, stop_before_pixels=True)
processed_paths.append(path)
slice_positions.append(float(dcm.ImagePositionPatient[-1]))
processed_paths, slice_positions = order_slices(
processed_paths, slice_positions
)
thickness = float(dcm.SliceThickness)
pixel_spacing = list(map(float, dcm.PixelSpacing))
manufacturer = dcm.Manufacturer
voxel_spacing = torch.tensor(pixel_spacing + [thickness, 1])
elif file_type == "png":
processed_paths = paths
slice_positions = list(range(len(paths)))
thickness = voxel_spacing[-1] if voxel_spacing is not None else None
pixel_spacing = []
manufacturer = ""
voxel_spacing = (
torch.tensor(voxel_spacing + [1]) if voxel_spacing is not None else None
)
meta = Meta(
paths=processed_paths,
thickness=thickness,
pixel_spacing=pixel_spacing,
manufacturer=manufacturer,
slice_positions=slice_positions,
voxel_spacing=voxel_spacing,
)
return meta
def _load_args(self, file_type):
"""
Load default args required for a single Serie volume
Parameters
----------
file_type : Literal['png', 'dicom']
File type of CT slices
Returns
-------
Namespace
args with preset values
"""
args = Namespace(
**{
"img_size": [256, 256],
"img_mean": [128.1722],
"img_std": [87.1849],
"num_images": 200,
"img_file_type": file_type,
"num_chan": 3,
"cache_path": None,
"use_annotations": False,
"fix_seed_for_multi_image_augmentations": True,
"slice_thickness_filter": 5,
}
)
return args
def _check_valid(self, args):
"""
Check if serie is acceptable:
Parameters
----------
`args` : Namespace
manually set args used to develop model
Raises
------
ValueError if:
- serie doesn't have a label, OR
- slice thickness is too big
"""
if self._meta.thickness is None:
raise ValueError("slice thickness not found")
if self._meta.thickness > args.slice_thickness_filter:
raise ValueError(
f"slice thickness {self._meta.thickness} is greater than {args.slice_thickness_filter}."
)
if self._meta.voxel_spacing is None:
raise ValueError("voxel spacing either not set or not found in DICOM")