All files / tools/src/utilities/segmentation/growCut runGrowCut.ts

2.85% Statements 3/105
0% Branches 0/24
0% Functions 0/4
2.88% Lines 3/104

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 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 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 480 481 482 483 484 485 486 487 488 489 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 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572        428x 428x   428x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        
import { cache } from '@cornerstonejs/core';
import type { Types } from '@cornerstonejs/core';
import shaderCode from './growCutShader';
 
const GB = 1024 * 1024 * 1024;
const WEBGPU_MEMORY_LIMIT = 1.99 * GB;
 
const DEFAULT_GROWCUT_OPTIONS = {
  windowSize: 3,
  maxProcessingTime: 30000,
  inspection: {
    numCyclesInterval: 5,
    numCyclesBelowThreshold: 3,
    threshold: 1e-4,
  },
};
 
/**
 * Grow cut options
 */
type GrowCutOptions = {
  /**
   * Maximum amount of time the grow cut will be running in the GPU. This value
   * also depends on `numCyclesInterval` because N (numCyclesInterval) steps are
   * pushed to the GPU asynchronously and only after getting the response back
   * for running those N steps it would check if the amount of time spent is
   * greater than `maxProcessingTime`.
   *
   * As an example, let say `numCyclesInterval` is set to 30 and `maxProcessingTime`
   * is set to 1 second. If it takes 45ms to run each batch of 30 cycles in the
   * GPU that means it should stop after running 23 batches and that would take
   * 1.035 second which is greater than 1 second.
   */
  maxProcessingTime?: number;
  /**
   * Window used to compare each voxel to all its NxNxN neighbors. Large window
   * size may result in a better segmentation but it would also take more time
   * to compute
   */
  windowSize?: number;
  /**
   * Configuration used to monitor and stop processing the volume before
   * reaching the number of steps expected to segment the volume.
   */
 
  positiveSeedValue?: number;
  negativeSeedValue?: number;
  positiveSeedVariance?: number;
  negativeSeedVariance?: number;
 
  inspection?: {
    /**
     * Number of grow cut steps (FOR loop) that shall be run in the GPU before
     * checking its current state. This is useful because if the expected number
     * of cycles is 100 it may get the segmentation done after 27 cycles. That
     * means if `numCyclesInterval` is set to 10 it would stop after 30 cycles
     * (3 batches * 10 cycles) saving 70 cycles.
     *
     * It changes automaticaly to 1 once it detects that its running below the
     * `threshold` and get back to `numCyclesInterval` if it gets above the
     * `threshold` again.
     *
     * Small values are not good because taking data out of the gpu to compare
     * is very expesive. Higher values may let the algorithm run for a few more
     * cycles even when it is already done.
     *
     * PS: 1 cycle is equal to 1 grow cut iteration (FOR loop running in the GPU)
     */
    numCyclesInterval?: number;
    /**
     * It stops running grow cut once it keeps below the threshold (see `threshold`)
     * for a few cycles (`numCyclesBelowThreashold`).
     */
    numCyclesBelowThreashold?: number;
    /**
     * Threshold used to decide if it should or not stop running grow cut. It
     * stops only after staying N cycles (`numCyclesBelowThreashold`) below this
     * threshold. In some cases the number of voxels updated may decrease
     * but increase again after a few cycles.
     *
     *   threshold = number of voxels updated / total number of voxels
     */
    threshold?: number;
  };
};
 
/**
 * Run the grow cut algorithm in the gpu (compute shader) and updates the label
 * map passed in as parameter.
 *
 * The volume, labelmap, another local buffer called `strengthBuffer` and the
 * previous state buffers are sent to the gpu that runs grow cut comparing each
 * voxel to all NxNxN neighbors voxels updating the labelmap accordingly.
 *
 * It also checks if the segmentation is complete before the expected number of
 * steps and stop when that happens saving processing time.
 *
 * @param referenceVolumeId - Volume id
 * @param labelmapVolumeId - Label map associated with the given volumeId
 * @param options - Options
 */
