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

87.78% Statements 194/221
65.21% Branches 30/46
87.5% Functions 21/24
87.8% Lines 180/205

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 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 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 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728                              1x                             1x                               6x     6x 6x 6x 6x           6x   6x                           6x 6x   6x   6x       6x         6x 3x 3x                 6x   6x             6x 3x                                                 3x 3x 3x 3x   3x 3x 3x     3x 7x                                                                                         7x 7x 7x 7x 7x             7x   7x   7x                 7x                                                     7x 7x   7x           7x 7x     7x 7x 7x         7x 7x                                                                                                                                                                                 7x   7x 7x 7x 7x   7x 7x 7x 7x 7x 7x   7x 1843x 1305x 1305x 1305x 1305x 1305x 1305x                   7x   7x                       3x 3x   3x         3x 3x   3x 3x     3x 3x   3x 3x   3x 3x   3x 3x     3x   3x                       3x           3x             3x 7061x 919x 919x 919x 919x   919x 919x 919x 919x       3x                               3x   3x         3x 7061x       7061x   7061x 20306731x         20306731x   20306731x 7061x       7061x 155x 155x       3x   3x 3x 3x 3x                     12x 12x 12x 12x                         6x               6x   1300x 1300x 1300x 1300x     1300x 1300x 1300x     1300x 12822x 12822x 12822x 12822x       6x                           6x   6x 14128x   6x 21752x     6x   6x 14128x     6x         14128x 1306x   14128x       6x   6x 1300x     6x                       6x 6x 6x 6x                       6x 6x     6x 12816x     6x                   6x   6x 1306x     6x                     6x   6x 1300x           1300x     6x                     6x         6x 1300x 1300x 1300x       6x 6x 6x   6x        
import { triggerEvent, utilities } from '@cornerstonejs/core';
import type { Types } from '@cornerstonejs/core';
import { vec3 } from 'gl-matrix';
 
import createPolylineToolData from './createPolylineToolData';
import findAnnotationsForInterpolation from './findAnnotationForInterpolation';
import type { InterpolationViewportData } from '../../../types/InterpolationTypes';
import type { InterpolationROIAnnotation } from '../../../types/ToolSpecificAnnotationTypes';
import type { AnnotationInterpolationCompletedEventDetail } from '../../../types/EventTypes';
import EventTypes from '../../../enums/Events';
import * as annotationState from '../../../stateManagement/annotation';
import selectHandles from './selectHandles';
import updateChildInterpolationUID from './updateChildInterpolationUID';
import { createPolylineHole } from '../../../eventListeners/annotations/contourSegmentation/contourSegmentationCompleted';
 
const { PointsManager } = utilities;
 
/**
 * An XYZ encoded points that also includes an indicator I for whether the
 * point is included in the original contour.
 */
export type PointsXYZI = Types.PointsXYZ & {
  I?: boolean[];
  kIndex?: number;
};
 
export type PointsArray3 = Types.PointsManager<Types.Point3> & {
  I?: boolean[];
};
 
const dP = 0.2; // Aim for < 0.2mm between interpolated nodes when super-sampling.
 
/**
 * interpolate - Interpolate missing contours in the ROIContours.
 * If input is tool data collection, it is expected to be sorted in the order
 * of stack image in which it was drawn.
 *
 * This is performed in a microtask in order to avoid delaying the event handler
 * excessively, but to ensure it is completed before the data is additionally
 * changed.  It was originally done in a setTimeout, but that allowed the data
 * to be updated between calls, causing issues with the interpolation process.
 *
 * @param viewportData - Object
 * @returns null
 */
function interpolate(viewportData: InterpolationViewportData) {
  Iif (!viewportData.annotation) {
    return;
  }
  const { isInterpolationUpdate, annotation } = viewportData;
  queueMicrotask(() => {
    try {
      Iif (isInterpolationUpdate) {
        annotation.isInterpolationUpdate = true;
        // This may not be true long term, but treat it as user generated for
        // this run.
        annotation.autoGenerated = false;
      }
      startInterpolation(viewportData);
    } finally {
      Iif (isInterpolationUpdate) {
        // Reset the auto generated flag
        annotation.autoGenerated = true;
      }
    }
  });
}
 
/**
 * Start the actual interpolation from the list
 * @param viewportData - Object
 * @returns null
 */
