Debian Codegraph @

dicompylercore/dicomparser.py

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