Debian Codegraph @

dicompylercore/dvhcalc.py

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