Debian Codegraph @

dicompylercore/dicomparser.py

raw symbols ◀ ▶
Source reconstructed at patch state 0 of 2 — not the installed (fully patched) source.
2 Debian patches touch this file
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3 # dicomparser.py
4 """Class that parses and returns formatted DICOM RT data."""
5 # Copyright (c) 2009-2016 Aditya Panchal
6 # Copyright (c) 2009-2010 Roy Keyes
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
12 import logging
13 import numpy as np
14 try:
15 from pydicom.dicomio import read_file
16 from pydicom.dataset import Dataset, validate_file_meta
17 from pydicom.pixel_data_handlers.util import pixel_dtype
18 except ImportError:
19 from dicom import read_file
20 from dicom.dataset import Dataset
21 import random
22 from numbers import Number
23 from six import PY2, iterkeys, string_types, BytesIO
24 from six.moves import range
25 from dicompylercore import dvh, util
26 from dicompylercore.config import pil_available, shapely_available
27
28 if pil_available:
29 from PIL import Image
30 if shapely_available:
31 from shapely.geometry import Polygon
32
33 logger = logging.getLogger('dicompylercore.dicomparser')
34
35
36 class DicomParser:
37 """Class to parse DICOM / DICOM RT files."""
38
39 def __init__(self, dataset, memmap_pixel_array=False):
40 """Initialize DicomParser from a pydicom Dataset or DICOM file.
41
42 Parameters
43 ----------
44 dataset : pydicom Dataset or filename
45 pydicom dataset object or DICOM file location
46 memmap_pixel_array : bool, optional
47 Enable pixel array access via memory mapping, by default False
48
49 Raises
50 ------
51 AttributeError
52 Raised if SOPClassUID is not present in the pydicom Dataset
53 AttributeError
54 Raised if the DICOM file or pydicom Dataset cannot be read
55 """
56 self.memmap_pixel_array = memmap_pixel_array
57 if isinstance(dataset, Dataset):
58 self.ds = dataset
59 elif isinstance(dataset, (string_types, BytesIO)):
60 try:
61 with open(dataset, "rb") as fp:
62 self.ds = read_file(fp, defer_size=100, force=True,
63 stop_before_pixels=memmap_pixel_array)
64 if memmap_pixel_array:
65 self.offset = fp.tell() + 8
66 except Exception:
67 # Raise the error for the calling method to handle
68 raise
69 else:
70 # Sometimes DICOM files may not have headers,
71 # but they should always have a SOPClassUID
72 # to declare what type of file it is.
73 # If the file doesn't have a SOPClassUID,
74 # then it probably isn't DICOM.
75 if "SOPClassUID" not in self.ds:
76 raise AttributeError
77 else:
78 raise AttributeError
79
80 # Fix dataset file_meta if incorrect
81 try:
82 validate_file_meta(self.ds.file_meta)
83 except ValueError:
84 logger.debug('Fixing invalid File Meta for ' +
85 str(self.ds.SOPInstanceUID))
86 self.ds.fix_meta_info()
87
88 # Remove the PixelData attribute if it is not set.
89 # i.e. RTStruct does not contain PixelData and its presence can confuse
90 # the parser
91 if "PixelData" in self.ds and self.ds.PixelData is None:
92 delattr(self.ds, 'PixelData')
93 if memmap_pixel_array:
94 self.filename = dataset
95 self.pixel_array = self.get_pixel_array
96 else:
97 if "PixelData" in self.ds:
98 self.pixel_array = self.ds.pixel_array
99
100 # ====================== SOP Class and Instance Methods ======================
101
102 def GetSOPClassUID(self):
103 """Determine the SOP Class UID of the current file."""
104 uid = getattr(self.ds, 'SOPClassUID', None)
105
106 if (uid == '1.2.840.10008.5.1.4.1.1.481.2'):
107 return 'rtdose'
108 elif (uid == '1.2.840.10008.5.1.4.1.1.481.3'):
109 return 'rtss'
110 elif (uid == '1.2.840.10008.5.1.4.1.1.481.5'):
111 return 'rtplan'
112 elif (uid == '1.2.840.10008.5.1.4.1.1.2'):
113 return 'ct'
114 else:
115 return None
116
117 def GetSOPInstanceUID(self):
118 """Determine the SOP Class UID of the current file."""
119 return getattr(self.ds, 'SOPInstanceUID', None)
120
121 def GetStudyInfo(self):
122 """Return the study information of the current file."""
123 return {'description': getattr(self.ds, 'StudyDescription',
124 'No description'),
125 'date': getattr(self.ds, 'StudyDate', None),
126 'time': getattr(self.ds, 'StudyTime', None),
127 'id': getattr(self.ds, 'StudyInstanceUID',
128 str(random.randint(0, 65535)))}
129
130 def GetSeriesDateTime(self):
131 """Return the series date/time information."""
132 dt = {'date': getattr(self.ds, 'SeriesDate', None),
133 'time': getattr(self.ds, 'SeriesTime', None)}
134
135 if dt['date'] is None:
136 dt['date'] = getattr(self.ds, 'InstanceCreationDate', None)
137 if dt['time'] is None:
138 dt['time'] = getattr(self.ds, 'InstanceCreationTime', None)
139
140 return dt
141
142 def GetSeriesInfo(self):
143 """Return the series information of the current file."""
144 series = {'description': getattr(self.ds, 'SeriesDescription',
145 'No description'),
146 'id': getattr(self.ds, 'SeriesInstanceUID', None),
147 'study': getattr(self.ds, 'SeriesInstanceUID', None),
148 'referenceframe': getattr(self.ds, 'FrameOfReferenceUID',
149 str(random.randint(0, 65535))),
150 'modality': getattr(self.ds, 'Modality', 'OT')}
151 series.update(self.GetSeriesDateTime())
152
153 series['study'] = getattr(self.ds, 'StudyInstanceUID', series['study'])
154
155 return series
156
157 def GetReferencedSeries(self):
158 """Return the SOP Class UID of the referenced series."""
159 if "ReferencedFrameOfReferenceSequence" in self.ds:
160 frame = self.ds.ReferencedFrameOfReferenceSequence
161 if "RTReferencedStudySequence" in frame[0]:
162 study = frame[0].RTReferencedStudySequence[0]
163 if "RTReferencedSeriesSequence" in study:
164 if "SeriesInstanceUID" in \
165 study.RTReferencedSeriesSequence[0]:
166 series = study.RTReferencedSeriesSequence[0]
167 return series.SeriesInstanceUID
168 else:
169 return ''
170
171 def GetFrameOfReferenceUID(self):
172 """Determine the Frame of Reference UID of the current file."""
173 if 'FrameOfReferenceUID' in self.ds:
174 # Some Files contain a Ref FoR but do not contain an FoR themselves
175 if not self.ds.FrameOfReferenceUID == '':
176 return self.ds.FrameOfReferenceUID
177 if 'ReferencedFrameOfReferenceSequence' in self.ds:
178 return self.ds.ReferencedFrameOfReferenceSequence[
179 0].FrameOfReferenceUID
180 else:
181 return ''
182
183 def GetReferencedStructureSet(self):
184 """Return the SOP Class UID of the referenced structure set."""
185 if "ReferencedStructureSetSequence" in self.ds:
186 return self.ds.ReferencedStructureSetSequence[
187 0].ReferencedSOPInstanceUID
188 else:
189 return ''
190
191 def GetReferencedRTPlan(self):
192 """Return the SOP Class UID of the referenced RT plan."""
193 if "ReferencedRTPlanSequence" in self.ds:
194 return self.ds.ReferencedRTPlanSequence[0].ReferencedSOPInstanceUID
195 else:
196 return ''
197
198 def GetDemographics(self):
199 """Return the patient demographics from a DICOM file."""
200 # Set up some sensible defaults for demographics
201 patient = {'name': 'None',
202 'id': 'None',
203 'birth_date': None,
204 'gender': 'Other'}
205 if 'PatientName' in self.ds:
206 if PY2:
207 self.ds.decode()
208 name = self.ds.PatientName
209 patient['name'] = str(name)
210 patient['given_name'] = name.given_name
211 patient['middle_name'] = name.middle_name
212 patient['family_name'] = name.family_name
213 if 'PatientID' in self.ds:
214 patient['id'] = self.ds.PatientID
215 if 'PatientSex' in self.ds:
216 if (self.ds.PatientSex == 'M'):
217 patient['gender'] = 'M'
218 elif (self.ds.PatientSex == 'F'):
219 patient['gender'] = 'F'
220 else:
221 patient['gender'] = 'O'
222 if 'PatientBirthDate' in self.ds:
223 if len(self.ds.PatientBirthDate):
224 patient['birth_date'] = str(self.ds.PatientBirthDate)
225
226 return patient
227
228 # =============================== Image Methods ===============================
229
230 def GetImageData(self):
231 """Return the image data from a DICOM file."""
232 data = {}
233
234 if 'ImagePositionPatient' in self.ds:
235 data['position'] = self.ds.ImagePositionPatient
236 if 'ImageOrientationPatient' in self.ds:
237 data['orientation'] = self.ds.ImageOrientationPatient
238 if 'PixelSpacing' in self.ds:
239 data['pixelspacing'] = self.ds.PixelSpacing
240 else:
241 data['pixelspacing'] = [1, 1]
242 data['rows'] = self.ds.Rows
243 data['columns'] = self.ds.Columns
244 data['samplesperpixel'] = self.ds.SamplesPerPixel
245 data['photometricinterpretation'] = self.ds.PhotometricInterpretation
246 data['littlendian'] = \
247 self.ds.file_meta.TransferSyntaxUID.is_little_endian
248 if 'PatientPosition' in self.ds:
249 data['patientposition'] = self.ds.PatientPosition
250 data['frames'] = self.GetNumberOfFrames()
251
252 return data
253
254 def GetPixelArray(self):
255 """Generate a memory mapped numpy accessor to the pixel array."""
256 if self.memmap_pixel_array is False:
257 return self.pixel_array
258 data = self.GetImageData()
259 filename = self.filename
260 dtype = pixel_dtype(self.ds)
261 offset = self.offset
262 frames = int(data['frames'])
263 shape = (int(self.GetNumberOfFrames()),
264 data['rows'], data['columns']) if frames > 1 \
265 else (data['rows'], data['columns'])
266
267 def get_pixel_array(filename, dtype, offset, shape):
268 array = np.memmap(
269 filename,
270 dtype=dtype,
271 mode="r",
272 offset=offset,
273 shape=shape
274 )
275 yield array
276 del array
277 return list(get_pixel_array(filename, dtype, offset, shape))[0]
278
279 get_pixel_array = property(GetPixelArray)
280
281 def GetImageLocation(self):
282 """Calculate the location of the current image slice."""
283 ipp = self.ds.ImagePositionPatient
284 iop = self.ds.ImageOrientationPatient
285
286 normal = []
287 normal.append(iop[1] * iop[5] - iop[2] * iop[4])
288 normal.append(iop[2] * iop[3] - iop[0] * iop[5])
289 normal.append(iop[0] * iop[4] - iop[1] * iop[3])
290
291 loc = 0
292 for i in range(0, len(normal)):
293 loc += normal[i] * ipp[i]
294
295 # The image location is inverted for Feet First images
296 if 'PatientPosition' in self.ds:
297 if ('ff' in self.ds.PatientPosition.lower()):
298 loc = loc * -1
299
300 return loc
301
302 def GetImageOrientationType(self):
303 """Get the orientation of the current image slice."""
304 if 'ImageOrientationPatient' in self.ds:
305 iop = np.array(self.ds.ImageOrientationPatient)
306
307 orientations = [
308 ["SA", np.array([1, 0, 0, 0, 1, 0])], # supine axial
309 ["PA", np.array([-1, 0, 0, 0, -1, 0])], # prone axial
310 ["SS", np.array([0, 1, 0, 0, 0, -1])], # supine sagittal
311 ["PS", np.array([0, -1, 0, 0, 0, -1])], # prone sagittal
312 ["SC", np.array([1, 0, 0, 0, 0, -1])], # supine coronal
313 ["PC", np.array([-1, 0, 0, 0, 0, -1])] # prone coronal
314 ]
315
316 for o in orientations:
317 if (not np.any(np.array(np.round(iop - o[1]),
318 dtype=np.int32))):
319 return o[0]
320 # Return N/A if orientation was not found or could not be determined
321 return "NA"
322
323 def GetNumberOfFrames(self):
324 """Return the number of frames in a DICOM image file."""
325 frames = 1
326 if 'NumberOfFrames' in self.ds:
327 frames = self.ds.NumberOfFrames.real
328 else:
329 if "PixelData" not in self.ds:
330 return 0
331 else:
332 if (self.pixel_array.ndim > 2):
333 if (self.ds.SamplesPerPixel == 1) and not \
334 (self.ds.PhotometricInterpretation == 'RGB'):
335 frames = self.pixel_array.shape[0]
336 return frames
337
338 def GetRescaleInterceptSlope(self):
339 """Return the rescale intercept and slope if present."""
340 intercept, slope = 0, 1
341 if ('RescaleIntercept' in self.ds and 'RescaleSlope' in self.ds):
342 intercept = self.ds.RescaleIntercept if \
343 isinstance(self.ds.RescaleIntercept, Number) else 0
344 slope = self.ds.RescaleSlope if \
345 isinstance(self.ds.RescaleSlope, Number) else 1
346
347 return intercept, slope
348
349 def GetImage(self, window=0, level=0, size=None, background=False,
350 frames=0):
351 """Return the image from a DICOM image storage file.
352
353 Parameters
354 ----------
355 window : int, optional
356 Image window, by default 0
357 level : int, optional
358 Image level or width, by default 0
359 size : tuple, optional
360 Image size tuple in pixels, by default None
361 background : bool, optional
362 Enable a black image background, by default False
363 frames : int, optional
364 If multi-frame, use requested frame to generate image, by default 0
365
366 Returns
367 -------
368 Pillow Image
369 A Pillow Image object
370 """
371 if not pil_available:
372 print("Python imaging library not available." +
373 " Cannot generate images.")
374 return
375
376 # Return a black image if the Numpy pixel array cannot be accessed
377 try:
378 self.pixel_array
379 except BaseException:
380 return Image.new('L', size)
381
382 # Samples per pixel are > 1 & RGB format
383 if (self.ds.SamplesPerPixel > 1) and \
384 (self.ds.PhotometricInterpretation == 'RGB'):
385
386 # Little Endian
387 if self.ds.file_meta.TransferSyntaxUID.is_little_endian:
388 im = Image.frombuffer('RGB', (self.ds.Columns, self.ds.Rows),
389 self.ds.PixelData, 'raw', 'RGB', 0, 1)
390 # Big Endian
391 else:
392 im = Image.fromarray(np.rollaxis(
393 self.pixel_array.transpose(), 0, 2))
394
395 # Otherwise the image is monochrome
396 else:
397 if ((window == 0) and (level == 0)):
398 window, level = self.GetDefaultImageWindowLevel()
399 # Rescale the slope and intercept of the image if present
400 intercept, slope = self.GetRescaleInterceptSlope()
401 # Get the requested frame if multi-frame
402 if (frames > 0):
403 pixel_array = self.pixel_array[frames]
404 else:
405 pixel_array = self.pixel_array
406
407 rescaled_image = pixel_array * slope + intercept
408
409 image = self.GetLUTValue(rescaled_image, window, level)
410 im = Image.fromarray(image).convert('L')
411
412 # Resize the image if a size is provided
413 if size:
414 im.thumbnail(size, Image.ANTIALIAS)
415
416 # Add a black background if requested
417 if background:
418 bg = Image.new('RGBA', size, (0, 0, 0, 255))
419 bg.paste(im, ((size[0] - im.size[0]) // 2,
420 (size[1] - im.size[1]) // 2))
421 return bg
422
423 return im
424
425 def GetDefaultImageWindowLevel(self):
426 """Determine the default window/level for the DICOM image."""
427 window, level = 0, 0
428 if ('WindowWidth' in self.ds) and ('WindowCenter' in self.ds):
429 if isinstance(self.ds.WindowWidth, float):
430 window = self.ds.WindowWidth
431 elif isinstance(self.ds.WindowWidth, list):
432 if (len(self.ds.WindowWidth) > 1):
433 window = self.ds.WindowWidth[1]
434 if isinstance(self.ds.WindowCenter, float):
435 level = self.ds.WindowCenter
436 elif isinstance(self.ds.WindowCenter, list):
437 if (len(self.ds.WindowCenter) > 1):
438 level = self.ds.WindowCenter[1]
439
440 if ((window, level) == (0, 0)):
441 wmax = 0
442 wmin = 0
443 # Rescale the slope and intercept of the image if present
444 intercept, slope = self.GetRescaleInterceptSlope()
445 pixel_array = self.pixel_array * slope + intercept
446
447 if (pixel_array.max() > wmax):
448 wmax = pixel_array.max()
449 if (pixel_array.min() < wmin):
450 wmin = pixel_array.min()
451 # Default window is the range of the data array
452 window = int(wmax - wmin)
453 # Default level is the range midpoint minus the window minimum
454 level = int(window / 2 - abs(wmin))
455 return window, level
456
457 def GetLUTValue(self, data, window, level):
458 """Apply the RGB Look-Up Table for the data and window/level value.
459
460 Parameters
461 ----------
462 data : numpy array
463 Pixel data array from pydicom dataset
464 window : float
465 Image window value
466 level : float
467 Image window level or width
468
469 Returns
470 -------
471 numpy array
472 Modified numpy array with RGB LUT applied
473 """
474 lutvalue = util.piecewise(
475 data,
476 [data <= (level - 0.5 - (window - 1) / 2),
477 data > (level - 0.5 + (window - 1) / 2)],
478 [0, 255, lambda data:
479 ((data - (level - 0.5)) / (window-1) + 0.5) *
480 (255 - 0)])
481 # Convert the resultant array to an unsigned 8-bit array to create
482 # an 8-bit grayscale LUT since the range is only from 0 to 255
483 return np.array(lutvalue, dtype=np.uint8)
484
485 def GetPatientToPixelLUT(self):
486 """Get image transformation matrix from the DICOM standard.
487
488 Referenced matrix can be found in Part 3 Section C.7.6.2.1.1
489 """
490 drow, dcol = self.ds.PixelSpacing
491
492 orientation = self.ds.ImageOrientationPatient
493 first_x, first_y, first_z = self.ds.ImagePositionPatient
494 num_cols = self.ds.Columns
495 num_rows = self.ds.Rows
496
497 # Determine which way X and Y real-world coords run
498 # X runs across columns if x_lut_index is 0
499 # limits to head-first/feet-first and prone/supine/decubitus
500 x_index = self.x_lut_index()
501
502 m = np.array(
503 [[orientation[0]*dcol, orientation[3]*drow, 0, first_x],
504 [orientation[1]*dcol, orientation[4]*drow, 0, first_y],
505 [orientation[2]*dcol, orientation[5]*drow, 0, first_z],
506 [0, 0, 0, 1]])
507
508 last_xy = np.matmul(
509 m, np.array([[num_cols-1], [num_rows-1], [0], [1]])
510 )
511 last_x, last_y = last_xy[0][0], last_xy[1][0]
512
513 if x_index == 0:
514 col_lut = np.linspace(first_x, last_x, num_cols)
515 row_lut = np.linspace(first_y, last_y, num_rows)
516 else:
517 col_lut = np.linspace(first_y, last_y, num_cols)
518 row_lut = np.linspace(first_x, last_x, num_rows)
519
520 return col_lut, row_lut
521
522 # ========================= RT Structure Set Methods =========================
523
524 def GetStructureInfo(self):
525 """Return the patient demographics from a DICOM file."""
526 structure = {}
527 structure['label'] = getattr(self.ds, 'StructureSetLabel', '')
528 structure['date'] = getattr(self.ds, 'StructureSetDate', '')
529 structure['time'] = getattr(self.ds, 'StructureSetTime', '')
530 structure['numcontours'] = len(self.ds.ROIContourSequence)
531
532 return structure
533
534 def GetStructures(self):
535 """Return a dictionary of structures (ROIs)."""
536 structures = {}
537
538 # Determine whether this is RT Structure Set file
539 if not (self.GetSOPClassUID() == 'rtss'):
540 return structures
541
542 # Locate the name and number of each ROI
543 if 'StructureSetROISequence' in self.ds:
544 for item in self.ds.StructureSetROISequence:
545 data = {}
546 number = int(item.ROINumber)
547 data['id'] = number
548 data['name'] = item.ROIName
549 logger.debug("Found ROI #%s: %s", str(number), data['name'])
550 structures[number] = data
551
552 # Determine the type of each structure (PTV, organ, external, etc)
553 if 'RTROIObservationsSequence' in self.ds:
554 for item in self.ds.RTROIObservationsSequence:
555 number = item.ReferencedROINumber
556 if number in structures:
557 structures[number]['type'] = item.RTROIInterpretedType
558
559 # The coordinate data of each ROI is stored within ROIContourSequence
560 if 'ROIContourSequence' in self.ds:
561 for roi in self.ds.ROIContourSequence:
562 number = roi.ReferencedROINumber
563
564 # Generate a random color for the current ROI
565 structures[number]['color'] = np.array((
566 random.randint(0, 255),
567 random.randint(0, 255),
568 random.randint(0, 255)), dtype=int)
569 # Get the RGB color triplet for the current ROI if it exists
570 if 'ROIDisplayColor' in roi:
571 # Make sure the color is not none
572 if not (roi.ROIDisplayColor is None):
573 color = roi.ROIDisplayColor
574 # Otherwise decode values separated by forward slashes
575 else:
576 value = roi[0x3006, 0x002a].repval
577 color = value.strip("'").split("/")
578 # Try to convert the detected value to a color triplet
579 try:
580 structures[number]['color'] = \
581 np.array(color, dtype=int)
582 # Otherwise fail and fallback on the random color
583 except Exception:
584 logger.debug(
585 "Unable to decode display color for ROI #%s",
586 str(number))
587
588 # Determine whether the ROI has any contours present
589 if 'ContourSequence' in roi:
590 structures[number]['empty'] = False
591 else:
592 structures[number]['empty'] = True
593
594 return structures
595
596 def GetStructureCoordinates(self, roi_number):
597 """Get the list of coordinates for each plane of the structure.
598
599 Parameters
600 ----------
601 roi_number : integer
602 ROI number used to index structure from RT Struct
603
604 Returns
605 -------
606 dict
607 Dict of structure coordinates sorted by slice position (z)
608 """
609 planes = {}
610 # The coordinate data of each ROI is stored within ROIContourSequence
611 if 'ROIContourSequence' in self.ds:
612 for roi in self.ds.ROIContourSequence:
613 if (roi.ReferencedROINumber == int(roi_number)):
614 if 'ContourSequence' in roi:
615 # Locate the contour sequence for each referenced ROI
616 for c in roi.ContourSequence:
617 # For each plane, initialize a new plane dict
618 plane = dict()
619
620 # Determine all the plane properties
621 plane['type'] = c.ContourGeometricType
622 plane['num_points'] = int(c.NumberOfContourPoints)
623 # Since DICOM RT Structure Set (C.8.8.6) specifies
624 # that a ContourData is stored as an flattened list
625 # of xyz triples, convert it to a unflattened list
626 # for easier parsing
627 plane['data'] = \
628 self.GetContourPoints(c.ContourData)
629
630 # Add each plane to the planes dict
631 # of the current ROI
632 z = str(round(plane['data'][0][2], 2)) + '0'
633 if z not in planes:
634 planes[z] = []
635 planes[z].append(plane)
636
637 return planes
638
639 def GetContourPoints(self, array):
640 """Unflatten a flattened list of xyz point triples.
641
642 Parameters
643 ----------
644 array : list
645 Flattened list of xyz point triples
646
647 Returns
648 -------
649 list
650 Unflattened list of xyz point triples
651 """
652 n = 3
653 return [array[i:i+n] for i in range(0, len(array), n)]
654
655 def CalculatePlaneThickness(self, planesDict):
656 """Calculate the plane thickness for each structure.
657
658 Parameters
659 ----------
660 planesDict : dict
661 Output from GetStructureCoordinates
662
663 Returns
664 -------
665 float
666 Thickness of the structure in mm
667 """
668 planes = []
669
670 # Iterate over each plane in the structure
671 for z in iterkeys(planesDict):
672 planes.append(float(z))
673 planes.sort()
674
675 # Determine the thickness
676 thickness = 10000
677 for n in range(0, len(planes)):
678 if (n > 0):
679 newThickness = planes[n] - planes[n-1]
680 if (newThickness < thickness):
681 thickness = newThickness
682
683 # If the thickness was not detected, set it to 0
684 if (thickness == 10000):
685 thickness = 0
686
687 return thickness
688
689 def CalculateStructureVolume(self, coords, thickness):
690 """Calculate the volume of the given structure.
691
692 Parameters
693 ----------
694 coords : dict
695 Coordinates of each plane of the structure
696 thickness : float
697 Thickness of the structure in mm
698
699 Returns
700 -------
701 float
702 Volume of structure in cm3
703 """
704 if not shapely_available:
705 print("Shapely library not available." +
706 " Please install to calculate.")
707 return 0
708
709 class Within:
710 def __init__(self, o):
711 self.o = o
712
713 def __lt__(self, other):
714 return self.o.within(other.o)
715
716 s = 0
717 for i, z in enumerate(sorted(coords.items())):
718 # Skip contour data if it is not CLOSED_PLANAR
719 if z[1][0]['type'] != 'CLOSED_PLANAR':
720 continue
721 polygons = []
722 contours = [[x[0:2] for x in c['data']] for c in z[1]]
723 for contour in contours:
724 p = Polygon(contour)
725 polygons.append(p)
726 # Sort polygons according whether they are contained
727 # by the previous polygon
728 if len(polygons) > 1:
729 ordered_polygons = sorted(polygons, key=Within, reverse=True)
730 else:
731 ordered_polygons = polygons
732 for ip, p in enumerate(ordered_polygons):
733 pa = 0
734 if ((i == 0) or (i == len(coords.items()) - 1)) and \
735 not (len(coords.items()) == 1):
736 pa += (p.area // 2)
737 else:
738 pa += p.area
739 # Subtract the volume if polygon is contained within the parent
740 # and is not the parent itself
741 if p.within(ordered_polygons[0]) and \
742 (p != ordered_polygons[0]):
743 s -= pa
744 else:
745 s += pa
746 vol = s * thickness / 1000
747 return vol
748
749 # ============================== RT Dose Methods ==============================
750
751 def HasDVHs(self):
752 """Return whether dose-volume histograms (DVHs) exist."""
753 if "DVHSequence" not in self.ds:
754 return False
755 else:
756 return True
757
758 def GetDVHs(self):
759 """Return cumulative dose-volume histograms (DVHs)."""
760 self.dvhs = {}
761
762 if self.HasDVHs():
763 for item in self.ds.DVHSequence:
764 # Make sure that the DVH has a referenced structure / ROI
765 if 'DVHReferencedROISequence' not in item:
766 continue
767 number = item.DVHReferencedROISequence[0].ReferencedROINumber
768 logger.debug("Found DVH for ROI #%s", str(number))
769 self.dvhs[number] = dvh.DVH.from_dicom_dvh(self.ds, number)
770
771 return self.dvhs
772
773 def GetDoseGrid(self, z=0, threshold=0.5):
774 """Return the 2d dose grid for the given slice position (mm).
775
776 Parameters
777 ----------
778 z : int, optional
779 Slice position in mm, by default 0
780 threshold : float, optional
781 Threshold in mm to determine the max difference from z
782 to the closest dose slice without using interpolation,
783 by default 0.5
784
785 Returns
786 -------
787 np.array
788 An numpy 2d array of dose points
789 """
790 # If this is a multi-frame dose pixel array,
791 # determine the offset for each frame
792 if 'GridFrameOffsetVector' in self.ds:
793 pixel_array = self.GetPixelArray()
794 z = float(z)
795 # Get the initial dose grid position (z) in patient coordinates
796 ipp = self.ds.ImagePositionPatient
797 gfov = self.ds.GridFrameOffsetVector
798 # Add the position to the offset vector to determine the
799 # z coordinate of each dose plane
800
801 z_sign = 1 if self.is_head_first_orientation() else -1
802
803 planes = (z_sign * np.array(gfov)) + ipp[2]
804 frame = -1
805 # Check to see if the requested plane exists in the array
806 if (np.amin(np.fabs(planes - z)) < threshold):
807 frame = np.argmin(np.fabs(planes - z))
808 # Return the requested dose plane, since it was found
809 if not (frame == -1):
810 return pixel_array[frame]
811 # Check if the requested plane is within the dose grid boundaries
812 elif ((z < np.amin(planes)) or (z > np.amax(planes))):
813 return np.array([])
814 # The requested plane was not found, so interpolate between planes
815 else:
816 # Determine the upper and lower bounds
817 umin = np.fabs(planes - z)
818 ub = np.argmin(umin)
819 lmin = umin.copy()
820 # Change the min value to the max so we can find the 2nd min
821 lmin[ub] = np.amax(umin)
822 lb = np.argmin(lmin)
823 # Fractional distance of dose plane between upper & lower bound
824 fz = (z - planes[lb]) / (planes[ub] - planes[lb])
825 plane = self.InterpolateDosePlanes(
826 pixel_array[ub], pixel_array[lb], fz)
827 return plane
828 else:
829 return np.array([])
830
831 def InterpolateDosePlanes(self, uplane, lplane, fz):
832 """Interpolate a dose plane between two bounding planes.
833
834 Parameters
835 ----------
836 uplane : float
837 Upper dose plane boundary in mm
838 lplane : float
839 Lower dose plane boundary in mm
840 fz : float
841 Fractional distance from the bottom to the top,
842 where the new plane is located.
843 E.g. if fz = 1, the plane is at the upper plane,
844 fz = 0, it is at the lower plane.
845
846 Returns
847 -------
848 numpy array
849 An numpy 2d array of the interpolated dose plane
850 """
851 # A simple linear interpolation
852 doseplane = fz*uplane + (1.0 - fz)*lplane
853
854 return doseplane
855
856 def is_head_first_orientation(self):
857 """Return True if self.orientation is head-first.
858
859 Raises
860 ------
861 NotImplementedError
862 Raised if orientation is not one of head/feet-first
863 and supine/prone/decubitus
864
865 Returns
866 -------
867 bool
868 True if orientation is head-first, else False
869
870
871 """
872 orientation = self.ds.ImageOrientationPatient
873 if any(
874 all(np.isclose(orientation, hf_orientation))
875 for hf_orientation in ( # noqa
876 [1, 0, 0, 0, 1, 0], # Head First Supine
877 [-1, 0, 0, 0, -1, 0], # Head First Prone
878 [0, -1, 0, 1, 0, 0], # Head First Decubitus Left
879 [0, 1, 0, -1, 0, 0] # Head First Decubitus Right
880 )
881 ):
882 return True
883 elif any(
884 all(np.isclose(orientation, ff_orientation))
885 for ff_orientation in (
886 [0, 1, 0, 1, 0, 0], # Feet First Decubitus Left
887 [0, -1, 0, -1, 0, 0], # Feet First Decubitus Right
888 [1, 0, 0, 0, -1, 0], # Feet First Prone
889 [-1, 0, 0, 0, 1, 0] # Feet First Supine
890 )
891 ):
892 return False
893 else:
894 raise NotImplementedError(
895 "Cannot calculate dose plane sign for non-standard orientation"
896 )
897
898 def x_lut_index(self):
899 """Return LUT index for real-world X direction.
900
901 Raises
902 ------
903 NotImplementedError
904 Raised if orientation is not one of head/feet-first
905 and supine/prone/decubitus
906
907 Returns
908 -------
909 X direction LUT index, matching 'lut' from GetDoseData
910 0 if real-world X across columns
911 1 if real-world X along rows
912 """
913 orientation = self.ds.ImageOrientationPatient
914 if any(
915 all(np.isclose(orientation, non_decub))
916 for non_decub in (
917 [1, 0, 0, 0, 1, 0], # Head First Supine
918 [-1, 0, 0, 0, -1, 0], # Head First Prone
919 [-1, 0, 0, 0, 1, 0], # Feet First Supine
920 [1, 0, 0, 0, -1, 0] # Feet First Prone
921 )
922 ):
923 return 0
924 elif any(
925 all(np.isclose(orientation, decub))
926 for decub in (
927 [0, -1, 0, 1, 0, 0], # Head First Decubitus Left
928 [0, 1, 0, -1, 0, 0], # Head First Decubitus Right
929 [0, 1, 0, 1, 0, 0], # Feet First Decubitus Left
930 [0, -1, 0, -1, 0, 0] # Feet First Decubitus Right
931 )
932 ):
933 return 1
934 else:
935 raise NotImplementedError(
936 "Cannot calculate X direction for non-standard orientation"
937 )
938
939 def GetIsodosePoints(self, z=0, level=100, threshold=0.5):
940 """Return dose grid points from an isodose level & slice position.
941
942 Parameters
943 ----------
944 z : int, optional
945 Slice position in mm., by default 0
946 level : int, optional
947 Isodose level in scaled form
948 (multiplied by self.ds.DoseGridScaling), by default 100
949 threshold : float, optional
950 Threshold in mm to determine the max difference
951 from z to the closest dose slice without
952 using interpolation, by default 0.5
953
954 Returns
955 -------
956 list
957 An list of tuples representing isodose points
958 """
959 plane = self.GetDoseGrid(z, threshold)
960 isodose = (plane >= level).nonzero()
961 return list(zip(isodose[1].tolist(), isodose[0].tolist()))
962
963 def GetDoseData(self):
964 """Return the dose data from a DICOM RT Dose file."""
965 data = self.GetImageData()
966 data['doseunits'] = getattr(self.ds, 'DoseUnits', '')
967 data['dosetype'] = getattr(self.ds, 'DoseType', '')
968 data['dosecomment'] = getattr(self.ds, 'DoseComment', '')
969 data['dosesummationtype'] = getattr(self.ds, 'DoseSummationType', '')
970 data['dosegridscaling'] = getattr(self.ds, 'DoseGridScaling', '')
971 dosemax = 0
972 for x in range(data["frames"]):
973 pixel_array = self.GetPixelArray()
974 newmax = pixel_array[x].max()
975 dosemax = newmax if newmax > dosemax else dosemax
976 if self.memmap_pixel_array:
977 del pixel_array
978 data['dosemax'] = float(dosemax)
979 data['lut'] = self.GetPatientToPixelLUT()
980 data['x_lut_index'] = self.x_lut_index()
981 data['fraction'] = ''
982 if "ReferencedRTPlanSequence" in self.ds:
983 plan = self.ds.ReferencedRTPlanSequence[0]
984 if "ReferencedFractionGroupSequence" in plan:
985 data['fraction'] = \
986 plan.ReferencedFractionGroupSequence[
987 0].ReferencedFractionGroupNumber
988
989 return data
990
991 def GetReferencedBeamNumber(self):
992 """Return the referenced beam number (if it exists) from RT Dose."""
993 beam = None
994 if "ReferencedRTPlanSequence" in self.ds:
995 rp = self.ds.ReferencedRTPlanSequence[0]
996 if "ReferencedFractionGroupSequence" in rp:
997 rf = rp.ReferencedFractionGroupSequence[0]
998 if "ReferencedBeamSequence" in rf:
999 if "ReferencedBeamNumber" in rf.ReferencedBeamSequence[0]:
1000 beam = \
1001 rf.ReferencedBeamSequence[0].ReferencedBeamNumber
1002
1003 return beam
1004
1005 # ============================== RT Plan Methods ==============================
1006
1007 def GetPlan(self):
1008 """Return the plan information."""
1009 self.plan = {}
1010
1011 self.plan['label'] = getattr(self.ds, 'RTPlanLabel', '')
1012 self.plan['date'] = getattr(self.ds, 'RTPlanDate', '')
1013 self.plan['time'] = getattr(self.ds, 'RTPlanTime', '')
1014 self.plan['name'] = ''
1015 self.plan['rxdose'] = 0
1016 if "DoseReferenceSequence" in self.ds:
1017 for item in self.ds.DoseReferenceSequence:
1018 if item.DoseReferenceStructureType == 'SITE':
1019 self.plan['name'] = "N/A"
1020 if "DoseReferenceDescription" in item:
1021 self.plan['name'] = item.DoseReferenceDescription
1022 if 'TargetPrescriptionDose' in item:
1023 rxdose = item.TargetPrescriptionDose * 100
1024 if (rxdose > self.plan['rxdose']):
1025 self.plan['rxdose'] = rxdose
1026 elif item.DoseReferenceStructureType == 'VOLUME':
1027 if 'TargetPrescriptionDose' in item:
1028 self.plan['rxdose'] = item.TargetPrescriptionDose * 100
1029 if (("FractionGroupSequence" in self.ds) and
1030 (self.plan['rxdose'] == 0)):
1031 fg = self.ds.FractionGroupSequence[0]
1032 if ("ReferencedBeamSequence" in fg) and \
1033 ("NumberOfFractionsPlanned" in fg):
1034 beams = fg.ReferencedBeamSequence
1035 fx = fg.NumberOfFractionsPlanned
1036 for beam in beams:
1037 if "BeamDose" in beam:
1038 self.plan['rxdose'] += beam.BeamDose * fx * 100
1039 self.plan['rxdose'] = round(self.plan['rxdose'])
1040 self.plan['brachy'] = False
1041 if ("BrachyTreatmentTechnique" in self.ds) or \
1042 ("BrachyTreatmentType" in self.ds):
1043 self.plan['brachy'] = True
1044 return self.plan
1045
1046 def GetReferencedBeamsInFraction(self, fx=0):
1047 """Return the referenced beams from the specified fraction.
1048
1049 Parameters
1050 ----------
1051 fx : int, optional
1052 FractionGroupSequence number, by default 0
1053
1054 Returns
1055 -------
1056 dict
1057 Dictionary of referenced beam data
1058 """
1059 beams = {}
1060 if ("BeamSequence" in self.ds):
1061 bdict = self.ds.BeamSequence
1062 elif ("IonBeamSequence" in self.ds):
1063 bdict = self.ds.IonBeamSequence
1064 else:
1065 return beams
1066
1067 # Obtain the beam information
1068 for b in bdict:
1069 beam = {}
1070 beam['name'] = b.BeamName if "BeamName" in b else ""
1071 beam['description'] = b.BeamDescription \
1072 if "BeamDescription" in b else ""
1073 beams[b.BeamNumber.real] = beam
1074
1075 # Obtain the referenced beam info from the fraction info
1076 if ("FractionGroupSequence" in self.ds):
1077 fg = self.ds.FractionGroupSequence[fx]
1078 if ("ReferencedBeamSequence" in fg):
1079 rb = fg.ReferencedBeamSequence
1080 nfx = fg.NumberOfFractionsPlanned
1081 for b in rb:
1082 if "BeamDose" in b:
1083 beams[b.ReferencedBeamNumber]['dose'] = \
1084 b.BeamDose * nfx * 100
1085 return beams