function startInterpolation(viewportData: InterpolationViewportData) {
  const { annotation: toolData } = viewportData;
  updateChildInterpolationUID(toolData);
  const { interpolationData, interpolationList } =
    findAnnotationsForInterpolation(toolData, viewportData) || {};
 
  Iif (!interpolationData || !interpolationList) {
    return;
  }
 
  const eventData = {
    toolName: toolData.metadata.toolName,
    toolType: toolData.metadata.toolName,
    viewport: viewportData.viewport,
  };
  for (let i = 0; i < interpolationList.length; i++) {
    Eif (interpolationList[i]) {
      _linearlyInterpolateBetween(
        interpolationList[i].list,
        interpolationList[i].pair,
        interpolationData,
        eventData
      );
    }
  }
 
  const { id, renderingEngineId, element } = viewportData.viewport;
 
  const eventDetails: AnnotationInterpolationCompletedEventDetail = {
    annotation: toolData,
    element,
    viewportId: id,
    renderingEngineId,
  };
 
  if (interpolationList.length) {
    triggerEvent(
      viewportData.viewport.element,
      EventTypes.ANNOTATION_INTERPOLATION_PROCESS_COMPLETED,
      eventDetails
    );
  }
}
 
/**
 * _linearlyInterpolateBetween - Linearly interpolate all the slices in the
 * indices array between the contourPair.
 *
 * @param indices - natural[], An array of slice indices to interpolate.
 * @param annotationPair - natural[2], The slice indices of the reference contours.
 * @param interpolationData - object
 * @param eventData - object
 * @returns null
 */
 
function _linearlyInterpolateBetween(
  indices,
  annotationPair,
  interpolationData,
  eventData
) {
  const annotation0 = interpolationData.get(annotationPair[0])[0];
  const annotation1 = interpolationData.get(annotationPair[1])[0];
  const c1 = _generateClosedContour(annotation0.data.contour.polyline);
  const c2 = _generateClosedContour(annotation1.data.contour.polyline);
 
  const { c1Interp, c2Interp } = _generateInterpolationContourPair(c1, c2);
  c1Interp.kIndex = annotationPair[0];
  c2Interp.kIndex = annotationPair[1];
 
  // Using the newly constructed contours, interpolate each ROI.
  indices.forEach(function (index) {
    _linearlyInterpolateContour(
      c1Interp,
      c2Interp,
      index,
      annotationPair,
      interpolationData,
      c1.x.length > c2.x.length,
      eventData
    );
  });
}
 
function getPointCount(pointArray) {
  let sum = 0;
  for (let i = 0; i < pointArray.I.length; i++) {
    if (pointArray.I[i]) {
      sum++;
    }
  }
  return sum;
}
 
/**
 * _linearlyInterpolateContour - Inserts a linearly interpolated contour at
 * specified slice index.
 *
 * @param c1Interp - object, The first reference contour.
 * @param c2Interp - object,  The second reference contour.
 * @param sliceIndex - Number, The slice index to interpolate.
 * @param annotationPair - Number[], The slice indices of the reference contours.
 * @param interpolationData - object[], Data for the slice location of contours
 *                                  for the ROIContour.
 * @param c1HasMoreNodes - boolean, True if c1 has more nodes than c2.
 * @param eventData - object
 * @returns null
 */
function _linearlyInterpolateContour(
  c1Interp,
  c2Interp,
  sliceIndex,
  annotationPair,
  interpolationData,
  c1HasMoreNodes,
  eventData
) {
  const [startIndex, endIndex] = annotationPair;
  const zInterp = (sliceIndex - startIndex) / (endIndex - startIndex);
  const annotation0 = interpolationData.get(startIndex)[0];
  const annotation1 = interpolationData.get(endIndex)[0];
  const interpolated3DPoints = _generateInterpolatedOpenContour(
    c1Interp,
    c2Interp,
    zInterp,
    c1HasMoreNodes
  );
 
  const nearestAnnotation = zInterp > 0.5 ? annotation1 : annotation0;
 
  const handlePoints = selectHandles(interpolated3DPoints);
 
  Iif (interpolationData.has(sliceIndex)) {
    _editInterpolatedContour(
      interpolated3DPoints,
      handlePoints,
      sliceIndex,
      nearestAnnotation,
      eventData
    );
  } else {
    _addInterpolatedContour(
      interpolated3DPoints,
      handlePoints,
      sliceIndex,
      nearestAnnotation,
      eventData
    );
  }
}
 
