Debian Codegraph @

dicompylercore/dvhcalc.py

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3 # dvhcalc.py
4 """Calculate dose volume histogram (DVH) from DICOM RT Structure/Dose data."""
5 # Copyright (c) 2011-2018 Aditya Panchal
6 # Copyright (c) 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 from __future__ import division
12 import numpy as np
13 import numpy.ma as ma
14 import matplotlib.path
15 from dicompylercore import dvh
16 from dicompylercore.config import skimage_available
17 import collections
18 try:
19 from collections.abc import Sequence
20 except ImportError:
21 from collections import Sequence
22 import logging
23 logger = logging.getLogger('dicompylercore.dvhcalc')
24
25 if skimage_available:
26 from skimage.transform import rescale
27
28
29 def get_dvh(structure,
30 dose,
31 roi,
32 limit=None,
33 calculate_full_volume=True,
34 use_structure_extents=False,
35 interpolation_resolution=None,
36 interpolation_segments_between_planes=0,
37 thickness=None,
38 memmap_rtdose=False,
39 callback=None):
40 """Calculate a cumulative DVH in Gy from a DICOM RT Structure Set & Dose.
41
42 Parameters
43 ----------
44 structure : pydicom Dataset or filename
45 DICOM RT Structure Set used to determine the structure data.
46 dose : pydicom Dataset or filename
47 DICOM RT Dose used to determine the dose grid.
48 roi : int
49 The ROI number used to uniquely identify the structure in the structure
50 set.
51 limit : int, optional
52 Dose limit in cGy as a maximum bin for the histogram.
53 calculate_full_volume : bool, optional
54 Calculate the full structure volume including contours outside of the
55 dose grid.
56 use_structure_extents : bool, optional
57 Limit the DVH calculation to the in-plane structure boundaries.
58 interpolation_resolution : tuple or float, optional
59 Resolution in mm (row, col) to interpolate structure and dose data to.
60 If float is provided, original dose grid pixel spacing must be square.
61 interpolation_segments_between_planes : integer, optional
62 Number of segments to interpolate between structure slices.
63 thickness : float, optional
64 Structure thickness used to calculate volume of a voxel.
65 memmap_rtdose : bool, optional
66 Use memory mapping to access the pixel array of the DICOM RT Dose.
67 This reduces memory usage at the expense of increased calculation time.
68 callback : function, optional
69 A function that will be called at every iteration of the calculation.
70
71 Returns
72 -------
73 dvh.DVH
74 An instance of dvh.DVH in cumulative dose. This can be converted to
75 different formats using the attributes and properties of the DVH class.
76 """
77 from dicompylercore import dicomparser
78
79 rtss = dicomparser.DicomParser(structure)
80 rtdose = dicomparser.DicomParser(dose, memmap_pixel_array=memmap_rtdose)
81 structures = rtss.GetStructures()
82 s = structures[roi]
83 s['planes'] = rtss.GetStructureCoordinates(roi)
84 s['thickness'] = thickness if thickness else rtss.CalculatePlaneThickness(
85 s['planes'])
86
87 calcdvh = _calculate_dvh(s, rtdose, limit, calculate_full_volume,
88 use_structure_extents, interpolation_resolution,
89 interpolation_segments_between_planes,
90 callback)
91 return dvh.DVH(counts=calcdvh.histogram,
92 bins=(np.arange(0, 2) if (calcdvh.histogram.size == 1) else
93 np.arange(0, calcdvh.histogram.size + 1) / 100),
94 dvh_type='differential',
95 dose_units='Gy',
96 notes=calcdvh.notes,
97 name=s['name']).cumulative
98
99
100 def _calculate_dvh(structure,
101 dose,
102 limit=None,
103 calculate_full_volume=True,
104 use_structure_extents=False,
105 interpolation_resolution=None,
106 interpolation_segments_between_planes=0,
107 callback=None):
108 """Calculate a differential DVH for the given structure and dose grid.
109
110 Parameters
111 ----------
112 structure : dict
113 A structure (ROI) from an RT Structure Set parsed using DicomParser.
114 The dictionary must include a `thickness` key with a thickness `float`.
115 dose : DicomParser
116 A DicomParser instance of an RT Dose
117 limit : int, optional
118 Dose limit in cGy as a maximum bin for the histogram.
119 calculate_full_volume : bool, optional
120 Calculate the full structure volume including contours outside of the
121 dose grid.
122 use_structure_extents : bool, optional
123 Limit the DVH calculation to the in-plane structure boundaries.
124 interpolation_resolution : tuple or float, optional
125 Resolution in mm (row, col) to interpolate structure and dose data to.
126 If float is provided, original dose grid pixel spacing must be square.
127 interpolation_segments_between_planes : integer, optional
128 Number of segments to interpolate between structure slices.
129 callback : function, optional
130 A function that will be called at every iteration of the calculation.
131
132 Returns
133 -------
134 calcdvh: collections.namedtuple
135 A named tuple of notes and and histogram data.
136
137 Notes
138 -----
139 This is an internal function called by `get_dvh` and
140 should not be called directly.
141 """
142 calcdvh = collections.namedtuple('DVH', ['notes', 'histogram'])
143 logger.debug("Calculating DVH of %s %s", structure['id'],
144 structure['name'])
•145 planes = collections.OrderedDict(sorted(structure["planes"].items()))
146
147 # Create an empty array of bins to store the histogram in cGy
148 # only if the structure has contour data or the dose grid exists
149 if ((len(planes)) and (hasattr(dose, 'pixel_array'))):
150
151 # Get the dose and image data information
152 dd = dose.GetDoseData()
153 id = dose.GetImageData()
154
155 # Determine structure and respectively dose grid extents
156 if interpolation_resolution or use_structure_extents:
157 extents = []
158 if use_structure_extents:
159 extents = structure_extents(structure['planes'])
160 dgindexextents = dosegrid_extents_indices(extents, dd)
161 dgextents = dosegrid_extents_positions(dgindexextents, dd)
162 # Determine LUT from extents
163 if use_structure_extents:
164 dd['lut'] = \
165 (dd['lut'][0][dgindexextents[0]:dgindexextents[2]],
166 dd['lut'][1][dgindexextents[1]:dgindexextents[3]])
167 # If interpolation is enabled, generate new LUT from extents
168 if interpolation_resolution:
169 dd['lut'] = get_resampled_lut(
170 dgindexextents,
171 dgextents,
172 new_pixel_spacing=interpolation_resolution,
173 min_pixel_spacing=id['pixelspacing'])
174 dd['rows'] = dd['lut'][1].shape[0]
175 dd['columns'] = dd['lut'][0].shape[0]
176
177 # Generate a 2d mesh grid to create a polygon mask in dose coordinates
178 # Code taken from Stack Overflow Answer from Joe Kington:
179 # https://stackoverflow.com/q/3654289/74123
180 # Create vertex coordinates for each grid cell
181 x_index = dd['x_lut_index']
182 x, y = np.meshgrid(
183 np.array(dd['lut'][x_index]), np.array(dd['lut'][1-x_index])
184 )
185 x, y = x.flatten(), y.flatten()
186 dosegridpoints = np.vstack((x, y)).T
187
188 maxdose = int(dd['dosemax'] * dd['dosegridscaling'] * 100) + 1
189 # Remove values above the limit (cGy) if specified
190 if isinstance(limit, int):
191 if (limit < maxdose):
192 maxdose = limit
193 hist = np.zeros(maxdose)
194 else:
195 return calcdvh('Empty DVH', np.array([0]))
196
197 n = 0
198 notes = None
199 planedata = {}
200 # Interpolate between planes in the direction of the structure
201 if interpolation_segments_between_planes:
202 planes = interpolate_between_planes(
203 planes, interpolation_segments_between_planes)
204 # Thickness derived from total number of segments relative to original
205 structure['thickness'] = structure[
206 'thickness'] / (interpolation_segments_between_planes + 1)
207
208 # Iterate over each plane in the structure
•209 for z, plane in planes.items():
210 # Get the dose plane for the current structure plane
211 if interpolation_resolution or use_structure_extents:
212 doseplane = get_interpolated_dose(
213 dose, z, interpolation_resolution, dgindexextents)
214 else:
215 doseplane = dose.GetDoseGrid(z)
216 if doseplane.size:
217 planedata[z] = calculate_plane_histogram(plane, doseplane,
218 dosegridpoints, maxdose,
219 dd, id, structure, hist)
220 # print(f'Slice: {z}, volume: {planedata[z][1]}')
221 else:
222 # If the dose plane is not found, still perform the calculation
223 # but only use it to calculate the volume for the slice
224 if not calculate_full_volume:
225 logger.warning('Dose plane not found for %s. Contours' +
226 ' not used for volume calculation.', z)
227 notes = 'Dose grid does not encompass every contour.' + \
228 ' Volume calculated within dose grid.'
229 else:
230 origin_z = id['position'][2]
231 logger.warning('Dose plane not found for %s.' +
232 ' Using %s to calculate contour volume.',
233 z, origin_z)
234 # Create a dummy dose grid with the correct size.
235 # calculate_plane_histogram() and its methods provide the
236 # volume calc needed, but do so as part of DVH calc,
237 # which requires a dose grid
238 dummy_dose = dose.GetDoseGrid(origin_z)
239 if use_structure_extents:
240 extents = dgindexextents
241 dummy_dose = dummy_dose[
242 extents[1]:extents[3], extents[0]:extents[2]
243 ]
244 _, vol = calculate_plane_histogram(
245 plane, dummy_dose, dosegridpoints, maxdose,
246 dd, id, structure, hist)
247 planedata[z] = (np.array([0]), vol)
248 notes = 'Dose grid does not encompass every contour.' + \
249 ' Volume calculated for all contours.'
250 n += 1
251 if callback:
252 callback(n, len(planes))
253 # Volume units are given in cm^3
254 volume = sum([p[1] for p in planedata.values()]) / 1000
255 # print(f'total volume: {volume}')
256 # Rescale the histogram to reflect the total volume
257 hist = sum([p[0] for p in planedata.values()])
258 if hist.max() > 0:
259 hist = hist * volume / sum(hist)
260 else:
261 return calcdvh('Empty DVH', np.array([0]))
262 # Remove the bins above the max dose for the structure
263 hist = np.trim_zeros(hist, trim='b')
264
265 return calcdvh(notes, hist)
266
267
268 def calculate_plane_histogram(plane, doseplane, dosegridpoints, maxdose, dd,
269 id, structure, hist):
270 """Calculate the DVH for the given plane in the structure."""
271 contours = [[x[0:2] for x in c['data']] for c in plane]
272
273 # Create a zero valued bool grid
274 grid = np.zeros((dd['rows'], dd['columns']), dtype=np.uint8)
275
276 # Calculate the dose plane mask for each contour in the plane
277 # and boolean xor to remove holes
278 for i, contour in enumerate(contours):
279 m = get_contour_mask(dd, id, dosegridpoints, contour)
280 grid = np.logical_xor(m.astype(np.uint8), grid).astype(np.bool_)
281
282 hist, vol = calculate_contour_dvh(grid, doseplane, maxdose, dd, id,
283 structure)
284 return (hist, vol)
285
286
287 def get_contour_mask(dd, id, dosegridpoints, contour):
288 """Get the mask for the contour with respect to the dose plane."""
289 doselut = dd['lut']
290
291 c = matplotlib.path.Path(list(contour))
292
293 # def inpolygon(polygon, xp, yp):
294 # return np.array(
295 # [Point(x, y).intersects(polygon) for x, y in zip(xp, yp)],
296 # dtype=np.bool)
297
298 # p = Polygon(contour)
299 # x, y = np.meshgrid(np.array(dd['lut'][0]), np.array(dd['lut'][1]))
300 # mask = inpolygon(p, x.ravel(), y.ravel())
301 # return mask.reshape((len(doselut[1]), len(doselut[0])))
302
303 grid = c.contains_points(dosegridpoints)
304 if dd['x_lut_index'] == 0: # X values across columns
305 grid = grid.reshape((len(doselut[1]), len(doselut[0])))
306 else: # decubitus
307 grid = grid.reshape((len(doselut[0]), len(doselut[1]))).T
308
309 return grid
310
311
312 def calculate_contour_dvh(mask, doseplane, maxdose, dd, id, structure):
313 """Calculate the differential DVH for the given contour and dose plane."""
314 # Multiply the structure mask by the dose plane to get the dose mask
315 mask = ma.array(doseplane * dd['dosegridscaling'] * 100, mask=~mask)
316 # Calculate the differential dvh
317 hist, edges = np.histogram(mask.compressed(),
318 bins=maxdose,
319 range=(0, maxdose))
320
321 # Calculate the volume for the contour for the given dose plane
322 vol = sum(hist) * (abs(np.mean(np.diff(dd['lut'][0]))) *
323 abs(np.mean(np.diff(dd['lut'][1]))) *
324 (structure['thickness']))
325 return hist, vol
326
327
328 def structure_extents(coords):
329 """Determine structure extents in patient coordinates.
330
331 Parameters
332 ----------
333 coords : dict
334 Structure coordinates from dicomparser.GetStructureCoordinates.
335
336 Returns
337 -------
338 list
339 Structure extents in patient coordintes: [xmin, ymin, xmax, ymax].
340 """
341 bounds = []
342 for z in sorted(coords.items()):
343 contours = [[x[0:2] for x in c['data']] for c in z[1]]
344 for contour in contours:
345 x, y = np.array([x[0:1] for x in contour]), np.array(
346 [x[1:2] for x in contour])
347 bounds.append([np.min(x), np.min(y), np.max(x), np.max(y)])
348 extents = np.array(bounds)
349 return np.array(
350 [np.amin(extents, axis=0)[0:2],
351 np.amax(extents, axis=0)[2:4]]).flatten().tolist()
352
353
354 def dosegrid_extents_indices(extents, dd, padding=1):
355 """Determine dose grid extents from structure extents as array indices.
356
357 Parameters
358 ----------
359 extents : list
360 Structure extents in patient coordinates: [xmin, ymin, xmax, ymax].
361 If an empty list, no structure extents will be used in the calculation.
362 dd : dict
363 Dose data from dicomparser.GetDoseData.
364 padding : int, optional
365 Pixel padding around the structure extents.
366
367 Returns
368 -------
369 list
370 Dose grid extents in pixel coordinates as array indices:
371 [col_min, row_min, col_max, row_max].
372 """
373 col_lut, row_lut = dd['lut']
374 num_cols = len(col_lut)
375 num_rows = len(row_lut)
376 if not len(extents):
377 return [0, 0, num_cols - 1, num_rows - 1]
378
379 if dd['x_lut_index'] == 0: # X is across rows
380 strx_col_min, strx_col_max = extents[0], extents[2]
381 strx_row_min, strx_row_max = extents[1], extents[3]
382 else: # decubitus case, X down rows
383 strx_col_min, strx_col_max = extents[1], extents[3]
384 strx_row_min, strx_row_max = extents[0], extents[2]
385
386 dg_col_min = np.argmin(np.fabs(col_lut - strx_col_min))
387 dg_col_max = np.argmin(np.fabs(col_lut - strx_col_max))
388 if dg_col_min > dg_col_max:
389 dg_col_min, dg_col_max = dg_col_max, dg_col_min
390 if col_lut[dg_col_min] > strx_col_min:
391 dg_col_min -= 1
392
393 dg_row_min = np.argmin(np.fabs(row_lut - strx_row_min))
394 dg_row_max = np.argmin(np.fabs(row_lut - strx_row_max))
395 if dg_row_min > dg_row_max:
396 dg_row_min, dg_row_max = dg_row_max, dg_row_min
397
398 # Ensure indices within array limits regardless of padding
399 dg_col_min = max(0, dg_col_min-padding)
400 dg_row_min = max(0, dg_row_min-padding)
401 dg_col_max = min(num_cols - 1, dg_col_max+padding)
402 dg_row_max = min(num_rows - 1, dg_row_max+padding)
403
404 return [dg_col_min, dg_row_min, dg_col_max, dg_row_max]
405
406
407 def dosegrid_extents_positions(extents, dd):
408 """Determine dose grid extents in patient coordinate indices.
409
410 Parameters
411 ----------
412 extents : list
413 Dose grid extents in pixel coordintes:
414 [col_pos_min, row_pos_min, col_pos_max, row_pos_max].
415 dd : dict
416 Dose data from dicomparser.GetDoseData.
417
418 Returns
419 -------
420 list
421 Dose grid extents in patient coordintes: [xmin, ymin, xmax, ymax].
422 """
423 return [
424 dd['lut'][0][extents[0]], dd['lut'][1][extents[1]],
425 dd['lut'][0][extents[2]], dd['lut'][1][extents[3]]
426 ]
427
428
429 def get_resampled_lut(index_extents,
430 extents,
431 new_pixel_spacing,
432 min_pixel_spacing):
433 """Determine the patient to pixel LUT based on new pixel spacing.
434
435 Parameters
436 ----------
437 index_extents : list
438 Dose grid extents as array indices.
439 extents : list
440 Dose grid extents in patient coordinates:
441 [col_pos_min, row_pos_min, col_pos_max, row_pos_max].
442 new_pixel_spacing : tuple or float
443 New pixel spacing in mm (row, column).
444 If float is provided, original dose grid pixel spacing must be square.
445 min_pixel_spacing : tuple
446 Min pixel spacing used to determine new pixel spacing (row, column).
447
448 Returns
449 -------
450 tuple
451 A tuple of lut lists (col lut, row lut) with the coordinates of the
452 dose grid in patient coordinates
453
454 Raises
455 ------
456 AttributeError
457 Raised if the new pixel_spacing is not a factor of the minimum pixel
458 spacing.
459
460 Notes
461 -----
462 The new pixel spacing must be a factor of the original (minimum) pixel
463 spacing. For example if the original pixel spacing was ``3`` mm, the new
464 pixel spacing should be: ``3 / (2^n)`` mm, where ``n`` is an integer.
465 This applies independently to both the row and column pixel spacing.
466
467 If a single float value is provided it will be applied to both row and
468 column. Additionally, the original dose grid pixel spacing must be square.
469
470 Examples
471 --------
472 Original pixel spacing: ``3`` mm, new pixel spacing: ``0.375`` mm
473 Derived via: ``(3 / 2^16) == 0.375``
474
475 """
476 if not isinstance(new_pixel_spacing, Sequence):
477 if not (min_pixel_spacing[0] == min_pixel_spacing[1]):
478 raise AttributeError(
479 "New pixel spacing must be provided as a (row, column) tuple.")
480 else:
481 new_pixel_spacing = (new_pixel_spacing, new_pixel_spacing)
482 if (min_pixel_spacing[0] % new_pixel_spacing[0] != 0.0):
483 raise AttributeError(
484 "New row pixel spacing must be a factor of %s/(2^n),"
485 % min_pixel_spacing[0] +
486 " where n is an integer. Value provided was %s."
487 % new_pixel_spacing[0])
488 if (min_pixel_spacing[1] % new_pixel_spacing[1] != 0.0):
489 raise AttributeError(
490 "New column pixel spacing must be a factor of %s/(2^n),"
491 % min_pixel_spacing[1] +
492 " where n is an integer. Value provided was %s."
493 % new_pixel_spacing[1])
494
495 # Existing number of cols, rows
496 num_cols = abs(index_extents[0] - index_extents[2])
497 num_rows = abs(index_extents[1] - index_extents[3])
498
499 col_samples = round(num_cols * min_pixel_spacing[1] / new_pixel_spacing[1])
500 row_samples = round(num_rows * min_pixel_spacing[0] / new_pixel_spacing[0])
501
502 col_lut = np.linspace(
503 extents[0], extents[2], int(col_samples), dtype=np.float64
504 )
505 row_lut = np.linspace(
506 extents[1], extents[3], int(row_samples), dtype=np.float64
507 )
508 return col_lut, row_lut
509
510
511 def get_interpolated_dose(dose, z, resolution, extents):
512 """Get interpolated dose for the given z, resolution & array extents.
513
514 Parameters
515 ----------
516 dose : DicomParser
517 A DicomParser instance of an RT Dose.
518 z : float
519 Index in mm of z plane of dose grid.dose
520 resolution : tuple
521 Interpolation resolution less than or equal to dose grid pixel spacing.
522 Provided in (row, col) format.
523 extents : list
524 Dose grid index extents.
525
526 Returns
527 -------
528 ndarray
529 Interpolated dose grid with a shape larger than the input dose grid.
530 """
531 # Return the dose bounded by extents if interpolation is not required
532 d = dose.GetDoseGrid(z)
533 if not d.size:
534 return d # cannot take 2d index below if empty
535 extent_dose = d[extents[1]:extents[3],
536 extents[0]:extents[2]] if len(extents) else d
537 if not resolution:
538 return extent_dose
539 if not skimage_available:
540 raise ImportError(
541 "scikit-image must be installed to perform DVH interpolation.")
542 scale = (np.array(dose.ds.PixelSpacing) / resolution).tolist()
543 interp_dose = rescale(
544 extent_dose,
545 scale=scale,
546 order=1,
547 mode='symmetric',
548 preserve_range=True,
549 channel_axis=None
550 )
551 return interp_dose
552
553
554 def interpolate_between_planes(planes, n=2):
555 """Interpolate n additional structure planes (segments) in between planes.
556
557 Parameters
558 ----------
559 planes : dict
560 RT Structure plane data from dicomparser.GetStructureCoordinates.
561 n : int, optional
562 Number of planes to interpolate in between the existing planes.
563
564 Returns
565 -------
566 dict
567 Plane data with additional keys representing interpolated planes.
568 """
569 keymap = {np.array([k], dtype=np.float32)[0]: k for k in planes.keys()}
570 sorted_keys = np.sort(np.array(list(planes.keys()), dtype=np.float32))
571 num_new_samples = (len(planes.keys()) * (n + 1)) - n
572 newgrid = np.linspace(sorted_keys[0], sorted_keys[-1], num_new_samples)
573 new_planes = {}
574 # If the plane already exists in the dictionary, use it
575 # otherwise use the closest plane
576 # TODO: Add actual interpolation of structure data between planes
577 for plane in newgrid:
578 new_plane = sorted_keys[np.argmin(np.fabs(sorted_keys - plane))]
579 new_planes[plane] = planes[keymap[new_plane]]
580 return new_planes