firstorder.py 24.1 KB
Newer Older
Andrea Bizzego's avatar
Andrea Bizzego committed
1
import numpy
2
from scipy import ndimage
Andrea Bizzego's avatar
Andrea Bizzego committed
3

4
from radiomics import base, cShape, deprecated, imageoperations
5
from oct2py import Oct2Py, Oct2PyError
Andrea Bizzego's avatar
Andrea Bizzego committed
6
7
8


class RadiomicsFirstOrder(base.RadiomicsFeaturesBase):
9
    r"""
Andrea Bizzego's avatar
Andrea Bizzego committed
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
  First-order statistics describe the distribution of voxel intensities within the image region defined by the mask
  through commonly used and basic metrics.

  Let:

  - :math:`\textbf{X}` be a set of :math:`N_p` voxels included in the ROI
  - :math:`\textbf{P}(i)` be the first order histogram with :math:`N_g` discrete intensity levels,
    where :math:`N_g` is the number of non-zero bins, equally spaced from 0 with a width defined in the ``binWidth``
    parameter.
  - :math:`p(i)` be the normalized first order histogram and equal to :math:`\frac{\textbf{P}(i)}{N_p}`

  Following additional settings are possible:

  - voxelArrayShift [0]: Integer, This amount is added to the gray level intensity in features Energy, Total Energy and
    RMS, this is to prevent negative values. *If using CT data, or data normalized with mean 0, consider setting this
    parameter to a fixed value (e.g. 2000) that ensures non-negative numbers in the image. Bear in mind however, that
    the larger the value, the larger the volume confounding effect will be.*

  .. note::
    In the IBSI feature definitions, no correction for negative gray values is implemented. To achieve similar behaviour
    in PyRadiomics, set ``voxelArrayShift`` to 0.
  """

33
34
    def __init__(self, inputImage, inputMask, **kwargs):
        super(RadiomicsFirstOrder, self).__init__(inputImage, inputMask, **kwargs)
Andrea Bizzego's avatar
Andrea Bizzego committed
35

36
37
        self.pixelSpacing = inputImage.GetSpacing()
        self.voxelArrayShift = kwargs.get('voxelArrayShift', 0)
Andrea Bizzego's avatar
Andrea Bizzego committed
38

39
40
41
42
43
44
    def _initCalculation(self):
        super(RadiomicsFirstOrder, self)._initSegmentBasedCalculation()
        self.targetVoxelArray = self.imageArray[self.labelledVoxelCoordinates].astype(
            'float'
        )
        self.discretizedTargetVoxelArray = None  # Lazy instantiation
Andrea Bizzego's avatar
Andrea Bizzego committed
45

46
        self.logger.debug('First order feature class initialized')
Andrea Bizzego's avatar
Andrea Bizzego committed
47

48
49
    def _moment(self, a, moment=1, axis=0):
        r"""
Andrea Bizzego's avatar
Andrea Bizzego committed
50
51
52
    Calculate n-order moment of an array for a given axis
    """

53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
        if moment == 1:
            return numpy.float64(0.0)
        else:
            mn = numpy.mean(a, axis, keepdims=True)
            s = numpy.power((a - mn), moment)
            return numpy.mean(s, axis)

    def _getDiscretizedTargetVoxelArray(self):
        if self.discretizedTargetVoxelArray is None:
            if self.binCount is not None:
                binEdges = self.binCount
            else:
                binEdges = imageoperations.getBinEdges(
                    self.binWidth, self.targetVoxelArray
                )

            self.discretizedTargetVoxelArray = numpy.histogram(
                self.targetVoxelArray, binEdges
            )[0]

        return self.discretizedTargetVoxelArray

    def getEnergyFeatureValue(self):
        r"""
Andrea Bizzego's avatar
Andrea Bizzego committed
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
    **1. Energy**

    .. math::
      \textit{energy} = \displaystyle\sum^{N_p}_{i=1}{(\textbf{X}(i) + c)^2}

    Here, :math:`c` is optional value, defined by ``voxelArrayShift``, which shifts the intensities to prevent negative
    values in :math:`\textbf{X}`. This ensures that voxels with the lowest gray values contribute the least to Energy,
    instead of voxels with gray level intensity closest to 0.

    Energy is a measure of the magnitude of voxel values in an image. A larger values implies a greater sum of the
    squares of these values.

    .. note::
      This feature is volume-confounded, a larger value of :math:`c` increases the effect of volume-confounding.
    """

