All files / tools/src/utilities/segmentation getStatistics.ts

76.04% Statements 73/96
58.97% Branches 23/39
84.61% Functions 11/13
75.78% Lines 72/95

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354                              428x                                                     16x   16x   16x   16x                   16x     16x         16x 16x                           16x                         16x             16x   16x       16x   16x 16x         16x   16x               16x               16x       16x                       16x   16x                 16x 16x 32x               16x       428x 128x       128x 1680x     128x 64x   64x       428x             32x 32x 32x   32x             32x 96x     32x 160x             160x     160x 160x 48x               48x             48x 48x       32x 32x 32x   32x             32x     32x                                                                                                                   160x   160x       480x       160x 39200x 39200x 39200x 39200x 39200x   160x 11680x 11680x     11680x   160x   160x           160x        
import { utilities, getWebWorkerManager } from '@cornerstonejs/core';
import {
  triggerWorkerProgress,
  getSegmentationDataForWorker,
  prepareVolumeStrategyDataForWorker,
  prepareStackDataForWorker,
  getImageReferenceInfo,
} from './utilsForWorker';
import { getPixelValueUnitsImageId } from '../getPixelValueUnits';
import VolumetricCalculator from './VolumetricCalculator';
import { WorkerTypes } from '../../enums';
import type { NamedStatistics } from '../../types';
import { registerComputeWorker } from '../registerComputeWorker';
 
// Radius for a volume of 10, eg 1 cm^3 = 1000 mm^3
const radiusForVol1 = Math.pow((3 * 1000) / (4 * Math.PI), 1 / 3);
 
/**
 * Get statistics for a segmentation.
 *
 * @param segmentationId - The segmentation ID.
 * @param segmentIndices - The segment indices to get statistics for.
 *   - If a single number is provided, it retrieves statistics for that specific segment.
 *   - If an array is provided:
 *     - In `collective` mode (default), it retrieves statistics for all voxels that belong to any of the specified segment indices (OR operation).
 *     - In `individual` mode, it retrieves statistics separately for each segment index.
 * @param mode - The computation mode (optional, defaults to `'collective'`).
 *   - `'collective'` (default): Treats the segment indices as a group, computing combined statistics.
 *   - `'individual'`: Treats each segment index separately, computing statistics for each one independently.
 *
 * @returns The statistics, either as a single aggregated result (if `collective` mode)
 * or an object with segment indices as keys and statistics as values (if `individual` mode).
 */
async function getStatistics({
  segmentationId,
  segmentIndices,
  mode = 'collective',
}: {
  segmentationId: string;
  segmentIndices: number[] | number;
  mode?: 'collective' | 'individual';
}): Promise<NamedStatistics | { [segmentIndex: number]: NamedStatistics }> {
  registerComputeWorker();
 
  triggerWorkerProgress(WorkerTypes.COMPUTE_STATISTICS, 0);
 
  const segData = getSegmentationDataForWorker(segmentationId, segmentIndices);
 
  Iif (!segData) {
    return;
  }
 
  const {
    operationData,
    segVolumeId,
    segImageIds,
    reconstructableVolume,
    indices,
  } = segData;
 
  // Get reference image ID and modality unit options
  const { refImageId, modalityUnitOptions } = getImageReferenceInfo(
    segVolumeId,
    segImageIds
  );
 
  const unit = getPixelValueUnitsImageId(refImageId, modalityUnitOptions);
  const stats = reconstructableVolume
    ? await calculateVolumeStatistics({
        operationData,
        indices,
        unit,
        mode,
      })
    : await calculateStackStatistics({
        segImageIds,
        indices,
        unit,
        mode,
      });
 
  return stats;
}
 
/**
 * Calculate statistics for a reconstructable volume
 */
async function calculateVolumeStatistics({
  operationData,
  indices,
  unit,
  mode,
}) {
  // Get the strategy data
  const strategyData = prepareVolumeStrategyDataForWorker(operationData);
 
  const {
    segmentationVoxelManager,
    imageVoxelManager,
    segmentationImageData,
    imageData,
  } = strategyData;
 
  Iif (!segmentationVoxelManager || !segmentationImageData) {
    return;
  }
 
  const spacing = segmentationImageData.getSpacing();
 
  const { boundsIJK: boundsOrig } = segmentationVoxelManager;
  Iif (!boundsOrig) {
    return VolumetricCalculator.getStatistics({ spacing });
  }
 
  const segmentationScalarData =
    segmentationVoxelManager.getCompleteScalarDataArray();
 
  const segmentationInfo = {
    scalarData: segmentationScalarData,
    dimensions: segmentationImageData.getDimensions(),
    spacing: segmentationImageData.getSpacing(),
    origin: segmentationImageData.getOrigin(),
    direction: segmentationImageData.getDirection(),
  };
 
  const imageInfo = {
    scalarData: imageVoxelManager.getCompleteScalarDataArray(),
    dimensions: imageData.getDimensions(),
    spacing: imageData.getSpacing(),
    origin: imageData.getOrigin(),
    direction: imageData.getDirection(),
  };
 
  Iif (!imageInfo.scalarData?.length) {
    return;
  }
 
  const stats = await getWebWorkerManager().executeTask(
    'compute',
    'calculateSegmentsStatisticsVolume',
    {
      segmentationInfo,
      imageInfo,
      indices,
      unit,
      mode,
    }
  );
 
  triggerWorkerProgress(WorkerTypes.COMPUTE_STATISTICS, 100);
 
  Iif (mode === 'collective') {
    return processSegmentationStatistics({
      stats,
      unit,
      spacing,
      segmentationImageData,
      imageVoxelManager,
    });
  } else {
    const finalStats = {};
    Object.entries(stats).forEach(([segmentIndex, stat]) => {
      finalStats[segmentIndex] = processSegmentationStatistics({
        stats: stat,
        unit,
        spacing,
        segmentationImageData,
        imageVoxelManager,
      });
    });
    return finalStats;
  }
}
 
