All files / packages/tools/src/utilities/segmentation/InterpolationManager InterpolationManager.ts

61.7% Statements 58/94
43.33% Branches 26/60
90.9% Functions 10/11
61.7% Lines 58/94

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                                          1x   1x           1x     3x 1x                                                                                                                                                           1x 72x 72x     72x   72x       66x     6x 6x       6x 6x           6x   6x 6x     2x 2x 2x   4x       6x         6x         6x     4x         4x 4x 4x 6x       4x 4x     4x   6x       4x   4x 4x             1x 69x 69x 69x     69x   69x         69x                                                             1x 78x 78x     78x   78x 77x   1x   1x               1x 1x             1x 1x         7x       7x    
import { utilities as csUtils } from '@cornerstonejs/core';
import type { Types } from '@cornerstonejs/core';
import {
  AnnotationCompletedEventType,
  AnnotationModifiedEventType,
  AnnotationRemovedEventType,
} from '../../../types/EventTypes';
import { state as annotationState } from '../../../stateManagement/annotation';
import type AnnotationGroupSelector from '../../../types/AnnotationGroupSelector';
import getInterpolationDataCollection from '../../contours/interpolation/getInterpolationDataCollection';
import type {
  InterpolationViewportData,
  AcceptInterpolationSelector,
} from '../../../types/InterpolationTypes';
import interpolate from '../../contours/interpolation/interpolate';
import deleteRelatedAnnotations from './deleteRelatedAnnotations';
import { InterpolationROIAnnotation } from '../../../types/ToolSpecificAnnotationTypes';
import ChangeTypes from '../../../enums/ChangeTypes';
import getViewportForAnnotation from '../../getViewportForAnnotation';
import { addContourSegmentationAnnotation } from '../../contourSegmentation/addContourSegmentationAnnotation';
 
const { uuidv4 } = csUtils;
 
const ChangeTypesForInterpolation = [
  ChangeTypes.HandlesUpdated,
  ChangeTypes.InterpolationUpdated,
];
 
export default class InterpolationManager {
  static toolNames = [];
 
  static addTool(toolName: string) {
    if (!this.toolNames.includes(toolName)) {
      this.toolNames.push(toolName);
    }
  }
 
  /**
   * Accepts the autogenerated interpolations, marking them as non-autogenerated.
   * Can provide a selector to choose which ones to accept.
   *
   * Rules for which items to select:
   * 1. Only choose annotations having the same segment index and segmentationID
   * 2. Exclude all contours having the same interpolation UID as any other contours
   *    on the same slice.
   * 3. Exclude autogenerated annotations
   * 4. Exclude any reset interpolationUIDs (this is a manual operation to allow
   *    creating a new interpolation)
   * 5. Find the set of interpolationUID's remaining
   *    a. If the set is of size 0, assign a new interpolationUID
   *    b. If the set is of size 1, assign that interpolationUID
   *    c. Otherwise (optional, otherwise do b for size>1 randomly),
   *       for every remaining annotation, find the one whose center
   *       point is closest to the center point of the new annotation.
   *       Choose that interpolationUID
   *
   * To allow creating new interpolated groups, the idea is to just use a new
   * segment index, then have an operation to update the segment index of an
   * interpolation set.  That way the user can easily draw/see the difference,
   * and then merge them as required.
   * However, the base rules allow creating two contours on a single image to
   * create a separate set.
   */
  static acceptAutoGenerated(
    annotationGroupSelector: AnnotationGroupSelector,
    selector: AcceptInterpolationSelector = {}
  ) {
    const { toolNames, segmentationId, segmentIndex, sliceIndex } = selector;
    for (const toolName of toolNames || InterpolationManager.toolNames) {
      const annotations = annotationState.getAnnotations(
        toolName,
        annotationGroupSelector
      ) as InterpolationROIAnnotation[];
      if (!annotations?.length) {
        continue;
      }
      for (const annotation of annotations) {
        const { interpolationUID, data, autoGenerated, metadata } = annotation;
        if (interpolationUID) {
          annotation.interpolationCompleted = true;
        }
        if (!autoGenerated) {
          continue;
        }
        if (segmentIndex && segmentIndex !== data.segmentation.segmentIndex) {
          continue;
        }
        if (
          sliceIndex !== undefined &&
          metadata &&
          sliceIndex !== metadata.sliceIndex
        ) {
          continue;
        }
        if (
          segmentationId &&
          segmentationId !== data.segmentation.segmentationId
        ) {
          continue;
        }
        addContourSegmentationAnnotation(annotation);
        annotation.autoGenerated = false;
      }
    }
  }
 