/**
 * _addInterpolatedContour - Adds a new contour to the imageId.
 *
 * @param interpolated3DPoints - object, The polygon to add to the ROIContour.
 * @param sliceIndex - Number, The slice index to interpolate..
 * @param referencedToolData - The toolData of another polygon in the
 * ROIContour, to assign appropriate metadata to the new polygon.
 * @param eventData - object
 * @returns null
 */
function _addInterpolatedContour(
  interpolated3DPoints: PointsArray3,
  handlePoints: PointsArray3,
  sliceIndex: number,
  referencedToolData,
  eventData
) {
  const points = interpolated3DPoints.points;
  const { viewport } = eventData;
 
  const interpolatedAnnotation = createPolylineToolData(
    points,
    handlePoints,
    referencedToolData
  );
 
  const viewRef = viewport.getViewReference({ sliceIndex });
  Iif (!viewRef) {
    throw new Error(`Can't find slice ${sliceIndex}`);
  }
  Object.assign(interpolatedAnnotation.metadata, viewRef);
  annotationState.state.addAnnotation(interpolatedAnnotation, viewport.element);
  referencedToolData.onInterpolationComplete?.(
    interpolatedAnnotation,
    referencedToolData
  );
 
  const { parentAnnotationUID } = referencedToolData;
  Iif (parentAnnotationUID) {
    const parentReferenced =
      annotationState.state.getAnnotation(parentAnnotationUID);
    const parentAnnotation = _findExistingAnnotation(
      parentReferenced,
      sliceIndex,
      eventData
    );
    createPolylineHole(viewport, parentAnnotation, interpolatedAnnotation);
  }
}
 
/**
 * Finds an existing annotation on the given slide, with the interpolation UID as
 * specified in the referenced tool data.
 */
function _findExistingAnnotation(referencedToolData, sliceIndex, eventData) {
  const { viewport } = eventData;
  const annotations = annotationState.state.getAnnotations(
    referencedToolData.metadata.toolName,
    viewport.element
  );
 
  for (let i = 0; i < annotations.length; i++) {
    const annotation = annotations[i] as InterpolationROIAnnotation;
    if (
      annotation.interpolationUID === referencedToolData.interpolationUID &&
      annotation.metadata.sliceIndex === sliceIndex
    ) {
      return annotation;
    }
  }
}
/**
 * _editInterpolatedContour - Edits an interpolated polygon on the imageId
 * that corresponds to the specified ROIContour.
 *
 * @param interpolated3DPoints - object, The polygon to add to the ROIContour.
 * @param sliceIndex - Number, The slice index to interpolate.
 * @param referencedToolData - type, The toolData of another polygon in the
 * ROIContour, to assign appropriate metadata to the new polygon.
 * @param eventData - object
 */
function _editInterpolatedContour(
  interpolated3DPoints: PointsArray3,
  handlePoints: PointsArray3,
  sliceIndex,
  referencedToolData,
  eventData
) {
  const oldAnnotationData = _findExistingAnnotation(
    referencedToolData,
    sliceIndex,
    eventData
  );
 
  const points = interpolated3DPoints.points;
  const interpolatedAnnotation = createPolylineToolData(
    points,
    handlePoints,
    oldAnnotationData
  );
  // Does a real update here instead of an add/remove, which caused delete issues in child annotations
  Object.assign(oldAnnotationData, {
    metadata: interpolatedAnnotation.metadata,
    data: interpolatedAnnotation.data,
  });
}
 
/**
 * _generateInterpolatedOpenContour - Interpolate an open contour between c1ir
 * and c2ir at the zInterp position.
 *
 * @param c1ir - object, The interpolated c1 contour with
 *                                  superfluous nodes removed.
 * @param c2ir - object, The interpolated c2 contour with
 *                                  superfluous nodes removed.
 * @param zInterp - Number, The z- coordinate of the desired
 *                                  interpolation.
 * @param c1HasMoreNodes - boolean, True if c1 has more original nodes
 *                                  than c2.
 * @returns object, The interpolated contour at z=zInterp.
 */