93
        shiftedParameterArray = self.targetVoxelArray + self.voxelArrayShift
Andrea Bizzego's avatar
Andrea Bizzego committed
94

95
        return numpy.sum(shiftedParameterArray ** 2)
Andrea Bizzego's avatar
Andrea Bizzego committed
96

97
98
    def getTotalEnergyFeatureValue(self):
        r"""
Andrea Bizzego's avatar
Andrea Bizzego committed
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
    **2. Total Energy**

    .. math::
      \textit{total energy} = V_{voxel}\displaystyle\sum^{N_p}_{i=1}{(\textbf{X}(i) + c)^2}

    Here, :math:`c` is optional value, defined by ``voxelArrayShift``, which shifts the intensities to prevent negative
    values in :math:`\textbf{X}`. This ensures that voxels with the lowest gray values contribute the least to Energy,
    instead of voxels with gray level intensity closest to 0.

    Total Energy is the value of Energy feature scaled by the volume of the voxel in cubic mm.

    .. note::
      This feature is volume-confounded, a larger value of :math:`c` increases the effect of volume-confounding.

    .. note::
      Not present in IBSI feature definitions
    """

117
118
        x, y, z = self.pixelSpacing
        cubicMMPerVoxel = x * y * z
Andrea Bizzego's avatar
Andrea Bizzego committed
119

120
        return cubicMMPerVoxel * self.getEnergyFeatureValue()
Andrea Bizzego's avatar
Andrea Bizzego committed
121

122
123
    def getEntropyFeatureValue(self):
        r"""
Andrea Bizzego's avatar
Andrea Bizzego committed
124
125
126
127
128
129
130
131
132
133
134
135
136
137
    **3. Entropy**

    .. math::
      \textit{entropy} = -\displaystyle\sum^{N_g}_{i=1}{p(i)\log_2\big(p(i)+\epsilon\big)}

    Here, :math:`\epsilon` is an arbitrarily small positive number (:math:`\approx 2.2\times10^{-16}`).

    Entropy specifies the uncertainty/randomness in the image values. It measures the average amount of information
    required to encode the image values.

    .. note::
      Defined by IBSI as Intensity Histogram Entropy.
    """

138
139
        eps = numpy.spacing(1)
        bins = self._getDiscretizedTargetVoxelArray()
Andrea Bizzego's avatar
Andrea Bizzego committed
140

141
142
143
        sumBins = bins.sum()
        if sumBins == 0:  # No segmented voxels
            return 0
Andrea Bizzego's avatar
Andrea Bizzego committed
144

145
146
147
        bins = bins + eps
        bins = bins / float(sumBins)
        return -1.0 * numpy.sum(bins * numpy.log2(bins))
Andrea Bizzego's avatar
Andrea Bizzego committed
148

149
150
    def getMinimumFeatureValue(self):
        r"""
Andrea Bizzego's avatar
Andrea Bizzego committed
151
152
153
154
155
156
    **4. Minimum**

    .. math::
      \textit{minimum} = \min(\textbf{X})
    """

157
        return numpy.min(self.targetVoxelArray)
Andrea Bizzego's avatar
Andrea Bizzego committed
158

159
160
    def get10PercentileFeatureValue(self):
        r"""
Andrea Bizzego's avatar
Andrea Bizzego committed
161
162
163
164
165
    **5. 10th percentile**

    The 10\ :sup:`th` percentile of :math:`\textbf{X}`
    """

166
        return numpy.percentile(self.targetVoxelArray, 10)
Andrea Bizzego's avatar
Andrea Bizzego committed
167

