Debian Codegraph @

dicompylercore/dose.py

raw symbols SCIP
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3 # dose.py
4 """Routines to access and modify DICOM RT Dose."""
5 # Copyright (c) 2009-2016 Aditya Panchal
6 # Copyright (c) 2019-2020 Dan Cutright
7 # This file is part of dicompyler-core, released under a BSD license.
8 # See the file license.txt included with this distribution, also
9 # available at https://github.com/dicompyler/dicompyler-core/
10 #
11 # This code was adapted from dicom_dose_sum.py from DVH Analytics:
12 # https://github.com/cutright/DVH-Analytics/
13
14 from copy import deepcopy
15 import numpy as np
16 from dicompylercore import dicomparser
17 from pydicom.uid import generate_uid
18 from pydicom.datadict import dictionary_VR, keyword_dict
19 from dicompylercore.config import (
20 dicompyler_uid_prefix_rtdose,
21 mpl_available,
22 scipy_available,
23 )
24 from datetime import datetime
25 from pydicom.sequence import Sequence
26 from pydicom.dataset import Dataset
27 from warnings import warn
28
29 if scipy_available:
30 from scipy.ndimage import map_coordinates
31
32
33 class DoseGrid:
34 """Class that stores DICOM-RT dose grids, performs addition/scaling."""
35
36 def __init__(
37 self,
38 rt_dose,
39 order=1,
40 mode="constant",
41 cval=0.0,
42 ):
43 """ Initialization of a DoseGrid from a DICOM-RT Dose file or dataset.
44
45 Parameters
46 ----------
47 rt_dose : pydicom Dataset or filename
48 DICOM RT Dose used to determine the structure dose grid data.
49 order : int, optional
50 The order of the spline interpolation (if needed), default is 1.
51 The order has to be in the range 0-5.
52 0: the nearest grid point, 1: trilinear, 2 to 5: spline
53 See scipy.ndimage.map_coordinates documentation for more details
54 mode : 'constant' or 'nearest', optional
55 The mode parameter determines how the other dose grid is extended
56 beyond its boundaries. Default is ``'constant'``. Behavior for
57 these values is as follows:
58
59 ``'constant'`` (k k k k | a b c d | k k k k)
60 The other dose grid is extended by filling all values beyond
61 the edge with the same constant value, defined by the cval
62 parameter.
63 ``'nearest'`` (a a a a | a b c d | d d d d)
64 The input is extended by replicating the last pixel.
65
66 Additional modes are available, see scipy.ndimage.map_coordinates
67 documentation for more details.
68 cval : scalar, optional
69 Value to fill past edges of input if mode is ‘constant’.
70 Default is 0.0.
71 """
72
73 self.ds = dicomparser.DicomParser(rt_dose).ds
74
75 self.interp_param = {"order": order, "mode": mode, "cval": cval}
76
77 self.summation_type = None
78 self.sop_class_uid = getattr(self.ds, 'SOPClassUID', '')
79 self.sop_instance_uid = getattr(self.ds, 'SOPInstanceUID', '')
80 self.other_sop_class_uid = None
81 self.other_sop_instance_uid = None
82
83 if self.ds.Modality == "RTDOSE":
84 self.x_axis = (
85 np.arange(self.ds.Columns) * self.ds.PixelSpacing[0]
86 + self.ds.ImagePositionPatient[0]
87 )
88 self.y_axis = (
89 np.arange(self.ds.Rows) * self.ds.PixelSpacing[1]
90 + self.ds.ImagePositionPatient[1]
91 )
92 self.z_axis = (
93 np.array(self.ds.GridFrameOffsetVector)
94 + self.ds.ImagePositionPatient[2]
95 )
96
97 # x and z are swapped in the pixel_array
98 pixel_array = self.ds.pixel_array * self.ds.DoseGridScaling
99 self.dose_grid = np.swapaxes(pixel_array, 0, 2)
100 else:
101 raise AttributeError(
102 "The DoseGrid class requires an RTDOSE file or dataset. "
103 "%s was detected" % self.ds.Modality
104 )
105
106 ####################################################
107 # Basic properties
108 ####################################################
109 @property
110 def shape(self):
111 """Get the x, y, z dimensions of the dose grid"""
112 return (
113 self.ds.Columns,
114 self.ds.Rows,
115 len(self.ds.GridFrameOffsetVector),
116 )
117
118 @property
119 def axes(self):
120 """Get the x, y, z axes of the dose grid (in mm)"""
121 return [self.x_axis, self.y_axis, self.z_axis]
122
123 @property
124 def scale(self):
125 """Get the dose grid resolution (xyz)"""
126 diffs = np.diff(self.ds.GridFrameOffsetVector)
127 if not np.all(np.isclose(diffs, [diffs[0]]*len(diffs))):
128 raise NotImplementedError(
129 "Non-uniform GridFrameOffsetVector detected. Interpolated "
130 "summation of non-uniform dose-grid scales is not supported."
131 )
132 return np.array(
133 [
134 self.ds.PixelSpacing[0],
135 self.ds.PixelSpacing[1],
136 self.ds.GridFrameOffsetVector[1]
137 - self.ds.GridFrameOffsetVector[0],
138 ]
139 )
140
141 @property
142 def offset(self):
143 """Get the coordinates of the dose grid origin (mm)"""
144 return np.array(self.ds.ImagePositionPatient, dtype="float")
145
146 @property
147 def max_boundary_dose(self):
148 """Get the max boundary dose"""
149 return max_boundary_value(self.dose_grid)
150
151 @property
152 def max_boundary_relative_dose(self):
153 return self.max_boundary_dose / np.max(self.dose_grid)
154
155 ####################################################
156 # Tools
157 ####################################################
158 def __add__(self, other):
159 """Overload + operator to sum this dose grid with the other dose grid
160
161 Parameters
162 ----------
163 other : DoseGrid
164 Another DoseGrid object.
165 """
166 new = deepcopy(self)
167 new.add(other)
168 return new
169
170 def __mul__(self, factor):
171 """Overload * operator to scale this dose grid by the provided factor
172
173 Parameters
174 ----------
175 factor : int, float
176 Scale the dose grid by this value.
177 """
178 new = deepcopy(self)
179 new.multiply(factor)
180 return new
181
182 def __rmul__(self, factor):
183 return self.__mul__(factor)
184
185 def multiply(self, factor):
186 """
187 Scale the dose grid.
188
189 Parameters
190 ----------
191 factor : int, float
192 Multiply the dose grid by this factor.
193 """
194
195 if factor < 0:
196 raise NotImplementedError("Negative doses are not supported.")
197
198 self.dose_grid *= factor
199 self.dose_grid_post_processing()
200
201 def dose_grid_post_processing(self, other=None):
202 """Set the pixel data and store UIDs from other DoseGrid"""
203 self.set_pixel_data()
204 if hasattr(self.ds, "DVHSequence"):
205 del self.ds.DVHSequence
206 if other is not None:
207 self.other_sop_class_uid = other.sop_class_uid
208 self.other_sop_instance_uid = other.sop_instance_uid
209
210 def is_coincident(self, other):
211 """Check dose grid spatial coincidence.
212
213 Parameters
214 ----------
215 other : DoseGrid
216 Another DoseGrid object.
217 """
218 return (
219 self.ds.PixelSpacing == other.ds.PixelSpacing
220 and self.ds.ImagePositionPatient == other.ds.ImagePositionPatient
221 and self.ds.pixel_array.shape == other.ds.pixel_array.shape
222 and self.ds.GridFrameOffsetVector == other.ds.GridFrameOffsetVector
223 )
224
225 def set_pixel_data(self):
226 """Update the PixelData with the current dose_grid"""
227 self.ds.BitsAllocated = 32
228 self.ds.BitsStored = 32
229 self.ds.HighBit = 31
230 self.ds.DoseGridScaling = (
231 np.max(self.dose_grid) / np.iinfo(np.uint32).max
232 )
233 pixel_data = (
234 np.swapaxes(self.dose_grid, 0, 2) / self.ds.DoseGridScaling
235 )
236 self.ds.PixelData = np.uint32(pixel_data).tobytes()
237
238 def save_dcm(self, file_path):
239 """Save the pydicom.FileDataset to file"""
240 self.update_dicom_tags()
241 self.ds.save_as(file_path)
242
243 def get_ijk_points(self, other_axes):
244 """Convert axes from another DoseGrid into ijk of this DoseGrid.
245
246 Parameters
247 ----------
248 other_axes : list
249 The x, y, and z axis arrays.
250
251 Returns
252 -------
253 np.vstack
254 Array of other_axes in this ijk space.
255 """
256 ijk_axes = [
257 (np.array(axis) - self.offset[a]) / self.scale[a]
258 for a, axis in enumerate(other_axes)
259 ]
260 j, i, k = np.meshgrid(ijk_axes[1], ijk_axes[0], ijk_axes[2])
261 return np.vstack((i.ravel(), j.ravel(), k.ravel()))
262
263 ####################################################
264 # Dose Summation
265 ####################################################
266 def add(self, other, force=False):
267 """
268 Add another dose grid to this dose grid, with interpolation if needed
269
270 Parameters
271 ----------
272 other : DoseGrid
273 Another DoseGrid object.
274 force : bool
275 Set to True to ignore differences in DoseSummationType, DoseType,
276 DoseUnits, ImageOrientationPatient
277 """
278
279 attrs = [
280 "DoseSummationType",
281 "DoseType",
282 "DoseUnits",
283 "ImageOrientationPatient",
284 ]
285 attr_check = [
286 validate_attr_equality(self.ds, other.ds, attr) for attr in attrs
287 ]
288 if not force and not all(attr_check):
289 mismatches = [
290 attr for i, attr in enumerate(attrs) if attr_check[i]
291 ]
292 raise NotImplementedError(
293 "Dose summation of dose grids with these mismatched "
294 "attributes is not recommended: %s. Use "
295 "DoseGrid.add(other, force=True) to ignore"
296 % ",".join(mismatches)
297 )
298
299 if self.is_coincident(other):
300 self._direct_sum(other)
301 else:
302 if not scipy_available:
303 raise ImportError(
304 "scipy must be installed to perform interpolated dose sum."
305 )
306 self._interp_sum(other)
307
308 def _direct_sum(self, other):
309 """Directly sum two coincident dose grids
310
311 Parameters
312 ----------
313 other: DoseGrid
314 Another DoseGrid object.
315 """
316 self.dose_grid += other.dose_grid
317 self.summation_type = "DIRECT"
318
319 self.dose_grid_post_processing(other)
320
321 def _interp_sum(self, other):
322 """
323 Interpolate the other dose grid to this dose grid's axes,
324 then perform direct summation
325
326 Parameters
327 ----------
328 other: DoseGrid
329 Another DoseGrid object.
330 """
331
332 self.dose_grid += self.interp_entire_grid(other)
333 self.summation_type = "INTERPOLATED"
334
335 self.dose_grid_post_processing(other)
336
337 def interp_entire_grid(self, other):
338 """
339 Interpolate the other dose grid to this dose grid's axes in one
340 operation
341
342 Parameters
343 ----------
344 other: DoseGrid
345 Another DoseGrid object.
346
347 Returns
348 -------
349 np.array
350 The other dose grid interpolated to this dose grid's axes
351 """
352 return map_coordinates(
353 input=other.dose_grid,
354 coordinates=other.get_ijk_points(self.axes),
355 **self.interp_param
356 ).reshape(self.shape)
357
358 def update_dicom_tags(self):
359 """Update DICOM UIDs, Content Date/Time, and Dose Comment"""
360
361 # Store the source SOPClassUID and SOPInstanceUID
362 seq_data = {
363 "ReferencedSOPClassUID": self.sop_class_uid,
364 "ReferencedSOPInstanceUID": self.sop_instance_uid,
365 }
366 add_dicom_sequence(self.ds, "ReferencedInstanceSequence", seq_data)
367
368 if self.other_sop_class_uid is not None:
369 seq_data = {
370 "ReferencedSOPClassUID": self.other_sop_class_uid,
371 "ReferencedSOPInstanceUID": self.other_sop_instance_uid,
372 }
373 add_dicom_sequence(self.ds, "ReferencedInstanceSequence", seq_data)
374
375 # Create a new SOPInstanceUID
376 set_dicom_tag_value(
377 self.ds,
378 "SOPInstanceUID",
379 generate_uid(prefix=dicompyler_uid_prefix_rtdose),
380 )
381
382 # Store the dose summation type in the DoseComment tag
383 if self.summation_type:
384 set_dicom_tag_value(
385 self.ds, "DoseComment", "%s SUMMATION" % self.summation_type
386 )
387
388 # Update the Date and Time tags
389 now = datetime.now()
390 set_dicom_tag_value(self.ds, "ContentDate", now.strftime("%Y%m%d"))
391 set_dicom_tag_value(self.ds, "ContentTime", now.strftime("%H%M%S"))
392
393 def show(self, z=None):
394 """Show the dose grid using Matplotlib if present.
395
396 Parameters
397 ----------
398 z : float, optional
399 slice position to display initially, by default None
400
401 """
402 if not mpl_available:
403 raise ImportError(
404 "Matplotlib could not be loaded. Install and try again.")
405 return self
406 import matplotlib.pyplot as plt
407 from matplotlib.widgets import Slider
408
409 # Extract the list of planes (z) from the dose grid
410 planes = (
411 np.array(self.ds.GridFrameOffsetVector)
412 * self.ds.ImageOrientationPatient[0]
413 * self.ds.ImageOrientationPatient[4]
414 ) + self.ds.ImagePositionPatient[2]
415
416 # Set up the plot
417 fig = plt.figure()
418 ax = fig.add_subplot(111)
419 rtdose = dicomparser.DicomParser(self.ds)
420
421 # Get the middle slice if the z is not provided
422 z = planes[planes.size // 2] if z is None else z
423 zplane = rtdose.GetDoseGrid(z) * self.ds.DoseGridScaling
424 # Flag to invert slider min/max if GFOV is decreasing (i.e. FFS)
425 reverse = planes[0] > planes[-1]
426 im = ax.imshow(zplane, cmap="jet",)
427
428 # Create a slider to change the (z)
429 axslice = fig.add_axes([0.34, 0.01, 0.50, 0.02])
430 slider = Slider(
431 ax=axslice,
432 label="Slice Position (mm):",
433 valmin=planes[-1] if reverse else planes[0],
434 valmax=planes[0] if reverse else planes[-1],
435 valinit=z,
436 valstep=np.diff(planes)[0],
437 )
438
439 def updateslice(z):
440 """Update the data to show on the plot."""
441 im.set_data(rtdose.GetDoseGrid(z) * self.ds.DoseGridScaling)
442 plt.draw()
443
444 slider.on_changed(updateslice)
445 plt.show()
446 return self
447
448
449 def set_dicom_tag_value(ds, tag, value):
450 """Set or update a DICOM tag value in the pydicom dataset.
451
452 Parameters
453 ----------
454 ds : pydicom Dataset
455 The pydicom dataset for the tag to be added/updated to.
456 tag : str, int or tuple
457 DICOM tag or keyword to be added.
458 value : any
459 New value for the tag's element.
460 """
461 try:
462 ds[tag].value = value
463 except KeyError:
464 if tag in keyword_dict: # Keyword provided rather than int or tuple
465 tag = keyword_dict[tag]
466 ds.add_new(tag, dictionary_VR(tag), value)
467
468
469 def add_dicom_sequence(ds, seq_keyword, data_set_dict):
470 """Add a sequence to a data set.
471
472 Parameters
473 ----------
474 ds : pydicom Dataset
475 The pydicom dataset for the sequence to be added to.
476 seq_keyword : str
477 The DICOM keyword for the sequence.
478 data_set_dict : dict
479 Dictionary of tags and values for the sequence element.
480 """
481 seq_ds = Dataset()
482 for tag, value in data_set_dict.items():
483 set_dicom_tag_value(seq_ds, tag, value)
484
485 if hasattr(ds, seq_keyword):
486 getattr(ds, seq_keyword).append(seq_ds)
487 else:
488 setattr(ds, seq_keyword, Sequence([seq_ds]))
489
490
491 def validate_attr_equality(obj_1, obj_2, attr):
492 """Assess the equality of the provided attr between two objects.
493 Send warning if unequal.
494
495 Parameters
496 ----------
497 obj_1 : object
498 Any object with an `attr` attribute that is comparable by !=
499 obj_2 : object
500 Any object with an `attr` attribute that is comparable by !=
501 attr : str
502 The attribute to be compared between obj_1 and obj_2
503 """
504 val_1 = getattr(obj_1, attr)
505 val_2 = getattr(obj_2, attr)
506 if val_1 != val_2:
507 warn("Different %s values detected:\n%s\n%s" % (attr, val_1, val_2))
508 return False
509 return True
510
511
512 def max_boundary_value(arr):
513 """Get the greatest value on the boundary of a 3D numpy array
514
515 Parameters
516 ----------
517 arr : numpy.array
518 Any 3-dimensional array-like object
519
520 Returns
521 -------
522 float
523 Maximum value along any side of the input array
524 """
525 return np.max(
526 [
527 np.max([np.max(arr[i, :, :]) for i in [0, -1]]),
528 np.max([np.max(arr[:, j, :]) for j in [0, -1]]),
529 np.max([np.max(arr[:, :, k]) for k in [0, -1]]),
530 ]
531 )