function _generateInterpolatedOpenContour(
  c1ir,
  c2ir,
  zInterp,
  c1HasMoreNodes
): PointsArray3 {
  const indices = c1HasMoreNodes ? c1ir.I : c2ir.I;
 
  const c1 = PointsManager.fromXYZ(c1ir);
  const c2 = PointsManager.fromXYZ(c2ir);
  const { length } = c1;
  const cInterp = PointsManager.create3(length) as PointsArray3;
 
  const vecSubtract = vec3.create();
  const vecResult = vec3.create();
  const c1Source = PointsManager.create3(length);
  c1Source.kIndex = c1ir.kIndex;
  const c2Source = PointsManager.create3(length);
  c2Source.kIndex = c2ir.kIndex;
 
  for (let i = 0; i < c1ir.x.length; i++) {
    if (indices[i]) {
      const c1point = c1.getPoint(i);
      const c2point = c2.getPoint(i);
      c1Source.push(c1point);
      c2Source.push(c2point);
      vec3.sub(vecSubtract, c2point, c1point);
      cInterp.push(
        vec3.scaleAndAdd(
          vecResult,
          c1point,
          vecSubtract,
          zInterp
        ) as Types.Point3
      );
    }
  }
  cInterp.sources = [c1Source, c2Source];
 
  return cInterp;
}
 
/**
 * _generateInterpolationContourPair - generates two aligned contours with an
 * equal number of nodes from which an intermediate contour may be interpolated.
 *
 * @param c1 - The first contour.
 * @param c2 - The second contour.
 * @returns -  An object containing the two contours.
 */
function _generateInterpolationContourPair(c1, c2) {
  const cumPerim1 = _getCumulativePerimeter(c1);
  const cumPerim2 = _getCumulativePerimeter(c2);
 
  const interpNodes = Math.max(
    Math.ceil(cumPerim1[cumPerim1.length - 1] / dP),
    Math.ceil(cumPerim2[cumPerim2.length - 1] / dP)
  );
 
  const cumPerim1Norm = _normalisedCumulativePerimeter(cumPerim1);
  const cumPerim2Norm = _normalisedCumulativePerimeter(cumPerim2);
 
  const numNodes1 = interpNodes + c2.x.length;
  const numNodes2 = interpNodes + c1.x.length;
 
  // concatenate p && cumPerimNorm
  const perim1Interp = _getInterpolatedPerim(numNodes1, cumPerim1Norm);
  const perim2Interp = _getInterpolatedPerim(numNodes2, cumPerim2Norm);
 
  const perim1Ind = _getIndicatorArray(numNodes1 - 2, c1.x.length);
  const perim2Ind = _getIndicatorArray(numNodes2 - 2, c2.x.length);
 
  const nodesPerSegment1 = _getNodesPerSegment(perim1Interp, perim1Ind);
  const nodesPerSegment2 = _getNodesPerSegment(perim2Interp, perim2Ind);
 
  const c1i = _getSuperSampledContour(c1, nodesPerSegment1);
  const c2i = _getSuperSampledContour(c2, nodesPerSegment2);
 
  // Keep c2i fixed and shift the starting node of c1i to minimise the total length of segments.
  _shiftSuperSampledContourInPlace(c1i, c2i);
 
  return _reduceContoursToOriginNodes(c1i, c2i);
}
 
/**
 * _reduceContoursToOriginNodes - Removes any nodes from the contours that don't
 * correspond to an original contour node.
 *
 * @param c1i - The first super-sampled contour.
 * @param c2i - The second super-sampled contour.
 * @returns  An object containing the two reduced contours.
 */
function _reduceContoursToOriginNodes(c1i: PointsXYZI, c2i: PointsXYZI) {
  const c1Interp: PointsXYZI = {
    x: [],
    y: [],
    z: [],
    I: [],
  };
  const c2Interp: PointsXYZI = {
    x: [],
    y: [],
    z: [],
    I: [],
  };
 
  for (let i = 0; i < c1i.x.length; i++) {
    if (c1i.I[i] || c2i.I[i]) {
      c1Interp.x.push(c1i.x[i]);
      c1Interp.y.push(c1i.y[i]);
      c1Interp.z.push(c1i.z[i]);
      c1Interp.I.push(c1i.I[i]);
 
      c2Interp.x.push(c2i.x[i]);
      c2Interp.y.push(c2i.y[i]);
      c2Interp.z.push(c2i.z[i]);
      c2Interp.I.push(c2i.I[i]);
    }
  }
 
  return {
    c1Interp,
    c2Interp,
  };
}
 