168
169
    def get90PercentileFeatureValue(self):
        r"""
Andrea Bizzego's avatar
Andrea Bizzego committed
170
171
172
173
174
    **6. 90th percentile**

    The 90\ :sup:`th` percentile of :math:`\textbf{X}`
    """

175
        return numpy.percentile(self.targetVoxelArray, 90)
Andrea Bizzego's avatar
Andrea Bizzego committed
176

177
178
    def getMaximumFeatureValue(self):
        r"""
Andrea Bizzego's avatar
Andrea Bizzego committed
179
180
181
182
183
184
185
186
    **7. Maximum**

    .. math::
      \textit{maximum} = \max(\textbf{X})

    The maximum gray level intensity within the ROI.
    """

187
        return numpy.max(self.targetVoxelArray)
Andrea Bizzego's avatar
Andrea Bizzego committed
188

189
190
    def getMeanFeatureValue(self):
        r"""
Andrea Bizzego's avatar
Andrea Bizzego committed
191
192
193
194
195
196
197
198
    **8. Mean**

    .. math::
      \textit{mean} = \frac{1}{N_p}\displaystyle\sum^{N_p}_{i=1}{\textbf{X}(i)}

    The average gray level intensity within the ROI.
    """

199
        return numpy.mean(self.targetVoxelArray)
Andrea Bizzego's avatar
Andrea Bizzego committed
200

201
202
    def getMedianFeatureValue(self):
        r"""
Andrea Bizzego's avatar
Andrea Bizzego committed
203
204
205
206
207
    **9. Median**

    The median gray level intensity within the ROI.
    """

208
        return numpy.median(self.targetVoxelArray)
Andrea Bizzego's avatar
Andrea Bizzego committed
209

210
211
    def getInterquartileRangeFeatureValue(self):
        r"""
Andrea Bizzego's avatar
Andrea Bizzego committed
212
213
214
215
216
217
218
219
220
    **10. Interquartile Range**

    .. math::
      \textit{interquartile range} = \textbf{P}_{75} - \textbf{P}_{25}

    Here :math:`\textbf{P}_{25}` and :math:`\textbf{P}_{75}` are the 25\ :sup:`th` and 75\ :sup:`th` percentile of the
    image array, respectively.
    """

221
222
223
        return numpy.percentile(self.targetVoxelArray, 75) - numpy.percentile(
            self.targetVoxelArray, 25
        )
Andrea Bizzego's avatar
Andrea Bizzego committed
224

225
226
    def getRangeFeatureValue(self):
        r"""
Andrea Bizzego's avatar
Andrea Bizzego committed
227
228
229
230
231
232
233
234
    **11. Range**

    .. math::
      \textit{range} = \max(\textbf{X}) - \min(\textbf{X})

    The range of gray values in the ROI.
    """

235
        return numpy.max(self.targetVoxelArray) - numpy.min(self.targetVoxelArray)
Andrea Bizzego's avatar
Andrea Bizzego committed
236

237
238
    def getMeanAbsoluteDeviationFeatureValue(self):
        r"""
Andrea Bizzego's avatar
Andrea Bizzego committed
239
240
241
242
243
244
245
246
    **12. Mean Absolute Deviation (MAD)**

    .. math::
      \textit{MAD} = \frac{1}{N_p}\displaystyle\sum^{N_p}_{i=1}{|\textbf{X}(i)-\bar{X}|}

    Mean Absolute Deviation is the mean distance of all intensity values from the Mean Value of the image array.
    """

247
248
249
        return numpy.mean(
            numpy.absolute((numpy.mean(self.targetVoxelArray) - self.targetVoxelArray))
        )
Andrea Bizzego's avatar
Andrea Bizzego committed
250