const updateStatsArray = (stats, newStat) => {
  Iif (!stats.array) {
    return;
  }
 
  const existingIndex = stats.array.findIndex(
    (stat) => stat.name === newStat.name
  );
 
  if (existingIndex !== -1) {
    stats.array[existingIndex] = newStat;
  } else {
    stats.array.push(newStat);
  }
};
 
const processSegmentationStatistics = ({
  stats,
  unit,
  spacing,
  segmentationImageData,
  imageVoxelManager,
}) => {
  stats.mean.unit = unit;
  stats.max.unit = unit;
  stats.min.unit = unit;
 
  Iif (unit !== 'SUV') {
    return stats;
  }
 
  // Get the IJK rounded radius, not using less than 1, and using the
  // radius for the spacing given the desired mm spacing of 10
  // Add 10% to the radius to account for whole pixel in/out issues
  const radiusIJK = spacing.map((s) =>
    Math.max(1, Math.round((1.1 * radiusForVol1) / s))
  );
 
  for (const testMax of stats.maxIJKs) {
    const testStats = getSphereStats(
      testMax,
      radiusIJK,
      segmentationImageData,
      imageVoxelManager,
      spacing
    );
    Iif (!testStats) {
      continue;
    }
    const { mean } = testStats;
    if (!stats.peakValue || stats.peakValue.value <= mean.value) {
      stats.peakValue = {
        name: 'peakValue',
        label: 'Peak Value',
        value: mean.value,
        unit,
      };
 
      // Store the LPS point coordinates for peak SUV
      stats.peakPoint = {
        name: 'peakLPS',
        label: 'Peak SUV Point',
        value: testMax.pointLPS ? [...testMax.pointLPS] : null,
        unit: null,
      };
 
      updateStatsArray(stats, stats.peakValue);
      updateStatsArray(stats, stats.peakPoint);
    }
  }
 
  Eif (stats.volume && stats.mean) {
    const mtv = stats.volume.value;
    const suvMean = stats.mean.value;
 
    stats.lesionGlycolysis = {
      name: 'lesionGlycolysis',
      label: 'Lesion Glycolysis',
      value: mtv * suvMean,
      unit: `${stats.volume.unit}ยท${unit}`,
    };
 
    updateStatsArray(stats, stats.lesionGlycolysis);
  }
 
  return stats;
};
 
/**
 * Calculate statistics for a stack of images
 */
async function calculateStackStatistics({ segImageIds, indices, unit, mode }) {
  triggerWorkerProgress(WorkerTypes.COMPUTE_STATISTICS, 0);
 
  // Get segmentation and image info for each image in the stack
  const { segmentationInfo, imageInfo } =
    prepareStackDataForWorker(segImageIds);
 
  const stats = await getWebWorkerManager().executeTask(
    'compute',
    'calculateSegmentsStatisticsStack',
    {
      segmentationInfo,
      imageInfo,
      indices,
      mode,
    }
  );
 
  triggerWorkerProgress(WorkerTypes.COMPUTE_STATISTICS, 100);
 
  const spacing = segmentationInfo[0].spacing;
  const segmentationImageData = segmentationInfo[0];
  const imageVoxelManager = imageInfo[0].voxelManager;
 
  if (mode === 'collective') {
    return processSegmentationStatistics({
      stats,
      unit,
      spacing,
      segmentationImageData,
      imageVoxelManager,
    });
  } else {
    const finalStats = {};
    Object.entries(stats).forEach(([segmentIndex, stat]) => {
      finalStats[segmentIndex] = processSegmentationStatistics({
        stats: stat,
        unit,
        spacing,
        segmentationImageData,
        imageVoxelManager,
      });
    });
    return finalStats;
  }
}
 
/**
 * Gets the statistics for a 1 cm^3 sphere centered on radiusIJK.
 * Assumes the segmentation and pixel data are co-incident.
 */
function getSphereStats(testMax, radiusIJK, segData, imageVoxels, spacing) {
  const { pointIJK: centerIJK, pointLPS: centerLPS } = testMax;
 
  Iif (!centerIJK) {
    return;
  }
 
  const boundsIJK = centerIJK.map((ijk, idx) => [
    ijk - radiusIJK[idx],
    ijk + radiusIJK[idx],
  ]);
  const testFunction = (_pointLPS, pointIJK) => {
    const i = (pointIJK[0] - centerIJK[0]) / radiusIJK[0];
    const j = (pointIJK[1] - centerIJK[1]) / radiusIJK[1];
    const k = (pointIJK[2] - centerIJK[2]) / radiusIJK[2];
    const radius = i * i + j * j + k * k;
    return radius <= 1;
  };
  const statsFunction = ({ pointIJK, pointLPS }) => {
    const value = imageVoxels.getAtIJKPoint(pointIJK);
    Iif (value === undefined) {
      return;
    }
    VolumetricCalculator.statsCallback({ value, pointLPS, pointIJK });
  };
  VolumetricCalculator.statsInit({ storePointData: false });
 
  utilities.pointInShapeCallback(segData, {
    pointInShapeFn: testFunction,
    callback: statsFunction,
    boundsIJK,
  });
 
  return VolumetricCalculator.getStatistics({ spacing });
}
 
export default getStatistics;