/**
 * _shiftSuperSampledContourInPlace - Shifts the indices of c1i around to
 * minimize: SUM (|c1i[i]-c2i[i]|) from 0 to N.
 *
 * @param c1i - The contour to shift.
 * @param c2i - The reference contour.
 * modifies c1i
 * @returns null
 */
function _shiftSuperSampledContourInPlace(c1i, c2i) {
  const c1iLength = c1i.x.length;
 
  const optimal = {
    startingNode: 0,
    totalSquaredXYLengths: Infinity,
  };
 
  for (let startingNode = 0; startingNode < c1iLength; startingNode++) {
    let node = startingNode;
 
    // NOTE: 1) Ignore calculating Z, as the sum of all squared Z distances will always be a constant.
    // NOTE: 2) Don't need actual length, so don't worry about square rooting.
    let totalSquaredXYLengths = 0;
 
    for (let iteration = 0; iteration < c1iLength; iteration++) {
      totalSquaredXYLengths +=
        (c1i.x[node] - c2i.x[iteration]) ** 2 +
        (c1i.y[node] - c2i.y[iteration]) ** 2 +
        (c1i.z[node] - c2i.z[iteration]) ** 2;
 
      node++;
 
      if (node === c1iLength) {
        node = 0;
      }
    }
 
    if (totalSquaredXYLengths < optimal.totalSquaredXYLengths) {
      optimal.totalSquaredXYLengths = totalSquaredXYLengths;
      optimal.startingNode = startingNode;
    }
  }
 
  const node = optimal.startingNode;
 
  _shiftCircularArray(c1i.x, node);
  _shiftCircularArray(c1i.y, node);
  _shiftCircularArray(c1i.z, node);
  _shiftCircularArray(c1i.I, node);
}
 
/**
 * _shiftCircularArray - Shift the circular array by the count.
 *
 * @param arr - Array, The array.
 * @param count - Number, The shift.
 * @returns The shifted array.
 */
function _shiftCircularArray(arr, count) {
  count -= arr.length * Math.floor(count / arr.length);
  const slicedArray = arr.splice(0, count);
  arr.push(...slicedArray);
  return arr;
}
 
/**
 * _getSuperSampledContour - Generates a super sampled contour with additional
 * nodes added per segment.
 *
 * @param c - object, The original contour.
 * @param nodesPerSegment - Number[], An array of the number of nodes to add
 *                                    per line segment.
 * @returns object, The super sampled contour.
 */
function _getSuperSampledContour(c, nodesPerSegment): PointsXYZI {
  const ci = {
    x: [],
    y: [],
    z: [],
    I: [],
  };
 
  // Length - 1, produces 'open' polygon.
  for (let n = 0; n < c.x.length - 1; n++) {
    // Add original node.
    ci.x.push(c.x[n]);
    ci.y.push(c.y[n]);
    ci.z.push(c.z[n]);
    ci.I.push(true);
 
    // Add linearly interpolated nodes.
    const xSpacing = (c.x[n + 1] - c.x[n]) / (nodesPerSegment[n] + 1);
    const ySpacing = (c.y[n + 1] - c.y[n]) / (nodesPerSegment[n] + 1);
    const zSpacing = (c.z[n + 1] - c.z[n]) / (nodesPerSegment[n] + 1);
 
    // Add other nodesPerSegment - 1 other nodes (as already put in original node).
    for (let i = 0; i < nodesPerSegment[n] - 1; i++) {
      ci.x.push(ci.x[ci.x.length - 1] + xSpacing);
      ci.y.push(ci.y[ci.y.length - 1] + ySpacing);
      ci.z.push(ci.z[ci.z.length - 1] + zSpacing);
      ci.I.push(false);
    }
  }
 
  return ci;
}
 
/**
 * _getNodesPerSegment - Returns an array of the number of interpolated nodes
 * to be added along each line segment of a polygon.
 *
 * @param perimInterp - Number[], Normalized array of original and added nodes.
 * @param perimInd - boolean[], The indicator array describing the location of
 *                            the original contour's nodes.
 * @returns Number[], An array containing the number of nodes to be
 *                    added per original line segment.
 */
