Debian Codegraph @

dicompylercore/dvh.py

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3 # dvh.py
4 """Class that stores dose volume histogram (DVH) data."""
5 # Copyright (c) 2016 Aditya Panchal
6 # This file is part of dicompyler-core, released under a BSD license.
7 # See the file license.txt included with this distribution, also
8 # available at https://github.com/dicompyler/dicompyler-core/
9
10 import numpy as np
11 import re
12 import logging
13 logger = logging.getLogger('dicompylercore.dvh')
14
15 # Set default absolute dose and volume units
16 abs_dose_units = 'Gy'
17 abs_volume_units = 'cm3'
18 relative_units = '%'
19
20
21 class DVH(object):
22 """Class that stores dose volume histogram (DVH) data."""
23
24 def __init__(self, counts, bins,
25 dvh_type='cumulative',
26 dose_units=abs_dose_units,
27 volume_units=abs_volume_units,
28 rx_dose=None, name=None, color=None, notes=None):
29 """Initialization for a DVH from existing histogram counts and bins.
30
31 Parameters
32 ----------
33 counts : iterable or numpy array
34 An iterable of volume or percent count data
35 bins : iterable or numpy array
36 An iterable of dose bins
37 dvh_type : str, optional
38 Choice of 'cumulative' or 'differential' type of DVH
39 dose_units : str, optional
40 Absolute dose units, i.e. 'gy' or relative units '%'
41 volume_units : str, optional
42 Absolute volume units, i.e. 'cm3' or relative units '%'
43 rx_dose : number, optional
44 Prescription dose value used to normalize dose bins (in Gy)
45 name : String, optional
46 Name of the structure of the DVH
47 color : numpy array, optional
48 RGB color triplet used for plotting the DVH
49 notes : String, optional
50 Additional notes about the DVH instance
51 """
52 self.counts = np.array(counts)
53 self.bins = np.array(bins) if bins[0] == 0 else np.append([0], bins)
54 self.dvh_type = dvh_type
55 self.dose_units = dose_units
56 self.volume_units = volume_units
57 self.rx_dose = rx_dose
58 self.name = name
59 self.color = color
60 self.notes = notes
61
62 @classmethod
63 def from_dicom_dvh(cls, dataset, roi_num, rx_dose=None, name=None,
64 color=None):
65 """Initialization for a DVH from a pydicom RT Dose DVH sequence."""
66 sequence_num = -1
67 for i, d in enumerate(dataset.DVHSequence):
68 if 'DVHReferencedROISequence' in d:
69 if 'ReferencedROINumber' in d.DVHReferencedROISequence[0]:
70 if roi_num == \
71 d.DVHReferencedROISequence[0].ReferencedROINumber:
72 sequence_num = i
73 break
74 if sequence_num == -1:
75 raise AttributeError(
76 "'DVHSequence' has no DVH with ROI Number '%d'." % roi_num)
77 dvh = dataset.DVHSequence[sequence_num]
78 data = np.array(dvh.DVHData)
79 return cls(counts=data[1::2],
80 bins=data[0::2].cumsum() * dvh.DVHDoseScaling,
81 dvh_type=dvh.DVHType.lower(),
82 dose_units=dvh.DoseUnits.capitalize(),
83 volume_units=dvh.DVHVolumeUnits.lower(),
84 rx_dose=rx_dose,
85 name=name,
86 color=color)
87
88 @classmethod
89 def from_data(cls, data, binsize=1):
90 """Initialization for a DVH from raw data.
91
92 Parameters
93 ----------
94 data : iterable or numpy array
95 An iterable of dose data that is used to create the histogram
96 binsize : int, optional
97 Bin width size (in cGy used to create the histogram)
98 """
99 data = np.array(data)
100 bins = np.arange(0, data.max() + 1, binsize)
101 if bins.size == 1:
102 bins = np.array([0, data.max()])
103 if data.max() not in bins:
104 bins = np.append(bins, data.max())
105 counts, bins = np.histogram(data, bins)
106
107 return cls(counts, bins)
108
109 def __repr__(self):
110 """String representation of the class."""
•111 return (
112 f'DVH({self.dvh_type}, {self.counts.size} bins: '
113 f'[{self.bins.min()}:{self.bins.max()}] {self.dose_units}, '
114 f'volume: {self.volume} {self.volume_units}, name: {self.name}, '
115 f'rx_dose: {0 if not self.rx_dose else self.rx_dose} '
116 f'{self.dose_units}'
117 f'{", *Notes: " + self.notes if self.notes else ""})'
118 )
119 def __eq__(self, other):
120 """Comparison method between two DVH objects.
121
122 Parameters
123 ----------
124 other : DVH
125 Other DVH object to compare with
126
127 Returns
128 -------
129 Bool
130 True or False if the DVHs have equal attribs and via numpy.allclose
131 """
132 attribs = ('dvh_type', 'dose_units', 'volume_units')
133 attribs_eq = {k: self.__dict__[k] for k in attribs} == \
134 {k: other.__dict__[k] for k in attribs}
135 return attribs_eq and \
136 np.allclose(self.counts, other.counts) and \
137 np.allclose(self.bins, other.bins)
138
139 # ============================= DVH properties ============================= #
140
141 @property
142 def bincenters(self):
143 """Return a numpy array containing the bin centers."""
144 return 0.5 * (self.bins[1:] + self.bins[:-1])
145
146 @property
147 def differential(self):
148 """Return a differential DVH from a cumulative DVH."""
149 dvh_type = 'differential'
150 if self.dvh_type == dvh_type:
151 return self
152 else:
153 return DVH(**dict(
154 self.__dict__,
155 counts=abs(np.diff(np.append(self.counts, 0))),
156 dvh_type=dvh_type))
157
158 @property
159 def cumulative(self):
160 """Return a cumulative DVH from a differential DVH."""
161 dvh_type = 'cumulative'
162 if self.dvh_type == dvh_type:
163 return self
164 else:
165 return DVH(**dict(
166 self.__dict__,
167 counts=self.counts[::-1].cumsum()[::-1],
168 dvh_type=dvh_type))
169
170 def absolute_dose(self, rx_dose=None, dose_units=abs_dose_units):
171 """Return an absolute dose DVH.
172
173 Parameters
174 ----------
175 rx_dose : number, optional
176 Prescription dose value used to normalize dose bins
177 dose_units : str, optional
178 Units for the absolute dose
179
180 Raises
181 ------
182 AttributeError
183 Description
184 """
185 if not (self.dose_units == relative_units):
186 return self
187 else:
188 # Raise an error if no rx_dose defined
189 if not self.rx_dose and not rx_dose:
190 raise AttributeError("'DVH' has no defined prescription dose.")
191 else:
192 rxdose = rx_dose if self.rx_dose is None else self.rx_dose
193 return DVH(**dict(
194 self.__dict__,
195 bins=self.bins * rxdose / 100,
196 dose_units=dose_units))
197
198 def relative_dose(self, rx_dose=None):
199 """Return a relative dose DVH based on a prescription dose.
200
201 Parameters
202 ----------
203 rx_dose : number, optional
204 Prescription dose value used to normalize dose bins
205
206 Raises
207 ------
208 AttributeError
209 Raised if prescription dose was not present either during
210 class initialization or passed via argument.
211 """
212 dose_units = relative_units
213 if self.dose_units == dose_units:
214 return self
215 else:
216 # Raise an error if no rx_dose defined
217 if not self.rx_dose and not rx_dose:
218 raise AttributeError("'DVH' has no defined prescription dose.")
219 else:
220 rxdose = rx_dose if self.rx_dose is None else self.rx_dose
221 return DVH(**dict(
222 self.__dict__,
223 bins=100 * self.bins / rxdose,
224 dose_units=dose_units))
225
226 def absolute_volume(self, volume, volume_units=abs_volume_units):
227 """Return an absolute volume DVH.
228
229 Parameters
230 ----------
231 volume : number
232 Absolute volume of the structure
233 volume_units : str, optional
234 Units for the absolute volume
235 """
236 if not (self.volume_units == relative_units):
237 return self
238 else:
239 return DVH(**dict(
240 self.__dict__,
241 counts=volume * self.counts / 100,
242 volume_units=volume_units))
243
244 @property
245 def relative_volume(self):
246 """Return a relative volume DVH."""
247 volume_units = relative_units
248 if self.volume_units == relative_units:
249 return self
250 # Convert back to cumulative before returning a relative volume
251 elif self.dvh_type == 'differential':
252 return self.cumulative.relative_volume.differential
253 else:
254 return DVH(**dict(
255 self.__dict__,
256 counts=100 * self.counts /
257 (1 if (self.max == 0) else self.counts.max()),
258 volume_units=volume_units))
259
260 @property
261 def max(self):
262 """Return the maximum dose."""
263 if self.counts.size <= 1 or max(self.counts) == 0:
264 return 0
265 diff = self.differential
266 # Find the the maximum non-zero dose bin
267 return diff.bins[1:][diff.counts > 0][-1]
268
269 @property
270 def min(self):
271 """Return the minimum dose."""
272 if self.counts.size <= 1 or max(self.counts) == 0:
273 return 0
274 diff = self.differential
275 # Find the the minimum non-zero dose bin
276 return diff.bins[1:][diff.counts > 0][0]
277
278 @property
279 def mean(self):
280 """Return the mean dose."""
281 if self.counts.size <= 1 or max(self.counts) == 0:
282 return 0
283 diff = self.differential
284 # Find the area under the differential histogram
285 return (diff.bincenters * diff.counts).sum() / diff.counts.sum()
286
287 @property
288 def volume(self):
289 """Return the volume of the structure."""
290 return self.differential.counts.sum()
291
292 def describe(self):
293 """Describe a summary of DVH statistics in a text based format."""
294 print("Structure: {}".format(self.name))
295 print("-----")
296 dose = "rel dose" if self.dose_units == relative_units else \
297 "abs dose: {}".format(self.dose_units)
298 vol = "rel volume" if self.volume_units == relative_units else \
299 "abs volume: {}".format(self.volume_units)
300 print("DVH Type: {}, {}, {}".format(
301 self.dvh_type, dose, vol))
302 print("Volume: {:0.2f} {}".format(
303 self.volume, self.volume_units))
304 print("Max Dose: {:0.2f} {}".format(
305 self.max, self.dose_units))
306 print("Min Dose: {:0.2f} {}".format(
307 self.min, self.dose_units))
308 print("Mean Dose: {:0.2f} {}".format(
309 self.mean, self.dose_units))
310 print("D100: {}".format(self.D100))
311 print("D98: {}".format(self.D98))
312 print("D95: {}".format(self.D95))
313 # Only show volume statistics if a Rx Dose has been defined
314 # i.e. dose is in relative units
315 if self.dose_units == relative_units:
316 print("V100: {}".format(self.V100))
317 print("V95: {}".format(self.V95))
318 print("V5: {}".format(self.V5))
319 print("D2cc: {}".format(self.D2cc))
320 if self.notes:
321 print("Notes: *{}".format(self.notes))
322
323 def compare(self, dvh):
324 """Compare the DVH properties with another DVH.
325
326 Parameters
327 ----------
328 dvh : DVH
329 DVH instance to compare against
330
331 Raises
332 ------
333 AttributeError
334 If DVHs do not have equivalent dose & volume units
335 """
336 if not (self.dose_units == dvh.dose_units) or \
337 not (self.volume_units == dvh.volume_units):
338 raise AttributeError("DVH units are not equivalent")
339
340 def fmtcmp(attr, units, ref=self, comp=dvh):
341 """Generate arguments for string formatting.
342
343 Parameters
344 ----------
345 attr : string
346 Attribute used for comparison
347 units : string
348 Units used for the value
349
350 Returns
351 -------
352 tuple
353 tuple used in a string formatter
354 """
355 if attr in ['volume', 'max', 'min', 'mean']:
356 val = ref.__getattribute__(attr)
357 cmpval = comp.__getattribute__(attr)
358 else:
359 val = ref.statistic(attr).value
360 cmpval = comp.statistic(attr).value
361 return attr.capitalize() + ":", val, units, cmpval, units, \
362 0 if not val else ((cmpval - val) / val) * 100, cmpval - val
363
364 print("{:11} {:>14} {:>17} {:>17} {:>14}".format(
365 'Structure:', self.name, dvh.name, 'Rel Diff', 'Abs diff'))
366 print("-----")
367 dose = "rel dose" if self.dose_units == relative_units else \
368 "abs dose: {}".format(self.dose_units)
369 vol = "rel volume" if self.volume_units == relative_units else \
370 "abs volume: {}".format(self.volume_units)
371 print("DVH Type: {}, {}, {}".format(self.dvh_type, dose, vol))
372 fmtstr = "{:11} {:12.2f} {:3}{:14.2f} {:3}{:+14.2f} % {:+14.2f}"
373 print(fmtstr.format(*fmtcmp('volume', self.volume_units)))
374 print(fmtstr.format(*fmtcmp('max', self.dose_units)))
375 print(fmtstr.format(*fmtcmp('min', self.dose_units)))
376 print(fmtstr.format(*fmtcmp('mean', self.dose_units)))
377 print(fmtstr.format(*fmtcmp('D100', self.dose_units)))
378 print(fmtstr.format(*fmtcmp('D98', self.dose_units)))
379 print(fmtstr.format(*fmtcmp('D95', self.dose_units)))
380 # Only show volume statistics if a Rx Dose has been defined
381 # i.e. dose is in relative units
382 if self.dose_units == relative_units:
383 print(fmtstr.format(
384 *fmtcmp('V100', self.dose_units,
385 self.relative_dose(), dvh.relative_dose())))
386 print(fmtstr.format(
387 *fmtcmp('V95', self.dose_units,
388 self.relative_dose(), dvh.relative_dose())))
389 print(fmtstr.format(
390 *fmtcmp('V5', self.dose_units,
391 self.relative_dose(), dvh.relative_dose())))
392 print(fmtstr.format(*fmtcmp('D2cc', self.dose_units)))
393 self.plot()
394 dvh.plot()
395
396 def plot(self):
397 """Plot the DVH using Matplotlib if present."""
398 try:
399 import matplotlib.pyplot as plt
400 except (ImportError, RuntimeError):
401 print('Matplotlib could not be loaded. Install and try again.')
402 else:
403 plt.plot(self.bincenters, self.counts, label=self.name,
404 color=None if not isinstance(self.color, np.ndarray) else
405 (self.color / 255))
406 # plt.axis([0, self.bins[-1], 0, self.counts[0]])
407 plt.xlabel('Dose [%s]' % self.dose_units)
408 plt.ylabel('Volume [%s]' % self.volume_units)
409 if self.name:
410 plt.legend(loc='best')
411 return self
412
413 def volume_constraint(self, dose, dose_units=None):
414 """Calculate the volume that receives at least a specific dose.
415
416 i.e. V100, V150 or V20Gy
417
418 Parameters
419 ----------
420 dose : number
421 Dose value used to determine minimum volume that receives
422 this dose. Can either be in relative or absolute dose units.
423
424 Returns
425 -------
426 number
427 Volume in self.volume_units units.
428 """
429 # Determine whether to lookup relative dose or absolute dose
430 if not dose_units:
431 dose_bins = self.relative_dose().bins
432 else:
433 dose_bins = self.absolute_dose().bins
434 index = np.argmin(np.fabs(dose_bins - dose))
435 # TODO Add interpolation
436 if index >= self.counts.size:
437 return DVHValue(0.0, self.volume_units)
438 else:
439 return DVHValue(self.counts[index], self.volume_units)
440
441 def dose_constraint(self, volume, volume_units=None):
442 """Calculate the maximum dose that a specific volume receives.
443
444 i.e. D90, D100 or D2cc
445
446 Parameters
447 ----------
448 volume : number
449 Volume used to determine the maximum dose that the volume receives.
450 Can either be in relative or absolute volume units.
451
452 Returns
453 -------
454 number
455 Dose in self.dose_units units.
456 """
457 # Determine whether to lookup relative volume or absolute volume
458 if not volume_units:
459 volume_counts = self.relative_volume.counts
460 else:
461 volume_counts = self.absolute_volume(self.volume).counts
462
463 if volume_counts.size == 0 or volume > volume_counts.max():
464 return DVHValue(0.0, self.dose_units)
465
466 # D100 case
467 if volume == 100 and not volume_units:
468 # Flipping the difference volume array
469 reversed_difference_of_volume = np.flip(
470 np.fabs(volume_counts - volume), 0)
471
472 # Index of the first minimum value in reversed array
473 index_min_value = np.argmin(reversed_difference_of_volume)
474 index_range = len(reversed_difference_of_volume) - 1
475
476 return DVHValue(
477 self.bins[index_range - index_min_value], self.dose_units)
478
479 # TODO Add interpolation
480 return DVHValue(
481 self.bins[np.argmin(
482 np.fabs(volume_counts - volume))],
483 self.dose_units)
484
485 def statistic(self, name):
486 """Return a DVH dose or volume statistic.
487
488 Parameters
489 ----------
490 name : str
491 DVH statistic in the form of D90, D100, D2cc, V100 or V20Gy, etc.
492
493 Returns
494 -------
495 number
496 Value from the dose or volume statistic calculation.
497 """
498 # Compile a regex to determine dose & volume statistics
499 p = re.compile(r'(\S+)?(D|V){1}(\d+[.]?\d*)(gy|cc)?(?!\S+)',
500 re.IGNORECASE)
501 match = re.match(p, name)
502 # Return the default attribute if not a dose or volume statistic
503 # print(match.groups())
504 if not match or match.groups()[0] is not None:
505 raise AttributeError("'DVH' has no attribute '%s'" % name)
506
507 # Process the regex match
508 c = [x.lower() for x in match.groups() if x]
509 if c[0] == ('v'):
510 # Volume Constraints (i.e. V100) & return a volume
511 if len(c) == 2:
512 return self.cumulative.volume_constraint(float(c[1]))
513 # Volume Constraints in abs dose (i.e. V20Gy) & return a volume
514 return self.cumulative.volume_constraint(float(c[1]), c[2])
515 elif c[0] == ('d'):
516 # Dose Constraints (i.e. D90) & return a dose
517 if len(c) == 2:
518 return self.cumulative.dose_constraint(float(c[1]))
519 # Dose Constraints in abs volume (i.e. D2cc) & return a dose
520 return self.cumulative.dose_constraint(float(c[1]), c[2])
521
522 def __getattr__(self, name):
523 """Method used to dynamically determine dose or volume stats.
524
525 Parameters
526 ----------
527 name : string
528 Property name called to determine dose & volume statistics
529
530 Returns
531 -------
532 number
533 Value from the dose or volume statistic calculation.
534 """
535 return self.statistic(name)
536
537
538 class DVHValue(object):
539 """Class that stores DVH values with the appropriate units."""
540
541 def __init__(self, value, units=''):
542 """Initialization for a DVH value that will also store units."""
543 self.value = value
544 self.units = units
545
546 def __repr__(self):
547 """Representation of the DVH value."""
548 return "dvh.DVHValue(" + self.value.__repr__() + \
549 ", '" + self.units + "')"
550
551 def __str__(self):
552 """String representation of the DVH value."""
553 if not self.units:
554 # return str(self.value)
555 return format(self.value, '0.2f')
556 else:
557 # return str(self.value) + ' ' + self.units
558 return format(self.value, '0.2f') + ' ' + self.units
559
560 def __eq__(self, other):
561 """Comparison method between two DVHValue objects.
562
563 Parameters
564 ----------
565 other : DVHValue
566 Other DVHValue object to compare with
567
568 Returns
569 -------
570 Bool
571 True or False if the DVHValues have equal attribs
572 """
573 attribs_eq = self.units == other.units
574 return attribs_eq and \
575 np.allclose(self.value, other.value)