251
252
    def getRobustMeanAbsoluteDeviationFeatureValue(self):
        r"""
Andrea Bizzego's avatar
Andrea Bizzego committed
253
254
255
256
257
258
259
260
261
262
263
    **13. Robust Mean Absolute Deviation (rMAD)**

    .. math::
      \textit{rMAD} = \frac{1}{N_{10-90}}\displaystyle\sum^{N_{10-90}}_{i=1}
      {|\textbf{X}_{10-90}(i)-\bar{X}_{10-90}|}

    Robust Mean Absolute Deviation is the mean distance of all intensity values
    from the Mean Value calculated on the subset of image array with gray levels in between, or equal
    to the 10\ :sup:`th` and 90\ :sup:`th` percentile.
    """

264
265
266
267
268
        prcnt10 = self.get10PercentileFeatureValue()
        prcnt90 = self.get90PercentileFeatureValue()
        percentileArray = self.targetVoxelArray[
            (self.targetVoxelArray >= prcnt10) * (self.targetVoxelArray <= prcnt90)
        ]
Andrea Bizzego's avatar
Andrea Bizzego committed
269

270
        return numpy.mean(numpy.absolute(percentileArray - numpy.mean(percentileArray)))
Andrea Bizzego's avatar
Andrea Bizzego committed
271

272
273
    def getRootMeanSquaredFeatureValue(self):
        r"""
Andrea Bizzego's avatar
Andrea Bizzego committed
274
275
276
277
278
279
280
281
282
283
284
285
286
287
    **14. Root Mean Squared (RMS)**

    .. math::
      \textit{RMS} = \sqrt{\frac{1}{N_p}\sum^{N_p}_{i=1}{(\textbf{X}(i) + c)^2}}

    Here, :math:`c` is optional value, defined by ``voxelArrayShift``, which shifts the intensities to prevent negative
    values in :math:`\textbf{X}`. This ensures that voxels with the lowest gray values contribute the least to RMS,
    instead of voxels with gray level intensity closest to 0.

    RMS is the square-root of the mean of all the squared intensity values. It is another measure of the magnitude of
    the image values. This feature is volume-confounded, a larger value of :math:`c` increases the effect of
    volume-confounding.
    """

288
289
290
        # If no voxels are segmented, prevent division by 0 and return 0
        if self.targetVoxelArray.size == 0:
            return 0
Andrea Bizzego's avatar
Andrea Bizzego committed
291

292
293
294
295
        shiftedParameterArray = self.targetVoxelArray + self.voxelArrayShift
        return numpy.sqrt(
            (numpy.sum(shiftedParameterArray ** 2)) / float(shiftedParameterArray.size)
        )
Andrea Bizzego's avatar
Andrea Bizzego committed
296

297
298
299
    @deprecated
    def getStandardDeviationFeatureValue(self):
        r"""
Andrea Bizzego's avatar
Andrea Bizzego committed
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
    **15. Standard Deviation**

    .. math::
      \textit{standard deviation} = \sqrt{\frac{1}{N_p}\sum^{N_p}_{i=1}{(\textbf{X}(i)-\bar{X})^2}}

    Standard Deviation measures the amount of variation or dispersion from the Mean Value. By definition,
    :math:`\textit{standard deviation} = \sqrt{\textit{variance}}`

    .. note::
      As this feature is correlated with variance, it is marked so it is not enabled by default.
      To include this feature in the extraction, specify it by name in the enabled features
      (i.e. this feature will not be enabled if no individual features are specified (enabling 'all' features),
      but will be enabled when individual features are specified, including this feature).
      Not present in IBSI feature definitions (correlated with variance)
    """

316
        return numpy.std(self.targetVoxelArray)
Andrea Bizzego's avatar
Andrea Bizzego committed
317

318
319
    def getSkewnessFeatureValue(self, axis=0):
        r"""
Andrea Bizzego's avatar
Andrea Bizzego committed
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
    **16. Skewness**

    .. math::
      \textit{skewness} = \displaystyle\frac{\mu_3}{\sigma^3} =
      \frac{\frac{1}{N_p}\sum^{N_p}_{i=1}{(\textbf{X}(i)-\bar{X})^3}}
      {\left(\sqrt{\frac{1}{N_p}\sum^{N_p}_{i=1}{(\textbf{X}(i)-\bar{X})^2}}\right)^3}

    Where :math:`\mu_3` is the 3\ :sup:`rd` central moment.

    Skewness measures the asymmetry of the distribution of values about the Mean value. Depending on where the tail is
    elongated and the mass of the distribution is concentrated, this value can be positive or negative.

    Related links:

    https://en.wikipedia.org/wiki/Skewness

    .. note::
      In case of a flat region, the standard deviation and 4\ :sup:`rd` central moment will be both 0. In this case, a
      value of 0 is returned.
    """

