All files / packages/tools/src/utilities/contours/interpolation selectHandles.ts

89.56% Statements 103/115
67.56% Branches 25/37
100% Functions 10/10
89.09% Lines 98/110

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        1x                           7x 7x 7x 7x   7x 7x 5x             2x     2x 4x     2x   2x 2x 2x 2x 2x 2x 12x 12x 12x 6x   6x       6x               6x       2x 2x     2x 2x                           2x 16x 16x 16x 32x     2x                                 2x 2x 2x 2x   2x 1280x 1280x 1280x 1280x 1280x   1280x 1280x     2x                 2x 2x   2x       2x 2x   2x   2x 1280x 1280x 68x 54x 54x 28x 28x   54x   14x 14x 14x     1212x 12x 12x       2x 2x 2x               2x                 8x   2x   8x 8x 8x             8x 16x 16x   8x               18x             2x 2x 2x 2x 2x 2x 1280x 1280x 1280x 1280x   2x 2x 1280x 1280x   2x                
import { vec3 } from 'gl-matrix';
import { utilities } from '@cornerstonejs/core';
import type { PointsArray3 } from './interpolate';
 
const { PointsManager } = utilities;
 
/**
 * Selects handles by looking for local maximums in the angle that the local
 * vector makes
 *
 * @param polyline - an array of points, usually the polyline for the contour to
 *        select handles from.
 * @param handleCount - a guideline for how many handles to create
 */
export default function selectHandles(
  polyline: PointsArray3,
  handleCount = 12
): PointsArray3 {
  const handles = PointsManager.create3(handleCount) as PointsArray3;
  handles.sources = [];
  const { sources: destPoints } = handles;
  const { length, sources: sourcePoints = [] } = polyline;
  // The distance used for figuring out the local angle of a line
  const distance = 5;
  if (length < distance * 3) {
    return polyline.subselect(handleCount);
  }
  // Need to make the interval between handles long enough to allow for some
  // variation between points in terms of the distance of a line angle, but
  // also not too many handles either.
  // On average, we get twice the interval between handles, so double the length here.
  // Or, choose a longer interval if the handle count would have too many handles (too short an interval)
  const interval = Math.floor(
    Math.max((2 * length) / handleCount, distance * 2)
  );
  sourcePoints.forEach(() =>
    destPoints.push(PointsManager.create3(handleCount))
  );
 
  const dotValues = createDotValues(polyline, distance);
 
  const minimumRegions = findMinimumRegions(dotValues, handleCount);
  const indices = [];
  if (minimumRegions?.length > 2) {
    let lastHandle = -1;
    const thirdInterval = interval / 3;
    minimumRegions.forEach((region) => {
      const [start, , end] = region;
      const midIndex = Math.ceil((start + end) / 2);
      if (end - lastHandle < thirdInterval) {
        return;
      }
      Iif (midIndex - start > 2 * thirdInterval) {
        addInterval(indices, lastHandle, start, interval, length);
        lastHandle = addInterval(indices, start, midIndex, interval, length);
      } else {
        lastHandle = addInterval(
          indices,
          lastHandle,
          midIndex,
          interval,
          length
        );
      }
      Iif (end - lastHandle > thirdInterval) {
        lastHandle = addInterval(indices, lastHandle, end, interval, length);
      }
    });
    const firstHandle = indices[0];
    const lastDistance = indexValue(firstHandle + length - lastHandle, length);
    // Check that there is enough space between the last and first handle to
    // need an extra handle.
    Eif (lastDistance > 2 * thirdInterval) {
      addInterval(
        indices,
        lastHandle,
        // Don't add a point too close to the first handle
        firstHandle - thirdInterval,
        interval,
        length
      );
    }
  } else E{
    const interval = Math.floor(length / handleCount);
    addInterval(indices, -1, length - interval, interval, length);
  }
 
  indices.forEach((index) => {
    const point = polyline.getPointArray(index);
    handles.push(point);
    sourcePoints.forEach((source, destSourceIndex) =>
      destPoints[destSourceIndex].push(source.getPoint(index))
    );
  });
  return handles;
}
 
