All files / platform/core/src/utils sortInstancesByPosition.ts

90% Statements 18/20
50% Branches 2/4
100% Functions 4/4
88.88% Lines 16/18

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                          216x         216x   216x       216x         216x           216x   216x             216x 17718x   17718x   17718x   17718x   17718x           64164x   17718x   216x    
import { vec3 } from 'gl-matrix';
 
/**
 * Given an array of imageIds, sort them based on their imagePositionPatient, and
 * also returns the spacing between images and the origin of the reference image
 *
 * @param imageIds - array of imageIds
 * @param scanAxisNormal - [x, y, z] array or gl-matrix vec3
 *
 * @returns The sortedImageIds, zSpacing, and origin of the first image in the series.
 */
export default function sortInstances(instances: Array<any>) {
  // Return if only one instance e.g., multiframe
  Iif (instances.length <= 1) {
    return instances;
  }
 
  const { ImagePositionPatient: referenceImagePositionPatient, ImageOrientationPatient } =
    instances[Math.floor(instances.length / 2)]; // this prevents getting scout image as test image
 
  Iif (!referenceImagePositionPatient || !ImageOrientationPatient) {
    return instances;
  }
 
  const rowCosineVec = vec3.fromValues(
    ImageOrientationPatient[0],
    ImageOrientationPatient[1],
    ImageOrientationPatient[2]
  );
  const colCosineVec = vec3.fromValues(
    ImageOrientationPatient[3],
    ImageOrientationPatient[4],
    ImageOrientationPatient[5]
  );
 
  const scanAxisNormal = vec3.cross(vec3.create(), rowCosineVec, colCosineVec);
 
  const refIppVec = vec3.set(
    vec3.create(),
    referenceImagePositionPatient[0],
    referenceImagePositionPatient[1],
    referenceImagePositionPatient[2]
  );
 
  const distanceInstancePairs = instances.map(instance => {
    const imagePositionPatient = instance.ImagePositionPatient;
 
    const positionVector = vec3.create();
 
    vec3.sub(positionVector, referenceImagePositionPatient, imagePositionPatient);
 
    const distance = vec3.dot(positionVector, scanAxisNormal);
 
    return {
      distance,
      instance,
    };
  });
 
  distanceInstancePairs.sort((a, b) => b.distance - a.distance);
 
  const sortedInstances = distanceInstancePairs.map(a => a.instance);
 
  return sortedInstances;
}