341
342
        m2 = self._moment(self.targetVoxelArray, 2, axis)
        m3 = self._moment(self.targetVoxelArray, 3, axis)
Andrea Bizzego's avatar
Andrea Bizzego committed
343

344
345
        if m2 == 0:  # Flat Region
            return 0
Andrea Bizzego's avatar
Andrea Bizzego committed
346

347
        return m3 / m2 ** 1.5
Andrea Bizzego's avatar
Andrea Bizzego committed
348

349
350
    def getKurtosisFeatureValue(self, axis=0):
        r"""
Andrea Bizzego's avatar
Andrea Bizzego committed
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
    **17. Kurtosis**

    .. math::
      \textit{kurtosis} = \displaystyle\frac{\mu_4}{\sigma^4} =
      \frac{\frac{1}{N_p}\sum^{N_p}_{i=1}{(\textbf{X}(i)-\bar{X})^4}}
      {\left(\frac{1}{N_p}\sum^{N_p}_{i=1}{(\textbf{X}(i)-\bar{X}})^2\right)^2}

    Where :math:`\mu_4` is the 4\ :sup:`th` central moment.

    Kurtosis is a measure of the 'peakedness' of the distribution of values in the image ROI. A higher kurtosis implies
    that the mass of the distribution is concentrated towards the tail(s) rather than towards the mean. A lower kurtosis
    implies the reverse: that the mass of the distribution is concentrated towards a spike near the Mean value.

    Related links:

    https://en.wikipedia.org/wiki/Kurtosis

    .. note::
      In case of a flat region, the standard deviation and 4\ :sup:`rd` central moment will be both 0. In this case, a
      value of 0 is returned.

    .. note::
      The IBSI feature definition implements excess kurtosis, where kurtosis is corrected by -3, yielding 0 for normal
      distributions. The PyRadiomics kurtosis is not corrected, yielding a value 3 higher than the IBSI kurtosis.
    """

377
378
        m2 = self._moment(self.targetVoxelArray, 2, axis)
        m4 = self._moment(self.targetVoxelArray, 4, axis)
Andrea Bizzego's avatar
Andrea Bizzego committed
379

380
381
        if m2 == 0:  # Flat Region
            return 0
Andrea Bizzego's avatar
Andrea Bizzego committed
382

383
        return m4 / m2 ** 2.0
Andrea Bizzego's avatar
Andrea Bizzego committed
384

385
386
    def getVarianceFeatureValue(self):
        r"""
Andrea Bizzego's avatar
Andrea Bizzego committed
387
388
389
390
391
392
393
394
395
    **18. Variance**

    .. math::
      \textit{variance} = \frac{1}{N_p}\displaystyle\sum^{N_p}_{i=1}{(\textbf{X}(i)-\bar{X})^2}

    Variance is the the mean of the squared distances of each intensity value from the Mean value. This is a measure of
    the spread of the distribution about the mean. By definition, :math:`\textit{variance} = \sigma^2`
    """

396
        return numpy.std(self.targetVoxelArray) ** 2
Andrea Bizzego's avatar
Andrea Bizzego committed
397

398
399
    def getUniformityFeatureValue(self):
        r"""
Andrea Bizzego's avatar
Andrea Bizzego committed
400
401
402
403
404
405
406
407
408
409
410
411
412
    **19. Uniformity**

    .. math::
      \textit{uniformity} = \displaystyle\sum^{N_g}_{i=1}{p(i)^2}

    Uniformity is a measure of the sum of the squares of each intensity value. This is a measure of the homogeneity of
    the image array, where a greater uniformity implies a greater homogeneity or a smaller range of discrete intensity
    values.

    .. note::
      Defined by IBSI as Intensity Histogram Uniformity.
    """