function _getNodesPerSegment(perimInterp, perimInd) {
  const idx = [];
 
  for (let i = 0; i < perimInterp.length; ++i) {
    idx[i] = i;
  }
  idx.sort(function (a, b) {
    return perimInterp[a] < perimInterp[b] ? -1 : 1;
  });
 
  const perimIndSorted = [];
 
  for (let i = 0; i < perimInd.length; i++) {
    perimIndSorted.push(perimInd[idx[i]]);
  }
 
  const indicesOfOriginNodes = perimIndSorted.reduce(function (
    arr,
    elementValue,
    i
  ) {
    if (elementValue) {
      arr.push(i);
    }
    return arr;
  },
  []);
 
  const nodesPerSegment = [];
 
  for (let i = 0; i < indicesOfOriginNodes.length - 1; i++) {
    nodesPerSegment.push(indicesOfOriginNodes[i + 1] - indicesOfOriginNodes[i]);
  }
 
  return nodesPerSegment;
}
 
/**
 * _getIndicatorArray - Produces an array of the location of the original nodes
 * in a super sampled contour.
 *
 * @param contour - object, The original contour.
 * @param numNodes - Number, The number of nodes added.
 * @returns boolean[], The indicator array of original node locations.
 */
function _getIndicatorArray(numFalse, numTrue) {
  const perimInd = new Array(numFalse + numTrue);
  perimInd.fill(false, 0, numFalse);
  perimInd.fill(true, numFalse, numFalse + numTrue);
  return perimInd;
}
 
/**
 * _getInterpolatedPerim - Adds additional interpolated nodes to the
 * normalized perimeter array.
 *
 * @param numNodes - object, The number of nodes to add.
 * @param cumPerimNorm - The cumulative perimeter array.
 * @returns Number[], The array of nodes.
 */
function _getInterpolatedPerim(numNodes, cumPerimNorm) {
  const diff = 1 / (numNodes - 1);
  const linspace = [diff];
 
  // Length - 2 as we are discarding 0 and 1 for efficiency (no need to calculate them).
  for (let i = 1; i < numNodes - 2; i++) {
    linspace.push(linspace[linspace.length - 1] + diff);
  }
 
  return linspace.concat(cumPerimNorm);
}
 
/**
 * _normalizedCumulativePerimeter - Normalizes the cumulative perimeter array.
 *
 * @param cumPerim - An array of the cumulative perimeter at each of a contour.
 * @returns  The normalized array.
 */
function _normalisedCumulativePerimeter(cumPerim) {
  const cumPerimNorm = [];
 
  for (let i = 0; i < cumPerim.length; i++) {
    cumPerimNorm.push(cumPerim[i] / cumPerim[cumPerim.length - 1]);
  }
 
  return cumPerimNorm;
}
 
/**
 * _getCumulativePerimeter - Returns an array of the the cumulative perimeter at
 * each node of the contour.
 *
 * @param contour - The contour.
 * @returns An array of the cumulative perimeter at each node.
 */
function _getCumulativePerimeter(contour: Types.PointsXYZ): number[] {
  const cumulativePerimeter = [0];
 
  for (let i = 1; i < contour.x.length; i++) {
    const lengthOfSegment = Math.sqrt(
      (contour.x[i] - contour.x[i - 1]) ** 2 +
        (contour.y[i] - contour.y[i - 1]) ** 2 +
        (contour.z[i] - contour.z[i - 1]) ** 2
    );
 
    cumulativePerimeter.push(cumulativePerimeter[i - 1] + lengthOfSegment);
  }
 
  return cumulativePerimeter;
}
 
/**
 * _generateClosedContour - Generate a clockwise contour object from the points
 * of a clockwise or anti-clockwise polygon.
 *
 * @param  points - The points to generate the contour from.
 * @returns The generated contour object.
 */
function _generateClosedContour(points): Types.PointsXYZ {
  const c = {
    x: [],
    y: [],
    z: [],
  };
  for (let i = 0; i < points.length; i++) {
    c.x[i] = points[i][0];
    c.y[i] = points[i][1];
    c.z[i] = points[i][2];
  }
 
  // Push last node to create closed contour.
  c.x.push(c.x[0]);
  c.y.push(c.y[0]);
  c.z.push(c.z[0]);
 
  return c;
}
 
export default interpolate;