  /**
   * When an annotation is completed, if the configuration includes interpolation,
   * then find matching interpolations and interpolation between this segmentation
   * and the other segmentations of the same type.
   */
  static handleAnnotationCompleted = (evt: AnnotationCompletedEventType) => {
    const annotation = evt.detail.annotation as InterpolationROIAnnotation;
    Iif (!annotation?.metadata) {
      return;
    }
    const { toolName, originalToolName } = annotation.metadata;
 
    if (
      !this.toolNames.includes(toolName) &&
      !this.toolNames.includes(originalToolName)
    ) {
      return;
    }
 
    const viewport = getViewportForAnnotation(annotation);
    Iif (!viewport) {
      console.warn('Unable to find viewport for', annotation);
      return;
    }
    const sliceData: Types.ImageSliceData = getSliceData(viewport);
    const viewportData: InterpolationViewportData = {
      viewport,
      sliceData,
      annotation,
      interpolationUID: annotation.interpolationUID,
    };
    const hasInterpolationUID = !!annotation.interpolationUID;
    // If any update, triggered on an annotation, then it will be treated as non-autogenerated.
    annotation.autoGenerated = false;
    if (hasInterpolationUID) {
      // This has already been configured with matching details, so just run
      //  the interpolation again.
      deleteRelatedAnnotations(viewportData);
      interpolate(viewportData);
      return;
    }
    const filterData = [
      {
        key: 'segmentIndex',
        value: annotation.data.segmentation.segmentIndex,
        parentKey: (annotation) => annotation.data.segmentation,
      },
      {
        key: 'viewPlaneNormal',
        value: annotation.metadata.viewPlaneNormal,
        parentKey: (annotation) => annotation.metadata,
      },
      {
        key: 'viewUp',
        value: annotation.metadata.viewUp,
        parentKey: (annotation) => annotation.metadata,
      },
    ];
    let interpolationAnnotations = getInterpolationDataCollection(
      viewportData,
      filterData
    );
    // Skip other type of annotation interpolationUID's that are co-located
    const { sliceIndex } = annotation.metadata;
    const skipUIDs = new Set<string>();
    interpolationAnnotations.forEach((interpolationAnnotation) => {
      if (
        interpolationAnnotation.interpolationCompleted ||
        interpolationAnnotation.metadata.sliceIndex === sliceIndex
      ) {
        const { interpolationUID } = interpolationAnnotation;
        skipUIDs.add(interpolationUID);
      }
    });
    interpolationAnnotations = interpolationAnnotations.filter(
      (interpolationAnnotation) =>
        !skipUIDs.has(interpolationAnnotation.interpolationUID)
    );
 
    // Assign a new interpolationUID (this is checked above, so will be empty initially)
    annotation.interpolationUID =
      interpolationAnnotations[0]?.interpolationUID || uuidv4();
    viewportData.interpolationUID = annotation.interpolationUID;
    interpolate(viewportData);
  };
 
  /**
   * This method gets called when an annotation changes.  It will then trigger
   * related already interpolated annotations to be updated with the modified data.
   */
  static handleAnnotationUpdate = (evt: AnnotationModifiedEventType) => {
    const annotation = evt.detail.annotation as InterpolationROIAnnotation;
    const { changeType = ChangeTypes.HandlesUpdated } = evt.detail;
    Iif (!annotation?.metadata) {
      return;
    }
    const { toolName, originalToolName } = annotation.metadata;
 
    Eif (
      (!this.toolNames.includes(toolName) &&
        !this.toolNames.includes(originalToolName)) ||
      !ChangeTypesForInterpolation.includes(changeType)
    ) {
      return;
    }
    const viewport = getViewportForAnnotation(annotation);
    if (!viewport) {
      console.warn(
        'Unable to find matching viewport for annotation interpolation',
        annotation
      );
      return;
    }
    if (annotation.autoGenerated) {
      // Dont fire the annotation changed events here, as that leads to recursion,
      // although this is in fact completing the event, so trigger the segmentation add
      addContourSegmentationAnnotation(annotation);
      annotation.autoGenerated = false;
    }
 
    const sliceData: Types.ImageSliceData = getSliceData(viewport);
    const viewportData: InterpolationViewportData = {
      viewport,
      sliceData,
      annotation,
      interpolationUID: annotation.interpolationUID,
      isInterpolationUpdate: changeType === ChangeTypes.InterpolationUpdated,
    };
    interpolate(viewportData);
  };
 
  /**
   * Delete interpolated annotations when their endpoints are deleted.
   */
  static handleAnnotationDelete = (evt: AnnotationRemovedEventType) => {
    const annotation = evt.detail.annotation as InterpolationROIAnnotation;
    Iif (!annotation?.metadata) {
      return;
    }
    const { toolName } = annotation.metadata;
 
    if (!this.toolNames.includes(toolName) || annotation.autoGenerated) {
      return;
    }
    const viewport = getViewportForAnnotation(annotation);
 
    Iif (!viewport) {
      console.warn(
        "No viewport, can't delete interpolated results",
        annotation
      );
      return;
    }
 
    const sliceData: Types.ImageSliceData = getSliceData(viewport);
    const viewportData: InterpolationViewportData = {
      viewport,
      sliceData,
      annotation,
      interpolationUID: annotation.interpolationUID,
    };
    // If any update, triggered on an annotation, then it will be treated as non-interpolated.
    annotation.autoGenerated = false;
    deleteRelatedAnnotations(viewportData);
  };
}
 
function getSliceData(viewport): Types.ImageSliceData {
  const sliceData: Types.ImageSliceData = {
    numberOfSlices: viewport.getNumberOfSlices(),
    imageIndex: viewport.getCurrentImageIdIndex(),
  };
  return sliceData;
}