413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
        eps = numpy.spacing(1)
        bins = self._getDiscretizedTargetVoxelArray()
        sumBins = bins.sum()

        if sumBins == 0:  # No segmented voxels
            return 0

        bins = bins / (float(sumBins + eps))
        return numpy.sum(bins ** 2)

    def getSuvMaxFeatureValue(self):
        r"""
    **20. SUV max**

    Implemented as one of the intensity features extracted by valieres et al.
    Maximum SUV of the tumour region. 

    - input: 3D array representing the PET volume in SUV format, with 
               voxels outside the ROI set to NaNs.

    .. note::
      Extracted from PET scans and not used in the CT feature set.
    """
        ROIPet = self.imageArray
        mask = self.maskArray
        ROIPet[~mask] = numpy.nan

        return numpy.max(ROIPet[~numpy.isnan(ROIPet)])

    def getSuvMeanFeatureValue(self):
        r"""
    **21. SUV mean**

    Implemented as one of the intensity features extracted by valieres et al.
    Average SUV of the tumour region. 

    - input: 3D array representing the PET volume in SUV format, with 
               voxels outside the ROI set to NaNs.

    .. note::
      Extracted from PET scans and not used in the CT feature set.
    """
        ROIPet = self.imageArray
        mask = self.maskArray
        ROIPet[~mask] = numpy.nan

        return numpy.mean(ROIPet[~numpy.isnan(ROIPet)])

    def getTLGFeatureValue(self):
        r"""
    **21. TLG**

    Total lesion glycolysis. 
    Defined as 
    
    .. math::
    \textit{SUVMean}\times \textit{total volume of the tumour region}
 
    - input: 3D array representing the PET volume in SUV format, with 
               voxels outside the ROI set to NaNs.
 
    .. note::
      Extracted from PET scans and not used in the CT feature set.
    """
        z, y, x = self.pixelSpacing
        Np = len(self.labelledVoxelCoordinates[0])
        volume = Np * (z * x * y)
Andrea Bizzego's avatar
Andrea Bizzego committed
480

481
482
483
484
485
        ROIPet = self.imageArray
        mask = self.maskArray
        ROIPet[~mask] = numpy.nan

        return numpy.mean(ROIPet[~numpy.isnan(ROIPet)]) * volume
Andrea Bizzego's avatar
Andrea Bizzego committed
486

487
488
    def getInactiveVolumeFeatureValue(self):
        r"""
489
    **22. Inactive volume **
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546

    Percentage of the tumour region that is inactive. Ast defined by Valieres et al
    a threshold of 0.01 × (SUVmax)^2 followed by closing and opening morphological operations were used 
    to differentiate active and inactive regions on FDG-PET scans
    
    - input: 3D array representing the PET volume in SUV format, with 
               voxels outside the ROI set to NaNs.

    .. note::
      Extracted from PET scans and not used in the CT feature set.
    """
        ROIPet = self.imageArray
        mask = self.maskArray

        ROIPet[~mask] = 0

        thresh = 0.01 * (numpy.max(ROIPet[~numpy.isnan(ROIPet)]) ** 2)

        mask_inactive = ROIPet > thresh

        # MORPHOLOGICAL OPERATIONS
        conn = numpy.zeros([5, 5, 5])
        conn[:, :, 0] = numpy.array(
            [
                [0, 0, 0, 0, 0],
                [0, 0, 0, 0, 0],
                [0, 0, 1, 0, 0],
                [0, 0, 0, 0, 0],
                [0, 0, 0, 0, 0],
            ]
        )
        conn[:, :, 4] = conn[:, :, 0]

        conn[:, :, 1] = numpy.array(
            [
                [0, 0, 0, 0, 0],
                [0, 0, 1, 0, 0],
                [0, 1, 1, 1, 0],
                [0, 0, 1, 0, 0],
                [0, 0, 0, 0, 0],
            ]
        )
        conn[:, :, 3] = conn[:, :, 1]

        conn[:, :, 2] = numpy.array(
            [
                [0, 0, 1, 0, 0],
                [0, 1, 1, 1, 0],
                [1, 1, 1, 1, 1],
                [0, 1, 1, 1, 0],
                [0, 0, 1, 0, 0],
            ]
        )

        with Oct2Py() as oc:
            try:
                oc.eval('pkg load image')