/**
 * Creates an array of the dot products between each point in the points array
 * and a point +/- distance from that point, unitized to vector length 1.
 * That is, this is a measure of the angle at the given point, where 1 is a
 * straight line, and -1 is a 180 degree angle change.
 *
 * @param polyline - the array of Point3 values
 * @param distance - previous/next distance to use for the vectors for the dot product
 * @returns - Float32Array of dot products, one per point in the source array.
 */
export function createDotValues(
  polyline: PointsArray3,
  distance = 6
): Float32Array {
  const { length } = polyline;
  const prevVec3 = vec3.create();
  const nextVec3 = vec3.create();
  const dotValues = new Float32Array(length);
 
  for (let i = 0; i < length; i++) {
    const point = polyline.getPoint(i);
    const prevPoint = polyline.getPoint(i - distance);
    const nextPoint = polyline.getPoint((i + distance) % length);
    vec3.sub(prevVec3, point, prevPoint);
    vec3.sub(nextVec3, nextPoint, point);
    const dot =
      vec3.dot(prevVec3, nextVec3) / (vec3.len(prevVec3) * vec3.len(nextVec3));
    dotValues[i] = dot;
  }
 
  return dotValues;
}
 
/**
 * Finds minimum regions in the dot products.  These are detected as
 * center points of the dot values regions having a minimum value - that is,
 * where the direction of the line is changing fastest.
 */
function findMinimumRegions(dotValues, handleCount) {
  const { max, deviation } = getStats(dotValues);
  const { length } = dotValues;
  // Fallback for very uniform ojects.
  Iif (deviation < 0.01 || length < handleCount * 3) {
    return [];
  }
 
  const inflection = [];
  let pair = null;
  let minValue;
  let minIndex = 0;
 
  for (let i = 0; i < length; i++) {
    const dot = dotValues[i];
    if (dot < max - deviation) {
      if (pair) {
        pair[2] = i;
        if (dot < minValue) {
          minValue = dot;
          minIndex = i;
        }
        pair[1] = minIndex;
      } else {
        minValue = dot;
        minIndex = i;
        pair = [i, i, i];
      }
    } else {
      if (pair) {
        inflection.push(pair);
        pair = null;
      }
    }
  }
  Eif (pair) {
    if (inflection[0][0] === 0) {
      inflection[0][0] = pair[0];
    } else E{
      pair[1] = minIndex;
      pair[2] = length - 1;
      inflection.push(pair);
    }
  }
 
  return inflection;
}
 
/**
 * Adds points in between the start and finish.
 * This is currently just the center point for short values and the start/center/end
 * for ranges where the distance between these is at least the increment.
 */
export function addInterval(indices, start, finish, interval, length) {
  if (finish < start) {
    // Always want a positive distance even if the long way round
    finish += length;
  }
  const distance = finish - start;
  const count = Math.ceil(distance / interval);
  Iif (count <= 0) {
    if (indices[indices.length - 1] !== finish) {
      indices.push(indexValue(finish, length));
    }
    return finish;
  }
  // Don't add the start index, and always add the end index
  for (let i = 1; i <= count; i++) {
    const index = indexValue(start + (i * distance) / count, length);
    indices.push(index);
  }
  return indices[indices.length - 1];
}
 
/**
 * Gets the index value of a closed polyline, rounding the value and
 * doing the module operation as required.
 */
function indexValue(v, length) {
  return (Math.round(v) + length) % length;
}
 
/**
 * Gets statistics on the provided array numbers.
 */
function getStats(dotValues) {
  const { length } = dotValues;
  let sum = 0;
  let min = Infinity;
  let max = -Infinity;
  let sumSq = 0;
  for (let i = 0; i < length; i++) {
    const dot = dotValues[i];
    sum += dot;
    min = Math.min(min, dot);
    max = Math.max(max, dot);
  }
  const mean = sum / length;
  for (let i = 0; i < length; i++) {
    const valueDiff = dotValues[i] - mean;
    sumSq += valueDiff * valueDiff;
  }
  return {
    mean,
    max,
    min,
    sumSq,
    deviation: Math.sqrt(sumSq / length),
  };
}