Debian Codegraph @

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