Nicole Bussola's avatar
Nicole Bussola committed
547
548
549
                perimeter = oc.bwperim(mask, 26)
                mask_inactive = oc.imclose(mask_inactive, conn)
                mask_inactive = oc.imopen(mask_inactive, conn)
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
                new_mask = mask_inactive + perimeter
                new_mask[mask == 0] = 10
                new_mask[new_mask == 1] = 10
                new_mask[new_mask == 2] = 10
                new_mask[new_mask == 0] = 1
                new_mask[new_mask == 10] = 0

                connObjects = oc.bwconncomp(new_mask, 26)
                b = numpy.zeros((1, connObjects.NumObjects))

                for i in range(connObjects.NumObjects):
                    a = oc.find(
                        len(connObjects.PixelIdxList[i]) >= 15
                    )  # If the number of of pixel forming and object is lower than 15, reject it
                    if a.size == 0:
                        b[i] = 0
                    else:
                        b[i] = 1

                [row, col] = oc.find(b > 0)

                sumInactive = 0

                for i in range(len(col)):
                    sumInactive = sumInactive + len(
                        connObjects.PixelIdxList[row[i], col[i]]
                    )

                sumVolume = numpy.sum(mask)
                import ipdb

                ipdb.set_trace()

583
584
585
586
            except Oct2PyError as e:
                print(e)
                oc.exit()

587
        return sumInactive / sumVolume * 100
588
589
590

    def getAUCCSHFeatureValue(self):
        r"""
591
    **23. AUCCSH **
592
593
594
595
596
597
598
599
600
601
602
603
604
605

    Area under the curve of the cumulative SUV-volume histogram describing the percentage 
    of total tumour volume above a percentage threshold of maximum SUV, as defined by van Velden et al.

    - input: 3D array representing the PET volume in SUV format, with 
               voxels outside the ROI set to NaNs.
    .. note::
      Extracted from PET scans and not used in the CT feature set.
    """
        nBins = 1000  # By default.
        ROIPet = self.imageArray
        mask = self.maskArray

        ROIPet[~mask] = numpy.nan
Nicole Bussola's avatar
Nicole Bussola committed
606

607
608
609
610
611
612
613
        outliers = numpy.where(
            ROIPet
            > (
                numpy.mean(ROIPet[~numpy.isnan(ROIPet)])
                + 3 * numpy.std(ROIPet[~numpy.isnan(ROIPet)])
            )
        )[0]
Nicole Bussola's avatar
Nicole Bussola committed
614
615

        good_voxels = numpy.where(
616
617
618
619
620
621
622
            ROIPet
            <= (
                numpy.mean(ROIPet[~numpy.isnan(ROIPet)])
                + 3 * numpy.std(ROIPet[~numpy.isnan(ROIPet)])
            )
        )[0]

Nicole Bussola's avatar
Nicole Bussola committed
623
624
625
        ROIPet[outliers] = numpy.mean(ROIPet[good_voxels])
        ROIPet = ROIPet - numpy.min(ROIPet[~numpy.isnan(ROIPet)])
        ROIPet = ROIPet / numpy.max(ROIPet[~numpy.isnan(ROIPet)])
626
627
628
        volume = ROIPet[~numpy.isnan(ROIPet)]
        nVoxel = len(volume)

Nicole Bussola's avatar
Nicole Bussola committed
629
        bins, _ = numpy.histogram(volume, nBins)
630

Nicole Bussola's avatar
Nicole Bussola committed
631
        csh = numpy.flipud(numpy.cumsum(numpy.flipud(bins)) / nVoxel)
632
633
        return numpy.sum(csh / nBins)

