-
Notifications
You must be signed in to change notification settings - Fork 71
/
dose.py
317 lines (244 loc) · 11.4 KB
/
dose.py
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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
# Copyright (C) 2016-2019 Matthew Jennings and Simon Biggs
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""A DICOM RT Dose toolbox"""
from pymedphys._imports import matplotlib
from pymedphys._imports import numpy as np
from pymedphys._imports import plt, pydicom, scipy
from .constants import IMAGE_ORIENTATION_MAP
from .coords import xyz_axes_from_dataset
from .rtplan import get_surface_entry_point_with_fallback, require_gantries_be_zero
from .structure import pull_structure
# pylint: disable=C0103
def zyx_and_dose_from_dataset(dataset):
x, y, z = xyz_axes_from_dataset(dataset)
coords = (z, y, x)
dose = dose_from_dataset(dataset)
return coords, dose
def dose_from_dataset(ds, set_transfer_syntax_uid=True):
r"""Extract the dose grid from a DICOM RT Dose file.
"""
if set_transfer_syntax_uid:
ds.file_meta.TransferSyntaxUID = pydicom.uid.ImplicitVRLittleEndian
dose = ds.pixel_array * ds.DoseGridScaling
return dose
def dicom_dose_interpolate(interp_coords, dicom_dose_dataset):
"""Interpolates across a DICOM dose dataset.
Parameters
----------
interp_coords : tuple(z, y, x)
A tuple of coordinates in DICOM order, z axis first, then y, then x
where x, y, and z are DICOM axes.
dose : pydicom.Dataset
An RT DICOM Dose object
"""
interp_z = np.array(interp_coords[0], copy=False)[:, None, None]
interp_y = np.array(interp_coords[1], copy=False)[None, :, None]
interp_x = np.array(interp_coords[2], copy=False)[None, None, :]
coords, dicom_dose_dataset = zyx_and_dose_from_dataset(dicom_dose_dataset)
interpolation = scipy.interpolate.RegularGridInterpolator(
coords, dicom_dose_dataset
)
try:
result = interpolation((interp_z, interp_y, interp_x))
except ValueError:
print(f"coords: {coords}")
raise
return result
def depth_dose(depths, dose_dataset, plan_dataset):
"""Interpolates dose for defined depths within a DICOM dose dataset.
Since the DICOM dose dataset is in CT coordinates the corresponding
DICOM plan is also required in order to calculate the conversion
between CT coordinate space and depth.
Currently, `depth_dose()` only supports a `dose_dataset` for which
the patient orientation is HFS and that any beams in `plan_dataset`
have gantry angle equal to 0 (head up). Depth is assumed to be
purely in the y axis direction in DICOM coordinates.
Parameters
----------
depths : numpy.ndarray
An array of depths to interpolate within the DICOM dose file. 0 is
defined as the surface of the phantom using either the
``SurfaceEntryPoint`` parameter or a combination of
``SourceAxisDistance``, ``SourceToSurfaceDistance``, and
``IsocentrePosition``.
dose_dataset : pydicom.dataset.Dataset
The RT DICOM dose dataset to be interpolated
plan_dataset : pydicom.dataset.Dataset
The RT DICOM plan used to extract surface parameters and verify gantry
angle 0 beams are used.
"""
require_patient_orientation(dose_dataset, "HFS")
require_gantries_be_zero(plan_dataset)
depths = np.array(depths, copy=False)
surface_entry_point = get_surface_entry_point_with_fallback(plan_dataset)
depth_adjust = surface_entry_point.y
y = depths + depth_adjust
x, z = [surface_entry_point.x], [surface_entry_point.z]
coords = (z, y, x)
extracted_dose = np.squeeze(dicom_dose_interpolate(coords, dose_dataset))
return extracted_dose
def profile(displacements, depth, direction, dose_dataset, plan_dataset):
"""Interpolates dose for cardinal angle horizontal profiles within a
DICOM dose dataset.
Since the DICOM dose dataset is in CT coordinates the corresponding
DICOM plan is also required in order to calculate the conversion
between CT coordinate space and depth and horizontal displacement.
Currently, `profile()` only supports a `dose_dataset` for which
the patient orientation is HFS and that any beams in `plan_dataset`
have gantry angle equal to 0 (head up). Depth is assumed to be
purely in the y axis direction in DICOM coordinates.
Parameters
----------
displacements : numpy.ndarray
An array of displacements to interpolate within the DICOM dose
file. 0 is defined in the DICOM z or x directions based either
upon the ``SurfaceEntryPoint`` or the ``IsocenterPosition``
depending on what is available within the DICOM plan file.
depth : float
The depth at which to interpolate within the DICOM dose file. 0 is
defined as the surface of the phantom using either the
``SurfaceEntryPoint`` parameter or a combination of
``SourceAxisDistance``, ``SourceToSurfaceDistance``, and
``IsocentrePosition``.
direction : str, one of ('inplane', 'inline', 'crossplane', 'crossline')
Corresponds to the axis upon which to apply the displacements.
- 'inplane' or 'inline' converts to DICOM z direction
- 'crossplane' or 'crossline' converts to DICOM x direction
dose_dataset : pydicom.dataset.Dataset
The RT DICOM dose dataset to be interpolated
plan_dataset : pydicom.dataset.Dataset
The RT DICOM plan used to extract surface and isocentre
parameters and verify gantry angle 0 beams are used.
"""
require_patient_orientation(dose_dataset, "HFS")
require_gantries_be_zero(plan_dataset)
displacements = np.array(displacements, copy=False)
surface_entry_point = get_surface_entry_point_with_fallback(plan_dataset)
depth_adjust = surface_entry_point.y
y = [depth + depth_adjust]
if direction in ("inplane", "inline"):
coords = (displacements + surface_entry_point.z, y, [surface_entry_point.x])
elif direction in ("crossplane", "crossline"):
coords = ([surface_entry_point.z], y, displacements + surface_entry_point.x)
else:
raise ValueError(
"Expected direction to be equal to one of "
"'inplane', 'inline', 'crossplane', or 'crossline'"
)
extracted_dose = np.squeeze(dicom_dose_interpolate(coords, dose_dataset))
return extracted_dose
def get_dose_grid_structure_mask(
structure_name: str,
structure_dataset: "pydicom.Dataset",
dose_dataset: "pydicom.Dataset",
):
"""Determines the 3D boolean mask defining whether or not a grid
point is inside or outside of a defined structure.
In its current implementation the dose grid and the planes upon
which the structures are defined need to be aligned. This is due to
the implementation only stepping through each structure plane and
undergoing a 2D mask on the respective dose grid. In order to
undergo a mask when the contours and dose grids do not align
inter-slice contour interpolation would be required.
For now, having two contours for the same structure name on a single
slice is also not supported.
Parameters
----------
structure_name
The name of the structure for which the mask is to be created
structure_dataset : pydicom.Dataset
An RT Structure DICOM object containing the respective
structures.
dose_dataset : pydicom.Dataset
An RT Dose DICOM object from which the grid mask coordinates are
determined.
Raises
------
ValueError
If an unsupported contour is provided or the dose grid does not
align with the structure planes.
"""
x_dose, y_dose, z_dose = xyz_axes_from_dataset(dose_dataset)
xx, yy = np.meshgrid(x_dose, y_dose)
points = np.swapaxes(np.vstack([xx.ravel(), yy.ravel()]), 0, 1)
x_structure, y_structure, z_structure = pull_structure(
structure_name, structure_dataset
)
structure_z_values = []
for item in z_structure:
item = np.unique(item)
if len(item) != 1:
raise ValueError("Only one z value per contour supported")
structure_z_values.append(item[0])
structure_z_values = np.sort(structure_z_values)
unique_structure_z_values = np.unique(structure_z_values)
if np.any(structure_z_values != unique_structure_z_values):
raise ValueError("Only one contour per slice is currently supported")
sorted_dose_z = np.sort(z_dose)
first_dose_index = np.where(sorted_dose_z == structure_z_values[0])[0][0]
for i, z_val in enumerate(structure_z_values):
dose_index = first_dose_index + i
if structure_z_values[i] != sorted_dose_z[dose_index]:
raise ValueError(
"Only contours where both, there are no gaps in the "
"z-axis of the contours, and the contour axis and dose "
"axis, are aligned are supported."
)
mask_yxz = np.zeros((len(y_dose), len(x_dose), len(z_dose)), dtype=bool)
for structure_index, z_val in enumerate(structure_z_values):
dose_index = int(np.where(z_dose == z_val)[0])
if z_structure[structure_index][0] != z_dose[dose_index]:
raise ValueError("Structure and dose indices do not align")
structure_polygon = matplotlib.path.Path(
[
(x_structure[structure_index][i], y_structure[structure_index][i])
for i in range(len(x_structure[structure_index]))
]
)
# This logical "or" here is actually in place for the case where
# there may be multiple contours on the one slice. That's not
# going to be used at the moment however, as that case is not
# yet supported in the logic above.
mask_yxz[:, :, dose_index] = mask_yxz[:, :, dose_index] | (
structure_polygon.contains_points(points).reshape(len(y_dose), len(x_dose))
)
mask_xyz = np.swapaxes(mask_yxz, 0, 1)
mask_zyx = np.swapaxes(mask_xyz, 0, 2)
return mask_zyx
def find_dose_within_structure(structure_name, structure_dataset, dose_dataset):
dose = dose_from_dataset(dose_dataset)
mask = get_dose_grid_structure_mask(structure_name, structure_dataset, dose_dataset)
return dose[mask]
def create_dvh(structure, structure_dataset, dose_dataset):
structure_dose_values = find_dose_within_structure(
structure, structure_dataset, dose_dataset
)
hist = np.histogram(structure_dose_values, 100)
freq = hist[0]
bin_edge = hist[1]
bin_mid = (bin_edge[1::] + bin_edge[:-1:]) / 2
cumulative = np.cumsum(freq[::-1])
cumulative = cumulative[::-1]
bin_mid = np.append([0], bin_mid)
cumulative = np.append(cumulative[0], cumulative)
percent_cumulative = cumulative / cumulative[0] * 100
plt.plot(bin_mid, percent_cumulative, label=structure)
plt.title("DVH")
plt.xlabel("Dose (Gy)")
plt.ylabel("Relative Volume (%)")
def require_patient_orientation(ds, patient_orientation):
if not np.array_equal(
ds.ImageOrientationPatient, np.array(IMAGE_ORIENTATION_MAP[patient_orientation])
):
raise ValueError(
"The supplied dataset has a patient "
f"orientation other than {patient_orientation}."
)