async function runGrowCut(
  referenceVolumeId: string,
  labelmapVolumeId: string,
  options: GrowCutOptions = DEFAULT_GROWCUT_OPTIONS
) {
  const workGroupSize = [8, 8, 4];
  const { windowSize, maxProcessingTime } = Object.assign(
    {},
    DEFAULT_GROWCUT_OPTIONS,
    options
  );
 
  const inspection = Object.assign(
    {},
    DEFAULT_GROWCUT_OPTIONS.inspection,
    options.inspection
  );
 
  const volume = cache.getVolume(referenceVolumeId);
  const labelmap = cache.getVolume(labelmapVolumeId);
 
  const [columns, rows, numSlices] = volume.dimensions;
 
  if (
    labelmap.dimensions[0] !== columns ||
    labelmap.dimensions[1] !== rows ||
    labelmap.dimensions[2] !== numSlices
  ) {
    throw new Error('Volume and labelmap must have the same size');
  }
 
  let numIterations = Math.floor(
    Math.sqrt(rows ** 2 + columns ** 2 + numSlices ** 2) / 2
  );
 
  numIterations = Math.min(numIterations, 500);
 
  const labelmapData =
    labelmap.voxelManager.getCompleteScalarDataArray() as Types.PixelDataTypedArray;
 
  let volumePixelData =
    volume.voxelManager.getCompleteScalarDataArray() as Types.PixelDataTypedArray;
  if (!(volumePixelData instanceof Float32Array)) {
    volumePixelData = new Float32Array(volumePixelData);
  }
 
  const requiredLimits = {
    maxStorageBufferBindingSize: WEBGPU_MEMORY_LIMIT,
    maxBufferSize: WEBGPU_MEMORY_LIMIT,
  };
 
  const adapter = await navigator.gpu?.requestAdapter();
  const device = await adapter.requestDevice({ requiredLimits });
  const BUFFER_SIZE = volumePixelData.byteLength;
 
  // Stores the number of voxels updated per iteration. If it expects to run 100
  // steps to segment the volume it then allocate 100 x 4 bytes and in the end
  // we know how many voxels got updated per iteration.
  const UPDATED_VOXELS_COUNTER_BUFFER_SIZE =
    numIterations * Uint32Array.BYTES_PER_ELEMENT;
 
  // Buffer to track the bounds of modified voxels 6 int32 values for min/max x,y,z
  const BOUNDS_BUFFER_SIZE = 6 * Int32Array.BYTES_PER_ELEMENT;
 
  const shaderModule = device.createShaderModule({
    code: shaderCode,
  });
 
  // `numIteration` index in the `paramsArrayValues` array
  const numIterationIndex = 3;
 
  const paramsArrayValues = new Uint32Array([
    columns,
    rows,
    numSlices,
    0, // reserved for `numIteration`
  ]);
 
  const gpuParamsBuffer = device.createBuffer({
    size: paramsArrayValues.byteLength,
    usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
  });
 
  const gpuVolumePixelDataBuffer = device.createBuffer({
    size: BUFFER_SIZE,
    usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST,
  });
 
  device.queue.writeBuffer(gpuVolumePixelDataBuffer, 0, volumePixelData);
 
  const gpuLabelmapBuffers = [0, 1].map(() =>
    device.createBuffer({
      size: BUFFER_SIZE,
      usage:
        GPUBufferUsage.STORAGE |
        GPUBufferUsage.COPY_SRC |
        GPUBufferUsage.COPY_DST,
    })
  );
 
  device.queue.writeBuffer(
    gpuLabelmapBuffers[0],
    0,
    new Uint32Array(labelmapData)
  );
 
  const gpuStrengthBuffers = [0, 1].map(() => {
    const strengthBuffer = device.createBuffer({
      size: BUFFER_SIZE,
      usage:
        GPUBufferUsage.STORAGE |
        GPUBufferUsage.COPY_SRC |
        GPUBufferUsage.COPY_DST,
    });
 
    return strengthBuffer;
  });
 
  // This buffer stores the number of voxels updated on each iteration making it
  // more performant when calculating the threshold instead of having to move the
  // entire labelmap which may be huge from the gpu to the cpu.
  const gpuCounterBuffer = device.createBuffer({
    size: UPDATED_VOXELS_COUNTER_BUFFER_SIZE,
    usage:
      GPUBufferUsage.STORAGE |
      GPUBufferUsage.COPY_SRC |
      GPUBufferUsage.COPY_DST,
  });
 
  const gpuBoundsBuffer = device.createBuffer({
    size: BOUNDS_BUFFER_SIZE,
    usage:
      GPUBufferUsage.STORAGE |
      GPUBufferUsage.COPY_SRC |
      GPUBufferUsage.COPY_DST,
  });
 
  // Initialize bounds buffer with extreme values
  const initialBounds = new Int32Array([
    columns, // minX (initialized to max value)
    rows, // minY (initialized to max value)
    numSlices, // minZ (initialized to max value)
    -1, // maxX (initialized to min value)
    -1, // maxY (initialized to min value)
    -1, // maxZ (initialized to min value)
  ]);
 
  device.queue.writeBuffer(gpuBoundsBuffer, 0, initialBounds);
 
  const bindGroupLayout = device.createBindGroupLayout({
    entries: [
      {
        binding: 0,
        visibility: GPUShaderStage.COMPUTE,
        buffer: {
          type: 'uniform',
        },
      },
      {
        binding: 1,
        visibility: GPUShaderStage.COMPUTE,
        buffer: {
          type: 'read-only-storage',
        },
      },
      {
        binding: 2,
        visibility: GPUShaderStage.COMPUTE,
        buffer: {
          type: 'storage',
        },
      },
      {
        binding: 3,
        visibility: GPUShaderStage.COMPUTE,
        buffer: {
          type: 'storage',
        },
      },
      {
        binding: 4,
        visibility: GPUShaderStage.COMPUTE,
        buffer: {
          type: 'read-only-storage',
        },
      },
      {
        binding: 5,
        visibility: GPUShaderStage.COMPUTE,
        buffer: {
          type: 'read-only-storage',
        },
      },
      {
        binding: 6,
        visibility: GPUShaderStage.COMPUTE,
        buffer: {
          type: 'storage',
        },
      },
      {
        binding: 7,
        visibility: GPUShaderStage.COMPUTE,
        buffer: {
          type: 'storage',
        },
      },
    ],
  });
 
  const bindGroups = [0, 1].map((i) => {
    const outputLabelmapBuffer = gpuLabelmapBuffers[i];
    const outputStrengthBuffer = gpuStrengthBuffers[i];
    const previouLabelmapBuffer = gpuLabelmapBuffers[(i + 1) % 2];
    const previousStrengthBuffer = gpuStrengthBuffers[(i + 1) % 2];
 
    return device.createBindGroup({
      layout: bindGroupLayout,
      entries: [
        {
          binding: 0,
          resource: {
            buffer: gpuParamsBuffer,
          },
        },
        {
          binding: 1,
          resource: {
            buffer: gpuVolumePixelDataBuffer,
          },
        },
        {
          binding: 2,
          resource: {
            buffer: outputLabelmapBuffer,
          },
        },
        {
          binding: 3,
          resource: {
            buffer: outputStrengthBuffer,
          },
        },
        {
          binding: 4,
          resource: {
            buffer: previouLabelmapBuffer,
          },
        },
        {
          binding: 5,
          resource: {
            buffer: previousStrengthBuffer,
          },
        },
        {
          binding: 6,
          resource: {
            buffer: gpuCounterBuffer,
          },
        },
        {
          binding: 7,
          resource: {
            buffer: gpuBoundsBuffer,
          },
        },
      ],
    });
  });
 
  const pipeline = device.createComputePipeline({
    layout: device.createPipelineLayout({
      bindGroupLayouts: [bindGroupLayout],
    }),
    compute: {
      module: shaderModule,
      entryPoint: 'main',
      constants: {
        workGroupSizeX: workGroupSize[0],
        workGroupSizeY: workGroupSize[1],
        workGroupSizeZ: workGroupSize[2],
        windowSize,
      },
    },
  });
 
  const numWorkGroups = [
    Math.ceil(columns / workGroupSize[0]),
    Math.ceil(rows / workGroupSize[1]),
    Math.ceil(numSlices / workGroupSize[2]),
  ];
 
  const gpuUpdatedVoxelsCounterStagingBuffer = device.createBuffer({
    size: UPDATED_VOXELS_COUNTER_BUFFER_SIZE,
    usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST,
  });
 
  const limitProcessingTime = maxProcessingTime
    ? performance.now() + maxProcessingTime
    : 0;
  let currentInspectionNumCyclesInterval = inspection.numCyclesInterval;
  let belowThresholdCounter = 0;
 
  // Create each iteration step and submit them to the GPU
  for (let i = 0; i < numIterations; i++) {
    paramsArrayValues[numIterationIndex] = i;
    device.queue.writeBuffer(gpuParamsBuffer, 0, paramsArrayValues);
 
    const commandEncoder = device.createCommandEncoder();
    const passEncoder = commandEncoder.beginComputePass();
    passEncoder.setPipeline(pipeline);
 
    passEncoder.setBindGroup(0, bindGroups[i % 2]);
    passEncoder.dispatchWorkgroups(
      numWorkGroups[0],
      numWorkGroups[1],
      numWorkGroups[2]
    );
 
    passEncoder.end();
 
    // Get the number of updated voxels for the current iteration only
    commandEncoder.copyBufferToBuffer(
      gpuCounterBuffer,
      i * Uint32Array.BYTES_PER_ELEMENT, // Source offset
      gpuUpdatedVoxelsCounterStagingBuffer,
      i * Uint32Array.BYTES_PER_ELEMENT, // Destination offset
      Uint32Array.BYTES_PER_ELEMENT
    );
 
    device.queue.submit([commandEncoder.finish()]);
 
    // Read some data out of the gpu on every N steps to see if it is already done
    const inspect = i > 0 && !(i % currentInspectionNumCyclesInterval);
 
    if (inspect) {
      // map staging buffer to read results back to JS
      await gpuUpdatedVoxelsCounterStagingBuffer.mapAsync(
        GPUMapMode.READ,
        0, // Offset
        UPDATED_VOXELS_COUNTER_BUFFER_SIZE // Length
      );
 
      const updatedVoxelsCounterResultBuffer =
        gpuUpdatedVoxelsCounterStagingBuffer.getMappedRange(
          0,
          UPDATED_VOXELS_COUNTER_BUFFER_SIZE
        );
 
      const updatedVoxelsCounterBufferData = new Uint32Array(
        updatedVoxelsCounterResultBuffer.slice(0)
      );
 
      const updatedVoxelsRatio =
        updatedVoxelsCounterBufferData[i] / volumePixelData.length;
 
      gpuUpdatedVoxelsCounterStagingBuffer.unmap();
 
      // Skip i=0 because the labelmap is not updated on the first iteration
      if (i >= 1 && updatedVoxelsRatio < inspection.threshold) {
        // Once if gets below the threshold it needs to check one by one otherwise
        // it may skip the stop point.
        currentInspectionNumCyclesInterval = 1;
        belowThresholdCounter++;
 
        if (belowThresholdCounter === inspection.numCyclesBelowThreshold) {
          break;
        }
      } else {
        // Reset it back to its original value
        currentInspectionNumCyclesInterval = inspection.numCyclesInterval;
      }
    }
 
    if (limitProcessingTime && performance.now() > limitProcessingTime) {
      console.warn(`Exceeded processing time limit (${maxProcessingTime})ms`);
      break;
    }
  }
 
  const commandEncoder = device.createCommandEncoder();
  const outputLabelmapBufferIndex = (numIterations + 1) % 2;
  const labelmapStagingBuffer = device.createBuffer({
    size: BUFFER_SIZE,
    usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST,
  });
 
  // Create a staging buffer for reading the bounds
  const boundsStagingBuffer = device.createBuffer({
    size: BOUNDS_BUFFER_SIZE,
    usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST,
  });
 
  // Copy output buffer to staging buffer
  commandEncoder.copyBufferToBuffer(
    gpuLabelmapBuffers[outputLabelmapBufferIndex],
    0, // Source offset
    labelmapStagingBuffer,
    0, // Destination offset
    BUFFER_SIZE
  );
 
  // Copy bounds buffer to staging buffer
  commandEncoder.copyBufferToBuffer(
    gpuBoundsBuffer,
    0, // Source offset
    boundsStagingBuffer,
    0, // Destination offset
    BOUNDS_BUFFER_SIZE
  );
 
  device.queue.submit([commandEncoder.finish()]);
 
  // map staging buffer to read results back to JS
  await labelmapStagingBuffer.mapAsync(
    GPUMapMode.READ,
    0, // Offset
    BUFFER_SIZE // Length
  );
 
  const labelmapResultBuffer = labelmapStagingBuffer.getMappedRange(
    0,
    BUFFER_SIZE
  );
 
  const labelmapResult = new Uint32Array(labelmapResultBuffer);
 
  // Copy the resulting buffer (Uint32) returned by the gpu to the `labelmapData` (Uint8)
  labelmapData.set(labelmapResult);
 
  // Release the gpu staging buffer used to copy the data from the gpu
  labelmapStagingBuffer.unmap();
 
  // Read the bounds information from the GPU
  await boundsStagingBuffer.mapAsync(
    GPUMapMode.READ,
    0, // Offset
    BOUNDS_BUFFER_SIZE // Length
  );
 
  const boundsResultBuffer = boundsStagingBuffer.getMappedRange(
    0,
    BOUNDS_BUFFER_SIZE
  );
 
  const boundsResult = new Int32Array(boundsResultBuffer.slice(0));
  boundsStagingBuffer.unmap();
 
  // Extract bounds values
  const minX = boundsResult[0];
  const minY = boundsResult[1];
  const minZ = boundsResult[2];
  const maxX = boundsResult[3];
  const maxY = boundsResult[4];
  const maxZ = boundsResult[5];
 
  // update the voxel manager with the new labelmap data
  labelmap.voxelManager.setCompleteScalarDataArray(labelmapData);
 
  labelmap.voxelManager.clearBounds();
  labelmap.voxelManager.setBounds([
    [minX, maxX],
    [minY, maxY],
    [minZ, maxZ],
  ]);
}
 
export { runGrowCut as default, runGrowCut as run };
export type { GrowCutOptions };