634
635
636
637
    def getSuvPeakFeatureValue(self):
        r"""
    **24. SuvPeak**

638
    Average of the voxel with maximum SUV within the tumour region and its 26 connected neighbours. 
639
640
641
642
643
644
645
646
647
 
    - input: 3D array representing the PET volume in SUV format, with 
               voxels outside the ROI set to NaNs.
 
    .. note::
      Extracted from PET scans and not used in the CT feature set.
    """
        ROIPet = self.imageArray
        mask = self.maskArray
648

649
        ROIPet[~mask] = numpy.nan
650

651
        oc = Oct2Py()
652
        # ROIPet = oc.double(ROIPet.tolist())
653
654
655
656
657
658
659
660
661

        with Oct2Py() as oc:
            try:
                oc.eval('pkg load image')
                ROIPet = oc.padarray(
                    ROIPet, oc.double(numpy.array([1, 1, 1]).tolist()), numpy.nan
                )

                SUVmax = numpy.max(ROIPet[~numpy.isnan(ROIPet)])
662
663
664
                indMax = numpy.where(ROIPet == SUVmax)

                indMaxX, indMaxY, indMaxZ = indMax[0][0], indMax[1][0], indMax[2][0]
665

666
667
668
669
670
671
                # connectivity = oc.getneighbors(
                #     oc.strel(
                #         'arbitrary',
                #         oc.double(numpy.ones((3, 3, 3), dtype=numpy.int).tolist()),
                #     )
                # )
672
                # import ipdb
673

674
                # ipdb.set_trace()
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
                connectivity = numpy.array(
                    [
                        [-1, -1, -1],
                        [0, -1, -1],
                        [1, -1, -1],
                        [-1, 0, -1],
                        [0, 0, -1],
                        [1, 0, -1],
                        [-1, 1, -1],
                        [0, 1, -1],
                        [1, 1, -1],
                        [-1, -1, 0],
                        [0, -1, 0],
                        [1, -1, 0],
                        [-1, 0, 0],
                        [0, 0, 0],
                        [1, 0, 0],
                        [-1, 1, 0],
                        [0, 1, 0],
                        [1, 1, 0],
                        [-1, -1, 1],
                        [0, -1, 1],
                        [1, -1, 1],
                        [-1, 0, 1],
                        [0, 0, 1],
                        [1, 0, 1],
                        [-1, 1, 1],
                        [0, 1, 1],
                        [1, 1, 1],
                    ]
705
706
                )
                nPeak = len(connectivity)
707
                neighborsMax = numpy.zeros((1, nPeak))
708
709

                for i in range(nPeak):
710
711
712
713
                    neighborsMax[0, i] = ROIPet[
                        connectivity[i, 0] + indMaxX - 1,
                        connectivity[i, 1] + indMaxY - 1,
                        connectivity[i, 2] + indMaxZ - 1,
714
                    ]
715
                # import ipdb
716

717
                # ipdb.set_trace()
718
719
720
721
            except Oct2PyError as e:
                print(e)
                oc.exit()

722
        return numpy.mean(neighborsMax[~numpy.isnan(neighborsMax)])
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738

    def getgETUFeatureValue(self):
        r"""
    **25. gETU**

    Generalized effective total uptake, with parameter a = 0.25 as defined by Rahim et al.

    - input: 3D array representing the PET volume in SUV format, with 
               voxels outside the ROI set to NaNs.

    .. note::
      Extracted from PET scans and not used in the CT feature set.
    """
        ROIPet = self.imageArray
        mask = self.maskArray
        ROIPet[~mask] = numpy.nan
Nicole Bussola's avatar
Nicole Bussola committed
739

740
741
742
        a = 0.25
        n_voxels = numpy.sum(ROIPet[~numpy.isnan(ROIPet)])
        ROIPet = ROIPet ** a
Nicole Bussola's avatar
Nicole Bussola committed
743

744
        return numpy.sum(ROIPet[~numpy.isnan(ROIPet)] / n_voxels) ** (1 / a)
745