Debian Codegraph @

dicompylercore/dicomparser.py

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